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