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