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