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