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