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