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