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