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