ide: Support for .epj files in econ format. econ is a superset of json.
[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 true;
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, "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),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),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),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 := $(GCC_PREFIX)%s$(_SYSROOT)$(if $(GCC_LD_FLAGS),$(space)$(GCC_LD_FLAGS),)\n",
2580                   compiler.ldCommand && compiler.ldCommand[0] ? compiler.ldCommand : "$(if $(CONTAINS_CXX),$(CXX),$(CC))");
2581             f.Printf("AR := $(GCC_PREFIX)%s\n", compiler.arCommand);
2582             f.Puts("STRIP := $(GCC_PREFIX)strip\n");
2583             f.Puts("ifdef WINDOWS_TARGET\n");
2584             f.Puts("WINDRES := $(GCC_PREFIX)windres\n");
2585             f.Puts(" ifdef ARCH\n");
2586             f.Puts("  ifeq ($(ARCH),x32)\n");
2587             f.Puts("WINDRES_FLAGS := -F pe-i386\n");
2588             f.Puts("  else\n");
2589             f.Puts("   ifeq ($(ARCH),x64)\n");
2590             f.Puts("WINDRES_FLAGS := -F pe-x86-64\n");
2591             f.Puts("   endif\n");
2592             f.Puts("  endif\n");
2593             f.Puts(" endif\n");
2594             f.Puts("endif\n");
2595             f.Puts("UPX := upx\n");
2596             f.Puts("\n");
2597
2598             f.Puts("UPXFLAGS = -9\n"); // TOFEAT: Compression Level Option? Other UPX Options?
2599             f.Puts("\n");
2600
2601             f.Puts("EARFLAGS = \n");
2602             f.Puts("\n");
2603
2604             f.Puts("ifndef ARCH\n");
2605             f.Puts("TARGET_ARCH :=$(shell $(CC) -dumpmachine)\n");
2606             f.Puts(" ifdef WINDOWS_HOST\n");
2607             f.Puts("  ifneq ($(filter x86_64%,$(TARGET_ARCH)),)\n");
2608             f.Puts("     TARGET_ARCH := x86_64\n");
2609             f.Puts("  else\n");
2610             f.Puts("     TARGET_ARCH := i386\n");
2611             f.Puts("  endif\n");
2612             f.Puts(" endif\n");
2613             f.Puts("endif\n\n");
2614
2615             f.Puts("# HARD CODED TARGET_PLATFORM-SPECIFIC OPTIONS\n");
2616             f.Printf("LDFLAGS +=$(if $(%s), -Wl$(comma)--no-undefined,)\n", PlatformToMakefileTargetVariable(tux));
2617             f.Puts("\n");
2618
2619             // JF's
2620             f.Printf("LDFLAGS +=$(if $(%s), -framework cocoa -framework OpenGL,)\n", PlatformToMakefileTargetVariable(apple));
2621
2622             if(gccCompiler)
2623             {
2624                f.Puts("\nCFLAGS += -fmessage-length=0\n");
2625             }
2626
2627             if(compiler.includeDirs && compiler.includeDirs.count)
2628             {
2629                f.Puts("\nCFLAGS +=");
2630                OutputFlags(f, gccCompiler ? _isystem : _I, compiler.includeDirs, lineEach);
2631                f.Puts("\n");
2632             }
2633             if(compiler.prepDirectives && compiler.prepDirectives.count)
2634             {
2635                f.Puts("\nCFLAGS +=");
2636                OutputFlags(f, _D, compiler.prepDirectives, inPlace);
2637                f.Puts("\n");
2638             }
2639             if(compiler.libraryDirs && compiler.libraryDirs.count)
2640             {
2641                f.Puts("\nLDFLAGS +=");
2642                OutputFlags(f, _L, compiler.libraryDirs, lineEach);
2643                // We would need a bool option to know whether we want to add to rpath as well...
2644                // OutputFlags(f, _Wl-rpath, compiler.libraryDirs, lineEach);
2645                f.Puts("\n");
2646             }
2647             if(compiler.excludeLibs && compiler.excludeLibs.count)
2648             {
2649                f.Puts("\nEXCLUDED_LIBS =");
2650                for(l : compiler.excludeLibs)
2651                {
2652                   f.Puts(" ");
2653                   f.Puts(l);
2654                }
2655             }
2656             if(compiler.eCcompilerFlags && compiler.eCcompilerFlags.count)
2657             {
2658                f.Puts("\nECFLAGS +=");
2659                OutputFlags(f, any, compiler.eCcompilerFlags, inPlace);
2660                f.Puts("\n");
2661             }
2662             if(compiler.compilerFlags && compiler.compilerFlags.count)
2663             {
2664                f.Puts("\nCFLAGS +=");
2665                OutputFlags(f, any, compiler.compilerFlags, inPlace);
2666                f.Puts("\n");
2667             }
2668             if(compiler.linkerFlags && compiler.linkerFlags.count)
2669             {
2670                f.Puts("\nLDFLAGS +=");
2671                OutputFlags(f, _Wl, compiler.linkerFlags, inPlace);
2672                f.Puts("\n");
2673             }
2674             f.Puts("\n");
2675             f.Puts("\nOFLAGS += $(LDFLAGS)");
2676             f.Puts("\n");
2677             f.Puts("ifdef ARCH_FLAGS\n");
2678             f.Puts("CFLAGS += $(ARCH_FLAGS)\n");
2679             f.Puts("OFLAGS += $(ARCH_FLAGS)\n");
2680             f.Puts("endif\n");
2681
2682             delete f;
2683
2684             result = true;
2685          }
2686       }
2687       delete name;
2688       delete compilerName;
2689       return result;
2690    }
2691
2692    bool GenerateMakefile(const char * altMakefilePath, bool noResources, const char * includemkPath, ProjectConfig config)
2693    {
2694       bool result = false;
2695       char filePath[MAX_LOCATION];
2696       char makeFile[MAX_LOCATION];
2697       // PathBackup pathBackup { };
2698       // char oldDirectory[MAX_LOCATION];
2699       File f = null;
2700
2701       if(!altMakefilePath)
2702       {
2703          strcpy(filePath, topNode.path);
2704          CatMakeFileName(makeFile, config);
2705          PathCatSlash(filePath, makeFile);
2706       }
2707
2708       f = FileOpen(altMakefilePath ? altMakefilePath : filePath, write);
2709
2710       /*SetPath(false, compiler, config);
2711       GetWorkingDir(oldDirectory, MAX_LOCATION);
2712       ChangeWorkingDir(topNode.path);*/
2713
2714       if(f)
2715       {
2716          bool test;
2717          int ifCount;
2718          Platform platform;
2719          char targetDir[MAX_LOCATION];
2720          char objDirExpNoSpaces[MAX_LOCATION];
2721          char objDirNoSpaces[MAX_LOCATION];
2722          char resDirNoSpaces[MAX_LOCATION];
2723          char targetDirExpNoSpaces[MAX_LOCATION];
2724          char fixedModuleName[MAX_FILENAME];
2725          char fixedConfigName[MAX_FILENAME];
2726          int c;
2727          int lenObjDirExpNoSpaces, lenTargetDirExpNoSpaces;
2728          // Non-zero if we're building eC code
2729          // We'll have to be careful with this when merging configs where eC files can be excluded in some configs and included in others
2730          int numCObjects = 0;
2731          int numObjects = 0;
2732          int numRCObjects = 0;
2733          bool containsCXX = false; // True if the project contains a C++ file
2734          bool relObjDir, sameOrRelObjTargetDirs;
2735          const String objDirExp = GetObjDirExpression(config);
2736          TargetTypes targetType = GetTargetType(config);
2737
2738          char cfDir[MAX_LOCATION];
2739          int objectsParts = 0;
2740          int eCsourcesParts = 0;
2741          int rcSourcesParts = 0;
2742          Array<String> listItems { };
2743          Map<String, int> varStringLenDiffs { };
2744          Map<String, NameCollisionInfo> namesInfo { };
2745
2746          Map<String, int> cflagsVariations { };
2747          Map<intptr, int> nodeCFlagsMapping { };
2748
2749          Map<String, int> ecflagsVariations { };
2750          Map<intptr, int> nodeECFlagsMapping { };
2751
2752          ReplaceSpaces(objDirNoSpaces, objDirExp);
2753          strcpy(targetDir, GetTargetDirExpression(config));
2754          ReplaceSpaces(targetDirExpNoSpaces, targetDir);
2755
2756          strcpy(objDirExpNoSpaces, GetObjDirExpression(config));
2757          ChangeCh(objDirExpNoSpaces, '\\', '/'); // TODO: this is a hack, paths should never include win32 path seperators - fix this in ProjectSettings and ProjectLoad instead
2758          {
2759             char temp[MAX_LOCATION];
2760             ReplaceSpaces(temp, objDirExpNoSpaces);
2761             strcpy(objDirExpNoSpaces, temp);
2762          }
2763          ReplaceSpaces(resDirNoSpaces, resNode.path ? resNode.path : "");
2764          ReplaceSpaces(fixedModuleName, moduleName);
2765          ReplaceSpaces(fixedConfigName, GetConfigName(config));
2766          CamelCase(fixedConfigName);
2767
2768          lenObjDirExpNoSpaces = strlen(objDirExpNoSpaces);
2769          relObjDir = lenObjDirExpNoSpaces == 0 ||
2770                (objDirExpNoSpaces[0] == '.' && (lenObjDirExpNoSpaces == 1 || objDirExpNoSpaces[1] == '.'));
2771          lenTargetDirExpNoSpaces = strlen(targetDirExpNoSpaces);
2772          sameOrRelObjTargetDirs = lenTargetDirExpNoSpaces == 0 ||
2773                (targetDirExpNoSpaces[0] == '.' && (lenTargetDirExpNoSpaces == 1 || targetDirExpNoSpaces[1] == '.')) ||
2774                !fstrcmp(objDirExpNoSpaces, targetDirExpNoSpaces);
2775
2776          f.Printf(".PHONY: all objdir%s cleantarget clean realclean distclean\n\n", sameOrRelObjTargetDirs ? "" : " targetdir");
2777
2778          f.Puts("# CORE VARIABLES\n\n");
2779
2780          f.Printf("MODULE := %s\n", fixedModuleName);
2781          f.Printf("VERSION := %s\n", property::moduleVersion);
2782          f.Printf("CONFIG := %s\n", fixedConfigName);
2783          topNode.GenMakefilePrintNode(f, this, noPrint, null, null, config, &containsCXX);
2784          if(containsCXX)
2785             f.Puts("CONTAINS_CXX := defined\n");
2786          f.Puts("ifndef COMPILER\n" "COMPILER := default\n" "endif\n");
2787          f.Puts("\n");
2788
2789          test = GetTargetTypeIsSetByPlatform(config);
2790          if(test)
2791          {
2792             ifCount = 0;
2793             for(platform = (Platform)1; platform < Platform::enumSize; platform++)
2794             {
2795                TargetTypes targetType;
2796                PlatformOptions projectPOs, configPOs;
2797                MatchProjectAndConfigPlatformOptions(config, platform, &projectPOs, &configPOs);
2798                targetType = platformTargetType;
2799                if(targetType)
2800                {
2801                   if(ifCount)
2802                      f.Puts("else\n");
2803                   ifCount++;
2804                   f.Printf("ifdef %s\n", PlatformToMakefileTargetVariable(platform));
2805                   f.Printf("TARGET_TYPE = %s\n", TargetTypeToMakefileVariable(targetType));
2806                }
2807             }
2808             f.Puts("else\n");
2809          }
2810          f.Printf("TARGET_TYPE = %s\n", TargetTypeToMakefileVariable(targetType));
2811          if(test)
2812          {
2813             if(ifCount)
2814             {
2815                for(c = 0; c < ifCount; c++)
2816                   f.Puts("endif\n");
2817             }
2818          }
2819          f.Puts("\n");
2820
2821          f.Puts("# FLAGS\n\n");
2822
2823          f.Puts("ECFLAGS =\n");
2824          f.Puts("ifndef DEBIAN_PACKAGE\n" "CFLAGS =\n" "LDFLAGS =\n" "endif\n");
2825          f.Puts("PRJ_CFLAGS =\n");
2826          f.Puts("CECFLAGS =\n");
2827          f.Puts("OFLAGS =\n");
2828          f.Puts("LIBS =\n");
2829          f.Puts("\n");
2830
2831          f.Puts("ifdef DEBUG\n" "NOSTRIP := y\n" "endif\n");
2832          f.Puts("\n");
2833
2834          // Important: We cannot use this ifdef anymore, EXECUTABLE_TARGET is not yet defined. It's embedded in the crossplatform.mk EXECUTABLE
2835          //f.Puts("ifdef EXECUTABLE_TARGET\n");
2836          f.Printf("CONSOLE = %s\n", GetConsole(config) ? "-mconsole" : "-mwindows");
2837          //f.Puts("endif\n");
2838          f.Puts("\n");
2839
2840          f.Puts("# INCLUDES\n\n");
2841
2842          if(compilerConfigsDir && compilerConfigsDir[0])
2843          {
2844             strcpy(cfDir, compilerConfigsDir);
2845             if(cfDir[0] && cfDir[strlen(cfDir)-1] != '/')
2846                strcat(cfDir, "/");
2847          }
2848          else
2849          {
2850             GetIDECompilerConfigsDir(cfDir, true, true);
2851             // Use CF_DIR environment variable for absolute paths only
2852             if(cfDir[0] == '/' || (cfDir[0] && cfDir[1] == ':'))
2853                strcpy(cfDir, "$(CF_DIR)");
2854          }
2855
2856          f.Printf("_CF_DIR = %s\n", cfDir);
2857          f.Puts("\n");
2858
2859          f.Printf("include %s\n", includemkPath ? includemkPath : "$(_CF_DIR)crossplatform.mk");
2860          f.Puts("include $(_CF_DIR)$(TARGET_PLATFORM)-$(COMPILER).cf\n");
2861          f.Puts("\n");
2862
2863          f.Puts("# POST-INCLUDES VARIABLES\n\n");
2864
2865          f.Printf("OBJ = %s%s\n", objDirExpNoSpaces, objDirExpNoSpaces[0] ? "/" : "");
2866          f.Puts("\n");
2867
2868          f.Printf("RES = %s%s\n", resDirNoSpaces, resDirNoSpaces[0] ? "/" : "");
2869          f.Puts("\n");
2870
2871          // test = GetTargetTypeIsSetByPlatform(config);
2872          {
2873             char target[MAX_LOCATION];
2874             char temp[MAX_LOCATION];
2875             if(test)
2876             {
2877                TargetTypes type;
2878                ifCount = 0;
2879                for(type = (TargetTypes)1; type < TargetTypes::enumSize; type++)
2880                {
2881                   if(type != targetType)
2882                   {
2883                      if(ifCount)
2884                         f.Puts("else\n");
2885                      ifCount++;
2886                      f.Printf("ifeq ($(TARGET_TYPE),%s)\n", TargetTypeToMakefileVariable(type));
2887
2888                      GetMakefileTargetFileName(type, target, config);
2889                      strcpy(temp, targetDir);
2890                      PathCatSlash(temp, target);
2891                      ReplaceSpaces(target, temp);
2892                      f.Printf("TARGET = %s\n", target);
2893                   }
2894                }
2895                f.Puts("else\n");
2896             }
2897             GetMakefileTargetFileName(targetType, target, config);
2898             strcpy(temp, targetDir);
2899             PathCatSlash(temp, target);
2900             ReplaceSpaces(target, temp);
2901             f.Printf("TARGET = %s\n", target);
2902
2903             if(test)
2904             {
2905                if(ifCount)
2906                {
2907                   for(c = 0; c < ifCount; c++)
2908                      f.Puts("endif\n");
2909                }
2910             }
2911          }
2912          f.Puts("\n");
2913
2914          // Use something fixed here, to not cause Makefile differences across compilers...
2915          varStringLenDiffs["$(OBJ)"] = 30; // strlen("obj/memoryGuard.android.gcc-4.6.2") - 6;
2916          // varStringLenDiffs["$(OBJ)"] = strlen(objDirNoSpaces) - 6;
2917
2918          topNode.GenMakefileGetNameCollisionInfo(namesInfo, config);
2919
2920          {
2921             int c;
2922             const char * map[5][2] = { { "COBJECTS", "C" }, { "SYMBOLS", "S" }, { "IMPORTS", "I" }, { "ECOBJECTS", "O" }, { "BOWLS", "B" } };
2923
2924             numCObjects = topNode.GenMakefilePrintNode(f, this, eCsources, namesInfo, listItems, config, null);
2925             if(numCObjects)
2926             {
2927                eCsourcesParts = OutputFileList(f, "_ECSOURCES", listItems, varStringLenDiffs, null);
2928
2929                f.Puts("ECSOURCES = $(call shwspace,$(_ECSOURCES))\n");
2930                if(eCsourcesParts > 1)
2931                {
2932                   for(c = 1; c <= eCsourcesParts; c++)
2933                      f.Printf("ECSOURCES%d = $(call shwspace,$(_ECSOURCES%d))\n", c, c);
2934                }
2935                f.Puts("\n");
2936
2937                for(c = 0; c < 5; c++)
2938                {
2939                   if(eCsourcesParts > 1)
2940                   {
2941                      int n;
2942                      f.Printf("_%s =", map[c][0]);
2943                      for(n = 1; n <= eCsourcesParts; n++)
2944                         f.Printf(" $(%s%d)", map[c][0], n);
2945                      f.Puts("\n");
2946                      for(n = 1; n <= eCsourcesParts; n++)
2947                         f.Printf("_%s%d = $(addprefix $(OBJ),$(patsubst %%.ec,%%$(%s),$(notdir $(_ECSOURCES%d))))\n", map[c][0], n, map[c][1], n);
2948                   }
2949                   else if(eCsourcesParts == 1)
2950                      f.Printf("_%s = $(addprefix $(OBJ),$(patsubst %%.ec,%%$(%s),$(notdir $(_ECSOURCES))))\n", map[c][0], map[c][1]);
2951                   f.Puts("\n");
2952                }
2953
2954                for(c = 0; c < 5; c++)
2955                {
2956                   if(eCsourcesParts > 1)
2957                   {
2958                      int n;
2959                      f.Printf("%s =", map[c][0]);
2960                      for(n = 1; n <= eCsourcesParts; n++)
2961                         f.Printf(" $(%s%d)", map[c][0], n);
2962                      f.Puts("\n");
2963                      for(n = 1; n <= eCsourcesParts; n++)
2964                         f.Printf("%s%d = $(call shwspace,$(_%s%d))\n", map[c][0], n, map[c][0], n);
2965                   }
2966                   else if(eCsourcesParts == 1)
2967                      f.Printf("%s = $(call shwspace,$(_%s))\n", map[c][0], map[c][0]);
2968                   f.Puts("\n");
2969                }
2970             }
2971          }
2972
2973          numRCObjects = topNode.GenMakefilePrintNode(f, this, rcSources, namesInfo, listItems, config, null);
2974          if(numRCObjects)
2975          {
2976             f.Puts("ifdef WINDOWS_TARGET\n\n");
2977
2978             rcSourcesParts = OutputFileList(f, "_RCSOURCES", listItems, varStringLenDiffs, null);
2979
2980             f.Puts("RCSOURCES = $(call shwspace,$(_RCSOURCES))\n");
2981             if(rcSourcesParts > 1)
2982             {
2983                for(c = 1; c <= rcSourcesParts; c++)
2984                   f.Printf("RCSOURCES%d = $(call shwspace,$(_RCSOURCES%d))\n", c, c);
2985             }
2986             f.Puts("\n");
2987             if(rcSourcesParts > 1)
2988             {
2989                int n;
2990                f.Printf("%s =", "RCOBJECTS");
2991                for(n = 1; n <= rcSourcesParts; n++)
2992                   f.Printf(" $(%s%d)", "RCOBJECTS", n);
2993                f.Puts("\n");
2994                for(n = 1; n <= rcSourcesParts; n++)
2995                   f.Printf("%s%d = $(call shwspace,$(addprefix $(OBJ),$(patsubst %%.rc,%%$(%s),$(notdir $(_RCSOURCES%d)))))\n", "RCOBJECTS", n, "O", n);
2996             }
2997             else if(rcSourcesParts == 1)
2998                f.Printf("%s = $(call shwspace,$(addprefix $(OBJ),$(patsubst %%.rc,%%$(%s),$(notdir $(_RCSOURCES)))))\n", "RCOBJECTS", "O");
2999             f.Puts("\n");
3000
3001             f.Puts("else\n");
3002             f.Puts("RCSOURCES =\n");
3003             f.Puts("RCOBJECTS =\n");
3004             f.Puts("endif\n\n");
3005          }
3006
3007          numObjects = topNode.GenMakefilePrintNode(f, this, objects, namesInfo, listItems, config, null);
3008          if(numObjects)
3009             objectsParts = OutputFileList(f, "_OBJECTS", listItems, varStringLenDiffs, null);
3010          f.Printf("OBJECTS =%s%s%s%s\n",
3011                numObjects ? " $(_OBJECTS)" : "", numCObjects ? " $(ECOBJECTS)" : "",
3012                numCObjects ? " $(OBJ)$(MODULE).main$(O)" : "",
3013                numRCObjects ? " $(RCOBJECTS)" : "");
3014          f.Puts("\n");
3015
3016          topNode.GenMakefilePrintNode(f, this, sources, null, listItems, config, null);
3017          {
3018             const char * prefix;
3019             if(numCObjects && numRCObjects)
3020                prefix = "$(ECSOURCES) $(RCSOURCES)";
3021             else if(numCObjects)
3022                prefix = "$(ECSOURCES)";
3023             else
3024                prefix = null;
3025             OutputFileList(f, "SOURCES", listItems, varStringLenDiffs, prefix);
3026          }
3027
3028          if(!noResources)
3029             resNode.GenMakefilePrintNode(f, this, resources, null, listItems, config, null);
3030          OutputFileList(f, "RESOURCES", listItems, varStringLenDiffs, null);
3031
3032          f.Puts("ifdef USE_RESOURCES_EAR\n");
3033          f.Puts("RESOURCES_EAR = $(OBJ)resources.ear\n");
3034          f.Puts("else\n");
3035          f.Puts("RESOURCES_EAR = $(RESOURCES)\n");
3036          f.Puts("endif\n");
3037          f.Puts("\n");
3038
3039          f.Puts("LIBS += $(SHAREDLIB) $(EXECUTABLE) $(LINKOPT)\n");
3040          f.Puts("\n");
3041          if((config && config.options && config.options.libraries) ||
3042                (options && options.libraries))
3043          {
3044             f.Puts("ifndef STATIC_LIBRARY_TARGET\n");
3045             f.Puts("LIBS +=");
3046             if(config && config.options && config.options.libraries)
3047                OutputLibraries(f, config.options.libraries);
3048             else if(options && options.libraries)
3049                OutputLibraries(f, options.libraries);
3050             f.Puts("\n");
3051             f.Puts("endif\n");
3052             f.Puts("\n");
3053          }
3054
3055          topNode.GenMakeCollectAssignNodeFlags(config, numCObjects != 0,
3056                cflagsVariations, nodeCFlagsMapping,
3057                ecflagsVariations, nodeECFlagsMapping, null);
3058
3059          GenMakePrintCustomFlags(f, "PRJ_CFLAGS", false, cflagsVariations);
3060          f.Puts("ECFLAGS += -module $(MODULE)\n");
3061          GenMakePrintCustomFlags(f, "ECFLAGS", true, ecflagsVariations);
3062
3063          if(platforms || (config && config.platforms))
3064          {
3065             ifCount = 0;
3066             //for(platform = firstPlatform; platform <= lastPlatform; platform++)
3067             //for(platform = win32; platform <= apple; platform++)
3068
3069             f.Puts("# PLATFORM-SPECIFIC OPTIONS\n\n");
3070             for(platform = (Platform)1; platform < Platform::enumSize; platform++)
3071             {
3072                PlatformOptions projectPlatformOptions, configPlatformOptions;
3073                MatchProjectAndConfigPlatformOptions(config, platform, &projectPlatformOptions, &configPlatformOptions);
3074
3075                if(projectPlatformOptions || configPlatformOptions)
3076                {
3077                   if(ifCount)
3078                      f.Puts("else\n");
3079                   ifCount++;
3080                   f.Printf("ifdef %s\n", PlatformToMakefileTargetVariable(platform));
3081                   f.Puts("\n");
3082
3083                   if((projectPlatformOptions && projectPlatformOptions.options.compilerOptions && projectPlatformOptions.options.compilerOptions.count) ||
3084                      (configPlatformOptions && configPlatformOptions.options.compilerOptions && configPlatformOptions.options.compilerOptions.count))
3085                   {
3086                      f.Puts("CFLAGS +=");
3087                      if(projectPlatformOptions && projectPlatformOptions.options.compilerOptions && projectPlatformOptions.options.compilerOptions.count)
3088                      {
3089                         f.Puts(" \\\n\t ");
3090                         for(s : projectPlatformOptions.options.compilerOptions)
3091                            f.Printf(" %s", s);
3092                      }
3093                      if(configPlatformOptions && configPlatformOptions.options.compilerOptions && configPlatformOptions.options.compilerOptions.count)
3094                      {
3095                         f.Puts(" \\\n\t ");
3096                         for(s : configPlatformOptions.options.compilerOptions)
3097                            f.Printf(" %s", s);
3098                      }
3099                      f.Puts("\n");
3100                      f.Puts("\n");
3101                   }
3102
3103                   if((projectPlatformOptions && projectPlatformOptions.options.linkerOptions && projectPlatformOptions.options.linkerOptions.count) ||
3104                      (configPlatformOptions && configPlatformOptions.options.linkerOptions && configPlatformOptions.options.linkerOptions.count))
3105                   {
3106                      f.Puts("OFLAGS +=");
3107                      if(projectPlatformOptions && projectPlatformOptions.options.linkerOptions && projectPlatformOptions.options.linkerOptions.count)
3108                      {
3109                         bool needWl = false;
3110                         f.Puts(" \\\n\t ");
3111                         for(s : projectPlatformOptions.options.linkerOptions)
3112                         {
3113                            if(!IsLinkerOption(s))
3114                               f.Printf(" %s", s);
3115                            else
3116                               needWl = true;
3117                         }
3118                         if(needWl)
3119                         {
3120                            f.Puts(" -Wl");
3121                            for(s : projectPlatformOptions.options.linkerOptions)
3122                               if(IsLinkerOption(s))
3123                                  f.Printf(",%s", s);
3124                         }
3125                      }
3126                      if(configPlatformOptions && configPlatformOptions.options.linkerOptions && configPlatformOptions.options.linkerOptions.count)
3127                      {
3128                         bool needWl = false;
3129                         f.Puts(" \\\n\t ");
3130                         for(s : configPlatformOptions.options.linkerOptions)
3131                         {
3132                            if(IsLinkerOption(s))
3133                               f.Printf(" %s", s);
3134                            else
3135                               needWl = true;
3136                         }
3137                         if(needWl)
3138                         {
3139                            f.Puts(" -Wl");
3140                            for(s : configPlatformOptions.options.linkerOptions)
3141                               if(!IsLinkerOption(s))
3142                                  f.Printf(",%s", s);
3143                         }
3144                      }
3145                      f.Puts("\n");
3146                      f.Puts("\n");
3147                   }
3148
3149                   if((projectPlatformOptions && projectPlatformOptions.options.libraryDirs && projectPlatformOptions.options.libraryDirs.count) ||
3150                         (configPlatformOptions && configPlatformOptions.options.libraryDirs && configPlatformOptions.options.libraryDirs.count) ||
3151                         (projectPlatformOptions && projectPlatformOptions.options.libraries && projectPlatformOptions.options.libraries.count) ||
3152                         (configPlatformOptions && configPlatformOptions.options.libraries && configPlatformOptions.options.libraries.count))
3153                   {
3154                      f.Puts("ifndef STATIC_LIBRARY_TARGET\n");
3155                      if((projectPlatformOptions && projectPlatformOptions.options.libraryDirs && projectPlatformOptions.options.libraryDirs.count) ||
3156                         (configPlatformOptions && configPlatformOptions.options.libraryDirs && configPlatformOptions.options.libraryDirs.count))
3157                      {
3158                         f.Puts("OFLAGS +=");
3159                         if(configPlatformOptions && configPlatformOptions.options.libraryDirs)
3160                            OutputFlags(f, _L, configPlatformOptions.options.libraryDirs, lineEach);
3161                         if(projectPlatformOptions && projectPlatformOptions.options.libraryDirs)
3162                            OutputFlags(f, _L, projectPlatformOptions.options.libraryDirs, lineEach);
3163                         f.Puts("\n");
3164                      }
3165
3166                      if(configPlatformOptions && configPlatformOptions.options.libraries)
3167                      {
3168                         if(configPlatformOptions.options.libraries.count)
3169                         {
3170                            f.Puts("LIBS +=");
3171                            OutputLibraries(f, configPlatformOptions.options.libraries);
3172                            f.Puts("\n");
3173                         }
3174                      }
3175                      else if(projectPlatformOptions && projectPlatformOptions.options.libraries)
3176                      {
3177                         if(projectPlatformOptions.options.libraries.count)
3178                         {
3179                            f.Puts("LIBS +=");
3180                            OutputLibraries(f, projectPlatformOptions.options.libraries);
3181                            f.Puts("\n");
3182                         }
3183                      }
3184                      f.Puts("endif\n");
3185                      f.Puts("\n");
3186                   }
3187                }
3188             }
3189             if(ifCount)
3190             {
3191                for(c = 0; c < ifCount; c++)
3192                   f.Puts("endif\n");
3193             }
3194             f.Puts("\n");
3195          }
3196
3197          if((config && config.options && config.options.compilerOptions && config.options.compilerOptions.count) ||
3198                (options && options.compilerOptions && options.compilerOptions.count))
3199          {
3200             f.Puts("CFLAGS +=");
3201             f.Puts(" \\\n\t");
3202
3203             if(config && config.options && config.options.compilerOptions && config.options.compilerOptions.count)
3204             {
3205                for(s : config.options.compilerOptions)
3206                   f.Printf(" %s", s);
3207             }
3208             if(options && options.compilerOptions && options.compilerOptions.count)
3209             {
3210                for(s : options.compilerOptions)
3211                   f.Printf(" %s", s);
3212             }
3213             f.Puts("\n");
3214             f.Puts("\n");
3215          }
3216
3217          if((config && config.options && config.options.linkerOptions && config.options.linkerOptions.count) ||
3218                (options && options.linkerOptions && options.linkerOptions.count))
3219          {
3220             f.Puts("OFLAGS +=");
3221             f.Puts(" \\\n\t");
3222
3223             if(config && config.options && config.options.linkerOptions && config.options.linkerOptions.count)
3224             {
3225                bool needWl = false;
3226                for(s : config.options.linkerOptions)
3227                {
3228                   if(!IsLinkerOption(s))
3229                      f.Printf(" %s", s);
3230                   else
3231                      needWl = true;
3232                }
3233                if(needWl)
3234                {
3235                   f.Puts(" -Wl");
3236                   for(s : config.options.linkerOptions)
3237                      if(IsLinkerOption(s))
3238                         f.Printf(",%s", s);
3239                }
3240             }
3241             if(options && options.linkerOptions && options.linkerOptions.count)
3242             {
3243                bool needWl = false;
3244                for(s : options.linkerOptions)
3245                {
3246                   if(!IsLinkerOption(s))
3247                      f.Printf(" %s", s);
3248                   else
3249                      needWl = true;
3250                }
3251                if(needWl)
3252                {
3253                   f.Puts(" -Wl");
3254                   for(s : options.linkerOptions)
3255                      if(IsLinkerOption(s))
3256                         f.Printf(",%s", s);
3257                }
3258             }
3259             f.Puts("\n");
3260             f.Puts("\n");
3261          }
3262
3263          f.Puts("CECFLAGS += -cpp $(_CPP)");
3264          f.Puts("\n");
3265          f.Puts("\n");
3266
3267          if(GetProfile(config))
3268             f.Puts("OFLAGS += -pg\n\n");
3269
3270          if((config && config.options && config.options.libraryDirs) || (options && options.libraryDirs))
3271          {
3272             f.Puts("ifndef STATIC_LIBRARY_TARGET\n");
3273             f.Puts("OFLAGS +=");
3274             if(config && config.options && config.options.libraryDirs)
3275                OutputFlags(f, _L, config.options.libraryDirs, lineEach);
3276             if(options && options.libraryDirs)
3277                OutputFlags(f, _L, options.libraryDirs, lineEach);
3278             f.Puts("\n");
3279             f.Puts("endif\n");
3280             f.Puts("\n");
3281          }
3282
3283          f.Puts("# TARGETS\n");
3284          f.Puts("\n");
3285
3286          f.Printf("all: objdir%s $(TARGET)\n", sameOrRelObjTargetDirs ? "" : " targetdir");
3287          f.Puts("\n");
3288
3289          f.Puts("objdir:\n");
3290          if(!relObjDir)
3291             f.Puts("\t$(if $(wildcard $(OBJ)),,$(call mkdir,$(OBJ)))\n");
3292          if(numCObjects)
3293          {
3294             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");
3295             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");
3296          }
3297          //f.Puts("# PRE-BUILD COMMANDS\n");
3298          if(options && options.prebuildCommands)
3299          {
3300             for(s : options.prebuildCommands)
3301                if(s && s[0]) f.Printf("\t%s\n", s);
3302          }
3303          if(config && config.options && config.options.prebuildCommands)
3304          {
3305             for(s : config.options.prebuildCommands)
3306                if(s && s[0]) f.Printf("\t%s\n", s);
3307          }
3308          if(platforms || (config && config.platforms))
3309          {
3310             ifCount = 0;
3311             //f.Puts("# TARGET_PLATFORM-SPECIFIC PRE-BUILD COMMANDS\n");
3312             for(platform = (Platform)1; platform < Platform::enumSize; platform++)
3313             {
3314                PlatformOptions projectPOs, configPOs;
3315                MatchProjectAndConfigPlatformOptions(config, platform, &projectPOs, &configPOs);
3316
3317                if((projectPOs && projectPOs.options.prebuildCommands && projectPOs.options.prebuildCommands.count) ||
3318                      (configPOs && configPOs.options.prebuildCommands && configPOs.options.prebuildCommands.count))
3319                {
3320                   if(ifCount)
3321                      f.Puts("else\n");
3322                   ifCount++;
3323                   f.Printf("ifdef %s\n", PlatformToMakefileTargetVariable(platform));
3324
3325                   if(projectPOs && projectPOs.options.prebuildCommands && projectPOs.options.prebuildCommands.count)
3326                   {
3327                      for(s : projectPOs.options.prebuildCommands)
3328                         if(s && s[0]) f.Printf("\t%s\n", s);
3329                   }
3330                   if(configPOs && configPOs.options.prebuildCommands && configPOs.options.prebuildCommands.count)
3331                   {
3332                      for(s : configPOs.options.prebuildCommands)
3333                         if(s && s[0]) f.Printf("\t%s\n", s);
3334                   }
3335                }
3336             }
3337             if(ifCount)
3338             {
3339                int c;
3340                for(c = 0; c < ifCount; c++)
3341                   f.Puts("endif\n");
3342             }
3343          }
3344          f.Puts("\n");
3345
3346          if(!sameOrRelObjTargetDirs)
3347          {
3348             f.Puts("targetdir:\n");
3349                f.Printf("\t$(if $(wildcard %s),,$(call mkdir,%s))\n", targetDirExpNoSpaces, targetDirExpNoSpaces);
3350             f.Puts("\n");
3351          }
3352
3353          if(numCObjects)
3354          {
3355             // Main Module (Linking) for ECERE C modules
3356             f.Puts("$(OBJ)$(MODULE).main.ec: $(SYMBOLS) $(COBJECTS)\n");
3357             f.Printf("\t@$(call rm,$(OBJ)symbols.lst)\n");
3358             f.Printf("\t@$(call touch,$(OBJ)symbols.lst)\n");
3359             OutputFileListActions(f, "SYMBOLS", eCsourcesParts, "$(OBJ)symbols.lst");
3360             OutputFileListActions(f, "IMPORTS", eCsourcesParts, "$(OBJ)symbols.lst");
3361             // use of objDirExpNoSpaces used instead of $(OBJ) to prevent problematic joining of arguments in ecs
3362             f.Printf("\t$(ECS)%s $(ARCH_FLAGS) $(ECSLIBOPT) @$(OBJ)symbols.lst -symbols %s -o $(call quote_path,$@)\n",
3363                GetConsole(config) ? " -console" : "", objDirExpNoSpaces);
3364             f.Puts("\n");
3365             // Main Module (Linking) for ECERE C modules
3366             f.Puts("$(OBJ)$(MODULE).main.c: $(OBJ)$(MODULE).main.ec\n");
3367             f.Puts("\t$(ECP) $(CFLAGS) $(CECFLAGS) $(ECFLAGS) $(PRJ_CFLAGS)"
3368                   " -c $(OBJ)$(MODULE).main.ec -o $(OBJ)$(MODULE).main.sym -symbols $(OBJ)\n");
3369             f.Puts("\t$(ECC) $(CFLAGS) $(CECFLAGS) $(ECFLAGS) $(PRJ_CFLAGS) $(FVISIBILITY)"
3370                   " -c $(OBJ)$(MODULE).main.ec -o $(call quote_path,$@) -symbols $(OBJ)\n");
3371             f.Puts("\n");
3372          }
3373
3374          if(resNode.files && resNode.files.count && !noResources)
3375          {
3376             f.Puts("ifdef USE_RESOURCES_EAR\n");
3377             f.Puts("$(RESOURCES_EAR): $(RESOURCES) | objdir\n");
3378                resNode.GenMakefileAddResources(f, resNode.path, config, "RESOURCES_EAR");
3379             f.Puts("endif\n");
3380             f.Puts("\n");
3381          }
3382
3383          // *** Target ***
3384
3385          // This would not rebuild the target on updated objects
3386          // f.Printf("$(TARGET): $(SOURCES) $(RESOURCES) | objdir $(SYMBOLS) $(OBJECTS)%s\n", sameOrRelObjTargetDirs ? "" : " targetdir");
3387
3388          // This should fix it for good!
3389          f.Puts("$(SYMBOLS): | objdir\n");
3390          f.Puts("$(OBJECTS): | objdir\n");
3391
3392          // This alone was breaking the tarball, object directory does not get created first (order-only rules happen last it seems!)
3393          f.Printf("$(TARGET): $(SOURCES)%s $(RESOURCES_EAR) $(SYMBOLS) $(OBJECTS) | objdir%s\n",
3394                rcSourcesParts ? " $(RCSOURCES)" : "", sameOrRelObjTargetDirs ? "" : " targetdir");
3395
3396          f.Printf("\t@$(call rm,$(OBJ)objects.lst)\n");
3397          f.Printf("\t@$(call touch,$(OBJ)objects.lst)\n");
3398          OutputFileListActions(f, "_OBJECTS", objectsParts, "$(OBJ)objects.lst");
3399          if(rcSourcesParts)
3400          {
3401             f.Puts("ifdef WINDOWS_TARGET\n");
3402             OutputFileListActions(f, "RCOBJECTS", rcSourcesParts, "$(OBJ)objects.lst");
3403             f.Puts("endif\n");
3404          }
3405          if(numCObjects)
3406          {
3407             f.Printf("\t$(call addtolistfile,$(OBJ)$(MODULE).main$(O),$(OBJ)objects.lst)\n");
3408             OutputFileListActions(f, "ECOBJECTS", eCsourcesParts, "$(OBJ)objects.lst");
3409          }
3410
3411          f.Puts("ifndef STATIC_LIBRARY_TARGET\n");
3412
3413          f.Puts("\t$(LD) $(OFLAGS) @$(OBJ)objects.lst $(LIBS) -o $(TARGET) $(INSTALLNAME)\n");
3414          if(!GetDebug(config))
3415          {
3416             f.Puts("ifndef NOSTRIP\n");
3417             f.Puts("\t$(STRIP) $(STRIPOPT) $(TARGET)\n");
3418             f.Puts("endif\n");
3419
3420             if(GetCompress(config))
3421             {
3422                f.Printf("ifndef %s\n", PlatformToMakefileTargetVariable(win32));
3423                f.Puts("ifdef EXECUTABLE_TARGET\n");
3424                   f.Puts("\t$(UPX) $(UPXFLAGS) $(TARGET)\n");
3425                f.Puts("endif\n");
3426                f.Puts("else\n");
3427                //f.Puts("ifneq ($(TARGET_ARCH),x86_64)\n");
3428                   f.Puts("\t$(UPX) $(UPXFLAGS) $(TARGET)\n");
3429                //f.Puts("endif\n");
3430                f.Puts("endif\n");
3431             }
3432          }
3433          if(resNode.files && resNode.files.count && !noResources)
3434          {
3435             f.Puts("ifndef USE_RESOURCES_EAR\n");
3436             resNode.GenMakefileAddResources(f, resNode.path, config, "TARGET");
3437             f.Puts("endif\n");
3438          }
3439          f.Puts("else\n");
3440          f.Puts("ifdef WINDOWS_HOST\n");
3441          f.Puts("\t$(AR) rcs $(TARGET) @$(OBJ)objects.lst $(LIBS)\n");
3442          f.Puts("else\n");
3443          f.Puts("\t$(AR) rcs $(TARGET) $(OBJECTS) $(LIBS)\n");
3444          f.Puts("endif\n");
3445          f.Puts("endif\n");
3446          f.Puts("ifdef SHARED_LIBRARY_TARGET\n");
3447          f.Puts("ifdef LINUX_TARGET\n");
3448          f.Puts("ifdef LINUX_HOST\n");
3449          // TODO?: support symlinks for longer version numbers
3450          f.Puts("\t$(if $(basename $(VER)),ln -sf $(LP)$(MODULE)$(SO)$(VER) $(OBJ)$(LP)$(MODULE)$(SO)$(basename $(VER)),)\n");
3451          f.Puts("\t$(if $(VER),ln -sf $(LP)$(MODULE)$(SO)$(VER) $(OBJ)$(LP)$(MODULE)$(SO),)\n");
3452          f.Puts("endif\n");
3453          f.Puts("endif\n");
3454          f.Puts("endif\n");
3455
3456          //f.Puts("# POST-BUILD COMMANDS\n");
3457          if(options && options.postbuildCommands)
3458          {
3459             for(s : options.postbuildCommands)
3460                if(s && s[0]) f.Printf("\t%s\n", s);
3461          }
3462          if(config && config.options && config.options.postbuildCommands)
3463          {
3464             for(s : config.options.postbuildCommands)
3465                if(s && s[0]) f.Printf("\t%s\n", s);
3466          }
3467          if(platforms || (config && config.platforms))
3468          {
3469             ifCount = 0;
3470             //f.Puts("# TARGET_PLATFORM-SPECIFIC POST-BUILD COMMANDS\n");
3471             for(platform = (Platform)1; platform < Platform::enumSize; platform++)
3472             {
3473                PlatformOptions projectPOs, configPOs;
3474                MatchProjectAndConfigPlatformOptions(config, platform, &projectPOs, &configPOs);
3475
3476                if((projectPOs && projectPOs.options.postbuildCommands && projectPOs.options.postbuildCommands.count) ||
3477                      (configPOs && configPOs.options.postbuildCommands && configPOs.options.postbuildCommands.count))
3478                {
3479                   if(ifCount)
3480                      f.Puts("else\n");
3481                   ifCount++;
3482                   f.Printf("ifdef %s\n", PlatformToMakefileTargetVariable(platform));
3483
3484                   if(projectPOs && projectPOs.options.postbuildCommands && projectPOs.options.postbuildCommands.count)
3485                   {
3486                      for(s : projectPOs.options.postbuildCommands)
3487                         if(s && s[0]) f.Printf("\t%s\n", s);
3488                   }
3489                   if(configPOs && configPOs.options.postbuildCommands && configPOs.options.postbuildCommands.count)
3490                   {
3491                      for(s : configPOs.options.postbuildCommands)
3492                         if(s && s[0]) f.Printf("\t%s\n", s);
3493                   }
3494                }
3495             }
3496             if(ifCount)
3497             {
3498                int c;
3499                for(c = 0; c < ifCount; c++)
3500                   f.Puts("endif\n");
3501             }
3502          }
3503          f.Puts("\n");
3504
3505          test = false;
3506          if(platforms || (config && config.platforms))
3507          {
3508             for(platform = (Platform)1; platform < Platform::enumSize; platform++)
3509             {
3510                PlatformOptions projectPOs, configPOs;
3511                MatchProjectAndConfigPlatformOptions(config, platform, &projectPOs, &configPOs);
3512
3513                if((projectPOs && projectPOs.options.installCommands && projectPOs.options.installCommands.count) ||
3514                      (configPOs && configPOs.options.installCommands && configPOs.options.installCommands.count))
3515                {
3516                   test = true;
3517                   break;
3518                }
3519             }
3520          }
3521          if(test || (options && options.installCommands) ||
3522                (config && config.options && config.options.installCommands))
3523          {
3524             f.Puts("install:\n");
3525             if(options && options.installCommands)
3526             {
3527                for(s : options.installCommands)
3528                   if(s && s[0]) f.Printf("\t%s\n", s);
3529             }
3530             if(config && config.options && config.options.installCommands)
3531             {
3532                for(s : config.options.installCommands)
3533                   if(s && s[0]) f.Printf("\t%s\n", s);
3534             }
3535             if(platforms || (config && config.platforms))
3536             {
3537                ifCount = 0;
3538                for(platform = (Platform)1; platform < Platform::enumSize; platform++)
3539                {
3540                   PlatformOptions projectPOs, configPOs;
3541                   MatchProjectAndConfigPlatformOptions(config, platform, &projectPOs, &configPOs);
3542
3543                   if((projectPOs && projectPOs.options.installCommands && projectPOs.options.installCommands.count) ||
3544                         (configPOs && configPOs.options.installCommands && configPOs.options.installCommands.count))
3545                   {
3546                      if(ifCount)
3547                         f.Puts("else\n");
3548                      ifCount++;
3549                      f.Printf("ifdef %s\n", PlatformToMakefileTargetVariable(platform));
3550
3551                      if(projectPOs && projectPOs.options.installCommands && projectPOs.options.installCommands.count)
3552                      {
3553                         for(s : projectPOs.options.installCommands)
3554                            if(s && s[0]) f.Printf("\t%s\n", s);
3555                      }
3556                      if(configPOs && configPOs.options.installCommands && configPOs.options.installCommands.count)
3557                      {
3558                         for(s : configPOs.options.installCommands)
3559                            if(s && s[0]) f.Printf("\t%s\n", s);
3560                      }
3561                   }
3562                }
3563                if(ifCount)
3564                {
3565                   int c;
3566                   for(c = 0; c < ifCount; c++)
3567                      f.Puts("endif\n");
3568                }
3569             }
3570             f.Puts("\n");
3571          }
3572
3573          f.Puts("# SYMBOL RULES\n");
3574          f.Puts("\n");
3575
3576          topNode.GenMakefilePrintSymbolRules(f, this, config, nodeCFlagsMapping, nodeECFlagsMapping);
3577
3578          f.Puts("# C OBJECT RULES\n");
3579          f.Puts("\n");
3580
3581          topNode.GenMakefilePrintCObjectRules(f, this, config, nodeCFlagsMapping, nodeECFlagsMapping);
3582
3583          f.Puts("# OBJECT RULES\n");
3584          f.Puts("\n");
3585          // todo call this still but only generate rules whith specific options
3586          // see we-have-file-specific-options in ProjectNode.ec
3587          topNode.GenMakefilePrintObjectRules(f, this, namesInfo, config, nodeCFlagsMapping, nodeECFlagsMapping);
3588
3589          if(numCObjects)
3590             GenMakefilePrintMainObjectRule(f, config);
3591
3592          f.Printf("cleantarget: objdir%s\n", sameOrRelObjTargetDirs ? "" : " targetdir");
3593          if(numCObjects)
3594          {
3595             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)");
3596             f.Printf("\t$(call rm,$(OBJ)symbols.lst)\n");
3597          }
3598          f.Printf("\t$(call rm,$(OBJ)objects.lst)\n");
3599          f.Puts("\t$(call rm,$(TARGET))\n");
3600          f.Puts("ifdef SHARED_LIBRARY_TARGET\n");
3601          f.Puts("ifdef LINUX_TARGET\n");
3602          f.Puts("ifdef LINUX_HOST\n");
3603          // TODO?: support symlinks for longer version numbers
3604          f.Puts("\t$(call rm,$(OBJ)$(LP)$(MODULE)$(SO)$(basename $(VER)))\n");
3605          f.Puts("\t$(call rm,$(OBJ)$(LP)$(MODULE)$(SO))\n");
3606          f.Puts("endif\n");
3607          f.Puts("endif\n");
3608          f.Puts("endif\n");
3609          f.Puts("\n");
3610
3611          f.Puts("clean: cleantarget\n");
3612          OutputCleanActions(f, "OBJECTS", objectsParts);
3613          if(rcSourcesParts)
3614          {
3615             f.Puts("ifdef WINDOWS_TARGET\n");
3616             OutputCleanActions(f, "RCOBJECTS", rcSourcesParts);
3617             f.Puts("endif\n");
3618          }
3619          if(numCObjects)
3620          {
3621             OutputCleanActions(f, "ECOBJECTS", eCsourcesParts);
3622             OutputCleanActions(f, "COBJECTS", eCsourcesParts);
3623             OutputCleanActions(f, "BOWLS", eCsourcesParts);
3624             OutputCleanActions(f, "IMPORTS", eCsourcesParts);
3625             OutputCleanActions(f, "SYMBOLS", eCsourcesParts);
3626          }
3627          if(resNode.files && resNode.files.count && !noResources)
3628          {
3629             f.Puts("ifdef USE_RESOURCES_EAR\n");
3630             f.Printf("\t$(call rm,$(RESOURCES_EAR))\n");
3631             f.Puts("endif\n");
3632          }
3633          f.Puts("\n");
3634
3635          f.Puts("realclean: cleantarget\n");
3636          f.Puts("\t$(call rmr,$(OBJ))\n");
3637          if(!sameOrRelObjTargetDirs)
3638             f.Printf("\t$(call rmdir,%s)\n", targetDirExpNoSpaces);
3639          f.Puts("\n");
3640
3641          f.Puts("distclean: cleantarget\n");
3642          if(!sameOrRelObjTargetDirs)
3643             f.Printf("\t$(call rmdir,%s)\n", targetDirExpNoSpaces);
3644          if(!relObjDir)
3645             f.Puts("\t$(call rmr,obj/)\n");
3646          f.Puts("\t$(call rmr,.configs/)\n");
3647          f.Puts("\t$(call rm,*.ews)\n");
3648          f.Puts("\t$(call rm,*.Makefile)\n");
3649
3650          delete f;
3651
3652          listItems.Free();
3653          delete listItems;
3654          varStringLenDiffs.Free();
3655          delete varStringLenDiffs;
3656          namesInfo.Free();
3657          delete namesInfo;
3658
3659          delete cflagsVariations;
3660          delete nodeCFlagsMapping;
3661          delete ecflagsVariations;
3662          delete nodeECFlagsMapping;
3663
3664          result = true;
3665       }
3666
3667       // ChangeWorkingDir(oldDirectory);
3668       // delete pathBackup;
3669
3670       if(config)
3671          config.makingModified = false;
3672       return result;
3673    }
3674
3675    void GenMakefilePrintMainObjectRule(File f, ProjectConfig config)
3676    {
3677       char extension[MAX_EXTENSION] = "c";
3678       //char modulePath[MAX_LOCATION];
3679       char fixedModuleName[MAX_FILENAME];
3680       //DualPipe dep;
3681       //char command[2048];
3682       char objDirNoSpaces[MAX_LOCATION];
3683       const String objDirExp = GetObjDirExpression(config);
3684
3685       ReplaceSpaces(objDirNoSpaces, objDirExp);
3686       ReplaceSpaces(fixedModuleName, moduleName);
3687
3688       //sprintf(fixedModuleName, "%s.main", fixedPrjName);
3689       //strcat(fixedModuleName, ".main");
3690
3691 #if 0       // TODO: Fix nospaces stuff
3692       // *** Dependency command ***
3693       sprintf(command, "gcc -MT $(OBJ)%s$(O) -MM $(OBJ)%s.c", fixedModuleName, fixedModuleName);
3694
3695       // System Includes (from global settings)
3696       for(item : compiler.dirs[Includes])
3697       {
3698          strcat(command, " -isystem ");
3699          if(strchr(item.name, ' '))
3700          {
3701             strcat(command, "\"");
3702             strcat(command, item);
3703             strcat(command, "\"");
3704          }
3705          else
3706             strcat(command, item);
3707       }
3708
3709       for(item = includeDirs.first; item; item = item.next)
3710       {
3711          strcat(command, " -I");
3712          if(strchr(item.name, ' '))
3713          {
3714             strcat(command, "\"");
3715             strcat(command, item.name);
3716             strcat(command, "\"");
3717          }
3718          else
3719             strcat(command, item.name);
3720       }
3721       for(item = preprocessorDefs.first; item; item = item.next)
3722       {
3723          strcat(command, " -D");
3724          strcat(command, item.name);
3725       }
3726
3727       // Execute it
3728       if((dep = DualPipeOpen(PipeOpenMode { output = true, error = true/*, input = true*/ }, command)))
3729       {
3730          char line[1024];
3731          bool result = true;
3732          bool firstLine = true;
3733
3734          // To do some time: auto save external dependencies?
3735          while(!dep.Eof())
3736          {
3737             if(dep.GetLine(line, sizeof(line)-1))
3738             {
3739                if(firstLine)
3740                {
3741                   char * colon = strstr(line, ":");
3742                   if(strstr(line, "No such file") || strstr(line, ",") || (colon && strstr(colon+1, ":")))
3743                   {
3744                      result = false;
3745                      break;
3746                   }
3747                   firstLine = false;
3748                }
3749                f.Puts(line);
3750                f.Puts("\n");
3751             }
3752             if(!result) break;
3753          }
3754          delete dep;
3755
3756          // If we failed to generate dependencies...
3757          if(!result)
3758          {
3759 #endif
3760             f.Puts("$(OBJ)$(MODULE).main$(O): $(OBJ)$(MODULE).main.c\n");
3761             f.Printf("\t$(CC) $(CFLAGS) $(PRJ_CFLAGS) $(FVISIBILITY) -c $(OBJ)$(MODULE).main.%s -o $(call quote_path,$@)\n", extension);
3762             f.Puts("\n");
3763 #if 0
3764          }
3765       }
3766 #endif
3767    }
3768
3769    void GenMakePrintCustomFlags(File f, const String variableName, bool printNonCustom, Map<String, int> cflagsVariations)
3770    {
3771       int c;
3772       for(c = printNonCustom ? 0 : 1; c <= cflagsVariations.count; c++)
3773       {
3774          for(v : cflagsVariations)
3775          {
3776             if(v == c)
3777             {
3778                if(v == 1)
3779                   f.Printf("%s +=", variableName);
3780                else
3781                   f.Printf("CUSTOM%d_%s =", v-1, variableName);
3782                f.Puts(&v ? &v : "");
3783                f.Puts("\n\n");
3784                break;
3785             }
3786          }
3787       }
3788    }
3789
3790    void MatchProjectAndConfigPlatformOptions(ProjectConfig config, Platform platform,
3791          PlatformOptions * projectPlatformOptions, PlatformOptions * configPlatformOptions)
3792    {
3793       *projectPlatformOptions = null;
3794       *configPlatformOptions = null;
3795       if(platforms)
3796       {
3797          for(p : platforms)
3798          {
3799             if(!strcmpi(p.name, platform))
3800             {
3801                *projectPlatformOptions = p;
3802                break;
3803             }
3804          }
3805       }
3806       if(config && config.platforms)
3807       {
3808          for(p : config.platforms)
3809          {
3810             if(!strcmpi(p.name, platform))
3811             {
3812                *configPlatformOptions = p;
3813                break;
3814             }
3815          }
3816       }
3817    }
3818 }
3819
3820 static inline void ProjectLoadLastBuildNamesInfo(Project prj, ProjectConfig cfg)
3821 {
3822    const char * cfgName = cfg ? cfg.name : "";
3823    Map<String, NameCollisionInfo> cfgNameCollisions = prj.configsNameCollisions[cfgName];
3824    if(cfgNameCollisions)
3825    {
3826       cfgNameCollisions.Free();
3827       delete cfgNameCollisions;
3828    }
3829    prj.configsNameCollisions[cfgName] = cfgNameCollisions = { };
3830    prj.topNode.GenMakefileGetNameCollisionInfo(cfgNameCollisions, cfg);
3831 }
3832
3833 Project LegacyBinaryLoadProject(File f, const char * filePath)
3834 {
3835    Project project = null;
3836    char signature[sizeof(epjSignature)];
3837
3838    f.Read(signature, sizeof(signature), 1);
3839    if(!strncmp(signature, (char *)epjSignature, sizeof(epjSignature)))
3840    {
3841       char topNodePath[MAX_LOCATION];
3842       /*ProjectConfig newConfig
3843       {
3844          name = CopyString("Default");
3845          makingModified = true;
3846          compilingModified = true;
3847          linkingModified = true;
3848          options = { };
3849       };*/
3850
3851       project = Project { options = { } };
3852       LegacyBinaryLoadNode(project.topNode, f);
3853       delete project.topNode.path;
3854       GetWorkingDir(topNodePath, sizeof(topNodePath)-1);
3855       MakeSlashPath(topNodePath);
3856
3857       PathCatSlash(topNodePath, filePath);
3858       project.filePath = topNodePath;
3859
3860       /* THIS IS ALREADY DONE BY filePath property
3861       StripLastDirectory(topNodePath, topNodePath);
3862       project.topNode.path = CopyString(topNodePath);
3863       */
3864       // Shouldn't this be done BEFORE the StripLastDirectory? project.filePath = topNodePath;
3865
3866       // newConfig.options.defaultNameSpace = "";
3867       /*newConfig.objDir.dir = "obj";
3868       newConfig.targetDir.dir = "";*/
3869
3870       //project.configurations = { [ newConfig ] };
3871       //project.config = newConfig;
3872
3873       // Project Settings
3874       if(!f.Eof())
3875       {
3876          int temp;
3877          int len,c, count;
3878          String targetFileName, targetDirectory, objectsDirectory;
3879
3880          // { executable = 0, sharedLibrary = 1, staticLibrary = 2 };
3881          f.Read(&temp, sizeof(int),1);
3882          switch(temp)
3883          {
3884             case 0: project.options.targetType = executable; break;
3885             case 1: project.options.targetType = sharedLibrary; break;
3886             case 2: project.options.targetType = staticLibrary; break;
3887          }
3888
3889          f.Read(&len, sizeof(int),1);
3890          targetFileName = new char[len+1];
3891          f.Read(targetFileName, sizeof(char), len+1);
3892          project.options.targetFileName = targetFileName;
3893          delete targetFileName;
3894
3895          f.Read(&len, sizeof(int),1);
3896          targetDirectory = new char[len+1];
3897          f.Read(targetDirectory, sizeof(char), len+1);
3898          project.options.targetDirectory = targetDirectory;
3899          delete targetDirectory;
3900
3901          f.Read(&len, sizeof(int),1);
3902          objectsDirectory = new byte[len+1];
3903          f.Read(objectsDirectory, sizeof(char), len+1);
3904          project.options.objectsDirectory = objectsDirectory;
3905          delete objectsDirectory;
3906
3907          f.Read(&temp, sizeof(int),1);
3908          project./*config.*/options.debug = temp ? true : false;
3909          f.Read(&temp, sizeof(int),1);
3910          project./*config.*/options.optimization = temp ? speed : none;
3911          f.Read(&temp, sizeof(int),1);
3912          project./*config.*/options.profile = temp ? true : false;
3913          f.Read(&temp, sizeof(int),1);
3914          project.options.warnings = temp ? all : unset;
3915
3916          f.Read(&count, sizeof(int),1);
3917          if(count)
3918          {
3919             project.options.includeDirs = { };
3920             for(c = 0; c < count; c++)
3921             {
3922                char * name;
3923                f.Read(&len, sizeof(int),1);
3924                name = new char[len+1];
3925                f.Read(name, sizeof(char), len+1);
3926                project.options.includeDirs.Add(name);
3927             }
3928          }
3929
3930          f.Read(&count, sizeof(int),1);
3931          if(count)
3932          {
3933             project.options.libraryDirs = { };
3934             for(c = 0; c < count; c++)
3935             {
3936                char * name;
3937                f.Read(&len, sizeof(int),1);
3938                name = new char[len+1];
3939                f.Read(name, sizeof(char), len+1);
3940                project.options.libraryDirs.Add(name);
3941             }
3942          }
3943
3944          f.Read(&count, sizeof(int),1);
3945          if(count)
3946          {
3947             project.options.libraries = { };
3948             for(c = 0; c < count; c++)
3949             {
3950                char * name;
3951                f.Read(&len, sizeof(int),1);
3952                name = new char[len+1];
3953                f.Read(name, sizeof(char), len+1);
3954                project.options.libraries.Add(name);
3955             }
3956          }
3957
3958          f.Read(&count, sizeof(int),1);
3959          if(count)
3960          {
3961             project.options.preprocessorDefinitions = { };
3962             for(c = 0; c < count; c++)
3963             {
3964                char * name;
3965                f.Read(&len, sizeof(int),1);
3966                name = new char[len+1];
3967                f.Read(name, sizeof(char), len+1);
3968                project.options.preprocessorDefinitions.Add(name);
3969             }
3970          }
3971
3972          f.Read(&temp, sizeof(int),1);
3973          project.options.console = temp ? true : false;
3974       }
3975
3976       for(node : project.topNode.files)
3977       {
3978          if(node.type == resources)
3979          {
3980             project.resNode = node;
3981             break;
3982          }
3983       }
3984    }
3985    else
3986       f.Seek(0, start);
3987    return project;
3988 }
3989
3990 void ProjectConfig::LegacyProjectConfigLoad(File f)
3991 {
3992    delete options;
3993    options = { };
3994    while(!f.Eof())
3995    {
3996       char buffer[65536];
3997       char section[128];
3998       char subSection[128];
3999       char * equal;
4000       uint pos;
4001
4002       pos = f.Tell();
4003       f.GetLine(buffer, 65536 - 1);
4004       TrimLSpaces(buffer, buffer);
4005       TrimRSpaces(buffer, buffer);
4006       if(strlen(buffer))
4007       {
4008          if(buffer[0] == '-')
4009          {
4010             equal = &buffer[0];
4011             equal[0] = ' ';
4012             TrimLSpaces(equal, equal);
4013             if(!strcmpi(subSection, "LibraryDirs"))
4014             {
4015                if(!options.libraryDirs)
4016                   options.libraryDirs = { [ CopyString(equal) ] };
4017                else
4018                   options.libraryDirs.Add(CopyString(equal));
4019             }
4020             else if(!strcmpi(subSection, "IncludeDirs"))
4021             {
4022                if(!options.includeDirs)
4023                   options.includeDirs = { [ CopyString(equal) ] };
4024                else
4025                   options.includeDirs.Add(CopyString(equal));
4026             }
4027          }
4028          else if(buffer[0] == '+')
4029          {
4030             if(name)
4031             {
4032                f.Seek(pos, start);
4033                break;
4034             }
4035             else
4036             {
4037                equal = &buffer[0];
4038                equal[0] = ' ';
4039                TrimLSpaces(equal, equal);
4040                delete name; name = CopyString(equal); // property::name = equal;
4041             }
4042          }
4043          else if(!strcmpi(buffer, "Compiler Options"))
4044             strcpy(section, buffer);
4045          else if(!strcmpi(buffer, "IncludeDirs"))
4046             strcpy(subSection, buffer);
4047          else if(!strcmpi(buffer, "Linker Options"))
4048             strcpy(section, buffer);
4049          else if(!strcmpi(buffer, "LibraryDirs"))
4050             strcpy(subSection, buffer);
4051          else if(!strcmpi(buffer, "Files") || !strcmpi(buffer, "Resources"))
4052          {
4053             f.Seek(pos, start);
4054             break;
4055          }
4056          else
4057          {
4058             equal = strstr(buffer, "=");
4059             if(equal)
4060             {
4061                equal[0] = '\0';
4062                TrimRSpaces(buffer, buffer);
4063                equal++;
4064                TrimLSpaces(equal, equal);
4065                if(!strcmpi(buffer, "Target Name"))
4066                   options.targetFileName = /*CopyString(*/equal/*)*/;
4067                else if(!strcmpi(buffer, "Target Type"))
4068                {
4069                   if(!strcmpi(equal, "Executable"))
4070                      options.targetType = executable;
4071                   else if(!strcmpi(equal, "Shared"))
4072                      options.targetType = sharedLibrary;
4073                   else if(!strcmpi(equal, "Static"))
4074                      options.targetType = staticLibrary;
4075                   else
4076                      options.targetType = executable;
4077                }
4078                else if(!strcmpi(buffer, "Target Directory"))
4079                   options.targetDirectory = /*CopyString(*/equal/*)*/;
4080                else if(!strcmpi(buffer, "Console"))
4081                   options.console = ParseTrueFalseValue(equal);
4082                else if(!strcmpi(buffer, "Libraries"))
4083                {
4084                   if(!options.libraries) options.libraries = { };
4085                   ParseArrayValue(options.libraries, equal);
4086                }
4087                else if(!strcmpi(buffer, "Intermediate Directory"))
4088                   options.objectsDirectory = /*CopyString(*/equal/*)*/; //objDir.expression = equal;
4089                else if(!strcmpi(buffer, "Debug"))
4090                   options.debug = ParseTrueFalseValue(equal);
4091                else if(!strcmpi(buffer, "Optimize"))
4092                {
4093                   if(!strcmpi(equal, "None"))
4094                      options.optimization = none;
4095                   else if(!strcmpi(equal, "Speed") || !strcmpi(equal, "True"))
4096                      options.optimization = speed;
4097                   else if(!strcmpi(equal, "Size"))
4098                      options.optimization = size;
4099                   else
4100                      options.optimization = none;
4101                }
4102                else if(!strcmpi(buffer, "Compress"))
4103                   options.compress = ParseTrueFalseValue(equal);
4104                else if(!strcmpi(buffer, "Profile"))
4105                   options.profile = ParseTrueFalseValue(equal);
4106                else if(!strcmpi(buffer, "AllWarnings"))
4107                   options.warnings = ParseTrueFalseValue(equal) ? all : unset;
4108                else if(!strcmpi(buffer, "MemoryGuard"))
4109                   options.memoryGuard = ParseTrueFalseValue(equal);
4110                else if(!strcmpi(buffer, "Default Name Space"))
4111                   options.defaultNameSpace = CopyString(equal);
4112                else if(!strcmpi(buffer, "Strict Name Spaces"))
4113                   options.strictNameSpaces = ParseTrueFalseValue(equal);
4114                else if(!strcmpi(buffer, "Preprocessor Definitions"))
4115                {
4116                   if(!options.preprocessorDefinitions) options.preprocessorDefinitions = { };
4117                   ParseArrayValue(options.preprocessorDefinitions, equal);
4118                }
4119             }
4120          }
4121       }
4122    }
4123    if(!options.targetDirectory && options.objectsDirectory)
4124       options.targetDirectory = /*CopyString(*/options.objectsDirectory/*)*/;
4125    //if(!objDir.dir) objDir.dir = "obj";
4126    //if(!targetDir.dir) targetDir.dir = "";
4127    // if(!targetName) property::targetName = "";   // How can a targetFileName be nothing???
4128    // if(!defaultNameSpace) property::defaultNameSpace = "";
4129    makingModified = true;
4130 }
4131
4132 Project LegacyAsciiLoadProject(File f, const char * filePath)
4133 {
4134    Project project = null;
4135    int pos;
4136    char parentPath[MAX_LOCATION];
4137    char section[128] = "";
4138    char subSection[128] = "";
4139    ProjectNode parent = null;
4140    bool configurationsPresent = false;
4141
4142    f.Seek(0, start);
4143    while(!f.Eof())
4144    {
4145       char buffer[65536];
4146       //char version[16];
4147       char * equal;
4148       int len;
4149       pos = f.Tell();
4150       f.GetLine(buffer, 65536 - 1);
4151       TrimLSpaces(buffer, buffer);
4152       TrimRSpaces(buffer, buffer);
4153       if(strlen(buffer))
4154       {
4155          if(buffer[0] == '-' || buffer[0] == '=')
4156          {
4157             bool simple = buffer[0] == '-';
4158             equal = &buffer[0];
4159             equal[0] = ' ';
4160             TrimLSpaces(equal, equal);
4161             if(!strcmpi(section, "Target") && !strcmpi(subSection, "LibraryDirs"))
4162             {
4163                if(!project.config.options.libraryDirs)
4164                   project.config.options.libraryDirs = { [ CopyString(equal) ] };
4165                else
4166                   project.config.options.libraryDirs.Add(CopyString(equal));
4167             }
4168             else if(!strcmpi(section, "Target") && !strcmpi(subSection, "IncludeDirs"))
4169             {
4170                if(!project.config.options.includeDirs)
4171                   project.config.options.includeDirs = { [ CopyString(equal) ] };
4172                else
4173                   project.config.options.includeDirs.Add(CopyString(equal));
4174             }
4175             else if(!strcmpi(section, "Target") && (!strcmpi(subSection, "Files") || !strcmpi(subSection, "Resources")))
4176             {
4177                len = strlen(equal);
4178                if(len)
4179                {
4180                   char temp[MAX_LOCATION];
4181                   ProjectNode child { };
4182                   // We don't need to do this anymore, fileName is just a property that sets name & path
4183                   // child.fileName = CopyString(equal);
4184                   if(simple)
4185                   {
4186                      child.name = CopyString(equal);
4187                      child.path = CopyString(parentPath);
4188                   }
4189                   else
4190                   {
4191                      GetLastDirectory(equal, temp);
4192                      child.name = CopyString(temp);
4193                      StripLastDirectory(equal, temp);
4194                      child.path = CopyString(temp);
4195                   }
4196                   child.nodeType = file;
4197                   child.parent = parent;
4198                   child.indent = parent.indent + 1;
4199                   child.type = file;
4200                   child.icon = NodeIcons::SelectFileIcon(child.name);
4201                   parent.files.Add(child);
4202                   //node = child;
4203                   //child = null;
4204                }
4205                else
4206                {
4207                   StripLastDirectory(parentPath, parentPath);
4208                   parent = parent.parent;
4209                }
4210             }
4211          }
4212          else if(buffer[0] == '+')
4213          {
4214             equal = &buffer[0];
4215             equal[0] = ' ';
4216             TrimLSpaces(equal, equal);
4217             if(!strcmpi(section, "Target") && (!strcmpi(subSection, "Files") || !strcmpi(subSection, "Resources")))
4218             {
4219                char temp[MAX_LOCATION];
4220                ProjectNode child { };
4221                // NEW: Folders now have a path set like files
4222                child.name = CopyString(equal);
4223                strcpy(temp, parentPath);
4224                PathCatSlash(temp, child.name);
4225                child.path = CopyString(temp);
4226
4227                child.parent = parent;
4228                child.indent = parent.indent + 1;
4229                child.type = folder;
4230                child.nodeType = folder;
4231                child.files = { };
4232                child.icon = folder;
4233                PathCatSlash(parentPath, child.name);
4234                parent.files.Add(child);
4235                parent = child;
4236                //node = child;
4237                //child = null;
4238             }
4239             else if(!strcmpi(section, "Configurations"))
4240             {
4241                ProjectConfig newConfig
4242                {
4243                   makingModified = true;
4244                   options = { };
4245                };
4246                f.Seek(pos, start);
4247                LegacyProjectConfigLoad(newConfig, f);
4248                project.configurations.Add(newConfig);
4249             }
4250          }
4251          else if(!strcmpi(buffer, "ECERE Project File"));
4252          else if(!strcmpi(buffer, "Version 0a"))
4253             ; //strcpy(version, "0a");
4254          else if(!strcmpi(buffer, "Version 0.1a"))
4255             ; //strcpy(version, "0.1a");
4256          else if(!strcmpi(buffer, "Configurations"))
4257          {
4258             project.configurations.Free();
4259             project.config = null;
4260             strcpy(section, buffer);
4261             configurationsPresent = true;
4262          }
4263          else if(!strcmpi(buffer, "Target") || !strnicmp(buffer, "Target \"", strlen("Target \"")))
4264          {
4265             ProjectConfig newConfig { name = CopyString("Default"), options = { } };
4266             char topNodePath[MAX_LOCATION];
4267             // newConfig.defaultNameSpace = "";
4268             //newConfig.objDir.dir = "obj";
4269             //newConfig.targetDir.dir = "";
4270             project = Project { /*options = { }*/ };
4271             project.configurations = { [ newConfig ] };
4272             project.config = newConfig;
4273             // if(project.topNode.path) delete project.topNode.path;
4274             GetWorkingDir(topNodePath, sizeof(topNodePath)-1);
4275             MakeSlashPath(topNodePath);
4276             PathCatSlash(topNodePath, filePath);
4277             project.filePath = topNodePath;
4278             parentPath[0] = '\0';
4279             parent = project.topNode;
4280             //node = parent;
4281             strcpy(section, "Target");
4282             equal = &buffer[6];
4283             if(equal[0] == ' ')
4284             {
4285                equal++;
4286                if(equal[0] == '\"')
4287                {
4288                   StripQuotes(equal, equal);
4289                   delete project.moduleName; project.moduleName = CopyString(equal);
4290                }
4291             }
4292          }
4293          else if(!strcmpi(buffer, "Compiler Options"));
4294          else if(!strcmpi(buffer, "IncludeDirs"))
4295             strcpy(subSection, buffer);
4296          else if(!strcmpi(buffer, "Linker Options"));
4297          else if(!strcmpi(buffer, "LibraryDirs"))
4298             strcpy(subSection, buffer);
4299          else if(!strcmpi(buffer, "Files"))
4300          {
4301             strcpy(section, "Target");
4302             strcpy(subSection, buffer);
4303          }
4304          else if(!strcmpi(buffer, "Resources"))
4305          {
4306             ProjectNode child { };
4307             parent.files.Add(child);
4308             child.parent = parent;
4309             child.indent = parent.indent + 1;
4310             child.name = CopyString(buffer);
4311             child.path = CopyString("");
4312             child.type = resources;
4313             child.files = { };
4314             child.icon = archiveFile;
4315             project.resNode = child;
4316             parent = child;
4317             //node = child;
4318             strcpy(subSection, buffer);
4319          }
4320          else
4321          {
4322             equal = strstr(buffer, "=");
4323             if(equal)
4324             {
4325                equal[0] = '\0';
4326                TrimRSpaces(buffer, buffer);
4327                equal++;
4328                TrimLSpaces(equal, equal);
4329
4330                if(!strcmpi(section, "Target"))
4331                {
4332                   if(!strcmpi(buffer, "Build Exclusions"))
4333                   {
4334                      if(!strcmpi(section, "Target") && !strcmpi(subSection, "Files"))
4335                      {
4336                         /*if(node && node.type != NodeTypes::project)
4337                            ParseListValue(node.buildExclusions, equal);*/
4338                      }
4339                   }
4340                   else if(!strcmpi(buffer, "Path") && !strcmpi(subSection, "Resources"))
4341                   {
4342                      delete project.resNode.path;
4343                      project.resNode.path = CopyString(equal);
4344                      PathCatSlash(parentPath, equal);
4345                   }
4346
4347                   // Config Settings
4348                   else if(!strcmpi(buffer, "Intermediate Directory"))
4349                      project.config.options.objectsDirectory = /*CopyString(*/equal/*)*/; //objDir.expression = equal;
4350                   else if(!strcmpi(buffer, "Debug"))
4351                      project.config.options.debug = ParseTrueFalseValue(equal);
4352                   else if(!strcmpi(buffer, "Optimize"))
4353                   {
4354                      if(!strcmpi(equal, "None"))
4355                         project.config.options.optimization = none;
4356                      else if(!strcmpi(equal, "Speed") || !strcmpi(equal, "True"))
4357                         project.config.options.optimization = speed;
4358                      else if(!strcmpi(equal, "Size"))
4359                         project.config.options.optimization = size;
4360                      else
4361                         project.config.options.optimization = none;
4362                   }
4363                   else if(!strcmpi(buffer, "Profile"))
4364                      project.config.options.profile = ParseTrueFalseValue(equal);
4365                   else if(!strcmpi(buffer, "MemoryGuard"))
4366                      project.config.options.memoryGuard = ParseTrueFalseValue(equal);
4367                   else
4368                   {
4369                      if(!project.options) project.options = { };
4370
4371                      // Project Wide Settings (All configs)
4372                      if(!strcmpi(buffer, "Target Name"))
4373                         project.options.targetFileName = /*CopyString(*/equal/*)*/;
4374                      else if(!strcmpi(buffer, "Target Type"))
4375                      {
4376                         if(!strcmpi(equal, "Executable"))
4377                            project.options.targetType = executable;
4378                         else if(!strcmpi(equal, "Shared"))
4379                            project.options.targetType = sharedLibrary;
4380                         else if(!strcmpi(equal, "Static"))
4381                            project.options.targetType = staticLibrary;
4382                         else
4383                            project.options.targetType = executable;
4384                      }
4385                      else if(!strcmpi(buffer, "Target Directory"))
4386                         project.options.targetDirectory = /*CopyString(*/equal/*)*/;
4387                      else if(!strcmpi(buffer, "Console"))
4388                         project.options.console = ParseTrueFalseValue(equal);
4389                      else if(!strcmpi(buffer, "Libraries"))
4390                      {
4391                         if(!project.options.libraries) project.options.libraries = { };
4392                         ParseArrayValue(project.options.libraries, equal);
4393                      }
4394                      else if(!strcmpi(buffer, "AllWarnings"))
4395                         project.options.warnings = ParseTrueFalseValue(equal) ? all : unset;
4396                      else if(!strcmpi(buffer, "Preprocessor Definitions"))
4397                      {
4398                         if(!strcmpi(section, "Target") && !strcmpi(subSection, "Files"))
4399                         {
4400                            /*if(node && (node.type == NodeTypes::project || (node.type == file && !node.isInResources) || node.type == folder))
4401                               ParseListValue(node.preprocessorDefs, equal);*/
4402                         }
4403                         else
4404                         {
4405                            if(!project.options.preprocessorDefinitions) project.options.preprocessorDefinitions = { };
4406                            ParseArrayValue(project.options.preprocessorDefinitions, equal);
4407                         }
4408                      }
4409                   }
4410                }
4411             }
4412          }
4413       }
4414    }
4415    parent = null;
4416
4417    SplitPlatformLibraries(project);
4418
4419    if(configurationsPresent)
4420       CombineIdenticalConfigOptions(project);
4421    return project;
4422 }
4423
4424 void SplitPlatformLibraries(Project project)
4425 {
4426    if(project && project.configurations)
4427    {
4428       for(cfg : project.configurations)
4429       {
4430          if(cfg.options.libraries && cfg.options.libraries.count)
4431          {
4432             Iterator<String> it { cfg.options.libraries };
4433             while(it.Next())
4434             {
4435                String l = it.data;
4436                char * platformName = strstr(l, ":");
4437                if(platformName)
4438                {
4439                   PlatformOptions platform = null;
4440                   platformName++;
4441                   if(!cfg.platforms) cfg.platforms = { };
4442                   for(p : cfg.platforms)
4443                   {
4444                      if(!strcmpi(platformName, p.name))
4445                      {
4446                         platform = p;
4447                         break;
4448                      }
4449                   }
4450                   if(!platform)
4451                   {
4452                      platform = { name = CopyString(platformName), options = { libraries = { } } };
4453                      cfg.platforms.Add(platform);
4454                   }
4455                   *(platformName-1) = 0;
4456                   platform.options.libraries.Add(CopyString(l));
4457
4458                   cfg.options.libraries.Delete(it.pointer);
4459                   it.pointer = null;
4460                }
4461             }
4462          }
4463       }
4464    }
4465 }
4466
4467 void CombineIdenticalConfigOptions(Project project)
4468 {
4469    if(project && project.configurations && project.configurations.count)
4470    {
4471       DataMember member;
4472       ProjectOptions nullOptions { };
4473       ProjectConfig firstConfig = null;
4474       for(cfg : project.configurations)
4475       {
4476          if(cfg.options.targetType != staticLibrary)
4477          {
4478             firstConfig = cfg;
4479             break;
4480          }
4481       }
4482       if(!firstConfig)
4483          firstConfig = project.configurations.firstIterator.data;
4484
4485       for(member = class(ProjectOptions).membersAndProperties.first; member; member = member.next)
4486       {
4487          if(!member.isProperty)
4488          {
4489             Class type = eSystem_FindClass(__thisModule, member.dataTypeString);
4490             if(type)
4491             {
4492                bool same = true;
4493
4494                for(cfg : project.configurations)
4495                {
4496                   if(cfg != firstConfig)
4497                   {
4498                      if(cfg.options.targetType != staticLibrary)
4499                      {
4500                         int result;
4501
4502                         if(type.type == noHeadClass || type.type == normalClass)
4503                         {
4504                            result = ((int (*)(void *, void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnCompare])(type,
4505                               *(void **)((byte *)firstConfig.options + member.offset + member._class.offset),
4506                               *(void **)((byte *)cfg.options         + member.offset + member._class.offset));
4507                         }
4508                         else
4509                         {
4510                            result = ((int (*)(void *, void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnCompare])(type,
4511                               (byte *)firstConfig.options + member.offset + member._class.offset,
4512                               (byte *)cfg.options         + member.offset + member._class.offset);
4513                         }
4514                         if(result)
4515                         {
4516                            same = false;
4517                            break;
4518                         }
4519                      }
4520                   }
4521                }
4522                if(same)
4523                {
4524                   if(type.type == noHeadClass || type.type == normalClass)
4525                   {
4526                      if(!((int (*)(void *, void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnCompare])(type,
4527                         *(void **)((byte *)firstConfig.options + member.offset + member._class.offset),
4528                         *(void **)((byte *)nullOptions         + member.offset + member._class.offset)))
4529                         continue;
4530                   }
4531                   else
4532                   {
4533                      if(!((int (*)(void *, void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnCompare])(type,
4534                         (byte *)firstConfig.options + member.offset + member._class.offset,
4535                         (byte *)nullOptions         + member.offset + member._class.offset))
4536                         continue;
4537                   }
4538
4539                   if(!project.options) project.options = { };
4540
4541                   /*if(type.type == noHeadClass || type.type == normalClass)
4542                   {
4543                      ((void (*)(void *, void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnCopy])(type,
4544                         (byte *)project.options + member.offset + member._class.offset,
4545                         *(void **)((byte *)firstConfig.options + member.offset + member._class.offset));
4546                   }
4547                   else
4548                   {
4549                      void * address = (byte *)firstConfig.options + member.offset + member._class.offset;
4550                      // TOFIX: ListBox::SetData / OnCopy mess
4551                      ((void (*)(void *, void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnCopy])(type,
4552                         (byte *)project.options + member.offset + member._class.offset,
4553                         (type.typeSize > 4) ? address :
4554                            ((type.typeSize == 4) ? (void *)*(uint32 *)address :
4555                               ((type.typeSize == 2) ? (void *)*(uint16*)address :
4556                                  (void *)*(byte *)address )));
4557                   }*/
4558                   memcpy(
4559                      (byte *)project.options + member.offset + member._class.offset,
4560                      (byte *)firstConfig.options + member.offset + member._class.offset, type.typeSize);
4561
4562                   for(cfg : project.configurations)
4563                   {
4564                      if(cfg.options.targetType == staticLibrary)
4565                      {
4566                         int result;
4567
4568                         if(type.type == noHeadClass || type.type == normalClass)
4569                         {
4570                            result = ((int (*)(void *, void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnCompare])(type,
4571                               *(void **)((byte *)firstConfig.options + member.offset + member._class.offset),
4572                               *(void **)((byte *)cfg.options         + member.offset + member._class.offset));
4573                         }
4574                         else
4575                         {
4576                            result = ((int (*)(void *, void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnCompare])(type,
4577                               (byte *)firstConfig.options + member.offset + member._class.offset,
4578                               (byte *)cfg.options         + member.offset + member._class.offset);
4579                         }
4580                         if(result)
4581                            continue;
4582                      }
4583                      if(cfg != firstConfig)
4584                      {
4585                         if(type.type == noHeadClass || type.type == normalClass)
4586                         {
4587                            ((void (*)(void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnFree])(type,
4588                               *(void **)((byte *)cfg.options + member.offset + member._class.offset));
4589                         }
4590                         else
4591                         {
4592                            ((void (*)(void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnFree])(type,
4593                               (byte *)cfg.options + member.offset + member._class.offset);
4594                         }
4595                         memset((byte *)cfg.options + member.offset + member._class.offset, 0, type.typeSize);
4596                      }
4597                   }
4598                   memset((byte *)firstConfig.options + member.offset + member._class.offset, 0, type.typeSize);
4599                }
4600             }
4601          }
4602       }
4603       delete nullOptions;
4604
4605       // Compare Platform Specific Settings
4606       {
4607          bool same = true;
4608          for(cfg : project.configurations)
4609          {
4610             if(cfg != firstConfig && cfg.options.targetType != staticLibrary && (firstConfig.platforms || cfg.platforms) &&
4611                ((!firstConfig.platforms && cfg.platforms) || firstConfig.platforms.OnCompare(cfg.platforms)))
4612             {
4613                same = false;
4614                break;
4615             }
4616          }
4617          if(same && firstConfig.platforms)
4618          {
4619             for(cfg : project.configurations)
4620             {
4621                if(cfg.options.targetType == staticLibrary && firstConfig.platforms.OnCompare(cfg.platforms))
4622                   continue;
4623                if(cfg != firstConfig)
4624                {
4625                   cfg.platforms = null;
4626                }
4627             }
4628             project.platforms = firstConfig.platforms;
4629             *&firstConfig.platforms = null;
4630          }
4631       }
4632
4633       // Static libraries can't contain libraries
4634       for(cfg : project.configurations)
4635       {
4636          if(cfg.options.targetType == staticLibrary)
4637          {
4638             if(!cfg.options.libraries) cfg.options.libraries = { };
4639             cfg.options.libraries.Free();
4640          }
4641       }
4642    }
4643 }
4644
4645 Project LoadProject(const char * filePath, const char * activeConfigName)
4646 {
4647    Project project = null;
4648    File f = FileOpen(filePath, read);
4649    if(f)
4650    {
4651       project = LegacyBinaryLoadProject(f, filePath);
4652       if(!project)
4653       {
4654          ECONParser parser { f = f };
4655          /*JSONResult result = */parser.GetObject(class(Project), &project);
4656          if(project)
4657          {
4658             char insidePath[MAX_LOCATION];
4659
4660             delete project.topNode.files;
4661             if(!project.files) project.files = { };
4662             project.topNode.files = project.files;
4663
4664             {
4665                char topNodePath[MAX_LOCATION];
4666                GetWorkingDir(topNodePath, sizeof(topNodePath)-1);
4667                MakeSlashPath(topNodePath);
4668                PathCatSlash(topNodePath, filePath);
4669                project.filePath = topNodePath;//filePath;
4670             }
4671
4672             project.topNode.FixupNode(insidePath);
4673
4674             project.resNode = project.topNode.Add(project, "Resources", project.topNode.files.last, resources, archiveFile, false);
4675             delete project.resNode.path;
4676             project.resNode.path = project.resourcesPath;
4677             project.resourcesPath = null;
4678             project.resNode.nodeType = (ProjectNodeType)-1;
4679             delete project.resNode.files;
4680             project.resNode.files = project.resources;
4681             project.files = null;
4682             project.resources = null;
4683             if(!project.configurations) project.configurations = { };
4684
4685             project.resNode.FixupNode(insidePath);
4686          }
4687          delete parser;
4688       }
4689       if(!project)
4690          project = LegacyAsciiLoadProject(f, filePath);
4691
4692       delete f;
4693
4694       if(project)
4695       {
4696          if(!project.options) project.options = { };
4697          if(activeConfigName && activeConfigName[0] && project.configurations)
4698             project.config = project.GetConfig(activeConfigName);
4699          if(!project.config && project.configurations)
4700             project.config = project.configurations.firstIterator.data;
4701
4702          if(!project.resNode)
4703          {
4704             project.resNode = project.topNode.Add(project, "Resources", project.topNode.files.last, resources, archiveFile, false);
4705          }
4706
4707          if(!project.moduleName)
4708             project.moduleName = CopyString(project.name);
4709          if(project.config &&
4710             (!project.options || !project.options.targetFileName || !project.options.targetFileName[0]) &&
4711             (!project.config.options.targetFileName || !project.config.options.targetFileName[0]))
4712          {
4713             //delete project.config.options.targetFileName;
4714
4715             project.options.targetFileName = /*CopyString(*/project.moduleName/*)*/;
4716             project.config.options.optimization = none;
4717             project.config.options.debug = true;
4718             //project.config.options.warnings = unset;
4719             project.config.options.memoryGuard = false;
4720             project.config.compilingModified = true;
4721             project.config.linkingModified = true;
4722          }
4723          else if(!project.topNode.name && project.config)
4724          {
4725             project.topNode.name = CopyString(project.config.options.targetFileName);
4726          }
4727
4728          /* // THIS IS NOW AUTOMATED WITH A project CHECK IN ProjectNode
4729          project.topNode.configurations = project.configurations;
4730          project.topNode.platforms = project.platforms;
4731          project.topNode.options = project.options;*/
4732       }
4733    }
4734    return project;
4735 }
4736
4737 #ifndef MAKEFILE_GENERATOR
4738 static GccVersionInfo GetGccVersionInfo(CompilerConfig compiler, const String compilerCommand)
4739 {
4740    GccVersionInfo result = unknown;
4741    if(compiler.ccCommand)
4742    {
4743       char command[MAX_F_STRING*4];
4744       DualPipe f;
4745       sprintf(command, "%s%s --version", compiler.gccPrefix ? compiler.gccPrefix : "", compilerCommand);
4746       if((f = DualPipeOpen(PipeOpenMode { output = true, error = true, input = true }, command)))
4747       {
4748          bool firstLine = true;
4749          while(!f.eof)
4750          {
4751             char line[1024];
4752             char * tokens[128];
4753             if(f.GetLine(line,sizeof(line)))
4754             {
4755                if(firstLine)
4756                {
4757                   uint count = Tokenize(line, sizeof(tokens)/sizeof(tokens[0]), tokens,false);
4758                   char * token = null;
4759                   int i;
4760                   bool inPar = false;
4761                   for(i = 0; i < count; i++)
4762                   {
4763                      if(tokens[i][0] == '(')
4764                      {
4765                         if(tokens[i][strlen(tokens[i])-1] != ')')
4766                            inPar = true;
4767                      }
4768                      else if(tokens[i][0] && tokens[i][strlen(tokens[i])-1] == ')')
4769                         inPar = false;
4770                      else if(!inPar && isdigit(tokens[i][0]) && strchr(tokens[i], '.'))
4771                         token = tokens[i];
4772                   }
4773                   if(token)
4774                      result = GccVersionInfo::GetVersionInfo(token);
4775                   firstLine = false;
4776                }
4777             }
4778          }
4779          delete f;
4780       }
4781    }
4782    return result;
4783 }
4784
4785 static enum GccVersionInfo
4786 {
4787    unknown, pre4_8, post4_8;
4788
4789    GccVersionInfo ::GetVersionInfo(char * version)
4790    {
4791       GccVersionInfo result = unknown;
4792       int ver;
4793       char * s = CopyString(version);
4794       char * tokens[16];
4795       uint count = TokenizeWith(s, sizeof(tokens)/sizeof(tokens[0]), tokens, ".", false);
4796       ver = count > 1 ? atoi(tokens[1]) : 0;
4797       ver += count ? atoi(tokens[0]) * 1000 : 0;
4798       if(ver > 0)
4799       {
4800          if(ver < 4008)
4801             result = pre4_8;
4802          else
4803             result = post4_8;
4804       }
4805       delete s;
4806       return result;
4807    }
4808 };
4809 #endif