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