ide/CodeEditor/autocomplete: Fixed potential crash
[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, (oldLine-1) * spaceH - editBox.scroll.y, editBox.anchor.left.distance, oldLine*spaceH-1 - editBox.scroll.y };
916             Update(box);
917          }
918          {
919             Box box { 0, (line-1) * spaceH - editBox.scroll.y, editBox.anchor.left.distance, 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 && type.kind == 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 && type.kind == functionType)
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((bool)(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          SetDefaultNameSpace(project.GetDefaultNameSpace(config));
2925          ide.SetPath(true, compiler, config, bitDepth);
2926
2927          delete objDir;
2928          delete compiler;
2929          // SetIncludeDirs(ide.projectView.project.config.includeDirs);
2930          // SetSysIncludeDirs(ide.ideSettings.systemDirs[includes]);
2931       }
2932       else
2933       {
2934          switch(__runtimePlatform)
2935          {
2936             case win32: SetSymbolsDir("obj/debug.win32"); break;
2937             case tux:   SetSymbolsDir("obj/debug.linux"); break;
2938             case apple: SetSymbolsDir("obj/debug.apple"); break;
2939          }
2940          SetIncludeDirs(null);
2941          SetSysIncludeDirs(null);
2942          SetDefaultNameSpace(null);
2943       }
2944
2945       {
2946          if(ide.projectView && ide.projectView.IsModuleInProject(this.fileName))
2947          {
2948             // TODO FIX for configless project
2949             if(ide.project.config && ide.project.config.options && ide.project.config.options.preprocessorDefinitions)
2950             {
2951                for(item : ide.project.config.options.preprocessorDefinitions)
2952                {
2953                   if(!strcmp(item, "BUILDING_ECERE_COM"))
2954                   {
2955                      SetBuildingEcereCom(true);
2956                      break;
2957                   }
2958                }
2959             }
2960          }
2961
2962          if(!(strcmpi(mainModuleName, "instance.ec") && strcmpi(mainModuleName, "BinaryTree.ec") &&
2963             strcmpi(mainModuleName, "dataTypes.ec") && strcmpi(mainModuleName, "OldList.ec") &&
2964             strcmpi(mainModuleName, "String.ec") && strcmpi(mainModuleName, "BTNode.ec") &&
2965             strcmpi(mainModuleName, "Array.ec") && strcmpi(mainModuleName, "AVLTree.ec") &&
2966             strcmpi(mainModuleName, "BuiltInContainer.ec") && strcmpi(mainModuleName, "Container.ec") &&
2967             strcmpi(mainModuleName, "CustomAVLTree.ec") && strcmpi(mainModuleName, "LinkList.ec") &&
2968             strcmpi(mainModuleName, "List.ec") && strcmpi(mainModuleName, "Map.ec") &&
2969             strcmpi(mainModuleName, "Mutex.ec")))
2970          {
2971             SetBuildingEcereComModule(true);
2972          }
2973
2974          // Predeclare all classes
2975          {
2976             char symFile[MAX_FILENAME];
2977             char symLocation[MAX_LOCATION];
2978             ImportedModule module, next;
2979
2980             GetLastDirectory(fileName, symFile);
2981             ChangeExtension(symFile, "sym", symFile);
2982
2983             strcpy(symLocation, GetSymbolsDir());
2984             PathCat(symLocation, symFile);
2985
2986             // if(!GetEcereImported() && !GetBuildingEcereCom())
2987             if(!strcmp(extension, "ec") || !strcmp(extension, "eh"))
2988             {
2989 #ifdef _TIMINGS
2990                startTime = GetTime();
2991 #endif
2992                eModule_LoadStrict(privateModule, "ecereCOM", privateAccess);
2993 #ifdef _TIMINGS
2994                printf("Loading ecereCOM took %.3f seconds\n", GetTime() - startTime);
2995 #endif
2996             }
2997
2998 #ifdef _TIMINGS
2999             startTime = GetTime();
3000 #endif
3001             // LoadSymbols(symLocation, normalImport, true);
3002             LoadSymbols(symLocation, preDeclImport, false);
3003 #ifdef _TIMINGS
3004             printf("Loading symbols took %.3f seconds\n", GetTime() - startTime);
3005 #endif
3006
3007             for(module = defines.first; module; module = next)
3008             {
3009                next = module.next;
3010                if(module.type == moduleDefinition && strcmpi(module.name, mainModuleName))
3011                {
3012                   delete module.name;
3013                   defines.Delete(module);
3014                }
3015             }
3016          }
3017       }
3018       if(!strcmp(extension, "ec") || !strcmp(extension, "eh"))
3019       {
3020          SetDefaultDeclMode(privateAccess);
3021          SetDeclMode(privateAccess);
3022       }
3023       else
3024       {
3025          SetDefaultDeclMode(defaultAccess);
3026          SetDeclMode(defaultAccess);
3027       }
3028
3029       StripExtension(mainModuleName);
3030       module = ImportedModule { name = CopyString(mainModuleName), type = moduleDefinition };
3031       defines.AddName(module);
3032
3033    #ifdef _DEBUG
3034       // SetYydebug(true);
3035    #endif
3036       resetScanner();
3037
3038 #ifdef _TIMINGS
3039       startTime = GetTime();
3040       startFindClass = checkTypeTotalTime;
3041 #endif
3042       ParseEc();
3043 #ifdef _TIMINGS
3044       printf("ParseEc took %.3f seconds, out of which %.3f seconds were in CheckType\n", GetTime() - startTime, checkTypeTotalTime - startFindClass);
3045 #endif
3046       CheckDataRedefinitions();
3047       SetYydebug(false);
3048
3049       SetIncludeDirs(null);
3050       SetSysIncludeDirs(null);
3051
3052       delete editFile;
3053       fileInput = null;
3054       SetFileInput(null);
3055
3056       if(GetAST())
3057       {
3058          ast = GetAST();
3059
3060 #ifdef _TIMINGS
3061          startTime = GetTime();
3062 #endif
3063          PrePreProcessClassDefinitions();
3064          ComputeModuleClasses(privateModule);
3065          PreProcessClassDefinitions();
3066          ProcessClassDefinitions();
3067 #ifdef _TIMINGS
3068          printf("Initial Passes took %.3f seconds\n", GetTime() - startTime);
3069          startTime = GetTime();
3070 #endif
3071
3072          ComputeDataTypes();
3073 #ifdef _TIMINGS
3074          printf("ComputeDataTypes took %.3f seconds\n", GetTime() - startTime);
3075          startTime = GetTime();
3076 #endif
3077          ProcessInstantiations();
3078 #ifdef _TIMINGS
3079          printf("ProcessInstantiations took %.3f seconds\n", GetTime() - startTime);
3080 #endif
3081
3082          if(!strcmp(extension, "ec") || !strcmp(extension, "eh"))
3083          {
3084             Class windowClass = eSystem_FindClass(this.privateModule, "ecere::gui::Window");
3085             if(!windowClass || windowClass.internalDecl)
3086             {
3087 #ifdef _TIMINGS
3088                startTime = GetTime();
3089 #endif
3090                // *** COMMENTED THIS OUT DUE TO ecereCOM issues
3091                // eModule_Load(this.privateModule.application.allModules.first ? this.privateModule.application.allModules.first : this.privateModule, "ecere", privateAccess);
3092                eModule_Load(this.privateModule, "ecere", privateAccess);
3093 #ifdef _TIMINGS
3094                printf("Loading ecere.dll took %.3f seconds\n", GetTime() - startTime);
3095 #endif
3096             }
3097             windowClass = eSystem_FindClass(this.privateModule, "ecere::gui::Window");
3098
3099             if(windowClass && windowClass.data)
3100                ApplySkin(windowClass, app.currentSkin.name, null);
3101          }
3102
3103 #ifdef _TIMINGS
3104          startTime = GetTime();
3105 #endif
3106          for(external = ast->first; external; external = external.next)
3107          {
3108             if(external.type == classExternal)
3109             {
3110                ClassDefinition _class = external._class;
3111                if(_class.baseSpecs && _class.baseSpecs->first && ((Specifier)_class.baseSpecs->first).type == nameSpecifier ) // classSpecifier
3112                {
3113                   Class regClass = eSystem_FindClass(this.privateModule, ((Specifier)_class.baseSpecs->first).name);
3114                   if(regClass)
3115                   {
3116                      if(eClass_GetDesigner(regClass) && !GetBuildingEcereComModule())
3117                      {
3118                         Instance instance = eInstance_New(regClass);
3119                         ObjectInfo classObject
3120                         {
3121                            name = CopyString(_class._class.name);
3122                            instance = instance;
3123                            classDefinition = _class;
3124                            oClass = classObject;
3125                         };
3126                         classes.Add(classObject);
3127
3128                         incref instance;
3129
3130                         // Moved this at bottom so that the file dialog doesn't show up in eCom
3131                         designer.CreateObject(instance, classObject, true, null);
3132                         sheet.AddObject(classObject, classObject.name ? classObject.name : _class._class.name, typeClass, false);
3133
3134                         if(_class.definitions)
3135                         {
3136                            ClassDef def;
3137                            ObjectInfo object;
3138                            for(def = _class.definitions->first; def; def = def.next)
3139                            {
3140                               switch(def.type)
3141                               {
3142                                  case defaultPropertiesClassDef:
3143                                  {
3144                                     MemberInit propDef;
3145                                     for(propDef = def.defProperties->first; propDef; propDef = propDef.next)
3146                                     {
3147                                        Identifier id = propDef.identifiers->first;
3148                                        if(id)
3149                                        {
3150                                           Property prop = eClass_FindProperty(regClass, id.string, this.privateModule);
3151                                           if(prop)
3152                                           {
3153                                              Class propertyClass = prop.dataTypeClass;
3154                                              if(!propertyClass)
3155                                                 propertyClass = prop.dataTypeClass = eSystem_FindClass(this.privateModule, prop.dataTypeString);
3156                                              if(prop.compiled && prop.Set && prop.Get && propertyClass && propDef.initializer && propDef.initializer.type == expInitializer && propDef.initializer.exp)
3157                                              {
3158                                                 Expression computed;
3159                                                 bool variable = true;
3160
3161                                                 FreeType(propDef.initializer.exp.destType);
3162                                                 propDef.initializer.exp.destType = MkClassType(propertyClass.name);
3163                                                 ProcessExpressionType(propDef.initializer.exp);
3164
3165                                                 computed = CopyExpression(propDef.initializer.exp);
3166                                                 ComputeExpression(computed);
3167                                                 if(computed.isConstant)
3168                                                 {
3169                                                    switch(computed.type)
3170                                                    {
3171                                                       case stringExp:
3172                                                          if(propertyClass.dataTypeString && strstr(propertyClass.dataTypeString, "char *"))
3173                                                          {
3174                                                             String temp = new char[strlen(computed.string)+1];
3175                                                             ReadString(temp, computed.string);
3176                                                             ((void (*)(void *, void *))(void *)prop.Set)(instance, temp);
3177                                                             delete temp;
3178
3179                                                             if(!propDef.initializer.exp.intlString)
3180                                                             {
3181                                                                Map<String, bool> i18nStrings = classObject.i18nStrings;
3182                                                                if(!i18nStrings)
3183                                                                   classObject.i18nStrings = i18nStrings = { };
3184                                                                i18nStrings[prop.name] = false;
3185                                                             }
3186                                                             variable = false;
3187                                                          }
3188                                                          break;
3189                                                       case instanceExp:
3190                                                          if((propertyClass.type == structClass || propertyClass.type == noHeadClass || propertyClass.type == normalClass) && !id.next)
3191                                                          {
3192                                                             if(prop.Set)
3193                                                             {
3194                                                                if(computed.instance._class && computed.instance._class.symbol &&
3195                                                                   computed.instance._class.symbol.registered &&
3196                                                                   eClass_IsDerived(computed.instance._class.symbol.registered, propertyClass))
3197                                                                {
3198                                                                   ((void (*)(void *, void *))(void *)prop.Set)(instance, computed.instance.data);
3199
3200                                                                   // This was saved in the control and shouldn't be freed by FreeExpression...
3201                                                                   // (Not doing this anymore, incrementing refCount in pass15 instead)
3202                                                                   /*if(propertyClass.type == normalClass)
3203                                                                      computed.instance.data = null;*/
3204                                                                }
3205                                                             }
3206                                                             variable = false;
3207                                                          }
3208                                                          break;
3209                                                       case constantExp:
3210                                                       {
3211                                                          Operand value = GetOperand(computed);
3212                                                          DataValue valueData;
3213                                                          valueData.i64 = value.i64;
3214                                                          SetProperty(prop, instance, valueData);
3215                                                          variable = false;
3216                                                          break;
3217                                                       }
3218                                                    }
3219                                                 }
3220                                                 if(variable)
3221                                                    propDef.variable = true;
3222                                                 FreeExpression(computed);
3223                                              }
3224                                           }
3225                                           else
3226                                           {
3227                                              Method method = eClass_FindMethod(regClass, id.string, this.privateModule);
3228                                              if(method && method.type == virtualMethod && propDef.initializer && propDef.initializer.type == expInitializer &&
3229                                                 propDef.initializer.exp && propDef.initializer.exp.type == identifierExp)
3230                                              {
3231                                                 ClassDef def;
3232                                                 // Maintain a list in FunctionDefinition of who is attached to it
3233                                                 for(def = _class.definitions->first; def; def = def.next)
3234                                                 {
3235                                                    if(def.type == functionClassDef)
3236                                                    {
3237                                                       ClassFunction function = def.function;
3238                                                       if(!strcmp(function.declarator.symbol.string, propDef.initializer.exp.identifier.string))
3239                                                       {
3240                                                          function.attached.Add(OldLink { data = method });
3241                                                       }
3242                                                    }
3243                                                 }
3244                                              }
3245                                           }
3246                                        }
3247                                     }
3248                                     break;
3249                                  }
3250                                  case declarationClassDef:
3251                                  {
3252                                     Declaration decl = def.decl;
3253                                     switch(decl.type)
3254                                     {
3255                                        case instDeclaration:
3256                                        {
3257                                           Instantiation inst = decl.inst;
3258                                           Class instClass = eSystem_FindClass(this.privateModule, inst._class.name);
3259                                           if(instClass && eClass_GetDesigner(instClass))
3260                                           {
3261                                              Instance control = eInstance_New(instClass);
3262                                              incref control;
3263
3264                                              object = ObjectInfo
3265                                              {
3266                                                 oClass = classObject;
3267                                                 instance = control;
3268                                                 instCode = inst;
3269                                              };
3270                                              classObject.instances.Add(object);
3271                                              if(inst.exp)
3272                                                 // TOCHECK: Why is this needed now?
3273                                                 object.name = CopyString((inst.exp.type == memberExp) ? inst.exp.member.member.string : inst.exp.identifier.string);
3274                                              def.object = object;
3275
3276                                              // if(object.name) { symbol = eList_Add(&curContext.symbols, sizeof(Symbol)); symbol.string = object.name; symbol.type = MkClassType(instClass.name); }
3277
3278                                              designer.CreateObject(control, object, false, classObject.instance);
3279                                              sheet.AddObject(object, object.name ? object.name : inst._class.name, typeData, false);
3280                                           }
3281                                           break;
3282                                        }
3283                                     }
3284                                     break;
3285                                  }
3286                               }
3287                            }
3288
3289                            // Second pass, process instantiation members
3290                            object = null;
3291                            for(def = _class.definitions->first; def; def = def.next)
3292                            {
3293                               switch(def.type)
3294                               {
3295                                  case declarationClassDef:
3296                                  {
3297                                     Declaration decl = def.decl;
3298                                     switch(decl.type)
3299                                     {
3300                                        case instDeclaration:
3301                                        {
3302                                           Instantiation inst = decl.inst;
3303                                           Class instClass = eSystem_FindClass(this.privateModule, inst._class.name);
3304                                           if(instClass && eClass_GetDesigner(instClass))
3305                                           {
3306                                              Instance control;
3307                                              object = object ? object.next : classObject.instances.first;
3308                                              control = object.instance;
3309
3310                                              if(inst.members)
3311                                              {
3312                                                 MembersInit members;
3313                                                 for(members = inst.members->first; members; members = members.next)
3314                                                 {
3315                                                    switch(members.type)
3316                                                    {
3317                                                       case dataMembersInit:
3318                                                       {
3319                                                          if(members.dataMembers)
3320                                                          {
3321                                                             MemberInit member;
3322                                                             DataMember curMember = null;
3323                                                             Class curClass = null;
3324                                                             DataMember subMemberStack[256];
3325                                                             int subMemberStackPos = 0;
3326
3327                                                             for(member = members.dataMembers->first; member; member = member.next)
3328                                                             {
3329                                                                bool found = false;
3330                                                                Identifier ident = member.identifiers ? member.identifiers->first : null;
3331                                                                if(ident)
3332                                                                {
3333                                                                   DataMember _subMemberStack[256];
3334                                                                   int _subMemberStackPos = 0;
3335                                                                   DataMember thisMember = (DataMember)eClass_FindDataMember(instClass, ident.string, privateModule, _subMemberStack, &_subMemberStackPos);
3336
3337                                                                   if(!thisMember)
3338                                                                   {
3339                                                                      thisMember = (DataMember)eClass_FindProperty(instClass, ident.string, privateModule);
3340                                                                   }
3341                                                                   if(thisMember && thisMember.memberAccess == publicAccess)
3342                                                                   {
3343                                                                      curMember = thisMember;
3344                                                                      curClass = curMember._class;
3345                                                                      memcpy(subMemberStack, _subMemberStack, sizeof(DataMember) * _subMemberStackPos);
3346                                                                      subMemberStackPos = _subMemberStackPos;
3347                                                                      found = true;
3348                                                                   }
3349                                                                }
3350                                                                else
3351                                                                {
3352                                                                   eClass_FindNextMember(instClass, &curClass, (DataMember *)&curMember, subMemberStack, &subMemberStackPos);
3353                                                                   if(curMember) found = true;
3354                                                                }
3355                                                                if(found && curMember.isProperty)
3356                                                                {
3357                                                                   Property prop = (Property) curMember;
3358                                                                   Class propertyClass = prop.dataTypeClass;
3359                                                                   bool variable = false;
3360                                                                   if(!propertyClass)
3361                                                                      propertyClass = prop.dataTypeClass = eSystem_FindClass(this.privateModule, prop.dataTypeString);
3362
3363                                                                   if(prop.compiled && prop.Set && prop.Get && propertyClass && member.initializer && member.initializer.type == expInitializer && member.initializer.exp)
3364                                                                   {
3365                                                                      FreeType(member.initializer.exp.destType);
3366                                                                      member.initializer.exp.destType = MkClassType(propertyClass.name);
3367                                                                      if(propertyClass)
3368                                                                      {
3369                                                                         Expression computed;
3370
3371                                                                         ProcessExpressionType(member.initializer.exp);
3372
3373                                                                         computed = CopyExpression(member.initializer.exp);
3374                                                                         if(computed)
3375                                                                         {
3376                                                                            bool isClass = propertyClass.type == structClass || propertyClass.type == normalClass || propertyClass.type == noHeadClass;
3377                                                                            {
3378 #ifdef _DEBUG
3379                                                                               /*char debugExpString[4096];
3380                                                                               debugExpString[0] = '\0';
3381                                                                               PrintExpression(member.initializer.exp, debugExpString);*/
3382 #endif
3383                                                                               ComputeExpression(computed);
3384
3385                                                                               switch(computed.type)
3386                                                                               {
3387                                                                                  case instanceExp:
3388                                                                                     if(isClass && computed.isConstant && computed.instance.data)
3389                                                                                     {
3390                                                                                        if(computed.instance._class && computed.instance._class.symbol &&
3391                                                                                           computed.instance._class.symbol.registered &&
3392                                                                                           eClass_IsDerived(computed.instance._class.symbol.registered, propertyClass))
3393                                                                                        {
3394                                                                                           ((void (*)(void *, void *))(void *)prop.Set)(control, computed.instance.data);
3395
3396                                                                                           // This was saved in the control and shouldn't be freed by FreeExpression...
3397                                                                                           // (Not doing this anymore, incrementing refCount in pass15 instead)
3398                                                                                           /*if(propertyClass.type == normalClass)
3399                                                                                              computed.instance.data = null;*/
3400                                                                                        }
3401                                                                                        variable = false;
3402                                                                                     }
3403                                                                                     break;
3404                                                                                  case identifierExp:
3405                                                                                     if(isClass && eClass_GetDesigner(propertyClass))
3406                                                                                     //if(prop.Set)
3407                                                                                     {
3408                                                                                        char * name = computed.identifier.string;
3409                                                                                        if(!strcmp(name, "this"))
3410                                                                                        {
3411                                                                                           if(prop.Set)
3412                                                                                              ((void (*)(void *, void *))(void *)prop.Set)(control, instance);
3413                                                                                           variable = false;
3414                                                                                        }
3415                                                                                        else
3416                                                                                        {
3417                                                                                           ObjectInfo check;
3418                                                                                           for(check = classObject.instances.first; check; check = check.next)
3419                                                                                              if(check.name && !strcmp(name, check.name))
3420                                                                                              {
3421                                                                                                 if(prop.Set)
3422                                                                                                    ((void (*)(void *, void *))(void *)prop.Set)(control, check.instance);
3423                                                                                                 variable = false;
3424                                                                                                 break;
3425                                                                                              }
3426                                                                                        }
3427                                                                                     }
3428                                                                                     break;
3429                                                                                  case memberExp:
3430                                                                                     if(isClass)
3431                                                                                     {
3432                                                                                        if(computed.member.exp.type == identifierExp)
3433                                                                                        {
3434                                                                                           char * name = computed.member.exp.identifier.string;
3435                                                                                           ObjectInfo check;
3436                                                                                           if(!strcmp(name, "this"))
3437                                                                                           {
3438                                                                                              char * name = computed.member.member.string;
3439                                                                                              ObjectInfo check;
3440                                                                                              for(check = classObject.instances.first; check; check = check.next)
3441                                                                                                 if(check.name && !strcmp(name, check.name))
3442                                                                                                 {
3443                                                                                                    if(prop.Set)
3444                                                                                                       ((void (*)(void *, void *))(void *)prop.Set)(control, check.instance);
3445                                                                                                    variable = false;
3446                                                                                                    break;
3447                                                                                                 }
3448                                                                                           }
3449                                                                                           else
3450                                                                                           {
3451                                                                                              for(check = classObject.instances.first; check; check = check.next)
3452                                                                                              {
3453                                                                                                 if(check.name && !strcmp(name, check.name))
3454                                                                                                 {
3455                                                                                                    Property getProperty = eClass_FindProperty(check.instance._class, computed.member.member.string, this.privateModule);
3456                                                                                                    if(getProperty)
3457                                                                                                    {
3458                                                                                                       DataValue value { };
3459                                                                                                       GetProperty(getProperty, check.instance, &value);
3460                                                                                                       SetProperty(prop, control, value);
3461                                                                                                       variable = false;
3462                                                                                                    }
3463                                                                                                    break;
3464                                                                                                 }
3465                                                                                              }
3466                                                                                           }
3467                                                                                        }
3468                                                                                     }
3469                                                                                     break;
3470                                                                                  case stringExp:
3471                                                                                     if(propertyClass.dataTypeString && strstr(propertyClass.dataTypeString, "char *"))
3472                                                                                     {
3473                                                                                        String temp = new char[strlen(computed.string)+1];
3474                                                                                        ReadString(temp, computed.string);
3475                                                                                        ((void (*)(void *, void *))(void *)prop.Set)(control, temp);
3476                                                                                        delete temp;
3477
3478                                                                                        if(!member.initializer.exp.intlString)
3479                                                                                        {
3480                                                                                           Map<String, bool> i18nStrings = object.i18nStrings;
3481                                                                                           if(!i18nStrings)
3482                                                                                              object.i18nStrings = i18nStrings = { };
3483                                                                                           i18nStrings[prop.name] = false;
3484                                                                                        }
3485
3486                                                                                        variable = false;
3487                                                                                     }
3488                                                                                     break;
3489                                                                                  case constantExp:
3490                                                                                     if(!isClass && computed.isConstant)
3491                                                                                     {
3492                                                                                        if(!strcmp(propertyClass.dataTypeString, "float"))
3493                                                                                           ((void (*)(void *, float))(void *)prop.Set)(control, (float)strtod(computed.constant, null));
3494                                                                                        else if(!strcmp(propertyClass.dataTypeString, "double"))
3495                                                                                           ((void (*)(void *, double))(void *)prop.Set)(control, strtod(computed.constant, null));
3496                                                                                        else
3497                                                                                           ((void (*)(void *, int))(void *)prop.Set)(control, strtol(computed.constant, null, 0));
3498                                                                                        variable = false;
3499                                                                                     }
3500                                                                                     break;
3501                                                                               }
3502                                                                            }
3503                                                                         }
3504                                                                         FreeExpression(computed);
3505                                                                      }
3506                                                                   }
3507                                                                   if(variable)
3508                                                                      member.variable = true;
3509                                                                }
3510                                                                else if(ident && member.initializer && member.initializer.type == expInitializer && member.initializer.exp &&
3511                                                                   member.initializer.exp.type == memberExp) // identifierExp
3512                                                                {
3513                                                                   Method method = eClass_FindMethod(instClass, ident.string, this.privateModule);
3514                                                                   if(method && method.type == virtualMethod)
3515                                                                   {
3516                                                                      ClassDef def;
3517                                                                      // Maintain a list in FunctionDefinition of who is attached to it
3518                                                                      for(def = _class.definitions->first; def; def = def.next)
3519                                                                      {
3520                                                                         if(def.type == functionClassDef)
3521                                                                         {
3522                                                                            ClassFunction function = def.function;
3523                                                                            Identifier id = (member.initializer.exp.type == memberExp) ? member.initializer.exp.member.member : member.initializer.exp.identifier;
3524                                                                            if(function.declarator && !strcmp(function.declarator.symbol.string, id.string))
3525                                                                            {
3526                                                                               function.attached.Add(OldLink { data = method });
3527                                                                               // Reference this particular instance?
3528                                                                            }
3529                                                                         }
3530                                                                      }
3531                                                                   }
3532                                                                }
3533                                                                id++;
3534                                                             }
3535                                                          }
3536                                                          break;
3537                                                       }
3538                                                    }
3539                                                 }
3540                                              }
3541
3542                                              designer.PostCreateObject(object.instance, object, false, classObject.instance);
3543                                              break;
3544                                           }
3545                                        }
3546                                        break;
3547                                     }
3548                                  }
3549                               }
3550                            }
3551                         }
3552
3553                         //designer.CreateObject(instance, classObject, true, null);
3554                         //sheet.AddObject(classObject, classObject.name ? classObject.name : _class._class.name, classType, false);
3555
3556                         designer.PostCreateObject(instance, classObject, true, null);
3557
3558                         //instance.state = Hidden;
3559                         //instance.Create();
3560                         //instance.SetState(Normal, true, 0);
3561                      }
3562                   }
3563                }
3564             }
3565          }
3566
3567          SetAST(null);
3568 #ifdef _TIMINGS
3569          printf("Class/Instance Processing took %.3f seconds\n", GetTime() - startTime);
3570 #endif
3571       }
3572
3573       // Restore Selection
3574       if(selectedClassName)
3575       {
3576          ObjectInfo oClass;
3577          for(oClass = classes.first; oClass; oClass = oClass.next)
3578          {
3579             if(!strcmp(oClass.name, selectedClassName))
3580             {
3581                this.oClass = oClass;
3582                break;
3583             }
3584          }
3585          delete selectedClassName;
3586       }
3587       if(this.oClass)
3588       {
3589          if(selectedName)
3590          {
3591             ObjectInfo check;
3592
3593             for(check = this.oClass.instances.first; check; check = check.next)
3594             {
3595                if(check.name && !strcmp(check.name, selectedName))
3596                {
3597                   this.selected = check;
3598                   break;
3599                }
3600             }
3601             if(!check)
3602             {
3603                if(this.oClass.instances.first)
3604                   this.selected = this.oClass.instances.first;
3605                else
3606                   this.selected = this.oClass;
3607             }
3608          }
3609          else if(selectedPos == -1 || !this.oClass.instances.count)
3610             this.selected = this.oClass;
3611          else
3612          {
3613             ObjectInfo check;
3614             int pos = 0;
3615
3616             if(selectedPos > this.oClass.instances.count)
3617                selectedPos = 0;
3618             for(check = this.oClass.instances.first; check; check = check.next)
3619             {
3620                if(selectedPos == pos++)
3621                {
3622                   this.selected = check;
3623                   break;
3624                }
3625             }
3626          }
3627       }
3628       else
3629       {
3630          this.oClass = classes.first;
3631          this.selected = (this.oClass && this.oClass.instances.first) ? this.oClass.instances.first : this.oClass;
3632       }
3633       delete selectedName;
3634       SetSymbolsDir(null);
3635
3636       if(sheet.codeEditor == this)
3637          sheet.SelectObject(selected);
3638       Update(null);
3639
3640       codeModified = false;
3641
3642       // TESTING THIS TO NOT GET EMPTY PARAMETERS
3643       if(paramsShown)
3644       {
3645          InvokeParameters(false, false, false);
3646       }
3647
3648       editBox.SetSelPos(l1, y1, x1, l2, y2, x2);
3649
3650       reentrant = false;
3651
3652       updatingCode--;
3653
3654       ChangeWorkingDir(oldWorkDir);
3655 #ifdef _TIMINGS
3656       printf("Total FindClass time is %.3f seconds, out of which %.3f is in Ignore NS\n\n", findClassTotalTime, findClassIgnoreNSTotalTime);
3657       printf("Total CheckType time is %.3f seconds\n\n", checkTypeTotalTime);
3658       printf("Total MkExternalImport time is %.3f seconds\n\n", externalImportTotalTime);
3659       printf("Total FindSymbol time is %.3f seconds\n\n", findSymbolTotalTime);
3660       // printf("Total Class Members Find time is %.3f seconds\n\n", GetClassFindTime());
3661
3662       printf("Whole ParseCode function took %.3f seconds\n\n", GetTime() - parseCodeStart);
3663 #endif
3664       if(inUseDebug && ide.projectView)
3665          ide.debugger.EvaluateWatches();
3666
3667       delete pathBackup;
3668    }
3669
3670    void UpdateInstanceCodeClass(Class _class, ObjectInfo object, EditBoxStream f, Instance test, bool * prev, bool * lastIsMethod, DataMember * curMember, Class * curClass)
3671    {
3672       Property propIt;
3673       Window control = (Window)object.instance;
3674       ObjectInfo classObject = object.oClass;
3675
3676       if(_class.base && _class.base.type != systemClass) UpdateInstanceCodeClass(_class.base, object, f, test, prev, lastIsMethod, curMember, curClass);
3677
3678       if(!strcmp(_class.name, "DesignerBase")) return;
3679
3680       for(propIt = _class.membersAndProperties.first; propIt; propIt = propIt.next)
3681       {
3682          Property prop = eClass_FindProperty(object.instance._class, propIt.name, privateModule);
3683          if(prop && prop.isProperty && !prop.conversion && eClass_FindProperty(object.instance._class, prop.name, privateModule))
3684          {
3685             if(prop.Set && prop.Get && prop.dataTypeString && strcmp(prop.name, "name") && !Code_IsPropertyDisabled(object, prop.name) &&
3686                prop.compiled && (!prop.IsSet || prop.IsSet(control)))
3687             {
3688                Class dataType = prop.dataTypeClass;
3689                if(!dataType)
3690                   dataType = prop.dataTypeClass = eSystem_FindClass(this.privateModule, prop.dataTypeString);
3691
3692                if(dataType)
3693                {
3694                   if(dataType.type == structClass)
3695                   {
3696                      void * dataForm = new0 byte[dataType.structSize];
3697                      void * dataTest = new0 byte[dataType.structSize];
3698
3699                      ((void (*)(void *, void *))(void *)prop.Get)(control, dataForm);
3700                      ((void (*)(void *, void *))(void *)prop.Get)(test, dataTest);
3701
3702                      if((prop.IsSet && !prop.IsSet(test)) || ((int (*)(void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnCompare])(dataType, dataForm, dataTest))
3703                      {
3704                         char tempString[1024] = "";
3705                         const char * string = "";
3706                         bool needClass = true;
3707                         if(*prev)
3708                            f.Printf(", ");
3709
3710                         ((void (*)(void *, void *))(void *)prop.Set)(test, dataForm);
3711
3712                         string = ((char * (*)(void *, void *, void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnGetString])(dataType, dataForm, tempString, null, &needClass);
3713
3714                         eClass_FindNextMember(_class, curClass, curMember, null, null);
3715                         if(*curMember != (DataMember)prop)
3716                            f.Printf("%s = ", prop.name);
3717
3718                         *curMember = (DataMember)prop;
3719                         *curClass = curMember->_class;
3720
3721                         if(needClass)
3722                            f.Printf("%c %s %c", /*dataType.name, */OpenBracket, string, CloseBracket);
3723                         else
3724                            f.Printf("%s", string);
3725                         *prev = true;
3726                      }
3727
3728                      delete dataForm;
3729                      delete dataTest;
3730                   }
3731                   else if(dataType.type == normalClass || dataType.type == noHeadClass)
3732                   {
3733                      void * dataForm, * dataTest;
3734                      bool isEditBoxContents = false;
3735                      bool freeDataForm = false, freeDataTest = false;
3736
3737                      // Because contents property is broken for mutiline EditBox at the moment
3738                      if(!strcmp(prop.name, "contents") && !strcmp(prop._class.name, "EditBox"))
3739                         isEditBoxContents = true;
3740
3741                      if(isEditBoxContents && ((EditBox)control).multiLine)
3742                      {
3743                         dataForm = ((EditBox)control).multiLineContents;
3744                         freeDataForm = true;
3745                      }
3746                      else
3747                         dataForm = ((void *(*)(void *))(void *)prop.Get)(control);
3748                      if(isEditBoxContents && ((EditBox)test).multiLine)
3749                      {
3750                         dataTest = ((EditBox)test).multiLineContents;
3751                         freeDataTest = true;
3752                      }
3753                      else
3754                         dataTest = ((void *(*)(void *))(void *)prop.Get)(test);
3755
3756                      if((prop.IsSet && !prop.IsSet(test)) || ((int (*)(void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnCompare])(dataType, dataForm, dataTest))
3757                      {
3758                         char tempString[1024] = "";
3759                         const char * string = "";
3760                         if(*prev)
3761                            f.Printf(", ");
3762
3763                         ((void (*)(void *, void *))(void *)prop.Set)(test, dataForm);
3764
3765                         eClass_FindNextMember(_class, curClass, curMember, null, null);
3766                         if(*curMember != (DataMember)prop)
3767                            f.Printf("%s = ", prop.name);
3768                         *curMember = (DataMember)prop;
3769                         *curClass = curMember->_class;
3770
3771                         if(eClass_GetDesigner(dataType))
3772                         {
3773                            if(eClass_IsDerived(classObject.instance._class, dataType) && classObject.instance == dataForm)
3774                            //if(!strcmp(classObject.instance._class.name, dataType.name) && classObject.instance == dataForm)
3775                               f.Printf("this", prop.name);
3776                            else
3777                            {
3778                               //ObjectInfo classObject;
3779                               //for(classObject = classes.first; classObject; classObject = classObject.next)
3780                               {
3781                                  ObjectInfo object;
3782
3783                                  for(object = classObject.instances.first; object; object = object.next)
3784                                  {
3785                                     if(!object.deleted && eClass_IsDerived(object.instance._class, dataType) && object.instance == dataForm && object.name)
3786                                     {
3787                                        f.Printf("%s", object.name);
3788                                        break;
3789                                     }
3790                                  }
3791
3792                                  if(!object)
3793                                  {
3794                                     bool needClass = true;
3795                                     string = ((char * (*)(void *, void *, void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnGetString])(dataType, dataForm, tempString, null, &needClass);
3796                                     f.Printf("%s", string);
3797                                  }
3798                               }
3799                            }
3800                         }
3801                         else
3802                         {
3803                            bool needClass = true;
3804                            string = ((char * (*)(void *, void *, void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnGetString])(dataType, dataForm, tempString, null, &needClass);
3805
3806                            if(!strcmp(dataType.dataTypeString, "char *"))
3807                            {
3808                               Map<String, bool> i18nStrings = object.i18nStrings;
3809                               bool i18n = true;
3810                               if(i18nStrings && i18nStrings.GetAtPosition(prop.name, false, null))
3811                                  i18n = false;
3812
3813                               f.Printf("%s\"", i18n ? "$" : "");
3814                               OutputString(f, string);
3815                               f.Puts("\"");
3816                            }
3817                            else if(needClass)
3818                               f.Printf("%c %s %c", /*dataType.name, */OpenBracket, string, CloseBracket);
3819                            else
3820                               f.Printf("%s", string);
3821                         }
3822                         *prev = true;
3823                         *lastIsMethod = false;
3824                      }
3825
3826                      if(freeDataForm) delete dataForm;
3827                      if(freeDataTest) delete dataTest;
3828                   }
3829                   else
3830                   {
3831                      DataValue dataForm, dataTest;
3832
3833                      GetProperty(prop, control, &dataForm);
3834                      GetProperty(prop, test, &dataTest);
3835
3836                      if((prop.IsSet && !prop.IsSet(test)) || ((int (*)(void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnCompare])(dataType, &dataForm, &dataTest))
3837                      {
3838                         char * string = null;
3839                         char tempString[1024] = "";
3840                         SetProperty(prop, test, dataForm);
3841
3842                         if(dataType.type != bitClass)
3843                         {
3844                            bool needClass = true;
3845
3846                            if(dataType.type == enumClass)
3847                            {
3848                               NamedLink64 value;
3849                               Class enumClass = eSystem_FindClass(privateModule, "enum");
3850                               EnumClassData e = ACCESS_CLASSDATA(dataType, enumClass);
3851                               int64 i64Value = GetI64EnumValue(dataType, dataForm);
3852
3853                               for(value = e.values.first; value; value = value.next)
3854                               {
3855                                  if(value.data == i64Value)
3856                                  {
3857                                     string = value.name;
3858                                     break;
3859                                  }
3860                               }
3861                            }
3862                            else
3863                               string = ((char * (*)(void *, void *, void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnGetString])(dataType, &dataForm, tempString, null, &needClass);
3864
3865                            if(string && string[0])
3866                            {
3867                               if(*prev)
3868                                  f.Printf(", ");
3869
3870                               eClass_FindNextMember(_class, curClass, curMember, null, null);
3871                               if(*curMember != (DataMember)prop)
3872                                  f.Printf("%s = ", prop.name);
3873                               *curMember = (DataMember)prop;
3874                               *curClass = curMember->_class;
3875
3876                               if(!strcmp(dataType.dataTypeString, "float") && strchr(string, '.'))
3877                                  f.Printf("%sf", string);
3878                               else
3879                                  f.Printf("%s", string);
3880                               *prev = true;
3881                            }
3882                         }
3883                         else if(dataType.type == bitClass)
3884                         {
3885                            bool needClass = true;
3886
3887                            if(*prev) f.Printf(", ");
3888
3889                            eClass_FindNextMember(_class, curClass, curMember, null, null);
3890                            if(*curMember != (DataMember)prop)
3891                               f.Printf("%s = ", prop.name);
3892                            *curMember = (DataMember)prop;
3893                            *curClass = curMember->_class;
3894
3895                            string = ((char * (*)(void *, void *, void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnGetString])(dataType, &dataForm.ui, tempString, null, &needClass);
3896                            if(needClass)
3897                               f.Printf("%c %s %c", /*dataType.name, */OpenBracket, string, CloseBracket);
3898                            else
3899                               f.Printf("%s", string);
3900                            *prev = true;
3901                            *lastIsMethod = false;
3902                         }
3903                      }
3904                   }
3905                }
3906             }
3907          }
3908       }
3909    }
3910
3911    int UpdateInstanceCode(EditBoxStream f, int position, Class regClass, ObjectInfo object, bool * firstObject, char ** text, int * textSize, int movedFuncIdLen, int movedFuncIdPos)
3912    {
3913       Instantiation inst = object.instCode;
3914       Window control = (Window)object.instance;
3915       bool prev = false;
3916       bool methodPresent = false;
3917       bool lastIsMethod = true;
3918
3919       if(inst)
3920       {
3921          if(object.deleted)
3922          {
3923             // Instance removed, delete it
3924             DeleteJunkBefore(f, inst.loc.start.pos, &position);
3925
3926             f.DeleteBytes(inst.loc.end.pos - inst.loc.start.pos + 1);
3927             position = inst.loc.end.pos + 1;
3928          }
3929          else
3930          {
3931             bool multiLine = false;
3932
3933             // Change the name
3934             // Check if it's an unnamed instance
3935             if(inst.exp)
3936             {
3937                f.Seek(inst.nameLoc.start.pos - position, current);
3938                f.DeleteBytes(inst.nameLoc.end.pos - inst.nameLoc.start.pos);
3939                position = inst.nameLoc.end.pos;
3940                if(object.name)
3941                   f.Printf(object.name);
3942                else
3943                {
3944                   char ch = 0;
3945                   f.Getc(&ch);
3946                   if(isspace(ch) && ch != '\n')
3947                   {
3948                      f.Seek(-1, current);
3949                      f.DeleteBytes(1);
3950                      position ++;
3951                   }
3952                }
3953             }
3954             else
3955             {
3956                int pos = inst.loc.start.pos; // + strlen(inst._class.name);
3957                char ch;
3958                f.Seek(pos - position, current);
3959                while(f.Getc(&ch))
3960                {
3961                   if(isspace(ch))
3962                   {
3963                      f.Seek(-1, current);
3964                      break;
3965                   }
3966                   pos++;
3967                }
3968
3969                if(object.name)
3970                {
3971                   f.Puts(" ");
3972                   f.Puts(object.name);
3973                }
3974                position = pos;
3975             }
3976
3977             if((this.methodAction == actionAddMethod || this.moveAttached) && this.selected == object)
3978                methodPresent = true;
3979
3980             for(;;)
3981             {
3982                char ch = 0;
3983                if(!f.Getc(&ch))
3984                   break;
3985                position++;
3986                if(ch == OpenBracket)
3987                   break;
3988                if(ch == '\n')
3989                   multiLine = true;
3990             }
3991
3992             // TODO: Simplify this?
3993             if(methodPresent)
3994             {
3995                if(!multiLine)
3996                {
3997                   int count = 0;
3998                   int toDelete = 0;
3999                   //int toAdd = 0;
4000
4001                   f.Seek(-1, current);
4002                   DeleteJunkBefore(f, position, &position);
4003                   f.Puts("\n   ");
4004                   f.Seek(1, current);
4005                   //f.Puts("\n");
4006
4007                   // Fix indentation
4008                   for(;;)
4009                   {
4010                      char ch = 0;
4011                      if(!f.Getc(&ch))
4012                         break;
4013                      position++;
4014                      if(ch == '\n') { toDelete = count; count = 0; }
4015                      else if(isspace(ch)) count++;
4016                      else
4017                      {
4018                         f.Seek(-1, current);
4019                         position--;
4020                         if(count > 6)
4021                         {
4022                            toDelete += count - 6;
4023                            count = 6;
4024                         }
4025                         /*else
4026                            toAdd = 6 - count;*/
4027                         break;
4028                      }
4029                   }
4030                   if(toDelete)
4031                   {
4032                      f.Seek(-toDelete-count, current);
4033                      f.DeleteBytes(toDelete);
4034                      f.Seek(count, current);
4035                   }
4036
4037                   DeleteJunkBefore(f, position, &position);
4038
4039                   // Removed this here as it was adding trailing spaces when adding a method
4040                   /*
4041                   if(toAdd)
4042                   {
4043                      int c;
4044                      for(c = 0; c<toAdd; c++)
4045                         f.Putc(' ');
4046                   }
4047                   */
4048                }
4049             }
4050             else
4051                methodPresent = multiLine;
4052
4053             //if(!prev) -- always false
4054                f.Printf(methodPresent ? "\n      " : " ");
4055          }
4056       }
4057       else
4058       {
4059          // Instance not there, create a brand new one
4060          DeleteJunkBefore(f, position, &position);
4061          f.Printf(*firstObject ? "\n\n" : "\n");
4062          *firstObject = false;
4063
4064          if((this.methodAction == actionAddMethod || this.moveAttached) && this.selected == object)
4065             methodPresent = true;
4066
4067          if(methodPresent)
4068          {
4069             if(object.name)
4070                f.Printf("   %s %s\n   %c\n      ", control._class.name, object.name, OpenBracket);
4071             else
4072                f.Printf("   %s\n   %c\n      ", control._class.name, OpenBracket);
4073          }
4074          else
4075          {
4076             if(object.name)
4077                f.Printf("   %s %s %c ", control._class.name, object.name, OpenBracket);
4078             else
4079                f.Printf("   %s %c ", control._class.name, OpenBracket);
4080          }
4081       }
4082
4083       if(!object.deleted)
4084       {
4085          Instance test = eInstance_New(control._class);
4086          DataMember curMember = null;
4087          Class curClass = null;
4088          incref test;
4089
4090          UpdateInstanceCodeClass(control._class, object, f, test, &prev, &lastIsMethod, &curMember, &curClass);
4091
4092          delete test;
4093
4094          // Attach Method here
4095          if((this.methodAction == actionAttachMethod || this.methodAction == actionReattachMethod) && !this.moveAttached && this.selected == object)
4096          {
4097             if(prev) f.Printf(", ");
4098             f.Printf("%s = %s", this.method.name, function.declarator.symbol.string);
4099             prev = true;
4100          }
4101       }
4102
4103       if(inst && !object.deleted)
4104       {
4105          MembersInit members;
4106          Class instClass = eSystem_FindClass(this.privateModule, inst._class.name);
4107
4108          DeleteJunkBefore(f, position, &position);
4109
4110          // Instance already there, clear out the properties
4111          for(members = inst.members ? inst.members->first : null; members; members = members.next)
4112          {
4113             if(members.type == dataMembersInit)
4114             {
4115                MemberInit member;
4116
4117                if(members.dataMembers)
4118                {
4119                   bool keptMember = false;
4120                   MemberInit lastKept = null;
4121
4122                   for(member = members.dataMembers->first; member; member = member.next)
4123                   {
4124                      Identifier ident = member.identifiers ? member.identifiers->first : null;
4125                      bool deleted = false;
4126
4127                      // For now delete if it's not a method
4128                      if(!member.variable) // && ident)
4129                      {
4130                         if(!ident || !ident.next)
4131                         {
4132                            Property prop = ident ? eClass_FindProperty(instClass, ident.string, this.privateModule) : null;
4133                            if(!ident || prop)
4134                            {
4135                               f.Seek(member.loc.start.pos - position, current);
4136                               f.DeleteBytes(member.loc.end.pos - member.loc.start.pos);
4137                               position = member.loc.end.pos;
4138                               deleted = true;
4139                            }
4140                            else
4141                            {
4142                               Method method = eClass_FindMethod(instClass, ident.string, this.privateModule);
4143                               if(method && method.type == virtualMethod && member.initializer && member.initializer.type == expInitializer && member.initializer.exp &&
4144                                  member.initializer.exp.type == memberExp /*ExpIdentifier*/)
4145                               {
4146                                  if(((this.methodAction == actionDetachMethod || this.methodAction == actionReattachMethod) && this.method == method && this.selected == object) ||
4147                                     (this.methodAction == actionDeleteMethod && !strcmp(function.declarator.symbol.string, member.initializer.exp.identifier.string)))
4148                                  {
4149                                     f.Seek(member.loc.start.pos - position, current);
4150                                     f.DeleteBytes(member.loc.end.pos - member.loc.start.pos);
4151                                     position = member.loc.end.pos;
4152                                     deleted = true;
4153                                  }
4154                               }
4155                            }
4156                         }
4157                      }
4158                      if(!deleted)
4159                      {
4160                         keptMember = true;
4161                         lastKept = member;
4162
4163                         //f.Seek(member.loc.start.pos - position, current);
4164                         //position = member.loc.start.pos;
4165                         DeleteJunkBefore(f, member.loc.start.pos, &position);
4166                         if(prev) f.Printf(", ");
4167                         else if(keptMember) f.Printf(" ");
4168                         prev = false;
4169                      }
4170                   }
4171
4172                   if(!keptMember || !members.next)
4173                   {
4174                      char ch = 0;
4175
4176                      if(keptMember && lastKept != members.dataMembers->last)
4177                      {
4178                         // Delete the comma
4179                         char ch;
4180                         int count = 0;
4181                         f.Seek(-1, current);
4182                         for(;f.Getc(&ch);)
4183                         {
4184                            if(ch == ',')
4185                            {
4186                               count++;
4187                               f.Seek(-1, current);
4188                               break;
4189                            }
4190                            else if(!isspace(ch))
4191                               break;
4192                            f.Seek(-2, current);
4193                            count++;
4194                         }
4195
4196                         if(ch == ',')
4197                            f.DeleteBytes(count);
4198                      }
4199
4200                      f.Seek(members.loc.end.pos - position, current);
4201                      f.Getc(&ch);
4202
4203                      if(ch == ';')
4204                      {
4205                         f.Seek(-1, current);
4206                         f.DeleteBytes(1);
4207                         position = members.loc.end.pos + 1;
4208                      }
4209                      else
4210                      {
4211                         f.Seek(-1, current);
4212                         position = members.loc.end.pos;
4213                      }
4214
4215                      if(keptMember)
4216                      {
4217                         prev = true;
4218                         lastIsMethod = false;
4219                      }
4220                   }
4221                   else
4222                   {
4223                      DeleteJunkBefore(f, position, &position);
4224                      f.Printf(" ");
4225
4226                      if(lastKept != members.dataMembers->last)
4227                      {
4228                         // Delete the comma
4229                         char ch;
4230                         int count = 0;
4231                         f.Seek(-1, current);
4232                         for(;f.Getc(&ch);)
4233                         {
4234                            if(ch == ',')
4235                            {
4236                               count++;
4237                               f.Seek(-1, current);
4238                               break;
4239                            }
4240                            else if(!isspace(ch))
4241                               break;
4242                            f.Seek(-2, current);
4243                            count++;
4244                         }
4245
4246                         if(ch == ',')
4247                            f.DeleteBytes(count);
4248                      }
4249                      else
4250                      {
4251                         f.Seek(members.loc.end.pos - position, current);
4252                         position = members.loc.end.pos;
4253                      }
4254                      /*
4255                      prev = false;
4256                      lastIsMethod = true;
4257                      */
4258                      prev = true;
4259                      lastIsMethod = false;
4260
4261                   }
4262                }
4263                else
4264                {
4265                   f.Seek(members.loc.end.pos - position, current);
4266                   position = members.loc.end.pos;
4267                   prev = false;
4268                   lastIsMethod = true;
4269                }
4270             }
4271             else if(members.type == methodMembersInit)
4272             {
4273                if(this.methodAction == actionDeleteMethod && members.function == function);
4274                else
4275                   methodPresent = true;
4276
4277                // Delete instance method here
4278                if((this.methodAction == actionDeleteMethod || (this.methodAction == actionDetachMethod && this.moveAttached)) &&
4279                   members.function == function)
4280                {
4281                   if(this.moveAttached && !*text)
4282                      GetLocText(editBox, f, position, &function.loc, text, textSize, Max((int)strlen(this.methodName) - movedFuncIdLen,0), 0);
4283
4284                   DeleteJunkBefore(f, members.loc.start.pos, &position);
4285                   f.DeleteBytes(members.loc.end.pos - members.loc.start.pos + 1);
4286                   position = members.loc.end.pos + 1;
4287                   f.Printf("\n");
4288                }
4289                else
4290                {
4291                   DeleteJunkBefore(f, position, &position);
4292                   if(!lastIsMethod)
4293                      f.Printf(";");
4294
4295                   DeleteJunkBefore(f, members.loc.start.pos, &position);
4296                   lastIsMethod = true;
4297                   f.Printf("\n\n      ");
4298                }
4299
4300                f.Seek(members.loc.end.pos - position, current);
4301                position = members.loc.end.pos;
4302             }
4303             DeleteJunkBefore(f, position, &position);
4304          }
4305       }
4306
4307       if(!object.deleted)
4308       {
4309          if(!methodPresent)
4310             f.Printf(" ");
4311
4312          if((this.methodAction == actionAddMethod || (this.moveAttached && (this.methodAction == actionAttachMethod || this.methodAction == actionReattachMethod))) && this.selected == object)
4313          {
4314             Method method = this.method;
4315             DeleteJunkBefore(f, position, &position);
4316             if(!lastIsMethod)
4317                f.Printf(";");
4318
4319             f.Printf("\n");
4320
4321             if(!method.dataType)
4322                method.dataType = ProcessTypeString(method.dataTypeString, false);
4323
4324             {
4325                Type dataType = method.dataType;
4326                Type returnType = dataType.returnType;
4327                Type param;
4328
4329                if(this.moveAttached)
4330                {
4331                   // Move function here:
4332                   int newLen = strlen(method.name);
4333
4334                   f.Printf("\n   ");
4335
4336                   if(!*text)
4337                      GetLocText(editBox, f, position, &function.loc, text, textSize, Max(newLen - movedFuncIdLen, 0), 3);
4338
4339                   // First change name of function
4340                   memmove(*text + movedFuncIdPos + newLen, *text + movedFuncIdPos + movedFuncIdLen, *textSize - movedFuncIdPos - movedFuncIdLen + 1);
4341                   *textSize += newLen - movedFuncIdLen;
4342                   memcpy(*text + movedFuncIdPos, method.name, newLen);
4343
4344                   // Second, tab right
4345                   {
4346                      int c;
4347                      for(c = 0; (*text)[c]; )
4348                      {
4349                         int i;
4350                         for(i = c; (*text)[i] && (*text)[i] != '\n'; i++);
4351                         if(i != c)
4352                         {
4353                            memmove((*text)+c+3, (*text)+c, *textSize+1-c);
4354                            (*text)[c] = (*text)[c+1] = (*text)[c+2] = ' ';
4355                            c += 3;
4356                            *textSize += 3;
4357                         }
4358                         for(; (*text)[c] && (*text)[c] != '\n'; c++);
4359                         if((*text)[c]) c++;
4360                      }
4361                   }
4362
4363                   f.Puts((*text));
4364                   f.Printf("\n");
4365                }
4366                else
4367                {
4368                   Class moduleClass = eSystem_FindClass(this.privateModule, "Module");
4369
4370                   // ADDING METHOD HERE
4371                   f.Printf("\n      ");
4372                   OutputType(f, returnType, false);
4373
4374                   f.Printf(" ");
4375                   if(dataType.thisClass)
4376                   {
4377                      if(!eClass_IsDerived(regClass, dataType.thisClass.registered) && !dataType.classObjectType)     // Just fixed this... was backwards.
4378                      {
4379                         if(dataType.thisClass.shortName)
4380                            f.Printf(dataType.thisClass.shortName);
4381                         else
4382                            f.Printf(dataType.thisClass.string);
4383                         f.Printf("::");
4384                      }
4385                   }
4386                   f.Printf(method.name);
4387                   f.Printf("(");
4388                   for(param = dataType.params.first; param; param = param.next)
4389                   {
4390                      OutputType(f, param, true);
4391                      if(param.next)
4392                         f.Printf(", ");
4393                   }
4394                   f.Printf(")\n");
4395                   f.Printf("      %c\n\n", OpenBracket);
4396
4397                   if(control._class._vTbl[method.vid] == moduleClass._vTbl[__ecereVMethodID___ecereNameSpace__ecere__com__Module_OnLoad]) // Temp Check for DefaultFunction
4398                   {
4399                      if(returnType.kind == classType && !strcmp(returnType._class.string, "bool"))
4400                         f.Printf("         return true;\n");
4401                      else if(returnType.kind != voidType)
4402                         f.Printf("         return 0;\n");
4403                   }
4404                   else
4405                   {
4406                      f.Printf("         ");
4407                      if(returnType.kind != voidType)
4408                         f.Printf("return ");
4409                      f.Printf("%s::%s(", control._class.name, method.name);
4410                      for(param = dataType.params.first; param; param = param.next)
4411                      {
4412                         if(param.prev) f.Printf(", ");
4413                         if(param.kind != voidType)
4414                            f.Printf(param.name);
4415                      }
4416                      f.Printf(");\n");
4417                   }
4418                   f.Printf("      %c\n", CloseBracket);
4419                }
4420             }
4421          }
4422       }
4423
4424       if(!object.instCode)
4425          f.Printf(methodPresent ? "   %c;" : "%c;", CloseBracket);
4426       else if(!object.deleted)
4427       {
4428          // Turn this into a multiline instance when adding a method
4429          DeleteJunkBefore(f, inst.loc.end.pos-1, &position);
4430
4431          f.Printf(methodPresent ? "\n   " : " ");
4432
4433          f.Seek(inst.loc.end.pos + 1 - position, current);
4434          position = inst.loc.end.pos + 1;
4435       }
4436       return position;
4437    }
4438
4439    void OutputClassProperties(Class _class, ObjectInfo classObject, EditBoxStream f, Instance test)
4440    {
4441       Property propIt;
4442       Class regClass = eSystem_FindClass(privateModule, classObject.name);
4443
4444       if(_class.base && _class.base.type != systemClass) OutputClassProperties(_class.base, classObject, f, test);
4445
4446       for(propIt = _class.membersAndProperties.first; propIt; propIt = propIt.next)
4447       {
4448          Property prop = eClass_FindProperty(selected.instance._class, propIt.name, privateModule);
4449          if(prop && prop.isProperty && !prop.conversion)
4450          {
4451             if(prop.Set && prop.Get && prop.dataTypeString && strcmp(prop.name, "name") && !Code_IsPropertyDisabled(classObject, prop.name) &&
4452                (!prop.IsSet || prop.IsSet(classObject.instance)))
4453             {
4454                Class dataType = prop.dataTypeClass;
4455                char tempString[1024] = "";
4456                char * string = null;
4457                bool specify = false;
4458                DataMember member;
4459
4460                member = eClass_FindDataMember(regClass, prop.name, privateModule, null, null);
4461                if(member && member._class == regClass)
4462                   specify = true;
4463
4464                if(!dataType)
4465                   dataType = prop.dataTypeClass = eSystem_FindClass(this.privateModule, prop.dataTypeString);
4466
4467                if(dataType && dataType.type == structClass)
4468                {
4469                   void * dataForm = new0 byte[dataType.structSize];
4470                   void * dataTest = new0 byte[dataType.structSize];
4471
4472                   ((void (*)(void *, void *))(void *)prop.Get)(classObject.instance, dataForm);
4473                   ((void (*)(void *, void *))(void *)prop.Get)(test, dataTest);
4474
4475                   if(((int (*)(void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnCompare])(dataType, dataForm, dataTest))
4476                   {
4477                      bool needClass = true;
4478
4479                      string = ((char * (*)(void *, void *, void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnGetString])(dataType, dataForm, tempString, null, &needClass);
4480                      ((void (*)(void *, void *))(void *)prop.Set)(test, dataForm);
4481                      if(needClass)
4482                         f.Printf("\n   %s%s = %c %s %c;", specify ? "property::" : "", prop.name, /*dataType.name, */OpenBracket, string, CloseBracket);
4483                      else
4484                         f.Printf("\n   %s%s = %s;", specify ? "property::" : "", prop.name, string);
4485                   }
4486                   delete dataForm;
4487                   delete dataTest;
4488                }
4489                else if(dataType && (dataType.type == normalClass || dataType.type == noHeadClass))
4490                {
4491                   void * dataForm, * dataTest;
4492                   bool isEditBoxContents = false;
4493                   bool freeDataForm = false, freeDataTest = false;
4494
4495                   // Because contents property is broken for mutiline EditBox at the moment
4496                   if(!strcmp(prop.name, "contents") && !strcmp(prop._class.name, "EditBox"))
4497                      isEditBoxContents = true;
4498
4499                   if(isEditBoxContents && ((EditBox)classObject.instance).multiLine)
4500                   {
4501                      dataForm = ((EditBox)classObject.instance).multiLineContents;
4502                      freeDataForm = true;
4503                   }
4504                   else
4505                      dataForm = ((void *(*)(void *))(void *)prop.Get)(classObject.instance);
4506                   if(isEditBoxContents && ((EditBox)test).multiLine)
4507                   {
4508                      dataTest = ((EditBox)test).multiLineContents;
4509                      freeDataTest = true;
4510                   }
4511                   else
4512                      dataTest = ((void *(*)(void *))(void *)prop.Get)(test);
4513
4514                   if(((int (*)(void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnCompare])(dataType, dataForm, dataTest))
4515                   {
4516                      char tempString[1024] = "";
4517                      char * string = null;
4518                      ((void (*)(void *, void *))(void *)prop.Set)(test, dataForm);
4519
4520                      if(eClass_IsDerived(classObject.instance._class, dataType) && classObject.instance == dataForm)
4521                      {
4522                         // Shouldn't go here ...
4523                         f.Printf("\n   %s%s = this;", specify ? "property::" : "", prop.name);
4524                      }
4525                      else
4526                      {
4527                         bool needClass = true;
4528
4529                         string = ((char * (*)(void *, void *, void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnGetString])(dataType, dataForm, tempString, null, &needClass);
4530
4531                         if(!strcmp(dataType.dataTypeString, "char *"))
4532                         {
4533                            Map<String, bool> i18nStrings = classObject.i18nStrings;
4534                            bool i18n = true;
4535                            if(i18nStrings && i18nStrings.GetAtPosition(prop.name, false, null))
4536                               i18n = false;
4537
4538                            f.Printf("\n   %s%s = %s\"", specify ? "property::" : "", prop.name, i18n ? "$" : "");
4539                            OutputString(f, string);
4540                            f.Puts("\";");
4541                         }
4542                         else if(needClass)
4543                            f.Printf("\n   %s%s = %c %s %c;", specify ? "property::" : "", prop.name, /*dataType.name, */OpenBracket, string, CloseBracket);
4544                         else
4545                            f.Printf("\n   %s%s = %s;", specify ? "property::" : "", prop.name, string);
4546                      }
4547                   }
4548                   if(freeDataForm) delete dataForm;
4549                   if(freeDataTest) delete dataTest;
4550                }
4551                else if(dataType)
4552                {
4553                   DataValue dataForm, dataTest;
4554
4555                   GetProperty(prop, classObject.instance, &dataForm);
4556                   GetProperty(prop, test, &dataTest);
4557
4558                   if(((int (*)(void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnCompare])(dataType, &dataForm, &dataTest))
4559                   {
4560                      SetProperty(prop, test, dataForm);
4561                      if(dataType.type == bitClass)
4562                      {
4563                         bool needClass = true;
4564                         string = ((char * (*)(void *, void *, void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnGetString])(dataType, &dataForm, tempString, null, &needClass);
4565                         if(needClass)
4566                            f.Printf("\n   %s%s = %c %s %c;", specify ? "property::" : "", prop.name, /*dataType.name, */OpenBracket, string, CloseBracket);
4567                         else if(string[0])
4568                            f.Printf("\n   %s%s = %s;", specify ? "property::" : "", prop.name, string);
4569                      }
4570                      else
4571                      {
4572                         bool needClass = true;
4573                         if(dataType.type == enumClass)
4574                         {
4575                            NamedLink64 value;
4576                            Class enumClass = eSystem_FindClass(privateModule, "enum");
4577                            EnumClassData e = ACCESS_CLASSDATA(dataType, enumClass);
4578                            int64 i64Value = GetI64EnumValue(dataType, dataForm);
4579
4580                            for(value = e.values.first; value; value = value.next)
4581                            {
4582                               if(value.data == i64Value)
4583                               {
4584                                  string = value.name;
4585                                  break;
4586                               }
4587                            }
4588                         }
4589                         else
4590                            string = ((char * (*)(void *, void *, void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnGetString])(dataType, &dataForm, tempString, null, &needClass);
4591                         if(!strcmp(dataType.dataTypeString, "float") && strchr(string, '.'))
4592                            f.Printf("\n   %s%s = %sf;", specify ? "property::" : "", prop.name, string);
4593                         else if(string[0])
4594                            f.Printf("\n   %s%s = %s;", specify ? "property::" : "", prop.name, string);
4595                      }
4596                   }
4597                }
4598             }
4599          }
4600       }
4601    }
4602
4603    void UpdateFormCode()
4604    {
4605       if(!this) return;
4606       if(!parsing) return;
4607
4608       updatingCode++;
4609       if(codeModified)
4610       {
4611          ParseCode();
4612       }
4613       else if(formModified)
4614       {
4615          EditBoxStream f { editBox = editBox };
4616          int position = 0;
4617          char * text = null;
4618          int textSize;
4619          Identifier movedFuncId;
4620          int movedFuncIdLen = 0, movedFuncIdPos = 0;
4621          ObjectInfo classObject;
4622
4623            updatingCode++;
4624
4625          editBox.recordUndoEvent = true;
4626
4627          if(moveAttached)
4628          {
4629             movedFuncId = GetDeclId(function.declarator);
4630             movedFuncIdLen = movedFuncId.loc.end.pos - movedFuncId.loc.start.pos;
4631             movedFuncIdPos = movedFuncId.loc.start.pos - function.loc.start.pos;
4632          }
4633
4634          for(classObject = classes.first; classObject; classObject = classObject.next)
4635          {
4636             ClassDefinition classDef = classObject.classDefinition;
4637             Class regClass = eSystem_FindClass(this.privateModule, ((Specifier)classDef.baseSpecs->first).name);
4638             Instance test;
4639             ClassDef def;
4640             bool firstObject = true;
4641             ObjectInfo object = classObject.instances.first;
4642             bool lastIsDecl = false;
4643
4644             if(!classObject.modified) continue;
4645
4646             test = eInstance_New(regClass);
4647             incref test;
4648
4649             // Put it in the same desktop window...
4650             designer.PrepareTestObject(test);
4651
4652             //f.Printf("class %s : %s\n", classObject.name, classObject.oClass.name);
4653             //f.Printf("%c\n\n", OpenBracket);
4654
4655             // Change the _class name
4656             f.Seek(classDef.nameLoc.start.pos - position, current);
4657             f.DeleteBytes(classDef.nameLoc.end.pos - classDef.nameLoc.start.pos);
4658             f.Printf(classObject.name);
4659             position = classDef.nameLoc.end.pos;
4660
4661             {
4662                // Go to block start, delete all until no white space, put \n
4663                char ch;
4664                int count = 0;
4665                int back = 0;
4666                f.Seek(classDef.blockStart.end.pos - position, current);
4667                position = classDef.blockStart.end.pos;
4668
4669                for(; f.Getc(&ch); count++)
4670                {
4671                   if(!isspace(ch))
4672                   {
4673                      f.Seek(-1, current);
4674                      break;
4675                   }
4676
4677                   if(ch == '\n')
4678                      back = 0;
4679                   else
4680                      back++;
4681                }
4682
4683                f.Seek(-count, current);
4684
4685                f.DeleteBytes(count-back);
4686                //f.Printf("\n");
4687                position += count-back;
4688             }
4689
4690             // Output properties
4691             OutputClassProperties(classObject.instance._class, classObject, f, test);
4692
4693             for(def = classDef.definitions->first; def; def = def.next)
4694             {
4695                switch(def.type)
4696                {
4697                   case defaultPropertiesClassDef:
4698                   {
4699                      bool keptMember = false;
4700                      MemberInit propDef;
4701                      MemberInit lastKept = null;
4702
4703                      lastIsDecl = false;
4704                      DeleteJunkBefore(f, def.loc.start.pos, &position);
4705
4706                      // This was adding blank spaces between comment and properties -- What was it for?
4707                      // f.Printf("\n   ");
4708
4709                      for(propDef = def.defProperties->first; propDef; propDef = propDef.next)
4710                      {
4711                         Identifier ident = propDef.identifiers->first;
4712                         bool deleted = false;
4713
4714                         // For now delete if it's a prop
4715                         if(!propDef.variable && ident)
4716                         {
4717                            if(!ident.next)
4718                            {
4719                               Property prop = eClass_FindProperty(regClass, ident.string, this.privateModule);
4720                               if(prop)
4721                               {
4722                                  f.Seek(propDef.loc.start.pos - position, current);
4723                                  f.DeleteBytes(propDef.loc.end.pos - propDef.loc.start.pos);
4724                                  position = propDef.loc.end.pos;
4725                                  deleted = true;
4726                               }
4727                               else
4728                               {
4729                                  Method method = eClass_FindMethod(regClass, ident.string, this.privateModule);
4730                                  if(method && method.type == virtualMethod && propDef.initializer && propDef.initializer.type == expInitializer && propDef.initializer.exp && propDef.initializer.exp.type == identifierExp)
4731                                  {
4732                                     if(((methodAction == actionDetachMethod || methodAction == actionReattachMethod) && method == this.method && selected == classObject) ||
4733                                        (methodAction == actionDeleteMethod && !strcmp(function.declarator.symbol.string, propDef.initializer.exp.identifier.string)))
4734                                     {
4735                                        f.Seek(propDef.loc.start.pos - position, current);
4736                                        f.DeleteBytes(propDef.loc.end.pos - propDef.loc.start.pos);
4737                                        position = propDef.loc.end.pos;
4738                                        deleted = true;
4739                                     }
4740                                  }
4741                               }
4742                            }
4743                         }
4744                         if(!deleted)
4745                         {
4746                            keptMember = true;
4747                            lastKept = propDef;
4748                         }
4749                      }
4750
4751                      if(!keptMember)
4752                      {
4753                         char ch = 0;
4754                         f.Seek(def.loc.end.pos - position - 1, current);
4755                         f.Getc(&ch);
4756
4757                         if(ch == ';')
4758                         {
4759                            f.Seek(-1, current);
4760                            f.DeleteBytes(1);
4761                         }
4762                         position = def.loc.end.pos;
4763                      }
4764                      else
4765                      {
4766                         if(lastKept != def.defProperties->last)
4767                         {
4768                            char ch;
4769                            int count = 0;
4770
4771                            f.Seek(-1, current);
4772                            for(;f.Getc(&ch);)
4773                            {
4774                               if(ch == ',')
4775                               {
4776                                  count++;
4777                                  f.Seek(-1, current);
4778                                  break;
4779                               }
4780                               else if(!isspace(ch))
4781                                  break;
4782                               f.Seek(-2, current);
4783                               count++;
4784                            }
4785
4786                            if(ch == ',')
4787                               f.DeleteBytes(count);
4788                         }
4789                         else
4790                         {
4791                            f.Seek(def.loc.end.pos - position, current);
4792                            position = def.loc.end.pos;
4793                         }
4794                      }
4795                      break;
4796                   }
4797                   case declarationClassDef:
4798                   {
4799                      Declaration decl = def.decl;
4800
4801                      if(decl.type == instDeclaration)
4802                      {
4803                         if(def.object/* && ((ObjectInfo)def.object).modified*/)
4804                         {
4805                            while(def.object && object != def.object)
4806                            {
4807                               if(object /*&& ((ObjectInfo)def.object).modified*/)
4808                                  position = UpdateInstanceCode(f, position, regClass, object, &firstObject, &text, &textSize, movedFuncIdLen, movedFuncIdPos);
4809                               object = object.next;
4810                            }
4811
4812                            DeleteJunkBefore(f, def.loc.start.pos, &position);
4813                            f.Printf(firstObject ? "\n\n   " : "\n   ");
4814                            firstObject = false;
4815
4816                            if(def.object && ((ObjectInfo)def.object).modified)
4817                               position = UpdateInstanceCode(f, position, regClass, def.object, &firstObject, &text, &textSize, movedFuncIdLen, movedFuncIdPos);
4818
4819                            object = object ? object.next : null;
4820                         }
4821                         else
4822                         {
4823                            DeleteJunkBefore(f, def.loc.start.pos, &position);
4824                            f.Printf(firstObject ? "\n\n   " : "\n   ");
4825                            firstObject = false;
4826                         }
4827                         lastIsDecl = false;
4828                      }
4829                      else
4830                      {
4831                         DeleteJunkBefore(f, def.loc.start.pos, &position);
4832                         f.Printf(lastIsDecl ? "\n   " : "\n\n   ");
4833                         lastIsDecl = true;
4834                      }
4835                      break;
4836                   }
4837                   case functionClassDef:
4838                   {
4839                      // TESTING IF THIS IS GOOD ENOUGH FOR GENERATED FUNCTION...
4840                      if(!def.function.body) continue;
4841
4842                      lastIsDecl = false;
4843
4844                      DeleteJunkBefore(f, def.loc.start.pos, &position);
4845                      f.Printf("\n\n   ");
4846
4847                      // Delete _class methods
4848                      if((methodAction == actionDeleteMethod || (moveAttached && selected != classObject)) &&
4849                         def.function == function)
4850                      {
4851                         char ch;
4852                         int count = 0;
4853
4854                         if(moveAttached && !text)
4855                         {
4856                            GetLocText(editBox, f, position, &function.loc, &text, &textSize, Max((int)strlen(methodName) - movedFuncIdLen,0), 3);
4857                         }
4858
4859                         f.Seek(def.loc.end.pos - position, current);
4860                         for(; f.Getc(&ch); count++)
4861                         {
4862                            if(!isspace(ch))
4863                            {
4864                               f.Seek(-1, current);
4865                               break;
4866                            }
4867                         }
4868                         f.Seek(def.loc.start.pos - def.loc.end.pos - count, current);
4869
4870                         f.DeleteBytes(def.loc.end.pos - def.loc.start.pos + count);
4871                         position = def.loc.end.pos + count;
4872                      }
4873
4874                      // In case of detaching methods in the _class, simply rename the method
4875                      if(methodAction == actionDetachMethod && moveAttached && selected == classObject && function == def.function)
4876                      {
4877                         f.Seek(function.loc.start.pos + movedFuncIdPos - position, current);
4878                         f.DeleteBytes(movedFuncIdLen);
4879                         f.Puts(methodName);
4880                         position = function.loc.start.pos + movedFuncIdPos + movedFuncIdLen;
4881                      }
4882
4883                      if((methodAction == actionAttachMethod || methodAction == actionReattachMethod) && selected == classObject && moveAttached &&
4884                         function == def.function)
4885                      {
4886                         // In case of attaching methods in the _class, simply rename the method
4887                         f.Seek(function.loc.start.pos + movedFuncIdPos - position, current);
4888                         position = function.loc.start.pos + movedFuncIdPos;
4889                         f.DeleteBytes(movedFuncIdLen);
4890                         if(method.dataType.thisClass)
4891                            f.Printf("%s::", method.dataType.thisClass.string);
4892                         f.Puts(method.name);
4893                         position += movedFuncIdLen;
4894                      }
4895                      break;
4896                   }
4897                   default:
4898                      DeleteJunkBefore(f, def.loc.start.pos, &position);
4899                      if(def.type == memberAccessClassDef)
4900                      {
4901                         f.Printf("\n\n");
4902                         firstObject = false;
4903                         lastIsDecl = true;
4904                      }
4905                      else
4906                      {
4907                         f.Printf("\n   ");
4908                         lastIsDecl = false;
4909                      }
4910                }
4911
4912                f.Seek(def.loc.end.pos - position, current);
4913                position = def.loc.end.pos;
4914             }
4915
4916             // Output attached methods
4917             if((methodAction == actionAttachMethod || methodAction == actionReattachMethod) && selected == classObject && !moveAttached)
4918             {
4919                DeleteJunkBefore(f, position, &position);
4920                f.Printf("\n   %s = %s;\n", method.name, function.declarator.symbol.string);
4921             }
4922
4923             // ********** INSTANCES ***************
4924             for(; object; object = object.next)
4925             {
4926                if(!object.instCode)
4927                {
4928                   position = UpdateInstanceCode(f, position, regClass, object, &firstObject, &text, &textSize, movedFuncIdLen, movedFuncIdPos);
4929                }
4930             }
4931
4932             DeleteJunkBefore(f, position, &position);
4933
4934             // ****************** METHODS ***********************
4935             if(methodAction == actionDetachMethod && moveAttached && classObject == oClass)
4936             {
4937                // If detaching an instance method
4938                if(selected != classObject)
4939                {
4940                   int newLen = strlen(methodName);
4941
4942                   if(!text)
4943                      GetLocText(editBox, f, position, &function.loc, &text, &textSize, Max(newLen - movedFuncIdLen,0), 0);
4944                   // Tab selection left
4945                   {
4946                      int c;
4947                      for(c = 0; text[c]; )
4948                      {
4949                         int start = c, i;
4950                         for(i = 0; i<3 && text[c] == ' '; i++, c++);
4951                         memmove(text+start, text+start+i, textSize+1-start-i);
4952                         textSize -= i;
4953                         c -= i;
4954                         for(; text[c] && text[c] != '\n'; c++);
4955                         if(text[c]) c++;
4956                      }
4957                   }
4958
4959                   // Rename function
4960                   memmove(text + movedFuncIdPos + newLen, text + movedFuncIdPos + movedFuncIdLen, textSize - movedFuncIdPos - movedFuncIdLen + 1);
4961                   textSize += newLen - movedFuncIdLen;
4962                   memcpy(text + movedFuncIdPos, methodName, newLen);
4963
4964                   f.Printf("\n\n   ");
4965                   f.Puts(text);
4966                }
4967             }
4968
4969             if(methodAction == actionAddMethod && selected == classObject)
4970             {
4971                Method method = this.method;
4972
4973                if(!method.dataType)
4974                   method.dataType = ProcessTypeString(method.dataTypeString, false);
4975
4976                // ADDING METHOD HERE
4977                {
4978                   Type dataType = method.dataType;
4979                   Type returnType = dataType.returnType;
4980                   Type param;
4981                   Class moduleClass = eSystem_FindClass(this.privateModule, "Module");
4982
4983                   f.Printf("\n\n");
4984                   f.Printf("   ");
4985                   OutputType(f, returnType, false);
4986
4987                   f.Printf(" ");
4988                   if(dataType.thisClass && !dataType.classObjectType)
4989                   {
4990                      if(dataType.thisClass.shortName)
4991                         f.Printf(dataType.thisClass.shortName);
4992                      else
4993                         f.Printf(dataType.thisClass.string);
4994                      f.Printf("::");
4995                   }
4996                   f.Printf(method.name);
4997                   f.Printf("(");
4998                   for(param = dataType.params.first; param; param = param.next)
4999                   {
5000                      OutputType(f, param, true);
5001                      if(param.next)
5002                         f.Printf(", ");
5003                   }
5004                   f.Printf(")\n");
5005                   f.Printf("   %c\n\n", OpenBracket);
5006
5007                   if(test._class._vTbl[method.vid] == moduleClass._vTbl[__ecereVMethodID___ecereNameSpace__ecere__com__Module_OnLoad]) // Temp Check for DefaultFunction
5008                   {
5009                      if(returnType && returnType.kind == classType && !strcmp(returnType._class.string, "bool"))
5010                         f.Printf("      return true;\n");
5011                      else if(returnType && returnType.kind != voidType)
5012                         f.Printf("      return 0;\n");
5013                   }
5014                   else
5015                   {
5016                      f.Printf("      ");
5017                      if(returnType.kind != voidType)
5018                         f.Printf("return ");
5019                      {
5020                         char * name = ((Specifier)classDef.baseSpecs->first).name;
5021                         Symbol _class = FindClass(name);
5022                         f.Printf("%s::%s(", (_class && _class.registered) ? _class.registered.name : name, method.name);
5023                      }
5024                      for(param = dataType.params.first; param; param = param.next)
5025                      {
5026                         if(param.prev) f.Printf(", ");
5027                         if(param.kind != voidType)
5028                            f.Printf(param.name);
5029                      }
5030                      f.Printf(");\n");
5031                   }
5032
5033                   f.Printf("   %c", CloseBracket);
5034                }
5035             }
5036
5037             DeleteJunkBefore(f, classDef.loc.end.pos-1, &position);
5038             f.Printf("\n");
5039
5040             delete test;
5041          }
5042
5043          editBox.recordUndoEvent = false;
5044
5045          updatingCode--;
5046          delete f;
5047
5048          ParseCode();
5049          delete text;
5050
5051          // TOFIX: Patch for a glitch where clicking at the end of the view seems one line off. No idea what could be going on?
5052          editBox.OnVScroll(setRange, editBox.scroll.y, 0);
5053       }
5054
5055       updatingCode--;
5056       codeModified = false;
5057       formModified = false;
5058       methodAction = 0;
5059       moveAttached = false;
5060       function = null;
5061       method = null;
5062    }
5063
5064    int FindMethod(const char * methodName /*Method method*/, ClassFunction*functionPtr, Location propLoc)
5065    {
5066       int found = 0;
5067       ClassFunction function = null;
5068       if(methodName)
5069       {
5070          ObjectInfo object = this.selected;
5071
5072          if(object && object == this.oClass)
5073          {
5074             ClassDefinition classDef = object.oClass.classDefinition;
5075             ClassDef def;
5076             if(classDef && classDef.definitions)
5077             {
5078                for(def = classDef.definitions->first; def; def = def.next)
5079                {
5080                   if(def.type == functionClassDef && def.function.declarator)
5081                   {
5082                      if(!strcmp(def.function.declarator.symbol.string, methodName))
5083                      {
5084                         function = def.function;
5085                         found = 1;
5086                         break;
5087                      }
5088                   }
5089                   else if(def.type == defaultPropertiesClassDef)
5090                   {
5091                      MemberInit propDef;
5092
5093                      for(propDef = def.defProperties->first; propDef; propDef = propDef.next)
5094                      {
5095                         Identifier ident = propDef.identifiers ? propDef.identifiers->first : null;
5096                         if(ident && !ident.next)
5097                         {
5098                            if(!strcmp(ident.string, methodName) && propDef.initializer && propDef.initializer.type == expInitializer && propDef.initializer.exp && propDef.initializer.exp.type == identifierExp)
5099                            {
5100                               found = 2;
5101                               if(propLoc != null)
5102                                  propLoc = propDef.loc;
5103                               if(functionPtr)
5104                               {
5105                                  ClassDefinition classDef = object.oClass.classDefinition;
5106                                  ClassDef def;
5107                                  if(classDef.definitions)
5108                                  {
5109                                     for(def = classDef.definitions->first; def; def = def.next)
5110                                     {
5111                                        if(def.type == functionClassDef)
5112                                        {
5113                                           if(!strcmp(def.function.declarator.symbol.string, propDef.initializer.exp.identifier.string))
5114                                           {
5115                                              function = def.function;
5116                                              break;
5117                                           }
5118                                        }
5119                                     }
5120                                     if(function) break;
5121                                  }
5122                               }
5123                               else
5124                                  break;
5125                            }
5126                         }
5127                      }
5128                   }
5129                }
5130             }
5131          }
5132          else if(object)
5133          {
5134             Instantiation inst = object.instCode;
5135
5136             // Check here to see if the method already exists, no need to call ModifyCode in that case
5137             if(inst && inst.members)
5138             {
5139                MembersInit members;
5140                for(members = inst.members->first; members; members = members.next)
5141                {
5142                   switch(members.type)
5143                   {
5144                      case dataMembersInit:
5145                      {
5146                         if(members.dataMembers)
5147                         {
5148                            MemberInit member;
5149                            for(member = members.dataMembers->first; member; member = member.next)
5150                            {
5151                               Identifier ident = member.identifiers ? member.identifiers->first : null;
5152                               if(ident && !ident.next)
5153                               {
5154                                  if(!strcmp(ident.string, methodName) && member.initializer && member.initializer.type == expInitializer && member.initializer.exp && member.initializer.exp.type == memberExp /*ExpIdentifier*/)
5155                                  {
5156                                     found = 2;
5157                                     if(propLoc != null)
5158                                        propLoc = member.loc;
5159                                     if(functionPtr)
5160                                     {
5161                                        ClassDefinition classDef = object.oClass.classDefinition;
5162                                        ClassDef def;
5163                                        if(classDef.definitions)
5164                                        {
5165                                           for(def = classDef.definitions->first; def; def = def.next)
5166                                           {
5167                                              if(def.type == functionClassDef)
5168                                              {
5169                                                 if(def.function.declarator && !strcmp(def.function.declarator.symbol.string, member.initializer.exp.identifier.string))
5170                                                 {
5171                                                    function = def.function;
5172                                                    break;
5173                                                 }
5174                                              }
5175                                           }
5176                                           if(function) break;
5177                                        }
5178                                        if(!function)
5179                                        {
5180                                           // TODO: Fix memory leak
5181                                           function = ClassFunction
5182                                           {
5183                                              declarator = Declarator { symbol = Symbol { string = CopyString(member.initializer.exp.member.member ? member.initializer.exp.member.member.string : "") } }
5184                                           };
5185                                        }
5186                                     }
5187                                     else
5188                                        break;
5189                                  }
5190                               }
5191                            }
5192                         }
5193                         break;
5194                      }
5195                      case methodMembersInit:
5196                      {
5197                         if(members.function.declarator && !strcmp(members.function.declarator.symbol.string, methodName))
5198                         {
5199                            function = members.function;
5200                            found = 1;
5201                         }
5202                         break;
5203                      }
5204                   }
5205                   if(function)
5206                      break;
5207                }
5208             }
5209          }
5210       }
5211       if(functionPtr) *functionPtr = function;
5212       return found;
5213    }
5214
5215    void GoToMethod(const char * methodName /*Method method*/)
5216    {
5217       if(methodName)
5218       {
5219          ObjectInfo object = selected;
5220          EditBoxStream f { editBox = editBox };
5221          ClassFunction function = null;
5222          bool atChar = false;
5223          int indent = 6;
5224          EditLine l1, l2;
5225          int y1,y2, x1, x2;
5226          Location propLoc = { {0,0,-1} };
5227
5228          // GO TO THE METHOD
5229          if(FindMethod(methodName, &function, &propLoc) == 1 && object != this.oClass) indent = 9;
5230          if(function && function.body)
5231          {
5232             bool lfCount = 0;
5233             f.Seek(function.body.loc.start.pos+1, current);
5234             for(;;)
5235             {
5236                char ch;
5237                if(!f.Getc(&ch))
5238                   break;
5239                if(ch == '\n')
5240                {
5241                   if(lfCount)
5242                   {
5243                      f.Seek(-1, current);
5244                      break;
5245                   }
5246                   lfCount++;
5247                }
5248                else if(!isspace(ch))
5249                {
5250                   f.Seek(-1, current);
5251                   atChar = true;
5252                   break;
5253                }
5254             }
5255          }
5256          else if(propLoc.start.pos > -1)
5257          {
5258             f.Seek(propLoc.start.pos, current);
5259             atChar = true;
5260          }
5261          editBox.GetSelPos(&l1, &y1, &x1, &l2, &y2, &x2, false);
5262          delete f;
5263          if(function || propLoc.start.pos > -1)
5264          {
5265             editBox.SetSelPos(l1, y1, atChar ? x1 : indent, l2, y2, atChar ? x2 : indent);
5266             editBox.CenterOnCursor();
5267             SetState(normal, false, 0);
5268             Activate();
5269
5270             if(function && function.declarator && function.declarator.symbol && !function.declarator.symbol.type)
5271             {
5272                FreeClassFunction(function);
5273             }
5274          }
5275       }
5276    }
5277
5278    void FindCompatibleMethods(Method method, OldList compatible)
5279    {
5280       ClassDefinition classDef = this.oClass.classDefinition;
5281       if(classDef && classDef.definitions)
5282       {
5283          Class regClass { };
5284          Class baseClass = eSystem_FindClass(this.privateModule, ((Specifier)classDef.baseSpecs->first).name);
5285          ClassDef def;
5286          Class _class;
5287          Symbol classSym { };
5288          Symbol selectedClass;
5289          if(this.selected == this.oClass)
5290             selectedClass = classSym;
5291          else
5292             selectedClass = FindClass(this.selected.instance._class.name);
5293
5294          regClass.name = classDef._class.name;
5295          regClass.base = eSystem_FindClass(this.privateModule, ((Specifier)classDef.baseSpecs->first).name);
5296          for(def = classDef.definitions->first; def; def = def.next)
5297          {
5298             if(def.type == functionClassDef && def.function.declarator)
5299             {
5300                Method vMethod = eClass_FindMethod(baseClass, def.function.declarator.symbol.string, this.privateModule);
5301                if(!vMethod)
5302                   vMethod = eClass_FindMethod(this.selected.instance._class, def.function.declarator.symbol.string, this.privateModule);
5303                if(!vMethod)
5304                {
5305                   Type type = def.function.declarator.symbol.type;
5306                   if(CheckCompatibleMethod(method, type, regClass, this.selected == this.oClass, FindClass(this.selected.instance._class.name)))
5307                   {
5308                      compatible.Add(OldLink { data = def.function });
5309                   }
5310                }
5311             }
5312          }
5313
5314          if(this.oClass && this.oClass.instance)
5315          {
5316             classSym.registered = regClass;
5317             //classSym.registered = this.oClass.oClass;
5318
5319             for(_class = regClass.base; _class; _class = _class.base)
5320             {
5321                Method testMethod;
5322                for(testMethod = (Method)_class.methods.first; testMethod; testMethod = (Method)((BTNode)testMethod).next)
5323                {
5324                   // TODO: Understand why these functions popup in attach list
5325                   if(testMethod.type != virtualMethod /*&& testMethod.function != Window_OnGetString && testMethod.function != Window_OnGetDataFromString*/)
5326                   {
5327                      if(!testMethod.dataType)
5328                         testMethod.dataType = ProcessTypeString(testMethod.dataTypeString, false);
5329
5330                      //if(CheckCompatibleMethod(method, testMethod.dataType, &regClass, false, selectedClass)) // this.selected == this.oClass, selectedClass))
5331                      if(CheckCompatibleMethod(method, testMethod.dataType, this.oClass.instance._class, false, selectedClass)) // this.selected == this.oClass, selectedClass))
5332                      //if(CheckCompatibleMethod(method, testMethod.dataType, &regClass, this.selected == this.oClass, FindClass(this.oClass.oClass.name)))
5333                      {
5334                         // TODO: Fix memory leak, Figure out if it should be ClassFunction or FunctionDefinition
5335                         // ClassFunction function { };
5336                         FunctionDefinition function { };
5337
5338                         function.declarator = Declarator { };
5339                         function.declarator.symbol = Symbol { string = CopyString(testMethod.name) };
5340                         excludedSymbols.Add(function.declarator.symbol);
5341
5342                         compatible.Add(OldLink { data = function });
5343                      }
5344                   }
5345                }
5346             }
5347          }
5348          delete regClass;
5349          delete classSym;
5350       }
5351    }
5352
5353    void AddMethod(Method method)
5354    {
5355       if(method)
5356       {
5357          char methodName[1024];
5358          strcpy(methodName, method.name);
5359          if(!FindMethod(methodName, null, null))
5360          {
5361             methodAction = actionAddMethod;
5362             this.method = method;
5363             ModifyCode();
5364          }
5365          UpdateFormCode();
5366          GoToMethod(methodName);
5367       }
5368    }
5369
5370    void DeleteMethod(ClassFunction function)
5371    {
5372       if(function)
5373       {
5374          methodAction = actionDeleteMethod;
5375          this.function = function;
5376          ModifyCode();
5377          UpdateFormCode();
5378
5379          Update(null);
5380       }
5381    }
5382
5383    void AttachMethod(Method method, ClassFunction function)
5384    {
5385       if(function)
5386       {
5387          // If it's an instance we'll ask if we want to move it inside...
5388          if(!function.attached.count && function.body)
5389          {
5390             // Find the function in the _class to check if it's a virtual function
5391             Class regClass = eSystem_FindClass(this.privateModule, ((Specifier)this.oClass.classDefinition.baseSpecs->first).name);
5392             Method method = eClass_FindMethod(regClass, function.declarator.symbol.string, this.privateModule);
5393             /*    LATER we'll need to check for public/virtual properties etc, for now only checked if virtual in base _class
5394             ClassDef def;
5395             for(def = this.classDefinition.first; def; def = def.next)
5396             {
5397                if(def.type == functionClassDef)
5398                {
5399                   if(def.function == function)
5400                      break;
5401                }
5402             }
5403             */
5404             if(!method || method.type != virtualMethod)
5405             {
5406                char title[1024];
5407                sprintf(title, $"Attach %s", function.declarator.symbol.string);
5408                if(MessageBox { type = yesNo, master = parent, text = title, contents = $"Method is unused. Move method inside instance?"}.Modal() == yes)
5409                {
5410                   moveAttached = true;
5411                }
5412             }
5413          }
5414
5415          methodAction = actionAttachMethod;
5416          this.method = method;
5417          this.function = function;
5418          ModifyCode();
5419          UpdateFormCode();
5420          Update(null);
5421       }
5422    }
5423
5424    void ReAttachMethod(Method method, ClassFunction function)
5425    {
5426       if(function)
5427       {
5428          // If it's an instance we'll ask if we want to move it inside...
5429          if(!function.attached.count && function.body)
5430          {
5431             // Find the function in the _class to check if it's a virtual function
5432             Class regClass = eSystem_FindClass(this.privateModule, ((Specifier)this.oClass.classDefinition.baseSpecs->first).name);
5433             Method method = eClass_FindMethod(regClass, function.declarator.symbol.string, this.privateModule);
5434             /*    LATER we'll need to check for public/virtual properties etc, for now only checked if virtual in base _class
5435             ClassDef def;
5436             for(def = this.classDefinition.first; def; def = def.next)
5437             {
5438                if(def.type == functionClassDef)
5439                {
5440                   if(def.function == function)
5441                      break;
5442                }
5443             }
5444             */
5445             if(!method || method.type != virtualMethod)
5446             {
5447                char title[1024];
5448                sprintf(title, $"Attach %s", function.declarator.symbol.string);
5449                if(MessageBox { type = yesNo, master = parent, text = title,
5450                   contents = $"Method is unused. Move method inside instance?" }.Modal() == yes)
5451                {
5452                   moveAttached = true;
5453                }
5454             }
5455          }
5456
5457          methodAction = actionReattachMethod;
5458          this.method = method;
5459          this.function = function;
5460          ModifyCode();
5461          UpdateFormCode();
5462          Update(null);
5463       }
5464    }
5465
5466    void DetachMethod(Method method, ClassFunction function, int type)
5467    {
5468       bool result = true;
5469
5470       if(type == 1)
5471       {
5472          Window dialog
5473          {
5474             hasClose = true, borderStyle = sizable, minClientSize = { 300, 55 },
5475             master = sheet, text = $"Name detached method", background = formColor
5476          };
5477          Button cancelButton
5478          {
5479             dialog, anchor = { horz = 45, top = 30 }, size = { 80 }, text = $"Cancel", hotKey = escape,
5480             id = DialogResult::cancel, NotifyClicked = ButtonCloseDialog
5481          };
5482          Button okButton
5483          {
5484             dialog, anchor = { horz = -45, top = 30 }, size = { 80 }, text = $"OK", isDefault = true,
5485             id = DialogResult::ok, NotifyClicked = ButtonCloseDialog
5486          };
5487          EditBox nameBox
5488          {
5489             dialog, anchor = { left = 5, right = 5, top = 5 }
5490          };
5491          sprintf(methodName, "%s_%s", selected.name, method.name);
5492          nameBox.contents = methodName;
5493          incref nameBox;
5494          result = dialog.Modal() == ok;
5495          strcpy(methodName, nameBox.contents);
5496          delete nameBox;
5497       }
5498       if(result)
5499       {
5500          // If the method is not attached, move it outside
5501          if(type == 1)
5502          {
5503             // Add this class to the methodName
5504             char name[1024] = "";
5505
5506             if(this.selected != this.oClass && !method.dataType.thisClass)
5507             {
5508                strcat(name, this.selected.instance._class.name);
5509                strcat(name, "::");
5510                strcat(name, this.methodName);
5511                strcpy(this.methodName, name);
5512             }
5513             else if(method.dataType.thisClass && (this.selected == this.oClass || !eClass_IsDerived(this.oClass.instance._class, method.dataType.thisClass.registered)))
5514             {
5515                strcat(name, method.dataType.thisClass.string);
5516                strcat(name, "::");
5517                strcat(name, this.methodName);
5518                strcpy(this.methodName, name);
5519             }
5520
5521             this.moveAttached = true;
5522          }
5523
5524          this.methodAction = actionDetachMethod;
5525          this.method = method;
5526          this.function = function;
5527          ModifyCode();
5528          UpdateFormCode();
5529          Update(null);
5530       }
5531    }
5532
5533    void AddObject(Instance instance, ObjectInfo * object)
5534    {
5535       int id;
5536       incref instance;
5537       //*object = _class.instances.Add(sizeof(ObjectInfo));
5538       *object = ObjectInfo { };
5539       oClass.instances.Insert((selected.oClass == selected) ? null : selected, *object);
5540       (*object).oClass = oClass;
5541       (*object).instance = instance;
5542       for(id = 1;; id++)
5543       {
5544          char name[1024];
5545          ObjectInfo check;
5546          sprintf(name, "%c%s%d", tolower(instance._class.name[0]), instance._class.name+1, id);
5547
5548          // if(strcmp(name, this.oClass.instance.name))
5549
5550          {
5551             for(check = oClass.instances.first; check; check = check.next)
5552                if(!check.deleted && check.name && !strcmp(name, check.name))
5553                   break;
5554             if(!check)
5555             {
5556                (*object).name = CopyString(name);
5557                break;
5558             }
5559          }
5560       }
5561       toolBox.controlClass = null;
5562
5563       ModifyCode();
5564
5565       //sheet.AddObject(*object, (*object).name, TypeData, true);
5566
5567       selected = *object;
5568    }
5569
5570    void EnsureUpToDate()
5571    {
5572       if(sheet && codeModified && parsing)
5573          ParseCode();
5574    }
5575
5576    void SelectObject(ObjectInfo object)
5577    {
5578       selected = object;
5579       oClass = object ? object.oClass : null;
5580       if(designer)
5581          designer.SelectObject(object, object ? object.instance : null);
5582    }
5583
5584    void SelectObjectFromDesigner(ObjectInfo object)
5585    {
5586       selected = object;
5587       sheet.SelectObject(object);
5588    }
5589
5590    void EnumerateObjects(Sheet sheet)
5591    {
5592       ObjectInfo oClass;
5593
5594       for(oClass = classes.first; oClass; oClass = oClass.next)
5595       {
5596          if(oClass.instance)
5597          {
5598             ObjectInfo object;
5599
5600             sheet.AddObject(oClass, oClass.name ? oClass.name : oClass.instance._class.name, typeClass, false);
5601             for(object = oClass.instances.first; object; object = object.next)
5602                sheet.AddObject(object, object.name ? object.name : object.instance._class.name, typeData, false);
5603          }
5604       }
5605       sheet.SelectObject(selected);
5606    }
5607
5608    void AddControl()
5609    {
5610       designer.AddObject();
5611    }
5612
5613    void DeleteObject(ObjectInfo object)
5614    {
5615       delete object.instance;
5616       object.deleted = true;
5617       object.modified = true;
5618       object.oClass.modified = true;
5619
5620       if(selected == object)
5621       {
5622          bool looped = false;
5623          ObjectInfo select = object;
5624
5625          for(;;)
5626          {
5627             select = select.prev;
5628             if(!select)
5629             {
5630                if(looped) break;
5631                select = object.oClass.instances.last;
5632                if(!select) break;
5633                looped = true;
5634             }
5635             if(!select.deleted)
5636                break;
5637          }
5638          sheet.SelectObject(select ? select : oClass);
5639       }
5640
5641       if(!object.instCode && object.oClass != object)
5642       {
5643          delete object.name;
5644          oClass.instances.Delete(object);
5645       }
5646
5647       if(sheet.codeEditor == this)
5648          sheet.DeleteObject(object);
5649    }
5650
5651    void RenameObject(ObjectInfo object, const char * name)
5652    {
5653       bool valid = false;
5654
5655       // Validate the name:
5656       if(object != oClass && (!name || !name[0])) valid = true;   // What's this one again?
5657       else if(name[0] && (isalpha(name[0]) || name[0] == '_'))
5658       {
5659          int c;
5660          for(c = 0; name[c]; c++)
5661             if(!isalnum(name[c]) && name[c] != '_' && name[c] != '_')
5662                break;
5663          if(!name[c])
5664             valid = true;
5665       }
5666       if(valid)
5667       {
5668          delete object.name;
5669          object.name = (name && name[0]) ? CopyString(name) : null;
5670
5671          sheet.RenameObject(object, object.name ? object.name : object.instance._class.name);
5672       }
5673    }
5674
5675    void DesignerModifiedObject()
5676    {
5677       sheet.ListProperties(false);
5678       sheet.Update(null);
5679    }
5680
5681    void ListSubMembers(Type member)
5682    {
5683       Type subMember;
5684
5685       for(subMember = member.members.first; subMember; subMember = subMember.next)
5686       {
5687          if(subMember.name)
5688          {
5689             DataRow row = membersList.AddString(subMember.name);
5690             row.icon = icons[typeData];
5691          }
5692          else
5693          {
5694             ListSubMembers(subMember);
5695          }
5696       }
5697    }
5698
5699    void ListSubDataMembers(DataMember member, bool isPrivate)
5700    {
5701       DataMember subMember;
5702       for(subMember = member.members.first; subMember; subMember = subMember.next)
5703       {
5704          if((subMember.memberAccess == publicAccess && !isPrivate) || subMember._class.module == privateModule)
5705          {
5706             if(subMember.name)
5707             {
5708                DataRow row = membersList.AddString(subMember.name);
5709                BitmapResource bitmap = null;
5710                if(!subMember.dataType)
5711                   subMember.dataType = ProcessTypeString(subMember.dataTypeString, false);
5712
5713                if(subMember.dataType && subMember.dataType.kind == classType && subMember.dataType._class)
5714                {
5715                   char * bitmapName = (char *)(intptr)eClass_GetProperty(subMember.dataType._class.registered, "icon");
5716                   if(bitmapName)
5717                   {
5718                      bitmap = { bitmapName };
5719                      membersList.AddResource(bitmap);
5720                   }
5721                }
5722                row.icon = bitmap ? bitmap : icons[(subMember.memberAccess == publicAccess && !isPrivate) ? typeData : typeDataPrivate];
5723             }
5724             else
5725             {
5726                ListSubDataMembers(subMember, isPrivate || member.memberAccess == privateAccess);
5727             }
5728          }
5729       }
5730    }
5731
5732    void ListClassMembers(Class whatClass, bool methodsOnly)
5733    {
5734       Class _class;
5735       Class baseClass = eSystem_FindClass(this.privateModule, "class");
5736       bool isPrivate = false;
5737
5738       for(_class = whatClass; _class && _class.type != systemClass; _class = _class.base)
5739       {
5740          Method method, methodIt;
5741          DataMember member;
5742          DataMember memberIt;
5743
5744          for(methodIt = (Method)_class.methods.first; methodIt; methodIt = (Method)((BTNode)methodIt).next)
5745          {
5746             method = eClass_FindMethod(whatClass, methodIt.name, privateModule);
5747             if(methodIt.memberAccess == privateAccess && method && method.memberAccess == publicAccess)
5748                method = methodIt;
5749             if(method && method._class.type != systemClass && !eClass_FindMethod(baseClass, method.name, this.privateModule))
5750             {
5751                if(method.memberAccess == publicAccess || method._class.module == privateModule)
5752                {
5753                   DataRow row = membersList.FindString(method.name);
5754                   if(!row)
5755                   {
5756                      row = membersList.AddString(method.name);
5757
5758                      if(!method.dataType)
5759                         method.dataType = ProcessTypeString(method.dataTypeString, false);
5760
5761                      row.icon = icons[(method.type == virtualMethod && method.dataType && method.dataType.thisClass) ? typeEvent : ((method.memberAccess == publicAccess && !isPrivate) ? typeMethod : typeMethodPrivate)];
5762                   }
5763                }
5764             }
5765          }
5766
5767          if(!methodsOnly)
5768          {
5769             for(memberIt = _class.membersAndProperties.first; memberIt; memberIt = memberIt.next)
5770             {
5771                if(memberIt.name)
5772                {
5773                   if(memberIt.isProperty)
5774                   {
5775                      member = (DataMember)eClass_FindProperty(whatClass, memberIt.name, privateModule);
5776                      if(!member)
5777                         member = eClass_FindDataMember(whatClass, memberIt.name, privateModule, null, null);
5778                   }
5779                   else
5780                   {
5781                      member = eClass_FindDataMember(whatClass, memberIt.name, privateModule, null, null);
5782                      if(!member)
5783                         member = (DataMember)eClass_FindProperty(whatClass, memberIt.name, privateModule);
5784                   }
5785
5786                   if(memberIt.memberAccess == privateAccess && member && member.memberAccess == publicAccess)
5787                      member = memberIt;
5788                }
5789                else
5790                   member = memberIt;
5791
5792                if(member && (member.memberAccess == publicAccess || member._class.module == privateModule))
5793                {
5794                   if(member.isProperty)
5795                   {
5796                      Property prop = (Property) member;
5797                      if(!membersList.FindString(prop.name))
5798                      {
5799                         DataRow row = membersList.AddString(prop.name);
5800                         row.icon = icons[(member.memberAccess == publicAccess && !isPrivate) ? typeProperty : typePropertyPrivate];
5801                      }
5802                   }
5803                   else if(member.name && !membersList.FindString(member.name))
5804                   {
5805                      DataRow row = membersList.AddString(member.name);
5806
5807                      BitmapResource bitmap = null;
5808                      if(!member.dataType)
5809                         member.dataType = ProcessTypeString(member.dataTypeString, false);
5810
5811                      if(member.dataType && member.dataType.kind == classType && member.dataType._class)
5812                      {
5813                         char * bitmapName = (char *)(intptr)eClass_GetProperty(member.dataType._class.registered, "icon");
5814                         if(bitmapName)
5815                         {
5816                            bitmap = { bitmapName };
5817                            membersList.AddResource(bitmap);
5818                         }
5819                      }
5820                      row.icon = bitmap ? bitmap : icons[(member.memberAccess == publicAccess && !isPrivate) ? typeData : typeDataPrivate];
5821                   }
5822                   else
5823                      ListSubDataMembers(member, member.memberAccess == privateAccess);
5824                }
5825             }
5826          }
5827          if(_class.inheritanceAccess == privateAccess)
5828          {
5829             isPrivate = true;
5830             if(_class.module != privateModule) break;
5831          }
5832       }
5833    }
5834
5835    void ListClassMembersMatch(Class whatClass, Type methodType)
5836    {
5837       Class _class;
5838       Class baseClass = eSystem_FindClass(this.privateModule, "class");
5839       bool isPrivate = false;
5840
5841       for(_class = whatClass; _class && _class.type != systemClass; _class = _class.base)
5842       {
5843          Method method;
5844
5845          for(method = (Method)_class.methods.first; method; method = (Method)((BTNode)method).next)
5846          {
5847             if(method.memberAccess == publicAccess || method._class.module == privateModule)
5848             {
5849                if(method._class.type != systemClass && !eClass_FindMethod(baseClass, method.name, this.privateModule))
5850                {
5851                   if(!method.dataType)
5852                      method.dataType = ProcessTypeString(method.dataTypeString, false);
5853
5854                   if(MatchTypes(method.dataType, methodType, null, whatClass, /*null, */whatClass, false, true, false, false, true))
5855                   {
5856                      DataRow row = membersList.FindString(method.name);
5857                      if(!row)
5858                      {
5859                         row = membersList.AddString(method.name);
5860                         row.icon = icons[(method.type == virtualMethod && method.dataType.thisClass) ? typeEvent : ((method.memberAccess == publicAccess && !isPrivate) ? typeMethod : typeMethodPrivate)];
5861                      }
5862                   }
5863                }
5864             }
5865          }
5866          if(_class.inheritanceAccess == privateAccess)
5867          {
5868             isPrivate = true;
5869             if(_class.module != privateModule) break;
5870          }
5871       }
5872    }
5873
5874    void ListClassPropertiesAndVirtual(Class whatClass, const String curString)
5875    {
5876       Class _class;
5877       bool isPrivate = false;
5878       for(_class = whatClass; _class /*&& _class.type != systemClass*/; _class = _class.base)
5879       {
5880          Method method;
5881          DataMember member;
5882
5883          for(method = (Method)_class.methods.first; method; method = (Method)((BTNode)method).next)
5884          {
5885             if(method.type == virtualMethod)
5886             {
5887                if(method.memberAccess == publicAccess || method._class.module == privateModule)
5888                {
5889                   DataRow row = membersList.FindString(method.name);
5890                   if(!row)
5891                   {
5892                      row = membersList.AddString(method.name);
5893
5894                      if(!method.dataType)
5895                         method.dataType = ProcessTypeString(method.dataTypeString, false);
5896
5897                      row.icon = icons[method.dataType.thisClass ? typeEvent : ((method.memberAccess == publicAccess && !isPrivate) ? typeMethod : typeMethodPrivate)];
5898                   }
5899                }
5900             }
5901          }
5902
5903          for(member = _class.membersAndProperties.first; member; member = member.next)
5904          {
5905             if(member.memberAccess == publicAccess || member._class.module == privateModule)
5906             {
5907                if(member.isProperty)
5908                {
5909                   Property prop = (Property)member;
5910                   {
5911                      DataRow row = membersList.AddString(prop.name);
5912                      row.icon = icons[(member.memberAccess == publicAccess && !isPrivate) ? typeProperty : typePropertyPrivate];
5913                   }
5914                }
5915                else if(member.name && (!curString || strcmp(curString, member.name)))
5916                {
5917                   DataRow row = membersList.AddString(member.name);
5918
5919                   BitmapResource bitmap = null;
5920                   if(!member.dataType)
5921                      member.dataType = ProcessTypeString(member.dataTypeString, false);
5922
5923                   if(member.dataType && member.dataType.kind == classType && member.dataType._class)
5924                   {
5925                      char * bitmapName = (char *)(intptr)eClass_GetProperty(member.dataType._class.registered, "icon");
5926                      if(bitmapName)
5927                      {
5928                         bitmap = { bitmapName };
5929                         membersList.AddResource(bitmap);
5930                      }
5931                   }
5932                   row.icon = bitmap ? bitmap : icons[(member.memberAccess == publicAccess && !isPrivate) ? typeData : typeDataPrivate];
5933                }
5934                else
5935                   ListSubDataMembers(member, member.memberAccess == privateAccess || isPrivate);
5936             }
5937          }
5938          if(_class.inheritanceAccess == privateAccess)
5939          {
5940             isPrivate = true;
5941             if(_class.module != privateModule) break;
5942          }
5943       }
5944    }
5945
5946    void ListMembers(Type type)
5947    {
5948       if(type && (type.kind == classType || type.kind == structType || type.kind == unionType))
5949       {
5950          if(type.kind == classType)
5951          {
5952             if(type._class)
5953                ListClassMembers(type._class.registered, false);
5954          }
5955          else
5956          {
5957             Type member;
5958             for(member = type.members.first; member; member = member.next)
5959             {
5960                if(member.name)
5961                {
5962                   DataRow row = membersList.AddString(member.name);
5963                   row.icon = icons[typeData];
5964                }
5965                else if(member.kind == structType || member.kind == unionType)
5966                   ListSubMembers(member);
5967             }
5968          }
5969       }
5970    }
5971
5972    void ListModule(Module mainModule, int recurse, bool listClasses)
5973    {
5974       Module module;
5975       ListNameSpace(mainModule.application.systemNameSpace, 1, listClasses);
5976       ListNameSpace(mainModule.application.privateNameSpace, 1, listClasses);
5977       ListNameSpace(mainModule.application.publicNameSpace, 1, listClasses);
5978       for(module = mainModule.application.allModules.first; module; module = module.next)
5979       {
5980          if(ModuleVisibility(mainModule, module))
5981             ListNameSpace(module.publicNameSpace, recurse, listClasses);
5982       }
5983    }
5984
5985    void ListNameSpace(NameSpace nameSpace, int recurse, bool listClasses)
5986    {
5987       NameSpace * ns;
5988       BTNamedLink link;
5989
5990       if(listClasses)
5991       {
5992          for(link = (BTNamedLink)nameSpace.classes.first; link; link = (BTNamedLink)((BTNode)link).next)
5993          {
5994             Class _class = link.data;
5995             if(_class.type != systemClass && !_class.templateClass)  // Omit templatized classes
5996             {
5997                DataRow row = membersList.AddString(_class.name);
5998                row.icon = (_class.type == unitClass || _class.type == enumClass) ? icons[typeDataType] : icons[typeClass];
5999             }
6000          }
6001       }
6002
6003       for(link = (BTNamedLink)nameSpace.defines.first; link; link = (BTNamedLink)((BTNode)link).next )
6004       {
6005          //DefinedExpression definedExp = link.data;
6006          DataRow row = membersList.AddString(link /*definedExp*/.name);
6007          row.icon = icons[typeData];
6008       }
6009
6010       for(link = (BTNamedLink)nameSpace.functions.first; link; link = (BTNamedLink)((BTNode)link).next)
6011       {
6012          //GlobalFunction function = link.data;
6013          DataRow row = membersList.AddString(link /*function*/.name);
6014          row.icon = icons[typeMethod];
6015       }
6016
6017
6018       for(ns = (NameSpace *)nameSpace.nameSpaces.first; ns; ns = (NameSpace *)((BTNode)ns).next)
6019       {
6020          if(recurse != 2 && listClasses)
6021          {
6022             if(!membersList.FindString(ns->name))
6023             {
6024                DataRow row = membersList.AddString(ns->name);
6025                row.icon = icons[typeNameSpace];
6026             }
6027          }
6028
6029          if(recurse)
6030             ListNameSpace(ns, 2, listClasses);
6031       }
6032    }
6033
6034    void ListEnumValues(Class _class)
6035    {
6036       List<Class> classes { };
6037       for(; _class && _class.type == enumClass; _class = _class.base)
6038          classes.Insert(null, _class);
6039       for(_class : classes)
6040       {
6041          EnumClassData enumeration = (EnumClassData)_class.data;
6042          NamedLink64 item;
6043          for(item = enumeration.values.first; item; item = item.next)
6044          {
6045             DataRow row = membersList.AddString(item.name);
6046             row.icon = icons[typeEnumValue];
6047          }
6048       }
6049       delete classes;
6050    }
6051
6052    bool ListEnumsModule(Module mainModule, Type dest)
6053    {
6054       bool result = false;
6055       Module module;
6056       result |= ListEnums(mainModule.application.systemNameSpace, dest);
6057       result |= ListEnums(mainModule.application.privateNameSpace, dest);
6058       result |= ListEnums(mainModule.application.publicNameSpace, dest);
6059       for(module = mainModule.application.allModules.first; module; module = module.next)
6060       {
6061          if(ModuleVisibility(mainModule, module))
6062             result |= ListEnums(module.publicNameSpace, dest);
6063       }
6064       return result;
6065    }
6066
6067    void ListNameSpaceByString(Module mainModule, const char * string)
6068    {
6069       NameSpace * nameSpace;
6070       Module module;
6071       nameSpace = FindNameSpace(mainModule.application.systemNameSpace, string);
6072       if(nameSpace) ListNameSpace(nameSpace, 0, true);
6073       nameSpace = FindNameSpace(mainModule.application.privateNameSpace, string);
6074       if(nameSpace) ListNameSpace(nameSpace, 0, true);
6075       nameSpace = FindNameSpace(mainModule.application.publicNameSpace, string);
6076       if(nameSpace) ListNameSpace(nameSpace, 0, true);
6077       for(module = mainModule.application.allModules.first; module; module = module.next)
6078       {
6079          if(ModuleVisibility(mainModule, module))
6080          {
6081             nameSpace = FindNameSpace(module.publicNameSpace, string);
6082             if(nameSpace) ListNameSpace(nameSpace, 0, true);
6083          }
6084       }
6085    }
6086
6087    bool ListEnums(NameSpace nameSpace, Type dest)
6088    {
6089       BTNamedLink link;
6090       bool result = false;
6091
6092       for(link = (BTNamedLink)nameSpace.classes.first; link; link = (BTNamedLink)((BTNode)link).next)
6093       {
6094          Class _class = link.data;
6095          if(_class.type == enumClass && (dest.kind != classType || ((!dest._class || !dest._class.registered || (dest._class.registered != _class && strcmp(dest._class.registered.dataTypeString, "char *") && strcmp(dest._class.string, "bool"))) && !dest.classObjectType)) &&
6096             dest.kind != pointerType && dest.kind != ellipsisType)
6097          {
6098             OldList conversions { };
6099             Type type { };
6100             type.kind = classType;
6101             type._class = FindClass(_class.name);
6102             if(MatchTypes(type, dest, &conversions, null, null, true, false, false, false, true))
6103             {
6104                ListEnumValues(_class);
6105                result = true;
6106             }
6107             conversions.Free(null);
6108             delete type;
6109          }
6110       }
6111       for(nameSpace = (NameSpace *)nameSpace.nameSpaces.first; nameSpace != null; nameSpace = (NameSpace *)((BTNode)nameSpace).next)
6112       {
6113          result |= ListEnums(nameSpace, dest);
6114       }
6115       return result;
6116    }
6117
6118    NameSpace * FindNameSpace(NameSpace nameSpace, const char * name)
6119    {
6120       int start = 0, c;
6121       char ch;
6122       for(c = 0; (ch = name[c]); c++)
6123       {
6124          if(ch == '.' || (ch == ':' && name[c+1] == ':'))
6125          {
6126             NameSpace * newSpace;
6127             char * spaceName = new char[c - start + 1];
6128             memcpy(spaceName, name + start, c - start);
6129             spaceName[c-start] = '\0';
6130             newSpace = (NameSpace *)nameSpace.nameSpaces.FindString(spaceName);
6131             delete spaceName;
6132             if(!newSpace)
6133                return null;
6134             nameSpace = newSpace;
6135             if(ch == ':') c++;
6136             start = c+1;
6137          }
6138       }
6139       if(c - start)
6140       {
6141          // name + start;
6142       }
6143       return (NameSpace *)nameSpace;
6144    }
6145
6146    void ListSymbols(Expression exp, bool enumOnly, const char * string, Identifier realIdentifier)
6147    {
6148       bool listedEnums = false;
6149       Type destType = (exp && exp.destType && !exp.destType.truth) ? exp.destType : null;
6150       bool listClasses = true;
6151
6152       if(exp && (exp.type == identifierExp || exp.type == memberExp))
6153       {
6154          // TOCHECK: This memberExp check wasn't here... Some stuff isn't quite done
6155          Identifier id = (exp.type == memberExp) ? exp.member.member : exp.identifier;
6156          char * colons = id ? RSearchString(id.string, "::", strlen(id.string), true, false) : null;
6157
6158          if(exp.type == identifierExp)
6159             id = realIdentifier;
6160
6161          if(id && id._class && !id._class.name)
6162          {
6163             listClasses = false;
6164             SetThisClass(null);
6165          }
6166          else if(id && id._class && id._class.name)
6167          {
6168             if(id.classSym)
6169             {
6170                Class _class = id.classSym.registered;
6171                if(_class && _class.type == enumClass)
6172                {
6173                   ListEnumValues(_class);
6174                }
6175                else
6176                   ListClassMembers(id.classSym.registered, true);
6177                return;
6178             }
6179             return;
6180          }
6181          else if(id && colons)
6182          {
6183             ListNameSpaceByString(this.privateModule, id.string);
6184             return;
6185          }
6186       }
6187
6188       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 ||
6189          (destType.kind == pointerType && destType.type.kind != voidType)))
6190       //if(this.privateModule && destType && (destType.kind != pointerType || destType.type.kind != voidType) && destType.kind != ellipsisType)
6191       {
6192          listedEnums = ListEnumsModule(this.privateModule, destType);
6193       }
6194
6195       if(destType && destType.kind == classType && destType._class.registered && destType._class.registered.type == enumClass)
6196       {
6197          ListEnumValues(destType._class.registered);
6198
6199          if(insideClass)
6200             ListClassPropertiesAndVirtual(insideClass, null);
6201
6202          listedEnums = true;
6203       }
6204       else if(destType && destType.kind == enumType)
6205       {
6206          NamedLink64 value;
6207
6208          for(value = destType.members.first; value; value = value.next)
6209          {
6210             DataRow row = membersList.AddString(value.name);
6211             row.icon = icons[typeEnumValue];
6212          }
6213
6214          if(insideClass)
6215             ListClassPropertiesAndVirtual(insideClass, null);
6216
6217          listedEnums = true;
6218       }
6219       else if(insideClass && !enumOnly)
6220       {
6221          ListClassPropertiesAndVirtual(insideClass, string);
6222       }
6223
6224       if(listedEnums && string && string[0])
6225       {
6226          DataRow row = membersList.FindSubString(string);
6227          if(!row)
6228             listedEnums = false;
6229       }
6230
6231       if(!insideClass && exp && exp.destType && exp.destType.kind == functionType && GetThisClass())
6232       {
6233          ListClassMembersMatch(GetThisClass(), exp.destType);
6234       }
6235       else if(!insideClass && !enumOnly && !listedEnums)
6236       {
6237          Context ctx;
6238          Symbol symbol = null;
6239          {
6240             if(GetThisClass())
6241             {
6242                ListClassMembers(GetThisClass(), false);
6243             }
6244
6245             for(ctx = listClasses ? GetCurrentContext() : GetTopContext(); ctx != GetTopContext().parent && !symbol; ctx = ctx.parent)
6246             {
6247                for(symbol = (Symbol)ctx.symbols.first; symbol; symbol = (Symbol)((BTNode)symbol).next)
6248                {
6249                   // Don't list enum values?
6250                   //if(symbol.type.kind != TypeEnum)
6251                   DataRow row = membersList.FindString(symbol.string);
6252                   if(!row)
6253                   {
6254                      if(GetBuildingEcereComModule() && symbol.type && symbol.type.kind == functionType && eSystem_FindFunction(privateModule, symbol.string))
6255                         continue;
6256                      row = membersList.AddString(symbol.string);
6257                      if(symbol.type && symbol.type.kind == functionType)
6258                         row.icon = icons[typeMethod];
6259                      else if(symbol.type && symbol.type.kind == enumType)
6260                      {
6261                         row.icon = icons[typeEnumValue];
6262                      }
6263                      else
6264                      {
6265                         BitmapResource bitmap = null;
6266                         if(symbol.type && symbol.type.kind == classType && symbol.type._class && symbol.type._class)
6267                         {
6268                            char * bitmapName = (char *)(intptr)eClass_GetProperty(symbol.type._class.registered, "icon");
6269                            if(bitmapName)
6270                            {
6271                               bitmap = { bitmapName };
6272                               membersList.AddResource(bitmap);
6273                            }
6274                         }
6275                         row.icon = bitmap ? bitmap : icons[typeData];
6276                      }
6277                   }
6278                }
6279
6280                if(listClasses)
6281                {
6282                   for(symbol = (Symbol)ctx.types.first; symbol; symbol = (Symbol)((BTNode)symbol).next)
6283                   {
6284                      DataRow row = membersList.FindString(symbol.string);
6285                      if(!row)
6286                      {
6287                         row = membersList.AddString(symbol.string);
6288                         if(symbol.type.kind == functionType)
6289                            row.icon = icons[typeMethod];
6290                         else if(symbol.type.kind == classType && (!symbol.type._class.registered || (symbol.type._class.registered.type != unitClass && symbol.type._class.registered.type != enumClass)))
6291                         {
6292                            row.icon = icons[typeClass];
6293                         }
6294                         else
6295                         {
6296                            row.icon = icons[typeDataType];
6297                         }
6298                      }
6299                   }
6300                }
6301             }
6302
6303             ListModule(this.privateModule, 1, listClasses);
6304             // TODO: Implement this with name space
6305             /*
6306             {
6307                GlobalData data;
6308                for(data = globalData.first; data; data = data.next)
6309                {
6310                   DataRow row = membersList.FindString(data.name);
6311                   if(!data.dataType)
6312                      data.dataType = ProcessTypeString(data.dataTypeString, false);
6313                   if(!row)
6314                   {
6315                      row = membersList.AddString(data.name);
6316
6317                      if(data.dataType && data.dataType.kind == TypeEnum)
6318                      {
6319                         row.icon = icons[typeEnumValue];
6320                      }
6321                      else
6322                      {
6323                         BitmapResource bitmap = null;
6324                         if(data.dataType && data.dataType.kind == classType && data.dataType._class && data.dataType._class)
6325                         {
6326                            char * bitmapName = (char *)eClass_GetProperty(data.dataType._class.registered, "icon");
6327                            if(bitmapName)
6328                            {
6329                               bitmap = { bitmapName };
6330                               membersList.AddResource(bitmap);
6331                            }
6332                         }
6333                         row.icon = bitmap ? bitmap : icons[typeData];
6334                      }
6335                   }
6336                }
6337             }
6338             */
6339
6340             {
6341                DataRow row = membersList.AddString("Min");
6342                row.icon = icons[typeMethod];
6343
6344                row = membersList.AddString("Max");
6345                row.icon = icons[typeMethod];
6346
6347                row = membersList.AddString("Abs");
6348                row.icon = icons[typeMethod];
6349
6350                row = membersList.AddString("Sgn");
6351                row.icon = icons[typeMethod];
6352             }
6353          }
6354       }
6355    }
6356
6357    void OverrideVirtualFunction(ClassFunction function, Method method, Class _class, bool isInstance, bool extraIndent)
6358    {
6359       EditBoxStream f { editBox = editBox };
6360       int position = 0;
6361       EditLine l1, l2;
6362       int x1,y1,x2,y2;
6363
6364       updatingCode = true;
6365
6366       if(!method.dataType)
6367          method.dataType = ProcessTypeString(method.dataTypeString, false);
6368
6369       DeleteJunkBefore(f, function.loc.start.pos, &position);
6370       f.DeleteBytes(function.loc.end.pos - function.loc.start.pos - 1);
6371
6372       // ADDING METHOD HERE
6373       {
6374          Type dataType = method.dataType;
6375          Type returnType = dataType.returnType;
6376          Type param;
6377          Class moduleClass = eSystem_FindClass(this.privateModule, "Module");
6378
6379          if(insideDef.prev)
6380              f.Printf("\n\n");
6381          else
6382             f.Printf("\n");
6383          if(extraIndent) f.Printf("   ");
6384          f.Printf("   ");
6385          OutputType(f, returnType, false);
6386
6387          f.Printf(" ");
6388
6389          if(dataType.thisClass && !dataType.classObjectType && (!isInstance || !insideClass || !eClass_IsDerived(insideClass, dataType.thisClass.registered)))
6390          {
6391             if(dataType.thisClass.shortName)
6392                f.Printf(dataType.thisClass.shortName);
6393             else
6394                f.Printf(dataType.thisClass.string);
6395             f.Printf("::");
6396          }
6397          f.Printf(method.name);
6398          f.Printf("(");
6399          for(param = dataType.params.first; param; param = param.next)
6400          {
6401             // Decided not to write void...
6402             if(param.kind != voidType)
6403             {
6404                OutputType(f, param, true);
6405                if(param.next)
6406                   f.Printf(", ");
6407             }
6408          }
6409          f.Printf(")\n");
6410          if(extraIndent) f.Printf("   ");
6411          f.Printf("   %c\n", OpenBracket);
6412
6413          editBox.GetSelPos(&l1, &y1, &x1, &l2, &y2, &x2, false);
6414
6415          f.Printf("\n");
6416
6417          if(!_class ||
6418             (
6419                (isInstance ? _class : _class.base)._vTbl[method.vid] == moduleClass._vTbl[__ecereVMethodID___ecereNameSpace__ecere__com__Module_OnLoad] ||
6420                (isInstance ? _class : _class.base)._vTbl[method.vid] == DummyMethod)) // Temp Check for DefaultFunction
6421          {
6422             if(returnType && returnType.kind == classType && !strcmp(returnType._class.string, "bool"))
6423             {
6424                if(extraIndent) f.Printf("   ");
6425                f.Printf("      return true;\n");
6426             }
6427             else if(returnType && returnType.kind != voidType)
6428             {
6429                if(extraIndent) f.Printf("   ");
6430                f.Printf("      return 0;\n");
6431             }
6432          }
6433          else
6434          {
6435             if(extraIndent) f.Printf("   ");
6436             f.Printf("      ");
6437             if(returnType.kind != voidType)
6438                f.Printf("return ");
6439             f.Printf("%s::%s(", isInstance ? _class.name : _class.base.name, method.name);
6440             for(param = dataType.params.first; param; param = param.next)
6441             {
6442                if(param.prev) f.Printf(", ");
6443                if(param.kind != voidType)
6444                   f.Printf(param.name);
6445             }
6446             f.Printf(");\n");
6447          }
6448       }
6449
6450       if(extraIndent) f.Printf("   ");
6451       f.Printf("   %c", CloseBracket);
6452       // f.Printf("\n");
6453
6454       delete f;
6455
6456       if(extraIndent) { x1 += 3; x2 += 3; }
6457       editBox.SetSelPos(l1, y1, x1 + 6, l2, y2, x2 + 6);
6458
6459       this.updatingCode = false;
6460
6461    }
6462
6463    // Return false if we overrided a function and don't want to run params listing
6464    bool InvokeAutoComplete(bool enumOnly, int pointer, bool caretMove)
6465    {
6466       bool didOverride = false;
6467       EditLine line = editBox.line;
6468       int lineNum, charPos;
6469       Expression exp = null;
6470       EditLine l1, l2;
6471       int x1,y1, x2,y2;
6472       //Identifier id = null;
6473       Expression memberExp = null;
6474       Identifier realIdentifier = null;
6475
6476       if(!parsing) return true;
6477       if(!privateModule) return !didOverride;
6478
6479       insideFunction = null;
6480
6481       charPos = editBox.charPos + 1;
6482       if(!membersListShown)
6483       {
6484          EnsureUpToDate();
6485       }
6486
6487       editBox.GetSelPos(&l1, &y1, &x1, &l2, &y2, &x2, false);
6488       {
6489          EditBoxStream f { editBox = editBox };
6490
6491          updatingCode = true;
6492          editBox.SetSelPos(l1, y1, x1, l2, y2, x2);
6493          for(;;)
6494          {
6495             char ch;
6496             if(!f.Seek(-1, current))
6497                break;
6498             f.Getc(&ch);
6499             if(!isspace(ch)) break;
6500             f.Seek(-1, current);
6501          }
6502          editBox.GetSelPos(&l1, &y1, &x1, &l2, &y2, &x2, false);
6503
6504          lineNum = editBox.lineNumber + 1;
6505          charPos = editBox.charPos + 1;
6506          delete f;
6507          updatingCode = false;
6508       }
6509
6510       if(!membersListShown)
6511       {
6512          memberExp = FindExpTree(ast, lineNum, charPos);
6513          if(memberExp && (memberExp.type == TypeKind::memberExp || memberExp.type == pointerExp) && !memberExp.addedThis)
6514          {
6515          }
6516          else if(!pointer)
6517          {
6518             editBox.GetSelPos(&l1, &y1, &x1, &l2, &y2, &x2, false);
6519             {
6520                EditBoxStream f { editBox = editBox };
6521                char ch = 0;
6522
6523                updatingCode = true;
6524
6525                editBox.SetSelPos(l1, y1, x1, l2, y2, x2);
6526
6527                f.Getc(&ch);
6528                if(ch == '}' || ch == ',' || ch == ')')
6529                {
6530                   f.Seek(-1, current);
6531                   ch = ' ';
6532                }
6533                if(isspace(ch))
6534                {
6535                   for(;;)
6536                   {
6537                      char ch;
6538                      if(!f.Seek(-1, current))
6539                         break;
6540                      f.Getc(&ch);
6541                      if(!isspace(ch)) break;
6542                      f.Seek(-1, current);
6543                   }
6544                }
6545                else
6546                   f.Seek(-1, current);
6547
6548                editBox.GetSelPos(&l1, &y1, &x1, &l2, &y2, &x2, false);
6549
6550                lineNum = editBox.lineNumber + 1;
6551                charPos = editBox.charPos + 1;
6552                delete f;
6553                updatingCode = false;
6554             }
6555
6556             realIdentifier = FindCtxTree(ast, lineNum, charPos);
6557             exp = ctxInsideExp;
6558          }
6559       }
6560
6561       editBox.GetSelPos(&l1, &y1, &x1, &l2, &y2, &x2, false);
6562       lineNum = editBox.lineNumber + 1;
6563       charPos = editBox.charPos/* + 1*/;
6564
6565       {
6566          int rowCount;
6567          char tempString[1024];
6568          char * string = null;
6569          CodePosition idStart { };
6570          CodePosition idEnd { };
6571
6572          if(membersListShown)
6573          {
6574             const char * buffer = membersLine.text;
6575             int c;
6576             bool firstChar = true;
6577             int len = 0;
6578             string = tempString;
6579
6580             for(c = membersLoc.start.charPos; c<membersLoc.end.charPos; c++)
6581             {
6582                bool isSpace = (buffer[c] == ' ' || buffer[c] == '\t');
6583                if(!isSpace) firstChar = false;
6584                if(!firstChar)
6585                   string[len++] = buffer[c];
6586             }
6587             string[len] = 0;
6588          }
6589          else //if(realIdentifier)//if(id)
6590          {
6591             /*
6592             char * buffer = id.string;
6593             int c;
6594             bool firstChar = true;
6595             int len = 0;
6596             string = tempString;
6597             for(c = 0; c<= charPos - id.loc.start.charPos; c++)
6598             {
6599                bool isSpace = (buffer[c] == ' ' || buffer[c] == '\t');
6600                if(!isSpace) firstChar = false;
6601                if(!firstChar)
6602                   string[len++] = buffer[c];
6603             }
6604             string[len] = 0;
6605             */
6606             int x = 0, y;
6607             int len = 0;
6608             EditLine editLine = editBox.line;
6609             bool firstChar = true;
6610             bool done = false;
6611
6612             string = tempString;
6613             for(y = lineNum-1; y >= 0; y--)
6614             {
6615                const char * buffer = editLine.text;
6616                int lineCount = editLine.count;
6617                for(x = (y == lineNum-1) ? (Min(charPos, lineCount) - 1 ): lineCount-1; x >= 0; x--)
6618                {
6619                   bool isSpace = (buffer[x] == ' ' || buffer[x] == '\t');
6620                   if(!isSpace)
6621                   {
6622                      if(firstChar)
6623                      {
6624                         idEnd.charPos = x + 2;
6625                         idEnd.line = y + 1;
6626                      }
6627                      firstChar = false;
6628                   }
6629                   // TESTING THIS CODE HERE FOR NOT CONSIDERING bool when doing ctrl-space past it
6630                   else if(firstChar)
6631                   {
6632                      idEnd.charPos = x + 2;
6633                      idEnd.line = y + 1;
6634                      done = true;
6635                      break;
6636                   }
6637                   if(!firstChar)
6638                   {
6639                      if(!isalnum(buffer[x]) && buffer[x] != '_')
6640                      {
6641                         x++;
6642                         done = true;
6643                         break;
6644                      }
6645                      memmove(string+1, string, len++);
6646                      string[0] = buffer[x];
6647                   }
6648                }
6649
6650                //if(done || firstChar)
6651                if(done || !firstChar)
6652                   break;
6653                editLine = editLine.prev;
6654             }
6655             string[len] = 0;
6656             if(!strcmp(string, "case"))
6657             {
6658                idEnd.charPos += 4;
6659                x+=4;
6660                string[0] = '\0';
6661             }
6662             else if(!strcmp(string, "return"))
6663             {
6664                idEnd.charPos += 6;
6665                x+=6;
6666                string[0] = '\0';
6667             }
6668             else if(!strcmp(string, "delete"))
6669             {
6670                idEnd.charPos += 6;
6671                x+=6;
6672                string[0] = '\0';
6673             }
6674             else if(!strcmp(string, "new"))
6675             {
6676                idEnd.charPos += 3;
6677                x+=3;
6678                string[0] = '\0';
6679             }
6680             else if(!strcmp(string, "renew"))
6681             {
6682                idEnd.charPos +=5;
6683                x+=5;
6684                string[0] = '\0';
6685             }
6686             if(x < 0) x = 0;
6687
6688             idStart.charPos = x + 1;
6689             idStart.line = y + 1;
6690          }
6691
6692          if(!membersListShown)
6693          {
6694             membersList.Clear();
6695             if(memberExp && (memberExp.type == ExpressionType::memberExp || memberExp.type == pointerExp) && !memberExp.addedThis)
6696             {
6697                Type type = memberExp.member.exp.expType;
6698                if(pointer == 2 && type)
6699                {
6700                   if(type.kind == pointerType || type.kind == arrayType)
6701                      type = type.type;
6702                   /*else
6703                      type = null;*/
6704                }
6705                ListMembers(type);
6706             }
6707             else if(!pointer)
6708             {
6709                ListSymbols(exp, enumOnly, string, realIdentifier);
6710             }
6711             membersList.Sort(null, 1);
6712          }
6713
6714          if(insideFunction)
6715          {
6716             // Virtual function override
6717             Identifier id = GetDeclId(insideFunction.declarator);
6718             char * string = id ? id.string : null;
6719
6720             Method method = eClass_FindMethod(GetThisClass(), string, this.privateModule);
6721             if(method)
6722             {
6723                if(method.type != virtualMethod || (!insideInstance && method._class == GetThisClass()))
6724                   insideFunction = null;
6725                else
6726                {
6727                   OverrideVirtualFunction(insideFunction, method, GetThisClass(), insideInstance, insideInstance && insideClass);
6728                   didOverride = true;
6729                }
6730             }
6731          }
6732          if(!didOverride) //insideFunction)
6733          {
6734             rowCount = membersList.rowCount;
6735             if(rowCount)
6736             {
6737                DataRow row = string ? membersList.FindSubString(string) : null;
6738                if(row && !membersList.FindSubStringAfter(row, string) && !caretMove)
6739                {
6740                   const char * newString = row.string;
6741                   if(!membersListShown)
6742                   {
6743                      membersLoc.start.line = idStart.line-1;
6744                      membersLoc.start.charPos = idStart.charPos-1;
6745                      //membersLoc.end = membersLoc.start;
6746                       membersLoc.end.charPos = idEnd.charPos-1;
6747                       membersLoc.end.line = idEnd.line-1;
6748                      //membersLoc.end.charPos = idStart.charPos + strlen(string)-1; //end.charPos-1;
6749                      //membersLoc.end.charPos = idStart.charPos + strlen(string)-1; //end.charPos-1;
6750                      membersLine = line;
6751                   }
6752                   else
6753                   {
6754                      membersList.Destroy(0);
6755                      membersListShown = false;
6756                   }
6757
6758                   editBox.GoToPosition(membersLine, membersLoc.start.line, membersLoc.start.charPos);
6759                   editBox.Delete(
6760                      line, membersLoc.start.line, membersLoc.start.charPos,
6761                      line, membersLoc.end.line, membersLoc.end.charPos);
6762                   editBox.PutS(newString);
6763                }
6764                else
6765                {
6766                   if(!row)
6767                   {
6768                      row = membersList.FindSubStringi(string);
6769                      if(row)
6770                         membersList.currentRow = row;
6771                      membersList.currentRow.selected = false;
6772                   }
6773                   else
6774                      membersList.currentRow = row;
6775
6776                   if(!membersListShown)
6777                   {
6778                      Point caret;
6779
6780                      // TESTING THESE ADDITIONS TO THE IF SO THAT CARET ISNT MOVED IF NOT ON TOP OF A WORD
6781                      if(string && string[0] && lineNum == idStart.line && charPos >= idStart.charPos-1 && charPos <= idEnd.charPos-1)
6782                         editBox.SetSelPos(l1, y1, idStart.charPos-1, l2, y2, idStart.charPos-1);
6783                      editBox.GetCaretPosition(caret);
6784                      editBox.SetSelPos(l1, y1, x1, l2, y2, x2);
6785
6786                      membersList.master = this;
6787
6788                      caret.y += editBox.GetCaretSize();
6789                      caret.x -= 20;
6790                      membersList.Create();
6791
6792                      {
6793                         int x = caret.x + editBox.absPosition.x - app.desktop.absPosition.x - editBox.scroll.x;
6794                         int y = caret.y + editBox.absPosition.y - app.desktop.absPosition.y - editBox.scroll.y;
6795                         Window parent = membersList.parent;
6796
6797                         if(!paramsAbove && (paramsShown || y + membersList.size.h > parent.clientSize.h))
6798                         {
6799                            y -= editBox.GetCaretSize() + membersList.size.h;
6800                            membersAbove = true;
6801                         }
6802                         else
6803                            membersAbove = false;
6804
6805                         membersList.position = { x, y };
6806                      }
6807
6808                      membersLine = l1;
6809                      membersLoc.start.line = lineNum - 1;
6810
6811                      if(string && string[0])
6812                      {
6813                         membersLoc.start.charPos = idStart.charPos-1;
6814                         membersLoc.end = membersLoc.start;
6815                         //membersLoc.end.charPos = id.loc.end.charPos-1;
6816                         membersLoc.end.charPos = idStart.charPos + strlen(string)-1; //end.charPos-1;
6817                      }
6818                      else
6819                      {
6820                         membersLoc.start.charPos = charPos;
6821                         membersLoc.end = membersLoc.start;
6822                         membersLoc.end.charPos = charPos;
6823                      }
6824                      membersListShown = true;
6825
6826                      // Hack to keep caret shown
6827                      editBox.GetCaretPosition(caret);
6828                      editBox.SetCaret(caret.x, caret.y, editBox.GetCaretSize());
6829                   }
6830                   if(row)
6831                      membersList.SetScrollPosition(0, row.index * membersList.rowHeight);
6832                }
6833             }
6834          }
6835       }
6836
6837       SetCurrentContext(globalContext);
6838       SetThisClass(null);
6839
6840       return !didOverride;
6841    }
6842
6843    void InvokeParameters(bool exact, bool reposition, bool caretMove)
6844    {
6845       int lineNum, charPos;
6846       EditLine l1, l2;
6847       int x1,y1, x2,y2;
6848
6849       if(!parsing) return;
6850
6851       charPos = editBox.charPos + 1;
6852       EnsureUpToDate();
6853
6854       editBox.GetSelPos(&l1, &y1, &x1, &l2, &y2, &x2, false);
6855       {
6856          EditBoxStream f { editBox = editBox };
6857          char ch;
6858
6859          updatingCode = true;
6860          editBox.SetSelPos(l1, y1, x1, l2, y2, x2);
6861
6862          f.Getc(&ch);
6863          if(ch == '}' || ch == ',' || ch == ')')
6864          {
6865             f.Seek(-1, current);
6866             ch = ' ';
6867          }
6868          if(isspace(ch))
6869          {
6870             for(;;)
6871             {
6872                char ch;
6873                if(!f.Seek(-1, current))
6874                   break;
6875                f.Getc(&ch);
6876                if(!isspace(ch)) break;
6877                f.Seek(-1, current);
6878             }
6879          }
6880          else
6881             f.Seek(-1, current);
6882
6883          editBox.GetSelPos(&l1, &y1, &x1, &l2, &y2, &x2, false);
6884
6885          lineNum = editBox.lineNumber + 1;
6886          charPos = editBox.charPos + 1;
6887          delete f;
6888          updatingCode = false;
6889       }
6890
6891       charPos = Min(charPos, l1.count + 1);
6892       if(!caretMove)
6893          FindParamsTree(ast, lineNum, charPos);
6894
6895       // Not sure about this == ExpCall... paramsInsideExp doesn't seem to necessarily be a ExpCall
6896       if(exact && ((::functionType && paramsInsideExp.type == callExp && paramsInsideExp.call.exp.loc.end.charPos != charPos-1) /*|| instanceType*/))
6897       {
6898          ::functionType = null;
6899          ::instanceType = null;
6900       }
6901
6902       //if((::functionType || ::instanceType) && (!paramsShown || insideExp != functionExp || ::paramsID != this.paramsID))
6903       if((::functionType || ::instanceType) && (!paramsShown || true /*paramsInsideExp.destType != functionExp.destType */|| ::paramsID != this.paramsID))
6904       {
6905
6906          int x, y;
6907          Window parent = paramsList.parent;
6908
6909          if(this.functionType != ::functionType || this.instanceType != ::instanceType)
6910             reposition = false;
6911
6912          if(!this.paramsShown || reposition || paramsInsideExp != functionExp || ::instanceType) // Added instanceType here, otherwise instance popups never reposition...
6913                                                                                                           // ( Dummy exp: always ends up with same memory)
6914          {
6915             editBox.GetSelPos(&l1, &y1, &x1, &l2, &y2, &x2, false);
6916             editBox.GetCaretPosition(paramsPosition);
6917             this.paramsPosition.y += editBox.GetCaretSize();
6918          }
6919
6920          FreeType(this.functionType);
6921          FreeType(this.instanceType);
6922
6923          this.functionType = ::functionType;
6924          this.instanceType = ::instanceType;
6925
6926          if(this.functionType) this.functionType.refCount++;
6927          if(this.instanceType) this.instanceType.refCount++;
6928
6929          this.paramsID = ::paramsID;
6930          functionExp = paramsInsideExp;
6931
6932          paramsList.master = this;
6933
6934          paramsList.Create();
6935
6936          x = paramsPosition.x + editBox.absPosition.x - app.desktop.absPosition.x - editBox.scroll.x;
6937          y = paramsPosition.y + editBox.absPosition.y - app.desktop.absPosition.y - editBox.scroll.y;
6938
6939          if(!this.membersAbove && ( this.membersListShown || y + paramsList.size.h > parent.clientSize.h) )
6940          {
6941             y -= editBox.GetCaretSize() + paramsList.clientSize.h;
6942             paramsAbove = true;
6943          }
6944          else
6945             paramsAbove = false;
6946          if(x + paramsList.size.w > parent.clientSize.w)
6947          {
6948             x = parent.clientSize.w - paramsList.size.w;
6949             if(x < 0) x = 0;
6950          }
6951
6952          paramsList.position = { x, y };
6953
6954          // Hack to keep caret shown
6955          {
6956             Point caret;
6957             editBox.GetCaretPosition(caret);
6958             editBox.SetCaret(caret.x, caret.y, editBox.GetCaretSize());
6959          }
6960
6961          this.paramsShown = true;
6962       }
6963       else if((!::functionType && !::instanceType) || reposition)
6964       {
6965          paramsList.Destroy(0);
6966          paramsShown = false;
6967
6968          FreeType(this.functionType);
6969          FreeType(this.instanceType);
6970          this.functionType = null;
6971          this.instanceType = null;
6972          this.paramsID = -1;
6973       }
6974
6975       SetCurrentContext(globalContext);
6976       SetThisClass(null);
6977    }
6978
6979    bool ViewDesigner()
6980    {
6981       if(designer)
6982       {
6983          designer.visible = true;
6984          designer.Activate();
6985       }
6986       return true;
6987    }
6988 };
6989
6990 CodeEditor NewCodeEditor(Window parent, WindowState state, bool modified)
6991 {
6992    CodeEditor document { state = state, parent = parent, modifiedDocument = modified };
6993    document.Create();
6994    return document;
6995 }
6996
6997 static int nofdigits(int v)
6998 {
6999    if(v == MININT) return 10 + 1;
7000    if(v < 0) return nofdigits(-v) + 1;
7001    if(v >= 10000)
7002    {
7003       if(v >= 10000000)
7004       {
7005          if(v >= 100000000)
7006          {
7007             if(v >= 1000000000)
7008                return 10;
7009             return 9;
7010          }
7011          return 8;
7012       }
7013       if(v >= 100000)
7014       {
7015          if(v >= 1000000)
7016             return 7;
7017          return 6;
7018       }
7019       return 5;
7020    }
7021    if(v >= 100)
7022    {
7023       if(v >= 1000)
7024          return 4;
7025       return 3;
7026    }
7027    if(v >= 10)
7028       return 2;
7029    return 1;
7030 }