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