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