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