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