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