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