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