buildsystem,epj2make,ide: fix makefile generation to be compiler agnostic again....
[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(const 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(const char * folderPath, bool isRoot)
24    {
25       stack.lastIterator.Remove(); //stack.Remove();
26    }
27
28    bool OnFile(const char * filePath)
29    {
30       ProjectNode parentNode = stack.lastIterator.data;
31       if(!projectView.AddFile(parentNode, filePath, parentNode.isInResources, false))
32       {
33          char * msg = PrintString($"This file can't be imported due to a conflict.\n\n", filePath,
34                "\n\nThis occurs with identical file paths and with conflicting file names.\n");
35          MessageBox { master = ide, type = ok, text = "Import File Conflict", contents = msg }.Modal();
36          delete msg;
37       }
38       return true;
39    }
40 }
41
42 static Array<FileFilter> fileFilters
43 { [
44    { $"eC/C/C++ Files (*.ec, *.eh, *.c, *.cpp, *.cc, *.cxx, *.h, *.hpp, *.hh, *.hxx)", "ec, eh, c, cpp, cc, cxx, h, hpp, hh, hxx" },
45    { $"eC/C/C++ Source Files (*.ec, *.c, *.cpp, *.cc, *.cxx)", "ec, eh, c, cpp, cc, cxx" },
46    { $"Header Files for eC/C/C++ (*.eh, *.h, *.hpp, *.hh, *.hxx)", "eh, h, hpp, hh, hxx" },
47    { $"All files", null }
48 ] };
49
50 static Array<FileFilter> resourceFilters
51 { [
52    { $"Image Files (*.jpg, *.jpeg, *.bmp, *.pcx, *.png, *.gif)", "jpg, jpeg, bmp, pcx, png, gif" },
53    { $"3D Studio Model Files (*.3ds)", "3ds" },
54    { $"Translations (*.mo)", "mo" },
55    { $"All files", null }
56 ] };
57
58 static Array<FileFilter> projectFilters
59 { [
60    { $"Project Files (*.epj)", ProjectExtension },
61    { $"Workspace Files (*.ews)", WorkspaceExtension }
62 ] };
63
64 static Array<FileType> projectTypes
65 { [
66    { $"Ecere IDE Project", ProjectExtension },
67    { $"Ecere IDE Workspace", WorkspaceExtension }
68 ] };
69
70 static const char * iconNames[] =
71 {
72    "<:ecere>mimeTypes/file.png",                   /*genFile*/
73    "<:ecere>mimeTypes/textEcereWorkspace.png",     /*ewsFile*/
74    "<:ecere>mimeTypes/textEcereProject.png",       /*epjFile*/
75    "<:ecere>places/folder.png",                    /*folder*/
76    "<:ecere>status/folderOpen.png",                /*openFolder*/
77    "<:ecere>mimeTypes/textEcereSource.png",        /*ecFile*/
78    "<:ecere>mimeTypes/textEcereHeader.png",        /*ehFile*/
79    "<:ecere>mimeTypes/textCSource.png",            /*sFile*/ // TODO: change sFile icon to differentiate from cFile icon
80    "<:ecere>mimeTypes/textCSource.png",            /*cFile*/
81    "<:ecere>mimeTypes/textCHeader.png",            /*hFile*/
82    "<:ecere>mimeTypes/textC++Source.png",          /*cppFile*/
83    "<:ecere>mimeTypes/textC++Header.png",          /*hppFile*/
84    "<:ecere>mimeTypes/text.png",                   /*textFile*/
85    "<:ecere>mimeTypes/textHyperTextMarkup.png",    /*webFile*/
86    "<:ecere>mimeTypes/image.png",                  /*pictureFile*/
87    "<:ecere>status/audioVolumeHigh.png",           /*soundFile*/
88    "<:ecere>mimeTypes/package.png",                /*archiveFile*/
89    "<:ecere>mimeTypes/packageSoftware.png",        /*packageFile*/
90    "<:ecere>mimeTypes/packageOpticalDisc.png",     /*opticalMediaImageFile*/
91    "<:ecere>mimeTypes/file.png",                   /*mFile*/ //TODO: create icon for .m file
92    "<:ecere>mimeTypes/file.png"                    /*mmFile*/ //TODO: create icon for .mm file
93 };
94
95 enum PrepareMakefileMethod { normal, force, forceExists };
96
97 enum CleanType { clean, realClean, cleanTarget };
98 enum BuildType { build, rebuild, relink, run, start, restart, clean, install };
99 enum BuildState
100 {
101    none, buildingMainProject, buildingSecondaryProject, compilingFile;
102
103    property bool { get { return this != none; } }
104    //property bool actualBuild { get { return this == buildingMainProject || this == buildingSecondaryProject;  } }
105 };
106
107 class ProjectView : Window
108 {
109    isDocument = true;
110    //hasMinimize = true;
111    hasClose = true;
112    borderStyle = sizable;
113    hasHorzScroll = true;
114    hasVertScroll = true;
115    background = white;
116    size = { 300 };
117    anchor = Anchor { left = 0, top = 0, bottom = 0 };
118    menu = Menu { };
119
120    //hasMinimize = true;
121    saveDialog = projectFileDialog;
122
123    DataRow resourceRow;
124    BuildState buildInProgress;
125    BitmapResource icons[NodeIcons];
126    Project project;
127    Workspace workspace;
128    property Workspace workspace
129    {
130       set
131       {
132          if(workspace)
133          {
134             for(prj : workspace.projects)
135             {
136                DeleteNode(prj.topNode);
137             }
138             workspace.projects.Free();
139             ide.debugger.CleanUp();
140          }
141          workspace = value;
142          if(workspace)
143          {
144             fileDialog.currentDirectory = workspace.workspaceDir;
145             resourceFileDialog.currentDirectory = workspace.workspaceDir;
146             for(prj : workspace.projects)
147                AddNode(prj.topNode, null);
148             ide.statusBar.text = $"Generating Makefile & Dependencies...";
149             app.UpdateDisplay();
150             for(prj : workspace.projects)
151                prj.ModifiedAllConfigs(true, false, false, false);
152             ide.statusBar.text = $"Initializing Debugger"; app.UpdateDisplay();
153             ide.statusBar.text = null;
154             app.UpdateDisplay();
155          }
156       }
157       get { return workspace; }
158    }
159
160    bool drawingInProjectSettingsDialog;
161    bool drawingInProjectSettingsDialogHeader;
162    ProjectSettings projectSettingsDialog;
163
164    bool stopBuild;
165    PopupMenu popupMenu;
166
167    ProjectView()
168    {
169       NodeIcons c;
170       for(c = 0; c < NodeIcons::enumSize; c++)
171       {
172          icons[c] = BitmapResource { iconNames[c], alphaBlend = true };
173          AddResource(icons[c]);
174       }
175       fileList.AddField(DataField { dataType = class(ProjectNode), freeData = false, userData = this });
176    }
177
178    ~ProjectView()
179    {
180       DebugStop();
181       ide.DestroyTemporaryProjectDir();
182       if(project)
183       {
184          workspace.Free();
185          delete workspace;
186       }
187    }
188
189    ListBox fileList
190    {
191       multiSelect = true, fullRowSelect = false, hasVertScroll = true, hasHorzScroll = true;
192       borderStyle = deep, parent = this, collapseControl = true, treeBranches = true;
193       anchor = Anchor { left = 0, right = 0, top = 0 , bottom = 0 };
194
195       background = projectViewBackground;
196       foreground = projectViewText;
197       selectionColor = selectionColor, selectionText = selectionText;
198       stippleColor = skyBlue;
199
200       bool OnActivate(bool active, Window previous, bool * goOnWithActivation, bool direct)
201       {
202          if(!active) Update(null);
203          return ListBox::OnActivate(active, previous, goOnWithActivation, direct);
204       }
205
206       bool NotifyDoubleClick(ListBox listBox, int x, int y, Modifiers mods)
207       {
208          // Prevent the double click from reactivating the project view (returns false if we opened something)
209          return !OpenSelectedNodes(mods.ctrl && mods.shift);
210       }
211
212       bool NotifyRightClick(ListBox listBox, int x, int y, Modifiers mods)
213       {
214          DataRow row = listBox.currentRow;
215          if(row)
216          {
217             bool showDebuggingMenuItems = mods.ctrl && mods.shift;
218             bool showInstallMenuItem = mods.ctrl && mods.shift;
219             ProjectNode node = (ProjectNode)(intptr)row.tag;
220 #ifdef IDE_SHOW_INSTALL_MENU_BUTTON
221             showInstallMenuItem = true;
222 #endif
223             if(node.type == NodeTypes::project || node.type == resources || node.type == file || node.type == folder)
224             {
225                bool na = buildInProgress; // N/A - buildMenuUnavailable
226                Menu pop { };
227
228                if(node.type == NodeTypes::project)
229                {
230                   MenuItem mi;
231                                                                                                                                              mi = ide.projectBuildItem;
232                   MenuItem { pop, $"Build"              , b, f7     , NotifySelect = ProjectBuild      , bitmap = mi.bitmap }.disabled = na; mi = ide.projectLinkItem;
233                   MenuItem { pop, $"Relink"             , l         , NotifySelect = ProjectLink       , bitmap = mi.bitmap }.disabled = na; mi = ide.projectRebuildItem;
234                   MenuItem { pop, $"Rebuild"            , r, shiftF7, NotifySelect = ProjectRebuild    , bitmap = mi.bitmap }.disabled = na; mi = ide.projectCleanTargetItem;
235                   MenuItem { pop, $"Clean Target"       , g         , NotifySelect = ProjectCleanTarget, bitmap = mi.bitmap }.disabled = na; mi = ide.projectCleanItem;
236                   MenuItem { pop, $"Clean"              , c         , NotifySelect = ProjectClean      , bitmap = mi.bitmap }.disabled = na; mi = ide.projectRealCleanItem;
237                   MenuItem { pop, $"Real Clean"                     , NotifySelect = ProjectRealClean  , bitmap = mi.bitmap }.disabled = na; mi = ide.projectRegenerateItem;
238                   MenuItem { pop, $"Regenerate Makefile", m         , NotifySelect = ProjectRegenerate , bitmap = mi.bitmap }.disabled = na;
239                   if(showInstallMenuItem)
240                   {
241                      mi = ide.projectInstallItem;
242                      MenuItem { pop, $"Install"            , t         , NotifySelect = ProjectInstall    , bitmap = mi.bitmap }.disabled = na;
243                   }
244                   if(showDebuggingMenuItems && node.ContainsFilesWithExtension("ec", node.project.config))
245                   {
246                      MenuDivider { pop };
247                      MenuItem { pop, $"Debug Generate Symbols", l, NotifySelect = FileDebugGenerateSymbols }.disabled = na;
248                      MenuItem { pop, $"Debug Precompile", l, NotifySelect = FileDebugPrecompile }.disabled = na;
249                      MenuItem { pop, $"Debug Compile", l, NotifySelect = FileDebugCompile }.disabled = na;
250                   }
251                   MenuDivider { pop };
252                   MenuItem { pop, $"New File...", l, Key { l, ctrl = true }, NotifySelect = ProjectNewFile };
253                   MenuItem { pop, $"New Folder...", n, Key { f, ctrl = true }, NotifySelect = ProjectNewFolder };
254                   MenuItem { pop, $"Import Folder...", i, NotifySelect = ProjectImportFolder };
255                   MenuItem { pop, $"Add Files to Project...", f, NotifySelect = ProjectAddFiles };
256                   MenuDivider { pop };
257                   MenuItem { pop, $"Add New Form...", o, NotifySelect = ProjectAddNewForm };
258                   // MenuItem { pop, "Add New Behavior Graph...", g, NotifySelect = ProjectAddNewGraph };
259                   MenuDivider { pop };
260                   if(node != ((Project)workspace.projects.first).topNode)
261                   {
262                      MenuItem { pop, $"Remove project from workspace", r, NotifySelect = ProjectRemove }.disabled = na;
263                      MenuDivider { pop };
264                   }
265                   MenuItem { pop, $"Settings...", s, Key { f7, alt = true } , NotifySelect = MenuSettings };
266                   MenuDivider { pop };
267                   MenuItem { pop, $"Browse Folder", w, NotifySelect = MenuBrowseFolder };
268                   MenuDivider { pop };
269                   MenuItem { pop, $"Save", v, Key { s, ctrl = true }, NotifySelect = ProjectSave }.disabled = !node.modified;
270                   MenuDivider { pop };
271                   MenuItem { pop, $"Properties...", p, Key { enter, alt = true }, NotifySelect = FileProperties };
272                }
273                else if(node.type == resources)
274                {
275                   MenuItem { pop, $"New File...", l, Key { l, ctrl = true }, NotifySelect = ProjectNewFile };
276                   MenuItem { pop, $"New Folder...", n, Key { f, ctrl = true }, NotifySelect = ProjectNewFolder };
277                   MenuItem { pop, $"Import Folder...", i, NotifySelect = ProjectImportFolder };
278                   MenuItem { pop, $"Add Resources to Project...", f, NotifySelect = ResourcesAddFiles };
279                   MenuItem { pop, $"Browse Folder", w, NotifySelect = MenuBrowseFolder };
280                   MenuDivider { pop };
281                   MenuItem { pop, $"Settings...", s, Key { f7, alt = true } , NotifySelect = MenuSettings };
282                   MenuItem { pop, $"Properties...", p, Key { enter, alt = true }, NotifySelect = FileProperties };
283                }
284                else if(node.type == file)
285                {
286                   MenuItem { pop, $"Open", o, NotifySelect = FileOpenFile };
287                   MenuDivider { pop };
288                   MenuItem { pop, $"Clean", l, NotifySelect = FileClean, bitmap = ide.projectCleanItem.bitmap }.disabled = na;
289                   MenuItem { pop, $"Compile", c, Key { f7, ctrl = true}, NotifySelect = FileCompile, bitmap = ide.projectBuildItem.bitmap }.disabled = na;
290                   if(showDebuggingMenuItems)
291                   {
292                      char extension[MAX_EXTENSION];
293                      GetExtension(node.name, extension);
294                      if(!strcmpi(extension, "ec"))
295                      {
296                         MenuDivider { pop };
297                         MenuItem { pop, $"Debug Precompile", l, NotifySelect = FileDebugPrecompile }.disabled = na;
298                         MenuItem { pop, $"Debug Compile", l, NotifySelect = FileDebugCompile }.disabled = na;
299                      }
300                   }
301                   MenuDivider { pop };
302                   MenuItem { pop, $"Remove", r, NotifySelect = FileRemoveFile };
303                   MenuDivider { pop };
304                   MenuItem { pop, $"Browse Folder", w, NotifySelect = MenuBrowseFolder };
305                   MenuDivider { pop };
306                   MenuItem { pop, $"Settings...", s, Key { f7, alt = true } , NotifySelect = MenuSettings };
307                   MenuItem { pop, $"Properties..", p, Key { enter, alt = true }, NotifySelect = FileProperties };
308                }
309                else if(node.type == folder)
310                {
311                   bool isInResources = node.isInResources;
312
313                   MenuItem { pop, $"New File...", l, Key { l, ctrl = true }, NotifySelect = ProjectNewFile };
314                   MenuItem { pop, $"New Folder...", n, Key { f, ctrl = true }, NotifySelect = ProjectNewFolder };
315                   MenuItem { pop, $"Import Folder...", i, NotifySelect = ProjectImportFolder };
316                   if(isInResources)
317                   {
318                      MenuItem { pop, $"Add Resources to Folder...", f, NotifySelect = ResourcesAddFiles };
319                   }
320                   else
321                   {
322                      MenuItem { pop, $"Add Files to Folder...", f, NotifySelect = ProjectAddFiles };
323                   }
324                   if(!isInResources)
325                   {
326                      MenuDivider { pop };
327                      MenuItem { pop, $"Add New Form...", o, NotifySelect = ProjectAddNewForm };
328                      // MenuItem { pop, $"Add New Behavior Graph...", g, NotifySelect = ProjectAddNewGraph };
329                   }
330                   MenuDivider { pop };
331                   MenuItem { pop, $"Clean", l, NotifySelect = FileClean, bitmap = ide.projectCleanItem.bitmap }.disabled = na;
332                   MenuItem { pop, $"Compile", c, Key { f7, ctrl = true}, NotifySelect = FileCompile, bitmap = ide.projectBuildItem.bitmap }.disabled = na;
333                   MenuDivider { pop };
334                   MenuItem { pop, $"Remove", r, NotifySelect = FileRemoveFile };
335                   MenuDivider { pop };
336                   MenuItem { pop, $"Browse Folder", w, NotifySelect = MenuBrowseFolder };
337                   MenuDivider { pop };
338                   MenuItem { pop, $"Settings...", s, Key { f7, alt = true } , NotifySelect = MenuSettings };
339                   MenuItem { pop, $"Properties...", p, Key { enter, alt = true }, NotifySelect = FileProperties };
340                }
341
342                popupMenu =
343                {
344                   master = this, menu = pop;
345                   position = {
346                      x + clientStart.x + absPosition.x - app.desktop.position.x,
347                      y + clientStart.y + absPosition.y - app.desktop.position.y };
348
349                   void NotifyDestroyed(Window window, DialogResult result)
350                   {
351                      popupMenu = null;
352                   }
353                };
354                popupMenu.Create();
355                ide.AdjustPopupBuildMenus();
356             }
357          }
358          return true;
359       }
360
361       bool NotifyKeyHit(ListBox listBox, DataRow row, Key key, unichar ch)
362       {
363          if(key == altUp || key == altDown)
364          {
365             SelectNextProject(key == altUp);
366             return false;
367          }
368          return true;
369       }
370
371       bool NotifyKeyDown(ListBox listBox, DataRow row, Key key, unichar ch)
372       {
373          if(row)
374          {
375             ProjectNode node = (ProjectNode)(intptr)row.tag;
376             switch(key)
377             {
378                case altEnter: case Key { keyPadEnter, alt = true }:
379                {
380                   NodeProperties { parent = parent, master = this,
381                      position = { position.x + 100, position.y + 100 }, node = node }.Create();
382                   return false;
383                }
384                case enter: case keyPadEnter:
385                {
386                   ProjectNode resNode;
387                   for(resNode = node.parent; resNode; resNode = resNode.parent)
388                      if(resNode.type == resources)
389                         break;
390                   if(node.type == project || (node.type == folder && !resNode))
391                   {
392                      AddFiles(false);
393                      return false;
394                   }
395                   else if(node.type == resources || node.type == folder)
396                   {
397                      AddFiles(true);
398                      return false;
399                   }
400                   break;
401                }
402                case ctrlI:
403                {
404                   if(node.type == project || node.type == folder || node.type == resources)
405                   {
406                      ImportFolder(node);
407                      return false;
408                   }
409                   break;
410                }
411                case ctrlF:
412                {
413                   if(node.type == project || node.type == folder || node.type == resources)
414                   {
415                      NewFolder(node, null, true);
416                      return false;
417                   }
418                   break;
419                }
420                case ctrlF7:
421                {
422                   if(node.type == file)
423                   {
424                      FileCompile(null, (Modifiers)key);
425                      return false;
426                   }
427                   break;
428                }
429                case Key { space, false, true }:
430                case Key { space, true, true }:
431                case Key { space, true }:
432                case space:
433                {
434                   if(node.type == NodeTypes::project)
435                   {
436                      Project prj = null;
437                      for(p : workspace.projects)
438                      {
439                         if(p.topNode == node)
440                         {
441                            prj = p;
442                            break;
443                         }
444                      }
445                      prj.RotateActiveConfig(!key.shift, key.ctrl);
446                      if(prj == project)
447                         ide.AdjustMenus();
448                      return false;
449                   }
450                   break;
451                }
452             }
453          }
454          switch(key)
455          {
456             case Key { enter, true, true }:        OpenSelectedNodes(true);   break;
457             case Key { keyPadEnter, true, true }:  OpenSelectedNodes(true);   break;
458             case enter: case keyPadEnter:          OpenSelectedNodes(false);  break;
459             case del:                              RemoveSelectedNodes();     break;
460             case escape:
461             {
462                Window activeClient = ide.activeClient;
463                if(activeClient)
464                   activeClient.Activate();
465                else
466                   ide.RepositionWindows(true);
467                break;
468             }
469          }
470          return true;
471       }
472
473       bool NotifyCollapse(ListBox listBox, DataRow row, bool collapsed)
474       {
475          ProjectNode node = (ProjectNode)(intptr)row.tag;
476          if(node.type == folder)
477             node.icon = collapsed ? folder : openFolder;
478          return true;
479       }
480    };
481
482    FileDialog importFileDialog { autoCreate = false, type = selectDir, text = $"Import Folder" };
483    FileDialog projectFileDialog
484    {
485       autoCreate = false, filters = projectFilters.array, sizeFilters = projectFilters.count * sizeof(FileFilter);
486       types = projectTypes.array, sizeTypes = projectTypes.count * sizeof(FileType);
487    };
488    FileDialog fileDialog
489    {
490       autoCreate = false, mayNotExist = true, filters = fileFilters.array, sizeFilters = fileFilters.count * sizeof(FileFilter);
491    };
492    FileDialog resourceFileDialog
493    {
494       autoCreate = false, mayNotExist = true, filters = resourceFilters.array, sizeFilters = resourceFilters.count * sizeof(FileFilter);
495    };
496
497    Menu fileMenu { menu, $"File", f };
498    MenuItem { fileMenu, $"Save", s, Key { s, ctrl = true }, NotifySelect = MenuFileSave };
499    // MenuItem { fileMenu, "Save As...", a, NotifySelect = MenuFileSaveAs };
500
501    bool OnClose(bool parentClosing)
502    {
503       if(!parentClosing && visible)
504       {
505          visible = false;
506          return false;
507       }
508       if(buildInProgress)
509          return false;
510
511       if(modifiedDocument)
512       {
513          DialogResult dialogRes;
514          char msg[2048];
515          bool first = true;
516          strcpy(msg, $"You have modified projects.\nSave changes to ");
517          for(p : ide.workspace.projects)
518          {
519             if(p.topNode.modified)
520             {
521                if(!first) strcat(msg, ", ");
522                strcat(msg, p.name);
523                first = false;
524             }
525          }
526          strcat(msg, "?");
527
528          dialogRes = MessageBox { master = master, type = yesNoCancel, text = parent.caption ? parent.caption : rootWindow.caption, contents = msg }.Modal();
529
530          if(dialogRes == yes)
531          {
532             // TOFIX: Precomp error if brackets are taken out
533             return (DialogResult)MenuFileSave(null, 0) != cancel;
534          }
535          else if(dialogRes == cancel)
536             return false;
537          modifiedDocument = false;
538       }
539       return true;
540    }
541
542    void OnDestroy(void)
543    {
544       //if(ide.findInFilesDialog && ide.findInFilesDialog.created && ide.findInFilesDialog.mode != directory)
545       //   ide.findInFilesDialog.SearchStop();
546
547       ide.outputView.buildBox.Clear();
548       ide.outputView.debugBox.Clear();
549       //ide.outputView.findBox.Clear();
550       ide.callStackView.Clear();
551       ide.watchesView.Clear();
552       ide.threadsView.Clear();
553       ide.breakpointsView.Clear();
554       ide.outputView.ShowClearSelectTab(find); // why this?
555    }
556
557    bool OnSaveFile(const char * fileName)
558    {
559       for(prj : ide.workspace.projects)
560       {
561          if(prj.topNode.modified)
562          {
563             prj.StopMonitoring();
564             if(prj.Save(prj.filePath))
565                prj.topNode.modified = false;
566             prj.StartMonitoring();
567          }
568       }
569       modifiedDocument = false;
570       Update(null);
571       return true;
572    }
573
574    bool IsModuleInProject(const char * filePath)
575    {
576       char moduleName[MAX_FILENAME]; //, modulePath[MAX_LOCATION];
577       GetLastDirectory(filePath, moduleName);
578       return project.topNode.Find(moduleName, false) != null;
579    }
580
581    ProjectNode GetNodeForCompilationFromWindow(Window document, bool nonExcludedFirst, bool * isExcluded, bool * isCObject)
582    {
583       ProjectNode node = null;
584       if(nonExcludedFirst)
585          node = GetNodeFromWindow(document, null, false, false, isExcluded);
586       if(!node)
587          node = GetNodeFromWindow(document, null, true, false, isExcluded);
588       if(!node && nonExcludedFirst)
589       {
590          node = GetNodeFromWindow(document, null, false, true, isExcluded);
591          if(isCObject && node) *isCObject = true;
592       }
593       if(!node)
594       {
595          node = GetNodeFromWindow(document, null, true, true, isExcluded);
596          if(isCObject && node) *isCObject = true;
597       }
598       return node;
599    }
600
601    ProjectNode GetNodeFromWindow(Window document, Project project, bool allNodes, bool isCObject, bool * isNodeExcluded)
602    {
603       ProjectNode node = null;
604       if(document.fileName)
605       {
606          bool excluded = false;
607          char winFileName[MAX_LOCATION];
608          char * documentFileName = GetSlashPathBuffer(winFileName, document.fileName);
609          Project prj;
610          ProjectNode n;
611          if(isCObject)
612          {
613             char name[MAX_FILENAME];
614             GetLastDirectory(documentFileName, name);
615             ChangeExtension(name, "ec", name);
616             for(p : ide.workspace.projects)
617             {
618                prj = project ? project : p;
619                if((n = prj.topNode.Find(name, false)))
620                {
621                   if(allNodes || !(excluded = n.GetIsExcluded(prj.config)))
622                   {
623                      node = n;
624                      break;
625                   }
626                }
627                if(project) break;
628             }
629          }
630          else
631          {
632             for(p : ide.workspace.projects)
633             {
634                prj = project ? project : p;
635                if((n = prj.topNode.FindByFullPath(documentFileName, false)))
636                {
637                   if(allNodes || !(excluded = n.GetIsExcluded(prj.config)))
638                   {
639                      node = n;
640                      break;
641                   }
642                }
643                if(project) break;
644             }
645          }
646          if(node && isNodeExcluded)
647             *isNodeExcluded = excluded;
648       }
649       return node;
650    }
651
652    //                          ((( UTILITY FUNCTIONS )))
653    //
654    //  ************************************************************************
655    //  *** These methods below are part of a sequence of events, and as     ***
656    //  *** such they must be passed the current compiler and project config ***
657    //  ************************************************************************
658    bool DisplayCompiler(CompilerConfig compiler, bool cleanLog)
659    {
660       ide.outputView.buildBox.Logf($"%s Compiler\n", compiler ? compiler.name : $"{problem with compiler selection}");
661       return true;
662    }
663
664    bool ProjectPrepareForToolchain(Project project, PrepareMakefileMethod method, bool cleanLog, bool displayCompiler,
665       CompilerConfig compiler, ProjectConfig config)
666    {
667       ShowOutputBuildLog(cleanLog);
668
669       if(displayCompiler)
670          DisplayCompiler(compiler, false);
671
672       ProjectPrepareCompiler(project, compiler, false);
673       ProjectPrepareMakefile(project, method, compiler, config);
674       return true;
675    }
676
677    bool ProjectPrepareCompiler(Project project, CompilerConfig compiler, bool silent)
678    {
679       if((!project.GenerateCrossPlatformMk(app.includeFile) ||
680             !project.GenerateCompilerCf(compiler, project.topNode.ContainsFilesWithExtension("ec", project.config))) && !silent)
681          ide.outputView.buildBox.Logf($"Error generating compiler configuration (Is the project/config directory writable?)\n");
682       return true;
683    }
684
685    // Note: Compiler is only passed in to for VisualStudio support
686    bool ProjectPrepareMakefile(Project project, PrepareMakefileMethod method, CompilerConfig compiler, ProjectConfig config)
687    {
688       if(compiler.type.isVC)
689       {
690          // I'm guessing we'll want to support generating VS files on Linux as well...
691          ide.statusBar.text = $"Generating Visual Studio Solution...";
692          app.UpdateDisplay();
693          //GenerateVSSolutionFile(project, compiler);
694          ide.statusBar.text = $"Generating Visual Studio Project...";
695          app.UpdateDisplay();
696          //GenerateVCProjectFile(project, compiler, bitDepth);
697          ide.statusBar.text = null;
698          app.UpdateDisplay();
699          return true;
700       }
701       else
702       {
703          char makefilePath[MAX_LOCATION];
704          char makefileName[MAX_LOCATION];
705          bool exists;
706          LogBox logBox = ide.outputView.buildBox;
707
708          strcpy(makefilePath, project.topNode.path);
709          project.CatMakeFileName(makefileName, config);
710          PathCatSlash(makefilePath, makefileName);
711
712          exists = FileExists(makefilePath);
713          if(method == force ||
714            (method == forceExists && exists) ||
715            (method == normal && (!exists || (config && config.makingModified))))
716          {
717             const char * reason;
718             const char * action;
719             ide.statusBar.text = $"Generating Makefile & Dependencies..."; // Dependencies?
720             app.UpdateDisplay();
721
722             if((method == normal && !exists) || (method == force && !exists))
723                action = $"Generating ";
724             else if(method == force)
725                action = $"Regenerating ";
726             else if(method == normal || method == forceExists)
727                action = $"Updating ";
728             else
729                action = "";
730             if(!exists)
731                reason = $"Makefile doesn't exist. ";
732             else if(project.topNode.modified)
733                reason = $"Project has been modified. ";
734             else
735                reason = "";
736
737             //logBox.Logf("%s\n", makefileName);
738             logBox.Logf($"%s - %s%smakefile for %s config...\n", makefileName, reason, action, GetConfigName(config));
739
740             if(!project.GenerateMakefile(null, false, null, config))
741                ide.outputView.buildBox.Logf($"Error generating makefile (Is the project directory writable?)\n");
742
743             ide.statusBar.text = null;
744             app.UpdateDisplay();
745             return true;
746          }
747       }
748       return false;
749    }
750
751    bool BuildInterrim(Project prj, BuildType buildType, CompilerConfig compiler, ProjectConfig config, int bitDepth, bool justPrint, bool raw)
752    {
753       if(ProjectPrepareForToolchain(prj, normal, true, true, compiler, config))
754       {
755          ide.outputView.buildBox.Logf($"Building project %s using the %s configuration...\n", prj.name, GetConfigName(config));
756          return Build(prj, buildType, compiler, config, bitDepth, justPrint, raw);
757       }
758       return false;
759    }
760
761    bool DebugStopForMake(Project prj, BuildType buildType, CompilerConfig compiler, ProjectConfig config)
762    {
763       bool result = false;
764       // TOFIX: DebugStop is being abused and backfiring on us.
765       //        It's supposed to be the 'Debug/Stop' item, not unloading executable or anything else
766
767       //        configIsInDebugSession seems to be used for two OPPOSITE things:
768       //        If we're debugging another config, we need to unload the executable!
769       //        In building, we want to stop if we're debugging the 'same' executable
770       if(buildType != run) ///* && prj == project*/ && prj.configIsInDebugSession)
771       {
772          if(buildType == start || buildType == restart)
773          {
774             if(ide.debugger && ide.debugger.isPrepared)
775                result = DebugStop();
776          }
777          else
778          {
779             if(ide.project == prj && ide.debugger && ide.debugger.prjConfig == config && ide.debugger.isPrepared)
780                result = DebugStop();
781          }
782       }
783       app.ProcessInput(true);
784       ShowOutputBuildLog(false);
785       return result;
786    }
787
788    bool Build(Project prj, BuildType buildType, CompilerConfig compiler, ProjectConfig config, int bitDepth, bool justPrint, bool raw)
789    {
790       bool result = true;
791       Window document;
792
793       stopBuild = false;
794       for(document = master.firstChild; document; document = document.next)
795       {
796          if(document.modifiedDocument)
797          {
798             ProjectNode node = GetNodeFromWindow(document, prj, true, false, null);
799             if(node && !document.MenuFileSave(null, 0))
800             {
801                result = false;
802                break;
803             }
804          }
805       }
806       if(result)
807       {
808          DirExpression targetDir = prj.GetTargetDir(compiler, config, bitDepth);
809
810          DebugStopForMake(prj, buildType, compiler, config);
811
812          // TODO: Disabled until problems fixed... is it fixed?
813          if(buildType == rebuild || (config && config.compilingModified))
814             prj.Clean(compiler, config, bitDepth, clean, justPrint, raw);
815          else
816          {
817             if(buildType == relink || (config && config.linkingModified))
818                prj.Clean(compiler, config, bitDepth, cleanTarget, false, raw);
819             if(config && config.symbolGenModified)
820             {
821                DirExpression objDir = prj.GetObjDir(compiler, config, bitDepth);
822                char fileName[MAX_LOCATION];
823                char moduleName[MAX_FILENAME];
824                strcpy(fileName, prj.topNode.path);
825                PathCatSlash(fileName, objDir.dir);
826                ReplaceSpaces(moduleName, prj.moduleName);
827                strcat(moduleName, ".main.ec");
828                PathCatSlash(fileName, moduleName);
829                if(FileExists(fileName))
830                   DeleteFile(fileName);
831                ChangeExtension(fileName, "c", fileName);
832                if(FileExists(fileName))
833                   DeleteFile(fileName);
834                ChangeExtension(fileName, "o", fileName);
835                if(FileExists(fileName))
836                   DeleteFile(fileName);
837
838                delete objDir;
839             }
840          }
841          buildInProgress = prj == project ? buildingMainProject : buildingSecondaryProject;
842          ide.AdjustBuildMenus();
843          ide.AdjustDebugMenus();
844
845          result = prj.Build(buildType, null, compiler, config, bitDepth, justPrint, raw, normal);
846
847          if(config)
848          {
849             config.compilingModified = false;
850             if(!stopBuild)
851                config.linkingModified = false;
852
853             config.symbolGenModified = false;
854          }
855          buildInProgress = none;
856          ide.AdjustBuildMenus();
857          ide.AdjustDebugMenus();
858
859          ide.workspace.modified = true;
860
861          delete targetDir;
862       }
863       return result;
864    }
865
866    //                          ((( USER ACTIONS )))
867    //
868    //  ************************************************************************
869    //  *** Methods below should atomically start a process, and as such     ***
870    //  *** they can query compiler and config directly from ide and project ***
871    //  *** but ONLY ONCE!!!                                                 ***
872    //  ************************************************************************
873
874    bool ProjectBuild(MenuItem selection, Modifiers mods)
875    {
876       if(buildInProgress == none)
877       {
878          Project prj = project;
879          CompilerConfig compiler = ideSettings.GetCompilerConfig(ide.workspace.compiler);
880          int bitDepth = ide.workspace.bitDepth;
881          ProjectConfig config;
882          if(selection || !ide.activeClient)
883          {
884             DataRow row = fileList.currentRow;
885             ProjectNode node = row ? (ProjectNode)(intptr)row.tag : null;
886             if(node) prj = node.project;
887          }
888          else
889          {
890             ProjectNode node = GetNodeForCompilationFromWindow(ide.activeClient, true, null, null);
891             if(node)
892                prj = node.project;
893          }
894          config = prj.config;
895          if(/*prj != project || */!prj.GetConfigIsInDebugSession(config) || !ide.DontTerminateDebugSession($"Project Build"))
896          {
897             BuildInterrim(prj, build, compiler, config, bitDepth, mods.ctrl && mods.shift, mods.ctrl && !mods.shift);
898          }
899          delete compiler;
900       }
901       else
902          stopBuild = true;
903       return true;
904    }
905
906    bool ProjectInstall(MenuItem selection, Modifiers mods)
907    {
908       Project prj = project;
909       CompilerConfig compiler = ideSettings.GetCompilerConfig(ide.workspace.compiler);
910       int bitDepth = ide.workspace.bitDepth;
911       ProjectConfig config;
912       if(selection || !ide.activeClient)
913       {
914          DataRow row = fileList.currentRow;
915          ProjectNode node = row ? (ProjectNode)(intptr)row.tag : null;
916          if(node) prj = node.project;
917       }
918       else
919       {
920          ProjectNode node = GetNodeFromWindow(ide.activeClient, null, true, false, null);
921          if(node)
922             prj = node.project;
923       }
924       config = prj.config;
925       if(!prj.GetConfigIsInDebugSession(config) ||
926             (!ide.DontTerminateDebugSession($"Project Install") && DebugStopForMake(prj, relink, compiler, config)))
927       {
928          BuildInterrim(prj, build, compiler, config, bitDepth, mods.ctrl && mods.shift, mods.ctrl && !mods.shift);
929          if(ProjectPrepareForToolchain(prj, normal, false, false, compiler, config))
930          {
931             ide.outputView.buildBox.Logf($"\nInstalling project %s using the %s configuration...\n", prj.name, GetConfigName(config));
932             Build(prj, install, compiler, config, bitDepth, mods.ctrl && mods.shift, mods.ctrl && !mods.shift);
933          }
934       }
935       delete compiler;
936       return true;
937    }
938
939    bool ProjectLink(MenuItem selection, Modifiers mods)
940    {
941       Project prj = project;
942       CompilerConfig compiler = ideSettings.GetCompilerConfig(ide.workspace.compiler);
943       int bitDepth = ide.workspace.bitDepth;
944       ProjectConfig config;
945       if(selection || !ide.activeClient)
946       {
947          DataRow row = fileList.currentRow;
948          ProjectNode node = row ? (ProjectNode)(intptr)row.tag : null;
949          if(node) prj = node.project;
950       }
951       else
952       {
953          ProjectNode node = GetNodeFromWindow(ide.activeClient, null, true, false, null);
954          if(node)
955             prj = node.project;
956       }
957       config = prj.config;
958       if(!prj.GetConfigIsInDebugSession(config) ||
959             (!ide.DontTerminateDebugSession($"Project Link") && DebugStopForMake(prj, relink, compiler, config)))
960       {
961          if(ProjectPrepareForToolchain(prj, normal, true, true, compiler, config))
962          {
963             ide.outputView.buildBox.Logf($"Relinking project %s using the %s configuration...\n", prj.name, GetConfigName(config));
964             if(config)
965                config.linkingModified = true;
966             Build(prj, relink, compiler, config, bitDepth, mods.ctrl && mods.shift, mods.ctrl && !mods.shift);
967          }
968       }
969       delete compiler;
970       return true;
971    }
972
973    bool ProjectRebuild(MenuItem selection, Modifiers mods)
974    {
975       CompilerConfig compiler = ideSettings.GetCompilerConfig(ide.workspace.compiler);
976       int bitDepth = ide.workspace.bitDepth;
977       Project prj = project;
978       ProjectConfig config;
979       if(selection || !ide.activeClient)
980       {
981          DataRow row = fileList.currentRow;
982          ProjectNode node = row ? (ProjectNode)(intptr)row.tag : null;
983          if(node) prj = node.project;
984       }
985       else
986       {
987          ProjectNode node = GetNodeFromWindow(ide.activeClient, null, true, false, null);
988          if(node)
989             prj = node.project;
990       }
991       config = prj.config;
992       if(!prj.GetConfigIsInDebugSession(config) ||
993             (!ide.DontTerminateDebugSession($"Project Rebuild") && DebugStopForMake(prj, rebuild, compiler, config)))
994       {
995          if(ProjectPrepareForToolchain(prj, normal, true, true, compiler, config))
996          {
997             ide.outputView.buildBox.Logf($"Rebuilding project %s using the %s configuration...\n", prj.name, GetConfigName(config));
998             /*if(config)
999             {
1000                config.compilingModified = true;
1001                config.makingModified = true;
1002             }*/ // -- should this still be used depite the new solution of BuildType?
1003             Build(prj, rebuild, compiler, config, bitDepth, mods.ctrl && mods.shift, mods.ctrl && !mods.shift);
1004          }
1005       }
1006       delete compiler;
1007       return true;
1008    }
1009
1010    bool ProjectCleanTarget(MenuItem selection, Modifiers mods)
1011    {
1012       CleanProject($"Project Clean Target", $"Cleaning project %s target using the %s configuration...\n", selection, cleanTarget, mods.ctrl && mods.shift, mods.ctrl && !mods.shift);
1013       return true;
1014    }
1015
1016    bool ProjectClean(MenuItem selection, Modifiers mods)
1017    {
1018       CleanProject($"Project Clean", $"Cleaning project %s using the %s configuration...\n", selection, clean, mods.ctrl && mods.shift, mods.ctrl && !mods.shift);
1019       return true;
1020    }
1021
1022    bool ProjectRealClean(MenuItem selection, Modifiers mods)
1023    {
1024       CleanProject($"Project Real Clean", $"Removing intermediate objects directory for project %s using the %s configuration...\n", selection, realClean, mods.ctrl && mods.shift, mods.ctrl && !mods.shift);
1025       return true;
1026    }
1027
1028    void CleanProject(const char * terminateDebugSessionMessage, const char * cleaningMessageLogFormat, MenuItem selection, CleanType cleanType, bool justPrint, bool raw)
1029    {
1030       Project prj = project;
1031       Array<Project> projects { };
1032       CompilerConfig compiler = ideSettings.GetCompilerConfig(ide.workspace.compiler);
1033       int bitDepth = ide.workspace.bitDepth;
1034       if(selection)
1035       {
1036          OldLink item;
1037          OldList selectedRows;
1038          fileList.GetMultiSelection(selectedRows);
1039          for(item = selectedRows.first; item; item = item.next)
1040          {
1041             DataRow row = item.data;
1042             ProjectNode node = (ProjectNode)(intptr)row.tag;
1043             if(node.type == project)
1044                projects.Add(node.project);
1045          }
1046          selectedRows.Free(null);
1047       }
1048       if(selection || !ide.activeClient)
1049       {
1050          DataRow row = fileList.currentRow;
1051          ProjectNode node = row ? (ProjectNode)(intptr)row.tag : null;
1052          if(node) prj = node.project;
1053          if(projects.count == 0)
1054             projects.Add(prj);
1055       }
1056       else
1057       {
1058          // TODO: a file can belong to more than one project, ask which one to clean
1059          ProjectNode node = GetNodeFromWindow(ide.activeClient, null, true, false, null);
1060          if(node) prj = node.project;
1061          if(projects.count == 0)
1062             projects.Add(prj);
1063       }
1064       for(prj : projects)
1065       {
1066          ProjectConfig config = prj.config;
1067          if(!prj.GetConfigIsInDebugSession(config) ||
1068                (!ide.DontTerminateDebugSession(terminateDebugSessionMessage) && DebugStopForMake(prj, clean, compiler, config)))
1069          {
1070             if(ProjectPrepareForToolchain(prj, normal, true, true, compiler, config))
1071             {
1072                ide.outputView.buildBox.Logf(cleaningMessageLogFormat, prj.name, GetConfigName(config));
1073
1074                buildInProgress = prj == project ? buildingMainProject : buildingSecondaryProject;
1075                ide.AdjustBuildMenus();
1076                ide.AdjustDebugMenus();
1077
1078                prj.Clean(compiler, config, bitDepth, cleanType, justPrint, raw);
1079                buildInProgress = none;
1080                ide.AdjustBuildMenus();
1081                ide.AdjustDebugMenus();
1082             }
1083          }
1084       }
1085       delete compiler;
1086       delete projects;
1087    }
1088
1089    bool ProjectRegenerate(MenuItem selection, Modifiers mods)
1090    {
1091       Project prj = project;
1092       CompilerConfig compiler = ideSettings.GetCompilerConfig(ide.workspace.compiler);
1093       ShowOutputBuildLog(true);
1094       if(selection || !ide.activeClient)
1095       {
1096          DataRow row = fileList.currentRow;
1097          ProjectNode node = row ? (ProjectNode)(intptr)row.tag : null;
1098          if(node)
1099             prj = node.project;
1100       }
1101       else
1102       {
1103          ProjectNode node = GetNodeFromWindow(ide.activeClient, null, true, false, null);
1104          if(node)
1105             prj = node.project;
1106       }
1107
1108       DisplayCompiler(compiler, false);
1109       ProjectPrepareCompiler(project, compiler, false);
1110       ProjectPrepareMakefile(prj, force, compiler, prj.config);
1111       delete compiler;
1112       return true;
1113    }
1114
1115    bool Compile(Project project, List<ProjectNode> nodes, bool justPrint, bool raw, SingleFileCompileMode mode)
1116    {
1117       bool result = true;
1118       Window document;
1119       ProjectConfig config = project.config;
1120
1121       stopBuild = false;
1122
1123       for(document = ide.firstChild; document; document = document.next)
1124       {
1125          if(document.modifiedDocument)
1126          {
1127             ProjectNode n = GetNodeFromWindow(document, project, true, mode == cObject ? true : false, null);
1128             for(node : nodes)
1129             {
1130                if(n && n.IsInNode(node) && !document.MenuFileSave(null, 0))
1131                {
1132                   ide.outputView.buildBox.Logf($"Unable to save %s file.\n", node.name);
1133                   result = false;
1134                   break;
1135                }
1136             }
1137          }
1138       }
1139
1140       if(result)
1141       {
1142          CompilerConfig compiler = ideSettings.GetCompilerConfig(ide.workspace.compiler);
1143          int bitDepth = ide.workspace.bitDepth;
1144          result = false;
1145          if(ProjectPrepareForToolchain(project, normal, true, true, compiler, config))
1146          {
1147             if(config)
1148                ide.outputView.buildBox.Logf($"%s specific file(s) in project %s using the %s configuration...\n",
1149                      (mode == normal || mode == cObject) ? $"Compiling" : $"Debug compiling", project.name, config.name);
1150             else
1151                ide.outputView.buildBox.Logf($"%s specific file(s) in project %s...\n",
1152                      (mode == normal || mode == cObject) ? $"Compiling" : $"Debug compiling", project.name);
1153
1154             buildInProgress = compilingFile;
1155             ide.AdjustBuildMenus();
1156             result = project.Compile(nodes, compiler, config, bitDepth, justPrint, raw, mode);
1157             buildInProgress = none;
1158             ide.AdjustBuildMenus();
1159          }
1160          delete compiler;
1161       }
1162       return result;
1163    }
1164
1165    bool Clean(Project project, List<ProjectNode> nodes, bool justPrint)
1166    {
1167       bool result = true;
1168       Window document;
1169       ProjectConfig config = project.config;
1170
1171       stopBuild = false;
1172
1173       for(document = ide.firstChild; document; document = document.next)
1174       {
1175          if(document.modifiedDocument)
1176          {
1177             ProjectNode n = GetNodeFromWindow(document, project, true, false, null);
1178             for(node : nodes)
1179             {
1180                if(n && n.IsInNode(node) && !document.MenuFileSave(null, 0))
1181                {
1182                   ide.outputView.buildBox.Logf($"Unable to save %s file.\n", node.name);
1183                   result = false;
1184                   break;
1185                }
1186             }
1187          }
1188       }
1189
1190       if(result)
1191       {
1192          CompilerConfig compiler = ideSettings.GetCompilerConfig(ide.workspace.compiler);
1193          int bitDepth = ide.workspace.bitDepth;
1194          result = false;
1195          if(ProjectPrepareForToolchain(project, normal, true, true, compiler, config))
1196          {
1197             Map<String, NameCollisionInfo> namesInfo { };
1198             project.topNode.GenMakefileGetNameCollisionInfo(namesInfo, config);
1199             for(node : nodes)
1200             {
1201                if(node.GetIsExcluded(config))
1202                   ide.outputView.buildBox.Logf($"File %s is excluded from current build configuration.\n", node.name);
1203                else
1204                {
1205                   if(config)
1206                      ide.outputView.buildBox.Logf($"Deleting intermediate objects for %s %s in project %s using the %s configuration...\n",
1207                            node.type == file ? $"single file" : $"folder", node.name, project.name, config.name);
1208                   else
1209                      ide.outputView.buildBox.Logf($"Deleting intermediate objects for %s %s in project %s...\n",
1210                            node.type == file ? $"single file" : $"folder", node.name, project.name);
1211
1212                   node.DeleteIntermediateFiles(compiler, config, bitDepth, namesInfo, false);
1213                   result = true;
1214                }
1215             }
1216             namesInfo.Free();
1217             delete namesInfo;
1218          }
1219          delete compiler;
1220       }
1221       return result;
1222    }
1223
1224    bool ProjectNewFile(MenuItem selection, Modifiers mods)
1225    {
1226       DataRow row = fileList.currentRow;
1227       if(row)
1228       {
1229          char fileName[1024];
1230          char filePath[MAX_LOCATION];
1231          ProjectNode parentNode = (ProjectNode)(intptr)row.tag;
1232          ProjectNode n, fileNode;
1233          parentNode.GetFileSysMatchingPath(filePath);
1234          MakePathRelative(filePath, parentNode.project.topNode.path, filePath);
1235          for(n = parentNode; n && n != parentNode.project.resNode; n = n.parent);
1236          sprintf(fileName, $"Untitled %d", documentID);
1237          fileNode = AddFile(parentNode, fileName, n != null, true);
1238          fileNode.path = CopyUnixPath(filePath);
1239          if(fileNode)
1240          {
1241             NodeProperties nodeProperties
1242             {
1243                parent, this;
1244                position = { position.x + 100, position.y + 100 };
1245                mode = newFile;
1246                node = fileNode;
1247             };
1248             nodeProperties.Create(); // not modal?
1249          }
1250       }
1251       return true;
1252    }
1253
1254    bool ProjectNewFolder(MenuItem selection, Modifiers mods)
1255    {
1256       DataRow row = fileList.currentRow;
1257       if(row)
1258       {
1259          ProjectNode parentNode = (ProjectNode)(intptr)row.tag;
1260          NewFolder(parentNode, null, true);
1261       }
1262       return true;
1263    }
1264
1265    bool ResourcesAddFiles(MenuItem selection, Modifiers mods)
1266    {
1267       AddFiles(true);
1268       return true;
1269    }
1270
1271    bool ProjectAddFiles(MenuItem selection, Modifiers mods)
1272    {
1273       AddFiles(false);
1274       return true;
1275    }
1276
1277    bool ProjectImportFolder(MenuItem selection, Modifiers mods)
1278    {
1279       DataRow row = fileList.currentRow;
1280       if(row)
1281       {
1282          ProjectNode toNode = (ProjectNode)(intptr)row.tag;
1283          ImportFolder(toNode);
1284       }
1285       return true;
1286    }
1287
1288    bool ProjectAddNewForm(MenuItem selection, Modifiers mods)
1289    {
1290       CodeEditor codeEditor = CreateNew("Form", "form", "Window", null);
1291       codeEditor.EnsureUpToDate();
1292       ide.RepositionWindows(false);
1293       return true;
1294    }
1295
1296    bool ProjectAddNewGraph(MenuItem selection, Modifiers mods)
1297    {
1298       CodeEditor codeEditor = CreateNew("Graph", "graph", "Block", null);
1299       if(codeEditor)
1300          codeEditor.EnsureUpToDate();
1301       return true;
1302    }
1303
1304    bool ProjectRemove(MenuItem selection, Modifiers mods)
1305    {
1306       DataRow row = fileList.currentRow;
1307       if(row)
1308       {
1309          ProjectNode node = (ProjectNode)(intptr)row.tag;
1310          if(node.type == project)
1311             RemoveSelectedNodes();
1312       }
1313       return true;
1314    }
1315
1316    bool ProjectUpdateMakefileForAllConfigs(Project project)
1317    {
1318       CompilerConfig compiler = ideSettings.GetCompilerConfig(ide.workspace.compiler);
1319
1320       // This call really does not belong here:
1321       ide.UpdateToolBarActiveConfigs(false);
1322       for(config : project.configurations)
1323          ProjectPrepareMakefile(project, forceExists, compiler, config);
1324
1325       ide.Update(null);
1326       delete compiler;
1327       return true;
1328    }
1329
1330    bool MenuSettings(MenuItem selection, Modifiers mods)
1331    {
1332       ProjectNode node = GetSelectedNode(true);
1333       Project prj = node ? node.project : project;
1334       projectSettingsDialog = ProjectSettings { master = parent, project = prj, projectNode = node };
1335       incref projectSettingsDialog;
1336       projectSettingsDialog.Modal();
1337       delete projectSettingsDialog;
1338       ide.UpdateToolBarActiveConfigs(false);
1339       Update(null);
1340       ide.AdjustMenus();
1341       return true;
1342    }
1343
1344    bool FileProperties(MenuItem selection, Modifiers mods)
1345    {
1346       DataRow row = fileList.currentRow;
1347       if(row)
1348       {
1349          ProjectNode node = (ProjectNode)(intptr)row.tag;
1350          NodeProperties { parent = parent, master = this, node = node,
1351                position = { position.x + 100, position.y + 100 } }.Create();
1352       }
1353       return true;
1354    }
1355
1356    bool FileOpenFile(MenuItem selection, Modifiers mods)
1357    {
1358       OpenSelectedNodes(mods.ctrl && mods.shift);
1359       return true;
1360    }
1361
1362    bool FileRemoveFile(MenuItem selection, Modifiers mods)
1363    {
1364       RemoveSelectedNodes();
1365       return true;
1366    }
1367
1368    bool FileCompile(MenuItem selection, Modifiers mods)
1369    {
1370       OldLink item;
1371       OldList selectedRows;
1372       Project project = null;
1373       List<ProjectNode> nodes { };
1374       fileList.GetMultiSelection(selectedRows);
1375       for(item = selectedRows.first; item; item = item.next)
1376       {
1377          DataRow row = item.data;
1378          ProjectNode node = (ProjectNode)(intptr)row.tag;
1379          if(!project)
1380             project = node.project;
1381          else if(node.project != project)
1382          {
1383             project = null;
1384             break;
1385          }
1386          nodes.Add(node);
1387       }
1388       selectedRows.Free(null);
1389       if(project)
1390          Compile(project, nodes, mods.ctrl && mods.shift, mods.ctrl && !mods.shift, normal);
1391       else
1392          ide.outputView.buildBox.Logf($"Please select files from a single project.\n");
1393       delete nodes;
1394       return true;
1395    }
1396
1397    bool FileClean(MenuItem selection, Modifiers mods)
1398    {
1399       OldLink item;
1400       OldList selectedRows;
1401       Project project = null;
1402       List<ProjectNode> nodes { };
1403       fileList.GetMultiSelection(selectedRows);
1404       for(item = selectedRows.first; item; item = item.next)
1405       {
1406          DataRow row = item.data;
1407          ProjectNode node = (ProjectNode)(intptr)row.tag;
1408          if(!project)
1409             project = node.project;
1410          else if(node.project != project)
1411          {
1412             project = null;
1413             break;
1414          }
1415          nodes.Add(node);
1416       }
1417       selectedRows.Free(null);
1418       if(project)
1419          Clean(project, nodes, mods.ctrl && mods.shift);
1420       else
1421          ide.outputView.buildBox.Logf($"Please select files from a single project.\n");
1422       delete nodes;
1423       return true;
1424    }
1425
1426    bool FileDebugPrecompile(MenuItem selection, Modifiers mods)
1427    {
1428       DataRow row = fileList.currentRow;
1429       ProjectNode node = row ? (ProjectNode)(intptr)row.tag : null;
1430       if(node)
1431       {
1432          List<ProjectNode> nodes { };
1433          nodes.Add(node);
1434          if(node.type == project)
1435             ProjectBuild(selection, mods);
1436          ide.Update(null);
1437          if(!stopBuild)
1438             Compile(node.project, nodes, mods.ctrl && mods.shift, mods.ctrl && !mods.shift, debugPrecompile);
1439          delete nodes;
1440       }
1441       return true;
1442    }
1443
1444    bool FileDebugCompile(MenuItem selection, Modifiers mods)
1445    {
1446       DataRow row = fileList.currentRow;
1447       ProjectNode node = row ? (ProjectNode)(intptr)row.tag : null;
1448       if(node)
1449       {
1450          List<ProjectNode> nodes { };
1451          nodes.Add(node);
1452          if(node.type == project)
1453             ProjectBuild(selection, mods);
1454          else
1455             Compile(node.project, nodes, mods.ctrl && mods.shift, mods.ctrl && !mods.shift, normal);
1456          if(!stopBuild)
1457             Compile(node.project, nodes, mods.ctrl && mods.shift, mods.ctrl && !mods.shift, debugCompile);
1458          delete nodes;
1459       }
1460       return true;
1461    }
1462
1463    bool FileDebugGenerateSymbols(MenuItem selection, Modifiers mods)
1464    {
1465       DataRow row = fileList.currentRow;
1466       ProjectNode node = row ? (ProjectNode)(intptr)row.tag : null;
1467       if(node)
1468       {
1469          List<ProjectNode> nodes { };
1470          nodes.Add(node);
1471          if(node.type == project)
1472             ProjectBuild(selection, mods);
1473          else
1474             Compile(node.project, nodes, mods.ctrl && mods.shift, mods.ctrl && !mods.shift, normal);
1475          if(!stopBuild)
1476             Compile(node.project, nodes, mods.ctrl && mods.shift, mods.ctrl && !mods.shift, debugGenerateSymbols);
1477          delete nodes;
1478       }
1479       return true;
1480    }
1481
1482    Project GetSelectedProject(bool useSelection)
1483    {
1484       Project prj = project;
1485       if(useSelection)
1486       {
1487          DataRow row = fileList.currentRow;
1488          ProjectNode node = row ? (ProjectNode)(intptr)row.tag : null;
1489          if(node)
1490             prj = node.project;
1491       }
1492       return prj;
1493    }
1494
1495    void SelectNextProject(bool backwards)
1496    {
1497       DataRow row = fileList.currentRow;
1498       if(!row)
1499          row = backwards ? fileList.lastRow : fileList.firstRow;
1500
1501       if(row)
1502       {
1503          DataRow currentRow = row;
1504          ProjectNode node = (ProjectNode)(intptr)row.tag;
1505          if(node.type != project)
1506             row = node.project.topNode.row;
1507          else if(backwards)
1508             row = row.previous ? row.previous : fileList.lastRow;
1509          if(!backwards)
1510             row = row.next ? row.next : fileList.firstRow;
1511          if(row && row != currentRow)
1512          {
1513             fileList.SelectRow(row);
1514             fileList.currentRow = row;
1515          }
1516       }
1517    }
1518
1519    ProjectNode GetSelectedNode(bool useSelection)
1520    {
1521       ProjectNode node = null;
1522       if(useSelection)
1523       {
1524          DataRow row = fileList.currentRow;
1525          if(row)
1526             node = (ProjectNode)(intptr)row.tag;
1527       }
1528       return node;
1529    }
1530
1531    bool MenuBrowseFolder(MenuItem selection, Modifiers mods)
1532    {
1533       char folder[MAX_LOCATION];
1534       Project prj;
1535       ProjectNode node = GetSelectedNode(true);
1536       if(!node)
1537          node = project.topNode;
1538       prj = node.project;
1539
1540       strcpy(folder, prj.topNode.path);
1541       if(node != prj.topNode)
1542          PathCatSlash(folder, node.path);
1543       ShellOpen(folder);
1544       return true;
1545    }
1546
1547    bool Run(MenuItem selection, Modifiers mods)
1548    {
1549       CompilerConfig compiler = ideSettings.GetCompilerConfig(ide.workspace.compiler);
1550       ProjectConfig config = project.config;
1551       int bitDepth = ide.workspace.bitDepth;
1552       String args = new char[maxPathLen];
1553       args[0] = '\0';
1554       if(ide.workspace.commandLineArgs)
1555          //ide.debugger.GetCommandLineArgs(args);
1556          strcpy(args, ide.workspace.commandLineArgs);
1557       if(ide.debugger.isActive)
1558          project.Run(args, compiler, config, bitDepth);
1559       /*else if(config.targetType == sharedLibrary || config.targetType == staticLibrary)
1560          MessageBox { master = ide, type = ok, text = "Run", contents = "Shared and static libraries cannot be run like executables." }.Modal();*/
1561       else if(BuildInterrim(project, run, compiler, config, bitDepth, false, false))
1562          project.Run(args, compiler, config, bitDepth);
1563       delete args;
1564       delete compiler;
1565       return true;
1566    }
1567
1568    bool DebugStart()
1569    {
1570       bool result = false;
1571       CompilerConfig compiler = ideSettings.GetCompilerConfig(ide.workspace.compiler);
1572       ProjectConfig config = project.config;
1573       int bitDepth = ide.workspace.bitDepth;
1574       bool useValgrind = ide.workspace.useValgrind;
1575       TargetTypes targetType = project.GetTargetType(config);
1576       if(targetType == sharedLibrary || targetType == staticLibrary)
1577          MessageBox { master = ide, type = ok, text = $"Run", contents = $"Shared and static libraries cannot be run like executables." }.Modal();
1578       else if(project.GetCompress(config))
1579          MessageBox { master = ide, text = $"Starting Debug", contents = $"Debugging compressed applications is not supported\n" }.Modal();
1580       else if(project.GetDebug(config) ||
1581          MessageBox { master = ide, type = okCancel, text = $"Starting Debug", contents = $"Attempting to debug non-debug configuration\nProceed anyways?" }.Modal() == ok)
1582       {
1583          if(/*!IsProjectModified() ||*/ BuildInterrim(project, start, compiler, config, bitDepth, false, false))
1584          {
1585             if(compiler.type.isVC)
1586             {
1587                //bool result = false;
1588                char oldwd[MAX_LOCATION];
1589                PathBackup pathBackup { };
1590                char command[MAX_LOCATION];
1591
1592                ide.SetPath(false, compiler, config, bitDepth);
1593
1594                GetWorkingDir(oldwd, sizeof(oldwd));
1595                ChangeWorkingDir(project.topNode.path);
1596
1597                sprintf(command, "%s /useenv %s.sln /projectconfig \"%s|Win32\" /command \"%s\"" , "devenv", project.name, config.name, "Debug.Start");
1598                Execute(command);
1599                ChangeWorkingDir(oldwd);
1600
1601                delete pathBackup;
1602             }
1603             else
1604             {
1605                ide.debugger.Start(compiler, config, bitDepth, useValgrind);
1606                result = true;
1607             }
1608          }
1609       }
1610       delete compiler;
1611       return result;
1612    }
1613
1614    void GoToError(const char * line, const bool noParsing, const char * objectFileExt)
1615    {
1616       char * colon;
1617
1618       while(isspace(*line)) line++;
1619       colon = strstr(line, ":");
1620
1621       {
1622          int lineNumber = 0;
1623          int col = 1;
1624          bool lookForLineNumber = true;
1625
1626          // deal with linking error
1627          if(colon && colon[1] == ' ')
1628          {
1629             colon = strstr(colon + 1, ":");
1630             if(colon && !colon[1])
1631             {
1632                colon = strstr(line, ":");
1633                lookForLineNumber = false;
1634             }
1635             else if(colon && !isdigit(colon[1]))
1636             {
1637                line = colon + 1;
1638                colon = strstr(line, ":");
1639             }
1640          }
1641          // Don't be mistaken by the drive letter colon
1642          if(colon && (colon[1] == '/' || colon[1] == '\\'))
1643             colon = strstr(colon + 1, ":");
1644          if(colon && lookForLineNumber)
1645          {
1646             char * comma;
1647 #if 0 // MSVS Errors -- todo fix this later
1648             char * par = RSearchString(line, "(", colon - line, true, false);
1649             if(par && strstr(par, ")"))
1650                colon = par;
1651             else if((colon+1)[0] == ' ')
1652             {
1653                // NOTE: This is the same thing as saying 'colon = line'
1654                for( ; colon != line; colon--)
1655                   /*if(*colon == '(')
1656                      break*/;
1657             }
1658 #endif
1659             lineNumber = atoi(colon + 1);
1660             /*
1661             comma = strchr(colon, ',');
1662             if(comma)
1663                col = atoi(comma+1);
1664             */
1665             comma = strchr(colon+1, ':');
1666             if(comma)
1667                col = atoi(comma+1);
1668          }
1669
1670          {
1671             char moduleName[MAX_LOCATION], filePath[MAX_LOCATION] = "";
1672             char ext[MAX_EXTENSION] = "";
1673             ProjectNode node = null;
1674             if(colon)
1675             {
1676                const char * inFileIncludedFrom = strstr(line, stringInFileIncludedFrom);
1677                const char * from = strstr(line, "from ");
1678                const char * start = inFileIncludedFrom ? inFileIncludedFrom + strlen(stringInFileIncludedFrom) : from ? from + strlen("from ") : line;
1679                int len;
1680                if(colon < start)
1681                   start = line;
1682                len = Min((int)(colon - start), MAX_LOCATION-1);
1683                // Cut module name
1684                strncpy(moduleName, start, len);
1685                moduleName[len] = '\0';
1686             }
1687             else
1688                strcpy(moduleName, line);
1689
1690             if(!colon)
1691             {
1692                char * msg;
1693                if((msg = strstr(moduleName, " - ")))
1694                {
1695                   bool found = false;
1696                   msg[0] = '\0';
1697                   for(prj : ide.workspace.projects)
1698                   {
1699                      strcpy(filePath, prj.topNode.path);
1700                      PathCatSlash(filePath, moduleName);
1701                      if(FileExists(filePath).isFile)
1702                      {
1703                         found = true;
1704                         break;
1705                      }
1706                   }
1707                   if(!found)
1708                   {
1709                      msg[0] = ' ';
1710                      filePath[0] = '\0';
1711                   }
1712                }
1713                else if((msg = strstr(moduleName, "...")) && (colon = strchr(moduleName, ' ')) && (++colon)[0])
1714                {
1715                   bool found = false;
1716                   msg[0] = '\0';
1717                   for(prj : ide.workspace.projects)
1718                   {
1719                      if((node = prj.resNode.Find(colon, true)))
1720                      {
1721                         strcpy(filePath, prj.topNode.path);
1722                         PathCatSlash(filePath, node.path);
1723                         PathCatSlash(filePath, node.name);
1724
1725                         found = true;
1726                         break;
1727                      }
1728                   }
1729                   if(!found)
1730                   {
1731                      msg[0] = '.';
1732                      filePath[0] = '\0';
1733                   }
1734                }
1735                colon = null;
1736             }
1737             // Remove stuff in brackets
1738             /*
1739             bracket = strstr(moduleName, "(");
1740             if(bracket) *bracket = '\0';
1741             */
1742             MakeSlashPath(moduleName);
1743             GetExtension(moduleName, ext);
1744
1745             if(!colon && !filePath[0])
1746             {
1747                // Check if it's one of our modules
1748                node = project.topNode.Find(moduleName, false);
1749                if(node)
1750                {
1751                   strcpy(filePath, node.path);
1752                   PathCatSlash(filePath, node.name);
1753                }
1754                else
1755                {
1756                   char ext[MAX_EXTENSION];
1757                   GetExtension(moduleName, ext);
1758                   {
1759                      DotMain dotMain = DotMain::FromFileName(moduleName);
1760                      IntermediateFileType type = IntermediateFileType::FromExtension(ext);
1761                      ProjectConfig config = null;
1762                      if(type)
1763                      {
1764                         for(prj : ide.workspace.projects; prj.lastBuildConfigName)
1765                         {
1766                            if((config = prj.GetConfig(prj.lastBuildConfigName)))
1767                               node = prj.FindNodeByObjectFileName(moduleName, type, dotMain, config, objectFileExt);
1768                            if(node)
1769                               break;
1770                         }
1771                      }
1772                      if(node)
1773                      {
1774                         char name[MAX_FILENAME];
1775                         Project project = node.project;
1776                         CompilerConfig compiler = ideSettings.GetCompilerConfig(project.lastBuildCompilerName);
1777                         if(compiler)
1778                         {
1779                            int bitDepth = ide.workspace.bitDepth;
1780                            const char * objectFileExt = compiler ? compiler.objectFileExt : objectDefaultFileExt;
1781                            DirExpression objDir = project.GetObjDir(compiler, config, bitDepth);
1782                            strcpy(filePath, project.topNode.path);
1783                            PathCatSlash(filePath, objDir.dir);
1784                            node.GetObjectFileName(name, project.configsNameCollisions[config ? config.name : ""], type, dotMain, objectFileExt);
1785                            PathCatSlash(filePath, name);
1786                            delete objDir;
1787                         }
1788                         delete compiler;
1789                      }
1790                   }
1791                }
1792                if(!node)
1793                   filePath[0] = '\0';
1794             }
1795             if(!strcmp(ext, "a") || !strcmp(ext, "o") || !strcmp(ext, "lib") ||
1796                   !strcmp(ext, "dll") || !strcmp(ext, "exe") || !strcmp(ext, "mo"))
1797                moduleName[0] = 0;    // Avoid opening binary files
1798             if(moduleName[0])
1799             {
1800                CodeEditor codeEditor = null;
1801
1802                if(ide.GoToCodeSelectFile(moduleName, null, project, null, filePath, objectFileExt))
1803                {
1804                   codeEditor = (CodeEditor)ide.OpenFile(filePath, false, true, null, no, normal, noParsing);
1805                }
1806
1807                if(!codeEditor)
1808                {
1809                   if(!filePath[0])
1810                   {
1811                      strcpy(filePath, project.topNode.path);
1812                      PathCatSlash(filePath, moduleName);
1813                   }
1814
1815                   codeEditor = (CodeEditor)ide.OpenFile(filePath, false, true, null, no, normal, noParsing);
1816                   if(!codeEditor && !strcmp(ext, "c"))
1817                   {
1818                      char ecName[MAX_LOCATION];
1819                      ChangeExtension(filePath, "ec", ecName);
1820                      codeEditor = (CodeEditor)ide.OpenFile(ecName, false, true, null, no, normal, noParsing);
1821                   }
1822                   if(!codeEditor)
1823                   {
1824                      char path[MAX_LOCATION];
1825                      // TOFIX: Improve on this, don't use only filename, make a function
1826                      if(ide && ide.workspace)
1827                      {
1828                         for(prj : ide.workspace.projects)
1829                         {
1830                            ProjectNode node;
1831                            MakePathRelative(filePath, prj.topNode.path, path);
1832
1833                            if((node = prj.topNode.FindWithPath(path, false)))
1834                            {
1835                               strcpy(filePath, prj.topNode.path);
1836                               PathCatSlash(filePath, node.path);
1837                               PathCatSlash(filePath, node.name);
1838                               codeEditor = (CodeEditor)ide.OpenFile(filePath, false, true, null, no, normal, noParsing);
1839                               if(codeEditor)
1840                                  break;
1841                            }
1842                         }
1843                         if(!codeEditor && (strchr(moduleName, '/') || strchr(moduleName, '\\')))
1844                         {
1845                            for(prj : ide.workspace.projects)
1846                            {
1847                               ProjectNode node;
1848                               if((node = prj.topNode.FindWithPath(moduleName, false)))
1849                               {
1850                                  strcpy(filePath, prj.topNode.path);
1851                                  PathCatSlash(filePath, node.path);
1852                                  PathCatSlash(filePath, node.name);
1853                                  codeEditor = (CodeEditor)ide.OpenFile(filePath, false, true, null, no, normal, noParsing);
1854                                  if(codeEditor)
1855                                     break;
1856                               }
1857                            }
1858                         }
1859                         if(!codeEditor)
1860                         {
1861                            GetLastDirectory(moduleName, moduleName);
1862                            for(prj : ide.workspace.projects)
1863                            {
1864                               ProjectNode node;
1865                               if((node = prj.topNode.Find(moduleName, false)))
1866                               {
1867                                  strcpy(filePath, prj.topNode.path);
1868                                  PathCatSlash(filePath, node.path);
1869                                  PathCatSlash(filePath, node.name);
1870                                  codeEditor = (CodeEditor)ide.OpenFile(filePath, false, true, null, no, normal, noParsing);
1871                                  if(codeEditor)
1872                                     break;
1873                               }
1874                            }
1875                         }
1876                      }
1877                   }
1878                }
1879                if(codeEditor && lineNumber)
1880                {
1881                   EditBox editBox = codeEditor.editBox;
1882                   if(editBox.GoToLineNum(lineNumber - 1))
1883                      editBox.GoToPosition(editBox.line, lineNumber - 1, col ? (col - 1) : 0);
1884                }
1885             }
1886          }
1887       }
1888    }
1889
1890    bool OpenNode(ProjectNode node, bool noParsing)
1891    {
1892       char filePath[MAX_LOCATION];
1893       char ext[MAX_EXTENSION];
1894       node.GetFullFilePath(filePath, true);
1895
1896       GetExtension(filePath, ext);
1897       if(binaryDocExt.Find(ext))
1898       {
1899          ShellOpen(filePath);
1900          return true;
1901       }
1902       else
1903          return ide.OpenFile(filePath, false, true/*false Why was it opening hidden?*/, null, something, normal, noParsing) ? true : false;
1904    }
1905
1906    void AddNode(ProjectNode node, DataRow addTo)
1907    {
1908       DataRow row = addTo ? addTo.AddRow() : fileList.AddRow();
1909
1910       row.tag = (int64)(intptr)node;
1911       node.row = row;
1912
1913       if(node.type == resources)
1914          resourceRow = row;
1915
1916       row.SetData(null, node);
1917
1918       if(node.files && node.files.first && node.parent &&
1919             !(!node.parent.parent &&
1920                (!strcmpi(node.name, "notes") || !strcmpi(node.name, "sources") ||
1921                   !strcmpi(node.name, "src") || !strcmpi(node.name, "tools"))))
1922          row.collapsed = true;
1923       else if(node.type == folder)
1924          node.icon = openFolder;
1925
1926       if(node.files)
1927       {
1928          for(child : node.files)
1929             AddNode(child, row);
1930       }
1931    }
1932
1933    void DeleteNode(ProjectNode projectNode)
1934    {
1935       if(projectNode.files)
1936       {
1937          ProjectNode child;
1938          while((child = projectNode.files.first))
1939             DeleteNode(child);
1940       }
1941       fileList.DeleteRow(projectNode.row);
1942       projectNode.Delete();
1943    }
1944
1945    bool ProjectSave(MenuItem selection, Modifiers mods)
1946    {
1947       DataRow row = fileList.currentRow;
1948       ProjectNode node = row ? (ProjectNode)(intptr)row.tag : null;
1949       Project prj = node ? node.project : null;
1950       if(prj)
1951       {
1952          prj.StopMonitoring();
1953          if(prj.Save(prj.filePath))
1954          {
1955             Project modPrj = null;
1956             prj.topNode.modified = false;
1957             for(p : ide.workspace.projects)
1958             {
1959                if(p.topNode.modified)
1960                {
1961                   modPrj = p;
1962                   break;
1963                }
1964             }
1965             if(!modPrj)
1966                modifiedDocument = false;
1967             Update(null);
1968          }
1969          prj.StartMonitoring();
1970       }
1971       return true;
1972    }
1973
1974    bool ShowOutputBuildLog(bool cleanLog)
1975    {
1976       OutputView output = ide.outputView;
1977       if(cleanLog)
1978          output.ShowClearSelectTab(build);
1979       else
1980       {
1981          output.SelectTab(build);
1982          output.Show();
1983       }
1984       return true;
1985    }
1986
1987    bool DebugRestart()
1988    {
1989       CompilerConfig compiler = ideSettings.GetCompilerConfig(ide.workspace.compiler);
1990       ProjectConfig config = project.config;
1991       int bitDepth = ide.workspace.bitDepth;
1992       bool useValgrind = ide.workspace.useValgrind;
1993
1994       bool result = false;
1995       if(/*!IsProjectModified() ||*/ BuildInterrim(project, restart, compiler, config, bitDepth, false, false))
1996       {
1997          // For Restart, compiler and config will only be used if for
1998          // whatever reason (if at all possible) the Debugger is in a
1999          // 'terminated' or 'none' state
2000          ide.debugger.Restart(compiler, config, bitDepth, useValgrind);
2001          result = true;
2002       }
2003
2004       delete compiler;
2005       return result;
2006    }
2007
2008    bool DebugResume()
2009    {
2010       ide.debugger.Resume();
2011       return true;
2012    }
2013
2014    bool DebugBreak()
2015    {
2016       ide.debugger.Break();
2017       return true;
2018    }
2019
2020    bool DebugStop()
2021    {
2022       ide.debugger.Stop();
2023       return true;
2024    }
2025
2026    bool DebugStepInto()
2027    {
2028       CompilerConfig compiler = ideSettings.GetCompilerConfig(ide.workspace.compiler);
2029       ProjectConfig config = project.config;
2030       int bitDepth = ide.workspace.bitDepth;
2031       bool useValgrind = ide.workspace.useValgrind;
2032
2033       if((ide.debugger.isActive) || (!buildInProgress && BuildInterrim(project, start, compiler, config, bitDepth, false, false)))
2034          ide.debugger.StepInto(compiler, config, bitDepth, useValgrind);
2035       delete compiler;
2036       return true;
2037    }
2038
2039    bool DebugStepOver(bool skip)
2040    {
2041       CompilerConfig compiler = ideSettings.GetCompilerConfig(ide.workspace.compiler);
2042       ProjectConfig config = project.config;
2043       int bitDepth = ide.workspace.bitDepth;
2044       bool useValgrind = ide.workspace.useValgrind;
2045
2046       if((ide.debugger.isActive) || (!buildInProgress && BuildInterrim(project, start, compiler, config, bitDepth, false, false)))
2047          ide.debugger.StepOver(compiler, config, bitDepth, useValgrind, skip);
2048
2049       delete compiler;
2050       return true;
2051    }
2052
2053    bool DebugStepUntil(bool skip)
2054    {
2055       CompilerConfig compiler = ideSettings.GetCompilerConfig(ide.workspace.compiler);
2056       ProjectConfig config = project.config;
2057       int bitDepth = ide.workspace.bitDepth;
2058       bool useValgrind = ide.workspace.useValgrind;
2059
2060       if((ide.debugger.isActive) || (!buildInProgress && BuildInterrim(project, start, compiler, config, bitDepth, false, false)))
2061          ide.debugger.StepUntil(compiler, config, bitDepth, useValgrind, skip);
2062
2063       delete compiler;
2064       return true;
2065    }
2066
2067    bool DebugStepOut(bool skip)
2068    {
2069       ide.debugger.StepOut(skip);
2070       return true;
2071    }
2072
2073    void ImportFolder(ProjectNode toNode)
2074    {
2075       if(toNode)
2076       {
2077          char path[MAX_LOCATION];
2078          char currentDir[MAX_LOCATION];
2079          ProjectNode node = toNode;
2080          FileDialog fileDialog = importFileDialog;
2081          fileDialog.master = parent;
2082          while(node)
2083          {
2084             node.GetFullFilePath(path, true);
2085             while(path[0])
2086             {
2087                StripLastDirectory(path, path);
2088                if(FileExists(path).isDirectory) break;
2089             }
2090             if(path[0] || node == toNode.project.topNode)
2091                node = null;
2092             else
2093                node = toNode.project.topNode;
2094          }
2095          MakeSystemPath(path);
2096          StripLastDirectory(path, currentDir);
2097          fileDialog.currentDirectory = currentDir[0] ? currentDir : path;
2098          fileDialog.filePath = path;
2099          if(fileDialog.Modal() == ok)
2100          {
2101             ImportFolderFSI fsi { projectView = this };
2102             fsi.stack.Add(toNode);
2103             fsi.Iterate(fileDialog.filePath);
2104             delete fsi;
2105          }
2106       }
2107    }
2108
2109    ProjectNode NewFolder(ProjectNode parentNode, char * name, bool showProperties)
2110    {
2111       if(parentNode)
2112       {
2113          ProjectNode folderNode;
2114          Project prj = parentNode.project;
2115          int c;
2116          ProjectNode after = null;
2117          for(node : parentNode.files)
2118          {
2119             if(node.type != folder)
2120                break;
2121             after = node;
2122          }
2123
2124          if(name && name[0])
2125             folderNode = parentNode.Add(prj, name, after, folder, folder, true);
2126          else
2127          {
2128             for(c = 0; c < 100; c++)
2129             {
2130                char string[16];
2131                sprintf(string, c ? "New Folder (%d)" : "New Folder", c);
2132                if((folderNode = parentNode.Add(prj, string, after, folder, folder, true)))
2133                   break;
2134             }
2135          }
2136
2137          if(folderNode)
2138          {
2139             NodeProperties nodeProperties;
2140             if(!showProperties)
2141             {
2142                modifiedDocument = true;
2143                prj.topNode.modified = true;
2144             }
2145             Update(null);
2146             folderNode.row = parentNode.row.AddRowAfter(after ? after.row : null);
2147             folderNode.row.tag = (int64)(intptr)folderNode;
2148
2149             folderNode.row.SetData(null, folderNode);
2150             fileList.currentRow = folderNode.row;
2151
2152             if(showProperties)
2153             {
2154                nodeProperties = NodeProperties
2155                {
2156                   parent, this, mode = newFolder, node = folderNode;
2157                   position = { position.x + 100, position.y + 100 };
2158                };
2159                nodeProperties.Create();   // Modal?
2160             }
2161             return folderNode;
2162          }
2163       }
2164       return null;
2165    }
2166
2167    void AddFiles(bool resources)
2168    {
2169       FileDialog fileDialog = (!resources) ? this.fileDialog : resourceFileDialog;
2170       fileDialog.type = multiOpen;
2171       fileDialog.text = !resources ? $"Add Files to Project" : $"Add Resources to Project";
2172       fileDialog.master = parent;
2173
2174       if(fileDialog.Modal() == ok)
2175       {
2176          int c;
2177          DataRow row = fileList.currentRow;
2178          ProjectNode parentNode = (ProjectNode)(intptr)row.tag;
2179          bool addFailed = false;
2180          int numSelections = fileDialog.numSelections;
2181          const char * const * multiFilePaths = fileDialog.multiFilePaths;
2182
2183          Array<String> nameConflictFiles { };
2184
2185          for(c = 0; c < numSelections; c++)
2186          {
2187             const char * filePath = multiFilePaths[c];
2188             FileAttribs exists = FileExists(filePath);
2189             bool addThisFile = true;
2190
2191             if(exists.isDirectory)
2192                addThisFile = false;
2193             else if(!exists)
2194             {
2195                if(MessageBox { master = ide, type = yesNo, text = filePath,
2196                      contents = $"File doesn't exist. Create?" }.Modal() == yes)
2197                {
2198                   File f = FileOpen(filePath, write);
2199                   if(f)
2200                   {
2201                      addThisFile = true;
2202                      delete f;
2203                   }
2204                   else
2205                   {
2206                      MessageBox { master = ide, type = ok, text = filePath,
2207                            contents = $"Couldn't create file."}.Modal();
2208                      addThisFile = false;
2209                   }
2210                }
2211             }
2212
2213             if(addThisFile)
2214             {
2215                /*addFailed = */if(!AddFile(parentNode, filePath, resources, false))//;
2216                {
2217                   nameConflictFiles.Add(CopyString(filePath));
2218                   addFailed = true;
2219                }
2220             }
2221          }
2222          if(addFailed)
2223          {
2224             int len = 0;
2225             const char * part1 = $"The following file";
2226             const char * opt1 = $" was ";
2227             const char * opt2 = $"s were ";
2228             const char * part2 = $"not added because of identical file name conflict within the project.\n\n";
2229             char * message;
2230             len += strlen(part1);
2231             len += strlen(part2);
2232             len += nameConflictFiles.count > 1 ? strlen(opt2) : strlen(opt1);
2233             for(s : nameConflictFiles)
2234                len += strlen(s) + 1;
2235             message = new char[len + 1];
2236             strcpy(message, part1);
2237             strcat(message, nameConflictFiles.count > 1 ? opt2 : opt1);
2238             strcat(message, part2);
2239             for(s : nameConflictFiles)
2240             {
2241                strcat(message, s);
2242                strcat(message, "\n");
2243             }
2244             MessageBox { master = ide, type = ok, text = $"Name Conflict",
2245                   contents = message }.Modal();
2246             delete message;
2247          }
2248          nameConflictFiles.Free();
2249          delete nameConflictFiles;
2250       }
2251    }
2252
2253    ProjectNode AddFile(ProjectNode parentNode, const char * filePath, bool resources, bool isTemporary)
2254    {
2255       ProjectNode result = null;
2256       ProjectNode after = null;
2257       for(node : parentNode.files)
2258       {
2259          if(node.type != folder && node.type != file && node.type)
2260             break;
2261          after = node;
2262       }
2263
2264       result = parentNode.Add(parentNode.project, filePath, after, file, NodeIcons::SelectFileIcon(filePath), !resources);
2265
2266       if(result)
2267       {
2268          if(!isTemporary)
2269          {
2270             modifiedDocument = true;
2271             parentNode.project.topNode.modified = true;
2272             parentNode.project.ModifiedAllConfigs(true, false, true, true);
2273          }
2274          Update(null);
2275          result.row = parentNode.row.AddRowAfter(after ? after.row : null);
2276          result.row.tag = (int64)(intptr)result;
2277          result.row.SetData(null, result);
2278       }
2279       return result;
2280    }
2281
2282    CodeEditor CreateNew(const char * upper, const char * lower, const char * base, char * className)
2283    {
2284       CodeEditor codeEditor = null;
2285       ProjectNode projectNode;
2286       ProjectNode after = null;
2287       DataRow row = fileList.currentRow;
2288       ProjectNode parentNode;
2289       int c;
2290
2291       if(!row) row = project.topNode.row;
2292
2293       parentNode = (ProjectNode)(intptr)row.tag;
2294
2295       for(node : parentNode.files)
2296       {
2297          if(node.type != folder && node.type != file && node.type)
2298             break;
2299          after = node;
2300       }
2301       for(c = 1; c < 100; c++)
2302       {
2303          char string[16];
2304          sprintf(string, "%s%d.ec", lower, c);
2305          if((projectNode = parentNode.Add(project, string, after, file, genFile, true)))
2306             break;
2307       }
2308       if(projectNode)
2309       {
2310          char name[256];
2311          char filePath[MAX_LOCATION];
2312
2313          modifiedDocument = true;
2314          project.topNode.modified = true;
2315          Update(null);
2316          project.ModifiedAllConfigs(true, false, false, true);
2317          projectNode.row = parentNode.row.AddRowAfter(after ? after.row : null);
2318          projectNode.row.tag = (int64)(intptr)projectNode;
2319
2320          projectNode.row.SetData(null, projectNode);
2321          fileList.currentRow = projectNode.row;
2322
2323          strcpy(filePath, project.topNode.path);
2324          PathCat(filePath, projectNode.path);
2325          PathCat(filePath, projectNode.name);
2326
2327          codeEditor = (CodeEditor)ide.FindWindow(filePath);
2328          if(!codeEditor)
2329          {
2330             Class baseClass = eSystem_FindClass(__thisModule, base);
2331             subclass(ClassDesignerBase) designerClass = eClass_GetDesigner(baseClass);
2332             if(designerClass)
2333             {
2334                codeEditor = (CodeEditor)ide.OpenFile(filePath, false, false, null, whatever, normal, false);
2335                strcpy(name, projectNode.name);
2336                sprintf(name, "%s%d", upper, c);
2337                if(className)
2338                   strcpy(className, name);
2339
2340                designerClass.CreateNew(codeEditor.editBox, codeEditor.clientSize, name, base);
2341
2342                //codeEditor.modifiedDocument = false;
2343                //codeEditor.designer.modifiedDocument = false;
2344
2345                //Code_EnsureUpToDate(codeEditor);
2346             }
2347          }
2348          else // TODO: fix no symbols generated when ommiting {} for following else
2349          {
2350             codeEditor = (CodeEditor)ide.OpenFile(filePath, false, false, null, whatever, normal, false);
2351          }
2352          ide.sheet.visible = true;
2353          ide.sheet.Activate();
2354          if(codeEditor)
2355          {
2356             codeEditor.ViewDesigner();
2357             codeEditor.codeModified = true;
2358          }
2359       }
2360       //visible = false;
2361       return codeEditor;
2362    }
2363
2364    // Returns true if we opened something
2365    bool OpenSelectedNodes(bool noParsing)
2366    {
2367       bool result = false;
2368       OldList selection;
2369       OldLink item;
2370
2371       fileList.GetMultiSelection(selection);
2372       for(item = selection.first; item; item = item.next)
2373       {
2374          DataRow row = item.data;
2375          ProjectNode node = (ProjectNode)(intptr)row.tag;
2376          if(node.type == file)
2377          {
2378             OpenNode(node, noParsing);
2379             result = true;
2380          }
2381       }
2382       selection.Free(null);
2383       ide.RepositionWindows(false);
2384       return result;
2385    }
2386
2387    void RemoveSelectedNodes()
2388    {
2389       OldList selection;
2390       OldLink item, next;
2391
2392       fileList.GetMultiSelection(selection);
2393
2394       // Remove children of parents we're deleting
2395       for(item = selection.first; item; item = next)
2396       {
2397          OldLink i;
2398          DataRow row = item.data;
2399          ProjectNode n, node = (ProjectNode)(intptr)row.tag;
2400          bool remove = false;
2401
2402          next = item.next;
2403          for(i = selection.first; i && !remove; i = i.next)
2404          {
2405             ProjectNode iNode = (ProjectNode)(intptr)((DataRow)i.data).tag;
2406             for(n = node.parent; n; n = n.parent)
2407             {
2408                if(iNode == n)
2409                {
2410                   remove = true;
2411                   break;
2412                }
2413             }
2414          }
2415          if(remove)
2416             selection.Delete(item);
2417       }
2418
2419       for(item = selection.first; item; item = item.next)
2420       {
2421          DataRow row = item.data;
2422          ProjectNode node = (ProjectNode)(intptr)row.tag;
2423          ProjectNode resNode;
2424          for(resNode = node.parent; resNode; resNode = resNode.parent)
2425             if(resNode.type == resources)
2426                break;
2427          if(node.type == file)
2428          {
2429             Project prj = node.project;
2430             DeleteNode(node);
2431             modifiedDocument = true;
2432             prj.topNode.modified = true;
2433             Update(null);
2434             prj.ModifiedAllConfigs(true, false, true, true);
2435          }
2436          else if(node.type == folder)
2437          {
2438             char message[1024];
2439             sprintf(message, $"Are you sure you want to remove the folder \"%s\"\n"
2440                   "and all of its contents from the project?", node.name);
2441             if(MessageBox { master = ide, type = yesNo, text = $"Delete Folder", contents = message }.Modal() == yes)
2442             {
2443                Project prj = node.project;
2444                if(node.containsFile)
2445                   prj.ModifiedAllConfigs(true, false, true, true);
2446                DeleteNode(node);
2447                modifiedDocument = true;
2448                prj.topNode.modified = true;
2449             }
2450          }
2451          else if(node.type == project && node != project.topNode && !buildInProgress)
2452          {
2453             char message[1024];
2454             Project prj = null;
2455             for(p : workspace.projects)
2456             {
2457                if(p.topNode == node)
2458                {
2459                   prj = p;
2460                   break;
2461                }
2462             }
2463             sprintf(message, $"Are you sure you want to remove the \"%s\" project\n" "from this workspace?", node.name);
2464             if(MessageBox { master = ide, type = yesNo, text = $"Remove Project", contents = message }.Modal() == yes)
2465             {
2466                // THIS GOES FIRST!
2467                DeleteNode(node);
2468                if(prj)
2469                   workspace.RemoveProject(prj);
2470                //modifiedDocument = true; // when project view is a workspace view
2471             }
2472          }
2473       }
2474       selection.Free(null);
2475    }
2476 }