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