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