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