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