ide/Project: Fixed support for spaces in project name
[sdk] / ide / src / project / Project.ec
1 #ifdef ECERE_STATIC
2 public import static "ecere"
3 #else
4 public import "ecere"
5 #endif
6
7 #ifndef MAKEFILE_GENERATOR
8 import "ide"
9 // We should have the .sln/.vcproj generation even on other platforms
10 // e.g. detect from an environment variable pointing to a Windows drive
11 #ifdef __WIN32__
12 import "vsSupport"
13 #endif
14 #endif
15
16 import "ProjectConfig"
17 import "ProjectNode"
18 import "IDESettings"
19
20 default:
21
22 static void DummyFunction()
23 {
24 int a;
25 a.OnFree();
26 }
27
28 private:
29
30 extern int __ecereVMethodID_class_OnCompare;
31 extern int __ecereVMethodID_class_OnFree;
32
33 IDESettings ideSettings;
34
35 IDESettingsContainer settingsContainer
36 {
37    driver = "JSON";
38    dataOwner = &ideSettings;
39    dataClass = class(IDESettings);
40
41    void OnLoad(GlobalSettingsData data)
42    {
43       IDESettings settings = (IDESettings)data;
44 #ifndef MAKEFILE_GENERATOR
45       globalSettingsDialog.ideSettings = settings;
46       ide.UpdateRecentMenus();
47       // ide.UpdateMakefiles(); -- can't really regenerate on Load since all recent menus changes will happen
48 #endif
49    }
50 };
51
52 #ifdef MAKEFILE_GENERATOR
53 CompilerConfig defaultCompiler;
54 #endif
55
56 // LEGACY BINARY EPJ LOADING
57
58 SetBool ParseTrueFalseValue(char * string)
59 {
60    if(!strcmpi(string, "True")) return true;
61    return false;
62 }
63
64 void ParseArrayValue(Array<String> array, char * equal)
65 {
66    char * start, * comma;
67    char * string;
68    string = CopyString(equal);
69    start = string;
70    while(start)
71    {
72       comma = strstr(start, ",");
73       if(comma)
74          comma[0] = '\0';
75       array.Add(CopyString(start));
76       if(comma)
77          comma++;
78       if(comma)
79          comma++;
80       start = comma;
81    }
82    delete string;
83 }
84
85 void ProjectNode::LegacyBinaryLoadNode(File f)
86 {
87    int len, count, c;
88    int fileNameLen;
89
90    f.Read(&len, sizeof(len), 1);
91    name = new char[len+1];
92    fileNameLen = len;
93    f.Read(name, sizeof(char), len+1);
94    f.Read(&len, sizeof(len), 1);
95    fileNameLen += len;
96    path = new char[len+1];
97    f.Read(path, sizeof(char), len+1);
98    
99    /*
100    fileName = new char[fileNameLen+2];
101    strcpy(fileName, path);
102    if(fileName[0]) strcat(fileName, "/");
103    strcat(fileName, name);
104    */
105
106    f.Read(&type, sizeof(type), 1);
107    f.Read(&count, sizeof(count), 1);
108    
109    if(type == file)
110    {
111       nodeType = file;
112       icon = NodeIcons::SelectFileIcon(name);
113    }
114    else
115    {
116       nodeType = folder;
117       icon = NodeIcons::SelectNodeIcon(type);
118    }
119
120    if(count && !files) files = { };
121    for(c = 0; c < count; c++)
122    {
123       ProjectNode child { };
124       files.Add(child);
125       child.parent = this;
126       child.indent = indent + 1;
127       LegacyBinaryLoadNode(child, f);
128    }
129 }
130
131 /*void LegacyBinarySaveNode(File f)
132 {
133    int len;
134    ProjectNode child;
135    len = strlen(name);
136    f.Write(&len, sizeof(len), 1);
137    f.Write(name, sizeof(char), len+1);
138
139    if(type == project)
140    {
141       // Projects Absolute Path Are Not Saved
142       len = 0;
143       f.Write(&len, sizeof(len), 1);
144       f.Write(&len, sizeof(char), 1);
145    }
146    else
147    {
148       len = strlen(path);
149       f.Write(&len, sizeof(len), 1);
150       f.Write(path, sizeof(char), len+1);
151    }
152    f.Write(&type, sizeof(type), 1);
153    f.Write(&children.count, sizeof(children.count), 1);
154    for(child = children.first; child; child.next)
155       child.SaveNode(f);
156 }*/
157
158 void ProjectNode::LegacyAsciiSaveNode(File f, char * indentation, char * insidePath)
159 {
160    int len;
161    char printPath[MAX_LOCATION];
162
163    if(type == project && (files.count /*|| preprocessorDefs.first*/))
164    {
165       f.Printf("\n   Files\n");
166    }
167    else if(type == file)
168    {
169       if(!strcmp(path, insidePath))
170          f.Printf("%s - %s\n", indentation, name);
171       else
172       {
173          strcpy(printPath, path);
174          len = strlen(printPath);
175          if(len)
176             if(printPath[len-1] != '/')
177                strcat(printPath, "/");
178          strcat(printPath, name);
179          f.Printf("%s = %s\n", indentation, printPath);
180       }
181       if(files.count)
182          f.Printf("\nError\n\n");
183    }
184    else if(type == folder)
185    {
186       f.Printf("%s + %s\n", indentation, name);
187    }
188    else if(type == resources && files.count)
189    {
190       PathCatSlash(insidePath, path);
191       f.Printf("\n%sResources\n", indentation);
192       if(path && path[0])
193          f.Printf("%s   Path = %s\n", indentation, path);
194    }
195    
196    /*if(buildExclusions.first && type != project)
197    {
198       for(item = buildExclusions.first; item; item = item.next)
199       {
200          if(item == buildExclusions.first)
201             f.Printf("%s      Build Exclusions = %s", indentation, item.name);
202          else
203             f.Printf(", %s", item.name);
204       }
205       f.Printf("\n");
206    }
207
208    if(preprocessorDefs.first && (type == project || ((type == file || type == folder) && !isInResources)))
209    {
210       for(item = preprocessorDefs.first; item; item = item.next)
211       {
212          if(item == preprocessorDefs.first)
213             f.Printf("%s%s   Preprocessor Definitions = %s", indentation, type == project ? "" : "   ", item.name);
214          else
215             f.Printf(", %s", item.name);
216       }
217       f.Printf("\n");
218    }
219    */
220    
221    if(type == project && (files.count /*|| preprocessorDefs.first*/))
222    {
223       f.Printf("\n");
224       for(child : files)
225          LegacyAsciiSaveNode(child, f, indentation, insidePath);
226    }
227    else if(type == folder)
228    {
229       strcat(indentation, "   ");
230       // WHAT WAS THIS: strcpy(printPath, path);
231       // TOCHECK: why is Unix/PathCat not used here
232       len = strlen(insidePath);
233       if(len)
234          if(insidePath[len-1] != '/')
235             strcat(insidePath, "/");
236       strcat(insidePath, name);
237
238       for(child : files)
239          LegacyAsciiSaveNode(child, f, indentation, insidePath);
240       f.Printf("%s -\n", indentation);
241       indentation[strlen(indentation) - 3] = '\0';
242       StripLastDirectory(insidePath, insidePath);
243    }
244    else if(type == resources && files.count)
245    {
246       f.Printf("\n");
247       for(child : files)
248          LegacyAsciiSaveNode(child, f, indentation, insidePath);
249       StripLastDirectory(insidePath, insidePath);
250    }
251 }
252
253 /*
254 void ProjectConfig::LegacyProjectConfigSave(File f)
255 {
256    char * indentation = "      ";
257    //if(isCommonConfig)
258       //f.Printf("\n * Common\n");
259    //else
260       f.Printf("\n + %s\n", name);
261    f.Printf("\n   Compiler\n\n");
262    if(objDir.expression[0])
263       f.Printf("%sIntermediate Directory = %s\n", indentation, objDir.expression);
264    f.Printf("%sDebug = %s\n", indentation, (options.debug == true) ? "True" : "False");
265    switch(options.optimization)
266    {
267       // case none:   f.Printf("%sOptimize = %s\n", indentation, "None"); break;
268       case speed: f.Printf("%sOptimize = %s\n", indentation, "Speed"); break;
269       case size:  f.Printf("%sOptimize = %s\n", indentation, "Size");  break;
270    }
271    f.Printf("%sAllWarnings = %s\n", indentation, (options.warnings == all) ? "True" : "False");
272    if(options.profile)
273       f.Printf("%sProfile = %s\n", indentation, (options.profile == true) ? "True" : "False");
274    if(options.memoryGuard == true)
275       f.Printf("%sMemoryGuard = %s\n", indentation, (options.memoryGuard == true) ? "True" : "False");
276    if(options.strictNameSpaces == true)
277       f.Printf("%sStrict Name Spaces = %s\n", indentation, (options.strictNameSpaces == true) ? "True" : "False");
278    if(options.defaultNameSpace && strlen(options.defaultNameSpace))
279       f.Printf("%sDefault Name Space = %s\n", indentation, options.defaultNameSpace);
280     TOFIX: Compiler Bug {
281       if(options.preprocessorDefinitions.count)
282       {
283          bool isFirst = true;
284          for(item : options.preprocessorDefinitions)
285          {
286             if(isFirst)
287             {
288                f.Printf("\n%sPreprocessor Definitions = %s", indentation, item);
289                isFirst = false;
290             }
291             else
292                f.Printf(", %s", item);
293          }
294          f.Printf("\n");
295       }
296    }
297    if(options.includeDirs.count)
298    {
299       f.Printf("\n%sInclude Directories\n", indentation);
300       for(item : options.includeDirs)
301          f.Printf("%s - %s\n", indentation, name);
302       f.Printf("\n");
303    }
304
305    f.Printf("\n%sLinker\n\n", indentation);
306    f.Printf("%sTarget Name = %s\n", indentation, options.targetFileName);
307    switch(options.targetType)
308    {
309       case executable:     f.Printf("%sTarget Type = %s\n", indentation, "Executable"); break;
310       case sharedLibrary:  f.Printf("%sTarget Type = %s\n", indentation, "Shared");     break;
311       case staticLibrary:  f.Printf("%sTarget Type = %s\n", indentation, "Static");     break;
312    }
313    if(targetDir.expression[0])
314       f.Printf("%sTarget Directory = %s\n", indentation, targetDir.expression);
315    if(options.console)
316       f.Printf("%sConsole = %s\n", indentation, options.console ? "True" : "False");
317    if(options.compress)
318       f.Printf("%sCompress = %s\n", indentation, options.compress ? "True" : "False");
319    if(options.libraries.count)
320    {
321       bool isFirst = true;
322       for(item : options.libraries)
323       {
324          if(isFirst)
325          {
326             f.Printf("\n%sLibraries = %s", indentation, name);
327             isFirst = false;
328          }
329          else
330             f.Printf(", %s", item);
331       }
332       f.Printf("\n");
333    }
334    if(options.libraryDirs.count)
335    {
336       f.Printf("\n%sLibrary Directories\n\n", indentation);
337       for(item : options.libraryDirs)
338          f.Printf("       - %s\n", indentation, item);
339    }
340 }
341
342 void LegacyAsciiSaveProject(File f, Project project)
343 {
344    char indentation[128*3];
345    char path[MAX_LOCATION];
346
347    f.Printf("\nECERE Project File : Format Version 0.1b\n");
348    f.Printf("\nDescription\n%s\n.\n", project.description);
349    f.Printf("\nLicense\n%s\n.\n", project.license);
350    f.Printf("\nModule Name = %s\n", project.moduleName);
351    f.Printf("\n   Configurations\n");
352    //////////////////////////////////////commonConfig.Save(f, true);
353    for(cfg : project.configurations)
354       LegacyProjectConfigSave(cfg, f);
355
356    strcpy(indentation, "   ");
357    path[0] = '\0';
358    LegacyAsciiSaveNode(project.topNode, f, indentation, path);
359    // f.Printf("\n");
360    delete f;
361 }
362 */
363
364 // *** NEW JSON PROJECT FORMAT ***
365 public enum ProjectNodeType { file, folder };
366
367 // *******************************
368
369 define PEEK_RESOLUTION = (18.2 * 10);
370
371 // On Windows & UNIX
372 #define SEPS    "/"
373 #define SEP     '/'
374
375 static byte epjSignature[] = { 'E', 'P', 'J', 0x04, 0x01, 0x12, 0x03, 0x12 };
376
377 enum GenMakefilePrintTypes { objects, cObjects, symbols, imports, sources, resources };
378
379 define WorkspaceExtension = "ews";
380 define ProjectExtension = "epj";
381
382 void ReplaceSpaces(char * output, char * source)
383 {
384    int c, dc;
385    char ch, pch = 0;
386
387    for(c = 0, dc = 0; (ch = source[c]); c++, dc++)
388    {
389       if(ch == ' ') output[dc++] = '\\';
390       if(pch != '$')
391       {
392          if(ch == '(' || ch == ')') output[dc++] = '\\';
393          pch = ch;
394       }
395       else if(ch == ')')
396          pch = 0;
397       output[dc] = ch;
398    }
399    output[dc] = '\0';
400 }
401
402 static void OutputNoSpace(File f, char * source)
403 {
404    char * output = new char[strlen(source)+1024];
405    ReplaceSpaces(output, source);
406    f.Puts(output);
407    delete output;
408 }
409
410 enum ListOutputMethod { inPlace, newLine, lineEach };
411
412 int OutputFileList(File f, char * name, Array<String> list, Map<String, int> varStringLenDiffs)
413 {
414    int numOfBreaks = 0;
415    const int breakListLength = 1536;
416    const int breakLineLength = 78; // TODO: turn this into an option.
417
418    int c, len, itemCount = 0;
419    Array<int> breaks { };
420    if(list.count)
421    {
422       int charCount = 0;
423       MapNode<String, int> mn;
424       for(c=0; c<list.count; c++)
425       {
426          len = strlen(list[c]) + 3;
427          if(strstr(list[c], "$(") && varStringLenDiffs && varStringLenDiffs.count)
428          {
429             for(mn = varStringLenDiffs.root.minimum; mn; mn = mn.next)
430             {
431                if(strstr(list[c], mn.key))
432                   len += mn.value;
433             }
434          }
435          if(charCount + len > breakListLength)
436          {
437             breaks.Add(itemCount);
438             itemCount = 0;
439             charCount = len;
440          }
441          itemCount++;
442          charCount += len;
443       }
444       if(itemCount)
445          breaks.Add(itemCount);
446       numOfBreaks = breaks.count;
447    }
448
449    if(numOfBreaks > 1)
450    {
451       f.Printf("%s =", name);
452       for(c=0; c<numOfBreaks; c++)
453          f.Printf(" $(%s%d)", name, c+1);
454       f.Printf("\n");
455    }
456    else
457       f.Printf("%s =", name);
458
459    if(numOfBreaks)
460    {
461       int n, offset = 0;
462
463       for(c=0; c<numOfBreaks; c++)
464       {
465          if(numOfBreaks > 1)
466             f.Printf("%s%d =", name, c+1);
467          
468          len = 3;
469          itemCount = breaks[c];
470          for(n=offset; n<offset+itemCount; n++)
471          {
472             if(false) // TODO: turn this into an option.
473             {
474                int itemLen = strlen(list[n]);
475                if(len > 3 && len + itemLen > breakLineLength)
476                {
477                   f.Printf(" \\\n\t%s", list[n]);
478                   len = 3;
479                }
480                else
481                {
482                   len += itemLen;
483                   f.Printf(" %s", list[n]);
484                }
485             }
486             else
487                f.Printf(" \\\n\t%s", list[n]);
488          }
489          offset += itemCount;
490          f.Printf("\n");
491       }
492       list.Free();
493       list.count = 0;
494    }
495    else
496       f.Printf("\n");
497    f.Printf("\n");
498    delete breaks;
499    return numOfBreaks;
500 }
501
502 void OutputCleanActions(File f, char * name, int parts)
503 {
504    if(parts > 1)
505    {
506       int c;
507       for(c=0; c<parts; c++)
508          f.Printf("\t$(call rmq,$(%s%d))\n", name, c+1);
509    }
510    else
511       f.Printf("\t$(call rmq,$(%s))\n", name);
512 }
513
514 void OutputListOption(File f, char * option, Array<String> list, ListOutputMethod method, bool noSpace)
515 {
516    if(list.count)
517    {
518       if(method == newLine)
519          f.Printf(" \\\n\t");
520       for(item : list)
521       {
522          if(method == lineEach)
523             f.Printf(" \\\n\t");
524          f.Printf(" -%s", option);
525          if(noSpace)
526             OutputNoSpace(f, item);
527          else
528             f.Printf("%s", item);
529       }
530    }
531 }
532
533 static void OutputLibraries(File f, Array<String> libraries)
534 {
535    for(item : libraries)
536    {
537       char ext[MAX_EXTENSION];
538       char temp[MAX_LOCATION];
539       char * s = item;
540       GetExtension(item, ext);
541       if(!strcmp(ext, "o") || !strcmp(ext, "a"))
542          f.Printf(" ");
543       else
544       {
545          if(!strcmp(ext, "so") || !strcmp(ext, "dylib"))
546          {
547             if(!strncmp(item, "lib", 3))
548                strcpy(temp, item + 3);
549             else
550                strcpy(temp, item);
551             StripExtension(temp);
552             s = temp;
553          } 
554          f.Printf(" -l");
555       }
556       OutputNoSpace(f, s);
557    }
558 }
559
560 void CamelCase(char * string)
561 {
562    int c, len = strlen(string);
563    for(c=0; c<len && string[c] >= 'A' && string[c] <= 'Z'; c++)
564       string[c] = (char)tolower(string[c]);
565 }
566
567 CompilerConfig GetCompilerConfig()
568 {
569 #ifndef MAKEFILE_GENERATOR
570    CompilerConfig compiler = null;
571    if(ide && ide.workspace)
572       compiler = ideSettings.GetCompilerConfig(ide.workspace.compiler);
573    return compiler;
574 #else
575    incref defaultCompiler;
576    return defaultCompiler;
577 #endif
578 }
579
580 define localTargetType = config && config.options && config.options.targetType ?
581             config.options.targetType : options && options.targetType ?
582             options.targetType : TargetTypes::executable;
583 define localWarnings = config && config.options && config.options.warnings ?
584             config.options.warnings : options && options.warnings ?
585             options.warnings : WarningsOption::unset;
586 define localDebug = config && config.options && config.options.debug ?
587             config.options.debug : options && options.debug ?
588             options.debug : SetBool::unset;
589 define localMemoryGuard = config && config.options && config.options.memoryGuard ?
590             config.options.memoryGuard : options && options.memoryGuard ?
591             options.memoryGuard : SetBool::unset;
592 define localNoLineNumbers = config && config.options && config.options.noLineNumbers ?
593             config.options.noLineNumbers : options && options.noLineNumbers ?
594             options.noLineNumbers : SetBool::unset;
595 define localProfile = config && config.options && config.options.profile ?
596             config.options.profile : options && options.profile ?
597             options.profile : SetBool::unset;
598 define localOptimization = config && config.options && config.options.optimization ?
599             config.options.optimization : options && options.optimization ?
600             options.optimization : OptimizationStrategy::none;
601 define localDefaultNameSpace = config && config.options && config.options.defaultNameSpace ?
602             config.options.defaultNameSpace : options && options.defaultNameSpace ?
603             options.defaultNameSpace : null;
604 define localStrictNameSpaces = config && config.options && config.options.strictNameSpaces ?
605             config.options.strictNameSpaces : options && options.strictNameSpaces ?
606             options.strictNameSpaces : SetBool::unset;
607 // TODO: I would rather have null here, check if it'll be ok, have the property return "" if required
608 define localTargetFileName = config && config.options && config.options.targetFileName ?
609             config.options.targetFileName : options && options.targetFileName ?
610             options.targetFileName : "";
611 define localTargetDirectory = config && config.options && config.options.targetDirectory && config.options.targetDirectory[0] ?
612             config.options.targetDirectory : options && options.targetDirectory && options.targetDirectory[0] ?
613             options.targetDirectory : null;
614 define settingsTargetDirectory = ideSettings && ideSettings.projectDefaultIntermediateObjDir &&
615             ideSettings.projectDefaultIntermediateObjDir[0] ?
616             ideSettings.projectDefaultIntermediateObjDir : defaultObjDirExpression;
617 define localObjectsDirectory = config && config.options && config.options.objectsDirectory && config.options.objectsDirectory[0] ?
618             config.options.objectsDirectory : options && options.objectsDirectory && options.objectsDirectory[0] ?
619             options.objectsDirectory : null;
620 define settingsObjectsDirectory = ideSettings && ideSettings.projectDefaultIntermediateObjDir &&
621             ideSettings.projectDefaultIntermediateObjDir[0] ?
622             ideSettings.projectDefaultIntermediateObjDir : defaultObjDirExpression;
623 define localConsole = config && config.options && config.options.console ?
624             config.options.console : options && options.console ?
625             options.console : SetBool::unset;
626 define localCompress = config && config.options && config.options.compress ?
627             config.options.compress : options && options.compress ?
628             options.compress : SetBool::unset;
629
630 char * PlatformToMakefileVariable(Platform platform)
631 {
632    return platform == win32 ? "WINDOWS" : platform == tux ? "LINUX" : platform == apple ? "OSX"/*"APPLE"*/ : platform;
633 }
634
635 // Move this to ProjectConfig? null vs Common to consider...
636 char * GetConfigName(ProjectConfig config)
637 {
638    return config ? config.name : "Common";
639 }
640
641 class Project : struct
642 {
643    class_no_expansion;  // To use Find on the Container<Project> in Workspace::projects
644                         // We might want to tweak this default behavior of regular classes ?
645                         // Expansion/the current default kind of Find matching we want for things like BitmapResource, FontResource (Also regular classes)
646 public:
647    float version;
648    String moduleName;
649
650    property ProjectOptions options { get { return options; } set { options = value; } isset { return options && !options.isEmpty; } }
651    property Array<PlatformOptions> platforms
652    {
653       get { return platforms; }
654       set
655       {
656          if(platforms) { platforms.Free(); delete platforms; }
657          if(value)
658          {
659             List<PlatformOptions> empty { };
660             Iterator<PlatformOptions> it { value };
661             platforms = value;
662             for(p : platforms; !p.options || p.options.isEmpty) empty.Add(p);
663             for(p : empty; it.Find(p)) platforms.Delete(it.pointer);
664             delete empty;
665          }
666       }
667       isset
668       {
669          if(platforms)
670          {
671             for(p : platforms)
672             {
673                if(p.options && !p.options.isEmpty)
674                   return true;
675             }
676          }
677          return false;
678       }
679    }
680    List<ProjectConfig> configurations;
681    LinkList<ProjectNode> files;
682    String resourcesPath;
683    LinkList<ProjectNode> resources;
684
685    property char * description
686    {
687       set { delete description; if(value && value[0]) description = CopyString(value); }
688       get { return description ? description : ""; }
689       isset { return description != null && description[0]; }
690    }
691
692    property char * license
693    {
694       set { delete license; if(value && value[0]) license = CopyString(value); }
695       get { return license ? license : ""; }
696       isset { return license != null && license[0]; }
697    }
698
699 private:
700    // topNode.name holds the file name (.epj)
701    ProjectOptions options;
702    Array<PlatformOptions> platforms;
703    ProjectNode topNode { type = project, icon = epjFile, files = LinkList<ProjectNode>{ }, project = this };
704    ProjectNode resNode;
705
706    ProjectConfig config;
707    String filePath;
708    // This is the file name stripped of the epj extension
709    // It should NOT be edited, saved or loaded anywhere
710    String name;
711
712    String description;
713    String license;
714
715    ~Project()
716    {
717       /* // THIS IS NOW AUTOMATED WITH A project CHECK IN ProjectNode
718       topNode.configurations = null;
719       topNode.platforms = null;
720       topNode.options = null;
721       */
722
723       if(platforms) { platforms.Free(); delete platforms; }
724       if(configurations) { configurations.Free(); delete configurations; }
725       if(files) { files.Free(); delete files; }
726       if(resources) { resources.Free(); delete resources; }
727       delete options;
728       delete resourcesPath;
729
730       delete description;
731       delete license;
732       delete moduleName;
733       delete filePath;
734       delete topNode;
735       delete name;
736    }
737
738    property ProjectConfig config
739    {
740       set
741       {
742          config = value;
743          delete topNode.info;
744          topNode.info = CopyString(GetConfigName(config));
745       }
746    }
747    property char * filePath
748    {
749       set
750       {
751          if(value)
752          {
753             char string[MAX_LOCATION];
754             GetLastDirectory(value, string);
755             delete topNode.name;
756             topNode.name = CopyString(string);
757             StripExtension(string);
758             delete name;
759             name = CopyString(string);
760             StripLastDirectory(value, string);
761             delete topNode.path;
762             topNode.path = CopyString(string);
763             delete filePath;
764             filePath = CopyString(value);
765          }
766       }
767    }
768
769    TargetTypes GetTargetType(ProjectConfig config)
770    {
771       // TODO: Implement platform specific options?
772       TargetTypes targetType = localTargetType;
773       return targetType;
774    }
775
776    char * GetObjDirExpression(CompilerConfig compiler, ProjectConfig config)
777    {
778       // TODO: Support platform options
779       char * expression = localObjectsDirectory;
780       if(!expression)
781          expression = settingsObjectsDirectory;
782       return expression;
783    }
784
785    DirExpression GetObjDir(CompilerConfig compiler, ProjectConfig config)
786    {
787       char * expression = GetObjDirExpression(compiler, config);
788       DirExpression objDir { type = intermediateObjectsDir };
789       objDir.Evaluate(expression, this, compiler, config);
790       return objDir;
791    }
792
793    char * GetTargetDirExpression(CompilerConfig compiler, ProjectConfig config)
794    {
795       // TODO: Support platform options
796       char * expression = localTargetDirectory;
797       if(!expression)
798          expression = settingsTargetDirectory;
799       return expression;
800    }
801
802    DirExpression GetTargetDir(CompilerConfig compiler, ProjectConfig config)
803    {
804       char * expression = GetTargetDirExpression(compiler, config);
805       DirExpression targetDir { type = DirExpressionType::targetDir /*intermediateObjectsDir*/};
806       targetDir.Evaluate(expression, this, compiler, config);
807       return targetDir;
808    }
809
810    WarningsOption GetWarnings(ProjectConfig config)
811    {
812       WarningsOption warnings = localWarnings;
813       return warnings;
814    }
815
816    bool GetDebug(ProjectConfig config)
817    {
818       SetBool debug = localDebug;
819       return debug == true;
820    }
821
822    bool GetMemoryGuard(ProjectConfig config)
823    {
824       SetBool memoryGuard = localMemoryGuard;
825       return memoryGuard == true;
826    }
827
828    bool GetNoLineNumbers(ProjectConfig config)
829    {
830       SetBool noLineNumbers = localNoLineNumbers;
831       return noLineNumbers == true;
832    }
833
834    bool GetProfile(ProjectConfig config)
835    {
836       SetBool profile = localProfile;
837       return profile == true;
838    }
839
840    OptimizationStrategy GetOptimization(ProjectConfig config)
841    {
842       OptimizationStrategy optimization = localOptimization;
843       return optimization;
844    }
845
846    String GetDefaultNameSpace(ProjectConfig config)
847    {
848       String defaultNameSpace = localDefaultNameSpace;
849       return defaultNameSpace;
850    }
851
852    bool GetStrictNameSpaces(ProjectConfig config)
853    {
854       SetBool strictNameSpaces = localStrictNameSpaces;
855       return strictNameSpaces == true;
856    }
857
858    String GetTargetFileName(ProjectConfig config)
859    {
860       String targetFileName = localTargetFileName;
861       return targetFileName;
862    }
863
864    //String targetDirectory;
865    //String objectsDirectory;
866    bool GetConsole(ProjectConfig config)
867    {
868       SetBool console = localConsole;
869       return console == true;
870    }
871
872    bool GetCompress(ProjectConfig config)
873    {
874       SetBool compress = localCompress;
875       return compress == true;
876    }
877    //SetBool excludeFromBuild;
878
879    bool GetConfigIsInActiveDebugSession(ProjectConfig config)
880    {
881 #ifndef MAKEFILE_GENERATOR
882       return ide.project == this && ide.debugger && ide.debugger.prjConfig == config && ide.debugger.isActive;
883 #endif
884    }
885
886    bool GetConfigIsInDebugSession(ProjectConfig config)
887    {
888 #ifndef MAKEFILE_GENERATOR
889       return ide.project == this  && ide.debugger && ide.debugger.prjConfig == config && ide.debugger.isPrepared;
890 #endif
891    }
892
893    void SetPath(bool projectsDirs, CompilerConfig compiler, ProjectConfig config)
894    {
895 #ifndef MAKEFILE_GENERATOR
896       ide.SetPath(projectsDirs, compiler, config);
897 #endif
898    }
899
900 #ifndef MAKEFILE_GENERATOR
901    bool Save(char * fileName)
902    {
903       File f;
904       /*char output[MAX_LOCATION];
905        ChangeExtension(fileName, "json", output);
906       f = FileOpen(output, write);*/
907       f = FileOpen(fileName, write);
908       if(f)
909       {
910          files = topNode.files;
911          resources = resNode.files;
912          resourcesPath = resNode.path;
913
914          files.Remove(resNode);
915          version = 0.2f;
916
917          WriteJSONObject(f, class(Project), this, 0);
918
919          files.Add(resNode);
920
921          files = null;
922          resources = null;
923          resourcesPath = null;
924          delete f;
925       }
926       return true;
927    }
928 #endif
929
930 #ifndef MAKEFILE_GENERATOR
931    bool GetRelativePath(char * filePath, char * relativePath)
932    {
933       ProjectNode node;
934       char moduleName[MAX_FILENAME];
935       GetLastDirectory(filePath, moduleName);
936       // try with workspace dir first?
937       if((node = topNode.Find(moduleName, false)))
938       {
939          strcpy(relativePath, strcmp(node.path, ".") ? node.path : "");
940          PathCatSlash(relativePath, node.name);
941          return true;
942       }
943       // WARNING: On failure, relative path is uninitialized
944       return false;   
945    }
946 #endif
947
948    void CatTargetFileName(char * string, CompilerConfig compiler, ProjectConfig config)
949    {
950       TargetTypes targetType = GetTargetType(config);
951       String targetFileName = GetTargetFileName(config);
952       if(targetType == staticLibrary)
953       {
954          PathCatSlash(string, "lib");
955          strcat(string, targetFileName);
956       }
957       else if(compiler.targetPlatform != win32 && targetType == sharedLibrary)
958       {
959          PathCatSlash(string, "lib");
960          strcat(string, targetFileName);
961       }
962       else
963          PathCatSlash(string, targetFileName);
964       
965       switch(targetType)
966       {
967          case executable:
968             if(compiler.targetPlatform == win32)
969                strcat(string, ".exe");
970             break;
971          case sharedLibrary:
972             if(compiler.targetPlatform == win32)
973                strcat(string, ".dll");
974             else if(compiler.targetPlatform == apple)
975                strcat(string, ".dylib");
976             else
977                strcat(string, ".so");
978             break;
979          case staticLibrary:
980             strcat(string, ".a");
981             break;
982       }
983    }
984
985    void CatMakeFileName(char * string, CompilerConfig compiler, ProjectConfig config)
986    {
987       char projectName[MAX_LOCATION];
988       strcpy(projectName, name);
989       if(strcmpi(compiler.name, defaultCompilerName))
990          sprintf(string, "%s-%s-%s.Makefile", projectName, compiler.name, config.name);
991       else
992          sprintf(string, "%s%s%s.Makefile", projectName, config ? "-" : "", config ? config.name : "");
993    }
994
995 #ifndef MAKEFILE_GENERATOR
996    void MarkChanges(ProjectNode node)
997    {
998       for(cfg : topNode.configurations)
999       {
1000          ProjectConfig c = null;
1001          for(i : node.configurations; !strcmpi(i.name, cfg.name)) { c = i; break; }
1002
1003          if(c && ((c.options && cfg.options && cfg.options.console != c.options.console) ||
1004                (!c.options || !cfg.options)))
1005             cfg.symbolGenModified = true;
1006
1007          cfg.makingModified = true;
1008       }
1009    }
1010
1011    void ModifiedAllConfigs(bool making, bool compiling, bool linking, bool symbolGen)
1012    {
1013       for(cfg : configurations)
1014       {
1015          if(making)
1016             cfg.makingModified = true;
1017          if(compiling)
1018             cfg.compilingModified = true;
1019          if(linking)
1020             cfg.linkingModified = true;
1021          if(symbolGen)
1022             cfg.symbolGenModified = true;
1023       }
1024       if(compiling || linking)
1025       {
1026          ide.projectView.modifiedDocument = true;
1027          ide.workspace.modified = true;
1028       }
1029    }
1030    
1031    void RotateActiveConfig(bool forward)
1032    {
1033       if(configurations.first && configurations.last != configurations.first)
1034       {
1035          Iterator<ProjectConfig> cfg { configurations };
1036          while(forward ? cfg.Next() : cfg.Prev())
1037             if(cfg.data == config)
1038                break;
1039
1040          if(forward)
1041          {
1042             if(!cfg.Next())
1043                cfg.Next();
1044          }
1045          else
1046          {
1047             if(!cfg.Prev())
1048                cfg.Prev();
1049          }
1050
1051          property::config = cfg.data;
1052          ide.workspace.modified = true;
1053          ide.projectView.Update(null);
1054       }
1055    }
1056
1057    void ProcessPipeOutputRaw(DualPipe f)
1058    {
1059       char line[65536];
1060       while(!f.Eof() && !ide.ShouldStopBuild())
1061       {
1062          bool result = true;
1063          double lastTime = GetTime();
1064          bool wait = true;
1065          while(result)
1066          {
1067             if((result = f.Peek()) && (result = f.GetLine(line, sizeof(line)-1)))
1068             {
1069                ide.outputView.buildBox.Logf("%s\n", line);
1070             }
1071             if(GetTime() - lastTime > 1.0 / PEEK_RESOLUTION) break;
1072          }
1073          //printf("Processing Input...\n");
1074          if(app.ProcessInput(true))
1075             wait = false;
1076          app.UpdateDisplay();
1077          if(wait)
1078          {
1079             //printf("Waiting...\n");
1080             app.Wait();
1081          }
1082          //if(!result) Sleep(1.0 / PEEK_RESOLUTION);
1083       }
1084       if(ide.ShouldStopBuild())
1085       {
1086          ide.outputView.buildBox.Logf($"\nBuild cancelled by user.\n", line);
1087          f.Terminate();
1088       }
1089    }
1090
1091    bool ProcessBuildPipeOutput(DualPipe f, DirExpression objDirExp, bool isARun, ProjectNode onlyNode,
1092       CompilerConfig compiler, ProjectConfig config)
1093    {
1094       char line[65536];
1095       bool compiling = false, linking = false, precompiling = false;
1096       int compilingEC = 0;
1097       int numErrors = 0, numWarnings = 0;
1098       bool loggedALine = false;
1099       char * configName = config.name;
1100       int lenMakeCommand = strlen(compiler.makeCommand);
1101       
1102       char cppCommand[MAX_LOCATION];
1103       char ccCommand[MAX_LOCATION];
1104       char ecpCommand[MAX_LOCATION];
1105       char eccCommand[MAX_LOCATION];
1106       char ecsCommand[MAX_LOCATION];
1107       char earCommand[MAX_LOCATION];
1108
1109       char * cc = compiler.ccCommand;
1110       char * cpp = compiler.cppCommand;
1111       sprintf(cppCommand, "%s%s%s%s ",
1112             compiler.ccacheEnabled ? "ccache " : "",
1113             compiler.ccacheEnabled && !compiler.distccEnabled ? " " : "",
1114             compiler.distccEnabled ? "distcc " : "",
1115             compiler.cppCommand);
1116       sprintf(ccCommand, "%s%s%s%s ",
1117             compiler.ccacheEnabled ? "ccache " : "",
1118             compiler.ccacheEnabled && !compiler.distccEnabled ? " " : "",
1119             compiler.distccEnabled ? "distcc " : "",
1120             compiler.ccCommand);
1121       sprintf(ecpCommand, "%s ", compiler.ecpCommand);
1122       sprintf(eccCommand, "%s ", compiler.eccCommand);
1123       sprintf(ecsCommand, "%s ", compiler.ecsCommand);
1124       sprintf(earCommand, "%s ", compiler.earCommand);
1125
1126       while(!f.Eof() && !ide.ShouldStopBuild())
1127       {
1128          bool result = true;
1129          double lastTime = GetTime();
1130          bool wait = true;
1131          while(result)
1132          {
1133             //printf("Peeking and GetLine...\n");
1134             if((result = f.Peek()) && (result = f.GetLine(line, sizeof(line)-1)))
1135             {
1136                if(strstr(line, compiler.makeCommand) == line && line[lenMakeCommand] == ':')
1137                {
1138                   char * module = strstr(line, "No rule to make target `");
1139                   if(module)
1140                   {
1141                      char * end;
1142                      module = strchr(module, '`') + 1;
1143                      end = strchr(module, '\'');
1144                      if(end)
1145                      {
1146                         *end = '\0';
1147                         ide.outputView.buildBox.Logf($"   %s: No such file or directory\n", module);
1148                         // ide.outputView.buildBox.Logf("error: %s\n   No such file or directory\n", module);
1149                         numErrors ++;
1150                      }
1151                   }
1152                   else
1153                   {
1154                      //ide.outputView.buildBox.Logf("error: %s\n", line);
1155                      //numErrors ++;
1156                   }
1157                }
1158                else if(strstr(line, "ear ") == line);
1159                else if(strstr(line, "strip ") == line);
1160                else if(strstr(line, ccCommand) == line || strstr(line, ecpCommand) == line || strstr(line, eccCommand) == line)
1161                {
1162                   char moduleName[MAX_FILENAME];
1163                   byte * tokens[1];
1164                   char * module;
1165                   bool isPrecomp = false;
1166                
1167                   if(strstr(line, ccCommand) == line)
1168                   {
1169                      module = strstr(line, " -c ");
1170                      if(module) module += 4;
1171                   }
1172                   else if(strstr(line, eccCommand) == line)
1173                   {
1174                      module = strstr(line, " -c ");
1175                      if(module) module += 4;
1176                      //module = line + 3;
1177                      // Don't show GCC warnings about generated C code because it does not compile clean yet...
1178                      compilingEC = 3;//2;
1179                   }
1180                   else if(strstr(line, ecpCommand) == line)
1181                   {
1182                      // module = line + 8;
1183                      module = strstr(line, " -c ");
1184                      if(module) module += 4;
1185                      isPrecomp = true;
1186                      compilingEC = 0;
1187                   }
1188
1189                   loggedALine = true;
1190
1191                   if(module)
1192                   {
1193                      if(!compiling && !isPrecomp)
1194                      {
1195                         ide.outputView.buildBox.Logf($"Compiling...\n");
1196                         compiling = true;
1197                      }
1198                      else if(!precompiling && isPrecomp)
1199                      {
1200                         ide.outputView.buildBox.Logf($"Generating symbols...\n");
1201                         precompiling = true;
1202                      }
1203                      // Changed escapeBackSlashes here to handle paths with spaces
1204                      Tokenize(module, 1, tokens, true); // false);
1205                      GetLastDirectory(module, moduleName);
1206                      ide.outputView.buildBox.Logf("%s\n", moduleName);
1207                   }
1208                   else if((module = strstr(line, " -o ")))
1209                   {
1210                      compiling = false;
1211                      precompiling = false;
1212                      linking = true;
1213                      ide.outputView.buildBox.Logf($"Linking...\n");
1214                   }
1215                   else
1216                   {
1217                      ide.outputView.buildBox.Logf("%s\n", line);
1218                      numErrors ++;
1219                   }
1220
1221                   if(compilingEC) compilingEC--;
1222                }
1223                else if(strstr(line, "ar rcs") == line)
1224                   ide.outputView.buildBox.Logf($"Building library...\n");
1225                else if(strstr(line, ecsCommand) == line)
1226                   ide.outputView.buildBox.Logf($"Writing symbol loader...\n");
1227                else
1228                {
1229                   if(linking || compiling || precompiling)
1230                   {
1231                      char * colon = strstr(line, ":"); //, * bracket;
1232                      if(colon && (colon[1] == '/' || colon[1] == '\\'))
1233                         colon = strstr(colon + 1, ":");
1234                      if(colon)
1235                      {
1236                         char moduleName[MAX_LOCATION], temp[MAX_LOCATION];
1237                         char * pointer;
1238                         int len = (int)(colon - line);
1239                         len = Min(len, MAX_LOCATION-1);
1240                         // Don't be mistaken by the drive letter colon
1241                         // Cut module name
1242                         // TODO: need to fix colon - line gives char * 
1243                         // warning: incompatible expression colon - line (char *); expected int
1244                         /*
1245                         strncpy(moduleName, line, (int)(colon - line));
1246                         moduleName[colon - line] = '\0';
1247                         */
1248                         strncpy(moduleName, line, len);
1249                         moduleName[len] = '\0';
1250                         // Remove stuff in brackets
1251                         //bracket = strstr(moduleName, "(");
1252                         //if(bracket) *bracket = '\0';
1253                      
1254                         GetLastDirectory(moduleName, temp);
1255                         if(linking && (!strcmp(temp, "ld") || !strcmp(temp, "ld.exe")))
1256                         {
1257                            numErrors++;
1258                            strcpy(moduleName, $"Linker Error");
1259                         }
1260                         else
1261                         {
1262                            strcpy(temp, topNode.path);
1263                            PathCatSlash(temp, moduleName);
1264                            MakePathRelative(temp, topNode.path, moduleName);
1265                         }
1266                         if(strstr(line, "error:"))
1267                            numErrors ++;
1268                         else
1269                         {
1270                            // Silence warnings for compiled EC
1271                            char * objDir = strstr(moduleName, objDirExp.dir);
1272                         
1273                            if(linking)
1274                            {
1275                               if((pointer = strstr(line, "undefined"))  ||
1276                                    (pointer = strstr(line, "No such file")) ||
1277                                    (pointer = strstr(line, "token")))
1278                               {
1279                                  strncat(moduleName, colon, pointer - colon);
1280                                  strcat(moduleName, "error: ");
1281                                  colon = pointer;
1282                                  numErrors ++;
1283                               }
1284                            }
1285                            else if((pointer = strstr(line, "No such file")))
1286                            {
1287                               strncat(moduleName, colon, pointer - colon);
1288                               strcat(moduleName, "error: ");
1289                               colon = pointer;
1290                               numErrors ++;
1291                            }
1292                            else if(compilingEC == 1 || (objDir && objDir == moduleName))
1293                               continue;
1294                            else if(strstr(line, "warning:"))
1295                            {
1296                               numWarnings++;
1297                            }
1298                         }
1299                         if(this == ide.workspace.projects.firstIterator.data)
1300                            ide.outputView.buildBox.Logf("   %s%s\n", moduleName, colon);
1301                         else
1302                         {
1303                            char fullModuleName[MAX_LOCATION];
1304                            strcpy(fullModuleName, topNode.path);
1305                            PathCat(fullModuleName, moduleName);
1306                            MakePathRelative(fullModuleName, ide.workspace.projects.firstIterator.data.topNode.path, fullModuleName);
1307                            MakeSystemPath(fullModuleName);
1308                            ide.outputView.buildBox.Logf("   %s%s\n", fullModuleName, colon);                              
1309                         }
1310                      }
1311                      else
1312                      {
1313                         ide.outputView.buildBox.Logf("%s\n", line);
1314                         linking = compiling = precompiling = false;
1315                      }
1316                   }
1317                   else
1318                      ide.outputView.buildBox.Logf("%s\n", line);
1319                }
1320                wait = false;
1321             }
1322             //printf("Done getting line\n");
1323             if(GetTime() - lastTime > 1.0 / PEEK_RESOLUTION) break;
1324          }
1325          //printf("Processing Input...\n");
1326          if(app.ProcessInput(true))
1327             wait = false;
1328          app.UpdateDisplay();
1329          if(wait)
1330          {
1331             //printf("Waiting...\n");
1332             app.Wait();
1333          }
1334          //if(!result) Sleep(1.0 / PEEK_RESOLUTION);
1335       }
1336       if(ide.ShouldStopBuild())
1337       {
1338          ide.outputView.buildBox.Logf($"\nBuild cancelled by user.\n", line);
1339          f.Terminate();
1340       }
1341       else if(loggedALine || !isARun)
1342       {
1343          if(f.GetExitCode() && !numErrors)
1344          {
1345             bool result = f.GetLine(line, sizeof(line)-1);
1346             ide.outputView.buildBox.Logf($"Fatal Error: child process terminated unexpectedly\n");
1347          }
1348          else
1349          {
1350             if(!onlyNode)
1351                ide.outputView.buildBox.Logf("\n%s (%s) - ", GetTargetFileName(config), configName);
1352             if(numErrors)
1353                ide.outputView.buildBox.Logf("%d %s, ", numErrors, (numErrors > 1) ? $"errors" : $"error");
1354             else
1355                ide.outputView.buildBox.Logf($"no error, ");
1356    
1357             if(numWarnings)
1358                ide.outputView.buildBox.Logf("%d %s\n", numWarnings, (numWarnings > 1) ? $"warnings" : $"warning");
1359             else
1360                ide.outputView.buildBox.Logf($"no warning\n");
1361          }
1362       }
1363       return numErrors == 0;
1364    }
1365
1366    void ProcessCleanPipeOutput(DualPipe f, CompilerConfig compiler, ProjectConfig config)
1367    {
1368       char line[65536];
1369       int lenMakeCommand = strlen(compiler.makeCommand);
1370       while(!f.Eof())
1371       {
1372          bool result = true;
1373          bool wait = true;
1374          double lastTime = GetTime();
1375          while(result)
1376          {
1377             if((result = f.Peek()) && (result = f.GetLine(line, sizeof(line)-1)))
1378             {
1379                if(strstr(line, compiler.makeCommand) == line && line[lenMakeCommand] == ':');
1380                else if(strstr(line, "del") == line);
1381                else if(strstr(line, "rm") == line);
1382                else if(strstr(line, "Could Not Find") == line);
1383                else
1384                {
1385                   ide.outputView.buildBox.Logf(line);
1386                   ide.outputView.buildBox.Logf("\n");
1387                }
1388                wait = false;
1389             }
1390             if(GetTime() - lastTime > 1.0 / PEEK_RESOLUTION) break;
1391          }
1392          if(app.ProcessInput(true))
1393             wait = false;
1394          app.UpdateDisplay();
1395          if(wait)
1396             app.Wait();
1397          //Sleep(1.0 / PEEK_RESOLUTION);
1398       }
1399    }
1400
1401    bool Build(bool isARun, ProjectNode onlyNode, CompilerConfig compiler, ProjectConfig config)
1402    {
1403       bool result = false;
1404       DualPipe f;
1405       char targetFileName[MAX_LOCATION] = "";
1406       char makeTarget[MAX_LOCATION] = "";
1407       char makeFile[MAX_LOCATION];
1408       char makeFilePath[MAX_LOCATION];
1409       char configName[MAX_LOCATION];
1410       DirExpression objDirExp = GetObjDir(compiler, config);
1411       PathBackup pathBackup { };
1412
1413       int numJobs = compiler.numJobs;
1414       char command[MAX_LOCATION];
1415
1416       strcpy(configName, config ? config.name : "Common");
1417       
1418       SetPath(false, compiler, config); //true
1419       CatTargetFileName(targetFileName, compiler, config);
1420
1421       strcpy(makeFilePath, topNode.path);
1422       CatMakeFileName(makeFile, compiler, config);
1423       PathCatSlash(makeFilePath, makeFile);
1424       
1425       // TODO: TEST ON UNIX IF \" around makeTarget is ok
1426       if(onlyNode)
1427       {
1428          if(compiler.type.isVC)
1429          {
1430             PrintLn("compiling a single file is not yet supported");
1431          }
1432          else
1433          {
1434             int len;
1435             char pushD[MAX_LOCATION];
1436             GetWorkingDir(pushD, sizeof(pushD));
1437             ChangeWorkingDir(topNode.path);
1438             // Create object dir if it does not exist already
1439             if(!FileExists(objDirExp.dir).isDirectory)
1440                Execute("%s objdir -C \"%s\" -f \"%s\"", compiler.makeCommand, topNode.path, makeFilePath);
1441             ChangeWorkingDir(pushD);
1442
1443             PathCatSlash(makeTarget+1, objDirExp.dir);
1444             PathCatSlash(makeTarget+1, onlyNode.name);
1445             StripExtension(makeTarget+1);
1446             strcat(makeTarget+1, ".o");
1447             makeTarget[0] = '\"';
1448             len = strlen(makeTarget);
1449             makeTarget[len++] = '\"';
1450             makeTarget[len++] = '\0';
1451          }
1452       }
1453
1454       if(compiler.type.isVC)
1455       {
1456          bool result = false;
1457          char oldwd[MAX_LOCATION];
1458          GetWorkingDir(oldwd, sizeof(oldwd));
1459          ChangeWorkingDir(topNode.path);
1460
1461          sprintf(command, "%s /useenv /nologo /logcommands %s.sln %s|Win32", compiler.makeCommand, name, config.name);
1462          ide.outputView.buildBox.Logf("command: %s\n", command);
1463          if((f = DualPipeOpen(PipeOpenMode { output = true, error = true, input = true }, command)))
1464          {
1465             ProcessPipeOutputRaw(f);
1466             delete f;
1467             result = true;
1468          }
1469          ChangeWorkingDir(oldwd);
1470       }
1471       else
1472       {
1473          sprintf(command, "%s -j%d %s%s%s -C \"%s\" -f \"%s\"", compiler.makeCommand, numJobs,
1474                compiler.ccacheEnabled ? "CCACHE=y " : "",
1475                compiler.distccEnabled ? "DISTCC=y " : "",
1476                makeTarget, topNode.path, makeFilePath);
1477          if((f = DualPipeOpen(PipeOpenMode { output = true, error = true, input = true }, command)))
1478          {
1479             result = ProcessBuildPipeOutput(f, objDirExp, isARun, onlyNode, compiler, config);
1480             delete f;
1481          }
1482          else
1483             ide.outputView.buildBox.Logf($"Error executing make (%s) command\n", compiler.makeCommand);
1484       }
1485
1486       delete pathBackup;
1487
1488       delete objDirExp;
1489       return result;
1490    }
1491
1492    void Clean(CompilerConfig compiler, ProjectConfig config)
1493    {
1494       char makeFile[MAX_LOCATION];
1495       char makeFilePath[MAX_LOCATION];
1496       char command[MAX_LOCATION];
1497       DualPipe f;
1498       PathBackup pathBackup { };
1499
1500       SetPath(false, compiler, config);
1501
1502       strcpy(makeFilePath, topNode.path);
1503       CatMakeFileName(makeFile, compiler, config);
1504       PathCatSlash(makeFilePath, makeFile);
1505       
1506       if(compiler.type.isVC)
1507       {
1508          bool result = false;
1509          char oldwd[MAX_LOCATION];
1510          GetWorkingDir(oldwd, sizeof(oldwd));
1511          ChangeWorkingDir(topNode.path);
1512          
1513          sprintf(command, "%s /useenv /clean /nologo /logcommands %s.sln %s|Win32", compiler.makeCommand, name, config.name);
1514          ide.outputView.buildBox.Logf("command: %s\n", command);
1515          if((f = DualPipeOpen(PipeOpenMode { output = true, error = true, input = true }, command)))
1516          {
1517             ProcessPipeOutputRaw(f);
1518             delete f;
1519             result = true;
1520          }
1521          ChangeWorkingDir(oldwd);
1522          return result;
1523       }
1524       else
1525       {
1526          sprintf(command, "%s clean -C \"%s\" -f \"%s\"", compiler.makeCommand, topNode.path, makeFilePath);
1527          if((f = DualPipeOpen(PipeOpenMode { output = 1, error = 1, input = 2 }, command)))
1528          {
1529             ide.outputView.buildBox.Tell($"Deleting target and object files...");
1530             ProcessCleanPipeOutput(f, compiler, config);
1531             delete f;
1532
1533             ide.outputView.buildBox.Logf($"Target and object files deleted\n");
1534          }
1535       }
1536
1537       delete pathBackup;
1538    }
1539
1540    void Run(char * args, CompilerConfig compiler, ProjectConfig config)
1541    {   
1542       String target = new char[maxPathLen];
1543       char oldDirectory[MAX_LOCATION];
1544       DirExpression targetDirExp = GetTargetDir(compiler, config);
1545       PathBackup pathBackup { };
1546
1547       // Build(project, ideMain, true, null);
1548
1549    #if defined(__WIN32__)
1550       strcpy(target, topNode.path);
1551    #else
1552       strcpy(target, "");
1553    #endif
1554       PathCatSlash(target, targetDirExp.dir);
1555       CatTargetFileName(target, compiler, config);
1556       sprintf(target, "%s %s", target, args);
1557       GetWorkingDir(oldDirectory, MAX_LOCATION);
1558
1559       if(strlen(ide.workspace.debugDir))
1560       {
1561          char temp[MAX_LOCATION];
1562          strcpy(temp, topNode.path);
1563          PathCatSlash(temp, ide.workspace.debugDir);
1564          ChangeWorkingDir(temp);
1565       }
1566       else
1567          ChangeWorkingDir(topNode.path);
1568       // ChangeWorkingDir(topNode.path);
1569       SetPath(true, compiler, config);
1570       if(compiler.execPrefixCommand)
1571       {
1572          char * prefixedTarget = new char[strlen(compiler.execPrefixCommand) + strlen(target) + 2];
1573          prefixedTarget[0] = '\0';
1574          strcat(prefixedTarget, compiler.execPrefixCommand);
1575          strcat(prefixedTarget, " ");
1576          strcat(prefixedTarget, target);
1577          Execute(prefixedTarget);
1578          delete prefixedTarget;
1579       }
1580       else
1581          Execute(target);
1582
1583       ChangeWorkingDir(oldDirectory);
1584       delete pathBackup;
1585
1586       delete targetDirExp;
1587       delete target;
1588    }
1589
1590    void Compile(ProjectNode node, CompilerConfig compiler, ProjectConfig config)
1591    {
1592       Build(false, node, compiler, config);
1593    }
1594 #endif
1595
1596    void GetMakefileTargetFileName(TargetTypes targetType, char * fileName, ProjectConfig config)
1597    {
1598       fileName[0] = '\0';
1599       if(targetType == staticLibrary || targetType == sharedLibrary)
1600          strcat(fileName, "$(LP)");
1601       // !!! ReplaceSpaces must be done after all PathCat calls !!!
1602       // ReplaceSpaces(s, GetTargetFileName(config));
1603       strcat(fileName, GetTargetFileName(config));
1604       switch(targetType)
1605       {
1606          case executable:
1607             strcat(fileName, "$(E)");
1608             break;
1609          case sharedLibrary:
1610             strcat(fileName, "$(SO)");
1611             break;
1612          case staticLibrary:
1613             strcat(fileName, "$(A)");
1614             break;
1615       }
1616    }
1617
1618    bool GenerateMakefile(char * altMakefilePath, bool noResources, char * includemkPath,
1619       CompilerConfig compiler, ProjectConfig config)
1620    {
1621       bool result = false;
1622       char filePath[MAX_LOCATION];
1623       char makeFile[MAX_LOCATION];
1624       // PathBackup pathBackup { };
1625       // char oldDirectory[MAX_LOCATION];
1626       File f = null;
1627
1628       if(!altMakefilePath)
1629       {
1630          strcpy(filePath, topNode.path);
1631          CatMakeFileName(makeFile, compiler, config);
1632          PathCatSlash(filePath, makeFile);
1633       }
1634
1635 #if defined(__WIN32__) && !defined(MAKEFILE_GENERATOR)
1636       if(compiler.type.isVC)
1637       {
1638          GenerateVSSolutionFile(this, compiler);
1639          GenerateVCProjectFile(this, compiler);
1640       }
1641       else
1642 #endif
1643       f = FileOpen(altMakefilePath ? altMakefilePath : filePath, write);
1644
1645       /*SetPath(false, compiler, config);
1646       GetWorkingDir(oldDirectory, MAX_LOCATION);
1647       ChangeWorkingDir(topNode.path);*/
1648
1649       if(f)
1650       {
1651          char temp[MAX_LOCATION];
1652          char target[MAX_LOCATION];
1653          char targetNoSpaces[MAX_LOCATION];
1654          char objDirExpNoSpaces[MAX_LOCATION];
1655          char objDirNoSpaces[MAX_LOCATION];
1656          char resDirNoSpaces[MAX_LOCATION];
1657          char targetDirExpNoSpaces[MAX_LOCATION];
1658          char fixedModuleName[MAX_FILENAME];
1659          char fixedConfigName[MAX_FILENAME];
1660          char fixedCompilerName[MAX_FILENAME];
1661          int c, len;
1662          int numCObjects = 0;
1663          bool sameObjTargetDirs;
1664          DirExpression objDirExp = GetObjDir(compiler, config);
1665          TargetTypes targetType = GetTargetType(config);
1666
1667          bool crossCompiling = compiler.targetPlatform != GetRuntimePlatform();
1668          bool gccCompiler = compiler.ccCommand && strstr(compiler.ccCommand, "gcc") != null;
1669          bool tccCompiler = compiler.ccCommand && strstr(compiler.ccCommand, "tcc") != null;
1670          bool defaultPreprocessor = compiler.cppCommand && (strstr(compiler.cppCommand, "gcc") != null || compiler.cppCommand && strstr(compiler.cppCommand, "cpp") != null);
1671
1672          int objectsParts, cobjectsParts, symbolsParts, importsParts;
1673          Array<String> listItems { };
1674          Map<String, int> varStringLenDiffs { };
1675          Map<String, NameCollisionInfo> namesInfo { };
1676
1677          ReplaceSpaces(objDirNoSpaces, objDirExp.dir);
1678          strcpy(temp, GetTargetDirExpression(compiler, config));
1679          ReplaceSpaces(targetDirExpNoSpaces, temp);
1680          GetMakefileTargetFileName(targetType, target, config);
1681          PathCatSlash(temp, target);
1682          ReplaceSpaces(targetNoSpaces, temp);
1683
1684          strcpy(objDirExpNoSpaces, GetObjDirExpression(compiler, config));
1685          ChangeCh(objDirExpNoSpaces, '\\', '/'); // TODO: this is a hack, paths should never include win32 path seperators - fix this in ProjectSettings and ProjectLoad instead
1686          ReplaceSpaces(objDirExpNoSpaces, objDirExpNoSpaces);
1687          ReplaceSpaces(resDirNoSpaces, resNode.path ? resNode.path : "");
1688          //ReplaceSpaces(fixedPrjName, name);
1689          ReplaceSpaces(fixedModuleName, moduleName);
1690          ReplaceSpaces(fixedConfigName, GetConfigName(config));
1691          ReplaceSpaces(fixedCompilerName, compiler.name);
1692          //CamelCase(fixedModuleName); // case is important for static linking
1693          CamelCase(fixedConfigName);
1694          CamelCase(fixedCompilerName);
1695
1696          sameObjTargetDirs = !fstrcmp(objDirExpNoSpaces, targetDirExpNoSpaces);
1697
1698          f.Printf(".PHONY: all objdir%s clean distclean\n\n", sameObjTargetDirs ? "" : " targetdir");
1699
1700          f.Printf("# CONTENT\n\n");
1701
1702          f.Printf("MODULE := %s\n", fixedModuleName);
1703          //f.Printf("VERSION = %s\n", version);
1704          f.Printf("CONFIG := %s\n", fixedConfigName);
1705          f.Printf("COMPILER := %s\n", fixedCompilerName);
1706          if(crossCompiling)
1707             f.Printf("PLATFORM = %s\n", (char *)compiler.targetPlatform);
1708          f.Printf("TARGET_TYPE = %s\n", targetType == executable ? "executable" :
1709                (targetType == sharedLibrary ? "sharedlib" : (targetType == staticLibrary ? "staticlib" : "unknown")));
1710          f.Printf("\n");
1711
1712          f.Printf("OBJ = %s%s\n\n", objDirExpNoSpaces, objDirExpNoSpaces[0] ? "/" : "");
1713
1714          f.Printf("RES = %s%s\n\n", resDirNoSpaces, resDirNoSpaces[0] ? "/" : "");
1715
1716          if(targetType == executable)
1717             f.Printf("CONSOLE = %s\n\n", GetConsole(config) ? "-mconsole" : "-mwindows");
1718
1719          f.Printf("TARGET = %s\n\n", targetNoSpaces);
1720
1721          varStringLenDiffs["$(OBJ)"] = strlen(objDirNoSpaces) - 6;
1722
1723          topNode.GenMakefileGetNameCollisionInfo(namesInfo, config);
1724
1725          numCObjects = topNode.GenMakefilePrintNode(f, this, objects, namesInfo, listItems, config);
1726          if(numCObjects)
1727             listItems.Add(CopyString("$(OBJ)$(MODULE).main$(O)"));
1728          objectsParts = OutputFileList(f, "OBJECTS", listItems, varStringLenDiffs);
1729
1730          topNode.GenMakefilePrintNode(f, this, cObjects, namesInfo, listItems, config);
1731          cobjectsParts = OutputFileList(f, "COBJECTS", listItems, varStringLenDiffs);
1732
1733          topNode.GenMakefilePrintNode(f, this, symbols, null, listItems, config);
1734          symbolsParts = OutputFileList(f, "SYMBOLS", listItems, varStringLenDiffs);
1735
1736          topNode.GenMakefilePrintNode(f, this, imports, null, listItems, config);
1737          importsParts = OutputFileList(f, "IMPORTS", listItems, varStringLenDiffs);
1738
1739          topNode.GenMakefilePrintNode(f, this, sources, null, listItems, config);
1740          OutputFileList(f, "SOURCES", listItems, varStringLenDiffs);
1741
1742          if(!noResources)
1743             resNode.GenMakefilePrintNode(f, this, resources, null, listItems, config);
1744          OutputFileList(f, "RESOURCES", listItems, varStringLenDiffs);
1745
1746          if(includemkPath)
1747          {
1748             f.Printf("# CROSS-PLATFORM MAGIC\n\n");
1749
1750             f.Printf("include %s\n\n", includemkPath);
1751          }
1752          else
1753          {
1754             File include = FileOpen(":include.mk", read);
1755             if(include)
1756             {
1757                for(; !include.Eof(); )
1758                {
1759                   char buffer[4096];
1760                   int count = include.Read(buffer, 1, 4096);
1761                   f.Write(buffer, 1, count);
1762                }
1763                delete include;
1764             }
1765          }
1766
1767          f.Printf("\n");
1768
1769          if(strcmpi(compiler.cppCommand, "cpp") ||
1770                strcmpi(compiler.ccCommand,  "gcc") ||
1771                strcmpi(compiler.ecpCommand, "ecp") ||
1772                strcmpi(compiler.eccCommand, "ecc") ||
1773                strcmpi(compiler.ecsCommand, "ecs") || crossCompiling ||
1774                strcmpi(compiler.earCommand, "ear"))
1775          {
1776             f.Printf("# TOOLCHAIN\n\n");
1777
1778             //f.Printf("SHELL := %s\n", "ar"/*compiler.arCommand*/); // is this really needed?
1779             if(strcmpi(compiler.cppCommand, "cpp"))
1780                f.Printf("CPP := $(CCACHE_COMPILE) $(DISTCC_COMPILE) %s\n", compiler.cppCommand);
1781             if(strcmpi(compiler.ccCommand,  "gcc"))
1782                f.Printf("CC := $(CCACHE_COMPILE) $(DISTCC_COMPILE) %s\n", compiler.ccCommand);
1783             if(strcmpi(compiler.ecpCommand, "ecp"))
1784                f.Printf("ECP := %s\n", compiler.ecpCommand);
1785             if(strcmpi(compiler.eccCommand, "ecc"))
1786                f.Printf("ECC := %s\n", compiler.eccCommand);
1787             if(strcmpi(compiler.ecsCommand, "ecs") || crossCompiling)
1788             {
1789                f.Printf("ECS := %s%s%s\n", compiler.ecsCommand,
1790                      crossCompiling ? " -t " : "", crossCompiling ? (char*)compiler.targetPlatform : "");
1791             }
1792             if(strcmpi(compiler.earCommand, "ear"))
1793                f.Printf("EAR := %s\n", compiler.earCommand);
1794             f.Printf("\n");
1795          }
1796
1797          f.Printf("# FLAGS\n\n");
1798
1799          f.Printf("CFLAGS =");
1800          if(gccCompiler)
1801          {
1802             f.Printf(" -fmessage-length=0");
1803             switch(GetOptimization(config))
1804             {
1805                case speed:
1806                   f.Printf(" -O2");
1807                   f.Printf(" -ffast-math");
1808                   break;
1809                case size:
1810                   f.Printf(" -Os");
1811                   break;
1812             }
1813             //if(compiler.targetPlatform.is32Bits)
1814                f.Printf(" -m32");
1815             //else if(compiler.targetPlatform.is64Bits)
1816             //   f.Printf(" -m64");
1817             f.Printf(" $(FPIC)");
1818             //f.Printf(" -fpack-struct");
1819          }
1820          switch(GetWarnings(config))
1821          {
1822             case all: f.Printf(" -Wall"); break;
1823             case none: f.Printf(" -w"); break;
1824          }
1825          if(GetDebug(config))
1826             f.Printf(" -g");
1827          if(GetProfile(config))
1828             f.Printf(" -pg");
1829          if(options && options.linkerOptions && options.linkerOptions.count)
1830          {
1831             f.Printf(" \\\n\t -Wl");
1832             for(s : options.linkerOptions)
1833                f.Printf(",%s", s);
1834          }
1835
1836          if(options && options.preprocessorDefinitions)
1837             OutputListOption(f, "D", options.preprocessorDefinitions, newLine, false);
1838          if(config && config.options && config.options.preprocessorDefinitions)
1839             OutputListOption(f, "D", config.options.preprocessorDefinitions, newLine, false);
1840          // no if?
1841          OutputListOption(f, gccCompiler ? "isystem " : "I", compiler.includeDirs, lineEach, true);
1842          if(options && options.includeDirs)
1843             OutputListOption(f, "I", options.includeDirs, lineEach, true);
1844          if(config && config.options && config.options.includeDirs)
1845             OutputListOption(f, "I", config.options.includeDirs, lineEach, true);
1846          f.Printf("\n\n");
1847
1848          f.Printf("CECFLAGS =%s%s%s%s", defaultPreprocessor ? "" : " -cpp ", defaultPreprocessor ? "" : compiler.cppCommand, 
1849                crossCompiling ? " -t " : "", crossCompiling ? (char*)compiler.targetPlatform : "");
1850          f.Printf("\n\n");
1851
1852          f.Printf("ECFLAGS =");
1853          if(GetMemoryGuard(config))
1854             f.Printf(" -memguard");
1855          if(GetStrictNameSpaces(config))
1856             f.Printf(" -strictns");
1857          if(GetNoLineNumbers(config))
1858             f.Printf(" -nolinenumbers");
1859          {
1860             char * s;
1861             if((s = GetDefaultNameSpace(config)) && s[0])
1862                f.Printf(" -defaultns %s", s);
1863          }
1864          f.Printf("\n\n");
1865
1866          if(targetType != staticLibrary)
1867          {
1868             f.Printf("OFLAGS = -m32"); // TARGET_TYPE is fixed in a Makefile, we don't want this. $(if TARGET_TYPE_STATIC_LIBRARY,,-m32)");
1869             if(GetProfile(config))
1870                f.Printf(" -pg");
1871             // no if? 
1872             OutputListOption(f, "L", compiler.libraryDirs, lineEach, true);
1873             if(options && options.libraryDirs)
1874                OutputListOption(f, "L", options.libraryDirs, lineEach, true);
1875             if(config && config.options && config.options.libraryDirs)
1876                OutputListOption(f, "L", config.options.libraryDirs, lineEach, true);
1877             f.Printf("\n\n");
1878          }
1879
1880          f.Printf("LIBS =");
1881          if(targetType != staticLibrary)
1882          {
1883             if(config && config.options && config.options.libraries)
1884                OutputLibraries(f, config.options.libraries);
1885             else if(options && options.libraries)
1886                OutputLibraries(f, options.libraries);
1887          }
1888          f.Printf(" $(SHAREDLIB) $(EXECUTABLE) $(LINKOPT)\n\n");
1889
1890          f.Printf("UPXFLAGS = -9\n\n"); // TOFEAT: Compression Level Option? Other UPX Options?
1891
1892          f.Printf("# HARD CODED PLATFORM-SPECIFIC OPTIONS\n");
1893          f.Printf("ifdef %s\n", PlatformToMakefileVariable(tux));
1894          f.Printf("OFLAGS += -Wl,--no-undefined\n");
1895          f.Printf("endif\n\n");
1896
1897          // JF's
1898          f.Printf("ifdef %s\n", PlatformToMakefileVariable(apple));
1899          f.Printf("OFLAGS += -framework cocoa -framework OpenGL\n");
1900          f.Printf("endif\n\n");
1901
1902          if(platforms || (config && config.platforms))
1903          {
1904             int ifCount = 0;
1905             Platform platform;
1906             //for(platform = firstPlatform; platform <= lastPlatform; platform++)
1907             //for(platform = win32; platform <= apple; platform++)
1908             
1909             f.Printf("# PLATFORM-SPECIFIC OPTIONS\n\n");
1910             for(platform = (Platform)1; platform < Platform::enumSize; platform++)
1911             {
1912                PlatformOptions projectPlatformOptions = null;
1913                PlatformOptions configPlatformOptions = null;
1914
1915                if(platforms)
1916                {
1917                   for(p : platforms)
1918                   {
1919                      if(!strcmpi(p.name, platform))
1920                      {
1921                         projectPlatformOptions = p;
1922                         break;
1923                      }
1924                   }
1925                }
1926                if(config && config.platforms)
1927                {
1928                   for(p : config.platforms)
1929                   {
1930                      if(!strcmpi(p.name, platform))
1931                      {
1932                         configPlatformOptions = p;
1933                         break;
1934                      }
1935                   }
1936                }
1937                if(projectPlatformOptions || configPlatformOptions)
1938                {
1939                   if(ifCount)
1940                      f.Printf("else\n");
1941                   ifCount++;
1942                   f.Printf("ifdef ");
1943                   // we should have some kind of direct mapping between a platform and it's makefile variable
1944                   f.Printf(PlatformToMakefileVariable(platform));
1945                   f.Printf("\n\n");
1946
1947                   if((projectPlatformOptions && projectPlatformOptions.options.preprocessorDefinitions && projectPlatformOptions.options.preprocessorDefinitions.count) ||
1948                      (configPlatformOptions && configPlatformOptions.options.preprocessorDefinitions && configPlatformOptions.options.preprocessorDefinitions.count) ||
1949                      (projectPlatformOptions && projectPlatformOptions.options.includeDirs && projectPlatformOptions.options.includeDirs.count) ||
1950                      (configPlatformOptions && configPlatformOptions.options.includeDirs && configPlatformOptions.options.includeDirs.count))
1951                   {
1952                      f.Printf("CFLAGS +=");
1953                      if(projectPlatformOptions && projectPlatformOptions.options.linkerOptions && projectPlatformOptions.options.linkerOptions.count)
1954                      {
1955                         f.Printf(" \\\n\t -Wl");
1956                         for(s : projectPlatformOptions.options.linkerOptions)
1957                            f.Printf(",%s", s);
1958                      }
1959                      if(configPlatformOptions && configPlatformOptions.options.linkerOptions && configPlatformOptions.options.linkerOptions.count)
1960                      {
1961                         f.Printf(" \\\n\t -Wl");
1962                         for(s : configPlatformOptions.options.linkerOptions)
1963                            f.Printf(",%s", s);
1964                      }
1965                      if(projectPlatformOptions && projectPlatformOptions.options.preprocessorDefinitions)
1966                         OutputListOption(f, "D", projectPlatformOptions.options.preprocessorDefinitions, newLine, false);
1967                      if(configPlatformOptions && configPlatformOptions.options.preprocessorDefinitions)
1968                         OutputListOption(f, "D", configPlatformOptions.options.preprocessorDefinitions, newLine, false );
1969                      if(projectPlatformOptions && projectPlatformOptions.options.includeDirs)
1970                         OutputListOption(f, "I", projectPlatformOptions.options.includeDirs, lineEach, true);
1971                      if(configPlatformOptions && configPlatformOptions.options.includeDirs)
1972                         OutputListOption(f, "I", configPlatformOptions.options.includeDirs, lineEach, true);
1973                      f.Printf("\n\n");
1974                   }
1975
1976                   if(targetType != staticLibrary)
1977                   {
1978                      if((projectPlatformOptions && projectPlatformOptions.options.libraryDirs && projectPlatformOptions.options.libraryDirs.count) ||
1979                         (configPlatformOptions && configPlatformOptions.options.libraryDirs && configPlatformOptions.options.libraryDirs.count))
1980                      {
1981                         f.Printf("OFLAGS +=");
1982                         if(projectPlatformOptions && projectPlatformOptions.options.libraryDirs)
1983                            OutputListOption(f, "L", projectPlatformOptions.options.libraryDirs, lineEach, true);
1984                         if(configPlatformOptions && configPlatformOptions.options.libraryDirs)
1985                            OutputListOption(f, "L", configPlatformOptions.options.libraryDirs, lineEach, true);
1986                         f.Printf("\n\n");
1987                      }
1988
1989                      if(projectPlatformOptions && projectPlatformOptions.options.libraries &&
1990                            projectPlatformOptions.options.libraries.count/* && 
1991                            (!config || !config.options || !config.options.libraries)*/)
1992                      {
1993                         f.Printf("LIBS +=");
1994                         OutputLibraries(f, projectPlatformOptions.options.libraries);
1995                         f.Printf("\n\n");
1996                      }
1997                      {/*TOFIX: EXTRA CURLIES FOR NASTY WARNING*/if((configPlatformOptions && configPlatformOptions.options.libraries && configPlatformOptions.options.libraries.count))
1998                      {
1999                         f.Printf("LIBS +=");
2000                         OutputLibraries(f, configPlatformOptions.options.libraries);
2001                         f.Printf("\n\n");
2002                      }}
2003                   }
2004                }
2005             }
2006             if(ifCount)
2007             {
2008                for(c = 0; c < ifCount; c++)
2009                   f.Printf("endif\n");
2010                ifCount = 0;
2011             }
2012             f.Printf("\n");
2013          }
2014
2015          f.Printf("# TARGETS\n\n");
2016
2017          f.Printf("all: objdir%s $(TARGET)\n\n", sameObjTargetDirs ? "" : " targetdir");
2018
2019          f.Printf("objdir:\n");
2020             f.Printf("\t$(if $(wildcard $(OBJ)),,$(call mkdirq,$(OBJ)))\n");
2021          //f.Printf("# PRE-BUILD COMMANDS\n");
2022          if(options && options.prebuildCommands)
2023          {
2024             for(s : options.prebuildCommands)
2025                if(s && s[0]) f.Printf("\t%s\n", s);
2026          }
2027          if(config && config.options && config.options.prebuildCommands)
2028          {
2029             for(s : config.options.prebuildCommands)
2030                if(s && s[0]) f.Printf("\t%s\n", s);
2031          }
2032          if(platforms || (config && config.platforms))
2033          {
2034             int ifCount = 0;
2035             Platform platform;
2036             //f.Printf("# PLATFORM-SPECIFIC PRE-BUILD COMMANDS\n");
2037             for(platform = (Platform)1; platform < Platform::enumSize; platform++)
2038             {
2039                PlatformOptions projectPOs = null;
2040                PlatformOptions configPOs = null;
2041
2042                if(platforms)
2043                {
2044                   for(p : platforms)
2045                   {
2046                      if(!strcmpi(p.name, platform))
2047                      {
2048                         projectPOs = p;
2049                         break;
2050                      }
2051                   }
2052                }
2053                if(config && config.platforms)
2054                {
2055                   for(p : config.platforms)
2056                   {
2057                      if(!strcmpi(p.name, platform))
2058                      {
2059                         configPOs = p;
2060                         break;
2061                      }
2062                   }
2063                }
2064                if((projectPOs && projectPOs.options.prebuildCommands && projectPOs.options.prebuildCommands.count) ||
2065                      (configPOs && configPOs.options.prebuildCommands && configPOs.options.prebuildCommands.count))
2066                {
2067                   if(ifCount)
2068                      f.Printf("else\n");
2069                   ifCount++;
2070                   f.Printf("ifdef ");
2071                   f.Printf(PlatformToMakefileVariable(platform));
2072                   f.Printf("\n");
2073
2074                   if(projectPOs && projectPOs.options.prebuildCommands && projectPOs.options.prebuildCommands.count)
2075                   {
2076                      for(s : projectPOs.options.prebuildCommands)
2077                         if(s && s[0]) f.Printf("\t%s\n", s);
2078                   }
2079                   if(configPOs && configPOs.options.prebuildCommands && configPOs.options.prebuildCommands.count)
2080                   {
2081                      for(s : configPOs.options.prebuildCommands)
2082                         if(s && s[0]) f.Printf("\t%s\n", s);
2083                   }
2084                }
2085             }
2086             if(ifCount)
2087             {
2088                int c;
2089                for(c = 0; c < ifCount; c++)
2090                   f.Printf("endif\n");
2091                ifCount = 0;
2092             }
2093          }
2094          f.Printf("\n");
2095
2096          if(!sameObjTargetDirs)
2097          {
2098             f.Printf("targetdir:\n");
2099                f.Printf("\t$(if $(wildcard %s),,$(call mkdirq,%s))\n\n", targetDirExpNoSpaces, targetDirExpNoSpaces);
2100          }
2101
2102          if(numCObjects)
2103          {
2104             // Main Module (Linking) for ECERE C modules
2105             f.Printf("$(OBJ)$(MODULE).main.ec: $(SYMBOLS) $(COBJECTS)\n");
2106             // use of objDirExpNoSpaces used instead of $(OBJ) to prevent problematic joining of arguments in ecs
2107             f.Printf("\t$(ECS)%s $(ECSLIBOPT) $(SYMBOLS) $(IMPORTS) -symbols %s -o $(OBJ)$(MODULE).main.ec\n\n", 
2108                GetConsole(config) ? " -console" : "", objDirExpNoSpaces);
2109             // Main Module (Linking) for ECERE C modules
2110             f.Printf("$(OBJ)$(MODULE).main.c: $(OBJ)$(MODULE).main.ec\n");
2111             f.Printf("\t$(ECP) $(CECFLAGS) $(ECFLAGS) $(CFLAGS)"
2112                   " -c $(OBJ)$(MODULE).main.ec -o $(OBJ)$(MODULE).main.sym -symbols $(OBJ)\n");
2113             f.Printf("\t$(ECC) $(CECFLAGS) $(ECFLAGS) $(CFLAGS) $(FVISIBILITY)"
2114                   " -c $(OBJ)$(MODULE).main.ec -o $(OBJ)$(MODULE).main.c -symbols $(OBJ)\n\n");
2115          }
2116
2117          // *** Target ***
2118
2119          // This would not rebuild the target on updated objects
2120          // f.Printf("$(TARGET): $(SOURCES) $(RESOURCES) | objdir $(SYMBOLS) $(OBJECTS)%s\n", sameObjTargetDirs ? "" : " targetdir");
2121
2122          // This should fix it for good!
2123          f.Printf("$(SYMBOLS): | objdir\n");
2124          f.Printf("$(OBJECTS): | objdir\n");
2125
2126          // This alone was breaking the tarball, object directory does not get created first (order-only rules happen last it seems!)
2127          f.Printf("$(TARGET): $(SOURCES) $(RESOURCES) $(SYMBOLS) $(OBJECTS) | objdir%s\n", sameObjTargetDirs ? "" : " targetdir");
2128
2129          if(targetType == sharedLibrary || targetType == executable)
2130          {
2131             // f.Printf("\tinstall_name_tool $(TARGET) $(LP)$(MODULE)%s\n", targetType == sharedLibrary ? "$(SO)" : "$(A)");
2132             //f.Printf("ifdef OSX\n");
2133             //f.Printf("ifeq \"$(TARGET_TYPE)\" \"sharedlib\"\n");
2134             //f.Printf("\t$(CC) $(OFLAGS) $(OBJECTS) $(LIBS) -o $(TARGET) -install_name $(LP)$(MODULE)$(SO)\n");
2135             //f.Printf("endif\n");
2136             //f.Printf("else\n");
2137             //f.Printf("\t$(CC) $(OFLAGS) $(OBJECTS) $(LIBS) -o $(TARGET)\n");
2138             //f.Printf("endif\n");
2139             f.Printf("\t$(CC) $(OFLAGS) $(OBJECTS) $(LIBS) -o $(TARGET) $(INSTALLNAME)\n");
2140
2141             if(!GetDebug(config))
2142             {
2143                f.Printf("ifndef NOSTRIP\n");
2144                f.Printf("\t$(STRIP) $(STRIPOPT) $(TARGET)\n");
2145                f.Printf("endif\n");
2146
2147                if(GetCompress(config))
2148                {
2149                   f.Printf("ifndef WINDOWS\n");
2150                   f.Printf("ifeq \"$(TARGET_TYPE)\" \"executable\"\n");
2151                      f.Printf("\t$(UPX) $(UPXFLAGS) $(TARGET)\n");
2152                   f.Printf("endif\n");
2153                   f.Printf("else\n");
2154                      f.Printf("\t$(UPX) $(UPXFLAGS) $(TARGET)\n");
2155                   f.Printf("endif\n");
2156                }
2157             }
2158             if(resNode.files && resNode.files.count && !noResources)
2159                resNode.GenMakefileAddResources(f, resNode.path, config);
2160          }
2161          else
2162             f.Printf("\t$(AR) rcs $(TARGET) $(OBJECTS) $(LIBS)\n");
2163
2164          //f.Printf("# POST-BUILD COMMANDS\n");
2165          if(options && options.postbuildCommands)
2166          {
2167             for(s : options.postbuildCommands)
2168                if(s && s[0]) f.Printf("\t%s\n", s);
2169          }
2170          if(config && config.options && config.options.postbuildCommands)
2171          {
2172             for(s : config.options.postbuildCommands)
2173                if(s && s[0]) f.Printf("\t%s\n", s);
2174          }
2175          if(platforms || (config && config.platforms))
2176          {
2177             int ifCount = 0;
2178             Platform platform;
2179
2180             //f.Printf("# PLATFORM-SPECIFIC POST-BUILD COMMANDS\n");
2181             for(platform = (Platform)1; platform < Platform::enumSize; platform++)
2182             {
2183                PlatformOptions projectPOs = null;
2184                PlatformOptions configPOs = null;
2185
2186                if(platforms)
2187                {
2188                   for(p : platforms)
2189                   {
2190                      if(!strcmpi(p.name, platform))
2191                      {
2192                         projectPOs = p;
2193                         break;
2194                      }
2195                   }
2196                }
2197                if(config && config.platforms)
2198                {
2199                   for(p : config.platforms)
2200                   {
2201                      if(!strcmpi(p.name, platform))
2202                      {
2203                         configPOs = p;
2204                         break;
2205                      }
2206                   }
2207                }
2208                if((projectPOs && projectPOs.options.postbuildCommands && projectPOs.options.postbuildCommands.count) ||
2209                      (configPOs && configPOs.options.postbuildCommands && configPOs.options.postbuildCommands.count))
2210                {
2211                   if(ifCount)
2212                      f.Printf("else\n");
2213                   ifCount++;
2214                   f.Printf("ifdef ");
2215                   f.Printf(PlatformToMakefileVariable(platform));
2216                   f.Printf("\n");
2217
2218                   if(projectPOs && projectPOs.options.postbuildCommands && projectPOs.options.postbuildCommands.count)
2219                   {
2220                      for(s : projectPOs.options.postbuildCommands)
2221                         if(s && s[0]) f.Printf("\t%s\n", s);
2222                   }
2223                   if(configPOs && configPOs.options.postbuildCommands && configPOs.options.postbuildCommands.count)
2224                   {
2225                      for(s : configPOs.options.postbuildCommands)
2226                         if(s && s[0]) f.Printf("\t%s\n", s);
2227                   }
2228                }
2229             }
2230             if(ifCount)
2231             {
2232                int c;
2233                for(c = 0; c < ifCount; c++)
2234                   f.Printf("endif\n");
2235                ifCount = 0;
2236             }
2237          }
2238          f.Printf("\n");
2239
2240          f.Printf("# SYMBOL RULES\n\n");
2241          topNode.GenMakefilePrintSymbolRules(f, this, compiler, config);
2242
2243          f.Printf("# C OBJECT RULES\n\n");
2244          topNode.GenMakefilePrintCObjectRules(f, this, compiler, config);
2245
2246          /*if(numCObjects)
2247          {
2248             f.Printf("# IMPLICIT OBJECT RULE\n\n");
2249
2250             f.Printf("$(OBJ)%%$(O) : $(OBJ)%%.c\n");
2251             f.Printf("\t$(CC) $(CFLAGS) $(FVISIBILITY) -c $< -o $@\n\n");
2252          }*/
2253
2254          f.Printf("# OBJECT RULES\n\n");
2255          // todo call this still but only generate rules whith specific options
2256          // see we-have-file-specific-options in ProjectNode.ec
2257          topNode.GenMakefilePrintObjectRules(f, this, namesInfo, compiler, config);
2258
2259          if(numCObjects)
2260             GenMakefilePrintMainObjectRule(f, compiler, config);
2261
2262          f.Printf("clean: objdir%s\n", sameObjTargetDirs ? "" : " targetdir");
2263          f.Printf("\t$(call rmq,%s$(TARGET))\n", numCObjects ? "$(OBJ)$(MODULE).main.c $(OBJ)$(MODULE).main.ec $(OBJ)$(MODULE).main$(I) $(OBJ)$(MODULE).main$(S) " : "");
2264          OutputCleanActions(f, "OBJECTS", objectsParts);
2265          OutputCleanActions(f, "COBJECTS", cobjectsParts);
2266          if(numCObjects)
2267          {
2268             OutputCleanActions(f, "IMPORTS", importsParts);
2269             OutputCleanActions(f, "SYMBOLS", symbolsParts);
2270          }
2271          f.Printf("\n");
2272
2273          f.Printf("distclean: clean\n");
2274          f.Printf("\t$(call rmdirq,$(OBJ))\n");
2275          if(!sameObjTargetDirs)
2276             f.Printf("\t$(call rmdirq,%s)\n", targetDirExpNoSpaces);
2277
2278          delete f;
2279          delete objDirExp;
2280          listItems.Free();
2281          delete listItems;
2282          varStringLenDiffs.Free();
2283          delete varStringLenDiffs;
2284          namesInfo.Free();
2285          delete namesInfo;
2286
2287          result = true;
2288       }
2289
2290       // ChangeWorkingDir(oldDirectory);
2291       // delete pathBackup;
2292
2293       if(config)
2294          config.makingModified = false;
2295       return result;
2296    }
2297
2298    void GenMakefilePrintMainObjectRule(File f, CompilerConfig compiler, ProjectConfig config)
2299    {
2300       char extension[MAX_EXTENSION] = "c";
2301       char modulePath[MAX_LOCATION];
2302       char fixedModuleName[MAX_FILENAME];
2303       DualPipe dep;
2304       char command[2048];
2305       char objDirNoSpaces[MAX_LOCATION];
2306       DirExpression objDirExp = GetObjDir(compiler, config);
2307
2308       ReplaceSpaces(objDirNoSpaces, objDirExp.dir);
2309       ReplaceSpaces(fixedModuleName, moduleName);
2310       
2311       //sprintf(fixedModuleName, "%s.main", fixedPrjName);
2312       //strcat(fixedModuleName, ".main");
2313
2314 #if 0       // TODO: Fix nospaces stuff
2315       // *** Dependency command ***
2316       sprintf(command, "gcc -MT $(OBJ)%s$(O) -MM $(OBJ)%s.c", fixedModuleName, fixedModuleName);
2317
2318       // System Includes (from global settings)
2319       for(item : compiler.dirs[Includes])
2320       {
2321          strcat(command, " -isystem ");
2322          if(strchr(item.name, ' '))
2323          {
2324             strcat(command, "\"");
2325             strcat(command, item);
2326             strcat(command, "\"");
2327          }
2328          else
2329             strcat(command, item);
2330       }
2331
2332       for(item = includeDirs.first; item; item = item.next)
2333       {
2334          strcat(command, " -I");
2335          if(strchr(item.name, ' '))
2336          {
2337             strcat(command, "\"");
2338             strcat(command, item.name);
2339             strcat(command, "\"");
2340          }
2341          else
2342             strcat(command, item.name);
2343       }
2344       for(item = preprocessorDefs.first; item; item = item.next)
2345       {
2346          strcat(command, " -D");
2347          strcat(command, item.name);
2348       }
2349
2350       // Execute it
2351       if((dep = DualPipeOpen(PipeOpenMode { output = 1, error = 1, input = 2 }, command)))
2352       {
2353          char line[1024];
2354          bool result = true;
2355          bool firstLine = true;
2356
2357          // To do some time: auto save external dependencies?
2358          while(!dep.Eof())
2359          {
2360             if(dep.GetLine(line, sizeof(line)-1))
2361             {
2362                if(firstLine)
2363                {
2364                   char * colon = strstr(line, ":");
2365                   if(strstr(line, "No such file") || strstr(line, ",") || (colon && strstr(colon+1, ":")))
2366                   {
2367                      result = false;
2368                      break;
2369                   }
2370                   firstLine = false;
2371                }
2372                f.Puts(line);
2373                f.Puts("\n");
2374             }
2375             if(!result) break;
2376          }
2377          delete dep;
2378
2379          // If we failed to generate dependencies...
2380          if(!result)
2381          {
2382 #endif
2383             f.Printf("$(OBJ)$(MODULE).main$(O): $(OBJ)$(MODULE).main.c\n");
2384 #if 0
2385          }
2386       }
2387 #endif
2388
2389       f.Printf("\t$(CC) $(CFLAGS) $(FVISIBILITY) -c $(OBJ)$(MODULE).main.%s -o $(OBJ)$(MODULE).main$(O)\n\n", extension);
2390
2391       delete objDirExp;
2392    }
2393 }
2394
2395 Project LegacyBinaryLoadProject(File f, char * filePath)
2396 {
2397    Project project = null;
2398    char signature[sizeof(epjSignature)];
2399
2400    f.Read(signature, sizeof(signature), 1);
2401    if(!strncmp(signature, (char *)epjSignature, sizeof(epjSignature)))
2402    {
2403       char topNodePath[MAX_LOCATION];
2404       /*ProjectConfig newConfig
2405       {
2406          name = CopyString("Default");
2407          makingModified = true;
2408          compilingModified = true;
2409          linkingModified = true;
2410          options = { };
2411       };*/
2412
2413       project = Project { options = { } };
2414       LegacyBinaryLoadNode(project.topNode, f);
2415       delete project.topNode.path;
2416       GetWorkingDir(topNodePath, sizeof(topNodePath)-1);
2417       MakeSlashPath(topNodePath);
2418
2419       PathCatSlash(topNodePath, filePath);
2420       project.filePath = topNodePath;
2421       
2422       /* THIS IS ALREADY DONE BY filePath property
2423       StripLastDirectory(topNodePath, topNodePath);
2424       project.topNode.path = CopyString(topNodePath);
2425       */
2426       // Shouldn't this be done BEFORE the StripLastDirectory? project.filePath = topNodePath;
2427       
2428       // newConfig.options.defaultNameSpace = "";
2429       /*newConfig.objDir.dir = "obj";
2430       newConfig.targetDir.dir = "";*/
2431
2432       //project.configurations = { [ newConfig ] };
2433       //project.config = newConfig;
2434
2435       // Project Settings
2436       if(!f.Eof())
2437       {
2438          int temp;
2439          int len,c, count;
2440          String targetFileName, targetDirectory, objectsDirectory;
2441
2442          // { executable = 0, sharedLibrary = 1, staticLibrary = 2 };
2443          f.Read(&temp, sizeof(int),1);
2444          switch(temp)
2445          {
2446             case 0: project.options.targetType = executable; break;
2447             case 1: project.options.targetType = sharedLibrary; break;
2448             case 2: project.options.targetType = staticLibrary; break;
2449          }
2450
2451          f.Read(&len, sizeof(int),1);
2452          targetFileName = new char[len+1];
2453          f.Read(targetFileName, sizeof(char), len+1);
2454          project.options.targetFileName = targetFileName;
2455          delete targetFileName;
2456
2457          f.Read(&len, sizeof(int),1);
2458          targetDirectory = new char[len+1];
2459          f.Read(targetDirectory, sizeof(char), len+1);
2460          project.options.targetDirectory = targetDirectory;
2461          delete targetDirectory;
2462
2463          f.Read(&len, sizeof(int),1);
2464          objectsDirectory = new byte[len+1];
2465          f.Read(objectsDirectory, sizeof(char), len+1);
2466          project.options.objectsDirectory = objectsDirectory;
2467          delete objectsDirectory;
2468
2469          f.Read(&temp, sizeof(int),1);
2470          project./*config.*/options.debug = temp ? true : false;
2471          f.Read(&temp, sizeof(int),1);         
2472          project./*config.*/options.optimization = temp ? speed : none;
2473          f.Read(&temp, sizeof(int),1);
2474          project./*config.*/options.profile = temp ? true : false;
2475          f.Read(&temp, sizeof(int),1);
2476          project.options.warnings = temp ? all : unset;
2477
2478          f.Read(&count, sizeof(int),1);
2479          if(count)
2480          {
2481             project.options.includeDirs = { };
2482             for(c = 0; c < count; c++)
2483             {
2484                char * name;
2485                f.Read(&len, sizeof(int),1);
2486                name = new char[len+1];
2487                f.Read(name, sizeof(char), len+1);
2488                project.options.includeDirs.Add(name);
2489             }
2490          }
2491
2492          f.Read(&count, sizeof(int),1);
2493          if(count)
2494          {
2495             project.options.libraryDirs = { };
2496             for(c = 0; c < count; c++)
2497             {
2498                char * name;            
2499                f.Read(&len, sizeof(int),1);
2500                name = new char[len+1];
2501                f.Read(name, sizeof(char), len+1);
2502                project.options.libraryDirs.Add(name);
2503             }
2504          }
2505
2506          f.Read(&count, sizeof(int),1);
2507          if(count)
2508          {
2509             project.options.libraries = { };
2510             for(c = 0; c < count; c++)
2511             {
2512                char * name;
2513                f.Read(&len, sizeof(int),1);
2514                name = new char[len+1];
2515                f.Read(name, sizeof(char), len+1);
2516                project.options.libraries.Add(name);
2517             }
2518          }
2519
2520          f.Read(&count, sizeof(int),1);
2521          if(count)
2522          {
2523             project.options.preprocessorDefinitions = { };
2524             for(c = 0; c < count; c++)
2525             {
2526                char * name;
2527                f.Read(&len, sizeof(int),1);
2528                name = new char[len+1];
2529                f.Read(name, sizeof(char), len+1);
2530                project.options.preprocessorDefinitions.Add(name);
2531             }
2532          }
2533
2534          f.Read(&temp, sizeof(int),1);
2535          project.options.console = temp ? true : false;
2536       }
2537
2538       for(node : project.topNode.files)
2539       {
2540          if(node.type == resources)
2541          {
2542             project.resNode = node;
2543             break;
2544          }
2545       }
2546    }
2547    else
2548       f.Seek(0, start);
2549    return project;
2550 }
2551
2552 void ProjectConfig::LegacyProjectConfigLoad(File f)
2553 {  
2554    delete options;
2555    options = { };
2556    while(!f.Eof())
2557    {
2558       char buffer[65536];
2559       char section[128];
2560       char subSection[128];
2561       char * equal;
2562       int len;
2563       uint pos;
2564       
2565       pos = f.Tell();
2566       f.GetLine(buffer, 65536 - 1);
2567       TrimLSpaces(buffer, buffer);
2568       TrimRSpaces(buffer, buffer);
2569       if(strlen(buffer))
2570       {
2571          if(buffer[0] == '-')
2572          {
2573             equal = &buffer[0];
2574             equal[0] = ' ';
2575             TrimLSpaces(equal, equal);
2576             if(!strcmpi(subSection, "LibraryDirs"))
2577             {
2578                if(!options.libraryDirs)
2579                   options.libraryDirs = { [ CopyString(equal) ] };
2580                else
2581                   options.libraryDirs.Add(CopyString(equal));
2582             }
2583             else if(!strcmpi(subSection, "IncludeDirs"))
2584             {
2585                if(!options.includeDirs)
2586                   options.includeDirs = { [ CopyString(equal) ] };
2587                else
2588                   options.includeDirs.Add(CopyString(equal));
2589             }
2590          }
2591          else if(buffer[0] == '+')
2592          {
2593             if(name)
2594             {
2595                f.Seek(pos, start);
2596                break;
2597             }
2598             else
2599             {
2600                equal = &buffer[0];
2601                equal[0] = ' ';
2602                TrimLSpaces(equal, equal);
2603                delete name; name = CopyString(equal); // property::name = equal;
2604             }
2605          }
2606          else if(!strcmpi(buffer, "Compiler Options"))
2607             strcpy(section, buffer);
2608          else if(!strcmpi(buffer, "IncludeDirs"))
2609             strcpy(subSection, buffer);
2610          else if(!strcmpi(buffer, "Linker Options"))
2611             strcpy(section, buffer);
2612          else if(!strcmpi(buffer, "LibraryDirs"))
2613             strcpy(subSection, buffer);
2614          else if(!strcmpi(buffer, "Files") || !strcmpi(buffer, "Resources"))
2615          {
2616             f.Seek(pos, start);
2617             break;
2618          }
2619          else
2620          {
2621             equal = strstr(buffer, "=");
2622             if(equal)
2623             {
2624                equal[0] = '\0';
2625                TrimRSpaces(buffer, buffer);
2626                equal++;
2627                TrimLSpaces(equal, equal);
2628                if(!strcmpi(buffer, "Target Name"))
2629                   options.targetFileName = /*CopyString(*/equal/*)*/;
2630                else if(!strcmpi(buffer, "Target Type"))
2631                {
2632                   if(!strcmpi(equal, "Executable"))
2633                      options.targetType = executable;
2634                   else if(!strcmpi(equal, "Shared"))
2635                      options.targetType = sharedLibrary;
2636                   else if(!strcmpi(equal, "Static"))
2637                      options.targetType = staticLibrary;
2638                   else
2639                      options.targetType = executable;
2640                }
2641                else if(!strcmpi(buffer, "Target Directory"))
2642                   options.targetDirectory = /*CopyString(*/equal/*)*/;
2643                else if(!strcmpi(buffer, "Console"))
2644                   options.console = ParseTrueFalseValue(equal);
2645                else if(!strcmpi(buffer, "Libraries"))
2646                {
2647                   if(!options.libraries) options.libraries = { };
2648                   ParseArrayValue(options.libraries, equal);
2649                }
2650                else if(!strcmpi(buffer, "Intermediate Directory"))
2651                   options.objectsDirectory = /*CopyString(*/equal/*)*/; //objDir.expression = equal;
2652                else if(!strcmpi(buffer, "Debug"))
2653                   options.debug = ParseTrueFalseValue(equal);
2654                else if(!strcmpi(buffer, "Optimize"))
2655                {
2656                   if(!strcmpi(equal, "None"))
2657                      options.optimization = none;
2658                   else if(!strcmpi(equal, "Speed") || !strcmpi(equal, "True"))
2659                      options.optimization = speed;
2660                   else if(!strcmpi(equal, "Size"))
2661                      options.optimization = size;
2662                   else
2663                      options.optimization = none;
2664                }
2665                else if(!strcmpi(buffer, "Compress"))
2666                   options.compress = ParseTrueFalseValue(equal);
2667                else if(!strcmpi(buffer, "Profile"))
2668                   options.profile = ParseTrueFalseValue(equal);
2669                else if(!strcmpi(buffer, "AllWarnings"))
2670                   options.warnings = ParseTrueFalseValue(equal) ? all : unset;
2671                else if(!strcmpi(buffer, "MemoryGuard"))
2672                   options.memoryGuard = ParseTrueFalseValue(equal);
2673                else if(!strcmpi(buffer, "Default Name Space"))
2674                   options.defaultNameSpace = CopyString(equal);
2675                else if(!strcmpi(buffer, "Strict Name Spaces"))
2676                   options.strictNameSpaces = ParseTrueFalseValue(equal);
2677                else if(!strcmpi(buffer, "Preprocessor Definitions"))
2678                {
2679                   if(!options.preprocessorDefinitions) options.preprocessorDefinitions = { };
2680                   ParseArrayValue(options.preprocessorDefinitions, equal);
2681                }
2682             }
2683          }
2684       }
2685    }
2686    if(!options.targetDirectory && options.objectsDirectory)
2687       options.targetDirectory = /*CopyString(*/options.objectsDirectory/*)*/;
2688    //if(!objDir.dir) objDir.dir = "obj";
2689    //if(!targetDir.dir) targetDir.dir = "";
2690    // if(!targetName) property::targetName = "";   // How can a targetFileName be nothing???
2691    // if(!defaultNameSpace) property::defaultNameSpace = "";
2692    makingModified = true;
2693 }
2694
2695 Project LegacyAsciiLoadProject(File f, char * filePath)
2696 {
2697    Project project = null;
2698    ProjectNode node = null;
2699    int pos;
2700    char parentPath[MAX_LOCATION];
2701    char section[128] = "";
2702    char subSection[128] = "";
2703    ProjectNode parent;
2704    bool configurationsPresent = false;
2705
2706    f.Seek(0, start);
2707    while(!f.Eof())
2708    {
2709       char buffer[65536];
2710       //char version[16];
2711       char * equal;
2712       int len;
2713       pos = f.Tell();
2714       f.GetLine(buffer, 65536 - 1);
2715       TrimLSpaces(buffer, buffer);
2716       TrimRSpaces(buffer, buffer);
2717       if(strlen(buffer))
2718       {
2719          if(buffer[0] == '-' || buffer[0] == '=')
2720          {
2721             bool simple = buffer[0] == '-';
2722             equal = &buffer[0];
2723             equal[0] = ' ';
2724             TrimLSpaces(equal, equal);
2725             if(!strcmpi(section, "Target") && !strcmpi(subSection, "LibraryDirs"))
2726             {
2727                if(!project.config.options.libraryDirs) project.config.options.libraryDirs = { };
2728                project.config.options.libraryDirs.Add(CopyString(equal));
2729             }
2730             else if(!strcmpi(section, "Target") && !strcmpi(subSection, "IncludeDirs"))
2731             {
2732                if(!project.config.options.includeDirs) project.config.options.includeDirs = { };
2733                project.config.options.includeDirs.Add(CopyString(equal));
2734             }
2735             else if(!strcmpi(section, "Target") && (!strcmpi(subSection, "Files") || !strcmpi(subSection, "Resources")))
2736             {
2737                len = strlen(equal);
2738                if(len)
2739                {
2740                   char temp[MAX_LOCATION];
2741                   ProjectNode child { };
2742                   // We don't need to do this anymore, fileName is just a property that sets name & path
2743                   // child.fileName = CopyString(equal);
2744                   if(simple)
2745                   {
2746                      child.name = CopyString(equal);
2747                      child.path = CopyString(parentPath);
2748                   }
2749                   else
2750                   {
2751                      GetLastDirectory(equal, temp);
2752                      child.name = CopyString(temp);
2753                      StripLastDirectory(equal, temp);
2754                      child.path = CopyString(temp);
2755                   }
2756                   child.nodeType = file;
2757                   child.parent = parent;
2758                   child.indent = parent.indent + 1;
2759                   child.type = file;
2760                   child.icon = NodeIcons::SelectFileIcon(child.name);
2761                   parent.files.Add(child);
2762                   node = child;
2763                   //child = null;
2764                }
2765                else
2766                {
2767                   StripLastDirectory(parentPath, parentPath);
2768                   parent = parent.parent;
2769                }
2770             }
2771          }
2772          else if(buffer[0] == '+')
2773          {
2774             equal = &buffer[0];
2775             equal[0] = ' ';
2776             TrimLSpaces(equal, equal);
2777             if(!strcmpi(section, "Target") && (!strcmpi(subSection, "Files") || !strcmpi(subSection, "Resources")))
2778             {
2779                char temp[MAX_LOCATION];
2780                ProjectNode child { };
2781                // NEW: Folders now have a path set like files
2782                child.name = CopyString(equal);
2783                strcpy(temp, parentPath);
2784                PathCatSlash(temp, child.name);
2785                child.path = CopyString(temp);
2786
2787                child.parent = parent;
2788                child.indent = parent.indent + 1;
2789                child.type = folder;
2790                child.nodeType = folder;
2791                child.files = { };
2792                child.icon = folder;
2793                PathCatSlash(parentPath, child.name);
2794                parent.files.Add(child);
2795                parent = child;
2796                node = child;
2797                //child = null;
2798             }
2799             else if(!strcmpi(section, "Configurations"))
2800             {
2801                ProjectConfig newConfig
2802                {
2803                   makingModified = true;
2804                   options = { };
2805                };
2806                f.Seek(pos, start);
2807                LegacyProjectConfigLoad(newConfig, f);
2808                project.configurations.Add(newConfig);
2809             }
2810          }
2811          else if(!strcmpi(buffer, "ECERE Project File"));
2812          else if(!strcmpi(buffer, "Version 0a"))
2813             ; //strcpy(version, "0a");
2814          else if(!strcmpi(buffer, "Version 0.1a"))
2815             ; //strcpy(version, "0.1a");
2816          else if(!strcmpi(buffer, "Configurations"))
2817          {
2818             project.configurations.Free();
2819             project.config = null;
2820             strcpy(section, buffer);
2821             configurationsPresent = true;
2822          }
2823          else if(!strcmpi(buffer, "Target") || !strnicmp(buffer, "Target \"", strlen("Target \"")))
2824          {
2825             ProjectConfig newConfig { name = CopyString("Default"), options = { } };
2826             char topNodePath[MAX_LOCATION];
2827             // newConfig.defaultNameSpace = "";
2828             //newConfig.objDir.dir = "obj";
2829             //newConfig.targetDir.dir = "";
2830             project = Project { /*options = { }*/ };
2831             project.configurations = { [ newConfig ] };
2832             project.config = newConfig;
2833             // if(project.topNode.path) delete project.topNode.path;
2834             GetWorkingDir(topNodePath, sizeof(topNodePath)-1);
2835             MakeSlashPath(topNodePath);
2836             PathCatSlash(topNodePath, filePath);
2837             project.filePath = topNodePath;
2838             parentPath[0] = '\0';
2839             parent = project.topNode;
2840             node = parent;
2841             strcpy(section, "Target");
2842             equal = &buffer[6];
2843             if(equal[0] == ' ')
2844             {
2845                equal++;
2846                if(equal[0] == '\"')
2847                {
2848                   StripQuotes(equal, equal);
2849                   delete project.moduleName; project.moduleName = CopyString(equal);
2850                }
2851             }
2852          }
2853          else if(!strcmpi(buffer, "Compiler Options"));
2854          else if(!strcmpi(buffer, "IncludeDirs"))
2855             strcpy(subSection, buffer);
2856          else if(!strcmpi(buffer, "Linker Options"));
2857          else if(!strcmpi(buffer, "LibraryDirs"))
2858             strcpy(subSection, buffer);
2859          else if(!strcmpi(buffer, "Files"))
2860          {
2861             strcpy(section, "Target");
2862             strcpy(subSection, buffer);
2863          }
2864          else if(!strcmpi(buffer, "Resources"))
2865          {
2866             ProjectNode child { };
2867             parent.files.Add(child);
2868             child.parent = parent;
2869             child.indent = parent.indent + 1;
2870             child.name = CopyString(buffer);
2871             child.path = CopyString("");
2872             child.type = resources;
2873             child.files = { };
2874             child.icon = archiveFile;
2875             project.resNode = child;
2876             parent = child;
2877             node = child;
2878             strcpy(subSection, buffer);
2879          }
2880          else
2881          {
2882             equal = strstr(buffer, "=");
2883             if(equal)
2884             {
2885                equal[0] = '\0';
2886                TrimRSpaces(buffer, buffer);
2887                equal++;
2888                TrimLSpaces(equal, equal);
2889
2890                if(!strcmpi(section, "Target"))
2891                {
2892                   if(!strcmpi(buffer, "Build Exclusions"))
2893                   {
2894                      if(!strcmpi(section, "Target") && !strcmpi(subSection, "Files"))
2895                      {
2896                         /*if(node && node.type != NodeTypes::project)
2897                            ParseListValue(node.buildExclusions, equal);*/
2898                      }
2899                   }
2900                   else if(!strcmpi(buffer, "Path") && !strcmpi(subSection, "Resources"))
2901                   {
2902                      delete project.resNode.path;
2903                      project.resNode.path = CopyString(equal);
2904                      PathCatSlash(parentPath, equal);
2905                   }
2906
2907                   // Config Settings
2908                   else if(!strcmpi(buffer, "Intermediate Directory"))
2909                      project.config.options.objectsDirectory = /*CopyString(*/equal/*)*/; //objDir.expression = equal;
2910                   else if(!strcmpi(buffer, "Debug"))
2911                      project.config.options.debug = ParseTrueFalseValue(equal);
2912                   else if(!strcmpi(buffer, "Optimize"))
2913                   {
2914                      if(!strcmpi(equal, "None"))
2915                         project.config.options.optimization = none;
2916                      else if(!strcmpi(equal, "Speed") || !strcmpi(equal, "True"))
2917                         project.config.options.optimization = speed;
2918                      else if(!strcmpi(equal, "Size"))
2919                         project.config.options.optimization = size;
2920                      else
2921                         project.config.options.optimization = none;
2922                   }
2923                   else if(!strcmpi(buffer, "Profile"))
2924                      project.config.options.profile = ParseTrueFalseValue(equal);
2925                   else if(!strcmpi(buffer, "MemoryGuard"))
2926                      project.config.options.memoryGuard = ParseTrueFalseValue(equal);
2927                   else
2928                   {
2929                      if(!project.options) project.options = { };
2930
2931                      // Project Wide Settings (All configs)
2932                      if(!strcmpi(buffer, "Target Name"))
2933                         project.options.targetFileName = /*CopyString(*/equal/*)*/;
2934                      else if(!strcmpi(buffer, "Target Type"))
2935                      {
2936                         if(!strcmpi(equal, "Executable"))
2937                            project.options.targetType = executable;
2938                         else if(!strcmpi(equal, "Shared"))
2939                            project.options.targetType = sharedLibrary;
2940                         else if(!strcmpi(equal, "Static"))
2941                            project.options.targetType = staticLibrary;
2942                         else
2943                            project.options.targetType = executable;
2944                      }
2945                      else if(!strcmpi(buffer, "Target Directory"))
2946                         project.options.targetDirectory = /*CopyString(*/equal/*)*/;
2947                      else if(!strcmpi(buffer, "Console"))
2948                         project.options.console = ParseTrueFalseValue(equal);
2949                      else if(!strcmpi(buffer, "Libraries"))
2950                      {
2951                         if(!project.options.libraries) project.options.libraries = { };
2952                         ParseArrayValue(project.options.libraries, equal);
2953                      }
2954                      else if(!strcmpi(buffer, "AllWarnings"))
2955                         project.options.warnings = ParseTrueFalseValue(equal) ? all : unset;
2956                      else if(!strcmpi(buffer, "Preprocessor Definitions"))
2957                      {
2958                         if(!strcmpi(section, "Target") && !strcmpi(subSection, "Files"))
2959                         {
2960                            /*if(node && (node.type == NodeTypes::project || (node.type == file && !node.isInResources) || node.type == folder))
2961                               ParseListValue(node.preprocessorDefs, equal);*/
2962                         }
2963                         else
2964                         {
2965                            if(!project.options.preprocessorDefinitions) project.options.preprocessorDefinitions = { };
2966                            ParseArrayValue(project.options.preprocessorDefinitions, equal);
2967                         }
2968                      }
2969                   }
2970                }
2971             }
2972          }
2973       }
2974    }
2975    parent = null;
2976
2977    SplitPlatformLibraries(project);
2978
2979    if(configurationsPresent)
2980       CombineIdenticalConfigOptions(project);
2981    return project;
2982 }
2983
2984 void SplitPlatformLibraries(Project project)
2985 {
2986    if(project && project.configurations)
2987    {
2988       for(cfg : project.configurations)
2989       {
2990          if(cfg.options.libraries && cfg.options.libraries.count)
2991          {
2992             Iterator<String> it { cfg.options.libraries };
2993             while(it.Next())
2994             {
2995                String l = it.data;
2996                char * platformName = strstr(l, ":");
2997                if(platformName)
2998                {
2999                   PlatformOptions platform = null;
3000                   platformName++;
3001                   if(!cfg.platforms) cfg.platforms = { };
3002                   for(p : cfg.platforms)
3003                   {
3004                      if(!strcmpi(platformName, p.name))
3005                      {
3006                         platform = p;
3007                         break;
3008                      }
3009                   }
3010                   if(!platform)
3011                   {
3012                      platform = { name = CopyString(platformName), options = { libraries = { } } };
3013                      cfg.platforms.Add(platform);
3014                   }
3015                   *(platformName-1) = 0;
3016                   platform.options.libraries.Add(CopyString(l));
3017
3018                   cfg.options.libraries.Delete(it.pointer);
3019                   it.pointer = null;
3020                }
3021             }
3022          }
3023       }      
3024    }
3025 }
3026
3027 void CombineIdenticalConfigOptions(Project project)
3028 {
3029    if(project && project.configurations && project.configurations.count)
3030    {
3031       DataMember member;
3032       ProjectOptions nullOptions { };
3033       ProjectConfig firstConfig = null;
3034       for(cfg : project.configurations)
3035       {
3036          if(cfg.options.targetType != staticLibrary)
3037          {
3038             firstConfig = cfg;
3039             break;
3040          }
3041       }
3042       if(!firstConfig)
3043          firstConfig = project.configurations.firstIterator.data;
3044
3045       for(member = class(ProjectOptions).membersAndProperties.first; member; member = member.next)
3046       {
3047          if(!member.isProperty)
3048          {
3049             Class type = eSystem_FindClass(__thisModule, member.dataTypeString);
3050             if(type)
3051             {
3052                bool same = true;
3053
3054                for(cfg : project.configurations)
3055                {
3056                   if(cfg != firstConfig)
3057                   {
3058                      if(cfg.options.targetType != staticLibrary)
3059                      {
3060                         int result;
3061                         
3062                         if(type.type == noHeadClass || type.type == normalClass)
3063                         {
3064                            result = type._vTbl[__ecereVMethodID_class_OnCompare](type, 
3065                               *(void **)((byte *)firstConfig.options + member.offset + member._class.offset),
3066                               *(void **)((byte *)cfg.options         + member.offset + member._class.offset));
3067                         }
3068                         else
3069                         {
3070                            result = type._vTbl[__ecereVMethodID_class_OnCompare](type, 
3071                               (byte *)firstConfig.options + member.offset + member._class.offset,
3072                               (byte *)cfg.options         + member.offset + member._class.offset);
3073                         }
3074                         if(result)
3075                         {
3076                            same = false;
3077                            break;
3078                         }
3079                      }
3080                   }                  
3081                }
3082                if(same)
3083                {
3084                   if(type.type == noHeadClass || type.type == normalClass)
3085                   {
3086                      if(!type._vTbl[__ecereVMethodID_class_OnCompare](type, 
3087                         *(void **)((byte *)firstConfig.options + member.offset + member._class.offset),
3088                         *(void **)((byte *)nullOptions         + member.offset + member._class.offset)))
3089                         continue;
3090                   }
3091                   else
3092                   {
3093                      if(!type._vTbl[__ecereVMethodID_class_OnCompare](type, 
3094                         (byte *)firstConfig.options + member.offset + member._class.offset,
3095                         (byte *)nullOptions         + member.offset + member._class.offset))
3096                         continue;
3097                   }
3098
3099                   if(!project.options) project.options = { };
3100                   
3101                   /*if(type.type == noHeadClass || type.type == normalClass)
3102                   {
3103                      type._vTbl[__ecereVMethodID_class_OnCopy](type, 
3104                         (byte *)project.options + member.offset + member._class.offset,
3105                         *(void **)((byte *)firstConfig.options + member.offset + member._class.offset));
3106                   }
3107                   else
3108                   {
3109                      void * address = (byte *)firstConfig.options + member.offset + member._class.offset;
3110                      // TOFIX: ListBox::SetData / OnCopy mess
3111                      type._vTbl[__ecereVMethodID_class_OnCopy](type, 
3112                         (byte *)project.options + member.offset + member._class.offset,
3113                         (type.typeSize > 4) ? address : 
3114                            ((type.typeSize == 4) ? (void *)*(uint32 *)address : 
3115                               ((type.typeSize == 2) ? (void *)*(uint16*)address : 
3116                                  (void *)*(byte *)address )));                              
3117                   }*/
3118                   memcpy(
3119                      (byte *)project.options + member.offset + member._class.offset,
3120                      (byte *)firstConfig.options + member.offset + member._class.offset, type.typeSize);
3121
3122                   for(cfg : project.configurations)
3123                   {
3124                      if(cfg.options.targetType == staticLibrary)
3125                      {
3126                         int result;
3127                         
3128                         if(type.type == noHeadClass || type.type == normalClass)
3129                         {
3130                            result = type._vTbl[__ecereVMethodID_class_OnCompare](type, 
3131                               *(void **)((byte *)firstConfig.options + member.offset + member._class.offset),
3132                               *(void **)((byte *)cfg.options         + member.offset + member._class.offset));
3133                         }
3134                         else
3135                         {
3136                            result = type._vTbl[__ecereVMethodID_class_OnCompare](type, 
3137                               (byte *)firstConfig.options + member.offset + member._class.offset,
3138                               (byte *)cfg.options         + member.offset + member._class.offset);
3139                         }
3140                         if(result)
3141                            continue;
3142                      }
3143                      if(cfg != firstConfig)
3144                      {
3145                         if(type.type == noHeadClass || type.type == normalClass)
3146                         {
3147                            type._vTbl[__ecereVMethodID_class_OnFree](type, 
3148                               *(void **)((byte *)cfg.options + member.offset + member._class.offset));
3149                         }
3150                         else
3151                         {
3152                            type._vTbl[__ecereVMethodID_class_OnFree](type, 
3153                               (byte *)cfg.options + member.offset + member._class.offset);
3154                         }
3155                         memset((byte *)cfg.options + member.offset + member._class.offset, 0, type.typeSize);
3156                      }                     
3157                   }
3158                   memset((byte *)firstConfig.options + member.offset + member._class.offset, 0, type.typeSize);
3159                }
3160             }
3161          }
3162       }
3163       delete nullOptions;
3164
3165       // Compare Platform Specific Settings
3166       {
3167          bool same = true;
3168          for(cfg : project.configurations)
3169          {
3170             if(cfg != firstConfig && cfg.options.targetType != staticLibrary && (firstConfig.platforms || cfg.platforms) &&
3171                ((!firstConfig.platforms && cfg.platforms) || firstConfig.platforms.OnCompare(cfg.platforms)))
3172             {
3173                same = false;
3174                break;
3175             }
3176          }
3177          if(same && firstConfig.platforms)
3178          {
3179             for(cfg : project.configurations)
3180             {
3181                if(cfg.options.targetType == staticLibrary && firstConfig.platforms.OnCompare(cfg.platforms))
3182                   continue;
3183                if(cfg != firstConfig)
3184                {
3185                   cfg.platforms.Free();
3186                   delete cfg.platforms;
3187                }
3188             }
3189             project.platforms = firstConfig.platforms;
3190             firstConfig.platforms = null;
3191          }
3192       }
3193
3194       // Static libraries can't contain libraries
3195       for(cfg : project.configurations)
3196       {
3197          if(cfg.options.targetType == staticLibrary)
3198          {
3199             if(!cfg.options.libraries) cfg.options.libraries = { };
3200             cfg.options.libraries.Free();
3201          }
3202       }
3203    }
3204 }
3205
3206 Project LoadProject(char * filePath)
3207 {
3208    Project project = null;
3209    File f = FileOpen(filePath, read);
3210    if(f)
3211    {
3212       project = LegacyBinaryLoadProject(f, filePath);
3213       if(!project)
3214       {
3215          JSONParser parser { f = f };
3216          JSONResult result = parser.GetObject(class(Project), &project);
3217          if(project)
3218          {
3219             char insidePath[MAX_LOCATION];
3220
3221             delete project.topNode.files;
3222             if(!project.files) project.files = { };
3223             project.topNode.files = project.files;
3224             project.resNode = project.topNode.Add(project, "Resources", project.topNode.files.last, resources, archiveFile, false);
3225             delete project.resNode.path;
3226             project.resNode.path = project.resourcesPath;
3227             project.resourcesPath = null;
3228             project.resNode.nodeType = (ProjectNodeType)-1;
3229             delete project.resNode.files;
3230             project.resNode.files = project.resources;
3231             project.files = null;
3232             project.resources = null;
3233             if(!project.configurations) project.configurations = { };
3234
3235             {
3236                char topNodePath[MAX_LOCATION];
3237                GetWorkingDir(topNodePath, sizeof(topNodePath)-1);
3238                MakeSlashPath(topNodePath);
3239                PathCatSlash(topNodePath, filePath);
3240                project.filePath = topNodePath;//filePath;
3241             }
3242
3243             project.topNode.FixupNode(insidePath);
3244          }
3245          delete parser;
3246       }
3247       if(!project)
3248          project = LegacyAsciiLoadProject(f, filePath);
3249
3250       delete f;
3251
3252       if(project)
3253       {
3254          if(!project.options) project.options = { };
3255          if(!project.config && project.configurations)
3256             project.config = project.configurations.firstIterator.data;
3257
3258          if(!project.resNode)
3259          {
3260             project.resNode = project.topNode.Add(project, "Resources", project.topNode.files.last, resources, archiveFile, false);
3261          }
3262          
3263          if(!project.moduleName)
3264             project.moduleName = CopyString(project.name);
3265          if(project.config && 
3266             (!project.options || !project.options.targetFileName || !project.options.targetFileName[0]) &&
3267             (!project.config.options.targetFileName || !project.config.options.targetFileName[0]))
3268          {
3269             //delete project.config.options.targetFileName;
3270             
3271             project.options.targetFileName = /*CopyString(*/project.moduleName/*)*/;
3272             project.config.options.optimization = none;
3273             project.config.options.debug = true;
3274             //project.config.options.warnings = unset;
3275             project.config.options.memoryGuard = false;
3276             project.config.compilingModified = true;
3277             project.config.linkingModified = true;
3278          }
3279          else if(!project.topNode.name && project.config)
3280          {
3281             project.topNode.name = CopyString(project.config.options.targetFileName);
3282          }
3283
3284          /* // THIS IS NOW AUTOMATED WITH A project CHECK IN ProjectNode
3285          project.topNode.configurations = project.configurations;
3286          project.topNode.platforms = project.platforms;
3287          project.topNode.options = project.options;*/
3288       }
3289    }
3290    return project;
3291 }