118b9c226a9e54bc23868c483310600ba2edb598
[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
1363       char cppCommand[MAX_LOCATION];
1364       char ccCommand[MAX_LOCATION];
1365       char cxxCommand[MAX_LOCATION];
1366       char stripCommand[MAX_LOCATION];
1367       char ecpCommand[MAX_LOCATION];
1368       char eccCommand[MAX_LOCATION];
1369       char ecsCommand[MAX_LOCATION];
1370       char earCommand[MAX_LOCATION];
1371
1372       char * cc = compiler.ccCommand;
1373       char * cxx = compiler.cxxCommand;
1374       char * cpp = compiler.cppCommand;
1375       char * strip = compiler.cppCommand;
1376       sprintf(cppCommand, "%s%s%s%s%s ",
1377             compiler.ccacheEnabled ? "ccache " : "",
1378             compiler.ccacheEnabled && !compiler.distccEnabled ? " " : "",
1379             compiler.distccEnabled ? "distcc " : "",
1380             compiler.gccPrefix ? compiler.gccPrefix : "",
1381             compiler.cppCommand);
1382       sprintf(ccCommand, "%s%s%s%s%s ",
1383             compiler.ccacheEnabled ? "ccache " : "",
1384             compiler.ccacheEnabled && !compiler.distccEnabled ? " " : "",
1385             compiler.distccEnabled ? "distcc " : "",
1386             compiler.gccPrefix ? compiler.gccPrefix : "",
1387             compiler.ccCommand);
1388       sprintf(cxxCommand, "%s%s%s%s%s ",
1389             compiler.ccacheEnabled ? "ccache " : "",
1390             compiler.ccacheEnabled && !compiler.distccEnabled ? " " : "",
1391             compiler.distccEnabled ? "distcc " : "",
1392             compiler.gccPrefix ? compiler.gccPrefix : "",
1393             compiler.cxxCommand);
1394
1395       sprintf(stripCommand, "%sstrip ",
1396             compiler.gccPrefix ? compiler.gccPrefix : "");
1397
1398       sprintf(ecpCommand, "%s ", compiler.ecpCommand);
1399       sprintf(eccCommand, "%s ", compiler.eccCommand);
1400       sprintf(ecsCommand, "%s ", compiler.ecsCommand);
1401       sprintf(earCommand, "%s ", compiler.earCommand);
1402
1403       while(!f.Eof() && !ide.ShouldStopBuild())
1404       {
1405          bool result = true;
1406          double lastTime = GetTime();
1407          bool wait = true;
1408          while(result)
1409          {
1410             //printf("Peeking and GetLine...\n");
1411             if((result = f.Peek()) && (result = f.GetLine(line, sizeof(line)-1)))
1412             {
1413                char * inFileIncludedFrom = strstr(line, stringInFileIncludedFrom);
1414                if(strstr(line, compiler.makeCommand) == line && line[lenMakeCommand] == ':')
1415                {
1416                   char * module = strstr(line, "No rule to make target `");
1417                   if(module)
1418                   {
1419                      char * end;
1420                      module = strchr(module, '`') + 1;
1421                      end = strchr(module, '\'');
1422                      if(end)
1423                      {
1424                         *end = '\0';
1425                         ide.outputView.buildBox.Logf($"   %s: No such file or directory\n", module);
1426                         // ide.outputView.buildBox.Logf("error: %s\n   No such file or directory\n", module);
1427                         numErrors++;
1428                      }
1429                   }
1430                   //else
1431                   //{
1432                      //ide.outputView.buildBox.Logf("error: %s\n", line);
1433                      //numErrors++;
1434                   //}
1435                }
1436                else if(strstr(line, "ear ") == line);
1437                else if(strstr(line, stripCommand) == line);
1438                else if(strstr(line, ccCommand) == line || strstr(line, cxxCommand) == line || strstr(line, ecpCommand) == line || strstr(line, eccCommand) == line)
1439                {
1440                   char moduleName[MAX_FILENAME];
1441                   byte * tokens[1];
1442                   char * module;
1443                   bool isPrecomp = false;
1444
1445                   if(strstr(line, ccCommand) == line || strstr(line, cxxCommand) == line)
1446                   {
1447                      module = strstr(line, " -c ");
1448                      if(module) module += 4;
1449                   }
1450                   else if(strstr(line, eccCommand) == line)
1451                   {
1452                      module = strstr(line, " -c ");
1453                      if(module) module += 4;
1454                      //module = line + 3;
1455                      // Don't show GCC warnings about generated C code because it does not compile clean yet...
1456                      compilingEC = 3;//2;
1457                   }
1458                   else if(strstr(line, ecpCommand) == line)
1459                   {
1460                      // module = line + 8;
1461                      module = strstr(line, " -c ");
1462                      if(module) module += 4;
1463                      isPrecomp = true;
1464                      compilingEC = 0;
1465                   }
1466
1467                   loggedALine = true;
1468
1469                   if(module)
1470                   {
1471                      if(!compiling && !isPrecomp)
1472                      {
1473                         ide.outputView.buildBox.Logf($"Compiling...\n");
1474                         compiling = true;
1475                      }
1476                      else if(!precompiling && isPrecomp)
1477                      {
1478                         ide.outputView.buildBox.Logf($"Generating symbols...\n");
1479                         precompiling = true;
1480                      }
1481                      // Changed escapeBackSlashes here to handle paths with spaces
1482                      Tokenize(module, 1, tokens, true); // false);
1483                      GetLastDirectory(module, moduleName);
1484                      ide.outputView.buildBox.Logf("%s\n", moduleName);
1485                   }
1486                   else if((module = strstr(line, " -o ")))
1487                   {
1488                      compiling = false;
1489                      precompiling = false;
1490                      linking = true;
1491                      ide.outputView.buildBox.Logf($"Linking...\n");
1492                   }
1493                   else
1494                   {
1495                      ide.outputView.buildBox.Logf("%s\n", line);
1496                      numErrors++;
1497                   }
1498
1499                   if(compilingEC) compilingEC--;
1500                }
1501                else if(strstr(line, "ar rcs") == line)
1502                   ide.outputView.buildBox.Logf($"Building library...\n");
1503                else if(strstr(line, ecsCommand) == line)
1504                   ide.outputView.buildBox.Logf($"Writing symbol loader...\n");
1505                else
1506                {
1507                   if(linking || compiling || precompiling)
1508                   {
1509                      char * colon = strstr(line, ":"); //, * bracket;
1510                      if(colon && (colon[1] == '/' || colon[1] == '\\'))
1511                         colon = strstr(colon + 1, ":");
1512                      if(colon)
1513                      {
1514                         char moduleName[MAX_LOCATION], temp[MAX_LOCATION];
1515                         char * pointer;
1516                         char * error;
1517                         char * start = inFileIncludedFrom ? line + strlen(stringInFileIncludedFrom) : line;
1518                         int len = (int)(colon - start);
1519                         len = Min(len, MAX_LOCATION-1);
1520                         // Don't be mistaken by the drive letter colon
1521                         // Cut module name
1522                         // TODO: need to fix colon - line gives char *
1523                         // warning: incompatible expression colon - line (char *); expected int
1524                         /*
1525                         strncpy(moduleName, line, (int)(colon - line));
1526                         moduleName[colon - line] = '\0';
1527                         */
1528                         strncpy(moduleName, start, len);
1529                         moduleName[len] = '\0';
1530                         // Remove stuff in brackets
1531                         //bracket = strstr(moduleName, "(");
1532                         //if(bracket) *bracket = '\0';
1533
1534                         GetLastDirectory(moduleName, temp);
1535                         if(linking && (!strcmp(temp, "ld") || !strcmp(temp, "ld.exe")))
1536                         {
1537                            numErrors++;
1538                            strcpy(moduleName, $"Linker Error");
1539                         }
1540                         else
1541                         {
1542                            strcpy(temp, topNode.path);
1543                            PathCatSlash(temp, moduleName);
1544                            MakePathRelative(temp, topNode.path, moduleName);
1545                         }
1546                         if(strstr(line, "error:"))
1547                            numErrors ++;
1548                         else
1549                         {
1550                            // Silence warnings for compiled EC
1551                            char * objDir = strstr(moduleName, objDirExp.dir);
1552                         
1553                            if(linking)
1554                            {
1555                               if((pointer = strstr(line, "undefined"))  ||
1556                                    (pointer = strstr(line, "No such file")) ||
1557                                    (pointer = strstr(line, "token")))
1558                               {
1559                                  strncat(moduleName, colon, pointer - colon);
1560                                  strcat(moduleName, "error: ");
1561                                  colon = pointer;
1562                                  numErrors ++;
1563                               }
1564                            }
1565                            else if((pointer = strstr(line, "No such file")))
1566                            {
1567                               strncat(moduleName, colon, pointer - colon);
1568                               strcat(moduleName, "error: ");
1569                               colon = pointer;
1570                               numErrors ++;
1571                            }
1572                            else if(compilingEC == 1 || (objDir && objDir == moduleName))
1573                               continue;
1574                            else if(strstr(line, "warning:"))
1575                            {
1576                               numWarnings++;
1577                            }
1578                         }
1579                         if(this == ide.workspace.projects.firstIterator.data)
1580                            ide.outputView.buildBox.Logf("   %s%s\n", moduleName, colon);
1581                         else
1582                         {
1583                            char fullModuleName[MAX_LOCATION];
1584                            strcpy(fullModuleName, topNode.path);
1585                            PathCat(fullModuleName, moduleName);
1586                            MakePathRelative(fullModuleName, ide.workspace.projects.firstIterator.data.topNode.path, fullModuleName);
1587                            MakeSystemPath(fullModuleName);
1588                            ide.outputView.buildBox.Logf("   %s%s%s\n", inFileIncludedFrom ? stringInFileIncludedFrom : "", fullModuleName, colon);
1589                         }
1590                      }
1591                      else
1592                      {
1593                         ide.outputView.buildBox.Logf("%s\n", line);
1594                         linking = compiling = precompiling = false;
1595                      }
1596                   }
1597                   else
1598                      ide.outputView.buildBox.Logf("%s\n", line);
1599                }
1600                wait = false;
1601             }
1602             //printf("Done getting line\n");
1603             if(GetTime() - lastTime > 1.0 / PEEK_RESOLUTION) break;
1604          }
1605          //printf("Processing Input...\n");
1606          if(app.ProcessInput(true))
1607             wait = false;
1608          app.UpdateDisplay();
1609          if(wait)
1610          {
1611             //printf("Waiting...\n");
1612             app.Wait();
1613          }
1614          //if(!result) Sleep(1.0 / PEEK_RESOLUTION);
1615       }
1616       if(ide.ShouldStopBuild())
1617       {
1618          ide.outputView.buildBox.Logf($"\nBuild cancelled by user.\n", line);
1619          f.Terminate();
1620       }
1621       else if(loggedALine || !isARun)
1622       {
1623          if(f.GetExitCode() && !numErrors)
1624          {
1625             bool result = f.GetLine(line, sizeof(line)-1);
1626             ide.outputView.buildBox.Logf($"Fatal Error: child process terminated unexpectedly\n");
1627          }
1628          else
1629          {
1630             if(!onlyNode)
1631                ide.outputView.buildBox.Logf("\n%s (%s) - ", GetTargetFileName(config), configName);
1632             if(numErrors)
1633                ide.outputView.buildBox.Logf("%d %s, ", numErrors, (numErrors > 1) ? $"errors" : $"error");
1634             else
1635                ide.outputView.buildBox.Logf($"no error, ");
1636    
1637             if(numWarnings)
1638                ide.outputView.buildBox.Logf("%d %s\n", numWarnings, (numWarnings > 1) ? $"warnings" : $"warning");
1639             else
1640                ide.outputView.buildBox.Logf($"no warning\n");
1641          }
1642       }
1643       return numErrors == 0;
1644    }
1645
1646    void ProcessCleanPipeOutput(DualPipe f, CompilerConfig compiler, ProjectConfig config)
1647    {
1648       char line[65536];
1649       int lenMakeCommand = strlen(compiler.makeCommand);
1650       while(!f.Eof())
1651       {
1652          bool result = true;
1653          bool wait = true;
1654          double lastTime = GetTime();
1655          while(result)
1656          {
1657             if((result = f.Peek()) && (result = f.GetLine(line, sizeof(line)-1)))
1658             {
1659                if(strstr(line, compiler.makeCommand) == line && line[lenMakeCommand] == ':');
1660                else if(strstr(line, "del") == line);
1661                else if(strstr(line, "rm") == line);
1662                else if(strstr(line, "Could Not Find") == line);
1663                else
1664                {
1665                   ide.outputView.buildBox.Logf(line);
1666                   ide.outputView.buildBox.Logf("\n");
1667                }
1668                wait = false;
1669             }
1670             if(GetTime() - lastTime > 1.0 / PEEK_RESOLUTION) break;
1671          }
1672          if(app.ProcessInput(true))
1673             wait = false;
1674          app.UpdateDisplay();
1675          if(wait)
1676             app.Wait();
1677          //Sleep(1.0 / PEEK_RESOLUTION);
1678       }
1679    }
1680
1681    bool Build(bool isARun, ProjectNode onlyNode, CompilerConfig compiler, ProjectConfig config)
1682    {
1683       bool result = false;
1684       DualPipe f;
1685       char targetFileName[MAX_LOCATION] = "";
1686       char makeTarget[MAX_LOCATION] = "";
1687       char makeFile[MAX_LOCATION];
1688       char makeFilePath[MAX_LOCATION];
1689       char configName[MAX_LOCATION];
1690       DirExpression objDirExp = GetObjDir(compiler, config);
1691       PathBackup pathBackup { };
1692       bool crossCompiling = (compiler.targetPlatform != GetRuntimePlatform());
1693       char * targetPlatform = crossCompiling ? (char *)compiler.targetPlatform : "";
1694
1695       int numJobs = compiler.numJobs;
1696       char command[MAX_LOCATION];
1697       char * compilerName;
1698
1699       compilerName = CopyString(compiler.name);
1700       CamelCase(compilerName);
1701
1702       strcpy(configName, config ? config.name : "Common");
1703
1704       SetPath(false, compiler, config); //true
1705       CatTargetFileName(targetFileName, compiler, config);
1706
1707       strcpy(makeFilePath, topNode.path);
1708       CatMakeFileName(makeFile, config);
1709       PathCatSlash(makeFilePath, makeFile);
1710
1711       // TODO: TEST ON UNIX IF \" around makeTarget is ok
1712       if(onlyNode)
1713       {
1714          if(compiler.type.isVC)
1715          {
1716             PrintLn("compiling a single file is not yet supported");
1717          }
1718          else
1719          {
1720             int len;
1721             char pushD[MAX_LOCATION];
1722             char cfDir[MAX_LOCATION];
1723             GetIDECompilerConfigsDir(cfDir, true, true);
1724             GetWorkingDir(pushD, sizeof(pushD));
1725             ChangeWorkingDir(topNode.path);
1726             // Create object dir if it does not exist already
1727             if(!FileExists(objDirExp.dir).isDirectory)
1728             {
1729                sprintf(command, "%s CF_DIR=\"%s\"%s%s COMPILER=%s objdir -C \"%s\" -f \"%s\"",
1730                      compiler.makeCommand, cfDir,
1731                      crossCompiling ? " TARGET_PLATFORM=" : "", targetPlatform,
1732                      compilerName, topNode.path, makeFilePath);
1733 #ifdef _DEBUG
1734                PrintLn(command);
1735                ide.outputView.buildBox.Logf("command: %s\n", command);
1736 #endif
1737                Execute(command);
1738             }
1739
1740             ChangeWorkingDir(pushD);
1741
1742             PathCatSlash(makeTarget+1, objDirExp.dir);
1743             PathCatSlash(makeTarget+1, onlyNode.name);
1744             StripExtension(makeTarget+1);
1745             strcat(makeTarget+1, ".o");
1746             makeTarget[0] = '\"';
1747             len = strlen(makeTarget);
1748             makeTarget[len++] = '\"';
1749             makeTarget[len++] = '\0';
1750          }
1751       }
1752
1753       if(compiler.type.isVC)
1754       {
1755          bool result = false;
1756          char oldwd[MAX_LOCATION];
1757          GetWorkingDir(oldwd, sizeof(oldwd));
1758          ChangeWorkingDir(topNode.path);
1759
1760          sprintf(command, "%s /useenv /nologo /logcommands %s.sln %s|Win32", compiler.makeCommand, name, config.name);
1761          ide.outputView.buildBox.Logf("command: %s\n", command);
1762 #ifdef _DEBUG
1763          PrintLn(command);
1764          ide.outputView.buildBox.Logf("command: %s\n", command);
1765 #endif
1766          if((f = DualPipeOpen(PipeOpenMode { output = true, error = true, input = true }, command)))
1767          {
1768             ProcessPipeOutputRaw(f);
1769             delete f;
1770             result = true;
1771          }
1772          ChangeWorkingDir(oldwd);
1773       }
1774       else
1775       {
1776          char cfDir[MAX_LOCATION];
1777          GetIDECompilerConfigsDir(cfDir, true, true);
1778          sprintf(command, "%s CF_DIR=\"%s\"%s%s COMPILER=%s -j%d %s%s%s -C \"%s\" -f \"%s\"",
1779                compiler.makeCommand, cfDir,
1780                crossCompiling ? " TARGET_PLATFORM=" : "", targetPlatform,
1781                compilerName, numJobs,
1782                compiler.ccacheEnabled ? "CCACHE=y " : "",
1783                compiler.distccEnabled ? "DISTCC=y " : "",
1784                makeTarget, topNode.path, makeFilePath);
1785 #ifdef _DEBUG
1786          PrintLn(command);
1787          ide.outputView.buildBox.Logf("command: %s\n", command);
1788 #endif
1789          if((f = DualPipeOpen(PipeOpenMode { output = true, error = true, input = true }, command)))
1790          {
1791             result = ProcessBuildPipeOutput(f, objDirExp, isARun, onlyNode, compiler, config);
1792             delete f;
1793          }
1794          else
1795          {
1796             ide.outputView.buildBox.Logf($"Error executing make (%s) command\n", compiler.makeCommand);
1797 #ifndef _DEBUG
1798             ide.outputView.buildBox.Logf("command: %s\n", command);
1799 #endif
1800          }
1801       }
1802
1803       delete pathBackup;
1804       delete objDirExp;
1805       delete compilerName;
1806       return result;
1807    }
1808
1809    void Clean(CompilerConfig compiler, ProjectConfig config, bool realclean)
1810    {
1811       char makeFile[MAX_LOCATION];
1812       char makeFilePath[MAX_LOCATION];
1813       char command[MAX_LOCATION];
1814       char * compilerName;
1815       DualPipe f;
1816       PathBackup pathBackup { };
1817       bool crossCompiling = (compiler.targetPlatform != GetRuntimePlatform());
1818       char * targetPlatform = crossCompiling ? (char *)compiler.targetPlatform : "";
1819
1820       compilerName = CopyString(compiler.name);
1821       CamelCase(compilerName);
1822
1823       SetPath(false, compiler, config);
1824
1825       strcpy(makeFilePath, topNode.path);
1826       CatMakeFileName(makeFile, config);
1827       PathCatSlash(makeFilePath, makeFile);
1828       
1829       if(compiler.type.isVC)
1830       {
1831          bool result = false;
1832          char oldwd[MAX_LOCATION];
1833          GetWorkingDir(oldwd, sizeof(oldwd));
1834          ChangeWorkingDir(topNode.path);
1835          
1836          sprintf(command, "%s /useenv /clean /nologo /logcommands %s.sln %s|Win32", compiler.makeCommand, name, config.name);
1837          ide.outputView.buildBox.Logf("command: %s\n", command);
1838 #ifdef _DEBUG
1839          PrintLn(command);
1840          ide.outputView.buildBox.Logf("command: %s\n", command);
1841 #endif
1842          if((f = DualPipeOpen(PipeOpenMode { output = true, error = true, input = true }, command)))
1843          {
1844             ProcessPipeOutputRaw(f);
1845             delete f;
1846             result = true;
1847          }
1848          ChangeWorkingDir(oldwd);
1849          return result;
1850       }
1851       else
1852       {
1853          char cfDir[MAX_LOCATION];
1854          GetIDECompilerConfigsDir(cfDir, true, true);
1855          sprintf(command, "%s CF_DIR=\"%s\"%s%s COMPILER=%s %sclean -C \"%s\" -f \"%s\"",
1856                compiler.makeCommand, cfDir,
1857                crossCompiling ? " TARGET_PLATFORM=" : "", targetPlatform,
1858                compilerName, realclean ? "real" : "", topNode.path, makeFilePath);
1859 #ifdef _DEBUG
1860          PrintLn(command);
1861          ide.outputView.buildBox.Logf("command: %s\n", command);
1862 #endif
1863          if((f = DualPipeOpen(PipeOpenMode { output = 1, error = 1, input = 2 }, command)))
1864          {
1865             ide.outputView.buildBox.Tell($"Deleting target and object files...");
1866             ProcessCleanPipeOutput(f, compiler, config);
1867             delete f;
1868
1869             ide.outputView.buildBox.Logf($"Target and object files deleted\n");
1870          }
1871       }
1872
1873       delete pathBackup;
1874       delete compilerName;
1875    }
1876
1877    void Run(char * args, CompilerConfig compiler, ProjectConfig config)
1878    {   
1879       String target = new char[maxPathLen];
1880       char oldDirectory[MAX_LOCATION];
1881       DirExpression targetDirExp = GetTargetDir(compiler, config);
1882       PathBackup pathBackup { };
1883
1884       // Build(project, ideMain, true, null);
1885
1886    #if defined(__WIN32__)
1887       strcpy(target, topNode.path);
1888    #else
1889       strcpy(target, "");
1890    #endif
1891       PathCatSlash(target, targetDirExp.dir);
1892       CatTargetFileName(target, compiler, config);
1893       sprintf(target, "%s %s", target, args);
1894       GetWorkingDir(oldDirectory, MAX_LOCATION);
1895
1896       if(strlen(ide.workspace.debugDir))
1897       {
1898          char temp[MAX_LOCATION];
1899          strcpy(temp, topNode.path);
1900          PathCatSlash(temp, ide.workspace.debugDir);
1901          ChangeWorkingDir(temp);
1902       }
1903       else
1904          ChangeWorkingDir(topNode.path);
1905       // ChangeWorkingDir(topNode.path);
1906       SetPath(true, compiler, config);
1907       if(compiler.execPrefixCommand)
1908       {
1909          char * prefixedTarget = new char[strlen(compiler.execPrefixCommand) + strlen(target) + 2];
1910          prefixedTarget[0] = '\0';
1911          strcat(prefixedTarget, compiler.execPrefixCommand);
1912          strcat(prefixedTarget, " ");
1913          strcat(prefixedTarget, target);
1914          Execute(prefixedTarget);
1915          delete prefixedTarget;
1916       }
1917       else
1918          Execute(target);
1919
1920       ChangeWorkingDir(oldDirectory);
1921       delete pathBackup;
1922
1923       delete targetDirExp;
1924       delete target;
1925    }
1926
1927    void Compile(ProjectNode node, CompilerConfig compiler, ProjectConfig config)
1928    {
1929       Build(false, node, compiler, config);
1930    }
1931 #endif
1932
1933    void GetMakefileTargetFileName(TargetTypes targetType, char * fileName, ProjectConfig config)
1934    {
1935       fileName[0] = '\0';
1936       if(targetType == staticLibrary || targetType == sharedLibrary)
1937          strcat(fileName, "$(LP)");
1938       // !!! ReplaceSpaces must be done after all PathCat calls !!!
1939       // ReplaceSpaces(s, GetTargetFileName(config));
1940       strcat(fileName, GetTargetFileName(config));
1941       switch(targetType)
1942       {
1943          case executable:
1944             strcat(fileName, "$(E)");
1945             break;
1946          case sharedLibrary:
1947             strcat(fileName, "$(SO)");
1948             break;
1949          case staticLibrary:
1950             strcat(fileName, "$(A)");
1951             break;
1952       }
1953    }
1954
1955    bool GenerateCrossPlatformMk()
1956    {
1957       bool result = false;
1958       char path[MAX_LOCATION];
1959
1960       if(!GetProjectCompilerConfigsDir(path, false, false))
1961          GetIDECompilerConfigsDir(path, false, false);
1962
1963       if(!FileExists(path).isDirectory)
1964       {
1965          MakeDir(path);
1966          {
1967             char dirName[MAX_FILENAME];
1968             GetLastDirectory(path, dirName);
1969             if(!strcmp(dirName, ".configs"))
1970                FileSetAttribs(path, FileAttribs { isHidden = true });
1971          }
1972       }
1973       PathCatSlash(path, "crossplatform.mk");
1974
1975       if(FileExists(path))
1976          DeleteFile(path);
1977       {
1978          File include = FileOpen(":crossplatform.mk", read);
1979          if(include)
1980          {
1981             File f = FileOpen(path, write);
1982             if(f)
1983             {
1984                for(; !include.Eof(); )
1985                {
1986                   char buffer[4096];
1987                   int count = include.Read(buffer, 1, 4096);
1988                   f.Write(buffer, 1, count);
1989                }
1990                delete f;
1991
1992                result = true;
1993             }
1994             delete include;
1995          }
1996       }
1997       return result;
1998    }
1999
2000    bool GenerateCompilerCf(CompilerConfig compiler)
2001    {
2002       bool result = false;
2003       char path[MAX_LOCATION];
2004       char * name;
2005       char * compilerName;
2006       bool gccCompiler = compiler.ccCommand && (strstr(compiler.ccCommand, "gcc") != null || strstr(compiler.ccCommand, "g++") != null);
2007       Platform platform = compiler.targetPlatform;
2008
2009       compilerName = CopyString(compiler.name);
2010       CamelCase(compilerName);
2011       name = PrintString(platform, "-", compilerName, ".cf");
2012
2013       if(!GetProjectCompilerConfigsDir(path, false, false))
2014          GetIDECompilerConfigsDir(path, false, false);
2015
2016       if(!FileExists(path).isDirectory)
2017       {
2018          MakeDir(path);
2019          {
2020             char dirName[MAX_FILENAME];
2021             GetLastDirectory(path, dirName);
2022             if(!strcmp(dirName, ".configs"))
2023                FileSetAttribs(path, FileAttribs { isHidden = true });
2024          }
2025       }
2026       PathCatSlash(path, name);
2027
2028       if(FileExists(path))
2029          DeleteFile(path);
2030       {
2031          File f = FileOpen(path, write);
2032          if(f)
2033          {
2034             f.Puts("# TOOLCHAIN\n");
2035             f.Puts("\n");
2036
2037             if(compiler.gccPrefix && compiler.gccPrefix[0])
2038             {
2039                f.Printf("GCC_PREFIX := %s\n", compiler.gccPrefix);
2040                f.Puts("\n");
2041             }
2042             if(compiler.sysroot && compiler.sysroot[0])
2043             {
2044                f.Printf("SYSROOT := %s\n", compiler.sysroot);
2045                f.Puts("_SYSROOT := $(space)--sysroot=$(SYSROOT)\n");
2046                f.Puts("\n");
2047             }
2048
2049             //f.Printf("SHELL := %s\n", "sh"/*compiler.shellCommand*/); // is this really needed?
2050             f.Printf("CPP := $(GCC_PREFIX)%s$(_SYSROOT)\n", compiler.cppCommand);
2051             f.Printf("CC := $(CCACHE_COMPILE) $(DISTCC_COMPILE) $(GCC_PREFIX)%s$(_SYSROOT)\n", compiler.ccCommand);
2052             f.Printf("CXX := $(CCACHE_COMPILE) $(DISTCC_COMPILE) $(GCC_PREFIX)%s$(_SYSROOT)\n", compiler.cxxCommand);
2053             f.Printf("ECP := %s\n", compiler.ecpCommand);
2054             f.Printf("ECC := %s\n", compiler.eccCommand);
2055             f.Printf("ECS := %s$(if $(CROSS_TARGET), -t $(TARGET_PLATFORM),)\n", compiler.ecsCommand);
2056             f.Printf("EAR := %s\n", compiler.earCommand);
2057
2058             f.Puts("AS := $(GCC_PREFIX)as\n");
2059             f.Puts("LD := $(GCC_PREFIX)ld\n");
2060             f.Puts("AR := $(GCC_PREFIX)ar\n");
2061             f.Puts("STRIP := $(GCC_PREFIX)strip\n");
2062             f.Puts("UPX := upx\n");
2063             f.Puts("\n");
2064
2065             if(compiler.environmentVars && compiler.environmentVars.count)
2066             {
2067                f.Puts("# ENVIRONMENT VARIABLES\n");
2068                f.Puts("\n");
2069                for(e : compiler.environmentVars)
2070                {
2071                   f.Printf("export %s := %s\n", e.name, e.string);
2072                }
2073             }
2074
2075             f.Puts("UPXFLAGS = -9\n"); // TOFEAT: Compression Level Option? Other UPX Options?
2076             f.Puts("\n");
2077
2078             f.Puts("EARFLAGS = aw\n");
2079             f.Puts("\n");
2080
2081             f.Puts("# HARD CODED TARGET_PLATFORM-SPECIFIC OPTIONS\n");
2082             f.Printf("LDFLAGS +=$(if $(%s), -Wl,--no-undefined,)\n", PlatformToMakefileTargetVariable(tux));
2083             f.Puts("\n");
2084
2085             // JF's
2086             f.Printf("LDFLAGS +=$(if $(%s), -framework cocoa -framework OpenGL,)\n", PlatformToMakefileTargetVariable(apple));
2087
2088             if(gccCompiler)
2089             {
2090                f.Puts("\nCFLAGS += -fmessage-length=0\n");
2091             }
2092
2093             if(compiler.includeDirs && compiler.includeDirs.count)
2094             {
2095                f.Puts("\nCFLAGS +=");
2096                OutputListOption(f, gccCompiler ? "isystem " : "I", compiler.includeDirs, lineEach, true);
2097                f.Puts("\n");
2098             }
2099             if(compiler.prepDirectives && compiler.prepDirectives.count)
2100             {
2101                f.Puts("\nCFLAGS +=");
2102                OutputListOption(f, "D", compiler.prepDirectives, inPlace, true);
2103                f.Puts("\n");
2104             }
2105             if(compiler.libraryDirs && compiler.libraryDirs.count)
2106             {
2107                f.Puts("\nLDFLAGS +=");
2108                OutputListOption(f, "L", compiler.libraryDirs, lineEach, true);
2109                // We would need a bool option to know whether we want to add to rpath as well...
2110                // OutputListOption(f, "Wl,-rpath ", compiler.libraryDirs, lineEach, true);
2111                f.Puts("\n");
2112             }
2113             if(compiler.excludeLibs && compiler.excludeLibs.count)
2114             {
2115                f.Puts("\nEXCLUDED_LIBS =");
2116                for(l : compiler.excludeLibs)
2117                {
2118                   f.Puts(" ");
2119                   f.Puts(l);
2120                }
2121             }
2122             if(compiler.linkerFlags && compiler.linkerFlags.count)
2123             {
2124                f.Puts("\nLDFLAGS +=");
2125                OutputListOption(f, "Wl,", compiler.linkerFlags, inPlace, true);
2126                f.Puts("\n");
2127             }
2128             f.Printf("\nFORCE_64_BIT := %s", compiler.supportsBitDepth ? "-m64" : "");
2129             f.Printf("\nFORCE_32_BIT := %s", compiler.supportsBitDepth ? "-m32" : "");
2130             f.Puts("\n");
2131
2132             delete f;
2133          }
2134       }
2135       delete name;
2136       delete compilerName;
2137       return result;
2138    }
2139
2140    bool GenerateMakefile(char * altMakefilePath, bool noResources, char * includemkPath, ProjectConfig config)
2141    {
2142       bool result = false;
2143       char filePath[MAX_LOCATION];
2144       char makeFile[MAX_LOCATION];
2145       // PathBackup pathBackup { };
2146       // char oldDirectory[MAX_LOCATION];
2147       File f = null;
2148
2149       if(!altMakefilePath)
2150       {
2151          strcpy(filePath, topNode.path);
2152          CatMakeFileName(makeFile, config);
2153          PathCatSlash(filePath, makeFile);
2154       }
2155
2156       f = FileOpen(altMakefilePath ? altMakefilePath : filePath, write);
2157
2158       /*SetPath(false, compiler, config);
2159       GetWorkingDir(oldDirectory, MAX_LOCATION);
2160       ChangeWorkingDir(topNode.path);*/
2161
2162       if(f)
2163       {
2164          bool test;
2165          int ifCount;
2166          Platform platform;
2167          char targetDir[MAX_LOCATION];
2168          char objDirExpNoSpaces[MAX_LOCATION];
2169          char objDirNoSpaces[MAX_LOCATION];
2170          char resDirNoSpaces[MAX_LOCATION];
2171          char targetDirExpNoSpaces[MAX_LOCATION];
2172          char fixedModuleName[MAX_FILENAME];
2173          char fixedConfigName[MAX_FILENAME];
2174          int c, len;
2175          // Non-zero if we're building eC code
2176          // We'll have to be careful with this when merging configs where eC files can be excluded in some configs and included in others
2177          int numCObjects = 0;
2178          int numObjects = 0;
2179          bool containsCXX = false; // True if the project contains a C++ file
2180          bool sameObjTargetDirs;
2181          String objDirExp = GetObjDirExpression(config);
2182          TargetTypes targetType = GetTargetType(config);
2183
2184          char cfDir[MAX_LOCATION];
2185          int objectsParts = 0, eCsourcesParts = 0;
2186          Array<String> listItems { };
2187          Map<String, int> varStringLenDiffs { };
2188          Map<String, NameCollisionInfo> namesInfo { };
2189          bool forceBitDepth = false;
2190
2191          Map<String, int> cflagsVariations { };
2192          Map<int, int> nodeCFlagsMapping { };
2193
2194          Map<String, int> ecflagsVariations { };
2195          Map<int, int> nodeECFlagsMapping { };
2196
2197          ReplaceSpaces(objDirNoSpaces, objDirExp);
2198          strcpy(targetDir, GetTargetDirExpression(config));
2199          ReplaceSpaces(targetDirExpNoSpaces, targetDir);
2200
2201          strcpy(objDirExpNoSpaces, GetObjDirExpression(config));
2202          ChangeCh(objDirExpNoSpaces, '\\', '/'); // TODO: this is a hack, paths should never include win32 path seperators - fix this in ProjectSettings and ProjectLoad instead
2203          ReplaceSpaces(objDirExpNoSpaces, objDirExpNoSpaces);
2204          ReplaceSpaces(resDirNoSpaces, resNode.path ? resNode.path : "");
2205          ReplaceSpaces(fixedModuleName, moduleName);
2206          ReplaceSpaces(fixedConfigName, GetConfigName(config));
2207          CamelCase(fixedConfigName);
2208
2209          sameObjTargetDirs = !fstrcmp(objDirExpNoSpaces, targetDirExpNoSpaces);
2210
2211          f.Printf(".PHONY: all objdir%s clean realclean distclean\n\n", sameObjTargetDirs ? "" : " targetdir");
2212
2213          f.Puts("# CORE VARIABLES\n\n");
2214
2215          f.Printf("MODULE := %s\n", fixedModuleName);
2216          //f.Printf("VERSION = %s\n", version);
2217          f.Printf("CONFIG := %s\n", fixedConfigName);
2218          f.Puts("ifndef COMPILER\n" "COMPILER := default\n" "endif\n");
2219          f.Puts("\n");
2220
2221          test = GetTargetTypeIsSetByPlatform(config);
2222          if(test)
2223          {
2224             ifCount = 0;
2225             for(platform = (Platform)1; platform < Platform::enumSize; platform++)
2226             {
2227                TargetTypes targetType;
2228                PlatformOptions projectPOs, configPOs;
2229                MatchProjectAndConfigPlatformOptions(config, platform, &projectPOs, &configPOs);
2230                targetType = platformTargetType;
2231                if(targetType)
2232                {
2233                   if(ifCount)
2234                      f.Puts("else\n");
2235                   ifCount++;
2236                   f.Printf("ifdef %s\n", PlatformToMakefileTargetVariable(platform));
2237                   f.Printf("TARGET_TYPE = %s\n", TargetTypeToMakefileVariable(targetType));
2238                }
2239             }
2240             f.Puts("else\n");
2241          }
2242          f.Printf("TARGET_TYPE = %s\n", TargetTypeToMakefileVariable(targetType));
2243          if(test)
2244          {
2245             if(ifCount)
2246             {
2247                for(c = 0; c < ifCount; c++)
2248                   f.Puts("endif\n");
2249             }
2250          }
2251          f.Puts("\n");
2252
2253          f.Puts("# FLAGS\n\n");
2254
2255          f.Puts("ECFLAGS =\n");
2256          f.Puts("ifndef DEBIAN_PACKAGE\n" "CFLAGS =\n" "endif\n");
2257          f.Puts("CECFLAGS =\n");
2258          f.Puts("OFLAGS =\n");
2259          f.Puts("LDFLAGS =\n");
2260          f.Puts("LIBS =\n");
2261          f.Puts("\n");
2262
2263          f.Puts("ifdef DEBUG\n" "NOSTRIP := y\n" "endif\n");
2264          f.Puts("\n");
2265
2266          f.Puts("ifdef EXECUTABLE_TARGET\n");
2267          f.Printf("CONSOLE = %s\n", GetConsole(config) ? "-mconsole" : "-mwindows");
2268          f.Puts("endif\n");
2269          f.Puts("\n");
2270
2271          f.Puts("# INCLUDES\n\n");
2272
2273          if(compilerConfigsDir && compilerConfigsDir[0])
2274          {
2275             strcpy(cfDir, compilerConfigsDir);
2276             if(cfDir && cfDir[0] && cfDir[strlen(cfDir)-1] != '/')
2277                strcat(cfDir, "/");
2278          }
2279          else
2280          {
2281             GetIDECompilerConfigsDir(cfDir, true, true);
2282             // Use CF_DIR environment variable for absolute paths only
2283             if(cfDir[0] == '/' || (cfDir[0] && cfDir[1] == ':'))
2284                strcpy(cfDir, "$(CF_DIR)");
2285          }
2286
2287          f.Printf("_CF_DIR = %s\n", cfDir);
2288          f.Puts("\n");
2289
2290          f.Printf("include %s\n", includemkPath ? includemkPath : "$(_CF_DIR)crossplatform.mk");
2291          f.Puts("include $(_CF_DIR)$(TARGET_PLATFORM)-$(COMPILER).cf\n");
2292          f.Puts("\n");
2293
2294          f.Puts("# POST-INCLUDES VARIABLES\n\n");
2295
2296          f.Printf("OBJ = %s%s\n", objDirExpNoSpaces, objDirExpNoSpaces[0] ? "/" : "");
2297          f.Puts("\n");
2298
2299          f.Printf("RES = %s%s\n", resDirNoSpaces, resDirNoSpaces[0] ? "/" : "");
2300          f.Puts("\n");
2301
2302          // test = GetTargetTypeIsSetByPlatform(config);
2303          {
2304             char target[MAX_LOCATION];
2305             char targetNoSpaces[MAX_LOCATION];
2306             if(test)
2307             {
2308                TargetTypes type;
2309                ifCount = 0;
2310                for(type = (TargetTypes)1; type < TargetTypes::enumSize; type++)
2311                {
2312                   if(type != targetType)
2313                   {
2314                      if(ifCount)
2315                         f.Puts("else\n");
2316                      ifCount++;
2317                      f.Printf("ifeq \"$(TARGET_TYPE)\" \"%s\"\n", TargetTypeToMakefileVariable(type));
2318
2319                      GetMakefileTargetFileName(type, target, config);
2320                      strcpy(targetNoSpaces, targetDir);
2321                      PathCatSlash(targetNoSpaces, target);
2322                      ReplaceSpaces(targetNoSpaces, targetNoSpaces);
2323                      f.Printf("TARGET = %s\n", targetNoSpaces);
2324                   }
2325                }
2326                f.Puts("else\n");
2327             }
2328             GetMakefileTargetFileName(targetType, target, config);
2329             strcpy(targetNoSpaces, targetDir);
2330             PathCatSlash(targetNoSpaces, target);
2331             ReplaceSpaces(targetNoSpaces, targetNoSpaces);
2332             f.Printf("TARGET = %s\n", targetNoSpaces);
2333
2334             if(test)
2335             {
2336                if(ifCount)
2337                {
2338                   for(c = 0; c < ifCount; c++)
2339                      f.Puts("endif\n");
2340                }
2341             }
2342          }
2343          f.Puts("\n");
2344
2345          // Use something fixed here, to not cause Makefile differences across compilers...
2346          varStringLenDiffs["$(OBJ)"] = 30; // strlen("obj/memoryGuard.android.gcc-4.6.2") - 6;
2347          // varStringLenDiffs["$(OBJ)"] = strlen(objDirNoSpaces) - 6;
2348
2349          topNode.GenMakefileGetNameCollisionInfo(namesInfo, config);
2350
2351          {
2352             int c;
2353             char * map[5][2] = { { "COBJECTS", "C" }, { "SYMBOLS", "S" }, { "IMPORTS", "I" }, { "ECOBJECTS", "O" }, { "BOWLS", "B" } };
2354
2355             numCObjects = topNode.GenMakefilePrintNode(f, this, eCsources, namesInfo, listItems, config, null);
2356             if(numCObjects)
2357             {
2358                eCsourcesParts = OutputFileList(f, "_ECSOURCES", listItems, varStringLenDiffs, null);
2359
2360                f.Puts("ECSOURCES = $(call shwspace,$(_ECSOURCES))\n");
2361                if(eCsourcesParts > 1)
2362                {
2363                   for(c = 1; c <= eCsourcesParts; c++)
2364                      f.Printf("ECSOURCES%d = $(call shwspace,$(_ECSOURCES%d))\n", c, c);
2365                }
2366                f.Puts("\n");
2367
2368                for(c = 0; c < 5; c++)
2369                {
2370                   if(eCsourcesParts > 1)
2371                   {
2372                      int n;
2373                      f.Printf("%s =", map[c][0]);
2374                      for(n = 1; n <= eCsourcesParts; n++)
2375                         f.Printf(" $(%s%d)", map[c][0], n);
2376                      f.Puts("\n");
2377                      for(n = 1; n <= eCsourcesParts; n++)
2378                         f.Printf("%s%d = $(call shwspace,$(addprefix $(OBJ),$(patsubst %%.ec,%%$(%s),$(notdir $(_ECSOURCES%d)))))\n", map[c][0], n, map[c][1], n);
2379                   }
2380                   else if(eCsourcesParts == 1)
2381                      f.Printf("%s = $(call shwspace,$(addprefix $(OBJ),$(patsubst %%.ec,%%$(%s),$(notdir $(_ECSOURCES)))))\n", map[c][0], map[c][1]);
2382                   f.Puts("\n");
2383                }
2384             }
2385          }
2386
2387          numObjects = topNode.GenMakefilePrintNode(f, this, objects, namesInfo, listItems, config, &containsCXX);
2388          if(numObjects)
2389             objectsParts = OutputFileList(f, "_OBJECTS", listItems, varStringLenDiffs, null);
2390          f.Printf("OBJECTS =%s%s%s\n", numObjects ? " $(_OBJECTS)" : "", numCObjects ? " $(ECOBJECTS)" : "", numCObjects ? " $(OBJ)$(MODULE).main$(O)" : "");
2391          f.Puts("\n");
2392
2393          topNode.GenMakefilePrintNode(f, this, sources, null, listItems, config, null);
2394          OutputFileList(f, "SOURCES", listItems, varStringLenDiffs, "$(ECSOURCES)");
2395
2396          if(!noResources)
2397             resNode.GenMakefilePrintNode(f, this, resources, null, listItems, config, null);
2398          OutputFileList(f, "RESOURCES", listItems, varStringLenDiffs, null);
2399
2400          f.Puts("LIBS += $(SHAREDLIB) $(EXECUTABLE) $(LINKOPT)\n");
2401          f.Puts("\n");
2402          if((config && config.options && config.options.libraries) ||
2403                (options && options.libraries))
2404          {
2405             f.Puts("ifndef STATIC_LIBRARY_TARGET\n");
2406             f.Puts("LIBS +=");
2407             if(config && config.options && config.options.libraries)
2408                OutputLibraries(f, config.options.libraries);
2409             else if(options && options.libraries)
2410                OutputLibraries(f, options.libraries);
2411             f.Puts("\n");
2412             f.Puts("endif\n");
2413             f.Puts("\n");
2414          }
2415
2416          topNode.GenMakeCollectAssignNodeFlags(config, numCObjects,
2417                cflagsVariations, nodeCFlagsMapping,
2418                ecflagsVariations, nodeECFlagsMapping, null);
2419
2420          GenMakePrintCustomFlags(f, "CFLAGS", false, cflagsVariations);
2421          GenMakePrintCustomFlags(f, "ECFLAGS", true, ecflagsVariations);
2422
2423          if(platforms || (config && config.platforms))
2424          {
2425             ifCount = 0;
2426             //for(platform = firstPlatform; platform <= lastPlatform; platform++)
2427             //for(platform = win32; platform <= apple; platform++)
2428
2429             f.Puts("# PLATFORM-SPECIFIC OPTIONS\n\n");
2430             for(platform = (Platform)1; platform < Platform::enumSize; platform++)
2431             {
2432                PlatformOptions projectPlatformOptions, configPlatformOptions;
2433                MatchProjectAndConfigPlatformOptions(config, platform, &projectPlatformOptions, &configPlatformOptions);
2434
2435                if(projectPlatformOptions || configPlatformOptions)
2436                {
2437                   if(ifCount)
2438                      f.Puts("else\n");
2439                   ifCount++;
2440                   f.Printf("ifdef %s\n", PlatformToMakefileTargetVariable(platform));
2441                   f.Puts("\n");
2442
2443                   if((projectPlatformOptions && projectPlatformOptions.options.linkerOptions && projectPlatformOptions.options.linkerOptions.count) ||
2444                      (configPlatformOptions && configPlatformOptions.options.linkerOptions && configPlatformOptions.options.linkerOptions.count))
2445                   {
2446                      f.Puts("CFLAGS +=");
2447                      // tocheck: does any of that -Wl stuff from linkerOptions have any business being in CFLAGS?
2448                      if(projectPlatformOptions && projectPlatformOptions.options.linkerOptions && projectPlatformOptions.options.linkerOptions.count)
2449                      {
2450                         f.Puts(" \\\n\t -Wl");
2451                         for(s : projectPlatformOptions.options.linkerOptions)
2452                            f.Printf(",%s", s);
2453                      }
2454                      if(configPlatformOptions && configPlatformOptions.options.linkerOptions && configPlatformOptions.options.linkerOptions.count)
2455                      {
2456                         f.Puts(" \\\n\t -Wl");
2457                         for(s : configPlatformOptions.options.linkerOptions)
2458                            f.Printf(",%s", s);
2459                      }
2460                      f.Puts("\n");
2461                      f.Puts("\n");
2462                   }
2463
2464                   if((projectPlatformOptions && projectPlatformOptions.options.libraryDirs && projectPlatformOptions.options.libraryDirs.count) ||
2465                         (configPlatformOptions && configPlatformOptions.options.libraryDirs && configPlatformOptions.options.libraryDirs.count) ||
2466                         (projectPlatformOptions && projectPlatformOptions.options.libraries && projectPlatformOptions.options.libraries.count) ||
2467                         (configPlatformOptions && configPlatformOptions.options.libraries && configPlatformOptions.options.libraries.count))
2468                   {
2469                      f.Puts("ifndef STATIC_LIBRARY_TARGET\n");
2470                      if((projectPlatformOptions && projectPlatformOptions.options.libraryDirs && projectPlatformOptions.options.libraryDirs.count) ||
2471                         (configPlatformOptions && configPlatformOptions.options.libraryDirs && configPlatformOptions.options.libraryDirs.count))
2472                      {
2473                         f.Puts("OFLAGS +=");
2474                         if(configPlatformOptions && configPlatformOptions.options.libraryDirs)
2475                            OutputListOption(f, "L", configPlatformOptions.options.libraryDirs, lineEach, true);
2476                         if(projectPlatformOptions && projectPlatformOptions.options.libraryDirs)
2477                            OutputListOption(f, "L", projectPlatformOptions.options.libraryDirs, lineEach, true);
2478                         f.Puts("\n");
2479                      }
2480
2481                      if((configPlatformOptions && configPlatformOptions.options.libraries))
2482                      {
2483                         if(configPlatformOptions.options.libraries.count)
2484                         {
2485                            f.Puts("LIBS +=");
2486                            OutputLibraries(f, configPlatformOptions.options.libraries);
2487                            f.Puts("\n");
2488                         }
2489                      }
2490                      else if(projectPlatformOptions && projectPlatformOptions.options.libraries)
2491                      {
2492                         if(projectPlatformOptions.options.libraries.count)
2493                         {
2494                            f.Puts("LIBS +=");
2495                            OutputLibraries(f, projectPlatformOptions.options.libraries);
2496                            f.Puts("\n");
2497                         }
2498                      }
2499                      f.Puts("endif\n");
2500                      f.Puts("\n");
2501                   }
2502                }
2503             }
2504             if(ifCount)
2505             {
2506                for(c = 0; c < ifCount; c++)
2507                   f.Puts("endif\n");
2508             }
2509             f.Puts("\n");
2510          }
2511
2512          // tocheck: does any of that -Wl stuff from linkerOptions have any business being in CFLAGS?
2513          if(options && options.linkerOptions && options.linkerOptions.count)
2514          {
2515             f.Puts("CFLAGS +=");
2516             f.Puts(" \\\n\t -Wl");
2517             for(s : options.linkerOptions)
2518                f.Printf(",%s", s);
2519          }
2520          f.Puts("\n");
2521          f.Puts("\n");
2522
2523          f.Puts("CECFLAGS += -cpp $(CPP)");
2524          f.Puts("\n");
2525          f.Puts("\n");
2526
2527          f.Puts("ifndef STATIC_LIBRARY_TARGET\n");
2528          f.Puts("OFLAGS +=");
2529          forceBitDepth = (options && options.buildBitDepth) || numCObjects;
2530          if(forceBitDepth)
2531             f.Puts((!options || !options.buildBitDepth || options.buildBitDepth == bits32) ? " $(FORCE_32_BIT)" : " $(FORCE_64_BIT) \\\n");
2532
2533          if(GetProfile(config))
2534             f.Puts(" -pg");
2535          if(config && config.options && config.options.libraryDirs)
2536             OutputListOption(f, "L", config.options.libraryDirs, lineEach, true);
2537          if(options && options.libraryDirs)
2538             OutputListOption(f, "L", options.libraryDirs, lineEach, true);
2539          f.Puts("\n");
2540          f.Puts("OFLAGS += $(LDFLAGS)\n");
2541          f.Puts("endif\n");
2542          f.Puts("\n");
2543
2544          f.Puts("# TARGETS\n");
2545          f.Puts("\n");
2546
2547          f.Printf("all: objdir%s $(TARGET)\n", sameObjTargetDirs ? "" : " targetdir");
2548          f.Puts("\n");
2549
2550          f.Puts("objdir:\n");
2551             f.Puts("\t$(if $(wildcard $(OBJ)),,$(call mkdirq,$(OBJ)))\n");
2552          //f.Puts("# PRE-BUILD COMMANDS\n");
2553          if(options && options.prebuildCommands)
2554          {
2555             for(s : options.prebuildCommands)
2556                if(s && s[0]) f.Printf("\t%s\n", s);
2557          }
2558          if(config && config.options && config.options.prebuildCommands)
2559          {
2560             for(s : config.options.prebuildCommands)
2561                if(s && s[0]) f.Printf("\t%s\n", s);
2562          }
2563          if(platforms || (config && config.platforms))
2564          {
2565             ifCount = 0;
2566             //f.Puts("# TARGET_PLATFORM-SPECIFIC PRE-BUILD COMMANDS\n");
2567             for(platform = (Platform)1; platform < Platform::enumSize; platform++)
2568             {
2569                PlatformOptions projectPOs, configPOs;
2570                MatchProjectAndConfigPlatformOptions(config, platform, &projectPOs, &configPOs);
2571
2572                if((projectPOs && projectPOs.options.prebuildCommands && projectPOs.options.prebuildCommands.count) ||
2573                      (configPOs && configPOs.options.prebuildCommands && configPOs.options.prebuildCommands.count))
2574                {
2575                   if(ifCount)
2576                      f.Puts("else\n");
2577                   ifCount++;
2578                   f.Printf("ifdef %s\n", PlatformToMakefileTargetVariable(platform));
2579
2580                   if(projectPOs && projectPOs.options.prebuildCommands && projectPOs.options.prebuildCommands.count)
2581                   {
2582                      for(s : projectPOs.options.prebuildCommands)
2583                         if(s && s[0]) f.Printf("\t%s\n", s);
2584                   }
2585                   if(configPOs && configPOs.options.prebuildCommands && configPOs.options.prebuildCommands.count)
2586                   {
2587                      for(s : configPOs.options.prebuildCommands)
2588                         if(s && s[0]) f.Printf("\t%s\n", s);
2589                   }
2590                }
2591             }
2592             if(ifCount)
2593             {
2594                int c;
2595                for(c = 0; c < ifCount; c++)
2596                   f.Puts("endif\n");
2597             }
2598          }
2599          f.Puts("\n");
2600
2601          if(!sameObjTargetDirs)
2602          {
2603             f.Puts("targetdir:\n");
2604                f.Printf("\t$(if $(wildcard %s),,$(call mkdirq,%s))\n", targetDirExpNoSpaces, targetDirExpNoSpaces);
2605             f.Puts("\n");
2606          }
2607
2608          if(numCObjects)
2609          {
2610             // Main Module (Linking) for ECERE C modules
2611             f.Puts("$(OBJ)$(MODULE).main.ec: $(SYMBOLS) $(COBJECTS)\n");
2612             // use of objDirExpNoSpaces used instead of $(OBJ) to prevent problematic joining of arguments in ecs
2613             f.Printf("\t$(ECS)%s $(ECSLIBOPT) $(SYMBOLS) $(IMPORTS) -symbols %s -o $(OBJ)$(MODULE).main.ec\n", 
2614                GetConsole(config) ? " -console" : "", objDirExpNoSpaces);
2615             f.Puts("\n");
2616             // Main Module (Linking) for ECERE C modules
2617             f.Puts("$(OBJ)$(MODULE).main.c: $(OBJ)$(MODULE).main.ec\n");
2618             f.Puts("\t$(ECP) $(CECFLAGS) $(ECFLAGS) $(CFLAGS)"
2619                   " -c $(OBJ)$(MODULE).main.ec -o $(OBJ)$(MODULE).main.sym -symbols $(OBJ)\n");
2620             f.Puts("\t$(ECC) $(CECFLAGS) $(ECFLAGS) $(CFLAGS) $(FVISIBILITY)"
2621                   " -c $(OBJ)$(MODULE).main.ec -o $(OBJ)$(MODULE).main.c -symbols $(OBJ)\n");
2622             f.Puts("\n");
2623          }
2624
2625          // *** Target ***
2626
2627          // This would not rebuild the target on updated objects
2628          // f.Printf("$(TARGET): $(SOURCES) $(RESOURCES) | objdir $(SYMBOLS) $(OBJECTS)%s\n", sameObjTargetDirs ? "" : " targetdir");
2629
2630          // This should fix it for good!
2631          f.Puts("$(SYMBOLS): | objdir\n");
2632          f.Puts("$(OBJECTS): | objdir\n");
2633
2634          // This alone was breaking the tarball, object directory does not get created first (order-only rules happen last it seems!)
2635          f.Printf("$(TARGET): $(SOURCES) $(RESOURCES) $(SYMBOLS) $(OBJECTS) | objdir%s\n", sameObjTargetDirs ? "" : " targetdir");
2636
2637          f.Puts("ifndef STATIC_LIBRARY_TARGET\n");
2638          f.Printf("\t$(%s) $(OFLAGS) $(OBJECTS) $(LIBS) %s-o $(TARGET) $(INSTALLNAME)\n", containsCXX ? "CXX" : "CC", containsCXX ? "-lstdc++ " : "");
2639          if(!GetDebug(config))
2640          {
2641             f.Puts("ifndef NOSTRIP\n");
2642             f.Puts("\t$(STRIP) $(STRIPOPT) $(TARGET)\n");
2643             f.Puts("endif\n");
2644
2645             if(GetCompress(config))
2646             {
2647                f.Printf("ifndef %s\n", PlatformToMakefileTargetVariable(win32));
2648                f.Puts("ifdef EXECUTABLE_TARGET\n");
2649                   f.Puts("\t$(UPX) $(UPXFLAGS) $(TARGET)\n");
2650                f.Puts("endif\n");
2651                f.Puts("else\n");
2652                   f.Puts("\t$(UPX) $(UPXFLAGS) $(TARGET)\n");
2653                f.Puts("endif\n");
2654             }
2655          }
2656          if(resNode.files && resNode.files.count && !noResources)
2657             resNode.GenMakefileAddResources(f, resNode.path, config);
2658          f.Puts("else\n");
2659          f.Puts("\t$(AR) rcs $(TARGET) $(OBJECTS) $(LIBS)\n");
2660          f.Puts("endif\n");
2661
2662          //f.Puts("# POST-BUILD COMMANDS\n");
2663          if(options && options.postbuildCommands)
2664          {
2665             for(s : options.postbuildCommands)
2666                if(s && s[0]) f.Printf("\t%s\n", s);
2667          }
2668          if(config && config.options && config.options.postbuildCommands)
2669          {
2670             for(s : config.options.postbuildCommands)
2671                if(s && s[0]) f.Printf("\t%s\n", s);
2672          }
2673          if(platforms || (config && config.platforms))
2674          {
2675             ifCount = 0;
2676             //f.Puts("# TARGET_PLATFORM-SPECIFIC POST-BUILD COMMANDS\n");
2677             for(platform = (Platform)1; platform < Platform::enumSize; platform++)
2678             {
2679                PlatformOptions projectPOs, configPOs;
2680                MatchProjectAndConfigPlatformOptions(config, platform, &projectPOs, &configPOs);
2681
2682                if((projectPOs && projectPOs.options.postbuildCommands && projectPOs.options.postbuildCommands.count) ||
2683                      (configPOs && configPOs.options.postbuildCommands && configPOs.options.postbuildCommands.count))
2684                {
2685                   if(ifCount)
2686                      f.Puts("else\n");
2687                   ifCount++;
2688                   f.Printf("ifdef %s\n", PlatformToMakefileTargetVariable(platform));
2689
2690                   if(projectPOs && projectPOs.options.postbuildCommands && projectPOs.options.postbuildCommands.count)
2691                   {
2692                      for(s : projectPOs.options.postbuildCommands)
2693                         if(s && s[0]) f.Printf("\t%s\n", s);
2694                   }
2695                   if(configPOs && configPOs.options.postbuildCommands && configPOs.options.postbuildCommands.count)
2696                   {
2697                      for(s : configPOs.options.postbuildCommands)
2698                         if(s && s[0]) f.Printf("\t%s\n", s);
2699                   }
2700                }
2701             }
2702             if(ifCount)
2703             {
2704                int c;
2705                for(c = 0; c < ifCount; c++)
2706                   f.Puts("endif\n");
2707             }
2708          }
2709          f.Puts("\n");
2710
2711          f.Puts("# SYMBOL RULES\n");
2712          f.Puts("\n");
2713          {
2714             Map<Platform, bool> excludedPlatforms { };
2715             topNode.GenMakefilePrintSymbolRules(f, this, config, excludedPlatforms,
2716                   nodeCFlagsMapping, nodeECFlagsMapping);
2717             delete excludedPlatforms;
2718          }
2719
2720          f.Puts("# C OBJECT RULES\n");
2721          f.Puts("\n");
2722          {
2723             Map<Platform, bool> excludedPlatforms { };
2724             topNode.GenMakefilePrintCObjectRules(f, this, config, excludedPlatforms,
2725                   nodeCFlagsMapping, nodeECFlagsMapping);
2726             delete excludedPlatforms;
2727          }
2728
2729          f.Puts("# OBJECT RULES\n");
2730          f.Puts("\n");
2731          // todo call this still but only generate rules whith specific options
2732          // see we-have-file-specific-options in ProjectNode.ec
2733          {
2734             Map<Platform, bool> excludedPlatforms { };
2735             topNode.GenMakefilePrintObjectRules(f, this, namesInfo, config, excludedPlatforms,
2736                   nodeCFlagsMapping, nodeECFlagsMapping);
2737             delete excludedPlatforms;
2738          }
2739
2740          if(numCObjects)
2741             GenMakefilePrintMainObjectRule(f, config);
2742
2743          f.Printf("clean: objdir%s\n", sameObjTargetDirs ? "" : " targetdir");
2744          f.Printf("\t$(call rmq,%s$(TARGET))\n", numCObjects ? "$(OBJ)$(MODULE).main.o $(OBJ)$(MODULE).main.c $(OBJ)$(MODULE).main.ec $(OBJ)$(MODULE).main$(I) $(OBJ)$(MODULE).main$(S) " : "");
2745          OutputCleanActions(f, "_OBJECTS", objectsParts);
2746          if(numCObjects)
2747          {
2748             OutputCleanActions(f, "ECOBJECTS", eCsourcesParts);
2749             OutputCleanActions(f, "COBJECTS", eCsourcesParts);
2750             OutputCleanActions(f, "BOWLS", eCsourcesParts);
2751             OutputCleanActions(f, "IMPORTS", eCsourcesParts);
2752             OutputCleanActions(f, "SYMBOLS", eCsourcesParts);
2753          }
2754          f.Puts("\n");
2755
2756          f.Puts("realclean: clean\n");
2757          f.Puts("\t$(call rmrq,$(OBJ))\n");
2758          if(!sameObjTargetDirs)
2759             f.Printf("\t$(call rmdirq,%s)\n", targetDirExpNoSpaces);
2760          f.Puts("\n");
2761
2762          f.Puts("distclean:\n");
2763          f.Puts("\t$(call rmrq,obj/)\n");
2764          f.Puts("\n");
2765
2766          delete f;
2767
2768          listItems.Free();
2769          delete listItems;
2770          varStringLenDiffs.Free();
2771          delete varStringLenDiffs;
2772          namesInfo.Free();
2773          delete namesInfo;
2774
2775          delete cflagsVariations;
2776          delete nodeCFlagsMapping;
2777          delete ecflagsVariations;
2778          delete nodeECFlagsMapping;
2779
2780          result = true;
2781       }
2782
2783       // ChangeWorkingDir(oldDirectory);
2784       // delete pathBackup;
2785
2786       if(config)
2787          config.makingModified = false;
2788       return result;
2789    }
2790
2791    void GenMakefilePrintMainObjectRule(File f, ProjectConfig config)
2792    {
2793       char extension[MAX_EXTENSION] = "c";
2794       char modulePath[MAX_LOCATION];
2795       char fixedModuleName[MAX_FILENAME];
2796       DualPipe dep;
2797       char command[2048];
2798       char objDirNoSpaces[MAX_LOCATION];
2799       String objDirExp = GetObjDirExpression(config);
2800
2801       ReplaceSpaces(objDirNoSpaces, objDirExp);
2802       ReplaceSpaces(fixedModuleName, moduleName);
2803       
2804       //sprintf(fixedModuleName, "%s.main", fixedPrjName);
2805       //strcat(fixedModuleName, ".main");
2806
2807 #if 0       // TODO: Fix nospaces stuff
2808       // *** Dependency command ***
2809       sprintf(command, "gcc -MT $(OBJ)%s$(O) -MM $(OBJ)%s.c", fixedModuleName, fixedModuleName);
2810
2811       // System Includes (from global settings)
2812       for(item : compiler.dirs[Includes])
2813       {
2814          strcat(command, " -isystem ");
2815          if(strchr(item.name, ' '))
2816          {
2817             strcat(command, "\"");
2818             strcat(command, item);
2819             strcat(command, "\"");
2820          }
2821          else
2822             strcat(command, item);
2823       }
2824
2825       for(item = includeDirs.first; item; item = item.next)
2826       {
2827          strcat(command, " -I");
2828          if(strchr(item.name, ' '))
2829          {
2830             strcat(command, "\"");
2831             strcat(command, item.name);
2832             strcat(command, "\"");
2833          }
2834          else
2835             strcat(command, item.name);
2836       }
2837       for(item = preprocessorDefs.first; item; item = item.next)
2838       {
2839          strcat(command, " -D");
2840          strcat(command, item.name);
2841       }
2842
2843       // Execute it
2844       if((dep = DualPipeOpen(PipeOpenMode { output = 1, error = 1, input = 2 }, command)))
2845       {
2846          char line[1024];
2847          bool result = true;
2848          bool firstLine = true;
2849
2850          // To do some time: auto save external dependencies?
2851          while(!dep.Eof())
2852          {
2853             if(dep.GetLine(line, sizeof(line)-1))
2854             {
2855                if(firstLine)
2856                {
2857                   char * colon = strstr(line, ":");
2858                   if(strstr(line, "No such file") || strstr(line, ",") || (colon && strstr(colon+1, ":")))
2859                   {
2860                      result = false;
2861                      break;
2862                   }
2863                   firstLine = false;
2864                }
2865                f.Puts(line);
2866                f.Puts("\n");
2867             }
2868             if(!result) break;
2869          }
2870          delete dep;
2871
2872          // If we failed to generate dependencies...
2873          if(!result)
2874          {
2875 #endif
2876             f.Puts("$(OBJ)$(MODULE).main$(O): $(OBJ)$(MODULE).main.c\n");
2877 #if 0
2878          }
2879       }
2880 #endif
2881
2882       f.Printf("\t$(CC) $(CFLAGS) $(FVISIBILITY) -c $(OBJ)$(MODULE).main.%s -o $(OBJ)$(MODULE).main$(O)\n", extension);
2883       f.Puts("\n");
2884    }
2885
2886    void GenMakePrintCustomFlags(File f, String variableName, bool printNonCustom, Map<String, int> cflagsVariations)
2887    {
2888       int c;
2889       for(c = printNonCustom ? 0 : 1; c <= cflagsVariations.count; c++)
2890       {
2891          for(v : cflagsVariations)
2892          {
2893             if(v == c)
2894             {
2895                if(v == 1)
2896                   f.Printf("%s +=", variableName);
2897                else
2898                   f.Printf("CUSTOM%d_%s =", v-1, variableName);
2899                f.Puts(&v ? &v : "");
2900                f.Puts("\n");
2901                f.Puts("\n");
2902                break;
2903             }
2904          }
2905       }
2906       f.Puts("\n");
2907    }
2908
2909    void MatchProjectAndConfigPlatformOptions(ProjectConfig config, Platform platform,
2910          PlatformOptions * projectPlatformOptions, PlatformOptions * configPlatformOptions)
2911    {
2912       *projectPlatformOptions = null;
2913       *configPlatformOptions = null;
2914       if(platforms)
2915       {
2916          for(p : platforms)
2917          {
2918             if(!strcmpi(p.name, platform))
2919             {
2920                *projectPlatformOptions = p;
2921                break;
2922             }
2923          }
2924       }
2925       if(config && config.platforms)
2926       {
2927          for(p : config.platforms)
2928          {
2929             if(!strcmpi(p.name, platform))
2930             {
2931                *configPlatformOptions = p;
2932                break;
2933             }
2934          }
2935       }
2936    }
2937 }
2938
2939 Project LegacyBinaryLoadProject(File f, char * filePath)
2940 {
2941    Project project = null;
2942    char signature[sizeof(epjSignature)];
2943
2944    f.Read(signature, sizeof(signature), 1);
2945    if(!strncmp(signature, (char *)epjSignature, sizeof(epjSignature)))
2946    {
2947       char topNodePath[MAX_LOCATION];
2948       /*ProjectConfig newConfig
2949       {
2950          name = CopyString("Default");
2951          makingModified = true;
2952          compilingModified = true;
2953          linkingModified = true;
2954          options = { };
2955       };*/
2956
2957       project = Project { options = { } };
2958       LegacyBinaryLoadNode(project.topNode, f);
2959       delete project.topNode.path;
2960       GetWorkingDir(topNodePath, sizeof(topNodePath)-1);
2961       MakeSlashPath(topNodePath);
2962
2963       PathCatSlash(topNodePath, filePath);
2964       project.filePath = topNodePath;
2965       
2966       /* THIS IS ALREADY DONE BY filePath property
2967       StripLastDirectory(topNodePath, topNodePath);
2968       project.topNode.path = CopyString(topNodePath);
2969       */
2970       // Shouldn't this be done BEFORE the StripLastDirectory? project.filePath = topNodePath;
2971       
2972       // newConfig.options.defaultNameSpace = "";
2973       /*newConfig.objDir.dir = "obj";
2974       newConfig.targetDir.dir = "";*/
2975
2976       //project.configurations = { [ newConfig ] };
2977       //project.config = newConfig;
2978
2979       // Project Settings
2980       if(!f.Eof())
2981       {
2982          int temp;
2983          int len,c, count;
2984          String targetFileName, targetDirectory, objectsDirectory;
2985
2986          // { executable = 0, sharedLibrary = 1, staticLibrary = 2 };
2987          f.Read(&temp, sizeof(int),1);
2988          switch(temp)
2989          {
2990             case 0: project.options.targetType = executable; break;
2991             case 1: project.options.targetType = sharedLibrary; break;
2992             case 2: project.options.targetType = staticLibrary; break;
2993          }
2994
2995          f.Read(&len, sizeof(int),1);
2996          targetFileName = new char[len+1];
2997          f.Read(targetFileName, sizeof(char), len+1);
2998          project.options.targetFileName = targetFileName;
2999          delete targetFileName;
3000
3001          f.Read(&len, sizeof(int),1);
3002          targetDirectory = new char[len+1];
3003          f.Read(targetDirectory, sizeof(char), len+1);
3004          project.options.targetDirectory = targetDirectory;
3005          delete targetDirectory;
3006
3007          f.Read(&len, sizeof(int),1);
3008          objectsDirectory = new byte[len+1];
3009          f.Read(objectsDirectory, sizeof(char), len+1);
3010          project.options.objectsDirectory = objectsDirectory;
3011          delete objectsDirectory;
3012
3013          f.Read(&temp, sizeof(int),1);
3014          project./*config.*/options.debug = temp ? true : false;
3015          f.Read(&temp, sizeof(int),1);         
3016          project./*config.*/options.optimization = temp ? speed : none;
3017          f.Read(&temp, sizeof(int),1);
3018          project./*config.*/options.profile = temp ? true : false;
3019          f.Read(&temp, sizeof(int),1);
3020          project.options.warnings = temp ? all : unset;
3021
3022          f.Read(&count, sizeof(int),1);
3023          if(count)
3024          {
3025             project.options.includeDirs = { };
3026             for(c = 0; c < count; c++)
3027             {
3028                char * name;
3029                f.Read(&len, sizeof(int),1);
3030                name = new char[len+1];
3031                f.Read(name, sizeof(char), len+1);
3032                project.options.includeDirs.Add(name);
3033             }
3034          }
3035
3036          f.Read(&count, sizeof(int),1);
3037          if(count)
3038          {
3039             project.options.libraryDirs = { };
3040             for(c = 0; c < count; c++)
3041             {
3042                char * name;            
3043                f.Read(&len, sizeof(int),1);
3044                name = new char[len+1];
3045                f.Read(name, sizeof(char), len+1);
3046                project.options.libraryDirs.Add(name);
3047             }
3048          }
3049
3050          f.Read(&count, sizeof(int),1);
3051          if(count)
3052          {
3053             project.options.libraries = { };
3054             for(c = 0; c < count; c++)
3055             {
3056                char * name;
3057                f.Read(&len, sizeof(int),1);
3058                name = new char[len+1];
3059                f.Read(name, sizeof(char), len+1);
3060                project.options.libraries.Add(name);
3061             }
3062          }
3063
3064          f.Read(&count, sizeof(int),1);
3065          if(count)
3066          {
3067             project.options.preprocessorDefinitions = { };
3068             for(c = 0; c < count; c++)
3069             {
3070                char * name;
3071                f.Read(&len, sizeof(int),1);
3072                name = new char[len+1];
3073                f.Read(name, sizeof(char), len+1);
3074                project.options.preprocessorDefinitions.Add(name);
3075             }
3076          }
3077
3078          f.Read(&temp, sizeof(int),1);
3079          project.options.console = temp ? true : false;
3080       }
3081
3082       for(node : project.topNode.files)
3083       {
3084          if(node.type == resources)
3085          {
3086             project.resNode = node;
3087             break;
3088          }
3089       }
3090    }
3091    else
3092       f.Seek(0, start);
3093    return project;
3094 }
3095
3096 void ProjectConfig::LegacyProjectConfigLoad(File f)
3097 {  
3098    delete options;
3099    options = { };
3100    while(!f.Eof())
3101    {
3102       char buffer[65536];
3103       char section[128];
3104       char subSection[128];
3105       char * equal;
3106       int len;
3107       uint pos;
3108       
3109       pos = f.Tell();
3110       f.GetLine(buffer, 65536 - 1);
3111       TrimLSpaces(buffer, buffer);
3112       TrimRSpaces(buffer, buffer);
3113       if(strlen(buffer))
3114       {
3115          if(buffer[0] == '-')
3116          {
3117             equal = &buffer[0];
3118             equal[0] = ' ';
3119             TrimLSpaces(equal, equal);
3120             if(!strcmpi(subSection, "LibraryDirs"))
3121             {
3122                if(!options.libraryDirs)
3123                   options.libraryDirs = { [ CopyString(equal) ] };
3124                else
3125                   options.libraryDirs.Add(CopyString(equal));
3126             }
3127             else if(!strcmpi(subSection, "IncludeDirs"))
3128             {
3129                if(!options.includeDirs)
3130                   options.includeDirs = { [ CopyString(equal) ] };
3131                else
3132                   options.includeDirs.Add(CopyString(equal));
3133             }
3134          }
3135          else if(buffer[0] == '+')
3136          {
3137             if(name)
3138             {
3139                f.Seek(pos, start);
3140                break;
3141             }
3142             else
3143             {
3144                equal = &buffer[0];
3145                equal[0] = ' ';
3146                TrimLSpaces(equal, equal);
3147                delete name; name = CopyString(equal); // property::name = equal;
3148             }
3149          }
3150          else if(!strcmpi(buffer, "Compiler Options"))
3151             strcpy(section, buffer);
3152          else if(!strcmpi(buffer, "IncludeDirs"))
3153             strcpy(subSection, buffer);
3154          else if(!strcmpi(buffer, "Linker Options"))
3155             strcpy(section, buffer);
3156          else if(!strcmpi(buffer, "LibraryDirs"))
3157             strcpy(subSection, buffer);
3158          else if(!strcmpi(buffer, "Files") || !strcmpi(buffer, "Resources"))
3159          {
3160             f.Seek(pos, start);
3161             break;
3162          }
3163          else
3164          {
3165             equal = strstr(buffer, "=");
3166             if(equal)
3167             {
3168                equal[0] = '\0';
3169                TrimRSpaces(buffer, buffer);
3170                equal++;
3171                TrimLSpaces(equal, equal);
3172                if(!strcmpi(buffer, "Target Name"))
3173                   options.targetFileName = /*CopyString(*/equal/*)*/;
3174                else if(!strcmpi(buffer, "Target Type"))
3175                {
3176                   if(!strcmpi(equal, "Executable"))
3177                      options.targetType = executable;
3178                   else if(!strcmpi(equal, "Shared"))
3179                      options.targetType = sharedLibrary;
3180                   else if(!strcmpi(equal, "Static"))
3181                      options.targetType = staticLibrary;
3182                   else
3183                      options.targetType = executable;
3184                }
3185                else if(!strcmpi(buffer, "Target Directory"))
3186                   options.targetDirectory = /*CopyString(*/equal/*)*/;
3187                else if(!strcmpi(buffer, "Console"))
3188                   options.console = ParseTrueFalseValue(equal);
3189                else if(!strcmpi(buffer, "Libraries"))
3190                {
3191                   if(!options.libraries) options.libraries = { };
3192                   ParseArrayValue(options.libraries, equal);
3193                }
3194                else if(!strcmpi(buffer, "Intermediate Directory"))
3195                   options.objectsDirectory = /*CopyString(*/equal/*)*/; //objDir.expression = equal;
3196                else if(!strcmpi(buffer, "Debug"))
3197                   options.debug = ParseTrueFalseValue(equal);
3198                else if(!strcmpi(buffer, "Optimize"))
3199                {
3200                   if(!strcmpi(equal, "None"))
3201                      options.optimization = none;
3202                   else if(!strcmpi(equal, "Speed") || !strcmpi(equal, "True"))
3203                      options.optimization = speed;
3204                   else if(!strcmpi(equal, "Size"))
3205                      options.optimization = size;
3206                   else
3207                      options.optimization = none;
3208                }
3209                else if(!strcmpi(buffer, "Compress"))
3210                   options.compress = ParseTrueFalseValue(equal);
3211                else if(!strcmpi(buffer, "Profile"))
3212                   options.profile = ParseTrueFalseValue(equal);
3213                else if(!strcmpi(buffer, "AllWarnings"))
3214                   options.warnings = ParseTrueFalseValue(equal) ? all : unset;
3215                else if(!strcmpi(buffer, "MemoryGuard"))
3216                   options.memoryGuard = ParseTrueFalseValue(equal);
3217                else if(!strcmpi(buffer, "Default Name Space"))
3218                   options.defaultNameSpace = CopyString(equal);
3219                else if(!strcmpi(buffer, "Strict Name Spaces"))
3220                   options.strictNameSpaces = ParseTrueFalseValue(equal);
3221                else if(!strcmpi(buffer, "Preprocessor Definitions"))
3222                {
3223                   if(!options.preprocessorDefinitions) options.preprocessorDefinitions = { };
3224                   ParseArrayValue(options.preprocessorDefinitions, equal);
3225                }
3226             }
3227          }
3228       }
3229    }
3230    if(!options.targetDirectory && options.objectsDirectory)
3231       options.targetDirectory = /*CopyString(*/options.objectsDirectory/*)*/;
3232    //if(!objDir.dir) objDir.dir = "obj";
3233    //if(!targetDir.dir) targetDir.dir = "";
3234    // if(!targetName) property::targetName = "";   // How can a targetFileName be nothing???
3235    // if(!defaultNameSpace) property::defaultNameSpace = "";
3236    makingModified = true;
3237 }
3238
3239 Project LegacyAsciiLoadProject(File f, char * filePath)
3240 {
3241    Project project = null;
3242    ProjectNode node = null;
3243    int pos;
3244    char parentPath[MAX_LOCATION];
3245    char section[128] = "";
3246    char subSection[128] = "";
3247    ProjectNode parent;
3248    bool configurationsPresent = false;
3249
3250    f.Seek(0, start);
3251    while(!f.Eof())
3252    {
3253       char buffer[65536];
3254       //char version[16];
3255       char * equal;
3256       int len;
3257       pos = f.Tell();
3258       f.GetLine(buffer, 65536 - 1);
3259       TrimLSpaces(buffer, buffer);
3260       TrimRSpaces(buffer, buffer);
3261       if(strlen(buffer))
3262       {
3263          if(buffer[0] == '-' || buffer[0] == '=')
3264          {
3265             bool simple = buffer[0] == '-';
3266             equal = &buffer[0];
3267             equal[0] = ' ';
3268             TrimLSpaces(equal, equal);
3269             if(!strcmpi(section, "Target") && !strcmpi(subSection, "LibraryDirs"))
3270             {
3271                if(!project.config.options.libraryDirs)
3272                   project.config.options.libraryDirs = { [ CopyString(equal) ] };
3273                else
3274                   project.config.options.libraryDirs.Add(CopyString(equal));
3275             }
3276             else if(!strcmpi(section, "Target") && !strcmpi(subSection, "IncludeDirs"))
3277             {
3278                if(!project.config.options.includeDirs)
3279                   project.config.options.includeDirs = { [ CopyString(equal) ] };
3280                else
3281                   project.config.options.includeDirs.Add(CopyString(equal));
3282             }
3283             else if(!strcmpi(section, "Target") && (!strcmpi(subSection, "Files") || !strcmpi(subSection, "Resources")))
3284             {
3285                len = strlen(equal);
3286                if(len)
3287                {
3288                   char temp[MAX_LOCATION];
3289                   ProjectNode child { };
3290                   // We don't need to do this anymore, fileName is just a property that sets name & path
3291                   // child.fileName = CopyString(equal);
3292                   if(simple)
3293                   {
3294                      child.name = CopyString(equal);
3295                      child.path = CopyString(parentPath);
3296                   }
3297                   else
3298                   {
3299                      GetLastDirectory(equal, temp);
3300                      child.name = CopyString(temp);
3301                      StripLastDirectory(equal, temp);
3302                      child.path = CopyString(temp);
3303                   }
3304                   child.nodeType = file;
3305                   child.parent = parent;
3306                   child.indent = parent.indent + 1;
3307                   child.type = file;
3308                   child.icon = NodeIcons::SelectFileIcon(child.name);
3309                   parent.files.Add(child);
3310                   node = child;
3311                   //child = null;
3312                }
3313                else
3314                {
3315                   StripLastDirectory(parentPath, parentPath);
3316                   parent = parent.parent;
3317                }
3318             }
3319          }
3320          else if(buffer[0] == '+')
3321          {
3322             equal = &buffer[0];
3323             equal[0] = ' ';
3324             TrimLSpaces(equal, equal);
3325             if(!strcmpi(section, "Target") && (!strcmpi(subSection, "Files") || !strcmpi(subSection, "Resources")))
3326             {
3327                char temp[MAX_LOCATION];
3328                ProjectNode child { };
3329                // NEW: Folders now have a path set like files
3330                child.name = CopyString(equal);
3331                strcpy(temp, parentPath);
3332                PathCatSlash(temp, child.name);
3333                child.path = CopyString(temp);
3334
3335                child.parent = parent;
3336                child.indent = parent.indent + 1;
3337                child.type = folder;
3338                child.nodeType = folder;
3339                child.files = { };
3340                child.icon = folder;
3341                PathCatSlash(parentPath, child.name);
3342                parent.files.Add(child);
3343                parent = child;
3344                node = child;
3345                //child = null;
3346             }
3347             else if(!strcmpi(section, "Configurations"))
3348             {
3349                ProjectConfig newConfig
3350                {
3351                   makingModified = true;
3352                   options = { };
3353                };
3354                f.Seek(pos, start);
3355                LegacyProjectConfigLoad(newConfig, f);
3356                project.configurations.Add(newConfig);
3357             }
3358          }
3359          else if(!strcmpi(buffer, "ECERE Project File"));
3360          else if(!strcmpi(buffer, "Version 0a"))
3361             ; //strcpy(version, "0a");
3362          else if(!strcmpi(buffer, "Version 0.1a"))
3363             ; //strcpy(version, "0.1a");
3364          else if(!strcmpi(buffer, "Configurations"))
3365          {
3366             project.configurations.Free();
3367             project.config = null;
3368             strcpy(section, buffer);
3369             configurationsPresent = true;
3370          }
3371          else if(!strcmpi(buffer, "Target") || !strnicmp(buffer, "Target \"", strlen("Target \"")))
3372          {
3373             ProjectConfig newConfig { name = CopyString("Default"), options = { } };
3374             char topNodePath[MAX_LOCATION];
3375             // newConfig.defaultNameSpace = "";
3376             //newConfig.objDir.dir = "obj";
3377             //newConfig.targetDir.dir = "";
3378             project = Project { /*options = { }*/ };
3379             project.configurations = { [ newConfig ] };
3380             project.config = newConfig;
3381             // if(project.topNode.path) delete project.topNode.path;
3382             GetWorkingDir(topNodePath, sizeof(topNodePath)-1);
3383             MakeSlashPath(topNodePath);
3384             PathCatSlash(topNodePath, filePath);
3385             project.filePath = topNodePath;
3386             parentPath[0] = '\0';
3387             parent = project.topNode;
3388             node = parent;
3389             strcpy(section, "Target");
3390             equal = &buffer[6];
3391             if(equal[0] == ' ')
3392             {
3393                equal++;
3394                if(equal[0] == '\"')
3395                {
3396                   StripQuotes(equal, equal);
3397                   delete project.moduleName; project.moduleName = CopyString(equal);
3398                }
3399             }
3400          }
3401          else if(!strcmpi(buffer, "Compiler Options"));
3402          else if(!strcmpi(buffer, "IncludeDirs"))
3403             strcpy(subSection, buffer);
3404          else if(!strcmpi(buffer, "Linker Options"));
3405          else if(!strcmpi(buffer, "LibraryDirs"))
3406             strcpy(subSection, buffer);
3407          else if(!strcmpi(buffer, "Files"))
3408          {
3409             strcpy(section, "Target");
3410             strcpy(subSection, buffer);
3411          }
3412          else if(!strcmpi(buffer, "Resources"))
3413          {
3414             ProjectNode child { };
3415             parent.files.Add(child);
3416             child.parent = parent;
3417             child.indent = parent.indent + 1;
3418             child.name = CopyString(buffer);
3419             child.path = CopyString("");
3420             child.type = resources;
3421             child.files = { };
3422             child.icon = archiveFile;
3423             project.resNode = child;
3424             parent = child;
3425             node = child;
3426             strcpy(subSection, buffer);
3427          }
3428          else
3429          {
3430             equal = strstr(buffer, "=");
3431             if(equal)
3432             {
3433                equal[0] = '\0';
3434                TrimRSpaces(buffer, buffer);
3435                equal++;
3436                TrimLSpaces(equal, equal);
3437
3438                if(!strcmpi(section, "Target"))
3439                {
3440                   if(!strcmpi(buffer, "Build Exclusions"))
3441                   {
3442                      if(!strcmpi(section, "Target") && !strcmpi(subSection, "Files"))
3443                      {
3444                         /*if(node && node.type != NodeTypes::project)
3445                            ParseListValue(node.buildExclusions, equal);*/
3446                      }
3447                   }
3448                   else if(!strcmpi(buffer, "Path") && !strcmpi(subSection, "Resources"))
3449                   {
3450                      delete project.resNode.path;
3451                      project.resNode.path = CopyString(equal);
3452                      PathCatSlash(parentPath, equal);
3453                   }
3454
3455                   // Config Settings
3456                   else if(!strcmpi(buffer, "Intermediate Directory"))
3457                      project.config.options.objectsDirectory = /*CopyString(*/equal/*)*/; //objDir.expression = equal;
3458                   else if(!strcmpi(buffer, "Debug"))
3459                      project.config.options.debug = ParseTrueFalseValue(equal);
3460                   else if(!strcmpi(buffer, "Optimize"))
3461                   {
3462                      if(!strcmpi(equal, "None"))
3463                         project.config.options.optimization = none;
3464                      else if(!strcmpi(equal, "Speed") || !strcmpi(equal, "True"))
3465                         project.config.options.optimization = speed;
3466                      else if(!strcmpi(equal, "Size"))
3467                         project.config.options.optimization = size;
3468                      else
3469                         project.config.options.optimization = none;
3470                   }
3471                   else if(!strcmpi(buffer, "Profile"))
3472                      project.config.options.profile = ParseTrueFalseValue(equal);
3473                   else if(!strcmpi(buffer, "MemoryGuard"))
3474                      project.config.options.memoryGuard = ParseTrueFalseValue(equal);
3475                   else
3476                   {
3477                      if(!project.options) project.options = { };
3478
3479                      // Project Wide Settings (All configs)
3480                      if(!strcmpi(buffer, "Target Name"))
3481                         project.options.targetFileName = /*CopyString(*/equal/*)*/;
3482                      else if(!strcmpi(buffer, "Target Type"))
3483                      {
3484                         if(!strcmpi(equal, "Executable"))
3485                            project.options.targetType = executable;
3486                         else if(!strcmpi(equal, "Shared"))
3487                            project.options.targetType = sharedLibrary;
3488                         else if(!strcmpi(equal, "Static"))
3489                            project.options.targetType = staticLibrary;
3490                         else
3491                            project.options.targetType = executable;
3492                      }
3493                      else if(!strcmpi(buffer, "Target Directory"))
3494                         project.options.targetDirectory = /*CopyString(*/equal/*)*/;
3495                      else if(!strcmpi(buffer, "Console"))
3496                         project.options.console = ParseTrueFalseValue(equal);
3497                      else if(!strcmpi(buffer, "Libraries"))
3498                      {
3499                         if(!project.options.libraries) project.options.libraries = { };
3500                         ParseArrayValue(project.options.libraries, equal);
3501                      }
3502                      else if(!strcmpi(buffer, "AllWarnings"))
3503                         project.options.warnings = ParseTrueFalseValue(equal) ? all : unset;
3504                      else if(!strcmpi(buffer, "Preprocessor Definitions"))
3505                      {
3506                         if(!strcmpi(section, "Target") && !strcmpi(subSection, "Files"))
3507                         {
3508                            /*if(node && (node.type == NodeTypes::project || (node.type == file && !node.isInResources) || node.type == folder))
3509                               ParseListValue(node.preprocessorDefs, equal);*/
3510                         }
3511                         else
3512                         {
3513                            if(!project.options.preprocessorDefinitions) project.options.preprocessorDefinitions = { };
3514                            ParseArrayValue(project.options.preprocessorDefinitions, equal);
3515                         }
3516                      }
3517                   }
3518                }
3519             }
3520          }
3521       }
3522    }
3523    parent = null;
3524
3525    SplitPlatformLibraries(project);
3526
3527    if(configurationsPresent)
3528       CombineIdenticalConfigOptions(project);
3529    return project;
3530 }
3531
3532 void SplitPlatformLibraries(Project project)
3533 {
3534    if(project && project.configurations)
3535    {
3536       for(cfg : project.configurations)
3537       {
3538          if(cfg.options.libraries && cfg.options.libraries.count)
3539          {
3540             Iterator<String> it { cfg.options.libraries };
3541             while(it.Next())
3542             {
3543                String l = it.data;
3544                char * platformName = strstr(l, ":");
3545                if(platformName)
3546                {
3547                   PlatformOptions platform = null;
3548                   platformName++;
3549                   if(!cfg.platforms) cfg.platforms = { };
3550                   for(p : cfg.platforms)
3551                   {
3552                      if(!strcmpi(platformName, p.name))
3553                      {
3554                         platform = p;
3555                         break;
3556                      }
3557                   }
3558                   if(!platform)
3559                   {
3560                      platform = { name = CopyString(platformName), options = { libraries = { } } };
3561                      cfg.platforms.Add(platform);
3562                   }
3563                   *(platformName-1) = 0;
3564                   platform.options.libraries.Add(CopyString(l));
3565
3566                   cfg.options.libraries.Delete(it.pointer);
3567                   it.pointer = null;
3568                }
3569             }
3570          }
3571       }      
3572    }
3573 }
3574
3575 void CombineIdenticalConfigOptions(Project project)
3576 {
3577    if(project && project.configurations && project.configurations.count)
3578    {
3579       DataMember member;
3580       ProjectOptions nullOptions { };
3581       ProjectConfig firstConfig = null;
3582       for(cfg : project.configurations)
3583       {
3584          if(cfg.options.targetType != staticLibrary)
3585          {
3586             firstConfig = cfg;
3587             break;
3588          }
3589       }
3590       if(!firstConfig)
3591          firstConfig = project.configurations.firstIterator.data;
3592
3593       for(member = class(ProjectOptions).membersAndProperties.first; member; member = member.next)
3594       {
3595          if(!member.isProperty)
3596          {
3597             Class type = eSystem_FindClass(__thisModule, member.dataTypeString);
3598             if(type)
3599             {
3600                bool same = true;
3601
3602                for(cfg : project.configurations)
3603                {
3604                   if(cfg != firstConfig)
3605                   {
3606                      if(cfg.options.targetType != staticLibrary)
3607                      {
3608                         int result;
3609                         
3610                         if(type.type == noHeadClass || type.type == normalClass)
3611                         {
3612                            result = type._vTbl[__ecereVMethodID_class_OnCompare](type, 
3613                               *(void **)((byte *)firstConfig.options + member.offset + member._class.offset),
3614                               *(void **)((byte *)cfg.options         + member.offset + member._class.offset));
3615                         }
3616                         else
3617                         {
3618                            result = type._vTbl[__ecereVMethodID_class_OnCompare](type, 
3619                               (byte *)firstConfig.options + member.offset + member._class.offset,
3620                               (byte *)cfg.options         + member.offset + member._class.offset);
3621                         }
3622                         if(result)
3623                         {
3624                            same = false;
3625                            break;
3626                         }
3627                      }
3628                   }                  
3629                }
3630                if(same)
3631                {
3632                   if(type.type == noHeadClass || type.type == normalClass)
3633                   {
3634                      if(!type._vTbl[__ecereVMethodID_class_OnCompare](type, 
3635                         *(void **)((byte *)firstConfig.options + member.offset + member._class.offset),
3636                         *(void **)((byte *)nullOptions         + member.offset + member._class.offset)))
3637                         continue;
3638                   }
3639                   else
3640                   {
3641                      if(!type._vTbl[__ecereVMethodID_class_OnCompare](type, 
3642                         (byte *)firstConfig.options + member.offset + member._class.offset,
3643                         (byte *)nullOptions         + member.offset + member._class.offset))
3644                         continue;
3645                   }
3646
3647                   if(!project.options) project.options = { };
3648                   
3649                   /*if(type.type == noHeadClass || type.type == normalClass)
3650                   {
3651                      type._vTbl[__ecereVMethodID_class_OnCopy](type, 
3652                         (byte *)project.options + member.offset + member._class.offset,
3653                         *(void **)((byte *)firstConfig.options + member.offset + member._class.offset));
3654                   }
3655                   else
3656                   {
3657                      void * address = (byte *)firstConfig.options + member.offset + member._class.offset;
3658                      // TOFIX: ListBox::SetData / OnCopy mess
3659                      type._vTbl[__ecereVMethodID_class_OnCopy](type, 
3660                         (byte *)project.options + member.offset + member._class.offset,
3661                         (type.typeSize > 4) ? address : 
3662                            ((type.typeSize == 4) ? (void *)*(uint32 *)address : 
3663                               ((type.typeSize == 2) ? (void *)*(uint16*)address : 
3664                                  (void *)*(byte *)address )));                              
3665                   }*/
3666                   memcpy(
3667                      (byte *)project.options + member.offset + member._class.offset,
3668                      (byte *)firstConfig.options + member.offset + member._class.offset, type.typeSize);
3669
3670                   for(cfg : project.configurations)
3671                   {
3672                      if(cfg.options.targetType == staticLibrary)
3673                      {
3674                         int result;
3675                         
3676                         if(type.type == noHeadClass || type.type == normalClass)
3677                         {
3678                            result = type._vTbl[__ecereVMethodID_class_OnCompare](type, 
3679                               *(void **)((byte *)firstConfig.options + member.offset + member._class.offset),
3680                               *(void **)((byte *)cfg.options         + member.offset + member._class.offset));
3681                         }
3682                         else
3683                         {
3684                            result = type._vTbl[__ecereVMethodID_class_OnCompare](type, 
3685                               (byte *)firstConfig.options + member.offset + member._class.offset,
3686                               (byte *)cfg.options         + member.offset + member._class.offset);
3687                         }
3688                         if(result)
3689                            continue;
3690                      }
3691                      if(cfg != firstConfig)
3692                      {
3693                         if(type.type == noHeadClass || type.type == normalClass)
3694                         {
3695                            type._vTbl[__ecereVMethodID_class_OnFree](type, 
3696                               *(void **)((byte *)cfg.options + member.offset + member._class.offset));
3697                         }
3698                         else
3699                         {
3700                            type._vTbl[__ecereVMethodID_class_OnFree](type, 
3701                               (byte *)cfg.options + member.offset + member._class.offset);
3702                         }
3703                         memset((byte *)cfg.options + member.offset + member._class.offset, 0, type.typeSize);
3704                      }                     
3705                   }
3706                   memset((byte *)firstConfig.options + member.offset + member._class.offset, 0, type.typeSize);
3707                }
3708             }
3709          }
3710       }
3711       delete nullOptions;
3712
3713       // Compare Platform Specific Settings
3714       {
3715          bool same = true;
3716          for(cfg : project.configurations)
3717          {
3718             if(cfg != firstConfig && cfg.options.targetType != staticLibrary && (firstConfig.platforms || cfg.platforms) &&
3719                ((!firstConfig.platforms && cfg.platforms) || firstConfig.platforms.OnCompare(cfg.platforms)))
3720             {
3721                same = false;
3722                break;
3723             }
3724          }
3725          if(same && firstConfig.platforms)
3726          {
3727             for(cfg : project.configurations)
3728             {
3729                if(cfg.options.targetType == staticLibrary && firstConfig.platforms.OnCompare(cfg.platforms))
3730                   continue;
3731                if(cfg != firstConfig)
3732                {
3733                   cfg.platforms.Free();
3734                   delete cfg.platforms;
3735                }
3736             }
3737             project.platforms = firstConfig.platforms;
3738             firstConfig.platforms = null;
3739          }
3740       }
3741
3742       // Static libraries can't contain libraries
3743       for(cfg : project.configurations)
3744       {
3745          if(cfg.options.targetType == staticLibrary)
3746          {
3747             if(!cfg.options.libraries) cfg.options.libraries = { };
3748             cfg.options.libraries.Free();
3749          }
3750       }
3751    }
3752 }
3753
3754 Project LoadProject(char * filePath, char * activeConfigName)
3755 {
3756    Project project = null;
3757    File f = FileOpen(filePath, read);
3758    if(f)
3759    {
3760       project = LegacyBinaryLoadProject(f, filePath);
3761       if(!project)
3762       {
3763          JSONParser parser { f = f };
3764          JSONResult result = parser.GetObject(class(Project), &project);
3765          if(project)
3766          {
3767             char insidePath[MAX_LOCATION];
3768
3769             delete project.topNode.files;
3770             if(!project.files) project.files = { };
3771             project.topNode.files = project.files;
3772             project.resNode = project.topNode.Add(project, "Resources", project.topNode.files.last, resources, archiveFile, false);
3773             delete project.resNode.path;
3774             project.resNode.path = project.resourcesPath;
3775             project.resourcesPath = null;
3776             project.resNode.nodeType = (ProjectNodeType)-1;
3777             delete project.resNode.files;
3778             project.resNode.files = project.resources;
3779             project.files = null;
3780             project.resources = null;
3781             if(!project.configurations) project.configurations = { };
3782
3783             {
3784                char topNodePath[MAX_LOCATION];
3785                GetWorkingDir(topNodePath, sizeof(topNodePath)-1);
3786                MakeSlashPath(topNodePath);
3787                PathCatSlash(topNodePath, filePath);
3788                project.filePath = topNodePath;//filePath;
3789             }
3790
3791             project.topNode.FixupNode(insidePath);
3792          }
3793          delete parser;
3794       }
3795       if(!project)
3796          project = LegacyAsciiLoadProject(f, filePath);
3797
3798       delete f;
3799
3800       if(project)
3801       {
3802          if(!project.options) project.options = { };
3803          if(activeConfigName && activeConfigName[0] && project.configurations)
3804          {
3805             for(cfg : project.configurations)
3806             {
3807                if(!strcmpi(cfg.name, activeConfigName))
3808                {
3809                   project.config = cfg;
3810                   break;
3811                }
3812             }
3813          }
3814          if(!project.config && project.configurations)
3815             project.config = project.configurations.firstIterator.data;
3816
3817          if(!project.resNode)
3818          {
3819             project.resNode = project.topNode.Add(project, "Resources", project.topNode.files.last, resources, archiveFile, false);
3820          }
3821          
3822          if(!project.moduleName)
3823             project.moduleName = CopyString(project.name);
3824          if(project.config && 
3825             (!project.options || !project.options.targetFileName || !project.options.targetFileName[0]) &&
3826             (!project.config.options.targetFileName || !project.config.options.targetFileName[0]))
3827          {
3828             //delete project.config.options.targetFileName;
3829             
3830             project.options.targetFileName = /*CopyString(*/project.moduleName/*)*/;
3831             project.config.options.optimization = none;
3832             project.config.options.debug = true;
3833             //project.config.options.warnings = unset;
3834             project.config.options.memoryGuard = false;
3835             project.config.compilingModified = true;
3836             project.config.linkingModified = true;
3837          }
3838          else if(!project.topNode.name && project.config)
3839          {
3840             project.topNode.name = CopyString(project.config.options.targetFileName);
3841          }
3842
3843          /* // THIS IS NOW AUTOMATED WITH A project CHECK IN ProjectNode
3844          project.topNode.configurations = project.configurations;
3845          project.topNode.platforms = project.platforms;
3846          project.topNode.options = project.options;*/
3847       }
3848    }
3849    return project;
3850 }