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