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