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