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