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