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