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