ide; fixed error/warnings parsing when ld is skipping an incompatible library.
[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 import "DynamicString"
8
9 #ifndef MAKEFILE_GENERATOR
10 import "ide"
11 // We should have the .sln/.vcproj generation even on other platforms
12 // e.g. detect from an environment variable pointing to a Windows drive
13 #ifdef __WIN32__
14 import "vsSupport"
15 #endif
16 #endif
17
18 import "ProjectConfig"
19 import "ProjectNode"
20 import "IDESettings"
21
22 default:
23
24 static void DummyFunction()
25 {
26 int a;
27 a.OnFree();
28 }
29
30 private:
31
32 extern int __ecereVMethodID_class_OnCompare;
33 extern int __ecereVMethodID_class_OnFree;
34
35 IDESettings ideSettings;
36
37 IDESettingsContainer settingsContainer
38 {
39    driver = "JSON";
40    dataOwner = &ideSettings;
41    dataClass = class(IDESettings);
42
43    void OnLoad(GlobalSettingsData data)
44    {
45       IDESettings settings = (IDESettings)data;
46 #ifndef MAKEFILE_GENERATOR
47       globalSettingsDialog.ideSettings = settings;
48       ide.UpdateRecentMenus();
49 #endif
50    }
51 };
52
53 #ifdef MAKEFILE_GENERATOR
54 CompilerConfig defaultCompiler;
55 #endif
56
57 // LEGACY BINARY EPJ LOADING
58
59 SetBool ParseTrueFalseValue(char * string)
60 {
61    if(!strcmpi(string, "True")) return true;
62    return false;
63 }
64
65 void ParseArrayValue(Array<String> array, char * equal)
66 {
67    char * start, * comma;
68    char * string;
69    string = CopyString(equal);
70    start = string;
71    while(start)
72    {
73       comma = strstr(start, ",");
74       if(comma)
75          comma[0] = '\0';
76       array.Add(CopyString(start));
77       if(comma)
78          comma++;
79       if(comma)
80          comma++;
81       start = comma;
82    }
83    delete string;
84 }
85
86 void ProjectNode::LegacyBinaryLoadNode(File f)
87 {
88    int len, count, c;
89    int fileNameLen;
90
91    f.Read(&len, sizeof(len), 1);
92    name = new char[len+1];
93    fileNameLen = len;
94    f.Read(name, sizeof(char), len+1);
95    f.Read(&len, sizeof(len), 1);
96    fileNameLen += len;
97    path = new char[len+1];
98    f.Read(path, sizeof(char), len+1);
99    
100    /*
101    fileName = new char[fileNameLen+2];
102    strcpy(fileName, path);
103    if(fileName[0]) strcat(fileName, "/");
104    strcat(fileName, name);
105    */
106
107    f.Read(&type, sizeof(type), 1);
108    f.Read(&count, sizeof(count), 1);
109    
110    if(type == file)
111    {
112       nodeType = file;
113       icon = NodeIcons::SelectFileIcon(name);
114    }
115    else
116    {
117       nodeType = folder;
118       icon = NodeIcons::SelectNodeIcon(type);
119    }
120
121    if(count && !files) files = { };
122    for(c = 0; c < count; c++)
123    {
124       ProjectNode child { };
125       files.Add(child);
126       child.parent = this;
127       child.indent = indent + 1;
128       LegacyBinaryLoadNode(child, f);
129    }
130 }
131
132 /*void LegacyBinarySaveNode(File f)
133 {
134    int len;
135    ProjectNode child;
136    len = strlen(name);
137    f.Write(&len, sizeof(len), 1);
138    f.Write(name, sizeof(char), len+1);
139
140    if(type == project)
141    {
142       // Projects Absolute Path Are Not Saved
143       len = 0;
144       f.Write(&len, sizeof(len), 1);
145       f.Write(&len, sizeof(char), 1);
146    }
147    else
148    {
149       len = strlen(path);
150       f.Write(&len, sizeof(len), 1);
151       f.Write(path, sizeof(char), len+1);
152    }
153    f.Write(&type, sizeof(type), 1);
154    f.Write(&children.count, sizeof(children.count), 1);
155    for(child = children.first; child; child.next)
156       child.SaveNode(f);
157 }*/
158
159 void ProjectNode::LegacyAsciiSaveNode(File f, char * indentation, char * insidePath)
160 {
161    int len;
162    char printPath[MAX_LOCATION];
163
164    if(type == project && (files.count /*|| preprocessorDefs.first*/))
165    {
166       f.Printf("\n   Files\n");
167    }
168    else if(type == file)
169    {
170       if(!strcmp(path, insidePath))
171          f.Printf("%s - %s\n", indentation, name);
172       else
173       {
174          strcpy(printPath, path);
175          len = strlen(printPath);
176          if(len)
177             if(printPath[len-1] != '/')
178                strcat(printPath, "/");
179          strcat(printPath, name);
180          f.Printf("%s = %s\n", indentation, printPath);
181       }
182       if(files.count)
183          f.Printf("\nError\n\n");
184    }
185    else if(type == folder)
186    {
187       f.Printf("%s + %s\n", indentation, name);
188    }
189    else if(type == resources && files.count)
190    {
191       PathCatSlash(insidePath, path);
192       f.Printf("\n%sResources\n", indentation);
193       if(path && path[0])
194          f.Printf("%s   Path = %s\n", indentation, path);
195    }
196    
197    /*if(buildExclusions.first && type != project)
198    {
199       for(item = buildExclusions.first; item; item = item.next)
200       {
201          if(item == buildExclusions.first)
202             f.Printf("%s      Build Exclusions = %s", indentation, item.name);
203          else
204             f.Printf(", %s", item.name);
205       }
206       f.Printf("\n");
207    }
208
209    if(preprocessorDefs.first && (type == project || ((type == file || type == folder) && !isInResources)))
210    {
211       for(item = preprocessorDefs.first; item; item = item.next)
212       {
213          if(item == preprocessorDefs.first)
214             f.Printf("%s%s   Preprocessor Definitions = %s", indentation, type == project ? "" : "   ", item.name);
215          else
216             f.Printf(", %s", item.name);
217       }
218       f.Printf("\n");
219    }
220    */
221    
222    if(type == project && (files.count /*|| preprocessorDefs.first*/))
223    {
224       f.Printf("\n");
225       for(child : files)
226          LegacyAsciiSaveNode(child, f, indentation, insidePath);
227    }
228    else if(type == folder)
229    {
230       strcat(indentation, "   ");
231       // WHAT WAS THIS: strcpy(printPath, path);
232       // TOCHECK: why is Unix/PathCat not used here
233       len = strlen(insidePath);
234       if(len)
235          if(insidePath[len-1] != '/')
236             strcat(insidePath, "/");
237       strcat(insidePath, name);
238
239       for(child : files)
240          LegacyAsciiSaveNode(child, f, indentation, insidePath);
241       f.Printf("%s -\n", indentation);
242       indentation[strlen(indentation) - 3] = '\0';
243       StripLastDirectory(insidePath, insidePath);
244    }
245    else if(type == resources && files.count)
246    {
247       f.Printf("\n");
248       for(child : files)
249          LegacyAsciiSaveNode(child, f, indentation, insidePath);
250       StripLastDirectory(insidePath, insidePath);
251    }
252 }
253
254 /*
255 void ProjectConfig::LegacyProjectConfigSave(File f)
256 {
257    char * indentation = "      ";
258    //if(isCommonConfig)
259       //f.Printf("\n * Common\n");
260    //else
261       f.Printf("\n + %s\n", name);
262    f.Printf("\n   Compiler\n\n");
263    if(objDir.expression[0])
264       f.Printf("%sIntermediate Directory = %s\n", indentation, objDir.expression);
265    f.Printf("%sDebug = %s\n", indentation, (options.debug == true) ? "True" : "False");
266    switch(options.optimization)
267    {
268       // case none:   f.Printf("%sOptimize = %s\n", indentation, "None"); break;
269       case speed: f.Printf("%sOptimize = %s\n", indentation, "Speed"); break;
270       case size:  f.Printf("%sOptimize = %s\n", indentation, "Size");  break;
271    }
272    f.Printf("%sAllWarnings = %s\n", indentation, (options.warnings == all) ? "True" : "False");
273    if(options.profile)
274       f.Printf("%sProfile = %s\n", indentation, (options.profile == true) ? "True" : "False");
275    if(options.memoryGuard == true)
276       f.Printf("%sMemoryGuard = %s\n", indentation, (options.memoryGuard == true) ? "True" : "False");
277    if(options.strictNameSpaces == true)
278       f.Printf("%sStrict Name Spaces = %s\n", indentation, (options.strictNameSpaces == true) ? "True" : "False");
279    if(options.defaultNameSpace && strlen(options.defaultNameSpace))
280       f.Printf("%sDefault Name Space = %s\n", indentation, options.defaultNameSpace);
281     TOFIX: Compiler Bug {
282       if(options.preprocessorDefinitions.count)
283       {
284          bool isFirst = true;
285          for(item : options.preprocessorDefinitions)
286          {
287             if(isFirst)
288             {
289                f.Printf("\n%sPreprocessor Definitions = %s", indentation, item);
290                isFirst = false;
291             }
292             else
293                f.Printf(", %s", item);
294          }
295          f.Printf("\n");
296       }
297    }
298    if(options.includeDirs.count)
299    {
300       f.Printf("\n%sInclude Directories\n", indentation);
301       for(item : options.includeDirs)
302          f.Printf("%s - %s\n", indentation, name);
303       f.Printf("\n");
304    }
305
306    f.Printf("\n%sLinker\n\n", indentation);
307    f.Printf("%sTarget Name = %s\n", indentation, options.targetFileName);
308    switch(options.targetType)
309    {
310       case executable:     f.Printf("%sTarget Type = %s\n", indentation, "Executable"); break;
311       case sharedLibrary:  f.Printf("%sTarget Type = %s\n", indentation, "Shared");     break;
312       case staticLibrary:  f.Printf("%sTarget Type = %s\n", indentation, "Static");     break;
313    }
314    if(targetDir.expression[0])
315       f.Printf("%sTarget Directory = %s\n", indentation, targetDir.expression);
316    if(options.console)
317       f.Printf("%sConsole = %s\n", indentation, options.console ? "True" : "False");
318    if(options.compress)
319       f.Printf("%sCompress = %s\n", indentation, options.compress ? "True" : "False");
320    if(options.libraries.count)
321    {
322       bool isFirst = true;
323       for(item : options.libraries)
324       {
325          if(isFirst)
326          {
327             f.Printf("\n%sLibraries = %s", indentation, name);
328             isFirst = false;
329          }
330          else
331             f.Printf(", %s", item);
332       }
333       f.Printf("\n");
334    }
335    if(options.libraryDirs.count)
336    {
337       f.Printf("\n%sLibrary Directories\n\n", indentation);
338       for(item : options.libraryDirs)
339          f.Printf("       - %s\n", indentation, item);
340    }
341 }
342
343 void LegacyAsciiSaveProject(File f, Project project)
344 {
345    char indentation[128*3];
346    char path[MAX_LOCATION];
347
348    f.Printf("\nECERE Project File : Format Version 0.1b\n");
349    f.Printf("\nDescription\n%s\n.\n", project.description);
350    f.Printf("\nLicense\n%s\n.\n", project.license);
351    f.Printf("\nModule Name = %s\n", project.moduleName);
352    f.Printf("\n   Configurations\n");
353    //////////////////////////////////////commonConfig.Save(f, true);
354    for(cfg : project.configurations)
355       LegacyProjectConfigSave(cfg, f);
356
357    strcpy(indentation, "   ");
358    path[0] = '\0';
359    LegacyAsciiSaveNode(project.topNode, f, indentation, path);
360    // f.Printf("\n");
361    delete f;
362 }
363 */
364
365 // *** NEW JSON PROJECT FORMAT ***
366 public enum ProjectNodeType { file, folder };
367
368 // *******************************
369
370 define PEEK_RESOLUTION = (18.2 * 10);
371
372 // On Windows & UNIX
373 #define SEPS    "/"
374 #define SEP     '/'
375
376 static Array<String> notLinkerOptions
377 { [
378    "-static-libgcc",
379    "-shared",
380    "-static",
381    "-s",
382    "-shared-libgcc",
383    "-nostartfiles",
384    "-nodefaultlibs",
385    "-nostdlib",
386    "-pie",
387    "-rdynamic",
388    "-static-libasan",
389    "-static-libtsan",
390    "-static libstdc++",
391    "-symbolic",
392    "-Wl,"
393    //"-T ",
394    //"-Xlinker ",
395    //"-u "
396 ] };
397
398 static bool IsLinkerOption(String s)
399 {
400    for(i : notLinkerOptions)
401       if(strstr(s, "-Wl,") || !strcmp(s, i))
402          return false;
403    return true;
404 }
405
406 static byte epjSignature[] = { 'E', 'P', 'J', 0x04, 0x01, 0x12, 0x03, 0x12 };
407
408 enum GenMakefilePrintTypes { objects, cObjects, symbols, imports, sources, resources, eCsources };
409
410 define WorkspaceExtension = "ews";
411 define ProjectExtension = "epj";
412
413 define stringInFileIncludedFrom = "In file included from ";
414
415 void ReplaceSpaces(char * output, char * source)
416 {
417    int c, dc;
418    char ch, pch = 0;
419
420    for(c = 0, dc = 0; (ch = source[c]); c++, dc++)
421    {
422       if(ch == ' ') output[dc++] = '\\';
423       if(pch != '$')
424       {
425          if(ch == '(' || ch == ')') output[dc++] = '\\';
426          pch = ch;
427       }
428       else if(ch == ')')
429          pch = 0;
430       output[dc] = ch;
431    }
432    output[dc] = '\0';
433 }
434
435 void ReplaceUnwantedMakeChars(char * output, char * source)
436 {
437    int c, dc;
438    char ch, pch = 0;
439
440    for(c = 0, dc = 0; (ch = source[c]); c++, dc++)
441    {
442       if(pch != '$')
443       {
444          if(ch == '(' || ch == ')') output[dc++] = '\\';
445          pch = ch;
446       }
447       else if(ch == ')')
448          pch = 0;
449       if(ch == ' ')
450          output[dc] = 127;
451       else
452          output[dc] = ch;
453    }
454    output[dc] = '\0';
455 }
456
457 static void OutputNoSpace(File f, char * source)
458 {
459    char * output = new char[strlen(source)+1024];
460    ReplaceSpaces(output, source);
461    f.Puts(output);
462    delete output;
463 }
464
465 enum ListOutputMethod { inPlace, newLine, lineEach };
466
467 int OutputFileList(File f, char * name, Array<String> list, Map<String, int> varStringLenDiffs, char * prefix)
468 {
469    int numOfBreaks = 0;
470    const int breakListLength = 1536;
471    const int breakLineLength = 78; // TODO: turn this into an option.
472
473    int c, len, itemCount = 0;
474    Array<int> breaks { };
475    if(list.count)
476    {
477       int charCount = 0;
478       MapNode<String, int> mn;
479       for(c=0; c<list.count; c++)
480       {
481          len = strlen(list[c]) + 3;
482          if(strstr(list[c], "$(") && varStringLenDiffs && varStringLenDiffs.count)
483          {
484             for(mn = varStringLenDiffs.root.minimum; mn; mn = mn.next)
485             {
486                if(strstr(list[c], mn.key))
487                   len += mn.value;
488             }
489          }
490          if(charCount + len > breakListLength)
491          {
492             breaks.Add(itemCount);
493             itemCount = 0;
494             charCount = len;
495          }
496          itemCount++;
497          charCount += len;
498       }
499       if(itemCount)
500          breaks.Add(itemCount);
501       numOfBreaks = breaks.count;
502    }
503
504    if(numOfBreaks > 1)
505    {
506       f.Printf("%s =%s%s", name, prefix ? " " : "", prefix ? prefix : "");
507       for(c=0; c<numOfBreaks; c++)
508          f.Printf(" $(%s%d)", name, c+1);
509       f.Puts("\n");
510    }
511    else
512       f.Printf("%s =%s%s", name, prefix ? " " : "", prefix ? prefix : "");
513
514    if(numOfBreaks)
515    {
516       int n, offset = 0;
517
518       for(c=0; c<numOfBreaks; c++)
519       {
520          if(numOfBreaks > 1)
521             f.Printf("%s%d =", name, c+1);
522          
523          len = 3;
524          itemCount = breaks[c];
525          for(n=offset; n<offset+itemCount; n++)
526          {
527             if(false) // TODO: turn this into an option.
528             {
529                int itemLen = strlen(list[n]);
530                if(len > 3 && len + itemLen > breakLineLength)
531                {
532                   f.Printf(" \\\n\t%s", list[n]);
533                   len = 3;
534                }
535                else
536                {
537                   len += itemLen;
538                   f.Printf(" %s", list[n]);
539                }
540             }
541             else
542                f.Printf(" \\\n\t%s", list[n]);
543          }
544          offset += itemCount;
545          f.Puts("\n");
546       }
547       list.Free();
548       list.count = 0;
549    }
550    else
551       f.Puts("\n");
552    f.Puts("\n");
553    delete breaks;
554    return numOfBreaks;
555 }
556
557 void OutputCleanActions(File f, char * name, int parts)
558 {
559    if(parts > 1)
560    {
561       int c;
562       for(c=0; c<parts; c++)
563          f.Printf("\t$(call rmq,$(%s%d))\n", name, c+1);
564    }
565    else
566       f.Printf("\t$(call rmq,$(%s))\n", name);
567 }
568
569 void OutputListOption(File f, char * option, Array<String> list, ListOutputMethod method, bool noSpace)
570 {
571    if(list.count)
572    {
573       if(method == newLine)
574          f.Puts(" \\\n\t");
575       for(item : list)
576       {
577          if(method == lineEach)
578             f.Puts(" \\\n\t");
579          f.Printf(" -%s", option);
580          if(noSpace)
581             OutputNoSpace(f, item);
582          else
583             f.Printf("%s", item);
584       }
585    }
586 }
587
588 void StringNoSpaceToDynamicString(DynamicString s, char * path)
589 {
590    char * output = new char[strlen(path)+1024];
591    ReplaceSpaces(output, path);
592    s.concat(output);
593    delete output;
594 }
595
596 static void OutputLibraries(File f, Array<String> libraries)
597 {
598    for(item : libraries)
599    {
600       char ext[MAX_EXTENSION];
601       char temp[MAX_LOCATION];
602       char * s = item;
603       bool usedFunction = false;
604       GetExtension(item, ext);
605       if(!strcmp(ext, "o") || !strcmp(ext, "a"))
606          f.Puts(" ");
607       else
608       {
609          if(!strcmp(ext, "so") || !strcmp(ext, "dylib"))
610          {
611             if(!strncmp(item, "lib", 3))
612                strcpy(temp, item + 3);
613             else
614                strcpy(temp, item);
615             StripExtension(temp);
616             s = temp;
617          } 
618          f.Puts(" \\\n\t$(call _L,");
619          usedFunction = true;
620       }
621       OutputNoSpace(f, s);
622       if(usedFunction)
623          f.Puts(")");
624    }
625 }
626
627 void CamelCase(char * string)
628 {
629    int c, len = strlen(string);
630    for(c=0; c<len && string[c] >= 'A' && string[c] <= 'Z'; c++)
631       string[c] = (char)tolower(string[c]);
632 }
633
634 CompilerConfig GetCompilerConfig()
635 {
636 #ifndef MAKEFILE_GENERATOR
637    CompilerConfig compiler = null;
638    if(ide && ide.workspace)
639       compiler = ideSettings.GetCompilerConfig(ide.workspace.compiler);
640    return compiler;
641 #else
642    incref defaultCompiler;
643    return defaultCompiler;
644 #endif
645 }
646
647 define localTargetType = config && config.options && config.options.targetType ?
648             config.options.targetType : options && options.targetType ?
649             options.targetType : TargetTypes::executable;
650 define localWarnings = config && config.options && config.options.warnings ?
651             config.options.warnings : options && options.warnings ?
652             options.warnings : WarningsOption::unset;
653 define localDebug = config && config.options && config.options.debug ?
654             config.options.debug : options && options.debug ?
655             options.debug : SetBool::unset;
656 define localMemoryGuard = config && config.options && config.options.memoryGuard ?
657             config.options.memoryGuard : options && options.memoryGuard ?
658             options.memoryGuard : SetBool::unset;
659 define localNoLineNumbers = config && config.options && config.options.noLineNumbers ?
660             config.options.noLineNumbers : options && options.noLineNumbers ?
661             options.noLineNumbers : SetBool::unset;
662 define localProfile = config && config.options && config.options.profile ?
663             config.options.profile : options && options.profile ?
664             options.profile : SetBool::unset;
665 define localOptimization = config && config.options && config.options.optimization ?
666             config.options.optimization : options && options.optimization ?
667             options.optimization : OptimizationStrategy::none;
668 define localFastMath = config && config.options && config.options.fastMath ?
669             config.options.fastMath : options && options.fastMath ?
670             options.fastMath : SetBool::unset;
671 define localDefaultNameSpace = config && config.options && config.options.defaultNameSpace ?
672             config.options.defaultNameSpace : options && options.defaultNameSpace ?
673             options.defaultNameSpace : null;
674 define localStrictNameSpaces = config && config.options && config.options.strictNameSpaces ?
675             config.options.strictNameSpaces : options && options.strictNameSpaces ?
676             options.strictNameSpaces : SetBool::unset;
677 // TODO: I would rather have null here, check if it'll be ok, have the property return "" if required
678 define localTargetFileName = config && config.options && config.options.targetFileName ?
679             config.options.targetFileName : options && options.targetFileName ?
680             options.targetFileName : "";
681 define localTargetDirectory = config && config.options && config.options.targetDirectory && config.options.targetDirectory[0] ?
682             config.options.targetDirectory : options && options.targetDirectory && options.targetDirectory[0] ?
683             options.targetDirectory : null;
684 define settingsTargetDirectory = ideSettings && ideSettings.projectDefaultIntermediateObjDir &&
685             ideSettings.projectDefaultIntermediateObjDir[0] ?
686             ideSettings.projectDefaultIntermediateObjDir : defaultObjDirExpression;
687 define localObjectsDirectory = config && config.options && config.options.objectsDirectory && config.options.objectsDirectory[0] ?
688             config.options.objectsDirectory : options && options.objectsDirectory && options.objectsDirectory[0] ?
689             options.objectsDirectory : null;
690 define settingsObjectsDirectory = ideSettings && ideSettings.projectDefaultIntermediateObjDir &&
691             ideSettings.projectDefaultIntermediateObjDir[0] ?
692             ideSettings.projectDefaultIntermediateObjDir : defaultObjDirExpression;
693 define localConsole = config && config.options && config.options.console ?
694             config.options.console : options && options.console ?
695             options.console : SetBool::unset;
696 define localCompress = config && config.options && config.options.compress ?
697             config.options.compress : options && options.compress ?
698             options.compress : SetBool::unset;
699
700 define platformTargetType =
701          configPOs && configPOs.options && configPOs.options.targetType && configPOs.options.targetType != localTargetType ?
702                configPOs.options.targetType :
703          projectPOs && projectPOs.options && projectPOs.options.targetType && projectPOs.options.targetType != localTargetType ?
704                projectPOs.options.targetType : TargetTypes::unset;
705
706
707 char * PlatformToMakefileTargetVariable(Platform platform)
708 {
709    return platform == win32 ? "WINDOWS_TARGET" :
710           platform == tux   ? "LINUX_TARGET"   :
711           platform == apple ? "OSX_TARGET"     :
712                               "ERROR_BAD_TARGET";
713 }
714
715 char * TargetTypeToMakefileVariable(TargetTypes targetType)
716 {
717    return targetType == executable    ? "executable" :
718           targetType == sharedLibrary ? "sharedlib"  :
719           targetType == staticLibrary ? "staticlib"  :
720                                         "unknown";
721 }
722
723 // Move this to ProjectConfig? null vs Common to consider...
724 char * GetConfigName(ProjectConfig config)
725 {
726    return config ? config.name : "Common";
727 }
728
729 public enum SingleFileCompileMode { normal, debugPrecompile, debugCompile, debugGenerateSymbols, cObject };
730
731 class Project : struct
732 {
733    class_no_expansion;  // To use Find on the Container<Project> in Workspace::projects
734                         // We might want to tweak this default behavior of regular classes ?
735                         // Expansion/the current default kind of Find matching we want for things like BitmapResource, FontResource (Also regular classes)
736 public:
737    float version;
738    String moduleName;
739
740    property ProjectOptions options { get { return options; } set { options = value; } isset { return options && !options.isEmpty; } }
741    property Array<PlatformOptions> platforms
742    {
743       get { return platforms; }
744       set
745       {
746          if(platforms) { platforms.Free(); delete platforms; }
747          if(value)
748          {
749             List<PlatformOptions> empty { };
750             Iterator<PlatformOptions> it { value };
751             platforms = value;
752             for(p : platforms; !p.options || p.options.isEmpty) empty.Add(p);
753             for(p : empty; it.Find(p)) platforms.Delete(it.pointer);
754             delete empty;
755          }
756       }
757       isset
758       {
759          if(platforms)
760          {
761             for(p : platforms)
762             {
763                if(p.options && !p.options.isEmpty)
764                   return true;
765             }
766          }
767          return false;
768       }
769    }
770    List<ProjectConfig> configurations;
771    LinkList<ProjectNode> files;
772    String resourcesPath;
773    LinkList<ProjectNode> resources;
774
775    property char * description
776    {
777       set { delete description; if(value && value[0]) description = CopyString(value); }
778       get { return description ? description : ""; }
779       isset { return description != null && description[0]; }
780    }
781
782    property char * license
783    {
784       set { delete license; if(value && value[0]) license = CopyString(value); }
785       get { return license ? license : ""; }
786       isset { return license != null && license[0]; }
787    }
788
789    property char * compilerConfigsDir
790    {
791       set { delete compilerConfigsDir; if(value && value[0]) compilerConfigsDir = CopyString(value); }
792       get { return compilerConfigsDir ? compilerConfigsDir : ""; }
793       isset { return compilerConfigsDir && compilerConfigsDir[0]; }
794    }
795
796    property char * moduleVersion
797    {
798       set { delete moduleVersion; if(value && value[0]) moduleVersion = CopyString(value); } // TODO: use CopyString function that filters chars
799       get { return moduleVersion ? moduleVersion : ""; }                                     //       version number should only use digits and dots
800       isset { return moduleVersion != null && moduleVersion[0]; }                            //       add leading/trailing 0 if value start/ends with dot(s)
801    }
802
803 private:
804    // topNode.name holds the file name (.epj)
805    ProjectOptions options;
806    Array<PlatformOptions> platforms;
807    ProjectNode topNode { type = project, icon = epjFile, files = LinkList<ProjectNode>{ }, project = this };
808    ProjectNode resNode;
809
810    ProjectConfig config;
811    String filePath;
812    // This is the file name stripped of the epj extension
813    // It should NOT be edited, saved or loaded anywhere
814    String name;
815
816    String description;
817    String license;
818    String compilerConfigsDir;
819    String moduleVersion;
820
821 #ifndef MAKEFILE_GENERATOR
822    FileMonitor fileMonitor
823    {
824       this, FileChange { modified = true };
825       bool OnFileNotify(FileChange action, char * param)
826       {
827          fileMonitor.StopMonitoring();
828          if(OnProjectModified(action, param))
829             fileMonitor.StartMonitoring();
830          return true;
831       }
832    };
833
834    bool StartMonitoring()
835    {
836       fileMonitor.fileName = filePath;
837       fileMonitor.StartMonitoring();
838       return true;
839    }
840
841    bool StopMonitoring()
842    {
843       fileMonitor.StopMonitoring();
844       return true;
845    }
846
847    bool OnProjectModified(FileChange fileChange, char * param)
848    {
849       char temp[4096];
850       sprintf(temp, $"The project %s was modified by another application.\n"
851             "Would you like to reload it and lose your changes?", name);
852       if(MessageBox { type = yesNo, master = ide,
853             text = $"Project has been modified", contents = temp }.Modal() == yes)
854       {
855          Project project = LoadProject(filePath, config.name);
856          if(project)
857          {
858             ProjectView projectView = ide.projectView;
859             DataRow prev = topNode.row ? topNode.row.previous : null;
860             FileMonitor fm = fileMonitor;
861
862             if(projectView) projectView.DeleteNode(topNode);
863
864             *this = *project;
865             delete fileMonitor;
866             fileMonitor = fm;
867             topNode.project = this;
868
869             if(projectView)
870             {
871                CompilerConfig compiler = ideSettings.GetCompilerConfig(projectView.workspace.compiler);
872                projectView.AddNode(topNode, null);
873                topNode.row.Move(prev);
874
875                projectView.ShowOutputBuildLog(true);
876                projectView.DisplayCompiler(compiler, false);
877                projectView.ProjectUpdateMakefileForAllConfigs(this);
878                delete compiler;
879             }
880             eSystem_Delete(project);
881          }
882          return true;
883       }
884       return true;
885    }
886
887 #endif
888
889    // This frees contents without freeing the instance
890    // For use from destructor and for file monitor reloading
891    // (To work around JSON loader (LoadProject) always returning a new instance)
892    void Free()
893    {
894       if(platforms) { platforms.Free(); delete platforms; }
895       if(configurations) { configurations.Free(); delete configurations; }
896       if(files) { files.Free(); delete files; }
897       if(resources) { resources.Free(); delete resources; }
898       delete options;
899       delete resourcesPath;
900
901       delete description;
902       delete license;
903       delete compilerConfigsDir;
904       delete moduleName;
905       delete moduleVersion;
906       delete filePath;
907       delete topNode;
908       delete name;
909    }
910
911    ~Project()
912    {
913       /* // THIS IS NOW AUTOMATED WITH A project CHECK IN ProjectNode
914       topNode.configurations = null;
915       topNode.platforms = null;
916       topNode.options = null;
917       */
918       Free();
919    }
920
921    property ProjectConfig config
922    {
923       set
924       {
925          config = value;
926          delete topNode.info;
927          topNode.info = CopyString(GetConfigName(config));
928       }
929    }
930    property char * filePath
931    {
932       set
933       {
934          if(value)
935          {
936             char string[MAX_LOCATION];
937             GetLastDirectory(value, string);
938             delete topNode.name;
939             topNode.name = CopyString(string);
940             StripExtension(string);
941             delete name;
942             name = CopyString(string);
943             StripLastDirectory(value, string);
944             delete topNode.path;
945             topNode.path = CopyString(string);
946             delete filePath;
947             filePath = CopyString(value);
948          }
949       }
950    }
951
952    TargetTypes GetTargetType(ProjectConfig config)
953    {
954       TargetTypes targetType = localTargetType;
955       return targetType;
956    }
957
958    bool GetTargetTypeIsSetByPlatform(ProjectConfig config)
959    {
960       Platform platform;
961       for(platform = (Platform)1; platform < Platform::enumSize; platform++)
962       {
963          PlatformOptions projectPOs, configPOs;
964          MatchProjectAndConfigPlatformOptions(config, platform, &projectPOs, &configPOs);
965          if(platformTargetType)
966             return true;
967       }
968       return false;
969    }
970
971
972    char * GetObjDirExpression(ProjectConfig config)
973    {
974       // TODO: Support platform options
975       char * expression = localObjectsDirectory;
976       if(!expression)
977          expression = settingsObjectsDirectory;
978       return expression;
979    }
980
981    DirExpression GetObjDir(CompilerConfig compiler, ProjectConfig config)
982    {
983       char * expression = GetObjDirExpression(config);
984       DirExpression objDir { type = intermediateObjectsDir };
985       objDir.Evaluate(expression, this, compiler, config);
986       return objDir;
987    }
988
989    char * GetTargetDirExpression(ProjectConfig config)
990    {
991       // TODO: Support platform options
992       char * expression = localTargetDirectory;
993       if(!expression)
994          expression = settingsTargetDirectory;
995       return expression;
996    }
997
998    DirExpression GetTargetDir(CompilerConfig compiler, ProjectConfig config)
999    {
1000       char * expression = GetTargetDirExpression(config);
1001       DirExpression targetDir { type = DirExpressionType::targetDir /*intermediateObjectsDir*/};
1002       targetDir.Evaluate(expression, this, compiler, config);
1003       return targetDir;
1004    }
1005
1006    WarningsOption GetWarnings(ProjectConfig config)
1007    {
1008       WarningsOption warnings = localWarnings;
1009       return warnings;
1010    }
1011
1012    bool GetDebug(ProjectConfig config)
1013    {
1014       SetBool debug = localDebug;
1015       return debug == true;
1016    }
1017
1018    bool GetMemoryGuard(ProjectConfig config)
1019    {
1020       SetBool memoryGuard = localMemoryGuard;
1021       return memoryGuard == true;
1022    }
1023
1024    bool GetNoLineNumbers(ProjectConfig config)
1025    {
1026       SetBool noLineNumbers = localNoLineNumbers;
1027       return noLineNumbers == true;
1028    }
1029
1030    bool GetProfile(ProjectConfig config)
1031    {
1032       SetBool profile = localProfile;
1033       return profile == true;
1034    }
1035
1036    OptimizationStrategy GetOptimization(ProjectConfig config)
1037    {
1038       OptimizationStrategy optimization = localOptimization;
1039       return optimization;
1040    }
1041
1042    bool GetFastMath(ProjectConfig config)
1043    {
1044       SetBool fastMath = localFastMath;
1045       return fastMath == true;
1046    }
1047
1048    String GetDefaultNameSpace(ProjectConfig config)
1049    {
1050       String defaultNameSpace = localDefaultNameSpace;
1051       return defaultNameSpace;
1052    }
1053
1054    bool GetStrictNameSpaces(ProjectConfig config)
1055    {
1056       SetBool strictNameSpaces = localStrictNameSpaces;
1057       return strictNameSpaces == true;
1058    }
1059
1060    String GetTargetFileName(ProjectConfig config)
1061    {
1062       String targetFileName = localTargetFileName;
1063       return targetFileName;
1064    }
1065
1066    //String targetDirectory;
1067    //String objectsDirectory;
1068    bool GetConsole(ProjectConfig config)
1069    {
1070       SetBool console = localConsole;
1071       return console == true;
1072    }
1073
1074    bool GetCompress(ProjectConfig config)
1075    {
1076       SetBool compress = localCompress;
1077       return compress == true;
1078    }
1079    //SetBool excludeFromBuild;
1080
1081    bool GetConfigIsInActiveDebugSession(ProjectConfig config)
1082    {
1083 #ifndef MAKEFILE_GENERATOR
1084       return ide.project == this && ide.debugger && ide.debugger.prjConfig == config && ide.debugger.isActive;
1085 #endif
1086    }
1087
1088    bool GetConfigIsInDebugSession(ProjectConfig config)
1089    {
1090 #ifndef MAKEFILE_GENERATOR
1091       return ide.project == this && ide.debugger && ide.debugger.prjConfig == config && ide.debugger.isPrepared;
1092 #endif
1093    }
1094
1095    void SetPath(bool projectsDirs, CompilerConfig compiler, ProjectConfig config)
1096    {
1097 #ifndef MAKEFILE_GENERATOR
1098       ide.SetPath(projectsDirs, compiler, config);
1099 #endif
1100    }
1101
1102 #ifndef MAKEFILE_GENERATOR
1103    bool Save(char * fileName)
1104    {
1105       File f;
1106       /*char output[MAX_LOCATION];
1107        ChangeExtension(fileName, "json", output);
1108       f = FileOpen(output, write);*/
1109       f = FileOpen(fileName, write);
1110       if(f)
1111       {
1112          files = topNode.files;
1113          resources = resNode.files;
1114          resourcesPath = resNode.path;
1115
1116          files.Remove(resNode);
1117          version = 0.2f;
1118
1119          WriteJSONObject(f, class(Project), this, 0);
1120
1121          files.Add(resNode);
1122
1123          files = null;
1124          resources = null;
1125          resourcesPath = null;
1126          delete f;
1127       }
1128       return true;
1129    }
1130 #endif
1131
1132    // This method is only called from Debugger, should be moved to Debugger class?
1133 #ifndef MAKEFILE_GENERATOR
1134    bool GetRelativePath(char * filePath, char * relativePath)
1135    {
1136       ProjectNode node;
1137       char moduleName[MAX_FILENAME];
1138       GetLastDirectory(filePath, moduleName);
1139       // try with workspace dir first?
1140       if((node = topNode.Find(moduleName, false)))
1141       {
1142          strcpy(relativePath, strcmp(node.path, ".") ? node.path : "");
1143          PathCatSlash(relativePath, node.name);
1144          return true;
1145       }
1146       else
1147       {
1148          // Tweak for automatically resolving symbol loader modules
1149          char * sl = strstr(moduleName, ".main.ec");
1150          if(sl && (*sl = 0, !strcmpi(moduleName, name)))
1151          {
1152             char objDir[MAX_LOCATION];
1153             DirExpression objDirExp;
1154             CompilerConfig compiler = ide.debugger.currentCompiler;
1155             ProjectConfig config = ide.debugger.prjConfig;
1156             // This is not perfect, as multiple source files exist for the symbol loader module...
1157             // We try to set it in the debug config object directory.
1158             if(!compiler || !config)
1159             {
1160                // If we're not currently debugging, set a breakpoint in the active compiler/config
1161                compiler = GetCompilerConfig();
1162                config = this.config;
1163                // If the current config is not debuggable, set it in the first debuggable config found
1164                if(config && !config.options.debug)
1165                {
1166                   for(c : configurations; c.options.debug)
1167                   {
1168                      config = c;
1169                      break;
1170                   }
1171                }
1172             }
1173             objDirExp = GetObjDir(compiler, config);
1174             strcpy(objDir, objDirExp.dir);
1175             delete objDirExp;
1176             ChangeCh(objDir, '\\', '/'); // TODO: this is a hack, paths should never include win32 path seperators - fix this in ProjectSettings and ProjectLoad instead
1177             ReplaceSpaces(objDir, objDir);
1178             strcpy(relativePath, objDir);
1179             *sl = '.';
1180             PathCatSlash(relativePath, moduleName);
1181             return true;
1182          }
1183       }
1184       // WARNING: On failure, relative path is uninitialized
1185       return false;   
1186    }
1187 #endif
1188
1189    void CatTargetFileName(char * string, CompilerConfig compiler, ProjectConfig config)
1190    {
1191       TargetTypes targetType = GetTargetType(config);
1192       String targetFileName = GetTargetFileName(config);
1193       if(targetType == staticLibrary)
1194       {
1195          PathCatSlash(string, "lib");
1196          strcat(string, targetFileName);
1197       }
1198       else if(compiler.targetPlatform != win32 && targetType == sharedLibrary)
1199       {
1200          PathCatSlash(string, "lib");
1201          strcat(string, targetFileName);
1202       }
1203       else
1204          PathCatSlash(string, targetFileName);
1205       
1206       switch(targetType)
1207       {
1208          case executable:
1209             if(compiler.targetPlatform == win32)
1210                strcat(string, ".exe");
1211             break;
1212          case sharedLibrary:
1213             if(compiler.targetPlatform == win32)
1214                strcat(string, ".dll");
1215             else if(compiler.targetPlatform == apple)
1216                strcat(string, ".dylib");
1217             else
1218                strcat(string, ".so");
1219             if(compiler.targetPlatform != win32 && moduleVersion && moduleVersion[0])
1220             {
1221                strcat(string, ".");
1222                strcat(string, moduleVersion);
1223             }
1224             break;
1225          case staticLibrary:
1226             strcat(string, ".a");
1227             break;
1228       }
1229    }
1230
1231    bool GetProjectCompilerConfigsDir(char * cfDir, bool replaceSpaces, bool makeRelative)
1232    {
1233       bool result = false;
1234       char temp[MAX_LOCATION];
1235       strcpy(cfDir, topNode.path);
1236       if(compilerConfigsDir && compilerConfigsDir[0])
1237       {
1238          PathCatSlash(cfDir, compilerConfigsDir);
1239          result = true;
1240       }
1241       if(makeRelative)
1242       {
1243          strcpy(temp, cfDir);
1244          // Using a relative path makes it less likely to run into spaces issues
1245          // Even with escaped spaces, there still seems to be issues including a config file
1246          // in a path containing spaces
1247
1248          MakePathRelative(temp, topNode.path, cfDir);
1249       }
1250
1251       if(cfDir && cfDir[0] && cfDir[strlen(cfDir)-1] != '/')
1252          strcat(cfDir, "/");
1253       if(replaceSpaces)
1254       {
1255          strcpy(temp, cfDir);
1256          ReplaceSpaces(cfDir, temp);
1257       }
1258       return result;
1259    }
1260
1261    bool GetIDECompilerConfigsDir(char * cfDir, bool replaceSpaces, bool makeRelative)
1262    {
1263       char temp[MAX_LOCATION];
1264       bool result = false;
1265       strcpy(cfDir, topNode.path);
1266       if(ideSettings && ideSettings.compilerConfigsDir && ideSettings.compilerConfigsDir[0])
1267       {
1268          PathCatSlash(cfDir, ideSettings.compilerConfigsDir);
1269          result = true;
1270       }
1271       else
1272       {
1273          // Default to <ProjectDir>/.configs if unset
1274          PathCatSlash(cfDir, ".configs");
1275          result = true;
1276       }
1277       if(makeRelative)
1278       {
1279          strcpy(temp, cfDir);
1280          // Using a relative path makes it less likely to run into spaces issues
1281          // Even with escaped spaces, there still seems to be issues including a config file
1282          // in a path containing spaces
1283          if(IsPathInsideOf(cfDir, topNode.path))
1284             MakePathRelative(temp, topNode.path, cfDir);
1285       }
1286       if(cfDir && cfDir[0] && cfDir[strlen(cfDir)-1] != '/')
1287          strcat(cfDir, "/");
1288       if(replaceSpaces)
1289       {
1290          strcpy(temp, cfDir);
1291          ReplaceSpaces(cfDir, temp);
1292       }
1293       return result;
1294    }
1295
1296    void CatMakeFileName(char * string, ProjectConfig config)
1297    {
1298       char projectName[MAX_LOCATION];
1299       strcpy(projectName, name);
1300       sprintf(string, "%s%s%s.Makefile", projectName, config ? "-" : "", config ? config.name : "");
1301    }
1302
1303 #ifndef MAKEFILE_GENERATOR
1304    void MarkChanges(ProjectNode node)
1305    {
1306       for(cfg : topNode.configurations)
1307       {
1308          ProjectConfig c = null;
1309          for(i : node.configurations; !strcmpi(i.name, cfg.name)) { c = i; break; }
1310
1311          if(c && ((c.options && cfg.options && cfg.options.console != c.options.console) ||
1312                (!c.options || !cfg.options)))
1313             cfg.symbolGenModified = true;
1314
1315          cfg.makingModified = true;
1316       }
1317    }
1318
1319    void ModifiedAllConfigs(bool making, bool compiling, bool linking, bool symbolGen)
1320    {
1321       for(cfg : configurations)
1322       {
1323          if(making)
1324             cfg.makingModified = true;
1325          if(compiling)
1326             cfg.compilingModified = true;
1327          if(linking)
1328             cfg.linkingModified = true;
1329          if(symbolGen)
1330             cfg.symbolGenModified = true;
1331       }
1332       if(compiling || linking)
1333       {
1334          ide.projectView.modifiedDocument = true;
1335          ide.workspace.modified = true;
1336       }
1337    }
1338    
1339    void RotateActiveConfig(bool forward)
1340    {
1341       if(configurations.first && configurations.last != configurations.first)
1342       {
1343          Iterator<ProjectConfig> cfg { configurations };
1344          while(forward ? cfg.Next() : cfg.Prev())
1345             if(cfg.data == config)
1346                break;
1347
1348          if(forward)
1349          {
1350             if(!cfg.Next())
1351                cfg.Next();
1352          }
1353          else
1354          {
1355             if(!cfg.Prev())
1356                cfg.Prev();
1357          }
1358
1359          property::config = cfg.data;
1360          ide.UpdateToolBarActiveConfigs(true);
1361          ide.workspace.modified = true;
1362          ide.projectView.Update(null);
1363       }
1364    }
1365
1366    void ProcessPipeOutputRaw(DualPipe f)
1367    {
1368       char line[65536];
1369       while(!f.Eof() && !ide.ShouldStopBuild())
1370       {
1371          bool result = true;
1372          double lastTime = GetTime();
1373          bool wait = true;
1374          while(result)
1375          {
1376             if((result = f.Peek()) && (result = f.GetLine(line, sizeof(line)-1)))
1377             {
1378                ide.outputView.buildBox.Logf("%s\n", line);
1379             }
1380             if(GetTime() - lastTime > 1.0 / PEEK_RESOLUTION) break;
1381          }
1382          //printf("Processing Input...\n");
1383          if(app.ProcessInput(true))
1384             wait = false;
1385          app.UpdateDisplay();
1386          if(wait)
1387          {
1388             //printf("Waiting...\n");
1389             app.Wait();
1390          }
1391          //if(!result) Sleep(1.0 / PEEK_RESOLUTION);
1392       }
1393       if(ide.ShouldStopBuild())
1394       {
1395          ide.outputView.buildBox.Logf($"\nBuild cancelled by user.\n", line);
1396          f.Terminate();
1397       }
1398    }
1399
1400    bool ProcessBuildPipeOutput(DualPipe f, DirExpression objDirExp, bool isARun, List<ProjectNode> onlyNodes,
1401       CompilerConfig compiler, ProjectConfig config)
1402    {
1403       char line[65536];
1404       bool compiling = false, linking = false, precompiling = false;
1405       int compilingEC = 0;
1406       int numErrors = 0, numWarnings = 0;
1407       bool loggedALine = false;
1408       char * configName = config ? config.name : "Common";
1409       int lenMakeCommand = strlen(compiler.makeCommand);
1410       int testLen = 0;
1411
1412       char * gnuToolchainPrefix = compiler.gnuToolchainPrefix ? compiler.gnuToolchainPrefix : "";
1413
1414       DynamicString test { };
1415       DynamicString ecp { };
1416       DynamicString ecc { };
1417       DynamicString ecs { };
1418       DynamicString ear { };
1419       DynamicString prefix { };
1420       DynamicString cpp { };
1421       DynamicString cc { };
1422       DynamicString cxx { };
1423       DynamicString strip { };
1424       DynamicString ar { };
1425
1426       ecp.concatx(compiler.ecpCommand, " ");
1427       ecc.concatx(compiler.eccCommand, " ");
1428       ecs.concatx(compiler.ecsCommand, " ");
1429       ear.concatx(compiler.earCommand, " ");
1430
1431       prefix.concatx(
1432             compiler.ccacheEnabled ? "ccache " : "",
1433             compiler.distccEnabled ? "distcc " : "",
1434             gnuToolchainPrefix);
1435
1436       cpp.concatx((String)prefix, compiler.cppCommand, " ");
1437       cc.concatx((String)prefix, compiler.ccCommand,  " ");
1438       cxx.concatx((String)prefix, compiler.cxxCommand, " ");
1439
1440       strip.concatx(gnuToolchainPrefix, "strip ");
1441       ar.concatx(gnuToolchainPrefix, "ar rcs");
1442
1443       testLen = Max(testLen, ecp.size);
1444       testLen = Max(testLen, ecc.size);
1445       testLen = Max(testLen, ecs.size);
1446       testLen = Max(testLen, ear.size);
1447       testLen = Max(testLen, cpp.size);
1448       testLen = Max(testLen, cc.size);
1449       testLen = Max(testLen, cxx.size);
1450       testLen = Max(testLen, strip.size);
1451       testLen = Max(testLen, ar.size);
1452       testLen++;
1453
1454       while(!f.Eof() && !ide.ShouldStopBuild())
1455       {
1456          bool result = true;
1457          double lastTime = GetTime();
1458          bool wait = true;
1459          while(result)
1460          {
1461             //printf("Peeking and GetLine...\n");
1462             if((result = f.Peek()) && (result = f.GetLine(line, sizeof(line)-1)))
1463             {
1464                char * message = null;
1465                char * inFileIncludedFrom = strstr(line, stringInFileIncludedFrom);
1466                test.copyLenSingleBlankReplTrim(line, ' ', true, testLen);
1467                if(strstr(line, compiler.makeCommand) == line && line[lenMakeCommand] == ':')
1468                {
1469                   char * module = strstr(line, "No rule to make target `");
1470                   if(module)
1471                   {
1472                      char * end;
1473                      module = strchr(module, '`') + 1;
1474                      end = strchr(module, '\'');
1475                      if(end)
1476                      {
1477                         *end = '\0';
1478                         ide.outputView.buildBox.Logf($"   %s: No such file or directory\n", module);
1479                         // ide.outputView.buildBox.Logf("error: %s\n   No such file or directory\n", module);
1480                         numErrors++;
1481                      }
1482                   }
1483                   //else
1484                   //{
1485                      //ide.outputView.buildBox.Logf("error: %s\n", line);
1486                      //numErrors++;
1487                   //}
1488                }
1489                else if(strstr(test, ear) == test);
1490                else if(strstr(test, strip) == test);
1491                else if(strstr(test, cc) == test || strstr(test, cxx) == test || strstr(test, ecp) == test || strstr(test, ecc) == test)
1492                {
1493                   char moduleName[MAX_FILENAME];
1494                   byte * tokens[1];
1495                   char * module;
1496                   bool isPrecomp = false;
1497
1498                   if(strstr(test, cc) == test || strstr(test, cxx) == test)
1499                   {
1500                      module = strstr(line, " -c ");
1501                      if(module) module += 4;
1502                   }
1503                   else if(strstr(test, ecc) == test)
1504                   {
1505                      module = strstr(line, " -c ");
1506                      if(module) module += 4;
1507                      //module = line + 3;
1508                      // Don't show GCC warnings about generated C code because it does not compile clean yet...
1509                      compilingEC = 3;//2;
1510                   }
1511                   else if(strstr(test, ecp) == test)
1512                   {
1513                      // module = line + 8;
1514                      module = strstr(line, " -c ");
1515                      if(module) module += 4;
1516                      isPrecomp = true;
1517                      compilingEC = 0;
1518                   }
1519
1520                   loggedALine = true;
1521
1522                   if(module)
1523                   {
1524                      if(!compiling && !isPrecomp)
1525                      {
1526                         ide.outputView.buildBox.Logf($"Compiling...\n");
1527                         compiling = true;
1528                      }
1529                      else if(!precompiling && isPrecomp)
1530                      {
1531                         ide.outputView.buildBox.Logf($"Generating symbols...\n");
1532                         precompiling = true;
1533                      }
1534                      // Changed escapeBackSlashes here to handle paths with spaces
1535                      Tokenize(module, 1, tokens, true); // false);
1536                      GetLastDirectory(module, moduleName);
1537                      ide.outputView.buildBox.Logf("%s\n", moduleName);
1538                   }
1539                   else if((module = strstr(line, " -o ")))
1540                   {
1541                      compiling = false;
1542                      precompiling = false;
1543                      linking = true;
1544                      ide.outputView.buildBox.Logf($"Linking...\n");
1545                   }
1546                   else
1547                   {
1548                      ide.outputView.buildBox.Logf("%s\n", line);
1549                      numErrors++;
1550                   }
1551
1552                   if(compilingEC) compilingEC--;
1553                }
1554                else if(strstr(test, ar) == test)
1555                   ide.outputView.buildBox.Logf($"Building library...\n");
1556                else if(strstr(test, ecs) == test)
1557                   ide.outputView.buildBox.Logf($"Writing symbol loader...\n");
1558                else
1559                {
1560                   if(linking || compiling || precompiling)
1561                   {
1562                      char * colon = strstr(line, ":"); //, * bracket;
1563                      if(colon && (colon[1] == '/' || colon[1] == '\\'))
1564                         colon = strstr(colon + 1, ":");
1565                      if(colon)
1566                      {
1567                         char moduleName[MAX_LOCATION], temp[MAX_LOCATION];
1568                         char * pointer;
1569                         char * error;
1570                         char * start = inFileIncludedFrom ? line + strlen(stringInFileIncludedFrom) : line;
1571                         int len = (int)(colon - start);
1572                         len = Min(len, MAX_LOCATION-1);
1573                         // Don't be mistaken by the drive letter colon
1574                         // Cut module name
1575                         // TODO: need to fix colon - line gives char *
1576                         // warning: incompatible expression colon - line (char *); expected int
1577                         /*
1578                         strncpy(moduleName, line, (int)(colon - line));
1579                         moduleName[colon - line] = '\0';
1580                         */
1581                         strncpy(moduleName, start, len);
1582                         moduleName[len] = '\0';
1583                         // Remove stuff in brackets
1584                         //bracket = strstr(moduleName, "(");
1585                         //if(bracket) *bracket = '\0';
1586
1587                         GetLastDirectory(moduleName, temp);
1588                         if(linking && (!strcmp(temp, "ld") || !strcmp(temp, "ld.exe")))
1589                         {
1590                            if(strstr(colon, "skipping incompatible"))
1591                               message = $"Linker Message";
1592                            else
1593                            {
1594                               numErrors++;
1595                               message = $"Linker Error";
1596                            }
1597                         }
1598                         else
1599                         {
1600                            strcpy(temp, topNode.path);
1601                            PathCatSlash(temp, moduleName);
1602                            MakePathRelative(temp, topNode.path, moduleName);
1603                         }
1604                         if(strstr(line, "error:"))
1605                            numErrors++;
1606                         else
1607                         {
1608                            // Silence warnings for compiled EC
1609                            char * objDir = strstr(moduleName, objDirExp.dir);
1610                         
1611                            if(linking)
1612                            {
1613                               if((pointer = strstr(line, "undefined"))  ||
1614                                    (pointer = strstr(line, "No such file")) ||
1615                                    (pointer = strstr(line, "token")))
1616                               {
1617                                  strncat(moduleName, colon, pointer - colon);
1618                                  strcat(moduleName, "error: ");
1619                                  colon = pointer;
1620                                  numErrors++;
1621                               }
1622                            }
1623                            else if((pointer = strstr(line, "No such file")))
1624                            {
1625                               strncat(moduleName, colon, pointer - colon);
1626                               strcat(moduleName, "error: ");
1627                               colon = pointer;
1628                               numErrors++;
1629                            }
1630                            else if(compilingEC == 1 || (objDir && objDir == moduleName))
1631                               continue;
1632                            else if(strstr(line, "warning:"))
1633                            {
1634                               numWarnings++;
1635                            }
1636                         }
1637                         if(message)
1638                            ide.outputView.buildBox.Logf("   %s: %s\n", message, line);
1639                         else if(this == ide.workspace.projects.firstIterator.data)
1640                            ide.outputView.buildBox.Logf("   %s%s\n", moduleName, colon);
1641                         else
1642                         {
1643                            char fullModuleName[MAX_LOCATION];
1644                            strcpy(fullModuleName, topNode.path);
1645                            PathCat(fullModuleName, moduleName);
1646                            MakePathRelative(fullModuleName, ide.workspace.projects.firstIterator.data.topNode.path, fullModuleName);
1647                            MakeSystemPath(fullModuleName);
1648                            ide.outputView.buildBox.Logf("   %s%s%s\n", inFileIncludedFrom ? stringInFileIncludedFrom : "", fullModuleName, colon);
1649                         }
1650                      }
1651                      else
1652                      {
1653                         ide.outputView.buildBox.Logf("%s\n", line);
1654                         linking = compiling = precompiling = false;
1655                      }
1656                   }
1657                   else
1658                      ide.outputView.buildBox.Logf("%s\n", line);
1659                }
1660                wait = false;
1661             }
1662             //printf("Done getting line\n");
1663             if(GetTime() - lastTime > 1.0 / PEEK_RESOLUTION) break;
1664          }
1665          //printf("Processing Input...\n");
1666          if(app.ProcessInput(true))
1667             wait = false;
1668          app.UpdateDisplay();
1669          if(wait)
1670          {
1671             //printf("Waiting...\n");
1672             app.Wait();
1673          }
1674          //if(!result) Sleep(1.0 / PEEK_RESOLUTION);
1675       }
1676       if(ide.ShouldStopBuild())
1677       {
1678          ide.outputView.buildBox.Logf($"\nBuild cancelled by user.\n", line);
1679          f.Terminate();
1680       }
1681       else if(loggedALine || !isARun)
1682       {
1683          if(f.GetExitCode() && !numErrors)
1684          {
1685             bool result = f.GetLine(line, sizeof(line)-1);
1686             ide.outputView.buildBox.Logf($"Fatal Error: child process terminated unexpectedly\n");
1687          }
1688          else
1689          {
1690             if(!onlyNodes)
1691             {
1692                char targetFileName[MAX_LOCATION];
1693                targetFileName[0] = '\0';
1694                CatTargetFileName(targetFileName, compiler, config);
1695                ide.outputView.buildBox.Logf("\n%s (%s) - ", targetFileName, configName);
1696             }
1697             if(numErrors)
1698                ide.outputView.buildBox.Logf("%d %s, ", numErrors, (numErrors > 1) ? $"errors" : $"error");
1699             else
1700                ide.outputView.buildBox.Logf($"no error, ");
1701    
1702             if(numWarnings)
1703                ide.outputView.buildBox.Logf("%d %s\n", numWarnings, (numWarnings > 1) ? $"warnings" : $"warning");
1704             else
1705                ide.outputView.buildBox.Logf($"no warning\n");
1706          }
1707       }
1708
1709       delete test;
1710       delete ecp;
1711       delete ecc;
1712       delete ecs;
1713       delete ear;
1714       delete prefix;
1715       delete cpp;
1716       delete cc;
1717       delete cxx;
1718       delete strip;
1719       delete ar;
1720
1721       return numErrors == 0;
1722    }
1723
1724    void ProcessCleanPipeOutput(DualPipe f, CompilerConfig compiler, ProjectConfig config)
1725    {
1726       char line[65536];
1727       int lenMakeCommand = strlen(compiler.makeCommand);
1728       while(!f.Eof())
1729       {
1730          bool result = true;
1731          bool wait = true;
1732          double lastTime = GetTime();
1733          while(result)
1734          {
1735             if((result = f.Peek()) && (result = f.GetLine(line, sizeof(line)-1)))
1736             {
1737                if(strstr(line, compiler.makeCommand) == line && line[lenMakeCommand] == ':');
1738                else if(strstr(line, "del") == line);
1739                else if(strstr(line, "rm") == line);
1740                else if(strstr(line, "Could Not Find") == line);
1741                else
1742                {
1743                   ide.outputView.buildBox.Logf(line);
1744                   ide.outputView.buildBox.Logf("\n");
1745                }
1746                wait = false;
1747             }
1748             if(GetTime() - lastTime > 1.0 / PEEK_RESOLUTION) break;
1749          }
1750          if(app.ProcessInput(true))
1751             wait = false;
1752          app.UpdateDisplay();
1753          if(wait)
1754             app.Wait();
1755          //Sleep(1.0 / PEEK_RESOLUTION);
1756       }
1757    }
1758
1759    bool Build(bool isARun, List<ProjectNode> onlyNodes, CompilerConfig compiler, ProjectConfig config, bool justPrint, SingleFileCompileMode mode)
1760    {
1761       bool result = false;
1762       DualPipe f;
1763       char targetFileName[MAX_LOCATION] = "";
1764       DynamicString makeTargets { };
1765       char makeFile[MAX_LOCATION];
1766       char makeFilePath[MAX_LOCATION];
1767       char configName[MAX_LOCATION];
1768       DirExpression objDirExp = GetObjDir(compiler, config);
1769       PathBackup pathBackup { };
1770       bool crossCompiling = (compiler.targetPlatform != GetRuntimePlatform());
1771       char * targetPlatform = crossCompiling ? (char *)compiler.targetPlatform : "";
1772
1773       int numJobs = compiler.numJobs;
1774       char command[MAX_F_STRING];
1775       char * compilerName;
1776
1777       compilerName = CopyString(compiler.name);
1778       CamelCase(compilerName);
1779
1780       strcpy(configName, config ? config.name : "Common");
1781
1782       SetPath(false, compiler, config); //true
1783       CatTargetFileName(targetFileName, compiler, config);
1784
1785       strcpy(makeFilePath, topNode.path);
1786       CatMakeFileName(makeFile, config);
1787       PathCatSlash(makeFilePath, makeFile);
1788
1789       // TODO: TEST ON UNIX IF \" around makeTarget is ok
1790       if(onlyNodes)
1791       {
1792          if(compiler.type.isVC)
1793          {
1794             PrintLn("compiling a single file is not yet supported");
1795          }
1796          else
1797          {
1798             int len;
1799             char pushD[MAX_LOCATION];
1800             char cfDir[MAX_LOCATION];
1801             Map<String, NameCollisionInfo> namesInfo { };
1802             GetIDECompilerConfigsDir(cfDir, true, true);
1803             GetWorkingDir(pushD, sizeof(pushD));
1804             ChangeWorkingDir(topNode.path);
1805             // Create object dir if it does not exist already
1806             if(!FileExists(objDirExp.dir).isDirectory)
1807             {
1808                sprintf(command, "%s CF_DIR=\"%s\"%s%s COMPILER=%s objdir -C \"%s\"%s -f \"%s\"",
1809                      compiler.makeCommand, cfDir,
1810                      crossCompiling ? " TARGET_PLATFORM=" : "", targetPlatform,
1811                      compilerName, topNode.path, justPrint ? " -n" : "", makeFilePath);
1812                if(justPrint)
1813                   ide.outputView.buildBox.Logf("%s\n", command);
1814                Execute(command);
1815             }
1816
1817             ChangeWorkingDir(pushD);
1818
1819             topNode.GenMakefileGetNameCollisionInfo(namesInfo, config);
1820             for(node : onlyNodes)
1821             {
1822                if(node.GetIsExcluded(config))
1823                   ide.outputView.buildBox.Logf($"File %s is excluded from current build configuration.\n", node.name);
1824                else
1825                {
1826                   node.DeleteIntermediateFiles(compiler, config, namesInfo, mode == cObject ? true : false);
1827                   node.GetTargets(config, namesInfo, objDirExp.dir, makeTargets);
1828                }
1829             }
1830             namesInfo.Free();
1831             delete namesInfo;
1832          }
1833       }
1834
1835       if(compiler.type.isVC)
1836       {
1837          bool result = false;
1838          char oldwd[MAX_LOCATION];
1839          GetWorkingDir(oldwd, sizeof(oldwd));
1840          ChangeWorkingDir(topNode.path);
1841
1842          // TODO: support justPrint
1843          sprintf(command, "%s /useenv /nologo /logcommands %s.sln %s|Win32", compiler.makeCommand, name, config.name);
1844          if(justPrint)
1845             ide.outputView.buildBox.Logf("%s\n", command);
1846          if((f = DualPipeOpen(PipeOpenMode { output = true, error = true, input = true }, command)))
1847          {
1848             ProcessPipeOutputRaw(f);
1849             delete f;
1850             result = true;
1851          }
1852          ChangeWorkingDir(oldwd);
1853       }
1854       else
1855       {
1856          char cfDir[MAX_LOCATION];
1857          GetIDECompilerConfigsDir(cfDir, true, true);
1858          sprintf(command, "%s %sCF_DIR=\"%s\"%s%s COMPILER=%s -j%d %s%s%s -C \"%s\"%s -f \"%s\"",
1859                compiler.makeCommand,
1860                mode == debugPrecompile ? "ECP_DEBUG=y " : mode == debugCompile ? "ECC_DEBUG=y " : mode == debugGenerateSymbols ? "ECS_DEBUG=y " : "",
1861                cfDir,
1862                crossCompiling ? " TARGET_PLATFORM=" : "", targetPlatform,
1863                compilerName, numJobs,
1864                compiler.ccacheEnabled ? "CCACHE=y " : "",
1865                compiler.distccEnabled ? "DISTCC=y " : "",
1866                (String)makeTargets, topNode.path, (justPrint || (mode != normal && mode != cObject)) ? " -n" : "", makeFilePath);
1867          if(justPrint)
1868             ide.outputView.buildBox.Logf("%s\n", command);
1869          if((f = DualPipeOpen(PipeOpenMode { output = true, error = true, input = true }, command)))
1870          {
1871             bool found = false;
1872             if(justPrint)
1873             {
1874                ProcessPipeOutputRaw(f);
1875                result = true;
1876             }
1877             else if(mode != normal && mode != cObject)
1878             {
1879                char line[65536];
1880                while(!f.Eof())
1881                {
1882                   bool result = true;
1883                   while(result)
1884                   {
1885                      if((result = f.Peek()) && (result = f.GetLine(line, sizeof(line)-1)))
1886                      {
1887                         if(!found && strstr(line, "ide ") == line)
1888                         {
1889                            strcpy(command, line);
1890                            found = true;
1891                         }
1892                      }
1893                   }
1894                }
1895             }
1896             else
1897                result = ProcessBuildPipeOutput(f, objDirExp, isARun, onlyNodes, compiler, config);
1898             delete f;
1899             if(found)
1900                Execute(command);
1901          }
1902          else
1903             ide.outputView.buildBox.Logf($"Error executing make (%s) command\n", compiler.makeCommand);
1904       }
1905
1906       delete pathBackup;
1907       delete objDirExp;
1908       delete compilerName;
1909       delete makeTargets;
1910       return result;
1911    }
1912
1913    void Clean(CompilerConfig compiler, ProjectConfig config, CleanType cleanType, bool justPrint)
1914    {
1915       char makeFile[MAX_LOCATION];
1916       char makeFilePath[MAX_LOCATION];
1917       char command[MAX_LOCATION];
1918       char * compilerName;
1919       DualPipe f;
1920       PathBackup pathBackup { };
1921       bool crossCompiling = (compiler.targetPlatform != GetRuntimePlatform());
1922       char * targetPlatform = crossCompiling ? (char *)compiler.targetPlatform : "";
1923
1924       compilerName = CopyString(compiler.name);
1925       CamelCase(compilerName);
1926
1927       SetPath(false, compiler, config);
1928
1929       strcpy(makeFilePath, topNode.path);
1930       CatMakeFileName(makeFile, config);
1931       PathCatSlash(makeFilePath, makeFile);
1932       
1933       if(compiler.type.isVC)
1934       {
1935          bool result = false;
1936          char oldwd[MAX_LOCATION];
1937          GetWorkingDir(oldwd, sizeof(oldwd));
1938          ChangeWorkingDir(topNode.path);
1939          
1940          // TODO: justPrint support
1941          sprintf(command, "%s /useenv /clean /nologo /logcommands %s.sln %s|Win32", compiler.makeCommand, name, config.name);
1942          if(justPrint)
1943             ide.outputView.buildBox.Logf("%s\n", command);
1944          if((f = DualPipeOpen(PipeOpenMode { output = true, error = true, input = true }, command)))
1945          {
1946             ProcessPipeOutputRaw(f);
1947             delete f;
1948             result = true;
1949          }
1950          ChangeWorkingDir(oldwd);
1951          return result;
1952       }
1953       else
1954       {
1955          char cfDir[MAX_LOCATION];
1956          GetIDECompilerConfigsDir(cfDir, true, true);
1957          sprintf(command, "%s CF_DIR=\"%s\"%s%s COMPILER=%s %sclean%s -C \"%s\"%s -f \"%s\"",
1958                compiler.makeCommand, cfDir,
1959                crossCompiling ? " TARGET_PLATFORM=" : "", targetPlatform, compilerName,
1960                cleanType == realClean ? "real" : "", cleanType == cleanTarget ? "target" : "",
1961                topNode.path, justPrint ? " -n": "", makeFilePath);
1962          if(justPrint)
1963             ide.outputView.buildBox.Logf("%s\n", command);
1964          if((f = DualPipeOpen(PipeOpenMode { output = 1, error = 1, input = 2 }, command)))
1965          {
1966             ide.outputView.buildBox.Tell($"Deleting target and object files...");
1967             if(justPrint)
1968                ProcessPipeOutputRaw(f);
1969             else
1970                ProcessCleanPipeOutput(f, compiler, config);
1971             delete f;
1972
1973             ide.outputView.buildBox.Logf($"Target and object files deleted\n");
1974          }
1975       }
1976
1977       delete pathBackup;
1978       delete compilerName;
1979    }
1980
1981    void Run(char * args, CompilerConfig compiler, ProjectConfig config)
1982    {   
1983       String target = new char[maxPathLen];
1984       char oldDirectory[MAX_LOCATION];
1985       char * executableLauncher = compiler.executableLauncher;
1986       DirExpression targetDirExp = GetTargetDir(compiler, config);
1987       PathBackup pathBackup { };
1988
1989       // Build(project, ideMain, true, null, false);
1990
1991    #if defined(__WIN32__)
1992       strcpy(target, topNode.path);
1993    #else
1994       strcpy(target, "");
1995    #endif
1996       PathCatSlash(target, targetDirExp.dir);
1997       CatTargetFileName(target, compiler, config);
1998       sprintf(target, "%s %s", target, args);
1999       GetWorkingDir(oldDirectory, MAX_LOCATION);
2000
2001       if(strlen(ide.workspace.debugDir))
2002       {
2003          char temp[MAX_LOCATION];
2004          strcpy(temp, topNode.path);
2005          PathCatSlash(temp, ide.workspace.debugDir);
2006          ChangeWorkingDir(temp);
2007       }
2008       else
2009          ChangeWorkingDir(topNode.path);
2010       // ChangeWorkingDir(topNode.path);
2011       SetPath(true, compiler, config);
2012       if(executableLauncher)
2013       {
2014          char * prefixedTarget = new char[strlen(executableLauncher) + strlen(target) + 2];
2015          prefixedTarget[0] = '\0';
2016          strcat(prefixedTarget, executableLauncher);
2017          strcat(prefixedTarget, " ");
2018          strcat(prefixedTarget, target);
2019          Execute(prefixedTarget);
2020          delete prefixedTarget;
2021       }
2022       else
2023          Execute(target);
2024
2025       ChangeWorkingDir(oldDirectory);
2026       delete pathBackup;
2027
2028       delete targetDirExp;
2029       delete target;
2030    }
2031
2032    void Compile(List<ProjectNode> nodes, CompilerConfig compiler, ProjectConfig config, bool justPrint, SingleFileCompileMode mode)
2033    {
2034       Build(false, nodes, compiler, config, justPrint, mode);
2035    }
2036 #endif
2037
2038    void GetMakefileTargetFileName(TargetTypes targetType, char * fileName, ProjectConfig config)
2039    {
2040       fileName[0] = '\0';
2041       if(targetType == staticLibrary || targetType == sharedLibrary)
2042          strcat(fileName, "$(LP)");
2043       // !!! ReplaceSpaces must be done after all PathCat calls !!!
2044       // ReplaceSpaces(s, GetTargetFileName(config));
2045       strcat(fileName, GetTargetFileName(config));
2046       switch(targetType)
2047       {
2048          case executable:
2049             strcat(fileName, "$(E)");
2050             break;
2051          case sharedLibrary:
2052             strcat(fileName, "$(SO)");
2053             break;
2054          case staticLibrary:
2055             strcat(fileName, "$(A)");
2056             break;
2057       }
2058    }
2059
2060    bool GenerateCrossPlatformMk(File altCrossPlatformMk)
2061    {
2062       bool result = false;
2063       char path[MAX_LOCATION];
2064
2065       if(!GetProjectCompilerConfigsDir(path, false, false))
2066          GetIDECompilerConfigsDir(path, false, false);
2067
2068       if(!FileExists(path).isDirectory)
2069       {
2070          MakeDir(path);
2071          {
2072             char dirName[MAX_FILENAME];
2073             GetLastDirectory(path, dirName);
2074             if(!strcmp(dirName, ".configs"))
2075                FileSetAttribs(path, FileAttribs { isHidden = true });
2076          }
2077       }
2078       PathCatSlash(path, "crossplatform.mk");
2079
2080       if(FileExists(path))
2081          DeleteFile(path);
2082       {
2083          File include = altCrossPlatformMk ? altCrossPlatformMk : FileOpen(":crossplatform.mk", read);
2084          if(include)
2085          {
2086             File f = FileOpen(path, write);
2087             if(f)
2088             {
2089                include.Seek(0, start);
2090                for(; !include.Eof(); )
2091                {
2092                   char buffer[4096];
2093                   int count = include.Read(buffer, 1, 4096);
2094                   f.Write(buffer, 1, count);
2095                }
2096                delete f;
2097
2098                result = true;
2099             }
2100             if(!altCrossPlatformMk)
2101                delete include;
2102          }
2103       }
2104       return result;
2105    }
2106
2107    bool GenerateCompilerCf(CompilerConfig compiler)
2108    {
2109       bool result = false;
2110       char path[MAX_LOCATION];
2111       char * name;
2112       char * compilerName;
2113       bool gccCompiler = compiler.ccCommand && (strstr(compiler.ccCommand, "gcc") != null || strstr(compiler.ccCommand, "g++") != null);
2114       char * gnuToolchainPrefix = compiler.gnuToolchainPrefix ? compiler.gnuToolchainPrefix : "";
2115       Platform platform = compiler.targetPlatform;
2116
2117       compilerName = CopyString(compiler.name);
2118       CamelCase(compilerName);
2119       name = PrintString(platform, "-", compilerName, ".cf");
2120
2121       if(!GetProjectCompilerConfigsDir(path, false, false))
2122          GetIDECompilerConfigsDir(path, false, false);
2123
2124       if(!FileExists(path).isDirectory)
2125       {
2126          MakeDir(path);
2127          {
2128             char dirName[MAX_FILENAME];
2129             GetLastDirectory(path, dirName);
2130             if(!strcmp(dirName, ".configs"))
2131                FileSetAttribs(path, FileAttribs { isHidden = true });
2132          }
2133       }
2134       PathCatSlash(path, name);
2135
2136       if(FileExists(path))
2137          DeleteFile(path);
2138       {
2139          File f = FileOpen(path, write);
2140          if(f)
2141          {
2142             if(compiler.environmentVars && compiler.environmentVars.count)
2143             {
2144                f.Puts("# ENVIRONMENT VARIABLES\n");
2145                f.Puts("\n");
2146                for(e : compiler.environmentVars)
2147                {
2148                   f.Printf("export %s := %s\n", e.name, e.string);
2149                }
2150             }
2151
2152             f.Puts("# TOOLCHAIN\n");
2153             f.Puts("\n");
2154
2155             if(gnuToolchainPrefix && gnuToolchainPrefix[0])
2156             {
2157                f.Printf("GCC_PREFIX := %s\n", gnuToolchainPrefix);
2158                f.Puts("\n");
2159             }
2160             if(compiler.sysroot && compiler.sysroot[0])
2161             {
2162                f.Printf("SYSROOT := %s\n", compiler.sysroot);
2163                // Moved this to crossplatform.mk
2164                //f.Puts("_SYSROOT := $(space)--sysroot=$(SYSROOT)\n");
2165                f.Puts("\n");
2166             }
2167
2168             //f.Printf("SHELL := %s\n", "sh"/*compiler.shellCommand*/); // is this really needed?
2169             f.Printf("CPP := $(CCACHE_COMPILE)$(DISTCC_COMPILE)$(GCC_PREFIX)%s$(_SYSROOT)\n", compiler.cppCommand);
2170             f.Printf("CC := $(CCACHE_COMPILE)$(DISTCC_COMPILE)$(GCC_PREFIX)%s$(_SYSROOT)\n", compiler.ccCommand);
2171             f.Printf("CXX := $(CCACHE_COMPILE)$(DISTCC_COMPILE)$(GCC_PREFIX)%s$(_SYSROOT)\n", compiler.cxxCommand);
2172             f.Printf("ECP := $(if $(ECP_DEBUG),ide -debug-start $(ECERE_SDK_SRC)/compiler/ecp/ecp.epj -@,%s)\n", compiler.ecpCommand);
2173             f.Printf("ECC := $(if $(ECC_DEBUG),ide -debug-start $(ECERE_SDK_SRC)/compiler/ecc/ecc.epj -@,%s)$(if $(CROSS_TARGET), -t $(TARGET_PLATFORM),)\n", compiler.eccCommand);
2174             f.Printf("ECS := $(if $(ECS_DEBUG),ide -debug-start $(ECERE_SDK_SRC)/compiler/ecs/ecs.epj -@,%s)$(if $(CROSS_TARGET), -t $(TARGET_PLATFORM),)\n", compiler.ecsCommand);
2175             f.Printf("EAR := %s\n", compiler.earCommand);
2176
2177             f.Puts("AS := $(GCC_PREFIX)as\n");
2178             f.Puts("LD := $(GCC_PREFIX)ld\n");
2179             f.Puts("AR := $(GCC_PREFIX)ar\n");
2180             f.Puts("STRIP := $(GCC_PREFIX)strip\n");
2181             f.Puts("UPX := upx\n");
2182             f.Puts("\n");
2183
2184             f.Puts("UPXFLAGS = -9\n"); // TOFEAT: Compression Level Option? Other UPX Options?
2185             f.Puts("\n");
2186
2187             f.Puts("EARFLAGS = \n");
2188             f.Puts("\n");
2189
2190             f.Puts("ifndef ARCH\n");
2191             f.Puts("TARGET_ARCH :=$(shell $(CC) -dumpmachine)\n");
2192             f.Puts(" ifdef WINDOWS_HOST\n");
2193             f.Puts("  ifneq ($(filter x86_64%,$(TARGET_ARCH)),)\n");
2194             f.Puts("     TARGET_ARCH := x86_64\n");
2195             f.Puts("  else\n");
2196             f.Puts("     TARGET_ARCH := i386\n");
2197             f.Puts("  endif\n");
2198             f.Puts(" endif\n");
2199             f.Puts("endif\n\n");
2200
2201             f.Puts("# HARD CODED TARGET_PLATFORM-SPECIFIC OPTIONS\n");
2202             f.Printf("LDFLAGS +=$(if $(%s), -Wl$(comma)--no-undefined,)\n", PlatformToMakefileTargetVariable(tux));
2203             f.Puts("\n");
2204
2205             // JF's
2206             f.Printf("LDFLAGS +=$(if $(%s), -framework cocoa -framework OpenGL,)\n", PlatformToMakefileTargetVariable(apple));
2207
2208             if(gccCompiler)
2209             {
2210                f.Puts("\nCFLAGS += -fmessage-length=0\n");
2211             }
2212
2213             if(compiler.includeDirs && compiler.includeDirs.count)
2214             {
2215                f.Puts("\nCFLAGS +=");
2216                OutputListOption(f, gccCompiler ? "isystem " : "I", compiler.includeDirs, lineEach, true);
2217                f.Puts("\n");
2218             }
2219             if(compiler.prepDirectives && compiler.prepDirectives.count)
2220             {
2221                f.Puts("\nCFLAGS +=");
2222                OutputListOption(f, "D", compiler.prepDirectives, inPlace, true);
2223                f.Puts("\n");
2224             }
2225             if(compiler.libraryDirs && compiler.libraryDirs.count)
2226             {
2227                f.Puts("\nLDFLAGS +=");
2228                OutputListOption(f, "L", compiler.libraryDirs, lineEach, true);
2229                // We would need a bool option to know whether we want to add to rpath as well...
2230                // OutputListOption(f, "Wl,-rpath ", compiler.libraryDirs, lineEach, true);
2231                f.Puts("\n");
2232             }
2233             if(compiler.excludeLibs && compiler.excludeLibs.count)
2234             {
2235                f.Puts("\nEXCLUDED_LIBS =");
2236                for(l : compiler.excludeLibs)
2237                {
2238                   f.Puts(" ");
2239                   f.Puts(l);
2240                }
2241             }
2242             if(compiler.linkerFlags && compiler.linkerFlags.count)
2243             {
2244                f.Puts("\nLDFLAGS +=");
2245                OutputListOption(f, "Wl,", compiler.linkerFlags, inPlace, true);
2246                f.Puts("\n");
2247             }
2248             f.Puts("\n");
2249             f.Puts("\nOFLAGS += $(LDFLAGS)");
2250             f.Puts("\n");
2251             f.Puts("ifdef ARCH_FLAGS\n");
2252             f.Puts("CFLAGS += $(ARCH_FLAGS)\n");
2253             f.Puts("OFLAGS += $(ARCH_FLAGS)\n");
2254             f.Puts("endif\n");
2255
2256             delete f;
2257
2258             result = true;
2259          }
2260       }
2261       delete name;
2262       delete compilerName;
2263       return result;
2264    }
2265
2266    bool GenerateMakefile(char * altMakefilePath, bool noResources, char * includemkPath, ProjectConfig config)
2267    {
2268       bool result = false;
2269       char filePath[MAX_LOCATION];
2270       char makeFile[MAX_LOCATION];
2271       // PathBackup pathBackup { };
2272       // char oldDirectory[MAX_LOCATION];
2273       File f = null;
2274
2275       if(!altMakefilePath)
2276       {
2277          strcpy(filePath, topNode.path);
2278          CatMakeFileName(makeFile, config);
2279          PathCatSlash(filePath, makeFile);
2280       }
2281
2282       f = FileOpen(altMakefilePath ? altMakefilePath : filePath, write);
2283
2284       /*SetPath(false, compiler, config);
2285       GetWorkingDir(oldDirectory, MAX_LOCATION);
2286       ChangeWorkingDir(topNode.path);*/
2287
2288       if(f)
2289       {
2290          bool test;
2291          int ifCount;
2292          Platform platform;
2293          char targetDir[MAX_LOCATION];
2294          char objDirExpNoSpaces[MAX_LOCATION];
2295          char objDirNoSpaces[MAX_LOCATION];
2296          char resDirNoSpaces[MAX_LOCATION];
2297          char targetDirExpNoSpaces[MAX_LOCATION];
2298          char fixedModuleName[MAX_FILENAME];
2299          char fixedConfigName[MAX_FILENAME];
2300          int c, len;
2301          // Non-zero if we're building eC code
2302          // We'll have to be careful with this when merging configs where eC files can be excluded in some configs and included in others
2303          int numCObjects = 0;
2304          int numObjects = 0;
2305          bool containsCXX = false; // True if the project contains a C++ file
2306          bool sameObjTargetDirs;
2307          String objDirExp = GetObjDirExpression(config);
2308          TargetTypes targetType = GetTargetType(config);
2309
2310          char cfDir[MAX_LOCATION];
2311          int objectsParts = 0, eCsourcesParts = 0;
2312          Array<String> listItems { };
2313          Map<String, int> varStringLenDiffs { };
2314          Map<String, NameCollisionInfo> namesInfo { };
2315          bool forceBitDepth = false;
2316
2317          Map<String, int> cflagsVariations { };
2318          Map<intptr, int> nodeCFlagsMapping { };
2319
2320          Map<String, int> ecflagsVariations { };
2321          Map<intptr, int> nodeECFlagsMapping { };
2322
2323          ReplaceSpaces(objDirNoSpaces, objDirExp);
2324          strcpy(targetDir, GetTargetDirExpression(config));
2325          ReplaceSpaces(targetDirExpNoSpaces, targetDir);
2326
2327          strcpy(objDirExpNoSpaces, GetObjDirExpression(config));
2328          ChangeCh(objDirExpNoSpaces, '\\', '/'); // TODO: this is a hack, paths should never include win32 path seperators - fix this in ProjectSettings and ProjectLoad instead
2329          ReplaceSpaces(objDirExpNoSpaces, objDirExpNoSpaces);
2330          ReplaceSpaces(resDirNoSpaces, resNode.path ? resNode.path : "");
2331          ReplaceSpaces(fixedModuleName, moduleName);
2332          ReplaceSpaces(fixedConfigName, GetConfigName(config));
2333          CamelCase(fixedConfigName);
2334
2335          sameObjTargetDirs = !fstrcmp(objDirExpNoSpaces, targetDirExpNoSpaces);
2336
2337          f.Printf(".PHONY: all objdir%s cleantarget clean realclean distclean\n\n", sameObjTargetDirs ? "" : " targetdir");
2338
2339          f.Puts("# CORE VARIABLES\n\n");
2340
2341          f.Printf("MODULE := %s\n", fixedModuleName);
2342          f.Printf("VERSION := %s\n", property::moduleVersion);
2343          f.Printf("CONFIG := %s\n", fixedConfigName);
2344          f.Puts("ifndef COMPILER\n" "COMPILER := default\n" "endif\n");
2345          f.Puts("\n");
2346
2347          test = GetTargetTypeIsSetByPlatform(config);
2348          if(test)
2349          {
2350             ifCount = 0;
2351             for(platform = (Platform)1; platform < Platform::enumSize; platform++)
2352             {
2353                TargetTypes targetType;
2354                PlatformOptions projectPOs, configPOs;
2355                MatchProjectAndConfigPlatformOptions(config, platform, &projectPOs, &configPOs);
2356                targetType = platformTargetType;
2357                if(targetType)
2358                {
2359                   if(ifCount)
2360                      f.Puts("else\n");
2361                   ifCount++;
2362                   f.Printf("ifdef %s\n", PlatformToMakefileTargetVariable(platform));
2363                   f.Printf("TARGET_TYPE = %s\n", TargetTypeToMakefileVariable(targetType));
2364                }
2365             }
2366             f.Puts("else\n");
2367          }
2368          f.Printf("TARGET_TYPE = %s\n", TargetTypeToMakefileVariable(targetType));
2369          if(test)
2370          {
2371             if(ifCount)
2372             {
2373                for(c = 0; c < ifCount; c++)
2374                   f.Puts("endif\n");
2375             }
2376          }
2377          f.Puts("\n");
2378
2379          f.Puts("# FLAGS\n\n");
2380
2381          f.Puts("ECFLAGS =\n");
2382          f.Puts("ifndef DEBIAN_PACKAGE\n" "CFLAGS =\n" "LDFLAGS =\n" "endif\n");
2383          f.Puts("PRJ_CFLAGS =\n");
2384          f.Puts("CECFLAGS =\n");
2385          f.Puts("OFLAGS =\n");
2386          f.Puts("LIBS =\n");
2387          f.Puts("\n");
2388
2389          f.Puts("ifdef DEBUG\n" "NOSTRIP := y\n" "endif\n");
2390          f.Puts("\n");
2391
2392          // Important: We cannot use this ifdef anymore, EXECUTABLE_TARGET is not yet defined. It's embedded in the crossplatform.mk EXECUTABLE
2393          //f.Puts("ifdef EXECUTABLE_TARGET\n");
2394          f.Printf("CONSOLE = %s\n", GetConsole(config) ? "-mconsole" : "-mwindows");
2395          //f.Puts("endif\n");
2396          f.Puts("\n");
2397
2398          f.Puts("# INCLUDES\n\n");
2399
2400          if(compilerConfigsDir && compilerConfigsDir[0])
2401          {
2402             strcpy(cfDir, compilerConfigsDir);
2403             if(cfDir && cfDir[0] && cfDir[strlen(cfDir)-1] != '/')
2404                strcat(cfDir, "/");
2405          }
2406          else
2407          {
2408             GetIDECompilerConfigsDir(cfDir, true, true);
2409             // Use CF_DIR environment variable for absolute paths only
2410             if(cfDir[0] == '/' || (cfDir[0] && cfDir[1] == ':'))
2411                strcpy(cfDir, "$(CF_DIR)");
2412          }
2413
2414          f.Printf("_CF_DIR = %s\n", cfDir);
2415          f.Puts("\n");
2416
2417          f.Printf("include %s\n", includemkPath ? includemkPath : "$(_CF_DIR)crossplatform.mk");
2418          f.Puts("include $(_CF_DIR)$(TARGET_PLATFORM)-$(COMPILER).cf\n");
2419          f.Puts("\n");
2420
2421          f.Puts("# POST-INCLUDES VARIABLES\n\n");
2422
2423          f.Printf("OBJ = %s%s\n", objDirExpNoSpaces, objDirExpNoSpaces[0] ? "/" : "");
2424          f.Puts("\n");
2425
2426          f.Printf("RES = %s%s\n", resDirNoSpaces, resDirNoSpaces[0] ? "/" : "");
2427          f.Puts("\n");
2428
2429          // test = GetTargetTypeIsSetByPlatform(config);
2430          {
2431             char target[MAX_LOCATION];
2432             char targetNoSpaces[MAX_LOCATION];
2433             if(test)
2434             {
2435                TargetTypes type;
2436                ifCount = 0;
2437                for(type = (TargetTypes)1; type < TargetTypes::enumSize; type++)
2438                {
2439                   if(type != targetType)
2440                   {
2441                      if(ifCount)
2442                         f.Puts("else\n");
2443                      ifCount++;
2444                      f.Printf("ifeq \"$(TARGET_TYPE)\" \"%s\"\n", TargetTypeToMakefileVariable(type));
2445
2446                      GetMakefileTargetFileName(type, target, config);
2447                      strcpy(targetNoSpaces, targetDir);
2448                      PathCatSlash(targetNoSpaces, target);
2449                      ReplaceSpaces(targetNoSpaces, targetNoSpaces);
2450                      f.Printf("TARGET = %s\n", targetNoSpaces);
2451                   }
2452                }
2453                f.Puts("else\n");
2454             }
2455             GetMakefileTargetFileName(targetType, target, config);
2456             strcpy(targetNoSpaces, targetDir);
2457             PathCatSlash(targetNoSpaces, target);
2458             ReplaceSpaces(targetNoSpaces, targetNoSpaces);
2459             f.Printf("TARGET = %s$(VER)\n", targetNoSpaces);
2460
2461             if(test)
2462             {
2463                if(ifCount)
2464                {
2465                   for(c = 0; c < ifCount; c++)
2466                      f.Puts("endif\n");
2467                }
2468             }
2469          }
2470          f.Puts("\n");
2471
2472          // Use something fixed here, to not cause Makefile differences across compilers...
2473          varStringLenDiffs["$(OBJ)"] = 30; // strlen("obj/memoryGuard.android.gcc-4.6.2") - 6;
2474          // varStringLenDiffs["$(OBJ)"] = strlen(objDirNoSpaces) - 6;
2475
2476          topNode.GenMakefileGetNameCollisionInfo(namesInfo, config);
2477
2478          {
2479             int c;
2480             char * map[5][2] = { { "COBJECTS", "C" }, { "SYMBOLS", "S" }, { "IMPORTS", "I" }, { "ECOBJECTS", "O" }, { "BOWLS", "B" } };
2481
2482             numCObjects = topNode.GenMakefilePrintNode(f, this, eCsources, namesInfo, listItems, config, null);
2483             if(numCObjects)
2484             {
2485                eCsourcesParts = OutputFileList(f, "_ECSOURCES", listItems, varStringLenDiffs, null);
2486
2487                f.Puts("ECSOURCES = $(call shwspace,$(_ECSOURCES))\n");
2488                if(eCsourcesParts > 1)
2489                {
2490                   for(c = 1; c <= eCsourcesParts; c++)
2491                      f.Printf("ECSOURCES%d = $(call shwspace,$(_ECSOURCES%d))\n", c, c);
2492                }
2493                f.Puts("\n");
2494
2495                for(c = 0; c < 5; c++)
2496                {
2497                   if(eCsourcesParts > 1)
2498                   {
2499                      int n;
2500                      f.Printf("%s =", map[c][0]);
2501                      for(n = 1; n <= eCsourcesParts; n++)
2502                         f.Printf(" $(%s%d)", map[c][0], n);
2503                      f.Puts("\n");
2504                      for(n = 1; n <= eCsourcesParts; n++)
2505                         f.Printf("%s%d = $(call shwspace,$(addprefix $(OBJ),$(patsubst %%.ec,%%$(%s),$(notdir $(_ECSOURCES%d)))))\n", map[c][0], n, map[c][1], n);
2506                   }
2507                   else if(eCsourcesParts == 1)
2508                      f.Printf("%s = $(call shwspace,$(addprefix $(OBJ),$(patsubst %%.ec,%%$(%s),$(notdir $(_ECSOURCES)))))\n", map[c][0], map[c][1]);
2509                   f.Puts("\n");
2510                }
2511             }
2512          }
2513
2514          numObjects = topNode.GenMakefilePrintNode(f, this, objects, namesInfo, listItems, config, &containsCXX);
2515          if(numObjects)
2516             objectsParts = OutputFileList(f, "_OBJECTS", listItems, varStringLenDiffs, null);
2517          f.Printf("OBJECTS =%s%s%s\n", numObjects ? " $(_OBJECTS)" : "", numCObjects ? " $(ECOBJECTS)" : "", numCObjects ? " $(OBJ)$(MODULE).main$(O)" : "");
2518          f.Puts("\n");
2519
2520          topNode.GenMakefilePrintNode(f, this, sources, null, listItems, config, null);
2521          OutputFileList(f, "SOURCES", listItems, varStringLenDiffs, numCObjects ? "$(ECSOURCES)" : null);
2522
2523          if(!noResources)
2524             resNode.GenMakefilePrintNode(f, this, resources, null, listItems, config, null);
2525          OutputFileList(f, "RESOURCES", listItems, varStringLenDiffs, null);
2526
2527          f.Puts("LIBS += $(SHAREDLIB) $(EXECUTABLE) $(LINKOPT)\n");
2528          f.Puts("\n");
2529          if((config && config.options && config.options.libraries) ||
2530                (options && options.libraries))
2531          {
2532             f.Puts("ifndef STATIC_LIBRARY_TARGET\n");
2533             f.Puts("LIBS +=");
2534             if(config && config.options && config.options.libraries)
2535                OutputLibraries(f, config.options.libraries);
2536             else if(options && options.libraries)
2537                OutputLibraries(f, options.libraries);
2538             f.Puts("\n");
2539             f.Puts("endif\n");
2540             f.Puts("\n");
2541          }
2542
2543          topNode.GenMakeCollectAssignNodeFlags(config, numCObjects,
2544                cflagsVariations, nodeCFlagsMapping,
2545                ecflagsVariations, nodeECFlagsMapping, null);
2546
2547          GenMakePrintCustomFlags(f, "PRJ_CFLAGS", false, cflagsVariations);
2548          GenMakePrintCustomFlags(f, "ECFLAGS", true, ecflagsVariations);
2549
2550          if(platforms || (config && config.platforms))
2551          {
2552             ifCount = 0;
2553             //for(platform = firstPlatform; platform <= lastPlatform; platform++)
2554             //for(platform = win32; platform <= apple; platform++)
2555
2556             f.Puts("# PLATFORM-SPECIFIC OPTIONS\n\n");
2557             for(platform = (Platform)1; platform < Platform::enumSize; platform++)
2558             {
2559                PlatformOptions projectPlatformOptions, configPlatformOptions;
2560                MatchProjectAndConfigPlatformOptions(config, platform, &projectPlatformOptions, &configPlatformOptions);
2561
2562                if(projectPlatformOptions || configPlatformOptions)
2563                {
2564                   if(ifCount)
2565                      f.Puts("else\n");
2566                   ifCount++;
2567                   f.Printf("ifdef %s\n", PlatformToMakefileTargetVariable(platform));
2568                   f.Puts("\n");
2569
2570                   if((projectPlatformOptions && projectPlatformOptions.options.linkerOptions && projectPlatformOptions.options.linkerOptions.count) ||
2571                      (configPlatformOptions && configPlatformOptions.options.linkerOptions && configPlatformOptions.options.linkerOptions.count))
2572                   {
2573                      f.Puts("OFLAGS +=");
2574                      if(projectPlatformOptions && projectPlatformOptions.options.linkerOptions && projectPlatformOptions.options.linkerOptions.count)
2575                      {
2576                         bool needWl = false;
2577                         f.Puts(" \\\n\t ");
2578                         for(s : projectPlatformOptions.options.linkerOptions)
2579                         {
2580                            if(!IsLinkerOption(s))
2581                               f.Printf(" %s", s);
2582                            else
2583                               needWl = true;
2584                         }
2585                         if(needWl)
2586                         {
2587                            f.Puts(" -Wl");
2588                            for(s : projectPlatformOptions.options.linkerOptions)
2589                               if(IsLinkerOption(s))
2590                                  f.Printf(",%s", s);
2591                         }
2592                      }
2593                      if(configPlatformOptions && configPlatformOptions.options.linkerOptions && configPlatformOptions.options.linkerOptions.count)
2594                      {
2595                         bool needWl = false;
2596                         f.Puts(" \\\n\t ");
2597                         for(s : configPlatformOptions.options.linkerOptions)
2598                         {
2599                            if(IsLinkerOption(s))
2600                               f.Printf(" %s", s);
2601                            else
2602                               needWl = true;
2603                         }
2604                         if(needWl)
2605                         {
2606                            f.Puts(" -Wl");
2607                            for(s : configPlatformOptions.options.linkerOptions)
2608                               if(!IsLinkerOption(s))
2609                                  f.Printf(",%s", s);
2610                         }
2611                      }
2612                      f.Puts("\n");
2613                      f.Puts("\n");
2614                   }
2615
2616                   if((projectPlatformOptions && projectPlatformOptions.options.libraryDirs && projectPlatformOptions.options.libraryDirs.count) ||
2617                         (configPlatformOptions && configPlatformOptions.options.libraryDirs && configPlatformOptions.options.libraryDirs.count) ||
2618                         (projectPlatformOptions && projectPlatformOptions.options.libraries && projectPlatformOptions.options.libraries.count) ||
2619                         (configPlatformOptions && configPlatformOptions.options.libraries && configPlatformOptions.options.libraries.count))
2620                   {
2621                      f.Puts("ifndef STATIC_LIBRARY_TARGET\n");
2622                      if((projectPlatformOptions && projectPlatformOptions.options.libraryDirs && projectPlatformOptions.options.libraryDirs.count) ||
2623                         (configPlatformOptions && configPlatformOptions.options.libraryDirs && configPlatformOptions.options.libraryDirs.count))
2624                      {
2625                         f.Puts("OFLAGS +=");
2626                         if(configPlatformOptions && configPlatformOptions.options.libraryDirs)
2627                            OutputListOption(f, "L", configPlatformOptions.options.libraryDirs, lineEach, true);
2628                         if(projectPlatformOptions && projectPlatformOptions.options.libraryDirs)
2629                            OutputListOption(f, "L", projectPlatformOptions.options.libraryDirs, lineEach, true);
2630                         f.Puts("\n");
2631                      }
2632
2633                      if((configPlatformOptions && configPlatformOptions.options.libraries))
2634                      {
2635                         if(configPlatformOptions.options.libraries.count)
2636                         {
2637                            f.Puts("LIBS +=");
2638                            OutputLibraries(f, configPlatformOptions.options.libraries);
2639                            f.Puts("\n");
2640                         }
2641                      }
2642                      else if(projectPlatformOptions && projectPlatformOptions.options.libraries)
2643                      {
2644                         if(projectPlatformOptions.options.libraries.count)
2645                         {
2646                            f.Puts("LIBS +=");
2647                            OutputLibraries(f, projectPlatformOptions.options.libraries);
2648                            f.Puts("\n");
2649                         }
2650                      }
2651                      f.Puts("endif\n");
2652                      f.Puts("\n");
2653                   }
2654                }
2655             }
2656             if(ifCount)
2657             {
2658                for(c = 0; c < ifCount; c++)
2659                   f.Puts("endif\n");
2660             }
2661             f.Puts("\n");
2662          }
2663
2664          if((config && config.options && config.options.linkerOptions && config.options.linkerOptions.count) ||
2665                (options && options.linkerOptions && options.linkerOptions.count))
2666          {
2667             f.Puts("OFLAGS +=");
2668             f.Puts(" \\\n\t");
2669
2670             if(config && config.options && config.options.linkerOptions && config.options.linkerOptions.count)
2671             {
2672                bool needWl = false;
2673                for(s : config.options.linkerOptions)
2674                {
2675                   if(!IsLinkerOption(s))
2676                      f.Printf(" %s", s);
2677                   else
2678                      needWl = true;
2679                }
2680                if(needWl)
2681                {
2682                   f.Puts(" -Wl");
2683                   for(s : config.options.linkerOptions)
2684                      if(IsLinkerOption(s))
2685                         f.Printf(",%s", s);
2686                }
2687             }
2688             if(options && options.linkerOptions && options.linkerOptions.count)
2689             {
2690                bool needWl = false;
2691                for(s : options.linkerOptions)
2692                {
2693                   if(!IsLinkerOption(s))
2694                      f.Printf(" %s", s);
2695                   else
2696                      needWl = true;
2697                }
2698                if(needWl)
2699                {
2700                   f.Puts(" -Wl");
2701                   for(s : options.linkerOptions)
2702                      if(IsLinkerOption(s))
2703                         f.Printf(",%s", s);
2704                }
2705             }
2706          }
2707          f.Puts("\n");
2708          f.Puts("\n");
2709
2710          f.Puts("CECFLAGS += -cpp $(_CPP)");
2711          f.Puts("\n");
2712          f.Puts("\n");
2713
2714          if(GetProfile(config))
2715             f.Puts("OFLAGS += -pg\n\n");
2716
2717          if((config && config.options && config.options.libraryDirs) || (options && options.libraryDirs))
2718          {
2719             f.Puts("ifndef STATIC_LIBRARY_TARGET\n");
2720             f.Puts("OFLAGS +=");
2721             if(config && config.options && config.options.libraryDirs)
2722                OutputListOption(f, "L", config.options.libraryDirs, lineEach, true);
2723             if(options && options.libraryDirs)
2724                OutputListOption(f, "L", options.libraryDirs, lineEach, true);
2725             f.Puts("\n");
2726             f.Puts("endif\n");
2727             f.Puts("\n");
2728          }
2729
2730          f.Puts("# TARGETS\n");
2731          f.Puts("\n");
2732
2733          f.Printf("all: objdir%s $(TARGET)\n", sameObjTargetDirs ? "" : " targetdir");
2734          f.Puts("\n");
2735
2736          f.Puts("objdir:\n");
2737             f.Puts("\t$(if $(wildcard $(OBJ)),,$(call mkdirq,$(OBJ)))\n");
2738          //f.Puts("# PRE-BUILD COMMANDS\n");
2739          if(options && options.prebuildCommands)
2740          {
2741             for(s : options.prebuildCommands)
2742                if(s && s[0]) f.Printf("\t%s\n", s);
2743          }
2744          if(config && config.options && config.options.prebuildCommands)
2745          {
2746             for(s : config.options.prebuildCommands)
2747                if(s && s[0]) f.Printf("\t%s\n", s);
2748          }
2749          if(platforms || (config && config.platforms))
2750          {
2751             ifCount = 0;
2752             //f.Puts("# TARGET_PLATFORM-SPECIFIC PRE-BUILD COMMANDS\n");
2753             for(platform = (Platform)1; platform < Platform::enumSize; platform++)
2754             {
2755                PlatformOptions projectPOs, configPOs;
2756                MatchProjectAndConfigPlatformOptions(config, platform, &projectPOs, &configPOs);
2757
2758                if((projectPOs && projectPOs.options.prebuildCommands && projectPOs.options.prebuildCommands.count) ||
2759                      (configPOs && configPOs.options.prebuildCommands && configPOs.options.prebuildCommands.count))
2760                {
2761                   if(ifCount)
2762                      f.Puts("else\n");
2763                   ifCount++;
2764                   f.Printf("ifdef %s\n", PlatformToMakefileTargetVariable(platform));
2765
2766                   if(projectPOs && projectPOs.options.prebuildCommands && projectPOs.options.prebuildCommands.count)
2767                   {
2768                      for(s : projectPOs.options.prebuildCommands)
2769                         if(s && s[0]) f.Printf("\t%s\n", s);
2770                   }
2771                   if(configPOs && configPOs.options.prebuildCommands && configPOs.options.prebuildCommands.count)
2772                   {
2773                      for(s : configPOs.options.prebuildCommands)
2774                         if(s && s[0]) f.Printf("\t%s\n", s);
2775                   }
2776                }
2777             }
2778             if(ifCount)
2779             {
2780                int c;
2781                for(c = 0; c < ifCount; c++)
2782                   f.Puts("endif\n");
2783             }
2784          }
2785          f.Puts("\n");
2786
2787          if(!sameObjTargetDirs)
2788          {
2789             f.Puts("targetdir:\n");
2790                f.Printf("\t$(if $(wildcard %s),,$(call mkdirq,%s))\n", targetDirExpNoSpaces, targetDirExpNoSpaces);
2791             f.Puts("\n");
2792          }
2793
2794          if(numCObjects)
2795          {
2796             // Main Module (Linking) for ECERE C modules
2797             f.Puts("$(OBJ)$(MODULE).main.ec: $(SYMBOLS) $(COBJECTS)\n");
2798             // use of objDirExpNoSpaces used instead of $(OBJ) to prevent problematic joining of arguments in ecs
2799             f.Printf("\t$(ECS)%s $(ARCH_FLAGS) $(ECSLIBOPT) $(SYMBOLS) $(IMPORTS) -symbols %s -o $(OBJ)$(MODULE).main.ec\n", 
2800                GetConsole(config) ? " -console" : "", objDirExpNoSpaces);
2801             f.Puts("\n");
2802             // Main Module (Linking) for ECERE C modules
2803             f.Puts("$(OBJ)$(MODULE).main.c: $(OBJ)$(MODULE).main.ec\n");
2804             f.Puts("\t$(ECP) $(CFLAGS) $(CECFLAGS) $(ECFLAGS) $(PRJ_CFLAGS)"
2805                   " -c $(OBJ)$(MODULE).main.ec -o $(OBJ)$(MODULE).main.sym -symbols $(OBJ)\n");
2806             f.Puts("\t$(ECC) $(CFLAGS) $(CECFLAGS) $(ECFLAGS) $(PRJ_CFLAGS) $(FVISIBILITY)"
2807                   " -c $(OBJ)$(MODULE).main.ec -o $(OBJ)$(MODULE).main.c -symbols $(OBJ)\n");
2808             f.Puts("\n");
2809          }
2810
2811          // *** Target ***
2812
2813          // This would not rebuild the target on updated objects
2814          // f.Printf("$(TARGET): $(SOURCES) $(RESOURCES) | objdir $(SYMBOLS) $(OBJECTS)%s\n", sameObjTargetDirs ? "" : " targetdir");
2815
2816          // This should fix it for good!
2817          f.Puts("$(SYMBOLS): | objdir\n");
2818          f.Puts("$(OBJECTS): | objdir\n");
2819
2820          // This alone was breaking the tarball, object directory does not get created first (order-only rules happen last it seems!)
2821          f.Printf("$(TARGET): $(SOURCES) $(RESOURCES) $(SYMBOLS) $(OBJECTS) | objdir%s\n", sameObjTargetDirs ? "" : " targetdir");
2822
2823          f.Puts("ifndef STATIC_LIBRARY_TARGET\n");
2824          f.Printf("\t@$(call echo,$(OBJECTS)) > $(OBJ)linkobjects.lst\n");
2825          f.Printf("\t$(%s) $(OFLAGS) @$(OBJ)linkobjects.lst $(LIBS) %s-o $(TARGET) $(INSTALLNAME)\n", containsCXX ? "CXX" : "CC", containsCXX ? "-lstdc++ " : "");
2826          if(!GetDebug(config))
2827          {
2828             f.Puts("ifndef NOSTRIP\n");
2829             f.Puts("\t$(STRIP) $(STRIPOPT) $(TARGET)\n");
2830             f.Puts("endif\n");
2831
2832             if(GetCompress(config))
2833             {
2834                f.Printf("ifndef %s\n", PlatformToMakefileTargetVariable(win32));
2835                f.Puts("ifdef EXECUTABLE_TARGET\n");
2836                   f.Puts("\t$(UPX) $(UPXFLAGS) $(TARGET)\n");
2837                f.Puts("endif\n");
2838                f.Puts("else\n");
2839                   f.Puts("\t$(UPX) $(UPXFLAGS) $(TARGET)\n");
2840                f.Puts("endif\n");
2841             }
2842          }
2843          if(resNode.files && resNode.files.count && !noResources)
2844             resNode.GenMakefileAddResources(f, resNode.path, config);
2845          f.Puts("else\n");
2846          f.Puts("\t$(AR) rcs $(TARGET) $(OBJECTS) $(LIBS)\n");
2847          f.Puts("endif\n");
2848          f.Puts("ifdef SHARED_LIBRARY_TARGET\n");
2849          f.Puts("ifdef LINUX_TARGET\n");
2850          // TODO?: support symlinks for longer version numbers
2851          f.Puts("\t$(if $(basename $(VER)),ln -sf $(LP)$(MODULE)$(SO)$(VER) $(OBJ)$(LP)$(MODULE)$(SO)$(basename $(VER)),)\n");
2852          f.Puts("\t$(if $(VER),ln -sf $(LP)$(MODULE)$(SO)$(VER) $(OBJ)$(LP)$(MODULE)$(SO),)\n");
2853          f.Puts("endif\n");
2854          f.Puts("endif\n");
2855
2856          //f.Puts("# POST-BUILD COMMANDS\n");
2857          if(options && options.postbuildCommands)
2858          {
2859             for(s : options.postbuildCommands)
2860                if(s && s[0]) f.Printf("\t%s\n", s);
2861          }
2862          if(config && config.options && config.options.postbuildCommands)
2863          {
2864             for(s : config.options.postbuildCommands)
2865                if(s && s[0]) f.Printf("\t%s\n", s);
2866          }
2867          if(platforms || (config && config.platforms))
2868          {
2869             ifCount = 0;
2870             //f.Puts("# TARGET_PLATFORM-SPECIFIC POST-BUILD COMMANDS\n");
2871             for(platform = (Platform)1; platform < Platform::enumSize; platform++)
2872             {
2873                PlatformOptions projectPOs, configPOs;
2874                MatchProjectAndConfigPlatformOptions(config, platform, &projectPOs, &configPOs);
2875
2876                if((projectPOs && projectPOs.options.postbuildCommands && projectPOs.options.postbuildCommands.count) ||
2877                      (configPOs && configPOs.options.postbuildCommands && configPOs.options.postbuildCommands.count))
2878                {
2879                   if(ifCount)
2880                      f.Puts("else\n");
2881                   ifCount++;
2882                   f.Printf("ifdef %s\n", PlatformToMakefileTargetVariable(platform));
2883
2884                   if(projectPOs && projectPOs.options.postbuildCommands && projectPOs.options.postbuildCommands.count)
2885                   {
2886                      for(s : projectPOs.options.postbuildCommands)
2887                         if(s && s[0]) f.Printf("\t%s\n", s);
2888                   }
2889                   if(configPOs && configPOs.options.postbuildCommands && configPOs.options.postbuildCommands.count)
2890                   {
2891                      for(s : configPOs.options.postbuildCommands)
2892                         if(s && s[0]) f.Printf("\t%s\n", s);
2893                   }
2894                }
2895             }
2896             if(ifCount)
2897             {
2898                int c;
2899                for(c = 0; c < ifCount; c++)
2900                   f.Puts("endif\n");
2901             }
2902          }
2903          f.Puts("\n");
2904
2905          f.Puts("# SYMBOL RULES\n");
2906          f.Puts("\n");
2907
2908          topNode.GenMakefilePrintSymbolRules(f, this, config, nodeCFlagsMapping, nodeECFlagsMapping);
2909
2910          f.Puts("# C OBJECT RULES\n");
2911          f.Puts("\n");
2912
2913          topNode.GenMakefilePrintCObjectRules(f, this, config, nodeCFlagsMapping, nodeECFlagsMapping);
2914
2915          f.Puts("# OBJECT RULES\n");
2916          f.Puts("\n");
2917          // todo call this still but only generate rules whith specific options
2918          // see we-have-file-specific-options in ProjectNode.ec
2919          topNode.GenMakefilePrintObjectRules(f, this, namesInfo, config, nodeCFlagsMapping, nodeECFlagsMapping);
2920
2921          if(numCObjects)
2922             GenMakefilePrintMainObjectRule(f, config);
2923
2924          f.Printf("cleantarget: objdir%s\n", sameObjTargetDirs ? "" : " targetdir");
2925          f.Puts("\t$(call rmq,$(TARGET))\n");
2926          f.Puts("ifdef SHARED_LIBRARY_TARGET\n");
2927          f.Puts("ifdef LINUX_TARGET\n");
2928          // TODO?: support symlinks for longer version numbers
2929          f.Puts("\t$(call rmq,$(OBJ)$(LP)$(MODULE)$(SO)$(basename $(VER)))\n");
2930          f.Puts("\t$(call rmq,$(OBJ)$(LP)$(MODULE)$(SO))\n");
2931          f.Puts("endif\n");
2932          f.Puts("endif\n");
2933          f.Puts("\n");
2934
2935          f.Puts("clean: cleantarget\n");
2936          OutputCleanActions(f, "_OBJECTS", objectsParts);
2937          if(numCObjects)
2938          {
2939             f.Printf("\t$(call rmq,%s)\n", "$(OBJ)$(MODULE).main.o $(OBJ)$(MODULE).main.c $(OBJ)$(MODULE).main.ec $(OBJ)$(MODULE).main$(I) $(OBJ)$(MODULE).main$(S) $(OBJ)linkobjects.lst");
2940             OutputCleanActions(f, "ECOBJECTS", eCsourcesParts);
2941             OutputCleanActions(f, "COBJECTS", eCsourcesParts);
2942             OutputCleanActions(f, "BOWLS", eCsourcesParts);
2943             OutputCleanActions(f, "IMPORTS", eCsourcesParts);
2944             OutputCleanActions(f, "SYMBOLS", eCsourcesParts);
2945          }
2946          f.Puts("\n");
2947
2948          f.Puts("realclean: cleantarget\n");
2949          f.Puts("\t$(call rmrq,$(OBJ))\n");
2950          if(!sameObjTargetDirs)
2951             f.Printf("\t$(call rmdirq,%s)\n", targetDirExpNoSpaces);
2952          f.Puts("\n");
2953
2954          f.Puts("distclean: cleantarget\n");
2955          if(!sameObjTargetDirs)
2956             f.Printf("\t$(call rmdirq,%s)\n", targetDirExpNoSpaces);
2957          f.Puts("\t$(call rmrq,obj/)\n");
2958
2959          delete f;
2960
2961          listItems.Free();
2962          delete listItems;
2963          varStringLenDiffs.Free();
2964          delete varStringLenDiffs;
2965          namesInfo.Free();
2966          delete namesInfo;
2967
2968          delete cflagsVariations;
2969          delete nodeCFlagsMapping;
2970          delete ecflagsVariations;
2971          delete nodeECFlagsMapping;
2972
2973          result = true;
2974       }
2975
2976       // ChangeWorkingDir(oldDirectory);
2977       // delete pathBackup;
2978
2979       if(config)
2980          config.makingModified = false;
2981       return result;
2982    }
2983
2984    void GenMakefilePrintMainObjectRule(File f, ProjectConfig config)
2985    {
2986       char extension[MAX_EXTENSION] = "c";
2987       char modulePath[MAX_LOCATION];
2988       char fixedModuleName[MAX_FILENAME];
2989       DualPipe dep;
2990       char command[2048];
2991       char objDirNoSpaces[MAX_LOCATION];
2992       String objDirExp = GetObjDirExpression(config);
2993
2994       ReplaceSpaces(objDirNoSpaces, objDirExp);
2995       ReplaceSpaces(fixedModuleName, moduleName);
2996       
2997       //sprintf(fixedModuleName, "%s.main", fixedPrjName);
2998       //strcat(fixedModuleName, ".main");
2999
3000 #if 0       // TODO: Fix nospaces stuff
3001       // *** Dependency command ***
3002       sprintf(command, "gcc -MT $(OBJ)%s$(O) -MM $(OBJ)%s.c", fixedModuleName, fixedModuleName);
3003
3004       // System Includes (from global settings)
3005       for(item : compiler.dirs[Includes])
3006       {
3007          strcat(command, " -isystem ");
3008          if(strchr(item.name, ' '))
3009          {
3010             strcat(command, "\"");
3011             strcat(command, item);
3012             strcat(command, "\"");
3013          }
3014          else
3015             strcat(command, item);
3016       }
3017
3018       for(item = includeDirs.first; item; item = item.next)
3019       {
3020          strcat(command, " -I");
3021          if(strchr(item.name, ' '))
3022          {
3023             strcat(command, "\"");
3024             strcat(command, item.name);
3025             strcat(command, "\"");
3026          }
3027          else
3028             strcat(command, item.name);
3029       }
3030       for(item = preprocessorDefs.first; item; item = item.next)
3031       {
3032          strcat(command, " -D");
3033          strcat(command, item.name);
3034       }
3035
3036       // Execute it
3037       if((dep = DualPipeOpen(PipeOpenMode { output = 1, error = 1, input = 2 }, command)))
3038       {
3039          char line[1024];
3040          bool result = true;
3041          bool firstLine = true;
3042
3043          // To do some time: auto save external dependencies?
3044          while(!dep.Eof())
3045          {
3046             if(dep.GetLine(line, sizeof(line)-1))
3047             {
3048                if(firstLine)
3049                {
3050                   char * colon = strstr(line, ":");
3051                   if(strstr(line, "No such file") || strstr(line, ",") || (colon && strstr(colon+1, ":")))
3052                   {
3053                      result = false;
3054                      break;
3055                   }
3056                   firstLine = false;
3057                }
3058                f.Puts(line);
3059                f.Puts("\n");
3060             }
3061             if(!result) break;
3062          }
3063          delete dep;
3064
3065          // If we failed to generate dependencies...
3066          if(!result)
3067          {
3068 #endif
3069             f.Puts("$(OBJ)$(MODULE).main$(O): $(OBJ)$(MODULE).main.c\n");
3070             f.Printf("\t$(CC) $(CFLAGS) $(PRJ_CFLAGS) $(FVISIBILITY) -c $(OBJ)$(MODULE).main.%s -o $(OBJ)$(MODULE).main$(O)\n", extension);
3071             f.Puts("\n");
3072 #if 0
3073          }
3074       }
3075 #endif
3076    }
3077
3078    void GenMakePrintCustomFlags(File f, String variableName, bool printNonCustom, Map<String, int> cflagsVariations)
3079    {
3080       int c;
3081       for(c = printNonCustom ? 0 : 1; c <= cflagsVariations.count; c++)
3082       {
3083          for(v : cflagsVariations)
3084          {
3085             if(v == c)
3086             {
3087                if(v == 1)
3088                   f.Printf("%s +=", variableName);
3089                else
3090                   f.Printf("CUSTOM%d_%s =", v-1, variableName);
3091                f.Puts(&v ? &v : "");
3092                f.Puts("\n");
3093                f.Puts("\n");
3094                break;
3095             }
3096          }
3097       }
3098       f.Puts("\n");
3099    }
3100
3101    void MatchProjectAndConfigPlatformOptions(ProjectConfig config, Platform platform,
3102          PlatformOptions * projectPlatformOptions, PlatformOptions * configPlatformOptions)
3103    {
3104       *projectPlatformOptions = null;
3105       *configPlatformOptions = null;
3106       if(platforms)
3107       {
3108          for(p : platforms)
3109          {
3110             if(!strcmpi(p.name, platform))
3111             {
3112                *projectPlatformOptions = p;
3113                break;
3114             }
3115          }
3116       }
3117       if(config && config.platforms)
3118       {
3119          for(p : config.platforms)
3120          {
3121             if(!strcmpi(p.name, platform))
3122             {
3123                *configPlatformOptions = p;
3124                break;
3125             }
3126          }
3127       }
3128    }
3129 }
3130
3131 Project LegacyBinaryLoadProject(File f, char * filePath)
3132 {
3133    Project project = null;
3134    char signature[sizeof(epjSignature)];
3135
3136    f.Read(signature, sizeof(signature), 1);
3137    if(!strncmp(signature, (char *)epjSignature, sizeof(epjSignature)))
3138    {
3139       char topNodePath[MAX_LOCATION];
3140       /*ProjectConfig newConfig
3141       {
3142          name = CopyString("Default");
3143          makingModified = true;
3144          compilingModified = true;
3145          linkingModified = true;
3146          options = { };
3147       };*/
3148
3149       project = Project { options = { } };
3150       LegacyBinaryLoadNode(project.topNode, f);
3151       delete project.topNode.path;
3152       GetWorkingDir(topNodePath, sizeof(topNodePath)-1);
3153       MakeSlashPath(topNodePath);
3154
3155       PathCatSlash(topNodePath, filePath);
3156       project.filePath = topNodePath;
3157       
3158       /* THIS IS ALREADY DONE BY filePath property
3159       StripLastDirectory(topNodePath, topNodePath);
3160       project.topNode.path = CopyString(topNodePath);
3161       */
3162       // Shouldn't this be done BEFORE the StripLastDirectory? project.filePath = topNodePath;
3163       
3164       // newConfig.options.defaultNameSpace = "";
3165       /*newConfig.objDir.dir = "obj";
3166       newConfig.targetDir.dir = "";*/
3167
3168       //project.configurations = { [ newConfig ] };
3169       //project.config = newConfig;
3170
3171       // Project Settings
3172       if(!f.Eof())
3173       {
3174          int temp;
3175          int len,c, count;
3176          String targetFileName, targetDirectory, objectsDirectory;
3177
3178          // { executable = 0, sharedLibrary = 1, staticLibrary = 2 };
3179          f.Read(&temp, sizeof(int),1);
3180          switch(temp)
3181          {
3182             case 0: project.options.targetType = executable; break;
3183             case 1: project.options.targetType = sharedLibrary; break;
3184             case 2: project.options.targetType = staticLibrary; break;
3185          }
3186
3187          f.Read(&len, sizeof(int),1);
3188          targetFileName = new char[len+1];
3189          f.Read(targetFileName, sizeof(char), len+1);
3190          project.options.targetFileName = targetFileName;
3191          delete targetFileName;
3192
3193          f.Read(&len, sizeof(int),1);
3194          targetDirectory = new char[len+1];
3195          f.Read(targetDirectory, sizeof(char), len+1);
3196          project.options.targetDirectory = targetDirectory;
3197          delete targetDirectory;
3198
3199          f.Read(&len, sizeof(int),1);
3200          objectsDirectory = new byte[len+1];
3201          f.Read(objectsDirectory, sizeof(char), len+1);
3202          project.options.objectsDirectory = objectsDirectory;
3203          delete objectsDirectory;
3204
3205          f.Read(&temp, sizeof(int),1);
3206          project./*config.*/options.debug = temp ? true : false;
3207          f.Read(&temp, sizeof(int),1);         
3208          project./*config.*/options.optimization = temp ? speed : none;
3209          f.Read(&temp, sizeof(int),1);
3210          project./*config.*/options.profile = temp ? true : false;
3211          f.Read(&temp, sizeof(int),1);
3212          project.options.warnings = temp ? all : unset;
3213
3214          f.Read(&count, sizeof(int),1);
3215          if(count)
3216          {
3217             project.options.includeDirs = { };
3218             for(c = 0; c < count; c++)
3219             {
3220                char * name;
3221                f.Read(&len, sizeof(int),1);
3222                name = new char[len+1];
3223                f.Read(name, sizeof(char), len+1);
3224                project.options.includeDirs.Add(name);
3225             }
3226          }
3227
3228          f.Read(&count, sizeof(int),1);
3229          if(count)
3230          {
3231             project.options.libraryDirs = { };
3232             for(c = 0; c < count; c++)
3233             {
3234                char * name;            
3235                f.Read(&len, sizeof(int),1);
3236                name = new char[len+1];
3237                f.Read(name, sizeof(char), len+1);
3238                project.options.libraryDirs.Add(name);
3239             }
3240          }
3241
3242          f.Read(&count, sizeof(int),1);
3243          if(count)
3244          {
3245             project.options.libraries = { };
3246             for(c = 0; c < count; c++)
3247             {
3248                char * name;
3249                f.Read(&len, sizeof(int),1);
3250                name = new char[len+1];
3251                f.Read(name, sizeof(char), len+1);
3252                project.options.libraries.Add(name);
3253             }
3254          }
3255
3256          f.Read(&count, sizeof(int),1);
3257          if(count)
3258          {
3259             project.options.preprocessorDefinitions = { };
3260             for(c = 0; c < count; c++)
3261             {
3262                char * name;
3263                f.Read(&len, sizeof(int),1);
3264                name = new char[len+1];
3265                f.Read(name, sizeof(char), len+1);
3266                project.options.preprocessorDefinitions.Add(name);
3267             }
3268          }
3269
3270          f.Read(&temp, sizeof(int),1);
3271          project.options.console = temp ? true : false;
3272       }
3273
3274       for(node : project.topNode.files)
3275       {
3276          if(node.type == resources)
3277          {
3278             project.resNode = node;
3279             break;
3280          }
3281       }
3282    }
3283    else
3284       f.Seek(0, start);
3285    return project;
3286 }
3287
3288 void ProjectConfig::LegacyProjectConfigLoad(File f)
3289 {  
3290    delete options;
3291    options = { };
3292    while(!f.Eof())
3293    {
3294       char buffer[65536];
3295       char section[128];
3296       char subSection[128];
3297       char * equal;
3298       int len;
3299       uint pos;
3300       
3301       pos = f.Tell();
3302       f.GetLine(buffer, 65536 - 1);
3303       TrimLSpaces(buffer, buffer);
3304       TrimRSpaces(buffer, buffer);
3305       if(strlen(buffer))
3306       {
3307          if(buffer[0] == '-')
3308          {
3309             equal = &buffer[0];
3310             equal[0] = ' ';
3311             TrimLSpaces(equal, equal);
3312             if(!strcmpi(subSection, "LibraryDirs"))
3313             {
3314                if(!options.libraryDirs)
3315                   options.libraryDirs = { [ CopyString(equal) ] };
3316                else
3317                   options.libraryDirs.Add(CopyString(equal));
3318             }
3319             else if(!strcmpi(subSection, "IncludeDirs"))
3320             {
3321                if(!options.includeDirs)
3322                   options.includeDirs = { [ CopyString(equal) ] };
3323                else
3324                   options.includeDirs.Add(CopyString(equal));
3325             }
3326          }
3327          else if(buffer[0] == '+')
3328          {
3329             if(name)
3330             {
3331                f.Seek(pos, start);
3332                break;
3333             }
3334             else
3335             {
3336                equal = &buffer[0];
3337                equal[0] = ' ';
3338                TrimLSpaces(equal, equal);
3339                delete name; name = CopyString(equal); // property::name = equal;
3340             }
3341          }
3342          else if(!strcmpi(buffer, "Compiler Options"))
3343             strcpy(section, buffer);
3344          else if(!strcmpi(buffer, "IncludeDirs"))
3345             strcpy(subSection, buffer);
3346          else if(!strcmpi(buffer, "Linker Options"))
3347             strcpy(section, buffer);
3348          else if(!strcmpi(buffer, "LibraryDirs"))
3349             strcpy(subSection, buffer);
3350          else if(!strcmpi(buffer, "Files") || !strcmpi(buffer, "Resources"))
3351          {
3352             f.Seek(pos, start);
3353             break;
3354          }
3355          else
3356          {
3357             equal = strstr(buffer, "=");
3358             if(equal)
3359             {
3360                equal[0] = '\0';
3361                TrimRSpaces(buffer, buffer);
3362                equal++;
3363                TrimLSpaces(equal, equal);
3364                if(!strcmpi(buffer, "Target Name"))
3365                   options.targetFileName = /*CopyString(*/equal/*)*/;
3366                else if(!strcmpi(buffer, "Target Type"))
3367                {
3368                   if(!strcmpi(equal, "Executable"))
3369                      options.targetType = executable;
3370                   else if(!strcmpi(equal, "Shared"))
3371                      options.targetType = sharedLibrary;
3372                   else if(!strcmpi(equal, "Static"))
3373                      options.targetType = staticLibrary;
3374                   else
3375                      options.targetType = executable;
3376                }
3377                else if(!strcmpi(buffer, "Target Directory"))
3378                   options.targetDirectory = /*CopyString(*/equal/*)*/;
3379                else if(!strcmpi(buffer, "Console"))
3380                   options.console = ParseTrueFalseValue(equal);
3381                else if(!strcmpi(buffer, "Libraries"))
3382                {
3383                   if(!options.libraries) options.libraries = { };
3384                   ParseArrayValue(options.libraries, equal);
3385                }
3386                else if(!strcmpi(buffer, "Intermediate Directory"))
3387                   options.objectsDirectory = /*CopyString(*/equal/*)*/; //objDir.expression = equal;
3388                else if(!strcmpi(buffer, "Debug"))
3389                   options.debug = ParseTrueFalseValue(equal);
3390                else if(!strcmpi(buffer, "Optimize"))
3391                {
3392                   if(!strcmpi(equal, "None"))
3393                      options.optimization = none;
3394                   else if(!strcmpi(equal, "Speed") || !strcmpi(equal, "True"))
3395                      options.optimization = speed;
3396                   else if(!strcmpi(equal, "Size"))
3397                      options.optimization = size;
3398                   else
3399                      options.optimization = none;
3400                }
3401                else if(!strcmpi(buffer, "Compress"))
3402                   options.compress = ParseTrueFalseValue(equal);
3403                else if(!strcmpi(buffer, "Profile"))
3404                   options.profile = ParseTrueFalseValue(equal);
3405                else if(!strcmpi(buffer, "AllWarnings"))
3406                   options.warnings = ParseTrueFalseValue(equal) ? all : unset;
3407                else if(!strcmpi(buffer, "MemoryGuard"))
3408                   options.memoryGuard = ParseTrueFalseValue(equal);
3409                else if(!strcmpi(buffer, "Default Name Space"))
3410                   options.defaultNameSpace = CopyString(equal);
3411                else if(!strcmpi(buffer, "Strict Name Spaces"))
3412                   options.strictNameSpaces = ParseTrueFalseValue(equal);
3413                else if(!strcmpi(buffer, "Preprocessor Definitions"))
3414                {
3415                   if(!options.preprocessorDefinitions) options.preprocessorDefinitions = { };
3416                   ParseArrayValue(options.preprocessorDefinitions, equal);
3417                }
3418             }
3419          }
3420       }
3421    }
3422    if(!options.targetDirectory && options.objectsDirectory)
3423       options.targetDirectory = /*CopyString(*/options.objectsDirectory/*)*/;
3424    //if(!objDir.dir) objDir.dir = "obj";
3425    //if(!targetDir.dir) targetDir.dir = "";
3426    // if(!targetName) property::targetName = "";   // How can a targetFileName be nothing???
3427    // if(!defaultNameSpace) property::defaultNameSpace = "";
3428    makingModified = true;
3429 }
3430
3431 Project LegacyAsciiLoadProject(File f, char * filePath)
3432 {
3433    Project project = null;
3434    ProjectNode node = null;
3435    int pos;
3436    char parentPath[MAX_LOCATION];
3437    char section[128] = "";
3438    char subSection[128] = "";
3439    ProjectNode parent;
3440    bool configurationsPresent = false;
3441
3442    f.Seek(0, start);
3443    while(!f.Eof())
3444    {
3445       char buffer[65536];
3446       //char version[16];
3447       char * equal;
3448       int len;
3449       pos = f.Tell();
3450       f.GetLine(buffer, 65536 - 1);
3451       TrimLSpaces(buffer, buffer);
3452       TrimRSpaces(buffer, buffer);
3453       if(strlen(buffer))
3454       {
3455          if(buffer[0] == '-' || buffer[0] == '=')
3456          {
3457             bool simple = buffer[0] == '-';
3458             equal = &buffer[0];
3459             equal[0] = ' ';
3460             TrimLSpaces(equal, equal);
3461             if(!strcmpi(section, "Target") && !strcmpi(subSection, "LibraryDirs"))
3462             {
3463                if(!project.config.options.libraryDirs)
3464                   project.config.options.libraryDirs = { [ CopyString(equal) ] };
3465                else
3466                   project.config.options.libraryDirs.Add(CopyString(equal));
3467             }
3468             else if(!strcmpi(section, "Target") && !strcmpi(subSection, "IncludeDirs"))
3469             {
3470                if(!project.config.options.includeDirs)
3471                   project.config.options.includeDirs = { [ CopyString(equal) ] };
3472                else
3473                   project.config.options.includeDirs.Add(CopyString(equal));
3474             }
3475             else if(!strcmpi(section, "Target") && (!strcmpi(subSection, "Files") || !strcmpi(subSection, "Resources")))
3476             {
3477                len = strlen(equal);
3478                if(len)
3479                {
3480                   char temp[MAX_LOCATION];
3481                   ProjectNode child { };
3482                   // We don't need to do this anymore, fileName is just a property that sets name & path
3483                   // child.fileName = CopyString(equal);
3484                   if(simple)
3485                   {
3486                      child.name = CopyString(equal);
3487                      child.path = CopyString(parentPath);
3488                   }
3489                   else
3490                   {
3491                      GetLastDirectory(equal, temp);
3492                      child.name = CopyString(temp);
3493                      StripLastDirectory(equal, temp);
3494                      child.path = CopyString(temp);
3495                   }
3496                   child.nodeType = file;
3497                   child.parent = parent;
3498                   child.indent = parent.indent + 1;
3499                   child.type = file;
3500                   child.icon = NodeIcons::SelectFileIcon(child.name);
3501                   parent.files.Add(child);
3502                   node = child;
3503                   //child = null;
3504                }
3505                else
3506                {
3507                   StripLastDirectory(parentPath, parentPath);
3508                   parent = parent.parent;
3509                }
3510             }
3511          }
3512          else if(buffer[0] == '+')
3513          {
3514             equal = &buffer[0];
3515             equal[0] = ' ';
3516             TrimLSpaces(equal, equal);
3517             if(!strcmpi(section, "Target") && (!strcmpi(subSection, "Files") || !strcmpi(subSection, "Resources")))
3518             {
3519                char temp[MAX_LOCATION];
3520                ProjectNode child { };
3521                // NEW: Folders now have a path set like files
3522                child.name = CopyString(equal);
3523                strcpy(temp, parentPath);
3524                PathCatSlash(temp, child.name);
3525                child.path = CopyString(temp);
3526
3527                child.parent = parent;
3528                child.indent = parent.indent + 1;
3529                child.type = folder;
3530                child.nodeType = folder;
3531                child.files = { };
3532                child.icon = folder;
3533                PathCatSlash(parentPath, child.name);
3534                parent.files.Add(child);
3535                parent = child;
3536                node = child;
3537                //child = null;
3538             }
3539             else if(!strcmpi(section, "Configurations"))
3540             {
3541                ProjectConfig newConfig
3542                {
3543                   makingModified = true;
3544                   options = { };
3545                };
3546                f.Seek(pos, start);
3547                LegacyProjectConfigLoad(newConfig, f);
3548                project.configurations.Add(newConfig);
3549             }
3550          }
3551          else if(!strcmpi(buffer, "ECERE Project File"));
3552          else if(!strcmpi(buffer, "Version 0a"))
3553             ; //strcpy(version, "0a");
3554          else if(!strcmpi(buffer, "Version 0.1a"))
3555             ; //strcpy(version, "0.1a");
3556          else if(!strcmpi(buffer, "Configurations"))
3557          {
3558             project.configurations.Free();
3559             project.config = null;
3560             strcpy(section, buffer);
3561             configurationsPresent = true;
3562          }
3563          else if(!strcmpi(buffer, "Target") || !strnicmp(buffer, "Target \"", strlen("Target \"")))
3564          {
3565             ProjectConfig newConfig { name = CopyString("Default"), options = { } };
3566             char topNodePath[MAX_LOCATION];
3567             // newConfig.defaultNameSpace = "";
3568             //newConfig.objDir.dir = "obj";
3569             //newConfig.targetDir.dir = "";
3570             project = Project { /*options = { }*/ };
3571             project.configurations = { [ newConfig ] };
3572             project.config = newConfig;
3573             // if(project.topNode.path) delete project.topNode.path;
3574             GetWorkingDir(topNodePath, sizeof(topNodePath)-1);
3575             MakeSlashPath(topNodePath);
3576             PathCatSlash(topNodePath, filePath);
3577             project.filePath = topNodePath;
3578             parentPath[0] = '\0';
3579             parent = project.topNode;
3580             node = parent;
3581             strcpy(section, "Target");
3582             equal = &buffer[6];
3583             if(equal[0] == ' ')
3584             {
3585                equal++;
3586                if(equal[0] == '\"')
3587                {
3588                   StripQuotes(equal, equal);
3589                   delete project.moduleName; project.moduleName = CopyString(equal);
3590                }
3591             }
3592          }
3593          else if(!strcmpi(buffer, "Compiler Options"));
3594          else if(!strcmpi(buffer, "IncludeDirs"))
3595             strcpy(subSection, buffer);
3596          else if(!strcmpi(buffer, "Linker Options"));
3597          else if(!strcmpi(buffer, "LibraryDirs"))
3598             strcpy(subSection, buffer);
3599          else if(!strcmpi(buffer, "Files"))
3600          {
3601             strcpy(section, "Target");
3602             strcpy(subSection, buffer);
3603          }
3604          else if(!strcmpi(buffer, "Resources"))
3605          {
3606             ProjectNode child { };
3607             parent.files.Add(child);
3608             child.parent = parent;
3609             child.indent = parent.indent + 1;
3610             child.name = CopyString(buffer);
3611             child.path = CopyString("");
3612             child.type = resources;
3613             child.files = { };
3614             child.icon = archiveFile;
3615             project.resNode = child;
3616             parent = child;
3617             node = child;
3618             strcpy(subSection, buffer);
3619          }
3620          else
3621          {
3622             equal = strstr(buffer, "=");
3623             if(equal)
3624             {
3625                equal[0] = '\0';
3626                TrimRSpaces(buffer, buffer);
3627                equal++;
3628                TrimLSpaces(equal, equal);
3629
3630                if(!strcmpi(section, "Target"))
3631                {
3632                   if(!strcmpi(buffer, "Build Exclusions"))
3633                   {
3634                      if(!strcmpi(section, "Target") && !strcmpi(subSection, "Files"))
3635                      {
3636                         /*if(node && node.type != NodeTypes::project)
3637                            ParseListValue(node.buildExclusions, equal);*/
3638                      }
3639                   }
3640                   else if(!strcmpi(buffer, "Path") && !strcmpi(subSection, "Resources"))
3641                   {
3642                      delete project.resNode.path;
3643                      project.resNode.path = CopyString(equal);
3644                      PathCatSlash(parentPath, equal);
3645                   }
3646
3647                   // Config Settings
3648                   else if(!strcmpi(buffer, "Intermediate Directory"))
3649                      project.config.options.objectsDirectory = /*CopyString(*/equal/*)*/; //objDir.expression = equal;
3650                   else if(!strcmpi(buffer, "Debug"))
3651                      project.config.options.debug = ParseTrueFalseValue(equal);
3652                   else if(!strcmpi(buffer, "Optimize"))
3653                   {
3654                      if(!strcmpi(equal, "None"))
3655                         project.config.options.optimization = none;
3656                      else if(!strcmpi(equal, "Speed") || !strcmpi(equal, "True"))
3657                         project.config.options.optimization = speed;
3658                      else if(!strcmpi(equal, "Size"))
3659                         project.config.options.optimization = size;
3660                      else
3661                         project.config.options.optimization = none;
3662                   }
3663                   else if(!strcmpi(buffer, "Profile"))
3664                      project.config.options.profile = ParseTrueFalseValue(equal);
3665                   else if(!strcmpi(buffer, "MemoryGuard"))
3666                      project.config.options.memoryGuard = ParseTrueFalseValue(equal);
3667                   else
3668                   {
3669                      if(!project.options) project.options = { };
3670
3671                      // Project Wide Settings (All configs)
3672                      if(!strcmpi(buffer, "Target Name"))
3673                         project.options.targetFileName = /*CopyString(*/equal/*)*/;
3674                      else if(!strcmpi(buffer, "Target Type"))
3675                      {
3676                         if(!strcmpi(equal, "Executable"))
3677                            project.options.targetType = executable;
3678                         else if(!strcmpi(equal, "Shared"))
3679                            project.options.targetType = sharedLibrary;
3680                         else if(!strcmpi(equal, "Static"))
3681                            project.options.targetType = staticLibrary;
3682                         else
3683                            project.options.targetType = executable;
3684                      }
3685                      else if(!strcmpi(buffer, "Target Directory"))
3686                         project.options.targetDirectory = /*CopyString(*/equal/*)*/;
3687                      else if(!strcmpi(buffer, "Console"))
3688                         project.options.console = ParseTrueFalseValue(equal);
3689                      else if(!strcmpi(buffer, "Libraries"))
3690                      {
3691                         if(!project.options.libraries) project.options.libraries = { };
3692                         ParseArrayValue(project.options.libraries, equal);
3693                      }
3694                      else if(!strcmpi(buffer, "AllWarnings"))
3695                         project.options.warnings = ParseTrueFalseValue(equal) ? all : unset;
3696                      else if(!strcmpi(buffer, "Preprocessor Definitions"))
3697                      {
3698                         if(!strcmpi(section, "Target") && !strcmpi(subSection, "Files"))
3699                         {
3700                            /*if(node && (node.type == NodeTypes::project || (node.type == file && !node.isInResources) || node.type == folder))
3701                               ParseListValue(node.preprocessorDefs, equal);*/
3702                         }
3703                         else
3704                         {
3705                            if(!project.options.preprocessorDefinitions) project.options.preprocessorDefinitions = { };
3706                            ParseArrayValue(project.options.preprocessorDefinitions, equal);
3707                         }
3708                      }
3709                   }
3710                }
3711             }
3712          }
3713       }
3714    }
3715    parent = null;
3716
3717    SplitPlatformLibraries(project);
3718
3719    if(configurationsPresent)
3720       CombineIdenticalConfigOptions(project);
3721    return project;
3722 }
3723
3724 void SplitPlatformLibraries(Project project)
3725 {
3726    if(project && project.configurations)
3727    {
3728       for(cfg : project.configurations)
3729       {
3730          if(cfg.options.libraries && cfg.options.libraries.count)
3731          {
3732             Iterator<String> it { cfg.options.libraries };
3733             while(it.Next())
3734             {
3735                String l = it.data;
3736                char * platformName = strstr(l, ":");
3737                if(platformName)
3738                {
3739                   PlatformOptions platform = null;
3740                   platformName++;
3741                   if(!cfg.platforms) cfg.platforms = { };
3742                   for(p : cfg.platforms)
3743                   {
3744                      if(!strcmpi(platformName, p.name))
3745                      {
3746                         platform = p;
3747                         break;
3748                      }
3749                   }
3750                   if(!platform)
3751                   {
3752                      platform = { name = CopyString(platformName), options = { libraries = { } } };
3753                      cfg.platforms.Add(platform);
3754                   }
3755                   *(platformName-1) = 0;
3756                   platform.options.libraries.Add(CopyString(l));
3757
3758                   cfg.options.libraries.Delete(it.pointer);
3759                   it.pointer = null;
3760                }
3761             }
3762          }
3763       }      
3764    }
3765 }
3766
3767 void CombineIdenticalConfigOptions(Project project)
3768 {
3769    if(project && project.configurations && project.configurations.count)
3770    {
3771       DataMember member;
3772       ProjectOptions nullOptions { };
3773       ProjectConfig firstConfig = null;
3774       for(cfg : project.configurations)
3775       {
3776          if(cfg.options.targetType != staticLibrary)
3777          {
3778             firstConfig = cfg;
3779             break;
3780          }
3781       }
3782       if(!firstConfig)
3783          firstConfig = project.configurations.firstIterator.data;
3784
3785       for(member = class(ProjectOptions).membersAndProperties.first; member; member = member.next)
3786       {
3787          if(!member.isProperty)
3788          {
3789             Class type = eSystem_FindClass(__thisModule, member.dataTypeString);
3790             if(type)
3791             {
3792                bool same = true;
3793
3794                for(cfg : project.configurations)
3795                {
3796                   if(cfg != firstConfig)
3797                   {
3798                      if(cfg.options.targetType != staticLibrary)
3799                      {
3800                         int result;
3801                         
3802                         if(type.type == noHeadClass || type.type == normalClass)
3803                         {
3804                            result = ((int (*)(void *, void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnCompare])(type, 
3805                               *(void **)((byte *)firstConfig.options + member.offset + member._class.offset),
3806                               *(void **)((byte *)cfg.options         + member.offset + member._class.offset));
3807                         }
3808                         else
3809                         {
3810                            result = ((int (*)(void *, void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnCompare])(type, 
3811                               (byte *)firstConfig.options + member.offset + member._class.offset,
3812                               (byte *)cfg.options         + member.offset + member._class.offset);
3813                         }
3814                         if(result)
3815                         {
3816                            same = false;
3817                            break;
3818                         }
3819                      }
3820                   }                  
3821                }
3822                if(same)
3823                {
3824                   if(type.type == noHeadClass || type.type == normalClass)
3825                   {
3826                      if(!((int (*)(void *, void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnCompare])(type, 
3827                         *(void **)((byte *)firstConfig.options + member.offset + member._class.offset),
3828                         *(void **)((byte *)nullOptions         + member.offset + member._class.offset)))
3829                         continue;
3830                   }
3831                   else
3832                   {
3833                      if(!((int (*)(void *, void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnCompare])(type, 
3834                         (byte *)firstConfig.options + member.offset + member._class.offset,
3835                         (byte *)nullOptions         + member.offset + member._class.offset))
3836                         continue;
3837                   }
3838
3839                   if(!project.options) project.options = { };
3840                   
3841                   /*if(type.type == noHeadClass || type.type == normalClass)
3842                   {
3843                      ((void (*)(void *, void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnCopy])(type, 
3844                         (byte *)project.options + member.offset + member._class.offset,
3845                         *(void **)((byte *)firstConfig.options + member.offset + member._class.offset));
3846                   }
3847                   else
3848                   {
3849                      void * address = (byte *)firstConfig.options + member.offset + member._class.offset;
3850                      // TOFIX: ListBox::SetData / OnCopy mess
3851                      ((void (*)(void *, void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnCopy])(type, 
3852                         (byte *)project.options + member.offset + member._class.offset,
3853                         (type.typeSize > 4) ? address : 
3854                            ((type.typeSize == 4) ? (void *)*(uint32 *)address : 
3855                               ((type.typeSize == 2) ? (void *)*(uint16*)address : 
3856                                  (void *)*(byte *)address )));                              
3857                   }*/
3858                   memcpy(
3859                      (byte *)project.options + member.offset + member._class.offset,
3860                      (byte *)firstConfig.options + member.offset + member._class.offset, type.typeSize);
3861
3862                   for(cfg : project.configurations)
3863                   {
3864                      if(cfg.options.targetType == staticLibrary)
3865                      {
3866                         int result;
3867                         
3868                         if(type.type == noHeadClass || type.type == normalClass)
3869                         {
3870                            result = ((int (*)(void *, void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnCompare])(type, 
3871                               *(void **)((byte *)firstConfig.options + member.offset + member._class.offset),
3872                               *(void **)((byte *)cfg.options         + member.offset + member._class.offset));
3873                         }
3874                         else
3875                         {
3876                            result = ((int (*)(void *, void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnCompare])(type, 
3877                               (byte *)firstConfig.options + member.offset + member._class.offset,
3878                               (byte *)cfg.options         + member.offset + member._class.offset);
3879                         }
3880                         if(result)
3881                            continue;
3882                      }
3883                      if(cfg != firstConfig)
3884                      {
3885                         if(type.type == noHeadClass || type.type == normalClass)
3886                         {
3887                            ((void (*)(void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnFree])(type, 
3888                               *(void **)((byte *)cfg.options + member.offset + member._class.offset));
3889                         }
3890                         else
3891                         {
3892                            ((void (*)(void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnFree])(type, 
3893                               (byte *)cfg.options + member.offset + member._class.offset);
3894                         }
3895                         memset((byte *)cfg.options + member.offset + member._class.offset, 0, type.typeSize);
3896                      }                     
3897                   }
3898                   memset((byte *)firstConfig.options + member.offset + member._class.offset, 0, type.typeSize);
3899                }
3900             }
3901          }
3902       }
3903       delete nullOptions;
3904
3905       // Compare Platform Specific Settings
3906       {
3907          bool same = true;
3908          for(cfg : project.configurations)
3909          {
3910             if(cfg != firstConfig && cfg.options.targetType != staticLibrary && (firstConfig.platforms || cfg.platforms) &&
3911                ((!firstConfig.platforms && cfg.platforms) || firstConfig.platforms.OnCompare(cfg.platforms)))
3912             {
3913                same = false;
3914                break;
3915             }
3916          }
3917          if(same && firstConfig.platforms)
3918          {
3919             for(cfg : project.configurations)
3920             {
3921                if(cfg.options.targetType == staticLibrary && firstConfig.platforms.OnCompare(cfg.platforms))
3922                   continue;
3923                if(cfg != firstConfig)
3924                {
3925                   cfg.platforms.Free();
3926                   delete cfg.platforms;
3927                }
3928             }
3929             project.platforms = firstConfig.platforms;
3930             firstConfig.platforms = null;
3931          }
3932       }
3933
3934       // Static libraries can't contain libraries
3935       for(cfg : project.configurations)
3936       {
3937          if(cfg.options.targetType == staticLibrary)
3938          {
3939             if(!cfg.options.libraries) cfg.options.libraries = { };
3940             cfg.options.libraries.Free();
3941          }
3942       }
3943    }
3944 }
3945
3946 Project LoadProject(char * filePath, char * activeConfigName)
3947 {
3948    Project project = null;
3949    File f = FileOpen(filePath, read);
3950    if(f)
3951    {
3952       project = LegacyBinaryLoadProject(f, filePath);
3953       if(!project)
3954       {
3955          JSONParser parser { f = f };
3956          JSONResult result = parser.GetObject(class(Project), &project);
3957          if(project)
3958          {
3959             char insidePath[MAX_LOCATION];
3960
3961             delete project.topNode.files;
3962             if(!project.files) project.files = { };
3963             project.topNode.files = project.files;
3964             project.resNode = project.topNode.Add(project, "Resources", project.topNode.files.last, resources, archiveFile, false);
3965             delete project.resNode.path;
3966             project.resNode.path = project.resourcesPath;
3967             project.resourcesPath = null;
3968             project.resNode.nodeType = (ProjectNodeType)-1;
3969             delete project.resNode.files;
3970             project.resNode.files = project.resources;
3971             project.files = null;
3972             project.resources = null;
3973             if(!project.configurations) project.configurations = { };
3974
3975             {
3976                char topNodePath[MAX_LOCATION];
3977                GetWorkingDir(topNodePath, sizeof(topNodePath)-1);
3978                MakeSlashPath(topNodePath);
3979                PathCatSlash(topNodePath, filePath);
3980                project.filePath = topNodePath;//filePath;
3981             }
3982
3983             project.topNode.FixupNode(insidePath);
3984          }
3985          delete parser;
3986       }
3987       if(!project)
3988          project = LegacyAsciiLoadProject(f, filePath);
3989
3990       delete f;
3991
3992       if(project)
3993       {
3994          if(!project.options) project.options = { };
3995          if(activeConfigName && activeConfigName[0] && project.configurations)
3996          {
3997             for(cfg : project.configurations)
3998             {
3999                if(!strcmpi(cfg.name, activeConfigName))
4000                {
4001                   project.config = cfg;
4002                   break;
4003                }
4004             }
4005          }
4006          if(!project.config && project.configurations)
4007             project.config = project.configurations.firstIterator.data;
4008
4009          if(!project.resNode)
4010          {
4011             project.resNode = project.topNode.Add(project, "Resources", project.topNode.files.last, resources, archiveFile, false);
4012          }
4013          
4014          if(!project.moduleName)
4015             project.moduleName = CopyString(project.name);
4016          if(project.config && 
4017             (!project.options || !project.options.targetFileName || !project.options.targetFileName[0]) &&
4018             (!project.config.options.targetFileName || !project.config.options.targetFileName[0]))
4019          {
4020             //delete project.config.options.targetFileName;
4021             
4022             project.options.targetFileName = /*CopyString(*/project.moduleName/*)*/;
4023             project.config.options.optimization = none;
4024             project.config.options.debug = true;
4025             //project.config.options.warnings = unset;
4026             project.config.options.memoryGuard = false;
4027             project.config.compilingModified = true;
4028             project.config.linkingModified = true;
4029          }
4030          else if(!project.topNode.name && project.config)
4031          {
4032             project.topNode.name = CopyString(project.config.options.targetFileName);
4033          }
4034
4035          /* // THIS IS NOW AUTOMATED WITH A project CHECK IN ProjectNode
4036          project.topNode.configurations = project.configurations;
4037          project.topNode.platforms = project.platforms;
4038          project.topNode.options = project.options;*/
4039       }
4040    }
4041    return project;
4042 }