ide/designer: Fixed location of controls being dropped in CodeEditor
[sdk] / ide / src / designer / CodeEditor.ec
1 import "ide"
2
3 // *** Color Schemes ***
4
5 // *** The Old Color Scheme that was causing me auras and ophtalmic migraines -- Uncomment at your own risk! ***
6 /*
7 FontResource panelFont { $"Courier New", 10 };
8 FontResource codeFont { $"Courier New", 10 };
9 Color selectionColor = Color { 10, 36, 106 };
10 Color selectionText = white;
11 Color viewsBackground = white;
12 Color viewsText = black;
13 Color outputBackground = white;
14 Color outputText = black;
15 Color projectViewBackground = white;
16 Color projectViewText = black;
17 Color codeEditorBG = white;
18 Color codeEditorFG = black;
19 Color marginColor = Color {230, 230, 230};
20 Color selectedMarginColor = Color {200, 200, 200};
21 Color lineNumbersColor = Color {60, 60, 60};
22 SyntaxColorScheme colorScheme
23 {
24    keywordColors = [ blue, blue ];
25    commentColor = dimGray;
26    charLiteralColor = crimson;
27    stringLiteralColor = crimson;
28    preprocessorColor = green;
29    numberColor = teal;
30 };
31 */
32
33 // The new nice dark scheme -- so peaceful on my brain
34
35 FontResource panelFont { $"Courier New", 10 };
36 FontResource codeFont { $"Courier New", 10 };
37 /*
38 FontResource panelFont { $"Consolas", 12 };
39 FontResource codeFont { $"Consolas", 12 };
40 */
41 Color selectionColor = lightYellow;
42 Color selectionText = Color { 30, 40, 50 };
43 Color viewsBackground = Color { 30, 40, 50 };
44 Color viewsText = lightGray;
45 Color outputBackground = black;
46 Color outputText = lime;
47 Color projectViewBackground = Color { 30, 40, 50 };
48 Color projectViewText = lightGray;
49 Color codeEditorBG = black;
50 Color codeEditorFG = ivory;
51 Color marginColor = Color {24, 24, 24};
52 Color selectedMarginColor = Color {64, 64, 64};
53 Color lineNumbersColor = Color {160, 160, 160};
54 SyntaxColorScheme colorScheme
55 {
56    keywordColors = [ skyBlue, skyBlue ];
57    commentColor = Color { 125, 125, 125 };
58    charLiteralColor = Color { 245, 50, 245 };
59    stringLiteralColor = Color { 245, 50, 245 };
60    preprocessorColor = { 120, 220, 140 };
61    numberColor = Color {   0, 192, 192 };
62 };
63
64 // *********************
65
66 import "findCtx"
67 import "findExp"
68 import "findParams"
69
70 // UNTIL IMPLEMENTED IN GRAMMAR
71 #define ACCESS_CLASSDATA(_class, baseClass) \
72    (_class ? ((void *)(((char *)_class.data) + baseClass.offsetClass)) : null)
73
74 #ifdef ECERE_STATIC
75 extern int __attribute__((__stdcall__)) __ecereDll_Load_ecere(struct __ecereNameSpace__ecere__com__Instance * module);
76 extern int __attribute__((__stdcall__)) __ecereDll_Unload_ecere(struct __ecereNameSpace__ecere__com__Instance * module);
77 #endif
78
79 static Array<FileFilter> fileFilters
80 { [
81    { $"C/C++/eC Files (*.ec, *.eh, *.c, *.cpp, *.cc, *.cxx, *.h, *.hpp, *.hh, *.hxx)", "ec, eh, c, cpp, cc, cxx, h, hpp, hh, hxx" },
82    { $"Header Files for C/C++ (*.eh, *.h, *.hpp, *.hh, *.hxx)", "eh, h, hpp, hh, hxx" },
83    { $"C/C++/eC Source Files (*.ec, *.c, *.cpp, *.cc, *.cxx)", "ec, c, cpp, cc, cxx" },
84    { $"Text files (*.txt)", "txt" },
85    { $"All files", null }
86 ] };
87
88 static Array<FileType> fileTypes
89 { [
90    { $"eC Source Code", "ec", whenNoneGiven },
91    { $"Text Files", "txt", never }
92 ] };
93
94 static char * iconNames[] =
95 {
96    "<:ecere>constructs/class.png",
97    "<:ecere>constructs/data.png",
98    "<:ecere>constructs/method.png",
99    "<:ecere>constructs/event.png",
100    "<:ecere>constructs/property.png",
101    "<:ecere>constructs/namespace.png",
102    "<:ecere>constructs/dataType.png",
103    "<:ecere>constructs/enumValue.png",
104    "<:ecere>constructs/dataPrivate.png",
105    "<:ecere>constructs/methodPrivate.png",
106    "<:ecere>constructs/propertyPrivate.png"
107 };
108
109 enum SheetType { methods, properties };
110
111 extern int __ecereVMethodID_class_OnEdit;
112 extern int __ecereVMethodID_class_OnDisplay;
113 extern int __ecereVMethodID_class_OnGetString;
114 extern int __ecereVMethodID_class_OnFree;
115 extern int __ecereVMethodID_class_OnCompare;
116 extern int __ecereVMethodID_class_OnCopy;
117 extern int __ecereVMethodID_class_OnSaveEdit;
118 extern int __ecereVMethodID___ecereNameSpace__ecere__com__Module_OnLoad;
119
120 class RTCMenuBits
121 {
122 public:
123    bool ignoreBreakpoints:1;
124    bool atSameLevel:1;
125    bool oldImplementation:1;
126 };
127
128 class EditFileDialog : FileDialog
129 {
130    bool OnCreate()
131    {
132       if(!ide.projectView && ideSettings.ideFileDialogLocation)
133          currentDirectory = ideSettings.ideFileDialogLocation;
134       return FileDialog::OnCreate();
135    }
136 }
137
138 EditFileDialog codeEditorFileDialog
139 {
140    type = multiOpen, text = $"Open",
141    types = fileTypes.array, sizeTypes = fileTypes.count * sizeof(FileType);
142    filters = fileFilters.array, sizeFilters = fileFilters.count * sizeof(FileFilter)
143 };
144
145 EditFileDialog codeEditorFormFileDialog
146 {
147    type = open, text = $"Open Project",
148    types = fileTypes.array, sizeTypes = fileTypes.count * sizeof(FileType),
149    filters = fileFilters.array, sizeFilters = fileFilters.count * sizeof(FileFilter)
150 };
151
152 define OpenBracket = '{';
153 define CloseBracket = '}';
154
155 enum MethodAction
156 {
157    actionAddMethod = 1,
158    actionDeleteMethod = 2,
159    actionDetachMethod = 3,
160    actionAttachMethod = 4,
161    actionReattachMethod = 5
162 };
163
164 //extern StatusField pos, ovr, caps, num;
165 //extern Class thisClass;
166
167 File output;
168
169 File fileInput;
170
171 bool parseError = false;
172
173 int returnCode;
174
175 Class insideClass;
176 Expression ctxInsideExp;
177 Expression paramsInsideExp;
178 ClassFunction insideFunction;
179 ClassDef insideDef;
180 Type instanceType;
181 char * instanceName;
182 Type functionType;
183 int paramsID;
184 bool insideInstance;
185
186 /****************************************************************************
187                               GENERATING
188 ****************************************************************************/
189
190 static void OutputString(File f, char * string)
191 {
192    int c;
193    for(c = 0; string[c]; c++)
194    {
195       if(string[c] == '\"')
196          f.Puts("\\\"");
197       else if(string[c] == '\\')
198          f.Puts("\\\\");
199       else
200          f.Putc(string[c]);
201    }
202 }
203
204 void OutputType(File f, Type type, bool outputName)
205 {
206    if(type)
207    {
208       switch(type.kind)
209       {
210          case voidType:
211             f.Printf("void");
212             break;
213          case charType:
214             if(!type.isSigned) f.Printf("unsigned ");
215             f.Printf("char");
216             break;
217          case shortType:
218             if(!type.isSigned) f.Printf("unsigned ");
219             f.Printf("short");
220             break;
221          case intType:
222             if(!type.isSigned) f.Printf("unsigned ");
223             f.Printf("int");
224             break;
225          case int64Type:
226             if(!type.isSigned) f.Printf("unsigned ");
227             f.Printf("__int64");
228             break;
229          case longType:
230             if(!type.isSigned) f.Printf("unsigned ");
231             f.Printf("long");
232             break;
233          case floatType:
234             f.Printf("float");
235             break;
236          case doubleType:
237             f.Printf("double");
238             break;
239          case classType:
240          {
241             if(type._class && !strcmp(type._class.string, "class"))
242             {
243                switch(type.classObjectType)
244                {
245                   case anyObject:
246                      f.Printf("any_object");
247                      break;
248                   default:
249                      f.Printf("typed_object");
250                      break;
251                }
252                if(type.byReference)
253                   f.Printf(" &");
254             }
255             else
256                // ADD CODE TO DECIDE WHETHER TO OUTPUT FULLY QUAlIFIED OR NOT:
257                f.Printf(type._class.shortName ? type._class.shortName : type._class.string);
258             break;
259          }
260          case structType:
261             break;
262          case unionType:
263             break;
264          case functionType:
265             break;
266          case arrayType:
267             OutputType(f, type.type, false);
268             break;
269          case pointerType:
270             OutputType(f, type.type, false);
271             f.Printf(" *");
272             break;
273          case ellipsisType:
274             f.Printf("...");
275             break;
276          case enumType:
277             break;
278          case methodType:
279             break;
280       }
281       if(outputName)
282       {
283          if(type.name)
284          {
285             f.Printf(" ");
286             f.Printf(type.name);
287          }
288       }
289       if(type.kind == arrayType)
290       {
291          f.Printf("[");
292          f.Printf("%d", type.arraySize);
293          f.Printf("]");
294       }
295    }
296 }
297
298 void DeleteJunkBefore(EditBoxStream f, int pos, int * position)
299 {
300    char ch;
301    int before = 0;
302
303    if(position)
304       f.Seek(pos - *position, current);
305
306    // Try to delete spaces and \n before...
307    f.Seek(-1, current);
308    for(;f.Getc(&ch);)
309    {
310       if(!isspace(ch))
311          break;
312       /*else if(ch == '\n')
313       {
314          // Look for // comments on the line before
315          EditBox editBox = f.editBox;
316          EditLine line = editBox.line;
317          char * text;
318          char last = 0;
319          int c;
320          bool quoted = false;
321          line = line.prev;
322          text = line.text;
323          for(c = 0; text[c]; c++)
324          {
325             if(text[c] == '"')
326             {
327                quoted ^= true;
328                last = 0;
329             }
330             else if(!quoted)
331             {
332                if(text[c] == '/' && last == '/')
333                   break;
334                last = text[c];
335             }
336          }
337          if(text[c])
338             break;
339       }*/
340       before++;
341       f.Seek(-2, current);
342    }
343
344    f.DeleteBytes(before);
345    if(position)
346       *position = pos;
347 }
348
349 void GetLocText(EditBox editBox, File f, int position, Location loc, char ** text, int * size, int pad, int linePad)
350 {
351    EditLine l1, l2;
352    int y1,x1, y2,x2;
353
354    editBox.GetSelPos(&l1, &y1, &x1, &l2, &y2, &x2, false);
355
356    // Cut & Paste function
357
358    {
359       EditLine l1, l2;
360       int y1,x1,y2,x2;
361
362       f.Seek(loc.start.pos - position, current);
363       l1 = editBox.line;
364       x1 = editBox.charPos;
365       y1 = editBox.lineNumber;
366       f.Seek(loc.end.pos - loc.start.pos, current);
367       l2 = editBox.line;
368       x2 = editBox.charPos;
369       y2 = editBox.lineNumber;
370       editBox.SetSelPos(l1, y1, x1, l2, y2, x2);
371
372       *size = editBox.SelSize();
373       *text = new char[*size+1 + (y2-y1+1) * linePad + pad]; // Add pad for tabs and new name
374       editBox.GetSel(*text, false);
375    }
376
377    editBox.SetSelPos(l1, y1, x1, l2, y2, x2);
378    f.Printf(""); // Make the stream point to where the editbox is
379 }
380
381 void Code_FixProperty(Property prop, Instance object)
382 {
383    Designer::FixProperty(prop, object);
384 }
385
386 bool Code_IsPropertyModified(Instance test, ObjectInfo selected, Property prop)
387 {
388    bool result = false;
389    if(prop.dataTypeString && (!prop.IsSet || prop.IsSet(selected.instance)))
390    {
391       Class dataType = prop.dataTypeClass;
392
393       if(!dataType)
394          dataType = prop.dataTypeClass = eSystem_FindClass(test._class.module, prop.dataTypeString);
395
396       if(dataType && dataType._vTbl && dataType.type == structClass)
397       {
398          void * dataForm = new0 byte[dataType.structSize];
399          void * dataTest = new0 byte[dataType.structSize];
400
401          ((void (*)(void *, void *))(void *)prop.Get)(selected.instance, dataForm);
402          ((void (*)(void *, void *))(void *)prop.Get)(test, dataTest);
403
404          if((prop.IsSet && !prop.IsSet(test)) || ((int (*)(void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnCompare])(dataType, dataForm, dataTest))
405          {
406             ((void (*)(void *, void *))(void *)prop.Set)(test, dataForm);
407             result = true;
408          }
409          delete dataForm;
410          delete dataTest;
411       }
412       else if(dataType && dataType._vTbl && (dataType.type == normalClass || dataType.type == noHeadClass))
413       {
414          void * dataForm, * dataTest;
415
416          dataForm = ((void *(*)(void *))(void *)prop.Get)(selected.instance);
417          dataTest = ((void *(*)(void *))(void *)prop.Get)(test);
418
419          if((prop.IsSet && !prop.IsSet(test)) || ((int (*)(void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnCompare])(dataType, dataForm, dataTest))
420          {
421             ((void (*)(void *, void *))(void *)prop.Set)(test, dataForm);
422             result = true;
423          }
424       }
425       else if(dataType && dataType._vTbl)
426       {
427          DataValue dataForm, dataTest;
428
429          GetProperty(prop, selected.instance, &dataForm);
430          GetProperty(prop, test, &dataTest);
431
432          if((prop.IsSet && !prop.IsSet(test)) || ((int (*)(void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnCompare])(dataType, &dataForm, &dataTest))
433          {
434             SetProperty(prop, test, dataForm);
435
436             // In case setting on test unset on real instance (e.g. isDefault)
437             if(strcmp(prop.name, "name"))
438             {
439                GetProperty(prop, selected.instance, &dataTest);
440                if(((int (*)(void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnCompare])(dataType, &dataForm, &dataTest))
441                   SetProperty(prop, selected.instance, dataForm);
442             }
443             result = true;
444          }
445       }
446    }
447    return result;
448 }
449
450 bool Code_IsPropertyDisabled(ObjectInfo selected, char * name)
451 {
452    bool disabled = false;
453    if(selected.oClass == selected)
454    {
455       ClassDef def;
456       if(selected.classDefinition)
457       {
458          for(def = selected.classDefinition.definitions->first; def; def = def.next)
459          {
460             if(def.type == defaultPropertiesClassDef)
461             {
462                MemberInit prop;
463                for(prop = def.defProperties->first; prop; prop = prop.next)
464                {
465                   if(prop.identifiers && prop.identifiers->first)
466                   {
467                      Identifier id = prop.identifiers->first;
468                      if(prop.variable && !strcmp(id.string, name))
469                      {
470                         disabled = true;
471                         break;
472                      }
473                   }
474                }
475             }
476             if(disabled) break;
477          }
478       }
479    }
480    else if(selected.instCode)
481    {
482       MembersInit members;
483       if(selected.instCode.members)
484       {
485          for(members = selected.instCode.members->first; members; members = members.next)
486          {
487             if(members.type == dataMembersInit && members.dataMembers)
488             {
489                MemberInit prop;
490                for(prop = members.dataMembers->first; prop; prop = prop.next)
491                {
492                   if(prop.identifiers && prop.identifiers->first)
493                   {
494                      Identifier id = prop.identifiers->first;
495                      if(prop.variable && !strcmp(id.string, name))
496                      {
497                         disabled = true;
498                         break;
499                      }
500                   }
501                }
502             }
503             if(disabled) break;
504          }
505       }
506    }
507    return disabled;
508 }
509
510 static bool CheckCompatibleMethod(Method method, Type type, Class regClass, bool isForm, Symbol selectedClass)
511 {
512    bool result = false;
513    bool reset = false;
514    if(!method.dataType)
515       method.dataType = ProcessTypeString(method.dataTypeString, false);
516    if(!method.dataType.thisClass && !isForm)
517    {
518       reset = true;
519       method.dataType.thisClass = selectedClass;
520    }
521    //result = MatchTypes(method.dataType, type, null, regClass, regClass, false);
522    result = MatchTypes(type, method.dataType, null, regClass, regClass, false, true, true, false);
523    if(reset)
524       method.dataType.thisClass = null;
525    return result;
526 }
527
528 bool Code_IsFunctionEmpty(ClassFunction function, Method method, ObjectInfo object)
529 {
530    bool confirmation = true;
531    Statement body = function.body;
532    // Check if it contains any code
533    if((!body.compound.declarations || !body.compound.declarations->count) && (!body.compound.statements || body.compound.statements->count <= 1))
534    {
535       Class moduleClass = eSystem_FindClass(object.instance._class.module, "Module");
536       Statement stmt = body.compound.statements ? body.compound.statements->first : null;
537       Type dataType = method.dataType;
538       Type returnType = dataType.returnType;
539       Expression exp = null;
540
541       if(!method.dataType)
542          method.dataType = ProcessTypeString(method.dataTypeString, false);
543
544       confirmation = false;
545
546       // Check if default function should be calling base class:
547       if(object.instance._class._vTbl[method.vid] == moduleClass._vTbl[__ecereVMethodID___ecereNameSpace__ecere__com__Module_OnLoad]) // Temp Check for DefaultFunction
548       {
549          if(returnType.kind != voidType)
550          {
551             if(!stmt || stmt.type != returnStmt || !stmt.expressions || stmt.expressions->count != 1)
552                confirmation = true;
553             else
554             {
555                exp = stmt.expressions->first;
556                if(returnType.kind == classType && !strcmp(returnType._class.string, "bool"))
557                {
558                   if( (exp.type != identifierExp || strcmp(exp.identifier.string, "true")) &&
559                       (exp.type != constantExp || strcmp(exp.constant, "1")))
560                      confirmation = true;
561                }
562                else
563                {
564                   if(exp.type != constantExp || strcmp(exp.constant, "0"))
565                      confirmation = true;
566                }
567             }
568          }
569          else
570          {
571             if(stmt)
572                confirmation = true;
573          }
574       }
575       else
576       {
577          if(stmt)
578          {
579             if(returnType.kind != voidType)
580             {
581                if(stmt.type == returnStmt && stmt.expressions && stmt.expressions->count == 1)
582                   exp = stmt.expressions->first;
583             }
584             else if(stmt.type == expressionStmt && stmt.expressions && stmt.expressions->count == 1)
585                exp = stmt.expressions->first;
586          }
587
588          if(!exp || exp.type != callExp || exp.call.exp.type != identifierExp)
589             confirmation = true;
590          else
591          {
592             Identifier id = exp.call.exp.identifier;
593             Class base = object.instance._class;
594             if(!id._class || (id._class.name && !strcmp(id._class.name, base.name)) || strcmp(id.string, method.name))
595                confirmation = true;
596             else
597             {
598                Expression arg = exp.call.arguments ? exp.call.arguments->first : null;
599                if(!arg || arg.type != identifierExp || strcmp("this", arg.identifier.string))
600                   confirmation = true;
601                else
602                {
603                   Type param;
604                   arg = arg.next;
605                   for(param = dataType.params.first; param; param = param.next)
606                   {
607                      if(!arg || arg.type != identifierExp || strcmp(param.name, arg.identifier.string))
608                      {
609                         confirmation = true;
610                         break;
611                      }
612                      arg = arg ?arg.next : null;
613                   }
614                }
615             }
616          }
617       }
618    }
619    return !confirmation;
620 }
621
622 class CodeEditor : Window
623 {
624    background = marginColor;
625    borderStyle = sizableDeep;
626    hasMaximize = true;
627    hasMinimize = true;
628    hasClose = true;
629    isDocument = true;
630    isActiveClient = true;
631    anchor = Anchor { left = 300, right = 150, top = 0, bottom = 0 };
632    menu = Menu { };
633
634    // eWindow_SetX(A_CASCADE); eWindow_SetY(A_CASCADE);
635    // eWindow_SetWidth(A_RELATIVE|80); eWindow_SetHeight(A_RELATIVE|80);
636
637    SheetType sheetSelected;
638    ToolBox toolBox;
639    Sheet sheet;
640
641    OldList * ast;
642    Context globalContext { };
643    OldList excludedSymbols { offset = (uint)&((Symbol)0).left };
644
645    OldList defines;
646    OldList imports;
647
648    OldList classes;
649    bool codeModified;
650    bool formModified;
651
652    ObjectInfo selected;
653    ObjectInfo oClass;
654
655    // Methods Editing:
656    MethodAction methodAction;
657    Method method;
658    ClassFunction function;
659    bool moveAttached;
660    char methodName[1024];
661
662    bool updatingCode;
663    bool loadingFile;
664    bool fixCaret;
665    bool membersListShown;
666    bool membersAbove;
667    Location membersLoc;
668    EditLine membersLine;
669
670    Type functionType, instanceType;
671    int paramsID;
672    bool paramsShown;
673    bool paramsAbove;
674    Point paramsPosition;
675    Expression functionExp;
676    bool expectingMove;
677
678    BitmapResource icons[CodeObjectType];
679
680    FontResource boldFont { $"Tahoma", 8.25f, bold = true, window = this };
681    FontResource normalFont { $"Tahoma", 8.25f, window = this };
682
683    Module privateModule;
684    NameSpace globalData;
685    bool skipModified;
686    bool inUseDebug;
687    OpenedFileInfo openedFileInfo;
688
689    FontResource font { codeFont.faceName, codeFont.size };
690    saveDialog = codeEditorFileDialog;
691
692    Designer designer { codeEditor = this, visible = false, saveDialog = codeEditorFormFileDialog };
693
694    bool noParsing;
695    int maxLineNumberLength;
696
697    property bool parsing { get { return editBox.syntaxHighlighting && !noParsing && !ide.noParsing; } };
698
699    void ProcessCaretMove(EditBox editBox, int line, int charPos)
700    {
701       char temp[512];
702       ObjectInfo classItem;
703
704       // OnActivateClient is called after OnActivate
705       if(!updatingCode)
706       {
707          sprintf(temp, $"Ln %d, Col %d", line, editBox.column + 1);
708          ide.pos.text = temp;
709       }
710       if(sheet.codeEditor != this) return;
711
712       if(!updatingCode)
713       {
714          for(classItem = classes.first; classItem; classItem = classItem.next)
715          {
716             ClassDefinition classDef = classItem.classDefinition;
717             if(classDef && classDef.loc.Inside(line, charPos))
718                break;
719          }
720
721          if(classItem)
722          {
723             ObjectInfo object;
724             for(object = classItem.instances.first; object; object = object.next)
725             {
726                if(object.instCode)
727                {
728                   if(object.instCode.loc.Inside(line, charPos))
729                      break;
730                }
731             }
732             if(object)
733                sheet.SelectObject(object);
734             else
735                sheet.SelectObject(classItem);
736             Update(null);
737          }
738          //else
739          {
740             //sheet.SelectObject(null);
741             //Update(null);
742          }
743
744          sprintf(temp, $"Ln %d, Col %d", line, editBox.column + 1);
745          ide.pos.text = temp;
746
747          if(expectingMove)
748             expectingMove = false;
749          else
750          {
751             if(membersListShown)
752             {
753                bool hide = false;
754                if(line-1 != membersLoc.start.line)
755                   hide = true;
756                else
757                {
758                   char * buffer = membersLine.text;
759                   int c;
760
761                   if(charPos - 1 < membersLoc.start.charPos)
762                      hide = true;
763                   else if(charPos - 1 > membersLoc.end.charPos)
764                   {
765                      char * buffer = membersLine.text;
766                      //if(membersList.currentRow)
767                      //   hide = true;
768                      //else
769                      {
770                         for(c = membersLoc.start.charPos; c<=charPos && buffer[c]; c++)
771                            if(buffer[c] != ' ' && buffer[c] != '\t')
772                               break;
773                         if(c < charPos && buffer[c])
774                            hide = true;
775                      }
776                   }
777                }
778                if(hide)
779                {
780                   membersList.Destroy(0);
781                   membersListShown = false;
782                }
783             }
784             {
785                bool back = codeModified;
786                codeModified = false;
787                if(paramsShown)
788                   InvokeParameters(false, false, false);
789                /*if(membersListShown)
790                   InvokeAutoComplete(false, 0, true);*/
791                codeModified = back;
792             }
793          }
794       }
795    }
796
797    watch(modifiedDocument)
798    {
799       ProjectView projectView = ide.projectView;
800       if(projectView)
801       {
802          char buffer[MAX_LOCATION];
803          char * fullPath = GetSlashPathBuffer(buffer, fileName);
804          Array<ProjectNode> nodes = ide.workspace.GetAllProjectNodes(fullPath, false);
805          if(nodes)
806          {
807             for(node : nodes)
808                node.modified = modifiedDocument;
809             projectView.Update(null);
810          }
811          delete nodes;
812       }
813    };
814
815
816    EditBox editBox
817    {
818       textVertScroll = true, multiLine = true, /*lineNumbers = ideSettings.showLineNumbers,*/
819       freeCaret = ideSettings.useFreeCaret, caretFollowsScrolling = ideSettings.caretFollowsScrolling,
820       tabKey = true, smartHome = true;
821       tabSelection = true, /*maxLineSize = 65536, */parent = this, hasHorzScroll = true, hasVertScroll = true;
822       selectionColor = selectionColor, selectionText = selectionText,
823       background = codeEditorBG, foreground = codeEditorFG, syntaxColorScheme = colorScheme,
824       font = font, borderStyle = none;
825       anchor = Anchor { left = 0, right = 0, top = 0, bottom = 0 };
826
827       bool OnMouseOver(int x, int y, Modifiers mods)
828       {
829          CodeEditor editor = (CodeEditor)master;
830          if(editor.designer && editor.designer.isDragging && !mods.isSideEffect)
831             Activate();
832          return true;
833       }
834
835       void NotifyCaretMove(EditBox editBox, int line, int charPos)
836       {
837          // Update Line Numbers
838          int spaceH;
839          int oldLine = lastLine;
840          display.FontExtent(font.font, " ", 1, null, &spaceH);
841          {
842             Box box { 0, (Min(oldLine,oldLine)-1) * spaceH - editBox.scroll.y, editBox.anchor.left.distance, (Max(oldLine, oldLine))*spaceH-1 - editBox.scroll.y };
843             Update(box);
844          }
845          {
846             Box box { 0, (Min(line,line)-1) * spaceH - editBox.scroll.y, editBox.anchor.left.distance, (Max(line, line))*spaceH-1 - editBox.scroll.y };
847             Update(box);
848          }
849          lastLine = line;
850
851          if(ide.activeClient == this)
852             ProcessCaretMove(editBox, line, charPos);
853          if(openedFileInfo)
854             openedFileInfo.CaretMove(line, charPos);
855       }
856
857       void NotifyOvrToggle(EditBox editBox, bool overwrite)
858       {
859          ide.UpdateStateLight(ide.ovr, overwrite);
860       }
861
862       void NotifyUpdate(EditBox editBox)
863       {
864          if(designer)
865          {
866             if(!skipModified)
867             {
868                codeModified = true;
869                designer.modifiedDocument = true;
870             }
871          }
872          modifiedDocument = true;
873       }
874
875       bool NotifyUnsetModified(EditBox editBox)
876       {
877          modifiedDocument = false;
878          return true;
879       }
880
881       bool NotifyCharsAdded(EditBox editBox, BufferLocation before, BufferLocation after, bool pasteOperation)
882       {
883          if(!loadingFile && after.y != before.y)
884          {
885             ProjectView projectView = ide.projectView;
886             if(projectView && fileName)
887             {
888                int c;
889                // HOW WE MIGHT WANT TO DO IT:
890                char * text = before.line.text;
891                for(c = before.x-1; c>= 0; c--)
892                   if(!isspace(text[c]))
893                      break;
894                ide.debugger.MoveIcons(fileName, before.y + (((!pasteOperation && c > -1) || !after.line.count) ? 1 : 0), after.y - before.y, false);
895
896                // HOW VISUAL STUDIO DOES IT:
897                /*
898                char * text = after.line.text;
899                for(c = after.line.count-1; c>= 0; c--)
900                   if(!isspace(text[c]))
901                      break;
902                ide.debugger.MoveIcons(fileName, before.y + ((c < 0) ? 1 : 0), after.y - before.y, false);
903                */
904             }
905             Update({ 0, 0, editBox.position.x, clientSize.h });
906             UpdateMarginSize();
907          }
908
909          if(!updatingCode)
910          {
911             ObjectInfo oClass;
912
913             for(oClass = classes.first; oClass; oClass = oClass.next)
914             {
915                ObjectInfo object;
916                for(object = oClass.instances.first; object; object = object.next)
917                {
918                   if(object.instCode)
919                   {
920                      object.instCode.loc.start.AdjustAdd(before, after);
921                      object.instCode.loc.end.AdjustAdd(before, after);
922                   }
923                }
924                if(oClass.instCode)
925                {
926                   oClass.classDefinition.loc.start.AdjustAdd(before, after);
927                   oClass.classDefinition.loc.end.AdjustAdd(before, after);
928                }
929             }
930
931             if(!pasteOperation)
932             {
933                expectingMove = true;
934                if(membersListShown)
935                {
936                   bool hide = false;
937                   if(before.y != after.y)
938                      hide = true;
939                   else
940                   {
941                      char * buffer = membersLine.text;
942                      int c;
943                      bool firstChar = true;
944                      bool addedChar = false;
945                      char string[1024];
946                      int len = 0;
947
948                      DataRow row;
949
950                      membersLoc.end.charPos += after.x - Max(membersLoc.start.charPos, before.x);
951
952                      for(c = membersLoc.start.charPos; c<membersLoc.end.charPos && len < sizeof(string)-1; c++)
953                      {
954                         bool isSpace = (buffer[c] == ' ' || buffer[c] == '\t');
955                         if(!isalnum(buffer[c]) && buffer[c] != '_' && (!isSpace || !firstChar)) //|| membersList.currentRow
956                         {
957                            hide = true;
958                            break;
959                         }
960                         if(!isSpace)
961                            firstChar = false;
962                         else if(firstChar)
963                         {
964                            membersLoc.start.charPos++;
965                            addedChar = true;
966                         }
967
968                         if(!firstChar)
969                            string[len++] = buffer[c];
970                      }
971                      if(firstChar)
972                      {
973                         row = membersList.currentRow;
974                         if(row && row.selected)
975                         {
976                            hide = true;
977                            if(addedChar)
978                               membersLoc.start.charPos--;
979                         }
980                      }
981
982                      string[len] = 0;
983
984                      if(!hide)
985                      {
986                         row = membersList.FindSubString(string);
987                         if(row)
988                            membersList.currentRow = row;
989                         else
990                         {
991                            row = membersList.FindSubStringi(string);
992                            if(row)
993                               membersList.currentRow = row;
994                            membersList.currentRow.selected = false;
995                         }
996                         if(row)
997                            membersList.SetScrollPosition(0, (row.index) * membersList.rowHeight);
998                      }
999                      else
1000                      {
1001                         row = membersList.currentRow;
1002                      }
1003
1004                      // Accept current string if hiding typing char
1005                      if(hide && row && row.selected)
1006                      {
1007                         char * string = row.string;
1008                         int len = strlen(string);
1009                         membersLoc.end.charPos -= after.x - before.x;
1010                         editBox.GoToPosition(membersLine, membersLoc.start.line, membersLoc.start.charPos);
1011                         editBox.Delete(membersLine, membersLoc.start.line, membersLoc.start.charPos,
1012                                        membersLine, membersLoc.end.line, membersLoc.end.charPos);
1013                         editBox.PutS(string);
1014                         editBox.GoToPosition(membersLine, membersLoc.start.line, membersLoc.start.charPos + len + 1 /*after.x - before.x*/);
1015
1016                         after.x += membersLoc.start.charPos + len - before.x;
1017                         before.x = membersLoc.start.charPos + len;
1018                      }
1019                   }
1020                   if(hide)
1021                   {
1022                      membersList.Destroy(0);
1023                      membersListShown = false;
1024                   }
1025                }
1026                if(/*after.x - before.x == 1 && */after.y == before.y && !membersListShown)
1027                {
1028                   EditLine line = editBox.line;
1029                   char * text = line.text;
1030                   char ch = text[after.x-1];
1031                   if(ch == '.' || (ch == '>' && after.x-1 > 0 && text[after.x-1-1] == '-') || (ch == ':' && after.x-1 > 0 && text[after.x-1-1] == ':'))
1032                   {
1033
1034                      /*
1035                      // Can we call invoke auto complete here instead?
1036
1037
1038                      int line, charPos;
1039                      Expression exp;
1040                      void * l1, * l2;
1041                      int x1,y1, x2,y2;
1042                      int oldCharPos;
1043                      Point caret;
1044
1045                      // Force caret update already...
1046                      editBox.GetSelPos(&l1, &y1, &x1, &l2, &y2, &x2, false);
1047                      editBox.SetSelPos(l1, y1, x1, l2, y2, x2);
1048
1049                      editBox.GetCaretPosition(&caret);
1050
1051
1052
1053                      // Go back in the buffer until no space before
1054                      //yydebug = true;
1055                      codeModified = true;
1056                      EnsureUpToDate();
1057                      SetYydebug(false);
1058                      {
1059                         EditBoxStream f { editBox = editBox };
1060                         oldCharPos = x1;
1061                         x1--;
1062                         x2--;
1063                         if(text[after.x-1] == '>')
1064                         {
1065                            x1--;
1066                            x2--;
1067                         }
1068
1069                         editBox.SetSelPos(l1, y1, x1, l2, y2, x2);
1070                         for(;;)
1071                         {
1072                            char ch;
1073                            if(!f.Seek(-1, current))
1074                               break;
1075                            f.Getc(&ch);
1076                            if(!isspace(ch)) break;
1077                            f.Seek(-1, current);
1078                         }
1079                         editBox.GetSelPos(&l1, &y1, &x1, &l2, &y2, &x2, false);
1080
1081                         line = editBox.lineNumber + 1;
1082                         charPos = editBox.charPos + 1;
1083                         delete f;
1084                      }
1085
1086                      exp = FindExpTree(ast, line, charPos);
1087
1088                      if(exp)
1089                      {
1090                         Type type = exp.expType;
1091
1092                         if(type && text[after.x-1] != '.')
1093                         {
1094                            if(type.kind == TypePointer || type.kind == TypeArray)
1095                               type = type.type;
1096                            else
1097                               type = null;
1098                         }
1099
1100                         membersList.Clear();
1101                         ListMembers(type);
1102
1103                         if(membersList.rowCount)
1104                         {
1105                            membersList.Sort(null, 1);
1106                            membersList.master = this;
1107
1108                            caret.y += editBox.GetCaretSize();
1109                            caret.x -= 20;
1110
1111                            membersList.Create();
1112
1113                            {
1114                               int x = caret.x + editBox.GetAbsX() - app.desktop.GetAbsX() - editBox.GetScrollX();
1115                               int y = caret.y + editBox.GetAbsY() - app.desktop.GetAbsY() - editBox.GetScrollY();
1116                               Window parent = membersList.parent;
1117
1118                               if(!paramsAbove && (paramsShown || y + membersList.GetHeight() > parent.GetClientHeight()))
1119                               {
1120                                  y -= editBox.GetCaretSize() + membersList.GetHeight();
1121                                  membersAbove = true;
1122                               }
1123                               else
1124                                  membersAbove = false;
1125
1126                               membersList.position = { x, y };
1127                            }
1128
1129                            membersLine = l1;
1130                            membersLoc.start.line = line - 1;
1131                            membersLoc.start.charPos = oldCharPos;
1132                            membersLoc.end = membersLoc.start;
1133                            membersListShown = true;
1134                         }
1135                      }
1136
1137                      SetThisClass(null);
1138                      SetCurrentContext(globalContext);
1139                      */
1140                      codeModified = true;
1141                      skipModified = true;
1142                      if(text[after.x-1] == ':')
1143                         InvokeAutoComplete(false, 0, false);
1144                      else if(text[after.x-1] == '.')
1145                         InvokeAutoComplete(false, 1, false);
1146                      else if(text[after.x-1] == '>')
1147                         InvokeAutoComplete(false, 2, false);
1148                      skipModified = false;
1149                   }
1150                   else if(ch == '(' || ch == OpenBracket || ch == ',' || ch == '='  || ch == '?'  || ch == ':')
1151                   {
1152                      codeModified = true;
1153                      skipModified = true;
1154
1155                      if(InvokeAutoComplete(true, 0, false))
1156                      {
1157                         if(ch == '(' || ch == OpenBracket)
1158                            InvokeParameters(true, true, false);
1159                         else
1160                            InvokeParameters(this.functionType ? false : true, false, false);
1161                      }
1162
1163                      // InvokeAutoComplete(true, 0, false);
1164                      skipModified = false;
1165                   }
1166                   else if(ch == ')' || ch == '}' || ch == ';')
1167                   {
1168                      codeModified = true;
1169                      skipModified = true;
1170                      if(paramsShown)
1171                         InvokeParameters(false, true, false);
1172                      skipModified = false;
1173                   }
1174                   else
1175                   {
1176                      bool back = codeModified;
1177                      codeModified = false;
1178                      if(paramsShown)
1179                         InvokeParameters(false, false, true);
1180                      if(membersListShown)
1181                         InvokeAutoComplete(false, 0, true);
1182                      codeModified = back;
1183                   }
1184                }
1185                else
1186                {
1187                   bool back = codeModified;
1188                   codeModified = false;
1189
1190                   if(paramsShown)
1191                      InvokeParameters(false, false, true);
1192                   /*if(membersListShown)
1193                      InvokeAutoComplete(false, 0, true);*/
1194
1195                   codeModified = back;
1196                }
1197             }
1198          }
1199          return true;
1200       }
1201
1202       bool NotifyCharsDeleted(EditBox editBox, BufferLocation before, BufferLocation after, bool pasteOperation)
1203       {
1204          if(!loadingFile && after.y != before.y)
1205          {
1206             ProjectView projectView = ide.projectView;
1207             if(projectView && fileName)
1208                ide.debugger.MoveIcons(fileName, before.y + 1, before.y - after.y, before.x == 0);
1209             Update({ 0, 0, editBox.position.x, clientSize.h });
1210             UpdateMarginSize();
1211          }
1212
1213          if(!updatingCode)
1214          {
1215             ObjectInfo oClass;
1216
1217             for(oClass = classes.first; oClass; oClass = oClass.next)
1218             {
1219                ObjectInfo object;
1220                Location * loc;
1221                for(object = oClass.instances.first; object; object = object.next)
1222                {
1223                   if(object.instCode)
1224                   {
1225                      loc = &object.instCode.loc;
1226
1227                      if((before.y+1 < loc->start.line || (before.y+1 == loc->start.line && before.x+1 <= loc->start.charPos)) &&
1228                         (after.y+1 > loc->end.line    || (after.y+1 == loc->end.line && after.x+1 >= loc->end.charPos)))
1229                      {
1230                         object.instCode = null;
1231                      }
1232                      else
1233                      {
1234                         loc->start.AdjustDelete(before, after);
1235                         loc->end.AdjustDelete(before, after);
1236                      }
1237                   }
1238                }
1239                if(oClass.classDefinition)
1240                {
1241                   loc = &oClass.classDefinition.loc;
1242                   if((before.y+1 < loc->start.line || (before.y+1 == loc->start.line && before.x+1 <= loc->start.charPos)) &&
1243                      (after.y+1 > loc->end.line    || (after.y+1 == loc->end.line && after.x+1 >= loc->end.charPos)))
1244                   {
1245                      oClass.classDefinition = null;
1246                   }
1247                   else
1248                   {
1249                      loc->start.AdjustDelete(before, after);
1250                      loc->end.AdjustDelete(before, after);
1251                   }
1252                }
1253             }
1254
1255             if(membersListShown)
1256             {
1257                bool hide = false;
1258                if(pasteOperation || before.y != after.y)
1259                   hide = true;
1260                else
1261                {
1262                   char * buffer = membersLine.text;
1263                   int c;
1264                   bool firstChar = true;
1265                   char string[1024];
1266                   int len = 0;
1267
1268                   if(before.x >= membersLoc.start.charPos)
1269                   {
1270                      for(c = membersLoc.start.charPos; c<before.x && len < sizeof(string)-1; c++)
1271                      {
1272                         bool isSpace = (buffer[c] == ' ' || buffer[c] == '\t');
1273                         if(!isalnum(buffer[c]) && buffer[c] != '_' && (!isSpace || !firstChar))
1274                         {
1275                            hide = true;
1276                            break;
1277                         }
1278                         if(!isSpace) firstChar = false;
1279
1280                         if(!firstChar)
1281                            string[len++] = buffer[c];
1282                      }
1283                   }
1284                   else
1285                   {
1286                      // If deleting spaces before...
1287                      for(c = before.x; c<membersLoc.start.charPos; c++)
1288                      {
1289                         bool isSpace = (buffer[c] == ' ' || buffer[c] == '\t');
1290                         if(!isSpace)
1291                         {
1292                            hide = true;
1293                            break;
1294                         }
1295                      }
1296                      if(!hide)
1297                         membersLoc.start.charPos = before.x;
1298                   }
1299
1300                   if(membersLoc.end.charPos >= after.x)
1301                   {
1302                      for(c = after.x; c<membersLoc.end.charPos && len < sizeof(string)-1; c++)
1303                      {
1304                         bool isSpace = (buffer[c] == ' ' || buffer[c] == '\t');
1305                         if(!isalnum(buffer[c]) && buffer[c] != '_' && (!isSpace || !firstChar))
1306                         {
1307                            hide = true;
1308                            break;
1309                         }
1310                         if(!isSpace) firstChar = false;
1311
1312                         if(!firstChar)
1313                            string[len++] = buffer[c];
1314                      }
1315                   }
1316                   else
1317                      hide = true;
1318
1319                   string[len] = '\0';
1320
1321                   membersLoc.end.charPos -= after.x - before.x;
1322                   if(!hide)
1323                   {
1324                      DataRow row;
1325                      row = membersList.FindSubString(string);
1326                      if(!row)
1327                      {
1328                         row = membersList.FindSubStringi(string);
1329                         if(row)
1330                            membersList.currentRow = row;
1331                         membersList.currentRow.selected = false;
1332                      }
1333                      else
1334                         membersList.currentRow = row;
1335                      if(row)
1336                         membersList.SetScrollPosition(0, row.index * membersList.rowHeight);
1337                   }
1338                }
1339                if(hide)
1340                {
1341                   membersList.Destroy(0);
1342                   membersListShown = false;
1343                }
1344
1345                /*
1346                if(paramsShown)
1347                {
1348                   InvokeParameters(false, false);
1349                }
1350                */
1351             }
1352          }
1353          return true;
1354       }
1355
1356       bool NotifyDropped(EditBox editBox, int x, int y)
1357       {
1358          char * controlClass = toolBox.controlClass;
1359          if(controlClass && controlClass[0])
1360          {
1361             Instance control;
1362             ObjectInfo object;
1363             ObjectInfo classObject;
1364
1365             editBox.GoToLineNum(y);
1366             x = Min(x, editBox.line.count);
1367             editBox.GoToPosition(editBox.line, y, x);
1368             // Note: Uncommented this to drag objects after the member instance on which they are dropped
1369             editBox.NotifyCaretMove(this, editBox, y+1, x+1);
1370
1371             classObject = selected ? selected.oClass : null;
1372
1373             if((!selected || selected == classObject) && classObject && classObject.instances.first)
1374                selected = classObject.instances.last;
1375
1376             UpdateFormCode();
1377             control = eInstance_New(eSystem_FindClass(privateModule, controlClass));
1378             if(control)
1379             {
1380                AddObject(control, &object);
1381
1382                designer.CreateObject(control, object, false, classObject.instance);
1383                // designer.PostCreateObject(control, object, false, classObject.instance);
1384                designer.DroppedObject(control, object, false, classObject.instance);
1385
1386                sheet.AddObject(object, object.name, typeData /* className*/, true);
1387
1388                UpdateFormCode();
1389                //codeModified = true;
1390                EnsureUpToDate();
1391             }
1392          }
1393          return true;
1394       }
1395
1396       bool NotifyKeyDown(EditBox editBox, Key key, unichar ch)
1397       {
1398          if(key == ctrlSpace)
1399          {
1400             membersList.Destroy(0);
1401             membersListShown = false;
1402             InvokeAutoComplete(false, 0, false);
1403             return false;
1404          }
1405          else if(key == Key { space, ctrl = true, shift = true })
1406             InvokeParameters(false, true, false);
1407          else if(key == escape)
1408             ide.RepositionWindows(true);
1409          else if(key == ctrlF7)
1410          {
1411             if(ide.projectView)
1412             {
1413                ProjectNode node = ide.projectView.GetNodeForCompilationFromWindow(this, false, null, null);
1414                if(!node)
1415                {
1416                   char * s;
1417                   s = PrintString($"The ", fileName, $" file is not part of any project.\n",
1418                      $"It can't be compiled.");
1419                   MessageBox { type = ok, /*parent = ide, */master = ide, text = $"File not in project error", contents = s }.Modal();
1420                   delete s;
1421                   return false;
1422                }
1423             }
1424          }
1425          return true;
1426       }
1427
1428       bool OnKeyDown(Key key, unichar ch)
1429       {
1430          CodeEditor editor = (CodeEditor)master;
1431          if(key == escape /*|| key == leftAlt || key == rightAlt || (key.ctrl && key.code != left && key.code != right && key.code != leftShift && key.code != rightShift && key.code !=  space)*/)
1432          {
1433             if(editor.membersListShown)
1434             {
1435                editor.membersList.Destroy(0);
1436                editor.membersListShown = false;
1437                return false;
1438             }
1439             if(editor.paramsShown)
1440             {
1441                editor.paramsList.Destroy(0);
1442                editor.paramsShown = false;
1443                FreeType(editor.functionType);
1444                FreeType(editor.instanceType);
1445
1446                editor.functionType = null;
1447                editor.instanceType = null;
1448                editor.paramsID = -1;
1449                return false;
1450             }
1451          }
1452          return EditBox::OnKeyDown(key, ch);
1453       }
1454
1455       void OnVScroll(ScrollBarAction action, int position, Key key)
1456       {
1457          if(anchor.left.distance)
1458          {
1459             Box box { 0, 0, anchor.left.distance-1, parent.clientSize.h - 1 };
1460             parent.Update(box);
1461          }
1462          EditBox::OnVScroll(action, position, key);
1463          {
1464             CodeEditor ce = (CodeEditor)parent;
1465             if(ce.openedFileInfo)
1466                ce.openedFileInfo.ScrollChange({ scroll.x, position });
1467          }
1468       }
1469
1470       void OnHScroll(ScrollBarAction action, int position, Key key)
1471       {
1472          EditBox::OnHScroll(action, position, key);
1473          {
1474             CodeEditor ce = (CodeEditor)parent;
1475             if(ce.openedFileInfo)
1476                ce.openedFileInfo.ScrollChange({ position, scroll.y });
1477          }
1478       }
1479    };
1480    ListBox membersList
1481    {
1482       master = this,
1483       fullRowSelect = false,
1484       interim = true,
1485       autoCreate = false,
1486       borderStyle = bevel;
1487       // size = { 200, 400 };
1488
1489       bool NotifyDoubleClick(ListBox listBox, int x, int y, Modifiers mods)
1490       {
1491          DataRow row = listBox.currentRow;
1492          if(row)
1493          {
1494             char * string = row.string;
1495
1496             editBox.GoToPosition(membersLine, membersLoc.start.line, membersLoc.start.charPos);
1497             editBox.Delete(
1498                membersLine, membersLoc.start.line, membersLoc.start.charPos,
1499                membersLine, membersLoc.end.line, membersLoc.end.charPos);
1500             editBox.PutS(string);
1501
1502             listBox.Destroy(0);
1503             membersListShown = false;
1504          }
1505          return true;
1506       }
1507
1508       bool OnKeyDown(Key key, unichar ch)
1509       {
1510          CodeEditor editor = (CodeEditor) master;
1511          if(key == escape || key == leftAlt || key == rightAlt ||
1512             (key.ctrl && key.code != left && key.code != right &&
1513              key.code != leftShift && key.code != rightShift && key.code != space))
1514          {
1515             bool result = true;
1516             if(editor.paramsShown)
1517             {
1518                if(key == escape)
1519                   result = false;
1520                editor.paramsList.Destroy(0);
1521                editor.paramsShown = false;
1522             }
1523             if(editor.membersListShown)
1524             {
1525                if(key == escape)
1526                   result = false;
1527                editor.membersList.Destroy(0);
1528                editor.membersListShown = false;
1529             }
1530
1531             FreeType(editor.functionType);
1532             editor.functionType = null;
1533
1534             FreeType(editor.instanceType);
1535             editor.instanceType = null;
1536
1537             editor.paramsID = -1;
1538
1539             return result;
1540          }
1541          else
1542             return editor.editBox.OnKeyDown(key, ch);
1543          return false;
1544       }
1545
1546       /*bool OnActivate(bool active, Window previous, bool * goOnWithActivation, bool direct)
1547       {
1548          CodeEditor editor = (CodeEditor)master;
1549          Window rw = previous ? previous.rootWindow : null;
1550          if(!active && rw != editor.paramsList)
1551          {
1552             Destroy(0);
1553             editor.membersListShown = false;
1554          }
1555          return ListBox::OnActivate(active, previous, goOnWithActivation, direct);
1556       }*/
1557
1558       bool OnKeyHit(Key key, unichar ch)
1559       {
1560          CodeEditor editor = (CodeEditor) master;
1561
1562          switch(key)
1563          {
1564             case enter: case tab:
1565             {
1566                DataRow row = currentRow;
1567                if(row && row.selected)
1568                {
1569                   char * string = row.string;
1570
1571                   editor.editBox.GoToPosition(editor.membersLine, editor.membersLoc.start.line, editor.membersLoc.start.charPos);
1572                   editor.editBox.Delete(
1573                      editor.membersLine, editor.membersLoc.start.line, editor.membersLoc.start.charPos,
1574                      editor.membersLine, editor.membersLoc.end.line, editor.membersLoc.end.charPos);
1575                   editor.editBox.PutS(string);
1576
1577                   Destroy(0);
1578                   editor.membersListShown = false;
1579                }
1580                else
1581                   editor.editBox.OnKeyHit(key, ch);
1582                break;
1583             }
1584             case down:
1585             case up:
1586             case pageDown:
1587             case pageUp:
1588             case home:
1589             case end:
1590             {
1591                return ListBox::OnKeyHit(key, ch);
1592             }
1593             default:
1594             {
1595                /*
1596                bool result;
1597                // If before . or after
1598                //listBox.Destroy(true);
1599                result = editor.editBox.OnKeyHit(key, ch);
1600                return result;
1601                */
1602                return true;
1603             }
1604          }
1605
1606          return false;
1607       }
1608    };
1609
1610    Window paramsList
1611    {
1612       master = this,
1613       interim = true,
1614       clickThrough = true,
1615       autoCreate = false,
1616       borderStyle = contour,
1617       cursor = null,
1618       background = { 255,255,225 },
1619
1620       OnKeyDown = membersList.OnKeyDown;
1621
1622       /*bool OnActivate(bool active, Window previous, bool * goOnWithActivation, bool direct)
1623       {
1624          CodeEditor editor = (CodeEditor)master;
1625          Window rw = previous ? previous.rootWindow : null;
1626          if(!active && previous != editor.editBox && rw != editor.membersList)
1627          {
1628             Destroy(0);
1629             editor.paramsShown = false;
1630          }
1631          return Window::OnActivate(active, previous, goOnWithActivation, direct);
1632       }*/
1633
1634       bool OnKeyHit(Key key, unichar ch)
1635       {
1636          CodeEditor editor = (CodeEditor)master;
1637
1638          if(!editor.membersListShown || editor.membersList.OnKeyHit(key, ch))
1639          {
1640             /*
1641             bool result = true; editor.editBox.OnKeyHit(key, ch);
1642             return (!created) ? false : result;
1643             */
1644             return true;
1645          }
1646          return false;
1647       }
1648
1649       void OnRedraw(Surface surface)
1650       {
1651          CodeEditor editor = (CodeEditor) master;
1652          Type type = editor.functionType ? editor.functionType : editor.instanceType;
1653          Type param;
1654          Type methodType = null;
1655
1656          char string[1024];
1657
1658          int functionW, nameW = 0;
1659          int totalW = 0;
1660          int spaceW, spaceH, commaW, commaWB, parW;
1661          int availW = 1024;
1662          int maxW = 0, lineW = 0;
1663          int realW = 0;
1664          int height = 0;
1665          int x = 2, y = 2;
1666          int id = 0;
1667
1668          Font font = editor.normalFont.font;
1669          Font boldFont = editor.boldFont.font;
1670          Display display = this.display;
1671
1672          if(!type) { return; };
1673
1674          if(type.kind == TypeKind::methodType) { methodType = type; type = type.method.dataType; }
1675
1676          display.FontExtent(boldFont, " ", 1, &spaceW, &spaceH);
1677          display.FontExtent(font, ", ", 2, &commaW, null);
1678          display.FontExtent(boldFont, ", ", 2, &commaWB, null);
1679          display.FontExtent(font, ")", 1, &parW, null);
1680
1681          string[0] = 0;
1682          if(editor.functionType)
1683          {
1684             PrintType(type.returnType, string, true, true);
1685             display.FontExtent(font, string, strlen(string), &functionW, null);
1686             if(type.name)
1687                display.FontExtent(font, type.name, strlen(type.name), &nameW, null);
1688             totalW = nameW + functionW + 2 * parW;
1689          }
1690          else
1691          {
1692             PrintType(type, string, (type.kind == functionType) ? true : false, true); // true);
1693             display.FontExtent(boldFont, string, strlen(string), &functionW, null);
1694             if(instanceName && type.kind != functionType)
1695                display.FontExtent(boldFont, instanceName, strlen(instanceName), &nameW, null);
1696             totalW = functionW + nameW;
1697             surface.TextFont(boldFont);
1698          }
1699
1700          surface.WriteText(x, y, string, strlen(string));
1701          x += functionW + spaceW;
1702
1703          if(editor.functionType)
1704          {
1705             if(type.name)
1706                surface.WriteText(x, y, type.name, strlen(type.name));
1707             x += nameW;
1708             surface.WriteText(x, y, "(", 1);
1709             x += parW;
1710
1711             if(methodType && !methodType.staticMethod && methodType.methodClass)
1712             {
1713                int tw = 0, width;
1714
1715                if(id == editor.paramsID)
1716                   surface.TextFont(boldFont);
1717
1718                if(methodType.methodClass)
1719                   surface.TextExtent(methodType.methodClass.name, strlen(methodType.methodClass.name), &tw, null);
1720
1721                width = tw;
1722
1723                if(type.params.first && (((Type)type.params.first).kind != voidType || type.params.count > 1))
1724                   width += ((id == editor.paramsID) ? commaWB : commaW);
1725
1726                if(!height)
1727                   maxW = lineW;
1728
1729                if(lineW && ((height && lineW + width > maxW) || (totalW + lineW + width + 20 > availW)))
1730                {
1731                   height += spaceH;
1732                   lineW = 0;
1733
1734                   x = 2 + nameW + spaceW + functionW + parW;
1735                   y += spaceH;
1736
1737                }
1738                if(methodType.methodClass)
1739                   surface.WriteText(x, y, methodType.methodClass.name, strlen(methodType.methodClass.name));
1740
1741                x += tw;
1742                if(type.params.first && (((Type)type.params.first).kind != voidType || type.params.count > 1))
1743                {
1744                   surface.WriteText(x, y, ",", 1);
1745                   x += ((id ==  editor.paramsID) ? commaWB : commaW);
1746                }
1747
1748                lineW += width;
1749
1750                if(lineW > realW)
1751                   realW = lineW;
1752
1753                if(id == editor.paramsID)
1754                   surface.TextFont(font);
1755                id ++;
1756             }
1757
1758             if(!methodType || (methodType.staticMethod || !methodType.methodClass) || !type.params.first || ((Type)type.params.first).kind != voidType || type.params.count > 1)
1759             {
1760                for(param = type.params.first; param; param = param.next)
1761                {
1762                   char paramString[1024];
1763                   int tw, width;
1764
1765                   if(id == editor.paramsID || (param.kind == ellipsisType && id < editor.paramsID && editor.paramsID != -1))
1766                      surface.TextFont(boldFont);
1767
1768                   paramString[0] = 0;
1769                   PrintType(param, paramString, true, true);
1770                   surface.TextExtent(paramString, strlen(paramString), &tw, null);
1771                   width = tw;
1772                   if(param.next) width += ((id ==  editor.paramsID) ? commaWB : commaW);
1773
1774                   if(!height)
1775                      maxW = lineW;
1776
1777                   if(lineW && ((height && lineW + width > maxW) || (totalW + lineW + width + 20 > availW)))
1778                   {
1779                      height += spaceH;
1780                      lineW = 0;
1781
1782                      x = 2 + nameW + spaceW + functionW + parW;
1783                      y += spaceH;
1784
1785                   }
1786                   surface.WriteText(x, y, paramString, strlen(paramString));
1787                   x += tw;
1788                   if(param.next)
1789                   {
1790                      surface.WriteText(x, y, ",", 1);
1791                      x += ((id ==  editor.paramsID) ? commaWB : commaW);
1792                   }
1793
1794                   lineW += width;
1795
1796                   if(lineW > realW)
1797                      realW = lineW;
1798
1799                   if(id == editor.paramsID || (param.kind == ellipsisType && id < editor.paramsID && editor.paramsID != -1))
1800                      surface.TextFont(font);
1801                   id ++;
1802                }
1803             }
1804
1805             surface.WriteText(x, y, ")", 1);
1806          }
1807          else if(instanceName && type.kind != functionType)
1808          {
1809             surface.WriteText(x, y, instanceName, strlen(instanceName));
1810          }
1811       }
1812
1813       bool OnResizing(int * w, int * h)
1814       {
1815          CodeEditor editor = (CodeEditor) master;
1816          Type type = editor.functionType ? editor.functionType : editor.instanceType;
1817          Type param;
1818          Type methodType = null;
1819
1820          char string[1024];
1821
1822          int functionW = 0, nameW = 0;
1823          int totalW = 0;
1824          int spaceW, spaceH, commaW, commaWB, parW;
1825          int availW = 1024;
1826          int maxW = 0, lineW = 0;
1827          int realW = 0;
1828          int height = 0;
1829          int id = 0;
1830
1831          Font font = editor.normalFont.font;
1832          Font boldFont = editor.boldFont.font;
1833          Display display = this.display;
1834
1835          if(type.kind == TypeKind::methodType)
1836          {
1837             methodType = type;
1838             ProcessMethodType(type.method);
1839             type = type.method.dataType;
1840          }
1841
1842          display.FontExtent(boldFont, " ", 1, &spaceW, &spaceH);
1843          display.FontExtent(font, ", ", 2, &commaW, null);
1844          display.FontExtent(boldFont, ", ", 2, &commaWB, null);
1845          display.FontExtent(font, ")", 1, &parW, null);
1846
1847          string[0] = 0;
1848          if(editor.functionType && type)
1849          {
1850             PrintType(type.returnType, string, true, true);
1851             display.FontExtent(font, string, strlen(string), &functionW, null);
1852             if(type.name)
1853                display.FontExtent(font, type.name, strlen(type.name), &nameW, null);
1854             totalW = nameW + spaceW + functionW + 2 * parW;
1855          }
1856          else if(type)
1857          {
1858             PrintType(type, string, false, true); // /*true);
1859             display.FontExtent(boldFont, string, strlen(string), &functionW, null);
1860             if(instanceName && type.kind != functionType)
1861                display.FontExtent(boldFont, instanceName, strlen(instanceName), &nameW, null);
1862             totalW = functionW + nameW + spaceW;
1863          }
1864
1865          if(editor.functionType)
1866          {
1867             if(methodType)
1868             {
1869                int width = 0;
1870
1871                if(methodType.methodClass)
1872                   display.FontExtent((id == editor.paramsID) ? boldFont : font, methodType.methodClass.name, strlen(methodType.methodClass.name), &width, null);
1873                if(type.params.first && (((Type)type.params.first).kind != voidType || type.params.count > 1))
1874                   width += ((id == editor.paramsID) ? commaWB : commaW);
1875
1876                if(!height)
1877                   maxW = lineW;
1878
1879                if(lineW && ((height && lineW + width > maxW) || (totalW + lineW + width + 20 > availW)))
1880                {
1881                   height += spaceH;
1882                   lineW = 0;
1883                }
1884
1885                lineW += width;
1886
1887                if(lineW > realW)
1888                   realW = lineW;
1889
1890                id++;
1891             }
1892             if(!methodType || methodType.staticMethod || !type.params.first || ((Type)type.params.first).kind != voidType || type.params.count > 1)
1893             {
1894                for(param = type.params.first; param; param = param.next)
1895                {
1896                   char paramString[1024];
1897                   int width = 0;
1898
1899                   paramString[0] = 0;
1900                   PrintType(param, paramString, true, true);
1901                   display.FontExtent((id == editor.paramsID || param.kind == ellipsisType) ? boldFont : font, paramString, strlen(paramString), &width, null);
1902                   if(param.next)
1903                      width += ((id == editor.paramsID) ? commaWB : commaW);
1904
1905                   if(!height)
1906                      maxW = lineW;
1907
1908                   if(lineW && ((height && lineW + width > maxW) || (totalW + lineW + width + 20 > availW)))
1909                   {
1910                      height += spaceH;
1911                      lineW = 0;
1912                   }
1913
1914                   lineW += width;
1915
1916                   if(lineW > realW)
1917                      realW = lineW;
1918
1919                   id++;
1920                }
1921             }
1922          }
1923          height += spaceH;
1924
1925          *w = realW + totalW + 4;
1926          *h = height + 4;
1927          return true;
1928       }
1929    };
1930
1931    Menu fileMenu { menu, $"File", f };
1932    MenuItem { fileMenu, $"Save", s, Key { s, ctrl = true }, NotifySelect = MenuFileSave };
1933    MenuItem { fileMenu, $"Save As...", a, NotifySelect = MenuFileSaveAs };
1934
1935    Menu debugMenu { menu, $"Debug", d };
1936    MenuItem debugRunToCursor                { debugMenu, $"Run To Cursor", c, ctrlF10,                                                                  id = RTCMenuBits { false, false, false }, NotifySelect = RTCMenu_NotifySelect; };
1937    MenuItem debugSkipRunToCursor            { debugMenu, $"Run To Cursor Skipping Breakpoints", u, Key { f10, ctrl = true, shift = true },              id = RTCMenuBits { true,  false, false }, NotifySelect = RTCMenu_NotifySelect; };
1938    MenuItem debugRunToCursorAtSameLevel     { debugMenu, $"Run To Cursor At Same Level", l, altF10,                                                     id = RTCMenuBits { false, true,  false }, NotifySelect = RTCMenu_NotifySelect; };
1939    MenuItem debugSkipRunToCursorAtSameLevel { debugMenu, $"Run To Cursor At Same Level Skipping Breakpoints", g, Key { f10, shift = true, alt = true }, id = RTCMenuBits { true,  true,  false }, NotifySelect = RTCMenu_NotifySelect; };
1940 #if 0
1941    MenuItem debugBpRunToCursor                { debugMenu, $"BP Run To Cursor"/*, c, ctrlF10*/,                                                                  id = RTCMenuBits { false, false, true  }, NotifySelect = RTCMenu_NotifySelect; };
1942    MenuItem debugBpSkipRunToCursor            { debugMenu, $"BP Run To Cursor Skipping Breakpoints"/*, u, Key { f10, ctrl = true, shift = true }*/,              id = RTCMenuBits { true,  false, true  }, NotifySelect = RTCMenu_NotifySelect; };
1943    MenuItem debugBpRunToCursorAtSameLevel     { debugMenu, $"BP Run To Cursor At Same Level"/*, l, altF10*/,                                                     id = RTCMenuBits { false, true,  true  }, NotifySelect = RTCMenu_NotifySelect; };
1944    MenuItem debugBpSkipRunToCursorAtSameLevel { debugMenu, $"BP Run To Cursor At Same Level Skipping Breakpoints"/*, g, Key { f10, shift = true, alt = true }*/, id = RTCMenuBits { true,  true,  true  }, NotifySelect = RTCMenu_NotifySelect; };
1945 #endif
1946    bool RTCMenu_NotifySelect(MenuItem selection, Modifiers mods)
1947    {
1948       ProjectView projectView = ide.projectView;
1949       if(!projectView.buildInProgress)
1950       {
1951          RTCMenuBits bits = (RTCMenuBits)selection.id;
1952          int line = editBox.lineNumber + 1;
1953          if(projectView)
1954          {
1955             CompilerConfig compiler = ideSettings.GetCompilerConfig(ide.workspace.compiler);
1956             ProjectConfig config = projectView.project.config;
1957             int bitDepth = ide.workspace.bitDepth;
1958             bool useValgrind = ide.workspace.useValgrind;
1959             ide.debugger.RunToCursor(compiler, config, bitDepth, useValgrind, fileName, line, bits.ignoreBreakpoints, bits.atSameLevel, bits.oldImplementation);
1960             delete compiler;
1961          }
1962       }
1963       return true;
1964    }
1965    MenuDivider { debugMenu };
1966    MenuItem debugToggleBreakpoint
1967    {
1968       debugMenu, $"Toggle Breakpoint", t, f9;
1969       bool NotifySelect(MenuItem selection, Modifiers mods)
1970       {
1971          ProjectView projectView = ide.projectView;
1972          if(projectView && fileName)
1973          {
1974             int line = editBox.lineNumber + 1;
1975             ide.debugger.ToggleBreakpoint(fileName, line);
1976             Update(null);
1977          }
1978          return true;
1979       }
1980    };
1981
1982    bool debugClosing;
1983    int lastLine;
1984
1985    //MenuItem viewDesignerItem, viewProperties, viewMethods;
1986
1987    bool OnCreate(void)
1988    {
1989       designer.parent = parent;
1990       designer.Create();
1991
1992       toolBox = ((IDEWorkSpace)master).toolBox;
1993       incref toolBox;
1994       // Debugger bug here: value of toolBox appears as 0
1995
1996       sheet = ((IDEWorkSpace)master).sheet;
1997       incref sheet;
1998       return true;
1999    }
2000
2001    bool OnClose(bool parentClosing)
2002    {
2003       if(!parentClosing)
2004       {
2005          if(ide.workspace && fileName)
2006             ide.workspace.UpdateOpenedFileInfo(fileName, closed);
2007          if(inUseDebug && !debugClosing)
2008          {
2009             debugClosing = true;
2010             closing = false;
2011             if(CloseConfirmation(false))
2012             {
2013                visible = false;
2014                if(modifiedDocument)
2015                   OnFileModified({ modified = true }, null);
2016             }
2017             debugClosing = false;
2018             return false;
2019          }
2020          if(designer && !designer.closing)
2021          {
2022             if(designer.visible)
2023             {
2024                visible = false;
2025                return false;
2026             }
2027             /*else
2028             {
2029                //Window formEditor = designer;
2030                //formEditor.Destroy(0);
2031             }*/
2032          }
2033          ide.AdjustFileMenus();
2034       }
2035       return true;
2036    }
2037
2038    void OnDestroy(void)
2039    {
2040       ObjectInfo oClass, next;
2041       Class windowClass = eSystem_FindClass(this.privateModule, "ecere::gui::Window");
2042
2043       FreeType(this.functionType);
2044       FreeType(this.instanceType);
2045
2046       if(designer)
2047       {
2048          designer.Reset();
2049          designer.codeEditor = null;
2050          designer.Destroy(0);
2051          delete designer;
2052       }
2053
2054       for(oClass = (classes).first, next = oClass ? oClass.next : null; oClass; oClass = next, next = next ? (next.next) : null)
2055       {
2056          ObjectInfo object, next;
2057
2058          for(object = oClass.instances.first; object; object = next)
2059          {
2060             next = object.next;
2061             if(object.instance)
2062             {
2063                Designer::DestroyObject(object.instance);
2064                delete object.instance;
2065             }
2066             sheet.DeleteObject(object);
2067             delete object.name;
2068             oClass.instances.Delete(object);
2069          }
2070          if(oClass.instance)
2071          {
2072             Designer::DestroyObject(oClass.instance);
2073             delete oClass.instance;
2074          }
2075          sheet.DeleteObject(oClass);
2076          delete oClass.name;
2077          classes.Delete(oClass);
2078       }
2079
2080       if(windowClass && windowClass.data)
2081          UnapplySkin(windowClass);
2082
2083       FreeParser();
2084
2085       if(sheet.codeEditor == this)
2086       {
2087          sheet.codeEditor = null;
2088          toolBox.codeEditor = null;
2089       }
2090       delete sheet;
2091       delete toolBox;
2092
2093       {
2094          ProjectView projectView = ide.projectView;
2095          if(projectView)
2096          {
2097             ProjectNode node = projectView.GetNodeFromWindow(this, null, true, false, null);
2098             if(node && node.modified)
2099             {
2100                node.modified = false;
2101                projectView.Update(null);
2102             }
2103          }
2104       }
2105    }
2106
2107    bool OnActivate(bool active, Window previous, bool * goOnWithActivation, bool directActivation)
2108    {
2109       // WHY WAS THIS HERE? I think this was here because once you move a window in the ide it's hard to reposition it correctly
2110       /*
2111       if(directActivation)
2112          ide.RepositionWindows(false);    // Moved this up before as resizing causes NotifyCaretMove to be called on all editors
2113       */
2114       if(active && directActivation)
2115       {
2116          AdjustDebugMenus();
2117          if(openedFileInfo)
2118             openedFileInfo.Activate();
2119          if(designer)
2120          {
2121             int line, charPos;
2122             Location * loc = null;
2123             UpdateFormCode(); // To ensure update when modifying properties...
2124
2125             // Got to the right spot in code so we don't lose our form selection...
2126             if(selected)
2127             {
2128                if(selected.instCode)
2129                   loc = &selected.instCode.loc;
2130                else if(selected.classDefinition)
2131                   loc = &selected.classDefinition.loc;
2132             }
2133             line = editBox.lineNumber + 1;
2134             charPos = editBox.charPos + 1;
2135             if(fixCaret)
2136             {
2137                fixCaret = false;
2138
2139                if(selected && !loc->Inside(line, charPos))
2140                {
2141                   editBox.GoToPosition(null, loc->start.line - 1, loc->start.charPos - 1);
2142                   line = editBox.lineNumber + 1;
2143                   charPos = editBox.charPos + 1;
2144                }
2145                else if(selected && selected.classDefinition)
2146                {
2147                   ObjectInfo object;
2148                   for(object = selected.instances.first; object; object = object.next)
2149                   {
2150                      if(object.instCode)
2151                      {
2152                         if(object.instCode.loc.Inside(line, charPos))
2153                            break;
2154                      }
2155                   }
2156                   if(object)
2157                   {
2158                      editBox.GoToPosition(null, loc->start.line - 1, loc->start.charPos - 1);
2159                      line = editBox.lineNumber + 1;
2160                      charPos = editBox.charPos + 1;
2161                   }
2162                }
2163             }
2164
2165             ProcessCaretMove(editBox, line, charPos);
2166          }
2167       }
2168       if(!active)
2169       {
2170          if(membersListShown)
2171          {
2172             membersList.Destroy(0);
2173             membersListShown = false;
2174          }
2175          if(paramsShown)
2176          {
2177             paramsList.Destroy(0);
2178             paramsShown = false;
2179             FreeType(functionType);
2180             FreeType(instanceType);
2181
2182             functionType = null;
2183             instanceType = null;
2184             paramsID = -1;
2185          }
2186       }
2187       return true;
2188    }
2189
2190    bool OnSaveFile(char * fileName)
2191    {
2192       File f;
2193       if(designer)
2194       {
2195          UpdateFormCode();
2196       }
2197       f = FileOpen(fileName, write);
2198       if(f)
2199       {
2200          if(!ide.projectView)
2201             ide.ChangeFileDialogsDirectory(codeEditorFileDialog.currentDirectory, true);
2202          if(designer)
2203          {
2204             if(!this.fileName)
2205                this.fileName = fileName;  // Put this here because the form designer will check for it...
2206             designer.fileName = fileName;
2207             designer.modifiedDocument = false;
2208          }
2209
2210          if(editBox.syntaxHighlighting)
2211          {
2212             // Nuke trailing spaces
2213             EditLine line;
2214             int y = 0;
2215             for(line = editBox.firstLine; line; line = line.next, y++)
2216             {
2217                String buffer = line.text;
2218                int count = line.count, i = count-1;
2219                while(i > 0 && isspace(buffer[i])) i--;
2220                if(i < count - 1)
2221                   editBox.Delete(line, y, i, line, y, count);
2222             }
2223          }
2224
2225          editBox.Save(f, false);
2226          modifiedDocument = false;
2227
2228          delete f;
2229          return true;
2230       }
2231       return false;
2232    }
2233
2234    bool OnFileModified(FileChange fileChange, char * param)
2235    {
2236       bool reload = false;
2237       if(visible == false && inUseDebug == true)
2238          ide.debugger.WatchesReleaseCodeEditor();
2239       else
2240       {
2241          char message[2048];
2242
2243          sprintf(message, $"The document %s was modified by another application.\n"
2244             "Would you like to reload it and lose your changes?", fileName);
2245          if(MessageBox { type = yesNo, master = /*parent = */parent, text = $"Document has been modified",
2246             contents = message }.Modal() == yes)
2247             reload = true;
2248       }
2249
2250       if(reload)
2251       {
2252          File f = FileOpen(fileName, read);
2253          if(f)
2254          {
2255             int lineNumber, charPos, len;
2256             Point scroll;
2257
2258             loadingFile = true;
2259             updatingCode = true;
2260             lineNumber = editBox.lineNumber;
2261             charPos = editBox.charPos;
2262             scroll = editBox.scroll;
2263             editBox.Clear();
2264             editBox.Load(f);
2265             lineNumber = lineNumber < editBox.numLines ? lineNumber : editBox.numLines - 1;
2266             len = strlen(editBox.line.text);
2267             editBox.GoToLineNum(lineNumber);
2268             editBox.GoToPosition(editBox.line, lineNumber, charPos <= len ? charPos - 1 : (len ? len - 1 : 0));
2269             editBox.scroll = scroll;
2270             updatingCode = false;
2271             loadingFile = false;
2272
2273             codeModified = true;
2274             if(designer)
2275             {
2276                UpdateFormCode();
2277                designer.modifiedDocument = false;
2278             }
2279             modifiedDocument = false;
2280
2281             delete f;
2282          }
2283       }
2284       return true;
2285    }
2286
2287    void OnRedraw(Surface surface)
2288    {
2289       // Line Numbers
2290       surface.SetBackground(marginColor);
2291       surface.Area(0, 0, editBox.anchor.left.distance, clientSize.h - 1);
2292       if(ideSettings.showLineNumbers)
2293       {
2294          int currentLineNumber;
2295          int i;
2296          char lineFormat[16];
2297          char lineText[256];
2298          int spaceH;
2299
2300          surface.textOpacity = false;
2301          surface.font = font.font;
2302          surface.TextExtent(" ", 1, null, &spaceH);
2303          currentLineNumber = editBox.scroll.y / spaceH + 1;
2304          sprintf(lineFormat, " %%%du", maxLineNumberLength);
2305
2306          surface.SetForeground(lineNumbersColor);
2307          for(i = 0; i < editBox.clientSize.h - 4; i += spaceH)
2308          {
2309             // Highlight current line
2310             if(editBox.lineNumber == currentLineNumber - 1)
2311             {
2312                surface.SetBackground(selectedMarginColor);
2313                surface.Area(0, i, editBox.anchor.left.distance, i+spaceH-1);
2314                surface.SetBackground(marginColor);
2315             }
2316             sprintf(lineText, lineFormat, currentLineNumber);
2317             if(currentLineNumber <= editBox.numLines)
2318                surface.WriteText(editBox.syntaxHighlighting * 20, i+1,lineText,maxLineNumberLength+1);
2319             currentLineNumber++;
2320          }
2321       }
2322
2323       if(editBox.syntaxHighlighting && fileName && ide.projectView)
2324       {
2325          bool error, bpOnCursor, bpOnTopFrame, breakpointEnabled[128];
2326          int lineCursor, lineTopFrame, breakpointLines[128];
2327          int count, i, lineH, boxH, scrollY; //, firstLine; firstLine = editBox.firstLine;
2328          Debugger debugger = ide.debugger;
2329          BitmapResource bmpRes;
2330
2331          boxH = clientSize.h;
2332          scrollY = editBox.scroll.y;
2333          displaySystem.FontExtent(editBox.font.font, " ", 1, null, &lineH);
2334
2335          bpOnCursor = bpOnTopFrame = false;
2336          count = debugger.GetMarginIconsLineNumbers(fileName, breakpointLines, breakpointEnabled, 128, &error, &lineCursor, &lineTopFrame);
2337          if(count)
2338          {
2339             for(i = 0; i < count; i++)
2340             {
2341                if(breakpointLines[i] == lineCursor || breakpointLines[i] == lineTopFrame)
2342                {
2343                   bmpRes = breakpointEnabled[i] ? ide.bmpBpHalf : ide.bmpBpHalfDisabled;
2344                   if(breakpointLines[i] == lineCursor)
2345                      bpOnCursor = true;
2346                   if(breakpointLines[i] == lineTopFrame)
2347                      bpOnTopFrame = true;
2348                }
2349                else
2350                   bmpRes = breakpointEnabled[i] ? ide.bmpBp : ide.bmpBpDisabled;
2351
2352                DrawLineMarginIcon(surface, bmpRes, breakpointLines[i], lineH, scrollY, boxH);
2353             }
2354          }
2355          DrawLineMarginIcon(surface, error ? ide.bmpCursorError : ide.bmpCursor, lineCursor, lineH, scrollY, boxH);
2356          bmpRes = bpOnTopFrame ? (error ? ide.bmpTopFrameHalfError : ide.bmpTopFrameHalf) : (error ? ide.bmpTopFrameError : ide.bmpTopFrame);
2357          DrawLineMarginIcon(surface, bmpRes, lineTopFrame, lineH, scrollY, boxH);
2358       }
2359       if(editBox.anchor.left.distance)
2360       {
2361          if(editBox.horzScroll && editBox.horzScroll.visible)
2362          {
2363             surface.SetBackground(control);
2364             surface.Area(0, editBox.clientSize.h, editBox.anchor.left.distance, clientSize.h - 1);
2365          }
2366       }
2367    }
2368
2369    void DrawLineMarginIcon(Surface surface, BitmapResource resource, int line, int lineH, int scrollY, int boxH)
2370    {
2371       int lineY;
2372       if(line)
2373       {
2374          lineY = (line - 1) * lineH;
2375          if(lineY + lineH > scrollY && lineY /*+ lineH*/ < scrollY + boxH)
2376          {
2377             Bitmap bitmap = resource.bitmap;
2378             if(bitmap)
2379                surface.Blit(bitmap, 0, lineY - scrollY + (lineH - bitmap.height) / 2 + 1, 0, 0, bitmap.width, bitmap.height);
2380          }
2381       }
2382    }
2383
2384    watch(fileName)
2385    {
2386       char ext[MAX_EXTENSION];
2387       char * fileName = property::fileName;
2388
2389       if(SearchString(fileName, 0, "Makefile", false, true))
2390          editBox.useTab = true;
2391       designer.fileName = fileName;
2392
2393       if(fileName)
2394       {
2395          GetExtension(fileName, ext);
2396
2397          if(!strcmpi(ext, "ec") || !strcmpi(ext, "eh") || !strcmpi(ext, "c") || !strcmpi(ext, "h") || !strcmpi(ext, "cpp") ||
2398                !strcmpi(ext, "hpp") || !strcmpi(ext, "cxx") || !strcmpi(ext, "hxx") || !strcmpi(ext, "cc") || !strcmpi(ext, "hh") ||
2399                !strcmpi(ext, "m") || !strcmpi(ext, "mm") || !strcmpi(ext, "cs") || !strcmpi(ext, "java") || !strcmpi(ext, "y") || !strcmpi(ext, "l"))
2400             editBox.syntaxHighlighting = true;
2401          else
2402             editBox.syntaxHighlighting = false;
2403
2404          if(parsing && !strcmpi(ext, "ec"))
2405          {
2406             codeModified = true;
2407             EnsureUpToDate();
2408          }
2409
2410          maxLineNumberLength = 0;
2411          UpdateMarginSize();
2412       }
2413    };
2414
2415    bool UpdateMarginSize()
2416    {
2417       if(ideSettings.showLineNumbers)
2418       {
2419          int numLen = Max(4, nofdigits(editBox.numLines));
2420          int digitWidth;
2421          maxLineNumberLength = numLen;
2422          display.FontExtent(font.font, "0", 1, &digitWidth, null);
2423          editBox.anchor = Anchor
2424          {
2425             left = editBox.syntaxHighlighting * 20 + ideSettings.showLineNumbers * (maxLineNumberLength+2) * digitWidth,
2426             right = 0, top = 0, bottom = 0
2427          };
2428       }
2429       else
2430       {
2431          maxLineNumberLength = 0;
2432          editBox.anchor = Anchor
2433          {
2434             left = editBox.syntaxHighlighting * 20,
2435             right = 0, top = 0, bottom = 0
2436          };
2437       }
2438       return true;
2439    }
2440
2441    bool OnPostCreate()
2442    {
2443       UpdateMarginSize();
2444       return true;
2445    }
2446
2447    bool LoadFile(char * filePath)
2448    {
2449       File f = FileOpen(filePath, read);
2450       if(f)
2451       {
2452          // Added this here...
2453          fileName = filePath;
2454          loadingFile = true;
2455          updatingCode = true;
2456          editBox.Load(f);
2457          updatingCode = false;
2458          loadingFile = false;
2459          Create();
2460
2461          delete f;
2462          return true;
2463       }
2464       return false;
2465    }
2466
2467    void AdjustDebugMenus()
2468    {
2469       bool unavailable = ide.areDebugMenusUnavailable;
2470       bool isNotNotRunning    = unavailable || ide.isDebuggerRunning;
2471       bool isNotStopped       = unavailable || !ide.isDebuggerStopped;
2472       bool noBreakpointToggle = ide.isBreakpointTogglingUnavailable;
2473
2474       debugRunToCursor.disabled                = isNotNotRunning;
2475       debugSkipRunToCursor.disabled            = isNotNotRunning;
2476       debugRunToCursorAtSameLevel.disabled     = isNotStopped;
2477       debugSkipRunToCursorAtSameLevel.disabled = isNotStopped;
2478 #if 0
2479       debugBpRunToCursor.disabled                = isNotNotRunning;
2480       debugBpSkipRunToCursor.disabled            = isNotNotRunning;
2481       debugBpRunToCursorAtSameLevel.disabled     = isNotStopped;
2482       debugBpSkipRunToCursorAtSameLevel.disabled = isNotStopped;
2483 #endif
2484       debugToggleBreakpoint.disabled           = noBreakpointToggle;
2485    }
2486
2487    CodeEditor()
2488    {
2489       CodeObjectType c;
2490       ProjectView projectView = ide.projectView;
2491
2492       /*if(fileName)
2493          designer.fileName = fileName;
2494       else
2495       */
2496       if(designer)
2497       {
2498          char title[1024];
2499          sprintf(title, $"Untitled %d", documentID);
2500          // designer.fileName = CopyString(title);
2501          designer.fileName = title;
2502       }
2503
2504       AdjustDebugMenus();
2505
2506       for(c = 0; c < CodeObjectType::enumSize; c++)
2507          icons[c] = BitmapResource { iconNames[c], window = this };
2508
2509       codeModified = true;
2510       inUseDebug = false;
2511       return true;
2512    }
2513
2514    ~CodeEditor()
2515    {
2516
2517    }
2518
2519    void ModifyCode()
2520    {
2521       selected.modified = true;
2522       selected.oClass.modified = true;
2523
2524       designer.modifiedDocument = true;
2525       modifiedDocument = true;
2526       formModified = true;
2527    }
2528
2529    /****************************************************************************
2530                                  PARSING
2531    ****************************************************************************/
2532    void FreeParser()
2533    {
2534       if(ast != null)
2535       {
2536          FreeASTTree(ast);
2537          ast = null;
2538       }
2539       this.defines.Free(FreeModuleDefine);
2540       this.imports.Free(FreeModuleImport);   // Moved this after FreeAST because Debug printing causes ModuleImports to be created
2541
2542       FreeExcludedSymbols(this.excludedSymbols);
2543       FreeContext(this.globalContext);
2544       FreeIncludeFiles();
2545       FreeGlobalData(&this.globalData);
2546       FindCtx_Terminate();
2547       FindParams_Terminate();
2548
2549       if(GetGlobalContext() == globalContext)
2550       {
2551          SetGlobalData(null);
2552          SetGlobalContext(null);
2553          SetExcludedSymbols(null);
2554          SetTopContext(null);
2555          SetCurrentContext(null);
2556          SetDefines(null);
2557          SetImports(null);
2558          SetPrivateModule(null);
2559       }
2560
2561       if(this.privateModule)
2562       {
2563          FreeTypeData(this.privateModule);
2564          delete this.privateModule;
2565          this.privateModule = null;
2566       }
2567    }
2568
2569    void ParseCode()
2570    {
2571       static bool reentrant = false;
2572       External external;
2573       File editFile;
2574       EditLine l1, l2;
2575       int x1,x2,y1,y2;
2576       char * selectedClassName = null, * selectedName = null;
2577       int selectedPos = 0;
2578       Designer backDesigner;
2579       char oldWorkDir[MAX_LOCATION];
2580       char mainModuleName[MAX_FILENAME] = "";
2581       char * fileName;
2582       ImportedModule module;
2583       char extension[MAX_EXTENSION];
2584       PathBackup pathBackup { };
2585 #ifdef _TIMINGS
2586       Time parseCodeStart = GetTime();
2587       Time startTime, startFindClass;
2588
2589       findClassTotalTime = 0;
2590       checkTypeTotalTime = 0;
2591       externalImportTotalTime = 0;
2592       findClassIgnoreNSTotalTime = 0;
2593       findSymbolTotalTime = 0;
2594       //ResetClassFindTime();
2595 #endif
2596       Project project;
2597
2598       // This temporarily fixes issue with 2 overrides in release mode with VC6 (only happens with both ecere.dll and ide.exe compiled in release mode)
2599       if(reentrant) return;
2600       reentrant = true;
2601
2602       updatingCode++;
2603
2604       if(selected)
2605       {
2606          selectedClassName = CopyString(oClass.name);
2607          if(selected != oClass)
2608          {
2609             ObjectInfo object = this.selected;
2610             selectedName = CopyString(object.name);
2611             if(!selectedName)
2612             {
2613                ObjectInfo check;
2614                for(check = this.oClass.instances.first; check; check = check.next)
2615                {
2616                   if(check == object)
2617                      break;
2618                   selectedPos++;
2619                }
2620             }
2621          }
2622          else
2623             selectedPos = -1;
2624       }
2625
2626       editBox.GetSelPos(&l1, &y1, &x1, &l2, &y2, &x2, false);
2627
2628       FindCtx_Terminate();
2629       FindParams_Terminate();
2630
2631       SetGlobalData(&globalData);
2632       SetGlobalContext(globalContext);
2633       SetExcludedSymbols(&excludedSymbols);
2634       SetTopContext(globalContext);
2635       SetCurrentContext(globalContext);
2636       SetDefines(&defines);
2637       SetImports(&imports);
2638       SetCurrentNameSpace(null);
2639
2640       /*
2641       sprintf(command, "C:\\Program Files\\Microsoft Visual Studio\\VC98\\Bin\\cl "
2642          "/nologo /D \"MSC\" /D \"WIN32\" /D \"NDEBUG\" /D \"_WINDOWS\" /D \"_MBCS\" "
2643          "/I \"C:\\Program Files\\Microsoft Visual Studio\\VC98\\Include\" "
2644          "/I T:\\ecere\\include /E %s", argv[1]);
2645       */
2646
2647       /*
2648       ChangeWorkingDir("e:\\ec");
2649       sprintf(command, "gcc -x c -E -");
2650       fileInput = DualPipeOpen({ output = true, input = true }, command);
2651       SetFileInput(fileInput);
2652       {
2653          for(;;)
2654          {
2655             byte buffer[8192];
2656             uint count = editFile.Read(buffer, 1, sizeof(buffer));
2657             if(count)
2658                fileInput.Write(buffer, 1, count);
2659             else
2660                break;
2661          }
2662          delete editFile;
2663          fileInput.CloseOutput();
2664       }
2665       */
2666
2667       // TOCHECK: COULDN'T WE CALL FreeParser here?
2668       // Clear everything
2669       FreeType(this.functionType);
2670       FreeType(this.instanceType);
2671       this.functionType = null;
2672       this.instanceType = null;
2673
2674       // Select nothing
2675       sheet.SelectObject(null);
2676
2677       designer.Reset();
2678
2679       selected = null;
2680
2681       // We don't want the designer to be notified of selection when deleting rows...
2682       backDesigner = designer;
2683       designer = null;
2684
2685       if(this.oClass)
2686       {
2687          ObjectInfo _class, next;
2688
2689          for(_class = classes.first; _class; _class = next)
2690          {
2691             ObjectInfo object;
2692
2693             next = _class.next;
2694
2695             for(;object = _class.instances.first;)
2696             {
2697                if(object.instance)
2698                {
2699                   Designer::DestroyObject(object.instance);
2700                   delete object.instance;
2701                }
2702                sheet.DeleteObject(object);
2703                delete object.name;
2704                _class.instances.Delete(object);
2705             }
2706             if(_class.instance)
2707             {
2708                Designer::DestroyObject(_class.instance);
2709                delete _class.instance;
2710             }
2711             sheet.DeleteObject(_class);
2712             delete _class.name;
2713             classes.Delete(_class);
2714          }
2715          this.oClass = null;
2716       }
2717
2718       {
2719          Class windowClass = eSystem_FindClass(this.privateModule, "ecere::gui::Window");
2720          if(windowClass && windowClass.data)
2721             UnapplySkin(windowClass);
2722       }
2723
2724       designer = backDesigner;
2725
2726       SetEchoOn(true);
2727       fileInput = editFile = EditBoxStream { editBox = editBox };
2728       SetFileInput(fileInput);
2729
2730       if(ast)
2731       {
2732          FreeASTTree(ast);
2733          ast = null;
2734          //SetAST(null);
2735       }
2736       defines.Free(FreeModuleDefine);
2737       imports.Free(FreeModuleImport);
2738
2739       FreeContext(this.globalContext);
2740       FreeExcludedSymbols(this.excludedSymbols);
2741
2742       FreeIncludeFiles();
2743       FreeGlobalData(&this.globalData);
2744
2745       if(this.privateModule)
2746       {
2747          FreeTypeData(this.privateModule);
2748          delete this.privateModule;
2749       }
2750
2751 #ifdef _TIMINGS
2752       startTime = GetTime();
2753       printf("Cleaning up took %.3f seconds\n", startTime - parseCodeStart);
2754
2755       printf("classes.count: %d\n", globalContext.classes.count);
2756 #endif
2757
2758       if(ide.workspace)
2759       {
2760          CompilerConfig compiler = ideSettings.GetCompilerConfig(ide.workspace.compiler);
2761          SetTargetBits(ide.workspace.bitDepth ? ide.workspace.bitDepth : GetHostBits());
2762          delete compiler;
2763       }
2764       this.privateModule = __ecere_COM_Initialize(false | ((GetTargetBits() == sizeof(uintptr) *8) ? 0 : GetTargetBits() == 64 ? 2 : 4), 1, null);
2765
2766       SetPrivateModule(privateModule);
2767
2768       {
2769          globalContext.types.Add((BTNode)Symbol { string = CopyString("uint"), type = ProcessTypeString("unsigned int", false) });
2770          globalContext.types.Add((BTNode)Symbol { string = CopyString("uint64"), type = ProcessTypeString("unsigned int64", false) });
2771          globalContext.types.Add((BTNode)Symbol { string = CopyString("uint32"), type = ProcessTypeString("unsigned int", false) });
2772          globalContext.types.Add((BTNode)Symbol { string = CopyString("uint16"), type = ProcessTypeString("unsigned short", false) });
2773          globalContext.types.Add((BTNode)Symbol { string = CopyString("byte"), type = ProcessTypeString("unsigned char", false) });
2774       }
2775
2776       fileName = this.fileName;
2777       project = null;
2778       if(ide.workspace && ide.workspace.projects && fileName)
2779       {
2780          for(p : ide.workspace.projects)
2781          {
2782             char path[MAX_LOCATION];
2783             ProjectNode pn;
2784             MakePathRelative(fileName, p.topNode.path, path);
2785             MakeSlashPath(path);
2786
2787             pn = p.topNode.FindWithPath(path, false);
2788             if(pn)
2789             {
2790                project = p;
2791                break;
2792             }
2793          }
2794       }
2795       if(!project)
2796          project = ide.project;
2797
2798       GetWorkingDir(oldWorkDir, MAX_LOCATION);
2799       if(project)
2800          ChangeWorkingDir(project.topNode.path);
2801
2802       SetSomeSourceFileStack(fileName ? fileName : "", 0); //strcpy(sourceFileStack[0], fileName ? fileName : "");
2803
2804       GetLastDirectory(fileName, mainModuleName);
2805       GetExtension(mainModuleName, extension);
2806
2807       SetBuildingEcereCom(false);
2808       SetBuildingEcereComModule(false);
2809
2810       // TODO: Get symbolsDir from project settings instead...
2811       if(ide.projectView)
2812       {
2813          CompilerConfig compiler = ideSettings.GetCompilerConfig(ide.workspace.compiler);
2814          ProjectConfig config = project.config;
2815          int bitDepth = ide.workspace.bitDepth;
2816          DirExpression objDir = project.GetObjDir(compiler, config, bitDepth);
2817          SetSymbolsDir(objDir.dir);
2818          ide.SetPath(true, compiler, config, bitDepth);
2819
2820          delete objDir;
2821          delete compiler;
2822          // SetIncludeDirs(ide.projectView.project.config.includeDirs);
2823          // SetSysIncludeDirs(ide.ideSettings.systemDirs[includes]);
2824       }
2825       else
2826       {
2827          switch(GetRuntimePlatform())
2828          {
2829             case win32: SetSymbolsDir("obj/debug.win32"); break;
2830             case tux:   SetSymbolsDir("obj/debug.linux"); break;
2831             case apple: SetSymbolsDir("obj/debug.apple"); break;
2832          }
2833          SetIncludeDirs(null);
2834          SetSysIncludeDirs(null);
2835       }
2836
2837       {
2838          if(ide.projectView && ide.projectView.IsModuleInProject(this.fileName))
2839          {
2840             // TODO FIX for configless project
2841             if(ide.project.config && ide.project.config.options && ide.project.config.options.preprocessorDefinitions)
2842             {
2843                for(item : ide.project.config.options.preprocessorDefinitions)
2844                {
2845                   if(!strcmp(item, "BUILDING_ECERE_COM"))
2846                   {
2847                      SetBuildingEcereCom(true);
2848                      break;
2849                   }
2850                }
2851             }
2852          }
2853
2854          if(!(strcmpi(mainModuleName, "instance.ec") && strcmpi(mainModuleName, "BinaryTree.ec") &&
2855             strcmpi(mainModuleName, "dataTypes.ec") && strcmpi(mainModuleName, "OldList.ec") &&
2856             strcmpi(mainModuleName, "String.ec") && strcmpi(mainModuleName, "BTNode.ec") &&
2857             strcmpi(mainModuleName, "Array.ec") && strcmpi(mainModuleName, "AVLTree.ec") &&
2858             strcmpi(mainModuleName, "BuiltInContainer.ec") && strcmpi(mainModuleName, "Container.ec") &&
2859             strcmpi(mainModuleName, "CustomAVLTree.ec") && strcmpi(mainModuleName, "LinkList.ec") &&
2860             strcmpi(mainModuleName, "List.ec") && strcmpi(mainModuleName, "Map.ec") &&
2861             strcmpi(mainModuleName, "Mutex.ec")))
2862          {
2863             SetBuildingEcereComModule(true);
2864          }
2865
2866          // Predeclare all classes
2867          {
2868             char symFile[MAX_FILENAME];
2869             char symLocation[MAX_LOCATION];
2870             ImportedModule module, next;
2871
2872             GetLastDirectory(fileName, symFile);
2873             ChangeExtension(symFile, "sym", symFile);
2874
2875             strcpy(symLocation, GetSymbolsDir());
2876             PathCat(symLocation, symFile);
2877
2878             // if(!GetEcereImported() && !GetBuildingEcereCom())
2879             if(!strcmp(extension, "ec") || !strcmp(extension, "eh"))
2880             {
2881 #ifdef _TIMINGS
2882                startTime = GetTime();
2883 #endif
2884                eModule_LoadStrict(privateModule, "ecereCOM", privateAccess);
2885 #ifdef _TIMINGS
2886                printf("Loading ecereCOM took %.3f seconds\n", GetTime() - startTime);
2887 #endif
2888             }
2889
2890 #ifdef _TIMINGS
2891             startTime = GetTime();
2892 #endif
2893             // LoadSymbols(symLocation, normalImport, true);
2894             LoadSymbols(symLocation, preDeclImport, false);
2895 #ifdef _TIMINGS
2896             printf("Loading symbols took %.3f seconds\n", GetTime() - startTime);
2897 #endif
2898
2899             for(module = defines.first; module; module = next)
2900             {
2901                next = module.next;
2902                if(module.type == moduleDefinition && strcmpi(module.name, mainModuleName))
2903                {
2904                   delete module.name;
2905                   defines.Delete(module);
2906                }
2907             }
2908          }
2909       }
2910       if(!strcmp(extension, "ec") || !strcmp(extension, "eh"))
2911       {
2912          SetDefaultDeclMode(privateAccess);
2913          SetDeclMode(privateAccess);
2914       }
2915       else
2916       {
2917          SetDefaultDeclMode(defaultAccess);
2918          SetDeclMode(defaultAccess);
2919       }
2920
2921       StripExtension(mainModuleName);
2922       module = ImportedModule { name = CopyString(mainModuleName), type = moduleDefinition };
2923       defines.AddName(module);
2924
2925    #ifdef _DEBUG
2926       // SetYydebug(true);
2927    #endif
2928       resetScanner();
2929
2930 #ifdef _TIMINGS
2931       startTime = GetTime();
2932       startFindClass = checkTypeTotalTime;
2933 #endif
2934       ParseEc();
2935 #ifdef _TIMINGS
2936       printf("ParseEc took %.3f seconds, out of which %.3f seconds were in CheckType\n", GetTime() - startTime, checkTypeTotalTime - startFindClass);
2937 #endif
2938       CheckDataRedefinitions();
2939       SetYydebug(false);
2940
2941       SetIncludeDirs(null);
2942       SetSysIncludeDirs(null);
2943
2944       delete editFile;
2945       fileInput = null;
2946       SetFileInput(null);
2947
2948       if(GetAST())
2949       {
2950          ast = GetAST();
2951
2952 #ifdef _TIMINGS
2953          startTime = GetTime();
2954 #endif
2955          PrePreProcessClassDefinitions();
2956          ComputeModuleClasses(privateModule);
2957          PreProcessClassDefinitions();
2958          ProcessClassDefinitions();
2959 #ifdef _TIMINGS
2960          printf("Initial Passes took %.3f seconds\n", GetTime() - startTime);
2961          startTime = GetTime();
2962 #endif
2963
2964          ComputeDataTypes();
2965 #ifdef _TIMINGS
2966          printf("ComputeDataTypes took %.3f seconds\n", GetTime() - startTime);
2967          startTime = GetTime();
2968 #endif
2969          ProcessInstantiations();
2970 #ifdef _TIMINGS
2971          printf("ProcessInstantiations took %.3f seconds\n", GetTime() - startTime);
2972 #endif
2973
2974          if(!strcmp(extension, "ec") || !strcmp(extension, "eh"))
2975          {
2976             Class windowClass = eSystem_FindClass(this.privateModule, "ecere::gui::Window");
2977             if(!windowClass || windowClass.internalDecl)
2978             {
2979 #ifdef _TIMINGS
2980                startTime = GetTime();
2981 #endif
2982                // *** COMMENTED THIS OUT DUE TO ecereCOM issues
2983                // eModule_Load(this.privateModule.application.allModules.first ? this.privateModule.application.allModules.first : this.privateModule, "ecere", privateAccess);
2984                eModule_Load(this.privateModule, "ecere", privateAccess);
2985 #ifdef _TIMINGS
2986                printf("Loading ecere.dll took %.3f seconds\n", GetTime() - startTime);
2987 #endif
2988             }
2989             windowClass = eSystem_FindClass(this.privateModule, "ecere::gui::Window");
2990
2991             if(windowClass && windowClass.data)
2992                ApplySkin(windowClass, app.currentSkin.name, null);
2993          }
2994
2995 #ifdef _TIMINGS
2996          startTime = GetTime();
2997 #endif
2998          for(external = ast->first; external; external = external.next)
2999          {
3000             if(external.type == classExternal)
3001             {
3002                ClassDefinition _class = external._class;
3003                if(_class.baseSpecs && _class.baseSpecs->first && ((Specifier)_class.baseSpecs->first).type == nameSpecifier ) // classSpecifier
3004                {
3005                   Class regClass = eSystem_FindClass(this.privateModule, ((Specifier)_class.baseSpecs->first).name);
3006                   if(regClass)
3007                   {
3008                      if(eClass_GetDesigner(regClass) && !GetBuildingEcereComModule())
3009                      {
3010                         Instance instance = eInstance_New(regClass);
3011                         ObjectInfo classObject
3012                         {
3013                            name = CopyString(_class._class.name);
3014                            instance = instance;
3015                            classDefinition = _class;
3016                            oClass = classObject;
3017                         };
3018                         Symbol symbol;
3019                         classes.Add(classObject);
3020
3021                         incref instance;
3022
3023                         // Moved this at bottom so that the file dialog doesn't show up in eCom
3024                         designer.CreateObject(instance, classObject, true, null);
3025                         sheet.AddObject(classObject, classObject.name ? classObject.name : _class._class.name, typeClass, false);
3026
3027                         if(_class.definitions)
3028                         {
3029                            ClassDef def;
3030                            ObjectInfo object;
3031                            for(def = _class.definitions->first; def; def = def.next)
3032                            {
3033                               switch(def.type)
3034                               {
3035                                  case defaultPropertiesClassDef:
3036                                  {
3037                                     MemberInit propDef;
3038                                     for(propDef = def.defProperties->first; propDef; propDef = propDef.next)
3039                                     {
3040                                        Identifier id = propDef.identifiers->first;
3041                                        if(id)
3042                                        {
3043                                           Property prop = eClass_FindProperty(regClass, id.string, this.privateModule);
3044                                           if(prop)
3045                                           {
3046                                              Class propertyClass = prop.dataTypeClass;
3047                                              if(!propertyClass)
3048                                                 propertyClass = prop.dataTypeClass = eSystem_FindClass(this.privateModule, prop.dataTypeString);
3049                                              if(prop.compiled && prop.Set && prop.Get && propertyClass && propDef.initializer && propDef.initializer.type == expInitializer && propDef.initializer.exp)
3050                                              {
3051                                                 FreeType(propDef.initializer.exp.destType);
3052                                                 propDef.initializer.exp.destType = MkClassType(propertyClass.name);
3053                                                 ProcessExpressionType(propDef.initializer.exp);
3054
3055                                                 if(propertyClass.type == structClass || propertyClass.type == noHeadClass || propertyClass.type == normalClass)
3056                                                 {
3057                                                    Expression computed = CopyExpression(propDef.initializer.exp);
3058                                                    ComputeExpression(computed);
3059
3060                                                    if(computed.isConstant && computed.type == instanceExp && !id.next)
3061                                                    {
3062                                                       if(prop.Set)
3063                                                       {
3064                                                          if(computed.instance._class && computed.instance._class.symbol &&
3065                                                             computed.instance._class.symbol.registered &&
3066                                                             eClass_IsDerived(computed.instance._class.symbol.registered, propertyClass))
3067                                                          {
3068                                                             ((void (*)(void *, void *))(void *)prop.Set)(instance, computed.instance.data);
3069
3070                                                             // This was saved in the control and shouldn't be freed by FreeExpression...
3071                                                             // (Not doing this anymore, incrementing refCount in pass15 instead)
3072                                                             /*if(propertyClass.type == normalClass)
3073                                                                computed.instance.data = null;*/
3074                                                          }
3075                                                       }
3076                                                    }
3077                                                    // MOVED THIS UP NOW THAT char * IS A NORMAL CLASS
3078                                                    else if(computed.type == stringExp && propertyClass.dataTypeString && strstr(propertyClass.dataTypeString, "char *"))
3079                                                    {
3080                                                       String temp = new char[strlen(computed.string)+1];
3081                                                       ReadString(temp, computed.string);
3082                                                       ((void (*)(void *, void *))(void *)prop.Set)(instance, temp);
3083                                                       delete temp;
3084                                                    }
3085                                                    else
3086                                                       propDef.variable = true;
3087
3088                                                    FreeExpression(computed);
3089                                                 }
3090                                                 else
3091                                                 {
3092                                                    Expression computed = CopyExpression(propDef.initializer.exp);
3093                                                    ComputeExpression(computed);
3094                                                    if(computed.isConstant)
3095                                                    {
3096                                                       //if(computed.type == memberExp) computed = computed.member.exp;
3097
3098                                                       if(computed.type == constantExp)
3099                                                       {
3100                                                          Operand value = GetOperand(computed);
3101                                                          DataValue valueData;
3102                                                          valueData.i64 = value.i64;
3103                                                          SetProperty(prop, instance, valueData);
3104                                                       }
3105                                                       else if(computed.type == stringExp && propertyClass.dataTypeString && strstr(propertyClass.dataTypeString, "char *"))
3106                                                       {
3107                                                          String temp = new char[strlen(computed.string)+1];
3108                                                          ReadString(temp, computed.string);
3109                                                          ((void (*)(void *, void *))(void *)prop.Set)(instance, temp);
3110                                                          delete temp;
3111                                                       }
3112                                                    }
3113                                                    else
3114                                                       propDef.variable = true;
3115
3116                                                    FreeExpression(computed);
3117                                                 }
3118                                              }
3119                                              else
3120                                                 propDef.variable = true;
3121                                           }
3122                                           else
3123                                           {
3124                                              Method method = eClass_FindMethod(regClass, id.string, this.privateModule);
3125                                              if(method && method.type == virtualMethod && propDef.initializer && propDef.initializer.type == expInitializer &&
3126                                                 propDef.initializer.exp && propDef.initializer.exp.type == identifierExp)
3127                                              {
3128                                                 ClassDef def;
3129                                                 // Maintain a list in FunctionDefinition of who is attached to it
3130                                                 for(def = _class.definitions->first; def; def = def.next)
3131                                                 {
3132                                                    if(def.type == functionClassDef)
3133                                                    {
3134                                                       ClassFunction function = def.function;
3135                                                       if(!strcmp(function.declarator.symbol.string, propDef.initializer.exp.identifier.string))
3136                                                       {
3137                                                          function.attached.Add(OldLink { data = method });
3138                                                       }
3139                                                    }
3140                                                 }
3141                                              }
3142                                           }
3143                                        }
3144                                     }
3145                                     break;
3146                                  }
3147                                  case declarationClassDef:
3148                                  {
3149                                     Declaration decl = def.decl;
3150                                     switch(decl.type)
3151                                     {
3152                                        case instDeclaration:
3153                                        {
3154                                           Instantiation inst = decl.inst;
3155                                           Class instClass = eSystem_FindClass(this.privateModule, inst._class.name);
3156                                           if(instClass && eClass_GetDesigner(instClass))
3157                                           {
3158                                              Instance control = eInstance_New(instClass);
3159                                              incref control;
3160
3161                                              object = ObjectInfo
3162                                              {
3163                                                 oClass = classObject;
3164                                                 instance = control;
3165                                                 instCode = inst;
3166                                              };
3167                                              classObject.instances.Add(object);
3168                                              if(inst.exp)
3169                                                 // TOCHECK: Why is this needed now?
3170                                                 object.name = CopyString((inst.exp.type == memberExp) ? inst.exp.member.member.string : inst.exp.identifier.string);
3171                                              def.object = object;
3172
3173                                              // if(object.name) { symbol = eList_Add(&curContext.symbols, sizeof(Symbol)); symbol.string = object.name; symbol.type = MkClassType(instClass.name); }
3174
3175                                              designer.CreateObject(control, object, false, classObject.instance);
3176                                              sheet.AddObject(object, object.name ? object.name : inst._class.name, typeData, false);
3177                                           }
3178                                           break;
3179                                        }
3180                                     }
3181                                     break;
3182                                  }
3183                               }
3184                            }
3185
3186                            // Second pass, process instantiation members
3187                            object = null;
3188                            for(def = _class.definitions->first; def; def = def.next)
3189                            {
3190                               switch(def.type)
3191                               {
3192                                  case declarationClassDef:
3193                                  {
3194                                     Declaration decl = def.decl;
3195                                     switch(decl.type)
3196                                     {
3197                                        case instDeclaration:
3198                                        {
3199                                           Instantiation inst = decl.inst;
3200                                           Class instClass = eSystem_FindClass(this.privateModule, inst._class.name);
3201                                           if(instClass && eClass_GetDesigner(instClass))
3202                                           {
3203                                              Instance control;
3204                                              object = object ? object.next : classObject.instances.first;
3205                                              control = object.instance;
3206
3207                                              if(inst.members)
3208                                              {
3209                                                 MembersInit members;
3210                                                 for(members = inst.members->first; members; members = members.next)
3211                                                 {
3212                                                    switch(members.type)
3213                                                    {
3214                                                       case dataMembersInit:
3215                                                       {
3216                                                          if(members.dataMembers)
3217                                                          {
3218                                                             MemberInit member;
3219                                                             DataMember curMember = null;
3220                                                             Class curClass = null;
3221                                                             DataMember subMemberStack[256];
3222                                                             int subMemberStackPos = 0;
3223
3224                                                             for(member = members.dataMembers->first; member; member = member.next)
3225                                                             {
3226                                                                bool found = false;
3227                                                                Identifier ident = member.identifiers ? member.identifiers->first : null;
3228                                                                if(ident)
3229                                                                {
3230                                                                   DataMember _subMemberStack[256];
3231                                                                   int _subMemberStackPos = 0;
3232                                                                   DataMember thisMember = (DataMember)eClass_FindDataMember(instClass, ident.string, privateModule, _subMemberStack, &_subMemberStackPos);
3233
3234                                                                   if(!thisMember)
3235                                                                   {
3236                                                                      thisMember = (DataMember)eClass_FindProperty(instClass, ident.string, privateModule);
3237                                                                   }
3238                                                                   if(thisMember && thisMember.memberAccess == publicAccess)
3239                                                                   {
3240                                                                      curMember = thisMember;
3241                                                                      curClass = curMember._class;
3242                                                                      memcpy(subMemberStack, _subMemberStack, sizeof(DataMember) * _subMemberStackPos);
3243                                                                      subMemberStackPos = _subMemberStackPos;
3244                                                                      found = true;
3245                                                                   }
3246                                                                }
3247                                                                else
3248                                                                {
3249                                                                   eClass_FindNextMember(instClass, &curClass, (DataMember *)&curMember, subMemberStack, &subMemberStackPos);
3250                                                                   if(curMember) found = true;
3251                                                                }
3252                                                                if(found && curMember.isProperty)
3253                                                                {
3254                                                                   Property prop = (Property) curMember;
3255                                                                   Class propertyClass = prop.dataTypeClass;
3256                                                                   if(!propertyClass)
3257                                                                      propertyClass = prop.dataTypeClass = eSystem_FindClass(this.privateModule, prop.dataTypeString);
3258
3259                                                                   if(prop.compiled && prop.Set && prop.Get && propertyClass && member.initializer && member.initializer.type == expInitializer && member.initializer.exp)
3260                                                                   {
3261                                                                      FreeType(member.initializer.exp.destType);
3262                                                                      member.initializer.exp.destType = MkClassType(propertyClass.name);
3263                                                                      if(propertyClass)
3264                                                                      {
3265                                                                         ProcessExpressionType(member.initializer.exp);
3266
3267                                                                         if(propertyClass.type == structClass || propertyClass.type == normalClass || propertyClass.type == noHeadClass)
3268                                                                         {
3269                                                                            Expression computed;
3270 #ifdef _DEBUG
3271                                                                            /*char debugExpString[4096];
3272                                                                            debugExpString[0] = '\0';
3273                                                                            PrintExpression(member.initializer.exp, debugExpString);*/
3274 #endif
3275                                                                            computed = CopyExpression(member.initializer.exp);
3276                                                                            if(computed)
3277                                                                            {
3278                                                                               ComputeExpression(computed);
3279
3280                                                                               if(computed.type == instanceExp && computed.isConstant && computed.isConstant)
3281                                                                               {
3282                                                                                  if(computed.instance.data)
3283                                                                                  {
3284                                                                                     if(computed.instance._class && computed.instance._class.symbol &&
3285                                                                                        computed.instance._class.symbol.registered &&
3286                                                                                        eClass_IsDerived(computed.instance._class.symbol.registered, propertyClass))
3287                                                                                     {
3288                                                                                        ((void (*)(void *, void *))(void *)prop.Set)(control, computed.instance.data);
3289
3290                                                                                        // This was saved in the control and shouldn't be freed by FreeExpression...
3291                                                                                        // (Not doing this anymore, incrementing refCount in pass15 instead)
3292                                                                                        /*if(propertyClass.type == normalClass)
3293                                                                                           computed.instance.data = null;*/
3294                                                                                     }
3295                                                                                  }
3296                                                                               }
3297                                                                               else if(computed.type == identifierExp)
3298                                                                               {
3299                                                                                  member.variable = true;
3300
3301                                                                                  if(eClass_GetDesigner(propertyClass))
3302                                                                                  //if(prop.Set)
3303                                                                                  {
3304                                                                                     char * name = computed.identifier.string;
3305                                                                                     if(!strcmp(name, "this"))
3306                                                                                     {
3307                                                                                        if(prop.Set)
3308                                                                                           ((void (*)(void *, void *))(void *)prop.Set)(control, instance);
3309                                                                                        member.variable = false;
3310                                                                                     }
3311                                                                                     else
3312                                                                                     {
3313                                                                                        ObjectInfo check;
3314                                                                                        for(check = classObject.instances.first; check; check = check.next)
3315                                                                                           if(check.name && !strcmp(name, check.name))
3316                                                                                           {
3317                                                                                              if(prop.Set)
3318                                                                                                 ((void (*)(void *, void *))(void *)prop.Set)(control, check.instance);
3319                                                                                              member.variable = false;
3320                                                                                              break;
3321                                                                                           }
3322                                                                                     }
3323                                                                                  }
3324                                                                               }
3325                                                                               else if(computed.type == memberExp)
3326                                                                               {
3327                                                                                  member.variable = true;
3328                                                                                  if(computed.member.exp.type == identifierExp)
3329                                                                                  {
3330                                                                                     char * name = computed.member.exp.identifier.string;
3331                                                                                     if(!strcmp(name, "this"))
3332                                                                                     {
3333                                                                                        char * name = computed.member.member.string;
3334                                                                                        {
3335                                                                                           ObjectInfo check;
3336                                                                                           for(check = classObject.instances.first; check; check = check.next)
3337                                                                                              if(check.name && !strcmp(name, check.name))
3338                                                                                              {
3339                                                                                                 if(prop.Set)
3340                                                                                                    ((void (*)(void *, void *))(void *)prop.Set)(control, check.instance);
3341                                                                                                 member.variable = false;
3342                                                                                                 break;
3343                                                                                              }
3344                                                                                        }
3345                                                                                     }
3346                                                                                     else
3347                                                                                     {
3348                                                                                        ObjectInfo check;
3349                                                                                        for(check = classObject.instances.first; check; check = check.next)
3350                                                                                        {
3351                                                                                           if(check.name && !strcmp(name, check.name))
3352                                                                                           {
3353                                                                                              Property getProperty = eClass_FindProperty(check.instance._class, computed.member.member.string, this.privateModule);
3354                                                                                              if(getProperty)
3355                                                                                              {
3356                                                                                                 DataValue value { };
3357                                                                                                 GetProperty(getProperty, check.instance, &value);
3358                                                                                                 SetProperty(prop, control, value);
3359                                                                                                 member.variable = false;
3360                                                                                              }
3361                                                                                              break;
3362                                                                                           }
3363                                                                                        }
3364                                                                                     }
3365                                                                                  }
3366                                                                               }
3367                                                                               // MOVED THIS UP NOW THAT char * IS A NORMAL CLASS
3368                                                                               else if(computed.isConstant && computed.type == stringExp && propertyClass.dataTypeString && strstr(propertyClass.dataTypeString, "char *"))
3369                                                                               {
3370                                                                                  String temp = new char[strlen(computed.string)+1];
3371                                                                                  ReadString(temp, computed.string);
3372                                                                                  ((void (*)(void *, void *))(void *)prop.Set)(control, temp);
3373                                                                                  delete temp;
3374                                                                               }
3375                                                                               else
3376                                                                                  member.variable = true;
3377
3378                                                                               FreeExpression(computed);
3379                                                                            }
3380                                                                         }
3381                                                                         else
3382                                                                         {
3383                                                                            Expression computed = CopyExpression(member.initializer.exp);
3384                                                                            if(computed)
3385                                                                            {
3386                                                                               ComputeExpression(computed);
3387                                                                               if(computed.isConstant)
3388                                                                               {
3389                                                                                  if(computed.type == constantExp && (!propertyClass.dataTypeString || strcmp(propertyClass.dataTypeString, "char *"))) //(strcmp(propertyClass.name, "char *") && (strcmp(propertyClass.name, "String"))))
3390                                                                                  {
3391                                                                                     if(!strcmp(propertyClass.dataTypeString, "float"))
3392                                                                                        ((void (*)(void *, float))(void *)prop.Set)(control, (float)strtod(computed.constant, null));
3393                                                                                     else if(!strcmp(propertyClass.dataTypeString, "double"))
3394                                                                                        ((void (*)(void *, double))(void *)prop.Set)(control, strtod(computed.constant, null));
3395                                                                                     else
3396                                                                                        ((void (*)(void *, int))(void *)prop.Set)(control, strtol(computed.constant, null, 0));
3397                                                                                  }
3398                                                                                  else if(computed.type == stringExp  && propertyClass.dataTypeString && strstr(propertyClass.dataTypeString, "char *"))
3399                                                                                  {
3400                                                                                     String temp = new char[strlen(computed.string)+1];
3401                                                                                     ReadString(temp, computed.string);
3402                                                                                     ((void (*)(void *, void *))(void *)prop.Set)(control, temp);
3403                                                                                     delete temp;
3404                                                                                  }
3405                                                                               }
3406                                                                               else
3407                                                                                  member.variable = true;
3408
3409                                                                               FreeExpression(computed);
3410                                                                            }
3411                                                                         }
3412                                                                      }
3413                                                                   }
3414                                                                   else
3415                                                                      member.variable = true;
3416                                                                }
3417                                                                else if(ident && member.initializer && member.initializer.type == expInitializer && member.initializer.exp &&
3418                                                                   member.initializer.exp.type == memberExp) // identifierExp
3419                                                                {
3420                                                                   Method method = eClass_FindMethod(instClass, ident.string, this.privateModule);
3421                                                                   if(method && method.type == virtualMethod)
3422                                                                   {
3423                                                                      ClassDef def;
3424                                                                      // Maintain a list in FunctionDefinition of who is attached to it
3425                                                                      for(def = _class.definitions->first; def; def = def.next)
3426                                                                      {
3427                                                                         if(def.type == functionClassDef)
3428                                                                         {
3429                                                                            ClassFunction function = def.function;
3430                                                                            Identifier id = (member.initializer.exp.type == memberExp) ? member.initializer.exp.member.member : member.initializer.exp.identifier;
3431                                                                            if(function.declarator && !strcmp(function.declarator.symbol.string, id.string))
3432                                                                            {
3433                                                                               function.attached.Add(OldLink { data = method });
3434                                                                               // Reference this particular instance?
3435                                                                            }
3436                                                                         }
3437                                                                      }
3438                                                                   }
3439                                                                }
3440                                                                id++;
3441                                                             }
3442                                                          }
3443                                                          break;
3444                                                       }
3445                                                    }
3446                                                 }
3447                                              }
3448
3449                                              designer.PostCreateObject(object.instance, object, false, classObject.instance);
3450                                              break;
3451                                           }
3452                                        }
3453                                        break;
3454                                     }
3455                                  }
3456                               }
3457                            }
3458                         }
3459
3460                         //designer.CreateObject(instance, classObject, true, null);
3461                         //sheet.AddObject(classObject, classObject.name ? classObject.name : _class._class.name, classType, false);
3462
3463                         designer.PostCreateObject(instance, classObject, true, null);
3464
3465                         //instance.state = Hidden;
3466                         //instance.Create();
3467                         //instance.SetState(Normal, true, 0);
3468                      }
3469                   }
3470                }
3471             }
3472          }
3473
3474          SetAST(null);
3475 #ifdef _TIMINGS
3476          printf("Class/Instance Processing took %.3f seconds\n", GetTime() - startTime);
3477 #endif
3478       }
3479
3480       // Restore Selection
3481       if(selectedClassName)
3482       {
3483          ObjectInfo oClass;
3484          for(oClass = classes.first; oClass; oClass = oClass.next)
3485          {
3486             if(!strcmp(oClass.name, selectedClassName))
3487             {
3488                this.oClass = oClass;
3489                break;
3490             }
3491          }
3492          delete selectedClassName;
3493       }
3494       if(this.oClass)
3495       {
3496          if(selectedName)
3497          {
3498             ObjectInfo check;
3499             int pos = 0;
3500
3501             for(check = this.oClass.instances.first; check; check = check.next)
3502             {
3503                if(check.name && !strcmp(check.name, selectedName))
3504                {
3505                   this.selected = check;
3506                   break;
3507                }
3508             }
3509             if(!check)
3510             {
3511                if(this.oClass.instances.first)
3512                   this.selected = this.oClass.instances.first;
3513                else
3514                   this.selected = this.oClass;
3515             }
3516          }
3517          else if(selectedPos == -1 || !this.oClass.instances.count)
3518             this.selected = this.oClass;
3519          else
3520          {
3521             ObjectInfo check;
3522             int pos = 0;
3523
3524             if(selectedPos > this.oClass.instances.count)
3525                selectedPos = 0;
3526             for(check = this.oClass.instances.first; check; check = check.next)
3527             {
3528                if(selectedPos == pos++)
3529                {
3530                   this.selected = check;
3531                   break;
3532                }
3533             }
3534          }
3535       }
3536       else
3537       {
3538          this.oClass = classes.first;
3539          this.selected = (this.oClass && this.oClass.instances.first) ? this.oClass.instances.first : this.oClass;
3540       }
3541       delete selectedName;
3542       SetSymbolsDir(null);
3543
3544       if(sheet.codeEditor == this)
3545          sheet.SelectObject(selected);
3546       Update(null);
3547
3548       codeModified = false;
3549
3550       // TESTING THIS TO NOT GET EMPTY PARAMETERS
3551       if(paramsShown)
3552       {
3553          InvokeParameters(false, false, false);
3554       }
3555
3556       editBox.SetSelPos(l1, y1, x1, l2, y2, x2);
3557
3558       reentrant = false;
3559
3560       updatingCode--;
3561
3562       ChangeWorkingDir(oldWorkDir);
3563 #ifdef _TIMINGS
3564       printf("Total FindClass time is %.3f seconds, out of which %.3f is in Ignore NS\n\n", findClassTotalTime, findClassIgnoreNSTotalTime);
3565       printf("Total CheckType time is %.3f seconds\n\n", checkTypeTotalTime);
3566       printf("Total MkExternalImport time is %.3f seconds\n\n", externalImportTotalTime);
3567       printf("Total FindSymbol time is %.3f seconds\n\n", findSymbolTotalTime);
3568       // printf("Total Class Members Find time is %.3f seconds\n\n", GetClassFindTime());
3569
3570       printf("Whole ParseCode function took %.3f seconds\n\n", GetTime() - parseCodeStart);
3571 #endif
3572       if(inUseDebug && ide.projectView)
3573          ide.debugger.EvaluateWatches();
3574
3575       delete pathBackup;
3576    }
3577
3578    void UpdateInstanceCodeClass(Class _class, ObjectInfo object, EditBoxStream f, Instance test, bool * prev, bool * lastIsMethod, DataMember * curMember, Class * curClass)
3579    {
3580       Property propIt;
3581       Window control = (Window)object.instance;
3582       ObjectInfo classObject = object.oClass;
3583
3584       if(_class.base && _class.base.type != systemClass) UpdateInstanceCodeClass(_class.base, object, f, test, prev, lastIsMethod, curMember, curClass);
3585
3586       if(!strcmp(_class.name, "DesignerBase")) return;
3587
3588       for(propIt = _class.membersAndProperties.first; propIt; propIt = propIt.next)
3589       {
3590          Property prop = eClass_FindProperty(object.instance._class, propIt.name, privateModule);
3591          if(prop && prop.isProperty && !prop.conversion && eClass_FindProperty(object.instance._class, prop.name, privateModule))
3592          {
3593             if(prop.Set && prop.Get && prop.dataTypeString && strcmp(prop.name, "name") && !Code_IsPropertyDisabled(object, prop.name) &&
3594                prop.compiled && (!prop.IsSet || prop.IsSet(control)))
3595             {
3596                Class dataType = prop.dataTypeClass;
3597                if(!dataType)
3598                   dataType = prop.dataTypeClass = eSystem_FindClass(this.privateModule, prop.dataTypeString);
3599
3600                if(dataType)
3601                {
3602                   if(dataType.type == structClass)
3603                   {
3604                      void * dataForm = new0 byte[dataType.structSize];
3605                      void * dataTest = new0 byte[dataType.structSize];
3606
3607                      ((void (*)(void *, void *))(void *)prop.Get)(control, dataForm);
3608                      ((void (*)(void *, void *))(void *)prop.Get)(test, dataTest);
3609
3610                      if((prop.IsSet && !prop.IsSet(test)) || ((int (*)(void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnCompare])(dataType, dataForm, dataTest))
3611                      {
3612                         char tempString[1024] = "";
3613                         char * string = "";
3614                         bool needClass = true;
3615                         if(*prev)
3616                            f.Printf(", ");
3617
3618                         ((void (*)(void *, void *))(void *)prop.Set)(test, dataForm);
3619
3620                         string = ((char * (*)(void *, void *, void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnGetString])(dataType, dataForm, tempString, null, &needClass);
3621
3622                         eClass_FindNextMember(_class, curClass, curMember, null, null);
3623                         if(*curMember != (DataMember)prop)
3624                            f.Printf("%s = ", prop.name);
3625
3626                         *curMember = (DataMember)prop;
3627                         *curClass = curMember->_class;
3628
3629                         if(needClass)
3630                            f.Printf("%c %s %c", /*dataType.name, */OpenBracket, string, CloseBracket);
3631                         else
3632                            f.Printf("%s", string);
3633                         *prev = true;
3634                      }
3635
3636                      delete dataForm;
3637                      delete dataTest;
3638                   }
3639                   else if(dataType.type == normalClass || dataType.type == noHeadClass)
3640                   {
3641                      void * dataForm, * dataTest;
3642
3643                      dataForm = ((void *(*)(void *))(void *)prop.Get)(control);
3644                      dataTest = ((void *(*)(void *))(void *)prop.Get)(test);
3645
3646                      if((prop.IsSet && !prop.IsSet(test)) || ((int (*)(void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnCompare])(dataType, dataForm, dataTest))
3647                      {
3648                         char tempString[1024] = "";
3649                         char * string = "";
3650                         if(*prev)
3651                            f.Printf(", ");
3652
3653                         ((void (*)(void *, void *))(void *)prop.Set)(test, dataForm);
3654
3655                         eClass_FindNextMember(_class, curClass, curMember, null, null);
3656                         if(*curMember != (DataMember)prop)
3657                            f.Printf("%s = ", prop.name);
3658                         *curMember = (DataMember)prop;
3659                         *curClass = curMember->_class;
3660
3661                         if(eClass_GetDesigner(dataType))
3662                         {
3663                            if(eClass_IsDerived(classObject.instance._class, dataType) && classObject.instance == dataForm)
3664                            //if(!strcmp(classObject.instance._class.name, dataType.name) && classObject.instance == dataForm)
3665                               f.Printf("this", prop.name);
3666                            else
3667                            {
3668                               //ObjectInfo classObject;
3669                               //for(classObject = classes.first; classObject; classObject = classObject.next)
3670                               {
3671                                  ObjectInfo object;
3672
3673                                  for(object = classObject.instances.first; object; object = object.next)
3674                                  {
3675                                     if(!object.deleted && eClass_IsDerived(object.instance._class, dataType) && object.instance == dataForm && object.name)
3676                                     {
3677                                        f.Printf("%s", object.name);
3678                                        break;
3679                                     }
3680                                  }
3681
3682                                  if(!object)
3683                                  {
3684                                     bool needClass = true;
3685                                     string = ((char * (*)(void *, void *, void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnGetString])(dataType, dataForm, tempString, null, &needClass);
3686                                     f.Printf("%s", string);
3687                                  }
3688                               }
3689                            }
3690                         }
3691                         else
3692                         {
3693                            bool needClass = true;
3694                            string = ((char * (*)(void *, void *, void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnGetString])(dataType, dataForm, tempString, null, &needClass);
3695
3696                            if(!strcmp(dataType.dataTypeString, "char *"))
3697                            {
3698                               f.Printf("\"");
3699                               OutputString(f, string);
3700                               f.Puts("\"");
3701                            }
3702                            else if(needClass)
3703                               f.Printf("%c %s %c", /*dataType.name, */OpenBracket, string, CloseBracket);
3704                            else
3705                               f.Printf("%s", string);
3706                         }
3707                         *prev = true;
3708                         *lastIsMethod = false;
3709                      }
3710                   }
3711                   else
3712                   {
3713                      DataValue dataForm, dataTest;
3714
3715                      GetProperty(prop, control, &dataForm);
3716                      GetProperty(prop, test, &dataTest);
3717
3718                      if((prop.IsSet && !prop.IsSet(test)) || ((int (*)(void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnCompare])(dataType, &dataForm, &dataTest))
3719                      {
3720                         char * string;
3721                         char tempString[1024] = "";
3722                         SetProperty(prop, test, dataForm);
3723
3724                         if(dataType.type != bitClass)
3725                         {
3726                            bool needClass = true;
3727
3728                            if(dataType.type == enumClass)
3729                            {
3730                               NamedLink value;
3731                               Class enumClass = eSystem_FindClass(privateModule, "enum");
3732                               EnumClassData e = ACCESS_CLASSDATA(dataType, enumClass);
3733
3734                               for(value = e.values.first; value; value = value.next)
3735                               {
3736                                  if((int)value.data == dataForm.i)
3737                                  {
3738                                     string = value.name;
3739                                     break;
3740                                  }
3741                               }
3742                            }
3743                            else
3744                               string = ((char * (*)(void *, void *, void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnGetString])(dataType, &dataForm, tempString, null, &needClass);
3745
3746                            if(string && string[0])
3747                            {
3748                               if(*prev)
3749                                  f.Printf(", ");
3750
3751                               eClass_FindNextMember(_class, curClass, curMember, null, null);
3752                               if(*curMember != (DataMember)prop)
3753                                  f.Printf("%s = ", prop.name);
3754                               *curMember = (DataMember)prop;
3755                               *curClass = curMember->_class;
3756
3757                               if(!strcmp(dataType.dataTypeString, "float") && strchr(string, '.'))
3758                                  f.Printf("%sf", string);
3759                               else
3760                                  f.Printf("%s", string);
3761                               *prev = true;
3762                            }
3763                         }
3764                         else if(dataType.type == bitClass)
3765                         {
3766                            bool needClass = true;
3767
3768                            if(*prev) f.Printf(", ");
3769
3770                            eClass_FindNextMember(_class, curClass, curMember, null, null);
3771                            if(*curMember != (DataMember)prop)
3772                               f.Printf("%s = ", prop.name);
3773                            *curMember = (DataMember)prop;
3774                            *curClass = curMember->_class;
3775
3776                            string = ((char * (*)(void *, void *, void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnGetString])(dataType, &dataForm.ui, tempString, null, &needClass);
3777                            if(needClass)
3778                               f.Printf("%c %s %c", /*dataType.name, */OpenBracket, string, CloseBracket);
3779                            else
3780                               f.Printf("%s", string);
3781                            *prev = true;
3782                            *lastIsMethod = false;
3783                         }
3784                      }
3785                   }
3786                }
3787             }
3788          }
3789       }
3790    }
3791
3792    int UpdateInstanceCode(EditBoxStream f, int position, Class regClass, ObjectInfo object, bool * firstObject, char ** text, int * textSize, int movedFuncIdLen, int movedFuncIdPos)
3793    {
3794       Instantiation inst = object.instCode;
3795       Window control = (Window)object.instance;
3796       bool prev = false;
3797       bool methodPresent = false;
3798       Class _class;
3799       bool lastIsMethod = true;
3800       ObjectInfo classObject = object.oClass;
3801
3802       if(inst)
3803       {
3804          if(object.deleted)
3805          {
3806             // Instance removed, delete it
3807             DeleteJunkBefore(f, inst.loc.start.pos, &position);
3808
3809             f.DeleteBytes(inst.loc.end.pos - inst.loc.start.pos + 1);
3810             position = inst.loc.end.pos + 1;
3811          }
3812          else
3813          {
3814             bool multiLine = false;
3815
3816             // Change the name
3817             // Check if it's an unnamed instance
3818             if(inst.exp)
3819             {
3820                f.Seek(inst.nameLoc.start.pos - position, current);
3821                f.DeleteBytes(inst.nameLoc.end.pos - inst.nameLoc.start.pos);
3822                position = inst.nameLoc.end.pos;
3823                if(object.name)
3824                   f.Printf(object.name);
3825                else
3826                {
3827                   char ch = 0;
3828                   f.Getc(&ch);
3829                   if(isspace(ch) && ch != '\n')
3830                   {
3831                      f.Seek(-1, current);
3832                      f.DeleteBytes(1);
3833                      position ++;
3834                   }
3835                }
3836             }
3837             else
3838             {
3839                int pos = inst.loc.start.pos; // + strlen(inst._class.name);
3840                char ch;
3841                f.Seek(pos - position, current);
3842                while(f.Getc(&ch))
3843                {
3844                   if(isspace(ch))
3845                   {
3846                      f.Seek(-1, current);
3847                      break;
3848                   }
3849                   pos++;
3850                }
3851
3852                if(object.name)
3853                {
3854                   f.Puts(" ");
3855                   f.Puts(object.name);
3856                }
3857                position = pos;
3858             }
3859
3860             if((this.methodAction == actionAddMethod || this.moveAttached) && this.selected == object)
3861                methodPresent = true;
3862
3863             for(;;)
3864             {
3865                char ch = 0;
3866                if(!f.Getc(&ch))
3867                   break;
3868                position++;
3869                if(ch == OpenBracket)
3870                   break;
3871                if(ch == '\n')
3872                   multiLine = true;
3873             }
3874
3875             // TODO: Simplify this?
3876             if(methodPresent)
3877             {
3878                if(!multiLine)
3879                {
3880                   int count = 0;
3881                   int toDelete = 0;
3882                   int toAdd = 0;
3883
3884                   f.Seek(-1, current);
3885                   DeleteJunkBefore(f, position, &position);
3886                   f.Puts("\n   ");
3887                   f.Seek(1, current);
3888                   //f.Puts("\n");
3889
3890                   // Fix indentation
3891                   for(;;)
3892                   {
3893                      char ch = 0;
3894                      if(!f.Getc(&ch))
3895                         break;
3896                      position++;
3897                      if(ch == '\n') { toDelete = count; count = 0; }
3898                      else if(isspace(ch)) count++;
3899                      else
3900                      {
3901                         f.Seek(-1, current);
3902                         position--;
3903                         if(count > 6)
3904                         {
3905                            toDelete += count - 6;
3906                            count = 6;
3907                         }
3908                         else
3909                            toAdd = 6 - count;
3910                         break;
3911                      }
3912                   }
3913                   if(toDelete)
3914                   {
3915                      f.Seek(-toDelete-count, current);
3916                      f.DeleteBytes(toDelete);
3917                      f.Seek(count, current);
3918                   }
3919
3920                   DeleteJunkBefore(f, position, &position);
3921
3922                   // Removed this here as it was adding trailing spaces when adding a method
3923                   /*
3924                   if(toAdd)
3925                   {
3926                      int c;
3927                      for(c = 0; c<toAdd; c++)
3928                         f.Putc(' ');
3929                   }
3930                   */
3931                }
3932             }
3933             else
3934                methodPresent = multiLine;
3935
3936             //if(!prev) -- always false
3937                f.Printf(methodPresent ? "\n      " : " ");
3938          }
3939       }
3940       else
3941       {
3942          // Instance not there, create a brand new one
3943          DeleteJunkBefore(f, position, &position);
3944          f.Printf(*firstObject ? "\n\n" : "\n");
3945          *firstObject = false;
3946
3947          if((this.methodAction == actionAddMethod || this.moveAttached) && this.selected == object)
3948             methodPresent = true;
3949
3950          if(methodPresent)
3951          {
3952             if(object.name)
3953                f.Printf("   %s %s\n   %c\n      ", control._class.name, object.name, OpenBracket);
3954             else
3955                f.Printf("   %s\n   %c\n      ", control._class.name, OpenBracket);
3956          }
3957          else
3958          {
3959             if(object.name)
3960                f.Printf("   %s %s %c ", control._class.name, object.name, OpenBracket);
3961             else
3962                f.Printf("   %s %c ", control._class.name, OpenBracket);
3963          }
3964       }
3965
3966       if(!object.deleted)
3967       {
3968          Instance test = eInstance_New(control._class);
3969          DataMember curMember = null;
3970          Class curClass = null;
3971          incref test;
3972
3973          UpdateInstanceCodeClass(control._class, object, f, test, &prev, &lastIsMethod, &curMember, &curClass);
3974
3975          delete test;
3976
3977          // Attach Method here
3978          if((this.methodAction == actionAttachMethod || this.methodAction == actionReattachMethod) && !this.moveAttached && this.selected == object)
3979          {
3980             if(prev) f.Printf(", ");
3981             f.Printf("%s = %s", this.method.name, function.declarator.symbol.string);
3982             prev = true;
3983          }
3984       }
3985
3986       if(inst && !object.deleted)
3987       {
3988          MembersInit members;
3989          Class instClass = eSystem_FindClass(this.privateModule, inst._class.name);
3990
3991          DeleteJunkBefore(f, position, &position);
3992
3993          // Instance already there, clear out the properties
3994          for(members = inst.members ? inst.members->first : null; members; members = members.next)
3995          {
3996             if(members.type == dataMembersInit)
3997             {
3998                MemberInit member;
3999
4000                if(members.dataMembers)
4001                {
4002                   bool keptMember = false;
4003                   MemberInit lastKept = null;
4004
4005                   for(member = members.dataMembers->first; member; member = member.next)
4006                   {
4007                      Identifier ident = member.identifiers ? member.identifiers->first : null;
4008                      bool deleted = false;
4009
4010                      // For now delete if it's not a method
4011                      if(!member.variable) // && ident)
4012                      {
4013                         if(!ident || !ident.next)
4014                         {
4015                            Property prop = ident ? eClass_FindProperty(instClass, ident.string, this.privateModule) : null;
4016                            if(!ident || prop)
4017                            {
4018                               f.Seek(member.loc.start.pos - position, current);
4019                               f.DeleteBytes(member.loc.end.pos - member.loc.start.pos);
4020                               position = member.loc.end.pos;
4021                               deleted = true;
4022                            }
4023                            else
4024                            {
4025                               Method method = eClass_FindMethod(instClass, ident.string, this.privateModule);
4026                               if(method && method.type == virtualMethod && member.initializer && member.initializer.type == expInitializer && member.initializer.exp &&
4027                                  member.initializer.exp.type == memberExp /*ExpIdentifier*/)
4028                               {
4029                                  if(((this.methodAction == actionDetachMethod || this.methodAction == actionReattachMethod) && this.method == method && this.selected == object) ||
4030                                     (this.methodAction == actionDeleteMethod && !strcmp(function.declarator.symbol.string, member.initializer.exp.identifier.string)))
4031                                  {
4032                                     f.Seek(member.loc.start.pos - position, current);
4033                                     f.DeleteBytes(member.loc.end.pos - member.loc.start.pos);
4034                                     position = member.loc.end.pos;
4035                                     deleted = true;
4036                                  }
4037                               }
4038                            }
4039                         }
4040                      }
4041                      if(!deleted)
4042                      {
4043                         keptMember = true;
4044                         lastKept = member;
4045
4046                         //f.Seek(member.loc.start.pos - position, current);
4047                         //position = member.loc.start.pos;
4048                         DeleteJunkBefore(f, member.loc.start.pos, &position);
4049                         if(prev) f.Printf(", ");
4050                         else if(keptMember) f.Printf(" ");
4051                         prev = false;
4052                      }
4053                   }
4054
4055                   if(!keptMember || !members.next)
4056                   {
4057                      char ch = 0;
4058                      int count = 0;
4059
4060                      if(keptMember && lastKept != members.dataMembers->last)
4061                      {
4062                         // Delete the comma
4063                         char ch;
4064                         int count = 0;
4065                         f.Seek(-1, current);
4066                         for(;f.Getc(&ch);)
4067                         {
4068                            if(ch == ',')
4069                            {
4070                               count++;
4071                               f.Seek(-1, current);
4072                               break;
4073                            }
4074                            else if(!isspace(ch))
4075                               break;
4076                            f.Seek(-2, current);
4077                            count++;
4078                         }
4079
4080                         if(ch == ',')
4081                            f.DeleteBytes(count);
4082                      }
4083
4084                      f.Seek(members.loc.end.pos - position, current);
4085                      f.Getc(&ch);
4086
4087                      if(ch == ';')
4088                      {
4089                         f.Seek(-1, current);
4090                         f.DeleteBytes(1);
4091                         position = members.loc.end.pos + 1;
4092                      }
4093                      else
4094                      {
4095                         f.Seek(-1, current);
4096                         position = members.loc.end.pos;
4097                      }
4098
4099                      if(keptMember)
4100                      {
4101                         prev = true;
4102                         lastIsMethod = false;
4103                      }
4104                   }
4105                   else
4106                   {
4107                      DeleteJunkBefore(f, position, &position);
4108                      f.Printf(" ");
4109
4110                      if(lastKept != members.dataMembers->last)
4111                      {
4112                         // Delete the comma
4113                         char ch;
4114                         int count = 0;
4115                         f.Seek(-1, current);
4116                         for(;f.Getc(&ch);)
4117                         {
4118                            if(ch == ',')
4119                            {
4120                               count++;
4121                               f.Seek(-1, current);
4122                               break;
4123                            }
4124                            else if(!isspace(ch))
4125                               break;
4126                            f.Seek(-2, current);
4127                            count++;
4128                         }
4129
4130                         if(ch == ',')
4131                            f.DeleteBytes(count);
4132                      }
4133                      else
4134                      {
4135                         f.Seek(members.loc.end.pos - position, current);
4136                         position = members.loc.end.pos;
4137                      }
4138                      /*
4139                      prev = false;
4140                      lastIsMethod = true;
4141                      */
4142                      prev = true;
4143                      lastIsMethod = false;
4144
4145                   }
4146                }
4147                else
4148                {
4149                   f.Seek(members.loc.end.pos - position, current);
4150                   position = members.loc.end.pos;
4151                   prev = false;
4152                   lastIsMethod = true;
4153                }
4154             }
4155             else if(members.type == methodMembersInit)
4156             {
4157                if(this.methodAction == actionDeleteMethod && members.function == function);
4158                else
4159                   methodPresent = true;
4160
4161                // Delete instance method here
4162                if((this.methodAction == actionDeleteMethod || (this.methodAction == actionDetachMethod && this.moveAttached)) &&
4163                   members.function == function)
4164                {
4165                   if(this.moveAttached && !*text)
4166                      GetLocText(editBox, f, position, &function.loc, text, textSize, Max((int)strlen(this.methodName) - movedFuncIdLen,0), 0);
4167
4168                   DeleteJunkBefore(f, members.loc.start.pos, &position);
4169                   f.DeleteBytes(members.loc.end.pos - members.loc.start.pos + 1);
4170                   position = members.loc.end.pos + 1;
4171                   f.Printf("\n");
4172                }
4173                else
4174                {
4175                   DeleteJunkBefore(f, position, &position);
4176                   if(!lastIsMethod)
4177                      f.Printf(";");
4178
4179                   DeleteJunkBefore(f, members.loc.start.pos, &position);
4180                   lastIsMethod = true;
4181                   f.Printf("\n\n      ");
4182                }
4183
4184                f.Seek(members.loc.end.pos - position, current);
4185                position = members.loc.end.pos;
4186             }
4187             DeleteJunkBefore(f, position, &position);
4188          }
4189       }
4190
4191       if(!object.deleted)
4192       {
4193          if(!methodPresent)
4194             f.Printf(" ");
4195
4196          if((this.methodAction == actionAddMethod || (this.moveAttached && (this.methodAction == actionAttachMethod || this.methodAction == actionReattachMethod))) && this.selected == object)
4197          {
4198             Method method = this.method;
4199             DeleteJunkBefore(f, position, &position);
4200             if(!lastIsMethod)
4201                f.Printf(";");
4202
4203             f.Printf("\n");
4204
4205             if(!method.dataType)
4206                method.dataType = ProcessTypeString(method.dataTypeString, false);
4207
4208             {
4209                Type dataType = method.dataType;
4210                Type returnType = dataType.returnType;
4211                Type param;
4212
4213                if(this.moveAttached)
4214                {
4215                   // Move function here:
4216                   int newLen = strlen(method.name);
4217
4218                   f.Printf("\n   ");
4219
4220                   if(!*text)
4221                      GetLocText(editBox, f, position, &function.loc, text, textSize, Max(newLen - movedFuncIdLen, 0), 3);
4222
4223                   // First change name of function
4224                   memmove(*text + movedFuncIdPos + newLen, *text + movedFuncIdPos + movedFuncIdLen, *textSize - movedFuncIdPos - movedFuncIdLen + 1);
4225                   *textSize += newLen - movedFuncIdLen;
4226                   memcpy(*text + movedFuncIdPos, method.name, newLen);
4227
4228                   // Second, tab right
4229                   {
4230                      int c;
4231                      for(c = 0; (*text)[c]; )
4232                      {
4233                         int i;
4234                         for(i = c; (*text)[i] && (*text)[i] != '\n'; i++);
4235                         if(i != c)
4236                         {
4237                            memmove((*text)+c+3, (*text)+c, *textSize+1-c);
4238                            (*text)[c] = (*text)[c+1] = (*text)[c+2] = ' ';
4239                            c += 3;
4240                            *textSize += 3;
4241                         }
4242                         for(; (*text)[c] && (*text)[c] != '\n'; c++);
4243                         if((*text)[c]) c++;
4244                      }
4245                   }
4246
4247                   f.Puts((*text));
4248                   f.Printf("\n");
4249                }
4250                else
4251                {
4252                   Class moduleClass = eSystem_FindClass(this.privateModule, "Module");
4253
4254                   // ADDING METHOD HERE
4255                   f.Printf("\n      ");
4256                   OutputType(f, returnType, false);
4257
4258                   f.Printf(" ");
4259                   if(dataType.thisClass)
4260                   {
4261                      if(!eClass_IsDerived(regClass, dataType.thisClass.registered) && !dataType.classObjectType)     // Just fixed this... was backwards.
4262                      {
4263                         if(dataType.thisClass.shortName)
4264                            f.Printf(dataType.thisClass.shortName);
4265                         else
4266                            f.Printf(dataType.thisClass.string);
4267                         f.Printf("::");
4268                      }
4269                   }
4270                   f.Printf(method.name);
4271                   f.Printf("(");
4272                   for(param = dataType.params.first; param; param = param.next)
4273                   {
4274                      OutputType(f, param, true);
4275                      if(param.next)
4276                         f.Printf(", ");
4277                   }
4278                   f.Printf(")\n");
4279                   f.Printf("      %c\n\n", OpenBracket);
4280
4281                   if(control._class._vTbl[method.vid] == moduleClass._vTbl[__ecereVMethodID___ecereNameSpace__ecere__com__Module_OnLoad]) // Temp Check for DefaultFunction
4282                   {
4283                      if(returnType.kind == classType && !strcmp(returnType._class.string, "bool"))
4284                         f.Printf("         return true;\n");
4285                      else if(returnType.kind != voidType)
4286                         f.Printf("         return 0;\n");
4287                   }
4288                   else
4289                   {
4290                      f.Printf("         ");
4291                      if(returnType.kind != voidType)
4292                         f.Printf("return ");
4293                      f.Printf("%s::%s(", control._class.name, method.name);
4294                      for(param = dataType.params.first; param; param = param.next)
4295                      {
4296                         if(param.prev) f.Printf(", ");
4297                         if(param.kind != voidType)
4298                            f.Printf(param.name);
4299                      }
4300                      f.Printf(");\n");
4301                   }
4302                   f.Printf("      %c\n", CloseBracket);
4303                }
4304             }
4305          }
4306       }
4307
4308       if(!object.instCode)
4309          f.Printf(methodPresent ? "   %c;" : "%c;", CloseBracket);
4310       else if(!object.deleted)
4311       {
4312          // Turn this into a multiline instance when adding a method
4313          DeleteJunkBefore(f, inst.loc.end.pos-1, &position);
4314
4315          f.Printf(methodPresent ? "\n   " : " ");
4316
4317          f.Seek(inst.loc.end.pos + 1 - position, current);
4318          position = inst.loc.end.pos + 1;
4319       }
4320       return position;
4321    }
4322
4323    void OutputClassProperties(Class _class, ObjectInfo classObject, EditBoxStream f, Instance test)
4324    {
4325       Property propIt;
4326       Class regClass = eSystem_FindClass(privateModule, classObject.name);
4327
4328       if(_class.base && _class.base.type != systemClass) OutputClassProperties(_class.base, classObject, f, test);
4329
4330       for(propIt = _class.membersAndProperties.first; propIt; propIt = propIt.next)
4331       {
4332          Property prop = eClass_FindProperty(selected.instance._class, propIt.name, privateModule);
4333          if(prop && prop.isProperty && !prop.conversion)
4334          {
4335             if(prop.Set && prop.Get && prop.dataTypeString && strcmp(prop.name, "name") && !Code_IsPropertyDisabled(classObject, prop.name) &&
4336                (!prop.IsSet || prop.IsSet(classObject.instance)))
4337             {
4338                Class dataType = prop.dataTypeClass;
4339                char tempString[1024] = "";
4340                char * string;
4341                bool specify = false;
4342                DataMember member;
4343
4344                member = eClass_FindDataMember(regClass, prop.name, privateModule, null, null);
4345                if(member && member._class == regClass)
4346                   specify = true;
4347
4348                if(!dataType)
4349                   dataType = prop.dataTypeClass = eSystem_FindClass(this.privateModule, prop.dataTypeString);
4350
4351                if(dataType && dataType.type == structClass)
4352                {
4353                   void * dataForm = new0 byte[dataType.structSize];
4354                   void * dataTest = new0 byte[dataType.structSize];
4355
4356                   ((void (*)(void *, void *))(void *)prop.Get)(classObject.instance, dataForm);
4357                   ((void (*)(void *, void *))(void *)prop.Get)(test, dataTest);
4358
4359                   if(((int (*)(void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnCompare])(dataType, dataForm, dataTest))
4360                   {
4361                      bool needClass = true;
4362
4363                      string = ((char * (*)(void *, void *, void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnGetString])(dataType, dataForm, tempString, null, &needClass);
4364                      ((void (*)(void *, void *))(void *)prop.Set)(test, dataForm);
4365                      if(needClass)
4366                         f.Printf("\n   %s%s = %c %s %c;", specify ? "property::" : "", prop.name, /*dataType.name, */OpenBracket, string, CloseBracket);
4367                      else
4368                         f.Printf("\n   %s%s = %s;", specify ? "property::" : "", prop.name, string);
4369                   }
4370                   delete dataForm;
4371                   delete dataTest;
4372                }
4373                else if(dataType && (dataType.type == normalClass || dataType.type == noHeadClass))
4374                {
4375                   void * dataForm, * dataTest;
4376
4377                   dataForm = ((void *(*)(void *))(void *)prop.Get)(classObject.instance);
4378                   dataTest = ((void *(*)(void *))(void *)prop.Get)(test);
4379
4380                   if(((int (*)(void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnCompare])(dataType, dataForm, dataTest))
4381                   {
4382                      char tempString[1024] = "";
4383                      char * string;
4384                      ((void (*)(void *, void *))(void *)prop.Set)(test, dataForm);
4385
4386                      if(eClass_IsDerived(classObject.instance._class, dataType) && classObject.instance == dataForm)
4387                      {
4388                         // Shouldn't go here ...
4389                         f.Printf("\n   %s%s = this;", specify ? "property::" : "", prop.name);
4390                      }
4391                      else
4392                      {
4393                         bool needClass = true;
4394
4395                         string = ((char * (*)(void *, void *, void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnGetString])(dataType, dataForm, tempString, null, &needClass);
4396
4397                         if(!strcmp(dataType.dataTypeString, "char *"))
4398                         {
4399                            f.Printf("\n   %s%s = \"", specify ? "property::" : "", prop.name);
4400                            OutputString(f, string);
4401                            f.Puts("\";");
4402                         }
4403                         else if(needClass)
4404                            f.Printf("\n   %s%s = %c %s %c;", specify ? "property::" : "", prop.name, /*dataType.name, */OpenBracket, string, CloseBracket);
4405                         else
4406                            f.Printf("\n   %s%s = %s;", specify ? "property::" : "", prop.name, string);
4407                      }
4408                   }
4409                }
4410                else if(dataType)
4411                {
4412                   DataValue dataForm, dataTest;
4413
4414                   GetProperty(prop, classObject.instance, &dataForm);
4415                   GetProperty(prop, test, &dataTest);
4416
4417                   if(((int (*)(void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnCompare])(dataType, &dataForm, &dataTest))
4418                   {
4419                      SetProperty(prop, test, dataForm);
4420                      if(dataType.type == bitClass)
4421                      {
4422                         bool needClass = true;
4423                         string = ((char * (*)(void *, void *, void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnGetString])(dataType, &dataForm, tempString, null, &needClass);
4424                         if(needClass)
4425                            f.Printf("\n   %s%s = %c %s %c;", specify ? "property::" : "", prop.name, /*dataType.name, */OpenBracket, string, CloseBracket);
4426                         else if(string[0])
4427                            f.Printf("\n   %s%s = %s;", specify ? "property::" : "", prop.name, string);
4428                      }
4429                      else
4430                      {
4431                         bool needClass = true;
4432                         if(dataType.type == enumClass)
4433                         {
4434                            NamedLink value;
4435                            Class enumClass = eSystem_FindClass(privateModule, "enum");
4436                            EnumClassData e = ACCESS_CLASSDATA(dataType, enumClass);
4437
4438                            for(value = e.values.first; value; value = value.next)
4439                            {
4440                               if((int)value.data == dataForm.i)
4441                               {
4442                                  string = value.name;
4443                                  break;
4444                               }
4445                            }
4446                         }
4447                         else
4448                            string = ((char * (*)(void *, void *, void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnGetString])(dataType, &dataForm, tempString, null, &needClass);
4449                         if(!strcmp(dataType.dataTypeString, "float") && strchr(string, '.'))
4450                            f.Printf("\n   %s%s = %sf;", specify ? "property::" : "", prop.name, string);
4451                         else if(string[0])
4452                            f.Printf("\n   %s%s = %s;", specify ? "property::" : "", prop.name, string);
4453                      }
4454                   }
4455                }
4456             }
4457          }
4458       }
4459    }
4460
4461    void UpdateFormCode()
4462    {
4463       if(!this) return;
4464       if(!parsing) return;
4465
4466       updatingCode++;
4467       if(codeModified)
4468       {
4469          ParseCode();
4470       }
4471       else if(formModified)
4472       {
4473          EditBoxStream f { editBox = editBox };
4474          int position = 0;
4475          char * text = null;
4476          int textSize;
4477          Identifier movedFuncId;
4478          int movedFuncIdLen = 0, movedFuncIdPos = 0;
4479          ObjectInfo classObject;
4480
4481            updatingCode++;
4482
4483          if(moveAttached)
4484          {
4485             movedFuncId = GetDeclId(function.declarator);
4486             movedFuncIdLen = movedFuncId.loc.end.pos - movedFuncId.loc.start.pos;
4487             movedFuncIdPos = movedFuncId.loc.start.pos - function.loc.start.pos;
4488          }
4489
4490          for(classObject = classes.first; classObject; classObject = classObject.next)
4491          {
4492             Class _class;
4493             ClassDefinition classDef = classObject.classDefinition;
4494             Class regClass = eSystem_FindClass(this.privateModule, ((Specifier)classDef.baseSpecs->first).name);
4495             Instance test;
4496             ClassDef def;
4497             bool firstObject = true;
4498             ObjectInfo object = classObject.instances.first;
4499             bool lastIsDecl = false;
4500
4501             if(!classObject.modified) continue;
4502
4503             test = eInstance_New(regClass);
4504             incref test;
4505
4506             // Put it in the same desktop window...
4507             designer.PrepareTestObject(test);
4508
4509             //f.Printf("class %s : %s\n", classObject.name, classObject.oClass.name);
4510             //f.Printf("%c\n\n", OpenBracket);
4511
4512             // Change the _class name
4513             f.Seek(classDef.nameLoc.start.pos - position, current);
4514             f.DeleteBytes(classDef.nameLoc.end.pos - classDef.nameLoc.start.pos);
4515             f.Printf(classObject.name);
4516             position = classDef.nameLoc.end.pos;
4517
4518             {
4519                // Go to block start, delete all until no white space, put \n
4520                char ch;
4521                int count = 0;
4522                int back = 0;
4523                f.Seek(classDef.blockStart.end.pos - position, current);
4524                position = classDef.blockStart.end.pos;
4525
4526                for(; f.Getc(&ch); count++)
4527                {
4528                   if(!isspace(ch))
4529                   {
4530                      f.Seek(-1, current);
4531                      break;
4532                   }
4533
4534                   if(ch == '\n')
4535                      back = 0;
4536                   else
4537                      back++;
4538                }
4539
4540                f.Seek(-count, current);
4541
4542                f.DeleteBytes(count-back);
4543                //f.Printf("\n");
4544                position += count-back;
4545             }
4546
4547             // Output properties
4548             OutputClassProperties(classObject.instance._class, classObject, f, test);
4549
4550             for(def = classDef.definitions->first; def; def = def.next)
4551             {
4552                switch(def.type)
4553                {
4554                   case defaultPropertiesClassDef:
4555                   {
4556                      bool keptMember = false;
4557                      MemberInit propDef;
4558                      MemberInit lastKept = null;
4559
4560                      lastIsDecl = false;
4561                      DeleteJunkBefore(f, def.loc.start.pos, &position);
4562
4563                      // This was adding blank spaces between comment and properties -- What was it for?
4564                      // f.Printf("\n   ");
4565
4566                      for(propDef = def.defProperties->first; propDef; propDef = propDef.next)
4567                      {
4568                         Identifier ident = propDef.identifiers->first;
4569                         bool deleted = false;
4570
4571                         // For now delete if it's a prop
4572                         if(!propDef.variable && ident)
4573                         {
4574                            if(!ident.next)
4575                            {
4576                               Property prop = eClass_FindProperty(regClass, ident.string, this.privateModule);
4577                               if(prop)
4578                               {
4579                                  f.Seek(propDef.loc.start.pos - position, current);
4580                                  f.DeleteBytes(propDef.loc.end.pos - propDef.loc.start.pos);
4581                                  position = propDef.loc.end.pos;
4582                                  deleted = true;
4583                               }
4584                               else
4585                               {
4586                                  Method method = eClass_FindMethod(regClass, ident.string, this.privateModule);
4587                                  if(method && method.type == virtualMethod && propDef.initializer && propDef.initializer.type == expInitializer && propDef.initializer.exp && propDef.initializer.exp.type == identifierExp)
4588                                  {
4589                                     if(((methodAction == actionDetachMethod || methodAction == actionReattachMethod) && method == this.method && selected == classObject) ||
4590                                        (methodAction == actionDeleteMethod && !strcmp(function.declarator.symbol.string, propDef.initializer.exp.identifier.string)))
4591                                     {
4592                                        f.Seek(propDef.loc.start.pos - position, current);
4593                                        f.DeleteBytes(propDef.loc.end.pos - propDef.loc.start.pos);
4594                                        position = propDef.loc.end.pos;
4595                                        deleted = true;
4596                                     }
4597                                  }
4598                               }
4599                            }
4600                         }
4601                         if(!deleted)
4602                         {
4603                            keptMember = true;
4604                            lastKept = propDef;
4605                         }
4606                      }
4607
4608                      if(!keptMember)
4609                      {
4610                         char ch = 0;
4611                         int count = 0;
4612                         f.Seek(def.loc.end.pos - position - 1, current);
4613                         f.Getc(&ch);
4614
4615                         if(ch == ';')
4616                         {
4617                            f.Seek(-1, current);
4618                            f.DeleteBytes(1);
4619                         }
4620                         position = def.loc.end.pos;
4621                      }
4622                      else
4623                      {
4624                         if(lastKept != def.defProperties->last)
4625                         {
4626                            char ch;
4627                            int count = 0;
4628
4629                            f.Seek(-1, current);
4630                            for(;f.Getc(&ch);)
4631                            {
4632                               if(ch == ',')
4633                               {
4634                                  count++;
4635                                  f.Seek(-1, current);
4636                                  break;
4637                               }
4638                               else if(!isspace(ch))
4639                                  break;
4640                               f.Seek(-2, current);
4641                               count++;
4642                            }
4643
4644                            if(ch == ',')
4645                               f.DeleteBytes(count);
4646                         }
4647                         else
4648                         {
4649                            f.Seek(def.loc.end.pos - position, current);
4650                            position = def.loc.end.pos;
4651                         }
4652                      }
4653                      break;
4654                   }
4655                   case declarationClassDef:
4656                   {
4657                      Declaration decl = def.decl;
4658
4659                      if(decl.type == instDeclaration)
4660                      {
4661                         if(def.object/* && ((ObjectInfo)def.object).modified*/)
4662                         {
4663                            while(def.object && object != def.object)
4664                            {
4665                               if(object /*&& ((ObjectInfo)def.object).modified*/)
4666                                  position = UpdateInstanceCode(f, position, regClass, object, &firstObject, &text, &textSize, movedFuncIdLen, movedFuncIdPos);
4667                               object = object.next;
4668                            }
4669
4670                            DeleteJunkBefore(f, def.loc.start.pos, &position);
4671                            f.Printf(firstObject ? "\n\n   " : "\n   ");
4672                            firstObject = false;
4673
4674                            if(def.object && ((ObjectInfo)def.object).modified)
4675                               position = UpdateInstanceCode(f, position, regClass, def.object, &firstObject, &text, &textSize, movedFuncIdLen, movedFuncIdPos);
4676
4677                            object = object ? object.next : null;
4678                         }
4679                         else
4680                         {
4681                            DeleteJunkBefore(f, def.loc.start.pos, &position);
4682                            f.Printf(firstObject ? "\n\n   " : "\n   ");
4683                            firstObject = false;
4684                         }
4685                         lastIsDecl = false;
4686                      }
4687                      else
4688                      {
4689                         DeleteJunkBefore(f, def.loc.start.pos, &position);
4690                         f.Printf(lastIsDecl ? "\n   " : "\n\n   ");
4691                         lastIsDecl = true;
4692                      }
4693                      break;
4694                   }
4695                   case functionClassDef:
4696                   {
4697                      // TESTING IF THIS IS GOOD ENOUGH FOR GENERATED FUNCTION...
4698                      if(!def.function.body) continue;
4699
4700                      lastIsDecl = false;
4701
4702                      DeleteJunkBefore(f, def.loc.start.pos, &position);
4703                      f.Printf("\n\n   ");
4704
4705                      // Delete _class methods
4706                      if((methodAction == actionDeleteMethod || (moveAttached && selected != classObject)) &&
4707                         def.function == function)
4708                      {
4709                         char ch;
4710                         int count = 0;
4711
4712                         if(moveAttached && !text)
4713                         {
4714                            GetLocText(editBox, f, position, &function.loc, &text, &textSize, Max((int)strlen(methodName) - movedFuncIdLen,0), 3);
4715                         }
4716
4717                         f.Seek(def.loc.end.pos - position, current);
4718                         for(; f.Getc(&ch); count++)
4719                         {
4720                            if(!isspace(ch))
4721                            {
4722                               f.Seek(-1, current);
4723                               break;
4724                            }
4725                         }
4726                         f.Seek(def.loc.start.pos - def.loc.end.pos - count, current);
4727
4728                         f.DeleteBytes(def.loc.end.pos - def.loc.start.pos + count);
4729                         position = def.loc.end.pos + count;
4730                      }
4731
4732                      // In case of detaching methods in the _class, simply rename the method
4733                      if(methodAction == actionDetachMethod && moveAttached && selected == classObject && function == def.function)
4734                      {
4735                         f.Seek(function.loc.start.pos + movedFuncIdPos - position, current);
4736                         f.DeleteBytes(movedFuncIdLen);
4737                         f.Puts(methodName);
4738                         position = function.loc.start.pos + movedFuncIdPos + movedFuncIdLen;
4739                      }
4740
4741                      if((methodAction == actionAttachMethod || methodAction == actionReattachMethod) && selected == classObject && moveAttached &&
4742                         function == def.function)
4743                      {
4744                         // In case of attaching methods in the _class, simply rename the method
4745                         f.Seek(function.loc.start.pos + movedFuncIdPos - position, current);
4746                         position = function.loc.start.pos + movedFuncIdPos;
4747                         f.DeleteBytes(movedFuncIdLen);
4748                         if(method.dataType.thisClass)
4749                            f.Printf("%s::", method.dataType.thisClass.string);
4750                         f.Puts(method.name);
4751                         position += movedFuncIdLen;
4752                      }
4753                      break;
4754                   }
4755                   default:
4756                      DeleteJunkBefore(f, def.loc.start.pos, &position);
4757                      if(def.type == memberAccessClassDef)
4758                      {
4759                         f.Printf("\n\n");
4760                         firstObject = false;
4761                         lastIsDecl = true;
4762                      }
4763                      else
4764                      {
4765                         f.Printf("\n   ");
4766                         lastIsDecl = false;
4767                      }
4768                }
4769
4770                f.Seek(def.loc.end.pos - position, current);
4771                position = def.loc.end.pos;
4772             }
4773
4774             // Output attached methods
4775             if((methodAction == actionAttachMethod || methodAction == actionReattachMethod) && selected == classObject && !moveAttached)
4776             {
4777                DeleteJunkBefore(f, position, &position);
4778                f.Printf("\n   %s = %s;\n", method.name, function.declarator.symbol.string);
4779             }
4780
4781             // ********** INSTANCES ***************
4782             for(; object; object = object.next)
4783             {
4784                if(!object.instCode)
4785                {
4786                   position = UpdateInstanceCode(f, position, regClass, object, &firstObject, &text, &textSize, movedFuncIdLen, movedFuncIdPos);
4787                }
4788             }
4789
4790             DeleteJunkBefore(f, position, &position);
4791
4792             // ****************** METHODS ***********************
4793             if(methodAction == actionDetachMethod && moveAttached && classObject == oClass)
4794             {
4795                // If detaching an instance method
4796                if(selected != classObject)
4797                {
4798                   int newLen = strlen(methodName);
4799
4800                   if(!text)
4801                      GetLocText(editBox, f, position, &function.loc, &text, &textSize, Max(newLen - movedFuncIdLen,0), 0);
4802                   // Tab selection left
4803                   {
4804                      int c;
4805                      for(c = 0; text[c]; )
4806                      {
4807                         int start = c, i;
4808                         for(i = 0; i<3 && text[c] == ' '; i++, c++);
4809                         memmove(text+start, text+start+i, textSize+1-start-i);
4810                         textSize -= i;
4811                         c -= i;
4812                         for(; text[c] && text[c] != '\n'; c++);
4813                         if(text[c]) c++;
4814                      }
4815                   }
4816
4817                   // Rename function
4818                   memmove(text + movedFuncIdPos + newLen, text + movedFuncIdPos + movedFuncIdLen, textSize - movedFuncIdPos - movedFuncIdLen + 1);
4819                   textSize += newLen - movedFuncIdLen;
4820                   memcpy(text + movedFuncIdPos, methodName, newLen);
4821
4822                   f.Printf("\n\n   ");
4823                   f.Puts(text);
4824                }
4825             }
4826
4827             if(methodAction == actionAddMethod && selected == classObject)
4828             {
4829                Method method = this.method;
4830
4831                if(!method.dataType)
4832                   method.dataType = ProcessTypeString(method.dataTypeString, false);
4833
4834                // ADDING METHOD HERE
4835                {
4836                   Type dataType = method.dataType;
4837                   Type returnType = dataType.returnType;
4838                   Type param;
4839                   Class moduleClass = eSystem_FindClass(this.privateModule, "Module");
4840
4841                   f.Printf("\n\n");
4842                   f.Printf("   ");
4843                   OutputType(f, returnType, false);
4844
4845                   f.Printf(" ");
4846                   if(dataType.thisClass && !dataType.classObjectType)
4847                   {
4848                      if(dataType.thisClass.shortName)
4849                         f.Printf(dataType.thisClass.shortName);
4850                      else
4851                         f.Printf(dataType.thisClass.string);
4852                      f.Printf("::");
4853                   }
4854                   f.Printf(method.name);
4855                   f.Printf("(");
4856                   for(param = dataType.params.first; param; param = param.next)
4857                   {
4858                      OutputType(f, param, true);
4859                      if(param.next)
4860                         f.Printf(", ");
4861                   }
4862                   f.Printf(")\n");
4863                   f.Printf("   %c\n\n", OpenBracket);
4864
4865                   if(test._class._vTbl[method.vid] == moduleClass._vTbl[__ecereVMethodID___ecereNameSpace__ecere__com__Module_OnLoad]) // Temp Check for DefaultFunction
4866                   {
4867                      if(returnType && returnType.kind == classType && !strcmp(returnType._class.string, "bool"))
4868                         f.Printf("      return true;\n");
4869                      else if(returnType && returnType.kind != voidType)
4870                         f.Printf("      return 0;\n");
4871                   }
4872                   else
4873                   {
4874                      f.Printf("      ");
4875                      if(returnType.kind != voidType)
4876                         f.Printf("return ");
4877                      {
4878                         char * name = ((Specifier)classDef.baseSpecs->first).name;
4879                         Symbol _class = FindClass(name);
4880                         f.Printf("%s::%s(", (_class && _class.registered) ? _class.registered.name : name, method.name);
4881                      }
4882                      for(param = dataType.params.first; param; param = param.next)
4883                      {
4884                         if(param.prev) f.Printf(", ");
4885                         if(param.kind != voidType)
4886                            f.Printf(param.name);
4887                      }
4888                      f.Printf(");\n");
4889                   }
4890
4891                   f.Printf("   %c", CloseBracket);
4892                }
4893             }
4894
4895             DeleteJunkBefore(f, classDef.loc.end.pos-1, &position);
4896             f.Printf("\n");
4897
4898             delete test;
4899          }
4900
4901          updatingCode--;
4902          delete f;
4903
4904          ParseCode();
4905          delete text;
4906
4907          // TOFIX: Patch for a glitch where clicking at the end of the view seems one line off. No idea what could be going on?
4908          editBox.OnVScroll(setRange, editBox.scroll.y, 0);
4909       }
4910
4911       updatingCode--;
4912       codeModified = false;
4913       formModified = false;
4914       methodAction = 0;
4915       moveAttached = false;
4916       function = null;
4917       method = null;
4918    }
4919
4920    int FindMethod(char * methodName /*Method method*/, ClassFunction*functionPtr, Location propLoc)
4921    {
4922       int found = 0;
4923       ClassFunction function = null;
4924       if(methodName)
4925       {
4926          ObjectInfo object = this.selected;
4927
4928          if(object && object == this.oClass)
4929          {
4930             ClassDefinition classDef = object.oClass.classDefinition;
4931             ClassDef def;
4932             if(classDef && classDef.definitions)
4933             {
4934                for(def = classDef.definitions->first; def; def = def.next)
4935                {
4936                   if(def.type == functionClassDef && def.function.declarator)
4937                   {
4938                      if(!strcmp(def.function.declarator.symbol.string, methodName))
4939                      {
4940                         function = def.function;
4941                         found = 1;
4942                         break;
4943                      }
4944                   }
4945                   else if(def.type == defaultPropertiesClassDef)
4946                   {
4947                      MemberInit propDef;
4948
4949                      for(propDef = def.defProperties->first; propDef; propDef = propDef.next)
4950                      {
4951                         Identifier ident = propDef.identifiers ? propDef.identifiers->first : null;
4952                         if(ident && !ident.next)
4953                         {
4954                            if(!strcmp(ident.string, methodName) && propDef.initializer && propDef.initializer.type == expInitializer && propDef.initializer.exp && propDef.initializer.exp.type == identifierExp)
4955                            {
4956                               found = 2;
4957                               if(propLoc != null)
4958                                  propLoc = propDef.loc;
4959                               if(functionPtr)
4960                               {
4961                                  ClassDefinition classDef = object.oClass.classDefinition;
4962                                  ClassDef def;
4963                                  if(classDef.definitions)
4964                                  {
4965                                     for(def = classDef.definitions->first; def; def = def.next)
4966                                     {
4967                                        if(def.type == functionClassDef)
4968                                        {
4969                                           if(!strcmp(def.function.declarator.symbol.string, propDef.initializer.exp.identifier.string))
4970                                           {
4971                                              function = def.function;
4972                                              break;
4973                                           }
4974                                        }
4975                                     }
4976                                     if(function) break;
4977                                  }
4978                               }
4979                               else
4980                                  break;
4981                            }
4982                         }
4983                      }
4984                   }
4985                }
4986             }
4987          }
4988          else if(object)
4989          {
4990             Instantiation inst = object.instCode;
4991
4992             // Check here to see if the method already exists, no need to call ModifyCode in that case
4993             if(inst && inst.members)
4994             {
4995                MembersInit members;
4996                for(members = inst.members->first; members; members = members.next)
4997                {
4998                   switch(members.type)
4999                   {
5000                      case dataMembersInit:
5001                      {
5002                         if(members.dataMembers)
5003                         {
5004                            MemberInit member;
5005                            for(member = members.dataMembers->first; member; member = member.next)
5006                            {
5007                               Identifier ident = member.identifiers ? member.identifiers->first : null;
5008                               if(ident && !ident.next)
5009                               {
5010                                  if(!strcmp(ident.string, methodName) && member.initializer && member.initializer.type == expInitializer && member.initializer.exp && member.initializer.exp.type == memberExp /*ExpIdentifier*/)
5011                                  {
5012                                     found = 2;
5013                                     if(propLoc != null)
5014                                        propLoc = member.loc;
5015                                     if(functionPtr)
5016                                     {
5017                                        ClassDefinition classDef = object.oClass.classDefinition;
5018                                        ClassDef def;
5019                                        if(classDef.definitions)
5020                                        {
5021                                           for(def = classDef.definitions->first; def; def = def.next)
5022                                           {
5023                                              if(def.type == functionClassDef)
5024                                              {
5025                                                 if(def.function.declarator && !strcmp(def.function.declarator.symbol.string, member.initializer.exp.identifier.string))
5026                                                 {
5027                                                    function = def.function;
5028                                                    break;
5029                                                 }
5030                                              }
5031                                           }
5032                                           if(function) break;
5033                                        }
5034                                        if(!function)
5035                                        {
5036                                           // TODO: Fix memory leak
5037                                           function = ClassFunction
5038                                           {
5039                                              declarator = Declarator { symbol = Symbol { string = CopyString(member.initializer.exp.member.member ? member.initializer.exp.member.member.string : "") } }
5040                                           };
5041                                        }
5042                                     }
5043                                     else
5044                                        break;
5045                                  }
5046                               }
5047                            }
5048                         }
5049                         break;
5050                      }
5051                      case methodMembersInit:
5052                      {
5053                         if(members.function.declarator && !strcmp(members.function.declarator.symbol.string, methodName))
5054                         {
5055                            function = members.function;
5056                            found = 1;
5057                         }
5058                         break;
5059                      }
5060                   }
5061                   if(function)
5062                      break;
5063                }
5064             }
5065          }
5066       }
5067       if(functionPtr) *functionPtr = function;
5068       return found;
5069    }
5070
5071    void GoToMethod(char * methodName /*Method method*/)
5072    {
5073       if(methodName)
5074       {
5075          ObjectInfo object = selected;
5076          EditBoxStream f { editBox = editBox };
5077          ClassFunction function = null;
5078          bool atChar = false;
5079          int indent = 6;
5080          EditLine l1, l2;
5081          int y1,y2, x1, x2;
5082          Location propLoc = { {0,0,-1} };
5083
5084          // GO TO THE METHOD
5085          if(FindMethod(methodName, &function, &propLoc) == 1 && object != this.oClass) indent = 9;
5086          if(function && function.body)
5087          {
5088             bool lfCount = 0;
5089             f.Seek(function.body.loc.start.pos+1, current);
5090             for(;;)
5091             {
5092                char ch;
5093                if(!f.Getc(&ch))
5094                   break;
5095                if(ch == '\n')
5096                {
5097                   if(lfCount)
5098                   {
5099                      f.Seek(-1, current);
5100                      break;
5101                   }
5102                   lfCount++;
5103                }
5104                else if(!isspace(ch))
5105                {
5106                   f.Seek(-1, current);
5107                   atChar = true;
5108                   break;
5109                }
5110             }
5111          }
5112          else if(propLoc.start.pos > -1)
5113          {
5114             f.Seek(propLoc.start.pos, current);
5115             atChar = true;
5116          }
5117          editBox.GetSelPos(&l1, &y1, &x1, &l2, &y2, &x2, false);
5118          delete f;
5119          if(function || propLoc.start.pos > -1)
5120          {
5121             editBox.SetSelPos(l1, y1, atChar ? x1 : indent, l2, y2, atChar ? x2 : indent);
5122             editBox.CenterOnCursor();
5123             SetState(normal, false, 0);
5124             Activate();
5125
5126             if(function && function.declarator && function.declarator.symbol && !function.declarator.symbol.type)
5127             {
5128                FreeClassFunction(function);
5129             }
5130          }
5131       }
5132    }
5133
5134    void FindCompatibleMethods(Method method, OldList compatible)
5135    {
5136       ClassDefinition classDef = this.oClass.classDefinition;
5137       if(classDef && classDef.definitions)
5138       {
5139          Class regClass { };
5140          Class baseClass = eSystem_FindClass(this.privateModule, ((Specifier)classDef.baseSpecs->first).name);
5141          ClassDef def;
5142          Class _class;
5143          Symbol classSym { };
5144          Symbol selectedClass;
5145          if(this.selected == this.oClass)
5146             selectedClass = classSym;
5147          else
5148             selectedClass = FindClass(this.selected.instance._class.name);
5149
5150          regClass.name = classDef._class.name;
5151          regClass.base = eSystem_FindClass(this.privateModule, ((Specifier)classDef.baseSpecs->first).name);
5152          for(def = classDef.definitions->first; def; def = def.next)
5153          {
5154             if(def.type == functionClassDef && def.function.declarator)
5155             {
5156                Method vMethod = eClass_FindMethod(baseClass, def.function.declarator.symbol.string, this.privateModule);
5157                if(!vMethod)
5158                   vMethod = eClass_FindMethod(this.selected.instance._class, def.function.declarator.symbol.string, this.privateModule);
5159                if(!vMethod)
5160                {
5161                   Type type = def.function.declarator.symbol.type;
5162                   if(CheckCompatibleMethod(method, type, regClass, this.selected == this.oClass, FindClass(this.selected.instance._class.name)))
5163                   {
5164                      compatible.Add(OldLink { data = def.function });
5165                   }
5166                }
5167             }
5168          }
5169
5170          if(this.oClass && this.oClass.instance)
5171          {
5172             classSym.registered = regClass;
5173             //classSym.registered = this.oClass.oClass;
5174
5175             for(_class = regClass.base; _class; _class = _class.base)
5176             {
5177                Method testMethod;
5178                for(testMethod = (Method)_class.methods.first; testMethod; testMethod = (Method)((BTNode)testMethod).next)
5179                {
5180                   // TODO: Understand why these functions popup in attach list
5181                   if(testMethod.type != virtualMethod /*&& testMethod.function != Window_OnGetString && testMethod.function != Window_OnGetDataFromString*/)
5182                   {
5183                      if(!testMethod.dataType)
5184                         testMethod.dataType = ProcessTypeString(testMethod.dataTypeString, false);
5185
5186                      //if(CheckCompatibleMethod(method, testMethod.dataType, &regClass, false, selectedClass)) // this.selected == this.oClass, selectedClass))
5187                      if(CheckCompatibleMethod(method, testMethod.dataType, this.oClass.instance._class, false, selectedClass)) // this.selected == this.oClass, selectedClass))
5188                      //if(CheckCompatibleMethod(method, testMethod.dataType, &regClass, this.selected == this.oClass, FindClass(this.oClass.oClass.name)))
5189                      {
5190                         // TODO: Fix memory leak, Figure out if it should be ClassFunction or FunctionDefinition
5191                         // ClassFunction function { };
5192                         FunctionDefinition function { };
5193
5194                         function.declarator = Declarator { };
5195                         function.declarator.symbol = Symbol { string = CopyString(testMethod.name) };
5196                         excludedSymbols.Add(function.declarator.symbol);
5197
5198                         compatible.Add(OldLink { data = function });
5199                      }
5200                   }
5201                }
5202             }
5203          }
5204          delete regClass;
5205          delete classSym;
5206       }
5207    }
5208
5209    void AddMethod(Method method)
5210    {
5211       if(method)
5212       {
5213          char methodName[1024];
5214          strcpy(methodName, method.name);
5215          if(!FindMethod(methodName, null, null))
5216          {
5217             methodAction = actionAddMethod;
5218             this.method = method;
5219             ModifyCode();
5220          }
5221          UpdateFormCode();
5222          GoToMethod(methodName);
5223       }
5224    }
5225
5226    void DeleteMethod(ClassFunction function)
5227    {
5228       if(function)
5229       {
5230          methodAction = actionDeleteMethod;
5231          this.function = function;
5232          ModifyCode();
5233          UpdateFormCode();
5234
5235          Update(null);
5236       }
5237    }
5238
5239    void AttachMethod(Method method, ClassFunction function)
5240    {
5241       if(function)
5242       {
5243          // If it's an instance we'll ask if we want to move it inside...
5244          if(!function.attached.count && function.body)
5245          {
5246             // Find the function in the _class to check if it's a virtual function
5247             Class regClass = eSystem_FindClass(this.privateModule, ((Specifier)this.oClass.classDefinition.baseSpecs->first).name);
5248             Method method = eClass_FindMethod(regClass, function.declarator.symbol.string, this.privateModule);
5249             /*    LATER we'll need to check for public/virtual properties etc, for now only checked if virtual in base _class
5250             ClassDef def;
5251             for(def = this.classDefinition.first; def; def = def.next)
5252             {
5253                if(def.type == functionClassDef)
5254                {
5255                   if(def.function == function)
5256                      break;
5257                }
5258             }
5259             */
5260             if(!method || method.type != virtualMethod)
5261             {
5262                char title[1024];
5263                sprintf(title, $"Attach %s", function.declarator.symbol.string);
5264                if(MessageBox { type = yesNo, master = parent, text = title, contents = $"Method is unused. Move method inside instance?"}.Modal() == yes)
5265                {
5266                   moveAttached = true;
5267                }
5268             }
5269          }
5270
5271          methodAction = actionAttachMethod;
5272          this.method = method;
5273          this.function = function;
5274          ModifyCode();
5275          UpdateFormCode();
5276          Update(null);
5277       }
5278    }
5279
5280    void ReAttachMethod(Method method, ClassFunction function)
5281    {
5282       if(function)
5283       {
5284          // If it's an instance we'll ask if we want to move it inside...
5285          if(!function.attached.count && function.body)
5286          {
5287             // Find the function in the _class to check if it's a virtual function
5288             Class regClass = eSystem_FindClass(this.privateModule, ((Specifier)this.oClass.classDefinition.baseSpecs->first).name);
5289             Method method = eClass_FindMethod(regClass, function.declarator.symbol.string, this.privateModule);
5290             /*    LATER we'll need to check for public/virtual properties etc, for now only checked if virtual in base _class
5291             ClassDef def;
5292             for(def = this.classDefinition.first; def; def = def.next)
5293             {
5294                if(def.type == functionClassDef)
5295                {
5296                   if(def.function == function)
5297                      break;
5298                }
5299             }
5300             */
5301             if(!method || method.type != virtualMethod)
5302             {
5303                char title[1024];
5304                sprintf(title, $"Attach %s", function.declarator.symbol.string);
5305                if(MessageBox { type = yesNo, master = parent, text = title,
5306                   contents = $"Method is unused. Move method inside instance?" }.Modal() == yes)
5307                {
5308                   moveAttached = true;
5309                }
5310             }
5311          }
5312
5313          methodAction = actionReattachMethod;
5314          this.method = method;
5315          this.function = function;
5316          ModifyCode();
5317          UpdateFormCode();
5318          Update(null);
5319       }
5320    }
5321
5322    void DetachMethod(Method method, ClassFunction function, int type)
5323    {
5324       bool result = true;
5325
5326       if(type == 1)
5327       {
5328          Window dialog
5329          {
5330             hasClose = true, borderStyle = sizable, minClientSize = { 300, 55 },
5331             master = sheet, text = $"Name detached method", background = formColor
5332          };
5333          Button cancelButton
5334          {
5335             dialog, anchor = { horz = 45, top = 30 }, size = { 80 }, text = $"Cancel", hotKey = escape,
5336             id = DialogResult::cancel, NotifyClicked = ButtonCloseDialog
5337          };
5338          Button okButton
5339          {
5340             dialog, anchor = { horz = -45, top = 30 }, size = { 80 }, text = $"OK", isDefault = true,
5341             id = DialogResult::ok, NotifyClicked = ButtonCloseDialog
5342          };
5343          EditBox nameBox
5344          {
5345             dialog, anchor = { left = 5, right = 5, top = 5 }
5346          };
5347          sprintf(methodName, "%s_%s", selected.name, method.name);
5348          nameBox.contents = methodName;
5349          incref nameBox;
5350          result = dialog.Modal() == ok;
5351          strcpy(methodName, nameBox.contents);
5352          delete nameBox;
5353       }
5354       if(result)
5355       {
5356          // If the method is not attached, move it outside
5357          if(type == 1)
5358          {
5359             // Add this class to the methodName
5360             char name[1024] = "";
5361
5362             if(this.selected != this.oClass && !method.dataType.thisClass)
5363             {
5364                strcat(name, this.selected.instance._class.name);
5365                strcat(name, "::");
5366                strcat(name, this.methodName);
5367                strcpy(this.methodName, name);
5368             }
5369             else if(method.dataType.thisClass && (this.selected == this.oClass || !eClass_IsDerived(this.oClass.instance._class, method.dataType.thisClass.registered)))
5370             {
5371                strcat(name, method.dataType.thisClass.string);
5372                strcat(name, "::");
5373                strcat(name, this.methodName);
5374                strcpy(this.methodName, name);
5375             }
5376
5377             this.moveAttached = true;
5378          }
5379
5380          this.methodAction = actionDetachMethod;
5381          this.method = method;
5382          this.function = function;
5383          ModifyCode();
5384          UpdateFormCode();
5385          Update(null);
5386       }
5387    }
5388
5389    void AddObject(Instance instance, ObjectInfo * object)
5390    {
5391       int id;
5392       incref instance;
5393       //*object = _class.instances.Add(sizeof(ObjectInfo));
5394       *object = ObjectInfo { };
5395       oClass.instances.Insert((selected.oClass == selected) ? null : selected, *object);
5396       (*object).oClass = oClass;
5397       (*object).instance = instance;
5398       for(id = 1;; id++)
5399       {
5400          char name[1024];
5401          ObjectInfo check;
5402          sprintf(name, "%c%s%d", tolower(instance._class.name[0]), instance._class.name+1, id);
5403
5404          // if(strcmp(name, this.oClass.instance.name))
5405
5406          {
5407             for(check = oClass.instances.first; check; check = check.next)
5408                if(!check.deleted && check.name && !strcmp(name, check.name))
5409                   break;
5410             if(!check)
5411             {
5412                (*object).name = CopyString(name);
5413                break;
5414             }
5415          }
5416       }
5417       toolBox.controlClass = null;
5418
5419       ModifyCode();
5420
5421       //sheet.AddObject(*object, (*object).name, TypeData, true);
5422
5423       selected = *object;
5424    }
5425
5426    void EnsureUpToDate()
5427    {
5428       if(sheet && codeModified && parsing)
5429          ParseCode();
5430    }
5431
5432    void SelectObject(ObjectInfo object)
5433    {
5434       selected = object;
5435       oClass = object ? object.oClass : null;
5436       if(designer)
5437          designer.SelectObject(object, object ? object.instance : null);
5438    }
5439
5440    void SelectObjectFromDesigner(ObjectInfo object)
5441    {
5442       selected = object;
5443       sheet.SelectObject(object);
5444    }
5445
5446    void EnumerateObjects(Sheet sheet)
5447    {
5448       ObjectInfo oClass;
5449
5450       for(oClass = classes.first; oClass; oClass = oClass.next)
5451       {
5452          if(oClass.instance)
5453          {
5454             ObjectInfo object;
5455
5456             sheet.AddObject(oClass, oClass.name ? oClass.name : oClass.instance._class.name, typeClass, false);
5457             for(object = oClass.instances.first; object; object = object.next)
5458                sheet.AddObject(object, object.name ? object.name : object.instance._class.name, typeData, false);
5459          }
5460       }
5461       sheet.SelectObject(selected);
5462    }
5463
5464    void AddControl()
5465    {
5466       designer.AddObject();
5467    }
5468
5469    void DeleteObject(ObjectInfo object)
5470    {
5471       delete object.instance;
5472       object.deleted = true;
5473       object.modified = true;
5474       object.oClass.modified = true;
5475
5476       if(selected == object)
5477       {
5478          bool looped = false;
5479          ObjectInfo select = object;
5480
5481          for(;;)
5482          {
5483             select = select.prev;
5484             if(!select)
5485             {
5486                if(looped) break;
5487                select = object.oClass.instances.last;
5488                if(!select) break;
5489                looped = true;
5490             }
5491             if(!select.deleted)
5492                break;
5493          }
5494          sheet.SelectObject(select ? select : oClass);
5495       }
5496
5497       if(!object.instCode && object.oClass != object)
5498       {
5499          delete object.name;
5500          oClass.instances.Delete(object);
5501       }
5502
5503       if(sheet.codeEditor == this)
5504          sheet.DeleteObject(object);
5505    }
5506
5507    void RenameObject(ObjectInfo object, char * name)
5508    {
5509       bool valid = false;
5510
5511       // Validate the name:
5512       if(object != oClass && (!name || !name[0])) valid = true;   // What's this one again?
5513       else if(name[0] && (isalpha(name[0]) || name[0] == '_'))
5514       {
5515          int c;
5516          for(c = 0; name[c]; c++)
5517             if(!isalnum(name[c]) && name[c] != '_' && name[c] != '_')
5518                break;
5519          if(!name[c])
5520             valid = true;
5521       }
5522       if(valid)
5523       {
5524          delete object.name;
5525          object.name = (name && name[0]) ? CopyString(name) : null;
5526
5527          sheet.RenameObject(object, object.name ? object.name : object.instance._class.name);
5528       }
5529    }
5530
5531    void DesignerModifiedObject()
5532    {
5533       sheet.ListProperties(false);
5534       sheet.Update(null);
5535    }
5536
5537    void ListSubMembers(Type member)
5538    {
5539       Type subMember;
5540
5541       for(subMember = member.members.first; subMember; subMember = subMember.next)
5542       {
5543          if(subMember.name)
5544          {
5545             DataRow row = membersList.AddString(subMember.name);
5546             row.icon = icons[typeData];
5547          }
5548          else
5549          {
5550             ListSubMembers(subMember);
5551          }
5552       }
5553    }
5554
5555    void ListSubDataMembers(DataMember member, bool isPrivate)
5556    {
5557       DataMember subMember;
5558       for(subMember = member.members.first; subMember; subMember = subMember.next)
5559       {
5560          if((subMember.memberAccess == publicAccess && !isPrivate) || subMember._class.module == privateModule)
5561          {
5562             if(subMember.name)
5563             {
5564                DataRow row = membersList.AddString(subMember.name);
5565                BitmapResource bitmap = null;
5566                if(!subMember.dataType)
5567                   subMember.dataType = ProcessTypeString(subMember.dataTypeString, false);
5568
5569                if(subMember.dataType && subMember.dataType.kind == classType && subMember.dataType._class)
5570                {
5571                   char * bitmapName = (char *)eClass_GetProperty(subMember.dataType._class.registered, "icon");
5572                   if(bitmapName)
5573                   {
5574                      bitmap = { bitmapName };
5575                      membersList.AddResource(bitmap);
5576                   }
5577                }
5578                row.icon = bitmap ? bitmap : icons[(subMember.memberAccess == publicAccess && !isPrivate) ? typeData : typeDataPrivate];
5579             }
5580             else
5581             {
5582                ListSubDataMembers(subMember, isPrivate || member.memberAccess == privateAccess);
5583             }
5584          }
5585       }
5586    }
5587
5588    void ListClassMembers(Class whatClass, bool methodsOnly)
5589    {
5590       Class _class;
5591       Class baseClass = eSystem_FindClass(this.privateModule, "class");
5592       bool isPrivate = false;
5593
5594       for(_class = whatClass; _class && _class.type != systemClass; _class = _class.base)
5595       {
5596          Method method, methodIt;
5597          DataMember member;
5598          DataMember memberIt;
5599
5600          for(methodIt = (Method)_class.methods.first; methodIt; methodIt = (Method)((BTNode)methodIt).next)
5601          {
5602             method = eClass_FindMethod(whatClass, methodIt.name, privateModule);
5603             if(methodIt.memberAccess == privateAccess && method && method.memberAccess == publicAccess)
5604                method = methodIt;
5605             if(method && method._class.type != systemClass && !eClass_FindMethod(baseClass, method.name, this.privateModule))
5606             {
5607                if(method.memberAccess == publicAccess || method._class.module == privateModule)
5608                {
5609                   DataRow row = membersList.FindString(method.name);
5610                   if(!row)
5611                   {
5612                      row = membersList.AddString(method.name);
5613
5614                      if(!method.dataType)
5615                         method.dataType = ProcessTypeString(method.dataTypeString, false);
5616
5617                      row.icon = icons[(method.type == virtualMethod && method.dataType && method.dataType.thisClass) ? typeEvent : ((method.memberAccess == publicAccess && !isPrivate) ? typeMethod : typeMethodPrivate)];
5618                   }
5619                }
5620             }
5621          }
5622
5623          if(!methodsOnly)
5624          {
5625             for(memberIt = _class.membersAndProperties.first; memberIt; memberIt = memberIt.next)
5626             {
5627                if(memberIt.name)
5628                {
5629                   if(memberIt.isProperty)
5630                   {
5631                      member = (DataMember)eClass_FindProperty(whatClass, memberIt.name, privateModule);
5632                      if(!member)
5633                         member = eClass_FindDataMember(whatClass, memberIt.name, privateModule, null, null);
5634                   }
5635                   else
5636                   {
5637                      member = eClass_FindDataMember(whatClass, memberIt.name, privateModule, null, null);
5638                      if(!member)
5639                         member = (DataMember)eClass_FindProperty(whatClass, memberIt.name, privateModule);
5640                   }
5641
5642                   if(memberIt.memberAccess == privateAccess && member && member.memberAccess == publicAccess)
5643                      member = memberIt;
5644                }
5645                else
5646                   member = memberIt;
5647
5648                if(member && (member.memberAccess == publicAccess || member._class.module == privateModule))
5649                {
5650                   if(member.isProperty)
5651                   {
5652                      Property prop = (Property) member;
5653                      if(!membersList.FindString(prop.name))
5654                      {
5655                         DataRow row = membersList.AddString(prop.name);
5656                         row.icon = icons[(member.memberAccess == publicAccess && !isPrivate) ? typeProperty : typePropertyPrivate];
5657                      }
5658                   }
5659                   else if(member.name && !membersList.FindString(member.name))
5660                   {
5661                      DataRow row = membersList.AddString(member.name);
5662
5663                      BitmapResource bitmap = null;
5664                      if(!member.dataType)
5665                         member.dataType = ProcessTypeString(member.dataTypeString, false);
5666
5667                      if(member.dataType && member.dataType.kind == classType && member.dataType._class)
5668                      {
5669                         char * bitmapName = (char *)eClass_GetProperty(member.dataType._class.registered, "icon");
5670                         if(bitmapName)
5671                         {
5672                            bitmap = { bitmapName };
5673                            membersList.AddResource(bitmap);
5674                         }
5675                      }
5676                      row.icon = bitmap ? bitmap : icons[(member.memberAccess == publicAccess && !isPrivate) ? typeData : typeDataPrivate];
5677                   }
5678                   else
5679                      ListSubDataMembers(member, member.memberAccess == privateAccess);
5680                }
5681             }
5682          }
5683          if(_class.inheritanceAccess == privateAccess)
5684          {
5685             isPrivate = true;
5686             if(_class.module != privateModule) break;
5687          }
5688       }
5689    }
5690
5691    void ListClassMembersMatch(Class whatClass, Type methodType)
5692    {
5693       Class _class;
5694       Class baseClass = eSystem_FindClass(this.privateModule, "class");
5695       bool isPrivate = false;
5696
5697       for(_class = whatClass; _class && _class.type != systemClass; _class = _class.base)
5698       {
5699          Method method;
5700          Property prop;
5701          DataMember member;
5702
5703          for(method = (Method)_class.methods.first; method; method = (Method)((BTNode)method).next)
5704          {
5705             if(method.memberAccess == publicAccess || method._class.module == privateModule)
5706             {
5707                if(method._class.type != systemClass && !eClass_FindMethod(baseClass, method.name, this.privateModule))
5708                {
5709                   if(!method.dataType)
5710                      method.dataType = ProcessTypeString(method.dataTypeString, false);
5711
5712                   if(MatchTypes(method.dataType, methodType, null, whatClass, /*null, */whatClass, false, true, false, false))
5713                   {
5714                      DataRow row = membersList.FindString(method.name);
5715                      if(!row)
5716                      {
5717                         row = membersList.AddString(method.name);
5718                         row.icon = icons[(method.type == virtualMethod && method.dataType.thisClass) ? typeEvent : ((method.memberAccess == publicAccess && !isPrivate) ? typeMethod : typeMethodPrivate)];
5719                      }
5720                   }
5721                }
5722             }
5723          }
5724          if(_class.inheritanceAccess == privateAccess)
5725          {
5726             isPrivate = true;
5727             if(_class.module != privateModule) break;
5728          }
5729       }
5730    }
5731
5732    void ListClassPropertiesAndVirtual(Class whatClass, String curString)
5733    {
5734       Class _class;
5735       bool isPrivate = false;
5736       for(_class = whatClass; _class /*&& _class.type != systemClass*/; _class = _class.base)
5737       {
5738          Method method;
5739          Property prop;
5740          DataMember member;
5741
5742          for(method = (Method)_class.methods.first; method; method = (Method)((BTNode)method).next)
5743          {
5744             if(method.type == virtualMethod)
5745             {
5746                if(method.memberAccess == publicAccess || method._class.module == privateModule)
5747                {
5748                   DataRow row = membersList.FindString(method.name);
5749                   if(!row)
5750                   {
5751                      row = membersList.AddString(method.name);
5752
5753                      if(!method.dataType)
5754                         method.dataType = ProcessTypeString(method.dataTypeString, false);
5755
5756                      row.icon = icons[method.dataType.thisClass ? typeEvent : ((method.memberAccess == publicAccess && !isPrivate) ? typeMethod : typeMethodPrivate)];
5757                   }
5758                }
5759             }
5760          }
5761
5762          for(member = _class.membersAndProperties.first; member; member = member.next)
5763          {
5764             if(member.memberAccess == publicAccess || member._class.module == privateModule)
5765             {
5766                if(member.isProperty)
5767                {
5768                   Property prop = (Property)member;
5769                   {
5770                      DataRow row = membersList.AddString(prop.name);
5771                      row.icon = icons[(member.memberAccess == publicAccess && !isPrivate) ? typeProperty : typePropertyPrivate];
5772                   }
5773                }
5774                else if(member.name && (!curString || strcmp(curString, member.name)))
5775                {
5776                   DataRow row = membersList.AddString(member.name);
5777
5778                   BitmapResource bitmap = null;
5779                   if(!member.dataType)
5780                      member.dataType = ProcessTypeString(member.dataTypeString, false);
5781
5782                   if(member.dataType && member.dataType.kind == classType && member.dataType._class)
5783                   {
5784                      char * bitmapName = (char *)eClass_GetProperty(member.dataType._class.registered, "icon");
5785                      if(bitmapName)
5786                      {
5787                         bitmap = { bitmapName };
5788                         membersList.AddResource(bitmap);
5789                      }
5790                   }
5791                   row.icon = bitmap ? bitmap : icons[(member.memberAccess == publicAccess && !isPrivate) ? typeData : typeDataPrivate];
5792                }
5793                else
5794                   ListSubDataMembers(member, member.memberAccess == privateAccess || isPrivate);
5795             }
5796          }
5797          if(_class.inheritanceAccess == privateAccess)
5798          {
5799             isPrivate = true;
5800             if(_class.module != privateModule) break;
5801          }
5802       }
5803    }
5804
5805    void ListMembers(Type type)
5806    {
5807       if(type && (type.kind == classType || type.kind == structType || type.kind == unionType))
5808       {
5809          Class _class;
5810
5811          if(type.kind == classType)
5812          {
5813             if(type._class)
5814                ListClassMembers(type._class.registered, false);
5815          }
5816          else
5817          {
5818             Type member;
5819             for(member = type.members.first; member; member = member.next)
5820             {
5821                if(member.name)
5822                {
5823                   DataRow row = membersList.AddString(member.name);
5824                   row.icon = icons[typeData];
5825                }
5826                else if(member.kind == structType || member.kind == unionType)
5827                   ListSubMembers(member);
5828             }
5829          }
5830       }
5831    }
5832
5833    void ListModule(Module mainModule, int recurse, bool listClasses)
5834    {
5835       Module module;
5836       ListNameSpace(mainModule.application.systemNameSpace, 1, listClasses);
5837       ListNameSpace(mainModule.application.privateNameSpace, 1, listClasses);
5838       ListNameSpace(mainModule.application.publicNameSpace, 1, listClasses);
5839       for(module = mainModule.application.allModules.first; module; module = module.next)
5840       {
5841          if(ModuleVisibility(mainModule, module))
5842             ListNameSpace(module.publicNameSpace, recurse, listClasses);
5843       }
5844    }
5845
5846    void ListNameSpace(NameSpace nameSpace, int recurse, bool listClasses)
5847    {
5848       NameSpace * ns;
5849       BTNamedLink link;
5850
5851       if(listClasses)
5852       {
5853          for(link = (BTNamedLink)nameSpace.classes.first; link; link = (BTNamedLink)((BTNode)link).next)
5854          {
5855             Class _class = link.data;
5856             if(_class.type != systemClass && !_class.templateClass)  // Omit templatized classes
5857             {
5858                DataRow row = membersList.AddString(_class.name);
5859                row.icon = (_class.type == unitClass || _class.type == enumClass) ? icons[typeDataType] : icons[typeClass];
5860             }
5861          }
5862       }
5863
5864       for(link = (BTNamedLink)nameSpace.defines.first; link; link = (BTNamedLink)((BTNode)link).next )
5865       {
5866          DefinedExpression definedExp = link.data;
5867          DataRow row = membersList.AddString(link /*definedExp*/.name);
5868          row.icon = icons[typeData];
5869       }
5870
5871       for(link = (BTNamedLink)nameSpace.functions.first; link; link = (BTNamedLink)((BTNode)link).next)
5872       {
5873          GlobalFunction function = link.data;
5874          DataRow row = membersList.AddString(link /*function*/.name);
5875          row.icon = icons[typeMethod];
5876       }
5877
5878
5879       for(ns = (NameSpace *)nameSpace.nameSpaces.first; ns; ns = (NameSpace *)((BTNode)ns).next)
5880       {
5881          if(recurse != 2 && listClasses)
5882          {
5883             if(!membersList.FindString(ns->name))
5884             {
5885                DataRow row = membersList.AddString(ns->name);
5886                row.icon = icons[typeNameSpace];
5887             }
5888          }
5889
5890          if(recurse)
5891             ListNameSpace(ns, 2, listClasses);
5892       }
5893    }
5894
5895    void ListEnumValues(Class _class)
5896    {
5897       List<Class> classes { };
5898       for(; _class && _class.type == enumClass; _class = _class.base)
5899          classes.Insert(null, _class);
5900       for(_class : classes)
5901       {
5902          EnumClassData enumeration = (EnumClassData)_class.data;
5903          NamedLink item;
5904          for(item = enumeration.values.first; item; item = item.next)
5905          {
5906             DataRow row = membersList.AddString(item.name);
5907             row.icon = icons[typeEnumValue];
5908          }
5909       }
5910       delete classes;
5911    }
5912
5913    bool ListEnumsModule(Module mainModule, Type dest)
5914    {
5915       bool result = false;
5916       Module module;
5917       result |= ListEnums(mainModule.application.systemNameSpace, dest);
5918       result |= ListEnums(mainModule.application.privateNameSpace, dest);
5919       result |= ListEnums(mainModule.application.publicNameSpace, dest);
5920       for(module = mainModule.application.allModules.first; module; module = module.next)
5921       {
5922          if(ModuleVisibility(mainModule, module))
5923             result |= ListEnums(module.publicNameSpace, dest);
5924       }
5925       return result;
5926    }
5927
5928    void ListNameSpaceByString(Module mainModule, char * string)
5929    {
5930       NameSpace * nameSpace;
5931       Module module;
5932       nameSpace = FindNameSpace(mainModule.application.systemNameSpace, string);
5933       if(nameSpace) ListNameSpace(nameSpace, 0, true);
5934       nameSpace = FindNameSpace(mainModule.application.privateNameSpace, string);
5935       if(nameSpace) ListNameSpace(nameSpace, 0, true);
5936       nameSpace = FindNameSpace(mainModule.application.publicNameSpace, string);
5937       if(nameSpace) ListNameSpace(nameSpace, 0, true);
5938       for(module = mainModule.application.allModules.first; module; module = module.next)
5939       {
5940          if(ModuleVisibility(mainModule, module))
5941          {
5942             nameSpace = FindNameSpace(module.publicNameSpace, string);
5943             if(nameSpace) ListNameSpace(nameSpace, 0, true);
5944          }
5945       }
5946    }
5947
5948    bool ListEnums(NameSpace nameSpace, Type dest)
5949    {
5950       BTNamedLink link;
5951       bool result = false;
5952
5953       for(link = (BTNamedLink)nameSpace.classes.first; link; link = (BTNamedLink)((BTNode)link).next)
5954       {
5955          Class _class = link.data;
5956          if(_class.type == enumClass && (dest.kind != classType || ((!dest._class || !dest._class.registered || (dest._class.registered != _class && strcmp(dest._class.registered.dataTypeString, "char *"))) && !dest.classObjectType)) &&
5957             dest.kind != pointerType && dest.kind != ellipsisType)
5958          {
5959             OldList conversions { };
5960             Type type { };
5961             type.kind = classType;
5962             type._class = FindClass(_class.name);
5963             if(MatchTypes(type, dest, &conversions, null, null, true, false, false, false))
5964             {
5965                ListEnumValues(_class);
5966                result = true;
5967             }
5968             conversions.Free(null);
5969             delete type;
5970          }
5971       }
5972       for(nameSpace = (NameSpace *)nameSpace.nameSpaces.first; nameSpace != null; nameSpace = (NameSpace *)((BTNode)nameSpace).next)
5973       {
5974          result |= ListEnums(nameSpace, dest);
5975       }
5976       return result;
5977    }
5978
5979    NameSpace * FindNameSpace(NameSpace nameSpace, char * name)
5980    {
5981       int start = 0, c;
5982       char ch;
5983       for(c = 0; (ch = name[c]); c++)
5984       {
5985          if(ch == '.' || (ch == ':' && name[c+1] == ':'))
5986          {
5987             NameSpace * newSpace;
5988             char * spaceName = new char[c - start + 1];
5989             memcpy(spaceName, name + start, c - start);
5990             spaceName[c-start] = '\0';
5991             newSpace = (NameSpace *)nameSpace.nameSpaces.FindString(spaceName);
5992             delete spaceName;
5993             if(!newSpace)
5994                return null;
5995             nameSpace = newSpace;
5996             if(ch == ':') c++;
5997             start = c+1;
5998          }
5999       }
6000       if(c - start)
6001       {
6002          // name + start;
6003       }
6004       return (NameSpace *)nameSpace;
6005    }
6006
6007    void ListSymbols(Expression exp, bool enumOnly, char * string, Identifier realIdentifier)
6008    {
6009       bool listedEnums = false;
6010       Type destType = (exp && exp.destType && !exp.destType.truth) ? exp.destType : null;
6011       bool listClasses = true;
6012
6013       if(exp && (exp.type == identifierExp || exp.type == memberExp))
6014       {
6015          // TOCHECK: This memberExp check wasn't here... Some stuff isn't quite done
6016          Identifier id = (exp.type == memberExp) ? exp.member.member : exp.identifier;
6017          char * colons = id ? RSearchString(id.string, "::", strlen(id.string), true, false) : null;
6018
6019          if(exp.type == identifierExp)
6020             id = realIdentifier;
6021
6022          if(id && id._class && !id._class.name)
6023          {
6024             listClasses = false;
6025             SetThisClass(null);
6026          }
6027          else if(id && id._class && id._class.name)
6028          {
6029             if(id.classSym)
6030             {
6031                Class _class = id.classSym.registered;
6032                if(_class && _class.type == enumClass)
6033                {
6034                   ListEnumValues(_class);
6035                }
6036                else
6037                   ListClassMembers(id.classSym.registered, true);
6038                return;
6039             }
6040             return;
6041          }
6042          else if(id && colons)
6043          {
6044             ListNameSpaceByString(this.privateModule, id.string);
6045             return;
6046          }
6047       }
6048
6049       if(this.privateModule && destType && (destType.kind != pointerType || destType.type.kind != voidType) && destType.kind != ellipsisType)
6050       {
6051          listedEnums = ListEnumsModule(this.privateModule, destType);
6052       }
6053
6054       if(destType && destType.kind == classType && destType._class.registered && destType._class.registered.type == enumClass)
6055       {
6056          ListEnumValues(destType._class.registered);
6057
6058          if(insideClass)
6059             ListClassPropertiesAndVirtual(insideClass, null);
6060
6061          listedEnums = true;
6062       }
6063       else if(destType && destType.kind == enumType)
6064       {
6065          NamedLink value;
6066
6067          for(value = destType.members.first; value; value = value.next)
6068          {
6069             DataRow row = membersList.AddString(value.name);
6070             row.icon = icons[typeEnumValue];
6071          }
6072
6073          if(insideClass)
6074             ListClassPropertiesAndVirtual(insideClass, null);
6075
6076          listedEnums = true;
6077       }
6078       else if(insideClass && !enumOnly)
6079       {
6080          ListClassPropertiesAndVirtual(insideClass, string);
6081       }
6082
6083       if(listedEnums && string && string[0])
6084       {
6085          DataRow row = membersList.FindSubString(string);
6086          if(!row)
6087             listedEnums = false;
6088       }
6089
6090       if(!insideClass && exp && exp.destType && exp.destType.kind == functionType && GetThisClass())
6091       {
6092          ListClassMembersMatch(GetThisClass(), exp.destType);
6093       }
6094       else if(!insideClass && !enumOnly && !listedEnums)
6095       {
6096          Context ctx;
6097          Symbol symbol = null;
6098          {
6099             if(GetThisClass())
6100             {
6101                ListClassMembers(GetThisClass(), false);
6102             }
6103
6104             for(ctx = listClasses ? GetCurrentContext() : GetTopContext(); ctx != GetTopContext().parent && !symbol; ctx = ctx.parent)
6105             {
6106                for(symbol = (Symbol)ctx.symbols.first; symbol; symbol = (Symbol)((BTNode)symbol).next)
6107                {
6108                   // Don't list enum values?
6109                   //if(symbol.type.kind != TypeEnum)
6110                   DataRow row = membersList.FindString(symbol.string);
6111                   if(!row)
6112                   {
6113                      if(GetBuildingEcereComModule() && symbol.type && symbol.type.kind == functionType && eSystem_FindFunction(privateModule, symbol.string))
6114                         continue;
6115                      row = membersList.AddString(symbol.string);
6116                      if(symbol.type && symbol.type.kind == functionType)
6117                         row.icon = icons[typeMethod];
6118                      else if(symbol.type && symbol.type.kind == enumType)
6119                      {
6120                         row.icon = icons[typeEnumValue];
6121                      }
6122                      else
6123                      {
6124                         BitmapResource bitmap = null;
6125                         if(symbol.type && symbol.type.kind == classType && symbol.type._class && symbol.type._class)
6126                         {
6127                            char * bitmapName = (char *)eClass_GetProperty(symbol.type._class.registered, "icon");
6128                            if(bitmapName)
6129                            {
6130                               bitmap = { bitmapName };
6131                               membersList.AddResource(bitmap);
6132                            }
6133                         }
6134                         row.icon = bitmap ? bitmap : icons[typeData];
6135                      }
6136                   }
6137                }
6138
6139                if(listClasses)
6140                {
6141                   for(symbol = (Symbol)ctx.types.first; symbol; symbol = (Symbol)((BTNode)symbol).next)
6142                   {
6143                      DataRow row = membersList.FindString(symbol.string);
6144                      if(!row)
6145                      {
6146                         row = membersList.AddString(symbol.string);
6147                         if(symbol.type.kind == functionType)
6148                            row.icon = icons[typeMethod];
6149                         else if(symbol.type.kind == classType && (!symbol.type._class.registered || (symbol.type._class.registered.type != unitClass && symbol.type._class.registered.type != enumClass)))
6150                         {
6151                            row.icon = icons[typeClass];
6152                         }
6153                         else
6154                         {
6155                            row.icon = icons[typeDataType];
6156                         }
6157                      }
6158                   }
6159                }
6160             }
6161
6162             ListModule(this.privateModule, 1, listClasses);
6163             // TODO: Implement this with name space
6164             /*
6165             {
6166                GlobalData data;
6167                for(data = globalData.first; data; data = data.next)
6168                {
6169                   DataRow row = membersList.FindString(data.name);
6170                   if(!data.dataType)
6171                      data.dataType = ProcessTypeString(data.dataTypeString, false);
6172                   if(!row)
6173                   {
6174                      row = membersList.AddString(data.name);
6175
6176                      if(data.dataType && data.dataType.kind == TypeEnum)
6177                      {
6178                         row.icon = icons[typeEnumValue];
6179                      }
6180                      else
6181                      {
6182                         BitmapResource bitmap = null;
6183                         if(data.dataType && data.dataType.kind == classType && data.dataType._class && data.dataType._class)
6184                         {
6185                            char * bitmapName = (char *)eClass_GetProperty(data.dataType._class.registered, "icon");
6186                            if(bitmapName)
6187                            {
6188                               bitmap = { bitmapName };
6189                               membersList.AddResource(bitmap);
6190                            }
6191                         }
6192                         row.icon = bitmap ? bitmap : icons[typeData];
6193                      }
6194                   }
6195                }
6196             }
6197             */
6198
6199             {
6200                DataRow row = membersList.AddString("Min");
6201                row.icon = icons[typeMethod];
6202
6203                row = membersList.AddString("Max");
6204                row.icon = icons[typeMethod];
6205
6206                row = membersList.AddString("Abs");
6207                row.icon = icons[typeMethod];
6208
6209                row = membersList.AddString("Sgn");
6210                row.icon = icons[typeMethod];
6211             }
6212          }
6213       }
6214    }
6215
6216    void OverrideVirtualFunction(ClassFunction function, Method method, Class _class, bool isInstance, bool extraIndent)
6217    {
6218       EditBoxStream f { editBox = editBox };
6219       uint position = 0;
6220       EditLine l1, l2;
6221       int x1,y1,x2,y2;
6222
6223       updatingCode = true;
6224
6225       if(!method.dataType)
6226          method.dataType = ProcessTypeString(method.dataTypeString, false);
6227
6228       DeleteJunkBefore(f, function.loc.start.pos, &position);
6229       f.DeleteBytes(function.loc.end.pos - function.loc.start.pos - 1);
6230
6231       // ADDING METHOD HERE
6232       {
6233          Type dataType = method.dataType;
6234          Type returnType = dataType.returnType;
6235          Type param;
6236          Class moduleClass = eSystem_FindClass(this.privateModule, "Module");
6237
6238          if(insideDef.prev)
6239              f.Printf("\n\n");
6240          else
6241             f.Printf("\n");
6242          if(extraIndent) f.Printf("   ");
6243          f.Printf("   ");
6244          OutputType(f, returnType, false);
6245
6246          f.Printf(" ");
6247
6248          if(dataType.thisClass && !dataType.classObjectType && (!isInstance || !insideClass || !eClass_IsDerived(insideClass, dataType.thisClass.registered)))
6249          {
6250             if(dataType.thisClass.shortName)
6251                f.Printf(dataType.thisClass.shortName);
6252             else
6253                f.Printf(dataType.thisClass.string);
6254             f.Printf("::");
6255          }
6256          f.Printf(method.name);
6257          f.Printf("(");
6258          for(param = dataType.params.first; param; param = param.next)
6259          {
6260             // Decided not to write void...
6261             if(param.kind != voidType)
6262             {
6263                OutputType(f, param, true);
6264                if(param.next)
6265                   f.Printf(", ");
6266             }
6267          }
6268          f.Printf(")\n");
6269          if(extraIndent) f.Printf("   ");
6270          f.Printf("   %c\n", OpenBracket);
6271
6272          editBox.GetSelPos(&l1, &y1, &x1, &l2, &y2, &x2, false);
6273
6274          f.Printf("\n");
6275
6276          if(!_class ||
6277             (
6278                (isInstance ? _class : _class.base)._vTbl[method.vid] == moduleClass._vTbl[__ecereVMethodID___ecereNameSpace__ecere__com__Module_OnLoad] ||
6279                (isInstance ? _class : _class.base)._vTbl[method.vid] == DummyMethod)) // Temp Check for DefaultFunction
6280          {
6281             if(returnType && returnType.kind == classType && !strcmp(returnType._class.string, "bool"))
6282             {
6283                if(extraIndent) f.Printf("   ");
6284                f.Printf("      return true;\n");
6285             }
6286             else if(returnType && returnType.kind != voidType)
6287             {
6288                if(extraIndent) f.Printf("   ");
6289                f.Printf("      return 0;\n");
6290             }
6291          }
6292          else
6293          {
6294             if(extraIndent) f.Printf("   ");
6295             f.Printf("      ");
6296             if(returnType.kind != voidType)
6297                f.Printf("return ");
6298             f.Printf("%s::%s(", isInstance ? _class.name : _class.base.name, method.name);
6299             for(param = dataType.params.first; param; param = param.next)
6300             {
6301                if(param.prev) f.Printf(", ");
6302                if(param.kind != voidType)
6303                   f.Printf(param.name);
6304             }
6305             f.Printf(");\n");
6306          }
6307       }
6308
6309       if(extraIndent) f.Printf("   ");
6310       f.Printf("   %c", CloseBracket);
6311       // f.Printf("\n");
6312
6313       delete f;
6314
6315       if(extraIndent) { x1 += 3; x2 += 3; }
6316       editBox.SetSelPos(l1, y1, x1 + 6, l2, y2, x2 + 6);
6317
6318       this.updatingCode = false;
6319
6320    }
6321
6322    // Return false if we overrided a function and don't want to run params listing
6323    bool InvokeAutoComplete(bool enumOnly, int pointer, bool caretMove)
6324    {
6325       bool didOverride = false;
6326       EditLine line = editBox.line;
6327       char * text = line.text;
6328       int lineNum, charPos;
6329       Expression exp = null;
6330       EditLine l1, l2;
6331       int x1,y1, x2,y2;
6332       //Identifier id = null;
6333       Expression memberExp = null;
6334       Identifier realIdentifier = null;
6335
6336       if(!parsing) return true;
6337       if(!privateModule) return !didOverride;
6338
6339       insideFunction = null;
6340
6341       charPos = editBox.charPos + 1;
6342       if(!membersListShown)
6343       {
6344          EnsureUpToDate();
6345       }
6346
6347       editBox.GetSelPos(&l1, &y1, &x1, &l2, &y2, &x2, false);
6348       {
6349          EditBoxStream f { editBox = editBox };
6350
6351          updatingCode = true;
6352          editBox.SetSelPos(l1, y1, x1, l2, y2, x2);
6353          for(;;)
6354          {
6355             char ch;
6356             if(!f.Seek(-1, current))
6357                break;
6358             f.Getc(&ch);
6359             if(!isspace(ch)) break;
6360             f.Seek(-1, current);
6361          }
6362          editBox.GetSelPos(&l1, &y1, &x1, &l2, &y2, &x2, false);
6363
6364          lineNum = editBox.lineNumber + 1;
6365          charPos = editBox.charPos + 1;
6366          delete f;
6367          updatingCode = false;
6368       }
6369
6370       if(!membersListShown)
6371       {
6372          memberExp = FindExpTree(ast, lineNum, charPos);
6373          if(memberExp && (memberExp.type == TypeKind::memberExp || memberExp.type == pointerExp) && !memberExp.addedThis)
6374          {
6375          }
6376          else if(!pointer)
6377          {
6378             editBox.GetSelPos(&l1, &y1, &x1, &l2, &y2, &x2, false);
6379             {
6380                EditBoxStream f { editBox = editBox };
6381                char ch = 0;
6382
6383                updatingCode = true;
6384
6385                editBox.SetSelPos(l1, y1, x1, l2, y2, x2);
6386
6387                f.Getc(&ch);
6388                if(ch == '}' || ch == ',' || ch == ')')
6389                {
6390                   f.Seek(-1, current);
6391                   ch = ' ';
6392                }
6393                if(isspace(ch))
6394                {
6395                   for(;;)
6396                   {
6397                      char ch;
6398                      if(!f.Seek(-1, current))
6399                         break;
6400                      f.Getc(&ch);
6401                      if(!isspace(ch)) break;
6402                      f.Seek(-1, current);
6403                   }
6404                }
6405                else
6406                   f.Seek(-1, current);
6407
6408                editBox.GetSelPos(&l1, &y1, &x1, &l2, &y2, &x2, false);
6409
6410                lineNum = editBox.lineNumber + 1;
6411                charPos = editBox.charPos + 1;
6412                delete f;
6413                updatingCode = false;
6414             }
6415
6416             realIdentifier = FindCtxTree(ast, lineNum, charPos);
6417             exp = ctxInsideExp;
6418          }
6419       }
6420
6421       editBox.GetSelPos(&l1, &y1, &x1, &l2, &y2, &x2, false);
6422       lineNum = editBox.lineNumber + 1;
6423       charPos = editBox.charPos/* + 1*/;
6424
6425       {
6426          int rowCount;
6427          char tempString[1024];
6428          char * string = null;
6429          CodePosition idStart, idEnd;
6430
6431          if(membersListShown)
6432          {
6433             char * buffer = membersLine.text;
6434             int c;
6435             bool firstChar = true;
6436             int len = 0;
6437             string = tempString;
6438
6439             for(c = membersLoc.start.charPos; c<membersLoc.end.charPos; c++)
6440             {
6441                bool isSpace = (buffer[c] == ' ' || buffer[c] == '\t');
6442                if(!isSpace) firstChar = false;
6443                if(!firstChar)
6444                   string[len++] = buffer[c];
6445             }
6446             string[len] = 0;
6447          }
6448          else //if(realIdentifier)//if(id)
6449          {
6450             /*
6451             char * buffer = id.string;
6452             int c;
6453             bool firstChar = true;
6454             int len = 0;
6455             string = tempString;
6456             for(c = 0; c<= charPos - id.loc.start.charPos; c++)
6457             {
6458                bool isSpace = (buffer[c] == ' ' || buffer[c] == '\t');
6459                if(!isSpace) firstChar = false;
6460                if(!firstChar)
6461                   string[len++] = buffer[c];
6462             }
6463             string[len] = 0;
6464             */
6465             int x, y;
6466             int len = 0;
6467             EditLine editLine = editBox.line;
6468             bool firstChar = true;
6469             bool done = false;
6470
6471             string = tempString;
6472             for(y = lineNum-1; y >= 0; y--)
6473             {
6474                char * buffer = editLine.text;
6475                int lineCount = editLine.count;
6476                for(x = (y == lineNum-1) ? (Min(charPos, lineCount) - 1 ): lineCount-1; x >= 0; x--)
6477                {
6478                   bool isSpace = (buffer[x] == ' ' || buffer[x] == '\t');
6479                   if(!isSpace)
6480                   {
6481                      if(firstChar)
6482                      {
6483                         idEnd.charPos = x + 2;
6484                         idEnd.line = y + 1;
6485                      }
6486                      firstChar = false;
6487                   }
6488                   // TESTING THIS CODE HERE FOR NOT CONSIDERING bool when doing ctrl-space past it
6489                   else if(firstChar)
6490                   {
6491                      idEnd.charPos = x + 2;
6492                      idEnd.line = y + 1;
6493                      done = true;
6494                      break;
6495                   }
6496                   if(!firstChar)
6497                   {
6498                      if(!isalnum(buffer[x]) && buffer[x] != '_')
6499                      {
6500                         x++;
6501                         done = true;
6502                         break;
6503                      }
6504                      memmove(string+1, string, len++);
6505                      string[0] = buffer[x];
6506                   }
6507                }
6508
6509                //if(done || firstChar)
6510                if(done || !firstChar)
6511                   break;
6512                editLine = editLine.prev;
6513             }
6514             string[len] = 0;
6515             if(!strcmp(string, "case"))
6516             {
6517                idEnd.charPos += 4;
6518                x+=4;
6519                string[0] = '\0';
6520             }
6521             else if(!strcmp(string, "return"))
6522             {
6523                idEnd.charPos += 6;
6524                x+=6;
6525                string[0] = '\0';
6526             }
6527             else if(!strcmp(string, "delete"))
6528             {
6529                idEnd.charPos += 6;
6530                x+=6;
6531                string[0] = '\0';
6532             }
6533             else if(!strcmp(string, "new"))
6534             {
6535                idEnd.charPos += 3;
6536                x+=3;
6537                string[0] = '\0';
6538             }
6539             else if(!strcmp(string, "renew"))
6540             {
6541                idEnd.charPos +=5;
6542                x+=5;
6543                string[0] = '\0';
6544             }
6545             if(x < 0) x = 0;
6546
6547             idStart.charPos = x + 1;
6548             idStart.line = y + 1;
6549          }
6550
6551          if(!membersListShown)
6552          {
6553             membersList.Clear();
6554             if(memberExp && (memberExp.type == ExpressionType::memberExp || memberExp.type == pointerExp) && !memberExp.addedThis)
6555             {
6556                Type type = memberExp.member.exp.expType;
6557                if(pointer == 2 && type)
6558                {
6559                   if(type.kind == pointerType || type.kind == arrayType)
6560                      type = type.type;
6561                   /*else
6562                      type = null;*/
6563                }
6564                ListMembers(type);
6565             }
6566             else if(!pointer)
6567             {
6568                ListSymbols(exp, enumOnly, string, realIdentifier);
6569             }
6570             membersList.Sort(null, 1);
6571          }
6572
6573          if(insideFunction)
6574          {
6575             // Virtual function override
6576             Identifier id = GetDeclId(insideFunction.declarator);
6577             char * string = id ? id.string : null;
6578
6579             Method method = eClass_FindMethod(GetThisClass(), string, this.privateModule);
6580             if(method)
6581             {
6582                if(method.type != virtualMethod || (!insideInstance && method._class == GetThisClass()))
6583                   insideFunction = null;
6584                else
6585                {
6586                   OverrideVirtualFunction(insideFunction, method, GetThisClass(), insideInstance, insideInstance && insideClass);
6587                   didOverride = true;
6588                }
6589             }
6590          }
6591          if(!didOverride) //insideFunction)
6592          {
6593             rowCount = membersList.rowCount;
6594             if(rowCount)
6595             {
6596                DataRow row = string ? membersList.FindSubString(string) : null;
6597                if(row && !membersList.FindSubStringAfter(row, string) && !caretMove)
6598                {
6599                   char * newString = row.string;
6600                   if(!membersListShown)
6601                   {
6602                      membersLoc.start.line = idStart.line-1;
6603                      membersLoc.start.charPos = idStart.charPos-1;
6604                      //membersLoc.end = membersLoc.start;
6605                       membersLoc.end.charPos = idEnd.charPos-1;
6606                       membersLoc.end.line = idEnd.line-1;
6607                      //membersLoc.end.charPos = idStart.charPos + strlen(string)-1; //end.charPos-1;
6608                      //membersLoc.end.charPos = idStart.charPos + strlen(string)-1; //end.charPos-1;
6609                      membersLine = line;
6610                   }
6611                   else
6612                   {
6613                      membersList.Destroy(0);
6614                      membersListShown = false;
6615                   }
6616
6617                   editBox.GoToPosition(membersLine, membersLoc.start.line, membersLoc.start.charPos);
6618                   editBox.Delete(
6619                      line, membersLoc.start.line, membersLoc.start.charPos,
6620                      line, membersLoc.end.line, membersLoc.end.charPos);
6621                   editBox.PutS(newString);
6622                }
6623                else
6624                {
6625                   if(!row)
6626                   {
6627                      row = membersList.FindSubStringi(string);
6628                      if(row)
6629                         membersList.currentRow = row;
6630                      membersList.currentRow.selected = false;
6631                   }
6632                   else
6633                      membersList.currentRow = row;
6634
6635                   if(!membersListShown)
6636                   {
6637                      Point caret;
6638
6639                      // TESTING THESE ADDITIONS TO THE IF SO THAT CARET ISNT MOVED IF NOT ON TOP OF A WORD
6640                      if(string && string[0] && lineNum == idStart.line && charPos >= idStart.charPos-1 && charPos <= idEnd.charPos-1)
6641                         editBox.SetSelPos(l1, y1, idStart.charPos-1, l2, y2, idStart.charPos-1);
6642                      editBox.GetCaretPosition(caret);
6643                      editBox.SetSelPos(l1, y1, x1, l2, y2, x2);
6644
6645                      membersList.master = this;
6646
6647                      caret.y += editBox.GetCaretSize();
6648                      caret.x -= 20;
6649                      membersList.Create();
6650
6651                      {
6652                         int x = caret.x + editBox.absPosition.x - app.desktop.absPosition.x - editBox.scroll.x;
6653                         int y = caret.y + editBox.absPosition.y - app.desktop.absPosition.y - editBox.scroll.y;
6654                         Window parent = membersList.parent;
6655
6656                         if(!paramsAbove && (paramsShown || y + membersList.size.h > parent.clientSize.h))
6657                         {
6658                            y -= editBox.GetCaretSize() + membersList.size.h;
6659                            membersAbove = true;
6660                         }
6661                         else
6662                            membersAbove = false;
6663
6664                         membersList.position = { x, y };
6665                      }
6666
6667                      membersLine = l1;
6668                      membersLoc.start.line = lineNum - 1;
6669
6670                      if(string && string[0])
6671                      {
6672                         membersLoc.start.charPos = idStart.charPos-1;
6673                         membersLoc.end = membersLoc.start;
6674                         //membersLoc.end.charPos = id.loc.end.charPos-1;
6675                         membersLoc.end.charPos = idStart.charPos + strlen(string)-1; //end.charPos-1;
6676                      }
6677                      else
6678                      {
6679                         membersLoc.start.charPos = charPos;
6680                         membersLoc.end = membersLoc.start;
6681                         membersLoc.end.charPos = charPos;
6682                      }
6683                      membersListShown = true;
6684
6685                      // Hack to keep caret shown
6686                      editBox.GetCaretPosition(caret);
6687                      editBox.SetCaret(caret.x, caret.y, editBox.GetCaretSize());
6688                   }
6689                   if(row)
6690                      membersList.SetScrollPosition(0, row.index * membersList.rowHeight);
6691                }
6692             }
6693          }
6694       }
6695
6696       SetCurrentContext(globalContext);
6697       SetThisClass(null);
6698
6699       return !didOverride;
6700    }
6701
6702    void InvokeParameters(bool exact, bool reposition, bool caretMove)
6703    {
6704       EditLine line = editBox.line;
6705       char * text = line.text;
6706       int lineNum, charPos;
6707       Expression exp = null;
6708       EditLine l1, l2;
6709       int x1,y1, x2,y2;
6710
6711       if(!parsing) return;
6712
6713       charPos = editBox.charPos + 1;
6714       EnsureUpToDate();
6715
6716       editBox.GetSelPos(&l1, &y1, &x1, &l2, &y2, &x2, false);
6717       {
6718          EditBoxStream f { editBox = editBox };
6719          char ch;
6720
6721          updatingCode = true;
6722          editBox.SetSelPos(l1, y1, x1, l2, y2, x2);
6723
6724          f.Getc(&ch);
6725          if(ch == '}' || ch == ',' || ch == ')')
6726          {
6727             f.Seek(-1, current);
6728             ch = ' ';
6729          }
6730          if(isspace(ch))
6731          {
6732             for(;;)
6733             {
6734                char ch;
6735                if(!f.Seek(-1, current))
6736                   break;
6737                f.Getc(&ch);
6738                if(!isspace(ch)) break;
6739                f.Seek(-1, current);
6740             }
6741          }
6742          else
6743             f.Seek(-1, current);
6744
6745          editBox.GetSelPos(&l1, &y1, &x1, &l2, &y2, &x2, false);
6746
6747          lineNum = editBox.lineNumber + 1;
6748          charPos = editBox.charPos + 1;
6749          delete f;
6750          updatingCode = false;
6751       }
6752
6753       charPos = Min(charPos, l1.count + 1);
6754       if(!caretMove)
6755          FindParamsTree(ast, lineNum, charPos);
6756
6757       // Not sure about this == ExpCall... paramsInsideExp doesn't seem to necessarily be a ExpCall
6758       if(exact && ((::functionType && paramsInsideExp.type == callExp && paramsInsideExp.call.exp.loc.end.charPos != charPos-1) /*|| instanceType*/))
6759       {
6760          ::functionType = null;
6761          ::instanceType = null;
6762       }
6763
6764       //if((::functionType || ::instanceType) && (!paramsShown || insideExp != functionExp || ::paramsID != this.paramsID))
6765       if((::functionType || ::instanceType) && (!paramsShown || true /*paramsInsideExp.destType != functionExp.destType */|| ::paramsID != this.paramsID))
6766       {
6767
6768          int x, y;
6769          Window parent = paramsList.parent;
6770
6771          if(this.functionType != ::functionType || this.instanceType != ::instanceType)
6772             reposition = false;
6773
6774          if(!this.paramsShown || reposition || paramsInsideExp != functionExp || ::instanceType) // Added instanceType here, otherwise instance popups never reposition...
6775                                                                                                           // ( Dummy exp: always ends up with same memory)
6776          {
6777             editBox.GetSelPos(&l1, &y1, &x1, &l2, &y2, &x2, false);
6778             editBox.GetCaretPosition(paramsPosition);
6779             this.paramsPosition.y += editBox.GetCaretSize();
6780          }
6781
6782          FreeType(this.functionType);
6783          FreeType(this.instanceType);
6784
6785          this.functionType = ::functionType;
6786          this.instanceType = ::instanceType;
6787
6788          if(this.functionType) this.functionType.refCount++;
6789          if(this.instanceType) this.instanceType.refCount++;
6790
6791          this.paramsID = ::paramsID;
6792          functionExp = paramsInsideExp;
6793
6794          paramsList.master = this;
6795
6796          paramsList.Create();
6797
6798          x = paramsPosition.x + editBox.absPosition.x - app.desktop.absPosition.x - editBox.scroll.x;
6799          y = paramsPosition.y + editBox.absPosition.y - app.desktop.absPosition.y - editBox.scroll.y;
6800
6801          if(!this.membersAbove && ( this.membersListShown || y + paramsList.size.h > parent.clientSize.h) )
6802          {
6803             y -= editBox.GetCaretSize() + paramsList.clientSize.h;
6804             paramsAbove = true;
6805          }
6806          else
6807             paramsAbove = false;
6808          if(x + paramsList.size.w > parent.clientSize.w)
6809          {
6810             x = parent.clientSize.w - paramsList.size.w;
6811             if(x < 0) x = 0;
6812          }
6813
6814          paramsList.position = { x, y };
6815
6816          // Hack to keep caret shown
6817          {
6818             Point caret;
6819             editBox.GetCaretPosition(caret);
6820             editBox.SetCaret(caret.x, caret.y, editBox.GetCaretSize());
6821          }
6822
6823          this.paramsShown = true;
6824       }
6825       else if((!::functionType && !::instanceType) || reposition)
6826       {
6827          paramsList.Destroy(0);
6828          paramsShown = false;
6829
6830          FreeType(this.functionType);
6831          FreeType(this.instanceType);
6832          this.functionType = null;
6833          this.instanceType = null;
6834          this.paramsID = -1;
6835       }
6836
6837       SetCurrentContext(globalContext);
6838       SetThisClass(null);
6839    }
6840
6841    bool ViewDesigner()
6842    {
6843       if(designer)
6844       {
6845          designer.visible = true;
6846          designer.Activate();
6847       }
6848       return true;
6849    }
6850 };
6851
6852 CodeEditor NewCodeEditor(Window parent, WindowState state, bool modified)
6853 {
6854    CodeEditor document { state = state, parent = parent, modifiedDocument = modified };
6855    document.Create();
6856    return document;
6857 }
6858
6859 static int nofdigits(int v)
6860 {
6861    if(v == MININT) return 10 + 1;
6862    if(v < 0) return nofdigits(-v) + 1;
6863    if(v >= 10000)
6864    {
6865       if(v >= 10000000)
6866       {
6867          if(v >= 100000000)
6868          {
6869             if(v >= 1000000000)
6870                return 10;
6871             return 9;
6872          }
6873          return 8;
6874       }
6875       if(v >= 100000)
6876       {
6877          if(v >= 1000000)
6878             return 7;
6879          return 6;
6880       }
6881       return 5;
6882    }
6883    if(v >= 100)
6884    {
6885       if(v >= 1000)
6886          return 4;
6887       return 3;
6888    }
6889    if(v >= 10)
6890       return 2;
6891    return 1;
6892 }