ide; fixed goto error in file won't work on files who's path contains parentheses...
[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                ReplaceSpaces(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 #if 0 // MSVS Errors -- todo fix this later
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 #endif
1559             lineNumber = atoi(colon + 1);
1560             /*
1561             comma = strchr(colon, ',');
1562             if(comma)
1563                col = atoi(comma+1);
1564             */
1565             comma = strchr(colon+1, ':');
1566             if(comma)
1567                col = atoi(comma+1);
1568          }
1569          
1570          {
1571             char moduleName[MAX_LOCATION], filePath[MAX_LOCATION] = "";
1572             char ext[MAX_EXTENSION] = "";
1573             char * bracket;
1574             ProjectNode node = null;
1575             if(colon)
1576             {
1577                char * inFileIncludedFrom = strstr(line, stringInFileIncludedFrom);
1578                char * from = strstr(line, "from ");
1579                char * start = inFileIncludedFrom ? inFileIncludedFrom + strlen(stringInFileIncludedFrom) : from ? from + strlen("from ") : line;
1580                int len;
1581                if(colon < start)
1582                   start = line;
1583                len = Min((int)(colon - start), MAX_LOCATION-1);
1584                // Cut module name
1585                strncpy(moduleName, start, len);
1586                moduleName[len] = '\0';
1587             }
1588             else
1589                strcpy(moduleName, line);
1590
1591             if(!colon)
1592             {
1593                char * msg;
1594                if((msg = strstr(moduleName, " - ")))
1595                {
1596                   bool found = false;
1597                   msg[0] = '\0';
1598                   for(prj : ide.workspace.projects)
1599                   {
1600                      strcpy(filePath, prj.topNode.path);
1601                      PathCatSlash(filePath, moduleName);
1602                      if(FileExists(filePath).isFile)
1603                      {
1604                         found = true;
1605                         break;
1606                      }
1607                   }
1608                   if(!found)
1609                   {
1610                      msg[0] = ' ';
1611                      filePath[0] = '\0';
1612                   }
1613                }
1614                else if((msg = strstr(moduleName, "...")) && (colon = strchr(moduleName, ' ')) && (++colon)[0])
1615                {
1616                   bool found = false;
1617                   msg[0] = '\0';
1618                   for(prj : ide.workspace.projects)
1619                   {
1620                      if((node = prj.resNode.Find(colon, true)))
1621                      {
1622                         strcpy(filePath, prj.topNode.path);
1623                         PathCatSlash(filePath, node.path);
1624                         PathCatSlash(filePath, node.name);
1625
1626                         found = true;
1627                         break;
1628                      }
1629                   }
1630                   if(!found)
1631                   {
1632                      msg[0] = '.';
1633                      filePath[0] = '\0';
1634                   }
1635                }
1636                colon = null;
1637             }
1638             // Remove stuff in brackets
1639             /*
1640             bracket = strstr(moduleName, "(");
1641             if(bracket) *bracket = '\0';
1642             */
1643             MakeSlashPath(moduleName);
1644             GetExtension(moduleName, ext);
1645
1646             if(!colon && !filePath[0])
1647             {
1648                bool dotMain = false;
1649                // Check if it's one of our modules
1650                node = project.topNode.Find(moduleName, false);
1651                if(node)
1652                {
1653                   strcpy(filePath, node.path);
1654                   PathCatSlash(filePath, node.name);
1655                }
1656                else
1657                {
1658                   IntermediateFileType type = none;
1659                   ProjectConfig config;
1660                   if(ext[0])
1661                   {
1662                      char ext2[MAX_EXTENSION];
1663                      char stripExt[MAX_LOCATION];
1664                      strcpy(stripExt, moduleName);
1665                      StripExtension(stripExt);
1666                      GetExtension(stripExt, ext2);
1667                      if(ext2[0] && !strcmp(ext2, "main"))
1668                         dotMain = true;
1669                      if(!strcmp(ext, "ec"))
1670                         type = ec;
1671                      else if(!strcmp(ext, "c"))
1672                         type = c;
1673                      else if(!strcmp(ext, "sym"))
1674                         type = sym;
1675                      else if(!strcmp(ext, "imp"))
1676                         type = imp;
1677                      else if(!strcmp(ext, "bowl"))
1678                         type = bowl;
1679                      else if(!strcmp(ext, "o"))
1680                         type = o;
1681
1682                      if(type)
1683                      {
1684                         for(prj : ide.workspace.projects; prj.lastBuildConfigName)
1685                         {
1686                            if((config = prj.GetConfig(prj.lastBuildConfigName)))
1687                               node = prj.FindNodeByObjectFileName(moduleName, type, dotMain, config);
1688                            if(node)
1689                               break;
1690                         }
1691                      }
1692                   }
1693                   if(node)
1694                   {
1695                      char name[MAX_FILENAME];
1696                      Project project = node.project;
1697                      CompilerConfig compiler = ideSettings.GetCompilerConfig(project.lastBuildCompilerName);
1698                      if(compiler)
1699                      {
1700                         int bitDepth = ide.workspace.bitDepth;
1701                         DirExpression objDir = project.GetObjDir(compiler, config, bitDepth);
1702                         strcpy(filePath, project.topNode.path);
1703                         PathCatSlash(filePath, objDir.dir);
1704                         node.GetObjectFileName(name, project.lastBuildNamesInfo, type, dotMain);
1705                         PathCatSlash(filePath, name);
1706                         delete objDir;
1707                      }
1708                      delete compiler;
1709                   }
1710                }
1711                if(!node)
1712                   filePath[0] = '\0';
1713             }
1714             if(!strcmp(ext, "a") || !strcmp(ext, "o") || !strcmp(ext, "lib") ||
1715                   !strcmp(ext, "dll") || !strcmp(ext, "exe") || !strcmp(ext, "mo"))
1716                moduleName[0] = 0;    // Avoid opening binary files
1717             if(moduleName[0])
1718             {
1719                CodeEditor codeEditor;
1720                if(!filePath[0])
1721                {
1722                   strcpy(filePath, project.topNode.path);
1723                   PathCatSlash(filePath, moduleName);
1724                }
1725       
1726                codeEditor = (CodeEditor)ide.OpenFile(filePath, normal, true, null, no, normal, noParsing);
1727                if(!codeEditor && !strcmp(ext, "c"))
1728                {
1729                   char ecName[MAX_LOCATION];
1730                   ChangeExtension(filePath, "ec", ecName);
1731                   codeEditor = (CodeEditor)ide.OpenFile(ecName, normal, true, null, no, normal, noParsing);
1732                }
1733                if(!codeEditor)
1734                {
1735                   char path[MAX_LOCATION];
1736                   // TOFIX: Improve on this, don't use only filename, make a function
1737                   if(ide && ide.workspace)
1738                   {
1739                      for(prj : ide.workspace.projects)
1740                      {
1741                         ProjectNode node;
1742                         MakePathRelative(filePath, prj.topNode.path, path);
1743
1744                         if((node = prj.topNode.FindWithPath(path, false)))
1745                         {
1746                            strcpy(filePath, prj.topNode.path);
1747                            PathCatSlash(filePath, node.path);
1748                            PathCatSlash(filePath, node.name);
1749                            codeEditor = (CodeEditor)ide.OpenFile(filePath, normal, true, null, no, normal, noParsing);
1750                            if(codeEditor)
1751                               break;
1752                         }
1753                      }
1754                      if(!codeEditor && !strchr(moduleName, '/') && !strchr(moduleName, '\\'))
1755                      {
1756                         for(prj : ide.workspace.projects)
1757                         {
1758                            ProjectNode node;
1759                            if((node = prj.topNode.Find(moduleName, false)))
1760                            {
1761                               strcpy(filePath, prj.topNode.path);
1762                               PathCatSlash(filePath, node.path);
1763                               PathCatSlash(filePath, node.name);
1764                               codeEditor = (CodeEditor)ide.OpenFile(filePath, normal, true, null, no, normal, noParsing);
1765                               if(codeEditor)
1766                                  break;
1767                            }
1768                         }
1769                      }
1770                   }
1771                }
1772                if(codeEditor && lineNumber)
1773                {
1774                   EditBox editBox = codeEditor.editBox;
1775                   editBox.GoToLineNum(lineNumber - 1);
1776                   editBox.GoToPosition(editBox.line, lineNumber - 1, col ? (col - 1) : 0);
1777                }
1778             }
1779          }
1780       }
1781    }
1782
1783    bool OpenNode(ProjectNode node, bool noParsing)
1784    {
1785       char filePath[MAX_LOCATION];
1786       node.GetFullFilePath(filePath);
1787       return ide.OpenFile(filePath, normal, true/*false Why was it opening hidden?*/, null, something, normal, noParsing) ? true : false;
1788    }
1789
1790    void AddNode(ProjectNode node, DataRow addTo)
1791    {
1792       DataRow row = addTo ? addTo.AddRow() : fileList.AddRow();
1793
1794       row.tag = (int64)node;
1795       node.row = row;
1796
1797       if(node.type == resources)
1798          resourceRow = row;
1799
1800       row.SetData(null, node);
1801
1802       if(node.files && node.files.first && node.parent && 
1803             !(!node.parent.parent && 
1804                (!strcmpi(node.name, "notes") || !strcmpi(node.name, "sources") || 
1805                   !strcmpi(node.name, "src") || !strcmpi(node.name, "tools"))))
1806          row.collapsed = true;
1807       else if(node.type == folder)
1808          node.icon = openFolder;
1809
1810       if(node.files)
1811       {
1812          for(child : node.files)
1813             AddNode(child, row);
1814       }
1815    }
1816
1817    void DeleteNode(ProjectNode projectNode)
1818    {
1819       if(projectNode.files)
1820       {
1821          ProjectNode child;
1822          while(child = projectNode.files.first)
1823             DeleteNode(child);
1824       }
1825       fileList.DeleteRow(projectNode.row);
1826       projectNode.Delete();
1827    }
1828
1829    bool ProjectSave(MenuItem selection, Modifiers mods)
1830    {
1831       DataRow row = fileList.currentRow;
1832       ProjectNode node = row ? (ProjectNode)row.tag : null;
1833       Project prj = node ? node.project : null;
1834       if(prj)
1835       {
1836          prj.StopMonitoring();
1837          if(prj.Save(prj.filePath))
1838          {
1839             Project modPrj = null;
1840             prj.topNode.modified = false;
1841             for(p : ide.workspace.projects)
1842             {
1843                if(p.topNode.modified)
1844                { 
1845                   modPrj = p;
1846                   break;
1847                }
1848             }
1849             if(!modPrj)
1850                modifiedDocument = false;
1851             Update(null);
1852          }
1853          prj.StartMonitoring();
1854       }
1855       return true;
1856    }
1857
1858    bool ShowOutputBuildLog(bool cleanLog)
1859    {
1860       OutputView output = ide.outputView;
1861       if(cleanLog)
1862          output.ShowClearSelectTab(build);
1863       else
1864       {
1865          output.SelectTab(build);
1866          output.Show();
1867       }
1868       return true;
1869    }
1870
1871    bool DebugRestart()
1872    {
1873       CompilerConfig compiler = ideSettings.GetCompilerConfig(ide.workspace.compiler);
1874       ProjectConfig config = project.config;
1875       int bitDepth = ide.workspace.bitDepth;
1876
1877       bool result = false;
1878       if(/*!IsProjectModified() ||*/ BuildInterrim(project, restart, compiler, config, bitDepth, false))
1879       {
1880          // For Restart, compiler and config will only be used if for
1881          // whatever reason (if at all possible) the Debugger is in a
1882          // 'terminated' or 'none' state
1883          ide.debugger.Restart(compiler, config, bitDepth);
1884          result = true;
1885       }
1886
1887       delete compiler;
1888       return result;
1889    }
1890
1891    bool DebugResume()
1892    {
1893       ide.debugger.Resume();
1894       return true;
1895    }
1896
1897    bool DebugBreak()
1898    {
1899       ide.debugger.Break();
1900       return true;
1901    }
1902
1903    bool DebugStop()
1904    {
1905       ide.debugger.Stop();
1906       return true;
1907    }
1908
1909    bool DebugStepInto()
1910    {
1911       CompilerConfig compiler = ideSettings.GetCompilerConfig(ide.workspace.compiler);
1912       ProjectConfig config = project.config;
1913       int bitDepth = ide.workspace.bitDepth;
1914
1915       if((ide.debugger.isActive) || (!buildInProgress && BuildInterrim(project, start, compiler, config, bitDepth, false)))
1916          ide.debugger.StepInto(compiler, config, bitDepth);
1917       delete compiler;
1918       return true;
1919    }
1920
1921    bool DebugStepOver(bool skip)
1922    {
1923       CompilerConfig compiler = ideSettings.GetCompilerConfig(ide.workspace.compiler);
1924       ProjectConfig config = project.config;
1925       int bitDepth = ide.workspace.bitDepth;
1926
1927       if((ide.debugger.isActive) || (!buildInProgress && BuildInterrim(project, start, compiler, config, bitDepth, false)))
1928          ide.debugger.StepOver(compiler, config, bitDepth, skip);
1929
1930       delete compiler;
1931       return true;
1932    }
1933
1934    bool DebugStepOut(bool skip)
1935    {
1936       ide.debugger.StepOut(skip);
1937       return true;
1938    }
1939
1940    void ImportFolder(ProjectNode toNode)
1941    {
1942       if(toNode)
1943       {
1944          //bool isFolder = toNode.type == folder;
1945          //bool isRes = toNode.isInResources;
1946          
1947          FileDialog fileDialog = importFileDialog;
1948          fileDialog.master = parent;
1949          if(fileDialog.Modal() == ok)
1950          {
1951             ImportFolderFSI fsi { projectView = this };
1952             fsi.stack.Add(toNode);
1953             fsi.Iterate(fileDialog.filePath);
1954             delete fsi;
1955          }
1956       }
1957    }
1958
1959    ProjectNode NewFolder(ProjectNode parentNode, char * name, bool showProperties)
1960    {
1961       if(parentNode)
1962       {
1963          ProjectNode folderNode;
1964          Project prj = parentNode.project;
1965          int c;
1966          ProjectNode after = null;
1967          for(node : parentNode.files)
1968          {
1969             if(node.type != folder)
1970                break;
1971             after = node;
1972          }
1973          
1974          if(name && name[0])
1975             folderNode = parentNode.Add(prj, name, after, folder, folder, true);
1976          else
1977          {
1978             for(c = 0; c < 100; c++)
1979             {
1980                char string[16];
1981                sprintf(string, c ? "New Folder (%d)" : "New Folder", c);
1982                if((folderNode = parentNode.Add(prj, string, after, folder, folder, true)))
1983                   break;
1984             }
1985          }
1986
1987          if(folderNode)
1988          {
1989             NodeProperties nodeProperties;
1990             if(!showProperties)
1991             {
1992                modifiedDocument = true;
1993                prj.topNode.modified = true;
1994             }
1995             Update(null);
1996             folderNode.row = parentNode.row.AddRowAfter(after ? after.row : null);
1997             folderNode.row.tag = (int64)folderNode;
1998                
1999             folderNode.row.SetData(null, folderNode);
2000             fileList.currentRow = folderNode.row;
2001             
2002             if(showProperties)
2003             {
2004                nodeProperties = NodeProperties
2005                {
2006                   parent, this, mode = newFolder, node = folderNode;
2007                   position = { position.x + 100, position.y + 100 };
2008                };
2009                nodeProperties.Create();   // Modal?
2010             }
2011             return folderNode;
2012          }
2013       }
2014       return null;
2015    }
2016
2017    void AddFiles(bool resources)
2018    {
2019       FileDialog fileDialog = (!resources) ? this.fileDialog : resourceFileDialog;
2020       fileDialog.type = multiOpen;
2021       fileDialog.text = !resources ? $"Add Files to Project" : $"Add Resources to Project";
2022       fileDialog.master = parent;
2023
2024       if(fileDialog.Modal() == ok)
2025       {
2026          int c;
2027          DataRow row = fileList.currentRow;
2028          ProjectNode parentNode = (ProjectNode)row.tag;
2029          bool addFailed = false;
2030          int numSelections = fileDialog.numSelections;
2031          char ** multiFilePaths = fileDialog.multiFilePaths;
2032
2033          Array<String> nameConflictFiles { };
2034
2035          for(c = 0; c < numSelections; c++)
2036          {
2037             char * filePath = multiFilePaths[c];
2038             FileAttribs exists = FileExists(filePath);
2039             bool addThisFile = true;
2040
2041             if(exists.isDirectory)
2042                addThisFile = false;
2043             else if(!exists)
2044             {
2045                if(MessageBox { master = ide, type = yesNo, text = filePath, 
2046                      contents = $"File doesn't exist. Create?" }.Modal() == yes)
2047                {
2048                   File f = FileOpen(filePath, write);
2049                   if(f)
2050                   {
2051                      addThisFile = true;
2052                      delete f;
2053                   }
2054                   else
2055                   {
2056                      MessageBox { master = ide, type = ok, text = filePath, 
2057                            contents = $"Couldn't create file."}.Modal();
2058                      addThisFile = false;
2059                   }
2060                }
2061             }
2062
2063             if(addThisFile)
2064             {
2065                /*addFailed = */if(!AddFile(parentNode, filePath, resources, false))//;
2066                {
2067                   nameConflictFiles.Add(CopyString(filePath));
2068                   addFailed = true;
2069                }
2070             }
2071          }
2072          if(addFailed)
2073          {
2074             int len = 0;
2075             char * part1 = $"The following file";
2076             char * opt1 = $" was ";
2077             char * opt2 = $"s were ";
2078             char * part2 = $"not added because of identical file name conflict within the project.\n\n";
2079             char * message;
2080             len += strlen(part1);
2081             len += strlen(part2);
2082             len += nameConflictFiles.count > 1 ? strlen(opt2) : strlen(opt1);
2083             for(s : nameConflictFiles)
2084                len += strlen(s) + 1;
2085             message = new char[len + 1];
2086             strcpy(message, part1);
2087             strcat(message, nameConflictFiles.count > 1 ? opt2 : opt1);
2088             strcat(message, part2);
2089             for(s : nameConflictFiles)
2090             {
2091                strcat(message, s);
2092                strcat(message, "\n");
2093             }
2094             MessageBox { master = ide, type = ok, text = $"Name Conflict", 
2095                   contents = message }.Modal();
2096             delete message;
2097          }
2098          nameConflictFiles.Free();
2099          delete nameConflictFiles;
2100       }
2101    }
2102
2103    ProjectNode AddFile(ProjectNode parentNode, char * filePath, bool resources, bool isTemporary)
2104    {
2105       ProjectNode result = null;
2106       ProjectNode after = null;
2107       for(node : parentNode.files)
2108       {
2109          if(node.type != folder && node.type != file && node.type)
2110             break;
2111          after = node;
2112       }
2113
2114       result = parentNode.Add(parentNode.project, filePath, after, file, NodeIcons::SelectFileIcon(filePath), !resources);
2115
2116       if(result)
2117       {
2118          if(!isTemporary)
2119          {
2120             modifiedDocument = true;
2121             parentNode.project.topNode.modified = true;
2122             parentNode.project.ModifiedAllConfigs(true, false, true, true);
2123          }
2124          Update(null);
2125          result.row = parentNode.row.AddRowAfter(after ? after.row : null);
2126          result.row.tag = (int64)result;
2127          result.row.SetData(null, result);
2128       }
2129       return result;
2130    }
2131
2132    CodeEditor CreateNew(char * upper, char * lower, char * base, char * className)
2133    {
2134       CodeEditor codeEditor = null;
2135       ProjectNode projectNode;
2136       ProjectNode after = null;
2137       DataRow row = fileList.currentRow;
2138       ProjectNode parentNode;
2139       int c;
2140
2141       if(!row) row = project.topNode.row;
2142
2143       parentNode = (ProjectNode)row.tag;
2144
2145       for(node : parentNode.files)
2146       {
2147          if(node.type != folder && node.type != file && node.type)
2148             break;
2149          after = node;
2150       }
2151       for(c = 1; c < 100; c++)
2152       {
2153          char string[16];
2154          sprintf(string, c ? "%s%d.ec" : "%s.ec", lower, c);
2155          if((projectNode = parentNode.Add(project, string, after, file, genFile, true)))
2156             break;
2157       }
2158       if(projectNode)
2159       {
2160          char name[256];
2161          char filePath[MAX_LOCATION];
2162
2163          modifiedDocument = true;
2164          project.topNode.modified = true;
2165          Update(null);
2166          project.ModifiedAllConfigs(true, false, false, true);
2167          projectNode.row = parentNode.row.AddRowAfter(after ? after.row : null);
2168          projectNode.row.tag =(int64)projectNode;
2169             
2170          projectNode.row.SetData(null, projectNode);
2171          fileList.currentRow = projectNode.row;
2172
2173          strcpy(filePath, project.topNode.path);
2174          PathCat(filePath, projectNode.path);
2175          PathCat(filePath, projectNode.name);
2176
2177          codeEditor = (CodeEditor)ide.FindWindow(filePath);
2178          if(!codeEditor)
2179          {
2180             Class baseClass = eSystem_FindClass(__thisModule, base);
2181             subclass(ClassDesignerBase) designerClass = eClass_GetDesigner(baseClass);
2182             if(designerClass)
2183             {
2184                codeEditor = (CodeEditor)ide.OpenFile(filePath, normal, false, null, whatever, normal, false);
2185                strcpy(name, projectNode.name);
2186                sprintf(name, "%s%d", upper, c);
2187                if(className)
2188                   strcpy(className, name);
2189
2190                designerClass.CreateNew(codeEditor.editBox, codeEditor.clientSize, name, base);
2191
2192                //codeEditor.modifiedDocument = false;
2193                //codeEditor.designer.modifiedDocument = false;
2194
2195                //Code_EnsureUpToDate(codeEditor);
2196             }
2197          }
2198          else // TODO: fix no symbols generated when ommiting {} for following else
2199          {
2200             codeEditor = (CodeEditor)ide.OpenFile(filePath, normal, false, null, whatever, normal, false);
2201          }
2202          ide.sheet.visible = true;
2203          ide.sheet.Activate();
2204          if(codeEditor)
2205          {
2206             codeEditor.ViewDesigner();
2207             codeEditor.codeModified = true;
2208          }
2209       }
2210       //visible = false;
2211       return codeEditor;   
2212    }
2213
2214    // Returns true if we opened something
2215    bool OpenSelectedNodes(bool noParsing)
2216    {
2217       bool result = false;
2218       OldList selection;
2219       OldLink item;
2220
2221       fileList.GetMultiSelection(selection);
2222       for(item = selection.first; item; item = item.next)
2223       {
2224          DataRow row = item.data;
2225          ProjectNode node = (ProjectNode)row.tag;
2226          if(node.type == file)
2227          {
2228             OpenNode(node, noParsing);
2229             result = true;
2230          }
2231       }
2232       selection.Free(null);
2233       return result;
2234    }
2235
2236    void RemoveSelectedNodes()
2237    {
2238       OldList selection;
2239       OldLink item, next;
2240       
2241       fileList.GetMultiSelection(selection);
2242
2243       // Remove children of parents we're deleting
2244       for(item = selection.first; item; item = next)
2245       {
2246          OldLink i;
2247          DataRow row = item.data;
2248          ProjectNode n, node = (ProjectNode)row.tag;
2249          bool remove = false;
2250
2251          next = item.next;
2252          for(i = selection.first; i && !remove; i = i.next)
2253          {
2254             ProjectNode iNode = (ProjectNode)((DataRow)i.data).tag;
2255             for(n = node.parent; n; n = n.parent)
2256             {
2257                if(iNode == n)
2258                {
2259                   remove = true;
2260                   break;
2261                }
2262             }
2263          }
2264          if(remove)
2265             selection.Delete(item);
2266       }
2267
2268       for(item = selection.first; item; item = item.next)
2269       {
2270          DataRow row = item.data;
2271          ProjectNode node = (ProjectNode)row.tag;
2272          ProjectNode resNode;
2273          for(resNode = node.parent; resNode; resNode = resNode.parent)
2274             if(resNode.type == resources)
2275                break;
2276          if(node.type == file)
2277          {
2278             Project prj = node.project;
2279             DeleteNode(node);
2280             modifiedDocument = true;
2281             prj.topNode.modified = true;
2282             Update(null);
2283             prj.ModifiedAllConfigs(true, false, true, true);
2284          }
2285          else if(node.type == folder)
2286          {
2287             char message[1024];
2288             sprintf(message, $"Are you sure you want to remove the folder \"%s\"\n"
2289                   "and all of its contents from the project?", node.name);
2290             if(MessageBox { master = ide, type = yesNo, text = $"Delete Folder", contents = message }.Modal() == yes)
2291             {
2292                Project prj = node.project;
2293                if(node.containsFile)
2294                   prj.ModifiedAllConfigs(true, false, true, true);
2295                DeleteNode(node);
2296                modifiedDocument = true;
2297                prj.topNode.modified = true;
2298             }
2299          }
2300          else if(node.type == project && node != project.topNode && !buildInProgress)
2301          {
2302             char message[1024];
2303             Project prj = null;
2304             for(p : workspace.projects)
2305             {
2306                if(p.topNode == node)
2307                {
2308                   prj = p;
2309                   break;
2310                }
2311             }
2312             sprintf(message, $"Are you sure you want to remove the \"%s\" project\n" "from this workspace?", node.name);
2313             if(MessageBox { master = ide, type = yesNo, text = $"Remove Project", contents = message }.Modal() == yes)
2314             {
2315                // THIS GOES FIRST!
2316                DeleteNode(node);
2317                if(prj)
2318                   workspace.RemoveProject(prj);
2319                //modifiedDocument = true; // when project view is a workspace view
2320             }
2321          }
2322       }
2323       selection.Free(null);
2324    }
2325 }