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