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