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