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