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