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