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