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