1c9f9c15f02489f80a7cf17faf5c58e0cf160f94
[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 __attribute__((unused)) 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 #ifndef MAKEFILE_GENERATOR
46       IDESettings settings = (IDESettings)data;
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<const 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 { noPrint, objects, cObjects, symbols, imports, sources, resources, eCsources, rcSources };
410
411 define WorkspaceExtension = "ews";
412 define ProjectExtension = "epj";
413
414 define stringInFileIncludedFrom = "In file included from ";
415 define stringFrom =               "                 from ";
416
417 // chars refused for project name: windowsFileNameCharsNotAllowed + " &,."
418
419 //define gnuMakeCharsNeedEscaping = "$%";
420
421 //define windowsFileNameCharsNotAllowed = "*/:<>?\\\"|";
422 //define linuxFileNameCharsNotAllowed = "/";
423
424 //define windowsFileNameCharsNeedEscaping = " !%&'()+,;=[]^`{}~"; // "#$-.@_" are ok
425 //define linuxFileNameCharsNeedEscaping = " !\"$&'()*:;<=>?[\\`{|"; // "#%+,-.@]^_}~" are ok
426
427 // NOTES: - this function should get only unescaped unix style paths
428 //        - paths with literal $(somestring) in them are not supported
429 //          my_$(messed_up)_path would likely become my__path
430 void EscapeForMake(char * output, const char * input, bool hideSpace, bool allowVars, bool allowDblQuote)
431 {
432    char ch, *o = output;
433    const char *i = input;
434    bool inVar = false;
435 #ifdef _DEBUG
436    int len = strlen(input);
437    if(len && ((input[0] == '"' && input[len-1] == '"') || strchr(input, '\\') || strchr(input, 127) || (!allowDblQuote && strchr(input, '"'))))
438       PrintLn("Invalid input for EscapeForMake! -- ", input);
439 #endif
440    while((ch = *i++))
441    {
442       if(ch == '(')
443       {
444          if(i-1 != input && *(i-2) == '$' && allowVars)
445             inVar = true;
446          else
447             *o++ = '\\';
448       }
449       else if(ch == ')')
450       {
451          if(inVar == true && allowVars)
452             inVar = false;
453          else
454             *o++ = '\\';
455       }
456       else if(ch == '$' && *i != '(')
457          *o++ = '$';
458       else if(ch == '&')
459          *o++ = '\\';
460       else if(ch == '"')
461          *o++ = '\\';
462       if(ch == ' ')
463       {
464          if(hideSpace)
465             *o++ = 127;
466          else
467          {
468             *o++ = '\\';
469             *o++ = ch;
470          }
471       }
472       else
473          *o++ = ch;
474    }
475    *o = '\0';
476 }
477
478 void EscapeForMakeToFile(File output, char * input, bool hideSpace, bool allowVars, bool allowDblQuote)
479 {
480    char * buf = new char[strlen(input)*2+1];
481    EscapeForMake(buf, input, hideSpace, allowVars, allowDblQuote);
482    output.Print(buf);
483    delete buf;
484 }
485
486 void EscapeForMakeToDynString(DynamicString output, const char * input, bool hideSpace, bool allowVars, bool allowDblQuote)
487 {
488    char * buf = new char[strlen(input)*2+1];
489    EscapeForMake(buf, input, hideSpace, allowVars, allowDblQuote);
490    output.concat(buf);
491    delete buf;
492 }
493
494 int OutputFileList(File f, const char * name, Array<String> list, Map<String, int> varStringLenDiffs, const char * prefix)
495 {
496    int numOfBreaks = 0;
497    const int breakListLength = 1536;
498    const int breakLineLength = 78; // TODO: turn this into an option.
499
500    int c, len, itemCount = 0;
501    Array<int> breaks { };
502    if(list.count)
503    {
504       int charCount = 0;
505       MapNode<String, int> mn;
506       for(c=0; c<list.count; c++)
507       {
508          len = strlen(list[c]) + 3;
509          if(strstr(list[c], "$(") && varStringLenDiffs && varStringLenDiffs.count)
510          {
511             for(mn = varStringLenDiffs.root.minimum; mn; mn = mn.next)
512             {
513                if(strstr(list[c], mn.key))
514                   len += mn.value;
515             }
516          }
517          if(charCount + len > breakListLength)
518          {
519             breaks.Add(itemCount);
520             itemCount = 0;
521             charCount = len;
522          }
523          itemCount++;
524          charCount += len;
525       }
526       if(itemCount)
527          breaks.Add(itemCount);
528       numOfBreaks = breaks.count;
529    }
530
531    if(numOfBreaks > 1)
532    {
533       f.Printf("%s =%s%s", name, prefix ? " " : "", prefix ? prefix : "");
534       for(c=0; c<numOfBreaks; c++)
535          f.Printf(" $(%s%d)", name, c+1);
536       f.Puts("\n");
537    }
538    else
539       f.Printf("%s =%s%s", name, prefix ? " " : "", prefix ? prefix : "");
540
541    if(numOfBreaks)
542    {
543       int n, offset = 0;
544
545       for(c=0; c<numOfBreaks; c++)
546       {
547          if(numOfBreaks > 1)
548             f.Printf("%s%d =", name, c+1);
549
550          len = 3;
551          itemCount = breaks[c];
552          for(n=offset; n<offset+itemCount; n++)
553          {
554             if(false) // TODO: turn this into an option.
555             {
556                int itemLen = strlen(list[n]);
557                if(len > 3 && len + itemLen > breakLineLength)
558                {
559                   f.Printf(" \\\n\t%s", list[n]);
560                   len = 3;
561                }
562                else
563                {
564                   len += itemLen;
565                   f.Printf(" %s", list[n]);
566                }
567             }
568             else
569                f.Printf(" \\\n\t%s", list[n]);
570          }
571          offset += itemCount;
572          f.Puts("\n");
573       }
574       list.Free();
575       list.count = 0;
576    }
577    else
578       f.Puts("\n");
579    f.Puts("\n");
580    delete breaks;
581    return numOfBreaks;
582 }
583
584 void OutputFileListActions(File f, const char * name, int parts, const char * fileName)
585 {
586    if(parts > 1)
587    {
588       int c;
589       for(c=0; c<parts; c++)
590          f.Printf("\t$(call addtolistfile,$(%s%d),%s)\n", name, c+1, fileName);
591    }
592    else if(parts)
593    {
594       f.Printf("\t$(call addtolistfile,$(%s),%s)\n", name, fileName);
595    }
596 }
597
598 void OutputCleanActions(File f, const char * name, int parts)
599 {
600    if(parts > 1)
601    {
602       int c;
603       for(c=0; c<parts; c++)
604          f.Printf("\t$(call rm,$(_%s%d))\n", name, c+1);
605    }
606    else
607       f.Printf("\t$(call rm,$(_%s))\n", name);
608 }
609
610 enum LineOutputMethod { inPlace, newLine, lineEach };
611 enum StringOutputMethod { asIs, escape, escapePath};
612
613 enum ToolchainFlag { any, _D, _I, _isystem, _Wl, _L/*, _Wl-rpath*/ };
614 const String flagNames[ToolchainFlag] = { "", "-D", "-I", "-isystem ", "-Wl,", /*"-Wl,--library-path="*/"-L"/*, "-Wl,-rpath "*/ };
615 void OutputFlags(File f, ToolchainFlag flag, Array<String> list, LineOutputMethod lineMethod)
616 {
617    if(list.count)
618    {
619       if(lineMethod == newLine)
620          f.Puts(" \\\n\t");
621       for(item : list)
622       {
623          if(lineMethod == lineEach)
624             f.Puts(" \\\n\t");
625          f.Printf(" %s", flagNames[flag]);
626          if(flag != _D && flag != _Wl && flag != any)
627          {
628             char * tmp = new char[strlen(item)*2+1];
629             EscapeForMake(tmp, item, false, true, false);
630             f.Printf("$(call quote_path,%s)", tmp);
631             delete tmp;
632          }
633          else
634             EscapeForMakeToFile(f, item, false, true, true);
635       }
636    }
637 }
638
639 static void OutputLibraries(File f, Array<String> libraries)
640 {
641    for(item : libraries)
642    {
643       char ext[MAX_EXTENSION];
644       char temp[MAX_LOCATION];
645       char * s = item;
646       bool usedFunction = false;
647       GetExtension(item, ext);
648       if(!strcmp(ext, "o") || !strcmp(ext, "a"))
649          f.Puts(" ");
650       else
651       {
652          if(!strcmp(ext, "so") || !strcmp(ext, "dylib"))
653          {
654             if(!strncmp(item, "lib", 3))
655                strcpy(temp, item + 3);
656             else
657                strcpy(temp, item);
658             StripExtension(temp);
659             s = temp;
660          }
661          f.Puts(" \\\n\t$(call _L,");
662          usedFunction = true;
663       }
664       EscapeForMakeToFile(f, s, false, false, false);
665       if(usedFunction)
666          f.Puts(")");
667    }
668 }
669
670 void CamelCase(char * string)
671 {
672    if(string)
673    {
674       int c, len = strlen(string);
675       for(c=0; c<len && string[c] >= 'A' && string[c] <= 'Z'; c++)
676          string[c] = (char)tolower(string[c]);
677    }
678 }
679
680 CompilerConfig GetCompilerConfig()
681 {
682 #ifndef MAKEFILE_GENERATOR
683    CompilerConfig compiler = null;
684    if(ide && ide.workspace)
685       compiler = ideSettings.GetCompilerConfig(ide.workspace.compiler);
686    return compiler;
687 #else
688    incref defaultCompiler;
689    return defaultCompiler;
690 #endif
691 }
692
693 int GetBitDepth()
694 {
695 #ifdef MAKEFILE_GENERATOR
696    return 0; // todo: improve this somehow? add bit depth command line option?
697 #else
698    return ide.workspace.bitDepth;
699 #endif
700 }
701
702 define localTargetType = config && config.options && config.options.targetType ?
703             config.options.targetType : options && options.targetType ?
704             options.targetType : TargetTypes::executable;
705 define localWarnings = config && config.options && config.options.warnings ?
706             config.options.warnings : options && options.warnings ?
707             options.warnings : WarningsOption::unset;
708 define localDebug = config && config.options && config.options.debug ?
709             config.options.debug : options && options.debug ?
710             options.debug : SetBool::unset;
711 define localMemoryGuard = config && config.options && config.options.memoryGuard ?
712             config.options.memoryGuard : options && options.memoryGuard ?
713             options.memoryGuard : SetBool::unset;
714 define localNoLineNumbers = config && config.options && config.options.noLineNumbers ?
715             config.options.noLineNumbers : options && options.noLineNumbers ?
716             options.noLineNumbers : SetBool::unset;
717 define localProfile = config && config.options && config.options.profile ?
718             config.options.profile : options && options.profile ?
719             options.profile : SetBool::unset;
720 define localOptimization = config && config.options && config.options.optimization ?
721             config.options.optimization : options && options.optimization ?
722             options.optimization : OptimizationStrategy::none;
723 define localFastMath = config && config.options && config.options.fastMath ?
724             config.options.fastMath : options && options.fastMath ?
725             options.fastMath : SetBool::unset;
726 define localDefaultNameSpace = config && config.options && config.options.defaultNameSpace ?
727             config.options.defaultNameSpace : options && options.defaultNameSpace ?
728             options.defaultNameSpace : null;
729 define localStrictNameSpaces = config && config.options && config.options.strictNameSpaces ?
730             config.options.strictNameSpaces : options && options.strictNameSpaces ?
731             options.strictNameSpaces : SetBool::unset;
732 // TODO: I would rather have null here, check if it'll be ok, have the property return "" if required
733 define localTargetFileName = config && config.options && config.options.targetFileName ?
734             config.options.targetFileName : options && options.targetFileName ?
735             options.targetFileName : "";
736 define localTargetDirectory = config && config.options && config.options.targetDirectory && config.options.targetDirectory[0] ?
737             config.options.targetDirectory : options && options.targetDirectory && options.targetDirectory[0] ?
738             options.targetDirectory : null;
739 define settingsTargetDirectory = ideSettings && ideSettings.projectDefaultIntermediateObjDir &&
740             ideSettings.projectDefaultIntermediateObjDir[0] ?
741             ideSettings.projectDefaultIntermediateObjDir : defaultObjDirExpression;
742 define localObjectsDirectory = config && config.options && config.options.objectsDirectory && config.options.objectsDirectory[0] ?
743             config.options.objectsDirectory : options && options.objectsDirectory && options.objectsDirectory[0] ?
744             options.objectsDirectory : null;
745 define settingsObjectsDirectory = ideSettings && ideSettings.projectDefaultIntermediateObjDir &&
746             ideSettings.projectDefaultIntermediateObjDir[0] ?
747             ideSettings.projectDefaultIntermediateObjDir : defaultObjDirExpression;
748 define localConsole = config && config.options && config.options.console ?
749             config.options.console : options && options.console ?
750             options.console : SetBool::unset;
751 define localCompress = config && config.options && config.options.compress ?
752             config.options.compress : options && options.compress ?
753             options.compress : SetBool::unset;
754
755 define platformTargetType =
756          configPOs && configPOs.options && configPOs.options.targetType && configPOs.options.targetType != localTargetType ?
757                configPOs.options.targetType :
758          projectPOs && projectPOs.options && projectPOs.options.targetType && projectPOs.options.targetType != localTargetType ?
759                projectPOs.options.targetType : TargetTypes::unset;
760
761
762 const char * PlatformToMakefileTargetVariable(Platform platform)
763 {
764    return platform == win32 ? "WINDOWS_TARGET" :
765           platform == tux   ? "LINUX_TARGET"   :
766           platform == apple ? "OSX_TARGET"     :
767                               "ERROR_BAD_TARGET";
768 }
769
770 const char * TargetTypeToMakefileVariable(TargetTypes targetType)
771 {
772    return targetType == executable    ? "executable" :
773           targetType == sharedLibrary ? "sharedlib"  :
774           targetType == staticLibrary ? "staticlib"  :
775                                         "unknown";
776 }
777
778 // Move this to ProjectConfig? null vs Common to consider...
779 const char * GetConfigName(ProjectConfig config)
780 {
781    return config ? config.name : "Common";
782 }
783
784 public enum SingleFileCompileMode
785 {
786    normal, debugPrecompile, debugCompile, debugGenerateSymbols, cObject;
787
788    property bool eC_ToolsDebug { get { return this == debugCompile || this == debugGenerateSymbols || this == debugPrecompile; } }
789 };
790
791 class Project : struct
792 {
793    class_no_expansion;  // To use Find on the Container<Project> in Workspace::projects
794                         // We might want to tweak this default behavior of regular classes ?
795                         // Expansion/the current default kind of Find matching we want for things like BitmapResource, FontResource (Also regular classes)
796 public:
797    float version;
798    String moduleName;
799
800    property const char * moduleVersion
801    {
802       set { delete moduleVersion; if(value && value[0]) moduleVersion = CopyString(value); } // TODO: use CopyString function that filters chars
803       get { return moduleVersion ? moduleVersion : ""; }                                     //       version number should only use digits and dots
804       isset { return moduleVersion != null && moduleVersion[0]; }                            //       add leading/trailing 0 if value start/ends with dot(s)
805    }
806
807    property const char * description
808    {
809       set { delete description; if(value && value[0]) description = CopyString(value); }
810       get { return description ? description : ""; }
811       isset { return description != null && description[0]; }
812    }
813
814    property const char * license
815    {
816       set { delete license; if(value && value[0]) license = CopyString(value); }
817       get { return license ? license : ""; }
818       isset { return license != null && license[0]; }
819    }
820
821    property const char * compilerConfigsDir
822    {
823       set { delete compilerConfigsDir; if(value && value[0]) compilerConfigsDir = CopyString(value); }
824       get { return compilerConfigsDir ? compilerConfigsDir : ""; }
825       isset { return compilerConfigsDir && compilerConfigsDir[0]; }
826    }
827
828    property ProjectOptions options { get { return options; } set { options = value; } isset { return options && !options.isEmpty; } }
829    property Array<PlatformOptions> platforms
830    {
831       get { return platforms; }
832       set
833       {
834          if(platforms) { platforms.Free(); delete platforms; }
835          if(value)
836          {
837             List<PlatformOptions> empty { };
838             Iterator<PlatformOptions> it { value };
839             platforms = value;
840             for(p : platforms; !p.options || p.options.isEmpty) empty.Add(p);
841             for(p : empty; it.Find(p)) platforms.Delete(it.pointer);
842             delete empty;
843          }
844       }
845       isset
846       {
847          if(platforms)
848          {
849             for(p : platforms)
850             {
851                if(p.options && !p.options.isEmpty)
852                   return true;
853             }
854          }
855          return false;
856       }
857    }
858    List<ProjectConfig> configurations;
859    LinkList<ProjectNode> files;
860    String resourcesPath;
861    LinkList<ProjectNode> resources;
862
863 private:
864    // topNode.name holds the file name (.epj)
865    ProjectOptions options;
866    Array<PlatformOptions> platforms;
867    ProjectNode topNode { type = project, icon = epjFile, files = LinkList<ProjectNode>{ }, project = this };
868    ProjectNode resNode;
869
870    ProjectConfig config;
871    String filePath;
872    // This is the file name stripped of the epj extension
873    // It should NOT be edited, saved or loaded anywhere
874    String name;
875
876    String description;
877    String license;
878    String compilerConfigsDir;
879    String moduleVersion;
880
881    String lastBuildConfigName;
882    String lastBuildCompilerName;
883
884    Map<String, Map<String, NameCollisionInfo>> configsNameCollisions { };
885
886 #ifndef MAKEFILE_GENERATOR
887    FileMonitor fileMonitor
888    {
889       this, FileChange { modified = true };
890       bool OnFileNotify(FileChange action, const char * param)
891       {
892          fileMonitor.StopMonitoring();
893          if(OnProjectModified(action, param))
894             fileMonitor.StartMonitoring();
895          return true;
896       }
897    };
898
899    bool StartMonitoring()
900    {
901       fileMonitor.fileName = filePath;
902       fileMonitor.StartMonitoring();
903       return true;
904    }
905
906    bool StopMonitoring()
907    {
908       fileMonitor.StopMonitoring();
909       return true;
910    }
911
912    bool OnProjectModified(FileChange fileChange, const char * param)
913    {
914       char temp[4096];
915       sprintf(temp, $"The project %s was modified by another application.\n"
916             "Would you like to reload it and lose your changes?", name);
917       if(MessageBox { type = yesNo, master = ide,
918             text = $"Project has been modified", contents = temp }.Modal() == yes)
919       {
920          Project project = LoadProject(filePath, config ? config.name : null);
921          if(project)
922          {
923             ProjectView projectView = ide.projectView;
924             DataRow prev = topNode.row ? topNode.row.previous : null;
925             FileMonitor fm = fileMonitor;
926             bool confirmation = true;
927
928             if(projectView)
929             {
930                if(projectView.projectSettingsDialog)
931                {
932                   confirmation = projectView.projectSettingsDialog.CloseConfirmation(true);
933                   if(confirmation)
934                      projectView.projectSettingsDialog.Destroy(0);
935                }
936                if(confirmation)
937                   projectView.DeleteNode(topNode);
938             }
939             if(confirmation)
940             {
941                *this = *project;
942                delete fileMonitor;
943                fileMonitor = fm;
944                topNode.project = this;
945
946                if(projectView)
947                {
948                   CompilerConfig compiler = ideSettings.GetCompilerConfig(projectView.workspace.compiler);
949                   projectView.AddNode(topNode, null);
950                   topNode.row.Move(prev);
951
952                   projectView.ShowOutputBuildLog(true);
953                   projectView.DisplayCompiler(compiler, false);
954                   projectView.ProjectUpdateMakefileForAllConfigs(this);
955                   delete compiler;
956                }
957                eSystem_Delete(project);
958             }
959             else
960                delete project;
961          }
962          return true;
963       }
964       return !ide.destroyed;
965    }
966
967 #endif
968
969    // This frees contents without freeing the instance
970    // For use from destructor and for file monitor reloading
971    // (To work around JSON loader (LoadProject) always returning a new instance)
972    void Free()
973    {
974       if(platforms) { platforms.Free(); delete platforms; }
975       if(configurations) { configurations.Free(); delete configurations; }
976       if(files) { files.Free(); delete files; }
977       if(resources) { resources.Free(); delete resources; }
978       delete options;
979       delete resourcesPath;
980
981       delete description;
982       delete license;
983       delete compilerConfigsDir;
984       delete moduleName;
985       delete moduleVersion;
986       delete filePath;
987       delete topNode;
988       delete name;
989       delete lastBuildConfigName;
990       delete lastBuildCompilerName;
991       for(map : configsNameCollisions)
992          map.Free();
993       configsNameCollisions.Free();
994    }
995
996    ~Project()
997    {
998       /* // THIS IS NOW AUTOMATED WITH A project CHECK IN ProjectNode
999       topNode.configurations = null;
1000       topNode.platforms = null;
1001       topNode.options = null;
1002       */
1003       Free();
1004    }
1005
1006    property ProjectConfig config
1007    {
1008       set
1009       {
1010          config = value;
1011          delete topNode.info;
1012          topNode.info = CopyString(GetConfigName(config));
1013       }
1014    }
1015
1016    property const char * filePath
1017    {
1018       set
1019       {
1020          if(value)
1021          {
1022             char string[MAX_LOCATION];
1023             GetLastDirectory(value, string);
1024             delete topNode.name;
1025             topNode.name = CopyString(string);
1026             StripExtension(string);
1027             delete name;
1028             name = CopyString(string);
1029             StripLastDirectory(value, string);
1030             delete topNode.path;
1031             topNode.path = CopyString(string);
1032             delete filePath;
1033             filePath = CopyString(value);
1034          }
1035       }
1036    }
1037
1038    ProjectConfig GetConfig(const char * configName)
1039    {
1040       ProjectConfig result = null;
1041       if(configName && configName[0] && configurations.count)
1042       {
1043          for(cfg : configurations; !strcmpi(cfg.name, configName))
1044          {
1045             result = cfg;
1046             break;
1047          }
1048       }
1049       return result;
1050    }
1051
1052    ProjectNode FindNodeByObjectFileName(const char * fileName, IntermediateFileType type, bool dotMain, ProjectConfig config, const char * objectFileExt)
1053    {
1054       ProjectNode result;
1055       const char * cfgName;
1056       if(!config)
1057          config = this.config;
1058       cfgName = config ? config.name : "";
1059       if(!configsNameCollisions[cfgName])
1060          ProjectLoadLastBuildNamesInfo(this, config);
1061       result = topNode.FindByObjectFileName(fileName, type, dotMain, configsNameCollisions[cfgName], objectFileExt);
1062       return result;
1063    }
1064
1065    TargetTypes GetTargetType(ProjectConfig config)
1066    {
1067       TargetTypes targetType = localTargetType;
1068       return targetType;
1069    }
1070
1071    bool GetTargetTypeIsSetByPlatform(ProjectConfig config)
1072    {
1073       Platform platform;
1074       for(platform = (Platform)1; platform < Platform::enumSize; platform++)
1075       {
1076          PlatformOptions projectPOs, configPOs;
1077          MatchProjectAndConfigPlatformOptions(config, platform, &projectPOs, &configPOs);
1078          if(platformTargetType)
1079             return true;
1080       }
1081       return false;
1082    }
1083
1084    const char * GetObjDirExpression(ProjectConfig config)
1085    {
1086       // TODO: Support platform options
1087       const char * expression = localObjectsDirectory;
1088       if(!expression)
1089          expression = settingsObjectsDirectory;
1090       return expression;
1091    }
1092
1093    DirExpression GetObjDir(CompilerConfig compiler, ProjectConfig config, int bitDepth)
1094    {
1095       const char * expression = GetObjDirExpression(config);
1096       DirExpression objDir { type = intermediateObjectsDir };
1097       objDir.Evaluate(expression, this, compiler, config, bitDepth);
1098       return objDir;
1099    }
1100
1101    const char * GetTargetDirExpression(ProjectConfig config)
1102    {
1103       // TODO: Support platform options
1104       const char * expression = localTargetDirectory;
1105       if(!expression)
1106          expression = settingsTargetDirectory;
1107       return expression;
1108    }
1109
1110    DirExpression GetTargetDir(CompilerConfig compiler, ProjectConfig config, int bitDepth)
1111    {
1112       const char * expression = GetTargetDirExpression(config);
1113       DirExpression targetDir { type = DirExpressionType::targetDir /*intermediateObjectsDir*/};
1114       targetDir.Evaluate(expression, this, compiler, config, bitDepth);
1115       return targetDir;
1116    }
1117
1118    WarningsOption GetWarnings(ProjectConfig config)
1119    {
1120       WarningsOption warnings = localWarnings;
1121       return warnings;
1122    }
1123
1124    bool GetDebug(ProjectConfig config)
1125    {
1126       SetBool debug = localDebug;
1127       return debug == true;
1128    }
1129
1130    bool GetMemoryGuard(ProjectConfig config)
1131    {
1132       SetBool memoryGuard = localMemoryGuard;
1133       return memoryGuard == true;
1134    }
1135
1136    bool GetNoLineNumbers(ProjectConfig config)
1137    {
1138       SetBool noLineNumbers = localNoLineNumbers;
1139       return noLineNumbers == true;
1140    }
1141
1142    bool GetProfile(ProjectConfig config)
1143    {
1144       SetBool profile = localProfile;
1145       return profile == true;
1146    }
1147
1148    OptimizationStrategy GetOptimization(ProjectConfig config)
1149    {
1150       OptimizationStrategy optimization = localOptimization;
1151       return optimization;
1152    }
1153
1154    bool GetFastMath(ProjectConfig config)
1155    {
1156       SetBool fastMath = localFastMath;
1157       return fastMath == true;
1158    }
1159
1160    const String GetDefaultNameSpace(ProjectConfig config)
1161    {
1162       const String defaultNameSpace = localDefaultNameSpace;
1163       return defaultNameSpace;
1164    }
1165
1166    bool GetStrictNameSpaces(ProjectConfig config)
1167    {
1168       SetBool strictNameSpaces = localStrictNameSpaces;
1169       return strictNameSpaces == true;
1170    }
1171
1172    const String GetTargetFileName(ProjectConfig config)
1173    {
1174       const String targetFileName = localTargetFileName;
1175       return targetFileName;
1176    }
1177
1178    //String targetDirectory;
1179    //String objectsDirectory;
1180    bool GetConsole(ProjectConfig config)
1181    {
1182       SetBool console = localConsole;
1183       return console == true;
1184    }
1185
1186    bool GetCompress(ProjectConfig config)
1187    {
1188       SetBool compress = localCompress;
1189       return compress == true;
1190    }
1191    //SetBool excludeFromBuild;
1192
1193    bool GetConfigIsInActiveDebugSession(ProjectConfig config)
1194    {
1195 #ifndef MAKEFILE_GENERATOR
1196       return ide.project == this && ide.debugger && ide.debugger.prjConfig == config && ide.debugger.isActive;
1197 #else
1198       return false;
1199 #endif
1200    }
1201
1202    bool GetConfigIsInDebugSession(ProjectConfig config)
1203    {
1204 #ifndef MAKEFILE_GENERATOR
1205       return ide.project == this && ide.debugger && ide.debugger.prjConfig == config && ide.debugger.isPrepared;
1206 #else
1207       return false;
1208 #endif
1209    }
1210
1211    void SetPath(bool projectsDirs, CompilerConfig compiler, ProjectConfig config, int bitDepth)
1212    {
1213 #ifndef MAKEFILE_GENERATOR
1214       ide.SetPath(projectsDirs, compiler, config, bitDepth);
1215 #endif
1216    }
1217
1218 #ifndef MAKEFILE_GENERATOR
1219    bool Save(const char * fileName)
1220    {
1221       File f;
1222       /*char output[MAX_LOCATION];
1223        ChangeExtension(fileName, "json", output);
1224       f = FileOpen(output, write);*/
1225       f = FileOpen(fileName, write);
1226       if(f)
1227       {
1228          files = topNode.files;
1229          resources = resNode.files;
1230          resourcesPath = resNode.path;
1231
1232          files.Remove(resNode);
1233          version = 0.2f;
1234
1235          WriteJSONObject(f, class(Project), this, 0);
1236
1237          files.Add(resNode);
1238
1239          files = null;
1240          resources = null;
1241          resourcesPath = null;
1242          delete f;
1243       }
1244       return true;
1245    }
1246 #endif
1247
1248    void CatTargetFileName(char * string, CompilerConfig compiler, ProjectConfig config)
1249    {
1250       TargetTypes targetType = GetTargetType(config);
1251       const String targetFileName = GetTargetFileName(config);
1252       if(targetType == staticLibrary)
1253       {
1254          PathCatSlash(string, "lib");
1255          strcat(string, targetFileName);
1256       }
1257       else if(compiler.targetPlatform != win32 && targetType == sharedLibrary)
1258       {
1259          PathCatSlash(string, "lib");
1260          strcat(string, targetFileName);
1261       }
1262       else
1263          PathCatSlash(string, targetFileName);
1264
1265       switch(targetType)
1266       {
1267          case executable:
1268             if(compiler.targetPlatform == win32)
1269                strcat(string, ".exe");
1270             break;
1271          case sharedLibrary:
1272             if(compiler.targetPlatform == win32)
1273                strcat(string, ".dll");
1274             else if(compiler.targetPlatform == apple)
1275                strcat(string, ".dylib");
1276             else
1277                strcat(string, ".so");
1278             if(compiler.targetPlatform == tux && __runtimePlatform == tux && moduleVersion && moduleVersion[0])
1279             {
1280                strcat(string, ".");
1281                strcat(string, moduleVersion);
1282             }
1283             break;
1284          case staticLibrary:
1285             strcat(string, ".a");
1286             break;
1287       }
1288    }
1289
1290    bool GetProjectCompilerConfigsDir(char * cfDir, bool replaceSpaces, bool makeRelative)
1291    {
1292       bool result = false;
1293       char temp[MAX_LOCATION];
1294       strcpy(cfDir, topNode.path);
1295       if(compilerConfigsDir && compilerConfigsDir[0])
1296       {
1297          PathCatSlash(cfDir, compilerConfigsDir);
1298          result = true;
1299       }
1300       if(makeRelative)
1301       {
1302          strcpy(temp, cfDir);
1303          // Using a relative path makes it less likely to run into spaces issues
1304          // Even with escaped spaces, there still seems to be issues including a config file
1305          // in a path containing spaces
1306
1307          MakePathRelative(temp, topNode.path, cfDir);
1308       }
1309
1310       if(cfDir && cfDir[0] && cfDir[strlen(cfDir)-1] != '/')
1311          strcat(cfDir, "/");
1312       if(replaceSpaces)
1313       {
1314          strcpy(temp, cfDir);
1315          ReplaceSpaces(cfDir, temp);
1316       }
1317       return result;
1318    }
1319
1320    bool GetIDECompilerConfigsDir(char * cfDir, bool replaceSpaces, bool makeRelative)
1321    {
1322       char temp[MAX_LOCATION];
1323       bool result = false;
1324       strcpy(cfDir, topNode.path);
1325       if(ideSettings && ideSettings.compilerConfigsDir && ideSettings.compilerConfigsDir[0])
1326       {
1327          PathCatSlash(cfDir, ideSettings.compilerConfigsDir);
1328          result = true;
1329       }
1330       else
1331       {
1332          // Default to <ProjectDir>/.configs if unset
1333          PathCatSlash(cfDir, ".configs");
1334          result = true;
1335       }
1336       if(makeRelative)
1337       {
1338          strcpy(temp, cfDir);
1339          // Using a relative path makes it less likely to run into spaces issues
1340          // Even with escaped spaces, there still seems to be issues including a config file
1341          // in a path containing spaces
1342          if(IsPathInsideOf(cfDir, topNode.path))
1343             MakePathRelative(temp, topNode.path, cfDir);
1344       }
1345       if(cfDir && cfDir[0] && cfDir[strlen(cfDir)-1] != '/')
1346          strcat(cfDir, "/");
1347       if(replaceSpaces)
1348       {
1349          strcpy(temp, cfDir);
1350          ReplaceSpaces(cfDir, temp);
1351       }
1352       return result;
1353    }
1354
1355    void CatMakeFileName(char * string, ProjectConfig config)
1356    {
1357       char projectName[MAX_LOCATION];
1358       strcpy(projectName, name);
1359       sprintf(string, "%s%s%s.Makefile", projectName, config ? "-" : "", config ? config.name : "");
1360    }
1361
1362 #ifndef MAKEFILE_GENERATOR
1363    ProjectNode GetObjectFileNode(const char * filePath, const char * objectFileExt)
1364    {
1365       ProjectNode node = null;
1366       char ext[MAX_EXTENSION];
1367       GetExtension(filePath, ext);
1368       if(ext[0])
1369       {
1370          IntermediateFileType type = IntermediateFileType::FromExtension(ext);
1371          if(type)
1372          {
1373             char fileName[MAX_FILENAME];
1374             GetLastDirectory(filePath, fileName);
1375             if(fileName[0])
1376             {
1377                DotMain dotMain = DotMain::FromFileName(fileName);
1378                node = FindNodeByObjectFileName(fileName, type, dotMain, null, objectFileExt);
1379             }
1380          }
1381       }
1382       return node;
1383    }
1384
1385    bool GetAbsoluteFromRelativePath(const char * relativePath, char * absolutePath, const char * objectFileExt)
1386    {
1387       ProjectNode node = topNode.FindWithPath(relativePath, false);
1388       if(!node)
1389          node = GetObjectFileNode(relativePath, objectFileExt);
1390       if(node)
1391       {
1392          strcpy(absolutePath, node.project.topNode.path);
1393          PathCat(absolutePath, relativePath);
1394          MakeSlashPath(absolutePath);
1395       }
1396       return node != null;
1397    }
1398
1399    void MarkChanges(ProjectNode node)
1400    {
1401       for(cfg : topNode.configurations)
1402       {
1403          ProjectConfig c = null;
1404          for(i : node.configurations; !strcmpi(i.name, cfg.name)) { c = i; break; }
1405
1406          if(c && ((c.options && cfg.options && cfg.options.console != c.options.console) ||
1407                (!c.options || !cfg.options)))
1408             cfg.symbolGenModified = true;
1409          if(c && ((c.options && cfg.options &&
1410                ( (cfg.options.libraries && c.options.libraries && cfg.options.libraries.OnCompare(c.options.libraries)) || (!cfg.options.libraries || !c.options.libraries)) )
1411             || (!c.options || !cfg.options)))
1412             cfg.linkingModified = true;
1413
1414          cfg.makingModified = true;
1415       }
1416    }
1417
1418    void ModifiedAllConfigs(bool making, bool compiling, bool linking, bool symbolGen)
1419    {
1420       Map<String, NameCollisionInfo> cfgNameCollision;
1421       MapIterator<const String, Map<String, NameCollisionInfo>> it { map = configsNameCollisions };
1422       if(it.Index("", false))
1423       {
1424          cfgNameCollision = it.data;
1425          cfgNameCollision.Free();
1426          delete cfgNameCollision;
1427          it.Remove();
1428       }
1429       for(cfg : configurations)
1430       {
1431          if(making)
1432          {
1433             cfg.makingModified = true;
1434             if(it.Index(cfg.name, false))
1435             {
1436                cfgNameCollision = it.data;
1437                cfgNameCollision.Free();
1438                delete cfgNameCollision;
1439                it.Remove();
1440             }
1441          }
1442          if(compiling)
1443             cfg.compilingModified = true;
1444          if(linking)
1445             cfg.linkingModified = true;
1446          if(symbolGen)
1447             cfg.symbolGenModified = true;
1448       }
1449       if(compiling || linking)
1450       {
1451          ide.projectView.modifiedDocument = true;
1452          ide.workspace.modified = true;
1453       }
1454    }
1455
1456    void RotateActiveConfig(bool forward, bool syncAllProjects)
1457    {
1458       if(configurations.first && configurations.last != configurations.first)
1459       {
1460          Iterator<ProjectConfig> cfg { configurations };
1461          while(forward ? cfg.Next() : cfg.Prev())
1462             if(cfg.data == config)
1463                break;
1464
1465          if(forward)
1466          {
1467             if(!cfg.Next())
1468                cfg.Next();
1469          }
1470          else
1471          {
1472             if(!cfg.Prev())
1473                cfg.Prev();
1474          }
1475
1476          if(syncAllProjects)
1477             ide.workspace.SelectActiveConfig(cfg.data.name);
1478          else
1479          {
1480             property::config = cfg.data;
1481             ide.UpdateToolBarActiveConfigs(true);
1482             ide.workspace.modified = true;
1483             ide.projectView.Update(null);
1484          }
1485       }
1486    }
1487
1488    bool ProcessPipeOutputRaw(DualPipe f)
1489    {
1490       char line[65536];
1491       while(!f.Eof() && !ide.projectView.stopBuild)
1492       {
1493          bool result = true;
1494          double lastTime = GetTime();
1495          bool wait = true;
1496          while(result)
1497          {
1498             if((result = f.Peek()) && (result = f.GetLine(line, sizeof(line)-1)))
1499             {
1500                ide.outputView.buildBox.Logf("%s\n", line);
1501             }
1502             if(GetTime() - lastTime > 1.0 / PEEK_RESOLUTION) break;
1503          }
1504          //printf("Processing Input...\n");
1505          if(app.ProcessInput(true))
1506             wait = false;
1507          app.UpdateDisplay();
1508          if(wait)
1509          {
1510             //printf("Waiting...\n");
1511             app.Wait();
1512          }
1513          //if(!result) Sleep(1.0 / PEEK_RESOLUTION);
1514       }
1515       if(ide.projectView.stopBuild)
1516       {
1517          ide.outputView.buildBox.Logf($"\nBuild cancelled by user.\n", line);
1518          f.Terminate();
1519       }
1520       return !ide.projectView.stopBuild;
1521    }
1522
1523    bool ProcessBuildPipeOutput(DualPipe f, DirExpression objDirExp, BuildType buildType, List<ProjectNode> onlyNodes,
1524       CompilerConfig compiler, ProjectConfig config, int bitDepth)
1525    {
1526       char line[65536];
1527       int linePos = 0;
1528       bool compiling = false, linking = false, precompiling = false;
1529       int compilingEC = 0;
1530       int numErrors = 0, numWarnings = 0;
1531       bool loggedALine = false;
1532       int lenMakeCommand = strlen(compiler.makeCommand);
1533       int testLen = 0;
1534       const char * t, * s, * s2;
1535       char moduleName[MAX_FILENAME];
1536       const char * gnuToolchainPrefix = compiler.gnuToolchainPrefix ? compiler.gnuToolchainPrefix : "";
1537
1538       DynamicString test { };
1539       DynamicString ecp { };
1540       DynamicString ecc { };
1541       DynamicString ecs { };
1542       DynamicString ear { };
1543       DynamicString prefix { };
1544       DynamicString cpp { };
1545       DynamicString cc { };
1546       DynamicString cxx { };
1547       DynamicString strip { };
1548       DynamicString ar { };
1549       DynamicString windres { };
1550
1551       /*
1552       if(bitDepth == 64 && compiler.targetPlatform == win32)
1553          gnuToolchainPrefix = "x86_64-w64-mingw32-";
1554       else if(bitDepth == 32 && compiler.targetPlatform == win32)
1555          gnuToolchainPrefix = "i686-w64-mingw32-";
1556       */
1557       ecp.concatx(compiler.ecpCommand, " ");
1558       ecc.concatx(compiler.eccCommand, " ");
1559       ecs.concatx(compiler.ecsCommand, " ");
1560       ear.concatx(compiler.earCommand, " ");
1561
1562       prefix.concatx(
1563             compiler.ccacheEnabled ? "ccache " : "",
1564             compiler.distccEnabled ? "distcc " : "",
1565             gnuToolchainPrefix);
1566
1567       cpp.concatx((String)prefix, compiler.cppCommand, " ");
1568       cc.concatx((String)prefix, compiler.ccCommand,  " ");
1569       cxx.concatx((String)prefix, compiler.cxxCommand, " ");
1570
1571       strip.concatx(gnuToolchainPrefix, "strip ");
1572       ar.concatx(gnuToolchainPrefix, "ar rcs");
1573       windres.concatx(gnuToolchainPrefix, "windres ");
1574
1575       testLen = Max(testLen, ecp.size);
1576       testLen = Max(testLen, ecc.size);
1577       testLen = Max(testLen, ecs.size);
1578       testLen = Max(testLen, ear.size);
1579       testLen = Max(testLen, cpp.size);
1580       testLen = Max(testLen, cc.size);
1581       testLen = Max(testLen, cxx.size);
1582       testLen = Max(testLen, strip.size);
1583       testLen = Max(testLen, ar.size);
1584       testLen = Max(testLen, windres.size);
1585       testLen = Max(testLen, strlen("mkdir "));
1586       testLen++;
1587
1588       while(!f.Eof() && !ide.projectView.stopBuild)
1589       {
1590          double lastTime = GetTime();
1591          bool wait = true;
1592          while(!f.Eof() && !ide.projectView.stopBuild)
1593          {
1594             int nChars;
1595             bool lineDone = f.GetLinePeek(line + linePos, sizeof(line)-linePos-1, &nChars);
1596             if(!lineDone)
1597             {
1598                linePos += nChars;
1599                Sleep(0.5 / PEEK_RESOLUTION);
1600             }
1601             else
1602             {
1603                linePos = 0;
1604                if(line[0])
1605                {
1606                   const char * message = null;
1607                   const char * inFileIncludedFrom = strstr(line, stringInFileIncludedFrom);
1608                   const char * from = strstr(line, stringFrom);
1609                   test.copyLenSingleBlankReplTrim(line, ' ', true, testLen);
1610                   if((t = strstr(line, (s=": recipe for target"))) && (t = strstr(t+strlen(s), (s2 = " failed"))) && (t+strlen(s2))[0] == '\0')
1611                      ; // ignore this new gnu make error but what is it about?
1612                   else if(strstr(line, compiler.makeCommand) == line && line[lenMakeCommand] == ':')
1613                   {
1614                      const char * moduleBackTick = strstr(line, "No rule to make target `");
1615                      const char * module = moduleBackTick ? moduleBackTick : strstr(line, "No rule to make target '");
1616                      if(module)
1617                      {
1618                         char * end;
1619                         module = strchr(module, moduleBackTick ? '`' : '\'') + 1;
1620                         end = strchr(module, '\'');
1621                         if(end)
1622                         {
1623                            *end = '\0';
1624                            ide.outputView.buildBox.Logf($"   %s: No such file or directory\n", module);
1625                            // ide.outputView.buildBox.Logf("error: %s\n   No such file or directory\n", module);
1626                            numErrors++;
1627                         }
1628                      }
1629                      //else
1630                      //{
1631                         //ide.outputView.buildBox.Logf("error: %s\n", line);
1632                         //numErrors++;
1633                      //}
1634                   }
1635                   else if(strstr(test, "mkdir ") == test);
1636                   else if((t = strstr(line, "cd ")) && (t = strstr(line, "type ")) && (t = strstr(line, "nul ")) && (t = strstr(line, "copy ")) && (t = strstr(line, "cd ")));
1637                   else if(strstr(test, ear) == test);
1638                   else if(strstr(test, strip) == test);
1639                   else if(strstr(test, cc) == test || strstr(test, cxx) == test || strstr(test, ecp) == test || strstr(test, ecc) == test)
1640                   {
1641                      char * module = null;
1642                      bool isPrecomp = false;
1643                      bool gotCC = false;
1644
1645                      if(strstr(test, cc) == test || strstr(test, cxx) == test)
1646                      {
1647                         module = strstr(line, " -c ");
1648                         if(module) module += 4;
1649                         gotCC = true;
1650                      }
1651                      else if(strstr(test, ecc) == test)
1652                      {
1653                         module = strstr(line, " -c ");
1654                         if(module) module += 4;
1655                         //module = line + 3;
1656                         // Don't show GCC warnings about generated C code because it does not compile clean yet...
1657                         compilingEC = 3;//2;
1658                         gotCC = true;
1659                      }
1660                      else if(strstr(test, ecp) == test)
1661                      {
1662                         // module = line + 8;
1663                         module = strstr(line, " -c ");
1664                         if(module) module += 4;
1665                         isPrecomp = true;
1666                         compilingEC = 0;
1667                         gotCC = true;
1668                      }
1669
1670                      loggedALine = true;
1671
1672                      if(module)
1673                      {
1674                         char * tokens[1];
1675                         if(!compiling && !isPrecomp)
1676                         {
1677                            ide.outputView.buildBox.Logf($"Compiling...\n");
1678                            compiling = true;
1679                         }
1680                         else if(!precompiling && isPrecomp)
1681                         {
1682                            ide.outputView.buildBox.Logf($"Generating symbols...\n");
1683                            precompiling = true;
1684                         }
1685                         Tokenize(module, 1, tokens, forArgsPassing/*(BackSlashEscaping)true*/);
1686                         GetLastDirectory(tokens[0], moduleName);
1687                         ide.outputView.buildBox.Logf("%s\n", moduleName);
1688                      }
1689                      else if((module = strstr(line, " -o ")))
1690                      {
1691                         compiling = false;
1692                         precompiling = false;
1693                         linking = true;
1694                         ide.outputView.buildBox.Logf($"Linking...\n");
1695                      }
1696                      else
1697                      {
1698                         ide.outputView.buildBox.Logf("%s\n", line);
1699                         if(strstr(line, "warning:") || strstr(line, "note:"))
1700                            numWarnings++;
1701                         else if(!gotCC && !strstr(line, "At top level") && !strstr(line, "In file included from") && !strstr(line, stringFrom))
1702                            numErrors++;
1703                      }
1704
1705                      if(compilingEC) compilingEC--;
1706                   }
1707                   else if(strstr(test, windres) == test)
1708                   {
1709                      char * module;
1710                      module = strstr(line, " ");
1711                      if(module) module++;
1712                      if(module)
1713                      {
1714                         char * tokens[1];
1715                         char * dashF = strstr(module, "-F ");
1716                         if(dashF)
1717                         {
1718                            dashF+= 3;
1719                            while(*dashF && *dashF != ' ') dashF++;
1720                            while(*dashF && *dashF == ' ') dashF++;
1721                            module = dashF;
1722                         }
1723                         Tokenize(module, 1, tokens, forArgsPassing/*(BackSlashEscaping)true*/);
1724                         GetLastDirectory(module, moduleName);
1725                         ide.outputView.buildBox.Logf("%s\n", moduleName);
1726                      }
1727                   }
1728                   else if(strstr(test, ar) == test)
1729                      ide.outputView.buildBox.Logf($"Building library...\n");
1730                   else if(strstr(test, ecs) == test)
1731                      ide.outputView.buildBox.Logf($"Writing symbol loader...\n");
1732                   else
1733                   {
1734                      if(linking || compiling || precompiling)
1735                      {
1736                         const char * start = inFileIncludedFrom ? inFileIncludedFrom + strlen(stringInFileIncludedFrom) : from ? from + strlen(stringFrom) : line;
1737                         const char * colon = strstr(start, ":"); //, * bracket;
1738                         if(colon && (colon[1] == '/' || colon[1] == '\\'))
1739                            colon = strstr(colon + 1, ":");
1740                         if(colon)
1741                         {
1742                            const char * sayError = "";
1743                            char moduleName[MAX_LOCATION], temp[MAX_LOCATION];
1744                            char * pointer;
1745                            char * error;
1746                            int len = (int)(colon - start);
1747                            char ext[MAX_EXTENSION];
1748                            len = Min(len, MAX_LOCATION-1);
1749                            // Don't be mistaken by the drive letter colon
1750                            // Cut module name
1751                            // TODO: need to fix colon - line gives char *
1752                            // warning: incompatible expression colon - line (char *); expected int
1753                            /*
1754                            strncpy(moduleName, line, (int)(colon - line));
1755                            moduleName[colon - line] = '\0';
1756                            */
1757                            strncpy(moduleName, start, len);
1758                            moduleName[len] = '\0';
1759                            // Remove stuff in brackets
1760                            //bracket = strstr(moduleName, "(");
1761                            //if(bracket) *bracket = '\0';
1762
1763                            GetLastDirectory(moduleName, temp);
1764                            GetExtension(temp, ext);
1765
1766                            if(linking && (!strcmp(ext, "o") || !strcmp(ext, "a") || !strcmp(ext, "lib")))
1767                            {
1768                               char * cColon = strstr(colon+1, ":");
1769                               if(cColon && (cColon[1] == '/' || cColon[1] == '\\'))
1770                                  cColon = strstr(cColon + 1, ":");
1771                               if(cColon)
1772                               {
1773                                  int len = (int)(cColon - (colon+1));
1774                                  char mName[MAX_LOCATION];
1775                                  len = Min(len, MAX_LOCATION-1);
1776                                  strncpy(mName, colon+1, len);
1777                                  mName[len] = '\0';
1778                                  GetLastDirectory(mName, temp);
1779                                  GetExtension(temp, ext);
1780                                  if(!strcmp(ext, "c") || !strcmp(ext, "cpp") || !strcmp(ext, "cxx") || !strcmp(ext, "ec"))
1781                                  {
1782                                     colon = cColon;
1783                                     strcpy(moduleName, mName);
1784                                  }
1785                               }
1786                            }
1787                            if(linking && (!strcmp(temp, "ld") || !strcmp(temp, "ld.exe")))
1788                            {
1789                               moduleName[0] = 0;
1790                               if(strstr(colon, "skipping incompatible") || strstr(colon, "Recognised but unhandled"))
1791                               {
1792                                  message = $"Linker Message: ";
1793                                  colon = line;
1794                               }
1795                               else if(SearchString(colon, 0, "warning:", false, false))
1796                               {
1797                                  message = $"Linker Warning: ";
1798                                  colon = line;
1799                               }
1800                               else
1801                               {
1802                                  numErrors++;
1803                                  message = $"Linker Error: ";
1804                               }
1805                            }
1806                            else if(linking && (!strcmp(ext, "") || !strcmp(ext, "exe")))
1807                            {
1808                               moduleName[0] = 0;
1809                               colon = line;
1810                               if(strstr(colon, "Warning:") == colon)
1811                               {
1812                                  message = $"Linker ";
1813                                  numWarnings++;
1814                               }
1815                               else if(strstr(line, "error:"))
1816                               {
1817                                  message = $"Linker Error: ";
1818                                  numErrors++;
1819                               }
1820                            }
1821                            else
1822                            {
1823                               strcpy(temp, topNode.path);
1824                               PathCatSlash(temp, moduleName);
1825                               MakePathRelative(temp, topNode.path, moduleName);
1826                            }
1827                            error = strstr(line, "error:");
1828                            if(!message && error && error > colon)
1829                               numErrors++;
1830                            else
1831                            {
1832                               // Silence warnings for compiled eC
1833                               //char * objDir = strstr(moduleName, objDirExp.dir);
1834
1835                               if(linking)
1836                               {
1837                                  if((pointer = strstr(line, "undefined"))  ||
1838                                       (pointer = strstr(line, "multiple definition")) ||
1839                                       (pointer = strstr(line, "No such file")) ||
1840                                       (pointer = strstr(line, "token")))
1841                                  {
1842                                     strncat(moduleName, colon, pointer - colon);
1843                                     sayError = "error: ";
1844                                     colon = pointer;
1845                                     numErrors++;
1846                                  }
1847                               }
1848                               else if((pointer = strstr(line, "No such file")))
1849                               {
1850                                  strncat(moduleName, colon, pointer - colon);
1851                                  sayError = "error: ";
1852                                  colon = pointer;
1853                                  numErrors++;
1854                               }
1855                               else //if(compilingEC == 1 || (objDir && objDir == moduleName))
1856                               {
1857                                  bool skip = false;
1858
1859                                  // Filter out these warnings caused by eC generated C code:
1860
1861                                  // Declaration ordering bugs -- Awaiting topo sort implementation
1862                                  /*
1863                                       if(strstr(line, "declared inside parameter list")) skip = true;
1864                                  else if(strstr(line, "its scope is only this definition")) skip = true;
1865                                  else if(strstr(line, "from incompatible pointer type")) skip = true;
1866                                  else if(strstr(line, "note: expected 'struct ") || strstr(line, "note: expected â€˜struct "))
1867                                  {
1868                                     #define STRUCT_A "'struct "
1869                                     #define STRUCT_B "‘struct "
1870                                     char * struct1, * struct2, ch1, ch2;
1871                                     struct1 = strstr(line, STRUCT_A);
1872                                     if(struct1) { struct1 += sizeof(STRUCT_A)-1; } else { struct1 = strstr(line, STRUCT_B); struct1 += sizeof(STRUCT_B)-1; };
1873
1874                                     struct2 = strstr(struct1, STRUCT_A);
1875                                     if(struct2) { struct2 += sizeof(STRUCT_A)-1; } else { struct2 = strstr(struct1, STRUCT_B); if(struct2) struct2 += sizeof(STRUCT_B)-1; };
1876
1877                                     if(struct1 && struct2)
1878                                     {
1879                                        while(ch1 = *(struct1++), ch2 = *(struct2++), ch1 && ch2 && (ch1 == '_' || isalnum(ch1)) && (ch2 == '_' || isalnum(ch2)));
1880                                        if(ch1 == ch2)
1881                                           skip = true;
1882                                     }
1883                                  }
1884
1885                                  // For preprocessed code from objidl.h (MinGW-w64 headers)
1886                                  else if(strstr(line, "declaration does not declare anything")) skip = true;
1887
1888                                  // Location information that could apply to ignored warnings
1889                                  else if(strstr(line, "In function '") || strstr(line, "In function â€˜") ) skip = true;
1890                                  else if(strstr(line, "At top level")) skip = true;
1891                                  else if(strstr(line, "(near initialization for '") || strstr(line, "(near initialization for â€˜")) skip = true;
1892                                  */
1893                                  if(skip) continue;
1894                                  numWarnings++;
1895                               }
1896                               /*else if(strstr(line, "warning:"))
1897                               {
1898                                  numWarnings++;
1899                               }*/
1900                            }
1901                            if(message)
1902                               ide.outputView.buildBox.Logf("   %s%s\n", message, colon);
1903                            /*else if(this == ide.workspace.projects.firstIterator.data)
1904                               ide.outputView.buildBox.Logf("   %s%s%s\n", moduleName, sayError, colon);*/
1905                            else
1906                            {
1907                               char fullModuleName[MAX_LOCATION];
1908                               FileAttribs found = 0;
1909                               //Project foundProject = this;
1910                               if(moduleName[0])
1911                               {
1912                                  char * loc = strstr(moduleName, ":");
1913                                  if(loc) *loc = 0;
1914                                  strcpy(fullModuleName, topNode.path);
1915                                  PathCat(fullModuleName, moduleName);
1916                                  found = FileExists(fullModuleName);
1917                                  if(!found && !strcmp(ext, "c"))
1918                                  {
1919                                     char ecName[MAX_LOCATION];
1920                                     ChangeExtension(fullModuleName, "ec", ecName);
1921                                     found = FileExists(ecName);
1922                                  }
1923                                  if(!found)
1924                                  {
1925                                     char path[MAX_LOCATION];
1926                                     if(ide && ide.workspace)
1927                                     {
1928                                        for(prj : ide.workspace.projects)
1929                                        {
1930                                           ProjectNode node;
1931                                           MakePathRelative(fullModuleName, prj.topNode.path, path);
1932
1933                                           if((node = prj.topNode.FindWithPath(path, false)))
1934                                           {
1935                                              strcpy(fullModuleName, prj.topNode.path);
1936                                              PathCatSlash(fullModuleName, node.path);
1937                                              PathCatSlash(fullModuleName, node.name);
1938                                              found = FileExists(fullModuleName);
1939                                              if(found)
1940                                              {
1941                                                 //foundProject = prj;
1942                                                 break;
1943                                              }
1944                                           }
1945                                        }
1946                                        if(!found && !strchr(moduleName, '/') && !strchr(moduleName, '\\'))
1947                                        {
1948                                           for(prj : ide.workspace.projects)
1949                                           {
1950                                              ProjectNode node;
1951                                              if((node = prj.topNode.Find(moduleName, false)))
1952                                              {
1953                                                 strcpy(fullModuleName, prj.topNode.path);
1954                                                 PathCatSlash(fullModuleName, node.path);
1955                                                 PathCatSlash(fullModuleName, node.name);
1956                                                 found = FileExists(fullModuleName);
1957                                                 if(found)
1958                                                 {
1959                                                    //foundProject = prj;
1960                                                    break;
1961                                                 }
1962                                              }
1963                                           }
1964                                        }
1965                                     }
1966                                  }
1967                                  if(found)
1968                                  {
1969                                     MakePathRelative(fullModuleName, ide.workspace.projects.firstIterator.data.topNode.path, fullModuleName);
1970                                     MakeSystemPath(fullModuleName);
1971                                  }
1972                                  else
1973                                     strcpy(fullModuleName, moduleName);
1974                                  if(loc)
1975                                  {
1976                                     strcat(fullModuleName, ":");
1977                                     strcat(fullModuleName, loc + 1);
1978                                  }
1979                               }
1980                               else
1981                                  fullModuleName[0] = 0;
1982                               ide.outputView.buildBox.Logf("   %s%s%s%s\n", inFileIncludedFrom ? stringInFileIncludedFrom : from ? stringFrom : "", fullModuleName, sayError, colon);
1983                            }
1984                         }
1985                         else
1986                         {
1987                            ide.outputView.buildBox.Logf("%s\n", line);
1988                            linking = compiling = precompiling = false;
1989                         }
1990                      }
1991                      else
1992                         ide.outputView.buildBox.Logf("%s\n", line);
1993                   }
1994                   wait = false;
1995                }
1996             }
1997             if(GetTime() - lastTime > 1.0 / PEEK_RESOLUTION) break;
1998          }
1999          //printf("Processing Input...\n");
2000          if(app.ProcessInput(true))
2001             wait = false;
2002          app.UpdateDisplay();
2003          if(wait)
2004          {
2005             //printf("Waiting...\n");
2006             app.Wait();
2007          }
2008          //if(!result) Sleep(1.0 / PEEK_RESOLUTION);
2009       }
2010       if(ide.projectView.stopBuild)
2011       {
2012          ide.outputView.buildBox.Logf($"\nBuild cancelled by user.\n", line);
2013          f.Terminate();
2014       }
2015       else if(loggedALine || buildType != run)
2016       {
2017          if(f.GetExitCode() && !numErrors)
2018          {
2019             /*bool result = */f.GetLine(line, sizeof(line)-1);
2020             ide.outputView.buildBox.Logf($"Fatal Error: child process terminated unexpectedly\n");
2021          }
2022          else if(buildType != install)
2023          {
2024             if(!onlyNodes)
2025             {
2026                char targetFileName[MAX_LOCATION];
2027                targetFileName[0] = '\0';
2028                CatTargetFileName(targetFileName, compiler, config);
2029                ide.outputView.buildBox.Logf("\n%s (%s) - ", targetFileName, lastBuildConfigName);
2030             }
2031             if(numErrors)
2032                ide.outputView.buildBox.Logf("%d %s, ", numErrors, (numErrors > 1) ? $"errors" : $"error");
2033             else
2034                ide.outputView.buildBox.Logf($"no error, ");
2035
2036             if(numWarnings)
2037                ide.outputView.buildBox.Logf("%d %s\n", numWarnings, (numWarnings > 1) ? $"warnings" : $"warning");
2038             else
2039                ide.outputView.buildBox.Logf($"no warning\n");
2040          }
2041       }
2042
2043       delete test;
2044       delete ecp;
2045       delete ecc;
2046       delete ecs;
2047       delete ear;
2048       delete prefix;
2049       delete cpp;
2050       delete cc;
2051       delete cxx;
2052       delete strip;
2053       delete ar;
2054       delete windres;
2055
2056       return numErrors == 0 && !ide.projectView.stopBuild;
2057    }
2058
2059    void ProcessCleanPipeOutput(DualPipe f, CompilerConfig compiler, ProjectConfig config)
2060    {
2061       char line[65536];
2062       int lenMakeCommand = strlen(compiler.makeCommand);
2063       while(!f.Eof())
2064       {
2065          bool result = true;
2066          bool wait = true;
2067          double lastTime = GetTime();
2068          while(result)
2069          {
2070             if((result = f.Peek()) && (result = f.GetLine(line, sizeof(line)-1)) && line[0])
2071             {
2072                if(strstr(line, compiler.makeCommand) == line && line[lenMakeCommand] == ':');
2073                else if(strstr(line, "mkdir") == line);
2074                else if(strstr(line, "del") == line);
2075                else if(strstr(line, "rm") == line);
2076                else if(strstr(line, "Could Not Find") == line);
2077                else
2078                {
2079                   ide.outputView.buildBox.Logf(line);
2080                   ide.outputView.buildBox.Logf("\n");
2081                }
2082                wait = false;
2083             }
2084             if(GetTime() - lastTime > 1.0 / PEEK_RESOLUTION) break;
2085          }
2086          if(app.ProcessInput(true))
2087             wait = false;
2088          app.UpdateDisplay();
2089          if(wait)
2090             app.Wait();
2091          //Sleep(1.0 / PEEK_RESOLUTION);
2092       }
2093    }
2094
2095    bool Build(BuildType buildType, List<ProjectNode> onlyNodes, CompilerConfig compiler, ProjectConfig config, int bitDepth, bool justPrint, bool raw, SingleFileCompileMode mode)
2096    {
2097       bool result = false;
2098       DualPipe f;
2099       char targetFileName[MAX_LOCATION] = "";
2100       DynamicString makeTargets { };
2101       char makeFile[MAX_LOCATION];
2102       char makeFilePath[MAX_LOCATION];
2103       char configName[MAX_LOCATION];
2104       DirExpression objDirExp = GetObjDir(compiler, config, bitDepth);
2105       PathBackup pathBackup { };
2106       bool crossCompiling = (compiler.targetPlatform != __runtimePlatform);
2107       const char * targetPlatform = crossCompiling ? (char *)compiler.targetPlatform : "";
2108
2109       bool eC_Debug = mode.eC_ToolsDebug;
2110       bool singleProjectOnlyNode = onlyNodes && onlyNodes.count == 1 && onlyNodes[0].type == project;
2111       int numJobs = compiler.numJobs;
2112       char command[MAX_F_STRING*4];
2113       char * compilerName = CopyString(compiler.name);
2114       Map<String, NameCollisionInfo> cfgNameCollisions;
2115       const char * objFileExt = strcmp(compiler.objectFileExt, objectDefaultFileExt) != 0 ? compiler.objectFileExt : null;
2116
2117       delete lastBuildConfigName;
2118       lastBuildConfigName = CopyString(config ? config.name : "Common");
2119       delete lastBuildCompilerName;
2120       lastBuildCompilerName = CopyString(compiler.name);
2121       ProjectLoadLastBuildNamesInfo(this, config);
2122       cfgNameCollisions = configsNameCollisions[config ? config.name : ""];
2123
2124       CamelCase(compilerName);
2125
2126       strcpy(configName, config ? config.name : "Common");
2127
2128       SetPath(false, compiler, config, bitDepth); //true
2129       CatTargetFileName(targetFileName, compiler, config);
2130
2131       strcpy(makeFilePath, topNode.path);
2132       CatMakeFileName(makeFile, config);
2133       PathCatSlash(makeFilePath, makeFile);
2134
2135       // TODO: TEST ON UNIX IF \" around makeTarget is ok
2136       if(buildType == install)
2137          makeTargets.concat(" install");
2138       else if(onlyNodes)
2139       {
2140          if(compiler.type.isVC)
2141          {
2142             PrintLn("compiling a single file is not yet supported");
2143          }
2144          else
2145          {
2146             char pushD[MAX_LOCATION];
2147             char cfDir[MAX_LOCATION];
2148             GetIDECompilerConfigsDir(cfDir, true, true);
2149             GetWorkingDir(pushD, sizeof(pushD));
2150             ChangeWorkingDir(topNode.path);
2151             // Create object dir if it does not exist already
2152             if(!FileExists(objDirExp.dir).isDirectory)
2153             {
2154                sprintf(command, "%s CF_DIR=\"%s\"%s%s%s%s%s COMPILER=%s%s%s objdir -C \"%s\"%s -f \"%s\"",
2155                      compiler.makeCommand, cfDir,
2156                      crossCompiling ? " TARGET_PLATFORM=" : "",
2157                      targetPlatform,
2158                      bitDepth ? " ARCH=" : "", bitDepth == 32 ? "32" : bitDepth == 64 ? "64" : "",
2159                      /*(bitDepth == 64 && compiler.targetPlatform == win32) ? " GCC_PREFIX=x86_64-w64-mingw32-" : (bitDepth == 32 && compiler.targetPlatform == win32) ? " GCC_PREFIX=i686-w64-mingw32-" : */"",
2160
2161                      compilerName,
2162                      objFileExt ? " O=." : "", objFileExt ? objFileExt : "",
2163                      topNode.path, justPrint ? " -n" : "", makeFilePath);
2164                if(justPrint || raw)
2165                   ide.outputView.buildBox.Logf("%s\n", command);
2166                Execute(command);
2167             }
2168
2169             ChangeWorkingDir(pushD);
2170
2171             for(node : onlyNodes)
2172             {
2173                if(node.GetIsExcludedForCompiler(config, compiler))
2174                   ide.outputView.buildBox.Logf($"File %s is excluded from current build configuration.\n", node.name);
2175                else
2176                {
2177                   if(!eC_Debug)
2178                      node.DeleteIntermediateFiles(compiler, config, bitDepth, cfgNameCollisions, mode == cObject ? true : false);
2179                   node.GetTargets(config, cfgNameCollisions, objDirExp.dir, compiler.objectFileExt, makeTargets);
2180                }
2181             }
2182          }
2183       }
2184
2185       if(compiler.type.isVC)
2186       {
2187          //bool result = false;
2188          char oldwd[MAX_LOCATION];
2189          GetWorkingDir(oldwd, sizeof(oldwd));
2190          ChangeWorkingDir(topNode.path);
2191
2192          // TODO: support justPrint
2193          sprintf(command, "%s /useenv /nologo /logcommands %s.sln %s|Win32", compiler.makeCommand, name, config.name);
2194          if(justPrint || raw)
2195             ide.outputView.buildBox.Logf("%s\n", command);
2196          if((f = DualPipeOpen(PipeOpenMode { output = true, error = true/*, input = true*/ }, command)))
2197          {
2198             ProcessPipeOutputRaw(f);
2199             delete f;
2200             //result = true;
2201          }
2202          ChangeWorkingDir(oldwd);
2203       }
2204       else if(onlyNodes && strlen(makeTargets) == 0)
2205       {
2206          ide.outputView.buildBox.Log("No targets to compile.\n");
2207       }
2208       else
2209       {
2210          GccVersionInfo ccVersion = GetGccVersionInfo(compiler, compiler.ccCommand);
2211          GccVersionInfo cxxVersion = GetGccVersionInfo(compiler, compiler.cxxCommand);
2212          char cfDir[MAX_LOCATION];
2213          GetIDECompilerConfigsDir(cfDir, true, true);
2214          sprintf(command, "%s%s %sCF_DIR=\"%s\"%s%s%s%s%s%s COMPILER=%s%s%s %s%s%s-j%d %s%s%s -C \"%s\"%s -f \"%s\"",
2215 #if defined(__WIN32__)
2216                "",
2217 #else
2218                buildType == install ? "pkexec --user root " : "",
2219 #endif
2220                compiler.makeCommand,
2221                mode == debugPrecompile ? "ECP_DEBUG=y " : mode == debugCompile ? "ECC_DEBUG=y " : mode == debugGenerateSymbols ? "ECS_DEBUG=y " : "",
2222                cfDir,
2223                crossCompiling ? " TARGET_PLATFORM=" : "",
2224                targetPlatform,
2225                bitDepth ? " ARCH=" : "",
2226                bitDepth == 32 ? "32" : bitDepth == 64 ? "64" : "",
2227                ide.workspace.useValgrind ? " DISABLED_POOLING=1" : "",
2228                /*(bitDepth == 64 && compiler.targetPlatform == win32) ? " GCC_PREFIX=x86_64-w64-mingw32-" : (bitDepth == 32 && compiler.targetPlatform == win32) ? " GCC_PREFIX=i686-w64-mingw32-" :*/ "",
2229                compilerName,
2230                objFileExt ? " O=." : "", objFileExt ? objFileExt : "",
2231                eC_Debug ? "--always-make " : "",
2232                ccVersion == post4_8 ? "GCC_CC_FLAGS=-fno-diagnostics-show-caret " : "",
2233                cxxVersion == post4_8 ? "GCC_CXX_FLAGS=-fno-diagnostics-show-caret " : "",
2234                numJobs,
2235                (compiler.ccacheEnabled && !eC_Debug) ? "CCACHE=y " : "",
2236                (compiler.distccEnabled && !eC_Debug) ? "DISTCC=y " : "",
2237                (String)makeTargets, topNode.path, (justPrint || eC_Debug) ? " -n" : "", makeFilePath);
2238          if(justPrint || raw)
2239             ide.outputView.buildBox.Logf("%s\n", command);
2240
2241          if((f = DualPipeOpen(PipeOpenMode { output = true, error = true, input = true }, command)))
2242          {
2243             bool found = false;
2244             bool error = false;
2245             if(eC_Debug)
2246             {
2247                char line[65536];
2248                if(justPrint)
2249                   ide.outputView.buildBox.Logf($"\nMake outputs the following list of commands to choose from:\n");
2250                while(!f.Eof())
2251                {
2252                   bool result = true;
2253                   while(result)
2254                   {
2255                      if((result = f.Peek()) && (result = f.GetLine(line, sizeof(line)-1)) && line[0])
2256                      {
2257                         if(justPrint)
2258                            ide.outputView.buildBox.Logf("%s\n", line);
2259                         if(!error && !found && strstr(line, "echo ") == line && strstr(line, "ECERE_SDK_SRC"))
2260                         {
2261                            strcpy(command, line+5);
2262                            error = true;
2263                         }
2264                         if(!error && (singleProjectOnlyNode || !found) && strstr(line, "ecere-ide ") == line)
2265                         {
2266                            strcpy(command, line);
2267                            found = true;
2268                         }
2269                      }
2270                   }
2271                }
2272                if(found)
2273                   result = true;
2274             }
2275             else if(justPrint || raw)
2276                result = ProcessPipeOutputRaw(f);
2277             else
2278                result = ProcessBuildPipeOutput(f, objDirExp, buildType, onlyNodes, compiler, config, bitDepth);
2279             delete f;
2280             if(error)
2281                ide.outputView.buildBox.Logf("%s\n", command);
2282             else if(justPrint && found)
2283                ide.outputView.buildBox.Logf($"\nThe following command was chosen to be executed:\n%s\n", command);
2284             else if(found)
2285                Execute(command);
2286          }
2287          else
2288             ide.outputView.buildBox.Logf($"Error executing make (%s) command\n", compiler.makeCommand);
2289       }
2290
2291       delete pathBackup;
2292       delete objDirExp;
2293       delete compilerName;
2294       delete makeTargets;
2295       return result;
2296    }
2297
2298    void Clean(CompilerConfig compiler, ProjectConfig config, int bitDepth, CleanType cleanType, bool justPrint, bool raw)
2299    {
2300       char makeFile[MAX_LOCATION];
2301       char makeFilePath[MAX_LOCATION];
2302       char command[MAX_LOCATION];
2303       char * compilerName;
2304       DualPipe f;
2305       PathBackup pathBackup { };
2306       bool crossCompiling = (compiler.targetPlatform != __runtimePlatform);
2307       const char * targetPlatform = crossCompiling ? (char *)compiler.targetPlatform : "";
2308       const char * objFileExt = strcmp(compiler.objectFileExt, objectDefaultFileExt) ? compiler.objectFileExt : null;
2309
2310       compilerName = CopyString(compiler.name);
2311       CamelCase(compilerName);
2312
2313       SetPath(false, compiler, config, bitDepth);
2314
2315       strcpy(makeFilePath, topNode.path);
2316       CatMakeFileName(makeFile, config);
2317       PathCatSlash(makeFilePath, makeFile);
2318
2319       if(compiler.type.isVC)
2320       {
2321          //bool result = false;
2322          char oldwd[MAX_LOCATION];
2323          GetWorkingDir(oldwd, sizeof(oldwd));
2324          ChangeWorkingDir(topNode.path);
2325
2326          // TODO: justPrint support
2327          sprintf(command, "%s /useenv /clean /nologo /logcommands %s.sln %s|Win32", compiler.makeCommand, name, config.name);
2328          if(justPrint || raw)
2329             ide.outputView.buildBox.Logf("%s\n", command);
2330          if((f = DualPipeOpen(PipeOpenMode { output = true, error = true, input = true }, command)))
2331          {
2332             ProcessPipeOutputRaw(f);
2333             delete f;
2334             //result = true;
2335          }
2336          ChangeWorkingDir(oldwd);
2337          //return result;
2338       }
2339       else
2340       {
2341          char cfDir[MAX_LOCATION];
2342          GetIDECompilerConfigsDir(cfDir, true, true);
2343          sprintf(command, "%s CF_DIR=\"%s\"%s%s%s%s COMPILER=%s%s%s %sclean%s -C \"%s\"%s -f \"%s\"",
2344                compiler.makeCommand, cfDir,
2345                crossCompiling ? " TARGET_PLATFORM=" : "", targetPlatform,
2346                bitDepth ? " ARCH=" : "", bitDepth == 32 ? "32" : bitDepth == 64 ? "64" : "",
2347                compilerName,
2348                objFileExt ? " O=." : "", objFileExt ? objFileExt : "",
2349                cleanType == realClean ? "real" : "", cleanType == cleanTarget ? "target" : "",
2350                topNode.path, justPrint ? " -n": "", makeFilePath);
2351          if(justPrint || raw)
2352             ide.outputView.buildBox.Logf("%s\n", command);
2353          if((f = DualPipeOpen(PipeOpenMode { output = true, error = true, input = true }, command)))
2354          {
2355             ide.outputView.buildBox.Tellf($"Deleting %s%s...",
2356                   cleanType == realClean ? $"intermediate objects directory" : $"target",
2357                   cleanType == clean ? $" and object files" : "");
2358             if(justPrint || raw)
2359                ProcessPipeOutputRaw(f);
2360             else
2361                ProcessCleanPipeOutput(f, compiler, config);
2362             ide.outputView.buildBox.Logf($"%s%s deleted\n",
2363                   cleanType == realClean ? $"Intermediate objects directory" : $"Target",
2364                   cleanType == clean ? $" and object files" : "");
2365             delete f;
2366          }
2367       }
2368
2369       delete pathBackup;
2370       delete compilerName;
2371    }
2372
2373    void Run(const char * args, CompilerConfig compiler, ProjectConfig config, int bitDepth)
2374    {
2375       String target = new char[maxPathLen];
2376       char oldDirectory[MAX_LOCATION];
2377       char * executableLauncher = compiler.executableLauncher;
2378       DirExpression targetDirExp = GetTargetDir(compiler, config, bitDepth);
2379       PathBackup pathBackup { };
2380
2381       // Build(project, ideMain, true, null, false);
2382
2383       strcpy(target, topNode.path);
2384       PathCatSlash(target, targetDirExp.dir);
2385       CatTargetFileName(target, compiler, config);
2386       sprintf(target, "%s %s", target, args);
2387       GetWorkingDir(oldDirectory, MAX_LOCATION);
2388
2389       if(strlen(ide.workspace.debugDir))
2390       {
2391          char temp[MAX_LOCATION];
2392          strcpy(temp, topNode.path);
2393          PathCatSlash(temp, ide.workspace.debugDir);
2394          ChangeWorkingDir(temp);
2395       }
2396       else
2397          ChangeWorkingDir(topNode.path);
2398       SetPath(true, compiler, config, bitDepth);
2399       if(executableLauncher)
2400       {
2401          char * prefixedTarget = new char[strlen(executableLauncher) + strlen(target) + 8];
2402          prefixedTarget[0] = '\0';
2403          strcat(prefixedTarget, executableLauncher);
2404          strcat(prefixedTarget, " ");
2405          strcat(prefixedTarget, target);
2406          Execute(prefixedTarget);
2407          delete prefixedTarget;
2408       }
2409       else
2410          Execute(target);
2411
2412       ChangeWorkingDir(oldDirectory);
2413       delete pathBackup;
2414
2415       delete targetDirExp;
2416       delete target;
2417    }
2418
2419    bool Compile(List<ProjectNode> nodes, CompilerConfig compiler, ProjectConfig config, int bitDepth, bool justPrint, bool raw, SingleFileCompileMode mode)
2420    {
2421       return Build(build, nodes, compiler, config, bitDepth, justPrint, raw, mode);
2422    }
2423 #endif
2424
2425    void GetMakefileTargetFileName(TargetTypes targetType, char * fileName, ProjectConfig config)
2426    {
2427       fileName[0] = '\0';
2428       if(targetType == staticLibrary || targetType == sharedLibrary)
2429          strcat(fileName, "$(LP)");
2430       strcat(fileName, GetTargetFileName(config));
2431       strcat(fileName, "$(OUT)");
2432    }
2433
2434    bool GenerateCrossPlatformMk(File altCrossPlatformMk)
2435    {
2436       bool result = false;
2437       char path[MAX_LOCATION];
2438
2439       if(!GetProjectCompilerConfigsDir(path, false, false))
2440          GetIDECompilerConfigsDir(path, false, false);
2441
2442       if(!FileExists(path).isDirectory)
2443       {
2444          MakeDir(path);
2445          {
2446             char dirName[MAX_FILENAME];
2447             GetLastDirectory(path, dirName);
2448             if(!strcmp(dirName, ".configs"))
2449                FileSetAttribs(path, FileAttribs { isHidden = true });
2450          }
2451       }
2452       PathCatSlash(path, "crossplatform.mk");
2453
2454       if(FileExists(path))
2455          DeleteFile(path);
2456       {
2457          File include = altCrossPlatformMk ? altCrossPlatformMk : FileOpen(":crossplatform.mk", read);
2458          if(include)
2459          {
2460             File f = FileOpen(path, write);
2461             if(f)
2462             {
2463                include.Seek(0, start);
2464                for(; !include.Eof(); )
2465                {
2466                   char buffer[4096];
2467                   int count = include.Read(buffer, 1, 4096);
2468                   f.Write(buffer, 1, count);
2469                }
2470                delete f;
2471
2472                result = true;
2473             }
2474             if(!altCrossPlatformMk)
2475                delete include;
2476          }
2477       }
2478       return result;
2479    }
2480
2481    bool GenerateCompilerCf(CompilerConfig compiler, bool eC)
2482    {
2483       bool result = false;
2484       char path[MAX_LOCATION];
2485       char * name;
2486       char * compilerName;
2487       bool gccCompiler = compiler.ccCommand && (strstr(compiler.ccCommand, "gcc") != null || strstr(compiler.ccCommand, "g++") != null);
2488       const char * gnuToolchainPrefix = compiler.gnuToolchainPrefix ? compiler.gnuToolchainPrefix : "";
2489       Platform platform = compiler.targetPlatform;
2490
2491       compilerName = CopyString(compiler.name);
2492       CamelCase(compilerName);
2493       name = PrintString(platform, "-", compilerName, ".cf");
2494
2495       if(!GetProjectCompilerConfigsDir(path, false, false))
2496          GetIDECompilerConfigsDir(path, false, false);
2497
2498       if(!FileExists(path).isDirectory)
2499       {
2500          MakeDir(path);
2501          {
2502             char dirName[MAX_FILENAME];
2503             GetLastDirectory(path, dirName);
2504             if(!strcmp(dirName, ".configs"))
2505                FileSetAttribs(path, FileAttribs { isHidden = true });
2506          }
2507       }
2508       PathCatSlash(path, name);
2509
2510       if(FileExists(path))
2511          DeleteFile(path);
2512       {
2513          File f = FileOpen(path, write);
2514          if(f)
2515          {
2516             if(compiler.environmentVars && compiler.environmentVars.count)
2517             {
2518                f.Puts("# ENVIRONMENT VARIABLES\n");
2519                f.Puts("\n");
2520                for(e : compiler.environmentVars)
2521                {
2522 #if defined(__WIN32__)
2523                   ChangeCh(e.string, '\\', '/');
2524 #endif
2525                   f.Printf("export %s := %s\n", e.name, e.string);
2526 #if defined(__WIN32__)
2527                   ChangeCh(e.string, '/', '\\');
2528 #endif
2529                }
2530                f.Puts("\n");
2531             }
2532
2533             f.Puts("# TOOLCHAIN\n");
2534             f.Puts("\n");
2535
2536             f.Puts("# OPTIONS\n");
2537             if(compiler.resourcesDotEar)
2538                f.Puts("USE_RESOURCES_EAR := defined\n");
2539             f.Puts("\n");
2540
2541             f.Puts("# EXTENSIONS\n");
2542             if(compiler.outputFileExt)
2543                f.Printf("OUT := %s\n", compiler.outputFileExt);
2544             else
2545                f.Puts("OUT := $(if $(STATIC_LIBRARY_TARGET),$(A),$(if $(SHARED_LIBRARY_TARGET),$(SO)$(VER),$(if $(EXECUTABLE_TARGET),$(E),.x)))\n");
2546
2547             if(gnuToolchainPrefix && gnuToolchainPrefix[0])
2548             {
2549                f.Printf("GCC_PREFIX := %s\n", gnuToolchainPrefix);
2550                f.Puts("\n");
2551             }
2552             if(compiler.sysroot && compiler.sysroot[0])
2553             {
2554                f.Printf("SYSROOT := %s\n", compiler.sysroot);
2555                // Moved this to crossplatform.mk
2556                //f.Puts("_SYSROOT := $(space)--sysroot=$(SYSROOT)\n");
2557                f.Puts("\n");
2558             }
2559
2560             //f.Printf("SHELL := %s\n", "sh"/*compiler.shellCommand*/); // is this really needed?
2561             f.Printf("CPP := $(CCACHE_COMPILE)$(DISTCC_COMPILE)$(GCC_PREFIX)%s$(_SYSROOT)\n", compiler.cppCommand);
2562             f.Printf("CC := $(CCACHE_COMPILE)$(DISTCC_COMPILE)$(GCC_PREFIX)%s$(_SYSROOT)$(if $(GCC_CC_FLAGS),$(space)$(GCC_CC_FLAGS),)\n", compiler.ccCommand);
2563             f.Printf("CXX := $(CCACHE_COMPILE)$(DISTCC_COMPILE)$(GCC_PREFIX)%s$(_SYSROOT)$(if $(GCC_CXX_FLAGS),$(space)$(GCC_CXX_FLAGS),)\n", compiler.cxxCommand);
2564             if(eC)
2565             {
2566                f.Printf("ECP := $(if $(ECP_DEBUG),ecere-ide -debug-start \"$(ECERE_SDK_SRC)/compiler/ecp/ecp.epj\" -debug-work-dir \"${CURDIR}\" -@,%s)$(if $(GCC_CC_FLAGS),$(space)$(GCC_CC_FLAGS),)\n", compiler.ecpCommand);
2567                f.Printf("ECC := $(if $(ECC_DEBUG),ecere-ide -debug-start \"$(ECERE_SDK_SRC)/compiler/ecc/ecc.epj\" -debug-work-dir \"${CURDIR}\" -@,%s)$(if $(CROSS_TARGET), -t $(TARGET_PLATFORM),)$(if $(GCC_CC_FLAGS),$(space)$(GCC_CC_FLAGS),)\n", compiler.eccCommand);
2568                f.Printf("ECS := $(if $(ECS_DEBUG),ecere-ide -debug-start \"$(ECERE_SDK_SRC)/compiler/ecs/ecs.epj\" -debug-work-dir \"${CURDIR}\" -@,%s)$(if $(CROSS_TARGET), -t $(TARGET_PLATFORM),)$(if $(OUTPUT_POT), -outputpot,)$(if $(DISABLED_POOLING), -disabled-pooling,)\n", compiler.ecsCommand);
2569             }
2570             else
2571             {
2572                f.Printf("ECP := %s\n", compiler.ecpCommand);
2573                f.Printf("ECC := %s$(if $(CROSS_TARGET), -t $(TARGET_PLATFORM),)\n", compiler.eccCommand);
2574                f.Printf("ECS := %s$(if $(CROSS_TARGET), -t $(TARGET_PLATFORM),)$(if $(OUTPUT_POT), -outputpot,)$(if $(DISABLED_POOLING), -disabled-pooling,)\n", compiler.ecsCommand);
2575             }
2576             f.Printf("EAR := %s\n", compiler.earCommand);
2577
2578             f.Puts("AS := $(GCC_PREFIX)as\n");
2579             f.Printf("LD := ");
2580             if(compiler.ldCommand && compiler.ldCommand[0])
2581             {
2582                f.Puts("$(GCC_PREFIX)");
2583                f.Puts(compiler.ldCommand);
2584             }
2585             else
2586                f.Puts("$(if $(CONTAINS_CXX),$(CXX),$(CC))");
2587             f.Puts("$(_SYSROOT)$(if $(GCC_LD_FLAGS),$(space)$(GCC_LD_FLAGS),)\n");
2588
2589             f.Printf("AR := $(GCC_PREFIX)%s\n", compiler.arCommand);
2590             f.Puts("STRIP := $(GCC_PREFIX)strip\n");
2591             f.Puts("ifdef WINDOWS_TARGET\n");
2592             f.Puts("WINDRES := $(GCC_PREFIX)windres\n");
2593             f.Puts(" ifdef ARCH\n");
2594             f.Puts("  ifeq ($(ARCH),x32)\n");
2595             f.Puts("WINDRES_FLAGS := -F pe-i386\n");
2596             f.Puts("  else\n");
2597             f.Puts("   ifeq ($(ARCH),x64)\n");
2598             f.Puts("WINDRES_FLAGS := -F pe-x86-64\n");
2599             f.Puts("   endif\n");
2600             f.Puts("  endif\n");
2601             f.Puts(" endif\n");
2602             f.Puts("endif\n");
2603             f.Puts("UPX := upx\n");
2604             f.Puts("\n");
2605
2606             f.Puts("UPXFLAGS = -9\n"); // TOFEAT: Compression Level Option? Other UPX Options?
2607             f.Puts("\n");
2608
2609             f.Puts("EARFLAGS = \n");
2610             f.Puts("\n");
2611
2612             f.Puts("ifndef ARCH\n");
2613             f.Puts("TARGET_ARCH :=$(shell $(CC) -dumpmachine)\n");
2614             f.Puts(" ifdef WINDOWS_HOST\n");
2615             f.Puts("  ifneq ($(filter x86_64%,$(TARGET_ARCH)),)\n");
2616             f.Puts("     TARGET_ARCH := x86_64\n");
2617             f.Puts("  else\n");
2618             f.Puts("     TARGET_ARCH := i386\n");
2619             f.Puts("  endif\n");
2620             f.Puts(" endif\n");
2621             f.Puts("endif\n\n");
2622
2623             f.Puts("# HARD CODED TARGET_PLATFORM-SPECIFIC OPTIONS\n");
2624             f.Printf("LDFLAGS +=$(if $(%s), -Wl$(comma)--no-undefined,)\n", PlatformToMakefileTargetVariable(tux));
2625             f.Puts("\n");
2626
2627             // JF's
2628             f.Printf("LDFLAGS +=$(if $(%s), -framework cocoa -framework OpenGL,)\n", PlatformToMakefileTargetVariable(apple));
2629
2630             if(gccCompiler)
2631             {
2632                f.Puts("\nCFLAGS += -fmessage-length=0\n");
2633             }
2634
2635             if(compiler.includeDirs && compiler.includeDirs.count)
2636             {
2637                f.Puts("\nCFLAGS +=");
2638                OutputFlags(f, gccCompiler ? _isystem : _I, compiler.includeDirs, lineEach);
2639                f.Puts("\n");
2640             }
2641             if(compiler.prepDirectives && compiler.prepDirectives.count)
2642             {
2643                f.Puts("\nCFLAGS +=");
2644                OutputFlags(f, _D, compiler.prepDirectives, inPlace);
2645                f.Puts("\n");
2646             }
2647             if(compiler.libraryDirs && compiler.libraryDirs.count)
2648             {
2649                f.Puts("\nLDFLAGS +=");
2650                OutputFlags(f, _L, compiler.libraryDirs, lineEach);
2651                // We would need a bool option to know whether we want to add to rpath as well...
2652                // OutputFlags(f, _Wl-rpath, compiler.libraryDirs, lineEach);
2653                f.Puts("\n");
2654             }
2655             if(compiler.excludeLibs && compiler.excludeLibs.count)
2656             {
2657                f.Puts("\nEXCLUDED_LIBS =");
2658                for(l : compiler.excludeLibs)
2659                {
2660                   f.Puts(" ");
2661                   f.Puts(l);
2662                }
2663             }
2664             if(compiler.eCcompilerFlags && compiler.eCcompilerFlags.count)
2665             {
2666                f.Puts("\nECFLAGS +=");
2667                OutputFlags(f, any, compiler.eCcompilerFlags, inPlace);
2668                f.Puts("\n");
2669             }
2670             if(compiler.compilerFlags && compiler.compilerFlags.count)
2671             {
2672                f.Puts("\nCFLAGS +=");
2673                OutputFlags(f, any, compiler.compilerFlags, inPlace);
2674                f.Puts("\n");
2675             }
2676             if(compiler.linkerFlags && compiler.linkerFlags.count)
2677             {
2678                f.Puts("\nLDFLAGS +=");
2679                OutputFlags(f, _Wl, compiler.linkerFlags, inPlace);
2680                f.Puts("\n");
2681             }
2682             f.Puts("\n");
2683             f.Puts("\nOFLAGS += $(LDFLAGS)");
2684             f.Puts("\n");
2685             f.Puts("ifdef ARCH_FLAGS\n");
2686             f.Puts("CFLAGS += $(ARCH_FLAGS)\n");
2687             f.Puts("OFLAGS += $(ARCH_FLAGS)\n");
2688             f.Puts("endif\n");
2689
2690             delete f;
2691
2692             result = true;
2693          }
2694       }
2695       delete name;
2696       delete compilerName;
2697       return result;
2698    }
2699
2700    bool GenerateMakefile(const char * altMakefilePath, bool noResources, const char * includemkPath, ProjectConfig config)
2701    {
2702       bool result = false;
2703       char filePath[MAX_LOCATION];
2704       char makeFile[MAX_LOCATION];
2705       // PathBackup pathBackup { };
2706       // char oldDirectory[MAX_LOCATION];
2707       File f = null;
2708
2709       if(!altMakefilePath)
2710       {
2711          strcpy(filePath, topNode.path);
2712          CatMakeFileName(makeFile, config);
2713          PathCatSlash(filePath, makeFile);
2714       }
2715
2716       f = FileOpen(altMakefilePath ? altMakefilePath : filePath, write);
2717
2718       /*SetPath(false, compiler, config);
2719       GetWorkingDir(oldDirectory, MAX_LOCATION);
2720       ChangeWorkingDir(topNode.path);*/
2721
2722       if(f)
2723       {
2724          bool test;
2725          int ifCount;
2726          Platform platform;
2727          char targetDir[MAX_LOCATION];
2728          char objDirExpNoSpaces[MAX_LOCATION];
2729          char objDirNoSpaces[MAX_LOCATION];
2730          char resDirNoSpaces[MAX_LOCATION];
2731          char targetDirExpNoSpaces[MAX_LOCATION];
2732          char fixedModuleName[MAX_FILENAME];
2733          char fixedConfigName[MAX_FILENAME];
2734          int c;
2735          int lenObjDirExpNoSpaces, lenTargetDirExpNoSpaces;
2736          // Non-zero if we're building eC code
2737          // We'll have to be careful with this when merging configs where eC files can be excluded in some configs and included in others
2738          int numCObjects = 0;
2739          int numObjects = 0;
2740          int numRCObjects = 0;
2741          bool containsCXX = false; // True if the project contains a C++ file
2742          bool relObjDir, sameOrRelObjTargetDirs;
2743          const String objDirExp = GetObjDirExpression(config);
2744          TargetTypes targetType = GetTargetType(config);
2745
2746          char cfDir[MAX_LOCATION];
2747          int objectsParts = 0;
2748          int eCsourcesParts = 0;
2749          int rcSourcesParts = 0;
2750          Array<String> listItems { };
2751          Map<String, int> varStringLenDiffs { };
2752          Map<String, NameCollisionInfo> namesInfo { };
2753
2754          Map<String, int> cflagsVariations { };
2755          Map<intptr, int> nodeCFlagsMapping { };
2756
2757          Map<String, int> ecflagsVariations { };
2758          Map<intptr, int> nodeECFlagsMapping { };
2759
2760          ReplaceSpaces(objDirNoSpaces, objDirExp);
2761          strcpy(targetDir, GetTargetDirExpression(config));
2762          ReplaceSpaces(targetDirExpNoSpaces, targetDir);
2763
2764          strcpy(objDirExpNoSpaces, GetObjDirExpression(config));
2765          ChangeCh(objDirExpNoSpaces, '\\', '/'); // TODO: this is a hack, paths should never include win32 path seperators - fix this in ProjectSettings and ProjectLoad instead
2766          {
2767             char temp[MAX_LOCATION];
2768             ReplaceSpaces(temp, objDirExpNoSpaces);
2769             strcpy(objDirExpNoSpaces, temp);
2770          }
2771          ReplaceSpaces(resDirNoSpaces, resNode.path ? resNode.path : "");
2772          ReplaceSpaces(fixedModuleName, moduleName);
2773          ReplaceSpaces(fixedConfigName, GetConfigName(config));
2774          CamelCase(fixedConfigName);
2775
2776          lenObjDirExpNoSpaces = strlen(objDirExpNoSpaces);
2777          relObjDir = lenObjDirExpNoSpaces == 0 ||
2778                (objDirExpNoSpaces[0] == '.' && (lenObjDirExpNoSpaces == 1 || objDirExpNoSpaces[1] == '.'));
2779          lenTargetDirExpNoSpaces = strlen(targetDirExpNoSpaces);
2780          sameOrRelObjTargetDirs = lenTargetDirExpNoSpaces == 0 ||
2781                (targetDirExpNoSpaces[0] == '.' && (lenTargetDirExpNoSpaces == 1 || targetDirExpNoSpaces[1] == '.')) ||
2782                !fstrcmp(objDirExpNoSpaces, targetDirExpNoSpaces);
2783
2784          f.Printf(".PHONY: all objdir%s cleantarget clean realclean distclean\n\n", sameOrRelObjTargetDirs ? "" : " targetdir");
2785
2786          f.Puts("# CORE VARIABLES\n\n");
2787
2788          f.Printf("MODULE := %s\n", fixedModuleName);
2789          f.Printf("VERSION := %s\n", property::moduleVersion);
2790          f.Printf("CONFIG := %s\n", fixedConfigName);
2791          topNode.GenMakefilePrintNode(f, this, noPrint, null, null, config, &containsCXX);
2792          if(containsCXX)
2793             f.Puts("CONTAINS_CXX := defined\n");
2794          f.Puts("ifndef COMPILER\n" "COMPILER := default\n" "endif\n");
2795          f.Puts("\n");
2796
2797          test = GetTargetTypeIsSetByPlatform(config);
2798          if(test)
2799          {
2800             ifCount = 0;
2801             for(platform = (Platform)1; platform < Platform::enumSize; platform++)
2802             {
2803                TargetTypes targetType;
2804                PlatformOptions projectPOs, configPOs;
2805                MatchProjectAndConfigPlatformOptions(config, platform, &projectPOs, &configPOs);
2806                targetType = platformTargetType;
2807                if(targetType)
2808                {
2809                   if(ifCount)
2810                      f.Puts("else\n");
2811                   ifCount++;
2812                   f.Printf("ifdef %s\n", PlatformToMakefileTargetVariable(platform));
2813                   f.Printf("TARGET_TYPE = %s\n", TargetTypeToMakefileVariable(targetType));
2814                }
2815             }
2816             f.Puts("else\n");
2817          }
2818          f.Printf("TARGET_TYPE = %s\n", TargetTypeToMakefileVariable(targetType));
2819          if(test)
2820          {
2821             if(ifCount)
2822             {
2823                for(c = 0; c < ifCount; c++)
2824                   f.Puts("endif\n");
2825             }
2826          }
2827          f.Puts("\n");
2828
2829          f.Puts("# FLAGS\n\n");
2830
2831          f.Puts("ECFLAGS =\n");
2832          f.Puts("ifndef DEBIAN_PACKAGE\n" "CFLAGS =\n" "LDFLAGS =\n" "endif\n");
2833          f.Puts("PRJ_CFLAGS =\n");
2834          f.Puts("CECFLAGS =\n");
2835          f.Puts("OFLAGS =\n");
2836          f.Puts("LIBS =\n");
2837          f.Puts("\n");
2838
2839          f.Puts("ifdef DEBUG\n" "NOSTRIP := y\n" "endif\n");
2840          f.Puts("\n");
2841
2842          // Important: We cannot use this ifdef anymore, EXECUTABLE_TARGET is not yet defined. It's embedded in the crossplatform.mk EXECUTABLE
2843          //f.Puts("ifdef EXECUTABLE_TARGET\n");
2844          f.Printf("CONSOLE = %s\n", GetConsole(config) ? "-mconsole" : "-mwindows");
2845          //f.Puts("endif\n");
2846          f.Puts("\n");
2847
2848          f.Puts("# INCLUDES\n\n");
2849
2850          if(compilerConfigsDir && compilerConfigsDir[0])
2851          {
2852             strcpy(cfDir, compilerConfigsDir);
2853             if(cfDir[0] && cfDir[strlen(cfDir)-1] != '/')
2854                strcat(cfDir, "/");
2855          }
2856          else
2857          {
2858             GetIDECompilerConfigsDir(cfDir, true, true);
2859             // Use CF_DIR environment variable for absolute paths only
2860             if(cfDir[0] == '/' || (cfDir[0] && cfDir[1] == ':'))
2861                strcpy(cfDir, "$(CF_DIR)");
2862          }
2863
2864          f.Printf("_CF_DIR = %s\n", cfDir);
2865          f.Puts("\n");
2866
2867          f.Printf("include %s\n", includemkPath ? includemkPath : "$(_CF_DIR)crossplatform.mk");
2868          f.Puts("include $(_CF_DIR)$(TARGET_PLATFORM)-$(COMPILER).cf\n");
2869          f.Puts("\n");
2870
2871          f.Puts("# POST-INCLUDES VARIABLES\n\n");
2872
2873          f.Printf("OBJ = %s%s\n", objDirExpNoSpaces, objDirExpNoSpaces[0] ? "/" : "");
2874          f.Puts("\n");
2875
2876          f.Printf("RES = %s%s\n", resDirNoSpaces, resDirNoSpaces[0] ? "/" : "");
2877          f.Puts("\n");
2878
2879          // test = GetTargetTypeIsSetByPlatform(config);
2880          {
2881             char target[MAX_LOCATION];
2882             char temp[MAX_LOCATION];
2883             if(test)
2884             {
2885                TargetTypes type;
2886                ifCount = 0;
2887                for(type = (TargetTypes)1; type < TargetTypes::enumSize; type++)
2888                {
2889                   if(type != targetType)
2890                   {
2891                      if(ifCount)
2892                         f.Puts("else\n");
2893                      ifCount++;
2894                      f.Printf("ifeq ($(TARGET_TYPE),%s)\n", TargetTypeToMakefileVariable(type));
2895
2896                      GetMakefileTargetFileName(type, target, config);
2897                      strcpy(temp, targetDir);
2898                      PathCatSlash(temp, target);
2899                      ReplaceSpaces(target, temp);
2900                      f.Printf("TARGET = %s\n", target);
2901                   }
2902                }
2903                f.Puts("else\n");
2904             }
2905             GetMakefileTargetFileName(targetType, target, config);
2906             strcpy(temp, targetDir);
2907             PathCatSlash(temp, target);
2908             ReplaceSpaces(target, temp);
2909             f.Printf("TARGET = %s\n", target);
2910
2911             if(test)
2912             {
2913                if(ifCount)
2914                {
2915                   for(c = 0; c < ifCount; c++)
2916                      f.Puts("endif\n");
2917                }
2918             }
2919          }
2920          f.Puts("\n");
2921
2922          // Use something fixed here, to not cause Makefile differences across compilers...
2923          varStringLenDiffs["$(OBJ)"] = 30; // strlen("obj/memoryGuard.android.gcc-4.6.2") - 6;
2924          // varStringLenDiffs["$(OBJ)"] = strlen(objDirNoSpaces) - 6;
2925
2926          topNode.GenMakefileGetNameCollisionInfo(namesInfo, config);
2927
2928          {
2929             int c;
2930             const char * map[5][2] = { { "COBJECTS", "C" }, { "SYMBOLS", "S" }, { "IMPORTS", "I" }, { "ECOBJECTS", "O" }, { "BOWLS", "B" } };
2931
2932             numCObjects = topNode.GenMakefilePrintNode(f, this, eCsources, namesInfo, listItems, config, null);
2933             if(numCObjects)
2934             {
2935                eCsourcesParts = OutputFileList(f, "_ECSOURCES", listItems, varStringLenDiffs, null);
2936
2937                f.Puts("ECSOURCES = $(call shwspace,$(_ECSOURCES))\n");
2938                if(eCsourcesParts > 1)
2939                {
2940                   for(c = 1; c <= eCsourcesParts; c++)
2941                      f.Printf("ECSOURCES%d = $(call shwspace,$(_ECSOURCES%d))\n", c, c);
2942                }
2943                f.Puts("\n");
2944
2945                for(c = 0; c < 5; c++)
2946                {
2947                   if(eCsourcesParts > 1)
2948                   {
2949                      int n;
2950                      f.Printf("_%s =", map[c][0]);
2951                      for(n = 1; n <= eCsourcesParts; n++)
2952                         f.Printf(" $(%s%d)", map[c][0], n);
2953                      f.Puts("\n");
2954                      for(n = 1; n <= eCsourcesParts; n++)
2955                         f.Printf("_%s%d = $(addprefix $(OBJ),$(patsubst %%.ec,%%$(%s),$(notdir $(_ECSOURCES%d))))\n", map[c][0], n, map[c][1], n);
2956                   }
2957                   else if(eCsourcesParts == 1)
2958                      f.Printf("_%s = $(addprefix $(OBJ),$(patsubst %%.ec,%%$(%s),$(notdir $(_ECSOURCES))))\n", map[c][0], map[c][1]);
2959                   f.Puts("\n");
2960                }
2961
2962                for(c = 0; c < 5; c++)
2963                {
2964                   if(eCsourcesParts > 1)
2965                   {
2966                      int n;
2967                      f.Printf("%s =", map[c][0]);
2968                      for(n = 1; n <= eCsourcesParts; n++)
2969                         f.Printf(" $(%s%d)", map[c][0], n);
2970                      f.Puts("\n");
2971                      for(n = 1; n <= eCsourcesParts; n++)
2972                         f.Printf("%s%d = $(call shwspace,$(_%s%d))\n", map[c][0], n, map[c][0], n);
2973                   }
2974                   else if(eCsourcesParts == 1)
2975                      f.Printf("%s = $(call shwspace,$(_%s))\n", map[c][0], map[c][0]);
2976                   f.Puts("\n");
2977                }
2978             }
2979          }
2980
2981          numRCObjects = topNode.GenMakefilePrintNode(f, this, rcSources, namesInfo, listItems, config, null);
2982          if(numRCObjects)
2983          {
2984             f.Puts("ifdef WINDOWS_TARGET\n\n");
2985
2986             rcSourcesParts = OutputFileList(f, "_RCSOURCES", listItems, varStringLenDiffs, null);
2987
2988             f.Puts("RCSOURCES = $(call shwspace,$(_RCSOURCES))\n");
2989             if(rcSourcesParts > 1)
2990             {
2991                for(c = 1; c <= rcSourcesParts; c++)
2992                   f.Printf("RCSOURCES%d = $(call shwspace,$(_RCSOURCES%d))\n", c, c);
2993             }
2994             f.Puts("\n");
2995             if(rcSourcesParts > 1)
2996             {
2997                int n;
2998                f.Printf("%s =", "RCOBJECTS");
2999                for(n = 1; n <= rcSourcesParts; n++)
3000                   f.Printf(" $(%s%d)", "RCOBJECTS", n);
3001                f.Puts("\n");
3002                for(n = 1; n <= rcSourcesParts; n++)
3003                   f.Printf("%s%d = $(call shwspace,$(addprefix $(OBJ),$(patsubst %%.rc,%%$(%s),$(notdir $(_RCSOURCES%d)))))\n", "RCOBJECTS", n, "O", n);
3004             }
3005             else if(rcSourcesParts == 1)
3006                f.Printf("%s = $(call shwspace,$(addprefix $(OBJ),$(patsubst %%.rc,%%$(%s),$(notdir $(_RCSOURCES)))))\n", "RCOBJECTS", "O");
3007             f.Puts("\n");
3008
3009             f.Puts("else\n");
3010             f.Puts("RCSOURCES =\n");
3011             f.Puts("RCOBJECTS =\n");
3012             f.Puts("endif\n\n");
3013          }
3014
3015          numObjects = topNode.GenMakefilePrintNode(f, this, objects, namesInfo, listItems, config, null);
3016          if(numObjects)
3017             objectsParts = OutputFileList(f, "_OBJECTS", listItems, varStringLenDiffs, null);
3018          f.Printf("OBJECTS =%s%s%s%s\n",
3019                numObjects ? " $(_OBJECTS)" : "", numCObjects ? " $(ECOBJECTS)" : "",
3020                numCObjects ? " $(OBJ)$(MODULE).main$(O)" : "",
3021                numRCObjects ? " $(RCOBJECTS)" : "");
3022          f.Puts("\n");
3023
3024          topNode.GenMakefilePrintNode(f, this, sources, null, listItems, config, null);
3025          {
3026             const char * prefix;
3027             if(numCObjects && numRCObjects)
3028                prefix = "$(ECSOURCES) $(RCSOURCES)";
3029             else if(numCObjects)
3030                prefix = "$(ECSOURCES)";
3031             else
3032                prefix = null;
3033             OutputFileList(f, "SOURCES", listItems, varStringLenDiffs, prefix);
3034          }
3035
3036          if(!noResources)
3037             resNode.GenMakefilePrintNode(f, this, resources, null, listItems, config, null);
3038          OutputFileList(f, "RESOURCES", listItems, varStringLenDiffs, null);
3039
3040          f.Puts("ifdef USE_RESOURCES_EAR\n");
3041          f.Puts("RESOURCES_EAR = $(OBJ)resources.ear\n");
3042          f.Puts("else\n");
3043          f.Puts("RESOURCES_EAR = $(RESOURCES)\n");
3044          f.Puts("endif\n");
3045          f.Puts("\n");
3046
3047          f.Puts("LIBS += $(SHAREDLIB) $(EXECUTABLE) $(LINKOPT)\n");
3048          f.Puts("\n");
3049          if((config && config.options && config.options.libraries) ||
3050                (options && options.libraries))
3051          {
3052             f.Puts("ifndef STATIC_LIBRARY_TARGET\n");
3053             f.Puts("LIBS +=");
3054             if(config && config.options && config.options.libraries)
3055                OutputLibraries(f, config.options.libraries);
3056             else if(options && options.libraries)
3057                OutputLibraries(f, options.libraries);
3058             f.Puts("\n");
3059             f.Puts("endif\n");
3060             f.Puts("\n");
3061          }
3062
3063          topNode.GenMakeCollectAssignNodeFlags(config, numCObjects != 0,
3064                cflagsVariations, nodeCFlagsMapping,
3065                ecflagsVariations, nodeECFlagsMapping, null);
3066
3067          GenMakePrintCustomFlags(f, "PRJ_CFLAGS", false, cflagsVariations);
3068          f.Puts("ECFLAGS += -module $(MODULE)\n");
3069          GenMakePrintCustomFlags(f, "ECFLAGS", true, ecflagsVariations);
3070
3071          if(platforms || (config && config.platforms))
3072          {
3073             ifCount = 0;
3074             //for(platform = firstPlatform; platform <= lastPlatform; platform++)
3075             //for(platform = win32; platform <= apple; platform++)
3076
3077             f.Puts("# PLATFORM-SPECIFIC OPTIONS\n\n");
3078             for(platform = (Platform)1; platform < Platform::enumSize; platform++)
3079             {
3080                PlatformOptions projectPlatformOptions, configPlatformOptions;
3081                MatchProjectAndConfigPlatformOptions(config, platform, &projectPlatformOptions, &configPlatformOptions);
3082
3083                if(projectPlatformOptions || configPlatformOptions)
3084                {
3085                   if(ifCount)
3086                      f.Puts("else\n");
3087                   ifCount++;
3088                   f.Printf("ifdef %s\n", PlatformToMakefileTargetVariable(platform));
3089                   f.Puts("\n");
3090
3091                   if((projectPlatformOptions && projectPlatformOptions.options.compilerOptions && projectPlatformOptions.options.compilerOptions.count) ||
3092                      (configPlatformOptions && configPlatformOptions.options.compilerOptions && configPlatformOptions.options.compilerOptions.count))
3093                   {
3094                      f.Puts("CFLAGS +=");
3095                      if(projectPlatformOptions && projectPlatformOptions.options.compilerOptions && projectPlatformOptions.options.compilerOptions.count)
3096                      {
3097                         f.Puts(" \\\n\t ");
3098                         for(s : projectPlatformOptions.options.compilerOptions)
3099                            f.Printf(" %s", s);
3100                      }
3101                      if(configPlatformOptions && configPlatformOptions.options.compilerOptions && configPlatformOptions.options.compilerOptions.count)
3102                      {
3103                         f.Puts(" \\\n\t ");
3104                         for(s : configPlatformOptions.options.compilerOptions)
3105                            f.Printf(" %s", s);
3106                      }
3107                      f.Puts("\n");
3108                      f.Puts("\n");
3109                   }
3110
3111                   if((projectPlatformOptions && projectPlatformOptions.options.linkerOptions && projectPlatformOptions.options.linkerOptions.count) ||
3112                      (configPlatformOptions && configPlatformOptions.options.linkerOptions && configPlatformOptions.options.linkerOptions.count))
3113                   {
3114                      f.Puts("OFLAGS +=");
3115                      if(projectPlatformOptions && projectPlatformOptions.options.linkerOptions && projectPlatformOptions.options.linkerOptions.count)
3116                      {
3117                         bool needWl = false;
3118                         f.Puts(" \\\n\t ");
3119                         for(s : projectPlatformOptions.options.linkerOptions)
3120                         {
3121                            if(!IsLinkerOption(s))
3122                               f.Printf(" %s", s);
3123                            else
3124                               needWl = true;
3125                         }
3126                         if(needWl)
3127                         {
3128                            f.Puts(" -Wl");
3129                            for(s : projectPlatformOptions.options.linkerOptions)
3130                               if(IsLinkerOption(s))
3131                                  f.Printf(",%s", s);
3132                         }
3133                      }
3134                      if(configPlatformOptions && configPlatformOptions.options.linkerOptions && configPlatformOptions.options.linkerOptions.count)
3135                      {
3136                         bool needWl = false;
3137                         f.Puts(" \\\n\t ");
3138                         for(s : configPlatformOptions.options.linkerOptions)
3139                         {
3140                            if(IsLinkerOption(s))
3141                               f.Printf(" %s", s);
3142                            else
3143                               needWl = true;
3144                         }
3145                         if(needWl)
3146                         {
3147                            f.Puts(" -Wl");
3148                            for(s : configPlatformOptions.options.linkerOptions)
3149                               if(!IsLinkerOption(s))
3150                                  f.Printf(",%s", s);
3151                         }
3152                      }
3153                      f.Puts("\n");
3154                      f.Puts("\n");
3155                   }
3156
3157                   if((projectPlatformOptions && projectPlatformOptions.options.libraryDirs && projectPlatformOptions.options.libraryDirs.count) ||
3158                         (configPlatformOptions && configPlatformOptions.options.libraryDirs && configPlatformOptions.options.libraryDirs.count) ||
3159                         (projectPlatformOptions && projectPlatformOptions.options.libraries && projectPlatformOptions.options.libraries.count) ||
3160                         (configPlatformOptions && configPlatformOptions.options.libraries && configPlatformOptions.options.libraries.count))
3161                   {
3162                      f.Puts("ifndef STATIC_LIBRARY_TARGET\n");
3163                      if((projectPlatformOptions && projectPlatformOptions.options.libraryDirs && projectPlatformOptions.options.libraryDirs.count) ||
3164                         (configPlatformOptions && configPlatformOptions.options.libraryDirs && configPlatformOptions.options.libraryDirs.count))
3165                      {
3166                         f.Puts("OFLAGS +=");
3167                         if(configPlatformOptions && configPlatformOptions.options.libraryDirs)
3168                            OutputFlags(f, _L, configPlatformOptions.options.libraryDirs, lineEach);
3169                         if(projectPlatformOptions && projectPlatformOptions.options.libraryDirs)
3170                            OutputFlags(f, _L, projectPlatformOptions.options.libraryDirs, lineEach);
3171                         f.Puts("\n");
3172                      }
3173
3174                      if(configPlatformOptions && configPlatformOptions.options.libraries)
3175                      {
3176                         if(configPlatformOptions.options.libraries.count)
3177                         {
3178                            f.Puts("LIBS +=");
3179                            OutputLibraries(f, configPlatformOptions.options.libraries);
3180                            f.Puts("\n");
3181                         }
3182                      }
3183                      else if(projectPlatformOptions && projectPlatformOptions.options.libraries)
3184                      {
3185                         if(projectPlatformOptions.options.libraries.count)
3186                         {
3187                            f.Puts("LIBS +=");
3188                            OutputLibraries(f, projectPlatformOptions.options.libraries);
3189                            f.Puts("\n");
3190                         }
3191                      }
3192                      f.Puts("endif\n");
3193                      f.Puts("\n");
3194                   }
3195                }
3196             }
3197             if(ifCount)
3198             {
3199                for(c = 0; c < ifCount; c++)
3200                   f.Puts("endif\n");
3201             }
3202             f.Puts("\n");
3203          }
3204
3205          if((config && config.options && config.options.compilerOptions && config.options.compilerOptions.count) ||
3206                (options && options.compilerOptions && options.compilerOptions.count))
3207          {
3208             f.Puts("CFLAGS +=");
3209             f.Puts(" \\\n\t");
3210
3211             if(config && config.options && config.options.compilerOptions && config.options.compilerOptions.count)
3212             {
3213                for(s : config.options.compilerOptions)
3214                   f.Printf(" %s", s);
3215             }
3216             if(options && options.compilerOptions && options.compilerOptions.count)
3217             {
3218                for(s : options.compilerOptions)
3219                   f.Printf(" %s", s);
3220             }
3221             f.Puts("\n");
3222             f.Puts("\n");
3223          }
3224
3225          if((config && config.options && config.options.linkerOptions && config.options.linkerOptions.count) ||
3226                (options && options.linkerOptions && options.linkerOptions.count))
3227          {
3228             f.Puts("OFLAGS +=");
3229             f.Puts(" \\\n\t");
3230
3231             if(config && config.options && config.options.linkerOptions && config.options.linkerOptions.count)
3232             {
3233                bool needWl = false;
3234                for(s : config.options.linkerOptions)
3235                {
3236                   if(!IsLinkerOption(s))
3237                      f.Printf(" %s", s);
3238                   else
3239                      needWl = true;
3240                }
3241                if(needWl)
3242                {
3243                   f.Puts(" -Wl");
3244                   for(s : config.options.linkerOptions)
3245                      if(IsLinkerOption(s))
3246                         f.Printf(",%s", s);
3247                }
3248             }
3249             if(options && options.linkerOptions && options.linkerOptions.count)
3250             {
3251                bool needWl = false;
3252                for(s : options.linkerOptions)
3253                {
3254                   if(!IsLinkerOption(s))
3255                      f.Printf(" %s", s);
3256                   else
3257                      needWl = true;
3258                }
3259                if(needWl)
3260                {
3261                   f.Puts(" -Wl");
3262                   for(s : options.linkerOptions)
3263                      if(IsLinkerOption(s))
3264                         f.Printf(",%s", s);
3265                }
3266             }
3267             f.Puts("\n");
3268             f.Puts("\n");
3269          }
3270
3271          f.Puts("CECFLAGS += -cpp $(_CPP)");
3272          f.Puts("\n");
3273          f.Puts("\n");
3274
3275          if(GetProfile(config))
3276             f.Puts("OFLAGS += -pg\n\n");
3277
3278          if((config && config.options && config.options.libraryDirs) || (options && options.libraryDirs))
3279          {
3280             f.Puts("ifndef STATIC_LIBRARY_TARGET\n");
3281             f.Puts("OFLAGS +=");
3282             if(config && config.options && config.options.libraryDirs)
3283                OutputFlags(f, _L, config.options.libraryDirs, lineEach);
3284             if(options && options.libraryDirs)
3285                OutputFlags(f, _L, options.libraryDirs, lineEach);
3286             f.Puts("\n");
3287             f.Puts("endif\n");
3288             f.Puts("\n");
3289          }
3290
3291          f.Puts("# TARGETS\n");
3292          f.Puts("\n");
3293
3294          f.Printf("all: objdir%s $(TARGET)\n", sameOrRelObjTargetDirs ? "" : " targetdir");
3295          f.Puts("\n");
3296
3297          f.Puts("objdir:\n");
3298          if(!relObjDir)
3299             f.Puts("\t$(if $(wildcard $(OBJ)),,$(call mkdir,$(OBJ)))\n");
3300          if(numCObjects)
3301          {
3302             f.Puts("\t$(if $(ECERE_SDK_SRC),$(if $(wildcard $(call escspace,$(ECERE_SDK_SRC)/crossplatform.mk)),,@$(call echo,Ecere SDK Source Warning: The value of ECERE_SDK_SRC is pointing to an incorrect ($(ECERE_SDK_SRC)) location.)),)\n");
3303             f.Puts("\t$(if $(ECERE_SDK_SRC),,$(if $(ECP_DEBUG)$(ECC_DEBUG)$(ECS_DEBUG),@$(call echo,ECC Debug Warning: Please define ECERE_SDK_SRC before using ECP_DEBUG, ECC_DEBUG or ECS_DEBUG),))\n");
3304          }
3305          //f.Puts("# PRE-BUILD COMMANDS\n");
3306          if(options && options.prebuildCommands)
3307          {
3308             for(s : options.prebuildCommands)
3309                if(s && s[0]) f.Printf("\t%s\n", s);
3310          }
3311          if(config && config.options && config.options.prebuildCommands)
3312          {
3313             for(s : config.options.prebuildCommands)
3314                if(s && s[0]) f.Printf("\t%s\n", s);
3315          }
3316          if(platforms || (config && config.platforms))
3317          {
3318             ifCount = 0;
3319             //f.Puts("# TARGET_PLATFORM-SPECIFIC PRE-BUILD COMMANDS\n");
3320             for(platform = (Platform)1; platform < Platform::enumSize; platform++)
3321             {
3322                PlatformOptions projectPOs, configPOs;
3323                MatchProjectAndConfigPlatformOptions(config, platform, &projectPOs, &configPOs);
3324
3325                if((projectPOs && projectPOs.options.prebuildCommands && projectPOs.options.prebuildCommands.count) ||
3326                      (configPOs && configPOs.options.prebuildCommands && configPOs.options.prebuildCommands.count))
3327                {
3328                   if(ifCount)
3329                      f.Puts("else\n");
3330                   ifCount++;
3331                   f.Printf("ifdef %s\n", PlatformToMakefileTargetVariable(platform));
3332
3333                   if(projectPOs && projectPOs.options.prebuildCommands && projectPOs.options.prebuildCommands.count)
3334                   {
3335                      for(s : projectPOs.options.prebuildCommands)
3336                         if(s && s[0]) f.Printf("\t%s\n", s);
3337                   }
3338                   if(configPOs && configPOs.options.prebuildCommands && configPOs.options.prebuildCommands.count)
3339                   {
3340                      for(s : configPOs.options.prebuildCommands)
3341                         if(s && s[0]) f.Printf("\t%s\n", s);
3342                   }
3343                }
3344             }
3345             if(ifCount)
3346             {
3347                int c;
3348                for(c = 0; c < ifCount; c++)
3349                   f.Puts("endif\n");
3350             }
3351          }
3352          f.Puts("\n");
3353
3354          if(!sameOrRelObjTargetDirs)
3355          {
3356             f.Puts("targetdir:\n");
3357                f.Printf("\t$(if $(wildcard %s),,$(call mkdir,%s))\n", targetDirExpNoSpaces, targetDirExpNoSpaces);
3358             f.Puts("\n");
3359          }
3360
3361          if(numCObjects)
3362          {
3363             // Main Module (Linking) for ECERE C modules
3364             f.Puts("$(OBJ)$(MODULE).main.ec: $(SYMBOLS) $(COBJECTS)\n");
3365             f.Printf("\t@$(call rm,$(OBJ)symbols.lst)\n");
3366             f.Printf("\t@$(call touch,$(OBJ)symbols.lst)\n");
3367             OutputFileListActions(f, "SYMBOLS", eCsourcesParts, "$(OBJ)symbols.lst");
3368             OutputFileListActions(f, "IMPORTS", eCsourcesParts, "$(OBJ)symbols.lst");
3369             // use of objDirExpNoSpaces used instead of $(OBJ) to prevent problematic joining of arguments in ecs
3370             f.Printf("\t$(ECS)%s $(ARCH_FLAGS) $(ECSLIBOPT) @$(OBJ)symbols.lst -symbols %s -o $(call quote_path,$@)\n",
3371                GetConsole(config) ? " -console" : "", objDirExpNoSpaces);
3372             f.Puts("\n");
3373             // Main Module (Linking) for ECERE C modules
3374             f.Puts("$(OBJ)$(MODULE).main.c: $(OBJ)$(MODULE).main.ec\n");
3375             f.Puts("\t$(ECP) $(CFLAGS) $(CECFLAGS) $(ECFLAGS) $(PRJ_CFLAGS)"
3376                   " -c $(OBJ)$(MODULE).main.ec -o $(OBJ)$(MODULE).main.sym -symbols $(OBJ)\n");
3377             f.Puts("\t$(ECC) $(CFLAGS) $(CECFLAGS) $(ECFLAGS) $(PRJ_CFLAGS) $(FVISIBILITY)"
3378                   " -c $(OBJ)$(MODULE).main.ec -o $(call quote_path,$@) -symbols $(OBJ)\n");
3379             f.Puts("\n");
3380          }
3381
3382          if(resNode.files && resNode.files.count && !noResources)
3383          {
3384             f.Puts("ifdef USE_RESOURCES_EAR\n");
3385             f.Puts("$(RESOURCES_EAR): $(RESOURCES) | objdir\n");
3386                resNode.GenMakefileAddResources(f, resNode.path, config, "RESOURCES_EAR");
3387             f.Puts("endif\n");
3388             f.Puts("\n");
3389          }
3390
3391          // *** Target ***
3392
3393          // This would not rebuild the target on updated objects
3394          // f.Printf("$(TARGET): $(SOURCES) $(RESOURCES) | objdir $(SYMBOLS) $(OBJECTS)%s\n", sameOrRelObjTargetDirs ? "" : " targetdir");
3395
3396          // This should fix it for good!
3397          f.Puts("$(SYMBOLS): | objdir\n");
3398          f.Puts("$(OBJECTS): | objdir\n");
3399
3400          // This alone was breaking the tarball, object directory does not get created first (order-only rules happen last it seems!)
3401          f.Printf("$(TARGET): $(SOURCES)%s $(RESOURCES_EAR) $(SYMBOLS) $(OBJECTS) | objdir%s\n",
3402                rcSourcesParts ? " $(RCSOURCES)" : "", sameOrRelObjTargetDirs ? "" : " targetdir");
3403
3404          f.Printf("\t@$(call rm,$(OBJ)objects.lst)\n");
3405          f.Printf("\t@$(call touch,$(OBJ)objects.lst)\n");
3406          OutputFileListActions(f, "_OBJECTS", objectsParts, "$(OBJ)objects.lst");
3407          if(rcSourcesParts)
3408          {
3409             f.Puts("ifdef WINDOWS_TARGET\n");
3410             OutputFileListActions(f, "RCOBJECTS", rcSourcesParts, "$(OBJ)objects.lst");
3411             f.Puts("endif\n");
3412          }
3413          if(numCObjects)
3414          {
3415             f.Printf("\t$(call addtolistfile,$(OBJ)$(MODULE).main$(O),$(OBJ)objects.lst)\n");
3416             OutputFileListActions(f, "ECOBJECTS", eCsourcesParts, "$(OBJ)objects.lst");
3417          }
3418
3419          f.Puts("ifndef STATIC_LIBRARY_TARGET\n");
3420
3421          f.Puts("\t$(LD) $(OFLAGS) @$(OBJ)objects.lst $(LIBS) -o $(TARGET) $(INSTALLNAME)\n");
3422          if(!GetDebug(config))
3423          {
3424             f.Puts("ifndef NOSTRIP\n");
3425             f.Puts("\t$(STRIP) $(STRIPOPT) $(TARGET)\n");
3426             f.Puts("endif\n");
3427
3428             if(GetCompress(config))
3429             {
3430                f.Printf("ifndef %s\n", PlatformToMakefileTargetVariable(win32));
3431                f.Puts("ifdef EXECUTABLE_TARGET\n");
3432                   f.Puts("\t$(UPX) $(UPXFLAGS) $(TARGET)\n");
3433                f.Puts("endif\n");
3434                f.Puts("else\n");
3435                //f.Puts("ifneq ($(TARGET_ARCH),x86_64)\n");
3436                   f.Puts("\t$(UPX) $(UPXFLAGS) $(TARGET)\n");
3437                //f.Puts("endif\n");
3438                f.Puts("endif\n");
3439             }
3440          }
3441          if(resNode.files && resNode.files.count && !noResources)
3442          {
3443             f.Puts("ifndef USE_RESOURCES_EAR\n");
3444             resNode.GenMakefileAddResources(f, resNode.path, config, "TARGET");
3445             f.Puts("endif\n");
3446          }
3447          f.Puts("else\n");
3448          f.Puts("ifdef WINDOWS_HOST\n");
3449          f.Puts("\t$(AR) rcs $(TARGET) @$(OBJ)objects.lst $(LIBS)\n");
3450          f.Puts("else\n");
3451          f.Puts("\t$(AR) rcs $(TARGET) $(OBJECTS) $(LIBS)\n");
3452          f.Puts("endif\n");
3453          f.Puts("endif\n");
3454          f.Puts("ifdef SHARED_LIBRARY_TARGET\n");
3455          f.Puts("ifdef LINUX_TARGET\n");
3456          f.Puts("ifdef LINUX_HOST\n");
3457          // TODO?: support symlinks for longer version numbers
3458          f.Puts("\t$(if $(basename $(VER)),ln -sf $(LP)$(MODULE)$(SO)$(VER) $(OBJ)$(LP)$(MODULE)$(SO)$(basename $(VER)),)\n");
3459          f.Puts("\t$(if $(VER),ln -sf $(LP)$(MODULE)$(SO)$(VER) $(OBJ)$(LP)$(MODULE)$(SO),)\n");
3460          f.Puts("endif\n");
3461          f.Puts("endif\n");
3462          f.Puts("endif\n");
3463
3464          //f.Puts("# POST-BUILD COMMANDS\n");
3465          if(options && options.postbuildCommands)
3466          {
3467             for(s : options.postbuildCommands)
3468                if(s && s[0]) f.Printf("\t%s\n", s);
3469          }
3470          if(config && config.options && config.options.postbuildCommands)
3471          {
3472             for(s : config.options.postbuildCommands)
3473                if(s && s[0]) f.Printf("\t%s\n", s);
3474          }
3475          if(platforms || (config && config.platforms))
3476          {
3477             ifCount = 0;
3478             //f.Puts("# TARGET_PLATFORM-SPECIFIC POST-BUILD COMMANDS\n");
3479             for(platform = (Platform)1; platform < Platform::enumSize; platform++)
3480             {
3481                PlatformOptions projectPOs, configPOs;
3482                MatchProjectAndConfigPlatformOptions(config, platform, &projectPOs, &configPOs);
3483
3484                if((projectPOs && projectPOs.options.postbuildCommands && projectPOs.options.postbuildCommands.count) ||
3485                      (configPOs && configPOs.options.postbuildCommands && configPOs.options.postbuildCommands.count))
3486                {
3487                   if(ifCount)
3488                      f.Puts("else\n");
3489                   ifCount++;
3490                   f.Printf("ifdef %s\n", PlatformToMakefileTargetVariable(platform));
3491
3492                   if(projectPOs && projectPOs.options.postbuildCommands && projectPOs.options.postbuildCommands.count)
3493                   {
3494                      for(s : projectPOs.options.postbuildCommands)
3495                         if(s && s[0]) f.Printf("\t%s\n", s);
3496                   }
3497                   if(configPOs && configPOs.options.postbuildCommands && configPOs.options.postbuildCommands.count)
3498                   {
3499                      for(s : configPOs.options.postbuildCommands)
3500                         if(s && s[0]) f.Printf("\t%s\n", s);
3501                   }
3502                }
3503             }
3504             if(ifCount)
3505             {
3506                int c;
3507                for(c = 0; c < ifCount; c++)
3508                   f.Puts("endif\n");
3509             }
3510          }
3511          f.Puts("\n");
3512
3513          test = false;
3514          if(platforms || (config && config.platforms))
3515          {
3516             for(platform = (Platform)1; platform < Platform::enumSize; platform++)
3517             {
3518                PlatformOptions projectPOs, configPOs;
3519                MatchProjectAndConfigPlatformOptions(config, platform, &projectPOs, &configPOs);
3520
3521                if((projectPOs && projectPOs.options.installCommands && projectPOs.options.installCommands.count) ||
3522                      (configPOs && configPOs.options.installCommands && configPOs.options.installCommands.count))
3523                {
3524                   test = true;
3525                   break;
3526                }
3527             }
3528          }
3529          if(test || (options && options.installCommands) ||
3530                (config && config.options && config.options.installCommands))
3531          {
3532             f.Puts("install:\n");
3533             if(options && options.installCommands)
3534             {
3535                for(s : options.installCommands)
3536                   if(s && s[0]) f.Printf("\t%s\n", s);
3537             }
3538             if(config && config.options && config.options.installCommands)
3539             {
3540                for(s : config.options.installCommands)
3541                   if(s && s[0]) f.Printf("\t%s\n", s);
3542             }
3543             if(platforms || (config && config.platforms))
3544             {
3545                ifCount = 0;
3546                for(platform = (Platform)1; platform < Platform::enumSize; platform++)
3547                {
3548                   PlatformOptions projectPOs, configPOs;
3549                   MatchProjectAndConfigPlatformOptions(config, platform, &projectPOs, &configPOs);
3550
3551                   if((projectPOs && projectPOs.options.installCommands && projectPOs.options.installCommands.count) ||
3552                         (configPOs && configPOs.options.installCommands && configPOs.options.installCommands.count))
3553                   {
3554                      if(ifCount)
3555                         f.Puts("else\n");
3556                      ifCount++;
3557                      f.Printf("ifdef %s\n", PlatformToMakefileTargetVariable(platform));
3558
3559                      if(projectPOs && projectPOs.options.installCommands && projectPOs.options.installCommands.count)
3560                      {
3561                         for(s : projectPOs.options.installCommands)
3562                            if(s && s[0]) f.Printf("\t%s\n", s);
3563                      }
3564                      if(configPOs && configPOs.options.installCommands && configPOs.options.installCommands.count)
3565                      {
3566                         for(s : configPOs.options.installCommands)
3567                            if(s && s[0]) f.Printf("\t%s\n", s);
3568                      }
3569                   }
3570                }
3571                if(ifCount)
3572                {
3573                   int c;
3574                   for(c = 0; c < ifCount; c++)
3575                      f.Puts("endif\n");
3576                }
3577             }
3578             f.Puts("\n");
3579          }
3580
3581          f.Puts("# SYMBOL RULES\n");
3582          f.Puts("\n");
3583
3584          topNode.GenMakefilePrintSymbolRules(f, this, config, nodeCFlagsMapping, nodeECFlagsMapping);
3585
3586          f.Puts("# C OBJECT RULES\n");
3587          f.Puts("\n");
3588
3589          topNode.GenMakefilePrintCObjectRules(f, this, config, nodeCFlagsMapping, nodeECFlagsMapping);
3590
3591          f.Puts("# OBJECT RULES\n");
3592          f.Puts("\n");
3593          // todo call this still but only generate rules whith specific options
3594          // see we-have-file-specific-options in ProjectNode.ec
3595          topNode.GenMakefilePrintObjectRules(f, this, namesInfo, config, nodeCFlagsMapping, nodeECFlagsMapping);
3596
3597          if(numCObjects)
3598             GenMakefilePrintMainObjectRule(f, config);
3599
3600          f.Printf("cleantarget: objdir%s\n", sameOrRelObjTargetDirs ? "" : " targetdir");
3601          if(numCObjects)
3602          {
3603             f.Printf("\t$(call rm,%s)\n", "$(OBJ)$(MODULE).main$(O) $(OBJ)$(MODULE).main.c $(OBJ)$(MODULE).main.ec $(OBJ)$(MODULE).main$(I) $(OBJ)$(MODULE).main$(S)");
3604             f.Printf("\t$(call rm,$(OBJ)symbols.lst)\n");
3605          }
3606          f.Printf("\t$(call rm,$(OBJ)objects.lst)\n");
3607          f.Puts("\t$(call rm,$(TARGET))\n");
3608          f.Puts("ifdef SHARED_LIBRARY_TARGET\n");
3609          f.Puts("ifdef LINUX_TARGET\n");
3610          f.Puts("ifdef LINUX_HOST\n");
3611          // TODO?: support symlinks for longer version numbers
3612          f.Puts("\t$(call rm,$(OBJ)$(LP)$(MODULE)$(SO)$(basename $(VER)))\n");
3613          f.Puts("\t$(call rm,$(OBJ)$(LP)$(MODULE)$(SO))\n");
3614          f.Puts("endif\n");
3615          f.Puts("endif\n");
3616          f.Puts("endif\n");
3617          f.Puts("\n");
3618
3619          f.Puts("clean: cleantarget\n");
3620          OutputCleanActions(f, "OBJECTS", objectsParts);
3621          if(rcSourcesParts)
3622          {
3623             f.Puts("ifdef WINDOWS_TARGET\n");
3624             OutputCleanActions(f, "RCOBJECTS", rcSourcesParts);
3625             f.Puts("endif\n");
3626          }
3627          if(numCObjects)
3628          {
3629             OutputCleanActions(f, "ECOBJECTS", eCsourcesParts);
3630             OutputCleanActions(f, "COBJECTS", eCsourcesParts);
3631             OutputCleanActions(f, "BOWLS", eCsourcesParts);
3632             OutputCleanActions(f, "IMPORTS", eCsourcesParts);
3633             OutputCleanActions(f, "SYMBOLS", eCsourcesParts);
3634          }
3635          if(resNode.files && resNode.files.count && !noResources)
3636          {
3637             f.Puts("ifdef USE_RESOURCES_EAR\n");
3638             f.Printf("\t$(call rm,$(RESOURCES_EAR))\n");
3639             f.Puts("endif\n");
3640          }
3641          f.Puts("\n");
3642
3643          f.Puts("realclean: cleantarget\n");
3644          f.Puts("\t$(call rmr,$(OBJ))\n");
3645          if(!sameOrRelObjTargetDirs)
3646             f.Printf("\t$(call rmdir,%s)\n", targetDirExpNoSpaces);
3647          f.Puts("\n");
3648
3649          f.Puts("distclean: cleantarget\n");
3650          if(!sameOrRelObjTargetDirs)
3651             f.Printf("\t$(call rmdir,%s)\n", targetDirExpNoSpaces);
3652          if(!relObjDir)
3653             f.Puts("\t$(call rmr,obj/)\n");
3654          f.Puts("\t$(call rmr,.configs/)\n");
3655          f.Puts("\t$(call rm,*.ews)\n");
3656          f.Puts("\t$(call rm,*.Makefile)\n");
3657
3658          delete f;
3659
3660          listItems.Free();
3661          delete listItems;
3662          varStringLenDiffs.Free();
3663          delete varStringLenDiffs;
3664          namesInfo.Free();
3665          delete namesInfo;
3666
3667          delete cflagsVariations;
3668          delete nodeCFlagsMapping;
3669          delete ecflagsVariations;
3670          delete nodeECFlagsMapping;
3671
3672          result = true;
3673       }
3674
3675       // ChangeWorkingDir(oldDirectory);
3676       // delete pathBackup;
3677
3678       if(config)
3679          config.makingModified = false;
3680       return result;
3681    }
3682
3683    void GenMakefilePrintMainObjectRule(File f, ProjectConfig config)
3684    {
3685       char extension[MAX_EXTENSION] = "c";
3686       //char modulePath[MAX_LOCATION];
3687       char fixedModuleName[MAX_FILENAME];
3688       //DualPipe dep;
3689       //char command[2048];
3690       char objDirNoSpaces[MAX_LOCATION];
3691       const String objDirExp = GetObjDirExpression(config);
3692
3693       ReplaceSpaces(objDirNoSpaces, objDirExp);
3694       ReplaceSpaces(fixedModuleName, moduleName);
3695
3696       //sprintf(fixedModuleName, "%s.main", fixedPrjName);
3697       //strcat(fixedModuleName, ".main");
3698
3699 #if 0       // TODO: Fix nospaces stuff
3700       // *** Dependency command ***
3701       sprintf(command, "gcc -MT $(OBJ)%s$(O) -MM $(OBJ)%s.c", fixedModuleName, fixedModuleName);
3702
3703       // System Includes (from global settings)
3704       for(item : compiler.dirs[Includes])
3705       {
3706          strcat(command, " -isystem ");
3707          if(strchr(item.name, ' '))
3708          {
3709             strcat(command, "\"");
3710             strcat(command, item);
3711             strcat(command, "\"");
3712          }
3713          else
3714             strcat(command, item);
3715       }
3716
3717       for(item = includeDirs.first; item; item = item.next)
3718       {
3719          strcat(command, " -I");
3720          if(strchr(item.name, ' '))
3721          {
3722             strcat(command, "\"");
3723             strcat(command, item.name);
3724             strcat(command, "\"");
3725          }
3726          else
3727             strcat(command, item.name);
3728       }
3729       for(item = preprocessorDefs.first; item; item = item.next)
3730       {
3731          strcat(command, " -D");
3732          strcat(command, item.name);
3733       }
3734
3735       // Execute it
3736       if((dep = DualPipeOpen(PipeOpenMode { output = true, error = true/*, input = true*/ }, command)))
3737       {
3738          char line[1024];
3739          bool result = true;
3740          bool firstLine = true;
3741
3742          // To do some time: auto save external dependencies?
3743          while(!dep.Eof())
3744          {
3745             if(dep.GetLine(line, sizeof(line)-1))
3746             {
3747                if(firstLine)
3748                {
3749                   char * colon = strstr(line, ":");
3750                   if(strstr(line, "No such file") || strstr(line, ",") || (colon && strstr(colon+1, ":")))
3751                   {
3752                      result = false;
3753                      break;
3754                   }
3755                   firstLine = false;
3756                }
3757                f.Puts(line);
3758                f.Puts("\n");
3759             }
3760             if(!result) break;
3761          }
3762          delete dep;
3763
3764          // If we failed to generate dependencies...
3765          if(!result)
3766          {
3767 #endif
3768             f.Puts("$(OBJ)$(MODULE).main$(O): $(OBJ)$(MODULE).main.c\n");
3769             f.Printf("\t$(CC) $(CFLAGS) $(PRJ_CFLAGS) $(FVISIBILITY) -c $(OBJ)$(MODULE).main.%s -o $(call quote_path,$@)\n", extension);
3770             f.Puts("\n");
3771 #if 0
3772          }
3773       }
3774 #endif
3775    }
3776
3777    void GenMakePrintCustomFlags(File f, const String variableName, bool printNonCustom, Map<String, int> cflagsVariations)
3778    {
3779       int c;
3780       for(c = printNonCustom ? 0 : 1; c <= cflagsVariations.count; c++)
3781       {
3782          for(v : cflagsVariations)
3783          {
3784             if(v == c)
3785             {
3786                if(v == 1)
3787                   f.Printf("%s +=", variableName);
3788                else
3789                   f.Printf("CUSTOM%d_%s =", v-1, variableName);
3790                f.Puts(&v ? &v : "");
3791                f.Puts("\n\n");
3792                break;
3793             }
3794          }
3795       }
3796    }
3797
3798    void MatchProjectAndConfigPlatformOptions(ProjectConfig config, Platform platform,
3799          PlatformOptions * projectPlatformOptions, PlatformOptions * configPlatformOptions)
3800    {
3801       *projectPlatformOptions = null;
3802       *configPlatformOptions = null;
3803       if(platforms)
3804       {
3805          for(p : platforms)
3806          {
3807             if(!strcmpi(p.name, platform))
3808             {
3809                *projectPlatformOptions = p;
3810                break;
3811             }
3812          }
3813       }
3814       if(config && config.platforms)
3815       {
3816          for(p : config.platforms)
3817          {
3818             if(!strcmpi(p.name, platform))
3819             {
3820                *configPlatformOptions = p;
3821                break;
3822             }
3823          }
3824       }
3825    }
3826 }
3827
3828 static inline void ProjectLoadLastBuildNamesInfo(Project prj, ProjectConfig cfg)
3829 {
3830    const char * cfgName = cfg ? cfg.name : "";
3831    Map<String, NameCollisionInfo> cfgNameCollisions = prj.configsNameCollisions[cfgName];
3832    if(cfgNameCollisions)
3833    {
3834       cfgNameCollisions.Free();
3835       delete cfgNameCollisions;
3836    }
3837    prj.configsNameCollisions[cfgName] = cfgNameCollisions = { };
3838    prj.topNode.GenMakefileGetNameCollisionInfo(cfgNameCollisions, cfg);
3839 }
3840
3841 Project LegacyBinaryLoadProject(File f, const char * filePath)
3842 {
3843    Project project = null;
3844    char signature[sizeof(epjSignature)];
3845
3846    f.Read(signature, sizeof(signature), 1);
3847    if(!strncmp(signature, (char *)epjSignature, sizeof(epjSignature)))
3848    {
3849       char topNodePath[MAX_LOCATION];
3850       /*ProjectConfig newConfig
3851       {
3852          name = CopyString("Default");
3853          makingModified = true;
3854          compilingModified = true;
3855          linkingModified = true;
3856          options = { };
3857       };*/
3858
3859       project = Project { options = { } };
3860       LegacyBinaryLoadNode(project.topNode, f);
3861       delete project.topNode.path;
3862       GetWorkingDir(topNodePath, sizeof(topNodePath)-1);
3863       MakeSlashPath(topNodePath);
3864
3865       PathCatSlash(topNodePath, filePath);
3866       project.filePath = topNodePath;
3867
3868       /* THIS IS ALREADY DONE BY filePath property
3869       StripLastDirectory(topNodePath, topNodePath);
3870       project.topNode.path = CopyString(topNodePath);
3871       */
3872       // Shouldn't this be done BEFORE the StripLastDirectory? project.filePath = topNodePath;
3873
3874       // newConfig.options.defaultNameSpace = "";
3875       /*newConfig.objDir.dir = "obj";
3876       newConfig.targetDir.dir = "";*/
3877
3878       //project.configurations = { [ newConfig ] };
3879       //project.config = newConfig;
3880
3881       // Project Settings
3882       if(!f.Eof())
3883       {
3884          int temp;
3885          int len,c, count;
3886          String targetFileName, targetDirectory, objectsDirectory;
3887
3888          // { executable = 0, sharedLibrary = 1, staticLibrary = 2 };
3889          f.Read(&temp, sizeof(int),1);
3890          switch(temp)
3891          {
3892             case 0: project.options.targetType = executable; break;
3893             case 1: project.options.targetType = sharedLibrary; break;
3894             case 2: project.options.targetType = staticLibrary; break;
3895          }
3896
3897          f.Read(&len, sizeof(int),1);
3898          targetFileName = new char[len+1];
3899          f.Read(targetFileName, sizeof(char), len+1);
3900          project.options.targetFileName = targetFileName;
3901          delete targetFileName;
3902
3903          f.Read(&len, sizeof(int),1);
3904          targetDirectory = new char[len+1];
3905          f.Read(targetDirectory, sizeof(char), len+1);
3906          project.options.targetDirectory = targetDirectory;
3907          delete targetDirectory;
3908
3909          f.Read(&len, sizeof(int),1);
3910          objectsDirectory = new byte[len+1];
3911          f.Read(objectsDirectory, sizeof(char), len+1);
3912          project.options.objectsDirectory = objectsDirectory;
3913          delete objectsDirectory;
3914
3915          f.Read(&temp, sizeof(int),1);
3916          project./*config.*/options.debug = temp ? true : false;
3917          f.Read(&temp, sizeof(int),1);
3918          project./*config.*/options.optimization = temp ? speed : none;
3919          f.Read(&temp, sizeof(int),1);
3920          project./*config.*/options.profile = temp ? true : false;
3921          f.Read(&temp, sizeof(int),1);
3922          project.options.warnings = temp ? all : unset;
3923
3924          f.Read(&count, sizeof(int),1);
3925          if(count)
3926          {
3927             project.options.includeDirs = { };
3928             for(c = 0; c < count; c++)
3929             {
3930                char * name;
3931                f.Read(&len, sizeof(int),1);
3932                name = new char[len+1];
3933                f.Read(name, sizeof(char), len+1);
3934                project.options.includeDirs.Add(name);
3935             }
3936          }
3937
3938          f.Read(&count, sizeof(int),1);
3939          if(count)
3940          {
3941             project.options.libraryDirs = { };
3942             for(c = 0; c < count; c++)
3943             {
3944                char * name;
3945                f.Read(&len, sizeof(int),1);
3946                name = new char[len+1];
3947                f.Read(name, sizeof(char), len+1);
3948                project.options.libraryDirs.Add(name);
3949             }
3950          }
3951
3952          f.Read(&count, sizeof(int),1);
3953          if(count)
3954          {
3955             project.options.libraries = { };
3956             for(c = 0; c < count; c++)
3957             {
3958                char * name;
3959                f.Read(&len, sizeof(int),1);
3960                name = new char[len+1];
3961                f.Read(name, sizeof(char), len+1);
3962                project.options.libraries.Add(name);
3963             }
3964          }
3965
3966          f.Read(&count, sizeof(int),1);
3967          if(count)
3968          {
3969             project.options.preprocessorDefinitions = { };
3970             for(c = 0; c < count; c++)
3971             {
3972                char * name;
3973                f.Read(&len, sizeof(int),1);
3974                name = new char[len+1];
3975                f.Read(name, sizeof(char), len+1);
3976                project.options.preprocessorDefinitions.Add(name);
3977             }
3978          }
3979
3980          f.Read(&temp, sizeof(int),1);
3981          project.options.console = temp ? true : false;
3982       }
3983
3984       for(node : project.topNode.files)
3985       {
3986          if(node.type == resources)
3987          {
3988             project.resNode = node;
3989             break;
3990          }
3991       }
3992    }
3993    else
3994       f.Seek(0, start);
3995    return project;
3996 }
3997
3998 void ProjectConfig::LegacyProjectConfigLoad(File f)
3999 {
4000    delete options;
4001    options = { };
4002    while(!f.Eof())
4003    {
4004       char buffer[65536];
4005       char section[128];
4006       char subSection[128];
4007       char * equal;
4008       uint pos;
4009
4010       pos = f.Tell();
4011       f.GetLine(buffer, 65536 - 1);
4012       TrimLSpaces(buffer, buffer);
4013       TrimRSpaces(buffer, buffer);
4014       if(strlen(buffer))
4015       {
4016          if(buffer[0] == '-')
4017          {
4018             equal = &buffer[0];
4019             equal[0] = ' ';
4020             TrimLSpaces(equal, equal);
4021             if(!strcmpi(subSection, "LibraryDirs"))
4022             {
4023                if(!options.libraryDirs)
4024                   options.libraryDirs = { [ CopyString(equal) ] };
4025                else
4026                   options.libraryDirs.Add(CopyString(equal));
4027             }
4028             else if(!strcmpi(subSection, "IncludeDirs"))
4029             {
4030                if(!options.includeDirs)
4031                   options.includeDirs = { [ CopyString(equal) ] };
4032                else
4033                   options.includeDirs.Add(CopyString(equal));
4034             }
4035          }
4036          else if(buffer[0] == '+')
4037          {
4038             if(name)
4039             {
4040                f.Seek(pos, start);
4041                break;
4042             }
4043             else
4044             {
4045                equal = &buffer[0];
4046                equal[0] = ' ';
4047                TrimLSpaces(equal, equal);
4048                delete name; name = CopyString(equal); // property::name = equal;
4049             }
4050          }
4051          else if(!strcmpi(buffer, "Compiler Options"))
4052             strcpy(section, buffer);
4053          else if(!strcmpi(buffer, "IncludeDirs"))
4054             strcpy(subSection, buffer);
4055          else if(!strcmpi(buffer, "Linker Options"))
4056             strcpy(section, buffer);
4057          else if(!strcmpi(buffer, "LibraryDirs"))
4058             strcpy(subSection, buffer);
4059          else if(!strcmpi(buffer, "Files") || !strcmpi(buffer, "Resources"))
4060          {
4061             f.Seek(pos, start);
4062             break;
4063          }
4064          else
4065          {
4066             equal = strstr(buffer, "=");
4067             if(equal)
4068             {
4069                equal[0] = '\0';
4070                TrimRSpaces(buffer, buffer);
4071                equal++;
4072                TrimLSpaces(equal, equal);
4073                if(!strcmpi(buffer, "Target Name"))
4074                   options.targetFileName = /*CopyString(*/equal/*)*/;
4075                else if(!strcmpi(buffer, "Target Type"))
4076                {
4077                   if(!strcmpi(equal, "Executable"))
4078                      options.targetType = executable;
4079                   else if(!strcmpi(equal, "Shared"))
4080                      options.targetType = sharedLibrary;
4081                   else if(!strcmpi(equal, "Static"))
4082                      options.targetType = staticLibrary;
4083                   else
4084                      options.targetType = executable;
4085                }
4086                else if(!strcmpi(buffer, "Target Directory"))
4087                   options.targetDirectory = /*CopyString(*/equal/*)*/;
4088                else if(!strcmpi(buffer, "Console"))
4089                   options.console = ParseTrueFalseValue(equal);
4090                else if(!strcmpi(buffer, "Libraries"))
4091                {
4092                   if(!options.libraries) options.libraries = { };
4093                   ParseArrayValue(options.libraries, equal);
4094                }
4095                else if(!strcmpi(buffer, "Intermediate Directory"))
4096                   options.objectsDirectory = /*CopyString(*/equal/*)*/; //objDir.expression = equal;
4097                else if(!strcmpi(buffer, "Debug"))
4098                   options.debug = ParseTrueFalseValue(equal);
4099                else if(!strcmpi(buffer, "Optimize"))
4100                {
4101                   if(!strcmpi(equal, "None"))
4102                      options.optimization = none;
4103                   else if(!strcmpi(equal, "Speed") || !strcmpi(equal, "True"))
4104                      options.optimization = speed;
4105                   else if(!strcmpi(equal, "Size"))
4106                      options.optimization = size;
4107                   else
4108                      options.optimization = none;
4109                }
4110                else if(!strcmpi(buffer, "Compress"))
4111                   options.compress = ParseTrueFalseValue(equal);
4112                else if(!strcmpi(buffer, "Profile"))
4113                   options.profile = ParseTrueFalseValue(equal);
4114                else if(!strcmpi(buffer, "AllWarnings"))
4115                   options.warnings = ParseTrueFalseValue(equal) ? all : unset;
4116                else if(!strcmpi(buffer, "MemoryGuard"))
4117                   options.memoryGuard = ParseTrueFalseValue(equal);
4118                else if(!strcmpi(buffer, "Default Name Space"))
4119                   options.defaultNameSpace = CopyString(equal);
4120                else if(!strcmpi(buffer, "Strict Name Spaces"))
4121                   options.strictNameSpaces = ParseTrueFalseValue(equal);
4122                else if(!strcmpi(buffer, "Preprocessor Definitions"))
4123                {
4124                   if(!options.preprocessorDefinitions) options.preprocessorDefinitions = { };
4125                   ParseArrayValue(options.preprocessorDefinitions, equal);
4126                }
4127             }
4128          }
4129       }
4130    }
4131    if(!options.targetDirectory && options.objectsDirectory)
4132       options.targetDirectory = /*CopyString(*/options.objectsDirectory/*)*/;
4133    //if(!objDir.dir) objDir.dir = "obj";
4134    //if(!targetDir.dir) targetDir.dir = "";
4135    // if(!targetName) property::targetName = "";   // How can a targetFileName be nothing???
4136    // if(!defaultNameSpace) property::defaultNameSpace = "";
4137    makingModified = true;
4138 }
4139
4140 Project LegacyAsciiLoadProject(File f, const char * filePath)
4141 {
4142    Project project = null;
4143    int pos;
4144    char parentPath[MAX_LOCATION];
4145    char section[128] = "";
4146    char subSection[128] = "";
4147    ProjectNode parent = null;
4148    bool configurationsPresent = false;
4149
4150    f.Seek(0, start);
4151    while(!f.Eof())
4152    {
4153       char buffer[65536];
4154       //char version[16];
4155       char * equal;
4156       int len;
4157       pos = f.Tell();
4158       f.GetLine(buffer, 65536 - 1);
4159       TrimLSpaces(buffer, buffer);
4160       TrimRSpaces(buffer, buffer);
4161       if(strlen(buffer))
4162       {
4163          if(buffer[0] == '-' || buffer[0] == '=')
4164          {
4165             bool simple = buffer[0] == '-';
4166             equal = &buffer[0];
4167             equal[0] = ' ';
4168             TrimLSpaces(equal, equal);
4169             if(!strcmpi(section, "Target") && !strcmpi(subSection, "LibraryDirs"))
4170             {
4171                if(!project.config.options.libraryDirs)
4172                   project.config.options.libraryDirs = { [ CopyString(equal) ] };
4173                else
4174                   project.config.options.libraryDirs.Add(CopyString(equal));
4175             }
4176             else if(!strcmpi(section, "Target") && !strcmpi(subSection, "IncludeDirs"))
4177             {
4178                if(!project.config.options.includeDirs)
4179                   project.config.options.includeDirs = { [ CopyString(equal) ] };
4180                else
4181                   project.config.options.includeDirs.Add(CopyString(equal));
4182             }
4183             else if(!strcmpi(section, "Target") && (!strcmpi(subSection, "Files") || !strcmpi(subSection, "Resources")))
4184             {
4185                len = strlen(equal);
4186                if(len)
4187                {
4188                   char temp[MAX_LOCATION];
4189                   ProjectNode child { };
4190                   // We don't need to do this anymore, fileName is just a property that sets name & path
4191                   // child.fileName = CopyString(equal);
4192                   if(simple)
4193                   {
4194                      child.name = CopyString(equal);
4195                      child.path = CopyString(parentPath);
4196                   }
4197                   else
4198                   {
4199                      GetLastDirectory(equal, temp);
4200                      child.name = CopyString(temp);
4201                      StripLastDirectory(equal, temp);
4202                      child.path = CopyString(temp);
4203                   }
4204                   child.nodeType = file;
4205                   child.parent = parent;
4206                   child.indent = parent.indent + 1;
4207                   child.type = file;
4208                   child.icon = NodeIcons::SelectFileIcon(child.name);
4209                   parent.files.Add(child);
4210                   //node = child;
4211                   //child = null;
4212                }
4213                else
4214                {
4215                   StripLastDirectory(parentPath, parentPath);
4216                   parent = parent.parent;
4217                }
4218             }
4219          }
4220          else if(buffer[0] == '+')
4221          {
4222             equal = &buffer[0];
4223             equal[0] = ' ';
4224             TrimLSpaces(equal, equal);
4225             if(!strcmpi(section, "Target") && (!strcmpi(subSection, "Files") || !strcmpi(subSection, "Resources")))
4226             {
4227                char temp[MAX_LOCATION];
4228                ProjectNode child { };
4229                // NEW: Folders now have a path set like files
4230                child.name = CopyString(equal);
4231                strcpy(temp, parentPath);
4232                PathCatSlash(temp, child.name);
4233                child.path = CopyString(temp);
4234
4235                child.parent = parent;
4236                child.indent = parent.indent + 1;
4237                child.type = folder;
4238                child.nodeType = folder;
4239                child.files = { };
4240                child.icon = folder;
4241                PathCatSlash(parentPath, child.name);
4242                parent.files.Add(child);
4243                parent = child;
4244                //node = child;
4245                //child = null;
4246             }
4247             else if(!strcmpi(section, "Configurations"))
4248             {
4249                ProjectConfig newConfig
4250                {
4251                   makingModified = true;
4252                   options = { };
4253                };
4254                f.Seek(pos, start);
4255                LegacyProjectConfigLoad(newConfig, f);
4256                project.configurations.Add(newConfig);
4257             }
4258          }
4259          else if(!strcmpi(buffer, "ECERE Project File"));
4260          else if(!strcmpi(buffer, "Version 0a"))
4261             ; //strcpy(version, "0a");
4262          else if(!strcmpi(buffer, "Version 0.1a"))
4263             ; //strcpy(version, "0.1a");
4264          else if(!strcmpi(buffer, "Configurations"))
4265          {
4266             project.configurations.Free();
4267             project.config = null;
4268             strcpy(section, buffer);
4269             configurationsPresent = true;
4270          }
4271          else if(!strcmpi(buffer, "Target") || !strnicmp(buffer, "Target \"", strlen("Target \"")))
4272          {
4273             ProjectConfig newConfig { name = CopyString("Default"), options = { } };
4274             char topNodePath[MAX_LOCATION];
4275             // newConfig.defaultNameSpace = "";
4276             //newConfig.objDir.dir = "obj";
4277             //newConfig.targetDir.dir = "";
4278             project = Project { /*options = { }*/ };
4279             project.configurations = { [ newConfig ] };
4280             project.config = newConfig;
4281             // if(project.topNode.path) delete project.topNode.path;
4282             GetWorkingDir(topNodePath, sizeof(topNodePath)-1);
4283             MakeSlashPath(topNodePath);
4284             PathCatSlash(topNodePath, filePath);
4285             project.filePath = topNodePath;
4286             parentPath[0] = '\0';
4287             parent = project.topNode;
4288             //node = parent;
4289             strcpy(section, "Target");
4290             equal = &buffer[6];
4291             if(equal[0] == ' ')
4292             {
4293                equal++;
4294                if(equal[0] == '\"')
4295                {
4296                   StripQuotes(equal, equal);
4297                   delete project.moduleName; project.moduleName = CopyString(equal);
4298                }
4299             }
4300          }
4301          else if(!strcmpi(buffer, "Compiler Options"));
4302          else if(!strcmpi(buffer, "IncludeDirs"))
4303             strcpy(subSection, buffer);
4304          else if(!strcmpi(buffer, "Linker Options"));
4305          else if(!strcmpi(buffer, "LibraryDirs"))
4306             strcpy(subSection, buffer);
4307          else if(!strcmpi(buffer, "Files"))
4308          {
4309             strcpy(section, "Target");
4310             strcpy(subSection, buffer);
4311          }
4312          else if(!strcmpi(buffer, "Resources"))
4313          {
4314             ProjectNode child { };
4315             parent.files.Add(child);
4316             child.parent = parent;
4317             child.indent = parent.indent + 1;
4318             child.name = CopyString(buffer);
4319             child.path = CopyString("");
4320             child.type = resources;
4321             child.files = { };
4322             child.icon = archiveFile;
4323             project.resNode = child;
4324             parent = child;
4325             //node = child;
4326             strcpy(subSection, buffer);
4327          }
4328          else
4329          {
4330             equal = strstr(buffer, "=");
4331             if(equal)
4332             {
4333                equal[0] = '\0';
4334                TrimRSpaces(buffer, buffer);
4335                equal++;
4336                TrimLSpaces(equal, equal);
4337
4338                if(!strcmpi(section, "Target"))
4339                {
4340                   if(!strcmpi(buffer, "Build Exclusions"))
4341                   {
4342                      if(!strcmpi(section, "Target") && !strcmpi(subSection, "Files"))
4343                      {
4344                         /*if(node && node.type != NodeTypes::project)
4345                            ParseListValue(node.buildExclusions, equal);*/
4346                      }
4347                   }
4348                   else if(!strcmpi(buffer, "Path") && !strcmpi(subSection, "Resources"))
4349                   {
4350                      delete project.resNode.path;
4351                      project.resNode.path = CopyString(equal);
4352                      PathCatSlash(parentPath, equal);
4353                   }
4354
4355                   // Config Settings
4356                   else if(!strcmpi(buffer, "Intermediate Directory"))
4357                      project.config.options.objectsDirectory = /*CopyString(*/equal/*)*/; //objDir.expression = equal;
4358                   else if(!strcmpi(buffer, "Debug"))
4359                      project.config.options.debug = ParseTrueFalseValue(equal);
4360                   else if(!strcmpi(buffer, "Optimize"))
4361                   {
4362                      if(!strcmpi(equal, "None"))
4363                         project.config.options.optimization = none;
4364                      else if(!strcmpi(equal, "Speed") || !strcmpi(equal, "True"))
4365                         project.config.options.optimization = speed;
4366                      else if(!strcmpi(equal, "Size"))
4367                         project.config.options.optimization = size;
4368                      else
4369                         project.config.options.optimization = none;
4370                   }
4371                   else if(!strcmpi(buffer, "Profile"))
4372                      project.config.options.profile = ParseTrueFalseValue(equal);
4373                   else if(!strcmpi(buffer, "MemoryGuard"))
4374                      project.config.options.memoryGuard = ParseTrueFalseValue(equal);
4375                   else
4376                   {
4377                      if(!project.options) project.options = { };
4378
4379                      // Project Wide Settings (All configs)
4380                      if(!strcmpi(buffer, "Target Name"))
4381                         project.options.targetFileName = /*CopyString(*/equal/*)*/;
4382                      else if(!strcmpi(buffer, "Target Type"))
4383                      {
4384                         if(!strcmpi(equal, "Executable"))
4385                            project.options.targetType = executable;
4386                         else if(!strcmpi(equal, "Shared"))
4387                            project.options.targetType = sharedLibrary;
4388                         else if(!strcmpi(equal, "Static"))
4389                            project.options.targetType = staticLibrary;
4390                         else
4391                            project.options.targetType = executable;
4392                      }
4393                      else if(!strcmpi(buffer, "Target Directory"))
4394                         project.options.targetDirectory = /*CopyString(*/equal/*)*/;
4395                      else if(!strcmpi(buffer, "Console"))
4396                         project.options.console = ParseTrueFalseValue(equal);
4397                      else if(!strcmpi(buffer, "Libraries"))
4398                      {
4399                         if(!project.options.libraries) project.options.libraries = { };
4400                         ParseArrayValue(project.options.libraries, equal);
4401                      }
4402                      else if(!strcmpi(buffer, "AllWarnings"))
4403                         project.options.warnings = ParseTrueFalseValue(equal) ? all : unset;
4404                      else if(!strcmpi(buffer, "Preprocessor Definitions"))
4405                      {
4406                         if(!strcmpi(section, "Target") && !strcmpi(subSection, "Files"))
4407                         {
4408                            /*if(node && (node.type == NodeTypes::project || (node.type == file && !node.isInResources) || node.type == folder))
4409                               ParseListValue(node.preprocessorDefs, equal);*/
4410                         }
4411                         else
4412                         {
4413                            if(!project.options.preprocessorDefinitions) project.options.preprocessorDefinitions = { };
4414                            ParseArrayValue(project.options.preprocessorDefinitions, equal);
4415                         }
4416                      }
4417                   }
4418                }
4419             }
4420          }
4421       }
4422    }
4423    parent = null;
4424
4425    SplitPlatformLibraries(project);
4426
4427    if(configurationsPresent)
4428       CombineIdenticalConfigOptions(project);
4429    return project;
4430 }
4431
4432 void SplitPlatformLibraries(Project project)
4433 {
4434    if(project && project.configurations)
4435    {
4436       for(cfg : project.configurations)
4437       {
4438          if(cfg.options.libraries && cfg.options.libraries.count)
4439          {
4440             Iterator<String> it { cfg.options.libraries };
4441             while(it.Next())
4442             {
4443                String l = it.data;
4444                char * platformName = strstr(l, ":");
4445                if(platformName)
4446                {
4447                   PlatformOptions platform = null;
4448                   platformName++;
4449                   if(!cfg.platforms) cfg.platforms = { };
4450                   for(p : cfg.platforms)
4451                   {
4452                      if(!strcmpi(platformName, p.name))
4453                      {
4454                         platform = p;
4455                         break;
4456                      }
4457                   }
4458                   if(!platform)
4459                   {
4460                      platform = { name = CopyString(platformName), options = { libraries = { } } };
4461                      cfg.platforms.Add(platform);
4462                   }
4463                   *(platformName-1) = 0;
4464                   platform.options.libraries.Add(CopyString(l));
4465
4466                   cfg.options.libraries.Delete(it.pointer);
4467                   it.pointer = null;
4468                }
4469             }
4470          }
4471       }
4472    }
4473 }
4474
4475 void CombineIdenticalConfigOptions(Project project)
4476 {
4477    if(project && project.configurations && project.configurations.count)
4478    {
4479       DataMember member;
4480       ProjectOptions nullOptions { };
4481       ProjectConfig firstConfig = null;
4482       for(cfg : project.configurations)
4483       {
4484          if(cfg.options.targetType != staticLibrary)
4485          {
4486             firstConfig = cfg;
4487             break;
4488          }
4489       }
4490       if(!firstConfig)
4491          firstConfig = project.configurations.firstIterator.data;
4492
4493       for(member = class(ProjectOptions).membersAndProperties.first; member; member = member.next)
4494       {
4495          if(!member.isProperty)
4496          {
4497             Class type = eSystem_FindClass(__thisModule, member.dataTypeString);
4498             if(type)
4499             {
4500                bool same = true;
4501
4502                for(cfg : project.configurations)
4503                {
4504                   if(cfg != firstConfig)
4505                   {
4506                      if(cfg.options.targetType != staticLibrary)
4507                      {
4508                         int result;
4509
4510                         if(type.type == noHeadClass || type.type == normalClass)
4511                         {
4512                            result = ((int (*)(void *, void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnCompare])(type,
4513                               *(void **)((byte *)firstConfig.options + member.offset + member._class.offset),
4514                               *(void **)((byte *)cfg.options         + member.offset + member._class.offset));
4515                         }
4516                         else
4517                         {
4518                            result = ((int (*)(void *, void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnCompare])(type,
4519                               (byte *)firstConfig.options + member.offset + member._class.offset,
4520                               (byte *)cfg.options         + member.offset + member._class.offset);
4521                         }
4522                         if(result)
4523                         {
4524                            same = false;
4525                            break;
4526                         }
4527                      }
4528                   }
4529                }
4530                if(same)
4531                {
4532                   if(type.type == noHeadClass || type.type == normalClass)
4533                   {
4534                      if(!((int (*)(void *, void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnCompare])(type,
4535                         *(void **)((byte *)firstConfig.options + member.offset + member._class.offset),
4536                         *(void **)((byte *)nullOptions         + member.offset + member._class.offset)))
4537                         continue;
4538                   }
4539                   else
4540                   {
4541                      if(!((int (*)(void *, void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnCompare])(type,
4542                         (byte *)firstConfig.options + member.offset + member._class.offset,
4543                         (byte *)nullOptions         + member.offset + member._class.offset))
4544                         continue;
4545                   }
4546
4547                   if(!project.options) project.options = { };
4548
4549                   /*if(type.type == noHeadClass || type.type == normalClass)
4550                   {
4551                      ((void (*)(void *, void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnCopy])(type,
4552                         (byte *)project.options + member.offset + member._class.offset,
4553                         *(void **)((byte *)firstConfig.options + member.offset + member._class.offset));
4554                   }
4555                   else
4556                   {
4557                      void * address = (byte *)firstConfig.options + member.offset + member._class.offset;
4558                      // TOFIX: ListBox::SetData / OnCopy mess
4559                      ((void (*)(void *, void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnCopy])(type,
4560                         (byte *)project.options + member.offset + member._class.offset,
4561                         (type.typeSize > 4) ? address :
4562                            ((type.typeSize == 4) ? (void *)*(uint32 *)address :
4563                               ((type.typeSize == 2) ? (void *)*(uint16*)address :
4564                                  (void *)*(byte *)address )));
4565                   }*/
4566                   memcpy(
4567                      (byte *)project.options + member.offset + member._class.offset,
4568                      (byte *)firstConfig.options + member.offset + member._class.offset, type.typeSize);
4569
4570                   for(cfg : project.configurations)
4571                   {
4572                      if(cfg.options.targetType == staticLibrary)
4573                      {
4574                         int result;
4575
4576                         if(type.type == noHeadClass || type.type == normalClass)
4577                         {
4578                            result = ((int (*)(void *, void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnCompare])(type,
4579                               *(void **)((byte *)firstConfig.options + member.offset + member._class.offset),
4580                               *(void **)((byte *)cfg.options         + member.offset + member._class.offset));
4581                         }
4582                         else
4583                         {
4584                            result = ((int (*)(void *, void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnCompare])(type,
4585                               (byte *)firstConfig.options + member.offset + member._class.offset,
4586                               (byte *)cfg.options         + member.offset + member._class.offset);
4587                         }
4588                         if(result)
4589                            continue;
4590                      }
4591                      if(cfg != firstConfig)
4592                      {
4593                         if(type.type == noHeadClass || type.type == normalClass)
4594                         {
4595                            ((void (*)(void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnFree])(type,
4596                               *(void **)((byte *)cfg.options + member.offset + member._class.offset));
4597                         }
4598                         else
4599                         {
4600                            ((void (*)(void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnFree])(type,
4601                               (byte *)cfg.options + member.offset + member._class.offset);
4602                         }
4603                         memset((byte *)cfg.options + member.offset + member._class.offset, 0, type.typeSize);
4604                      }
4605                   }
4606                   memset((byte *)firstConfig.options + member.offset + member._class.offset, 0, type.typeSize);
4607                }
4608             }
4609          }
4610       }
4611       delete nullOptions;
4612
4613       // Compare Platform Specific Settings
4614       {
4615          bool same = true;
4616          for(cfg : project.configurations)
4617          {
4618             if(cfg != firstConfig && cfg.options.targetType != staticLibrary && (firstConfig.platforms || cfg.platforms) &&
4619                ((!firstConfig.platforms && cfg.platforms) || firstConfig.platforms.OnCompare(cfg.platforms)))
4620             {
4621                same = false;
4622                break;
4623             }
4624          }
4625          if(same && firstConfig.platforms)
4626          {
4627             for(cfg : project.configurations)
4628             {
4629                if(cfg.options.targetType == staticLibrary && firstConfig.platforms.OnCompare(cfg.platforms))
4630                   continue;
4631                if(cfg != firstConfig)
4632                {
4633                   cfg.platforms = null;
4634                }
4635             }
4636             project.platforms = firstConfig.platforms;
4637             *&firstConfig.platforms = null;
4638          }
4639       }
4640
4641       // Static libraries can't contain libraries
4642       for(cfg : project.configurations)
4643       {
4644          if(cfg.options.targetType == staticLibrary)
4645          {
4646             if(!cfg.options.libraries) cfg.options.libraries = { };
4647             cfg.options.libraries.Free();
4648          }
4649       }
4650    }
4651 }
4652
4653 Project LoadProject(const char * filePath, const char * activeConfigName)
4654 {
4655    Project project = null;
4656    File f = FileOpen(filePath, read);
4657    if(f)
4658    {
4659       project = LegacyBinaryLoadProject(f, filePath);
4660       if(!project)
4661       {
4662          ECONParser parser { f = f };
4663          /*JSONResult result = */parser.GetObject(class(Project), &project);
4664          if(project)
4665          {
4666             char insidePath[MAX_LOCATION];
4667
4668             delete project.topNode.files;
4669             if(!project.files) project.files = { };
4670             project.topNode.files = project.files;
4671
4672             {
4673                char topNodePath[MAX_LOCATION];
4674                GetWorkingDir(topNodePath, sizeof(topNodePath)-1);
4675                MakeSlashPath(topNodePath);
4676                PathCatSlash(topNodePath, filePath);
4677                project.filePath = topNodePath;//filePath;
4678             }
4679
4680             project.topNode.FixupNode(insidePath);
4681
4682             project.resNode = project.topNode.Add(project, "Resources", project.topNode.files.last, resources, archiveFile, false);
4683             delete project.resNode.path;
4684             project.resNode.path = project.resourcesPath;
4685             project.resourcesPath = null;
4686             project.resNode.nodeType = (ProjectNodeType)-1;
4687             delete project.resNode.files;
4688             project.resNode.files = project.resources;
4689             project.files = null;
4690             project.resources = null;
4691             if(!project.configurations) project.configurations = { };
4692
4693             project.resNode.FixupNode(insidePath);
4694          }
4695          delete parser;
4696       }
4697       if(!project)
4698          project = LegacyAsciiLoadProject(f, filePath);
4699
4700       delete f;
4701
4702       if(project)
4703       {
4704          if(!project.options) project.options = { };
4705          if(activeConfigName && activeConfigName[0] && project.configurations)
4706             project.config = project.GetConfig(activeConfigName);
4707          if(!project.config && project.configurations)
4708             project.config = project.configurations.firstIterator.data;
4709
4710          if(!project.resNode)
4711          {
4712             project.resNode = project.topNode.Add(project, "Resources", project.topNode.files.last, resources, archiveFile, false);
4713          }
4714
4715          if(!project.moduleName)
4716             project.moduleName = CopyString(project.name);
4717          if(project.config &&
4718             (!project.options || !project.options.targetFileName || !project.options.targetFileName[0]) &&
4719             (!project.config.options.targetFileName || !project.config.options.targetFileName[0]))
4720          {
4721             //delete project.config.options.targetFileName;
4722
4723             project.options.targetFileName = /*CopyString(*/project.moduleName/*)*/;
4724             project.config.options.optimization = none;
4725             project.config.options.debug = true;
4726             //project.config.options.warnings = unset;
4727             project.config.options.memoryGuard = false;
4728             project.config.compilingModified = true;
4729             project.config.linkingModified = true;
4730          }
4731          else if(!project.topNode.name && project.config)
4732          {
4733             project.topNode.name = CopyString(project.config.options.targetFileName);
4734          }
4735
4736          /* // THIS IS NOW AUTOMATED WITH A project CHECK IN ProjectNode
4737          project.topNode.configurations = project.configurations;
4738          project.topNode.platforms = project.platforms;
4739          project.topNode.options = project.options;*/
4740       }
4741    }
4742    return project;
4743 }
4744
4745 #ifndef MAKEFILE_GENERATOR
4746 static GccVersionInfo GetGccVersionInfo(CompilerConfig compiler, const String compilerCommand)
4747 {
4748    GccVersionInfo result = unknown;
4749    if(compiler.ccCommand)
4750    {
4751       char command[MAX_F_STRING*4];
4752       DualPipe f;
4753       sprintf(command, "%s%s --version", compiler.gccPrefix ? compiler.gccPrefix : "", compilerCommand);
4754       if((f = DualPipeOpen(PipeOpenMode { output = true, error = true, input = true }, command)))
4755       {
4756          bool firstLine = true;
4757          while(!f.eof)
4758          {
4759             char line[1024];
4760             char * tokens[128];
4761             if(f.GetLine(line,sizeof(line)))
4762             {
4763                if(firstLine)
4764                {
4765                   uint count = Tokenize(line, sizeof(tokens)/sizeof(tokens[0]), tokens,false);
4766                   char * token = null;
4767                   int i;
4768                   bool inPar = false;
4769                   for(i = 0; i < count; i++)
4770                   {
4771                      if(tokens[i][0] == '(')
4772                      {
4773                         if(tokens[i][strlen(tokens[i])-1] != ')')
4774                            inPar = true;
4775                      }
4776                      else if(tokens[i][0] && tokens[i][strlen(tokens[i])-1] == ')')
4777                         inPar = false;
4778                      else if(!inPar && isdigit(tokens[i][0]) && strchr(tokens[i], '.'))
4779                         token = tokens[i];
4780                   }
4781                   if(token)
4782                      result = GccVersionInfo::GetVersionInfo(token);
4783                   firstLine = false;
4784                }
4785             }
4786          }
4787          delete f;
4788       }
4789    }
4790    return result;
4791 }
4792
4793 static enum GccVersionInfo
4794 {
4795    unknown, pre4_8, post4_8;
4796
4797    GccVersionInfo ::GetVersionInfo(char * version)
4798    {
4799       GccVersionInfo result = unknown;
4800       int ver;
4801       char * s = CopyString(version);
4802       char * tokens[16];
4803       uint count = TokenizeWith(s, sizeof(tokens)/sizeof(tokens[0]), tokens, ".", false);
4804       ver = count > 1 ? atoi(tokens[1]) : 0;
4805       ver += count ? atoi(tokens[0]) * 1000 : 0;
4806       if(ver > 0)
4807       {
4808          if(ver < 4008)
4809             result = pre4_8;
4810          else
4811             result = post4_8;
4812       }
4813       delete s;
4814       return result;
4815    }
4816 };
4817 #endif