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