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