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