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