ide:Project/Makefile: added realclean feature making use of realclean makefile target...
[sdk] / ide / src / project / ProjectView.ec
1 import "ide"
2
3 import "FileSystemIterator"
4
5 class ImportFolderFSI : NormalFileSystemIterator
6 {
7    ProjectView projectView;
8    Array<ProjectNode> stack { };
9
10    bool OnFolder(char * folderPath)
11    {
12       char name[MAX_LOCATION];
13       ProjectNode parentNode = stack.lastIterator.data;
14       ProjectNode folder;
15       GetLastDirectory(folderPath, name);
16       folder = parentNode.FindSpecial(name, false, true, true);
17       if(!folder)
18          folder = projectView.NewFolder(parentNode, name, false);
19       stack.Add(folder);
20       return true;
21    }
22
23    void OutFolder(char * folderPath, bool isRoot)
24    {
25       stack.lastIterator.Remove(); //stack.Remove();
26    }
27
28    bool OnFile(char * filePath)
29    {
30       ProjectNode parentNode = stack.lastIterator.data;
31       projectView.AddFile(parentNode, filePath, parentNode.isInResources, false);
32       return true;
33    }
34 }
35
36 static Array<FileFilter> fileFilters
37 { [
38    { $"eC/C/C++ Files (*.ec, *.eh, *.c, *.cpp, *.cc, *.cxx, *.h, *.hpp, *.hh, *.hxx)", "ec, eh, c, cpp, cc, cxx, h, hpp, hh, hxx" },
39    { $"eC/C/C++ Source Files (*.ec, *.c, *.cpp, *.cc, *.cxx)", "ec, eh, c, cpp, cc, cxx" },
40    { $"Header Files for eC/C/C++ (*.eh, *.h, *.hpp, *.hh, *.hxx)", "eh, h, hpp, hh, hxx" },
41    { $"All files", null }
42 ] };
43
44 static Array<FileFilter> resourceFilters
45 { [
46    { $"Image Files (*.jpg, *.jpeg, *.bmp, *.pcx, *.png,*.gif)", "jpg, jpeg, bmp, pcx, png, gif" },
47    { $"3D Studio Model Files (*.3ds)", "3ds" },
48    { $"Translations (*.mo)", "mo" },
49    { $"All files", null }
50 ] };
51
52 static Array<FileFilter> projectFilters
53 { [
54    { $"Project Files (*.epj)", ProjectExtension },
55    { $"Workspace Files (*.ews)", WorkspaceExtension }
56 ] };
57
58 static Array<FileType> projectTypes
59 { [
60    { $"Ecere IDE Project", ProjectExtension },
61    { $"Ecere IDE Workspace", WorkspaceExtension }
62 ] };
63
64 static char * iconNames[] = 
65 {
66    "<:ecere>mimeTypes/file.png",                   /*genFile*/
67    "<:ecere>mimeTypes/textEcereWorkspace.png",     /*ewsFile*/
68    "<:ecere>mimeTypes/textEcereProject.png",       /*epjFile*/
69    "<:ecere>places/folder.png",                    /*folder*/
70    "<:ecere>status/folderOpen.png",                /*openFolder*/
71    "<:ecere>mimeTypes/textEcereSource.png",        /*ecFile*/
72    "<:ecere>mimeTypes/textEcereHeader.png",        /*ehFile*/
73    "<:ecere>mimeTypes/textCSource.png",            /*cFile*/
74    "<:ecere>mimeTypes/textCHeader.png",            /*hFile*/
75    "<:ecere>mimeTypes/textC++Source.png",          /*cppFile*/
76    "<:ecere>mimeTypes/textC++Header.png",          /*hppFile*/
77    "<:ecere>mimeTypes/text.png",                   /*textFile*/
78    "<:ecere>mimeTypes/textHyperTextMarkup.png",    /*webFile*/
79    "<:ecere>mimeTypes/image.png",                  /*pictureFile*/
80    "<:ecere>status/audioVolumeHigh.png",           /*soundFile*/
81    "<:ecere>mimeTypes/package.png",                /*archiveFile*/
82    "<:ecere>mimeTypes/packageSoftware.png",        /*packageFile*/
83    "<:ecere>mimeTypes/packageOpticalDisc.png",     /*opticalMediaImageFile*/
84    "<:ecere>mimeTypes/file.png"                    /*mFile*/ //TODO: create icon for mfile
85 };
86
87 enum PrepareMakefileMethod { normal, force, forceExists };
88
89 enum BuildType { build, rebuild, relink, run, start, restart };
90 enum BuildState
91 {
92    none, buildingMainProject, buildingSecondaryProject, compilingFile;
93
94    property bool { get { return this != none; } }
95    //property bool actualBuild { get { return this == buildingMainProject || this == buildingSecondaryProject;  } }
96 };
97
98 class ProjectView : Window
99 {
100    isDocument = true;
101    //hasMinimize = true;
102    hasClose = true;
103    borderStyle = sizable;
104    hasHorzScroll = true;
105    hasVertScroll = true;
106    background = white;
107    size = { 300 };
108    anchor = Anchor { left = 0, top = 0, bottom = 0 };
109    menu = Menu { };
110    
111    //hasMinimize = true;
112    saveDialog = projectFileDialog;
113    
114    DataRow resourceRow;
115    BuildState buildInProgress;
116    BitmapResource icons[NodeIcons];
117    Project project;
118    Workspace workspace;
119    property Workspace workspace
120    {
121       set
122       {
123          if(workspace)
124          {
125             for(prj : workspace.projects)
126             {
127                DeleteNode(prj.topNode);
128             }
129             workspace.projects.Free();
130             ide.debugger.CleanUp();
131          }
132          workspace = value;
133          if(workspace)
134          {
135             fileDialog.currentDirectory = workspace.workspaceDir;
136             resourceFileDialog.currentDirectory = workspace.workspaceDir;
137             for(prj : workspace.projects)
138                AddNode(prj.topNode, null);
139             ide.statusBar.text = $"Generating Makefile & Dependencies...";
140             app.UpdateDisplay();
141             for(prj : workspace.projects)
142                prj.ModifiedAllConfigs(true, false, false, false);
143             ide.statusBar.text = $"Initializing Debugger"; app.UpdateDisplay();
144             ide.statusBar.text = null;
145             app.UpdateDisplay();
146          }
147       }
148       get { return workspace; }
149    }
150    
151    bool drawingInProjectSettingsDialog;
152    bool drawingInProjectSettingsDialogHeader;
153    ProjectSettings projectSettingsDialog;
154
155    bool stopBuild;
156
157    ProjectView()
158    {
159       NodeIcons c;
160       for(c = 0; c < NodeIcons::enumSize; c++)
161       {
162          icons[c] = BitmapResource { iconNames[c], alphaBlend = true };
163          AddResource(icons[c]);
164       }
165       fileList.AddField(DataField { dataType = class(ProjectNode), freeData = false, userData = this });
166    }
167
168    ~ProjectView()
169    {
170       DebugStop();
171       ide.DestroyTemporaryProjectDir();
172       if(project)
173       {
174          workspace.Free();
175          delete workspace;
176       }
177    }
178
179    ListBox fileList
180    {
181       multiSelect = true, fullRowSelect = false, hasVertScroll = true, hasHorzScroll = true;
182       borderStyle = deep, parent = this, collapseControl = true, treeBranches = true;
183       anchor = Anchor { left = 0, right = 0, top = 0 , bottom = 0 };
184
185       background = projectViewBackground;
186       foreground = projectViewText;
187       selectionColor = selectionColor, selectionText = selectionText;
188       stippleColor = skyBlue;
189
190       bool OnActivate(bool active, Window previous, bool * goOnWithActivation, bool direct)
191       {
192          if(!active) Update(null);
193          return ListBox::OnActivate(active, previous, goOnWithActivation, direct);
194       }
195       
196       bool NotifyDoubleClick(ListBox listBox, int x, int y, Modifiers mods)
197       {
198          // Prevent the double click from reactivating the project view (returns false if we opened something)
199          return !OpenSelectedNodes();
200       }
201
202       bool NotifyRightClick(ListBox listBox, int x, int y, Modifiers mods)
203       {
204          DataRow row = listBox.currentRow;
205          if(row)
206          {
207             ProjectNode node = (ProjectNode)row.tag;
208             if(node.type == NodeTypes::project || node.type == resources || node.type == file || node.type == folder)
209             {
210                bool buildMenuUnavailable = buildInProgress;
211                PopupMenu popupMenu;
212                Menu popupContent { };
213                
214                if(node.type == NodeTypes::project)
215                {
216                   //if(node == ((Project)workspace.projects.first).topNode)
217                   {
218                      MenuItem { popupContent, $"Build", b, NotifySelect = ProjectBuild }.disabled = buildMenuUnavailable;
219                      MenuItem { popupContent, $"Relink", l, NotifySelect = ProjectLink }.disabled = buildMenuUnavailable;
220                      MenuItem { popupContent, $"Rebuild", r, NotifySelect = ProjectRebuild }.disabled = buildMenuUnavailable;
221                      MenuItem { popupContent, $"Clean", c, NotifySelect = ProjectClean }.disabled = buildMenuUnavailable;
222                      MenuItem { popupContent, $"Real Clean", d, NotifySelect = ProjectRealClean }.disabled = buildMenuUnavailable;
223                      MenuItem { popupContent, $"Regenerate Makefile", m, NotifySelect = ProjectRegenerate }.disabled = buildMenuUnavailable;
224                      MenuDivider { popupContent };
225                   }
226                   MenuItem { popupContent, $"New File...", l, Key { l, ctrl = true }, NotifySelect = ProjectNewFile };
227                   MenuItem { popupContent, $"New Folder...", n, Key { f, ctrl = true }, NotifySelect = ProjectNewFolder };
228                   MenuItem { popupContent, $"Import Folder...", i, NotifySelect = ProjectImportFolder };
229                   MenuItem { popupContent, $"Add Files to Project...", f, NotifySelect = ProjectAddFiles };
230                   MenuDivider { popupContent };
231                   MenuItem { popupContent, $"Add New Form...", o, NotifySelect = ProjectAddNewForm };
232                   // MenuItem { popupContent, "Add New Behavior Graph...", g, NotifySelect = ProjectAddNewGraph };
233                   MenuDivider { popupContent };
234                   if(node != ((Project)workspace.projects.first).topNode)
235                   {
236                      MenuItem { popupContent, $"Remove project from workspace", r, NotifySelect = ProjectRemove }.disabled = buildMenuUnavailable;
237                      MenuDivider { popupContent };
238                   }
239                   MenuItem { popupContent, $"Active Configuration...", s, Key { f5, alt = true } , NotifySelect = MenuConfig };
240                   MenuItem { popupContent, $"Settings...", s, Key { f7, alt = true } , NotifySelect = MenuSettings };
241                   MenuDivider { popupContent };
242                   MenuItem { popupContent, $"Browse Folder", w, NotifySelect = MenuBrowseFolder };
243                   MenuDivider { popupContent };
244                   MenuItem { popupContent, $"Save", v, Key { s, ctrl = true }, NotifySelect = ProjectSave }.disabled = !node.modified;
245                   MenuDivider { popupContent };
246                   MenuItem { popupContent, $"Properties...", p, Key { enter, alt = true }, NotifySelect = FileProperties };
247                }
248                else if(node.type == resources)
249                {
250                   MenuItem { popupContent, $"New File...", l, Key { l, ctrl = true }, NotifySelect = ProjectNewFile };
251                   MenuItem { popupContent, $"New Folder...", n, Key { f, ctrl = true }, NotifySelect = ProjectNewFolder };
252                   MenuItem { popupContent, $"Import Folder...", i, NotifySelect = ProjectImportFolder };
253                   MenuItem { popupContent, $"Add Resources to Project...", f, NotifySelect = ResourcesAddFiles };
254                   MenuItem { popupContent, $"Browse Folder", w, NotifySelect = MenuBrowseFolder };
255                   MenuDivider { popupContent };
256                   MenuItem { popupContent, $"Settings...", s, Key { f7, alt = true } , NotifySelect = MenuSettings };
257                   MenuItem { popupContent, $"Properties...", p, Key { enter, alt = true }, NotifySelect = FileProperties };
258                }
259                else if(node.type == file)
260                {
261                   MenuItem { popupContent, $"Open", o, NotifySelect = FileOpenFile };
262                   MenuItem { popupContent, $"Compile", c, Key { f7, ctrl = true}, NotifySelect = FileCompile }.disabled = buildMenuUnavailable;
263                   MenuDivider { popupContent };
264                   MenuItem { popupContent, $"Remove", r, NotifySelect = FileRemoveFile };
265                   MenuDivider { popupContent };
266                   MenuItem { popupContent, $"Browse Folder", w, NotifySelect = MenuBrowseFolder };
267                   MenuDivider { popupContent };
268                   MenuItem { popupContent, $"Settings...", s, Key { f7, alt = true } , NotifySelect = MenuSettings };
269                   MenuItem { popupContent, $"Properties..", p, Key { enter, alt = true }, NotifySelect = FileProperties };
270                }
271                else if(node.type == folder)
272                {
273                   bool isInResources = node.isInResources;
274
275                   MenuItem { popupContent, $"New File...", l, Key { l, ctrl = true }, NotifySelect = ProjectNewFile };
276                   MenuItem { popupContent, $"New Folder...", n, Key { f, ctrl = true }, NotifySelect = ProjectNewFolder };
277                   MenuItem { popupContent, $"Import Folder...", i, NotifySelect = ProjectImportFolder };
278                   if(isInResources)
279                   {
280                      MenuItem { popupContent, $"Add Resources to Folder...", f, NotifySelect = ResourcesAddFiles };
281                   }
282                   else
283                   {
284                      MenuItem { popupContent, $"Add Files to Folder...", f, NotifySelect = ProjectAddFiles };
285                   }
286                   if(!isInResources)
287                   {
288                      MenuDivider { popupContent };
289                      MenuItem { popupContent, $"Add New Form...", o, NotifySelect = ProjectAddNewForm };
290                      MenuItem { popupContent, $"Add New Behavior Graph...", g, NotifySelect = ProjectAddNewGraph };
291                   }
292                   MenuDivider { popupContent };
293                   MenuItem { popupContent, $"Remove", r, NotifySelect = FileRemoveFile };
294                   MenuDivider { popupContent };
295                   MenuItem { popupContent, $"Browse Folder", w, NotifySelect = MenuBrowseFolder };
296                   MenuDivider { popupContent };
297                   MenuItem { popupContent, $"Settings...", s, Key { f7, alt = true } , NotifySelect = MenuSettings };
298                   MenuItem { popupContent, $"Properties...", p, Key { enter, alt = true }, NotifySelect = FileProperties };
299                }
300
301                popupMenu = 
302                {
303                   master = this, menu = popupContent;
304                   position = {
305                      x + clientStart.x + absPosition.x - app.desktop.position.x, 
306                      y + clientStart.y + absPosition.y - app.desktop.position.y };
307                };
308                popupMenu.Create();
309             }
310          }
311          return true;
312       }
313
314       bool NotifyKeyDown(ListBox listBox, DataRow row, Key key, unichar ch)
315       {
316          if(row)
317          {
318             ProjectNode node = (ProjectNode)row.tag;
319             switch(key)
320             {
321                case altEnter: case Key { keyPadEnter, alt = true }:
322                {
323                   NodeProperties { parent = parent, master = this, 
324                      position = { position.x + 100, position.y + 100 }, node = node }.Create();
325                   return false;
326                }
327                case enter: case keyPadEnter:
328                {
329                   ProjectNode resNode;
330                   for(resNode = node.parent; resNode; resNode = resNode.parent)
331                      if(resNode.type == resources)
332                         break;
333                   if(node.type == project || (node.type == folder && !resNode))
334                   {
335                      AddFiles(false);
336                      return false;
337                   }
338                   else if(node.type == resources || node.type == folder)
339                   {
340                      AddFiles(true);
341                      return false;
342                   }
343                   break;
344                }
345                case ctrlI:
346                {
347                   if(node.type == project || node.type == folder || node.type == resources)
348                   {
349                      ImportFolder(node);
350                      return false;
351                   }
352                   break;
353                }
354                case ctrlF:
355                {
356                   if(node.type == project || node.type == folder || node.type == resources)
357                   {
358                      NewFolder(node, null, true);
359                      return false;
360                   }
361                   break;
362                }
363                case ctrlF7:
364                {
365                   if(node.type == file)
366                   {
367                      FileCompile(null, (Modifiers)key);
368                      return false;
369                   }
370                   break;
371                }
372                case Key { space, shift = true }:
373                case space:
374                {
375                   if(node.type == NodeTypes::project)
376                   {
377                      Project prj = null;
378                      for(p : workspace.projects)
379                      {
380                         if(p.topNode == node)
381                         {
382                            prj = p;
383                            break;
384                         }
385                      }
386                      prj.RotateActiveConfig(!key.shift);
387                      if(prj == project)
388                         ide.AdjustMenus();
389                      return false;
390                   }
391                   break;
392                }
393             }
394          }
395          switch(key)
396          {
397             case enter: case keyPadEnter:  OpenSelectedNodes();   break;
398             case del:                      RemoveSelectedNodes(); break;
399             case escape:                      
400             {
401                Window activeClient = ide.activeClient;
402                if(activeClient)
403                   activeClient.Activate();
404                else
405                   ide.RepositionWindows(true);
406                break;
407             }
408          }
409          return true;
410       }
411
412       bool NotifyCollapse(ListBox listBox, DataRow row, bool collapsed)
413       {
414          ProjectNode node = (ProjectNode)row.tag;
415          if(node.type == folder)
416             node.icon = collapsed ? folder : openFolder;
417          return true;
418       }
419    };
420
421    FileDialog importFileDialog { autoCreate = false, type = selectDir, text = $"Import Folder" };
422    FileDialog projectFileDialog
423    {
424       autoCreate = false, filters = projectFilters.array, sizeFilters = projectFilters.count * sizeof(FileFilter);
425       types = projectTypes.array, sizeTypes = projectTypes.count * sizeof(FileType);
426    };
427    FileDialog fileDialog
428    {
429       autoCreate = false, mayNotExist = true, filters = fileFilters.array, sizeFilters = fileFilters.count * sizeof(FileFilter);
430    };
431    FileDialog resourceFileDialog
432    {
433       autoCreate = false, mayNotExist = true, filters = resourceFilters.array, sizeFilters = resourceFilters.count * sizeof(FileFilter);
434    };
435
436    Menu fileMenu { menu, $"File", f };
437    MenuItem { fileMenu, $"Save", s, Key { s, ctrl = true }, NotifySelect = MenuFileSave };
438    // MenuItem { fileMenu, "Save As...", a, NotifySelect = MenuFileSaveAs };
439
440    bool OnClose(bool parentClosing)
441    {
442       if(!parentClosing && visible)
443       {
444          visible = false;
445          return false;
446       }
447       if(buildInProgress)
448          return false;
449       return true;
450    }
451
452    void OnDestroy(void)
453    {
454       //if(ide.findInFilesDialog && ide.findInFilesDialog.created && ide.findInFilesDialog.mode != directory)
455       //   ide.findInFilesDialog.SearchStop();
456
457       ide.outputView.buildBox.Clear();
458       ide.outputView.debugBox.Clear();
459       //ide.outputView.findBox.Clear();
460       ide.callStackView.Clear();
461       ide.watchesView.Clear();
462       ide.threadsView.Clear();
463       ide.breakpointsView.Clear();
464       ide.outputView.ShowClearSelectTab(find); // why this? 
465    }
466
467    bool OnSaveFile(char * fileName)
468    {
469       for(prj : ide.workspace.projects)
470       {
471          if(prj.topNode.modified && prj.Save(prj.filePath))
472          {
473             // ProjectUpdateMakefileForAllConfigs(prj, true, true);
474             prj.topNode.modified = false;
475          }
476       }
477       modifiedDocument = false;
478       Update(null);
479       return true;
480    }
481
482    bool IsModuleInProject(char * filePath)
483    {
484       char moduleName[MAX_FILENAME]; //, modulePath[MAX_LOCATION];
485       GetLastDirectory(filePath, moduleName);
486       return project.topNode.Find(moduleName, false) != null;
487    }
488
489    bool GetRelativePath(char * filePath, char * relativePath)
490    {
491       return project.GetRelativePath(filePath, relativePath);
492    }
493
494    ProjectNode GetNodeFromWindow(Window document, Project project)
495    {
496       if(document.fileName)
497       {
498          char winFileName[MAX_LOCATION];
499          char * documentFileName = GetSlashPathBuffer(winFileName, document.fileName);
500          for(p : ide.workspace.projects)
501          {
502             Project prj = project ? project : p;
503             ProjectNode node;
504             char moduleName[MAX_FILENAME], modulePath[MAX_LOCATION];
505             GetLastDirectory(document.fileName, moduleName);
506
507             if((node = prj.topNode.Find(moduleName, false)))
508             {
509                strcpy(modulePath, prj.topNode.path);
510                PathCatSlash(modulePath, node.path);
511                PathCatSlash(modulePath, node.name);
512                if(!fstrcmp(documentFileName, modulePath))
513                {
514                   return node;
515                }
516             }
517             if(project) break;
518          }
519       }
520       return null;
521    }
522
523    //                          ((( UTILITY FUNCTIONS )))
524    //
525    //  ************************************************************************
526    //  *** These methods below are part of a sequence of events, and as     ***
527    //  *** such they must be passed the current compiler and project config ***
528    //  ************************************************************************
529    bool DisplayCompiler(CompilerConfig compiler, bool cleanLog)
530    {
531       ShowOutputBuildLog(cleanLog);
532       ide.outputView.buildBox.Logf($"%s Compiler\n", compiler ? compiler.name : $"{problem with compiler selection}");
533    }
534
535    bool ProjectPrepareForToolchain(Project project, PrepareMakefileMethod method, bool cleanLog, bool displayCompiler,
536       CompilerConfig compiler, ProjectConfig config)
537    {
538       bool isReady = true;
539       char message[MAX_F_STRING];
540       LogBox logBox = ide.outputView.buildBox;
541
542       ShowOutputBuildLog(cleanLog);
543
544       if(displayCompiler)
545          DisplayCompiler(compiler, false);
546
547       ProjectPrepareMakefile(project, method, false, false, compiler, config);
548       return true;
549    }
550
551    bool ProjectPrepareMakefile(Project project, PrepareMakefileMethod method, bool cleanLog, bool displayCompiler,
552       CompilerConfig compiler, ProjectConfig config)
553    {
554       char makefilePath[MAX_LOCATION];
555       char makefileName[MAX_LOCATION];
556       bool exists;
557       LogBox logBox = ide.outputView.buildBox;
558       
559       ShowOutputBuildLog(cleanLog);
560
561       if(displayCompiler)
562          DisplayCompiler(compiler, false);
563
564       strcpy(makefilePath, project.topNode.path);
565       project.CatMakeFileName(makefileName, compiler, config);
566       PathCatSlash(makefilePath, makefileName);
567
568       exists = FileExists(makefilePath);
569       if((method == normal && (!exists || config.makingModified/*|| project.topNode.modified*/)) ||
570             (method == forceExists && exists) || 
571             method == force) // || config.makingModified || makefileDirty
572       {
573          char * reason;
574          char * action;
575          ide.statusBar.text = $"Generating Makefile & Dependencies..."; // Dependencies?
576          app.UpdateDisplay();
577          
578          if((method == normal && !exists) || (method == force && !exists))
579             action = $"Generating ";
580          else if(method == force)
581             action = $"Regenerating ";
582          else if(method == normal || method == forceExists)
583             action = $"Updating ";
584          else
585             action = "";
586          if(!exists)
587             reason = $"Makefile doesn't exist. ";
588          else if(project.topNode.modified)
589             reason = $"Project has been modified. ";
590          else
591             reason = "";
592
593          //logBox.Logf("%s\n", makefileName);
594          logBox.Logf($"%s - %s%smakefile for %s config...\n", makefileName, reason, action, GetConfigName(config));
595          project.GenerateMakefile(null, false, null, compiler, config);
596
597          ide.statusBar.text = null;
598          app.UpdateDisplay();
599          return true;
600       }
601       return false;
602    }
603    
604    bool BuildInterrim(Project prj, BuildType buildType, CompilerConfig compiler, ProjectConfig config)
605    {
606       if(ProjectPrepareForToolchain(prj, normal, true, true, compiler, config))
607       {
608          ide.outputView.buildBox.Logf($"Building project %s using the %s configuration...\n", prj.name, GetConfigName(config));
609          return Build(prj, buildType, compiler, config);
610       }
611       return false;
612    }
613
614    bool Build(Project prj, BuildType buildType, CompilerConfig compiler, ProjectConfig config)
615    {
616       bool result = true;
617       Window document;
618
619       stopBuild = false;
620       for(document = master.firstChild; document; document = document.next)
621       {
622          if(document.modifiedDocument)
623          {
624             ProjectNode node = GetNodeFromWindow(document, prj);
625             if(node && !document.MenuFileSave(null, 0))
626             {
627                result = false;
628                break;
629             }
630          }
631       }
632       if(result)
633       {
634          DirExpression targetDir = prj.GetTargetDir(compiler, config);
635
636          // TOFIX: DebugStop is being abused and backfiring on us.
637          //        It's supposed to be the 'Debug/Stop' item, not unloading executable or anything else
638
639          //        configIsInDebugSession seems to be used for two OPPOSITE things:
640          //        If we're debugging another config, we need to unload the executable!
641          //        In building, we want to stop if we're debugging the 'same' executable
642          if(buildType != run) ///* && prj == project*/ && prj.configIsInDebugSession)
643          {
644             if(buildType == start || buildType == restart)
645             {
646                if(ide.debugger && ide.debugger.isPrepared)
647                {
648                   DebugStop();
649                }
650             }
651             else
652             {
653                if(ide.project == prj && ide.debugger && ide.debugger.prjConfig == config && ide.debugger.isPrepared)
654                {
655                   DebugStop();
656                }
657             }
658          }
659          
660          // TODO: Disabled until problems fixed... is it fixed?
661          if(buildType == rebuild || (config && config.compilingModified))
662             prj.Clean(compiler, config, false);
663          else
664          {
665             if(buildType == relink || (config && config.linkingModified))
666             {
667                char target[MAX_LOCATION];
668
669                strcpy(target, prj.topNode.path);
670                PathCat(target, targetDir.dir);
671                prj.CatTargetFileName(target, compiler, config);
672                if(FileExists(target))
673                   DeleteFile(target);
674             }
675             if(config && config.symbolGenModified)
676             {
677                DirExpression objDir = prj.GetObjDir(compiler, config);
678                char fileName[MAX_LOCATION];
679                char moduleName[MAX_FILENAME];
680                strcpy(fileName, prj.topNode.path);
681                PathCatSlash(fileName, objDir.dir);
682                strcpy(moduleName, prj.moduleName);
683                strcat(moduleName, ".main.ec");
684                PathCatSlash(fileName, moduleName);
685                if(FileExists(fileName))
686                   DeleteFile(fileName);
687                ChangeExtension(fileName, "c", fileName);
688                if(FileExists(fileName))
689                   DeleteFile(fileName);
690                ChangeExtension(fileName, "o", fileName);
691                if(FileExists(fileName))
692                   DeleteFile(fileName);
693
694                delete objDir;
695             }
696          }
697          buildInProgress = prj == project ? buildingMainProject : buildingSecondaryProject;
698          ide.AdjustBuildMenus();
699          ide.AdjustDebugMenus();
700
701          result = prj.Build(buildType == run, null, compiler, config);
702
703          if(config)
704          {
705             config.compilingModified = false;
706             if(!ide.ShouldStopBuild())
707                config.linkingModified = false;
708
709             config.symbolGenModified = false;
710          }
711          buildInProgress = none;
712          ide.AdjustBuildMenus();
713          ide.AdjustDebugMenus();
714
715          ide.workspace.modified = true;
716
717          delete targetDir;
718       }
719       return result;
720    }
721
722    //                          ((( USER ACTIONS )))
723    //
724    //  ************************************************************************
725    //  *** Methods below should atomically start a process, and as such     ***
726    //  *** they can query compiler and config directly from ide and project ***
727    //  *** but ONLY ONCE!!!                                                 ***
728    //  ************************************************************************
729
730    bool ProjectBuild(MenuItem selection, Modifiers mods)
731    {
732       Project prj = project;
733       CompilerConfig compiler = ideSettings.GetCompilerConfig(ide.workspace.compiler);
734       ProjectConfig config;
735       if(selection || !ide.activeClient)
736       {
737          DataRow row = fileList.currentRow;
738          ProjectNode node = row ? (ProjectNode)row.tag : null;
739          if(node) prj = node.project;
740       }
741       else
742       {
743          ProjectNode node = GetNodeFromWindow(ide.activeClient, null);
744          if(node)
745             prj = node.project;
746       }
747       config = prj.config;
748       if(/*prj != project || */!prj.GetConfigIsInDebugSession(config) || !ide.DontTerminateDebugSession($"Project Build"))
749       {
750          BuildInterrim(prj, build, compiler, config);
751       }
752       delete compiler;
753       return true;
754    }
755
756    bool ProjectLink(MenuItem selection, Modifiers mods)
757    {
758       Project prj = project;
759       CompilerConfig compiler = ideSettings.GetCompilerConfig(ide.workspace.compiler);
760       ProjectConfig config;
761       if(selection || !ide.activeClient)
762       {
763          DataRow row = fileList.currentRow;
764          ProjectNode node = row ? (ProjectNode)row.tag : null;
765          if(node) prj = node.project;
766       }
767       else
768       {
769          ProjectNode node = GetNodeFromWindow(ide.activeClient, null);
770          if(node)
771             prj = node.project;
772       }
773       config = prj.config;
774       if(ProjectPrepareForToolchain(prj, normal, true, true, compiler, config))
775       {
776          ide.outputView.buildBox.Logf($"Relinking project %s using the %s configuration...\n", prj.name, GetConfigName(config));
777          if(config)
778             config.linkingModified = true;
779          Build(prj, relink, compiler, config);
780       }
781       delete compiler;
782       return true;
783    }
784
785    bool ProjectRebuild(MenuItem selection, Modifiers mods)
786    {
787       CompilerConfig compiler = ideSettings.GetCompilerConfig(ide.workspace.compiler);
788       Project prj = project;
789       ProjectConfig config;
790       if(selection || !ide.activeClient)
791       {
792          DataRow row = fileList.currentRow;
793          ProjectNode node = row ? (ProjectNode)row.tag : null;
794          if(node) prj = node.project;
795       }
796       else
797       {
798          ProjectNode node = GetNodeFromWindow(ide.activeClient, null);
799          if(node)
800             prj = node.project;
801       }
802       config = prj.config;
803       if(ProjectPrepareForToolchain(prj, normal, true, true, compiler, config))
804       {
805          ide.outputView.buildBox.Logf($"Rebuilding project %s using the %s configuration...\n", prj.name, GetConfigName(config));
806          /*if(config)
807          {
808             config.compilingModified = true;
809             config.makingModified = true;
810          }*/ // -- should this still be used depite the new solution of BuildType?
811          Build(prj, rebuild, compiler, config);
812       }
813       delete compiler;
814       return true;
815    }
816
817    bool ProjectClean(MenuItem selection, Modifiers mods)
818    {
819       Project prj = project;
820       CompilerConfig compiler = ideSettings.GetCompilerConfig(ide.workspace.compiler);
821       ProjectConfig config;
822       if(selection || !ide.activeClient)
823       {
824          DataRow row = fileList.currentRow;
825          ProjectNode node = row ? (ProjectNode)row.tag : null;
826          if(node) prj = node.project;
827       }
828       else
829       {
830          ProjectNode node = GetNodeFromWindow(ide.activeClient, null);
831          if(node)
832             prj = node.project;
833       }
834       config = prj.config;
835       if(ProjectPrepareForToolchain(prj, normal, true, true, compiler, config))
836       {
837          ide.outputView.buildBox.Logf($"Cleaning project %s using the %s configuration...\n", prj.name, GetConfigName(config));
838
839          buildInProgress = prj == project ? buildingMainProject : buildingSecondaryProject;
840          ide.AdjustBuildMenus();
841
842          prj.Clean(compiler, config, false);
843          buildInProgress = none;
844          ide.AdjustBuildMenus();
845       }
846       delete compiler;
847       return true;
848    }
849
850    bool ProjectRealClean(MenuItem selection, Modifiers mods)
851    {
852       Project prj = project;
853       CompilerConfig compiler = ideSettings.GetCompilerConfig(ide.workspace.compiler);
854       ProjectConfig config;
855       if(selection || !ide.activeClient)
856       {
857          DataRow row = fileList.currentRow;
858          ProjectNode node = row ? (ProjectNode)row.tag : null;
859          if(node) prj = node.project;
860       }
861       else
862       {
863          ProjectNode node = GetNodeFromWindow(ide.activeClient, null);
864          if(node)
865             prj = node.project;
866       }
867       config = prj.config;
868       if(ProjectPrepareForToolchain(prj, normal, true, true, compiler, config))
869       {
870          ide.outputView.buildBox.Logf($"Removing intermediate objects directory for project %s using the %s configuration...\n", prj.name, GetConfigName(config));
871
872          buildInProgress = prj == project ? buildingMainProject : buildingSecondaryProject;
873          ide.AdjustBuildMenus();
874
875          prj.Clean(compiler, config, true);
876          buildInProgress = none;
877          ide.AdjustBuildMenus();
878       }
879       delete compiler;
880       return true;
881    }
882
883    bool ProjectRegenerate(MenuItem selection, Modifiers mods)
884    {
885       Project prj = project;
886       CompilerConfig compiler = ideSettings.GetCompilerConfig(ide.workspace.compiler);
887       if(selection || !ide.activeClient)
888       {
889          DataRow row = fileList.currentRow;
890          ProjectNode node = row ? (ProjectNode)row.tag : null;
891          if(node)
892             prj = node.project;
893       }
894       else
895       {
896          ProjectNode node = GetNodeFromWindow(ide.activeClient, null);
897          if(node)
898             prj = node.project;
899       }
900
901       ProjectPrepareMakefile(prj, force, true, true, compiler, prj.config);
902       delete compiler;
903       return true;
904    }
905
906    void Compile(ProjectNode node)
907    {
908       char fileName[MAX_LOCATION];
909       char extension[MAX_EXTENSION];
910       Window document;
911       Project prj = node.project;
912       ProjectConfig config = prj.config;
913       CompilerConfig compiler = ideSettings.GetCompilerConfig(ide.workspace.compiler);
914       DirExpression objDir = prj.GetObjDir(compiler, config);
915
916       strcpy(fileName, prj.topNode.path);
917       PathCatSlash(fileName, objDir.dir);
918       PathCatSlash(fileName, node.name);
919       StripExtension(fileName);
920       strcat(fileName, ".o");
921       if(FileExists(fileName))
922          DeleteFile(fileName);
923
924       GetExtension(node.name, extension);
925       if(!strcmp(extension, "ec"))
926       {
927          // Delete generated C file
928          strcpy(fileName, prj.topNode.path);
929          PathCat(fileName, objDir.dir);
930          PathCat(fileName, node.name);
931          StripExtension(fileName);
932          strcat(fileName, ".c");
933          if(FileExists(fileName))
934             DeleteFile(fileName);
935
936          // Delete symbol file
937          strcpy(fileName, prj.topNode.path);
938          PathCat(fileName, node.path);
939          PathCat(fileName, node.name);
940          StripExtension(fileName);
941          strcat(fileName, ".sym");
942          if(FileExists(fileName))
943             DeleteFile(fileName);
944       }
945
946       stopBuild = false;
947
948       // Check if we have to save
949       strcpy(fileName, prj.topNode.path);
950       PathCatSlash(fileName, node.path);
951       PathCatSlash(fileName, node.name);
952       for(document = ide.firstChild; document; document = document.next)
953       {
954          if(document.modifiedDocument)
955          {
956             char documentFileName[MAX_LOCATION];
957             if(!fstrcmp(GetSlashPathBuffer(documentFileName, document.fileName), fileName))
958                if(!document.MenuFileSave(null, 0))
959                   return;
960          }
961       }
962
963       if(ProjectPrepareForToolchain(prj, normal, true, true, compiler, config))
964       {
965          if(!node.GetIsExcluded(config))
966          {
967             buildInProgress = compilingFile;
968             ide.AdjustBuildMenus();
969
970             //ide.outputView.ShowClearSelectTab(build);
971             // this stuff doesn't even appear
972             //ide.outputView.buildBox.Logf($"%s Compiler\n", compiler.name);
973             if(config)
974                ide.outputView.buildBox.Logf($"Compiling single file %s in project %s using the %s configuration...\n", node.name, prj.name, config.name);
975             else
976                ide.outputView.buildBox.Logf($"Compiling single file %s in project %s...\n", node.name, prj.name);
977
978             prj.Compile(node, compiler, config);
979             buildInProgress = none;
980             ide.AdjustBuildMenus();
981          }
982          else
983             ide.outputView.buildBox.Logf($"File %s is excluded from current build configuration.\n", node.name);
984       }
985       delete objDir;
986       delete compiler;
987    }
988
989    bool ProjectNewFile(MenuItem selection, Modifiers mods)
990    {
991       DataRow row = fileList.currentRow;
992       if(row)
993       {
994          char fileName[1024];
995          char filePath[MAX_LOCATION];
996          ProjectNode parentNode = (ProjectNode)row.tag;
997          ProjectNode n, fileNode;
998          parentNode.GetFileSysMatchingPath(filePath);
999          MakePathRelative(filePath, parentNode.project.topNode.path, filePath);
1000          for(n = parentNode; n && n != parentNode.project.resNode; n = n.parent);
1001          sprintf(fileName, $"Untitled %d", documentID);
1002          fileNode = AddFile(parentNode, fileName, (bool)n, true);
1003          fileNode.path = CopyUnixPath(filePath);
1004          if(fileNode)
1005          {
1006             NodeProperties nodeProperties
1007             {
1008                parent, this;
1009                position = { position.x + 100, position.y + 100 };
1010                mode = newFile;
1011                node = fileNode;
1012             };
1013             nodeProperties.Create(); // not modal?
1014          }
1015       }
1016       return true;
1017    }
1018
1019    bool ProjectNewFolder(MenuItem selection, Modifiers mods)
1020    {
1021       DataRow row = fileList.currentRow;
1022       if(row)
1023       {
1024          ProjectNode parentNode = (ProjectNode)row.tag;
1025          NewFolder(parentNode, null, true);
1026       }
1027       return true;
1028    }
1029
1030    bool ResourcesAddFiles(MenuItem selection, Modifiers mods)
1031    {
1032       AddFiles(true);
1033       return true;
1034    }
1035
1036    bool ProjectAddFiles(MenuItem selection, Modifiers mods)
1037    {
1038       AddFiles(false);
1039       return true;
1040    }
1041
1042    bool ProjectImportFolder(MenuItem selection, Modifiers mods)
1043    {
1044       DataRow row = fileList.currentRow;
1045       if(row)
1046       {
1047          ProjectNode toNode = (ProjectNode)row.tag;
1048          ImportFolder(toNode);
1049       }
1050       return true;
1051    }
1052
1053    bool ProjectAddNewForm(MenuItem selection, Modifiers mods)
1054    {
1055       CodeEditor codeEditor = CreateNew("Form", "form", "Window", null);
1056       codeEditor.EnsureUpToDate();
1057       return true;
1058    }
1059
1060    bool ProjectAddNewGraph(MenuItem selection, Modifiers mods)
1061    {
1062       CodeEditor codeEditor = CreateNew("Graph", "graph", "Block", null);
1063       if(codeEditor)
1064          codeEditor.EnsureUpToDate();
1065       return true;
1066    }
1067
1068    bool ProjectRemove(MenuItem selection, Modifiers mods)
1069    {
1070       DataRow row = fileList.currentRow;
1071       if(row)
1072       {
1073          ProjectNode node = (ProjectNode)row.tag;
1074          if(node.type == project)
1075             RemoveSelectedNodes();
1076       }
1077       return true;
1078    }
1079
1080    bool ProjectUpdateMakefileForAllConfigs(Project project, bool cleanLog, bool displayCompiler)
1081    {
1082       CompilerConfig compiler = ideSettings.GetCompilerConfig(ide.workspace.compiler);
1083       ShowOutputBuildLog(cleanLog);
1084
1085       if(displayCompiler)
1086          DisplayCompiler(compiler, false);
1087       
1088       for(config : project.configurations)
1089       {
1090          ProjectPrepareMakefile(project, forceExists, false, false,
1091             compiler, config);
1092       }
1093
1094       ide.Update(null);
1095       delete compiler;
1096    }
1097
1098    bool MenuConfig(MenuItem selection, Modifiers mods)
1099    {
1100       if(ProjectActiveConfig { master = parent, project = project }.Modal() == ok)
1101          ide.AdjustMenus();
1102       return true;
1103    }
1104
1105    bool MenuCompiler(MenuItem selection, Modifiers mods)
1106    {
1107       ActiveCompilerDialog compilerDialog
1108       {
1109          master = parent;
1110          ideSettings = ideSettings, workspaceActiveCompiler = ide.workspace.compiler;
1111       };
1112       incref compilerDialog;
1113       if(compilerDialog.Modal() == ok && strcmp(compilerDialog.workspaceActiveCompiler, ide.workspace.compiler))
1114       {
1115          ide.workspace.compiler = compilerDialog.workspaceActiveCompiler;
1116          for(prj : ide.workspace.projects)
1117             ide.projectView.ProjectUpdateMakefileForAllConfigs(prj, true, true);
1118       }
1119       delete compilerDialog;
1120       return true;
1121    }
1122
1123    bool MenuSettings(MenuItem selection, Modifiers mods)
1124    {
1125       ProjectNode node = GetSelectedNode(true);
1126       Project prj = node ? node.project : project;
1127       projectSettingsDialog = ProjectSettings { master = parent, project = prj, projectNode = node };
1128       projectSettingsDialog.Modal();
1129
1130       Update(null);
1131       ide.AdjustMenus();
1132       return true;
1133    }
1134
1135    bool FileProperties(MenuItem selection, Modifiers mods)
1136    {
1137       DataRow row = fileList.currentRow;
1138       if(row)
1139       {
1140          ProjectNode node = (ProjectNode)row.tag;
1141          NodeProperties { parent = parent, master = this, node = node, 
1142                position = { position.x + 100, position.y + 100 } }.Create();
1143       }
1144       return true;
1145    }
1146
1147    bool FileOpenFile(MenuItem selection, Modifiers mods)
1148    {
1149       OpenSelectedNodes();
1150       return true;
1151    }
1152
1153    bool FileRemoveFile(MenuItem selection, Modifiers mods)
1154    {
1155       RemoveSelectedNodes();
1156       return true;
1157    }
1158
1159    bool FileCompile(MenuItem selection, Modifiers mods)
1160    {
1161       DataRow row = fileList.currentRow;
1162       if(row)
1163       {
1164          ProjectNode node = (ProjectNode)row.tag;
1165          Compile(node);
1166       }
1167       return true;
1168    }
1169
1170    Project GetSelectedProject(bool useSelection)
1171    {
1172       Project prj = project;
1173       if(useSelection)
1174       {
1175          DataRow row = fileList.currentRow;
1176          ProjectNode node = row ? (ProjectNode)row.tag : null;
1177          if(node)
1178             prj = node.project;
1179       }
1180       return prj;
1181    }
1182    
1183    ProjectNode GetSelectedNode(bool useSelection)
1184    {
1185       ProjectNode node = null;
1186       if(useSelection)
1187       {
1188          DataRow row = fileList.currentRow;
1189          if(row)
1190             node = (ProjectNode)row.tag;
1191       }
1192       return node;
1193    }
1194
1195    bool MenuBrowseFolder(MenuItem selection, Modifiers mods)
1196    {
1197       char folder[MAX_LOCATION];
1198       Project prj;
1199       ProjectNode node = GetSelectedNode(true);
1200       if(!node)
1201          node = project.topNode;
1202       prj = node.project;
1203
1204       strcpy(folder, prj.topNode.path);
1205       if(node != prj.topNode)
1206          PathCatSlash(folder, node.path);
1207       ShellOpen(folder);
1208    }
1209
1210    bool Run(MenuItem selection, Modifiers mods)
1211    {
1212       CompilerConfig compiler = ideSettings.GetCompilerConfig(ide.workspace.compiler);
1213       ProjectConfig config = project.config;
1214       String args = new char[maxPathLen];
1215       args[0] = '\0';
1216       if(ide.workspace.commandLineArgs)
1217          //ide.debugger.GetCommandLineArgs(args);
1218          strcpy(args, ide.workspace.commandLineArgs);
1219       if(ide.debugger.isActive)
1220          project.Run(args, compiler, config);
1221       /*else if(config.targetType == sharedLibrary || config.targetType == staticLibrary)
1222          MessageBox { master = ide, type = ok, text = "Run", contents = "Shared and static libraries cannot be run like executables." }.Modal();*/
1223       else if(BuildInterrim(project, run, compiler, config))
1224          project.Run(args, compiler, config);
1225       delete args;
1226       delete compiler;
1227       return true;
1228    }
1229
1230    bool DebugStart()
1231    {
1232       bool result = false;
1233       CompilerConfig compiler = ideSettings.GetCompilerConfig(ide.workspace.compiler);
1234       ProjectConfig config = project.config;
1235       TargetTypes targetType = project.GetTargetType(config);
1236       if(targetType == sharedLibrary || targetType == staticLibrary)
1237          MessageBox { master = ide, type = ok, text = $"Run", contents = $"Shared and static libraries cannot be run like executables." }.Modal();
1238       else if(project.GetCompress(config))
1239          MessageBox { master = ide, text = $"Starting Debug", contents = $"Debugging compressed applications is not supported\n" }.Modal();
1240       else if(project.GetDebug(config) ||
1241          MessageBox { master = ide, type = okCancel, text = $"Starting Debug", contents = $"Attempting to debug non-debug configuration\nProceed anyways?" }.Modal() == ok)
1242       {
1243          if(/*!IsProjectModified() ||*/ BuildInterrim(project, start, compiler, config))
1244          {
1245             if(compiler.type.isVC)
1246             {
1247                //bool result = false;
1248                char oldwd[MAX_LOCATION];
1249                PathBackup pathBackup { };
1250                char command[MAX_LOCATION];
1251
1252                ide.SetPath(false, compiler, config);
1253                
1254                GetWorkingDir(oldwd, sizeof(oldwd));
1255                ChangeWorkingDir(project.topNode.path);
1256
1257                sprintf(command, "%s /useenv %s.sln /projectconfig \"%s|Win32\" /command \"%s\"" , "devenv", project.name, config.name, "Debug.Start");
1258                //ide.outputView.buildBox.Logf("command: %s\n", command);
1259                Execute(command);
1260                ChangeWorkingDir(oldwd);
1261
1262                delete pathBackup;
1263             }
1264             else
1265             {
1266                ide.debugger.Start(compiler, config);
1267                result = true;
1268             }
1269          }
1270       }
1271       delete compiler;
1272       return result;      
1273    }
1274
1275    void GoToError(const char * line)
1276    {
1277       char * colon;
1278       
1279       while(isspace(*line)) line++;
1280       colon = strstr(line, ":");
1281
1282       {
1283          int lineNumber = 0;
1284          int col = 1;
1285          bool lookForLineNumber = true;
1286
1287          // deal with linking error
1288          if(colon && colon[1] == ' ')
1289          {
1290             colon = strstr(colon + 1, ":");
1291             if(colon && !colon[1])
1292             {
1293                colon = strstr(line, ":");
1294                lookForLineNumber = false;
1295             }
1296             else if(colon && !isdigit(colon[1]))
1297             {
1298                line = colon + 1;
1299                colon = strstr(line, ":");
1300             }
1301          }
1302          // Don't be mistaken by the drive letter colon
1303          if(colon && (colon[1] == '/' || colon[1] == '\\'))
1304             colon = strstr(colon + 1, ":");
1305          if(colon && lookForLineNumber)
1306          {
1307             char * comma;
1308             // MSVS Errors
1309             char * par = RSearchString(line, "(", colon - line, true, false);
1310             if(par && strstr(par, ")"))
1311                colon = par;
1312             else if((colon+1)[0] == ' ')
1313             {
1314                // NOTE: This is the same thing as saying 'colon = line'
1315                for( ; colon != line; colon--)
1316                   /*if(*colon == '(')
1317                      break*/;
1318             }
1319             lineNumber = atoi(colon + 1);
1320             /*
1321             comma = strchr(colon, ',');
1322             if(comma)
1323                col = atoi(comma+1);
1324             */
1325             comma = strchr(colon+1, ':');
1326             if(comma)
1327                col = atoi(comma+1);
1328          }
1329          
1330          {
1331             char moduleName[MAX_LOCATION], filePath[MAX_LOCATION];
1332             char * bracket;
1333             if(colon)
1334             {
1335                // Cut module name
1336                strncpy(moduleName, line, colon - line);
1337                moduleName[colon - line] = '\0';
1338             }
1339             else
1340                strcpy(moduleName, line);
1341
1342             // Remove stuff in brackets
1343             /*
1344             bracket = strstr(moduleName, "(");
1345             if(bracket) *bracket = '\0';
1346             */
1347             MakeSlashPath(moduleName);
1348
1349             if(!colon)
1350             {
1351                // Check if it's one of our modules
1352                ProjectNode node = project.topNode.Find(moduleName, false);
1353                if(node)
1354                {
1355                   strcpy(moduleName, node.path);
1356                   PathCatSlash(moduleName, node.name);
1357                }
1358                else
1359                   moduleName[0] = '\0';
1360             }
1361             if(moduleName[0])
1362             {
1363                CodeEditor codeEditor;
1364                strcpy(filePath, project.topNode.path);
1365                PathCatSlash(filePath, moduleName);
1366       
1367                codeEditor = (CodeEditor)ide.OpenFile(filePath, normal, true, null, no, normal);
1368                if(!codeEditor)
1369                {
1370                   char name[MAX_LOCATION];
1371                   // TOFIX: Improve on this, don't use only filename, make a function
1372                   if(ide && ide.workspace)
1373                   {
1374                      for(prj : ide.workspace.projects)
1375                      {
1376                         if(prj.topNode.FindWithPath(moduleName, false))
1377                         {
1378                            strcpy(filePath, prj.topNode.path);
1379                            PathCatSlash(filePath, moduleName);
1380                            codeEditor = (CodeEditor)ide.OpenFile(filePath, normal, true, null, no, normal);
1381                            if(codeEditor)
1382                               break;
1383                         }
1384                      }
1385                   }
1386                }
1387                if(codeEditor && lineNumber)
1388                {
1389                   EditBox editBox = codeEditor.editBox;
1390                   editBox.GoToLineNum(lineNumber - 1);
1391                   editBox.GoToPosition(editBox.line, lineNumber - 1, col ? (col - 1) : 0);
1392                }
1393             }
1394          }
1395       }
1396    }
1397
1398    bool OpenNode(ProjectNode node)
1399    {
1400       char filePath[MAX_LOCATION];
1401       node.GetFullFilePath(filePath);
1402       return ide.OpenFile(filePath, normal, true/*false Why was it opening hidden?*/, null, something, normal) ? true : false;
1403    }
1404
1405    void AddNode(ProjectNode node, DataRow addTo)
1406    {
1407       DataRow row = addTo ? addTo.AddRow() : fileList.AddRow();
1408
1409       row.tag = (int)node;
1410       node.row = row;
1411
1412       if(node.type == resources)
1413          resourceRow = row;
1414
1415       row.SetData(null, node);
1416
1417       if(node.files && node.files.first && node.parent && 
1418             !(!node.parent.parent && 
1419                (!strcmpi(node.name, "notes") || !strcmpi(node.name, "sources") || 
1420                   !strcmpi(node.name, "src") || !strcmpi(node.name, "tools"))))
1421          row.collapsed = true;
1422       else if(node.type == folder)
1423          node.icon = openFolder;
1424
1425       if(node.files)
1426       {
1427          for(child : node.files)
1428             AddNode(child, row);
1429       }
1430    }
1431
1432    void DeleteNode(ProjectNode projectNode)
1433    {
1434       if(projectNode.files)
1435       {
1436          ProjectNode child;
1437          while(child = projectNode.files.first)
1438             DeleteNode(child);
1439       }
1440       fileList.DeleteRow(projectNode.row);
1441       projectNode.Delete();
1442    }
1443
1444    bool ProjectSave(MenuItem selection, Modifiers mods)
1445    {
1446       DataRow row = fileList.currentRow;
1447       ProjectNode node = row ? (ProjectNode)row.tag : null;
1448       Project prj = node ? node.project : null;
1449       if(prj)
1450       {
1451          if(prj.Save(prj.filePath))
1452          {
1453             // ProjectUpdateMakefileForAllConfigs(prj, true, true);
1454             prj.topNode.modified = false;
1455             prj = null;
1456             for(p : ide.workspace.projects)
1457             {
1458                if(p.topNode.modified)
1459                { 
1460                   prj = p;
1461                   break;
1462                }
1463             }
1464             if(!prj)
1465                modifiedDocument = false;
1466             Update(null);
1467          }
1468       }
1469       return true;
1470    }
1471
1472    bool ShowOutputBuildLog(bool cleanLog)
1473    {
1474       OutputView output = ide.outputView;
1475       if(cleanLog)
1476          output.ShowClearSelectTab(build);
1477       else
1478       {
1479          output.SelectTab(build);
1480          output.Show();
1481       }
1482    }
1483
1484    bool DebugRestart()
1485    {
1486       CompilerConfig compiler = ideSettings.GetCompilerConfig(ide.workspace.compiler);
1487       ProjectConfig config = project.config;
1488
1489       bool result = false;
1490       if(/*!IsProjectModified() ||*/ BuildInterrim(project, restart, compiler, config))
1491       {
1492          // For Restart, compiler and config will only be used if for
1493          // whatever reason (if at all possible) the Debugger is in a
1494          // 'terminated' or 'none' state
1495          ide.debugger.Restart(compiler, config);
1496          result = true;
1497       }
1498
1499       delete compiler;
1500       return result;
1501    }
1502
1503    bool DebugResume()
1504    {
1505       ide.debugger.Resume();
1506       return true;
1507    }
1508
1509    bool DebugBreak()
1510    {
1511       ide.debugger.Break();
1512       return true;
1513    }
1514
1515    bool DebugStop()
1516    {
1517       ide.debugger.Stop();
1518       return true;
1519    }
1520
1521    bool DebugStepInto()
1522    {
1523       CompilerConfig compiler = ideSettings.GetCompilerConfig(ide.workspace.compiler);
1524       ProjectConfig config = project.config;
1525
1526       if((ide.debugger.isActive) || (!buildInProgress && BuildInterrim(project, start, compiler, config)))
1527          ide.debugger.StepInto(compiler, config);
1528       delete compiler;
1529       return true;
1530    }
1531
1532    bool DebugStepOver(bool skip)
1533    {
1534       CompilerConfig compiler = ideSettings.GetCompilerConfig(ide.workspace.compiler);
1535       ProjectConfig config = project.config;
1536
1537       if((ide.debugger.isActive) || (!buildInProgress && BuildInterrim(project, start, compiler, config)))
1538          ide.debugger.StepOver(compiler, config, skip);
1539
1540       delete compiler;
1541       return true;
1542    }
1543
1544    bool DebugStepOut(bool skip)
1545    {
1546       ide.debugger.StepOut(skip);
1547       return true;
1548    }
1549
1550    void ImportFolder(ProjectNode toNode)
1551    {
1552       if(toNode)
1553       {
1554          //bool isFolder = toNode.type == folder;
1555          //bool isRes = toNode.isInResources;
1556          
1557          FileDialog fileDialog = importFileDialog;
1558          fileDialog.master = parent;
1559          if(fileDialog.Modal() == ok)
1560          {
1561             ImportFolderFSI fsi { projectView = this };
1562             fsi.stack.Add(toNode);
1563             fsi.Iterate(fileDialog.filePath);
1564             delete fsi;
1565          }
1566       }
1567    }
1568
1569    ProjectNode NewFolder(ProjectNode parentNode, char * name, bool showProperties)
1570    {
1571       if(parentNode)
1572       {
1573          ProjectNode folderNode;
1574          Project prj = parentNode.project;
1575          int c;
1576          ProjectNode after = null;
1577          for(node : parentNode.files)
1578          {
1579             if(node.type != folder)
1580                break;
1581             after = node;
1582          }
1583          
1584          if(name && name[0])
1585             folderNode = parentNode.Add(prj, name, after, folder, folder, true);
1586          else
1587          {
1588             for(c = 0; c < 100; c++)
1589             {
1590                char string[16];
1591                sprintf(string, c ? "New Folder (%d)" : "New Folder", c);
1592                if((folderNode = parentNode.Add(prj, string, after, folder, folder, true)))
1593                   break;
1594             }
1595          }
1596
1597          if(folderNode)
1598          {
1599             NodeProperties nodeProperties;
1600             if(!showProperties)
1601             {
1602                modifiedDocument = true;
1603                prj.topNode.modified = true;
1604             }
1605             Update(null);
1606             folderNode.row = parentNode.row.AddRowAfter(after ? after.row : null);
1607             folderNode.row.tag = (int)folderNode;
1608                
1609             folderNode.row.SetData(null, folderNode);
1610             fileList.currentRow = folderNode.row;
1611             
1612             if(showProperties)
1613             {
1614                nodeProperties = NodeProperties
1615                {
1616                   parent, this, mode = newFolder, node = folderNode;
1617                   position = { position.x + 100, position.y + 100 };
1618                };
1619                nodeProperties.Create();   // Modal?
1620             }
1621             return folderNode;
1622          }
1623       }
1624       return null;
1625    }
1626
1627    void AddFiles(bool resources)
1628    {
1629       FileDialog fileDialog = (!resources) ? this.fileDialog : resourceFileDialog;
1630       fileDialog.type = multiOpen;
1631       fileDialog.text = !resources ? $"Add Files to Project" : $"Add Resources to Project";
1632       fileDialog.master = parent;
1633
1634       if(fileDialog.Modal() == ok)
1635       {
1636          int c;
1637          DataRow row = fileList.currentRow;
1638          ProjectNode parentNode = (ProjectNode)row.tag;
1639          bool addFailed = false;
1640          int numSelections = fileDialog.numSelections;
1641          char ** multiFilePaths = fileDialog.multiFilePaths;
1642
1643          Array<String> nameConflictFiles { };
1644
1645          for(c = 0; c < numSelections; c++)
1646          {
1647             char * filePath = multiFilePaths[c];
1648             FileAttribs exists = FileExists(filePath);
1649             bool addThisFile = true;
1650
1651             if(exists.isDirectory)
1652                addThisFile = false;
1653             else if(!exists)
1654             {
1655                if(MessageBox { master = ide, type = yesNo, text = filePath, 
1656                      contents = $"File doesn't exist. Create?" }.Modal() == yes)
1657                {
1658                   File f = FileOpen(filePath, write);
1659                   if(f)
1660                   {
1661                      addThisFile = true;
1662                      delete f;
1663                   }
1664                   else
1665                   {
1666                      MessageBox { master = ide, type = ok, text = filePath, 
1667                            contents = $"Couldn't create file."}.Modal();
1668                      addThisFile = false;
1669                   }
1670                }
1671             }
1672
1673             if(addThisFile)
1674             {
1675                /*addFailed = */if(!AddFile(parentNode, filePath, resources, false))//;
1676                {
1677                   nameConflictFiles.Add(CopyString(filePath));
1678                   addFailed = true;
1679                }
1680             }
1681          }
1682          if(addFailed)
1683          {
1684             int len = 0;
1685             char * part1 = $"The following file";
1686             char * opt1 = $" was ";
1687             char * opt2 = $"s were ";
1688             char * part2 = $"not added because of identical file name conflict within the project.\n\n";
1689             char * message;
1690             len += strlen(part1);
1691             len += strlen(part2);
1692             len += nameConflictFiles.count > 1 ? strlen(opt2) : strlen(opt1);
1693             for(s : nameConflictFiles)
1694                len += strlen(s) + 1;
1695             message = new char[len + 1];
1696             strcpy(message, part1);
1697             strcat(message, nameConflictFiles.count > 1 ? opt2 : opt1);
1698             strcat(message, part2);
1699             for(s : nameConflictFiles)
1700             {
1701                strcat(message, s);
1702                strcat(message, "\n");
1703             }
1704             MessageBox { master = ide, type = ok, text = $"Name Conflict", 
1705                   contents = message }.Modal();
1706             delete message;
1707          }
1708          nameConflictFiles.Free();
1709          delete nameConflictFiles;
1710       }
1711    }
1712
1713    ProjectNode AddFile(ProjectNode parentNode, char * filePath, bool resources, bool isTemporary)
1714    {
1715       ProjectNode result = null;
1716       ProjectNode after = null;
1717       for(node : parentNode.files)
1718       {
1719          if(node.type != folder && node.type != file && node.type)
1720             break;
1721          after = node;
1722       }
1723
1724       result = parentNode.Add(parentNode.project, filePath, after, file, NodeIcons::SelectFileIcon(filePath), !resources);
1725
1726       if(result)
1727       {
1728          if(!isTemporary)
1729          {
1730             modifiedDocument = true;
1731             parentNode.project.topNode.modified = true;
1732             parentNode.project.ModifiedAllConfigs(true, false, true, true);
1733          }
1734          Update(null);
1735          result.row = parentNode.row.AddRowAfter(after ? after.row : null);
1736          result.row.tag = (int)result;
1737          result.row.SetData(null, result);
1738       }
1739       return result;
1740    }
1741
1742    CodeEditor CreateNew(char * upper, char * lower, char * base, char * className)
1743    {
1744       CodeEditor codeEditor = null;
1745       ProjectNode projectNode;
1746       ProjectNode after = null;
1747       DataRow row = fileList.currentRow;
1748       ProjectNode parentNode;
1749       int c;
1750
1751       if(!row) row = project.topNode.row;
1752
1753       parentNode = (ProjectNode)row.tag;
1754
1755       for(node : parentNode.files)
1756       {
1757          if(node.type != folder && node.type != file && node.type)
1758             break;
1759          after = node;
1760       }
1761       for(c = 1; c < 100; c++)
1762       {
1763          char string[16];
1764          sprintf(string, c ? "%s%d.ec" : "%s.ec", lower, c);
1765          if((projectNode = parentNode.Add(project, string, after, file, genFile, true)))
1766             break;
1767       }
1768       if(projectNode)
1769       {
1770          char name[256];
1771          char filePath[MAX_LOCATION];
1772
1773          modifiedDocument = true;
1774          project.topNode.modified = true;
1775          Update(null);
1776          project.ModifiedAllConfigs(true, false, false, true);
1777          projectNode.row = parentNode.row.AddRowAfter(after ? after.row : null);
1778          projectNode.row.tag =(int)projectNode;
1779             
1780          projectNode.row.SetData(null, projectNode);
1781          fileList.currentRow = projectNode.row;
1782
1783          strcpy(filePath, project.topNode.path);
1784          PathCat(filePath, projectNode.path);
1785          PathCat(filePath, projectNode.name);
1786
1787          codeEditor = (CodeEditor)ide.FindWindow(filePath);
1788          if(!codeEditor)
1789          {
1790             Class baseClass = eSystem_FindClass(__thisModule, base);
1791             subclass(ClassDesignerBase) designerClass = eClass_GetDesigner(baseClass);
1792             if(designerClass)
1793             {
1794                codeEditor = (CodeEditor)ide.OpenFile(filePath, normal, false, null, whatever, normal);
1795                strcpy(name, projectNode.name);
1796                sprintf(name, "%s%d", upper, c);
1797                if(className)
1798                   strcpy(className, name);
1799
1800                designerClass.CreateNew(codeEditor.editBox, codeEditor.clientSize, name, base);
1801
1802                //codeEditor.modifiedDocument = false;
1803                //codeEditor.designer.modifiedDocument = false;
1804
1805                //Code_EnsureUpToDate(codeEditor);
1806             }
1807          }
1808          else // TODO: fix no symbols generated when ommiting {} for following else
1809          {
1810             codeEditor = (CodeEditor)ide.OpenFile(filePath, normal, false, null, whatever, normal);
1811          }
1812          if(codeEditor)
1813          {
1814             codeEditor.ViewDesigner();
1815             codeEditor.codeModified = true;
1816          }
1817       }
1818       visible = false;
1819       return codeEditor;   
1820    }
1821
1822    // Returns true if we opened something
1823    bool OpenSelectedNodes()
1824    {
1825       bool result = false;
1826       OldList selection;
1827       OldLink item;
1828
1829       fileList.GetMultiSelection(selection);
1830       for(item = selection.first; item; item = item.next)
1831       {
1832          DataRow row = item.data;
1833          ProjectNode node = (ProjectNode)row.tag;
1834          if(node.type == file)
1835          {
1836             OpenNode(node);
1837             result = true;
1838             break;
1839          }
1840       }
1841       selection.Free(null);
1842       return result;
1843    }
1844
1845    void RemoveSelectedNodes()
1846    {
1847       OldList selection;
1848       OldLink item, next;
1849       
1850       fileList.GetMultiSelection(selection);
1851
1852       // Remove children of parents we're deleting
1853       for(item = selection.first; item; item = next)
1854       {
1855          OldLink i;
1856          DataRow row = item.data;
1857          ProjectNode n, node = (ProjectNode)row.tag;
1858          bool remove = false;
1859
1860          next = item.next;
1861          for(i = selection.first; i && !remove; i = i.next)
1862          {
1863             ProjectNode iNode = (ProjectNode)((DataRow)i.data).tag;
1864             for(n = node.parent; n; n = n.parent)
1865             {
1866                if(iNode == n)
1867                {
1868                   remove = true;
1869                   break;
1870                }
1871             }
1872          }
1873          if(remove)
1874             selection.Delete(item);
1875       }
1876
1877       for(item = selection.first; item; item = item.next)
1878       {
1879          DataRow row = item.data;
1880          ProjectNode node = (ProjectNode)row.tag;
1881          ProjectNode resNode;
1882          for(resNode = node.parent; resNode; resNode = resNode.parent)
1883             if(resNode.type == resources)
1884                break;
1885          if(node.type == file)
1886          {
1887             Project prj = node.project;
1888             DeleteNode(node);
1889             modifiedDocument = true;
1890             prj.topNode.modified = true;
1891             Update(null);
1892             prj.ModifiedAllConfigs(true, false, true, true);
1893          }
1894          else if(node.type == folder)
1895          {
1896             char message[1024];
1897             sprintf(message, $"Are you sure you want to remove the folder \"%s\"\n"
1898                   "and all of its contents from the project?", node.name);
1899             if(MessageBox { master = ide, type = yesNo, text = $"Delete Folder", contents = message }.Modal() == yes)
1900             {
1901                Project prj = node.project;
1902                if(node.containsFile)
1903                   prj.ModifiedAllConfigs(true, false, true, true);
1904                DeleteNode(node);
1905                modifiedDocument = true;
1906                prj.topNode.modified = true;
1907             }
1908          }
1909          else if(node.type == project && node != project.topNode && !buildInProgress)
1910          {
1911             char message[1024];
1912             Project prj = null;
1913             for(p : workspace.projects)
1914             {
1915                if(p.topNode == node)
1916                {
1917                   prj = p;
1918                   break;
1919                }
1920             }
1921             sprintf(message, $"Are you sure you want to remove the \"%s\" project\n" "from this workspace?", node.name);
1922             if(MessageBox { master = ide, type = yesNo, text = $"Remove Project", contents = message }.Modal() == yes)
1923             {
1924                // THIS GOES FIRST!
1925                DeleteNode(node);
1926                if(prj)
1927                   workspace.RemoveProject(prj);
1928                //modifiedDocument = true; // when project view is a workspace view
1929             }
1930          }
1931       }
1932       selection.Free(null);
1933    }
1934 }