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