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