ide: fixed go to error didn't work with "In file included from" error message.
[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 =");
1909          if(gccCompiler)
1910          {
1911             f.Printf(" -fmessage-length=0");
1912             switch(GetOptimization(config))
1913             {
1914                case speed:
1915                   f.Printf(" -O2");
1916                   f.Printf(" -ffast-math");
1917                   break;
1918                case size:
1919                   f.Printf(" -Os");
1920                   break;
1921             }
1922             //if(compiler.targetPlatform.is32Bits)
1923                f.Printf(" -m32");
1924             //else if(compiler.targetPlatform.is64Bits)
1925             //   f.Printf(" -m64");
1926             f.Printf(" $(FPIC)");
1927             //f.Printf(" -fpack-struct");
1928          }
1929          switch(GetWarnings(config))
1930          {
1931             case all: f.Printf(" -Wall"); break;
1932             case none: f.Printf(" -w"); break;
1933          }
1934          if(GetDebug(config))
1935             f.Printf(" -g");
1936          if(GetProfile(config))
1937             f.Printf(" -pg");
1938          if(options && options.linkerOptions && options.linkerOptions.count)
1939          {
1940             f.Printf(" \\\n\t -Wl");
1941             for(s : options.linkerOptions)
1942                f.Printf(",%s", s);
1943          }
1944
1945          if(options && options.preprocessorDefinitions)
1946             OutputListOption(f, "D", options.preprocessorDefinitions, newLine, false);
1947          if(config && config.options && config.options.preprocessorDefinitions)
1948             OutputListOption(f, "D", config.options.preprocessorDefinitions, newLine, false);
1949          if(compiler.includeDirs)
1950             OutputListOption(f, gccCompiler ? "isystem " : "I", compiler.includeDirs, lineEach, true);
1951          if(options && options.includeDirs)
1952             OutputListOption(f, "I", options.includeDirs, lineEach, true);
1953          if(config && config.options && config.options.includeDirs)
1954             OutputListOption(f, "I", config.options.includeDirs, lineEach, true);
1955          f.Printf("\n\n");
1956
1957          f.Printf("CECFLAGS =%s%s%s%s", defaultPreprocessor ? "" : " -cpp ", defaultPreprocessor ? "" : compiler.cppCommand, 
1958                crossCompiling ? " -t " : "", crossCompiling ? (char*)compiler.targetPlatform : "");
1959          f.Printf("\n\n");
1960
1961          f.Printf("ECFLAGS =");
1962          if(GetMemoryGuard(config))
1963             f.Printf(" -memguard");
1964          if(GetStrictNameSpaces(config))
1965             f.Printf(" -strictns");
1966          if(GetNoLineNumbers(config))
1967             f.Printf(" -nolinenumbers");
1968          {
1969             char * s;
1970             if((s = GetDefaultNameSpace(config)) && s[0])
1971                f.Printf(" -defaultns %s", s);
1972          }
1973          f.Printf("\n\n");
1974
1975          f.Printf("OFLAGS =\n");
1976          f.Printf("ifneq \"$(TARGET_TYPE)\" \"%s\"\n", TargetTypeToMakefileVariable(staticLibrary));
1977          f.Printf("OFLAGS += -m32");
1978          if(GetProfile(config))
1979             f.Printf(" -pg");
1980          // no if?
1981          if(compiler.libraryDirs)
1982             OutputListOption(f, "L", compiler.libraryDirs, lineEach, true);
1983          if(options && options.libraryDirs)
1984             OutputListOption(f, "L", options.libraryDirs, lineEach, true);
1985          if(config && config.options && config.options.libraryDirs)
1986             OutputListOption(f, "L", config.options.libraryDirs, lineEach, true);
1987          f.Printf("\n");
1988          f.Printf("endif\n\n");
1989
1990          if((config && config.options && config.options.libraries) ||
1991                (options && options.libraries))
1992          {
1993             f.Printf("LIBS =\n");
1994             f.Printf("ifneq \"$(TARGET_TYPE)\" \"%s\"\n", TargetTypeToMakefileVariable(staticLibrary));
1995             f.Printf("LIBS +=");
1996             if(config && config.options && config.options.libraries)
1997                OutputLibraries(f, config.options.libraries);
1998             else if(options && options.libraries)
1999                OutputLibraries(f, options.libraries);
2000             f.Printf("\n");
2001             f.Printf("endif\n");
2002             f.Printf("LIBS +=");
2003          }
2004          else
2005             f.Printf("LIBS =");
2006
2007          f.Printf(" $(SHAREDLIB) $(EXECUTABLE) $(LINKOPT)\n\n");
2008
2009          f.Printf("UPXFLAGS = -9\n\n"); // TOFEAT: Compression Level Option? Other UPX Options?
2010
2011          f.Printf("# HARD CODED PLATFORM-SPECIFIC OPTIONS\n");
2012          f.Printf("ifdef %s\n", PlatformToMakefileVariable(tux));
2013          f.Printf("OFLAGS += -Wl,--no-undefined\n");
2014          f.Printf("endif\n\n");
2015
2016          // JF's
2017          f.Printf("ifdef %s\n", PlatformToMakefileVariable(apple));
2018          f.Printf("OFLAGS += -framework cocoa -framework OpenGL\n");
2019          f.Printf("endif\n\n");
2020
2021          if(platforms || (config && config.platforms))
2022          {
2023             ifCount = 0;
2024             //for(platform = firstPlatform; platform <= lastPlatform; platform++)
2025             //for(platform = win32; platform <= apple; platform++)
2026             
2027             f.Printf("# PLATFORM-SPECIFIC OPTIONS\n\n");
2028             for(platform = (Platform)1; platform < Platform::enumSize; platform++)
2029             {
2030                PlatformOptions projectPlatformOptions, configPlatformOptions;
2031                MatchProjectAndConfigPlatformOptions(config, platform, &projectPlatformOptions, &configPlatformOptions);
2032
2033                if(projectPlatformOptions || configPlatformOptions)
2034                {
2035                   if(ifCount)
2036                      f.Printf("else\n");
2037                   ifCount++;
2038                   f.Printf("ifdef ");
2039                   f.Printf(PlatformToMakefileVariable(platform));
2040                   f.Printf("\n\n");
2041
2042                   if((projectPlatformOptions && projectPlatformOptions.options.preprocessorDefinitions && projectPlatformOptions.options.preprocessorDefinitions.count) ||
2043                      (configPlatformOptions && configPlatformOptions.options.preprocessorDefinitions && configPlatformOptions.options.preprocessorDefinitions.count) ||
2044                      (projectPlatformOptions && projectPlatformOptions.options.includeDirs && projectPlatformOptions.options.includeDirs.count) ||
2045                      (configPlatformOptions && configPlatformOptions.options.includeDirs && configPlatformOptions.options.includeDirs.count))
2046                   {
2047                      f.Printf("CFLAGS +=");
2048                      if(projectPlatformOptions && projectPlatformOptions.options.linkerOptions && projectPlatformOptions.options.linkerOptions.count)
2049                      {
2050                         f.Printf(" \\\n\t -Wl");
2051                         for(s : projectPlatformOptions.options.linkerOptions)
2052                            f.Printf(",%s", s);
2053                      }
2054                      if(configPlatformOptions && configPlatformOptions.options.linkerOptions && configPlatformOptions.options.linkerOptions.count)
2055                      {
2056                         f.Printf(" \\\n\t -Wl");
2057                         for(s : configPlatformOptions.options.linkerOptions)
2058                            f.Printf(",%s", s);
2059                      }
2060                      if(projectPlatformOptions && projectPlatformOptions.options.preprocessorDefinitions)
2061                         OutputListOption(f, "D", projectPlatformOptions.options.preprocessorDefinitions, newLine, false);
2062                      if(configPlatformOptions && configPlatformOptions.options.preprocessorDefinitions)
2063                         OutputListOption(f, "D", configPlatformOptions.options.preprocessorDefinitions, newLine, false );
2064                      if(projectPlatformOptions && projectPlatformOptions.options.includeDirs)
2065                         OutputListOption(f, "I", projectPlatformOptions.options.includeDirs, lineEach, true);
2066                      if(configPlatformOptions && configPlatformOptions.options.includeDirs)
2067                         OutputListOption(f, "I", configPlatformOptions.options.includeDirs, lineEach, true);
2068                      f.Printf("\n\n");
2069                   }
2070
2071                   if((projectPlatformOptions && projectPlatformOptions.options.libraryDirs && projectPlatformOptions.options.libraryDirs.count) ||
2072                         (configPlatformOptions && configPlatformOptions.options.libraryDirs && configPlatformOptions.options.libraryDirs.count) ||
2073                         (projectPlatformOptions && projectPlatformOptions.options.libraries && projectPlatformOptions.options.libraries.count) ||
2074                         (configPlatformOptions && configPlatformOptions.options.libraries && configPlatformOptions.options.libraries.count))
2075                   {
2076                      f.Printf("ifneq \"$(TARGET_TYPE)\" \"%s\"\n", TargetTypeToMakefileVariable(staticLibrary));
2077                      if((projectPlatformOptions && projectPlatformOptions.options.libraryDirs && projectPlatformOptions.options.libraryDirs.count) ||
2078                         (configPlatformOptions && configPlatformOptions.options.libraryDirs && configPlatformOptions.options.libraryDirs.count))
2079                      {
2080                         f.Printf("OFLAGS +=");
2081                         if(projectPlatformOptions && projectPlatformOptions.options.libraryDirs)
2082                            OutputListOption(f, "L", projectPlatformOptions.options.libraryDirs, lineEach, true);
2083                         if(configPlatformOptions && configPlatformOptions.options.libraryDirs)
2084                            OutputListOption(f, "L", configPlatformOptions.options.libraryDirs, lineEach, true);
2085                         f.Printf("\n");
2086                      }
2087
2088                      if(projectPlatformOptions && projectPlatformOptions.options.libraries &&
2089                            projectPlatformOptions.options.libraries.count/* && 
2090                            (!config || !config.options || !config.options.libraries)*/)
2091                      {
2092                         f.Printf("LIBS +=");
2093                         OutputLibraries(f, projectPlatformOptions.options.libraries);
2094                         f.Printf("\n");
2095                      }
2096                      {/*TOFIX: EXTRA CURLIES FOR NASTY WARNING*/if((configPlatformOptions && configPlatformOptions.options.libraries && configPlatformOptions.options.libraries.count))
2097                      {
2098                         f.Printf("LIBS +=");
2099                         OutputLibraries(f, configPlatformOptions.options.libraries);
2100                         f.Printf("\n");
2101                      }}
2102                      f.Printf("endif\n\n");
2103                   }
2104                }
2105             }
2106             if(ifCount)
2107             {
2108                for(c = 0; c < ifCount; c++)
2109                   f.Printf("endif\n");
2110             }
2111             f.Printf("\n");
2112          }
2113
2114          f.Printf("# TARGETS\n\n");
2115
2116          f.Printf("all: objdir%s $(TARGET)\n\n", sameObjTargetDirs ? "" : " targetdir");
2117
2118          f.Printf("objdir:\n");
2119             f.Printf("\t$(if $(wildcard $(OBJ)),,$(call mkdirq,$(OBJ)))\n");
2120          //f.Printf("# PRE-BUILD COMMANDS\n");
2121          if(options && options.prebuildCommands)
2122          {
2123             for(s : options.prebuildCommands)
2124                if(s && s[0]) f.Printf("\t%s\n", s);
2125          }
2126          if(config && config.options && config.options.prebuildCommands)
2127          {
2128             for(s : config.options.prebuildCommands)
2129                if(s && s[0]) f.Printf("\t%s\n", s);
2130          }
2131          if(platforms || (config && config.platforms))
2132          {
2133             ifCount = 0;
2134             //f.Printf("# PLATFORM-SPECIFIC PRE-BUILD COMMANDS\n");
2135             for(platform = (Platform)1; platform < Platform::enumSize; platform++)
2136             {
2137                PlatformOptions projectPOs, configPOs;
2138                MatchProjectAndConfigPlatformOptions(config, platform, &projectPOs, &configPOs);
2139
2140                if((projectPOs && projectPOs.options.prebuildCommands && projectPOs.options.prebuildCommands.count) ||
2141                      (configPOs && configPOs.options.prebuildCommands && configPOs.options.prebuildCommands.count))
2142                {
2143                   if(ifCount)
2144                      f.Printf("else\n");
2145                   ifCount++;
2146                   f.Printf("ifdef ");
2147                   f.Printf(PlatformToMakefileVariable(platform));
2148                   f.Printf("\n");
2149
2150                   if(projectPOs && projectPOs.options.prebuildCommands && projectPOs.options.prebuildCommands.count)
2151                   {
2152                      for(s : projectPOs.options.prebuildCommands)
2153                         if(s && s[0]) f.Printf("\t%s\n", s);
2154                   }
2155                   if(configPOs && configPOs.options.prebuildCommands && configPOs.options.prebuildCommands.count)
2156                   {
2157                      for(s : configPOs.options.prebuildCommands)
2158                         if(s && s[0]) f.Printf("\t%s\n", s);
2159                   }
2160                }
2161             }
2162             if(ifCount)
2163             {
2164                int c;
2165                for(c = 0; c < ifCount; c++)
2166                   f.Printf("endif\n");
2167             }
2168          }
2169          f.Printf("\n");
2170
2171          if(!sameObjTargetDirs)
2172          {
2173             f.Printf("targetdir:\n");
2174                f.Printf("\t$(if $(wildcard %s),,$(call mkdirq,%s))\n\n", targetDirExpNoSpaces, targetDirExpNoSpaces);
2175          }
2176
2177          if(numCObjects)
2178          {
2179             // Main Module (Linking) for ECERE C modules
2180             f.Printf("$(OBJ)$(MODULE).main.ec: $(SYMBOLS) $(COBJECTS)\n");
2181             // use of objDirExpNoSpaces used instead of $(OBJ) to prevent problematic joining of arguments in ecs
2182             f.Printf("\t$(ECS)%s $(ECSLIBOPT) $(SYMBOLS) $(IMPORTS) -symbols %s -o $(OBJ)$(MODULE).main.ec\n\n", 
2183                GetConsole(config) ? " -console" : "", objDirExpNoSpaces);
2184             // Main Module (Linking) for ECERE C modules
2185             f.Printf("$(OBJ)$(MODULE).main.c: $(OBJ)$(MODULE).main.ec\n");
2186             f.Printf("\t$(ECP) $(CECFLAGS) $(ECFLAGS) $(CFLAGS)"
2187                   " -c $(OBJ)$(MODULE).main.ec -o $(OBJ)$(MODULE).main.sym -symbols $(OBJ)\n");
2188             f.Printf("\t$(ECC) $(CECFLAGS) $(ECFLAGS) $(CFLAGS) $(FVISIBILITY)"
2189                   " -c $(OBJ)$(MODULE).main.ec -o $(OBJ)$(MODULE).main.c -symbols $(OBJ)\n\n");
2190          }
2191
2192          // *** Target ***
2193
2194          // This would not rebuild the target on updated objects
2195          // f.Printf("$(TARGET): $(SOURCES) $(RESOURCES) | objdir $(SYMBOLS) $(OBJECTS)%s\n", sameObjTargetDirs ? "" : " targetdir");
2196
2197          // This should fix it for good!
2198          f.Printf("$(SYMBOLS): | objdir\n");
2199          f.Printf("$(OBJECTS): | objdir\n");
2200
2201          // This alone was breaking the tarball, object directory does not get created first (order-only rules happen last it seems!)
2202          f.Printf("$(TARGET): $(SOURCES) $(RESOURCES) $(SYMBOLS) $(OBJECTS) | objdir%s\n", sameObjTargetDirs ? "" : " targetdir");
2203
2204          f.Printf("ifneq \"$(TARGET_TYPE)\" \"%s\"\n", TargetTypeToMakefileVariable(staticLibrary));
2205          f.Printf("\t$(CC) $(OFLAGS) $(OBJECTS) $(LIBS) -o $(TARGET) $(INSTALLNAME)\n");
2206          if(!GetDebug(config))
2207          {
2208             f.Printf("ifndef NOSTRIP\n");
2209             f.Printf("\t$(STRIP) $(STRIPOPT) $(TARGET)\n");
2210             f.Printf("endif\n");
2211
2212             if(GetCompress(config))
2213             {
2214                f.Printf("ifndef WINDOWS\n");
2215                f.Printf("ifeq \"$(TARGET_TYPE)\" \"%s\"\n", TargetTypeToMakefileVariable(executable));
2216                   f.Printf("\t$(UPX) $(UPXFLAGS) $(TARGET)\n");
2217                f.Printf("endif\n");
2218                f.Printf("else\n");
2219                   f.Printf("\t$(UPX) $(UPXFLAGS) $(TARGET)\n");
2220                f.Printf("endif\n");
2221             }
2222          }
2223          if(resNode.files && resNode.files.count && !noResources)
2224             resNode.GenMakefileAddResources(f, resNode.path, config);
2225          f.Printf("else\n");
2226          f.Printf("\t$(AR) rcs $(TARGET) $(OBJECTS) $(LIBS)\n");
2227          f.Printf("endif\n");
2228
2229          //f.Printf("# POST-BUILD COMMANDS\n");
2230          if(options && options.postbuildCommands)
2231          {
2232             for(s : options.postbuildCommands)
2233                if(s && s[0]) f.Printf("\t%s\n", s);
2234          }
2235          if(config && config.options && config.options.postbuildCommands)
2236          {
2237             for(s : config.options.postbuildCommands)
2238                if(s && s[0]) f.Printf("\t%s\n", s);
2239          }
2240          if(platforms || (config && config.platforms))
2241          {
2242             ifCount = 0;
2243             //f.Printf("# PLATFORM-SPECIFIC POST-BUILD COMMANDS\n");
2244             for(platform = (Platform)1; platform < Platform::enumSize; platform++)
2245             {
2246                PlatformOptions projectPOs, configPOs;
2247                MatchProjectAndConfigPlatformOptions(config, platform, &projectPOs, &configPOs);
2248
2249                if((projectPOs && projectPOs.options.postbuildCommands && projectPOs.options.postbuildCommands.count) ||
2250                      (configPOs && configPOs.options.postbuildCommands && configPOs.options.postbuildCommands.count))
2251                {
2252                   if(ifCount)
2253                      f.Printf("else\n");
2254                   ifCount++;
2255                   f.Printf("ifdef ");
2256                   f.Printf(PlatformToMakefileVariable(platform));
2257                   f.Printf("\n");
2258
2259                   if(projectPOs && projectPOs.options.postbuildCommands && projectPOs.options.postbuildCommands.count)
2260                   {
2261                      for(s : projectPOs.options.postbuildCommands)
2262                         if(s && s[0]) f.Printf("\t%s\n", s);
2263                   }
2264                   if(configPOs && configPOs.options.postbuildCommands && configPOs.options.postbuildCommands.count)
2265                   {
2266                      for(s : configPOs.options.postbuildCommands)
2267                         if(s && s[0]) f.Printf("\t%s\n", s);
2268                   }
2269                }
2270             }
2271             if(ifCount)
2272             {
2273                int c;
2274                for(c = 0; c < ifCount; c++)
2275                   f.Printf("endif\n");
2276             }
2277          }
2278          f.Printf("\n");
2279
2280          f.Printf("# SYMBOL RULES\n\n");
2281          topNode.GenMakefilePrintSymbolRules(f, this, compiler, config);
2282
2283          f.Printf("# C OBJECT RULES\n\n");
2284          topNode.GenMakefilePrintCObjectRules(f, this, compiler, config);
2285
2286          /*if(numCObjects)
2287          {
2288             f.Printf("# IMPLICIT OBJECT RULE\n\n");
2289
2290             f.Printf("$(OBJ)%%$(O) : $(OBJ)%%.c\n");
2291             f.Printf("\t$(CC) $(CFLAGS) $(FVISIBILITY) -c $< -o $@\n\n");
2292          }*/
2293
2294          f.Printf("# OBJECT RULES\n\n");
2295          // todo call this still but only generate rules whith specific options
2296          // see we-have-file-specific-options in ProjectNode.ec
2297          topNode.GenMakefilePrintObjectRules(f, this, namesInfo, compiler, config);
2298
2299          if(numCObjects)
2300             GenMakefilePrintMainObjectRule(f, compiler, config);
2301
2302          f.Printf("clean: objdir%s\n", sameObjTargetDirs ? "" : " targetdir");
2303          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) " : "");
2304          OutputCleanActions(f, "OBJECTS", objectsParts);
2305          OutputCleanActions(f, "COBJECTS", cobjectsParts);
2306          if(numCObjects)
2307          {
2308             OutputCleanActions(f, "IMPORTS", importsParts);
2309             OutputCleanActions(f, "SYMBOLS", symbolsParts);
2310          }
2311          f.Printf("\n");
2312
2313          f.Printf("realclean: clean\n");
2314          f.Printf("\t$(call rmrq,$(OBJ))\n");
2315          if(!sameObjTargetDirs)
2316             f.Printf("\t$(call rmdirq,%s)\n", targetDirExpNoSpaces);
2317
2318          delete f;
2319          delete objDirExp;
2320          listItems.Free();
2321          delete listItems;
2322          varStringLenDiffs.Free();
2323          delete varStringLenDiffs;
2324          namesInfo.Free();
2325          delete namesInfo;
2326
2327          result = true;
2328       }
2329
2330       // ChangeWorkingDir(oldDirectory);
2331       // delete pathBackup;
2332
2333       if(config)
2334          config.makingModified = false;
2335       return result;
2336    }
2337
2338    void GenMakefilePrintMainObjectRule(File f, CompilerConfig compiler, ProjectConfig config)
2339    {
2340       char extension[MAX_EXTENSION] = "c";
2341       char modulePath[MAX_LOCATION];
2342       char fixedModuleName[MAX_FILENAME];
2343       DualPipe dep;
2344       char command[2048];
2345       char objDirNoSpaces[MAX_LOCATION];
2346       DirExpression objDirExp = GetObjDir(compiler, config);
2347
2348       ReplaceSpaces(objDirNoSpaces, objDirExp.dir);
2349       ReplaceSpaces(fixedModuleName, moduleName);
2350       
2351       //sprintf(fixedModuleName, "%s.main", fixedPrjName);
2352       //strcat(fixedModuleName, ".main");
2353
2354 #if 0       // TODO: Fix nospaces stuff
2355       // *** Dependency command ***
2356       sprintf(command, "gcc -MT $(OBJ)%s$(O) -MM $(OBJ)%s.c", fixedModuleName, fixedModuleName);
2357
2358       // System Includes (from global settings)
2359       for(item : compiler.dirs[Includes])
2360       {
2361          strcat(command, " -isystem ");
2362          if(strchr(item.name, ' '))
2363          {
2364             strcat(command, "\"");
2365             strcat(command, item);
2366             strcat(command, "\"");
2367          }
2368          else
2369             strcat(command, item);
2370       }
2371
2372       for(item = includeDirs.first; item; item = item.next)
2373       {
2374          strcat(command, " -I");
2375          if(strchr(item.name, ' '))
2376          {
2377             strcat(command, "\"");
2378             strcat(command, item.name);
2379             strcat(command, "\"");
2380          }
2381          else
2382             strcat(command, item.name);
2383       }
2384       for(item = preprocessorDefs.first; item; item = item.next)
2385       {
2386          strcat(command, " -D");
2387          strcat(command, item.name);
2388       }
2389
2390       // Execute it
2391       if((dep = DualPipeOpen(PipeOpenMode { output = 1, error = 1, input = 2 }, command)))
2392       {
2393          char line[1024];
2394          bool result = true;
2395          bool firstLine = true;
2396
2397          // To do some time: auto save external dependencies?
2398          while(!dep.Eof())
2399          {
2400             if(dep.GetLine(line, sizeof(line)-1))
2401             {
2402                if(firstLine)
2403                {
2404                   char * colon = strstr(line, ":");
2405                   if(strstr(line, "No such file") || strstr(line, ",") || (colon && strstr(colon+1, ":")))
2406                   {
2407                      result = false;
2408                      break;
2409                   }
2410                   firstLine = false;
2411                }
2412                f.Puts(line);
2413                f.Puts("\n");
2414             }
2415             if(!result) break;
2416          }
2417          delete dep;
2418
2419          // If we failed to generate dependencies...
2420          if(!result)
2421          {
2422 #endif
2423             f.Printf("$(OBJ)$(MODULE).main$(O): $(OBJ)$(MODULE).main.c\n");
2424 #if 0
2425          }
2426       }
2427 #endif
2428
2429       f.Printf("\t$(CC) $(CFLAGS) $(FVISIBILITY) -c $(OBJ)$(MODULE).main.%s -o $(OBJ)$(MODULE).main$(O)\n\n", extension);
2430
2431       delete objDirExp;
2432    }
2433
2434    void MatchProjectAndConfigPlatformOptions(ProjectConfig config, Platform platform,
2435          PlatformOptions * projectPlatformOptions, PlatformOptions * configPlatformOptions)
2436    {
2437       *projectPlatformOptions = null;
2438       *configPlatformOptions = null;
2439       if(platforms)
2440       {
2441          for(p : platforms)
2442          {
2443             if(!strcmpi(p.name, platform))
2444             {
2445                *projectPlatformOptions = p;
2446                break;
2447             }
2448          }
2449       }
2450       if(config && config.platforms)
2451       {
2452          for(p : config.platforms)
2453          {
2454             if(!strcmpi(p.name, platform))
2455             {
2456                *configPlatformOptions = p;
2457                break;
2458             }
2459          }
2460       }
2461    }
2462 }
2463
2464 Project LegacyBinaryLoadProject(File f, char * filePath)
2465 {
2466    Project project = null;
2467    char signature[sizeof(epjSignature)];
2468
2469    f.Read(signature, sizeof(signature), 1);
2470    if(!strncmp(signature, (char *)epjSignature, sizeof(epjSignature)))
2471    {
2472       char topNodePath[MAX_LOCATION];
2473       /*ProjectConfig newConfig
2474       {
2475          name = CopyString("Default");
2476          makingModified = true;
2477          compilingModified = true;
2478          linkingModified = true;
2479          options = { };
2480       };*/
2481
2482       project = Project { options = { } };
2483       LegacyBinaryLoadNode(project.topNode, f);
2484       delete project.topNode.path;
2485       GetWorkingDir(topNodePath, sizeof(topNodePath)-1);
2486       MakeSlashPath(topNodePath);
2487
2488       PathCatSlash(topNodePath, filePath);
2489       project.filePath = topNodePath;
2490       
2491       /* THIS IS ALREADY DONE BY filePath property
2492       StripLastDirectory(topNodePath, topNodePath);
2493       project.topNode.path = CopyString(topNodePath);
2494       */
2495       // Shouldn't this be done BEFORE the StripLastDirectory? project.filePath = topNodePath;
2496       
2497       // newConfig.options.defaultNameSpace = "";
2498       /*newConfig.objDir.dir = "obj";
2499       newConfig.targetDir.dir = "";*/
2500
2501       //project.configurations = { [ newConfig ] };
2502       //project.config = newConfig;
2503
2504       // Project Settings
2505       if(!f.Eof())
2506       {
2507          int temp;
2508          int len,c, count;
2509          String targetFileName, targetDirectory, objectsDirectory;
2510
2511          // { executable = 0, sharedLibrary = 1, staticLibrary = 2 };
2512          f.Read(&temp, sizeof(int),1);
2513          switch(temp)
2514          {
2515             case 0: project.options.targetType = executable; break;
2516             case 1: project.options.targetType = sharedLibrary; break;
2517             case 2: project.options.targetType = staticLibrary; break;
2518          }
2519
2520          f.Read(&len, sizeof(int),1);
2521          targetFileName = new char[len+1];
2522          f.Read(targetFileName, sizeof(char), len+1);
2523          project.options.targetFileName = targetFileName;
2524          delete targetFileName;
2525
2526          f.Read(&len, sizeof(int),1);
2527          targetDirectory = new char[len+1];
2528          f.Read(targetDirectory, sizeof(char), len+1);
2529          project.options.targetDirectory = targetDirectory;
2530          delete targetDirectory;
2531
2532          f.Read(&len, sizeof(int),1);
2533          objectsDirectory = new byte[len+1];
2534          f.Read(objectsDirectory, sizeof(char), len+1);
2535          project.options.objectsDirectory = objectsDirectory;
2536          delete objectsDirectory;
2537
2538          f.Read(&temp, sizeof(int),1);
2539          project./*config.*/options.debug = temp ? true : false;
2540          f.Read(&temp, sizeof(int),1);         
2541          project./*config.*/options.optimization = temp ? speed : none;
2542          f.Read(&temp, sizeof(int),1);
2543          project./*config.*/options.profile = temp ? true : false;
2544          f.Read(&temp, sizeof(int),1);
2545          project.options.warnings = temp ? all : unset;
2546
2547          f.Read(&count, sizeof(int),1);
2548          if(count)
2549          {
2550             project.options.includeDirs = { };
2551             for(c = 0; c < count; c++)
2552             {
2553                char * name;
2554                f.Read(&len, sizeof(int),1);
2555                name = new char[len+1];
2556                f.Read(name, sizeof(char), len+1);
2557                project.options.includeDirs.Add(name);
2558             }
2559          }
2560
2561          f.Read(&count, sizeof(int),1);
2562          if(count)
2563          {
2564             project.options.libraryDirs = { };
2565             for(c = 0; c < count; c++)
2566             {
2567                char * name;            
2568                f.Read(&len, sizeof(int),1);
2569                name = new char[len+1];
2570                f.Read(name, sizeof(char), len+1);
2571                project.options.libraryDirs.Add(name);
2572             }
2573          }
2574
2575          f.Read(&count, sizeof(int),1);
2576          if(count)
2577          {
2578             project.options.libraries = { };
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.libraries.Add(name);
2586             }
2587          }
2588
2589          f.Read(&count, sizeof(int),1);
2590          if(count)
2591          {
2592             project.options.preprocessorDefinitions = { };
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.preprocessorDefinitions.Add(name);
2600             }
2601          }
2602
2603          f.Read(&temp, sizeof(int),1);
2604          project.options.console = temp ? true : false;
2605       }
2606
2607       for(node : project.topNode.files)
2608       {
2609          if(node.type == resources)
2610          {
2611             project.resNode = node;
2612             break;
2613          }
2614       }
2615    }
2616    else
2617       f.Seek(0, start);
2618    return project;
2619 }
2620
2621 void ProjectConfig::LegacyProjectConfigLoad(File f)
2622 {  
2623    delete options;
2624    options = { };
2625    while(!f.Eof())
2626    {
2627       char buffer[65536];
2628       char section[128];
2629       char subSection[128];
2630       char * equal;
2631       int len;
2632       uint pos;
2633       
2634       pos = f.Tell();
2635       f.GetLine(buffer, 65536 - 1);
2636       TrimLSpaces(buffer, buffer);
2637       TrimRSpaces(buffer, buffer);
2638       if(strlen(buffer))
2639       {
2640          if(buffer[0] == '-')
2641          {
2642             equal = &buffer[0];
2643             equal[0] = ' ';
2644             TrimLSpaces(equal, equal);
2645             if(!strcmpi(subSection, "LibraryDirs"))
2646             {
2647                if(!options.libraryDirs)
2648                   options.libraryDirs = { [ CopyString(equal) ] };
2649                else
2650                   options.libraryDirs.Add(CopyString(equal));
2651             }
2652             else if(!strcmpi(subSection, "IncludeDirs"))
2653             {
2654                if(!options.includeDirs)
2655                   options.includeDirs = { [ CopyString(equal) ] };
2656                else
2657                   options.includeDirs.Add(CopyString(equal));
2658             }
2659          }
2660          else if(buffer[0] == '+')
2661          {
2662             if(name)
2663             {
2664                f.Seek(pos, start);
2665                break;
2666             }
2667             else
2668             {
2669                equal = &buffer[0];
2670                equal[0] = ' ';
2671                TrimLSpaces(equal, equal);
2672                delete name; name = CopyString(equal); // property::name = equal;
2673             }
2674          }
2675          else if(!strcmpi(buffer, "Compiler Options"))
2676             strcpy(section, buffer);
2677          else if(!strcmpi(buffer, "IncludeDirs"))
2678             strcpy(subSection, buffer);
2679          else if(!strcmpi(buffer, "Linker Options"))
2680             strcpy(section, buffer);
2681          else if(!strcmpi(buffer, "LibraryDirs"))
2682             strcpy(subSection, buffer);
2683          else if(!strcmpi(buffer, "Files") || !strcmpi(buffer, "Resources"))
2684          {
2685             f.Seek(pos, start);
2686             break;
2687          }
2688          else
2689          {
2690             equal = strstr(buffer, "=");
2691             if(equal)
2692             {
2693                equal[0] = '\0';
2694                TrimRSpaces(buffer, buffer);
2695                equal++;
2696                TrimLSpaces(equal, equal);
2697                if(!strcmpi(buffer, "Target Name"))
2698                   options.targetFileName = /*CopyString(*/equal/*)*/;
2699                else if(!strcmpi(buffer, "Target Type"))
2700                {
2701                   if(!strcmpi(equal, "Executable"))
2702                      options.targetType = executable;
2703                   else if(!strcmpi(equal, "Shared"))
2704                      options.targetType = sharedLibrary;
2705                   else if(!strcmpi(equal, "Static"))
2706                      options.targetType = staticLibrary;
2707                   else
2708                      options.targetType = executable;
2709                }
2710                else if(!strcmpi(buffer, "Target Directory"))
2711                   options.targetDirectory = /*CopyString(*/equal/*)*/;
2712                else if(!strcmpi(buffer, "Console"))
2713                   options.console = ParseTrueFalseValue(equal);
2714                else if(!strcmpi(buffer, "Libraries"))
2715                {
2716                   if(!options.libraries) options.libraries = { };
2717                   ParseArrayValue(options.libraries, equal);
2718                }
2719                else if(!strcmpi(buffer, "Intermediate Directory"))
2720                   options.objectsDirectory = /*CopyString(*/equal/*)*/; //objDir.expression = equal;
2721                else if(!strcmpi(buffer, "Debug"))
2722                   options.debug = ParseTrueFalseValue(equal);
2723                else if(!strcmpi(buffer, "Optimize"))
2724                {
2725                   if(!strcmpi(equal, "None"))
2726                      options.optimization = none;
2727                   else if(!strcmpi(equal, "Speed") || !strcmpi(equal, "True"))
2728                      options.optimization = speed;
2729                   else if(!strcmpi(equal, "Size"))
2730                      options.optimization = size;
2731                   else
2732                      options.optimization = none;
2733                }
2734                else if(!strcmpi(buffer, "Compress"))
2735                   options.compress = ParseTrueFalseValue(equal);
2736                else if(!strcmpi(buffer, "Profile"))
2737                   options.profile = ParseTrueFalseValue(equal);
2738                else if(!strcmpi(buffer, "AllWarnings"))
2739                   options.warnings = ParseTrueFalseValue(equal) ? all : unset;
2740                else if(!strcmpi(buffer, "MemoryGuard"))
2741                   options.memoryGuard = ParseTrueFalseValue(equal);
2742                else if(!strcmpi(buffer, "Default Name Space"))
2743                   options.defaultNameSpace = CopyString(equal);
2744                else if(!strcmpi(buffer, "Strict Name Spaces"))
2745                   options.strictNameSpaces = ParseTrueFalseValue(equal);
2746                else if(!strcmpi(buffer, "Preprocessor Definitions"))
2747                {
2748                   if(!options.preprocessorDefinitions) options.preprocessorDefinitions = { };
2749                   ParseArrayValue(options.preprocessorDefinitions, equal);
2750                }
2751             }
2752          }
2753       }
2754    }
2755    if(!options.targetDirectory && options.objectsDirectory)
2756       options.targetDirectory = /*CopyString(*/options.objectsDirectory/*)*/;
2757    //if(!objDir.dir) objDir.dir = "obj";
2758    //if(!targetDir.dir) targetDir.dir = "";
2759    // if(!targetName) property::targetName = "";   // How can a targetFileName be nothing???
2760    // if(!defaultNameSpace) property::defaultNameSpace = "";
2761    makingModified = true;
2762 }
2763
2764 Project LegacyAsciiLoadProject(File f, char * filePath)
2765 {
2766    Project project = null;
2767    ProjectNode node = null;
2768    int pos;
2769    char parentPath[MAX_LOCATION];
2770    char section[128] = "";
2771    char subSection[128] = "";
2772    ProjectNode parent;
2773    bool configurationsPresent = false;
2774
2775    f.Seek(0, start);
2776    while(!f.Eof())
2777    {
2778       char buffer[65536];
2779       //char version[16];
2780       char * equal;
2781       int len;
2782       pos = f.Tell();
2783       f.GetLine(buffer, 65536 - 1);
2784       TrimLSpaces(buffer, buffer);
2785       TrimRSpaces(buffer, buffer);
2786       if(strlen(buffer))
2787       {
2788          if(buffer[0] == '-' || buffer[0] == '=')
2789          {
2790             bool simple = buffer[0] == '-';
2791             equal = &buffer[0];
2792             equal[0] = ' ';
2793             TrimLSpaces(equal, equal);
2794             if(!strcmpi(section, "Target") && !strcmpi(subSection, "LibraryDirs"))
2795             {
2796                if(!project.config.options.libraryDirs) project.config.options.libraryDirs = { };
2797                project.config.options.libraryDirs.Add(CopyString(equal));
2798             }
2799             else if(!strcmpi(section, "Target") && !strcmpi(subSection, "IncludeDirs"))
2800             {
2801                if(!project.config.options.includeDirs) project.config.options.includeDirs = { };
2802                project.config.options.includeDirs.Add(CopyString(equal));
2803             }
2804             else if(!strcmpi(section, "Target") && (!strcmpi(subSection, "Files") || !strcmpi(subSection, "Resources")))
2805             {
2806                len = strlen(equal);
2807                if(len)
2808                {
2809                   char temp[MAX_LOCATION];
2810                   ProjectNode child { };
2811                   // We don't need to do this anymore, fileName is just a property that sets name & path
2812                   // child.fileName = CopyString(equal);
2813                   if(simple)
2814                   {
2815                      child.name = CopyString(equal);
2816                      child.path = CopyString(parentPath);
2817                   }
2818                   else
2819                   {
2820                      GetLastDirectory(equal, temp);
2821                      child.name = CopyString(temp);
2822                      StripLastDirectory(equal, temp);
2823                      child.path = CopyString(temp);
2824                   }
2825                   child.nodeType = file;
2826                   child.parent = parent;
2827                   child.indent = parent.indent + 1;
2828                   child.type = file;
2829                   child.icon = NodeIcons::SelectFileIcon(child.name);
2830                   parent.files.Add(child);
2831                   node = child;
2832                   //child = null;
2833                }
2834                else
2835                {
2836                   StripLastDirectory(parentPath, parentPath);
2837                   parent = parent.parent;
2838                }
2839             }
2840          }
2841          else if(buffer[0] == '+')
2842          {
2843             equal = &buffer[0];
2844             equal[0] = ' ';
2845             TrimLSpaces(equal, equal);
2846             if(!strcmpi(section, "Target") && (!strcmpi(subSection, "Files") || !strcmpi(subSection, "Resources")))
2847             {
2848                char temp[MAX_LOCATION];
2849                ProjectNode child { };
2850                // NEW: Folders now have a path set like files
2851                child.name = CopyString(equal);
2852                strcpy(temp, parentPath);
2853                PathCatSlash(temp, child.name);
2854                child.path = CopyString(temp);
2855
2856                child.parent = parent;
2857                child.indent = parent.indent + 1;
2858                child.type = folder;
2859                child.nodeType = folder;
2860                child.files = { };
2861                child.icon = folder;
2862                PathCatSlash(parentPath, child.name);
2863                parent.files.Add(child);
2864                parent = child;
2865                node = child;
2866                //child = null;
2867             }
2868             else if(!strcmpi(section, "Configurations"))
2869             {
2870                ProjectConfig newConfig
2871                {
2872                   makingModified = true;
2873                   options = { };
2874                };
2875                f.Seek(pos, start);
2876                LegacyProjectConfigLoad(newConfig, f);
2877                project.configurations.Add(newConfig);
2878             }
2879          }
2880          else if(!strcmpi(buffer, "ECERE Project File"));
2881          else if(!strcmpi(buffer, "Version 0a"))
2882             ; //strcpy(version, "0a");
2883          else if(!strcmpi(buffer, "Version 0.1a"))
2884             ; //strcpy(version, "0.1a");
2885          else if(!strcmpi(buffer, "Configurations"))
2886          {
2887             project.configurations.Free();
2888             project.config = null;
2889             strcpy(section, buffer);
2890             configurationsPresent = true;
2891          }
2892          else if(!strcmpi(buffer, "Target") || !strnicmp(buffer, "Target \"", strlen("Target \"")))
2893          {
2894             ProjectConfig newConfig { name = CopyString("Default"), options = { } };
2895             char topNodePath[MAX_LOCATION];
2896             // newConfig.defaultNameSpace = "";
2897             //newConfig.objDir.dir = "obj";
2898             //newConfig.targetDir.dir = "";
2899             project = Project { /*options = { }*/ };
2900             project.configurations = { [ newConfig ] };
2901             project.config = newConfig;
2902             // if(project.topNode.path) delete project.topNode.path;
2903             GetWorkingDir(topNodePath, sizeof(topNodePath)-1);
2904             MakeSlashPath(topNodePath);
2905             PathCatSlash(topNodePath, filePath);
2906             project.filePath = topNodePath;
2907             parentPath[0] = '\0';
2908             parent = project.topNode;
2909             node = parent;
2910             strcpy(section, "Target");
2911             equal = &buffer[6];
2912             if(equal[0] == ' ')
2913             {
2914                equal++;
2915                if(equal[0] == '\"')
2916                {
2917                   StripQuotes(equal, equal);
2918                   delete project.moduleName; project.moduleName = CopyString(equal);
2919                }
2920             }
2921          }
2922          else if(!strcmpi(buffer, "Compiler Options"));
2923          else if(!strcmpi(buffer, "IncludeDirs"))
2924             strcpy(subSection, buffer);
2925          else if(!strcmpi(buffer, "Linker Options"));
2926          else if(!strcmpi(buffer, "LibraryDirs"))
2927             strcpy(subSection, buffer);
2928          else if(!strcmpi(buffer, "Files"))
2929          {
2930             strcpy(section, "Target");
2931             strcpy(subSection, buffer);
2932          }
2933          else if(!strcmpi(buffer, "Resources"))
2934          {
2935             ProjectNode child { };
2936             parent.files.Add(child);
2937             child.parent = parent;
2938             child.indent = parent.indent + 1;
2939             child.name = CopyString(buffer);
2940             child.path = CopyString("");
2941             child.type = resources;
2942             child.files = { };
2943             child.icon = archiveFile;
2944             project.resNode = child;
2945             parent = child;
2946             node = child;
2947             strcpy(subSection, buffer);
2948          }
2949          else
2950          {
2951             equal = strstr(buffer, "=");
2952             if(equal)
2953             {
2954                equal[0] = '\0';
2955                TrimRSpaces(buffer, buffer);
2956                equal++;
2957                TrimLSpaces(equal, equal);
2958
2959                if(!strcmpi(section, "Target"))
2960                {
2961                   if(!strcmpi(buffer, "Build Exclusions"))
2962                   {
2963                      if(!strcmpi(section, "Target") && !strcmpi(subSection, "Files"))
2964                      {
2965                         /*if(node && node.type != NodeTypes::project)
2966                            ParseListValue(node.buildExclusions, equal);*/
2967                      }
2968                   }
2969                   else if(!strcmpi(buffer, "Path") && !strcmpi(subSection, "Resources"))
2970                   {
2971                      delete project.resNode.path;
2972                      project.resNode.path = CopyString(equal);
2973                      PathCatSlash(parentPath, equal);
2974                   }
2975
2976                   // Config Settings
2977                   else if(!strcmpi(buffer, "Intermediate Directory"))
2978                      project.config.options.objectsDirectory = /*CopyString(*/equal/*)*/; //objDir.expression = equal;
2979                   else if(!strcmpi(buffer, "Debug"))
2980                      project.config.options.debug = ParseTrueFalseValue(equal);
2981                   else if(!strcmpi(buffer, "Optimize"))
2982                   {
2983                      if(!strcmpi(equal, "None"))
2984                         project.config.options.optimization = none;
2985                      else if(!strcmpi(equal, "Speed") || !strcmpi(equal, "True"))
2986                         project.config.options.optimization = speed;
2987                      else if(!strcmpi(equal, "Size"))
2988                         project.config.options.optimization = size;
2989                      else
2990                         project.config.options.optimization = none;
2991                   }
2992                   else if(!strcmpi(buffer, "Profile"))
2993                      project.config.options.profile = ParseTrueFalseValue(equal);
2994                   else if(!strcmpi(buffer, "MemoryGuard"))
2995                      project.config.options.memoryGuard = ParseTrueFalseValue(equal);
2996                   else
2997                   {
2998                      if(!project.options) project.options = { };
2999
3000                      // Project Wide Settings (All configs)
3001                      if(!strcmpi(buffer, "Target Name"))
3002                         project.options.targetFileName = /*CopyString(*/equal/*)*/;
3003                      else if(!strcmpi(buffer, "Target Type"))
3004                      {
3005                         if(!strcmpi(equal, "Executable"))
3006                            project.options.targetType = executable;
3007                         else if(!strcmpi(equal, "Shared"))
3008                            project.options.targetType = sharedLibrary;
3009                         else if(!strcmpi(equal, "Static"))
3010                            project.options.targetType = staticLibrary;
3011                         else
3012                            project.options.targetType = executable;
3013                      }
3014                      else if(!strcmpi(buffer, "Target Directory"))
3015                         project.options.targetDirectory = /*CopyString(*/equal/*)*/;
3016                      else if(!strcmpi(buffer, "Console"))
3017                         project.options.console = ParseTrueFalseValue(equal);
3018                      else if(!strcmpi(buffer, "Libraries"))
3019                      {
3020                         if(!project.options.libraries) project.options.libraries = { };
3021                         ParseArrayValue(project.options.libraries, equal);
3022                      }
3023                      else if(!strcmpi(buffer, "AllWarnings"))
3024                         project.options.warnings = ParseTrueFalseValue(equal) ? all : unset;
3025                      else if(!strcmpi(buffer, "Preprocessor Definitions"))
3026                      {
3027                         if(!strcmpi(section, "Target") && !strcmpi(subSection, "Files"))
3028                         {
3029                            /*if(node && (node.type == NodeTypes::project || (node.type == file && !node.isInResources) || node.type == folder))
3030                               ParseListValue(node.preprocessorDefs, equal);*/
3031                         }
3032                         else
3033                         {
3034                            if(!project.options.preprocessorDefinitions) project.options.preprocessorDefinitions = { };
3035                            ParseArrayValue(project.options.preprocessorDefinitions, equal);
3036                         }
3037                      }
3038                   }
3039                }
3040             }
3041          }
3042       }
3043    }
3044    parent = null;
3045
3046    SplitPlatformLibraries(project);
3047
3048    if(configurationsPresent)
3049       CombineIdenticalConfigOptions(project);
3050    return project;
3051 }
3052
3053 void SplitPlatformLibraries(Project project)
3054 {
3055    if(project && project.configurations)
3056    {
3057       for(cfg : project.configurations)
3058       {
3059          if(cfg.options.libraries && cfg.options.libraries.count)
3060          {
3061             Iterator<String> it { cfg.options.libraries };
3062             while(it.Next())
3063             {
3064                String l = it.data;
3065                char * platformName = strstr(l, ":");
3066                if(platformName)
3067                {
3068                   PlatformOptions platform = null;
3069                   platformName++;
3070                   if(!cfg.platforms) cfg.platforms = { };
3071                   for(p : cfg.platforms)
3072                   {
3073                      if(!strcmpi(platformName, p.name))
3074                      {
3075                         platform = p;
3076                         break;
3077                      }
3078                   }
3079                   if(!platform)
3080                   {
3081                      platform = { name = CopyString(platformName), options = { libraries = { } } };
3082                      cfg.platforms.Add(platform);
3083                   }
3084                   *(platformName-1) = 0;
3085                   platform.options.libraries.Add(CopyString(l));
3086
3087                   cfg.options.libraries.Delete(it.pointer);
3088                   it.pointer = null;
3089                }
3090             }
3091          }
3092       }      
3093    }
3094 }
3095
3096 void CombineIdenticalConfigOptions(Project project)
3097 {
3098    if(project && project.configurations && project.configurations.count)
3099    {
3100       DataMember member;
3101       ProjectOptions nullOptions { };
3102       ProjectConfig firstConfig = null;
3103       for(cfg : project.configurations)
3104       {
3105          if(cfg.options.targetType != staticLibrary)
3106          {
3107             firstConfig = cfg;
3108             break;
3109          }
3110       }
3111       if(!firstConfig)
3112          firstConfig = project.configurations.firstIterator.data;
3113
3114       for(member = class(ProjectOptions).membersAndProperties.first; member; member = member.next)
3115       {
3116          if(!member.isProperty)
3117          {
3118             Class type = eSystem_FindClass(__thisModule, member.dataTypeString);
3119             if(type)
3120             {
3121                bool same = true;
3122
3123                for(cfg : project.configurations)
3124                {
3125                   if(cfg != firstConfig)
3126                   {
3127                      if(cfg.options.targetType != staticLibrary)
3128                      {
3129                         int result;
3130                         
3131                         if(type.type == noHeadClass || type.type == normalClass)
3132                         {
3133                            result = type._vTbl[__ecereVMethodID_class_OnCompare](type, 
3134                               *(void **)((byte *)firstConfig.options + member.offset + member._class.offset),
3135                               *(void **)((byte *)cfg.options         + member.offset + member._class.offset));
3136                         }
3137                         else
3138                         {
3139                            result = type._vTbl[__ecereVMethodID_class_OnCompare](type, 
3140                               (byte *)firstConfig.options + member.offset + member._class.offset,
3141                               (byte *)cfg.options         + member.offset + member._class.offset);
3142                         }
3143                         if(result)
3144                         {
3145                            same = false;
3146                            break;
3147                         }
3148                      }
3149                   }                  
3150                }
3151                if(same)
3152                {
3153                   if(type.type == noHeadClass || type.type == normalClass)
3154                   {
3155                      if(!type._vTbl[__ecereVMethodID_class_OnCompare](type, 
3156                         *(void **)((byte *)firstConfig.options + member.offset + member._class.offset),
3157                         *(void **)((byte *)nullOptions         + member.offset + member._class.offset)))
3158                         continue;
3159                   }
3160                   else
3161                   {
3162                      if(!type._vTbl[__ecereVMethodID_class_OnCompare](type, 
3163                         (byte *)firstConfig.options + member.offset + member._class.offset,
3164                         (byte *)nullOptions         + member.offset + member._class.offset))
3165                         continue;
3166                   }
3167
3168                   if(!project.options) project.options = { };
3169                   
3170                   /*if(type.type == noHeadClass || type.type == normalClass)
3171                   {
3172                      type._vTbl[__ecereVMethodID_class_OnCopy](type, 
3173                         (byte *)project.options + member.offset + member._class.offset,
3174                         *(void **)((byte *)firstConfig.options + member.offset + member._class.offset));
3175                   }
3176                   else
3177                   {
3178                      void * address = (byte *)firstConfig.options + member.offset + member._class.offset;
3179                      // TOFIX: ListBox::SetData / OnCopy mess
3180                      type._vTbl[__ecereVMethodID_class_OnCopy](type, 
3181                         (byte *)project.options + member.offset + member._class.offset,
3182                         (type.typeSize > 4) ? address : 
3183                            ((type.typeSize == 4) ? (void *)*(uint32 *)address : 
3184                               ((type.typeSize == 2) ? (void *)*(uint16*)address : 
3185                                  (void *)*(byte *)address )));                              
3186                   }*/
3187                   memcpy(
3188                      (byte *)project.options + member.offset + member._class.offset,
3189                      (byte *)firstConfig.options + member.offset + member._class.offset, type.typeSize);
3190
3191                   for(cfg : project.configurations)
3192                   {
3193                      if(cfg.options.targetType == staticLibrary)
3194                      {
3195                         int result;
3196                         
3197                         if(type.type == noHeadClass || type.type == normalClass)
3198                         {
3199                            result = type._vTbl[__ecereVMethodID_class_OnCompare](type, 
3200                               *(void **)((byte *)firstConfig.options + member.offset + member._class.offset),
3201                               *(void **)((byte *)cfg.options         + member.offset + member._class.offset));
3202                         }
3203                         else
3204                         {
3205                            result = type._vTbl[__ecereVMethodID_class_OnCompare](type, 
3206                               (byte *)firstConfig.options + member.offset + member._class.offset,
3207                               (byte *)cfg.options         + member.offset + member._class.offset);
3208                         }
3209                         if(result)
3210                            continue;
3211                      }
3212                      if(cfg != firstConfig)
3213                      {
3214                         if(type.type == noHeadClass || type.type == normalClass)
3215                         {
3216                            type._vTbl[__ecereVMethodID_class_OnFree](type, 
3217                               *(void **)((byte *)cfg.options + member.offset + member._class.offset));
3218                         }
3219                         else
3220                         {
3221                            type._vTbl[__ecereVMethodID_class_OnFree](type, 
3222                               (byte *)cfg.options + member.offset + member._class.offset);
3223                         }
3224                         memset((byte *)cfg.options + member.offset + member._class.offset, 0, type.typeSize);
3225                      }                     
3226                   }
3227                   memset((byte *)firstConfig.options + member.offset + member._class.offset, 0, type.typeSize);
3228                }
3229             }
3230          }
3231       }
3232       delete nullOptions;
3233
3234       // Compare Platform Specific Settings
3235       {
3236          bool same = true;
3237          for(cfg : project.configurations)
3238          {
3239             if(cfg != firstConfig && cfg.options.targetType != staticLibrary && (firstConfig.platforms || cfg.platforms) &&
3240                ((!firstConfig.platforms && cfg.platforms) || firstConfig.platforms.OnCompare(cfg.platforms)))
3241             {
3242                same = false;
3243                break;
3244             }
3245          }
3246          if(same && firstConfig.platforms)
3247          {
3248             for(cfg : project.configurations)
3249             {
3250                if(cfg.options.targetType == staticLibrary && firstConfig.platforms.OnCompare(cfg.platforms))
3251                   continue;
3252                if(cfg != firstConfig)
3253                {
3254                   cfg.platforms.Free();
3255                   delete cfg.platforms;
3256                }
3257             }
3258             project.platforms = firstConfig.platforms;
3259             firstConfig.platforms = null;
3260          }
3261       }
3262
3263       // Static libraries can't contain libraries
3264       for(cfg : project.configurations)
3265       {
3266          if(cfg.options.targetType == staticLibrary)
3267          {
3268             if(!cfg.options.libraries) cfg.options.libraries = { };
3269             cfg.options.libraries.Free();
3270          }
3271       }
3272    }
3273 }
3274
3275 Project LoadProject(char * filePath)
3276 {
3277    Project project = null;
3278    File f = FileOpen(filePath, read);
3279    if(f)
3280    {
3281       project = LegacyBinaryLoadProject(f, filePath);
3282       if(!project)
3283       {
3284          JSONParser parser { f = f };
3285          JSONResult result = parser.GetObject(class(Project), &project);
3286          if(project)
3287          {
3288             char insidePath[MAX_LOCATION];
3289
3290             delete project.topNode.files;
3291             if(!project.files) project.files = { };
3292             project.topNode.files = project.files;
3293             project.resNode = project.topNode.Add(project, "Resources", project.topNode.files.last, resources, archiveFile, false);
3294             delete project.resNode.path;
3295             project.resNode.path = project.resourcesPath;
3296             project.resourcesPath = null;
3297             project.resNode.nodeType = (ProjectNodeType)-1;
3298             delete project.resNode.files;
3299             project.resNode.files = project.resources;
3300             project.files = null;
3301             project.resources = null;
3302             if(!project.configurations) project.configurations = { };
3303
3304             {
3305                char topNodePath[MAX_LOCATION];
3306                GetWorkingDir(topNodePath, sizeof(topNodePath)-1);
3307                MakeSlashPath(topNodePath);
3308                PathCatSlash(topNodePath, filePath);
3309                project.filePath = topNodePath;//filePath;
3310             }
3311
3312             project.topNode.FixupNode(insidePath);
3313          }
3314          delete parser;
3315       }
3316       if(!project)
3317          project = LegacyAsciiLoadProject(f, filePath);
3318
3319       delete f;
3320
3321       if(project)
3322       {
3323          if(!project.options) project.options = { };
3324          if(!project.config && project.configurations)
3325             project.config = project.configurations.firstIterator.data;
3326
3327          if(!project.resNode)
3328          {
3329             project.resNode = project.topNode.Add(project, "Resources", project.topNode.files.last, resources, archiveFile, false);
3330          }
3331          
3332          if(!project.moduleName)
3333             project.moduleName = CopyString(project.name);
3334          if(project.config && 
3335             (!project.options || !project.options.targetFileName || !project.options.targetFileName[0]) &&
3336             (!project.config.options.targetFileName || !project.config.options.targetFileName[0]))
3337          {
3338             //delete project.config.options.targetFileName;
3339             
3340             project.options.targetFileName = /*CopyString(*/project.moduleName/*)*/;
3341             project.config.options.optimization = none;
3342             project.config.options.debug = true;
3343             //project.config.options.warnings = unset;
3344             project.config.options.memoryGuard = false;
3345             project.config.compilingModified = true;
3346             project.config.linkingModified = true;
3347          }
3348          else if(!project.topNode.name && project.config)
3349          {
3350             project.topNode.name = CopyString(project.config.options.targetFileName);
3351          }
3352
3353          /* // THIS IS NOW AUTOMATED WITH A project CHECK IN ProjectNode
3354          project.topNode.configurations = project.configurations;
3355          project.topNode.platforms = project.platforms;
3356          project.topNode.options = project.options;*/
3357       }
3358    }
3359    return project;
3360 }