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