ide/Project: Fixed crashes on replacing spaces (#156)
[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 import "DynamicString"
8
9 #ifndef MAKEFILE_GENERATOR
10 import "ide"
11 // We should have the .sln/.vcproj generation even on other platforms
12 // e.g. detect from an environment variable pointing to a Windows drive
13 #ifdef __WIN32__
14 import "vsSupport"
15 #endif
16 #endif
17
18 import "ProjectConfig"
19 import "ProjectNode"
20 import "IDESettings"
21
22 default:
23
24 static void DummyFunction()
25 {
26 int a;
27 a.OnFree();
28 }
29
30 private:
31
32 extern int __ecereVMethodID_class_OnCompare;
33 extern int __ecereVMethodID_class_OnFree;
34
35 IDESettings ideSettings;
36
37 IDESettingsContainer settingsContainer
38 {
39    driver = "JSON";
40    dataOwner = &ideSettings;
41    dataClass = class(IDESettings);
42
43    void OnLoad(GlobalSettingsData data)
44    {
45       IDESettings settings = (IDESettings)data;
46 #ifndef MAKEFILE_GENERATOR
47       globalSettingsDialog.ideSettings = settings;
48       ide.UpdateRecentMenus();
49       ide.UpdateCompilerConfigs(true);
50 #endif
51    }
52 };
53
54 #ifdef MAKEFILE_GENERATOR
55 CompilerConfig defaultCompiler;
56 #endif
57
58 // LEGACY BINARY EPJ LOADING
59
60 SetBool ParseTrueFalseValue(char * string)
61 {
62    if(!strcmpi(string, "True")) return true;
63    return false;
64 }
65
66 void ParseArrayValue(Array<String> array, char * equal)
67 {
68    char * start, * comma;
69    char * string;
70    string = CopyString(equal);
71    start = string;
72    while(start)
73    {
74       comma = strstr(start, ",");
75       if(comma)
76          comma[0] = '\0';
77       array.Add(CopyString(start));
78       if(comma)
79          comma++;
80       if(comma)
81          comma++;
82       start = comma;
83    }
84    delete string;
85 }
86
87 void ProjectNode::LegacyBinaryLoadNode(File f)
88 {
89    int len, count, c;
90    int fileNameLen;
91
92    f.Read(&len, sizeof(len), 1);
93    name = new char[len+1];
94    fileNameLen = len;
95    f.Read(name, sizeof(char), len+1);
96    f.Read(&len, sizeof(len), 1);
97    fileNameLen += len;
98    path = new char[len+1];
99    f.Read(path, sizeof(char), len+1);
100    
101    /*
102    fileName = new char[fileNameLen+2];
103    strcpy(fileName, path);
104    if(fileName[0]) strcat(fileName, "/");
105    strcat(fileName, name);
106    */
107
108    f.Read(&type, sizeof(type), 1);
109    f.Read(&count, sizeof(count), 1);
110    
111    if(type == file)
112    {
113       nodeType = file;
114       icon = NodeIcons::SelectFileIcon(name);
115    }
116    else
117    {
118       nodeType = folder;
119       icon = NodeIcons::SelectNodeIcon(type);
120    }
121
122    if(count && !files) files = { };
123    for(c = 0; c < count; c++)
124    {
125       ProjectNode child { };
126       files.Add(child);
127       child.parent = this;
128       child.indent = indent + 1;
129       LegacyBinaryLoadNode(child, f);
130    }
131 }
132
133 /*void LegacyBinarySaveNode(File f)
134 {
135    int len;
136    ProjectNode child;
137    len = strlen(name);
138    f.Write(&len, sizeof(len), 1);
139    f.Write(name, sizeof(char), len+1);
140
141    if(type == project)
142    {
143       // Projects Absolute Path Are Not Saved
144       len = 0;
145       f.Write(&len, sizeof(len), 1);
146       f.Write(&len, sizeof(char), 1);
147    }
148    else
149    {
150       len = strlen(path);
151       f.Write(&len, sizeof(len), 1);
152       f.Write(path, sizeof(char), len+1);
153    }
154    f.Write(&type, sizeof(type), 1);
155    f.Write(&children.count, sizeof(children.count), 1);
156    for(child = children.first; child; child.next)
157       child.SaveNode(f);
158 }*/
159
160 void ProjectNode::LegacyAsciiSaveNode(File f, char * indentation, char * insidePath)
161 {
162    int len;
163    char printPath[MAX_LOCATION];
164
165    if(type == project && (files.count /*|| preprocessorDefs.first*/))
166    {
167       f.Printf("\n   Files\n");
168    }
169    else if(type == file)
170    {
171       if(!strcmp(path, insidePath))
172          f.Printf("%s - %s\n", indentation, name);
173       else
174       {
175          strcpy(printPath, path);
176          len = strlen(printPath);
177          if(len)
178             if(printPath[len-1] != '/')
179                strcat(printPath, "/");
180          strcat(printPath, name);
181          f.Printf("%s = %s\n", indentation, printPath);
182       }
183       if(files.count)
184          f.Printf("\nError\n\n");
185    }
186    else if(type == folder)
187    {
188       f.Printf("%s + %s\n", indentation, name);
189    }
190    else if(type == resources && files.count)
191    {
192       PathCatSlash(insidePath, path);
193       f.Printf("\n%sResources\n", indentation);
194       if(path && path[0])
195          f.Printf("%s   Path = %s\n", indentation, path);
196    }
197    
198    /*if(buildExclusions.first && type != project)
199    {
200       for(item = buildExclusions.first; item; item = item.next)
201       {
202          if(item == buildExclusions.first)
203             f.Printf("%s      Build Exclusions = %s", indentation, item.name);
204          else
205             f.Printf(", %s", item.name);
206       }
207       f.Printf("\n");
208    }
209
210    if(preprocessorDefs.first && (type == project || ((type == file || type == folder) && !isInResources)))
211    {
212       for(item = preprocessorDefs.first; item; item = item.next)
213       {
214          if(item == preprocessorDefs.first)
215             f.Printf("%s%s   Preprocessor Definitions = %s", indentation, type == project ? "" : "   ", item.name);
216          else
217             f.Printf(", %s", item.name);
218       }
219       f.Printf("\n");
220    }
221    */
222    
223    if(type == project && (files.count /*|| preprocessorDefs.first*/))
224    {
225       f.Printf("\n");
226       for(child : files)
227          LegacyAsciiSaveNode(child, f, indentation, insidePath);
228    }
229    else if(type == folder)
230    {
231       strcat(indentation, "   ");
232       // WHAT WAS THIS: strcpy(printPath, path);
233       // TOCHECK: why is Unix/PathCat not used here
234       len = strlen(insidePath);
235       if(len)
236          if(insidePath[len-1] != '/')
237             strcat(insidePath, "/");
238       strcat(insidePath, name);
239
240       for(child : files)
241          LegacyAsciiSaveNode(child, f, indentation, insidePath);
242       f.Printf("%s -\n", indentation);
243       indentation[strlen(indentation) - 3] = '\0';
244       StripLastDirectory(insidePath, insidePath);
245    }
246    else if(type == resources && files.count)
247    {
248       f.Printf("\n");
249       for(child : files)
250          LegacyAsciiSaveNode(child, f, indentation, insidePath);
251       StripLastDirectory(insidePath, insidePath);
252    }
253 }
254
255 /*
256 void ProjectConfig::LegacyProjectConfigSave(File f)
257 {
258    char * indentation = "      ";
259    //if(isCommonConfig)
260       //f.Printf("\n * Common\n");
261    //else
262       f.Printf("\n + %s\n", name);
263    f.Printf("\n   Compiler\n\n");
264    if(objDir.expression[0])
265       f.Printf("%sIntermediate Directory = %s\n", indentation, objDir.expression);
266    f.Printf("%sDebug = %s\n", indentation, (options.debug == true) ? "True" : "False");
267    switch(options.optimization)
268    {
269       // case none:   f.Printf("%sOptimize = %s\n", indentation, "None"); break;
270       case speed: f.Printf("%sOptimize = %s\n", indentation, "Speed"); break;
271       case size:  f.Printf("%sOptimize = %s\n", indentation, "Size");  break;
272    }
273    f.Printf("%sAllWarnings = %s\n", indentation, (options.warnings == all) ? "True" : "False");
274    if(options.profile)
275       f.Printf("%sProfile = %s\n", indentation, (options.profile == true) ? "True" : "False");
276    if(options.memoryGuard == true)
277       f.Printf("%sMemoryGuard = %s\n", indentation, (options.memoryGuard == true) ? "True" : "False");
278    if(options.strictNameSpaces == true)
279       f.Printf("%sStrict Name Spaces = %s\n", indentation, (options.strictNameSpaces == true) ? "True" : "False");
280    if(options.defaultNameSpace && strlen(options.defaultNameSpace))
281       f.Printf("%sDefault Name Space = %s\n", indentation, options.defaultNameSpace);
282     TOFIX: Compiler Bug {
283       if(options.preprocessorDefinitions.count)
284       {
285          bool isFirst = true;
286          for(item : options.preprocessorDefinitions)
287          {
288             if(isFirst)
289             {
290                f.Printf("\n%sPreprocessor Definitions = %s", indentation, item);
291                isFirst = false;
292             }
293             else
294                f.Printf(", %s", item);
295          }
296          f.Printf("\n");
297       }
298    }
299    if(options.includeDirs.count)
300    {
301       f.Printf("\n%sInclude Directories\n", indentation);
302       for(item : options.includeDirs)
303          f.Printf("%s - %s\n", indentation, name);
304       f.Printf("\n");
305    }
306
307    f.Printf("\n%sLinker\n\n", indentation);
308    f.Printf("%sTarget Name = %s\n", indentation, options.targetFileName);
309    switch(options.targetType)
310    {
311       case executable:     f.Printf("%sTarget Type = %s\n", indentation, "Executable"); break;
312       case sharedLibrary:  f.Printf("%sTarget Type = %s\n", indentation, "Shared");     break;
313       case staticLibrary:  f.Printf("%sTarget Type = %s\n", indentation, "Static");     break;
314    }
315    if(targetDir.expression[0])
316       f.Printf("%sTarget Directory = %s\n", indentation, targetDir.expression);
317    if(options.console)
318       f.Printf("%sConsole = %s\n", indentation, options.console ? "True" : "False");
319    if(options.compress)
320       f.Printf("%sCompress = %s\n", indentation, options.compress ? "True" : "False");
321    if(options.libraries.count)
322    {
323       bool isFirst = true;
324       for(item : options.libraries)
325       {
326          if(isFirst)
327          {
328             f.Printf("\n%sLibraries = %s", indentation, name);
329             isFirst = false;
330          }
331          else
332             f.Printf(", %s", item);
333       }
334       f.Printf("\n");
335    }
336    if(options.libraryDirs.count)
337    {
338       f.Printf("\n%sLibrary Directories\n\n", indentation);
339       for(item : options.libraryDirs)
340          f.Printf("       - %s\n", indentation, item);
341    }
342 }
343
344 void LegacyAsciiSaveProject(File f, Project project)
345 {
346    char indentation[128*3];
347    char path[MAX_LOCATION];
348
349    f.Printf("\nECERE Project File : Format Version 0.1b\n");
350    f.Printf("\nDescription\n%s\n.\n", project.description);
351    f.Printf("\nLicense\n%s\n.\n", project.license);
352    f.Printf("\nModule Name = %s\n", project.moduleName);
353    f.Printf("\n   Configurations\n");
354    //////////////////////////////////////commonConfig.Save(f, true);
355    for(cfg : project.configurations)
356       LegacyProjectConfigSave(cfg, f);
357
358    strcpy(indentation, "   ");
359    path[0] = '\0';
360    LegacyAsciiSaveNode(project.topNode, f, indentation, path);
361    // f.Printf("\n");
362    delete f;
363 }
364 */
365
366 // *** NEW JSON PROJECT FORMAT ***
367 public enum ProjectNodeType { file, folder };
368
369 // *******************************
370
371 define PEEK_RESOLUTION = (18.2 * 10);
372
373 // On Windows & UNIX
374 #define SEPS    "/"
375 #define SEP     '/'
376
377 static Array<String> notLinkerOptions
378 { [
379    "-static-libgcc",
380    "-shared",
381    "-static",
382    "-s",
383    "-shared-libgcc",
384    "-nostartfiles",
385    "-nodefaultlibs",
386    "-nostdlib",
387    "-pie",
388    "-rdynamic",
389    "-static-libasan",
390    "-static-libtsan",
391    "-static libstdc++",
392    "-symbolic",
393    "-Wl,"
394    //"-T ",
395    //"-Xlinker ",
396    //"-u "
397 ] };
398
399 static bool IsLinkerOption(String s)
400 {
401    for(i : notLinkerOptions)
402       if(strstr(s, "-Wl,") || !strcmp(s, i))
403          return false;
404    return true;
405 }
406
407 static byte epjSignature[] = { 'E', 'P', 'J', 0x04, 0x01, 0x12, 0x03, 0x12 };
408
409 enum GenMakefilePrintTypes { objects, cObjects, symbols, imports, sources, resources, eCsources };
410
411 define WorkspaceExtension = "ews";
412 define ProjectExtension = "epj";
413
414 define stringInFileIncludedFrom = "In file included from ";
415 define stringFrom =               "                 from ";
416
417 // This function cannot accept same pointer for source and output
418 void ReplaceSpaces(char * output, char * source)
419 {
420    int c, dc;
421    char ch, pch = 0;
422
423    for(c = 0, dc = 0; (ch = source[c]); c++, dc++)
424    {
425       if(ch == ' ') output[dc++] = '\\';
426       if(pch != '$')
427       {
428          if(ch == '(' || ch == ')') output[dc++] = '\\';
429          pch = ch;
430       }
431       else if(ch == ')')
432          pch = 0;
433       output[dc] = ch;
434    }
435    output[dc] = '\0';
436 }
437
438 // This function cannot accept same pointer for source and output
439 void ReplaceUnwantedMakeChars(char * output, char * source)
440 {
441    int c, dc;
442    char ch, pch = 0;
443
444    for(c = 0, dc = 0; (ch = source[c]); c++, dc++)
445    {
446       if(pch != '$')
447       {
448          if(ch == '(' || ch == ')') output[dc++] = '\\';
449          pch = ch;
450       }
451       else if(ch == ')')
452          pch = 0;
453       if(ch == ' ')
454          output[dc] = 127;
455       else
456          output[dc] = ch;
457    }
458    output[dc] = '\0';
459 }
460
461 static void OutputNoSpace(File f, char * source)
462 {
463    char * output = new char[strlen(source)+1024];
464    ReplaceSpaces(output, source);
465    f.Puts(output);
466    delete output;
467 }
468
469 enum ListOutputMethod { inPlace, newLine, lineEach };
470
471 int OutputFileList(File f, char * name, Array<String> list, Map<String, int> varStringLenDiffs, char * prefix)
472 {
473    int numOfBreaks = 0;
474    const int breakListLength = 1536;
475    const int breakLineLength = 78; // TODO: turn this into an option.
476
477    int c, len, itemCount = 0;
478    Array<int> breaks { };
479    if(list.count)
480    {
481       int charCount = 0;
482       MapNode<String, int> mn;
483       for(c=0; c<list.count; c++)
484       {
485          len = strlen(list[c]) + 3;
486          if(strstr(list[c], "$(") && varStringLenDiffs && varStringLenDiffs.count)
487          {
488             for(mn = varStringLenDiffs.root.minimum; mn; mn = mn.next)
489             {
490                if(strstr(list[c], mn.key))
491                   len += mn.value;
492             }
493          }
494          if(charCount + len > breakListLength)
495          {
496             breaks.Add(itemCount);
497             itemCount = 0;
498             charCount = len;
499          }
500          itemCount++;
501          charCount += len;
502       }
503       if(itemCount)
504          breaks.Add(itemCount);
505       numOfBreaks = breaks.count;
506    }
507
508    if(numOfBreaks > 1)
509    {
510       f.Printf("%s =%s%s", name, prefix ? " " : "", prefix ? prefix : "");
511       for(c=0; c<numOfBreaks; c++)
512          f.Printf(" $(%s%d)", name, c+1);
513       f.Puts("\n");
514    }
515    else
516       f.Printf("%s =%s%s", name, prefix ? " " : "", prefix ? prefix : "");
517
518    if(numOfBreaks)
519    {
520       int n, offset = 0;
521
522       for(c=0; c<numOfBreaks; c++)
523       {
524          if(numOfBreaks > 1)
525             f.Printf("%s%d =", name, c+1);
526          
527          len = 3;
528          itemCount = breaks[c];
529          for(n=offset; n<offset+itemCount; n++)
530          {
531             if(false) // TODO: turn this into an option.
532             {
533                int itemLen = strlen(list[n]);
534                if(len > 3 && len + itemLen > breakLineLength)
535                {
536                   f.Printf(" \\\n\t%s", list[n]);
537                   len = 3;
538                }
539                else
540                {
541                   len += itemLen;
542                   f.Printf(" %s", list[n]);
543                }
544             }
545             else
546                f.Printf(" \\\n\t%s", list[n]);
547          }
548          offset += itemCount;
549          f.Puts("\n");
550       }
551       list.Free();
552       list.count = 0;
553    }
554    else
555       f.Puts("\n");
556    f.Puts("\n");
557    delete breaks;
558    return numOfBreaks;
559 }
560
561 void OutputLinkObjectActions(File f, char * name, int parts)
562 {
563    if(parts > 1)
564    {
565       int c;
566       for(c=0; c<parts; c++)
567          f.Printf("\t@$(call echo,$(%s%d)) >> $(OBJ)linkobjects.lst\n", name, c+1);
568    } else if(parts) {
569       f.Printf("\t@$(call echo,$(%s)) >> $(OBJ)linkobjects.lst\n", name);
570    }
571 }
572
573 void OutputCleanActions(File f, char * name, int parts)
574 {
575    if(parts > 1)
576    {
577       int c;
578       for(c=0; c<parts; c++)
579          f.Printf("\t$(call rmq,$(%s%d))\n", name, c+1);
580    }
581    else
582       f.Printf("\t$(call rmq,$(%s))\n", name);
583 }
584
585 void OutputListOption(File f, char * option, Array<String> list, ListOutputMethod method, bool noSpace)
586 {
587    if(list.count)
588    {
589       if(method == newLine)
590          f.Puts(" \\\n\t");
591       for(item : list)
592       {
593          if(method == lineEach)
594             f.Puts(" \\\n\t");
595          f.Printf(" -%s", option);
596          if(noSpace)
597             OutputNoSpace(f, item);
598          else
599             f.Printf("%s", item);
600       }
601    }
602 }
603
604 void StringNoSpaceToDynamicString(DynamicString s, char * path)
605 {
606    char * output = new char[strlen(path)+1024];
607    ReplaceSpaces(output, path);
608    s.concat(output);
609    delete output;
610 }
611
612 static void OutputLibraries(File f, Array<String> libraries)
613 {
614    for(item : libraries)
615    {
616       char ext[MAX_EXTENSION];
617       char temp[MAX_LOCATION];
618       char * s = item;
619       bool usedFunction = false;
620       GetExtension(item, ext);
621       if(!strcmp(ext, "o") || !strcmp(ext, "a"))
622          f.Puts(" ");
623       else
624       {
625          if(!strcmp(ext, "so") || !strcmp(ext, "dylib"))
626          {
627             if(!strncmp(item, "lib", 3))
628                strcpy(temp, item + 3);
629             else
630                strcpy(temp, item);
631             StripExtension(temp);
632             s = temp;
633          } 
634          f.Puts(" \\\n\t$(call _L,");
635          usedFunction = true;
636       }
637       OutputNoSpace(f, s);
638       if(usedFunction)
639          f.Puts(")");
640    }
641 }
642
643 void CamelCase(char * string)
644 {
645    int c, len = strlen(string);
646    for(c=0; c<len && string[c] >= 'A' && string[c] <= 'Z'; c++)
647       string[c] = (char)tolower(string[c]);
648 }
649
650 CompilerConfig GetCompilerConfig()
651 {
652 #ifndef MAKEFILE_GENERATOR
653    CompilerConfig compiler = null;
654    if(ide && ide.workspace)
655       compiler = ideSettings.GetCompilerConfig(ide.workspace.compiler);
656    return compiler;
657 #else
658    incref defaultCompiler;
659    return defaultCompiler;
660 #endif
661 }
662
663 define localTargetType = config && config.options && config.options.targetType ?
664             config.options.targetType : options && options.targetType ?
665             options.targetType : TargetTypes::executable;
666 define localWarnings = config && config.options && config.options.warnings ?
667             config.options.warnings : options && options.warnings ?
668             options.warnings : WarningsOption::unset;
669 define localDebug = config && config.options && config.options.debug ?
670             config.options.debug : options && options.debug ?
671             options.debug : SetBool::unset;
672 define localMemoryGuard = config && config.options && config.options.memoryGuard ?
673             config.options.memoryGuard : options && options.memoryGuard ?
674             options.memoryGuard : SetBool::unset;
675 define localNoLineNumbers = config && config.options && config.options.noLineNumbers ?
676             config.options.noLineNumbers : options && options.noLineNumbers ?
677             options.noLineNumbers : SetBool::unset;
678 define localProfile = config && config.options && config.options.profile ?
679             config.options.profile : options && options.profile ?
680             options.profile : SetBool::unset;
681 define localOptimization = config && config.options && config.options.optimization ?
682             config.options.optimization : options && options.optimization ?
683             options.optimization : OptimizationStrategy::none;
684 define localFastMath = config && config.options && config.options.fastMath ?
685             config.options.fastMath : options && options.fastMath ?
686             options.fastMath : SetBool::unset;
687 define localDefaultNameSpace = config && config.options && config.options.defaultNameSpace ?
688             config.options.defaultNameSpace : options && options.defaultNameSpace ?
689             options.defaultNameSpace : null;
690 define localStrictNameSpaces = config && config.options && config.options.strictNameSpaces ?
691             config.options.strictNameSpaces : options && options.strictNameSpaces ?
692             options.strictNameSpaces : SetBool::unset;
693 // TODO: I would rather have null here, check if it'll be ok, have the property return "" if required
694 define localTargetFileName = config && config.options && config.options.targetFileName ?
695             config.options.targetFileName : options && options.targetFileName ?
696             options.targetFileName : "";
697 define localTargetDirectory = config && config.options && config.options.targetDirectory && config.options.targetDirectory[0] ?
698             config.options.targetDirectory : options && options.targetDirectory && options.targetDirectory[0] ?
699             options.targetDirectory : null;
700 define settingsTargetDirectory = ideSettings && ideSettings.projectDefaultIntermediateObjDir &&
701             ideSettings.projectDefaultIntermediateObjDir[0] ?
702             ideSettings.projectDefaultIntermediateObjDir : defaultObjDirExpression;
703 define localObjectsDirectory = config && config.options && config.options.objectsDirectory && config.options.objectsDirectory[0] ?
704             config.options.objectsDirectory : options && options.objectsDirectory && options.objectsDirectory[0] ?
705             options.objectsDirectory : null;
706 define settingsObjectsDirectory = ideSettings && ideSettings.projectDefaultIntermediateObjDir &&
707             ideSettings.projectDefaultIntermediateObjDir[0] ?
708             ideSettings.projectDefaultIntermediateObjDir : defaultObjDirExpression;
709 define localConsole = config && config.options && config.options.console ?
710             config.options.console : options && options.console ?
711             options.console : SetBool::unset;
712 define localCompress = config && config.options && config.options.compress ?
713             config.options.compress : options && options.compress ?
714             options.compress : SetBool::unset;
715
716 define platformTargetType =
717          configPOs && configPOs.options && configPOs.options.targetType && configPOs.options.targetType != localTargetType ?
718                configPOs.options.targetType :
719          projectPOs && projectPOs.options && projectPOs.options.targetType && projectPOs.options.targetType != localTargetType ?
720                projectPOs.options.targetType : TargetTypes::unset;
721
722
723 char * PlatformToMakefileTargetVariable(Platform platform)
724 {
725    return platform == win32 ? "WINDOWS_TARGET" :
726           platform == tux   ? "LINUX_TARGET"   :
727           platform == apple ? "OSX_TARGET"     :
728                               "ERROR_BAD_TARGET";
729 }
730
731 char * TargetTypeToMakefileVariable(TargetTypes targetType)
732 {
733    return targetType == executable    ? "executable" :
734           targetType == sharedLibrary ? "sharedlib"  :
735           targetType == staticLibrary ? "staticlib"  :
736                                         "unknown";
737 }
738
739 // Move this to ProjectConfig? null vs Common to consider...
740 char * GetConfigName(ProjectConfig config)
741 {
742    return config ? config.name : "Common";
743 }
744
745 public enum SingleFileCompileMode { normal, debugPrecompile, debugCompile, debugGenerateSymbols, cObject };
746
747 class Project : struct
748 {
749    class_no_expansion;  // To use Find on the Container<Project> in Workspace::projects
750                         // We might want to tweak this default behavior of regular classes ?
751                         // Expansion/the current default kind of Find matching we want for things like BitmapResource, FontResource (Also regular classes)
752 public:
753    float version;
754    String moduleName;
755
756    property char * moduleVersion
757    {
758       set { delete moduleVersion; if(value && value[0]) moduleVersion = CopyString(value); } // TODO: use CopyString function that filters chars
759       get { return moduleVersion ? moduleVersion : ""; }                                     //       version number should only use digits and dots
760       isset { return moduleVersion != null && moduleVersion[0]; }                            //       add leading/trailing 0 if value start/ends with dot(s)
761    }
762
763    property char * description
764    {
765       set { delete description; if(value && value[0]) description = CopyString(value); }
766       get { return description ? description : ""; }
767       isset { return description != null && description[0]; }
768    }
769
770    property char * license
771    {
772       set { delete license; if(value && value[0]) license = CopyString(value); }
773       get { return license ? license : ""; }
774       isset { return license != null && license[0]; }
775    }
776
777    property char * compilerConfigsDir
778    {
779       set { delete compilerConfigsDir; if(value && value[0]) compilerConfigsDir = CopyString(value); }
780       get { return compilerConfigsDir ? compilerConfigsDir : ""; }
781       isset { return compilerConfigsDir && compilerConfigsDir[0]; }
782    }
783
784    property ProjectOptions options { get { return options; } set { options = value; } isset { return options && !options.isEmpty; } }
785    property Array<PlatformOptions> platforms
786    {
787       get { return platforms; }
788       set
789       {
790          if(platforms) { platforms.Free(); delete platforms; }
791          if(value)
792          {
793             List<PlatformOptions> empty { };
794             Iterator<PlatformOptions> it { value };
795             platforms = value;
796             for(p : platforms; !p.options || p.options.isEmpty) empty.Add(p);
797             for(p : empty; it.Find(p)) platforms.Delete(it.pointer);
798             delete empty;
799          }
800       }
801       isset
802       {
803          if(platforms)
804          {
805             for(p : platforms)
806             {
807                if(p.options && !p.options.isEmpty)
808                   return true;
809             }
810          }
811          return false;
812       }
813    }
814    List<ProjectConfig> configurations;
815    LinkList<ProjectNode> files;
816    String resourcesPath;
817    LinkList<ProjectNode> resources;
818
819 private:
820    // topNode.name holds the file name (.epj)
821    ProjectOptions options;
822    Array<PlatformOptions> platforms;
823    ProjectNode topNode { type = project, icon = epjFile, files = LinkList<ProjectNode>{ }, project = this };
824    ProjectNode resNode;
825
826    ProjectConfig config;
827    String filePath;
828    // This is the file name stripped of the epj extension
829    // It should NOT be edited, saved or loaded anywhere
830    String name;
831
832    String description;
833    String license;
834    String compilerConfigsDir;
835    String moduleVersion;
836
837 #ifndef MAKEFILE_GENERATOR
838    FileMonitor fileMonitor
839    {
840       this, FileChange { modified = true };
841       bool OnFileNotify(FileChange action, char * param)
842       {
843          fileMonitor.StopMonitoring();
844          if(OnProjectModified(action, param))
845             fileMonitor.StartMonitoring();
846          return true;
847       }
848    };
849
850    bool StartMonitoring()
851    {
852       fileMonitor.fileName = filePath;
853       fileMonitor.StartMonitoring();
854       return true;
855    }
856
857    bool StopMonitoring()
858    {
859       fileMonitor.StopMonitoring();
860       return true;
861    }
862
863    bool OnProjectModified(FileChange fileChange, char * param)
864    {
865       char temp[4096];
866       sprintf(temp, $"The project %s was modified by another application.\n"
867             "Would you like to reload it and lose your changes?", name);
868       if(MessageBox { type = yesNo, master = ide,
869             text = $"Project has been modified", contents = temp }.Modal() == yes)
870       {
871          Project project = LoadProject(filePath, config.name);
872          if(project)
873          {
874             ProjectView projectView = ide.projectView;
875             DataRow prev = topNode.row ? topNode.row.previous : null;
876             FileMonitor fm = fileMonitor;
877             bool confirmation = true;
878
879             if(projectView)
880             {
881                if(projectView.projectSettingsDialog)
882                {
883                   confirmation = projectView.projectSettingsDialog.CloseConfirmation(true);
884                   if(confirmation)
885                      projectView.projectSettingsDialog.Destroy(0);
886                }
887                if(confirmation)
888                   projectView.DeleteNode(topNode);
889             }
890             if(confirmation)
891             {
892                *this = *project;
893                delete fileMonitor;
894                fileMonitor = fm;
895                topNode.project = this;
896
897                if(projectView)
898                {
899                   CompilerConfig compiler = ideSettings.GetCompilerConfig(projectView.workspace.compiler);
900                   projectView.AddNode(topNode, null);
901                   topNode.row.Move(prev);
902
903                   projectView.ShowOutputBuildLog(true);
904                   projectView.DisplayCompiler(compiler, false);
905                   projectView.ProjectUpdateMakefileForAllConfigs(this);
906                   delete compiler;
907                }
908                eSystem_Delete(project);
909             }
910             else
911                delete project;
912          }
913          return true;
914       }
915       return true;
916    }
917
918 #endif
919
920    // This frees contents without freeing the instance
921    // For use from destructor and for file monitor reloading
922    // (To work around JSON loader (LoadProject) always returning a new instance)
923    void Free()
924    {
925       if(platforms) { platforms.Free(); delete platforms; }
926       if(configurations) { configurations.Free(); delete configurations; }
927       if(files) { files.Free(); delete files; }
928       if(resources) { resources.Free(); delete resources; }
929       delete options;
930       delete resourcesPath;
931
932       delete description;
933       delete license;
934       delete compilerConfigsDir;
935       delete moduleName;
936       delete moduleVersion;
937       delete filePath;
938       delete topNode;
939       delete name;
940    }
941
942    ~Project()
943    {
944       /* // THIS IS NOW AUTOMATED WITH A project CHECK IN ProjectNode
945       topNode.configurations = null;
946       topNode.platforms = null;
947       topNode.options = null;
948       */
949       Free();
950    }
951
952    property ProjectConfig config
953    {
954       set
955       {
956          config = value;
957          delete topNode.info;
958          topNode.info = CopyString(GetConfigName(config));
959       }
960    }
961    property char * filePath
962    {
963       set
964       {
965          if(value)
966          {
967             char string[MAX_LOCATION];
968             GetLastDirectory(value, string);
969             delete topNode.name;
970             topNode.name = CopyString(string);
971             StripExtension(string);
972             delete name;
973             name = CopyString(string);
974             StripLastDirectory(value, string);
975             delete topNode.path;
976             topNode.path = CopyString(string);
977             delete filePath;
978             filePath = CopyString(value);
979          }
980       }
981    }
982
983    TargetTypes GetTargetType(ProjectConfig config)
984    {
985       TargetTypes targetType = localTargetType;
986       return targetType;
987    }
988
989    bool GetTargetTypeIsSetByPlatform(ProjectConfig config)
990    {
991       Platform platform;
992       for(platform = (Platform)1; platform < Platform::enumSize; platform++)
993       {
994          PlatformOptions projectPOs, configPOs;
995          MatchProjectAndConfigPlatformOptions(config, platform, &projectPOs, &configPOs);
996          if(platformTargetType)
997             return true;
998       }
999       return false;
1000    }
1001
1002
1003    char * GetObjDirExpression(ProjectConfig config)
1004    {
1005       // TODO: Support platform options
1006       char * expression = localObjectsDirectory;
1007       if(!expression)
1008          expression = settingsObjectsDirectory;
1009       return expression;
1010    }
1011
1012    DirExpression GetObjDir(CompilerConfig compiler, ProjectConfig config, int bitDepth)
1013    {
1014       char * expression = GetObjDirExpression(config);
1015       DirExpression objDir { type = intermediateObjectsDir };
1016       objDir.Evaluate(expression, this, compiler, config, bitDepth);
1017       return objDir;
1018    }
1019
1020    char * GetTargetDirExpression(ProjectConfig config)
1021    {
1022       // TODO: Support platform options
1023       char * expression = localTargetDirectory;
1024       if(!expression)
1025          expression = settingsTargetDirectory;
1026       return expression;
1027    }
1028
1029    DirExpression GetTargetDir(CompilerConfig compiler, ProjectConfig config, int bitDepth)
1030    {
1031       char * expression = GetTargetDirExpression(config);
1032       DirExpression targetDir { type = DirExpressionType::targetDir /*intermediateObjectsDir*/};
1033       targetDir.Evaluate(expression, this, compiler, config, bitDepth);
1034       return targetDir;
1035    }
1036
1037    WarningsOption GetWarnings(ProjectConfig config)
1038    {
1039       WarningsOption warnings = localWarnings;
1040       return warnings;
1041    }
1042
1043    bool GetDebug(ProjectConfig config)
1044    {
1045       SetBool debug = localDebug;
1046       return debug == true;
1047    }
1048
1049    bool GetMemoryGuard(ProjectConfig config)
1050    {
1051       SetBool memoryGuard = localMemoryGuard;
1052       return memoryGuard == true;
1053    }
1054
1055    bool GetNoLineNumbers(ProjectConfig config)
1056    {
1057       SetBool noLineNumbers = localNoLineNumbers;
1058       return noLineNumbers == true;
1059    }
1060
1061    bool GetProfile(ProjectConfig config)
1062    {
1063       SetBool profile = localProfile;
1064       return profile == true;
1065    }
1066
1067    OptimizationStrategy GetOptimization(ProjectConfig config)
1068    {
1069       OptimizationStrategy optimization = localOptimization;
1070       return optimization;
1071    }
1072
1073    bool GetFastMath(ProjectConfig config)
1074    {
1075       SetBool fastMath = localFastMath;
1076       return fastMath == true;
1077    }
1078
1079    String GetDefaultNameSpace(ProjectConfig config)
1080    {
1081       String defaultNameSpace = localDefaultNameSpace;
1082       return defaultNameSpace;
1083    }
1084
1085    bool GetStrictNameSpaces(ProjectConfig config)
1086    {
1087       SetBool strictNameSpaces = localStrictNameSpaces;
1088       return strictNameSpaces == true;
1089    }
1090
1091    String GetTargetFileName(ProjectConfig config)
1092    {
1093       String targetFileName = localTargetFileName;
1094       return targetFileName;
1095    }
1096
1097    //String targetDirectory;
1098    //String objectsDirectory;
1099    bool GetConsole(ProjectConfig config)
1100    {
1101       SetBool console = localConsole;
1102       return console == true;
1103    }
1104
1105    bool GetCompress(ProjectConfig config)
1106    {
1107       SetBool compress = localCompress;
1108       return compress == true;
1109    }
1110    //SetBool excludeFromBuild;
1111
1112    bool GetConfigIsInActiveDebugSession(ProjectConfig config)
1113    {
1114 #ifndef MAKEFILE_GENERATOR
1115       return ide.project == this && ide.debugger && ide.debugger.prjConfig == config && ide.debugger.isActive;
1116 #endif
1117    }
1118
1119    bool GetConfigIsInDebugSession(ProjectConfig config)
1120    {
1121 #ifndef MAKEFILE_GENERATOR
1122       return ide.project == this && ide.debugger && ide.debugger.prjConfig == config && ide.debugger.isPrepared;
1123 #endif
1124    }
1125
1126    void SetPath(bool projectsDirs, CompilerConfig compiler, ProjectConfig config, int bitDepth)
1127    {
1128 #ifndef MAKEFILE_GENERATOR
1129       ide.SetPath(projectsDirs, compiler, config, bitDepth);
1130 #endif
1131    }
1132
1133 #ifndef MAKEFILE_GENERATOR
1134    bool Save(char * fileName)
1135    {
1136       File f;
1137       /*char output[MAX_LOCATION];
1138        ChangeExtension(fileName, "json", output);
1139       f = FileOpen(output, write);*/
1140       f = FileOpen(fileName, write);
1141       if(f)
1142       {
1143          files = topNode.files;
1144          resources = resNode.files;
1145          resourcesPath = resNode.path;
1146
1147          files.Remove(resNode);
1148          version = 0.2f;
1149
1150          WriteJSONObject(f, class(Project), this, 0);
1151
1152          files.Add(resNode);
1153
1154          files = null;
1155          resources = null;
1156          resourcesPath = null;
1157          delete f;
1158       }
1159       return true;
1160    }
1161 #endif
1162
1163    // This method is only called from Debugger, should be moved to Debugger class?
1164 #ifndef MAKEFILE_GENERATOR
1165    bool GetRelativePath(char * filePath, char * relativePath)
1166    {
1167       ProjectNode node;
1168       char moduleName[MAX_FILENAME];
1169       GetLastDirectory(filePath, moduleName);
1170       // try with workspace dir first?
1171       if((node = topNode.Find(moduleName, false)))
1172       {
1173          strcpy(relativePath, strcmp(node.path, ".") ? node.path : "");
1174          PathCatSlash(relativePath, node.name);
1175          return true;
1176       }
1177       else
1178       {
1179          // Tweak for automatically resolving symbol loader modules
1180          char * sl = strstr(moduleName, ".main.ec");
1181          if(sl && (*sl = 0, !strcmpi(moduleName, name)))
1182          {
1183             char objDir[MAX_LOCATION];
1184             DirExpression objDirExp;
1185             CompilerConfig compiler = ide.debugger.currentCompiler;
1186             ProjectConfig config = ide.debugger.prjConfig;
1187             int bitDepth = ide.debugger.bitDepth;
1188             // This is not perfect, as multiple source files exist for the symbol loader module...
1189             // We try to set it in the debug config object directory.
1190             if(!compiler || !config)
1191             {
1192                // If we're not currently debugging, set a breakpoint in the active compiler/config
1193                compiler = GetCompilerConfig();
1194                config = this.config;
1195                // If the current config is not debuggable, set it in the first debuggable config found
1196                if(config && !config.options.debug)
1197                {
1198                   for(c : configurations; c.options.debug)
1199                   {
1200                      config = c;
1201                      break;
1202                   }
1203                }
1204             }
1205             objDirExp = GetObjDir(compiler, config, bitDepth);
1206             strcpy(objDir, objDirExp.dir);
1207             delete objDirExp;
1208             ChangeCh(objDir, '\\', '/'); // TODO: this is a hack, paths should never include win32 path seperators - fix this in ProjectSettings and ProjectLoad instead
1209             ReplaceSpaces(relativePath, objDir);
1210             *sl = '.';
1211             PathCatSlash(relativePath, moduleName);
1212             return true;
1213          }
1214       }
1215       // WARNING: On failure, relative path is uninitialized
1216       return false;   
1217    }
1218 #endif
1219
1220    void CatTargetFileName(char * string, CompilerConfig compiler, ProjectConfig config)
1221    {
1222       TargetTypes targetType = GetTargetType(config);
1223       String targetFileName = GetTargetFileName(config);
1224       if(targetType == staticLibrary)
1225       {
1226          PathCatSlash(string, "lib");
1227          strcat(string, targetFileName);
1228       }
1229       else if(compiler.targetPlatform != win32 && targetType == sharedLibrary)
1230       {
1231          PathCatSlash(string, "lib");
1232          strcat(string, targetFileName);
1233       }
1234       else
1235          PathCatSlash(string, targetFileName);
1236       
1237       switch(targetType)
1238       {
1239          case executable:
1240             if(compiler.targetPlatform == win32)
1241                strcat(string, ".exe");
1242             break;
1243          case sharedLibrary:
1244             if(compiler.targetPlatform == win32)
1245                strcat(string, ".dll");
1246             else if(compiler.targetPlatform == apple)
1247                strcat(string, ".dylib");
1248             else
1249                strcat(string, ".so");
1250             if(compiler.targetPlatform == tux && GetRuntimePlatform() == tux && moduleVersion && moduleVersion[0])
1251             {
1252                strcat(string, ".");
1253                strcat(string, moduleVersion);
1254             }
1255             break;
1256          case staticLibrary:
1257             strcat(string, ".a");
1258             break;
1259       }
1260    }
1261
1262    bool GetProjectCompilerConfigsDir(char * cfDir, bool replaceSpaces, bool makeRelative)
1263    {
1264       bool result = false;
1265       char temp[MAX_LOCATION];
1266       strcpy(cfDir, topNode.path);
1267       if(compilerConfigsDir && compilerConfigsDir[0])
1268       {
1269          PathCatSlash(cfDir, compilerConfigsDir);
1270          result = true;
1271       }
1272       if(makeRelative)
1273       {
1274          strcpy(temp, cfDir);
1275          // Using a relative path makes it less likely to run into spaces issues
1276          // Even with escaped spaces, there still seems to be issues including a config file
1277          // in a path containing spaces
1278
1279          MakePathRelative(temp, topNode.path, cfDir);
1280       }
1281
1282       if(cfDir && cfDir[0] && cfDir[strlen(cfDir)-1] != '/')
1283          strcat(cfDir, "/");
1284       if(replaceSpaces)
1285       {
1286          strcpy(temp, cfDir);
1287          ReplaceSpaces(cfDir, temp);
1288       }
1289       return result;
1290    }
1291
1292    bool GetIDECompilerConfigsDir(char * cfDir, bool replaceSpaces, bool makeRelative)
1293    {
1294       char temp[MAX_LOCATION];
1295       bool result = false;
1296       strcpy(cfDir, topNode.path);
1297       if(ideSettings && ideSettings.compilerConfigsDir && ideSettings.compilerConfigsDir[0])
1298       {
1299          PathCatSlash(cfDir, ideSettings.compilerConfigsDir);
1300          result = true;
1301       }
1302       else
1303       {
1304          // Default to <ProjectDir>/.configs if unset
1305          PathCatSlash(cfDir, ".configs");
1306          result = true;
1307       }
1308       if(makeRelative)
1309       {
1310          strcpy(temp, cfDir);
1311          // Using a relative path makes it less likely to run into spaces issues
1312          // Even with escaped spaces, there still seems to be issues including a config file
1313          // in a path containing spaces
1314          if(IsPathInsideOf(cfDir, topNode.path))
1315             MakePathRelative(temp, topNode.path, cfDir);
1316       }
1317       if(cfDir && cfDir[0] && cfDir[strlen(cfDir)-1] != '/')
1318          strcat(cfDir, "/");
1319       if(replaceSpaces)
1320       {
1321          strcpy(temp, cfDir);
1322          ReplaceSpaces(cfDir, temp);
1323       }
1324       return result;
1325    }
1326
1327    void CatMakeFileName(char * string, ProjectConfig config)
1328    {
1329       char projectName[MAX_LOCATION];
1330       strcpy(projectName, name);
1331       sprintf(string, "%s%s%s.Makefile", projectName, config ? "-" : "", config ? config.name : "");
1332    }
1333
1334 #ifndef MAKEFILE_GENERATOR
1335    void MarkChanges(ProjectNode node)
1336    {
1337       for(cfg : topNode.configurations)
1338       {
1339          ProjectConfig c = null;
1340          for(i : node.configurations; !strcmpi(i.name, cfg.name)) { c = i; break; }
1341
1342          if(c && ((c.options && cfg.options && cfg.options.console != c.options.console) ||
1343                (!c.options || !cfg.options)))
1344             cfg.symbolGenModified = true;
1345          if(c && ((c.options && cfg.options && 
1346                ( (cfg.options.libraries && c.options.libraries && cfg.options.libraries.OnCompare(c.options.libraries)) || (!cfg.options.libraries || !c.options.libraries)) ) 
1347             || (!c.options || !cfg.options)))
1348             cfg.linkingModified = true;
1349
1350          cfg.makingModified = true;
1351       }
1352    }
1353
1354    void ModifiedAllConfigs(bool making, bool compiling, bool linking, bool symbolGen)
1355    {
1356       for(cfg : configurations)
1357       {
1358          if(making)
1359             cfg.makingModified = true;
1360          if(compiling)
1361             cfg.compilingModified = true;
1362          if(linking)
1363             cfg.linkingModified = true;
1364          if(symbolGen)
1365             cfg.symbolGenModified = true;
1366       }
1367       if(compiling || linking)
1368       {
1369          ide.projectView.modifiedDocument = true;
1370          ide.workspace.modified = true;
1371       }
1372    }
1373    
1374    void RotateActiveConfig(bool forward)
1375    {
1376       if(configurations.first && configurations.last != configurations.first)
1377       {
1378          Iterator<ProjectConfig> cfg { configurations };
1379          while(forward ? cfg.Next() : cfg.Prev())
1380             if(cfg.data == config)
1381                break;
1382
1383          if(forward)
1384          {
1385             if(!cfg.Next())
1386                cfg.Next();
1387          }
1388          else
1389          {
1390             if(!cfg.Prev())
1391                cfg.Prev();
1392          }
1393
1394          property::config = cfg.data;
1395          ide.UpdateToolBarActiveConfigs(true);
1396          ide.workspace.modified = true;
1397          ide.projectView.Update(null);
1398       }
1399    }
1400
1401    void ProcessPipeOutputRaw(DualPipe f)
1402    {
1403       char line[65536];
1404       while(!f.Eof() && !ide.ShouldStopBuild())
1405       {
1406          bool result = true;
1407          double lastTime = GetTime();
1408          bool wait = true;
1409          while(result)
1410          {
1411             if((result = f.Peek()) && (result = f.GetLine(line, sizeof(line)-1)))
1412             {
1413                ide.outputView.buildBox.Logf("%s\n", line);
1414             }
1415             if(GetTime() - lastTime > 1.0 / PEEK_RESOLUTION) break;
1416          }
1417          //printf("Processing Input...\n");
1418          if(app.ProcessInput(true))
1419             wait = false;
1420          app.UpdateDisplay();
1421          if(wait)
1422          {
1423             //printf("Waiting...\n");
1424             app.Wait();
1425          }
1426          //if(!result) Sleep(1.0 / PEEK_RESOLUTION);
1427       }
1428       if(ide.ShouldStopBuild())
1429       {
1430          ide.outputView.buildBox.Logf($"\nBuild cancelled by user.\n", line);
1431          f.Terminate();
1432       }
1433    }
1434
1435    bool ProcessBuildPipeOutput(DualPipe f, DirExpression objDirExp, bool isARun, List<ProjectNode> onlyNodes,
1436       CompilerConfig compiler, ProjectConfig config, int bitDepth)
1437    {
1438       char line[65536];
1439       bool compiling = false, linking = false, precompiling = false;
1440       int compilingEC = 0;
1441       int numErrors = 0, numWarnings = 0;
1442       bool loggedALine = false;
1443       char * configName = config ? config.name : "Common";
1444       int lenMakeCommand = strlen(compiler.makeCommand);
1445       int testLen = 0;
1446
1447       char * gnuToolchainPrefix = compiler.gnuToolchainPrefix ? compiler.gnuToolchainPrefix : "";
1448
1449       DynamicString test { };
1450       DynamicString ecp { };
1451       DynamicString ecc { };
1452       DynamicString ecs { };
1453       DynamicString ear { };
1454       DynamicString prefix { };
1455       DynamicString cpp { };
1456       DynamicString cc { };
1457       DynamicString cxx { };
1458       DynamicString strip { };
1459       DynamicString ar { };
1460       /*
1461       if(bitDepth == 64 && compiler.targetPlatform == win32) 
1462          gnuToolchainPrefix = "x86_64-w64-mingw32-";
1463       else if(bitDepth == 32 && compiler.targetPlatform == win32)
1464          gnuToolchainPrefix = "i686-w64-mingw32-";
1465       */
1466       ecp.concatx(compiler.ecpCommand, " ");
1467       ecc.concatx(compiler.eccCommand, " ");
1468       ecs.concatx(compiler.ecsCommand, " ");
1469       ear.concatx(compiler.earCommand, " ");
1470
1471       prefix.concatx(
1472             compiler.ccacheEnabled ? "ccache " : "",
1473             compiler.distccEnabled ? "distcc " : "",
1474             gnuToolchainPrefix);
1475
1476       cpp.concatx((String)prefix, compiler.cppCommand, " ");
1477       cc.concatx((String)prefix, compiler.ccCommand,  " ");
1478       cxx.concatx((String)prefix, compiler.cxxCommand, " ");
1479
1480       strip.concatx(gnuToolchainPrefix, "strip ");
1481       ar.concatx(gnuToolchainPrefix, "ar rcs");
1482
1483       testLen = Max(testLen, ecp.size);
1484       testLen = Max(testLen, ecc.size);
1485       testLen = Max(testLen, ecs.size);
1486       testLen = Max(testLen, ear.size);
1487       testLen = Max(testLen, cpp.size);
1488       testLen = Max(testLen, cc.size);
1489       testLen = Max(testLen, cxx.size);
1490       testLen = Max(testLen, strip.size);
1491       testLen = Max(testLen, ar.size);
1492       testLen++;
1493
1494       while(!f.Eof() && !ide.ShouldStopBuild())
1495       {
1496          bool result = true;
1497          double lastTime = GetTime();
1498          bool wait = true;
1499          while(result)
1500          {
1501             //printf("Peeking and GetLine...\n");
1502             if((result = f.Peek()) && (result = f.GetLine(line, sizeof(line)-1)))
1503             {
1504                char * message = null;
1505                char * inFileIncludedFrom = strstr(line, stringInFileIncludedFrom);
1506                char * from = strstr(line, stringFrom);
1507                test.copyLenSingleBlankReplTrim(line, ' ', true, testLen);
1508                if(strstr(line, compiler.makeCommand) == line && line[lenMakeCommand] == ':')
1509                {
1510                   char * module = strstr(line, "No rule to make target `");
1511                   if(module)
1512                   {
1513                      char * end;
1514                      module = strchr(module, '`') + 1;
1515                      end = strchr(module, '\'');
1516                      if(end)
1517                      {
1518                         *end = '\0';
1519                         ide.outputView.buildBox.Logf($"   %s: No such file or directory\n", module);
1520                         // ide.outputView.buildBox.Logf("error: %s\n   No such file or directory\n", module);
1521                         numErrors++;
1522                      }
1523                   }
1524                   //else
1525                   //{
1526                      //ide.outputView.buildBox.Logf("error: %s\n", line);
1527                      //numErrors++;
1528                   //}
1529                }
1530                else if(strstr(test, ear) == test);
1531                else if(strstr(test, strip) == test);
1532                else if(strstr(test, cc) == test || strstr(test, cxx) == test || strstr(test, ecp) == test || strstr(test, ecc) == test)
1533                {
1534                   char moduleName[MAX_FILENAME];
1535                   byte * tokens[1];
1536                   char * module;
1537                   bool isPrecomp = false;
1538                   bool gotCC = false;
1539
1540                   if(strstr(test, cc) == test || strstr(test, cxx) == test)
1541                   {
1542                      module = strstr(line, " -c ");
1543                      if(module) module += 4;
1544                      gotCC = true;
1545                   }
1546                   else if(strstr(test, ecc) == test)
1547                   {
1548                      module = strstr(line, " -c ");
1549                      if(module) module += 4;
1550                      //module = line + 3;
1551                      // Don't show GCC warnings about generated C code because it does not compile clean yet...
1552                      compilingEC = 3;//2;
1553                      gotCC = true;
1554                   }
1555                   else if(strstr(test, ecp) == test)
1556                   {
1557                      // module = line + 8;
1558                      module = strstr(line, " -c ");
1559                      if(module) module += 4;
1560                      isPrecomp = true;
1561                      compilingEC = 0;
1562                      gotCC = true;
1563                   }
1564
1565                   loggedALine = true;
1566
1567                   if(module)
1568                   {
1569                      if(!compiling && !isPrecomp)
1570                      {
1571                         ide.outputView.buildBox.Logf($"Compiling...\n");
1572                         compiling = true;
1573                      }
1574                      else if(!precompiling && isPrecomp)
1575                      {
1576                         ide.outputView.buildBox.Logf($"Generating symbols...\n");
1577                         precompiling = true;
1578                      }
1579                      // Changed escapeBackSlashes here to handle paths with spaces
1580                      Tokenize(module, 1, tokens, true); // false);
1581                      GetLastDirectory(module, moduleName);
1582                      ide.outputView.buildBox.Logf("%s\n", moduleName);
1583                   }
1584                   else if((module = strstr(line, " -o ")))
1585                   {
1586                      compiling = false;
1587                      precompiling = false;
1588                      linking = true;
1589                      ide.outputView.buildBox.Logf($"Linking...\n");
1590                   }
1591                   else
1592                   {
1593                      ide.outputView.buildBox.Logf("%s\n", line);
1594                      if(strstr(line, "warning:") || strstr(line, "note:"))
1595                         numWarnings++;
1596                      else if(!gotCC && !strstr(line, "At top level") && !strstr(line, "In file included from") && !strstr(line, stringFrom))
1597                         numErrors++;
1598                   }
1599
1600                   if(compilingEC) compilingEC--;
1601                }
1602                else if(strstr(test, ar) == test)
1603                   ide.outputView.buildBox.Logf($"Building library...\n");
1604                else if(strstr(test, ecs) == test)
1605                   ide.outputView.buildBox.Logf($"Writing symbol loader...\n");
1606                else
1607                {
1608                   if(linking || compiling || precompiling)
1609                   {
1610                      char * colon = strstr(line, ":"); //, * bracket;
1611                      if(colon && (colon[1] == '/' || colon[1] == '\\'))
1612                         colon = strstr(colon + 1, ":");
1613                      if(colon)
1614                      {
1615                         char * sayError = "";
1616                         char moduleName[MAX_LOCATION], temp[MAX_LOCATION];
1617                         char * pointer;
1618                         char * error;
1619                         char * start = inFileIncludedFrom ? inFileIncludedFrom + strlen(stringInFileIncludedFrom) : from ? from + strlen(stringFrom) : line;
1620                         int len = (int)(colon - start);
1621                         char ext[MAX_EXTENSION];
1622                         len = Min(len, MAX_LOCATION-1);
1623                         // Don't be mistaken by the drive letter colon
1624                         // Cut module name
1625                         // TODO: need to fix colon - line gives char *
1626                         // warning: incompatible expression colon - line (char *); expected int
1627                         /*
1628                         strncpy(moduleName, line, (int)(colon - line));
1629                         moduleName[colon - line] = '\0';
1630                         */
1631                         strncpy(moduleName, start, len);
1632                         moduleName[len] = '\0';
1633                         // Remove stuff in brackets
1634                         //bracket = strstr(moduleName, "(");
1635                         //if(bracket) *bracket = '\0';
1636
1637                         GetLastDirectory(moduleName, temp);
1638                         GetExtension(temp, ext);
1639
1640                         if(linking && (!strcmp(ext, "o") || !strcmp(ext, "a") || !strcmp(ext, "lib")))
1641                         {
1642                            char * cColon = strstr(colon+1, ":");
1643                            if(cColon && (cColon[1] == '/' || cColon[1] == '\\'))
1644                               cColon = strstr(cColon + 1, ":");
1645                            if(cColon)
1646                            {
1647                               int len = (int)(cColon - (colon+1));
1648                               char mName[MAX_LOCATION];
1649                               len = Min(len, MAX_LOCATION-1);
1650                               strncpy(mName, colon+1, len);
1651                               mName[len] = '\0';
1652                               GetLastDirectory(mName, temp);
1653                               GetExtension(temp, ext);
1654                               if(!strcmp(ext, "c") || !strcmp(ext, "cpp") || !strcmp(ext, "cxx") || !strcmp(ext, "ec"))
1655                               {
1656                                  colon = cColon;
1657                                  strcpy(moduleName, mName);
1658                               }
1659                            }
1660                         }
1661                         if(linking && (!strcmp(temp, "ld") || !strcmp(temp, "ld.exe")))
1662                         {
1663                            moduleName[0] = 0;
1664                            if(strstr(colon, "skipping incompatible") || strstr(colon, "Recognised but unhandled"))
1665                            {
1666                               message = $"Linker Message: ";
1667                               colon = line;
1668                            }
1669                            else
1670                            {
1671                               numErrors++;
1672                               message = $"Linker Error";
1673                            }
1674                         }
1675                         else if(linking && (!strcmp(ext, "") || !strcmp(ext, "exe")))
1676                         {
1677                            moduleName[0] = 0;
1678                            colon = line;
1679                            if(!strstr(line, "error:"))
1680                            {
1681                               message = $"Linker Error: ";
1682                               numErrors++;
1683                            }
1684                         }
1685                         else
1686                         {
1687                            strcpy(temp, topNode.path);
1688                            PathCatSlash(temp, moduleName);
1689                            MakePathRelative(temp, topNode.path, moduleName);
1690                         }
1691                         error = strstr(line, "error:");
1692                         if(!message && error && error > colon)
1693                            numErrors++;
1694                         else
1695                         {
1696                            // Silence warnings for compiled eC
1697                            char * objDir = strstr(moduleName, objDirExp.dir);
1698                         
1699                            if(linking)
1700                            {
1701                               if((pointer = strstr(line, "undefined"))  ||
1702                                    (pointer = strstr(line, "multiple definition")) ||
1703                                    (pointer = strstr(line, "No such file")) ||
1704                                    (pointer = strstr(line, "token")))
1705                               {
1706                                  strncat(moduleName, colon, pointer - colon);
1707                                  sayError = "error: ";
1708                                  colon = pointer;
1709                                  numErrors++;
1710                               }
1711                            }
1712                            else if((pointer = strstr(line, "No such file")))
1713                            {
1714                               strncat(moduleName, colon, pointer - colon);
1715                               sayError = "error: ";
1716                               colon = pointer;
1717                               numErrors++;
1718                            }
1719                            else if(compilingEC == 1 || (objDir && objDir == moduleName))
1720                               continue;
1721                            else if(strstr(line, "warning:"))
1722                            {
1723                               numWarnings++;
1724                            }
1725                         }
1726                         if(message)
1727                            ide.outputView.buildBox.Logf("   %s%s\n", message, colon);
1728                         /*else if(this == ide.workspace.projects.firstIterator.data)
1729                            ide.outputView.buildBox.Logf("   %s%s%s\n", moduleName, sayError, colon);*/
1730                         else
1731                         {
1732                            char fullModuleName[MAX_LOCATION];
1733                            FileAttribs found = 0;
1734                            Project foundProject = this;
1735                            if(moduleName[0])
1736                            {
1737                               char * loc = strstr(moduleName, ":");
1738                               if(loc) *loc = 0;
1739                               strcpy(fullModuleName, topNode.path);
1740                               PathCat(fullModuleName, moduleName);
1741                               found = FileExists(fullModuleName);
1742                               if(!found && !strcmp(ext, "c"))
1743                               {
1744                                  char ecName[MAX_LOCATION];
1745                                  ChangeExtension(fullModuleName, "ec", ecName);
1746                                  found = FileExists(ecName);
1747                               }
1748                               if(!found)
1749                               {
1750                                  char path[MAX_LOCATION];
1751                                  if(ide && ide.workspace)
1752                                  {
1753                                     for(prj : ide.workspace.projects)
1754                                     {
1755                                        ProjectNode node;
1756                                        MakePathRelative(fullModuleName, prj.topNode.path, path);
1757
1758                                        if((node = prj.topNode.FindWithPath(path, false)))
1759                                        {
1760                                           strcpy(fullModuleName, prj.topNode.path);
1761                                           PathCatSlash(fullModuleName, node.path);
1762                                           PathCatSlash(fullModuleName, node.name);
1763                                           found = FileExists(fullModuleName);
1764                                           if(found)
1765                                           {
1766                                              foundProject = prj;
1767                                              break;
1768                                           }
1769                                        }
1770                                     }
1771                                     if(!found && !strchr(moduleName, '/') && !strchr(moduleName, '\\'))
1772                                     {
1773                                        for(prj : ide.workspace.projects)
1774                                        {
1775                                           ProjectNode node;
1776                                           if((node = prj.topNode.Find(moduleName, false)))
1777                                           {
1778                                              strcpy(fullModuleName, prj.topNode.path);
1779                                              PathCatSlash(fullModuleName, node.path);
1780                                              PathCatSlash(fullModuleName, node.name);
1781                                              found = FileExists(fullModuleName);
1782                                              if(found)
1783                                              {
1784                                                 foundProject = prj;
1785                                                 break;
1786                                              }
1787                                           }
1788                                        }
1789                                     }
1790                                  }
1791                               }
1792                               if(found)
1793                               {
1794                                  MakePathRelative(fullModuleName, ide.workspace.projects.firstIterator.data.topNode.path, fullModuleName);
1795                                  MakeSystemPath(fullModuleName);
1796                               }
1797                               else
1798                                  strcpy(fullModuleName, moduleName);
1799                               if(loc)
1800                               {
1801                                  strcat(fullModuleName, ":");
1802                                  strcat(fullModuleName, loc + 1);
1803                               }
1804                            }
1805                            else
1806                               fullModuleName[0] = 0;
1807                            ide.outputView.buildBox.Logf("   %s%s%s%s\n", inFileIncludedFrom ? stringInFileIncludedFrom : from ? stringFrom : "", fullModuleName, sayError, colon);
1808                         }
1809                      }
1810                      else
1811                      {
1812                         ide.outputView.buildBox.Logf("%s\n", line);
1813                         linking = compiling = precompiling = false;
1814                      }
1815                   }
1816                   else
1817                      ide.outputView.buildBox.Logf("%s\n", line);
1818                }
1819                wait = false;
1820             }
1821             //printf("Done getting line\n");
1822             if(GetTime() - lastTime > 1.0 / PEEK_RESOLUTION) break;
1823          }
1824          //printf("Processing Input...\n");
1825          if(app.ProcessInput(true))
1826             wait = false;
1827          app.UpdateDisplay();
1828          if(wait)
1829          {
1830             //printf("Waiting...\n");
1831             app.Wait();
1832          }
1833          //if(!result) Sleep(1.0 / PEEK_RESOLUTION);
1834       }
1835       if(ide.ShouldStopBuild())
1836       {
1837          ide.outputView.buildBox.Logf($"\nBuild cancelled by user.\n", line);
1838          f.Terminate();
1839       }
1840       else if(loggedALine || !isARun)
1841       {
1842          if(f.GetExitCode() && !numErrors)
1843          {
1844             bool result = f.GetLine(line, sizeof(line)-1);
1845             ide.outputView.buildBox.Logf($"Fatal Error: child process terminated unexpectedly\n");
1846          }
1847          else
1848          {
1849             if(!onlyNodes)
1850             {
1851                char targetFileName[MAX_LOCATION];
1852                targetFileName[0] = '\0';
1853                CatTargetFileName(targetFileName, compiler, config);
1854                ide.outputView.buildBox.Logf("\n%s (%s) - ", targetFileName, configName);
1855             }
1856             if(numErrors)
1857                ide.outputView.buildBox.Logf("%d %s, ", numErrors, (numErrors > 1) ? $"errors" : $"error");
1858             else
1859                ide.outputView.buildBox.Logf($"no error, ");
1860    
1861             if(numWarnings)
1862                ide.outputView.buildBox.Logf("%d %s\n", numWarnings, (numWarnings > 1) ? $"warnings" : $"warning");
1863             else
1864                ide.outputView.buildBox.Logf($"no warning\n");
1865          }
1866       }
1867
1868       delete test;
1869       delete ecp;
1870       delete ecc;
1871       delete ecs;
1872       delete ear;
1873       delete prefix;
1874       delete cpp;
1875       delete cc;
1876       delete cxx;
1877       delete strip;
1878       delete ar;
1879
1880       return numErrors == 0;
1881    }
1882
1883    void ProcessCleanPipeOutput(DualPipe f, CompilerConfig compiler, ProjectConfig config)
1884    {
1885       char line[65536];
1886       int lenMakeCommand = strlen(compiler.makeCommand);
1887       while(!f.Eof())
1888       {
1889          bool result = true;
1890          bool wait = true;
1891          double lastTime = GetTime();
1892          while(result)
1893          {
1894             if((result = f.Peek()) && (result = f.GetLine(line, sizeof(line)-1)))
1895             {
1896                if(strstr(line, compiler.makeCommand) == line && line[lenMakeCommand] == ':');
1897                else if(strstr(line, "del") == line);
1898                else if(strstr(line, "rm") == line);
1899                else if(strstr(line, "Could Not Find") == line);
1900                else
1901                {
1902                   ide.outputView.buildBox.Logf(line);
1903                   ide.outputView.buildBox.Logf("\n");
1904                }
1905                wait = false;
1906             }
1907             if(GetTime() - lastTime > 1.0 / PEEK_RESOLUTION) break;
1908          }
1909          if(app.ProcessInput(true))
1910             wait = false;
1911          app.UpdateDisplay();
1912          if(wait)
1913             app.Wait();
1914          //Sleep(1.0 / PEEK_RESOLUTION);
1915       }
1916    }
1917
1918    bool Build(bool isARun, List<ProjectNode> onlyNodes, CompilerConfig compiler, ProjectConfig config, int bitDepth, bool justPrint, SingleFileCompileMode mode)
1919    {
1920       bool result = false;
1921       DualPipe f;
1922       char targetFileName[MAX_LOCATION] = "";
1923       DynamicString makeTargets { };
1924       char makeFile[MAX_LOCATION];
1925       char makeFilePath[MAX_LOCATION];
1926       char configName[MAX_LOCATION];
1927       DirExpression objDirExp = GetObjDir(compiler, config, bitDepth);
1928       PathBackup pathBackup { };
1929       bool crossCompiling = (compiler.targetPlatform != GetRuntimePlatform());
1930       char * targetPlatform = crossCompiling ? (char *)compiler.targetPlatform : "";
1931
1932       int numJobs = compiler.numJobs;
1933       char command[MAX_F_STRING];
1934       char * compilerName;
1935
1936       compilerName = CopyString(compiler.name);
1937       CamelCase(compilerName);
1938
1939       strcpy(configName, config ? config.name : "Common");
1940
1941       SetPath(false, compiler, config, bitDepth); //true
1942       CatTargetFileName(targetFileName, compiler, config);
1943
1944       strcpy(makeFilePath, topNode.path);
1945       CatMakeFileName(makeFile, config);
1946       PathCatSlash(makeFilePath, makeFile);
1947
1948       // TODO: TEST ON UNIX IF \" around makeTarget is ok
1949       if(onlyNodes)
1950       {
1951          if(compiler.type.isVC)
1952          {
1953             PrintLn("compiling a single file is not yet supported");
1954          }
1955          else
1956          {
1957             int len;
1958             char pushD[MAX_LOCATION];
1959             char cfDir[MAX_LOCATION];
1960             Map<String, NameCollisionInfo> namesInfo { };
1961             GetIDECompilerConfigsDir(cfDir, true, true);
1962             GetWorkingDir(pushD, sizeof(pushD));
1963             ChangeWorkingDir(topNode.path);
1964             // Create object dir if it does not exist already
1965             if(!FileExists(objDirExp.dir).isDirectory)
1966             {
1967                sprintf(command, "%s CF_DIR=\"%s\"%s%s%s%s COMPILER=%s objdir -C \"%s\"%s -f \"%s\"",
1968                      compiler.makeCommand, cfDir,
1969                      crossCompiling ? " TARGET_PLATFORM=" : "",
1970                      targetPlatform,
1971                      bitDepth ? " ARCH=" : "", bitDepth == 32 ? "32" : bitDepth == 64 ? "64" : "",
1972                      /*(bitDepth == 64 && compiler.targetPlatform == win32) ? " GCC_PREFIX=x86_64-w64-mingw32-" : (bitDepth == 32 && compiler.targetPlatform == win32) ? " GCC_PREFIX=i686-w64-mingw32-" : */"",
1973
1974                      compilerName, topNode.path, justPrint ? " -n" : "", makeFilePath);
1975                if(justPrint)
1976                   ide.outputView.buildBox.Logf("%s\n", command);
1977                Execute(command);
1978             }
1979
1980             ChangeWorkingDir(pushD);
1981
1982             topNode.GenMakefileGetNameCollisionInfo(namesInfo, config);
1983             for(node : onlyNodes)
1984             {
1985                if(node.GetIsExcluded(config))
1986                   ide.outputView.buildBox.Logf($"File %s is excluded from current build configuration.\n", node.name);
1987                else
1988                {
1989                   node.DeleteIntermediateFiles(compiler, config, bitDepth, namesInfo, mode == cObject ? true : false);
1990                   node.GetTargets(config, namesInfo, objDirExp.dir, makeTargets);
1991                }
1992             }
1993             namesInfo.Free();
1994             delete namesInfo;
1995          }
1996       }
1997
1998       if(compiler.type.isVC)
1999       {
2000          bool result = false;
2001          char oldwd[MAX_LOCATION];
2002          GetWorkingDir(oldwd, sizeof(oldwd));
2003          ChangeWorkingDir(topNode.path);
2004
2005          // TODO: support justPrint
2006          sprintf(command, "%s /useenv /nologo /logcommands %s.sln %s|Win32", compiler.makeCommand, name, config.name);
2007          if(justPrint)
2008             ide.outputView.buildBox.Logf("%s\n", command);
2009          if((f = DualPipeOpen(PipeOpenMode { output = true, error = true, input = true }, command)))
2010          {
2011             ProcessPipeOutputRaw(f);
2012             delete f;
2013             result = true;
2014          }
2015          ChangeWorkingDir(oldwd);
2016       }
2017       else
2018       {
2019          char cfDir[MAX_LOCATION];
2020          GetIDECompilerConfigsDir(cfDir, true, true);
2021          sprintf(command, "%s %sCF_DIR=\"%s\"%s%s%s%s%s COMPILER=%s -j%d %s%s%s -C \"%s\"%s -f \"%s\"",
2022                compiler.makeCommand,
2023                mode == debugPrecompile ? "ECP_DEBUG=y " : mode == debugCompile ? "ECC_DEBUG=y " : mode == debugGenerateSymbols ? "ECS_DEBUG=y " : "",
2024                cfDir,
2025                crossCompiling ? " TARGET_PLATFORM=" : "",
2026                targetPlatform,
2027                bitDepth ? " ARCH=" : "",
2028                bitDepth == 32 ? "32" : bitDepth == 64 ? "64" : "",
2029                /*(bitDepth == 64 && compiler.targetPlatform == win32) ? " GCC_PREFIX=x86_64-w64-mingw32-" : (bitDepth == 32 && compiler.targetPlatform == win32) ? " GCC_PREFIX=i686-w64-mingw32-" :*/ "",
2030                compilerName, numJobs,
2031                compiler.ccacheEnabled ? "CCACHE=y " : "",
2032                compiler.distccEnabled ? "DISTCC=y " : "",
2033                (String)makeTargets, topNode.path, (justPrint || (mode != normal && mode != cObject)) ? " -n" : "", makeFilePath);
2034          if(justPrint)
2035             ide.outputView.buildBox.Logf("%s\n", command);
2036
2037          if((f = DualPipeOpen(PipeOpenMode { output = true, error = true, input = true }, command)))
2038          {
2039             bool found = false;
2040             if(justPrint)
2041             {
2042                ProcessPipeOutputRaw(f);
2043                result = true;
2044             }
2045             else if(mode != normal && mode != cObject)
2046             {
2047                char line[65536];
2048                while(!f.Eof())
2049                {
2050                   bool result = true;
2051                   while(result)
2052                   {
2053                      if((result = f.Peek()) && (result = f.GetLine(line, sizeof(line)-1)))
2054                      {
2055                         if(!found && strstr(line, "ide ") == line)
2056                         {
2057                            strcpy(command, line);
2058                            found = true;
2059                         }
2060                      }
2061                   }
2062                }
2063             }
2064             else
2065                result = ProcessBuildPipeOutput(f, objDirExp, isARun, onlyNodes, compiler, config, bitDepth);
2066             delete f;
2067             if(found)
2068                Execute(command);
2069          }
2070          else
2071             ide.outputView.buildBox.Logf($"Error executing make (%s) command\n", compiler.makeCommand);
2072       }
2073
2074       delete pathBackup;
2075       delete objDirExp;
2076       delete compilerName;
2077       delete makeTargets;
2078       return result;
2079    }
2080
2081    void Clean(CompilerConfig compiler, ProjectConfig config, int bitDepth, CleanType cleanType, bool justPrint)
2082    {
2083       char makeFile[MAX_LOCATION];
2084       char makeFilePath[MAX_LOCATION];
2085       char command[MAX_LOCATION];
2086       char * compilerName;
2087       DualPipe f;
2088       PathBackup pathBackup { };
2089       bool crossCompiling = (compiler.targetPlatform != GetRuntimePlatform());
2090       char * targetPlatform = crossCompiling ? (char *)compiler.targetPlatform : "";
2091
2092       compilerName = CopyString(compiler.name);
2093       CamelCase(compilerName);
2094
2095       SetPath(false, compiler, config, bitDepth);
2096
2097       strcpy(makeFilePath, topNode.path);
2098       CatMakeFileName(makeFile, config);
2099       PathCatSlash(makeFilePath, makeFile);
2100       
2101       if(compiler.type.isVC)
2102       {
2103          bool result = false;
2104          char oldwd[MAX_LOCATION];
2105          GetWorkingDir(oldwd, sizeof(oldwd));
2106          ChangeWorkingDir(topNode.path);
2107          
2108          // TODO: justPrint support
2109          sprintf(command, "%s /useenv /clean /nologo /logcommands %s.sln %s|Win32", compiler.makeCommand, name, config.name);
2110          if(justPrint)
2111             ide.outputView.buildBox.Logf("%s\n", command);
2112          if((f = DualPipeOpen(PipeOpenMode { output = true, error = true, input = true }, command)))
2113          {
2114             ProcessPipeOutputRaw(f);
2115             delete f;
2116             result = true;
2117          }
2118          ChangeWorkingDir(oldwd);
2119          return result;
2120       }
2121       else
2122       {
2123          char cfDir[MAX_LOCATION];
2124          GetIDECompilerConfigsDir(cfDir, true, true);
2125          sprintf(command, "%s CF_DIR=\"%s\"%s%s%s%s COMPILER=%s %sclean%s -C \"%s\"%s -f \"%s\"",
2126                compiler.makeCommand, cfDir,
2127                crossCompiling ? " TARGET_PLATFORM=" : "", targetPlatform,
2128                bitDepth ? " ARCH=" : "", bitDepth == 32 ? "32" : bitDepth == 64 ? "64" : "",
2129                compilerName,
2130                cleanType == realClean ? "real" : "", cleanType == cleanTarget ? "target" : "",
2131                topNode.path, justPrint ? " -n": "", makeFilePath);
2132          if(justPrint)
2133             ide.outputView.buildBox.Logf("%s\n", command);
2134          if((f = DualPipeOpen(PipeOpenMode { output = 1, error = 1, input = 2 }, command)))
2135          {
2136             ide.outputView.buildBox.Tell($"Deleting target and object files...");
2137             if(justPrint)
2138                ProcessPipeOutputRaw(f);
2139             else
2140                ProcessCleanPipeOutput(f, compiler, config);
2141             delete f;
2142
2143             ide.outputView.buildBox.Logf($"Target and object files deleted\n");
2144          }
2145       }
2146
2147       delete pathBackup;
2148       delete compilerName;
2149    }
2150
2151    void Run(char * args, CompilerConfig compiler, ProjectConfig config, int bitDepth)
2152    {   
2153       String target = new char[maxPathLen];
2154       char oldDirectory[MAX_LOCATION];
2155       char * executableLauncher = compiler.executableLauncher;
2156       DirExpression targetDirExp = GetTargetDir(compiler, config, bitDepth);
2157       PathBackup pathBackup { };
2158
2159       // Build(project, ideMain, true, null, false);
2160
2161    #if defined(__WIN32__)
2162       strcpy(target, topNode.path);
2163    #else
2164       strcpy(target, "");
2165    #endif
2166       PathCatSlash(target, targetDirExp.dir);
2167       CatTargetFileName(target, compiler, config);
2168       sprintf(target, "%s %s", target, args);
2169       GetWorkingDir(oldDirectory, MAX_LOCATION);
2170
2171       if(strlen(ide.workspace.debugDir))
2172       {
2173          char temp[MAX_LOCATION];
2174          strcpy(temp, topNode.path);
2175          PathCatSlash(temp, ide.workspace.debugDir);
2176          ChangeWorkingDir(temp);
2177       }
2178       else
2179          ChangeWorkingDir(topNode.path);
2180       // ChangeWorkingDir(topNode.path);
2181       SetPath(true, compiler, config, bitDepth);
2182       if(executableLauncher)
2183       {
2184          char * prefixedTarget = new char[strlen(executableLauncher) + strlen(target) + 2];
2185          prefixedTarget[0] = '\0';
2186          strcat(prefixedTarget, executableLauncher);
2187          strcat(prefixedTarget, " ");
2188          strcat(prefixedTarget, target);
2189          Execute(prefixedTarget);
2190          delete prefixedTarget;
2191       }
2192       else
2193          Execute(target);
2194
2195       ChangeWorkingDir(oldDirectory);
2196       delete pathBackup;
2197
2198       delete targetDirExp;
2199       delete target;
2200    }
2201
2202    void Compile(List<ProjectNode> nodes, CompilerConfig compiler, ProjectConfig config, int bitDepth, bool justPrint, SingleFileCompileMode mode)
2203    {
2204       Build(false, nodes, compiler, config, bitDepth, justPrint, mode);
2205    }
2206 #endif
2207
2208    void GetMakefileTargetFileName(TargetTypes targetType, char * fileName, ProjectConfig config)
2209    {
2210       fileName[0] = '\0';
2211       if(targetType == staticLibrary || targetType == sharedLibrary)
2212          strcat(fileName, "$(LP)");
2213       // !!! ReplaceSpaces must be done after all PathCat calls !!!
2214       // ReplaceSpaces(s, GetTargetFileName(config));
2215       strcat(fileName, GetTargetFileName(config));
2216       switch(targetType)
2217       {
2218          case executable:
2219             strcat(fileName, "$(E)");
2220             break;
2221          case sharedLibrary:
2222             strcat(fileName, "$(SO)$(VER)");
2223             break;
2224          case staticLibrary:
2225             strcat(fileName, "$(A)");
2226             break;
2227       }
2228    }
2229
2230    bool GenerateCrossPlatformMk(File altCrossPlatformMk)
2231    {
2232       bool result = false;
2233       char path[MAX_LOCATION];
2234
2235       if(!GetProjectCompilerConfigsDir(path, false, false))
2236          GetIDECompilerConfigsDir(path, false, false);
2237
2238       if(!FileExists(path).isDirectory)
2239       {
2240          MakeDir(path);
2241          {
2242             char dirName[MAX_FILENAME];
2243             GetLastDirectory(path, dirName);
2244             if(!strcmp(dirName, ".configs"))
2245                FileSetAttribs(path, FileAttribs { isHidden = true });
2246          }
2247       }
2248       PathCatSlash(path, "crossplatform.mk");
2249
2250       if(FileExists(path))
2251          DeleteFile(path);
2252       {
2253          File include = altCrossPlatformMk ? altCrossPlatformMk : FileOpen(":crossplatform.mk", read);
2254          if(include)
2255          {
2256             File f = FileOpen(path, write);
2257             if(f)
2258             {
2259                include.Seek(0, start);
2260                for(; !include.Eof(); )
2261                {
2262                   char buffer[4096];
2263                   int count = include.Read(buffer, 1, 4096);
2264                   f.Write(buffer, 1, count);
2265                }
2266                delete f;
2267
2268                result = true;
2269             }
2270             if(!altCrossPlatformMk)
2271                delete include;
2272          }
2273       }
2274       return result;
2275    }
2276
2277    bool GenerateCompilerCf(CompilerConfig compiler)
2278    {
2279       bool result = false;
2280       char path[MAX_LOCATION];
2281       char * name;
2282       char * compilerName;
2283       bool gccCompiler = compiler.ccCommand && (strstr(compiler.ccCommand, "gcc") != null || strstr(compiler.ccCommand, "g++") != null);
2284       char * gnuToolchainPrefix = compiler.gnuToolchainPrefix ? compiler.gnuToolchainPrefix : "";
2285       Platform platform = compiler.targetPlatform;
2286
2287       compilerName = CopyString(compiler.name);
2288       CamelCase(compilerName);
2289       name = PrintString(platform, "-", compilerName, ".cf");
2290
2291       if(!GetProjectCompilerConfigsDir(path, false, false))
2292          GetIDECompilerConfigsDir(path, false, false);
2293
2294       if(!FileExists(path).isDirectory)
2295       {
2296          MakeDir(path);
2297          {
2298             char dirName[MAX_FILENAME];
2299             GetLastDirectory(path, dirName);
2300             if(!strcmp(dirName, ".configs"))
2301                FileSetAttribs(path, FileAttribs { isHidden = true });
2302          }
2303       }
2304       PathCatSlash(path, name);
2305
2306       if(FileExists(path))
2307          DeleteFile(path);
2308       {
2309          File f = FileOpen(path, write);
2310          if(f)
2311          {
2312             if(compiler.environmentVars && compiler.environmentVars.count)
2313             {
2314                f.Puts("# ENVIRONMENT VARIABLES\n");
2315                f.Puts("\n");
2316                for(e : compiler.environmentVars)
2317                {
2318                   f.Printf("export %s := %s\n", e.name, e.string);
2319                }
2320                f.Puts("\n");
2321             }
2322
2323             f.Puts("# TOOLCHAIN\n");
2324             f.Puts("\n");
2325
2326             if(gnuToolchainPrefix && gnuToolchainPrefix[0])
2327             {
2328                f.Printf("GCC_PREFIX := %s\n", gnuToolchainPrefix);
2329                f.Puts("\n");
2330             }
2331             if(compiler.sysroot && compiler.sysroot[0])
2332             {
2333                f.Printf("SYSROOT := %s\n", compiler.sysroot);
2334                // Moved this to crossplatform.mk
2335                //f.Puts("_SYSROOT := $(space)--sysroot=$(SYSROOT)\n");
2336                f.Puts("\n");
2337             }
2338
2339             //f.Printf("SHELL := %s\n", "sh"/*compiler.shellCommand*/); // is this really needed?
2340             f.Printf("CPP := $(CCACHE_COMPILE)$(DISTCC_COMPILE)$(GCC_PREFIX)%s$(_SYSROOT)\n", compiler.cppCommand);
2341             f.Printf("CC := $(CCACHE_COMPILE)$(DISTCC_COMPILE)$(GCC_PREFIX)%s$(_SYSROOT)\n", compiler.ccCommand);
2342             f.Printf("CXX := $(CCACHE_COMPILE)$(DISTCC_COMPILE)$(GCC_PREFIX)%s$(_SYSROOT)\n", compiler.cxxCommand);
2343             f.Printf("ECP := $(if $(ECP_DEBUG),ide -debug-start $(ECERE_SDK_SRC)/compiler/ecp/ecp.epj -@,%s)\n", compiler.ecpCommand);
2344             f.Printf("ECC := $(if $(ECC_DEBUG),ide -debug-start $(ECERE_SDK_SRC)/compiler/ecc/ecc.epj -@,%s)$(if $(CROSS_TARGET), -t $(TARGET_PLATFORM),)\n", compiler.eccCommand);
2345             f.Printf("ECS := $(if $(ECS_DEBUG),ide -debug-start $(ECERE_SDK_SRC)/compiler/ecs/ecs.epj -@,%s)$(if $(CROSS_TARGET), -t $(TARGET_PLATFORM),)\n", compiler.ecsCommand);
2346             f.Printf("EAR := %s\n", compiler.earCommand);
2347
2348             f.Puts("AS := $(GCC_PREFIX)as\n");
2349             f.Puts("LD := $(GCC_PREFIX)ld\n");
2350             f.Puts("AR := $(GCC_PREFIX)ar\n");
2351             f.Puts("STRIP := $(GCC_PREFIX)strip\n");
2352             f.Puts("UPX := upx\n");
2353             f.Puts("\n");
2354
2355             f.Puts("UPXFLAGS = -9\n"); // TOFEAT: Compression Level Option? Other UPX Options?
2356             f.Puts("\n");
2357
2358             f.Puts("EARFLAGS = \n");
2359             f.Puts("\n");
2360
2361             f.Puts("ifndef ARCH\n");
2362             f.Puts("TARGET_ARCH :=$(shell $(CC) -dumpmachine)\n");
2363             f.Puts(" ifdef WINDOWS_HOST\n");
2364             f.Puts("  ifneq ($(filter x86_64%,$(TARGET_ARCH)),)\n");
2365             f.Puts("     TARGET_ARCH := x86_64\n");
2366             f.Puts("  else\n");
2367             f.Puts("     TARGET_ARCH := i386\n");
2368             f.Puts("  endif\n");
2369             f.Puts(" endif\n");
2370             f.Puts("endif\n\n");
2371
2372             f.Puts("# HARD CODED TARGET_PLATFORM-SPECIFIC OPTIONS\n");
2373             f.Printf("LDFLAGS +=$(if $(%s), -Wl$(comma)--no-undefined,)\n", PlatformToMakefileTargetVariable(tux));
2374             f.Puts("\n");
2375
2376             // JF's
2377             f.Printf("LDFLAGS +=$(if $(%s), -framework cocoa -framework OpenGL,)\n", PlatformToMakefileTargetVariable(apple));
2378
2379             if(gccCompiler)
2380             {
2381                f.Puts("\nCFLAGS += -fmessage-length=0\n");
2382             }
2383
2384             if(compiler.includeDirs && compiler.includeDirs.count)
2385             {
2386                f.Puts("\nCFLAGS +=");
2387                OutputListOption(f, gccCompiler ? "isystem " : "I", compiler.includeDirs, lineEach, true);
2388                f.Puts("\n");
2389             }
2390             if(compiler.prepDirectives && compiler.prepDirectives.count)
2391             {
2392                f.Puts("\nCFLAGS +=");
2393                OutputListOption(f, "D", compiler.prepDirectives, inPlace, true);
2394                f.Puts("\n");
2395             }
2396             if(compiler.libraryDirs && compiler.libraryDirs.count)
2397             {
2398                f.Puts("\nLDFLAGS +=");
2399                OutputListOption(f, "L", compiler.libraryDirs, lineEach, true);
2400                // We would need a bool option to know whether we want to add to rpath as well...
2401                // OutputListOption(f, "Wl,-rpath ", compiler.libraryDirs, lineEach, true);
2402                f.Puts("\n");
2403             }
2404             if(compiler.excludeLibs && compiler.excludeLibs.count)
2405             {
2406                f.Puts("\nEXCLUDED_LIBS =");
2407                for(l : compiler.excludeLibs)
2408                {
2409                   f.Puts(" ");
2410                   f.Puts(l);
2411                }
2412             }
2413             if(compiler.linkerFlags && compiler.linkerFlags.count)
2414             {
2415                f.Puts("\nLDFLAGS +=");
2416                OutputListOption(f, "Wl,", compiler.linkerFlags, inPlace, true);
2417                f.Puts("\n");
2418             }
2419             f.Puts("\n");
2420             f.Puts("\nOFLAGS += $(LDFLAGS)");
2421             f.Puts("\n");
2422             f.Puts("ifdef ARCH_FLAGS\n");
2423             f.Puts("CFLAGS += $(ARCH_FLAGS)\n");
2424             f.Puts("OFLAGS += $(ARCH_FLAGS)\n");
2425             f.Puts("endif\n");
2426
2427             delete f;
2428
2429             result = true;
2430          }
2431       }
2432       delete name;
2433       delete compilerName;
2434       return result;
2435    }
2436
2437    bool GenerateMakefile(char * altMakefilePath, bool noResources, char * includemkPath, ProjectConfig config)
2438    {
2439       bool result = false;
2440       char filePath[MAX_LOCATION];
2441       char makeFile[MAX_LOCATION];
2442       // PathBackup pathBackup { };
2443       // char oldDirectory[MAX_LOCATION];
2444       File f = null;
2445
2446       if(!altMakefilePath)
2447       {
2448          strcpy(filePath, topNode.path);
2449          CatMakeFileName(makeFile, config);
2450          PathCatSlash(filePath, makeFile);
2451       }
2452
2453       f = FileOpen(altMakefilePath ? altMakefilePath : filePath, write);
2454
2455       /*SetPath(false, compiler, config);
2456       GetWorkingDir(oldDirectory, MAX_LOCATION);
2457       ChangeWorkingDir(topNode.path);*/
2458
2459       if(f)
2460       {
2461          bool test;
2462          int ifCount;
2463          Platform platform;
2464          char targetDir[MAX_LOCATION];
2465          char objDirExpNoSpaces[MAX_LOCATION];
2466          char objDirNoSpaces[MAX_LOCATION];
2467          char resDirNoSpaces[MAX_LOCATION];
2468          char targetDirExpNoSpaces[MAX_LOCATION];
2469          char fixedModuleName[MAX_FILENAME];
2470          char fixedConfigName[MAX_FILENAME];
2471          int c, len;
2472          // Non-zero if we're building eC code
2473          // We'll have to be careful with this when merging configs where eC files can be excluded in some configs and included in others
2474          int numCObjects = 0;
2475          int numObjects = 0;
2476          bool containsCXX = false; // True if the project contains a C++ file
2477          bool sameObjTargetDirs;
2478          String objDirExp = GetObjDirExpression(config);
2479          TargetTypes targetType = GetTargetType(config);
2480
2481          char cfDir[MAX_LOCATION];
2482          int objectsParts = 0, eCsourcesParts = 0;
2483          Array<String> listItems { };
2484          Map<String, int> varStringLenDiffs { };
2485          Map<String, NameCollisionInfo> namesInfo { };
2486
2487          Map<String, int> cflagsVariations { };
2488          Map<intptr, int> nodeCFlagsMapping { };
2489
2490          Map<String, int> ecflagsVariations { };
2491          Map<intptr, int> nodeECFlagsMapping { };
2492
2493          ReplaceSpaces(objDirNoSpaces, objDirExp);
2494          strcpy(targetDir, GetTargetDirExpression(config));
2495          ReplaceSpaces(targetDirExpNoSpaces, targetDir);
2496
2497          strcpy(objDirExpNoSpaces, GetObjDirExpression(config));
2498          ChangeCh(objDirExpNoSpaces, '\\', '/'); // TODO: this is a hack, paths should never include win32 path seperators - fix this in ProjectSettings and ProjectLoad instead
2499          {
2500             char temp[MAX_LOCATION];
2501             ReplaceSpaces(temp, objDirExpNoSpaces);
2502             strcpy(objDirExpNoSpaces, temp);
2503          }
2504          ReplaceSpaces(resDirNoSpaces, resNode.path ? resNode.path : "");
2505          ReplaceSpaces(fixedModuleName, moduleName);
2506          ReplaceSpaces(fixedConfigName, GetConfigName(config));
2507          CamelCase(fixedConfigName);
2508
2509          sameObjTargetDirs = !fstrcmp(objDirExpNoSpaces, targetDirExpNoSpaces);
2510
2511          f.Printf(".PHONY: all objdir%s cleantarget clean realclean distclean\n\n", sameObjTargetDirs ? "" : " targetdir");
2512
2513          f.Puts("# CORE VARIABLES\n\n");
2514
2515          f.Printf("MODULE := %s\n", fixedModuleName);
2516          f.Printf("VERSION := %s\n", property::moduleVersion);
2517          f.Printf("CONFIG := %s\n", fixedConfigName);
2518          f.Puts("ifndef COMPILER\n" "COMPILER := default\n" "endif\n");
2519          f.Puts("\n");
2520
2521          test = GetTargetTypeIsSetByPlatform(config);
2522          if(test)
2523          {
2524             ifCount = 0;
2525             for(platform = (Platform)1; platform < Platform::enumSize; platform++)
2526             {
2527                TargetTypes targetType;
2528                PlatformOptions projectPOs, configPOs;
2529                MatchProjectAndConfigPlatformOptions(config, platform, &projectPOs, &configPOs);
2530                targetType = platformTargetType;
2531                if(targetType)
2532                {
2533                   if(ifCount)
2534                      f.Puts("else\n");
2535                   ifCount++;
2536                   f.Printf("ifdef %s\n", PlatformToMakefileTargetVariable(platform));
2537                   f.Printf("TARGET_TYPE = %s\n", TargetTypeToMakefileVariable(targetType));
2538                }
2539             }
2540             f.Puts("else\n");
2541          }
2542          f.Printf("TARGET_TYPE = %s\n", TargetTypeToMakefileVariable(targetType));
2543          if(test)
2544          {
2545             if(ifCount)
2546             {
2547                for(c = 0; c < ifCount; c++)
2548                   f.Puts("endif\n");
2549             }
2550          }
2551          f.Puts("\n");
2552
2553          f.Puts("# FLAGS\n\n");
2554
2555          f.Puts("ECFLAGS =\n");
2556          f.Puts("ifndef DEBIAN_PACKAGE\n" "CFLAGS =\n" "LDFLAGS =\n" "endif\n");
2557          f.Puts("PRJ_CFLAGS =\n");
2558          f.Puts("CECFLAGS =\n");
2559          f.Puts("OFLAGS =\n");
2560          f.Puts("LIBS =\n");
2561          f.Puts("\n");
2562
2563          f.Puts("ifdef DEBUG\n" "NOSTRIP := y\n" "endif\n");
2564          f.Puts("\n");
2565
2566          // Important: We cannot use this ifdef anymore, EXECUTABLE_TARGET is not yet defined. It's embedded in the crossplatform.mk EXECUTABLE
2567          //f.Puts("ifdef EXECUTABLE_TARGET\n");
2568          f.Printf("CONSOLE = %s\n", GetConsole(config) ? "-mconsole" : "-mwindows");
2569          //f.Puts("endif\n");
2570          f.Puts("\n");
2571
2572          f.Puts("# INCLUDES\n\n");
2573
2574          if(compilerConfigsDir && compilerConfigsDir[0])
2575          {
2576             strcpy(cfDir, compilerConfigsDir);
2577             if(cfDir && cfDir[0] && cfDir[strlen(cfDir)-1] != '/')
2578                strcat(cfDir, "/");
2579          }
2580          else
2581          {
2582             GetIDECompilerConfigsDir(cfDir, true, true);
2583             // Use CF_DIR environment variable for absolute paths only
2584             if(cfDir[0] == '/' || (cfDir[0] && cfDir[1] == ':'))
2585                strcpy(cfDir, "$(CF_DIR)");
2586          }
2587
2588          f.Printf("_CF_DIR = %s\n", cfDir);
2589          f.Puts("\n");
2590
2591          f.Printf("include %s\n", includemkPath ? includemkPath : "$(_CF_DIR)crossplatform.mk");
2592          f.Puts("include $(_CF_DIR)$(TARGET_PLATFORM)-$(COMPILER).cf\n");
2593          f.Puts("\n");
2594
2595          f.Puts("# POST-INCLUDES VARIABLES\n\n");
2596
2597          f.Printf("OBJ = %s%s\n", objDirExpNoSpaces, objDirExpNoSpaces[0] ? "/" : "");
2598          f.Puts("\n");
2599
2600          f.Printf("RES = %s%s\n", resDirNoSpaces, resDirNoSpaces[0] ? "/" : "");
2601          f.Puts("\n");
2602
2603          // test = GetTargetTypeIsSetByPlatform(config);
2604          {
2605             char target[MAX_LOCATION];
2606             char temp[MAX_LOCATION];
2607             if(test)
2608             {
2609                TargetTypes type;
2610                ifCount = 0;
2611                for(type = (TargetTypes)1; type < TargetTypes::enumSize; type++)
2612                {
2613                   if(type != targetType)
2614                   {
2615                      if(ifCount)
2616                         f.Puts("else\n");
2617                      ifCount++;
2618                      f.Printf("ifeq \"$(TARGET_TYPE)\" \"%s\"\n", TargetTypeToMakefileVariable(type));
2619
2620                      GetMakefileTargetFileName(type, target, config);
2621                      strcpy(temp, targetDir);
2622                      PathCatSlash(temp, target);
2623                      ReplaceSpaces(target, temp);
2624                      f.Printf("TARGET = %s\n", target);
2625                   }
2626                }
2627                f.Puts("else\n");
2628             }
2629             GetMakefileTargetFileName(targetType, target, config);
2630             strcpy(temp, targetDir);
2631             PathCatSlash(temp, target);
2632             ReplaceSpaces(target, temp);
2633             f.Printf("TARGET = %s\n", target);
2634
2635             if(test)
2636             {
2637                if(ifCount)
2638                {
2639                   for(c = 0; c < ifCount; c++)
2640                      f.Puts("endif\n");
2641                }
2642             }
2643          }
2644          f.Puts("\n");
2645
2646          // Use something fixed here, to not cause Makefile differences across compilers...
2647          varStringLenDiffs["$(OBJ)"] = 30; // strlen("obj/memoryGuard.android.gcc-4.6.2") - 6;
2648          // varStringLenDiffs["$(OBJ)"] = strlen(objDirNoSpaces) - 6;
2649
2650          topNode.GenMakefileGetNameCollisionInfo(namesInfo, config);
2651
2652          {
2653             int c;
2654             char * map[5][2] = { { "COBJECTS", "C" }, { "SYMBOLS", "S" }, { "IMPORTS", "I" }, { "ECOBJECTS", "O" }, { "BOWLS", "B" } };
2655
2656             numCObjects = topNode.GenMakefilePrintNode(f, this, eCsources, namesInfo, listItems, config, null);
2657             if(numCObjects)
2658             {
2659                eCsourcesParts = OutputFileList(f, "_ECSOURCES", listItems, varStringLenDiffs, null);
2660
2661                f.Puts("ECSOURCES = $(call shwspace,$(_ECSOURCES))\n");
2662                if(eCsourcesParts > 1)
2663                {
2664                   for(c = 1; c <= eCsourcesParts; c++)
2665                      f.Printf("ECSOURCES%d = $(call shwspace,$(_ECSOURCES%d))\n", c, c);
2666                }
2667                f.Puts("\n");
2668
2669                for(c = 0; c < 5; c++)
2670                {
2671                   if(eCsourcesParts > 1)
2672                   {
2673                      int n;
2674                      f.Printf("%s =", map[c][0]);
2675                      for(n = 1; n <= eCsourcesParts; n++)
2676                         f.Printf(" $(%s%d)", map[c][0], n);
2677                      f.Puts("\n");
2678                      for(n = 1; n <= eCsourcesParts; n++)
2679                         f.Printf("%s%d = $(call shwspace,$(addprefix $(OBJ),$(patsubst %%.ec,%%$(%s),$(notdir $(_ECSOURCES%d)))))\n", map[c][0], n, map[c][1], n);
2680                   }
2681                   else if(eCsourcesParts == 1)
2682                      f.Printf("%s = $(call shwspace,$(addprefix $(OBJ),$(patsubst %%.ec,%%$(%s),$(notdir $(_ECSOURCES)))))\n", map[c][0], map[c][1]);
2683                   f.Puts("\n");
2684                }
2685             }
2686          }
2687
2688          numObjects = topNode.GenMakefilePrintNode(f, this, objects, namesInfo, listItems, config, &containsCXX);
2689          if(numObjects)
2690             objectsParts = OutputFileList(f, "_OBJECTS", listItems, varStringLenDiffs, null);
2691          f.Printf("OBJECTS =%s%s%s\n", numObjects ? " $(_OBJECTS)" : "", numCObjects ? " $(ECOBJECTS)" : "", numCObjects ? " $(OBJ)$(MODULE).main$(O)" : "");
2692          f.Puts("\n");
2693
2694          topNode.GenMakefilePrintNode(f, this, sources, null, listItems, config, null);
2695          OutputFileList(f, "SOURCES", listItems, varStringLenDiffs, numCObjects ? "$(ECSOURCES)" : null);
2696
2697          if(!noResources)
2698             resNode.GenMakefilePrintNode(f, this, resources, null, listItems, config, null);
2699          OutputFileList(f, "RESOURCES", listItems, varStringLenDiffs, null);
2700
2701          f.Puts("LIBS += $(SHAREDLIB) $(EXECUTABLE) $(LINKOPT)\n");
2702          f.Puts("\n");
2703          if((config && config.options && config.options.libraries) ||
2704                (options && options.libraries))
2705          {
2706             f.Puts("ifndef STATIC_LIBRARY_TARGET\n");
2707             f.Puts("LIBS +=");
2708             if(config && config.options && config.options.libraries)
2709                OutputLibraries(f, config.options.libraries);
2710             else if(options && options.libraries)
2711                OutputLibraries(f, options.libraries);
2712             f.Puts("\n");
2713             f.Puts("endif\n");
2714             f.Puts("\n");
2715          }
2716
2717          topNode.GenMakeCollectAssignNodeFlags(config, numCObjects,
2718                cflagsVariations, nodeCFlagsMapping,
2719                ecflagsVariations, nodeECFlagsMapping, null);
2720
2721          GenMakePrintCustomFlags(f, "PRJ_CFLAGS", false, cflagsVariations);
2722          GenMakePrintCustomFlags(f, "ECFLAGS", true, ecflagsVariations);
2723
2724          if(platforms || (config && config.platforms))
2725          {
2726             ifCount = 0;
2727             //for(platform = firstPlatform; platform <= lastPlatform; platform++)
2728             //for(platform = win32; platform <= apple; platform++)
2729
2730             f.Puts("# PLATFORM-SPECIFIC OPTIONS\n\n");
2731             for(platform = (Platform)1; platform < Platform::enumSize; platform++)
2732             {
2733                PlatformOptions projectPlatformOptions, configPlatformOptions;
2734                MatchProjectAndConfigPlatformOptions(config, platform, &projectPlatformOptions, &configPlatformOptions);
2735
2736                if(projectPlatformOptions || configPlatformOptions)
2737                {
2738                   if(ifCount)
2739                      f.Puts("else\n");
2740                   ifCount++;
2741                   f.Printf("ifdef %s\n", PlatformToMakefileTargetVariable(platform));
2742                   f.Puts("\n");
2743
2744                   if((projectPlatformOptions && projectPlatformOptions.options.linkerOptions && projectPlatformOptions.options.linkerOptions.count) ||
2745                      (configPlatformOptions && configPlatformOptions.options.linkerOptions && configPlatformOptions.options.linkerOptions.count))
2746                   {
2747                      f.Puts("OFLAGS +=");
2748                      if(projectPlatformOptions && projectPlatformOptions.options.linkerOptions && projectPlatformOptions.options.linkerOptions.count)
2749                      {
2750                         bool needWl = false;
2751                         f.Puts(" \\\n\t ");
2752                         for(s : projectPlatformOptions.options.linkerOptions)
2753                         {
2754                            if(!IsLinkerOption(s))
2755                               f.Printf(" %s", s);
2756                            else
2757                               needWl = true;
2758                         }
2759                         if(needWl)
2760                         {
2761                            f.Puts(" -Wl");
2762                            for(s : projectPlatformOptions.options.linkerOptions)
2763                               if(IsLinkerOption(s))
2764                                  f.Printf(",%s", s);
2765                         }
2766                      }
2767                      if(configPlatformOptions && configPlatformOptions.options.linkerOptions && configPlatformOptions.options.linkerOptions.count)
2768                      {
2769                         bool needWl = false;
2770                         f.Puts(" \\\n\t ");
2771                         for(s : configPlatformOptions.options.linkerOptions)
2772                         {
2773                            if(IsLinkerOption(s))
2774                               f.Printf(" %s", s);
2775                            else
2776                               needWl = true;
2777                         }
2778                         if(needWl)
2779                         {
2780                            f.Puts(" -Wl");
2781                            for(s : configPlatformOptions.options.linkerOptions)
2782                               if(!IsLinkerOption(s))
2783                                  f.Printf(",%s", s);
2784                         }
2785                      }
2786                      f.Puts("\n");
2787                      f.Puts("\n");
2788                   }
2789
2790                   if((projectPlatformOptions && projectPlatformOptions.options.libraryDirs && projectPlatformOptions.options.libraryDirs.count) ||
2791                         (configPlatformOptions && configPlatformOptions.options.libraryDirs && configPlatformOptions.options.libraryDirs.count) ||
2792                         (projectPlatformOptions && projectPlatformOptions.options.libraries && projectPlatformOptions.options.libraries.count) ||
2793                         (configPlatformOptions && configPlatformOptions.options.libraries && configPlatformOptions.options.libraries.count))
2794                   {
2795                      f.Puts("ifndef STATIC_LIBRARY_TARGET\n");
2796                      if((projectPlatformOptions && projectPlatformOptions.options.libraryDirs && projectPlatformOptions.options.libraryDirs.count) ||
2797                         (configPlatformOptions && configPlatformOptions.options.libraryDirs && configPlatformOptions.options.libraryDirs.count))
2798                      {
2799                         f.Puts("OFLAGS +=");
2800                         if(configPlatformOptions && configPlatformOptions.options.libraryDirs)
2801                            OutputListOption(f, "L", configPlatformOptions.options.libraryDirs, lineEach, true);
2802                         if(projectPlatformOptions && projectPlatformOptions.options.libraryDirs)
2803                            OutputListOption(f, "L", projectPlatformOptions.options.libraryDirs, lineEach, true);
2804                         f.Puts("\n");
2805                      }
2806
2807                      if((configPlatformOptions && configPlatformOptions.options.libraries))
2808                      {
2809                         if(configPlatformOptions.options.libraries.count)
2810                         {
2811                            f.Puts("LIBS +=");
2812                            OutputLibraries(f, configPlatformOptions.options.libraries);
2813                            f.Puts("\n");
2814                         }
2815                      }
2816                      else if(projectPlatformOptions && projectPlatformOptions.options.libraries)
2817                      {
2818                         if(projectPlatformOptions.options.libraries.count)
2819                         {
2820                            f.Puts("LIBS +=");
2821                            OutputLibraries(f, projectPlatformOptions.options.libraries);
2822                            f.Puts("\n");
2823                         }
2824                      }
2825                      f.Puts("endif\n");
2826                      f.Puts("\n");
2827                   }
2828                }
2829             }
2830             if(ifCount)
2831             {
2832                for(c = 0; c < ifCount; c++)
2833                   f.Puts("endif\n");
2834             }
2835             f.Puts("\n");
2836          }
2837
2838          if((config && config.options && config.options.linkerOptions && config.options.linkerOptions.count) ||
2839                (options && options.linkerOptions && options.linkerOptions.count))
2840          {
2841             f.Puts("OFLAGS +=");
2842             f.Puts(" \\\n\t");
2843
2844             if(config && config.options && config.options.linkerOptions && config.options.linkerOptions.count)
2845             {
2846                bool needWl = false;
2847                for(s : config.options.linkerOptions)
2848                {
2849                   if(!IsLinkerOption(s))
2850                      f.Printf(" %s", s);
2851                   else
2852                      needWl = true;
2853                }
2854                if(needWl)
2855                {
2856                   f.Puts(" -Wl");
2857                   for(s : config.options.linkerOptions)
2858                      if(IsLinkerOption(s))
2859                         f.Printf(",%s", s);
2860                }
2861             }
2862             if(options && options.linkerOptions && options.linkerOptions.count)
2863             {
2864                bool needWl = false;
2865                for(s : options.linkerOptions)
2866                {
2867                   if(!IsLinkerOption(s))
2868                      f.Printf(" %s", s);
2869                   else
2870                      needWl = true;
2871                }
2872                if(needWl)
2873                {
2874                   f.Puts(" -Wl");
2875                   for(s : options.linkerOptions)
2876                      if(IsLinkerOption(s))
2877                         f.Printf(",%s", s);
2878                }
2879             }
2880          }
2881          f.Puts("\n");
2882          f.Puts("\n");
2883
2884          f.Puts("CECFLAGS += -cpp $(_CPP)");
2885          f.Puts("\n");
2886          f.Puts("\n");
2887
2888          if(GetProfile(config))
2889             f.Puts("OFLAGS += -pg\n\n");
2890
2891          if((config && config.options && config.options.libraryDirs) || (options && options.libraryDirs))
2892          {
2893             f.Puts("ifndef STATIC_LIBRARY_TARGET\n");
2894             f.Puts("OFLAGS +=");
2895             if(config && config.options && config.options.libraryDirs)
2896                OutputListOption(f, "L", config.options.libraryDirs, lineEach, true);
2897             if(options && options.libraryDirs)
2898                OutputListOption(f, "L", options.libraryDirs, lineEach, true);
2899             f.Puts("\n");
2900             f.Puts("endif\n");
2901             f.Puts("\n");
2902          }
2903
2904          f.Puts("# TARGETS\n");
2905          f.Puts("\n");
2906
2907          f.Printf("all: objdir%s $(TARGET)\n", sameObjTargetDirs ? "" : " targetdir");
2908          f.Puts("\n");
2909
2910          f.Puts("objdir:\n");
2911             f.Puts("\t$(if $(wildcard $(OBJ)),,$(call mkdirq,$(OBJ)))\n");
2912          //f.Puts("# PRE-BUILD COMMANDS\n");
2913          if(options && options.prebuildCommands)
2914          {
2915             for(s : options.prebuildCommands)
2916                if(s && s[0]) f.Printf("\t%s\n", s);
2917          }
2918          if(config && config.options && config.options.prebuildCommands)
2919          {
2920             for(s : config.options.prebuildCommands)
2921                if(s && s[0]) f.Printf("\t%s\n", s);
2922          }
2923          if(platforms || (config && config.platforms))
2924          {
2925             ifCount = 0;
2926             //f.Puts("# TARGET_PLATFORM-SPECIFIC PRE-BUILD COMMANDS\n");
2927             for(platform = (Platform)1; platform < Platform::enumSize; platform++)
2928             {
2929                PlatformOptions projectPOs, configPOs;
2930                MatchProjectAndConfigPlatformOptions(config, platform, &projectPOs, &configPOs);
2931
2932                if((projectPOs && projectPOs.options.prebuildCommands && projectPOs.options.prebuildCommands.count) ||
2933                      (configPOs && configPOs.options.prebuildCommands && configPOs.options.prebuildCommands.count))
2934                {
2935                   if(ifCount)
2936                      f.Puts("else\n");
2937                   ifCount++;
2938                   f.Printf("ifdef %s\n", PlatformToMakefileTargetVariable(platform));
2939
2940                   if(projectPOs && projectPOs.options.prebuildCommands && projectPOs.options.prebuildCommands.count)
2941                   {
2942                      for(s : projectPOs.options.prebuildCommands)
2943                         if(s && s[0]) f.Printf("\t%s\n", s);
2944                   }
2945                   if(configPOs && configPOs.options.prebuildCommands && configPOs.options.prebuildCommands.count)
2946                   {
2947                      for(s : configPOs.options.prebuildCommands)
2948                         if(s && s[0]) f.Printf("\t%s\n", s);
2949                   }
2950                }
2951             }
2952             if(ifCount)
2953             {
2954                int c;
2955                for(c = 0; c < ifCount; c++)
2956                   f.Puts("endif\n");
2957             }
2958          }
2959          f.Puts("\n");
2960
2961          if(!sameObjTargetDirs)
2962          {
2963             f.Puts("targetdir:\n");
2964                f.Printf("\t$(if $(wildcard %s),,$(call mkdirq,%s))\n", targetDirExpNoSpaces, targetDirExpNoSpaces);
2965             f.Puts("\n");
2966          }
2967
2968          if(numCObjects)
2969          {
2970             // Main Module (Linking) for ECERE C modules
2971             f.Puts("$(OBJ)$(MODULE).main.ec: $(SYMBOLS) $(COBJECTS)\n");
2972             // use of objDirExpNoSpaces used instead of $(OBJ) to prevent problematic joining of arguments in ecs
2973             f.Printf("\t$(ECS)%s $(ARCH_FLAGS) $(ECSLIBOPT) $(SYMBOLS) $(IMPORTS) -symbols %s -o $(OBJ)$(MODULE).main.ec\n", 
2974                GetConsole(config) ? " -console" : "", objDirExpNoSpaces);
2975             f.Puts("\n");
2976             // Main Module (Linking) for ECERE C modules
2977             f.Puts("$(OBJ)$(MODULE).main.c: $(OBJ)$(MODULE).main.ec\n");
2978             f.Puts("\t$(ECP) $(CFLAGS) $(CECFLAGS) $(ECFLAGS) $(PRJ_CFLAGS)"
2979                   " -c $(OBJ)$(MODULE).main.ec -o $(OBJ)$(MODULE).main.sym -symbols $(OBJ)\n");
2980             f.Puts("\t$(ECC) $(CFLAGS) $(CECFLAGS) $(ECFLAGS) $(PRJ_CFLAGS) $(FVISIBILITY)"
2981                   " -c $(OBJ)$(MODULE).main.ec -o $(OBJ)$(MODULE).main.c -symbols $(OBJ)\n");
2982             f.Puts("\n");
2983          }
2984
2985          // *** Target ***
2986
2987          // This would not rebuild the target on updated objects
2988          // f.Printf("$(TARGET): $(SOURCES) $(RESOURCES) | objdir $(SYMBOLS) $(OBJECTS)%s\n", sameObjTargetDirs ? "" : " targetdir");
2989
2990          // This should fix it for good!
2991          f.Puts("$(SYMBOLS): | objdir\n");
2992          f.Puts("$(OBJECTS): | objdir\n");
2993
2994          // This alone was breaking the tarball, object directory does not get created first (order-only rules happen last it seems!)
2995          f.Printf("$(TARGET): $(SOURCES) $(RESOURCES) $(SYMBOLS) $(OBJECTS) | objdir%s\n", sameObjTargetDirs ? "" : " targetdir");
2996
2997          f.Printf("\t@$(call rmq,$(OBJ)linkobjects.lst)\n");
2998          f.Printf("\t@$(call touch,$(OBJ)linkobjects.lst)\n");
2999          OutputLinkObjectActions(f, "_OBJECTS", objectsParts);
3000          if(numCObjects)
3001          {
3002             f.Printf("\t@$(call echo,$(OBJ)$(MODULE).main$(O)) >> $(OBJ)linkobjects.lst\n");
3003             OutputLinkObjectActions(f, "ECOBJECTS", eCsourcesParts);
3004          }
3005
3006          f.Puts("ifndef STATIC_LIBRARY_TARGET\n");
3007
3008          f.Printf("\t$(%s) $(OFLAGS) @$(OBJ)linkobjects.lst $(LIBS) %s-o $(TARGET) $(INSTALLNAME)\n", containsCXX ? "CXX" : "CC", containsCXX ? "-lstdc++ " : "");
3009          if(!GetDebug(config))
3010          {
3011             f.Puts("ifndef NOSTRIP\n");
3012             f.Puts("\t$(STRIP) $(STRIPOPT) $(TARGET)\n");
3013             f.Puts("endif\n");
3014
3015             if(GetCompress(config))
3016             {
3017                f.Printf("ifndef %s\n", PlatformToMakefileTargetVariable(win32));
3018                f.Puts("ifdef EXECUTABLE_TARGET\n");
3019                   f.Puts("\t$(UPX) $(UPXFLAGS) $(TARGET)\n");
3020                f.Puts("endif\n");
3021                f.Puts("else\n");
3022                   f.Puts("\t$(UPX) $(UPXFLAGS) $(TARGET)\n");
3023                f.Puts("endif\n");
3024             }
3025          }
3026          if(resNode.files && resNode.files.count && !noResources)
3027             resNode.GenMakefileAddResources(f, resNode.path, config);
3028          f.Puts("else\n");
3029          f.Puts("\t$(AR) rcs $(TARGET) @$(OBJ)linkobjects.lst $(LIBS)\n");
3030          f.Puts("endif\n");
3031          f.Puts("ifdef SHARED_LIBRARY_TARGET\n");
3032          f.Puts("ifdef LINUX_TARGET\n");
3033          f.Puts("ifdef LINUX_HOST\n");
3034          // TODO?: support symlinks for longer version numbers
3035          f.Puts("\t$(if $(basename $(VER)),ln -sf $(LP)$(MODULE)$(SO)$(VER) $(OBJ)$(LP)$(MODULE)$(SO)$(basename $(VER)),)\n");
3036          f.Puts("\t$(if $(VER),ln -sf $(LP)$(MODULE)$(SO)$(VER) $(OBJ)$(LP)$(MODULE)$(SO),)\n");
3037          f.Puts("endif\n");
3038          f.Puts("endif\n");
3039          f.Puts("endif\n");
3040
3041          //f.Puts("# POST-BUILD COMMANDS\n");
3042          if(options && options.postbuildCommands)
3043          {
3044             for(s : options.postbuildCommands)
3045                if(s && s[0]) f.Printf("\t%s\n", s);
3046          }
3047          if(config && config.options && config.options.postbuildCommands)
3048          {
3049             for(s : config.options.postbuildCommands)
3050                if(s && s[0]) f.Printf("\t%s\n", s);
3051          }
3052          if(platforms || (config && config.platforms))
3053          {
3054             ifCount = 0;
3055             //f.Puts("# TARGET_PLATFORM-SPECIFIC POST-BUILD COMMANDS\n");
3056             for(platform = (Platform)1; platform < Platform::enumSize; platform++)
3057             {
3058                PlatformOptions projectPOs, configPOs;
3059                MatchProjectAndConfigPlatformOptions(config, platform, &projectPOs, &configPOs);
3060
3061                if((projectPOs && projectPOs.options.postbuildCommands && projectPOs.options.postbuildCommands.count) ||
3062                      (configPOs && configPOs.options.postbuildCommands && configPOs.options.postbuildCommands.count))
3063                {
3064                   if(ifCount)
3065                      f.Puts("else\n");
3066                   ifCount++;
3067                   f.Printf("ifdef %s\n", PlatformToMakefileTargetVariable(platform));
3068
3069                   if(projectPOs && projectPOs.options.postbuildCommands && projectPOs.options.postbuildCommands.count)
3070                   {
3071                      for(s : projectPOs.options.postbuildCommands)
3072                         if(s && s[0]) f.Printf("\t%s\n", s);
3073                   }
3074                   if(configPOs && configPOs.options.postbuildCommands && configPOs.options.postbuildCommands.count)
3075                   {
3076                      for(s : configPOs.options.postbuildCommands)
3077                         if(s && s[0]) f.Printf("\t%s\n", s);
3078                   }
3079                }
3080             }
3081             if(ifCount)
3082             {
3083                int c;
3084                for(c = 0; c < ifCount; c++)
3085                   f.Puts("endif\n");
3086             }
3087          }
3088          f.Puts("\n");
3089
3090          f.Puts("# SYMBOL RULES\n");
3091          f.Puts("\n");
3092
3093          topNode.GenMakefilePrintSymbolRules(f, this, config, nodeCFlagsMapping, nodeECFlagsMapping);
3094
3095          f.Puts("# C OBJECT RULES\n");
3096          f.Puts("\n");
3097
3098          topNode.GenMakefilePrintCObjectRules(f, this, config, nodeCFlagsMapping, nodeECFlagsMapping);
3099
3100          f.Puts("# OBJECT RULES\n");
3101          f.Puts("\n");
3102          // todo call this still but only generate rules whith specific options
3103          // see we-have-file-specific-options in ProjectNode.ec
3104          topNode.GenMakefilePrintObjectRules(f, this, namesInfo, config, nodeCFlagsMapping, nodeECFlagsMapping);
3105
3106          if(numCObjects)
3107             GenMakefilePrintMainObjectRule(f, config);
3108
3109          f.Printf("cleantarget: objdir%s\n", sameObjTargetDirs ? "" : " targetdir");
3110          f.Puts("\t$(call rmq,$(TARGET))\n");
3111          f.Puts("ifdef SHARED_LIBRARY_TARGET\n");
3112          f.Puts("ifdef LINUX_TARGET\n");
3113          f.Puts("ifdef LINUX_HOST\n");
3114          // TODO?: support symlinks for longer version numbers
3115          f.Puts("\t$(call rmq,$(OBJ)$(LP)$(MODULE)$(SO)$(basename $(VER)))\n");
3116          f.Puts("\t$(call rmq,$(OBJ)$(LP)$(MODULE)$(SO))\n");
3117          f.Puts("endif\n");
3118          f.Puts("endif\n");
3119          f.Puts("endif\n");
3120          f.Puts("\n");
3121
3122          f.Puts("clean: cleantarget\n");
3123          f.Printf("\t$(call rmq,$(OBJ)linkobjects.lst)\n");
3124          OutputCleanActions(f, "_OBJECTS", objectsParts);
3125          if(numCObjects)
3126          {
3127             f.Printf("\t$(call rmq,%s)\n", "$(OBJ)$(MODULE).main.o $(OBJ)$(MODULE).main.c $(OBJ)$(MODULE).main.ec $(OBJ)$(MODULE).main$(I) $(OBJ)$(MODULE).main$(S)");
3128             OutputCleanActions(f, "ECOBJECTS", eCsourcesParts);
3129             OutputCleanActions(f, "COBJECTS", eCsourcesParts);
3130             OutputCleanActions(f, "BOWLS", eCsourcesParts);
3131             OutputCleanActions(f, "IMPORTS", eCsourcesParts);
3132             OutputCleanActions(f, "SYMBOLS", eCsourcesParts);
3133          }
3134          f.Puts("\n");
3135
3136          f.Puts("realclean: cleantarget\n");
3137          f.Puts("\t$(call rmrq,$(OBJ))\n");
3138          if(!sameObjTargetDirs)
3139             f.Printf("\t$(call rmdirq,%s)\n", targetDirExpNoSpaces);
3140          f.Puts("\n");
3141
3142          f.Puts("distclean: cleantarget\n");
3143          if(!sameObjTargetDirs)
3144             f.Printf("\t$(call rmdirq,%s)\n", targetDirExpNoSpaces);
3145          f.Puts("\t$(call rmrq,obj/)\n");
3146
3147          delete f;
3148
3149          listItems.Free();
3150          delete listItems;
3151          varStringLenDiffs.Free();
3152          delete varStringLenDiffs;
3153          namesInfo.Free();
3154          delete namesInfo;
3155
3156          delete cflagsVariations;
3157          delete nodeCFlagsMapping;
3158          delete ecflagsVariations;
3159          delete nodeECFlagsMapping;
3160
3161          result = true;
3162       }
3163
3164       // ChangeWorkingDir(oldDirectory);
3165       // delete pathBackup;
3166
3167       if(config)
3168          config.makingModified = false;
3169       return result;
3170    }
3171
3172    void GenMakefilePrintMainObjectRule(File f, ProjectConfig config)
3173    {
3174       char extension[MAX_EXTENSION] = "c";
3175       char modulePath[MAX_LOCATION];
3176       char fixedModuleName[MAX_FILENAME];
3177       DualPipe dep;
3178       char command[2048];
3179       char objDirNoSpaces[MAX_LOCATION];
3180       String objDirExp = GetObjDirExpression(config);
3181
3182       ReplaceSpaces(objDirNoSpaces, objDirExp);
3183       ReplaceSpaces(fixedModuleName, moduleName);
3184       
3185       //sprintf(fixedModuleName, "%s.main", fixedPrjName);
3186       //strcat(fixedModuleName, ".main");
3187
3188 #if 0       // TODO: Fix nospaces stuff
3189       // *** Dependency command ***
3190       sprintf(command, "gcc -MT $(OBJ)%s$(O) -MM $(OBJ)%s.c", fixedModuleName, fixedModuleName);
3191
3192       // System Includes (from global settings)
3193       for(item : compiler.dirs[Includes])
3194       {
3195          strcat(command, " -isystem ");
3196          if(strchr(item.name, ' '))
3197          {
3198             strcat(command, "\"");
3199             strcat(command, item);
3200             strcat(command, "\"");
3201          }
3202          else
3203             strcat(command, item);
3204       }
3205
3206       for(item = includeDirs.first; item; item = item.next)
3207       {
3208          strcat(command, " -I");
3209          if(strchr(item.name, ' '))
3210          {
3211             strcat(command, "\"");
3212             strcat(command, item.name);
3213             strcat(command, "\"");
3214          }
3215          else
3216             strcat(command, item.name);
3217       }
3218       for(item = preprocessorDefs.first; item; item = item.next)
3219       {
3220          strcat(command, " -D");
3221          strcat(command, item.name);
3222       }
3223
3224       // Execute it
3225       if((dep = DualPipeOpen(PipeOpenMode { output = 1, error = 1, input = 2 }, command)))
3226       {
3227          char line[1024];
3228          bool result = true;
3229          bool firstLine = true;
3230
3231          // To do some time: auto save external dependencies?
3232          while(!dep.Eof())
3233          {
3234             if(dep.GetLine(line, sizeof(line)-1))
3235             {
3236                if(firstLine)
3237                {
3238                   char * colon = strstr(line, ":");
3239                   if(strstr(line, "No such file") || strstr(line, ",") || (colon && strstr(colon+1, ":")))
3240                   {
3241                      result = false;
3242                      break;
3243                   }
3244                   firstLine = false;
3245                }
3246                f.Puts(line);
3247                f.Puts("\n");
3248             }
3249             if(!result) break;
3250          }
3251          delete dep;
3252
3253          // If we failed to generate dependencies...
3254          if(!result)
3255          {
3256 #endif
3257             f.Puts("$(OBJ)$(MODULE).main$(O): $(OBJ)$(MODULE).main.c\n");
3258             f.Printf("\t$(CC) $(CFLAGS) $(PRJ_CFLAGS) $(FVISIBILITY) -c $(OBJ)$(MODULE).main.%s -o $(OBJ)$(MODULE).main$(O)\n", extension);
3259             f.Puts("\n");
3260 #if 0
3261          }
3262       }
3263 #endif
3264    }
3265
3266    void GenMakePrintCustomFlags(File f, String variableName, bool printNonCustom, Map<String, int> cflagsVariations)
3267    {
3268       int c;
3269       for(c = printNonCustom ? 0 : 1; c <= cflagsVariations.count; c++)
3270       {
3271          for(v : cflagsVariations)
3272          {
3273             if(v == c)
3274             {
3275                if(v == 1)
3276                   f.Printf("%s +=", variableName);
3277                else
3278                   f.Printf("CUSTOM%d_%s =", v-1, variableName);
3279                f.Puts(&v ? &v : "");
3280                f.Puts("\n");
3281                f.Puts("\n");
3282                break;
3283             }
3284          }
3285       }
3286       f.Puts("\n");
3287    }
3288
3289    void MatchProjectAndConfigPlatformOptions(ProjectConfig config, Platform platform,
3290          PlatformOptions * projectPlatformOptions, PlatformOptions * configPlatformOptions)
3291    {
3292       *projectPlatformOptions = null;
3293       *configPlatformOptions = null;
3294       if(platforms)
3295       {
3296          for(p : platforms)
3297          {
3298             if(!strcmpi(p.name, platform))
3299             {
3300                *projectPlatformOptions = p;
3301                break;
3302             }
3303          }
3304       }
3305       if(config && config.platforms)
3306       {
3307          for(p : config.platforms)
3308          {
3309             if(!strcmpi(p.name, platform))
3310             {
3311                *configPlatformOptions = p;
3312                break;
3313             }
3314          }
3315       }
3316    }
3317 }
3318
3319 Project LegacyBinaryLoadProject(File f, char * filePath)
3320 {
3321    Project project = null;
3322    char signature[sizeof(epjSignature)];
3323
3324    f.Read(signature, sizeof(signature), 1);
3325    if(!strncmp(signature, (char *)epjSignature, sizeof(epjSignature)))
3326    {
3327       char topNodePath[MAX_LOCATION];
3328       /*ProjectConfig newConfig
3329       {
3330          name = CopyString("Default");
3331          makingModified = true;
3332          compilingModified = true;
3333          linkingModified = true;
3334          options = { };
3335       };*/
3336
3337       project = Project { options = { } };
3338       LegacyBinaryLoadNode(project.topNode, f);
3339       delete project.topNode.path;
3340       GetWorkingDir(topNodePath, sizeof(topNodePath)-1);
3341       MakeSlashPath(topNodePath);
3342
3343       PathCatSlash(topNodePath, filePath);
3344       project.filePath = topNodePath;
3345       
3346       /* THIS IS ALREADY DONE BY filePath property
3347       StripLastDirectory(topNodePath, topNodePath);
3348       project.topNode.path = CopyString(topNodePath);
3349       */
3350       // Shouldn't this be done BEFORE the StripLastDirectory? project.filePath = topNodePath;
3351       
3352       // newConfig.options.defaultNameSpace = "";
3353       /*newConfig.objDir.dir = "obj";
3354       newConfig.targetDir.dir = "";*/
3355
3356       //project.configurations = { [ newConfig ] };
3357       //project.config = newConfig;
3358
3359       // Project Settings
3360       if(!f.Eof())
3361       {
3362          int temp;
3363          int len,c, count;
3364          String targetFileName, targetDirectory, objectsDirectory;
3365
3366          // { executable = 0, sharedLibrary = 1, staticLibrary = 2 };
3367          f.Read(&temp, sizeof(int),1);
3368          switch(temp)
3369          {
3370             case 0: project.options.targetType = executable; break;
3371             case 1: project.options.targetType = sharedLibrary; break;
3372             case 2: project.options.targetType = staticLibrary; break;
3373          }
3374
3375          f.Read(&len, sizeof(int),1);
3376          targetFileName = new char[len+1];
3377          f.Read(targetFileName, sizeof(char), len+1);
3378          project.options.targetFileName = targetFileName;
3379          delete targetFileName;
3380
3381          f.Read(&len, sizeof(int),1);
3382          targetDirectory = new char[len+1];
3383          f.Read(targetDirectory, sizeof(char), len+1);
3384          project.options.targetDirectory = targetDirectory;
3385          delete targetDirectory;
3386
3387          f.Read(&len, sizeof(int),1);
3388          objectsDirectory = new byte[len+1];
3389          f.Read(objectsDirectory, sizeof(char), len+1);
3390          project.options.objectsDirectory = objectsDirectory;
3391          delete objectsDirectory;
3392
3393          f.Read(&temp, sizeof(int),1);
3394          project./*config.*/options.debug = temp ? true : false;
3395          f.Read(&temp, sizeof(int),1);         
3396          project./*config.*/options.optimization = temp ? speed : none;
3397          f.Read(&temp, sizeof(int),1);
3398          project./*config.*/options.profile = temp ? true : false;
3399          f.Read(&temp, sizeof(int),1);
3400          project.options.warnings = temp ? all : unset;
3401
3402          f.Read(&count, sizeof(int),1);
3403          if(count)
3404          {
3405             project.options.includeDirs = { };
3406             for(c = 0; c < count; c++)
3407             {
3408                char * name;
3409                f.Read(&len, sizeof(int),1);
3410                name = new char[len+1];
3411                f.Read(name, sizeof(char), len+1);
3412                project.options.includeDirs.Add(name);
3413             }
3414          }
3415
3416          f.Read(&count, sizeof(int),1);
3417          if(count)
3418          {
3419             project.options.libraryDirs = { };
3420             for(c = 0; c < count; c++)
3421             {
3422                char * name;            
3423                f.Read(&len, sizeof(int),1);
3424                name = new char[len+1];
3425                f.Read(name, sizeof(char), len+1);
3426                project.options.libraryDirs.Add(name);
3427             }
3428          }
3429
3430          f.Read(&count, sizeof(int),1);
3431          if(count)
3432          {
3433             project.options.libraries = { };
3434             for(c = 0; c < count; c++)
3435             {
3436                char * name;
3437                f.Read(&len, sizeof(int),1);
3438                name = new char[len+1];
3439                f.Read(name, sizeof(char), len+1);
3440                project.options.libraries.Add(name);
3441             }
3442          }
3443
3444          f.Read(&count, sizeof(int),1);
3445          if(count)
3446          {
3447             project.options.preprocessorDefinitions = { };
3448             for(c = 0; c < count; c++)
3449             {
3450                char * name;
3451                f.Read(&len, sizeof(int),1);
3452                name = new char[len+1];
3453                f.Read(name, sizeof(char), len+1);
3454                project.options.preprocessorDefinitions.Add(name);
3455             }
3456          }
3457
3458          f.Read(&temp, sizeof(int),1);
3459          project.options.console = temp ? true : false;
3460       }
3461
3462       for(node : project.topNode.files)
3463       {
3464          if(node.type == resources)
3465          {
3466             project.resNode = node;
3467             break;
3468          }
3469       }
3470    }
3471    else
3472       f.Seek(0, start);
3473    return project;
3474 }
3475
3476 void ProjectConfig::LegacyProjectConfigLoad(File f)
3477 {  
3478    delete options;
3479    options = { };
3480    while(!f.Eof())
3481    {
3482       char buffer[65536];
3483       char section[128];
3484       char subSection[128];
3485       char * equal;
3486       int len;
3487       uint pos;
3488       
3489       pos = f.Tell();
3490       f.GetLine(buffer, 65536 - 1);
3491       TrimLSpaces(buffer, buffer);
3492       TrimRSpaces(buffer, buffer);
3493       if(strlen(buffer))
3494       {
3495          if(buffer[0] == '-')
3496          {
3497             equal = &buffer[0];
3498             equal[0] = ' ';
3499             TrimLSpaces(equal, equal);
3500             if(!strcmpi(subSection, "LibraryDirs"))
3501             {
3502                if(!options.libraryDirs)
3503                   options.libraryDirs = { [ CopyString(equal) ] };
3504                else
3505                   options.libraryDirs.Add(CopyString(equal));
3506             }
3507             else if(!strcmpi(subSection, "IncludeDirs"))
3508             {
3509                if(!options.includeDirs)
3510                   options.includeDirs = { [ CopyString(equal) ] };
3511                else
3512                   options.includeDirs.Add(CopyString(equal));
3513             }
3514          }
3515          else if(buffer[0] == '+')
3516          {
3517             if(name)
3518             {
3519                f.Seek(pos, start);
3520                break;
3521             }
3522             else
3523             {
3524                equal = &buffer[0];
3525                equal[0] = ' ';
3526                TrimLSpaces(equal, equal);
3527                delete name; name = CopyString(equal); // property::name = equal;
3528             }
3529          }
3530          else if(!strcmpi(buffer, "Compiler Options"))
3531             strcpy(section, buffer);
3532          else if(!strcmpi(buffer, "IncludeDirs"))
3533             strcpy(subSection, buffer);
3534          else if(!strcmpi(buffer, "Linker Options"))
3535             strcpy(section, buffer);
3536          else if(!strcmpi(buffer, "LibraryDirs"))
3537             strcpy(subSection, buffer);
3538          else if(!strcmpi(buffer, "Files") || !strcmpi(buffer, "Resources"))
3539          {
3540             f.Seek(pos, start);
3541             break;
3542          }
3543          else
3544          {
3545             equal = strstr(buffer, "=");
3546             if(equal)
3547             {
3548                equal[0] = '\0';
3549                TrimRSpaces(buffer, buffer);
3550                equal++;
3551                TrimLSpaces(equal, equal);
3552                if(!strcmpi(buffer, "Target Name"))
3553                   options.targetFileName = /*CopyString(*/equal/*)*/;
3554                else if(!strcmpi(buffer, "Target Type"))
3555                {
3556                   if(!strcmpi(equal, "Executable"))
3557                      options.targetType = executable;
3558                   else if(!strcmpi(equal, "Shared"))
3559                      options.targetType = sharedLibrary;
3560                   else if(!strcmpi(equal, "Static"))
3561                      options.targetType = staticLibrary;
3562                   else
3563                      options.targetType = executable;
3564                }
3565                else if(!strcmpi(buffer, "Target Directory"))
3566                   options.targetDirectory = /*CopyString(*/equal/*)*/;
3567                else if(!strcmpi(buffer, "Console"))
3568                   options.console = ParseTrueFalseValue(equal);
3569                else if(!strcmpi(buffer, "Libraries"))
3570                {
3571                   if(!options.libraries) options.libraries = { };
3572                   ParseArrayValue(options.libraries, equal);
3573                }
3574                else if(!strcmpi(buffer, "Intermediate Directory"))
3575                   options.objectsDirectory = /*CopyString(*/equal/*)*/; //objDir.expression = equal;
3576                else if(!strcmpi(buffer, "Debug"))
3577                   options.debug = ParseTrueFalseValue(equal);
3578                else if(!strcmpi(buffer, "Optimize"))
3579                {
3580                   if(!strcmpi(equal, "None"))
3581                      options.optimization = none;
3582                   else if(!strcmpi(equal, "Speed") || !strcmpi(equal, "True"))
3583                      options.optimization = speed;
3584                   else if(!strcmpi(equal, "Size"))
3585                      options.optimization = size;
3586                   else
3587                      options.optimization = none;
3588                }
3589                else if(!strcmpi(buffer, "Compress"))
3590                   options.compress = ParseTrueFalseValue(equal);
3591                else if(!strcmpi(buffer, "Profile"))
3592                   options.profile = ParseTrueFalseValue(equal);
3593                else if(!strcmpi(buffer, "AllWarnings"))
3594                   options.warnings = ParseTrueFalseValue(equal) ? all : unset;
3595                else if(!strcmpi(buffer, "MemoryGuard"))
3596                   options.memoryGuard = ParseTrueFalseValue(equal);
3597                else if(!strcmpi(buffer, "Default Name Space"))
3598                   options.defaultNameSpace = CopyString(equal);
3599                else if(!strcmpi(buffer, "Strict Name Spaces"))
3600                   options.strictNameSpaces = ParseTrueFalseValue(equal);
3601                else if(!strcmpi(buffer, "Preprocessor Definitions"))
3602                {
3603                   if(!options.preprocessorDefinitions) options.preprocessorDefinitions = { };
3604                   ParseArrayValue(options.preprocessorDefinitions, equal);
3605                }
3606             }
3607          }
3608       }
3609    }
3610    if(!options.targetDirectory && options.objectsDirectory)
3611       options.targetDirectory = /*CopyString(*/options.objectsDirectory/*)*/;
3612    //if(!objDir.dir) objDir.dir = "obj";
3613    //if(!targetDir.dir) targetDir.dir = "";
3614    // if(!targetName) property::targetName = "";   // How can a targetFileName be nothing???
3615    // if(!defaultNameSpace) property::defaultNameSpace = "";
3616    makingModified = true;
3617 }
3618
3619 Project LegacyAsciiLoadProject(File f, char * filePath)
3620 {
3621    Project project = null;
3622    ProjectNode node = null;
3623    int pos;
3624    char parentPath[MAX_LOCATION];
3625    char section[128] = "";
3626    char subSection[128] = "";
3627    ProjectNode parent;
3628    bool configurationsPresent = false;
3629
3630    f.Seek(0, start);
3631    while(!f.Eof())
3632    {
3633       char buffer[65536];
3634       //char version[16];
3635       char * equal;
3636       int len;
3637       pos = f.Tell();
3638       f.GetLine(buffer, 65536 - 1);
3639       TrimLSpaces(buffer, buffer);
3640       TrimRSpaces(buffer, buffer);
3641       if(strlen(buffer))
3642       {
3643          if(buffer[0] == '-' || buffer[0] == '=')
3644          {
3645             bool simple = buffer[0] == '-';
3646             equal = &buffer[0];
3647             equal[0] = ' ';
3648             TrimLSpaces(equal, equal);
3649             if(!strcmpi(section, "Target") && !strcmpi(subSection, "LibraryDirs"))
3650             {
3651                if(!project.config.options.libraryDirs)
3652                   project.config.options.libraryDirs = { [ CopyString(equal) ] };
3653                else
3654                   project.config.options.libraryDirs.Add(CopyString(equal));
3655             }
3656             else if(!strcmpi(section, "Target") && !strcmpi(subSection, "IncludeDirs"))
3657             {
3658                if(!project.config.options.includeDirs)
3659                   project.config.options.includeDirs = { [ CopyString(equal) ] };
3660                else
3661                   project.config.options.includeDirs.Add(CopyString(equal));
3662             }
3663             else if(!strcmpi(section, "Target") && (!strcmpi(subSection, "Files") || !strcmpi(subSection, "Resources")))
3664             {
3665                len = strlen(equal);
3666                if(len)
3667                {
3668                   char temp[MAX_LOCATION];
3669                   ProjectNode child { };
3670                   // We don't need to do this anymore, fileName is just a property that sets name & path
3671                   // child.fileName = CopyString(equal);
3672                   if(simple)
3673                   {
3674                      child.name = CopyString(equal);
3675                      child.path = CopyString(parentPath);
3676                   }
3677                   else
3678                   {
3679                      GetLastDirectory(equal, temp);
3680                      child.name = CopyString(temp);
3681                      StripLastDirectory(equal, temp);
3682                      child.path = CopyString(temp);
3683                   }
3684                   child.nodeType = file;
3685                   child.parent = parent;
3686                   child.indent = parent.indent + 1;
3687                   child.type = file;
3688                   child.icon = NodeIcons::SelectFileIcon(child.name);
3689                   parent.files.Add(child);
3690                   node = child;
3691                   //child = null;
3692                }
3693                else
3694                {
3695                   StripLastDirectory(parentPath, parentPath);
3696                   parent = parent.parent;
3697                }
3698             }
3699          }
3700          else if(buffer[0] == '+')
3701          {
3702             equal = &buffer[0];
3703             equal[0] = ' ';
3704             TrimLSpaces(equal, equal);
3705             if(!strcmpi(section, "Target") && (!strcmpi(subSection, "Files") || !strcmpi(subSection, "Resources")))
3706             {
3707                char temp[MAX_LOCATION];
3708                ProjectNode child { };
3709                // NEW: Folders now have a path set like files
3710                child.name = CopyString(equal);
3711                strcpy(temp, parentPath);
3712                PathCatSlash(temp, child.name);
3713                child.path = CopyString(temp);
3714
3715                child.parent = parent;
3716                child.indent = parent.indent + 1;
3717                child.type = folder;
3718                child.nodeType = folder;
3719                child.files = { };
3720                child.icon = folder;
3721                PathCatSlash(parentPath, child.name);
3722                parent.files.Add(child);
3723                parent = child;
3724                node = child;
3725                //child = null;
3726             }
3727             else if(!strcmpi(section, "Configurations"))
3728             {
3729                ProjectConfig newConfig
3730                {
3731                   makingModified = true;
3732                   options = { };
3733                };
3734                f.Seek(pos, start);
3735                LegacyProjectConfigLoad(newConfig, f);
3736                project.configurations.Add(newConfig);
3737             }
3738          }
3739          else if(!strcmpi(buffer, "ECERE Project File"));
3740          else if(!strcmpi(buffer, "Version 0a"))
3741             ; //strcpy(version, "0a");
3742          else if(!strcmpi(buffer, "Version 0.1a"))
3743             ; //strcpy(version, "0.1a");
3744          else if(!strcmpi(buffer, "Configurations"))
3745          {
3746             project.configurations.Free();
3747             project.config = null;
3748             strcpy(section, buffer);
3749             configurationsPresent = true;
3750          }
3751          else if(!strcmpi(buffer, "Target") || !strnicmp(buffer, "Target \"", strlen("Target \"")))
3752          {
3753             ProjectConfig newConfig { name = CopyString("Default"), options = { } };
3754             char topNodePath[MAX_LOCATION];
3755             // newConfig.defaultNameSpace = "";
3756             //newConfig.objDir.dir = "obj";
3757             //newConfig.targetDir.dir = "";
3758             project = Project { /*options = { }*/ };
3759             project.configurations = { [ newConfig ] };
3760             project.config = newConfig;
3761             // if(project.topNode.path) delete project.topNode.path;
3762             GetWorkingDir(topNodePath, sizeof(topNodePath)-1);
3763             MakeSlashPath(topNodePath);
3764             PathCatSlash(topNodePath, filePath);
3765             project.filePath = topNodePath;
3766             parentPath[0] = '\0';
3767             parent = project.topNode;
3768             node = parent;
3769             strcpy(section, "Target");
3770             equal = &buffer[6];
3771             if(equal[0] == ' ')
3772             {
3773                equal++;
3774                if(equal[0] == '\"')
3775                {
3776                   StripQuotes(equal, equal);
3777                   delete project.moduleName; project.moduleName = CopyString(equal);
3778                }
3779             }
3780          }
3781          else if(!strcmpi(buffer, "Compiler Options"));
3782          else if(!strcmpi(buffer, "IncludeDirs"))
3783             strcpy(subSection, buffer);
3784          else if(!strcmpi(buffer, "Linker Options"));
3785          else if(!strcmpi(buffer, "LibraryDirs"))
3786             strcpy(subSection, buffer);
3787          else if(!strcmpi(buffer, "Files"))
3788          {
3789             strcpy(section, "Target");
3790             strcpy(subSection, buffer);
3791          }
3792          else if(!strcmpi(buffer, "Resources"))
3793          {
3794             ProjectNode child { };
3795             parent.files.Add(child);
3796             child.parent = parent;
3797             child.indent = parent.indent + 1;
3798             child.name = CopyString(buffer);
3799             child.path = CopyString("");
3800             child.type = resources;
3801             child.files = { };
3802             child.icon = archiveFile;
3803             project.resNode = child;
3804             parent = child;
3805             node = child;
3806             strcpy(subSection, buffer);
3807          }
3808          else
3809          {
3810             equal = strstr(buffer, "=");
3811             if(equal)
3812             {
3813                equal[0] = '\0';
3814                TrimRSpaces(buffer, buffer);
3815                equal++;
3816                TrimLSpaces(equal, equal);
3817
3818                if(!strcmpi(section, "Target"))
3819                {
3820                   if(!strcmpi(buffer, "Build Exclusions"))
3821                   {
3822                      if(!strcmpi(section, "Target") && !strcmpi(subSection, "Files"))
3823                      {
3824                         /*if(node && node.type != NodeTypes::project)
3825                            ParseListValue(node.buildExclusions, equal);*/
3826                      }
3827                   }
3828                   else if(!strcmpi(buffer, "Path") && !strcmpi(subSection, "Resources"))
3829                   {
3830                      delete project.resNode.path;
3831                      project.resNode.path = CopyString(equal);
3832                      PathCatSlash(parentPath, equal);
3833                   }
3834
3835                   // Config Settings
3836                   else if(!strcmpi(buffer, "Intermediate Directory"))
3837                      project.config.options.objectsDirectory = /*CopyString(*/equal/*)*/; //objDir.expression = equal;
3838                   else if(!strcmpi(buffer, "Debug"))
3839                      project.config.options.debug = ParseTrueFalseValue(equal);
3840                   else if(!strcmpi(buffer, "Optimize"))
3841                   {
3842                      if(!strcmpi(equal, "None"))
3843                         project.config.options.optimization = none;
3844                      else if(!strcmpi(equal, "Speed") || !strcmpi(equal, "True"))
3845                         project.config.options.optimization = speed;
3846                      else if(!strcmpi(equal, "Size"))
3847                         project.config.options.optimization = size;
3848                      else
3849                         project.config.options.optimization = none;
3850                   }
3851                   else if(!strcmpi(buffer, "Profile"))
3852                      project.config.options.profile = ParseTrueFalseValue(equal);
3853                   else if(!strcmpi(buffer, "MemoryGuard"))
3854                      project.config.options.memoryGuard = ParseTrueFalseValue(equal);
3855                   else
3856                   {
3857                      if(!project.options) project.options = { };
3858
3859                      // Project Wide Settings (All configs)
3860                      if(!strcmpi(buffer, "Target Name"))
3861                         project.options.targetFileName = /*CopyString(*/equal/*)*/;
3862                      else if(!strcmpi(buffer, "Target Type"))
3863                      {
3864                         if(!strcmpi(equal, "Executable"))
3865                            project.options.targetType = executable;
3866                         else if(!strcmpi(equal, "Shared"))
3867                            project.options.targetType = sharedLibrary;
3868                         else if(!strcmpi(equal, "Static"))
3869                            project.options.targetType = staticLibrary;
3870                         else
3871                            project.options.targetType = executable;
3872                      }
3873                      else if(!strcmpi(buffer, "Target Directory"))
3874                         project.options.targetDirectory = /*CopyString(*/equal/*)*/;
3875                      else if(!strcmpi(buffer, "Console"))
3876                         project.options.console = ParseTrueFalseValue(equal);
3877                      else if(!strcmpi(buffer, "Libraries"))
3878                      {
3879                         if(!project.options.libraries) project.options.libraries = { };
3880                         ParseArrayValue(project.options.libraries, equal);
3881                      }
3882                      else if(!strcmpi(buffer, "AllWarnings"))
3883                         project.options.warnings = ParseTrueFalseValue(equal) ? all : unset;
3884                      else if(!strcmpi(buffer, "Preprocessor Definitions"))
3885                      {
3886                         if(!strcmpi(section, "Target") && !strcmpi(subSection, "Files"))
3887                         {
3888                            /*if(node && (node.type == NodeTypes::project || (node.type == file && !node.isInResources) || node.type == folder))
3889                               ParseListValue(node.preprocessorDefs, equal);*/
3890                         }
3891                         else
3892                         {
3893                            if(!project.options.preprocessorDefinitions) project.options.preprocessorDefinitions = { };
3894                            ParseArrayValue(project.options.preprocessorDefinitions, equal);
3895                         }
3896                      }
3897                   }
3898                }
3899             }
3900          }
3901       }
3902    }
3903    parent = null;
3904
3905    SplitPlatformLibraries(project);
3906
3907    if(configurationsPresent)
3908       CombineIdenticalConfigOptions(project);
3909    return project;
3910 }
3911
3912 void SplitPlatformLibraries(Project project)
3913 {
3914    if(project && project.configurations)
3915    {
3916       for(cfg : project.configurations)
3917       {
3918          if(cfg.options.libraries && cfg.options.libraries.count)
3919          {
3920             Iterator<String> it { cfg.options.libraries };
3921             while(it.Next())
3922             {
3923                String l = it.data;
3924                char * platformName = strstr(l, ":");
3925                if(platformName)
3926                {
3927                   PlatformOptions platform = null;
3928                   platformName++;
3929                   if(!cfg.platforms) cfg.platforms = { };
3930                   for(p : cfg.platforms)
3931                   {
3932                      if(!strcmpi(platformName, p.name))
3933                      {
3934                         platform = p;
3935                         break;
3936                      }
3937                   }
3938                   if(!platform)
3939                   {
3940                      platform = { name = CopyString(platformName), options = { libraries = { } } };
3941                      cfg.platforms.Add(platform);
3942                   }
3943                   *(platformName-1) = 0;
3944                   platform.options.libraries.Add(CopyString(l));
3945
3946                   cfg.options.libraries.Delete(it.pointer);
3947                   it.pointer = null;
3948                }
3949             }
3950          }
3951       }      
3952    }
3953 }
3954
3955 void CombineIdenticalConfigOptions(Project project)
3956 {
3957    if(project && project.configurations && project.configurations.count)
3958    {
3959       DataMember member;
3960       ProjectOptions nullOptions { };
3961       ProjectConfig firstConfig = null;
3962       for(cfg : project.configurations)
3963       {
3964          if(cfg.options.targetType != staticLibrary)
3965          {
3966             firstConfig = cfg;
3967             break;
3968          }
3969       }
3970       if(!firstConfig)
3971          firstConfig = project.configurations.firstIterator.data;
3972
3973       for(member = class(ProjectOptions).membersAndProperties.first; member; member = member.next)
3974       {
3975          if(!member.isProperty)
3976          {
3977             Class type = eSystem_FindClass(__thisModule, member.dataTypeString);
3978             if(type)
3979             {
3980                bool same = true;
3981
3982                for(cfg : project.configurations)
3983                {
3984                   if(cfg != firstConfig)
3985                   {
3986                      if(cfg.options.targetType != staticLibrary)
3987                      {
3988                         int result;
3989                         
3990                         if(type.type == noHeadClass || type.type == normalClass)
3991                         {
3992                            result = ((int (*)(void *, void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnCompare])(type, 
3993                               *(void **)((byte *)firstConfig.options + member.offset + member._class.offset),
3994                               *(void **)((byte *)cfg.options         + member.offset + member._class.offset));
3995                         }
3996                         else
3997                         {
3998                            result = ((int (*)(void *, void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnCompare])(type, 
3999                               (byte *)firstConfig.options + member.offset + member._class.offset,
4000                               (byte *)cfg.options         + member.offset + member._class.offset);
4001                         }
4002                         if(result)
4003                         {
4004                            same = false;
4005                            break;
4006                         }
4007                      }
4008                   }                  
4009                }
4010                if(same)
4011                {
4012                   if(type.type == noHeadClass || type.type == normalClass)
4013                   {
4014                      if(!((int (*)(void *, void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnCompare])(type, 
4015                         *(void **)((byte *)firstConfig.options + member.offset + member._class.offset),
4016                         *(void **)((byte *)nullOptions         + member.offset + member._class.offset)))
4017                         continue;
4018                   }
4019                   else
4020                   {
4021                      if(!((int (*)(void *, void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnCompare])(type, 
4022                         (byte *)firstConfig.options + member.offset + member._class.offset,
4023                         (byte *)nullOptions         + member.offset + member._class.offset))
4024                         continue;
4025                   }
4026
4027                   if(!project.options) project.options = { };
4028                   
4029                   /*if(type.type == noHeadClass || type.type == normalClass)
4030                   {
4031                      ((void (*)(void *, void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnCopy])(type, 
4032                         (byte *)project.options + member.offset + member._class.offset,
4033                         *(void **)((byte *)firstConfig.options + member.offset + member._class.offset));
4034                   }
4035                   else
4036                   {
4037                      void * address = (byte *)firstConfig.options + member.offset + member._class.offset;
4038                      // TOFIX: ListBox::SetData / OnCopy mess
4039                      ((void (*)(void *, void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnCopy])(type, 
4040                         (byte *)project.options + member.offset + member._class.offset,
4041                         (type.typeSize > 4) ? address : 
4042                            ((type.typeSize == 4) ? (void *)*(uint32 *)address : 
4043                               ((type.typeSize == 2) ? (void *)*(uint16*)address : 
4044                                  (void *)*(byte *)address )));                              
4045                   }*/
4046                   memcpy(
4047                      (byte *)project.options + member.offset + member._class.offset,
4048                      (byte *)firstConfig.options + member.offset + member._class.offset, type.typeSize);
4049
4050                   for(cfg : project.configurations)
4051                   {
4052                      if(cfg.options.targetType == staticLibrary)
4053                      {
4054                         int result;
4055                         
4056                         if(type.type == noHeadClass || type.type == normalClass)
4057                         {
4058                            result = ((int (*)(void *, void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnCompare])(type, 
4059                               *(void **)((byte *)firstConfig.options + member.offset + member._class.offset),
4060                               *(void **)((byte *)cfg.options         + member.offset + member._class.offset));
4061                         }
4062                         else
4063                         {
4064                            result = ((int (*)(void *, void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnCompare])(type, 
4065                               (byte *)firstConfig.options + member.offset + member._class.offset,
4066                               (byte *)cfg.options         + member.offset + member._class.offset);
4067                         }
4068                         if(result)
4069                            continue;
4070                      }
4071                      if(cfg != firstConfig)
4072                      {
4073                         if(type.type == noHeadClass || type.type == normalClass)
4074                         {
4075                            ((void (*)(void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnFree])(type, 
4076                               *(void **)((byte *)cfg.options + member.offset + member._class.offset));
4077                         }
4078                         else
4079                         {
4080                            ((void (*)(void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnFree])(type, 
4081                               (byte *)cfg.options + member.offset + member._class.offset);
4082                         }
4083                         memset((byte *)cfg.options + member.offset + member._class.offset, 0, type.typeSize);
4084                      }                     
4085                   }
4086                   memset((byte *)firstConfig.options + member.offset + member._class.offset, 0, type.typeSize);
4087                }
4088             }
4089          }
4090       }
4091       delete nullOptions;
4092
4093       // Compare Platform Specific Settings
4094       {
4095          bool same = true;
4096          for(cfg : project.configurations)
4097          {
4098             if(cfg != firstConfig && cfg.options.targetType != staticLibrary && (firstConfig.platforms || cfg.platforms) &&
4099                ((!firstConfig.platforms && cfg.platforms) || firstConfig.platforms.OnCompare(cfg.platforms)))
4100             {
4101                same = false;
4102                break;
4103             }
4104          }
4105          if(same && firstConfig.platforms)
4106          {
4107             for(cfg : project.configurations)
4108             {
4109                if(cfg.options.targetType == staticLibrary && firstConfig.platforms.OnCompare(cfg.platforms))
4110                   continue;
4111                if(cfg != firstConfig)
4112                {
4113                   cfg.platforms.Free();
4114                   delete cfg.platforms;
4115                }
4116             }
4117             project.platforms = firstConfig.platforms;
4118             firstConfig.platforms = null;
4119          }
4120       }
4121
4122       // Static libraries can't contain libraries
4123       for(cfg : project.configurations)
4124       {
4125          if(cfg.options.targetType == staticLibrary)
4126          {
4127             if(!cfg.options.libraries) cfg.options.libraries = { };
4128             cfg.options.libraries.Free();
4129          }
4130       }
4131    }
4132 }
4133
4134 Project LoadProject(char * filePath, char * activeConfigName)
4135 {
4136    Project project = null;
4137    File f = FileOpen(filePath, read);
4138    if(f)
4139    {
4140       project = LegacyBinaryLoadProject(f, filePath);
4141       if(!project)
4142       {
4143          JSONParser parser { f = f };
4144          JSONResult result = parser.GetObject(class(Project), &project);
4145          if(project)
4146          {
4147             char insidePath[MAX_LOCATION];
4148
4149             delete project.topNode.files;
4150             if(!project.files) project.files = { };
4151             project.topNode.files = project.files;
4152             project.resNode = project.topNode.Add(project, "Resources", project.topNode.files.last, resources, archiveFile, false);
4153             delete project.resNode.path;
4154             project.resNode.path = project.resourcesPath;
4155             project.resourcesPath = null;
4156             project.resNode.nodeType = (ProjectNodeType)-1;
4157             delete project.resNode.files;
4158             project.resNode.files = project.resources;
4159             project.files = null;
4160             project.resources = null;
4161             if(!project.configurations) project.configurations = { };
4162
4163             {
4164                char topNodePath[MAX_LOCATION];
4165                GetWorkingDir(topNodePath, sizeof(topNodePath)-1);
4166                MakeSlashPath(topNodePath);
4167                PathCatSlash(topNodePath, filePath);
4168                project.filePath = topNodePath;//filePath;
4169             }
4170
4171             project.topNode.FixupNode(insidePath);
4172          }
4173          delete parser;
4174       }
4175       if(!project)
4176          project = LegacyAsciiLoadProject(f, filePath);
4177
4178       delete f;
4179
4180       if(project)
4181       {
4182          if(!project.options) project.options = { };
4183          if(activeConfigName && activeConfigName[0] && project.configurations)
4184          {
4185             for(cfg : project.configurations)
4186             {
4187                if(!strcmpi(cfg.name, activeConfigName))
4188                {
4189                   project.config = cfg;
4190                   break;
4191                }
4192             }
4193          }
4194          if(!project.config && project.configurations)
4195             project.config = project.configurations.firstIterator.data;
4196
4197          if(!project.resNode)
4198          {
4199             project.resNode = project.topNode.Add(project, "Resources", project.topNode.files.last, resources, archiveFile, false);
4200          }
4201          
4202          if(!project.moduleName)
4203             project.moduleName = CopyString(project.name);
4204          if(project.config && 
4205             (!project.options || !project.options.targetFileName || !project.options.targetFileName[0]) &&
4206             (!project.config.options.targetFileName || !project.config.options.targetFileName[0]))
4207          {
4208             //delete project.config.options.targetFileName;
4209             
4210             project.options.targetFileName = /*CopyString(*/project.moduleName/*)*/;
4211             project.config.options.optimization = none;
4212             project.config.options.debug = true;
4213             //project.config.options.warnings = unset;
4214             project.config.options.memoryGuard = false;
4215             project.config.compilingModified = true;
4216             project.config.linkingModified = true;
4217          }
4218          else if(!project.topNode.name && project.config)
4219          {
4220             project.topNode.name = CopyString(project.config.options.targetFileName);
4221          }
4222
4223          /* // THIS IS NOW AUTOMATED WITH A project CHECK IN ProjectNode
4224          project.topNode.configurations = project.configurations;
4225          project.topNode.platforms = project.platforms;
4226          project.topNode.options = project.options;*/
4227       }
4228    }
4229    return project;
4230 }