01aa84677a5343112bc4268e8296603041a569bb
[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                                                             if(propertyClass.type == normalClass)
3035                                                                computed.instance.data = null;
3036                                                          }
3037                                                       }
3038                                                    }
3039                                                    // MOVED THIS UP NOW THAT char * IS A NORMAL CLASS
3040                                                    else if(computed.type == stringExp && propertyClass.dataTypeString && strstr(propertyClass.dataTypeString, "char *"))
3041                                                    {
3042                                                       String temp = new char[strlen(computed.string)+1];
3043                                                       ReadString(temp, computed.string);
3044                                                       ((void (*)(void *, void *))(void *)prop.Set)(instance, temp);
3045                                                       delete temp;
3046                                                    }
3047                                                    else
3048                                                       propDef.variable = true;
3049                                                    
3050                                                    FreeExpression(computed);
3051                                                 }
3052                                                 else
3053                                                 {
3054                                                    Expression computed = CopyExpression(propDef.initializer.exp);
3055                                                    ComputeExpression(computed);
3056                                                    if(computed.isConstant)
3057                                                    {
3058                                                       //if(computed.type == memberExp) computed = computed.member.exp;
3059
3060                                                       if(computed.type == constantExp)
3061                                                       {
3062                                                          Operand value = GetOperand(computed);
3063                                                          DataValue valueData;
3064                                                          valueData.i64 = value.i64;
3065                                                          SetProperty(prop, instance, valueData);
3066                                                       }
3067                                                       else if(computed.type == stringExp && propertyClass.dataTypeString && strstr(propertyClass.dataTypeString, "char *"))
3068                                                       {
3069                                                          String temp = new char[strlen(computed.string)+1];
3070                                                          ReadString(temp, computed.string);
3071                                                          ((void (*)(void *, void *))(void *)prop.Set)(instance, temp);
3072                                                          delete temp;
3073                                                       }
3074                                                    }
3075                                                    else
3076                                                       propDef.variable = true;
3077
3078                                                    FreeExpression(computed);
3079                                                 }
3080                                              }
3081                                              else
3082                                                 propDef.variable = true;
3083                                           }
3084                                           else
3085                                           {
3086                                              Method method = eClass_FindMethod(regClass, id.string, this.privateModule);
3087                                              if(method && method.type == virtualMethod && propDef.initializer && propDef.initializer.type == expInitializer && 
3088                                                 propDef.initializer.exp && propDef.initializer.exp.type == identifierExp)
3089                                              {
3090                                                 ClassDef def;
3091                                                 // Maintain a list in FunctionDefinition of who is attached to it
3092                                                 for(def = _class.definitions->first; def; def = def.next)
3093                                                 {
3094                                                    if(def.type == functionClassDef)
3095                                                    {
3096                                                       ClassFunction function = def.function;
3097                                                       if(!strcmp(function.declarator.symbol.string, propDef.initializer.exp.identifier.string))
3098                                                       {
3099                                                          function.attached.Add(OldLink { data = method });
3100                                                       }
3101                                                    }
3102                                                 }
3103                                              }                                          
3104                                           }
3105                                        }
3106                                     }
3107                                     break;
3108                                  }
3109                                  case declarationClassDef:
3110                                  {
3111                                     Declaration decl = def.decl;
3112                                     switch(decl.type)
3113                                     {
3114                                        case instDeclaration:
3115                                        {
3116                                           Instantiation inst = decl.inst;
3117                                           Class instClass = eSystem_FindClass(this.privateModule, inst._class.name);
3118                                           if(instClass && eClass_GetDesigner(instClass))
3119                                           {
3120                                              Instance control = eInstance_New(instClass);
3121                                              incref control;
3122
3123                                              object = ObjectInfo
3124                                              {
3125                                                 oClass = classObject;
3126                                                 instance = control;
3127                                                 instCode = inst;
3128                                              };
3129                                              classObject.instances.Add(object);
3130                                              if(inst.exp)
3131                                                 // TOCHECK: Why is this needed now?
3132                                                 object.name = CopyString((inst.exp.type == memberExp) ? inst.exp.member.member.string : inst.exp.identifier.string);
3133                                              def.object = object;
3134
3135                                              // if(object.name) { symbol = eList_Add(&curContext.symbols, sizeof(Symbol)); symbol.string = object.name; symbol.type = MkClassType(instClass.name); }
3136
3137                                              designer.CreateObject(control, object, false, classObject.instance);
3138                                              sheet.AddObject(object, object.name ? object.name : inst._class.name, typeData, false);
3139                                           }
3140                                           break;
3141                                        }
3142                                     }
3143                                     break;
3144                                  }
3145                               }
3146                            }
3147
3148                            // Second pass, process instantiation members
3149                            object = null;
3150                            for(def = _class.definitions->first; def; def = def.next)
3151                            {
3152                               switch(def.type)
3153                               {
3154                                  case declarationClassDef:
3155                                  {
3156                                     Declaration decl = def.decl;
3157                                     switch(decl.type)
3158                                     {
3159                                        case instDeclaration:
3160                                        {
3161                                           Instantiation inst = decl.inst;
3162                                           Class instClass = eSystem_FindClass(this.privateModule, inst._class.name);
3163                                           if(instClass && eClass_GetDesigner(instClass))
3164                                           {
3165                                              Instance control;
3166                                              object = object ? object.next : classObject.instances.first;
3167                                              control = object.instance;                                             
3168                                              
3169                                              if(inst.members)
3170                                              {
3171                                                 MembersInit members;
3172                                                 for(members = inst.members->first; members; members = members.next)
3173                                                 {
3174                                                    switch(members.type)
3175                                                    {
3176                                                       case dataMembersInit:
3177                                                       {
3178                                                          if(members.dataMembers)
3179                                                          {
3180                                                             MemberInit member;
3181                                                             DataMember curMember = null;
3182                                                             Class curClass = null;
3183                                                             DataMember subMemberStack[256];
3184                                                             int subMemberStackPos = 0;
3185
3186                                                             for(member = members.dataMembers->first; member; member = member.next)
3187                                                             {
3188                                                                bool found = false;
3189                                                                Identifier ident = member.identifiers ? member.identifiers->first : null;
3190                                                                if(ident)
3191                                                                {
3192                                                                   DataMember _subMemberStack[256];
3193                                                                   int _subMemberStackPos = 0;
3194                                                                   DataMember thisMember = (DataMember)eClass_FindDataMember(instClass, ident.string, privateModule, _subMemberStack, &_subMemberStackPos);
3195
3196                                                                   if(!thisMember)
3197                                                                   {
3198                                                                      thisMember = (DataMember)eClass_FindProperty(instClass, ident.string, privateModule);
3199                                                                   }
3200                                                                   if(thisMember && thisMember.memberAccess == publicAccess)
3201                                                                   {
3202                                                                      curMember = thisMember;
3203                                                                      curClass = curMember._class;
3204                                                                      memcpy(subMemberStack, _subMemberStack, sizeof(DataMember) * _subMemberStackPos);
3205                                                                      subMemberStackPos = _subMemberStackPos;
3206                                                                      found = true;
3207                                                                   }
3208                                                                }
3209                                                                else
3210                                                                {
3211                                                                   eClass_FindNextMember(instClass, &curClass, (DataMember *)&curMember, subMemberStack, &subMemberStackPos);
3212                                                                   if(curMember) found = true;
3213                                                                }
3214                                                                if(found && curMember.isProperty)
3215                                                                {
3216                                                                   Property prop = (Property) curMember;
3217                                                                   Class propertyClass = prop.dataTypeClass;
3218                                                                   if(!propertyClass)
3219                                                                      propertyClass = prop.dataTypeClass = eSystem_FindClass(this.privateModule, prop.dataTypeString);
3220
3221                                                                   if(prop.compiled && prop.Set && prop.Get && propertyClass && member.initializer && member.initializer.type == expInitializer && member.initializer.exp)
3222                                                                   {
3223                                                                      FreeType(member.initializer.exp.destType);
3224                                                                      member.initializer.exp.destType = MkClassType(propertyClass.name);
3225                                                                      if(propertyClass)
3226                                                                      {
3227                                                                         ProcessExpressionType(member.initializer.exp);
3228                                        
3229                                                                         if(propertyClass.type == structClass || propertyClass.type == normalClass || propertyClass.type == noHeadClass)
3230                                                                         {
3231                                                                            Expression computed;
3232 #ifdef _DEBUG
3233                                                                            /*char debugExpString[4096];
3234                                                                            debugExpString[0] = '\0';
3235                                                                            PrintExpression(member.initializer.exp, debugExpString);*/
3236 #endif
3237                                                                            computed = CopyExpression(member.initializer.exp);
3238                                                                            if(computed)
3239                                                                            {
3240                                                                               ComputeExpression(computed);
3241                                                                               
3242                                                                               if(computed.type == instanceExp && computed.isConstant && computed.isConstant)
3243                                                                               {
3244                                                                                  if(computed.instance.data)
3245                                                                                  {
3246                                                                                     if(computed.instance._class && computed.instance._class.symbol &&
3247                                                                                        computed.instance._class.symbol.registered && 
3248                                                                                        eClass_IsDerived(computed.instance._class.symbol.registered, propertyClass))
3249                                                                                     {
3250                                                                                        ((void (*)(void *, void *))(void *)prop.Set)(control, computed.instance.data);
3251
3252                                                                                        // This was saved in the control and shouldn't be freed by FreeExpression...
3253                                                                                        if(propertyClass.type == normalClass)
3254                                                                                           computed.instance.data = null;
3255                                                                                     }
3256                                                                                  }
3257                                                                               }
3258                                                                               else if(computed.type == identifierExp)
3259                                                                               {
3260                                                                                  member.variable = true;
3261
3262                                                                                  if(eClass_GetDesigner(propertyClass))
3263                                                                                  //if(prop.Set)
3264                                                                                  {
3265                                                                                     char * name = computed.identifier.string;
3266                                                                                     if(!strcmp(name, "this"))
3267                                                                                     {
3268                                                                                        if(prop.Set)
3269                                                                                           ((void (*)(void *, void *))(void *)prop.Set)(control, instance);
3270                                                                                        member.variable = false;
3271                                                                                     }
3272                                                                                     else
3273                                                                                     {
3274                                                                                        ObjectInfo check;
3275                                                                                        for(check = classObject.instances.first; check; check = check.next)
3276                                                                                           if(check.name && !strcmp(name, check.name))
3277                                                                                           {
3278                                                                                              if(prop.Set)
3279                                                                                                 ((void (*)(void *, void *))(void *)prop.Set)(control, check.instance);
3280                                                                                              member.variable = false;
3281                                                                                              break;
3282                                                                                           }
3283                                                                                     }
3284                                                                                  }
3285                                                                               }
3286                                                                               else if(computed.type == memberExp)
3287                                                                               {
3288                                                                                  member.variable = true;
3289                                                                                  if(computed.member.exp.type == identifierExp)
3290                                                                                  {
3291                                                                                     char * name = computed.member.exp.identifier.string;
3292                                                                                     if(!strcmp(name, "this"))
3293                                                                                     {
3294                                                                                        char * name = computed.member.member.string;
3295                                                                                        {
3296                                                                                           ObjectInfo check;
3297                                                                                           for(check = classObject.instances.first; check; check = check.next)
3298                                                                                              if(check.name && !strcmp(name, check.name))
3299                                                                                              {
3300                                                                                                 if(prop.Set)
3301                                                                                                    ((void (*)(void *, void *))(void *)prop.Set)(control, check.instance);
3302                                                                                                 member.variable = false;
3303                                                                                                 break;
3304                                                                                              }
3305                                                                                        }
3306                                                                                     }
3307                                                                                     else
3308                                                                                     {
3309                                                                                        ObjectInfo check;
3310                                                                                        for(check = classObject.instances.first; check; check = check.next)
3311                                                                                        {
3312                                                                                           if(check.name && !strcmp(name, check.name))
3313                                                                                           {
3314                                                                                              Property getProperty = eClass_FindProperty(check.instance._class, computed.member.member.string, this.privateModule);
3315                                                                                              if(getProperty)
3316                                                                                              {
3317                                                                                                 DataValue value { };
3318                                                                                                 GetProperty(getProperty, check.instance, &value);
3319                                                                                                 SetProperty(prop, control, value);
3320                                                                                                 member.variable = false;
3321                                                                                              }
3322                                                                                              break;
3323                                                                                           }
3324                                                                                        }
3325                                                                                     }
3326                                                                                  }
3327                                                                               }
3328                                                                               // MOVED THIS UP NOW THAT char * IS A NORMAL CLASS
3329                                                                               else if(computed.isConstant && computed.type == stringExp && propertyClass.dataTypeString && strstr(propertyClass.dataTypeString, "char *"))
3330                                                                               {
3331                                                                                  String temp = new char[strlen(computed.string)+1];
3332                                                                                  ReadString(temp, computed.string);
3333                                                                                  ((void (*)(void *, void *))(void *)prop.Set)(control, temp);
3334                                                                                  delete temp;
3335                                                                               }
3336                                                                               else
3337                                                                                  member.variable = true;
3338
3339                                                                               FreeExpression(computed);
3340                                                                            }
3341                                                                         }
3342                                                                         else
3343                                                                         {
3344                                                                            Expression computed = CopyExpression(member.initializer.exp);
3345                                                                            if(computed)
3346                                                                            {
3347                                                                               ComputeExpression(computed);
3348                                                                               if(computed.isConstant)
3349                                                                               {
3350                                                                                  if(computed.type == constantExp && (!propertyClass.dataTypeString || strcmp(propertyClass.dataTypeString, "char *"))) //(strcmp(propertyClass.name, "char *") && (strcmp(propertyClass.name, "String"))))
3351                                                                                  {
3352                                                                                     if(!strcmp(propertyClass.dataTypeString, "float"))
3353                                                                                        ((void (*)(void *, float))(void *)prop.Set)(control, (float)strtod(computed.constant, null));
3354                                                                                     else if(!strcmp(propertyClass.dataTypeString, "double"))
3355                                                                                        ((void (*)(void *, double))(void *)prop.Set)(control, strtod(computed.constant, null));
3356                                                                                     else
3357                                                                                        ((void (*)(void *, int))(void *)prop.Set)(control, strtol(computed.constant, null, 0));
3358                                                                                  }
3359                                                                                  else if(computed.type == stringExp  && propertyClass.dataTypeString && strstr(propertyClass.dataTypeString, "char *"))
3360                                                                                  {
3361                                                                                     String temp = new char[strlen(computed.string)+1];
3362                                                                                     ReadString(temp, computed.string);
3363                                                                                     ((void (*)(void *, void *))(void *)prop.Set)(control, temp);
3364                                                                                     delete temp;
3365                                                                                  }
3366                                                                               }
3367                                                                               else
3368                                                                                  member.variable = true;
3369
3370                                                                               FreeExpression(computed);
3371                                                                            }
3372                                                                         }
3373                                                                      }
3374                                                                   }
3375                                                                   else
3376                                                                      member.variable = true;
3377                                                                }
3378                                                                else if(ident && member.initializer && member.initializer.type == expInitializer && member.initializer.exp && 
3379                                                                   member.initializer.exp.type == memberExp) // identifierExp
3380                                                                {
3381                                                                   Method method = eClass_FindMethod(instClass, ident.string, this.privateModule);
3382                                                                   if(method && method.type == virtualMethod)
3383                                                                   {
3384                                                                      ClassDef def;
3385                                                                      // Maintain a list in FunctionDefinition of who is attached to it
3386                                                                      for(def = _class.definitions->first; def; def = def.next)
3387                                                                      {
3388                                                                         if(def.type == functionClassDef)
3389                                                                         {
3390                                                                            ClassFunction function = def.function;
3391                                                                            Identifier id = (member.initializer.exp.type == memberExp) ? member.initializer.exp.member.member : member.initializer.exp.identifier;
3392                                                                            if(function.declarator && !strcmp(function.declarator.symbol.string, id.string))
3393                                                                            {
3394                                                                               function.attached.Add(OldLink { data = method });
3395                                                                               // Reference this particular instance?
3396                                                                            }
3397                                                                         }
3398                                                                      }
3399                                                                   }
3400                                                                }
3401                                                                id++;
3402                                                             }
3403                                                          }
3404                                                          break;
3405                                                       }
3406                                                    }
3407                                                 }                                          
3408                                              }
3409
3410                                              designer.PostCreateObject(object.instance, object, false, classObject.instance);
3411                                              break;
3412                                           }
3413                                        }
3414                                        break;
3415                                     }
3416                                  }
3417                               }
3418                            }
3419                         }
3420
3421                         //designer.CreateObject(instance, classObject, true, null);
3422                         //sheet.AddObject(classObject, classObject.name ? classObject.name : _class._class.name, classType, false);
3423
3424                         designer.PostCreateObject(instance, classObject, true, null);
3425
3426                         //instance.state = Hidden;
3427                         //instance.Create();
3428                         //instance.SetState(Normal, true, 0);
3429                      }
3430                   }
3431                }
3432             }
3433          }
3434
3435          SetAST(null);
3436 #ifdef _TIMINGS
3437          printf("Class/Instance Processing took %.3f seconds\n", GetTime() - startTime);
3438 #endif
3439       }
3440
3441       // Restore Selection
3442       if(selectedClassName)
3443       {
3444          ObjectInfo oClass;
3445          for(oClass = classes.first; oClass; oClass = oClass.next)
3446          {
3447             if(!strcmp(oClass.name, selectedClassName))
3448             {
3449                this.oClass = oClass;
3450                break;
3451             }
3452          }
3453          delete selectedClassName;
3454       }
3455       if(this.oClass)
3456       {
3457          if(selectedName)
3458          {
3459             ObjectInfo check;
3460             int pos = 0;
3461          
3462             for(check = this.oClass.instances.first; check; check = check.next)
3463             {
3464                if(check.name && !strcmp(check.name, selectedName))
3465                {
3466                   this.selected = check;
3467                   break;
3468                }
3469             }
3470             if(!check)
3471             {
3472                if(this.oClass.instances.first)
3473                   this.selected = this.oClass.instances.first;
3474                else
3475                   this.selected = this.oClass;
3476             }
3477          }
3478          else if(selectedPos == -1 || !this.oClass.instances.count)
3479             this.selected = this.oClass;
3480          else
3481          {
3482             ObjectInfo check;
3483             int pos = 0;
3484
3485             if(selectedPos > this.oClass.instances.count)
3486                selectedPos = 0;
3487             for(check = this.oClass.instances.first; check; check = check.next)
3488             {
3489                if(selectedPos == pos++)
3490                {
3491                   this.selected = check;
3492                   break;
3493                }
3494             }
3495          }
3496       }
3497       else
3498       {
3499          this.oClass = classes.first;
3500          this.selected = (this.oClass && this.oClass.instances.first) ? this.oClass.instances.first : this.oClass;
3501       }
3502       delete selectedName;
3503       SetSymbolsDir(null);
3504
3505       if(sheet.codeEditor == this)
3506          sheet.SelectObject(selected);
3507       Update(null);
3508
3509       codeModified = false;
3510
3511       // TESTING THIS TO NOT GET EMPTY PARAMETERS
3512       if(paramsShown)
3513       {
3514          InvokeParameters(false, false, false);
3515       }
3516
3517       editBox.SetSelPos(l1, y1, x1, l2, y2, x2);
3518
3519       reentrant = false;
3520
3521       updatingCode--;
3522
3523       ChangeWorkingDir(oldWorkDir);
3524 #ifdef _TIMINGS
3525       printf("Total FindClass time is %.3f seconds, out of which %.3f is in Ignore NS\n\n", findClassTotalTime, findClassIgnoreNSTotalTime);
3526       printf("Total CheckType time is %.3f seconds\n\n", checkTypeTotalTime);
3527       printf("Total MkExternalImport time is %.3f seconds\n\n", externalImportTotalTime);
3528       printf("Total FindSymbol time is %.3f seconds\n\n", findSymbolTotalTime);
3529       // printf("Total Class Members Find time is %.3f seconds\n\n", GetClassFindTime());
3530       
3531       printf("Whole ParseCode function took %.3f seconds\n\n", GetTime() - parseCodeStart);
3532 #endif
3533       if(inUseDebug && ide.projectView)
3534          ide.debugger.EvaluateWatches();
3535
3536       delete pathBackup;
3537    }
3538
3539    void UpdateInstanceCodeClass(Class _class, ObjectInfo object, EditBoxStream f, Instance test, bool * prev, bool * lastIsMethod, DataMember * curMember, Class * curClass)
3540    {
3541       Property propIt;
3542       Window control = (Window)object.instance;
3543       ObjectInfo classObject = object.oClass;
3544
3545       if(_class.base && _class.base.type != systemClass) UpdateInstanceCodeClass(_class.base, object, f, test, prev, lastIsMethod, curMember, curClass);
3546
3547       if(!strcmp(_class.name, "DesignerBase")) return;
3548
3549       for(propIt = _class.membersAndProperties.first; propIt; propIt = propIt.next)
3550       {
3551          Property prop = eClass_FindProperty(object.instance._class, propIt.name, privateModule);
3552          if(prop && prop.isProperty && !prop.conversion && eClass_FindProperty(object.instance._class, prop.name, privateModule))
3553          {
3554             if(prop.Set && prop.Get && prop.dataTypeString && strcmp(prop.name, "name") && !Code_IsPropertyDisabled(object, prop.name) &&
3555                prop.compiled && (!prop.IsSet || prop.IsSet(control)))
3556             {
3557                Class dataType = prop.dataTypeClass;
3558                if(!dataType)
3559                   dataType = prop.dataTypeClass = eSystem_FindClass(this.privateModule, prop.dataTypeString);
3560          
3561                if(dataType)
3562                {
3563                   if(dataType.type == structClass)
3564                   {
3565                      void * dataForm = new0 byte[dataType.structSize];
3566                      void * dataTest = new0 byte[dataType.structSize];
3567                
3568                      ((void (*)(void *, void *))(void *)prop.Get)(control, dataForm);
3569                      ((void (*)(void *, void *))(void *)prop.Get)(test, dataTest);
3570                
3571                      if((prop.IsSet && !prop.IsSet(test)) || ((int (*)(void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnCompare])(dataType, dataForm, dataTest))
3572                      {
3573                         char tempString[1024] = "";
3574                         char * string = "";
3575                         bool needClass = true;
3576                         if(*prev)
3577                            f.Printf(", ");
3578                   
3579                         ((void (*)(void *, void *))(void *)prop.Set)(test, dataForm);
3580                   
3581                         string = ((char * (*)(void *, void *, void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnGetString])(dataType, dataForm, tempString, null, &needClass);
3582                         
3583                         eClass_FindNextMember(_class, curClass, curMember, null, null);
3584                         if(*curMember != (DataMember)prop)
3585                            f.Printf("%s = ", prop.name);
3586
3587                         *curMember = (DataMember)prop;
3588                         *curClass = curMember->_class;
3589
3590                         if(needClass)
3591                            f.Printf("%c %s %c", /*dataType.name, */OpenBracket, string, CloseBracket);
3592                         else
3593                            f.Printf("%s", string);
3594                         *prev = true;
3595                      }
3596
3597                      delete dataForm;
3598                      delete dataTest;
3599                   }
3600                   else if(dataType.type == normalClass || dataType.type == noHeadClass)
3601                   {
3602                      void * dataForm, * dataTest;
3603                
3604                      dataForm = ((void *(*)(void *))(void *)prop.Get)(control);
3605                      dataTest = ((void *(*)(void *))(void *)prop.Get)(test);
3606                
3607                      if((prop.IsSet && !prop.IsSet(test)) || ((int (*)(void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnCompare])(dataType, dataForm, dataTest))
3608                      {
3609                         char tempString[1024] = "";
3610                         char * string = "";
3611                         if(*prev)
3612                            f.Printf(", ");
3613                   
3614                         ((void (*)(void *, void *))(void *)prop.Set)(test, dataForm);
3615                   
3616                         eClass_FindNextMember(_class, curClass, curMember, null, null);
3617                         if(*curMember != (DataMember)prop)
3618                            f.Printf("%s = ", prop.name);
3619                         *curMember = (DataMember)prop;
3620                         *curClass = curMember->_class;
3621
3622                         if(eClass_GetDesigner(dataType))
3623                         {
3624                            if(eClass_IsDerived(classObject.instance._class, dataType) && classObject.instance == dataForm)
3625                            //if(!strcmp(classObject.instance._class.name, dataType.name) && classObject.instance == dataForm)
3626                               f.Printf("this", prop.name);
3627                            else
3628                            {
3629                               //ObjectInfo classObject;
3630                               //for(classObject = classes.first; classObject; classObject = classObject.next)
3631                               {
3632                                  ObjectInfo object;
3633
3634                                  for(object = classObject.instances.first; object; object = object.next)
3635                                  {
3636                                     if(!object.deleted && eClass_IsDerived(object.instance._class, dataType) && object.instance == dataForm && object.name)
3637                                     {
3638                                        f.Printf("%s", object.name);
3639                                        break;
3640                                     }
3641                                  }
3642
3643                                  if(!object)
3644                                  {
3645                                     bool needClass = true;
3646                                     string = ((char * (*)(void *, void *, void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnGetString])(dataType, dataForm, tempString, null, &needClass);
3647                                     f.Printf("%s", string);
3648                                  }
3649                               }
3650                            }
3651                         }
3652                         else
3653                         {
3654                            bool needClass = true;
3655                            string = ((char * (*)(void *, void *, void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnGetString])(dataType, dataForm, tempString, null, &needClass);
3656
3657                            if(!strcmp(dataType.dataTypeString, "char *"))
3658                            {
3659                               f.Printf("\"");
3660                               OutputString(f, string);
3661                               f.Puts("\"");
3662                            }
3663                            else if(needClass)
3664                               f.Printf("%c %s %c", /*dataType.name, */OpenBracket, string, CloseBracket);
3665                            else
3666                               f.Printf("%s", string);
3667                         }
3668                         *prev = true;
3669                         *lastIsMethod = false;
3670                      }
3671                   }
3672                   else
3673                   {
3674                      DataValue dataForm, dataTest;
3675                
3676                      GetProperty(prop, control, &dataForm);
3677                      GetProperty(prop, test, &dataTest);
3678                
3679                      if((prop.IsSet && !prop.IsSet(test)) || ((int (*)(void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnCompare])(dataType, &dataForm, &dataTest))
3680                      {
3681                         char * string;
3682                         char tempString[1024] = "";
3683                         SetProperty(prop, test, dataForm);
3684                   
3685                         if(dataType.type != bitClass)
3686                         {
3687                            bool needClass = true;
3688
3689                            if(dataType.type == enumClass)
3690                            {
3691                               NamedLink value;
3692                               Class enumClass = eSystem_FindClass(privateModule, "enum");
3693                               EnumClassData e = ACCESS_CLASSDATA(dataType, enumClass);
3694
3695                               for(value = e.values.first; value; value = value.next)
3696                               {
3697                                  if((int)value.data == dataForm.i)
3698                                  {
3699                                     string = value.name;
3700                                     break;
3701                                  }
3702                               }
3703                            }
3704                            else
3705                               string = ((char * (*)(void *, void *, void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnGetString])(dataType, &dataForm, tempString, null, &needClass);
3706                      
3707                            if(string && string[0])
3708                            {
3709                               if(*prev)
3710                                  f.Printf(", ");
3711
3712                               eClass_FindNextMember(_class, curClass, curMember, null, null);
3713                               if(*curMember != (DataMember)prop)
3714                                  f.Printf("%s = ", prop.name);
3715                               *curMember = (DataMember)prop;
3716                               *curClass = curMember->_class;
3717
3718                               if(!strcmp(dataType.dataTypeString, "float") && strchr(string, '.'))
3719                                  f.Printf("%sf", string);
3720                               else
3721                                  f.Printf("%s", string);
3722                               *prev = true;
3723                            }
3724                         }
3725                         else if(dataType.type == bitClass)
3726                         {
3727                            bool needClass = true;
3728
3729                            if(*prev) f.Printf(", ");
3730
3731                            eClass_FindNextMember(_class, curClass, curMember, null, null);
3732                            if(*curMember != (DataMember)prop)
3733                               f.Printf("%s = ", prop.name);
3734                            *curMember = (DataMember)prop;
3735                            *curClass = curMember->_class;
3736
3737                            string = ((char * (*)(void *, void *, void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnGetString])(dataType, &dataForm.ui, tempString, null, &needClass);
3738                            if(needClass)
3739                               f.Printf("%c %s %c", /*dataType.name, */OpenBracket, string, CloseBracket);
3740                            else
3741                               f.Printf("%s", string);
3742                            *prev = true;
3743                            *lastIsMethod = false;
3744                         }
3745                      }
3746                   }
3747                }
3748             }
3749          }
3750       }
3751    }
3752
3753    int UpdateInstanceCode(EditBoxStream f, int position, Class regClass, ObjectInfo object, bool * firstObject, char ** text, int * textSize, int movedFuncIdLen, int movedFuncIdPos)
3754    {
3755       Instantiation inst = object.instCode;
3756       Window control = (Window)object.instance;
3757       bool prev = false;
3758       bool methodPresent = false;
3759       Class _class;
3760       bool lastIsMethod = true;
3761       ObjectInfo classObject = object.oClass;
3762       
3763       if(inst)
3764       {
3765          if(object.deleted)
3766          {
3767             // Instance removed, delete it
3768             DeleteJunkBefore(f, inst.loc.start.pos, &position);
3769
3770             f.DeleteBytes(inst.loc.end.pos - inst.loc.start.pos + 1);
3771             position = inst.loc.end.pos + 1;
3772          }
3773          else
3774          {
3775             bool multiLine = false;
3776
3777             // Change the name
3778             // Check if it's an unnamed instance
3779             if(inst.exp)
3780             {
3781                f.Seek(inst.nameLoc.start.pos - position, current);
3782                f.DeleteBytes(inst.nameLoc.end.pos - inst.nameLoc.start.pos);
3783                position = inst.nameLoc.end.pos;
3784                if(object.name)
3785                   f.Printf(object.name);
3786                else
3787                {
3788                   char ch = 0;
3789                   f.Getc(&ch);
3790                   if(isspace(ch) && ch != '\n')
3791                   {
3792                      f.Seek(-1, current);
3793                      f.DeleteBytes(1);
3794                      position ++;
3795                   }
3796                }
3797             }
3798             else
3799             {
3800                int pos = inst.loc.start.pos; // + strlen(inst._class.name);
3801                char ch;
3802                f.Seek(pos - position, current);
3803                while(f.Getc(&ch))
3804                {  
3805                   if(isspace(ch))
3806                   {
3807                      f.Seek(-1, current);
3808                      break;
3809                   }
3810                   pos++;
3811                }
3812
3813                if(object.name)
3814                {
3815                   f.Puts(" ");
3816                   f.Puts(object.name);
3817                }
3818                position = pos;
3819             }
3820
3821             if((this.methodAction == actionAddMethod || this.moveAttached) && this.selected == object)
3822                methodPresent = true;
3823
3824             for(;;)
3825             {
3826                char ch = 0;
3827                if(!f.Getc(&ch))
3828                   break;
3829                position++;
3830                if(ch == OpenBracket)
3831                   break;
3832                if(ch == '\n')
3833                   multiLine = true;
3834             }
3835
3836             // TODO: Simplify this?
3837             if(methodPresent)
3838             {
3839                if(!multiLine)
3840                {
3841                   int count = 0;
3842                   int toDelete = 0;
3843                   int toAdd = 0;
3844
3845                   f.Seek(-1, current);
3846                   f.Puts("\n   ");
3847                   f.Seek(1, current);
3848                   //f.Puts("\n");
3849
3850                   // Fix indentation
3851                   for(;;)
3852                   {
3853                      char ch = 0;
3854                      if(!f.Getc(&ch))
3855                         break;
3856                      position++;
3857                      if(ch == '\n') { toDelete = count; count = 0; }
3858                      else if(isspace(ch)) count++;
3859                      else
3860                      {
3861                         f.Seek(-1, current);
3862                         position--;
3863                         if(count > 6)
3864                         {
3865                            toDelete += count - 6; 
3866                            count = 6;
3867                         }
3868                         else 
3869                            toAdd = 6 - count;
3870                         break;                              
3871                      }
3872                   }
3873                   if(toDelete)
3874                   {
3875                      f.Seek(-toDelete-count, current);
3876                      f.DeleteBytes(toDelete);
3877                      f.Seek(count, current);
3878                   }
3879                   if(toAdd)
3880                   {
3881                      int c;
3882                      for(c = 0; c<toAdd; c++)
3883                         f.Putc(' ');
3884                   }
3885                }
3886             }
3887             else
3888                methodPresent = multiLine;
3889
3890             if(!prev)
3891                f.Printf(methodPresent ? "\n      " : " ");
3892
3893          }
3894       }
3895       else 
3896       {
3897          // Instance not there, create a brand new one
3898          DeleteJunkBefore(f, position, &position);
3899          f.Printf(*firstObject ? "\n\n" : "\n");
3900          *firstObject = false;
3901
3902          if((this.methodAction == actionAddMethod || this.moveAttached) && this.selected == object)
3903             methodPresent = true;
3904
3905          if(methodPresent)
3906          {
3907             if(object.name)
3908                f.Printf("   %s %s\n   %c\n      ", control._class.name, object.name, OpenBracket);
3909             else
3910                f.Printf("   %s\n   %c\n      ", control._class.name, OpenBracket);
3911          }
3912          else
3913          {
3914             if(object.name)
3915                f.Printf("   %s %s %c ", control._class.name, object.name, OpenBracket);
3916             else
3917                f.Printf("   %s %c ", control._class.name, OpenBracket);
3918          }
3919       }
3920
3921       if(!object.deleted)
3922       {
3923          Instance test = eInstance_New(control._class);
3924          DataMember curMember = null;
3925          Class curClass = null;
3926          incref test;
3927
3928          UpdateInstanceCodeClass(control._class, object, f, test, &prev, &lastIsMethod, &curMember, &curClass);
3929
3930          delete test;
3931
3932          // Attach Method here
3933          if((this.methodAction == actionAttachMethod || this.methodAction == actionReattachMethod) && !this.moveAttached && this.selected == object)
3934          {
3935             if(prev) f.Printf(", ");
3936             f.Printf("%s = %s", this.method.name, function.declarator.symbol.string);
3937             prev = true;
3938          }
3939       }
3940
3941       if(inst && !object.deleted)
3942       {
3943          MembersInit members;
3944          Class instClass = eSystem_FindClass(this.privateModule, inst._class.name);
3945
3946          DeleteJunkBefore(f, position, &position);
3947          
3948          // Instance already there, clear out the properties
3949          for(members = inst.members->first; members; members = members.next)
3950          {
3951             if(members.type == dataMembersInit)
3952             {
3953                MemberInit member;
3954
3955                if(members.dataMembers)
3956                {
3957                   bool keptMember = false;
3958                   MemberInit lastKept = null;
3959
3960                   for(member = members.dataMembers->first; member; member = member.next)
3961                   {
3962                      Identifier ident = member.identifiers ? member.identifiers->first : null;
3963                      bool deleted = false;
3964
3965                      // For now delete if it's not a method
3966                      if(!member.variable) // && ident)
3967                      {
3968                         if(!ident || !ident.next)
3969                         {
3970                            Property prop = ident ? eClass_FindProperty(instClass, ident.string, this.privateModule) : null;
3971                            if(!ident || prop)
3972                            {
3973                               f.Seek(member.loc.start.pos - position, current);
3974                               f.DeleteBytes(member.loc.end.pos - member.loc.start.pos);
3975                               position = member.loc.end.pos;
3976                               deleted = true;
3977                            }
3978                            else
3979                            {
3980                               Method method = eClass_FindMethod(instClass, ident.string, this.privateModule);
3981                               if(method && method.type == virtualMethod && member.initializer && member.initializer.type == expInitializer && member.initializer.exp && 
3982                                  member.initializer.exp.type == memberExp /*ExpIdentifier*/)
3983                               {
3984                                  if(((this.methodAction == actionDetachMethod || this.methodAction == actionReattachMethod) && this.method == method && this.selected == object) ||
3985                                     (this.methodAction == actionDeleteMethod && !strcmp(function.declarator.symbol.string, member.initializer.exp.identifier.string)))
3986                                  {
3987                                     f.Seek(member.loc.start.pos - position, current);
3988                                     f.DeleteBytes(member.loc.end.pos - member.loc.start.pos);
3989                                     position = member.loc.end.pos;
3990                                     deleted = true;
3991                                  }
3992                               }                                          
3993                            }
3994                         }
3995                      }
3996                      if(!deleted)
3997                      {
3998                         keptMember = true;
3999                         lastKept = member;
4000
4001                         //f.Seek(member.loc.start.pos - position, current);
4002                         //position = member.loc.start.pos;
4003                         DeleteJunkBefore(f, member.loc.start.pos, &position);
4004                         if(prev) f.Printf(", "); 
4005                         else if(keptMember) f.Printf(" ");
4006                         prev = false;
4007                      }
4008                   } 
4009                
4010                   if(!keptMember || !members.next)
4011                   {
4012                      char ch = 0;
4013                      int count = 0;
4014
4015                      if(keptMember && lastKept != members.dataMembers->last)
4016                      {
4017                         // Delete the comma
4018                         char ch;
4019                         int count = 0;
4020                         f.Seek(-1, current);
4021                         for(;f.Getc(&ch);)
4022                         {
4023                            if(ch == ',')
4024                            {
4025                               count++;
4026                               f.Seek(-1, current);
4027                               break;
4028                            }
4029                            else if(!isspace(ch))
4030                               break;
4031                            f.Seek(-2, current);
4032                            count++;
4033                         }
4034
4035                         if(ch == ',')
4036                            f.DeleteBytes(count);
4037                      }
4038
4039                      f.Seek(members.loc.end.pos - position, current);
4040                      f.Getc(&ch);
4041             
4042                      if(ch == ';')
4043                      {
4044                         f.Seek(-1, current);
4045                         f.DeleteBytes(1);
4046                         position = members.loc.end.pos + 1;
4047                      }
4048                      else
4049                      {
4050                         f.Seek(-1, current);
4051                         position = members.loc.end.pos;
4052                      }
4053
4054                      if(keptMember)
4055                      {
4056                         prev = true;
4057                         lastIsMethod = false;
4058                      }
4059                   }
4060                   else
4061                   {
4062                      DeleteJunkBefore(f, position, &position);
4063                      f.Printf(" ");
4064
4065                      if(lastKept != members.dataMembers->last)
4066                      {
4067                         // Delete the comma
4068                         char ch;
4069                         int count = 0;
4070                         f.Seek(-1, current);
4071                         for(;f.Getc(&ch);)
4072                         {
4073                            if(ch == ',')
4074                            {
4075                               count++;
4076                               f.Seek(-1, current);
4077                               break;
4078                            }
4079                            else if(!isspace(ch))
4080                               break;
4081                            f.Seek(-2, current);
4082                            count++;
4083                         }
4084
4085                         if(ch == ',')
4086                            f.DeleteBytes(count);
4087                      }
4088                      else
4089                      {
4090                         f.Seek(members.loc.end.pos - position, current);
4091                         position = members.loc.end.pos;
4092                      }
4093                      /*
4094                      prev = false;
4095                      lastIsMethod = true;
4096                      */
4097                      prev = true;
4098                      lastIsMethod = false;
4099                      
4100                   }
4101                }
4102                else
4103                {
4104                   f.Seek(members.loc.end.pos - position, current);
4105                   position = members.loc.end.pos;
4106                   prev = false;
4107                   lastIsMethod = true;
4108                }
4109             }
4110             else if(members.type == methodMembersInit)
4111             {
4112                if(this.methodAction == actionDeleteMethod && members.function == function);
4113                else
4114                   methodPresent = true;
4115
4116                // Delete instance method here
4117                if((this.methodAction == actionDeleteMethod || (this.methodAction == actionDetachMethod && this.moveAttached)) && 
4118                   members.function == function)
4119                {
4120                   if(this.moveAttached && !*text)
4121                      GetLocText(editBox, f, position, &function.loc, text, textSize, Max((int)strlen(this.methodName) - movedFuncIdLen,0), 0);
4122
4123                   DeleteJunkBefore(f, members.loc.start.pos, &position);
4124                   f.DeleteBytes(members.loc.end.pos - members.loc.start.pos + 1);
4125                   position = members.loc.end.pos + 1;
4126                   f.Printf("\n");
4127                }
4128                else
4129                {
4130                   DeleteJunkBefore(f, position, &position);
4131                   if(!lastIsMethod)
4132                      f.Printf(";");
4133
4134                   DeleteJunkBefore(f, members.loc.start.pos, &position);
4135                   lastIsMethod = true;
4136                   f.Printf("\n\n      ");               
4137                }
4138
4139                f.Seek(members.loc.end.pos - position, current);
4140                position = members.loc.end.pos;
4141             }
4142             DeleteJunkBefore(f, position, &position);
4143          }
4144       }
4145
4146       if(!object.deleted)
4147       {
4148          if(!methodPresent)
4149             f.Printf(" ");
4150
4151          if((this.methodAction == actionAddMethod || (this.moveAttached && (this.methodAction == actionAttachMethod || this.methodAction == actionReattachMethod))) && this.selected == object)
4152          {
4153             Method method = this.method;
4154             DeleteJunkBefore(f, position, &position);
4155             if(!lastIsMethod)
4156                f.Printf(";");
4157
4158             f.Printf("\n");
4159
4160             if(!method.dataType)
4161                method.dataType = ProcessTypeString(method.dataTypeString, false);
4162
4163             {
4164                Type dataType = method.dataType;
4165                Type returnType = dataType.returnType;
4166                Type param;
4167
4168                if(this.moveAttached)
4169                {
4170                   // Move function here:
4171                   int newLen = strlen(method.name);
4172
4173                   f.Printf("\n   ");
4174
4175                   if(!*text)
4176                      GetLocText(editBox, f, position, &function.loc, text, textSize, Max(newLen - movedFuncIdLen, 0), 3);
4177
4178                   // First change name of function
4179                   memmove(*text + movedFuncIdPos + newLen, *text + movedFuncIdPos + movedFuncIdLen, *textSize - movedFuncIdPos - movedFuncIdLen + 1);
4180                   *textSize += newLen - movedFuncIdLen;
4181                   memcpy(*text + movedFuncIdPos, method.name, newLen);
4182                                           
4183                   // Second, tab right
4184                   {
4185                      int c;
4186                      for(c = 0; (*text)[c]; )
4187                      {
4188                         int i;
4189                         for(i = c; (*text)[i] && (*text)[i] != '\n'; i++);
4190                         if(i != c)
4191                         {
4192                            memmove((*text)+c+3, (*text)+c, *textSize+1-c);
4193                            (*text)[c] = (*text)[c+1] = (*text)[c+2] = ' ';
4194                            c += 3;
4195                            *textSize += 3;
4196                         }
4197                         for(; (*text)[c] && (*text)[c] != '\n'; c++);
4198                         if((*text)[c]) c++;
4199                      }
4200                   }
4201
4202                   f.Puts((*text));
4203                   f.Printf("\n");
4204                }
4205                else
4206                {
4207                   Class moduleClass = eSystem_FindClass(this.privateModule, "Module");
4208
4209                   // ADDING METHOD HERE
4210                   f.Printf("\n      ");
4211                   OutputType(f, returnType, false);
4212             
4213                   f.Printf(" ");
4214                   if(dataType.thisClass)
4215                   {
4216                      if(!eClass_IsDerived(regClass, dataType.thisClass.registered) && !dataType.classObjectType)     // Just fixed this... was backwards.
4217                      {
4218                         if(dataType.thisClass.shortName)
4219                            f.Printf(dataType.thisClass.shortName);
4220                         else
4221                            f.Printf(dataType.thisClass.string);
4222                         f.Printf("::");
4223                      }
4224                   }
4225                   f.Printf(method.name);
4226                   f.Printf("(");
4227                   for(param = dataType.params.first; param; param = param.next)
4228                   {
4229                      OutputType(f, param, true);
4230                      if(param.next)
4231                         f.Printf(", ");
4232                   }
4233                   f.Printf(")\n");                  
4234                   f.Printf("      %c\n\n", OpenBracket);
4235
4236                   if(control._class._vTbl[method.vid] == moduleClass._vTbl[__ecereVMethodID___ecereNameSpace__ecere__com__Module_OnLoad]) // Temp Check for DefaultFunction
4237                   {
4238                      if(returnType.kind == classType && !strcmp(returnType._class.string, "bool"))
4239                         f.Printf("         return true;\n");
4240                      else if(returnType.kind != voidType)
4241                         f.Printf("         return 0;\n");
4242                   }
4243                   else
4244                   {
4245                      f.Printf("         ");
4246                      if(returnType.kind != voidType)
4247                         f.Printf("return ");
4248                      f.Printf("%s::%s(", control._class.name, method.name);
4249                      for(param = dataType.params.first; param; param = param.next)
4250                      {
4251                         if(param.prev) f.Printf(", ");
4252                         if(param.kind != voidType)
4253                            f.Printf(param.name);
4254                      }
4255                      f.Printf(");\n");
4256                   }
4257                   f.Printf("      %c\n", CloseBracket);
4258                }
4259             }
4260          }
4261       }
4262
4263       if(!object.instCode)
4264       {
4265          if(methodPresent)
4266             f.Printf("   %c;\n", CloseBracket);
4267          else
4268             f.Printf("%c;\n", CloseBracket);
4269       }
4270       else if(!object.deleted)
4271       {
4272          // Turn this into a multiline instance when adding a method
4273          DeleteJunkBefore(f, inst.loc.end.pos-1, &position);
4274
4275          f.Printf(methodPresent ? "\n   " : " ");
4276
4277          f.Seek(inst.loc.end.pos + 1 - position, current);
4278          position = inst.loc.end.pos + 1;
4279       }
4280       return position;
4281    }
4282
4283    void OutputClassProperties(Class _class, ObjectInfo classObject, EditBoxStream f, Instance test)
4284    {
4285       Property propIt;
4286       Class regClass = eSystem_FindClass(privateModule, classObject.name);
4287      
4288       if(_class.base && _class.base.type != systemClass) OutputClassProperties(_class.base, classObject, f, test);
4289       
4290       for(propIt = _class.membersAndProperties.first; propIt; propIt = propIt.next)
4291       {
4292          Property prop = eClass_FindProperty(selected.instance._class, propIt.name, privateModule);
4293          if(prop && prop.isProperty && !prop.conversion)
4294          {
4295             if(prop.Set && prop.Get && prop.dataTypeString && strcmp(prop.name, "name") && !Code_IsPropertyDisabled(classObject, prop.name) && 
4296                (!prop.IsSet || prop.IsSet(classObject.instance)))
4297             {
4298                Class dataType = prop.dataTypeClass;
4299                char tempString[1024] = "";
4300                char * string;
4301                bool specify = false;
4302                DataMember member;
4303
4304                member = eClass_FindDataMember(regClass, prop.name, privateModule, null, null);
4305                if(member && member._class == regClass)
4306                   specify = true;
4307
4308                if(!dataType)
4309                   dataType = prop.dataTypeClass = eSystem_FindClass(this.privateModule, prop.dataTypeString);
4310             
4311                if(dataType && dataType.type == structClass)
4312                {
4313                   void * dataForm = new0 byte[dataType.structSize];
4314                   void * dataTest = new0 byte[dataType.structSize];
4315                
4316                   ((void (*)(void *, void *))(void *)prop.Get)(classObject.instance, dataForm);
4317                   ((void (*)(void *, void *))(void *)prop.Get)(test, dataTest);
4318
4319                   if(((int (*)(void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnCompare])(dataType, dataForm, dataTest))
4320                   {
4321                      bool needClass = true;
4322                      
4323                      string = ((char * (*)(void *, void *, void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnGetString])(dataType, dataForm, tempString, null, &needClass);
4324                      ((void (*)(void *, void *))(void *)prop.Set)(test, dataForm);
4325                      if(needClass)
4326                         f.Printf("\n   %s%s = %c %s %c;", specify ? "property::" : "", prop.name, /*dataType.name, */OpenBracket, string, CloseBracket);
4327                      else
4328                         f.Printf("\n   %s%s = %s;", specify ? "property::" : "", prop.name, string);
4329                   }
4330                   delete dataForm;
4331                   delete dataTest;
4332                }
4333                else if(dataType && (dataType.type == normalClass || dataType.type == noHeadClass))
4334                {
4335                   void * dataForm, * dataTest;
4336                
4337                   dataForm = ((void *(*)(void *))(void *)prop.Get)(classObject.instance);
4338                   dataTest = ((void *(*)(void *))(void *)prop.Get)(test);
4339                
4340                   if(((int (*)(void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnCompare])(dataType, dataForm, dataTest))
4341                   {
4342                      char tempString[1024] = "";
4343                      char * string;
4344                      ((void (*)(void *, void *))(void *)prop.Set)(test, dataForm);
4345                   
4346                      if(eClass_IsDerived(classObject.instance._class, dataType) && classObject.instance == dataForm)
4347                      {
4348                         // Shouldn't go here ...
4349                         f.Printf("\n   %s%s = this;", specify ? "property::" : "", prop.name);
4350                      }
4351                      else
4352                      {
4353                         bool needClass = true;
4354
4355                         string = ((char * (*)(void *, void *, void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnGetString])(dataType, dataForm, tempString, null, &needClass);
4356
4357                         if(!strcmp(dataType.dataTypeString, "char *"))
4358                         {
4359                            f.Printf("\n   %s%s = \"", specify ? "property::" : "", prop.name);
4360                            OutputString(f, string);
4361                            f.Puts("\";");
4362                         }
4363                         else if(needClass)
4364                            f.Printf("\n   %s%s = %c %s %c;", specify ? "property::" : "", prop.name, /*dataType.name, */OpenBracket, string, CloseBracket);
4365                         else
4366                            f.Printf("\n   %s%s = %s;", specify ? "property::" : "", prop.name, string);
4367                      }
4368                   }
4369                }
4370                else if(dataType)
4371                {
4372                   DataValue dataForm, dataTest;
4373                
4374                   GetProperty(prop, classObject.instance, &dataForm);
4375                   GetProperty(prop, test, &dataTest);
4376                
4377                   if(((int (*)(void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnCompare])(dataType, &dataForm, &dataTest))
4378                   {
4379                      SetProperty(prop, test, dataForm);
4380                      if(dataType.type == bitClass)
4381                      {
4382                         bool needClass = true;
4383                         string = ((char * (*)(void *, void *, void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnGetString])(dataType, &dataForm, tempString, null, &needClass);
4384                         if(needClass)
4385                            f.Printf("\n   %s%s = %c %s %c;", specify ? "property::" : "", prop.name, /*dataType.name, */OpenBracket, string, CloseBracket);
4386                         else if(string[0])
4387                            f.Printf("\n   %s%s = %s;", specify ? "property::" : "", prop.name, string);
4388                      }
4389                      else
4390                      {
4391                         bool needClass = true;
4392                         if(dataType.type == enumClass)
4393                         {
4394                            NamedLink value;
4395                            Class enumClass = eSystem_FindClass(privateModule, "enum");
4396                            EnumClassData e = ACCESS_CLASSDATA(dataType, enumClass);
4397
4398                            for(value = e.values.first; value; value = value.next)
4399                            {
4400                               if((int)value.data == dataForm.i)
4401                               {
4402                                  string = value.name;
4403                                  break;
4404                               }
4405                            }
4406                         }
4407                         else
4408                            string = ((char * (*)(void *, void *, void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnGetString])(dataType, &dataForm, tempString, null, &needClass);
4409                         if(!strcmp(dataType.dataTypeString, "float") && strchr(string, '.'))
4410                            f.Printf("\n   %s%s = %sf;", specify ? "property::" : "", prop.name, string);
4411                         else if(string[0])
4412                            f.Printf("\n   %s%s = %s;", specify ? "property::" : "", prop.name, string);
4413                      }
4414                   }                                          
4415                }
4416             }
4417          }
4418       }
4419    }
4420
4421    void UpdateFormCode()
4422    {
4423       if(!this) return;
4424       if(!parsing) return;
4425
4426       updatingCode++;
4427       if(codeModified)
4428       {
4429          ParseCode();
4430       }
4431       else if(formModified)
4432       {
4433          EditBoxStream f { editBox = editBox };
4434          int position = 0;
4435          char * text = null;
4436          int textSize;
4437          Identifier movedFuncId; 
4438          int movedFuncIdLen = 0, movedFuncIdPos = 0;
4439          ObjectInfo classObject;
4440
4441            updatingCode++;
4442
4443          if(moveAttached)
4444          {
4445             movedFuncId = GetDeclId(function.declarator);
4446             movedFuncIdLen = movedFuncId.loc.end.pos - movedFuncId.loc.start.pos;
4447             movedFuncIdPos = movedFuncId.loc.start.pos - function.loc.start.pos;
4448          }
4449
4450          for(classObject = classes.first; classObject; classObject = classObject.next)
4451          {
4452             Class _class;
4453             ClassDefinition classDef = classObject.classDefinition;
4454             Class regClass = eSystem_FindClass(this.privateModule, ((Specifier)classDef.baseSpecs->first).name);
4455             Instance test;
4456             ClassDef def;
4457             bool firstObject = true;
4458             ObjectInfo object = classObject.instances.first;
4459             bool lastIsDecl = false;
4460
4461             if(!classObject.modified) continue;
4462
4463             test = eInstance_New(regClass);
4464             incref test;
4465
4466             // Put it in the same desktop window...
4467             designer.PrepareTestObject(test);
4468             
4469             //f.Printf("class %s : %s\n", classObject.name, classObject.oClass.name);
4470             //f.Printf("%c\n\n", OpenBracket);
4471
4472             // Change the _class name
4473             f.Seek(classDef.nameLoc.start.pos - position, current);
4474             f.DeleteBytes(classDef.nameLoc.end.pos - classDef.nameLoc.start.pos);
4475             f.Printf(classObject.name);
4476             position = classDef.nameLoc.end.pos;
4477
4478             {
4479                // Go to block start, delete all until no white space, put \n
4480                char ch;
4481                int count = 0;
4482                int back = 0;
4483                f.Seek(classDef.blockStart.end.pos - position, current);
4484                position = classDef.blockStart.end.pos;
4485                
4486                for(; f.Getc(&ch); count++)
4487                {
4488                   if(!isspace(ch))
4489                   {
4490                      f.Seek(-1, current);
4491                      break;
4492                   }
4493                
4494                   if(ch == '\n')
4495                      back = 0;
4496                   else
4497                      back++;
4498                }
4499             
4500                f.Seek(-count, current);
4501             
4502                f.DeleteBytes(count-back);
4503                //f.Printf("\n");
4504                position += count-back;
4505             }
4506
4507             // Output properties
4508             OutputClassProperties(classObject.instance._class, classObject, f, test);
4509
4510             for(def = classDef.definitions->first; def; def = def.next)
4511             {
4512                switch(def.type)
4513                {
4514                   case defaultPropertiesClassDef:
4515                   {
4516                      bool keptMember = false;
4517                      MemberInit propDef;
4518                      MemberInit lastKept = null;
4519                      
4520                      lastIsDecl = false;
4521                      DeleteJunkBefore(f, def.loc.start.pos, &position);
4522                      f.Printf("\n   ");
4523
4524                      for(propDef = def.defProperties->first; propDef; propDef = propDef.next)
4525                      {
4526                         Identifier ident = propDef.identifiers->first;
4527                         bool deleted = false;
4528
4529                         // For now delete if it's a prop
4530                         if(!propDef.variable && ident)
4531                         {
4532                            if(!ident.next)
4533                            {
4534                               Property prop = eClass_FindProperty(regClass, ident.string, this.privateModule);
4535                               if(prop)
4536                               {
4537                                  f.Seek(propDef.loc.start.pos - position, current);
4538                                  f.DeleteBytes(propDef.loc.end.pos - propDef.loc.start.pos);
4539                                  position = propDef.loc.end.pos;
4540                                  deleted = true;
4541                               }
4542                               else
4543                               {
4544                                  Method method = eClass_FindMethod(regClass, ident.string, this.privateModule);
4545                                  if(method && method.type == virtualMethod && propDef.initializer && propDef.initializer.type == expInitializer && propDef.initializer.exp && propDef.initializer.exp.type == identifierExp)
4546                                  {
4547                                     if(((methodAction == actionDetachMethod || methodAction == actionReattachMethod) && method == this.method && selected == classObject) ||
4548                                        (methodAction == actionDeleteMethod && !strcmp(function.declarator.symbol.string, propDef.initializer.exp.identifier.string)))
4549                                     {
4550                                        f.Seek(propDef.loc.start.pos - position, current);
4551                                        f.DeleteBytes(propDef.loc.end.pos - propDef.loc.start.pos);
4552                                        position = propDef.loc.end.pos;
4553                                        deleted = true;
4554                                     }
4555                                  }                                          
4556                               }
4557                            }
4558                         }
4559                         if(!deleted)
4560                         {
4561                            keptMember = true;
4562                            lastKept = propDef;
4563                         }
4564                      }
4565                   
4566                      if(!keptMember)
4567                      {
4568                         char ch = 0;
4569                         int count = 0;
4570                         f.Seek(def.loc.end.pos - position - 1, current);
4571                         f.Getc(&ch);
4572                         
4573                         if(ch == ';')
4574                         {
4575                            f.Seek(-1, current);
4576                            f.DeleteBytes(1);
4577                         }
4578                         position = def.loc.end.pos;
4579                      }
4580                      else
4581                      {
4582                         if(lastKept != def.defProperties->last)
4583                         {
4584                            char ch;
4585                            int count = 0;
4586                            
4587                            f.Seek(-1, current);
4588                            for(;f.Getc(&ch);)
4589                            {
4590                               if(ch == ',')
4591                               {
4592                                  count++;
4593                                  f.Seek(-1, current);
4594                                  break;
4595                               }
4596                               else if(!isspace(ch))
4597                                  break;
4598                               f.Seek(-2, current);
4599                               count++;
4600                            }
4601
4602                            if(ch == ',')
4603                               f.DeleteBytes(count);
4604                         }
4605                         else
4606                         {
4607                            f.Seek(def.loc.end.pos - position, current);
4608                            position = def.loc.end.pos;
4609                         }                
4610                      }
4611                      break;
4612                   }
4613                   case declarationClassDef:
4614                   {
4615                      Declaration decl = def.decl;
4616
4617                      if(decl.type == instDeclaration)
4618                      {
4619                         if(def.object/* && ((ObjectInfo)def.object).modified*/)
4620                         {
4621                            while(def.object && object != def.object)
4622                            {
4623                               if(object /*&& ((ObjectInfo)def.object).modified*/)
4624                                  position = UpdateInstanceCode(f, position, regClass, object, &firstObject, &text, &textSize, movedFuncIdLen, movedFuncIdPos);
4625                               object = object.next;
4626                            }
4627
4628                            DeleteJunkBefore(f, def.loc.start.pos, &position);
4629                            f.Printf(firstObject ? "\n\n   " : "\n   ");
4630                            firstObject = false;
4631
4632                            if(def.object && ((ObjectInfo)def.object).modified)
4633                               position = UpdateInstanceCode(f, position, regClass, def.object, &firstObject, &text, &textSize, movedFuncIdLen, movedFuncIdPos);
4634
4635                            object = object ? object.next : null;
4636                         }
4637                         else
4638                         {
4639                            DeleteJunkBefore(f, def.loc.start.pos, &position);
4640                            f.Printf(firstObject ? "\n\n   " : "\n   ");
4641                            firstObject = false;
4642                         }
4643                         lastIsDecl = false;
4644                      }
4645                      else
4646                      {
4647                         DeleteJunkBefore(f, def.loc.start.pos, &position);
4648                         f.Printf(lastIsDecl ? "\n   " : "\n\n   ");
4649                         lastIsDecl = true;
4650                      }
4651                      break;
4652                   }
4653                   case functionClassDef:
4654                   {
4655                      // TESTING IF THIS IS GOOD ENOUGH FOR GENERATED FUNCTION...
4656                      if(!def.function.body) continue;
4657
4658                      lastIsDecl = false;
4659
4660                      DeleteJunkBefore(f, def.loc.start.pos, &position);
4661                      f.Printf("\n\n   ");
4662
4663                      // Delete _class methods
4664                      if((methodAction == actionDeleteMethod || (moveAttached && selected != classObject)) && 
4665                         def.function == function)
4666                      {
4667                         char ch;
4668                         int count = 0;
4669
4670                         if(moveAttached && !text)
4671                         {
4672                            GetLocText(editBox, f, position, &function.loc, &text, &textSize, Max((int)strlen(methodName) - movedFuncIdLen,0), 3);
4673                         }
4674
4675                         f.Seek(def.loc.end.pos - position, current);
4676                         for(; f.Getc(&ch); count++)
4677                         {
4678                            if(!isspace(ch))
4679                            {
4680                               f.Seek(-1, current);
4681                               break;
4682                            }
4683                         }
4684                         f.Seek(def.loc.start.pos - def.loc.end.pos - count, current);
4685
4686                         f.DeleteBytes(def.loc.end.pos - def.loc.start.pos + count);
4687                         position = def.loc.end.pos + count;
4688                      }
4689
4690                      // In case of detaching methods in the _class, simply rename the method
4691                      if(methodAction == actionDetachMethod && moveAttached && selected == classObject && function == def.function)
4692                      {
4693                         f.Seek(function.loc.start.pos + movedFuncIdPos - position, current);
4694                         f.DeleteBytes(movedFuncIdLen);
4695                         f.Puts(methodName);
4696                         position = function.loc.start.pos + movedFuncIdPos + movedFuncIdLen;
4697                      }
4698
4699                      if((methodAction == actionAttachMethod || methodAction == actionReattachMethod) && selected == classObject && moveAttached && 
4700                         function == def.function)
4701                      {
4702                         // In case of attaching methods in the _class, simply rename the method
4703                         f.Seek(function.loc.start.pos + movedFuncIdPos - position, current);
4704                         position = function.loc.start.pos + movedFuncIdPos;
4705                         f.DeleteBytes(movedFuncIdLen);
4706                         if(method.dataType.thisClass)
4707                            f.Printf("%s::", method.dataType.thisClass.string);
4708                         f.Puts(method.name);
4709                         position += movedFuncIdLen;
4710                      }
4711                      break;
4712                   }
4713                   default:
4714                      DeleteJunkBefore(f, def.loc.start.pos, &position);
4715                      if(def.type == memberAccessClassDef)
4716                      {
4717                         f.Printf("\n\n");
4718                         firstObject = false;
4719                         lastIsDecl = true;
4720                      }
4721                      else           
4722                      {
4723                         f.Printf("\n   ");
4724                         lastIsDecl = false;
4725                      }
4726                }
4727
4728                f.Seek(def.loc.end.pos - position, current);
4729                position = def.loc.end.pos;
4730             }
4731
4732             // Output attached methods
4733             if((methodAction == actionAttachMethod || methodAction == actionReattachMethod) && selected == classObject && !moveAttached)
4734             {
4735                DeleteJunkBefore(f, position, &position);
4736                f.Printf("\n   %s = %s;\n", method.name, function.declarator.symbol.string);
4737             }
4738             
4739             // ********** INSTANCES ***************
4740             for(; object; object = object.next)
4741             {
4742                if(!object.instCode)
4743                {
4744                   position = UpdateInstanceCode(f, position, regClass, object, &firstObject, &text, &textSize, movedFuncIdLen, movedFuncIdPos);
4745                }
4746             }
4747
4748             DeleteJunkBefore(f, position, &position);
4749
4750             // ****************** METHODS ***********************
4751             if(methodAction == actionDetachMethod && moveAttached && classObject == oClass)
4752             {
4753                // If detaching an instance method
4754                if(selected != classObject)
4755                {
4756                   int newLen = strlen(methodName);
4757
4758                   if(!text)
4759                      GetLocText(editBox, f, position, &function.loc, &text, &textSize, Max(newLen - movedFuncIdLen,0), 0);
4760                   // Tab selection left
4761                   {
4762                      int c;
4763                      for(c = 0; text[c]; )
4764                      {
4765                         int start = c, i;
4766                         for(i = 0; i<3 && text[c] == ' '; i++, c++);
4767                         memmove(text+start, text+start+i, textSize+1-start-i);
4768                         textSize -= i;
4769                         c -= i;
4770                         for(; text[c] && text[c] != '\n'; c++);
4771                         if(text[c]) c++;
4772                      }
4773                   }
4774
4775                   // Rename function
4776                   memmove(text + movedFuncIdPos + newLen, text + movedFuncIdPos + movedFuncIdLen, textSize - movedFuncIdPos - movedFuncIdLen + 1);
4777                   textSize += newLen - movedFuncIdLen;
4778                   memcpy(text + movedFuncIdPos, methodName, newLen);
4779
4780                   f.Printf("\n\n   ");
4781                   f.Puts(text);
4782                }
4783             }
4784
4785             if(methodAction == actionAddMethod && selected == classObject)
4786             {
4787                Method method = this.method;
4788
4789                if(!method.dataType)
4790                   method.dataType = ProcessTypeString(method.dataTypeString, false);
4791
4792                // ADDING METHOD HERE
4793                {
4794                   Type dataType = method.dataType;
4795                   Type returnType = dataType.returnType;
4796                   Type param;
4797                   Class moduleClass = eSystem_FindClass(this.privateModule, "Module");
4798
4799                   f.Printf("\n\n");
4800                   f.Printf("   ");
4801                   OutputType(f, returnType, false);
4802                
4803                   f.Printf(" ");
4804                   if(dataType.thisClass && !dataType.classObjectType)
4805                   {
4806                      if(dataType.thisClass.shortName)
4807                         f.Printf(dataType.thisClass.shortName);
4808                      else
4809                         f.Printf(dataType.thisClass.string);
4810                      f.Printf("::");
4811                   }
4812                   f.Printf(method.name);
4813                   f.Printf("(");
4814                   for(param = dataType.params.first; param; param = param.next)
4815                   {
4816                      OutputType(f, param, true);
4817                      if(param.next)
4818                         f.Printf(", ");
4819                   }
4820                   f.Printf(")\n");                  
4821                   f.Printf("   %c\n\n", OpenBracket);
4822
4823                   if(test._class._vTbl[method.vid] == moduleClass._vTbl[__ecereVMethodID___ecereNameSpace__ecere__com__Module_OnLoad]) // Temp Check for DefaultFunction
4824                   {
4825                      if(returnType && returnType.kind == classType && !strcmp(returnType._class.string, "bool"))
4826                         f.Printf("      return true;\n");
4827                      else if(returnType && returnType.kind != voidType)
4828                         f.Printf("      return 0;\n");
4829                   }
4830                   else
4831                   {
4832                      f.Printf("      ");
4833                      if(returnType.kind != voidType)
4834                         f.Printf("return ");
4835                      {
4836                         char * name = ((Specifier)classDef.baseSpecs->first).name;
4837                         Symbol _class = FindClass(name);
4838                         f.Printf("%s::%s(", (_class && _class.registered) ? _class.registered.name : name, method.name);
4839                      }
4840                      for(param = dataType.params.first; param; param = param.next)
4841                      {
4842                         if(param.prev) f.Printf(", ");
4843                         if(param.kind != voidType)
4844                            f.Printf(param.name);
4845                      }
4846                      f.Printf(");\n");
4847                   }
4848
4849                   f.Printf("   %c", CloseBracket);
4850                }
4851             }
4852
4853             DeleteJunkBefore(f, classDef.loc.end.pos-1, &position);
4854             f.Printf("\n");
4855
4856             delete test;
4857          }
4858
4859          updatingCode--;
4860          delete f;
4861
4862          ParseCode();
4863          delete text;
4864
4865          // TOFIX: Patch for a glitch where clicking at the end of the view seems one line off. No idea what could be going on?
4866          editBox.OnVScroll(setRange, editBox.scroll.y, 0);
4867       }
4868
4869       updatingCode--;
4870       codeModified = false;
4871       formModified = false;
4872       methodAction = 0;
4873       moveAttached = false;
4874       function = null;
4875       method = null;
4876    }
4877
4878    int FindMethod(char * methodName /*Method method*/, ClassFunction*functionPtr, Location propLoc)
4879    {
4880       int found = 0;
4881       ClassFunction function = null;
4882       if(methodName)
4883       {
4884          ObjectInfo object = this.selected;
4885          
4886          if(object && object == this.oClass)
4887          {
4888             ClassDefinition classDef = object.oClass.classDefinition;
4889             ClassDef def;
4890             if(classDef && classDef.definitions)
4891             {
4892                for(def = classDef.definitions->first; def; def = def.next)
4893                {
4894                   if(def.type == functionClassDef && def.function.declarator)
4895                   {
4896                      if(!strcmp(def.function.declarator.symbol.string, methodName))
4897                      {
4898                         function = def.function;
4899                         found = 1;
4900                         break;
4901                      }
4902                   }
4903                   else if(def.type == defaultPropertiesClassDef)
4904                   {
4905                      MemberInit propDef;
4906
4907                      for(propDef = def.defProperties->first; propDef; propDef = propDef.next)
4908                      {
4909                         Identifier ident = propDef.identifiers ? propDef.identifiers->first : null;
4910                         if(ident && !ident.next)
4911                         {
4912                            if(!strcmp(ident.string, methodName) && propDef.initializer && propDef.initializer.type == expInitializer && propDef.initializer.exp && propDef.initializer.exp.type == identifierExp)
4913                            {
4914                               found = 2;
4915                               if(propLoc != null)
4916                                  propLoc = propDef.loc;
4917                               if(functionPtr)
4918                               {
4919                                  ClassDefinition classDef = object.oClass.classDefinition;
4920                                  ClassDef def;
4921                                  if(classDef.definitions)
4922                                  {
4923                                     for(def = classDef.definitions->first; def; def = def.next)
4924                                     {
4925                                        if(def.type == functionClassDef)
4926                                        {
4927                                           if(!strcmp(def.function.declarator.symbol.string, propDef.initializer.exp.identifier.string))
4928                                           {
4929                                              function = def.function;
4930                                              break;
4931                                           }
4932                                        }
4933                                     }
4934                                     if(function) break;
4935                                  }
4936                               }
4937                               else
4938                                  break;
4939                            }
4940                         }
4941                      }
4942                   }
4943                }
4944             }
4945          }
4946          else if(object)
4947          {
4948             Instantiation inst = object.instCode;
4949
4950             // Check here to see if the method already exists, no need to call ModifyCode in that case
4951             if(inst && inst.members)
4952             {
4953                MembersInit members;
4954                for(members = inst.members->first; members; members = members.next)
4955                {
4956                   switch(members.type)
4957                   {
4958                      case dataMembersInit:
4959                      {
4960                         if(members.dataMembers)
4961                         {
4962                            MemberInit member;
4963                            for(member = members.dataMembers->first; member; member = member.next)
4964                            {
4965                               Identifier ident = member.identifiers ? member.identifiers->first : null;
4966                               if(ident && !ident.next)
4967                               {
4968                                  if(!strcmp(ident.string, methodName) && member.initializer && member.initializer.type == expInitializer && member.initializer.exp && member.initializer.exp.type == memberExp /*ExpIdentifier*/)
4969                                  {
4970                                     found = 2;
4971                                     if(propLoc != null)
4972                                        propLoc = member.loc;
4973                                     if(functionPtr)
4974                                     {
4975                                        ClassDefinition classDef = object.oClass.classDefinition;
4976                                        ClassDef def;
4977                                        if(classDef.definitions)
4978                                        {
4979                                           for(def = classDef.definitions->first; def; def = def.next)
4980                                           {
4981                                              if(def.type == functionClassDef)
4982                                              {
4983                                                 if(def.function.declarator && !strcmp(def.function.declarator.symbol.string, member.initializer.exp.identifier.string))
4984                                                 {
4985                                                    function = def.function;
4986                                                    break;
4987                                                 }
4988                                              }
4989                                           }
4990                                           if(function) break;
4991                                        }
4992                                        if(!function)
4993                                        {
4994                                           // TODO: Fix memory leak
4995                                           function = ClassFunction
4996                                           {
4997                                              declarator = Declarator { symbol = Symbol { string = CopyString(member.initializer.exp.member.member ? member.initializer.exp.member.member.string : "") } }
4998                                           };
4999                                        }
5000                                     }
5001                                     else
5002                                        break;
5003                                  }
5004                               }
5005                            }
5006                         }
5007                         break;
5008                      }
5009                      case methodMembersInit:
5010                      {
5011                         if(members.function.declarator && !strcmp(members.function.declarator.symbol.string, methodName))
5012                         {
5013                            function = members.function;
5014                            found = 1;
5015                         }
5016                         break;
5017                      }
5018                   }
5019                   if(function)
5020                      break;
5021                }
5022             }
5023          }
5024       }
5025       if(functionPtr) *functionPtr = function;
5026       return found;
5027    }
5028
5029    void GoToMethod(char * methodName /*Method method*/)
5030    {
5031       if(methodName)
5032       {
5033          ObjectInfo object = selected;
5034          EditBoxStream f { editBox = editBox };
5035          ClassFunction function = null;
5036          bool atChar = false;
5037          int indent = 6;
5038          EditLine l1, l2;
5039          int y1,y2, x1, x2;
5040          Location propLoc = { {0,0,-1} };
5041
5042          // GO TO THE METHOD
5043          if(FindMethod(methodName, &function, &propLoc) == 1 && object != this.oClass) indent = 9;
5044          if(function && function.body)
5045          {
5046             bool lfCount = 0;
5047             f.Seek(function.body.loc.start.pos+1, current);
5048             for(;;)
5049             {
5050                char ch;
5051                if(!f.Getc(&ch))
5052                   break;
5053                if(ch == '\n')
5054                {
5055                   if(lfCount)
5056                   {
5057                      f.Seek(-1, current);
5058                      break;
5059                   }
5060                   lfCount++;
5061                }
5062                else if(!isspace(ch))
5063                {
5064                   f.Seek(-1, current);
5065                   atChar = true;
5066                   break;
5067                }
5068             }
5069          }
5070          else if(propLoc.start.pos > -1)
5071          {
5072             f.Seek(propLoc.start.pos, current);
5073             atChar = true;
5074          }
5075          editBox.GetSelPos(&l1, &y1, &x1, &l2, &y2, &x2, false);
5076          delete f;
5077          if(function || propLoc.start.pos > -1)
5078          {
5079             editBox.SetSelPos(l1, y1, atChar ? x1 : indent, l2, y2, atChar ? x2 : indent);
5080             editBox.CenterOnCursor();
5081             SetState(normal, false, 0);
5082             Activate();
5083
5084             if(function && function.declarator && function.declarator.symbol && !function.declarator.symbol.type)
5085             {
5086                FreeClassFunction(function);
5087             }
5088          }
5089       }
5090    }
5091
5092    void FindCompatibleMethods(Method method, OldList compatible)
5093    {
5094       ClassDefinition classDef = this.oClass.classDefinition;
5095       if(classDef && classDef.definitions)
5096       {
5097          Class regClass { };
5098          Class baseClass = eSystem_FindClass(this.privateModule, ((Specifier)classDef.baseSpecs->first).name);
5099          ClassDef def;
5100          Class _class;
5101          Symbol classSym { };
5102          Symbol selectedClass;
5103          if(this.selected == this.oClass)
5104             selectedClass = classSym;
5105          else
5106             selectedClass = FindClass(this.selected.instance._class.name);
5107
5108          regClass.name = classDef._class.name;
5109          regClass.base = eSystem_FindClass(this.privateModule, ((Specifier)classDef.baseSpecs->first).name);
5110          for(def = classDef.definitions->first; def; def = def.next)
5111          {
5112             if(def.type == functionClassDef && def.function.declarator)
5113             {
5114                Method vMethod = eClass_FindMethod(baseClass, def.function.declarator.symbol.string, this.privateModule);
5115                if(!vMethod)
5116                   vMethod = eClass_FindMethod(this.selected.instance._class, def.function.declarator.symbol.string, this.privateModule);
5117                if(!vMethod)
5118                {
5119                   Type type = def.function.declarator.symbol.type;
5120                   if(CheckCompatibleMethod(method, type, regClass, this.selected == this.oClass, FindClass(this.selected.instance._class.name)))
5121                   {
5122                      compatible.Add(OldLink { data = def.function });
5123                   }
5124                }
5125             }
5126          }
5127
5128          if(this.oClass && this.oClass.instance)
5129          {
5130             classSym.registered = regClass;
5131             //classSym.registered = this.oClass.oClass;
5132
5133             for(_class = regClass.base; _class; _class = _class.base)
5134             {
5135                Method testMethod;
5136                for(testMethod = (Method)_class.methods.first; testMethod; testMethod = (Method)((BTNode)testMethod).next)
5137                {
5138                   // TODO: Understand why these functions popup in attach list
5139                   if(testMethod.type != virtualMethod /*&& testMethod.function != Window_OnGetString && testMethod.function != Window_OnGetDataFromString*/)
5140                   {
5141                      if(!testMethod.dataType)
5142                         testMethod.dataType = ProcessTypeString(testMethod.dataTypeString, false);
5143                         
5144                      //if(CheckCompatibleMethod(method, testMethod.dataType, &regClass, false, selectedClass)) // this.selected == this.oClass, selectedClass))
5145                      if(CheckCompatibleMethod(method, testMethod.dataType, this.oClass.instance._class, false, selectedClass)) // this.selected == this.oClass, selectedClass))
5146                      //if(CheckCompatibleMethod(method, testMethod.dataType, &regClass, this.selected == this.oClass, FindClass(this.oClass.oClass.name)))
5147                      {
5148                         // TODO: Fix memory leak, Figure out if it should be ClassFunction or FunctionDefinition
5149                         // ClassFunction function { };
5150                         FunctionDefinition function { };
5151
5152                         function.declarator = Declarator { };
5153                         function.declarator.symbol = Symbol { string = CopyString(testMethod.name) };
5154                         excludedSymbols.Add(function.declarator.symbol);
5155
5156                         compatible.Add(OldLink { data = function });
5157                      }
5158                   }
5159                }
5160             }
5161          }
5162          delete regClass;
5163          delete classSym;
5164       }
5165    }
5166
5167    void AddMethod(Method method)
5168    {
5169       if(method)
5170       {
5171          char methodName[1024];
5172          strcpy(methodName, method.name);
5173          if(!FindMethod(methodName, null, null))
5174          {
5175             methodAction = actionAddMethod;
5176             this.method = method;
5177             ModifyCode();
5178          }
5179          UpdateFormCode();         
5180          GoToMethod(methodName);
5181       }
5182    }
5183
5184    void DeleteMethod(ClassFunction function)
5185    {
5186       if(function)
5187       {
5188          methodAction = actionDeleteMethod;
5189          this.function = function;
5190          ModifyCode();
5191          UpdateFormCode(); 
5192
5193          Update(null);
5194       }
5195    }
5196
5197    void AttachMethod(Method method, ClassFunction function)
5198    {
5199       if(function)
5200       {
5201          // If it's an instance we'll ask if we want to move it inside...
5202          if(!function.attached.count && function.body)
5203          {
5204             // Find the function in the _class to check if it's a virtual function
5205             Class regClass = eSystem_FindClass(this.privateModule, ((Specifier)this.oClass.classDefinition.baseSpecs->first).name);
5206             Method method = eClass_FindMethod(regClass, function.declarator.symbol.string, this.privateModule);
5207             /*    LATER we'll need to check for public/virtual properties etc, for now only checked if virtual in base _class
5208             ClassDef def;
5209             for(def = this.classDefinition.first; def; def = def.next)
5210             {
5211                if(def.type == functionClassDef)
5212                {
5213                   if(def.function == function)
5214                      break;
5215                }
5216             }
5217             */
5218             if(!method || method.type != virtualMethod)
5219             {
5220                char title[1024];
5221                sprintf(title, $"Attach %s", function.declarator.symbol.string);
5222                if(MessageBox { type = yesNo, master = parent, text = title, contents = $"Method is unused. Move method inside instance?"}.Modal() == yes)
5223                {
5224                   moveAttached = true;
5225                }
5226             }
5227          }
5228
5229          methodAction = actionAttachMethod;
5230          this.method = method;
5231          this.function = function;
5232          ModifyCode();
5233          UpdateFormCode(); 
5234          Update(null);
5235       }
5236    }
5237
5238    void ReAttachMethod(Method method, ClassFunction function)
5239    {
5240       if(function)
5241       {
5242          // If it's an instance we'll ask if we want to move it inside...
5243          if(!function.attached.count && function.body)
5244          {
5245             // Find the function in the _class to check if it's a virtual function
5246             Class regClass = eSystem_FindClass(this.privateModule, ((Specifier)this.oClass.classDefinition.baseSpecs->first).name);
5247             Method method = eClass_FindMethod(regClass, function.declarator.symbol.string, this.privateModule);
5248             /*    LATER we'll need to check for public/virtual properties etc, for now only checked if virtual in base _class
5249             ClassDef def;
5250             for(def = this.classDefinition.first; def; def = def.next)
5251             {
5252                if(def.type == functionClassDef)
5253                {
5254                   if(def.function == function)
5255                      break;
5256                }
5257             }
5258             */
5259             if(!method || method.type != virtualMethod)
5260             {
5261                char title[1024];
5262                sprintf(title, $"Attach %s", function.declarator.symbol.string);
5263                if(MessageBox { type = yesNo, master = parent, text = title, 
5264                   contents = $"Method is unused. Move method inside instance?" }.Modal() == yes)
5265                {
5266                   moveAttached = true;
5267                }
5268             }
5269          }
5270
5271          methodAction = actionReattachMethod;
5272          this.method = method;
5273          this.function = function;
5274          ModifyCode();
5275          UpdateFormCode(); 
5276          Update(null);
5277       }
5278    }
5279
5280    void DetachMethod(Method method, ClassFunction function, int type)
5281    {
5282       bool result = true;
5283
5284       if(type == 1)
5285       {
5286          Window dialog
5287          {
5288             hasClose = true, borderStyle = sizable, minClientSize = { 300, 55 }, 
5289             master = sheet, text = $"Name detached method", background = formColor
5290          };
5291          Button cancelButton
5292          {
5293             dialog, anchor = { horz = 45, top = 30 }, size = { 80 }, text = $"Cancel", hotKey = escape,
5294             id = DialogResult::cancel, NotifyClicked = ButtonCloseDialog
5295          };
5296          Button okButton
5297          {
5298             dialog, anchor = { horz = -45, top = 30 }, size = { 80 }, text = $"OK", isDefault = true,
5299             id = DialogResult::ok, NotifyClicked = ButtonCloseDialog
5300          };
5301          EditBox nameBox
5302          {
5303             dialog, anchor = { left = 5, right = 5, top = 5 }
5304          };
5305          sprintf(methodName, "%s_%s", selected.name, method.name);
5306          nameBox.contents = methodName;
5307          incref nameBox;
5308          result = dialog.Modal() == ok;
5309          strcpy(methodName, nameBox.contents);
5310          delete nameBox;
5311       }
5312       if(result)
5313       {
5314          // If the method is not attached, move it outside
5315          if(type == 1)
5316          {
5317             // Add this class to the methodName
5318             char name[1024] = "";
5319
5320             if(this.selected != this.oClass && !method.dataType.thisClass)
5321             {
5322                strcat(name, this.selected.instance._class.name);
5323                strcat(name, "::");
5324                strcat(name, this.methodName);
5325                strcpy(this.methodName, name);
5326             }
5327             else if(method.dataType.thisClass && (this.selected == this.oClass || !eClass_IsDerived(this.oClass.instance._class, method.dataType.thisClass.registered)))
5328             {
5329                strcat(name, method.dataType.thisClass.string);
5330                strcat(name, "::");
5331                strcat(name, this.methodName);
5332                strcpy(this.methodName, name);
5333             }
5334             
5335             this.moveAttached = true;
5336          }
5337
5338          this.methodAction = actionDetachMethod;
5339          this.method = method;
5340          this.function = function;
5341          ModifyCode();
5342          UpdateFormCode(); 
5343          Update(null);
5344       }
5345    }
5346
5347    void AddObject(Instance instance, ObjectInfo * object)
5348    {
5349       int id;
5350       incref instance;
5351       //*object = _class.instances.Add(sizeof(ObjectInfo));
5352       *object = ObjectInfo { };
5353       oClass.instances.Insert((selected.oClass == selected) ? null : selected, *object);
5354       (*object).oClass = oClass;
5355       (*object).instance = instance;
5356       for(id = 1;; id++)
5357       {
5358          char name[1024];
5359          ObjectInfo check;
5360          sprintf(name, "%c%s%d", tolower(instance._class.name[0]), instance._class.name+1, id);
5361
5362          // if(strcmp(name, this.oClass.instance.name)) 
5363          
5364          {
5365             for(check = oClass.instances.first; check; check = check.next)
5366                if(!check.deleted && check.name && !strcmp(name, check.name)) 
5367                   break;
5368             if(!check)
5369             {
5370                (*object).name = CopyString(name);
5371                break;
5372             }
5373          }
5374       }            
5375       toolBox.controlClass = null;
5376
5377       ModifyCode();
5378
5379       //sheet.AddObject(*object, (*object).name, TypeData, true);
5380
5381       selected = *object;
5382    }
5383
5384    void EnsureUpToDate()
5385    {
5386       if(sheet && codeModified && parsing)
5387          ParseCode();
5388    }
5389
5390    void SelectObject(ObjectInfo object)
5391    {
5392       selected = object;
5393       oClass = object ? object.oClass : null;
5394       if(designer)
5395          designer.SelectObject(object, object ? object.instance : null);
5396    }
5397
5398    void SelectObjectFromDesigner(ObjectInfo object)
5399    {
5400       selected = object;
5401       sheet.SelectObject(object);
5402    }
5403
5404    void EnumerateObjects(Sheet sheet)
5405    {
5406       ObjectInfo oClass;
5407
5408       for(oClass = classes.first; oClass; oClass = oClass.next)
5409       {
5410          if(oClass.instance)
5411          {
5412             ObjectInfo object;
5413
5414             sheet.AddObject(oClass, oClass.name ? oClass.name : oClass.instance._class.name, typeClass, false);
5415             for(object = oClass.instances.first; object; object = object.next)
5416                sheet.AddObject(object, object.name ? object.name : object.instance._class.name, typeData, false);
5417          }
5418       }
5419       sheet.SelectObject(selected);
5420    }
5421
5422    void AddControl()
5423    {
5424       designer.AddObject();
5425    }
5426
5427    void DeleteObject(ObjectInfo object)
5428    {
5429       delete object.instance;
5430       object.deleted = true;
5431       object.modified = true;
5432       object.oClass.modified = true;
5433
5434       if(selected == object)
5435       {
5436          bool looped = false;
5437          ObjectInfo select = object;
5438
5439          for(;;)
5440          {            
5441             select = select.prev;
5442             if(!select) 
5443             {
5444                if(looped) break;
5445                select = object.oClass.instances.last;
5446                if(!select) break;
5447                looped = true;
5448             }
5449             if(!select.deleted)
5450                break;
5451          }
5452          sheet.SelectObject(select ? select : oClass);
5453       }
5454
5455       if(!object.instCode && object.oClass != object)
5456       {
5457          delete object.name;
5458          oClass.instances.Delete(object);
5459       }
5460
5461       if(sheet.codeEditor == this)
5462          sheet.DeleteObject(object);
5463    }
5464
5465    void RenameObject(ObjectInfo object, char * name)
5466    {
5467       bool valid = false;
5468
5469       // Validate the name:
5470       if(object != oClass && (!name || !name[0])) valid = true;   // What's this one again?
5471       else if(name[0] && (isalpha(name[0]) || name[0] == '_'))
5472       {
5473          int c;
5474          for(c = 0; name[c]; c++)
5475             if(!isalnum(name[c]) && name[c] != '_' && name[c] != '_')
5476                break;
5477          if(!name[c])
5478             valid = true;
5479       }
5480       if(valid)
5481       {
5482          delete object.name;
5483          object.name = (name && name[0]) ? CopyString(name) : null;
5484
5485          sheet.RenameObject(object, object.name ? object.name : object.instance._class.name);
5486       }
5487    }
5488
5489    void DesignerModifiedObject()
5490    {
5491       sheet.ListProperties(false);
5492       sheet.Update(null);
5493    }
5494
5495    void ListSubMembers(Type member)
5496    {
5497       Type subMember;
5498
5499       for(subMember = member.members.first; subMember; subMember = subMember.next)
5500       {
5501          if(subMember.name)
5502          {
5503             DataRow row = membersList.AddString(subMember.name);
5504             row.icon = icons[typeData];
5505          }
5506          else
5507          {
5508             ListSubMembers(subMember);
5509          }
5510       }
5511    }
5512
5513    void ListSubDataMembers(DataMember member, bool isPrivate)
5514    {
5515       DataMember subMember;
5516       for(subMember = member.members.first; subMember; subMember = subMember.next)
5517       {
5518          if((subMember.memberAccess == publicAccess && !isPrivate) || subMember._class.module == privateModule)
5519          {
5520             if(subMember.name)
5521             {
5522                DataRow row = membersList.AddString(subMember.name);
5523                BitmapResource bitmap = null;
5524                if(!subMember.dataType)
5525                   subMember.dataType = ProcessTypeString(subMember.dataTypeString, false);
5526             
5527                if(subMember.dataType && subMember.dataType.kind == classType && subMember.dataType._class)
5528                {
5529                   char * bitmapName = (char *)eClass_GetProperty(subMember.dataType._class.registered, "icon");
5530                   if(bitmapName)
5531                   {
5532                      bitmap = { bitmapName };
5533                      membersList.AddResource(bitmap);
5534                   }
5535                }
5536                row.icon = bitmap ? bitmap : icons[(subMember.memberAccess == publicAccess && !isPrivate) ? typeData : typeDataPrivate];
5537             }
5538             else
5539             {
5540                ListSubDataMembers(subMember, isPrivate || member.memberAccess == privateAccess);
5541             }
5542          }
5543       }
5544    }
5545
5546    void ListClassMembers(Class whatClass, bool methodsOnly)
5547    {
5548       Class _class;
5549       Class baseClass = eSystem_FindClass(this.privateModule, "class");
5550       bool isPrivate = false;
5551
5552       for(_class = whatClass; _class && _class.type != systemClass; _class = _class.base)
5553       {
5554          Method method, methodIt;
5555          DataMember member;
5556          DataMember memberIt;
5557
5558          for(methodIt = (Method)_class.methods.first; methodIt; methodIt = (Method)((BTNode)methodIt).next)
5559          {
5560             method = eClass_FindMethod(whatClass, methodIt.name, privateModule);
5561             if(methodIt.memberAccess == privateAccess && method && method.memberAccess == publicAccess)
5562                method = methodIt;
5563             if(method && method._class.type != systemClass && !eClass_FindMethod(baseClass, method.name, this.privateModule))
5564             {
5565                if(method.memberAccess == publicAccess || method._class.module == privateModule)
5566                {
5567                   DataRow row = membersList.FindString(method.name);
5568                   if(!row)
5569                   {
5570                      row = membersList.AddString(method.name);
5571
5572                      if(!method.dataType)
5573                         method.dataType = ProcessTypeString(method.dataTypeString, false);
5574
5575                      row.icon = icons[(method.type == virtualMethod && method.dataType && method.dataType.thisClass) ? typeEvent : ((method.memberAccess == publicAccess && !isPrivate) ? typeMethod : typeMethodPrivate)];
5576                   }
5577                }
5578             }
5579          }
5580
5581          if(!methodsOnly)
5582          {
5583             for(memberIt = _class.membersAndProperties.first; memberIt; memberIt = memberIt.next)
5584             {
5585                if(memberIt.name)
5586                {
5587                   if(memberIt.isProperty)
5588                   {
5589                      member = (DataMember)eClass_FindProperty(whatClass, memberIt.name, privateModule);
5590                      if(!member)
5591                         member = eClass_FindDataMember(whatClass, memberIt.name, privateModule, null, null);
5592                   }
5593                   else
5594                   {
5595                      member = eClass_FindDataMember(whatClass, memberIt.name, privateModule, null, null);
5596                      if(!member)
5597                         member = (DataMember)eClass_FindProperty(whatClass, memberIt.name, privateModule);
5598                   }
5599
5600                   if(memberIt.memberAccess == privateAccess && member && member.memberAccess == publicAccess)
5601                      member = memberIt;
5602                }
5603                else
5604                   member = memberIt;
5605
5606                if(member && (member.memberAccess == publicAccess || member._class.module == privateModule))
5607                {
5608                   if(member.isProperty)
5609                   {
5610                      Property prop = (Property) member;
5611                      if(!membersList.FindString(prop.name))
5612                      {
5613                         DataRow row = membersList.AddString(prop.name);
5614                         row.icon = icons[(member.memberAccess == publicAccess && !isPrivate) ? typeProperty : typePropertyPrivate];
5615                      }
5616                   }
5617                   else if(member.name && !membersList.FindString(member.name))
5618                   {
5619                      DataRow row = membersList.AddString(member.name);
5620                
5621                      BitmapResource bitmap = null;
5622                      if(!member.dataType)
5623                         member.dataType = ProcessTypeString(member.dataTypeString, false);
5624                
5625                      if(member.dataType && member.dataType.kind == classType && member.dataType._class)
5626                      {
5627                         char * bitmapName = (char *)eClass_GetProperty(member.dataType._class.registered, "icon");
5628                         if(bitmapName)
5629                         {
5630                            bitmap = { bitmapName };
5631                            membersList.AddResource(bitmap);
5632                         }
5633                      }
5634                      row.icon = bitmap ? bitmap : icons[(member.memberAccess == publicAccess && !isPrivate) ? typeData : typeDataPrivate];
5635                   }
5636                   else
5637                      ListSubDataMembers(member, member.memberAccess == privateAccess);
5638                }
5639             }
5640          }
5641          if(_class.inheritanceAccess == privateAccess)
5642          {
5643             isPrivate = true;
5644             if(_class.module != privateModule) break;
5645          }
5646       }
5647    }
5648
5649    void ListClassMembersMatch(Class whatClass, Type methodType)
5650    {
5651       Class _class;
5652       Class baseClass = eSystem_FindClass(this.privateModule, "class");
5653       bool isPrivate = false;
5654
5655       for(_class = whatClass; _class && _class.type != systemClass; _class = _class.base)
5656       {
5657          Method method;
5658          Property prop;
5659          DataMember member;
5660
5661          for(method = (Method)_class.methods.first; method; method = (Method)((BTNode)method).next)
5662          {
5663             if(method.memberAccess == publicAccess || method._class.module == privateModule)
5664             {
5665                if(method._class.type != systemClass && !eClass_FindMethod(baseClass, method.name, this.privateModule))
5666                {
5667                   if(!method.dataType)
5668                      method.dataType = ProcessTypeString(method.dataTypeString, false);
5669
5670                   if(MatchTypes(method.dataType, methodType, null, whatClass, /*null, */whatClass, false, true, false, false))
5671                   {
5672                      DataRow row = membersList.FindString(method.name);
5673                      if(!row)
5674                      {
5675                         row = membersList.AddString(method.name);
5676                         row.icon = icons[(method.type == virtualMethod && method.dataType.thisClass) ? typeEvent : ((method.memberAccess == publicAccess && !isPrivate) ? typeMethod : typeMethodPrivate)];
5677                      }
5678                   }
5679                }
5680             }
5681          }
5682          if(_class.inheritanceAccess == privateAccess)
5683          {
5684             isPrivate = true;
5685             if(_class.module != privateModule) break;
5686          }
5687       }
5688    }
5689
5690    void ListClassPropertiesAndVirtual(Class whatClass, String curString)
5691    {
5692       Class _class;
5693       bool isPrivate = false;
5694       for(_class = whatClass; _class /*&& _class.type != systemClass*/; _class = _class.base)
5695       {
5696          Method method;
5697          Property prop;
5698          DataMember member;
5699
5700          for(method = (Method)_class.methods.first; method; method = (Method)((BTNode)method).next)
5701          {
5702             if(method.type == virtualMethod)
5703             {
5704                if(method.memberAccess == publicAccess || method._class.module == privateModule)
5705                {
5706                   DataRow row = membersList.FindString(method.name);
5707                   if(!row)
5708                   {
5709                      row = membersList.AddString(method.name);
5710
5711                      if(!method.dataType)
5712                         method.dataType = ProcessTypeString(method.dataTypeString, false);
5713
5714                      row.icon = icons[method.dataType.thisClass ? typeEvent : ((method.memberAccess == publicAccess && !isPrivate) ? typeMethod : typeMethodPrivate)];
5715                   }
5716                }
5717             }
5718          }
5719
5720          for(member = _class.membersAndProperties.first; member; member = member.next)
5721          {
5722             if(member.memberAccess == publicAccess || member._class.module == privateModule)
5723             {
5724                if(member.isProperty)
5725                {
5726                   Property prop = (Property)member;
5727                   {
5728                      DataRow row = membersList.AddString(prop.name);
5729                      row.icon = icons[(member.memberAccess == publicAccess && !isPrivate) ? typeProperty : typePropertyPrivate];
5730                   }
5731                }
5732                else if(member.name && (!curString || strcmp(curString, member.name)))
5733                {
5734                   DataRow row = membersList.AddString(member.name);
5735                
5736                   BitmapResource bitmap = null;
5737                   if(!member.dataType)
5738                      member.dataType = ProcessTypeString(member.dataTypeString, false);
5739                
5740                   if(member.dataType && member.dataType.kind == classType && member.dataType._class)
5741                   {
5742                      char * bitmapName = (char *)eClass_GetProperty(member.dataType._class.registered, "icon");
5743                      if(bitmapName)
5744                      {
5745                         bitmap = { bitmapName };
5746                         membersList.AddResource(bitmap);
5747                      }
5748                   }
5749                   row.icon = bitmap ? bitmap : icons[(member.memberAccess == publicAccess && !isPrivate) ? typeData : typeDataPrivate];
5750                }
5751                else
5752                   ListSubDataMembers(member, member.memberAccess == privateAccess || isPrivate);
5753             }
5754          }
5755          if(_class.inheritanceAccess == privateAccess)
5756          {
5757             isPrivate = true;
5758             if(_class.module != privateModule) break;
5759          }
5760       }
5761    }
5762
5763    void ListMembers(Type type)
5764    {
5765       if(type && (type.kind == classType || type.kind == structType || type.kind == unionType))
5766       {
5767          Class _class;
5768          
5769          if(type.kind == classType)
5770          {
5771             if(type._class)
5772                ListClassMembers(type._class.registered, false);
5773          }
5774          else
5775          {
5776             Type member;
5777             for(member = type.members.first; member; member = member.next)
5778             {
5779                if(member.name)
5780                {
5781                   DataRow row = membersList.AddString(member.name);
5782                   row.icon = icons[typeData];
5783                }
5784                else if(member.kind == structType || member.kind == unionType)
5785                   ListSubMembers(member);
5786             }
5787          }
5788       }
5789    }
5790
5791    void ListModule(Module mainModule, int recurse, bool listClasses)
5792    {
5793       Module module;
5794       ListNameSpace(mainModule.application.systemNameSpace, 1, listClasses);
5795       ListNameSpace(mainModule.application.privateNameSpace, 1, listClasses);
5796       ListNameSpace(mainModule.application.publicNameSpace, 1, listClasses);
5797       for(module = mainModule.application.allModules.first; module; module = module.next)
5798       {
5799          if(ModuleVisibility(mainModule, module))
5800             ListNameSpace(module.publicNameSpace, recurse, listClasses);
5801       }
5802    }
5803
5804    void ListNameSpace(NameSpace nameSpace, int recurse, bool listClasses)
5805    {
5806       NameSpace * ns;
5807       BTNamedLink link;
5808
5809       if(listClasses)
5810       {
5811          for(link = (BTNamedLink)nameSpace.classes.first; link; link = (BTNamedLink)((BTNode)link).next)
5812          {
5813             Class _class = link.data;
5814             if(_class.type != systemClass && !_class.templateClass)  // Omit templatized classes
5815             {
5816                DataRow row = membersList.AddString(_class.name);
5817                row.icon = (_class.type == unitClass || _class.type == enumClass) ? icons[typeDataType] : icons[typeClass];
5818             }
5819          }
5820       }
5821
5822       for(link = (BTNamedLink)nameSpace.defines.first; link; link = (BTNamedLink)((BTNode)link).next )
5823       {
5824          DefinedExpression definedExp = link.data;
5825          DataRow row = membersList.AddString(link /*definedExp*/.name);
5826          row.icon = icons[typeData];
5827       }
5828
5829       for(link = (BTNamedLink)nameSpace.functions.first; link; link = (BTNamedLink)((BTNode)link).next)
5830       {
5831          GlobalFunction function = link.data;
5832          DataRow row = membersList.AddString(link /*function*/.name);
5833          row.icon = icons[typeMethod];
5834       }
5835
5836
5837       for(ns = (NameSpace *)nameSpace.nameSpaces.first; ns; ns = (NameSpace *)((BTNode)ns).next)
5838       {
5839          if(recurse != 2 && listClasses)
5840          {
5841             if(!membersList.FindString(ns->name))
5842             {
5843                DataRow row = membersList.AddString(ns->name);
5844                row.icon = icons[typeNameSpace];
5845             }
5846          }
5847
5848          if(recurse)
5849             ListNameSpace(ns, 2, listClasses);
5850       }
5851    }
5852
5853    void ListEnumValues(Class _class)
5854    {
5855       List<Class> classes { };
5856       for(; _class && _class.type == enumClass; _class = _class.base)
5857          classes.Insert(null, _class);
5858       for(_class : classes)
5859       {
5860          EnumClassData enumeration = (EnumClassData)_class.data;
5861          NamedLink item;
5862          for(item = enumeration.values.first; item; item = item.next)
5863          {
5864             DataRow row = membersList.AddString(item.name);
5865             row.icon = icons[typeEnumValue];
5866          }
5867       }
5868       delete classes;
5869    }
5870
5871    bool ListEnumsModule(Module mainModule, Type dest)
5872    {
5873       bool result = false;
5874       Module module;
5875       result |= ListEnums(mainModule.application.systemNameSpace, dest);
5876       result |= ListEnums(mainModule.application.privateNameSpace, dest);
5877       result |= ListEnums(mainModule.application.publicNameSpace, dest);
5878       for(module = mainModule.application.allModules.first; module; module = module.next)
5879       {
5880          if(ModuleVisibility(mainModule, module))
5881             result |= ListEnums(module.publicNameSpace, dest);
5882       }
5883       return result;
5884    }
5885
5886    void ListNameSpaceByString(Module mainModule, char * string)
5887    {
5888       NameSpace * nameSpace;
5889       Module module;
5890       nameSpace = FindNameSpace(mainModule.application.systemNameSpace, string);
5891       if(nameSpace) ListNameSpace(nameSpace, 0, true);
5892       nameSpace = FindNameSpace(mainModule.application.privateNameSpace, string);
5893       if(nameSpace) ListNameSpace(nameSpace, 0, true);
5894       nameSpace = FindNameSpace(mainModule.application.publicNameSpace, string);
5895       if(nameSpace) ListNameSpace(nameSpace, 0, true);
5896       for(module = mainModule.application.allModules.first; module; module = module.next)
5897       {
5898          if(ModuleVisibility(mainModule, module))
5899          {
5900             nameSpace = FindNameSpace(module.publicNameSpace, string);
5901             if(nameSpace) ListNameSpace(nameSpace, 0, true);
5902          }
5903       }
5904    }
5905
5906    bool ListEnums(NameSpace nameSpace, Type dest)
5907    {
5908       BTNamedLink link;
5909       bool result = false;
5910
5911       for(link = (BTNamedLink)nameSpace.classes.first; link; link = (BTNamedLink)((BTNode)link).next)
5912       {
5913          Class _class = link.data;
5914          if(_class.type == enumClass && (dest.kind != classType || ((!dest._class || !dest._class.registered || (dest._class.registered != _class && strcmp(dest._class.registered.dataTypeString, "char *"))) && !dest.classObjectType)) &&
5915             dest.kind != pointerType && dest.kind != ellipsisType)
5916          {
5917             OldList conversions { };
5918             Type type { };
5919             type.kind = classType;
5920             type._class = FindClass(_class.name);
5921             if(MatchTypes(type, dest, &conversions, null, null, true, false, false, false))
5922             {
5923                ListEnumValues(_class);
5924                result = true;
5925             }
5926             conversions.Free(null);
5927             delete type;
5928          }
5929       }
5930       for(nameSpace = (NameSpace *)nameSpace.nameSpaces.first; nameSpace != null; nameSpace = (NameSpace *)((BTNode)nameSpace).next)
5931       {
5932          result |= ListEnums(nameSpace, dest);
5933       }
5934       return result;
5935    }
5936
5937    NameSpace * FindNameSpace(NameSpace nameSpace, char * name)
5938    {
5939       int start = 0, c;
5940       char ch;
5941       for(c = 0; (ch = name[c]); c++)
5942       {
5943          if(ch == '.' || (ch == ':' && name[c+1] == ':'))
5944          {
5945             NameSpace * newSpace;
5946             char * spaceName = new char[c - start + 1];
5947             memcpy(spaceName, name + start, c - start);
5948             spaceName[c-start] = '\0';
5949             newSpace = (NameSpace *)nameSpace.nameSpaces.FindString(spaceName);
5950             delete spaceName;
5951             if(!newSpace)
5952                return null;
5953             nameSpace = newSpace;
5954             if(ch == ':') c++;
5955             start = c+1;
5956          }
5957       }
5958       if(c - start)
5959       {
5960          // name + start;
5961       }
5962       return (NameSpace *)nameSpace;
5963    }
5964
5965    void ListSymbols(Expression exp, bool enumOnly, char * string, Identifier realIdentifier)
5966    {
5967       bool listedEnums = false;
5968       Type destType = (exp && exp.destType && !exp.destType.truth) ? exp.destType : null;
5969       bool listClasses = true;
5970
5971       if(exp && (exp.type == identifierExp || exp.type == memberExp))
5972       {
5973          // TOCHECK: This memberExp check wasn't here... Some stuff isn't quite done
5974          Identifier id = (exp.type == memberExp) ? exp.member.member : exp.identifier;
5975          char * colons = id ? RSearchString(id.string, "::", strlen(id.string), true, false) : null;
5976
5977          if(exp.type == identifierExp)
5978             id = realIdentifier;
5979
5980          if(id && id._class && !id._class.name)
5981          {
5982             listClasses = false;
5983             SetThisClass(null);
5984          }
5985          else if(id && id._class && id._class.name)
5986          {
5987             if(id.classSym)
5988             {
5989                Class _class = id.classSym.registered;
5990                if(_class && _class.type == enumClass)
5991                {
5992                   ListEnumValues(_class);
5993                }
5994                else
5995                   ListClassMembers(id.classSym.registered, true);
5996                return;
5997             }
5998             return;
5999          }
6000          else if(id && colons)
6001          {
6002             ListNameSpaceByString(this.privateModule, id.string);
6003             return;
6004          }
6005       }
6006
6007       if(this.privateModule && destType && (destType.kind != pointerType || destType.type.kind != voidType) && destType.kind != ellipsisType)
6008       {
6009          listedEnums = ListEnumsModule(this.privateModule, destType);
6010       }
6011
6012       if(destType && destType.kind == classType && destType._class.registered && destType._class.registered.type == enumClass)
6013       {
6014          ListEnumValues(destType._class.registered);
6015
6016          if(insideClass)
6017             ListClassPropertiesAndVirtual(insideClass, null);
6018
6019          listedEnums = true;
6020       }
6021       else if(destType && destType.kind == enumType)
6022       {
6023          NamedLink value;
6024
6025          for(value = destType.members.first; value; value = value.next)
6026          {
6027             DataRow row = membersList.AddString(value.name);
6028             row.icon = icons[typeEnumValue];
6029          }
6030
6031          if(insideClass)
6032             ListClassPropertiesAndVirtual(insideClass, null);
6033
6034          listedEnums = true;
6035       }
6036       else if(insideClass && !enumOnly)
6037       {
6038          ListClassPropertiesAndVirtual(insideClass, string);
6039       }
6040
6041       if(listedEnums && string && string[0])
6042       {
6043          DataRow row = membersList.FindSubString(string);
6044          if(!row)
6045             listedEnums = false;      
6046       }
6047       
6048       if(!insideClass && exp && exp.destType && exp.destType.kind == functionType && GetThisClass())
6049       {
6050          ListClassMembersMatch(GetThisClass(), exp.destType);
6051       }
6052       else if(!insideClass && !enumOnly && !listedEnums)
6053       {
6054          Context ctx;
6055          Symbol symbol = null;
6056          {
6057             if(GetThisClass())
6058             { 
6059                ListClassMembers(GetThisClass(), false);
6060             }
6061
6062             for(ctx = listClasses ? GetCurrentContext() : GetTopContext(); ctx != GetTopContext().parent && !symbol; ctx = ctx.parent)
6063             {
6064                for(symbol = (Symbol)ctx.symbols.first; symbol; symbol = (Symbol)((BTNode)symbol).next)
6065                {
6066                   // Don't list enum values?
6067                   //if(symbol.type.kind != TypeEnum)
6068                   DataRow row = membersList.FindString(symbol.string);
6069                   if(!row)
6070                   {
6071                      if(GetBuildingEcereComModule() && symbol.type && symbol.type.kind == functionType && eSystem_FindFunction(privateModule, symbol.string))
6072                         continue;
6073                      row = membersList.AddString(symbol.string);
6074                      if(symbol.type && symbol.type.kind == functionType)
6075                         row.icon = icons[typeMethod];
6076                      else if(symbol.type && symbol.type.kind == enumType)
6077                      {
6078                         row.icon = icons[typeEnumValue];
6079                      }
6080                      else 
6081                      {
6082                         BitmapResource bitmap = null;
6083                         if(symbol.type && symbol.type.kind == classType && symbol.type._class && symbol.type._class)
6084                         {
6085                            char * bitmapName = (char *)eClass_GetProperty(symbol.type._class.registered, "icon");
6086                            if(bitmapName)
6087                            {
6088                               bitmap = { bitmapName };
6089                               membersList.AddResource(bitmap);
6090                            }
6091                         }
6092                         row.icon = bitmap ? bitmap : icons[typeData];
6093                      }
6094                   }
6095                }
6096
6097                if(listClasses)
6098                {
6099                   for(symbol = (Symbol)ctx.types.first; symbol; symbol = (Symbol)((BTNode)symbol).next)
6100                   {
6101                      DataRow row = membersList.FindString(symbol.string);
6102                      if(!row)
6103                      {
6104                         row = membersList.AddString(symbol.string);
6105                         if(symbol.type.kind == functionType)
6106                            row.icon = icons[typeMethod];
6107                         else if(symbol.type.kind == classType && (!symbol.type._class.registered || (symbol.type._class.registered.type != unitClass && symbol.type._class.registered.type != enumClass)))
6108                         {
6109                            row.icon = icons[typeClass];
6110                         }
6111                         else
6112                         {
6113                            row.icon = icons[typeDataType];
6114                         }
6115                      }
6116                   }
6117                }
6118             }
6119
6120             ListModule(this.privateModule, 1, listClasses);
6121             // TODO: Implement this with name space
6122             /*
6123             {
6124                GlobalData data;
6125                for(data = globalData.first; data; data = data.next)
6126                {
6127                   DataRow row = membersList.FindString(data.name);
6128                   if(!data.dataType)
6129                      data.dataType = ProcessTypeString(data.dataTypeString, false);
6130                   if(!row)
6131                   {
6132                      row = membersList.AddString(data.name);
6133
6134                      if(data.dataType && data.dataType.kind == TypeEnum)
6135                      {
6136                         row.icon = icons[typeEnumValue];
6137                      }
6138                      else 
6139                      {
6140                         BitmapResource bitmap = null;
6141                         if(data.dataType && data.dataType.kind == classType && data.dataType._class && data.dataType._class)
6142                         {
6143                            char * bitmapName = (char *)eClass_GetProperty(data.dataType._class.registered, "icon");
6144                            if(bitmapName)
6145                            {
6146                               bitmap = { bitmapName };
6147                               membersList.AddResource(bitmap);
6148                            }
6149                         }
6150                         row.icon = bitmap ? bitmap : icons[typeData];
6151                      }
6152                   }
6153                }
6154             }
6155             */
6156
6157             {
6158                DataRow row = membersList.AddString("Min");
6159                row.icon = icons[typeMethod];
6160
6161                row = membersList.AddString("Max");
6162                row.icon = icons[typeMethod];
6163
6164                row = membersList.AddString("Abs");
6165                row.icon = icons[typeMethod];
6166
6167                row = membersList.AddString("Sgn");
6168                row.icon = icons[typeMethod];
6169             }
6170          }
6171       }
6172    }
6173
6174    void OverrideVirtualFunction(ClassFunction function, Method method, Class _class, bool isInstance, bool extraIndent)
6175    {
6176       EditBoxStream f { editBox = editBox };
6177       uint position = 0;
6178       EditLine l1, l2;
6179       int x1,y1,x2,y2;
6180
6181       updatingCode = true;
6182
6183       if(!method.dataType)
6184          method.dataType = ProcessTypeString(method.dataTypeString, false);
6185
6186       DeleteJunkBefore(f, function.loc.start.pos, &position);
6187       f.DeleteBytes(function.loc.end.pos - function.loc.start.pos - 1);
6188
6189       // ADDING METHOD HERE
6190       {
6191          Type dataType = method.dataType;
6192          Type returnType = dataType.returnType;
6193          Type param;
6194          Class moduleClass = eSystem_FindClass(this.privateModule, "Module");
6195
6196          if(insideDef.prev)
6197              f.Printf("\n\n");
6198          else
6199             f.Printf("\n");
6200          if(extraIndent) f.Printf("   ");
6201          f.Printf("   ");
6202          OutputType(f, returnType, false);
6203
6204          f.Printf(" ");
6205          
6206          if(dataType.thisClass && !dataType.classObjectType && (!isInstance || !insideClass || !eClass_IsDerived(insideClass, dataType.thisClass.registered)))
6207          {
6208             if(dataType.thisClass.shortName)
6209                f.Printf(dataType.thisClass.shortName);
6210             else
6211                f.Printf(dataType.thisClass.string);
6212             f.Printf("::");
6213          }
6214          f.Printf(method.name);
6215          f.Printf("(");
6216          for(param = dataType.params.first; param; param = param.next)
6217          {
6218             // Decided not to write void...
6219             if(param.kind != voidType)
6220             {
6221                OutputType(f, param, true);
6222                if(param.next)
6223                   f.Printf(", ");
6224             }
6225          }
6226          f.Printf(")\n");                  
6227          if(extraIndent) f.Printf("   ");
6228          f.Printf("   %c\n", OpenBracket);
6229
6230          editBox.GetSelPos(&l1, &y1, &x1, &l2, &y2, &x2, false);
6231
6232          f.Printf("\n");
6233
6234          if(!_class || 
6235             (
6236                (isInstance ? _class : _class.base)._vTbl[method.vid] == moduleClass._vTbl[__ecereVMethodID___ecereNameSpace__ecere__com__Module_OnLoad] ||
6237                (isInstance ? _class : _class.base)._vTbl[method.vid] == DummyMethod)) // Temp Check for DefaultFunction
6238          {
6239             if(returnType && returnType.kind == classType && !strcmp(returnType._class.string, "bool"))
6240             {
6241                if(extraIndent) f.Printf("   ");
6242                f.Printf("      return true;\n");
6243             }
6244             else if(returnType && returnType.kind != voidType)
6245             {
6246                if(extraIndent) f.Printf("   ");
6247                f.Printf("      return 0;\n");
6248             }
6249          }
6250          else
6251          {
6252             if(extraIndent) f.Printf("   ");
6253             f.Printf("      ");
6254             if(returnType.kind != voidType)
6255                f.Printf("return ");
6256             f.Printf("%s::%s(", isInstance ? _class.name : _class.base.name, method.name);
6257             for(param = dataType.params.first; param; param = param.next)
6258             {
6259                if(param.prev) f.Printf(", ");
6260                if(param.kind != voidType)
6261                   f.Printf(param.name);
6262             }
6263             f.Printf(");\n");
6264          }
6265       }
6266
6267       if(extraIndent) f.Printf("   ");
6268       f.Printf("   %c", CloseBracket);
6269       // f.Printf("\n");
6270
6271       delete f;
6272
6273       if(extraIndent) { x1 += 3; x2 += 3; }
6274       editBox.SetSelPos(l1, y1, x1 + 6, l2, y2, x2 + 6);
6275
6276       this.updatingCode = false;
6277
6278    }
6279
6280    // Return false if we overrided a function and don't want to run params listing
6281    bool InvokeAutoComplete(bool enumOnly, int pointer, bool caretMove)
6282    {
6283       bool didOverride = false;
6284       EditLine line = editBox.line;
6285       char * text = line.text;
6286       int lineNum, charPos;
6287       Expression exp = null;
6288       EditLine l1, l2;
6289       int x1,y1, x2,y2;
6290       //Identifier id = null;
6291       Expression memberExp = null;
6292       Identifier realIdentifier = null;
6293
6294       if(!parsing) return true;
6295       if(!privateModule) return !didOverride;
6296
6297       insideFunction = null;
6298
6299       charPos = editBox.charPos + 1;
6300       if(!membersListShown)
6301       {
6302          EnsureUpToDate();
6303       }
6304
6305       editBox.GetSelPos(&l1, &y1, &x1, &l2, &y2, &x2, false);
6306       { 
6307          EditBoxStream f { editBox = editBox };
6308
6309          updatingCode = true;
6310          editBox.SetSelPos(l1, y1, x1, l2, y2, x2);
6311          for(;;)
6312          {
6313             char ch;
6314             if(!f.Seek(-1, current))
6315                break;
6316             f.Getc(&ch);
6317             if(!isspace(ch)) break;
6318             f.Seek(-1, current);
6319          }
6320          editBox.GetSelPos(&l1, &y1, &x1, &l2, &y2, &x2, false);
6321
6322          lineNum = editBox.lineNumber + 1;
6323          charPos = editBox.charPos + 1;
6324          delete f;
6325          updatingCode = false;
6326       }
6327
6328       if(!membersListShown)
6329       {
6330          memberExp = FindExpTree(ast, lineNum, charPos);
6331          if(memberExp && (memberExp.type == TypeKind::memberExp || memberExp.type == pointerExp) && !memberExp.addedThis)
6332          {
6333          }
6334          else if(!pointer)
6335          {
6336             editBox.GetSelPos(&l1, &y1, &x1, &l2, &y2, &x2, false);
6337             { 
6338                EditBoxStream f { editBox = editBox };
6339                char ch = 0;
6340
6341                updatingCode = true;
6342
6343                editBox.SetSelPos(l1, y1, x1, l2, y2, x2);
6344
6345                f.Getc(&ch);
6346                if(ch == '}' || ch == ',' || ch == ')')
6347                {
6348                   f.Seek(-1, current);
6349                   ch = ' ';
6350                }
6351                if(isspace(ch))
6352                {
6353                   for(;;)
6354                   {
6355                      char ch;
6356                      if(!f.Seek(-1, current))
6357                         break;
6358                      f.Getc(&ch);
6359                      if(!isspace(ch)) break;
6360                      f.Seek(-1, current);
6361                   }
6362                }
6363                else
6364                   f.Seek(-1, current);
6365
6366                editBox.GetSelPos(&l1, &y1, &x1, &l2, &y2, &x2, false);
6367
6368                lineNum = editBox.lineNumber + 1;
6369                charPos = editBox.charPos + 1;
6370                delete f;
6371                updatingCode = false;
6372             }
6373
6374             realIdentifier = FindCtxTree(ast, lineNum, charPos);
6375             exp = ctxInsideExp;
6376          }
6377       }
6378
6379       editBox.GetSelPos(&l1, &y1, &x1, &l2, &y2, &x2, false);
6380       lineNum = editBox.lineNumber + 1;
6381       charPos = editBox.charPos/* + 1*/;
6382
6383       {
6384          int rowCount;
6385          char tempString[1024];
6386          char * string = null;
6387          CodePosition idStart, idEnd;
6388
6389          if(membersListShown)
6390          {
6391             char * buffer = membersLine.text;
6392             int c;
6393             bool firstChar = true;
6394             int len = 0;
6395             string = tempString;
6396
6397             for(c = membersLoc.start.charPos; c<membersLoc.end.charPos; c++)
6398             {
6399                bool isSpace = (buffer[c] == ' ' || buffer[c] == '\t');
6400                if(!isSpace) firstChar = false;
6401                if(!firstChar)
6402                   string[len++] = buffer[c];
6403             }
6404             string[len] = 0;
6405          }
6406          else //if(realIdentifier)//if(id)
6407          {
6408             /*
6409             char * buffer = id.string;
6410             int c;
6411             bool firstChar = true;
6412             int len = 0;
6413             string = tempString;
6414             for(c = 0; c<= charPos - id.loc.start.charPos; c++)
6415             {
6416                bool isSpace = (buffer[c] == ' ' || buffer[c] == '\t');
6417                if(!isSpace) firstChar = false;
6418                if(!firstChar)
6419                   string[len++] = buffer[c];
6420             }
6421             string[len] = 0;
6422             */
6423             int x, y;
6424             int len = 0;
6425             EditLine editLine = editBox.line;
6426             bool firstChar = true;
6427             bool done = false;
6428
6429             string = tempString;
6430             for(y = lineNum-1; y >= 0; y--)
6431             {
6432                char * buffer = editLine.text;
6433                int lineCount = editLine.count;
6434                for(x = (y == lineNum-1) ? (Min(charPos, lineCount) - 1 ): lineCount-1; x >= 0; x--)
6435                {
6436                   bool isSpace = (buffer[x] == ' ' || buffer[x] == '\t');
6437                   if(!isSpace)
6438                   {
6439                      if(firstChar)
6440                      {
6441                         idEnd.charPos = x + 2;
6442                         idEnd.line = y + 1;
6443                      }
6444                      firstChar = false;
6445                   }
6446                   // TESTING THIS CODE HERE FOR NOT CONSIDERING bool when doing ctrl-space past it
6447                   else if(firstChar)
6448                   {
6449                      idEnd.charPos = x + 2;
6450                      idEnd.line = y + 1;
6451                      done = true;
6452                      break;
6453                   }
6454                   if(!firstChar)
6455                   {
6456                      if(!isalnum(buffer[x]) && buffer[x] != '_')
6457                      {
6458                         x++;
6459                         done = true;
6460                         break;
6461                      }
6462                      memmove(string+1, string, len++);
6463                      string[0] = buffer[x];
6464                   }
6465                }
6466
6467                //if(done || firstChar)
6468                if(done || !firstChar)
6469                   break;
6470                editLine = editLine.prev;
6471             }
6472             string[len] = 0;
6473             if(!strcmp(string, "case"))
6474             {
6475                idEnd.charPos += 4;
6476                x+=4;
6477                string[0] = '\0';
6478             }
6479             else if(!strcmp(string, "return"))
6480             {
6481                idEnd.charPos += 6;
6482                x+=6;
6483                string[0] = '\0';
6484             }
6485             else if(!strcmp(string, "delete"))
6486             {
6487                idEnd.charPos += 6;
6488                x+=6;
6489                string[0] = '\0';
6490             }
6491             else if(!strcmp(string, "new"))
6492             {
6493                idEnd.charPos += 3;
6494                x+=3;
6495                string[0] = '\0';
6496             }
6497             else if(!strcmp(string, "renew"))
6498             {
6499                idEnd.charPos +=5;
6500                x+=5;
6501                string[0] = '\0';
6502             }
6503             if(x < 0) x = 0;
6504
6505             idStart.charPos = x + 1;
6506             idStart.line = y + 1;
6507          }
6508
6509          if(!membersListShown)
6510          {
6511             membersList.Clear();
6512             if(memberExp && (memberExp.type == ExpressionType::memberExp || memberExp.type == pointerExp) && !memberExp.addedThis)
6513             {
6514                Type type = memberExp.member.exp.expType;
6515                if(pointer == 2 && type)
6516                {
6517                   if(type.kind == pointerType || type.kind == arrayType)
6518                      type = type.type;
6519                   /*else
6520                      type = null;*/
6521                }
6522                ListMembers(type);
6523             }
6524             else if(!pointer)
6525             {
6526                ListSymbols(exp, enumOnly, string, realIdentifier);
6527             }
6528             membersList.Sort(null, 1);
6529          }
6530
6531          if(insideFunction)
6532          {
6533             // Virtual function override
6534             Identifier id = GetDeclId(insideFunction.declarator);
6535             char * string = id ? id.string : null;
6536
6537             Method method = eClass_FindMethod(GetThisClass(), string, this.privateModule);
6538             if(method)
6539             {
6540                if(method.type != virtualMethod || (!insideInstance && method._class == GetThisClass()))
6541                   insideFunction = null;
6542                else
6543                {
6544                   OverrideVirtualFunction(insideFunction, method, GetThisClass(), insideInstance, insideInstance && insideClass);
6545                   didOverride = true;
6546                }
6547             }
6548          }
6549          if(!didOverride) //insideFunction)
6550          {
6551             rowCount = membersList.rowCount;
6552             if(rowCount)
6553             {
6554                DataRow row = string ? membersList.FindSubString(string) : null;
6555                if(row && !membersList.FindSubStringAfter(row, string) && !caretMove)
6556                {
6557                   char * newString = row.string;
6558                   if(!membersListShown)
6559                   {
6560                      membersLoc.start.line = idStart.line-1;
6561                      membersLoc.start.charPos = idStart.charPos-1;
6562                      //membersLoc.end = membersLoc.start;
6563                       membersLoc.end.charPos = idEnd.charPos-1;
6564                       membersLoc.end.line = idEnd.line-1;
6565                      //membersLoc.end.charPos = idStart.charPos + strlen(string)-1; //end.charPos-1;
6566                      //membersLoc.end.charPos = idStart.charPos + strlen(string)-1; //end.charPos-1;
6567                      membersLine = line;
6568                   }
6569                   else
6570                   {
6571                      membersList.Destroy(0);
6572                      membersListShown = false;
6573                   }
6574
6575                   editBox.GoToPosition(membersLine, membersLoc.start.line, membersLoc.start.charPos);
6576                   editBox.Delete(
6577                      line, membersLoc.start.line, membersLoc.start.charPos,
6578                      line, membersLoc.end.line, membersLoc.end.charPos);
6579                   editBox.PutS(newString);
6580                }
6581                else
6582                {
6583                   if(!row)
6584                   {
6585                      row = membersList.FindSubStringi(string);
6586                      if(row)
6587                         membersList.currentRow = row;
6588                      membersList.currentRow.selected = false;
6589                   }
6590                   else
6591                      membersList.currentRow = row;
6592
6593                   if(!membersListShown)
6594                   {
6595                      Point caret;
6596
6597                      // TESTING THESE ADDITIONS TO THE IF SO THAT CARET ISNT MOVED IF NOT ON TOP OF A WORD
6598                      if(string && string[0] && lineNum == idStart.line && charPos >= idStart.charPos-1 && charPos <= idEnd.charPos-1)
6599                         editBox.SetSelPos(l1, y1, idStart.charPos-1, l2, y2, idStart.charPos-1);
6600                      editBox.GetCaretPosition(caret);
6601                      editBox.SetSelPos(l1, y1, x1, l2, y2, x2);
6602                
6603                      membersList.master = this;
6604
6605                      caret.y += editBox.GetCaretSize();
6606                      caret.x -= 20;
6607                      membersList.Create();
6608
6609                      {
6610                         int x = caret.x + editBox.absPosition.x - app.desktop.absPosition.x - editBox.scroll.x;
6611                         int y = caret.y + editBox.absPosition.y - app.desktop.absPosition.y - editBox.scroll.y;
6612                         Window parent = membersList.parent;
6613
6614                         if(!paramsAbove && (paramsShown || y + membersList.size.h > parent.clientSize.h))
6615                         {
6616                            y -= editBox.GetCaretSize() + membersList.size.h;
6617                            membersAbove = true;
6618                         }
6619                         else
6620                            membersAbove = false;
6621
6622                         membersList.position = { x, y };
6623                      }
6624
6625                      membersLine = l1;
6626                      membersLoc.start.line = lineNum - 1;
6627
6628                      if(string && string[0])
6629                      {
6630                         membersLoc.start.charPos = idStart.charPos-1;
6631                         membersLoc.end = membersLoc.start;
6632                         //membersLoc.end.charPos = id.loc.end.charPos-1;
6633                         membersLoc.end.charPos = idStart.charPos + strlen(string)-1; //end.charPos-1;
6634                      }
6635                      else
6636                      {
6637                         membersLoc.start.charPos = charPos;
6638                         membersLoc.end = membersLoc.start;
6639                         membersLoc.end.charPos = charPos;
6640                      }
6641                      membersListShown = true;
6642
6643                      // Hack to keep caret shown
6644                      editBox.GetCaretPosition(caret);
6645                      editBox.SetCaret(caret.x, caret.y, editBox.GetCaretSize());
6646                   }
6647                   if(row)
6648                      membersList.SetScrollPosition(0, row.index * membersList.rowHeight);
6649                }            
6650             }
6651          }
6652       }
6653
6654       SetCurrentContext(globalContext);
6655       SetThisClass(null);
6656
6657       return !didOverride;
6658    }
6659
6660    void InvokeParameters(bool exact, bool reposition, bool caretMove)
6661    {
6662       EditLine line = editBox.line;
6663       char * text = line.text;
6664       int lineNum, charPos;
6665       Expression exp = null;
6666       EditLine l1, l2;
6667       int x1,y1, x2,y2;
6668
6669       if(!parsing) return;
6670
6671       charPos = editBox.charPos + 1;
6672       EnsureUpToDate();
6673
6674       editBox.GetSelPos(&l1, &y1, &x1, &l2, &y2, &x2, false);
6675       { 
6676          EditBoxStream f { editBox = editBox };
6677          char ch;
6678
6679          updatingCode = true;
6680          editBox.SetSelPos(l1, y1, x1, l2, y2, x2);
6681
6682          f.Getc(&ch);
6683          if(ch == '}' || ch == ',' || ch == ')')
6684          {
6685             f.Seek(-1, current);
6686             ch = ' ';
6687          }
6688          if(isspace(ch))
6689          {
6690             for(;;)
6691             {
6692                char ch;
6693                if(!f.Seek(-1, current))
6694                   break;
6695                f.Getc(&ch);
6696                if(!isspace(ch)) break;
6697                f.Seek(-1, current);
6698             }
6699          }
6700          else
6701             f.Seek(-1, current);
6702
6703          editBox.GetSelPos(&l1, &y1, &x1, &l2, &y2, &x2, false);
6704
6705          lineNum = editBox.lineNumber + 1;
6706          charPos = editBox.charPos + 1;
6707          delete f;
6708          updatingCode = false;
6709       }
6710       
6711       charPos = Min(charPos, l1.count + 1);
6712       if(!caretMove)
6713          FindParamsTree(ast, lineNum, charPos);
6714
6715       // Not sure about this == ExpCall... paramsInsideExp doesn't seem to necessarily be a ExpCall
6716       if(exact && ((::functionType && paramsInsideExp.type == callExp && paramsInsideExp.call.exp.loc.end.charPos != charPos-1) /*|| instanceType*/))
6717       {
6718          ::functionType = null;
6719          ::instanceType = null;
6720       }
6721
6722       //if((::functionType || ::instanceType) && (!paramsShown || insideExp != functionExp || ::paramsID != this.paramsID))
6723       if((::functionType || ::instanceType) && (!paramsShown || true /*paramsInsideExp.destType != functionExp.destType */|| ::paramsID != this.paramsID))
6724       {
6725
6726          int x, y;
6727          Window parent = paramsList.parent;
6728
6729          if(this.functionType != ::functionType || this.instanceType != ::instanceType)
6730             reposition = false;
6731
6732          if(!this.paramsShown || reposition || paramsInsideExp != functionExp || ::instanceType) // Added instanceType here, otherwise instance popups never reposition... 
6733                                                                                                           // ( Dummy exp: always ends up with same memory)
6734          {
6735             editBox.GetSelPos(&l1, &y1, &x1, &l2, &y2, &x2, false);
6736             editBox.GetCaretPosition(paramsPosition);
6737             this.paramsPosition.y += editBox.GetCaretSize();
6738          }
6739
6740          FreeType(this.functionType);
6741          FreeType(this.instanceType);
6742
6743          this.functionType = ::functionType;
6744          this.instanceType = ::instanceType;
6745
6746          if(this.functionType) this.functionType.refCount++;
6747          if(this.instanceType) this.instanceType.refCount++;
6748
6749          this.paramsID = ::paramsID;
6750          functionExp = paramsInsideExp;
6751
6752          paramsList.master = this;
6753
6754          paramsList.Create();
6755
6756          x = paramsPosition.x + editBox.absPosition.x - app.desktop.absPosition.x - editBox.scroll.x;
6757          y = paramsPosition.y + editBox.absPosition.y - app.desktop.absPosition.y - editBox.scroll.y;
6758
6759          if(!this.membersAbove && ( this.membersListShown || y + paramsList.size.h > parent.clientSize.h) )
6760          {
6761             y -= editBox.GetCaretSize() + paramsList.clientSize.h;
6762             paramsAbove = true;
6763          }
6764          else
6765             paramsAbove = false;
6766          if(x + paramsList.size.w > parent.clientSize.w)
6767          {
6768             x = parent.clientSize.w - paramsList.size.w;
6769             if(x < 0) x = 0;
6770          }
6771
6772          paramsList.position = { x, y };
6773
6774          // Hack to keep caret shown
6775          {
6776             Point caret;
6777             editBox.GetCaretPosition(caret);
6778             editBox.SetCaret(caret.x, caret.y, editBox.GetCaretSize());
6779          }
6780
6781          this.paramsShown = true;
6782       }
6783       else if((!::functionType && !::instanceType) || reposition)
6784       {
6785          paramsList.Destroy(0);
6786          paramsShown = false;
6787
6788          FreeType(this.functionType);
6789          FreeType(this.instanceType);
6790          this.functionType = null;
6791          this.instanceType = null;
6792          this.paramsID = -1;
6793       }
6794
6795       SetCurrentContext(globalContext);
6796       SetThisClass(null);
6797    }
6798
6799    bool ViewDesigner()
6800    {
6801       if(designer)
6802       {
6803          designer.visible = true;
6804          designer.Activate();
6805       }
6806       return true;
6807    }
6808 };
6809
6810 CodeEditor NewCodeEditor(Window parent, WindowState state, bool modified)
6811 {
6812    CodeEditor document { state = state, parent = parent, modifiedDocument = modified };
6813    document.Create();
6814    return document;
6815 }