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