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