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