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