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