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