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