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