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