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