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