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