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