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