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