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