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