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