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