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