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