4605ab1d5a5b2fe6cb0be6be9d1a93542a5d3b91
[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, bool replaceSpaces, bool makeRelative)
1161    {
1162       bool result = false;
1163       char temp[MAX_LOCATION];
1164       strcpy(cfDir, topNode.path);
1165       if(compilerConfigsDir && compilerConfigsDir[0])
1166       {
1167          PathCatSlash(cfDir, compilerConfigsDir);
1168          result = true;
1169       }
1170       if(makeRelative)
1171       {
1172          strcpy(temp, cfDir);
1173          // Using a relative path makes it less likely to run into spaces issues
1174          // Even with escaped spaces, there still seems to be issues including a config file
1175          // in a path containing spaces
1176
1177          MakePathRelative(temp, topNode.path, cfDir);
1178       }
1179
1180       if(cfDir && cfDir[0] && cfDir[strlen(cfDir)-1] != '/')
1181          strcat(cfDir, "/");
1182       if(replaceSpaces)
1183       {
1184          strcpy(temp, cfDir);
1185          ReplaceSpaces(cfDir, temp);
1186       }
1187       return result;
1188    }
1189
1190    bool GetIDECompilerConfigsDir(char * cfDir, bool replaceSpaces, bool makeRelative)
1191    {
1192       char temp[MAX_LOCATION];
1193       bool result = false;
1194       strcpy(cfDir, topNode.path);
1195       if(ideSettings.compilerConfigsDir && ideSettings.compilerConfigsDir[0])
1196       {
1197          PathCatSlash(cfDir, ideSettings.compilerConfigsDir);
1198          result = true;
1199       }
1200       else
1201       {
1202          // Default to <ProjectDir>/.configs if unset
1203          PathCatSlash(cfDir, ".configs");
1204          result = true;
1205       }
1206       if(makeRelative)
1207       {
1208          strcpy(temp, cfDir);
1209          // Using a relative path makes it less likely to run into spaces issues
1210          // Even with escaped spaces, there still seems to be issues including a config file
1211          // in a path containing spaces
1212
1213          MakePathRelative(temp, topNode.path, cfDir);
1214       }
1215       if(cfDir && cfDir[0] && cfDir[strlen(cfDir)-1] != '/')
1216          strcat(cfDir, "/");
1217       if(replaceSpaces)
1218       {
1219          strcpy(temp, cfDir);
1220          ReplaceSpaces(cfDir, temp);
1221       }
1222       return result;
1223    }
1224
1225    void CatMakeFileName(char * string, ProjectConfig config)
1226    {
1227       char projectName[MAX_LOCATION];
1228       strcpy(projectName, name);
1229       sprintf(string, "%s%s%s.Makefile", projectName, config ? "-" : "", config ? config.name : "");
1230    }
1231
1232 #ifndef MAKEFILE_GENERATOR
1233    void MarkChanges(ProjectNode node)
1234    {
1235       for(cfg : topNode.configurations)
1236       {
1237          ProjectConfig c = null;
1238          for(i : node.configurations; !strcmpi(i.name, cfg.name)) { c = i; break; }
1239
1240          if(c && ((c.options && cfg.options && cfg.options.console != c.options.console) ||
1241                (!c.options || !cfg.options)))
1242             cfg.symbolGenModified = true;
1243
1244          cfg.makingModified = true;
1245       }
1246    }
1247
1248    void ModifiedAllConfigs(bool making, bool compiling, bool linking, bool symbolGen)
1249    {
1250       for(cfg : configurations)
1251       {
1252          if(making)
1253             cfg.makingModified = true;
1254          if(compiling)
1255             cfg.compilingModified = true;
1256          if(linking)
1257             cfg.linkingModified = true;
1258          if(symbolGen)
1259             cfg.symbolGenModified = true;
1260       }
1261       if(compiling || linking)
1262       {
1263          ide.projectView.modifiedDocument = true;
1264          ide.workspace.modified = true;
1265       }
1266    }
1267    
1268    void RotateActiveConfig(bool forward)
1269    {
1270       if(configurations.first && configurations.last != configurations.first)
1271       {
1272          Iterator<ProjectConfig> cfg { configurations };
1273          while(forward ? cfg.Next() : cfg.Prev())
1274             if(cfg.data == config)
1275                break;
1276
1277          if(forward)
1278          {
1279             if(!cfg.Next())
1280                cfg.Next();
1281          }
1282          else
1283          {
1284             if(!cfg.Prev())
1285                cfg.Prev();
1286          }
1287
1288          property::config = cfg.data;
1289          ide.workspace.modified = true;
1290          ide.projectView.Update(null);
1291       }
1292    }
1293
1294    void ProcessPipeOutputRaw(DualPipe f)
1295    {
1296       char line[65536];
1297       while(!f.Eof() && !ide.ShouldStopBuild())
1298       {
1299          bool result = true;
1300          double lastTime = GetTime();
1301          bool wait = true;
1302          while(result)
1303          {
1304             if((result = f.Peek()) && (result = f.GetLine(line, sizeof(line)-1)))
1305             {
1306                ide.outputView.buildBox.Logf("%s\n", line);
1307             }
1308             if(GetTime() - lastTime > 1.0 / PEEK_RESOLUTION) break;
1309          }
1310          //printf("Processing Input...\n");
1311          if(app.ProcessInput(true))
1312             wait = false;
1313          app.UpdateDisplay();
1314          if(wait)
1315          {
1316             //printf("Waiting...\n");
1317             app.Wait();
1318          }
1319          //if(!result) Sleep(1.0 / PEEK_RESOLUTION);
1320       }
1321       if(ide.ShouldStopBuild())
1322       {
1323          ide.outputView.buildBox.Logf($"\nBuild cancelled by user.\n", line);
1324          f.Terminate();
1325       }
1326    }
1327
1328    bool ProcessBuildPipeOutput(DualPipe f, DirExpression objDirExp, bool isARun, ProjectNode onlyNode,
1329       CompilerConfig compiler, ProjectConfig config)
1330    {
1331       char line[65536];
1332       bool compiling = false, linking = false, precompiling = false;
1333       int compilingEC = 0;
1334       int numErrors = 0, numWarnings = 0;
1335       bool loggedALine = false;
1336       char * configName = config.name;
1337       int lenMakeCommand = strlen(compiler.makeCommand);
1338
1339       char cppCommand[MAX_LOCATION];
1340       char ccCommand[MAX_LOCATION];
1341       char cxxCommand[MAX_LOCATION];
1342       char ecpCommand[MAX_LOCATION];
1343       char eccCommand[MAX_LOCATION];
1344       char ecsCommand[MAX_LOCATION];
1345       char earCommand[MAX_LOCATION];
1346
1347       char * cc = compiler.ccCommand;
1348       char * cxx = compiler.cxxCommand;
1349       char * cpp = compiler.cppCommand;
1350       sprintf(cppCommand, "%s%s%s%s ",
1351             compiler.ccacheEnabled ? "ccache " : "",
1352             compiler.ccacheEnabled && !compiler.distccEnabled ? " " : "",
1353             compiler.distccEnabled ? "distcc " : "",
1354             compiler.cppCommand);
1355       sprintf(ccCommand, "%s%s%s%s ",
1356             compiler.ccacheEnabled ? "ccache " : "",
1357             compiler.ccacheEnabled && !compiler.distccEnabled ? " " : "",
1358             compiler.distccEnabled ? "distcc " : "",
1359             compiler.ccCommand);
1360       sprintf(cxxCommand, "%s%s%s%s ",
1361             compiler.ccacheEnabled ? "ccache " : "",
1362             compiler.ccacheEnabled && !compiler.distccEnabled ? " " : "",
1363             compiler.distccEnabled ? "distcc " : "",
1364             compiler.cxxCommand);
1365       sprintf(ecpCommand, "%s ", compiler.ecpCommand);
1366       sprintf(eccCommand, "%s ", compiler.eccCommand);
1367       sprintf(ecsCommand, "%s ", compiler.ecsCommand);
1368       sprintf(earCommand, "%s ", compiler.earCommand);
1369
1370       while(!f.Eof() && !ide.ShouldStopBuild())
1371       {
1372          bool result = true;
1373          double lastTime = GetTime();
1374          bool wait = true;
1375          while(result)
1376          {
1377             //printf("Peeking and GetLine...\n");
1378             if((result = f.Peek()) && (result = f.GetLine(line, sizeof(line)-1)))
1379             {
1380                char * inFileIncludedFrom = strstr(line, stringInFileIncludedFrom);
1381                if(strstr(line, compiler.makeCommand) == line && line[lenMakeCommand] == ':')
1382                {
1383                   char * module = strstr(line, "No rule to make target `");
1384                   if(module)
1385                   {
1386                      char * end;
1387                      module = strchr(module, '`') + 1;
1388                      end = strchr(module, '\'');
1389                      if(end)
1390                      {
1391                         *end = '\0';
1392                         ide.outputView.buildBox.Logf($"   %s: No such file or directory\n", module);
1393                         // ide.outputView.buildBox.Logf("error: %s\n   No such file or directory\n", module);
1394                         numErrors++;
1395                      }
1396                   }
1397                   //else
1398                   //{
1399                      //ide.outputView.buildBox.Logf("error: %s\n", line);
1400                      //numErrors++;
1401                   //}
1402                }
1403                else if(strstr(line, "ear ") == line);
1404                else if(strstr(line, "strip ") == line);
1405                else if(strstr(line, ccCommand) == line || strstr(line, cxxCommand) == line || strstr(line, ecpCommand) == line || strstr(line, eccCommand) == line)
1406                {
1407                   char moduleName[MAX_FILENAME];
1408                   byte * tokens[1];
1409                   char * module;
1410                   bool isPrecomp = false;
1411
1412                   if(strstr(line, ccCommand) == line || strstr(line, cxxCommand) == line)
1413                   {
1414                      module = strstr(line, " -c ");
1415                      if(module) module += 4;
1416                   }
1417                   else if(strstr(line, eccCommand) == line)
1418                   {
1419                      module = strstr(line, " -c ");
1420                      if(module) module += 4;
1421                      //module = line + 3;
1422                      // Don't show GCC warnings about generated C code because it does not compile clean yet...
1423                      compilingEC = 3;//2;
1424                   }
1425                   else if(strstr(line, ecpCommand) == line)
1426                   {
1427                      // module = line + 8;
1428                      module = strstr(line, " -c ");
1429                      if(module) module += 4;
1430                      isPrecomp = true;
1431                      compilingEC = 0;
1432                   }
1433
1434                   loggedALine = true;
1435
1436                   if(module)
1437                   {
1438                      if(!compiling && !isPrecomp)
1439                      {
1440                         ide.outputView.buildBox.Logf($"Compiling...\n");
1441                         compiling = true;
1442                      }
1443                      else if(!precompiling && isPrecomp)
1444                      {
1445                         ide.outputView.buildBox.Logf($"Generating symbols...\n");
1446                         precompiling = true;
1447                      }
1448                      // Changed escapeBackSlashes here to handle paths with spaces
1449                      Tokenize(module, 1, tokens, true); // false);
1450                      GetLastDirectory(module, moduleName);
1451                      ide.outputView.buildBox.Logf("%s\n", moduleName);
1452                   }
1453                   else if((module = strstr(line, " -o ")))
1454                   {
1455                      compiling = false;
1456                      precompiling = false;
1457                      linking = true;
1458                      ide.outputView.buildBox.Logf($"Linking...\n");
1459                   }
1460                   else
1461                   {
1462                      ide.outputView.buildBox.Logf("%s\n", line);
1463                      numErrors++;
1464                   }
1465
1466                   if(compilingEC) compilingEC--;
1467                }
1468                else if(strstr(line, "ar rcs") == line)
1469                   ide.outputView.buildBox.Logf($"Building library...\n");
1470                else if(strstr(line, ecsCommand) == line)
1471                   ide.outputView.buildBox.Logf($"Writing symbol loader...\n");
1472                else
1473                {
1474                   if(linking || compiling || precompiling)
1475                   {
1476                      char * colon = strstr(line, ":"); //, * bracket;
1477                      if(colon && (colon[1] == '/' || colon[1] == '\\'))
1478                         colon = strstr(colon + 1, ":");
1479                      if(colon)
1480                      {
1481                         char moduleName[MAX_LOCATION], temp[MAX_LOCATION];
1482                         char * pointer;
1483                         char * error;
1484                         char * start = inFileIncludedFrom ? line + strlen(stringInFileIncludedFrom) : line;
1485                         int len = (int)(colon - start);
1486                         len = Min(len, MAX_LOCATION-1);
1487                         // Don't be mistaken by the drive letter colon
1488                         // Cut module name
1489                         // TODO: need to fix colon - line gives char *
1490                         // warning: incompatible expression colon - line (char *); expected int
1491                         /*
1492                         strncpy(moduleName, line, (int)(colon - line));
1493                         moduleName[colon - line] = '\0';
1494                         */
1495                         strncpy(moduleName, start, len);
1496                         moduleName[len] = '\0';
1497                         // Remove stuff in brackets
1498                         //bracket = strstr(moduleName, "(");
1499                         //if(bracket) *bracket = '\0';
1500
1501                         GetLastDirectory(moduleName, temp);
1502                         if(linking && (!strcmp(temp, "ld") || !strcmp(temp, "ld.exe")))
1503                         {
1504                            numErrors++;
1505                            strcpy(moduleName, $"Linker Error");
1506                         }
1507                         else
1508                         {
1509                            strcpy(temp, topNode.path);
1510                            PathCatSlash(temp, moduleName);
1511                            MakePathRelative(temp, topNode.path, moduleName);
1512                         }
1513                         if(strstr(line, "error:"))
1514                            numErrors ++;
1515                         else
1516                         {
1517                            // Silence warnings for compiled EC
1518                            char * objDir = strstr(moduleName, objDirExp.dir);
1519                         
1520                            if(linking)
1521                            {
1522                               if((pointer = strstr(line, "undefined"))  ||
1523                                    (pointer = strstr(line, "No such file")) ||
1524                                    (pointer = strstr(line, "token")))
1525                               {
1526                                  strncat(moduleName, colon, pointer - colon);
1527                                  strcat(moduleName, "error: ");
1528                                  colon = pointer;
1529                                  numErrors ++;
1530                               }
1531                            }
1532                            else if((pointer = strstr(line, "No such file")))
1533                            {
1534                               strncat(moduleName, colon, pointer - colon);
1535                               strcat(moduleName, "error: ");
1536                               colon = pointer;
1537                               numErrors ++;
1538                            }
1539                            else if(compilingEC == 1 || (objDir && objDir == moduleName))
1540                               continue;
1541                            else if(strstr(line, "warning:"))
1542                            {
1543                               numWarnings++;
1544                            }
1545                         }
1546                         if(this == ide.workspace.projects.firstIterator.data)
1547                            ide.outputView.buildBox.Logf("   %s%s\n", moduleName, colon);
1548                         else
1549                         {
1550                            char fullModuleName[MAX_LOCATION];
1551                            strcpy(fullModuleName, topNode.path);
1552                            PathCat(fullModuleName, moduleName);
1553                            MakePathRelative(fullModuleName, ide.workspace.projects.firstIterator.data.topNode.path, fullModuleName);
1554                            MakeSystemPath(fullModuleName);
1555                            ide.outputView.buildBox.Logf("   %s%s%s\n", inFileIncludedFrom ? stringInFileIncludedFrom : "", fullModuleName, colon);
1556                         }
1557                      }
1558                      else
1559                      {
1560                         ide.outputView.buildBox.Logf("%s\n", line);
1561                         linking = compiling = precompiling = false;
1562                      }
1563                   }
1564                   else
1565                      ide.outputView.buildBox.Logf("%s\n", line);
1566                }
1567                wait = false;
1568             }
1569             //printf("Done getting line\n");
1570             if(GetTime() - lastTime > 1.0 / PEEK_RESOLUTION) break;
1571          }
1572          //printf("Processing Input...\n");
1573          if(app.ProcessInput(true))
1574             wait = false;
1575          app.UpdateDisplay();
1576          if(wait)
1577          {
1578             //printf("Waiting...\n");
1579             app.Wait();
1580          }
1581          //if(!result) Sleep(1.0 / PEEK_RESOLUTION);
1582       }
1583       if(ide.ShouldStopBuild())
1584       {
1585          ide.outputView.buildBox.Logf($"\nBuild cancelled by user.\n", line);
1586          f.Terminate();
1587       }
1588       else if(loggedALine || !isARun)
1589       {
1590          if(f.GetExitCode() && !numErrors)
1591          {
1592             bool result = f.GetLine(line, sizeof(line)-1);
1593             ide.outputView.buildBox.Logf($"Fatal Error: child process terminated unexpectedly\n");
1594          }
1595          else
1596          {
1597             if(!onlyNode)
1598                ide.outputView.buildBox.Logf("\n%s (%s) - ", GetTargetFileName(config), configName);
1599             if(numErrors)
1600                ide.outputView.buildBox.Logf("%d %s, ", numErrors, (numErrors > 1) ? $"errors" : $"error");
1601             else
1602                ide.outputView.buildBox.Logf($"no error, ");
1603    
1604             if(numWarnings)
1605                ide.outputView.buildBox.Logf("%d %s\n", numWarnings, (numWarnings > 1) ? $"warnings" : $"warning");
1606             else
1607                ide.outputView.buildBox.Logf($"no warning\n");
1608          }
1609       }
1610       return numErrors == 0;
1611    }
1612
1613    void ProcessCleanPipeOutput(DualPipe f, CompilerConfig compiler, ProjectConfig config)
1614    {
1615       char line[65536];
1616       int lenMakeCommand = strlen(compiler.makeCommand);
1617       while(!f.Eof())
1618       {
1619          bool result = true;
1620          bool wait = true;
1621          double lastTime = GetTime();
1622          while(result)
1623          {
1624             if((result = f.Peek()) && (result = f.GetLine(line, sizeof(line)-1)))
1625             {
1626                if(strstr(line, compiler.makeCommand) == line && line[lenMakeCommand] == ':');
1627                else if(strstr(line, "del") == line);
1628                else if(strstr(line, "rm") == line);
1629                else if(strstr(line, "Could Not Find") == line);
1630                else
1631                {
1632                   ide.outputView.buildBox.Logf(line);
1633                   ide.outputView.buildBox.Logf("\n");
1634                }
1635                wait = false;
1636             }
1637             if(GetTime() - lastTime > 1.0 / PEEK_RESOLUTION) break;
1638          }
1639          if(app.ProcessInput(true))
1640             wait = false;
1641          app.UpdateDisplay();
1642          if(wait)
1643             app.Wait();
1644          //Sleep(1.0 / PEEK_RESOLUTION);
1645       }
1646    }
1647
1648    bool Build(bool isARun, ProjectNode onlyNode, CompilerConfig compiler, ProjectConfig config)
1649    {
1650       bool result = false;
1651       DualPipe f;
1652       char targetFileName[MAX_LOCATION] = "";
1653       char makeTarget[MAX_LOCATION] = "";
1654       char makeFile[MAX_LOCATION];
1655       char makeFilePath[MAX_LOCATION];
1656       char configName[MAX_LOCATION];
1657       DirExpression objDirExp = GetObjDir(compiler, config);
1658       PathBackup pathBackup { };
1659       bool crossCompiling = (compiler.targetPlatform != GetRuntimePlatform());
1660       char * targetPlatform = crossCompiling ? (char *)compiler.targetPlatform : "";
1661
1662       int numJobs = compiler.numJobs;
1663       char command[MAX_LOCATION];
1664       char * compilerName;
1665
1666       compilerName = CopyString(compiler.name);
1667       CamelCase(compilerName);
1668
1669       strcpy(configName, config ? config.name : "Common");
1670
1671       SetPath(false, compiler, config); //true
1672       CatTargetFileName(targetFileName, compiler, config);
1673
1674       strcpy(makeFilePath, topNode.path);
1675       CatMakeFileName(makeFile, config);
1676       PathCatSlash(makeFilePath, makeFile);
1677       
1678       // TODO: TEST ON UNIX IF \" around makeTarget is ok
1679       if(onlyNode)
1680       {
1681          if(compiler.type.isVC)
1682          {
1683             PrintLn("compiling a single file is not yet supported");
1684          }
1685          else
1686          {
1687             int len;
1688             char pushD[MAX_LOCATION];
1689             char cfDir[MAX_LOCATION];
1690             GetIDECompilerConfigsDir(cfDir, true, true);
1691             GetWorkingDir(pushD, sizeof(pushD));
1692             ChangeWorkingDir(topNode.path);
1693             // Create object dir if it does not exist already
1694             if(!FileExists(objDirExp.dir).isDirectory)
1695                Execute("%s CF_DIR=%s%s%s COMPILER=%s objdir -C \"%s\" -f \"%s\"", compiler.makeCommand, cfDir,
1696                   crossCompiling ? " PLATFORM=" : "", targetPlatform, compilerName, topNode.path, makeFilePath);
1697             ChangeWorkingDir(pushD);
1698
1699             PathCatSlash(makeTarget+1, objDirExp.dir);
1700             PathCatSlash(makeTarget+1, onlyNode.name);
1701             StripExtension(makeTarget+1);
1702             strcat(makeTarget+1, ".o");
1703             makeTarget[0] = '\"';
1704             len = strlen(makeTarget);
1705             makeTarget[len++] = '\"';
1706             makeTarget[len++] = '\0';
1707          }
1708       }
1709
1710       if(compiler.type.isVC)
1711       {
1712          bool result = false;
1713          char oldwd[MAX_LOCATION];
1714          GetWorkingDir(oldwd, sizeof(oldwd));
1715          ChangeWorkingDir(topNode.path);
1716
1717          sprintf(command, "%s /useenv /nologo /logcommands %s.sln %s|Win32", compiler.makeCommand, name, config.name);
1718          ide.outputView.buildBox.Logf("command: %s\n", command);
1719          if((f = DualPipeOpen(PipeOpenMode { output = true, error = true, input = true }, command)))
1720          {
1721             ProcessPipeOutputRaw(f);
1722             delete f;
1723             result = true;
1724          }
1725          ChangeWorkingDir(oldwd);
1726       }
1727       else
1728       {
1729          char cfDir[MAX_LOCATION];
1730          GetIDECompilerConfigsDir(cfDir, true, true);
1731          sprintf(command, "%s CF_DIR=\"%s\"%s%s COMPILER=%s -j%d %s%s%s -C \"%s\" -f \"%s\"", compiler.makeCommand, cfDir,
1732                crossCompiling ? " PLATFORM=" : "", targetPlatform,
1733                compilerName, numJobs,
1734                compiler.ccacheEnabled ? "CCACHE=y " : "",
1735                compiler.distccEnabled ? "DISTCC=y " : "",
1736                makeTarget, topNode.path, makeFilePath);
1737          if((f = DualPipeOpen(PipeOpenMode { output = true, error = true, input = true }, command)))
1738          {
1739             result = ProcessBuildPipeOutput(f, objDirExp, isARun, onlyNode, compiler, config);
1740             delete f;
1741          }
1742          else
1743             ide.outputView.buildBox.Logf($"Error executing make (%s) command\n", compiler.makeCommand);
1744       }
1745
1746       delete pathBackup;
1747       delete objDirExp;
1748       delete compilerName;
1749       return result;
1750    }
1751
1752    void Clean(CompilerConfig compiler, ProjectConfig config, bool realclean)
1753    {
1754       char makeFile[MAX_LOCATION];
1755       char makeFilePath[MAX_LOCATION];
1756       char command[MAX_LOCATION];
1757       char * compilerName;
1758       DualPipe f;
1759       PathBackup pathBackup { };
1760       bool crossCompiling = (compiler.targetPlatform != GetRuntimePlatform());
1761       char * targetPlatform = crossCompiling ? (char *)compiler.targetPlatform : "";
1762
1763       compilerName = CopyString(compiler.name);
1764       CamelCase(compilerName);
1765
1766       SetPath(false, compiler, config);
1767
1768       strcpy(makeFilePath, topNode.path);
1769       CatMakeFileName(makeFile, config);
1770       PathCatSlash(makeFilePath, makeFile);
1771       
1772       if(compiler.type.isVC)
1773       {
1774          bool result = false;
1775          char oldwd[MAX_LOCATION];
1776          GetWorkingDir(oldwd, sizeof(oldwd));
1777          ChangeWorkingDir(topNode.path);
1778          
1779          sprintf(command, "%s /useenv /clean /nologo /logcommands %s.sln %s|Win32", compiler.makeCommand, name, config.name);
1780          ide.outputView.buildBox.Logf("command: %s\n", command);
1781          if((f = DualPipeOpen(PipeOpenMode { output = true, error = true, input = true }, command)))
1782          {
1783             ProcessPipeOutputRaw(f);
1784             delete f;
1785             result = true;
1786          }
1787          ChangeWorkingDir(oldwd);
1788          return result;
1789       }
1790       else
1791       {
1792          char cfDir[MAX_LOCATION];
1793          GetIDECompilerConfigsDir(cfDir, true, true);
1794          sprintf(command, "%s CF_DIR=%s%s%s COMPILER=%s %sclean -C \"%s\" -f \"%s\"", compiler.makeCommand, cfDir,
1795             crossCompiling ? " PLATFORM=" : "", targetPlatform, compilerName, realclean ? "real" : "", topNode.path, makeFilePath);
1796          if((f = DualPipeOpen(PipeOpenMode { output = 1, error = 1, input = 2 }, command)))
1797          {
1798             ide.outputView.buildBox.Tell($"Deleting target and object files...");
1799             ProcessCleanPipeOutput(f, compiler, config);
1800             delete f;
1801
1802             ide.outputView.buildBox.Logf($"Target and object files deleted\n");
1803          }
1804       }
1805
1806       delete pathBackup;
1807       delete compilerName;
1808    }
1809
1810    void Run(char * args, CompilerConfig compiler, ProjectConfig config)
1811    {   
1812       String target = new char[maxPathLen];
1813       char oldDirectory[MAX_LOCATION];
1814       DirExpression targetDirExp = GetTargetDir(compiler, config);
1815       PathBackup pathBackup { };
1816
1817       // Build(project, ideMain, true, null);
1818
1819    #if defined(__WIN32__)
1820       strcpy(target, topNode.path);
1821    #else
1822       strcpy(target, "");
1823    #endif
1824       PathCatSlash(target, targetDirExp.dir);
1825       CatTargetFileName(target, compiler, config);
1826       sprintf(target, "%s %s", target, args);
1827       GetWorkingDir(oldDirectory, MAX_LOCATION);
1828
1829       if(strlen(ide.workspace.debugDir))
1830       {
1831          char temp[MAX_LOCATION];
1832          strcpy(temp, topNode.path);
1833          PathCatSlash(temp, ide.workspace.debugDir);
1834          ChangeWorkingDir(temp);
1835       }
1836       else
1837          ChangeWorkingDir(topNode.path);
1838       // ChangeWorkingDir(topNode.path);
1839       SetPath(true, compiler, config);
1840       if(compiler.execPrefixCommand)
1841       {
1842          char * prefixedTarget = new char[strlen(compiler.execPrefixCommand) + strlen(target) + 2];
1843          prefixedTarget[0] = '\0';
1844          strcat(prefixedTarget, compiler.execPrefixCommand);
1845          strcat(prefixedTarget, " ");
1846          strcat(prefixedTarget, target);
1847          Execute(prefixedTarget);
1848          delete prefixedTarget;
1849       }
1850       else
1851          Execute(target);
1852
1853       ChangeWorkingDir(oldDirectory);
1854       delete pathBackup;
1855
1856       delete targetDirExp;
1857       delete target;
1858    }
1859
1860    void Compile(ProjectNode node, CompilerConfig compiler, ProjectConfig config)
1861    {
1862       Build(false, node, compiler, config);
1863    }
1864 #endif
1865
1866    void GetMakefileTargetFileName(TargetTypes targetType, char * fileName, ProjectConfig config)
1867    {
1868       fileName[0] = '\0';
1869       if(targetType == staticLibrary || targetType == sharedLibrary)
1870          strcat(fileName, "$(LP)");
1871       // !!! ReplaceSpaces must be done after all PathCat calls !!!
1872       // ReplaceSpaces(s, GetTargetFileName(config));
1873       strcat(fileName, GetTargetFileName(config));
1874       switch(targetType)
1875       {
1876          case executable:
1877             strcat(fileName, "$(E)");
1878             break;
1879          case sharedLibrary:
1880             strcat(fileName, "$(SO)");
1881             break;
1882          case staticLibrary:
1883             strcat(fileName, "$(A)");
1884             break;
1885       }
1886    }
1887
1888    bool GenerateCrossPlatformCf()
1889    {
1890       bool result = false;
1891       char path[MAX_LOCATION];
1892
1893       if(!GetProjectCompilerConfigsDir(path, false, false))
1894          GetIDECompilerConfigsDir(path, false, false);
1895
1896       if(!FileExists(path).isDirectory)
1897       {
1898          MakeDir(path);
1899          {
1900             char dirName[MAX_FILENAME];
1901             GetLastDirectory(path, dirName);
1902             if(!strcmp(dirName, ".configs"))
1903                FileSetAttribs(path, FileAttribs { isHidden = true });
1904          }
1905       }
1906       PathCatSlash(path, "crossplatform.mk");
1907
1908       if(FileExists(path))
1909          DeleteFile(path);
1910       {
1911          File include = FileOpen(":crossplatform.mk", read);
1912          if(include)
1913          {
1914             File f = FileOpen(path, write);
1915             if(f)
1916             {
1917                for(; !include.Eof(); )
1918                {
1919                   char buffer[4096];
1920                   int count = include.Read(buffer, 1, 4096);
1921                   f.Write(buffer, 1, count);
1922                }
1923                delete f;
1924
1925                result = true;
1926             }
1927             delete include;
1928          }
1929       }
1930       return result;
1931    }
1932
1933    bool GenerateCompilerMk(CompilerConfig compiler)
1934    {
1935       bool result = false;
1936       char path[MAX_LOCATION];
1937       char * name;
1938       char * compilerName;
1939       bool gccCompiler = compiler.ccCommand && (strstr(compiler.ccCommand, "gcc") != null || strstr(compiler.ccCommand, "g++") != null);
1940       Platform platform = compiler.targetPlatform;
1941
1942       compilerName = CopyString(compiler.name);
1943       CamelCase(compilerName);
1944       name = PrintString(platform, "-", compilerName, ".cf");
1945
1946       if(!GetProjectCompilerConfigsDir(path, false, false))
1947          GetIDECompilerConfigsDir(path, false, false);
1948
1949       if(!FileExists(path).isDirectory)
1950       {
1951          MakeDir(path);
1952          {
1953             char dirName[MAX_FILENAME];
1954             GetLastDirectory(path, dirName);
1955             if(!strcmp(dirName, ".configs"))
1956                FileSetAttribs(path, FileAttribs { isHidden = true });
1957          }
1958       }
1959       PathCatSlash(path, name);
1960
1961       if(FileExists(path))
1962          DeleteFile(path);
1963       {
1964          File f = FileOpen(path, write);
1965          if(f)
1966          {
1967             /*
1968             if(compiler.targetPlatform != GetRuntimePlatform())
1969                f.Printf("\nPLATFORM = %s\n", (char *)compiler.targetPlatform);
1970             */
1971
1972             f.Printf("# TOOLCHAIN\n\n");
1973
1974             //f.Printf("SHELL := %s\n", "sh"/*compiler.shellCommand*/); // is this really needed?
1975             f.Printf("CPP := %s\n", compiler.cppCommand);
1976             f.Printf("CC := $(CCACHE_COMPILE) $(DISTCC_COMPILE) %s\n", compiler.ccCommand);
1977             f.Printf("CXX := $(CCACHE_COMPILE) $(DISTCC_COMPILE) %s\n", compiler.cxxCommand);
1978             f.Printf("ECP := %s\n", compiler.ecpCommand);
1979             f.Printf("ECC := %s\n", compiler.eccCommand);
1980             f.Printf("ECS := %s -t $(PLATFORM)\n", compiler.ecsCommand);
1981             f.Printf("EAR := %s\n", compiler.earCommand);
1982
1983             f.Printf("AS := as\n");
1984             f.Printf("LD := ld\n");
1985             f.Printf("AR := ar\n");
1986             f.Printf("STRIP := strip\n");
1987             f.Printf("UPX := upx\n");
1988
1989             f.Printf("\n");
1990
1991             f.Printf("UPXFLAGS = -9\n\n"); // TOFEAT: Compression Level Option? Other UPX Options?
1992
1993             f.Printf("# HARD CODED PLATFORM-SPECIFIC OPTIONS\n");
1994             f.Printf("ifeq \"$(PLATFORM)\" \"linux\"\n"); //, PlatformToMakefileVariable(tux));
1995             f.Printf("OFLAGS += -Wl,--no-undefined\n");
1996             f.Printf("endif\n\n");
1997
1998             // JF's
1999             f.Printf("ifeq \"$(PLATFORM)\" \"apple\"\n"); //%s\n", PlatformToMakefileVariable(apple));
2000             f.Printf("OFLAGS += -framework cocoa -framework OpenGL\n");
2001             f.Printf("endif\n");
2002
2003             if(gccCompiler)
2004             {
2005                f.Printf("\nCFLAGS += -fmessage-length=0\n");
2006             }
2007
2008             if(compiler.includeDirs && compiler.includeDirs.count)
2009             {
2010                f.Printf("\nCFLAGS +=");
2011                OutputListOption(f, gccCompiler ? "isystem " : "I", compiler.includeDirs, lineEach, true);
2012                f.Printf("\n");
2013             }
2014             if(compiler.prepDirectives && compiler.prepDirectives.count)
2015             {
2016                f.Printf("\nCFLAGS +=");
2017                OutputListOption(f, "D", compiler.prepDirectives, inPlace, true);
2018                f.Printf("\n");
2019             }
2020             if(compiler.libraryDirs && compiler.libraryDirs.count)
2021             {
2022                f.Printf("\nOFLAGS +=");
2023                OutputListOption(f, "L", compiler.libraryDirs, lineEach, true);
2024                f.Printf("\n");
2025             }
2026             if(compiler.excludeLibs && compiler.excludeLibs.count)
2027             {
2028                f.Puts("\nEXCLUDED_LIBS =");
2029                for(l : compiler.excludeLibs)
2030                {
2031                   f.Puts(" ");
2032                   f.Puts(l);
2033                }
2034             }
2035             f.Printf("\nFORCE_64_BIT = %s", compiler.supportsBitDepth ? "-m64" : "");
2036             f.Printf("\nFORCE_32_BIT = %s", compiler.supportsBitDepth ? "-m32" : "");
2037             f.Printf("\n");
2038
2039             delete f;
2040          }
2041       }
2042       delete name;
2043       delete compilerName;
2044       return result;
2045    }
2046
2047    bool GenerateMakefile(char * altMakefilePath, bool noResources, char * includemkPath, ProjectConfig config)
2048    {
2049       bool result = false;
2050       char filePath[MAX_LOCATION];
2051       char makeFile[MAX_LOCATION];
2052       // PathBackup pathBackup { };
2053       // char oldDirectory[MAX_LOCATION];
2054       File f = null;
2055
2056       if(!altMakefilePath)
2057       {
2058          strcpy(filePath, topNode.path);
2059          CatMakeFileName(makeFile, config);
2060          PathCatSlash(filePath, makeFile);
2061       }
2062
2063       f = FileOpen(altMakefilePath ? altMakefilePath : filePath, write);
2064
2065       /*SetPath(false, compiler, config);
2066       GetWorkingDir(oldDirectory, MAX_LOCATION);
2067       ChangeWorkingDir(topNode.path);*/
2068
2069       if(f)
2070       {
2071          bool test;
2072          int ifCount;
2073          Platform platform;
2074          char targetDir[MAX_LOCATION];
2075          char objDirExpNoSpaces[MAX_LOCATION];
2076          char objDirNoSpaces[MAX_LOCATION];
2077          char resDirNoSpaces[MAX_LOCATION];
2078          char targetDirExpNoSpaces[MAX_LOCATION];
2079          char fixedModuleName[MAX_FILENAME];
2080          char fixedConfigName[MAX_FILENAME];
2081          int c, len;
2082          // Non-zero if we're building eC code
2083          // We'll have to be careful with this when merging configs where eC files can be excluded in some configs and included in others
2084          int numCObjects = 0;
2085          bool containsCXX = false; // True if the project contains a C++ file
2086          bool sameObjTargetDirs;
2087          String objDirExp = GetObjDirExpression(config);
2088          TargetTypes targetType = GetTargetType(config);
2089
2090          char cfDir[MAX_LOCATION];
2091          int objectsParts, eCsourcesParts;
2092          Array<String> listItems { };
2093          Map<String, int> varStringLenDiffs { };
2094          Map<String, NameCollisionInfo> namesInfo { };
2095          bool forceBitDepth = false;
2096
2097          ReplaceSpaces(objDirNoSpaces, objDirExp);
2098          strcpy(targetDir, GetTargetDirExpression(config));
2099          ReplaceSpaces(targetDirExpNoSpaces, targetDir);
2100
2101          strcpy(objDirExpNoSpaces, GetObjDirExpression(config));
2102          ChangeCh(objDirExpNoSpaces, '\\', '/'); // TODO: this is a hack, paths should never include win32 path seperators - fix this in ProjectSettings and ProjectLoad instead
2103          ReplaceSpaces(objDirExpNoSpaces, objDirExpNoSpaces);
2104          ReplaceSpaces(resDirNoSpaces, resNode.path ? resNode.path : "");
2105          ReplaceSpaces(fixedModuleName, moduleName);
2106          ReplaceSpaces(fixedConfigName, GetConfigName(config));
2107          CamelCase(fixedConfigName);
2108
2109          sameObjTargetDirs = !fstrcmp(objDirExpNoSpaces, targetDirExpNoSpaces);
2110
2111          f.Printf(".PHONY: all objdir%s clean realclean\n\n", sameObjTargetDirs ? "" : " targetdir");
2112
2113          f.Printf("# CONTENT\n\n");
2114
2115          f.Printf("MODULE := %s\n", fixedModuleName);
2116          //f.Printf("VERSION = %s\n", version);
2117          f.Printf("CONFIG := %s\n", fixedConfigName);
2118          f.Printf("ifndef COMPILER\n");
2119          f.Printf("COMPILER := default\n");
2120          f.Printf("endif\n");
2121          f.Printf("\n");
2122
2123          if(compilerConfigsDir && compilerConfigsDir[0])
2124          {
2125             strcpy(cfDir, compilerConfigsDir);
2126             if(cfDir && cfDir[0] && cfDir[strlen(cfDir)-1] != '/')
2127                strcat(cfDir, "/");
2128          }
2129          else
2130             strcpy(cfDir, "$(CF_DIR)");
2131
2132          f.Printf("_CF_DIR = %s\n", cfDir);
2133          f.Printf("\n");
2134
2135          f.Printf("ifndef DEBUG\n");
2136          f.Printf("OPTIMIZE :=");
2137          switch(GetOptimization(config))
2138          {
2139             case speed:
2140                f.Printf(" -O2");
2141                f.Printf(" -ffast-math");
2142                break;
2143             case size:
2144                f.Printf(" -Os");
2145                break;
2146          }
2147          if(GetDebug(config))
2148             f.Printf(" -g");
2149          f.Printf("\n");
2150          f.Printf("else\n");
2151          f.Printf("OPTIMIZE := -g\n");
2152          f.Printf("NOSTRIP := y\n");
2153          f.Printf("endif\n");
2154
2155          test = GetTargetTypeIsSetByPlatform(config);
2156          if(test)
2157          {
2158             ifCount = 0;
2159             for(platform = (Platform)1; platform < Platform::enumSize; platform++)
2160             {
2161                TargetTypes targetType;
2162                PlatformOptions projectPOs, configPOs;
2163                MatchProjectAndConfigPlatformOptions(config, platform, &projectPOs, &configPOs);
2164                targetType = platformTargetType;
2165                if(targetType)
2166                {
2167                   if(ifCount)
2168                      f.Printf("else\n");
2169                   ifCount++;
2170                   f.Printf("ifeq \"$(PLATFORM)\" \"%s\"\n", (char *)platform); //%s\n", PlatformToMakefileVariable(platform));
2171
2172                   f.Printf("TARGET_TYPE = ");
2173                   f.Printf(TargetTypeToMakefileVariable(targetType));
2174                   f.Printf("\n");
2175                }
2176             }
2177             f.Printf("else\n"); // ifCount should always be > 0
2178          }
2179          f.Printf("TARGET_TYPE = ");
2180          f.Printf(TargetTypeToMakefileVariable(targetType));
2181          f.Printf("\n");
2182          if(test)
2183          {
2184             if(ifCount)
2185             {
2186                for(c = 0; c < ifCount; c++)
2187                   f.Printf("endif\n");
2188             }
2189          }
2190          f.Printf("\n");
2191
2192          f.Printf("ifeq \"$(TARGET_TYPE)\" \"%s\"\n", TargetTypeToMakefileVariable(executable));
2193          f.Printf("CONSOLE = %s\n", GetConsole(config) ? "-mconsole" : "-mwindows");
2194          f.Printf("endif\n\n");
2195
2196          f.Printf("# FLAGS\n\n");
2197
2198          f.Printf("CFLAGS =\n");
2199          f.Printf("CECFLAGS =\n");
2200          f.Printf("ECFLAGS =\n");
2201          f.Printf("OFLAGS =\n");
2202          f.Printf("LIBS =\n");
2203          f.Printf("\n");
2204
2205          f.Printf("# INCLUDES\n\n");
2206
2207          f.Printf("include %s\n", includemkPath ? includemkPath : "$(_CF_DIR)crossplatform.mk");
2208          f.Printf("include $(_CF_DIR)$(PLATFORM)-$(COMPILER).cf\n");
2209          f.Printf("\n");
2210
2211          f.Printf("# VARIABLES\n\n");
2212
2213          f.Printf("OBJ = %s%s\n\n", objDirExpNoSpaces, objDirExpNoSpaces[0] ? "/" : "");
2214
2215          f.Printf("ifdef DEBUG\n");
2216          f.Printf("CFLAGS += -D_DEBUG\n");
2217          f.Printf("endif\n\n");
2218
2219          f.Printf("RES = %s%s\n\n", resDirNoSpaces, resDirNoSpaces[0] ? "/" : "");
2220
2221          // test = GetTargetTypeIsSetByPlatform(config);
2222          {
2223             char target[MAX_LOCATION];
2224             char targetNoSpaces[MAX_LOCATION];
2225          if(test)
2226          {
2227             TargetTypes type;
2228             ifCount = 0;
2229             for(type = (TargetTypes)1; type < TargetTypes::enumSize; type++)
2230             {
2231                if(type != targetType)
2232                {
2233                   if(ifCount)
2234                      f.Printf("else\n");
2235                   ifCount++;
2236                   f.Printf("ifeq \"$(TARGET_TYPE)\" \"%s\"\n", TargetTypeToMakefileVariable(type));
2237
2238                   GetMakefileTargetFileName(type, target, config);
2239                   strcpy(targetNoSpaces, targetDir);
2240                   PathCatSlash(targetNoSpaces, target);
2241                   ReplaceSpaces(targetNoSpaces, targetNoSpaces);
2242                   f.Printf("TARGET = %s\n", targetNoSpaces);
2243                }
2244             }
2245             f.Printf("else\n"); // ifCount should always be > 0
2246          }
2247          GetMakefileTargetFileName(targetType, target, config);
2248          strcpy(targetNoSpaces, targetDir);
2249          PathCatSlash(targetNoSpaces, target);
2250          ReplaceSpaces(targetNoSpaces, targetNoSpaces);
2251          f.Printf("TARGET = %s\n", targetNoSpaces);
2252
2253          if(test)
2254          {
2255             if(ifCount)
2256             {
2257                for(c = 0; c < ifCount; c++)
2258                   f.Printf("endif\n");
2259             }
2260          }
2261          }
2262          f.Printf("\n");
2263
2264          // Use something fixed here, to not cause Makefile differences across compilers...
2265          varStringLenDiffs["$(OBJ)"] = 30; // strlen("obj/memoryGuard.android.gcc-4.6.2") - 6;
2266          // varStringLenDiffs["$(OBJ)"] = strlen(objDirNoSpaces) - 6;
2267
2268          topNode.GenMakefileGetNameCollisionInfo(namesInfo, config);
2269
2270          numCObjects = topNode.GenMakefilePrintNode(f, this, objects, namesInfo, listItems, config, &containsCXX);
2271          if(numCObjects)
2272             listItems.Add(CopyString("$(OBJ)$(MODULE).main$(O)"));
2273          objectsParts = OutputFileList(f, "OBJECTS", listItems, varStringLenDiffs, null);
2274
2275          {
2276             int c;
2277             char * map[4][2] = { { "COBJECTS", "C" }, { "SYMBOLS", "S" }, { "IMPORTS", "I" }, { "BOWLS", "B" } };
2278
2279             topNode.GenMakefilePrintNode(f, this, eCsources, namesInfo, listItems, config, null);
2280             eCsourcesParts = OutputFileList(f, "_ECSOURCES", listItems, varStringLenDiffs, null);
2281
2282             f.Printf("ECSOURCES = $(call shwspace,$(_ECSOURCES))\n");
2283             if(eCsourcesParts > 1)
2284             {
2285                for(c = 1; c <= eCsourcesParts; c++)
2286                   f.Printf("ECSOURCES%d = $(call shwspace,$(_ECSOURCES%d))\n", c, c);
2287             }
2288             f.Printf("\n");
2289
2290             for(c = 0; c < 3; c++)
2291             {
2292                if(eCsourcesParts > 1)
2293                {
2294                   int n;
2295                   f.Printf("%s =", map[c][0]);
2296                   for(n = 1; n <= eCsourcesParts; n++)
2297                      f.Printf(" $(%s%d)", map[c][0], n);
2298                   f.Printf("\n");
2299                   for(n = 1; n <= eCsourcesParts; n++)
2300                      f.Printf("%s%d = $(call shwspace,$(addprefix $(OBJ),$(patsubst %%.ec,%%$(%s),$(notdir $(_ECSOURCES%d)))))\n", map[c][0], n, map[c][1], n);
2301                }
2302                else if(eCsourcesParts == 1)
2303                   f.Printf("%s = $(call shwspace,$(addprefix $(OBJ),$(patsubst %%.ec,%%$(%s),$(notdir $(_ECSOURCES)))))\n", map[c][0], map[c][1]);
2304                f.Printf("\n");
2305             }
2306          }
2307
2308          topNode.GenMakefilePrintNode(f, this, sources, null, listItems, config, null);
2309          OutputFileList(f, "SOURCES", listItems, varStringLenDiffs, "$(ECSOURCES)");
2310
2311          if(!noResources)
2312             resNode.GenMakefilePrintNode(f, this, resources, null, listItems, config, null);
2313          OutputFileList(f, "RESOURCES", listItems, varStringLenDiffs, null);
2314
2315          f.Printf("LIBS += $(SHAREDLIB) $(EXECUTABLE) $(LINKOPT)\n\n");
2316          if((config && config.options && config.options.libraries) ||
2317                (options && options.libraries))
2318          {
2319             f.Printf("ifneq \"$(TARGET_TYPE)\" \"%s\"\n", TargetTypeToMakefileVariable(staticLibrary));
2320             f.Printf("LIBS +=");
2321             if(config && config.options && config.options.libraries)
2322                OutputLibraries(f, config.options.libraries);
2323             else if(options && options.libraries)
2324                OutputLibraries(f, options.libraries);
2325             f.Printf("\n");
2326             f.Printf("endif\n");
2327             f.Printf("\n");
2328          }
2329
2330          if(platforms || (config && config.platforms))
2331          {
2332             ifCount = 0;
2333             //for(platform = firstPlatform; platform <= lastPlatform; platform++)
2334             //for(platform = win32; platform <= apple; platform++)
2335
2336             f.Printf("# PLATFORM-SPECIFIC OPTIONS\n\n");
2337             for(platform = (Platform)1; platform < Platform::enumSize; platform++)
2338             {
2339                PlatformOptions projectPlatformOptions, configPlatformOptions;
2340                MatchProjectAndConfigPlatformOptions(config, platform, &projectPlatformOptions, &configPlatformOptions);
2341
2342                if(projectPlatformOptions || configPlatformOptions)
2343                {
2344                   if(ifCount)
2345                      f.Printf("else\n");
2346                   ifCount++;
2347                   f.Printf("ifeq \"$(PLATFORM)\" \"");
2348                   // f.Printf(PlatformToMakefileVariable(platform));
2349                   f.Printf((char *)platform);
2350                   f.Printf("\"\n\n");
2351
2352                   if((projectPlatformOptions && projectPlatformOptions.options.preprocessorDefinitions && projectPlatformOptions.options.preprocessorDefinitions.count) ||
2353                      (configPlatformOptions && configPlatformOptions.options.preprocessorDefinitions && configPlatformOptions.options.preprocessorDefinitions.count) ||
2354                      (projectPlatformOptions && projectPlatformOptions.options.includeDirs && projectPlatformOptions.options.includeDirs.count) ||
2355                      (configPlatformOptions && configPlatformOptions.options.includeDirs && configPlatformOptions.options.includeDirs.count))
2356                   {
2357                      f.Printf("CFLAGS +=");
2358                      if(projectPlatformOptions && projectPlatformOptions.options.linkerOptions && projectPlatformOptions.options.linkerOptions.count)
2359                      {
2360                         f.Printf(" \\\n\t -Wl");
2361                         for(s : projectPlatformOptions.options.linkerOptions)
2362                            f.Printf(",%s", s);
2363                      }
2364                      if(configPlatformOptions && configPlatformOptions.options.linkerOptions && configPlatformOptions.options.linkerOptions.count)
2365                      {
2366                         f.Printf(" \\\n\t -Wl");
2367                         for(s : configPlatformOptions.options.linkerOptions)
2368                            f.Printf(",%s", s);
2369                      }
2370                      if(projectPlatformOptions && projectPlatformOptions.options.preprocessorDefinitions)
2371                         OutputListOption(f, "D", projectPlatformOptions.options.preprocessorDefinitions, newLine, false);
2372                      if(configPlatformOptions && configPlatformOptions.options.preprocessorDefinitions)
2373                         OutputListOption(f, "D", configPlatformOptions.options.preprocessorDefinitions, newLine, false );
2374                      if(configPlatformOptions && configPlatformOptions.options.includeDirs)
2375                         OutputListOption(f, "I", configPlatformOptions.options.includeDirs, lineEach, true);
2376                      if(projectPlatformOptions && projectPlatformOptions.options.includeDirs)
2377                         OutputListOption(f, "I", projectPlatformOptions.options.includeDirs, lineEach, true);
2378                      f.Printf("\n\n");
2379                   }
2380
2381                   if((projectPlatformOptions && projectPlatformOptions.options.libraryDirs && projectPlatformOptions.options.libraryDirs.count) ||
2382                         (configPlatformOptions && configPlatformOptions.options.libraryDirs && configPlatformOptions.options.libraryDirs.count) ||
2383                         (projectPlatformOptions && projectPlatformOptions.options.libraries && projectPlatformOptions.options.libraries.count) ||
2384                         (configPlatformOptions && configPlatformOptions.options.libraries && configPlatformOptions.options.libraries.count))
2385                   {
2386                      f.Printf("ifneq \"$(TARGET_TYPE)\" \"%s\"\n", TargetTypeToMakefileVariable(staticLibrary));
2387                      if((projectPlatformOptions && projectPlatformOptions.options.libraryDirs && projectPlatformOptions.options.libraryDirs.count) ||
2388                         (configPlatformOptions && configPlatformOptions.options.libraryDirs && configPlatformOptions.options.libraryDirs.count))
2389                      {
2390                         f.Printf("OFLAGS +=");
2391                         if(configPlatformOptions && configPlatformOptions.options.libraryDirs)
2392                            OutputListOption(f, "L", configPlatformOptions.options.libraryDirs, lineEach, true);
2393                         if(projectPlatformOptions && projectPlatformOptions.options.libraryDirs)
2394                            OutputListOption(f, "L", projectPlatformOptions.options.libraryDirs, lineEach, true);
2395                         f.Printf("\n");
2396                      }
2397
2398                      if((configPlatformOptions && configPlatformOptions.options.libraries))
2399                      {
2400                         if(configPlatformOptions.options.libraries.count)
2401                         {
2402                            f.Printf("LIBS +=");
2403                            OutputLibraries(f, configPlatformOptions.options.libraries);
2404                            f.Printf("\n");
2405                         }
2406                      }
2407                      else if(projectPlatformOptions && projectPlatformOptions.options.libraries)
2408                      {
2409                         if(projectPlatformOptions.options.libraries.count)
2410                         {
2411                            f.Printf("LIBS +=");
2412                            OutputLibraries(f, projectPlatformOptions.options.libraries);
2413                            f.Printf("\n");
2414                         }
2415                      }
2416                      f.Printf("endif\n\n");
2417                   }
2418                }
2419             }
2420             if(ifCount)
2421             {
2422                for(c = 0; c < ifCount; c++)
2423                   f.Printf("endif\n");
2424             }
2425             f.Printf("\n");
2426          }
2427
2428          f.Printf("CFLAGS +=");
2429          //if(gccCompiler)
2430          {
2431             f.Printf(" $(OPTIMIZE)");
2432             forceBitDepth = (options && options.buildBitDepth) || numCObjects;
2433             if(forceBitDepth)
2434                f.Printf(" %s",(!options || !options.buildBitDepth || options.buildBitDepth == bits32) ? "$(FORCE_32_BIT)" : "$(FORCE_64_BIT)");
2435             f.Printf(" $(FPIC)");
2436          }
2437          switch(GetWarnings(config))
2438          {
2439             case all: f.Printf(" -Wall"); break;
2440             case none: f.Printf(" -w"); break;
2441          }
2442          if(GetProfile(config))
2443             f.Printf(" -pg");
2444          if(options && options.linkerOptions && options.linkerOptions.count)
2445          {
2446             f.Printf(" \\\n\t -Wl");
2447             for(s : options.linkerOptions)
2448                f.Printf(",%s", s);
2449          }
2450
2451          if(options && options.preprocessorDefinitions)
2452             OutputListOption(f, "D", options.preprocessorDefinitions, newLine, false);
2453          if(config && config.options && config.options.preprocessorDefinitions)
2454             OutputListOption(f, "D", config.options.preprocessorDefinitions, newLine, false);
2455          if(config && config.options && config.options.includeDirs)
2456             OutputListOption(f, "I", config.options.includeDirs, lineEach, true);
2457          if(options && options.includeDirs)
2458             OutputListOption(f, "I", options.includeDirs, lineEach, true);
2459          f.Printf("\n\n");
2460
2461          f.Printf("CECFLAGS += -cpp $(call escspace,$(CPP)) -t $(PLATFORM)");
2462          f.Printf("\n\n");
2463
2464          f.Printf("ECFLAGS +=");
2465          if(GetMemoryGuard(config))
2466             f.Printf(" -memguard");
2467          if(GetStrictNameSpaces(config))
2468             f.Printf(" -strictns");
2469          if(GetNoLineNumbers(config))
2470             f.Printf(" -nolinenumbers");
2471          {
2472             char * s;
2473             if((s = GetDefaultNameSpace(config)) && s[0])
2474                f.Printf(" -defaultns %s", s);
2475          }
2476          f.Printf("\n\n");
2477
2478          f.Printf("ifneq \"$(TARGET_TYPE)\" \"%s\"\n", TargetTypeToMakefileVariable(staticLibrary));
2479          f.Printf("OFLAGS +=");
2480          if(forceBitDepth)
2481             f.Printf((!options || !options.buildBitDepth || options.buildBitDepth == bits32) ? " -m32" : " -m64 \\\n");
2482
2483          if(GetProfile(config))
2484             f.Printf(" -pg");
2485          if(config && config.options && config.options.libraryDirs)
2486             OutputListOption(f, "L", config.options.libraryDirs, lineEach, true);
2487          if(options && options.libraryDirs)
2488             OutputListOption(f, "L", options.libraryDirs, lineEach, true);
2489          f.Printf("\n");
2490          f.Printf("endif\n\n");
2491
2492          f.Printf("# TARGETS\n\n");
2493
2494          f.Printf("all: objdir%s $(TARGET)\n\n", sameObjTargetDirs ? "" : " targetdir");
2495
2496          f.Printf("objdir:\n");
2497             f.Printf("\t$(if $(wildcard $(OBJ)),,$(call mkdirq,$(OBJ)))\n");
2498          //f.Printf("# PRE-BUILD COMMANDS\n");
2499          if(options && options.prebuildCommands)
2500          {
2501             for(s : options.prebuildCommands)
2502                if(s && s[0]) f.Printf("\t%s\n", s);
2503          }
2504          if(config && config.options && config.options.prebuildCommands)
2505          {
2506             for(s : config.options.prebuildCommands)
2507                if(s && s[0]) f.Printf("\t%s\n", s);
2508          }
2509          if(platforms || (config && config.platforms))
2510          {
2511             ifCount = 0;
2512             //f.Printf("# PLATFORM-SPECIFIC PRE-BUILD COMMANDS\n");
2513             for(platform = (Platform)1; platform < Platform::enumSize; platform++)
2514             {
2515                PlatformOptions projectPOs, configPOs;
2516                MatchProjectAndConfigPlatformOptions(config, platform, &projectPOs, &configPOs);
2517
2518                if((projectPOs && projectPOs.options.prebuildCommands && projectPOs.options.prebuildCommands.count) ||
2519                      (configPOs && configPOs.options.prebuildCommands && configPOs.options.prebuildCommands.count))
2520                {
2521                   if(ifCount)
2522                      f.Printf("else\n");
2523                   ifCount++;
2524                   f.Printf("ifdef ");
2525                   f.Printf(PlatformToMakefileVariable(platform));
2526                   f.Printf("\n");
2527
2528                   if(projectPOs && projectPOs.options.prebuildCommands && projectPOs.options.prebuildCommands.count)
2529                   {
2530                      for(s : projectPOs.options.prebuildCommands)
2531                         if(s && s[0]) f.Printf("\t%s\n", s);
2532                   }
2533                   if(configPOs && configPOs.options.prebuildCommands && configPOs.options.prebuildCommands.count)
2534                   {
2535                      for(s : configPOs.options.prebuildCommands)
2536                         if(s && s[0]) f.Printf("\t%s\n", s);
2537                   }
2538                }
2539             }
2540             if(ifCount)
2541             {
2542                int c;
2543                for(c = 0; c < ifCount; c++)
2544                   f.Printf("endif\n");
2545             }
2546          }
2547          f.Printf("\n");
2548
2549          if(!sameObjTargetDirs)
2550          {
2551             f.Printf("targetdir:\n");
2552                f.Printf("\t$(if $(wildcard %s),,$(call mkdirq,%s))\n\n", targetDirExpNoSpaces, targetDirExpNoSpaces);
2553          }
2554
2555          if(numCObjects)
2556          {
2557             // Main Module (Linking) for ECERE C modules
2558             f.Printf("$(OBJ)$(MODULE).main.ec: $(SYMBOLS) $(COBJECTS)\n");
2559             // use of objDirExpNoSpaces used instead of $(OBJ) to prevent problematic joining of arguments in ecs
2560             f.Printf("\t$(ECS)%s $(ECSLIBOPT) $(SYMBOLS) $(IMPORTS) -symbols %s -o $(OBJ)$(MODULE).main.ec\n\n", 
2561                GetConsole(config) ? " -console" : "", objDirExpNoSpaces);
2562             // Main Module (Linking) for ECERE C modules
2563             f.Printf("$(OBJ)$(MODULE).main.c: $(OBJ)$(MODULE).main.ec\n");
2564             f.Printf("\t$(ECP) $(CECFLAGS) $(ECFLAGS) $(CFLAGS)"
2565                   " -c $(OBJ)$(MODULE).main.ec -o $(OBJ)$(MODULE).main.sym -symbols $(OBJ)\n");
2566             f.Printf("\t$(ECC) $(CECFLAGS) $(ECFLAGS) $(CFLAGS) $(FVISIBILITY)"
2567                   " -c $(OBJ)$(MODULE).main.ec -o $(OBJ)$(MODULE).main.c -symbols $(OBJ)\n\n");
2568          }
2569
2570          // *** Target ***
2571
2572          // This would not rebuild the target on updated objects
2573          // f.Printf("$(TARGET): $(SOURCES) $(RESOURCES) | objdir $(SYMBOLS) $(OBJECTS)%s\n", sameObjTargetDirs ? "" : " targetdir");
2574
2575          // This should fix it for good!
2576          f.Printf("$(SYMBOLS): | objdir\n");
2577          f.Printf("$(OBJECTS): | objdir\n");
2578
2579          // This alone was breaking the tarball, object directory does not get created first (order-only rules happen last it seems!)
2580          f.Printf("$(TARGET): $(SOURCES) $(RESOURCES) $(SYMBOLS) $(OBJECTS) | objdir%s\n", sameObjTargetDirs ? "" : " targetdir");
2581
2582          f.Printf("ifneq \"$(TARGET_TYPE)\" \"%s\"\n", TargetTypeToMakefileVariable(staticLibrary));
2583          f.Printf("\t$(%s) $(OFLAGS) $(OBJECTS) $(LIBS) %s-o $(TARGET) $(INSTALLNAME)\n", containsCXX ? "CXX" : "CC", containsCXX ? "-lstdc++ " : "");
2584          if(!GetDebug(config))
2585          {
2586             f.Printf("ifndef NOSTRIP\n");
2587             f.Printf("\t$(STRIP) $(STRIPOPT) $(TARGET)\n");
2588             f.Printf("endif\n");
2589
2590             if(GetCompress(config))
2591             {
2592                f.Printf("ifndef WINDOWS\n");
2593                f.Printf("ifeq \"$(TARGET_TYPE)\" \"%s\"\n", TargetTypeToMakefileVariable(executable));
2594                   f.Printf("\t$(UPX) $(UPXFLAGS) $(TARGET)\n");
2595                f.Printf("endif\n");
2596                f.Printf("else\n");
2597                   f.Printf("\t$(UPX) $(UPXFLAGS) $(TARGET)\n");
2598                f.Printf("endif\n");
2599             }
2600          }
2601          if(resNode.files && resNode.files.count && !noResources)
2602             resNode.GenMakefileAddResources(f, resNode.path, config);
2603          f.Printf("else\n");
2604          f.Printf("\t$(AR) rcs $(TARGET) $(OBJECTS) $(LIBS)\n");
2605          f.Printf("endif\n");
2606
2607          //f.Printf("# POST-BUILD COMMANDS\n");
2608          if(options && options.postbuildCommands)
2609          {
2610             for(s : options.postbuildCommands)
2611                if(s && s[0]) f.Printf("\t%s\n", s);
2612          }
2613          if(config && config.options && config.options.postbuildCommands)
2614          {
2615             for(s : config.options.postbuildCommands)
2616                if(s && s[0]) f.Printf("\t%s\n", s);
2617          }
2618          if(platforms || (config && config.platforms))
2619          {
2620             ifCount = 0;
2621             //f.Printf("# PLATFORM-SPECIFIC POST-BUILD COMMANDS\n");
2622             for(platform = (Platform)1; platform < Platform::enumSize; platform++)
2623             {
2624                PlatformOptions projectPOs, configPOs;
2625                MatchProjectAndConfigPlatformOptions(config, platform, &projectPOs, &configPOs);
2626
2627                if((projectPOs && projectPOs.options.postbuildCommands && projectPOs.options.postbuildCommands.count) ||
2628                      (configPOs && configPOs.options.postbuildCommands && configPOs.options.postbuildCommands.count))
2629                {
2630                   if(ifCount)
2631                      f.Printf("else\n");
2632                   ifCount++;
2633                   f.Printf("ifdef ");
2634                   f.Printf(PlatformToMakefileVariable(platform));
2635                   f.Printf("\n");
2636
2637                   if(projectPOs && projectPOs.options.postbuildCommands && projectPOs.options.postbuildCommands.count)
2638                   {
2639                      for(s : projectPOs.options.postbuildCommands)
2640                         if(s && s[0]) f.Printf("\t%s\n", s);
2641                   }
2642                   if(configPOs && configPOs.options.postbuildCommands && configPOs.options.postbuildCommands.count)
2643                   {
2644                      for(s : configPOs.options.postbuildCommands)
2645                         if(s && s[0]) f.Printf("\t%s\n", s);
2646                   }
2647                }
2648             }
2649             if(ifCount)
2650             {
2651                int c;
2652                for(c = 0; c < ifCount; c++)
2653                   f.Printf("endif\n");
2654             }
2655          }
2656          f.Printf("\n");
2657
2658          f.Printf("# SYMBOL RULES\n\n");
2659          {
2660             Map<Platform, bool> excludedPlatforms { };
2661             topNode.GenMakefilePrintSymbolRules(f, this, config, excludedPlatforms);
2662             delete excludedPlatforms;
2663          }
2664
2665          f.Printf("# C OBJECT RULES\n\n");
2666          {
2667             Map<Platform, bool> excludedPlatforms { };
2668             topNode.GenMakefilePrintCObjectRules(f, this, config, excludedPlatforms);
2669             delete excludedPlatforms;
2670          }
2671
2672          f.Printf("# OBJECT RULES\n\n");
2673          // todo call this still but only generate rules whith specific options
2674          // see we-have-file-specific-options in ProjectNode.ec
2675          {
2676             Map<Platform, bool> excludedPlatforms { };
2677             topNode.GenMakefilePrintObjectRules(f, this, namesInfo, config, excludedPlatforms);
2678             delete excludedPlatforms;
2679          }
2680
2681          if(numCObjects)
2682             GenMakefilePrintMainObjectRule(f, config);
2683
2684          f.Printf("clean: objdir%s\n", sameObjTargetDirs ? "" : " targetdir");
2685          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) " : "");
2686          OutputCleanActions(f, "OBJECTS", objectsParts);
2687          if(numCObjects)
2688          {
2689             OutputCleanActions(f, "COBJECTS", eCsourcesParts);
2690             OutputCleanActions(f, "BOWLS", eCsourcesParts);
2691             OutputCleanActions(f, "IMPORTS", eCsourcesParts);
2692             OutputCleanActions(f, "SYMBOLS", eCsourcesParts);
2693          }
2694          f.Printf("\n");
2695
2696          f.Printf("realclean: clean\n");
2697          f.Printf("\t$(call rmrq,$(OBJ))\n");
2698          if(!sameObjTargetDirs)
2699             f.Printf("\t$(call rmdirq,%s)\n", targetDirExpNoSpaces);
2700          f.Printf("\n");
2701
2702          delete f;
2703
2704          listItems.Free();
2705          delete listItems;
2706          varStringLenDiffs.Free();
2707          delete varStringLenDiffs;
2708          namesInfo.Free();
2709          delete namesInfo;
2710
2711          result = true;
2712       }
2713
2714       // ChangeWorkingDir(oldDirectory);
2715       // delete pathBackup;
2716
2717       if(config)
2718          config.makingModified = false;
2719       return result;
2720    }
2721
2722    void GenMakefilePrintMainObjectRule(File f, ProjectConfig config)
2723    {
2724       char extension[MAX_EXTENSION] = "c";
2725       char modulePath[MAX_LOCATION];
2726       char fixedModuleName[MAX_FILENAME];
2727       DualPipe dep;
2728       char command[2048];
2729       char objDirNoSpaces[MAX_LOCATION];
2730       String objDirExp = GetObjDirExpression(config);
2731
2732       ReplaceSpaces(objDirNoSpaces, objDirExp);
2733       ReplaceSpaces(fixedModuleName, moduleName);
2734       
2735       //sprintf(fixedModuleName, "%s.main", fixedPrjName);
2736       //strcat(fixedModuleName, ".main");
2737
2738 #if 0       // TODO: Fix nospaces stuff
2739       // *** Dependency command ***
2740       sprintf(command, "gcc -MT $(OBJ)%s$(O) -MM $(OBJ)%s.c", fixedModuleName, fixedModuleName);
2741
2742       // System Includes (from global settings)
2743       for(item : compiler.dirs[Includes])
2744       {
2745          strcat(command, " -isystem ");
2746          if(strchr(item.name, ' '))
2747          {
2748             strcat(command, "\"");
2749             strcat(command, item);
2750             strcat(command, "\"");
2751          }
2752          else
2753             strcat(command, item);
2754       }
2755
2756       for(item = includeDirs.first; item; item = item.next)
2757       {
2758          strcat(command, " -I");
2759          if(strchr(item.name, ' '))
2760          {
2761             strcat(command, "\"");
2762             strcat(command, item.name);
2763             strcat(command, "\"");
2764          }
2765          else
2766             strcat(command, item.name);
2767       }
2768       for(item = preprocessorDefs.first; item; item = item.next)
2769       {
2770          strcat(command, " -D");
2771          strcat(command, item.name);
2772       }
2773
2774       // Execute it
2775       if((dep = DualPipeOpen(PipeOpenMode { output = 1, error = 1, input = 2 }, command)))
2776       {
2777          char line[1024];
2778          bool result = true;
2779          bool firstLine = true;
2780
2781          // To do some time: auto save external dependencies?
2782          while(!dep.Eof())
2783          {
2784             if(dep.GetLine(line, sizeof(line)-1))
2785             {
2786                if(firstLine)
2787                {
2788                   char * colon = strstr(line, ":");
2789                   if(strstr(line, "No such file") || strstr(line, ",") || (colon && strstr(colon+1, ":")))
2790                   {
2791                      result = false;
2792                      break;
2793                   }
2794                   firstLine = false;
2795                }
2796                f.Puts(line);
2797                f.Puts("\n");
2798             }
2799             if(!result) break;
2800          }
2801          delete dep;
2802
2803          // If we failed to generate dependencies...
2804          if(!result)
2805          {
2806 #endif
2807             f.Printf("$(OBJ)$(MODULE).main$(O): $(OBJ)$(MODULE).main.c\n");
2808 #if 0
2809          }
2810       }
2811 #endif
2812
2813       f.Printf("\t$(CC) $(CFLAGS) $(FVISIBILITY) -c $(OBJ)$(MODULE).main.%s -o $(OBJ)$(MODULE).main$(O)\n\n", extension);
2814    }
2815
2816    void MatchProjectAndConfigPlatformOptions(ProjectConfig config, Platform platform,
2817          PlatformOptions * projectPlatformOptions, PlatformOptions * configPlatformOptions)
2818    {
2819       *projectPlatformOptions = null;
2820       *configPlatformOptions = null;
2821       if(platforms)
2822       {
2823          for(p : platforms)
2824          {
2825             if(!strcmpi(p.name, platform))
2826             {
2827                *projectPlatformOptions = p;
2828                break;
2829             }
2830          }
2831       }
2832       if(config && config.platforms)
2833       {
2834          for(p : config.platforms)
2835          {
2836             if(!strcmpi(p.name, platform))
2837             {
2838                *configPlatformOptions = p;
2839                break;
2840             }
2841          }
2842       }
2843    }
2844 }
2845
2846 Project LegacyBinaryLoadProject(File f, char * filePath)
2847 {
2848    Project project = null;
2849    char signature[sizeof(epjSignature)];
2850
2851    f.Read(signature, sizeof(signature), 1);
2852    if(!strncmp(signature, (char *)epjSignature, sizeof(epjSignature)))
2853    {
2854       char topNodePath[MAX_LOCATION];
2855       /*ProjectConfig newConfig
2856       {
2857          name = CopyString("Default");
2858          makingModified = true;
2859          compilingModified = true;
2860          linkingModified = true;
2861          options = { };
2862       };*/
2863
2864       project = Project { options = { } };
2865       LegacyBinaryLoadNode(project.topNode, f);
2866       delete project.topNode.path;
2867       GetWorkingDir(topNodePath, sizeof(topNodePath)-1);
2868       MakeSlashPath(topNodePath);
2869
2870       PathCatSlash(topNodePath, filePath);
2871       project.filePath = topNodePath;
2872       
2873       /* THIS IS ALREADY DONE BY filePath property
2874       StripLastDirectory(topNodePath, topNodePath);
2875       project.topNode.path = CopyString(topNodePath);
2876       */
2877       // Shouldn't this be done BEFORE the StripLastDirectory? project.filePath = topNodePath;
2878       
2879       // newConfig.options.defaultNameSpace = "";
2880       /*newConfig.objDir.dir = "obj";
2881       newConfig.targetDir.dir = "";*/
2882
2883       //project.configurations = { [ newConfig ] };
2884       //project.config = newConfig;
2885
2886       // Project Settings
2887       if(!f.Eof())
2888       {
2889          int temp;
2890          int len,c, count;
2891          String targetFileName, targetDirectory, objectsDirectory;
2892
2893          // { executable = 0, sharedLibrary = 1, staticLibrary = 2 };
2894          f.Read(&temp, sizeof(int),1);
2895          switch(temp)
2896          {
2897             case 0: project.options.targetType = executable; break;
2898             case 1: project.options.targetType = sharedLibrary; break;
2899             case 2: project.options.targetType = staticLibrary; break;
2900          }
2901
2902          f.Read(&len, sizeof(int),1);
2903          targetFileName = new char[len+1];
2904          f.Read(targetFileName, sizeof(char), len+1);
2905          project.options.targetFileName = targetFileName;
2906          delete targetFileName;
2907
2908          f.Read(&len, sizeof(int),1);
2909          targetDirectory = new char[len+1];
2910          f.Read(targetDirectory, sizeof(char), len+1);
2911          project.options.targetDirectory = targetDirectory;
2912          delete targetDirectory;
2913
2914          f.Read(&len, sizeof(int),1);
2915          objectsDirectory = new byte[len+1];
2916          f.Read(objectsDirectory, sizeof(char), len+1);
2917          project.options.objectsDirectory = objectsDirectory;
2918          delete objectsDirectory;
2919
2920          f.Read(&temp, sizeof(int),1);
2921          project./*config.*/options.debug = temp ? true : false;
2922          f.Read(&temp, sizeof(int),1);         
2923          project./*config.*/options.optimization = temp ? speed : none;
2924          f.Read(&temp, sizeof(int),1);
2925          project./*config.*/options.profile = temp ? true : false;
2926          f.Read(&temp, sizeof(int),1);
2927          project.options.warnings = temp ? all : unset;
2928
2929          f.Read(&count, sizeof(int),1);
2930          if(count)
2931          {
2932             project.options.includeDirs = { };
2933             for(c = 0; c < count; c++)
2934             {
2935                char * name;
2936                f.Read(&len, sizeof(int),1);
2937                name = new char[len+1];
2938                f.Read(name, sizeof(char), len+1);
2939                project.options.includeDirs.Add(name);
2940             }
2941          }
2942
2943          f.Read(&count, sizeof(int),1);
2944          if(count)
2945          {
2946             project.options.libraryDirs = { };
2947             for(c = 0; c < count; c++)
2948             {
2949                char * name;            
2950                f.Read(&len, sizeof(int),1);
2951                name = new char[len+1];
2952                f.Read(name, sizeof(char), len+1);
2953                project.options.libraryDirs.Add(name);
2954             }
2955          }
2956
2957          f.Read(&count, sizeof(int),1);
2958          if(count)
2959          {
2960             project.options.libraries = { };
2961             for(c = 0; c < count; c++)
2962             {
2963                char * name;
2964                f.Read(&len, sizeof(int),1);
2965                name = new char[len+1];
2966                f.Read(name, sizeof(char), len+1);
2967                project.options.libraries.Add(name);
2968             }
2969          }
2970
2971          f.Read(&count, sizeof(int),1);
2972          if(count)
2973          {
2974             project.options.preprocessorDefinitions = { };
2975             for(c = 0; c < count; c++)
2976             {
2977                char * name;
2978                f.Read(&len, sizeof(int),1);
2979                name = new char[len+1];
2980                f.Read(name, sizeof(char), len+1);
2981                project.options.preprocessorDefinitions.Add(name);
2982             }
2983          }
2984
2985          f.Read(&temp, sizeof(int),1);
2986          project.options.console = temp ? true : false;
2987       }
2988
2989       for(node : project.topNode.files)
2990       {
2991          if(node.type == resources)
2992          {
2993             project.resNode = node;
2994             break;
2995          }
2996       }
2997    }
2998    else
2999       f.Seek(0, start);
3000    return project;
3001 }
3002
3003 void ProjectConfig::LegacyProjectConfigLoad(File f)
3004 {  
3005    delete options;
3006    options = { };
3007    while(!f.Eof())
3008    {
3009       char buffer[65536];
3010       char section[128];
3011       char subSection[128];
3012       char * equal;
3013       int len;
3014       uint pos;
3015       
3016       pos = f.Tell();
3017       f.GetLine(buffer, 65536 - 1);
3018       TrimLSpaces(buffer, buffer);
3019       TrimRSpaces(buffer, buffer);
3020       if(strlen(buffer))
3021       {
3022          if(buffer[0] == '-')
3023          {
3024             equal = &buffer[0];
3025             equal[0] = ' ';
3026             TrimLSpaces(equal, equal);
3027             if(!strcmpi(subSection, "LibraryDirs"))
3028             {
3029                if(!options.libraryDirs)
3030                   options.libraryDirs = { [ CopyString(equal) ] };
3031                else
3032                   options.libraryDirs.Add(CopyString(equal));
3033             }
3034             else if(!strcmpi(subSection, "IncludeDirs"))
3035             {
3036                if(!options.includeDirs)
3037                   options.includeDirs = { [ CopyString(equal) ] };
3038                else
3039                   options.includeDirs.Add(CopyString(equal));
3040             }
3041          }
3042          else if(buffer[0] == '+')
3043          {
3044             if(name)
3045             {
3046                f.Seek(pos, start);
3047                break;
3048             }
3049             else
3050             {
3051                equal = &buffer[0];
3052                equal[0] = ' ';
3053                TrimLSpaces(equal, equal);
3054                delete name; name = CopyString(equal); // property::name = equal;
3055             }
3056          }
3057          else if(!strcmpi(buffer, "Compiler Options"))
3058             strcpy(section, buffer);
3059          else if(!strcmpi(buffer, "IncludeDirs"))
3060             strcpy(subSection, buffer);
3061          else if(!strcmpi(buffer, "Linker Options"))
3062             strcpy(section, buffer);
3063          else if(!strcmpi(buffer, "LibraryDirs"))
3064             strcpy(subSection, buffer);
3065          else if(!strcmpi(buffer, "Files") || !strcmpi(buffer, "Resources"))
3066          {
3067             f.Seek(pos, start);
3068             break;
3069          }
3070          else
3071          {
3072             equal = strstr(buffer, "=");
3073             if(equal)
3074             {
3075                equal[0] = '\0';
3076                TrimRSpaces(buffer, buffer);
3077                equal++;
3078                TrimLSpaces(equal, equal);
3079                if(!strcmpi(buffer, "Target Name"))
3080                   options.targetFileName = /*CopyString(*/equal/*)*/;
3081                else if(!strcmpi(buffer, "Target Type"))
3082                {
3083                   if(!strcmpi(equal, "Executable"))
3084                      options.targetType = executable;
3085                   else if(!strcmpi(equal, "Shared"))
3086                      options.targetType = sharedLibrary;
3087                   else if(!strcmpi(equal, "Static"))
3088                      options.targetType = staticLibrary;
3089                   else
3090                      options.targetType = executable;
3091                }
3092                else if(!strcmpi(buffer, "Target Directory"))
3093                   options.targetDirectory = /*CopyString(*/equal/*)*/;
3094                else if(!strcmpi(buffer, "Console"))
3095                   options.console = ParseTrueFalseValue(equal);
3096                else if(!strcmpi(buffer, "Libraries"))
3097                {
3098                   if(!options.libraries) options.libraries = { };
3099                   ParseArrayValue(options.libraries, equal);
3100                }
3101                else if(!strcmpi(buffer, "Intermediate Directory"))
3102                   options.objectsDirectory = /*CopyString(*/equal/*)*/; //objDir.expression = equal;
3103                else if(!strcmpi(buffer, "Debug"))
3104                   options.debug = ParseTrueFalseValue(equal);
3105                else if(!strcmpi(buffer, "Optimize"))
3106                {
3107                   if(!strcmpi(equal, "None"))
3108                      options.optimization = none;
3109                   else if(!strcmpi(equal, "Speed") || !strcmpi(equal, "True"))
3110                      options.optimization = speed;
3111                   else if(!strcmpi(equal, "Size"))
3112                      options.optimization = size;
3113                   else
3114                      options.optimization = none;
3115                }
3116                else if(!strcmpi(buffer, "Compress"))
3117                   options.compress = ParseTrueFalseValue(equal);
3118                else if(!strcmpi(buffer, "Profile"))
3119                   options.profile = ParseTrueFalseValue(equal);
3120                else if(!strcmpi(buffer, "AllWarnings"))
3121                   options.warnings = ParseTrueFalseValue(equal) ? all : unset;
3122                else if(!strcmpi(buffer, "MemoryGuard"))
3123                   options.memoryGuard = ParseTrueFalseValue(equal);
3124                else if(!strcmpi(buffer, "Default Name Space"))
3125                   options.defaultNameSpace = CopyString(equal);
3126                else if(!strcmpi(buffer, "Strict Name Spaces"))
3127                   options.strictNameSpaces = ParseTrueFalseValue(equal);
3128                else if(!strcmpi(buffer, "Preprocessor Definitions"))
3129                {
3130                   if(!options.preprocessorDefinitions) options.preprocessorDefinitions = { };
3131                   ParseArrayValue(options.preprocessorDefinitions, equal);
3132                }
3133             }
3134          }
3135       }
3136    }
3137    if(!options.targetDirectory && options.objectsDirectory)
3138       options.targetDirectory = /*CopyString(*/options.objectsDirectory/*)*/;
3139    //if(!objDir.dir) objDir.dir = "obj";
3140    //if(!targetDir.dir) targetDir.dir = "";
3141    // if(!targetName) property::targetName = "";   // How can a targetFileName be nothing???
3142    // if(!defaultNameSpace) property::defaultNameSpace = "";
3143    makingModified = true;
3144 }
3145
3146 Project LegacyAsciiLoadProject(File f, char * filePath)
3147 {
3148    Project project = null;
3149    ProjectNode node = null;
3150    int pos;
3151    char parentPath[MAX_LOCATION];
3152    char section[128] = "";
3153    char subSection[128] = "";
3154    ProjectNode parent;
3155    bool configurationsPresent = false;
3156
3157    f.Seek(0, start);
3158    while(!f.Eof())
3159    {
3160       char buffer[65536];
3161       //char version[16];
3162       char * equal;
3163       int len;
3164       pos = f.Tell();
3165       f.GetLine(buffer, 65536 - 1);
3166       TrimLSpaces(buffer, buffer);
3167       TrimRSpaces(buffer, buffer);
3168       if(strlen(buffer))
3169       {
3170          if(buffer[0] == '-' || buffer[0] == '=')
3171          {
3172             bool simple = buffer[0] == '-';
3173             equal = &buffer[0];
3174             equal[0] = ' ';
3175             TrimLSpaces(equal, equal);
3176             if(!strcmpi(section, "Target") && !strcmpi(subSection, "LibraryDirs"))
3177             {
3178                if(!project.config.options.libraryDirs)
3179                   project.config.options.libraryDirs = { [ CopyString(equal) ] };
3180                else
3181                   project.config.options.libraryDirs.Add(CopyString(equal));
3182             }
3183             else if(!strcmpi(section, "Target") && !strcmpi(subSection, "IncludeDirs"))
3184             {
3185                if(!project.config.options.includeDirs)
3186                   project.config.options.includeDirs = { [ CopyString(equal) ] };
3187                else
3188                   project.config.options.includeDirs.Add(CopyString(equal));
3189             }
3190             else if(!strcmpi(section, "Target") && (!strcmpi(subSection, "Files") || !strcmpi(subSection, "Resources")))
3191             {
3192                len = strlen(equal);
3193                if(len)
3194                {
3195                   char temp[MAX_LOCATION];
3196                   ProjectNode child { };
3197                   // We don't need to do this anymore, fileName is just a property that sets name & path
3198                   // child.fileName = CopyString(equal);
3199                   if(simple)
3200                   {
3201                      child.name = CopyString(equal);
3202                      child.path = CopyString(parentPath);
3203                   }
3204                   else
3205                   {
3206                      GetLastDirectory(equal, temp);
3207                      child.name = CopyString(temp);
3208                      StripLastDirectory(equal, temp);
3209                      child.path = CopyString(temp);
3210                   }
3211                   child.nodeType = file;
3212                   child.parent = parent;
3213                   child.indent = parent.indent + 1;
3214                   child.type = file;
3215                   child.icon = NodeIcons::SelectFileIcon(child.name);
3216                   parent.files.Add(child);
3217                   node = child;
3218                   //child = null;
3219                }
3220                else
3221                {
3222                   StripLastDirectory(parentPath, parentPath);
3223                   parent = parent.parent;
3224                }
3225             }
3226          }
3227          else if(buffer[0] == '+')
3228          {
3229             equal = &buffer[0];
3230             equal[0] = ' ';
3231             TrimLSpaces(equal, equal);
3232             if(!strcmpi(section, "Target") && (!strcmpi(subSection, "Files") || !strcmpi(subSection, "Resources")))
3233             {
3234                char temp[MAX_LOCATION];
3235                ProjectNode child { };
3236                // NEW: Folders now have a path set like files
3237                child.name = CopyString(equal);
3238                strcpy(temp, parentPath);
3239                PathCatSlash(temp, child.name);
3240                child.path = CopyString(temp);
3241
3242                child.parent = parent;
3243                child.indent = parent.indent + 1;
3244                child.type = folder;
3245                child.nodeType = folder;
3246                child.files = { };
3247                child.icon = folder;
3248                PathCatSlash(parentPath, child.name);
3249                parent.files.Add(child);
3250                parent = child;
3251                node = child;
3252                //child = null;
3253             }
3254             else if(!strcmpi(section, "Configurations"))
3255             {
3256                ProjectConfig newConfig
3257                {
3258                   makingModified = true;
3259                   options = { };
3260                };
3261                f.Seek(pos, start);
3262                LegacyProjectConfigLoad(newConfig, f);
3263                project.configurations.Add(newConfig);
3264             }
3265          }
3266          else if(!strcmpi(buffer, "ECERE Project File"));
3267          else if(!strcmpi(buffer, "Version 0a"))
3268             ; //strcpy(version, "0a");
3269          else if(!strcmpi(buffer, "Version 0.1a"))
3270             ; //strcpy(version, "0.1a");
3271          else if(!strcmpi(buffer, "Configurations"))
3272          {
3273             project.configurations.Free();
3274             project.config = null;
3275             strcpy(section, buffer);
3276             configurationsPresent = true;
3277          }
3278          else if(!strcmpi(buffer, "Target") || !strnicmp(buffer, "Target \"", strlen("Target \"")))
3279          {
3280             ProjectConfig newConfig { name = CopyString("Default"), options = { } };
3281             char topNodePath[MAX_LOCATION];
3282             // newConfig.defaultNameSpace = "";
3283             //newConfig.objDir.dir = "obj";
3284             //newConfig.targetDir.dir = "";
3285             project = Project { /*options = { }*/ };
3286             project.configurations = { [ newConfig ] };
3287             project.config = newConfig;
3288             // if(project.topNode.path) delete project.topNode.path;
3289             GetWorkingDir(topNodePath, sizeof(topNodePath)-1);
3290             MakeSlashPath(topNodePath);
3291             PathCatSlash(topNodePath, filePath);
3292             project.filePath = topNodePath;
3293             parentPath[0] = '\0';
3294             parent = project.topNode;
3295             node = parent;
3296             strcpy(section, "Target");
3297             equal = &buffer[6];
3298             if(equal[0] == ' ')
3299             {
3300                equal++;
3301                if(equal[0] == '\"')
3302                {
3303                   StripQuotes(equal, equal);
3304                   delete project.moduleName; project.moduleName = CopyString(equal);
3305                }
3306             }
3307          }
3308          else if(!strcmpi(buffer, "Compiler Options"));
3309          else if(!strcmpi(buffer, "IncludeDirs"))
3310             strcpy(subSection, buffer);
3311          else if(!strcmpi(buffer, "Linker Options"));
3312          else if(!strcmpi(buffer, "LibraryDirs"))
3313             strcpy(subSection, buffer);
3314          else if(!strcmpi(buffer, "Files"))
3315          {
3316             strcpy(section, "Target");
3317             strcpy(subSection, buffer);
3318          }
3319          else if(!strcmpi(buffer, "Resources"))
3320          {
3321             ProjectNode child { };
3322             parent.files.Add(child);
3323             child.parent = parent;
3324             child.indent = parent.indent + 1;
3325             child.name = CopyString(buffer);
3326             child.path = CopyString("");
3327             child.type = resources;
3328             child.files = { };
3329             child.icon = archiveFile;
3330             project.resNode = child;
3331             parent = child;
3332             node = child;
3333             strcpy(subSection, buffer);
3334          }
3335          else
3336          {
3337             equal = strstr(buffer, "=");
3338             if(equal)
3339             {
3340                equal[0] = '\0';
3341                TrimRSpaces(buffer, buffer);
3342                equal++;
3343                TrimLSpaces(equal, equal);
3344
3345                if(!strcmpi(section, "Target"))
3346                {
3347                   if(!strcmpi(buffer, "Build Exclusions"))
3348                   {
3349                      if(!strcmpi(section, "Target") && !strcmpi(subSection, "Files"))
3350                      {
3351                         /*if(node && node.type != NodeTypes::project)
3352                            ParseListValue(node.buildExclusions, equal);*/
3353                      }
3354                   }
3355                   else if(!strcmpi(buffer, "Path") && !strcmpi(subSection, "Resources"))
3356                   {
3357                      delete project.resNode.path;
3358                      project.resNode.path = CopyString(equal);
3359                      PathCatSlash(parentPath, equal);
3360                   }
3361
3362                   // Config Settings
3363                   else if(!strcmpi(buffer, "Intermediate Directory"))
3364                      project.config.options.objectsDirectory = /*CopyString(*/equal/*)*/; //objDir.expression = equal;
3365                   else if(!strcmpi(buffer, "Debug"))
3366                      project.config.options.debug = ParseTrueFalseValue(equal);
3367                   else if(!strcmpi(buffer, "Optimize"))
3368                   {
3369                      if(!strcmpi(equal, "None"))
3370                         project.config.options.optimization = none;
3371                      else if(!strcmpi(equal, "Speed") || !strcmpi(equal, "True"))
3372                         project.config.options.optimization = speed;
3373                      else if(!strcmpi(equal, "Size"))
3374                         project.config.options.optimization = size;
3375                      else
3376                         project.config.options.optimization = none;
3377                   }
3378                   else if(!strcmpi(buffer, "Profile"))
3379                      project.config.options.profile = ParseTrueFalseValue(equal);
3380                   else if(!strcmpi(buffer, "MemoryGuard"))
3381                      project.config.options.memoryGuard = ParseTrueFalseValue(equal);
3382                   else
3383                   {
3384                      if(!project.options) project.options = { };
3385
3386                      // Project Wide Settings (All configs)
3387                      if(!strcmpi(buffer, "Target Name"))
3388                         project.options.targetFileName = /*CopyString(*/equal/*)*/;
3389                      else if(!strcmpi(buffer, "Target Type"))
3390                      {
3391                         if(!strcmpi(equal, "Executable"))
3392                            project.options.targetType = executable;
3393                         else if(!strcmpi(equal, "Shared"))
3394                            project.options.targetType = sharedLibrary;
3395                         else if(!strcmpi(equal, "Static"))
3396                            project.options.targetType = staticLibrary;
3397                         else
3398                            project.options.targetType = executable;
3399                      }
3400                      else if(!strcmpi(buffer, "Target Directory"))
3401                         project.options.targetDirectory = /*CopyString(*/equal/*)*/;
3402                      else if(!strcmpi(buffer, "Console"))
3403                         project.options.console = ParseTrueFalseValue(equal);
3404                      else if(!strcmpi(buffer, "Libraries"))
3405                      {
3406                         if(!project.options.libraries) project.options.libraries = { };
3407                         ParseArrayValue(project.options.libraries, equal);
3408                      }
3409                      else if(!strcmpi(buffer, "AllWarnings"))
3410                         project.options.warnings = ParseTrueFalseValue(equal) ? all : unset;
3411                      else if(!strcmpi(buffer, "Preprocessor Definitions"))
3412                      {
3413                         if(!strcmpi(section, "Target") && !strcmpi(subSection, "Files"))
3414                         {
3415                            /*if(node && (node.type == NodeTypes::project || (node.type == file && !node.isInResources) || node.type == folder))
3416                               ParseListValue(node.preprocessorDefs, equal);*/
3417                         }
3418                         else
3419                         {
3420                            if(!project.options.preprocessorDefinitions) project.options.preprocessorDefinitions = { };
3421                            ParseArrayValue(project.options.preprocessorDefinitions, equal);
3422                         }
3423                      }
3424                   }
3425                }
3426             }
3427          }
3428       }
3429    }
3430    parent = null;
3431
3432    SplitPlatformLibraries(project);
3433
3434    if(configurationsPresent)
3435       CombineIdenticalConfigOptions(project);
3436    return project;
3437 }
3438
3439 void SplitPlatformLibraries(Project project)
3440 {
3441    if(project && project.configurations)
3442    {
3443       for(cfg : project.configurations)
3444       {
3445          if(cfg.options.libraries && cfg.options.libraries.count)
3446          {
3447             Iterator<String> it { cfg.options.libraries };
3448             while(it.Next())
3449             {
3450                String l = it.data;
3451                char * platformName = strstr(l, ":");
3452                if(platformName)
3453                {
3454                   PlatformOptions platform = null;
3455                   platformName++;
3456                   if(!cfg.platforms) cfg.platforms = { };
3457                   for(p : cfg.platforms)
3458                   {
3459                      if(!strcmpi(platformName, p.name))
3460                      {
3461                         platform = p;
3462                         break;
3463                      }
3464                   }
3465                   if(!platform)
3466                   {
3467                      platform = { name = CopyString(platformName), options = { libraries = { } } };
3468                      cfg.platforms.Add(platform);
3469                   }
3470                   *(platformName-1) = 0;
3471                   platform.options.libraries.Add(CopyString(l));
3472
3473                   cfg.options.libraries.Delete(it.pointer);
3474                   it.pointer = null;
3475                }
3476             }
3477          }
3478       }      
3479    }
3480 }
3481
3482 void CombineIdenticalConfigOptions(Project project)
3483 {
3484    if(project && project.configurations && project.configurations.count)
3485    {
3486       DataMember member;
3487       ProjectOptions nullOptions { };
3488       ProjectConfig firstConfig = null;
3489       for(cfg : project.configurations)
3490       {
3491          if(cfg.options.targetType != staticLibrary)
3492          {
3493             firstConfig = cfg;
3494             break;
3495          }
3496       }
3497       if(!firstConfig)
3498          firstConfig = project.configurations.firstIterator.data;
3499
3500       for(member = class(ProjectOptions).membersAndProperties.first; member; member = member.next)
3501       {
3502          if(!member.isProperty)
3503          {
3504             Class type = eSystem_FindClass(__thisModule, member.dataTypeString);
3505             if(type)
3506             {
3507                bool same = true;
3508
3509                for(cfg : project.configurations)
3510                {
3511                   if(cfg != firstConfig)
3512                   {
3513                      if(cfg.options.targetType != staticLibrary)
3514                      {
3515                         int result;
3516                         
3517                         if(type.type == noHeadClass || type.type == normalClass)
3518                         {
3519                            result = type._vTbl[__ecereVMethodID_class_OnCompare](type, 
3520                               *(void **)((byte *)firstConfig.options + member.offset + member._class.offset),
3521                               *(void **)((byte *)cfg.options         + member.offset + member._class.offset));
3522                         }
3523                         else
3524                         {
3525                            result = type._vTbl[__ecereVMethodID_class_OnCompare](type, 
3526                               (byte *)firstConfig.options + member.offset + member._class.offset,
3527                               (byte *)cfg.options         + member.offset + member._class.offset);
3528                         }
3529                         if(result)
3530                         {
3531                            same = false;
3532                            break;
3533                         }
3534                      }
3535                   }                  
3536                }
3537                if(same)
3538                {
3539                   if(type.type == noHeadClass || type.type == normalClass)
3540                   {
3541                      if(!type._vTbl[__ecereVMethodID_class_OnCompare](type, 
3542                         *(void **)((byte *)firstConfig.options + member.offset + member._class.offset),
3543                         *(void **)((byte *)nullOptions         + member.offset + member._class.offset)))
3544                         continue;
3545                   }
3546                   else
3547                   {
3548                      if(!type._vTbl[__ecereVMethodID_class_OnCompare](type, 
3549                         (byte *)firstConfig.options + member.offset + member._class.offset,
3550                         (byte *)nullOptions         + member.offset + member._class.offset))
3551                         continue;
3552                   }
3553
3554                   if(!project.options) project.options = { };
3555                   
3556                   /*if(type.type == noHeadClass || type.type == normalClass)
3557                   {
3558                      type._vTbl[__ecereVMethodID_class_OnCopy](type, 
3559                         (byte *)project.options + member.offset + member._class.offset,
3560                         *(void **)((byte *)firstConfig.options + member.offset + member._class.offset));
3561                   }
3562                   else
3563                   {
3564                      void * address = (byte *)firstConfig.options + member.offset + member._class.offset;
3565                      // TOFIX: ListBox::SetData / OnCopy mess
3566                      type._vTbl[__ecereVMethodID_class_OnCopy](type, 
3567                         (byte *)project.options + member.offset + member._class.offset,
3568                         (type.typeSize > 4) ? address : 
3569                            ((type.typeSize == 4) ? (void *)*(uint32 *)address : 
3570                               ((type.typeSize == 2) ? (void *)*(uint16*)address : 
3571                                  (void *)*(byte *)address )));                              
3572                   }*/
3573                   memcpy(
3574                      (byte *)project.options + member.offset + member._class.offset,
3575                      (byte *)firstConfig.options + member.offset + member._class.offset, type.typeSize);
3576
3577                   for(cfg : project.configurations)
3578                   {
3579                      if(cfg.options.targetType == staticLibrary)
3580                      {
3581                         int result;
3582                         
3583                         if(type.type == noHeadClass || type.type == normalClass)
3584                         {
3585                            result = type._vTbl[__ecereVMethodID_class_OnCompare](type, 
3586                               *(void **)((byte *)firstConfig.options + member.offset + member._class.offset),
3587                               *(void **)((byte *)cfg.options         + member.offset + member._class.offset));
3588                         }
3589                         else
3590                         {
3591                            result = type._vTbl[__ecereVMethodID_class_OnCompare](type, 
3592                               (byte *)firstConfig.options + member.offset + member._class.offset,
3593                               (byte *)cfg.options         + member.offset + member._class.offset);
3594                         }
3595                         if(result)
3596                            continue;
3597                      }
3598                      if(cfg != firstConfig)
3599                      {
3600                         if(type.type == noHeadClass || type.type == normalClass)
3601                         {
3602                            type._vTbl[__ecereVMethodID_class_OnFree](type, 
3603                               *(void **)((byte *)cfg.options + member.offset + member._class.offset));
3604                         }
3605                         else
3606                         {
3607                            type._vTbl[__ecereVMethodID_class_OnFree](type, 
3608                               (byte *)cfg.options + member.offset + member._class.offset);
3609                         }
3610                         memset((byte *)cfg.options + member.offset + member._class.offset, 0, type.typeSize);
3611                      }                     
3612                   }
3613                   memset((byte *)firstConfig.options + member.offset + member._class.offset, 0, type.typeSize);
3614                }
3615             }
3616          }
3617       }
3618       delete nullOptions;
3619
3620       // Compare Platform Specific Settings
3621       {
3622          bool same = true;
3623          for(cfg : project.configurations)
3624          {
3625             if(cfg != firstConfig && cfg.options.targetType != staticLibrary && (firstConfig.platforms || cfg.platforms) &&
3626                ((!firstConfig.platforms && cfg.platforms) || firstConfig.platforms.OnCompare(cfg.platforms)))
3627             {
3628                same = false;
3629                break;
3630             }
3631          }
3632          if(same && firstConfig.platforms)
3633          {
3634             for(cfg : project.configurations)
3635             {
3636                if(cfg.options.targetType == staticLibrary && firstConfig.platforms.OnCompare(cfg.platforms))
3637                   continue;
3638                if(cfg != firstConfig)
3639                {
3640                   cfg.platforms.Free();
3641                   delete cfg.platforms;
3642                }
3643             }
3644             project.platforms = firstConfig.platforms;
3645             firstConfig.platforms = null;
3646          }
3647       }
3648
3649       // Static libraries can't contain libraries
3650       for(cfg : project.configurations)
3651       {
3652          if(cfg.options.targetType == staticLibrary)
3653          {
3654             if(!cfg.options.libraries) cfg.options.libraries = { };
3655             cfg.options.libraries.Free();
3656          }
3657       }
3658    }
3659 }
3660
3661 Project LoadProject(char * filePath)
3662 {
3663    Project project = null;
3664    File f = FileOpen(filePath, read);
3665    if(f)
3666    {
3667       project = LegacyBinaryLoadProject(f, filePath);
3668       if(!project)
3669       {
3670          JSONParser parser { f = f };
3671          JSONResult result = parser.GetObject(class(Project), &project);
3672          if(project)
3673          {
3674             char insidePath[MAX_LOCATION];
3675
3676             delete project.topNode.files;
3677             if(!project.files) project.files = { };
3678             project.topNode.files = project.files;
3679             project.resNode = project.topNode.Add(project, "Resources", project.topNode.files.last, resources, archiveFile, false);
3680             delete project.resNode.path;
3681             project.resNode.path = project.resourcesPath;
3682             project.resourcesPath = null;
3683             project.resNode.nodeType = (ProjectNodeType)-1;
3684             delete project.resNode.files;
3685             project.resNode.files = project.resources;
3686             project.files = null;
3687             project.resources = null;
3688             if(!project.configurations) project.configurations = { };
3689
3690             {
3691                char topNodePath[MAX_LOCATION];
3692                GetWorkingDir(topNodePath, sizeof(topNodePath)-1);
3693                MakeSlashPath(topNodePath);
3694                PathCatSlash(topNodePath, filePath);
3695                project.filePath = topNodePath;//filePath;
3696             }
3697
3698             project.topNode.FixupNode(insidePath);
3699          }
3700          delete parser;
3701       }
3702       if(!project)
3703          project = LegacyAsciiLoadProject(f, filePath);
3704
3705       delete f;
3706
3707       if(project)
3708       {
3709          if(!project.options) project.options = { };
3710          if(!project.config && project.configurations)
3711             project.config = project.configurations.firstIterator.data;
3712
3713          if(!project.resNode)
3714          {
3715             project.resNode = project.topNode.Add(project, "Resources", project.topNode.files.last, resources, archiveFile, false);
3716          }
3717          
3718          if(!project.moduleName)
3719             project.moduleName = CopyString(project.name);
3720          if(project.config && 
3721             (!project.options || !project.options.targetFileName || !project.options.targetFileName[0]) &&
3722             (!project.config.options.targetFileName || !project.config.options.targetFileName[0]))
3723          {
3724             //delete project.config.options.targetFileName;
3725             
3726             project.options.targetFileName = /*CopyString(*/project.moduleName/*)*/;
3727             project.config.options.optimization = none;
3728             project.config.options.debug = true;
3729             //project.config.options.warnings = unset;
3730             project.config.options.memoryGuard = false;
3731             project.config.compilingModified = true;
3732             project.config.linkingModified = true;
3733          }
3734          else if(!project.topNode.name && project.config)
3735          {
3736             project.topNode.name = CopyString(project.config.options.targetFileName);
3737          }
3738
3739          /* // THIS IS NOW AUTOMATED WITH A project CHECK IN ProjectNode
3740          project.topNode.configurations = project.configurations;
3741          project.topNode.platforms = project.platforms;
3742          project.topNode.options = project.options;*/
3743       }
3744    }
3745    return project;
3746 }