ide; improved cleantarget/clean/realclean output.
[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.Tellf($"Deleting %s%s...",
2179                   cleanType == realClean ? $"intermediate objects directory" : $"target",
2180                   cleanType == clean ? $" and object files" : "");
2181             if(justPrint)
2182                ProcessPipeOutputRaw(f);
2183             else
2184                ProcessCleanPipeOutput(f, compiler, config);
2185             ide.outputView.buildBox.Logf($"%s%s deleted\n",
2186                   cleanType == realClean ? $"Intermediate objects directory" : $"Target",
2187                   cleanType == clean ? $" and object files" : "");
2188             delete f;
2189          }
2190       }
2191
2192       delete pathBackup;
2193       delete compilerName;
2194    }
2195
2196    void Run(char * args, CompilerConfig compiler, ProjectConfig config, int bitDepth)
2197    {   
2198       String target = new char[maxPathLen];
2199       char oldDirectory[MAX_LOCATION];
2200       char * executableLauncher = compiler.executableLauncher;
2201       DirExpression targetDirExp = GetTargetDir(compiler, config, bitDepth);
2202       PathBackup pathBackup { };
2203
2204       // Build(project, ideMain, true, null, false);
2205
2206    #if defined(__WIN32__)
2207       strcpy(target, topNode.path);
2208    #else
2209       strcpy(target, "");
2210    #endif
2211       PathCatSlash(target, targetDirExp.dir);
2212       CatTargetFileName(target, compiler, config);
2213       sprintf(target, "%s %s", target, args);
2214       GetWorkingDir(oldDirectory, MAX_LOCATION);
2215
2216       if(strlen(ide.workspace.debugDir))
2217       {
2218          char temp[MAX_LOCATION];
2219          strcpy(temp, topNode.path);
2220          PathCatSlash(temp, ide.workspace.debugDir);
2221          ChangeWorkingDir(temp);
2222       }
2223       else
2224          ChangeWorkingDir(topNode.path);
2225       // ChangeWorkingDir(topNode.path);
2226       SetPath(true, compiler, config, bitDepth);
2227       if(executableLauncher)
2228       {
2229          char * prefixedTarget = new char[strlen(executableLauncher) + strlen(target) + 2];
2230          prefixedTarget[0] = '\0';
2231          strcat(prefixedTarget, executableLauncher);
2232          strcat(prefixedTarget, " ");
2233          strcat(prefixedTarget, target);
2234          Execute(prefixedTarget);
2235          delete prefixedTarget;
2236       }
2237       else
2238          Execute(target);
2239
2240       ChangeWorkingDir(oldDirectory);
2241       delete pathBackup;
2242
2243       delete targetDirExp;
2244       delete target;
2245    }
2246
2247    bool Compile(List<ProjectNode> nodes, CompilerConfig compiler, ProjectConfig config, int bitDepth, bool justPrint, SingleFileCompileMode mode)
2248    {
2249       return Build(false, nodes, compiler, config, bitDepth, justPrint, mode);
2250    }
2251 #endif
2252
2253    void GetMakefileTargetFileName(TargetTypes targetType, char * fileName, ProjectConfig config)
2254    {
2255       fileName[0] = '\0';
2256       if(targetType == staticLibrary || targetType == sharedLibrary)
2257          strcat(fileName, "$(LP)");
2258       // !!! ReplaceSpaces must be done after all PathCat calls !!!
2259       // ReplaceSpaces(s, GetTargetFileName(config));
2260       strcat(fileName, GetTargetFileName(config));
2261       switch(targetType)
2262       {
2263          case executable:
2264             strcat(fileName, "$(E)");
2265             break;
2266          case sharedLibrary:
2267             strcat(fileName, "$(SO)$(VER)");
2268             break;
2269          case staticLibrary:
2270             strcat(fileName, "$(A)");
2271             break;
2272       }
2273    }
2274
2275    bool GenerateCrossPlatformMk(File altCrossPlatformMk)
2276    {
2277       bool result = false;
2278       char path[MAX_LOCATION];
2279
2280       if(!GetProjectCompilerConfigsDir(path, false, false))
2281          GetIDECompilerConfigsDir(path, false, false);
2282
2283       if(!FileExists(path).isDirectory)
2284       {
2285          MakeDir(path);
2286          {
2287             char dirName[MAX_FILENAME];
2288             GetLastDirectory(path, dirName);
2289             if(!strcmp(dirName, ".configs"))
2290                FileSetAttribs(path, FileAttribs { isHidden = true });
2291          }
2292       }
2293       PathCatSlash(path, "crossplatform.mk");
2294
2295       if(FileExists(path))
2296          DeleteFile(path);
2297       {
2298          File include = altCrossPlatformMk ? altCrossPlatformMk : FileOpen(":crossplatform.mk", read);
2299          if(include)
2300          {
2301             File f = FileOpen(path, write);
2302             if(f)
2303             {
2304                include.Seek(0, start);
2305                for(; !include.Eof(); )
2306                {
2307                   char buffer[4096];
2308                   int count = include.Read(buffer, 1, 4096);
2309                   f.Write(buffer, 1, count);
2310                }
2311                delete f;
2312
2313                result = true;
2314             }
2315             if(!altCrossPlatformMk)
2316                delete include;
2317          }
2318       }
2319       return result;
2320    }
2321
2322    bool GenerateCompilerCf(CompilerConfig compiler)
2323    {
2324       bool result = false;
2325       char path[MAX_LOCATION];
2326       char * name;
2327       char * compilerName;
2328       bool gccCompiler = compiler.ccCommand && (strstr(compiler.ccCommand, "gcc") != null || strstr(compiler.ccCommand, "g++") != null);
2329       char * gnuToolchainPrefix = compiler.gnuToolchainPrefix ? compiler.gnuToolchainPrefix : "";
2330       Platform platform = compiler.targetPlatform;
2331
2332       compilerName = CopyString(compiler.name);
2333       CamelCase(compilerName);
2334       name = PrintString(platform, "-", compilerName, ".cf");
2335
2336       if(!GetProjectCompilerConfigsDir(path, false, false))
2337          GetIDECompilerConfigsDir(path, false, false);
2338
2339       if(!FileExists(path).isDirectory)
2340       {
2341          MakeDir(path);
2342          {
2343             char dirName[MAX_FILENAME];
2344             GetLastDirectory(path, dirName);
2345             if(!strcmp(dirName, ".configs"))
2346                FileSetAttribs(path, FileAttribs { isHidden = true });
2347          }
2348       }
2349       PathCatSlash(path, name);
2350
2351       if(FileExists(path))
2352          DeleteFile(path);
2353       {
2354          File f = FileOpen(path, write);
2355          if(f)
2356          {
2357             if(compiler.environmentVars && compiler.environmentVars.count)
2358             {
2359                f.Puts("# ENVIRONMENT VARIABLES\n");
2360                f.Puts("\n");
2361                for(e : compiler.environmentVars)
2362                {
2363                   f.Printf("export %s := %s\n", e.name, e.string);
2364                }
2365                f.Puts("\n");
2366             }
2367
2368             f.Puts("# TOOLCHAIN\n");
2369             f.Puts("\n");
2370
2371             if(gnuToolchainPrefix && gnuToolchainPrefix[0])
2372             {
2373                f.Printf("GCC_PREFIX := %s\n", gnuToolchainPrefix);
2374                f.Puts("\n");
2375             }
2376             if(compiler.sysroot && compiler.sysroot[0])
2377             {
2378                f.Printf("SYSROOT := %s\n", compiler.sysroot);
2379                // Moved this to crossplatform.mk
2380                //f.Puts("_SYSROOT := $(space)--sysroot=$(SYSROOT)\n");
2381                f.Puts("\n");
2382             }
2383
2384             //f.Printf("SHELL := %s\n", "sh"/*compiler.shellCommand*/); // is this really needed?
2385             f.Printf("CPP := $(CCACHE_COMPILE)$(DISTCC_COMPILE)$(GCC_PREFIX)%s$(_SYSROOT)\n", compiler.cppCommand);
2386             f.Printf("CC := $(CCACHE_COMPILE)$(DISTCC_COMPILE)$(GCC_PREFIX)%s$(_SYSROOT)\n", compiler.ccCommand);
2387             f.Printf("CXX := $(CCACHE_COMPILE)$(DISTCC_COMPILE)$(GCC_PREFIX)%s$(_SYSROOT)\n", compiler.cxxCommand);
2388             f.Printf("ECP := $(if $(ECP_DEBUG),ide -debug-start \"$(ECERE_SDK_SRC)/compiler/ecp/ecp.epj\" -debug-work-dir \"${CURDIR}\" -@,%s)\n", compiler.ecpCommand);
2389             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);
2390             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);
2391             f.Printf("EAR := %s\n", compiler.earCommand);
2392
2393             f.Puts("AS := $(GCC_PREFIX)as\n");
2394             f.Puts("LD := $(GCC_PREFIX)ld\n");
2395             f.Puts("AR := $(GCC_PREFIX)ar\n");
2396             f.Puts("STRIP := $(GCC_PREFIX)strip\n");
2397             f.Puts("ifdef WINDOWS_TARGET\n");
2398             f.Puts("WINDRES := $(GCC_PREFIX)windres\n");
2399             f.Puts(" ifdef ARCH\n");
2400             f.Puts("  ifeq \"$(ARCH)\" \"x32\"\n");
2401             f.Puts("WINDRES_FLAGS := -F pe-i386\n");
2402             f.Puts("  else\n");
2403             f.Puts("   ifeq \"$(ARCH)\" \"x64\"\n");
2404             f.Puts("WINDRES_FLAGS := -F pe-x86-64\n");
2405             f.Puts("   endif\n");
2406             f.Puts("  endif\n");
2407             f.Puts(" endif\n");
2408             f.Puts("endif\n");
2409             f.Puts("UPX := upx\n");
2410             f.Puts("\n");
2411
2412             f.Puts("UPXFLAGS = -9\n"); // TOFEAT: Compression Level Option? Other UPX Options?
2413             f.Puts("\n");
2414
2415             f.Puts("EARFLAGS = \n");
2416             f.Puts("\n");
2417
2418             f.Puts("ifndef ARCH\n");
2419             f.Puts("TARGET_ARCH :=$(shell $(CC) -dumpmachine)\n");
2420             f.Puts(" ifdef WINDOWS_HOST\n");
2421             f.Puts("  ifneq ($(filter x86_64%,$(TARGET_ARCH)),)\n");
2422             f.Puts("     TARGET_ARCH := x86_64\n");
2423             f.Puts("  else\n");
2424             f.Puts("     TARGET_ARCH := i386\n");
2425             f.Puts("  endif\n");
2426             f.Puts(" endif\n");
2427             f.Puts("endif\n\n");
2428
2429             f.Puts("# HARD CODED TARGET_PLATFORM-SPECIFIC OPTIONS\n");
2430             f.Printf("LDFLAGS +=$(if $(%s), -Wl$(comma)--no-undefined,)\n", PlatformToMakefileTargetVariable(tux));
2431             f.Puts("\n");
2432
2433             // JF's
2434             f.Printf("LDFLAGS +=$(if $(%s), -framework cocoa -framework OpenGL,)\n", PlatformToMakefileTargetVariable(apple));
2435
2436             if(gccCompiler)
2437             {
2438                f.Puts("\nCFLAGS += -fmessage-length=0\n");
2439             }
2440
2441             if(compiler.includeDirs && compiler.includeDirs.count)
2442             {
2443                f.Puts("\nCFLAGS +=");
2444                OutputListOption(f, gccCompiler ? "isystem " : "I", compiler.includeDirs, lineEach, true);
2445                f.Puts("\n");
2446             }
2447             if(compiler.prepDirectives && compiler.prepDirectives.count)
2448             {
2449                f.Puts("\nCFLAGS +=");
2450                OutputListOption(f, "D", compiler.prepDirectives, inPlace, true);
2451                f.Puts("\n");
2452             }
2453             if(compiler.libraryDirs && compiler.libraryDirs.count)
2454             {
2455                f.Puts("\nLDFLAGS +=");
2456                OutputListOption(f, "L", compiler.libraryDirs, lineEach, true);
2457                // We would need a bool option to know whether we want to add to rpath as well...
2458                // OutputListOption(f, "Wl,-rpath ", compiler.libraryDirs, lineEach, true);
2459                f.Puts("\n");
2460             }
2461             if(compiler.excludeLibs && compiler.excludeLibs.count)
2462             {
2463                f.Puts("\nEXCLUDED_LIBS =");
2464                for(l : compiler.excludeLibs)
2465                {
2466                   f.Puts(" ");
2467                   f.Puts(l);
2468                }
2469             }
2470             if(compiler.compilerFlags && compiler.compilerFlags.count)
2471             {
2472                f.Puts("\nCFLAGS +=");
2473                OutputListOption(f, "", compiler.compilerFlags, inPlace, true);
2474                f.Puts("\n");
2475             }
2476             if(compiler.linkerFlags && compiler.linkerFlags.count)
2477             {
2478                f.Puts("\nLDFLAGS +=");
2479                OutputListOption(f, "Wl,", compiler.linkerFlags, inPlace, true);
2480                f.Puts("\n");
2481             }
2482             f.Puts("\n");
2483             f.Puts("\nOFLAGS += $(LDFLAGS)");
2484             f.Puts("\n");
2485             f.Puts("ifdef ARCH_FLAGS\n");
2486             f.Puts("CFLAGS += $(ARCH_FLAGS)\n");
2487             f.Puts("OFLAGS += $(ARCH_FLAGS)\n");
2488             f.Puts("endif\n");
2489
2490             delete f;
2491
2492             result = true;
2493          }
2494       }
2495       delete name;
2496       delete compilerName;
2497       return result;
2498    }
2499
2500    bool GenerateMakefile(char * altMakefilePath, bool noResources, char * includemkPath, ProjectConfig config)
2501    {
2502       bool result = false;
2503       char filePath[MAX_LOCATION];
2504       char makeFile[MAX_LOCATION];
2505       // PathBackup pathBackup { };
2506       // char oldDirectory[MAX_LOCATION];
2507       File f = null;
2508
2509       if(!altMakefilePath)
2510       {
2511          strcpy(filePath, topNode.path);
2512          CatMakeFileName(makeFile, config);
2513          PathCatSlash(filePath, makeFile);
2514       }
2515
2516       f = FileOpen(altMakefilePath ? altMakefilePath : filePath, write);
2517
2518       /*SetPath(false, compiler, config);
2519       GetWorkingDir(oldDirectory, MAX_LOCATION);
2520       ChangeWorkingDir(topNode.path);*/
2521
2522       if(f)
2523       {
2524          bool test;
2525          int ifCount;
2526          Platform platform;
2527          char targetDir[MAX_LOCATION];
2528          char objDirExpNoSpaces[MAX_LOCATION];
2529          char objDirNoSpaces[MAX_LOCATION];
2530          char resDirNoSpaces[MAX_LOCATION];
2531          char targetDirExpNoSpaces[MAX_LOCATION];
2532          char fixedModuleName[MAX_FILENAME];
2533          char fixedConfigName[MAX_FILENAME];
2534          int c, len;
2535          // Non-zero if we're building eC code
2536          // We'll have to be careful with this when merging configs where eC files can be excluded in some configs and included in others
2537          int numCObjects = 0;
2538          int numObjects = 0;
2539          int numRCObjects = 0;
2540          bool containsCXX = false; // True if the project contains a C++ file
2541          bool sameObjTargetDirs;
2542          String objDirExp = GetObjDirExpression(config);
2543          TargetTypes targetType = GetTargetType(config);
2544
2545          char cfDir[MAX_LOCATION];
2546          int objectsParts = 0;
2547          int eCsourcesParts = 0;
2548          int rcSourcesParts = 0;
2549          Array<String> listItems { };
2550          Map<String, int> varStringLenDiffs { };
2551          Map<String, NameCollisionInfo> namesInfo { };
2552
2553          Map<String, int> cflagsVariations { };
2554          Map<intptr, int> nodeCFlagsMapping { };
2555
2556          Map<String, int> ecflagsVariations { };
2557          Map<intptr, int> nodeECFlagsMapping { };
2558
2559          ReplaceSpaces(objDirNoSpaces, objDirExp);
2560          strcpy(targetDir, GetTargetDirExpression(config));
2561          ReplaceSpaces(targetDirExpNoSpaces, targetDir);
2562
2563          strcpy(objDirExpNoSpaces, GetObjDirExpression(config));
2564          ChangeCh(objDirExpNoSpaces, '\\', '/'); // TODO: this is a hack, paths should never include win32 path seperators - fix this in ProjectSettings and ProjectLoad instead
2565          {
2566             char temp[MAX_LOCATION];
2567             ReplaceSpaces(temp, objDirExpNoSpaces);
2568             strcpy(objDirExpNoSpaces, temp);
2569          }
2570          ReplaceSpaces(resDirNoSpaces, resNode.path ? resNode.path : "");
2571          ReplaceSpaces(fixedModuleName, moduleName);
2572          ReplaceSpaces(fixedConfigName, GetConfigName(config));
2573          CamelCase(fixedConfigName);
2574
2575          sameObjTargetDirs = !fstrcmp(objDirExpNoSpaces, targetDirExpNoSpaces);
2576
2577          f.Printf(".PHONY: all objdir%s cleantarget clean realclean distclean\n\n", sameObjTargetDirs ? "" : " targetdir");
2578
2579          f.Puts("# CORE VARIABLES\n\n");
2580
2581          f.Printf("MODULE := %s\n", fixedModuleName);
2582          f.Printf("VERSION := %s\n", property::moduleVersion);
2583          f.Printf("CONFIG := %s\n", fixedConfigName);
2584          f.Puts("ifndef COMPILER\n" "COMPILER := default\n" "endif\n");
2585          f.Puts("\n");
2586
2587          test = GetTargetTypeIsSetByPlatform(config);
2588          if(test)
2589          {
2590             ifCount = 0;
2591             for(platform = (Platform)1; platform < Platform::enumSize; platform++)
2592             {
2593                TargetTypes targetType;
2594                PlatformOptions projectPOs, configPOs;
2595                MatchProjectAndConfigPlatformOptions(config, platform, &projectPOs, &configPOs);
2596                targetType = platformTargetType;
2597                if(targetType)
2598                {
2599                   if(ifCount)
2600                      f.Puts("else\n");
2601                   ifCount++;
2602                   f.Printf("ifdef %s\n", PlatformToMakefileTargetVariable(platform));
2603                   f.Printf("TARGET_TYPE = %s\n", TargetTypeToMakefileVariable(targetType));
2604                }
2605             }
2606             f.Puts("else\n");
2607          }
2608          f.Printf("TARGET_TYPE = %s\n", TargetTypeToMakefileVariable(targetType));
2609          if(test)
2610          {
2611             if(ifCount)
2612             {
2613                for(c = 0; c < ifCount; c++)
2614                   f.Puts("endif\n");
2615             }
2616          }
2617          f.Puts("\n");
2618
2619          f.Puts("# FLAGS\n\n");
2620
2621          f.Puts("ECFLAGS =\n");
2622          f.Puts("ifndef DEBIAN_PACKAGE\n" "CFLAGS =\n" "LDFLAGS =\n" "endif\n");
2623          f.Puts("PRJ_CFLAGS =\n");
2624          f.Puts("CECFLAGS =\n");
2625          f.Puts("OFLAGS =\n");
2626          f.Puts("LIBS =\n");
2627          f.Puts("\n");
2628
2629          f.Puts("ifdef DEBUG\n" "NOSTRIP := y\n" "endif\n");
2630          f.Puts("\n");
2631
2632          // Important: We cannot use this ifdef anymore, EXECUTABLE_TARGET is not yet defined. It's embedded in the crossplatform.mk EXECUTABLE
2633          //f.Puts("ifdef EXECUTABLE_TARGET\n");
2634          f.Printf("CONSOLE = %s\n", GetConsole(config) ? "-mconsole" : "-mwindows");
2635          //f.Puts("endif\n");
2636          f.Puts("\n");
2637
2638          f.Puts("# INCLUDES\n\n");
2639
2640          if(compilerConfigsDir && compilerConfigsDir[0])
2641          {
2642             strcpy(cfDir, compilerConfigsDir);
2643             if(cfDir && cfDir[0] && cfDir[strlen(cfDir)-1] != '/')
2644                strcat(cfDir, "/");
2645          }
2646          else
2647          {
2648             GetIDECompilerConfigsDir(cfDir, true, true);
2649             // Use CF_DIR environment variable for absolute paths only
2650             if(cfDir[0] == '/' || (cfDir[0] && cfDir[1] == ':'))
2651                strcpy(cfDir, "$(CF_DIR)");
2652          }
2653
2654          f.Printf("_CF_DIR = %s\n", cfDir);
2655          f.Puts("\n");
2656
2657          f.Printf("include %s\n", includemkPath ? includemkPath : "$(_CF_DIR)crossplatform.mk");
2658          f.Puts("include $(_CF_DIR)$(TARGET_PLATFORM)-$(COMPILER).cf\n");
2659          f.Puts("\n");
2660
2661          f.Puts("# POST-INCLUDES VARIABLES\n\n");
2662
2663          f.Printf("OBJ = %s%s\n", objDirExpNoSpaces, objDirExpNoSpaces[0] ? "/" : "");
2664          f.Puts("\n");
2665
2666          f.Printf("RES = %s%s\n", resDirNoSpaces, resDirNoSpaces[0] ? "/" : "");
2667          f.Puts("\n");
2668
2669          // test = GetTargetTypeIsSetByPlatform(config);
2670          {
2671             char target[MAX_LOCATION];
2672             char temp[MAX_LOCATION];
2673             if(test)
2674             {
2675                TargetTypes type;
2676                ifCount = 0;
2677                for(type = (TargetTypes)1; type < TargetTypes::enumSize; type++)
2678                {
2679                   if(type != targetType)
2680                   {
2681                      if(ifCount)
2682                         f.Puts("else\n");
2683                      ifCount++;
2684                      f.Printf("ifeq \"$(TARGET_TYPE)\" \"%s\"\n", TargetTypeToMakefileVariable(type));
2685
2686                      GetMakefileTargetFileName(type, target, config);
2687                      strcpy(temp, targetDir);
2688                      PathCatSlash(temp, target);
2689                      ReplaceSpaces(target, temp);
2690                      f.Printf("TARGET = %s\n", target);
2691                   }
2692                }
2693                f.Puts("else\n");
2694             }
2695             GetMakefileTargetFileName(targetType, target, config);
2696             strcpy(temp, targetDir);
2697             PathCatSlash(temp, target);
2698             ReplaceSpaces(target, temp);
2699             f.Printf("TARGET = %s\n", target);
2700
2701             if(test)
2702             {
2703                if(ifCount)
2704                {
2705                   for(c = 0; c < ifCount; c++)
2706                      f.Puts("endif\n");
2707                }
2708             }
2709          }
2710          f.Puts("\n");
2711
2712          // Use something fixed here, to not cause Makefile differences across compilers...
2713          varStringLenDiffs["$(OBJ)"] = 30; // strlen("obj/memoryGuard.android.gcc-4.6.2") - 6;
2714          // varStringLenDiffs["$(OBJ)"] = strlen(objDirNoSpaces) - 6;
2715
2716          topNode.GenMakefileGetNameCollisionInfo(namesInfo, config);
2717
2718          {
2719             int c;
2720             char * map[5][2] = { { "COBJECTS", "C" }, { "SYMBOLS", "S" }, { "IMPORTS", "I" }, { "ECOBJECTS", "O" }, { "BOWLS", "B" } };
2721
2722             numCObjects = topNode.GenMakefilePrintNode(f, this, eCsources, namesInfo, listItems, config, null);
2723             if(numCObjects)
2724             {
2725                eCsourcesParts = OutputFileList(f, "_ECSOURCES", listItems, varStringLenDiffs, null);
2726
2727                f.Puts("ECSOURCES = $(call shwspace,$(_ECSOURCES))\n");
2728                if(eCsourcesParts > 1)
2729                {
2730                   for(c = 1; c <= eCsourcesParts; c++)
2731                      f.Printf("ECSOURCES%d = $(call shwspace,$(_ECSOURCES%d))\n", c, c);
2732                }
2733                f.Puts("\n");
2734
2735                for(c = 0; c < 5; c++)
2736                {
2737                   if(eCsourcesParts > 1)
2738                   {
2739                      int n;
2740                      f.Printf("%s =", map[c][0]);
2741                      for(n = 1; n <= eCsourcesParts; n++)
2742                         f.Printf(" $(%s%d)", map[c][0], n);
2743                      f.Puts("\n");
2744                      for(n = 1; n <= eCsourcesParts; n++)
2745                         f.Printf("%s%d = $(call shwspace,$(addprefix $(OBJ),$(patsubst %%.ec,%%$(%s),$(notdir $(_ECSOURCES%d)))))\n", map[c][0], n, map[c][1], n);
2746                   }
2747                   else if(eCsourcesParts == 1)
2748                      f.Printf("%s = $(call shwspace,$(addprefix $(OBJ),$(patsubst %%.ec,%%$(%s),$(notdir $(_ECSOURCES)))))\n", map[c][0], map[c][1]);
2749                   f.Puts("\n");
2750                }
2751             }
2752          }
2753
2754          numRCObjects = topNode.GenMakefilePrintNode(f, this, rcSources, namesInfo, listItems, config, null);
2755          if(numRCObjects)
2756          {
2757             f.Puts("ifdef WINDOWS_TARGET\n\n");
2758
2759             rcSourcesParts = OutputFileList(f, "_RCSOURCES", listItems, varStringLenDiffs, null);
2760
2761             f.Puts("RCSOURCES = $(call shwspace,$(_RCSOURCES))\n");
2762             if(rcSourcesParts > 1)
2763             {
2764                for(c = 1; c <= rcSourcesParts; c++)
2765                   f.Printf("RCSOURCES%d = $(call shwspace,$(_RCSOURCES%d))\n", c, c);
2766             }
2767             f.Puts("\n");
2768             if(rcSourcesParts > 1)
2769             {
2770                int n;
2771                f.Printf("%s =", "RCOBJECTS");
2772                for(n = 1; n <= rcSourcesParts; n++)
2773                   f.Printf(" $(%s%d)", "RCOBJECTS", n);
2774                f.Puts("\n");
2775                for(n = 1; n <= rcSourcesParts; n++)
2776                   f.Printf("%s%d = $(call shwspace,$(addprefix $(OBJ),$(patsubst %%.rc,%%$(%s),$(notdir $(_RCSOURCES%d)))))\n", "RCOBJECTS", n, "O", n);
2777             }
2778             else if(rcSourcesParts == 1)
2779                f.Printf("%s = $(call shwspace,$(addprefix $(OBJ),$(patsubst %%.rc,%%$(%s),$(notdir $(_RCSOURCES)))))\n", "RCOBJECTS", "O");
2780             f.Puts("\n");
2781
2782             f.Puts("else\n");
2783             f.Puts("RCSOURCES =\n");
2784             f.Puts("RCOBJECTS =\n");
2785             f.Puts("endif\n\n");
2786          }
2787
2788          numObjects = topNode.GenMakefilePrintNode(f, this, objects, namesInfo, listItems, config, &containsCXX);
2789          if(numObjects)
2790             objectsParts = OutputFileList(f, "_OBJECTS", listItems, varStringLenDiffs, null);
2791          f.Printf("OBJECTS =%s%s%s%s\n",
2792                numObjects ? " $(_OBJECTS)" : "", numCObjects ? " $(ECOBJECTS)" : "",
2793                numCObjects ? " $(OBJ)$(MODULE).main$(O)" : "",
2794                numRCObjects ? " $(RCOBJECTS)" : "");
2795          f.Puts("\n");
2796
2797          topNode.GenMakefilePrintNode(f, this, sources, null, listItems, config, null);
2798          {
2799             char * prefix;
2800             if(numCObjects && numRCObjects)
2801                prefix = "$(ECSOURCES) $(RCSOURCES)";
2802             else if(numCObjects)
2803                prefix = "$(ECSOURCES)";
2804             else
2805                prefix = null;
2806             OutputFileList(f, "SOURCES", listItems, varStringLenDiffs, prefix);
2807          }
2808
2809          if(!noResources)
2810             resNode.GenMakefilePrintNode(f, this, resources, null, listItems, config, null);
2811          OutputFileList(f, "RESOURCES", listItems, varStringLenDiffs, null);
2812
2813          f.Puts("LIBS += $(SHAREDLIB) $(EXECUTABLE) $(LINKOPT)\n");
2814          f.Puts("\n");
2815          if((config && config.options && config.options.libraries) ||
2816                (options && options.libraries))
2817          {
2818             f.Puts("ifndef STATIC_LIBRARY_TARGET\n");
2819             f.Puts("LIBS +=");
2820             if(config && config.options && config.options.libraries)
2821                OutputLibraries(f, config.options.libraries);
2822             else if(options && options.libraries)
2823                OutputLibraries(f, options.libraries);
2824             f.Puts("\n");
2825             f.Puts("endif\n");
2826             f.Puts("\n");
2827          }
2828
2829          topNode.GenMakeCollectAssignNodeFlags(config, numCObjects,
2830                cflagsVariations, nodeCFlagsMapping,
2831                ecflagsVariations, nodeECFlagsMapping, null);
2832
2833          GenMakePrintCustomFlags(f, "PRJ_CFLAGS", false, cflagsVariations);
2834          GenMakePrintCustomFlags(f, "ECFLAGS", true, ecflagsVariations);
2835
2836          if(platforms || (config && config.platforms))
2837          {
2838             ifCount = 0;
2839             //for(platform = firstPlatform; platform <= lastPlatform; platform++)
2840             //for(platform = win32; platform <= apple; platform++)
2841
2842             f.Puts("# PLATFORM-SPECIFIC OPTIONS\n\n");
2843             for(platform = (Platform)1; platform < Platform::enumSize; platform++)
2844             {
2845                PlatformOptions projectPlatformOptions, configPlatformOptions;
2846                MatchProjectAndConfigPlatformOptions(config, platform, &projectPlatformOptions, &configPlatformOptions);
2847
2848                if(projectPlatformOptions || configPlatformOptions)
2849                {
2850                   if(ifCount)
2851                      f.Puts("else\n");
2852                   ifCount++;
2853                   f.Printf("ifdef %s\n", PlatformToMakefileTargetVariable(platform));
2854                   f.Puts("\n");
2855
2856                   if((projectPlatformOptions && projectPlatformOptions.options.compilerOptions && projectPlatformOptions.options.compilerOptions.count) ||
2857                      (configPlatformOptions && configPlatformOptions.options.compilerOptions && configPlatformOptions.options.compilerOptions.count))
2858                   {
2859                      f.Puts("CFLAGS +=");
2860                      if(projectPlatformOptions && projectPlatformOptions.options.compilerOptions && projectPlatformOptions.options.compilerOptions.count)
2861                      {
2862                         f.Puts(" \\\n\t ");
2863                         for(s : projectPlatformOptions.options.compilerOptions)
2864                         {
2865                            f.Printf(" %s", s);
2866                         }
2867                      }
2868                      if(configPlatformOptions && configPlatformOptions.options.compilerOptions && configPlatformOptions.options.compilerOptions.count)
2869                      {
2870                         f.Puts(" \\\n\t ");
2871                         for(s : configPlatformOptions.options.compilerOptions)
2872                         {
2873                            f.Printf(" %s", s);
2874                         }
2875                      }
2876                      f.Puts("\n");
2877                      f.Puts("\n");
2878                   }
2879
2880                   if((projectPlatformOptions && projectPlatformOptions.options.linkerOptions && projectPlatformOptions.options.linkerOptions.count) ||
2881                      (configPlatformOptions && configPlatformOptions.options.linkerOptions && configPlatformOptions.options.linkerOptions.count))
2882                   {
2883                      f.Puts("OFLAGS +=");
2884                      if(projectPlatformOptions && projectPlatformOptions.options.linkerOptions && projectPlatformOptions.options.linkerOptions.count)
2885                      {
2886                         bool needWl = false;
2887                         f.Puts(" \\\n\t ");
2888                         for(s : projectPlatformOptions.options.linkerOptions)
2889                         {
2890                            if(!IsLinkerOption(s))
2891                               f.Printf(" %s", s);
2892                            else
2893                               needWl = true;
2894                         }
2895                         if(needWl)
2896                         {
2897                            f.Puts(" -Wl");
2898                            for(s : projectPlatformOptions.options.linkerOptions)
2899                               if(IsLinkerOption(s))
2900                                  f.Printf(",%s", s);
2901                         }
2902                      }
2903                      if(configPlatformOptions && configPlatformOptions.options.linkerOptions && configPlatformOptions.options.linkerOptions.count)
2904                      {
2905                         bool needWl = false;
2906                         f.Puts(" \\\n\t ");
2907                         for(s : configPlatformOptions.options.linkerOptions)
2908                         {
2909                            if(IsLinkerOption(s))
2910                               f.Printf(" %s", s);
2911                            else
2912                               needWl = true;
2913                         }
2914                         if(needWl)
2915                         {
2916                            f.Puts(" -Wl");
2917                            for(s : configPlatformOptions.options.linkerOptions)
2918                               if(!IsLinkerOption(s))
2919                                  f.Printf(",%s", s);
2920                         }
2921                      }
2922                      f.Puts("\n");
2923                      f.Puts("\n");
2924                   }
2925
2926                   if((projectPlatformOptions && projectPlatformOptions.options.libraryDirs && projectPlatformOptions.options.libraryDirs.count) ||
2927                         (configPlatformOptions && configPlatformOptions.options.libraryDirs && configPlatformOptions.options.libraryDirs.count) ||
2928                         (projectPlatformOptions && projectPlatformOptions.options.libraries && projectPlatformOptions.options.libraries.count) ||
2929                         (configPlatformOptions && configPlatformOptions.options.libraries && configPlatformOptions.options.libraries.count))
2930                   {
2931                      f.Puts("ifndef STATIC_LIBRARY_TARGET\n");
2932                      if((projectPlatformOptions && projectPlatformOptions.options.libraryDirs && projectPlatformOptions.options.libraryDirs.count) ||
2933                         (configPlatformOptions && configPlatformOptions.options.libraryDirs && configPlatformOptions.options.libraryDirs.count))
2934                      {
2935                         f.Puts("OFLAGS +=");
2936                         if(configPlatformOptions && configPlatformOptions.options.libraryDirs)
2937                            OutputListOption(f, "L", configPlatformOptions.options.libraryDirs, lineEach, true);
2938                         if(projectPlatformOptions && projectPlatformOptions.options.libraryDirs)
2939                            OutputListOption(f, "L", projectPlatformOptions.options.libraryDirs, lineEach, true);
2940                         f.Puts("\n");
2941                      }
2942
2943                      if((configPlatformOptions && configPlatformOptions.options.libraries))
2944                      {
2945                         if(configPlatformOptions.options.libraries.count)
2946                         {
2947                            f.Puts("LIBS +=");
2948                            OutputLibraries(f, configPlatformOptions.options.libraries);
2949                            f.Puts("\n");
2950                         }
2951                      }
2952                      else if(projectPlatformOptions && projectPlatformOptions.options.libraries)
2953                      {
2954                         if(projectPlatformOptions.options.libraries.count)
2955                         {
2956                            f.Puts("LIBS +=");
2957                            OutputLibraries(f, projectPlatformOptions.options.libraries);
2958                            f.Puts("\n");
2959                         }
2960                      }
2961                      f.Puts("endif\n");
2962                      f.Puts("\n");
2963                   }
2964                }
2965             }
2966             if(ifCount)
2967             {
2968                for(c = 0; c < ifCount; c++)
2969                   f.Puts("endif\n");
2970             }
2971             f.Puts("\n");
2972          }
2973
2974          if((config && config.options && config.options.linkerOptions && config.options.linkerOptions.count) ||
2975                (options && options.linkerOptions && options.linkerOptions.count))
2976          {
2977             f.Puts("OFLAGS +=");
2978             f.Puts(" \\\n\t");
2979
2980             if(config && config.options && config.options.linkerOptions && config.options.linkerOptions.count)
2981             {
2982                bool needWl = false;
2983                for(s : config.options.linkerOptions)
2984                {
2985                   if(!IsLinkerOption(s))
2986                      f.Printf(" %s", s);
2987                   else
2988                      needWl = true;
2989                }
2990                if(needWl)
2991                {
2992                   f.Puts(" -Wl");
2993                   for(s : config.options.linkerOptions)
2994                      if(IsLinkerOption(s))
2995                         f.Printf(",%s", s);
2996                }
2997             }
2998             if(options && options.linkerOptions && options.linkerOptions.count)
2999             {
3000                bool needWl = false;
3001                for(s : options.linkerOptions)
3002                {
3003                   if(!IsLinkerOption(s))
3004                      f.Printf(" %s", s);
3005                   else
3006                      needWl = true;
3007                }
3008                if(needWl)
3009                {
3010                   f.Puts(" -Wl");
3011                   for(s : options.linkerOptions)
3012                      if(IsLinkerOption(s))
3013                         f.Printf(",%s", s);
3014                }
3015             }
3016          }
3017          f.Puts("\n");
3018          f.Puts("\n");
3019
3020          f.Puts("CECFLAGS += -cpp $(_CPP)");
3021          f.Puts("\n");
3022          f.Puts("\n");
3023
3024          if(GetProfile(config))
3025             f.Puts("OFLAGS += -pg\n\n");
3026
3027          if((config && config.options && config.options.libraryDirs) || (options && options.libraryDirs))
3028          {
3029             f.Puts("ifndef STATIC_LIBRARY_TARGET\n");
3030             f.Puts("OFLAGS +=");
3031             if(config && config.options && config.options.libraryDirs)
3032                OutputListOption(f, "L", config.options.libraryDirs, lineEach, true);
3033             if(options && options.libraryDirs)
3034                OutputListOption(f, "L", options.libraryDirs, lineEach, true);
3035             f.Puts("\n");
3036             f.Puts("endif\n");
3037             f.Puts("\n");
3038          }
3039
3040          f.Puts("# TARGETS\n");
3041          f.Puts("\n");
3042
3043          f.Printf("all: objdir%s $(TARGET)\n", sameObjTargetDirs ? "" : " targetdir");
3044          f.Puts("\n");
3045
3046          f.Puts("objdir:\n");
3047             f.Puts("\t$(if $(wildcard $(OBJ)),,$(call mkdirq,$(OBJ)))\n");
3048             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");
3049             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");
3050          //f.Puts("# PRE-BUILD COMMANDS\n");
3051          if(options && options.prebuildCommands)
3052          {
3053             for(s : options.prebuildCommands)
3054                if(s && s[0]) f.Printf("\t%s\n", s);
3055          }
3056          if(config && config.options && config.options.prebuildCommands)
3057          {
3058             for(s : config.options.prebuildCommands)
3059                if(s && s[0]) f.Printf("\t%s\n", s);
3060          }
3061          if(platforms || (config && config.platforms))
3062          {
3063             ifCount = 0;
3064             //f.Puts("# TARGET_PLATFORM-SPECIFIC PRE-BUILD COMMANDS\n");
3065             for(platform = (Platform)1; platform < Platform::enumSize; platform++)
3066             {
3067                PlatformOptions projectPOs, configPOs;
3068                MatchProjectAndConfigPlatformOptions(config, platform, &projectPOs, &configPOs);
3069
3070                if((projectPOs && projectPOs.options.prebuildCommands && projectPOs.options.prebuildCommands.count) ||
3071                      (configPOs && configPOs.options.prebuildCommands && configPOs.options.prebuildCommands.count))
3072                {
3073                   if(ifCount)
3074                      f.Puts("else\n");
3075                   ifCount++;
3076                   f.Printf("ifdef %s\n", PlatformToMakefileTargetVariable(platform));
3077
3078                   if(projectPOs && projectPOs.options.prebuildCommands && projectPOs.options.prebuildCommands.count)
3079                   {
3080                      for(s : projectPOs.options.prebuildCommands)
3081                         if(s && s[0]) f.Printf("\t%s\n", s);
3082                   }
3083                   if(configPOs && configPOs.options.prebuildCommands && configPOs.options.prebuildCommands.count)
3084                   {
3085                      for(s : configPOs.options.prebuildCommands)
3086                         if(s && s[0]) f.Printf("\t%s\n", s);
3087                   }
3088                }
3089             }
3090             if(ifCount)
3091             {
3092                int c;
3093                for(c = 0; c < ifCount; c++)
3094                   f.Puts("endif\n");
3095             }
3096          }
3097          f.Puts("\n");
3098
3099          if(!sameObjTargetDirs)
3100          {
3101             f.Puts("targetdir:\n");
3102                f.Printf("\t$(if $(wildcard %s),,$(call mkdirq,%s))\n", targetDirExpNoSpaces, targetDirExpNoSpaces);
3103             f.Puts("\n");
3104          }
3105
3106          if(numCObjects)
3107          {
3108             // Main Module (Linking) for ECERE C modules
3109             f.Puts("$(OBJ)$(MODULE).main.ec: $(SYMBOLS) $(COBJECTS)\n");
3110             // use of objDirExpNoSpaces used instead of $(OBJ) to prevent problematic joining of arguments in ecs
3111             f.Printf("\t$(ECS)%s $(ARCH_FLAGS) $(ECSLIBOPT) $(SYMBOLS) $(IMPORTS) -symbols %s -o $@\n",
3112                GetConsole(config) ? " -console" : "", objDirExpNoSpaces);
3113             f.Puts("\n");
3114             // Main Module (Linking) for ECERE C modules
3115             f.Puts("$(OBJ)$(MODULE).main.c: $(OBJ)$(MODULE).main.ec\n");
3116             f.Puts("\t$(ECP) $(CFLAGS) $(CECFLAGS) $(ECFLAGS) $(PRJ_CFLAGS)"
3117                   " -c $(OBJ)$(MODULE).main.ec -o $(OBJ)$(MODULE).main.sym -symbols $(OBJ)\n");
3118             f.Puts("\t$(ECC) $(CFLAGS) $(CECFLAGS) $(ECFLAGS) $(PRJ_CFLAGS) $(FVISIBILITY)"
3119                   " -c $(OBJ)$(MODULE).main.ec -o $@ -symbols $(OBJ)\n");
3120             f.Puts("\n");
3121          }
3122
3123          // *** Target ***
3124
3125          // This would not rebuild the target on updated objects
3126          // f.Printf("$(TARGET): $(SOURCES) $(RESOURCES) | objdir $(SYMBOLS) $(OBJECTS)%s\n", sameObjTargetDirs ? "" : " targetdir");
3127
3128          // This should fix it for good!
3129          f.Puts("$(SYMBOLS): | objdir\n");
3130          f.Puts("$(OBJECTS): | objdir\n");
3131
3132          // This alone was breaking the tarball, object directory does not get created first (order-only rules happen last it seems!)
3133          f.Printf("$(TARGET): $(SOURCES)%s $(RESOURCES) $(SYMBOLS) $(OBJECTS) | objdir%s\n",
3134                rcSourcesParts ? " $(RCSOURCES)" : "", sameObjTargetDirs ? "" : " targetdir");
3135
3136          f.Printf("\t@$(call rmq,$(OBJ)linkobjects.lst)\n");
3137          f.Printf("\t@$(call touch,$(OBJ)linkobjects.lst)\n");
3138          OutputLinkObjectActions(f, "_OBJECTS", objectsParts);
3139          if(rcSourcesParts)
3140          {
3141             f.Puts("ifdef WINDOWS_TARGET\n");
3142             OutputLinkObjectActions(f, "RCOBJECTS", rcSourcesParts);
3143             f.Puts("endif\n");
3144          }
3145          if(numCObjects)
3146          {
3147             f.Printf("\t@$(call echo,$(OBJ)$(MODULE).main$(O)) >> $(OBJ)linkobjects.lst\n");
3148             OutputLinkObjectActions(f, "ECOBJECTS", eCsourcesParts);
3149          }
3150
3151          f.Puts("ifndef STATIC_LIBRARY_TARGET\n");
3152
3153          f.Printf("\t$(%s) $(OFLAGS) @$(OBJ)linkobjects.lst $(LIBS) %s-o $(TARGET) $(INSTALLNAME)\n", containsCXX ? "CXX" : "CC", containsCXX ? "-lstdc++ " : "");
3154          if(!GetDebug(config))
3155          {
3156             f.Puts("ifndef NOSTRIP\n");
3157             f.Puts("\t$(STRIP) $(STRIPOPT) $(TARGET)\n");
3158             f.Puts("endif\n");
3159
3160             if(GetCompress(config))
3161             {
3162                f.Printf("ifndef %s\n", PlatformToMakefileTargetVariable(win32));
3163                f.Puts("ifdef EXECUTABLE_TARGET\n");
3164                   f.Puts("\t$(UPX) $(UPXFLAGS) $(TARGET)\n");
3165                f.Puts("endif\n");
3166                f.Puts("else\n");
3167                   f.Puts("\t$(UPX) $(UPXFLAGS) $(TARGET)\n");
3168                f.Puts("endif\n");
3169             }
3170          }
3171          if(resNode.files && resNode.files.count && !noResources)
3172             resNode.GenMakefileAddResources(f, resNode.path, config);
3173          f.Puts("else\n");
3174          f.Puts("\t$(AR) rcs $(TARGET) @$(OBJ)linkobjects.lst $(LIBS)\n");
3175          f.Puts("endif\n");
3176          f.Puts("ifdef SHARED_LIBRARY_TARGET\n");
3177          f.Puts("ifdef LINUX_TARGET\n");
3178          f.Puts("ifdef LINUX_HOST\n");
3179          // TODO?: support symlinks for longer version numbers
3180          f.Puts("\t$(if $(basename $(VER)),ln -sf $(LP)$(MODULE)$(SO)$(VER) $(OBJ)$(LP)$(MODULE)$(SO)$(basename $(VER)),)\n");
3181          f.Puts("\t$(if $(VER),ln -sf $(LP)$(MODULE)$(SO)$(VER) $(OBJ)$(LP)$(MODULE)$(SO),)\n");
3182          f.Puts("endif\n");
3183          f.Puts("endif\n");
3184          f.Puts("endif\n");
3185
3186          //f.Puts("# POST-BUILD COMMANDS\n");
3187          if(options && options.postbuildCommands)
3188          {
3189             for(s : options.postbuildCommands)
3190                if(s && s[0]) f.Printf("\t%s\n", s);
3191          }
3192          if(config && config.options && config.options.postbuildCommands)
3193          {
3194             for(s : config.options.postbuildCommands)
3195                if(s && s[0]) f.Printf("\t%s\n", s);
3196          }
3197          if(platforms || (config && config.platforms))
3198          {
3199             ifCount = 0;
3200             //f.Puts("# TARGET_PLATFORM-SPECIFIC POST-BUILD COMMANDS\n");
3201             for(platform = (Platform)1; platform < Platform::enumSize; platform++)
3202             {
3203                PlatformOptions projectPOs, configPOs;
3204                MatchProjectAndConfigPlatformOptions(config, platform, &projectPOs, &configPOs);
3205
3206                if((projectPOs && projectPOs.options.postbuildCommands && projectPOs.options.postbuildCommands.count) ||
3207                      (configPOs && configPOs.options.postbuildCommands && configPOs.options.postbuildCommands.count))
3208                {
3209                   if(ifCount)
3210                      f.Puts("else\n");
3211                   ifCount++;
3212                   f.Printf("ifdef %s\n", PlatformToMakefileTargetVariable(platform));
3213
3214                   if(projectPOs && projectPOs.options.postbuildCommands && projectPOs.options.postbuildCommands.count)
3215                   {
3216                      for(s : projectPOs.options.postbuildCommands)
3217                         if(s && s[0]) f.Printf("\t%s\n", s);
3218                   }
3219                   if(configPOs && configPOs.options.postbuildCommands && configPOs.options.postbuildCommands.count)
3220                   {
3221                      for(s : configPOs.options.postbuildCommands)
3222                         if(s && s[0]) f.Printf("\t%s\n", s);
3223                   }
3224                }
3225             }
3226             if(ifCount)
3227             {
3228                int c;
3229                for(c = 0; c < ifCount; c++)
3230                   f.Puts("endif\n");
3231             }
3232          }
3233          f.Puts("\n");
3234
3235          f.Puts("# SYMBOL RULES\n");
3236          f.Puts("\n");
3237
3238          topNode.GenMakefilePrintSymbolRules(f, this, config, nodeCFlagsMapping, nodeECFlagsMapping);
3239
3240          f.Puts("# C OBJECT RULES\n");
3241          f.Puts("\n");
3242
3243          topNode.GenMakefilePrintCObjectRules(f, this, config, nodeCFlagsMapping, nodeECFlagsMapping);
3244
3245          f.Puts("# OBJECT RULES\n");
3246          f.Puts("\n");
3247          // todo call this still but only generate rules whith specific options
3248          // see we-have-file-specific-options in ProjectNode.ec
3249          topNode.GenMakefilePrintObjectRules(f, this, namesInfo, config, nodeCFlagsMapping, nodeECFlagsMapping);
3250
3251          if(numCObjects)
3252             GenMakefilePrintMainObjectRule(f, config);
3253
3254          f.Printf("cleantarget: objdir%s\n", sameObjTargetDirs ? "" : " targetdir");
3255          f.Puts("\t$(call rmq,$(TARGET))\n");
3256          f.Puts("ifdef SHARED_LIBRARY_TARGET\n");
3257          f.Puts("ifdef LINUX_TARGET\n");
3258          f.Puts("ifdef LINUX_HOST\n");
3259          // TODO?: support symlinks for longer version numbers
3260          f.Puts("\t$(call rmq,$(OBJ)$(LP)$(MODULE)$(SO)$(basename $(VER)))\n");
3261          f.Puts("\t$(call rmq,$(OBJ)$(LP)$(MODULE)$(SO))\n");
3262          f.Puts("endif\n");
3263          f.Puts("endif\n");
3264          f.Puts("endif\n");
3265          f.Puts("\n");
3266
3267          f.Puts("clean: cleantarget\n");
3268          f.Printf("\t$(call rmq,$(OBJ)linkobjects.lst)\n");
3269          OutputCleanActions(f, "_OBJECTS", objectsParts);
3270          if(rcSourcesParts)
3271          {
3272             f.Puts("ifdef WINDOWS_TARGET\n");
3273             OutputCleanActions(f, "RCOBJECTS", rcSourcesParts);
3274             f.Puts("endif\n");
3275          }
3276          if(numCObjects)
3277          {
3278             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)");
3279             OutputCleanActions(f, "ECOBJECTS", eCsourcesParts);
3280             OutputCleanActions(f, "COBJECTS", eCsourcesParts);
3281             OutputCleanActions(f, "BOWLS", eCsourcesParts);
3282             OutputCleanActions(f, "IMPORTS", eCsourcesParts);
3283             OutputCleanActions(f, "SYMBOLS", eCsourcesParts);
3284          }
3285          f.Puts("\n");
3286
3287          f.Puts("realclean: cleantarget\n");
3288          f.Puts("\t$(call rmrq,$(OBJ))\n");
3289          if(!sameObjTargetDirs)
3290             f.Printf("\t$(call rmdirq,%s)\n", targetDirExpNoSpaces);
3291          f.Puts("\n");
3292
3293          f.Puts("distclean: cleantarget\n");
3294          if(!sameObjTargetDirs)
3295             f.Printf("\t$(call rmdirq,%s)\n", targetDirExpNoSpaces);
3296          f.Puts("\t$(call rmrq,obj/)\n");
3297
3298          delete f;
3299
3300          listItems.Free();
3301          delete listItems;
3302          varStringLenDiffs.Free();
3303          delete varStringLenDiffs;
3304          namesInfo.Free();
3305          delete namesInfo;
3306
3307          delete cflagsVariations;
3308          delete nodeCFlagsMapping;
3309          delete ecflagsVariations;
3310          delete nodeECFlagsMapping;
3311
3312          result = true;
3313       }
3314
3315       // ChangeWorkingDir(oldDirectory);
3316       // delete pathBackup;
3317
3318       if(config)
3319          config.makingModified = false;
3320       return result;
3321    }
3322
3323    void GenMakefilePrintMainObjectRule(File f, ProjectConfig config)
3324    {
3325       char extension[MAX_EXTENSION] = "c";
3326       char modulePath[MAX_LOCATION];
3327       char fixedModuleName[MAX_FILENAME];
3328       DualPipe dep;
3329       char command[2048];
3330       char objDirNoSpaces[MAX_LOCATION];
3331       String objDirExp = GetObjDirExpression(config);
3332
3333       ReplaceSpaces(objDirNoSpaces, objDirExp);
3334       ReplaceSpaces(fixedModuleName, moduleName);
3335       
3336       //sprintf(fixedModuleName, "%s.main", fixedPrjName);
3337       //strcat(fixedModuleName, ".main");
3338
3339 #if 0       // TODO: Fix nospaces stuff
3340       // *** Dependency command ***
3341       sprintf(command, "gcc -MT $(OBJ)%s$(O) -MM $(OBJ)%s.c", fixedModuleName, fixedModuleName);
3342
3343       // System Includes (from global settings)
3344       for(item : compiler.dirs[Includes])
3345       {
3346          strcat(command, " -isystem ");
3347          if(strchr(item.name, ' '))
3348          {
3349             strcat(command, "\"");
3350             strcat(command, item);
3351             strcat(command, "\"");
3352          }
3353          else
3354             strcat(command, item);
3355       }
3356
3357       for(item = includeDirs.first; item; item = item.next)
3358       {
3359          strcat(command, " -I");
3360          if(strchr(item.name, ' '))
3361          {
3362             strcat(command, "\"");
3363             strcat(command, item.name);
3364             strcat(command, "\"");
3365          }
3366          else
3367             strcat(command, item.name);
3368       }
3369       for(item = preprocessorDefs.first; item; item = item.next)
3370       {
3371          strcat(command, " -D");
3372          strcat(command, item.name);
3373       }
3374
3375       // Execute it
3376       if((dep = DualPipeOpen(PipeOpenMode { output = 1, error = 1, input = 2 }, command)))
3377       {
3378          char line[1024];
3379          bool result = true;
3380          bool firstLine = true;
3381
3382          // To do some time: auto save external dependencies?
3383          while(!dep.Eof())
3384          {
3385             if(dep.GetLine(line, sizeof(line)-1))
3386             {
3387                if(firstLine)
3388                {
3389                   char * colon = strstr(line, ":");
3390                   if(strstr(line, "No such file") || strstr(line, ",") || (colon && strstr(colon+1, ":")))
3391                   {
3392                      result = false;
3393                      break;
3394                   }
3395                   firstLine = false;
3396                }
3397                f.Puts(line);
3398                f.Puts("\n");
3399             }
3400             if(!result) break;
3401          }
3402          delete dep;
3403
3404          // If we failed to generate dependencies...
3405          if(!result)
3406          {
3407 #endif
3408             f.Puts("$(OBJ)$(MODULE).main$(O): $(OBJ)$(MODULE).main.c\n");
3409             f.Printf("\t$(CC) $(CFLAGS) $(PRJ_CFLAGS) $(FVISIBILITY) -c $(OBJ)$(MODULE).main.%s -o $@\n", extension);
3410             f.Puts("\n");
3411 #if 0
3412          }
3413       }
3414 #endif
3415    }
3416
3417    void GenMakePrintCustomFlags(File f, String variableName, bool printNonCustom, Map<String, int> cflagsVariations)
3418    {
3419       int c;
3420       for(c = printNonCustom ? 0 : 1; c <= cflagsVariations.count; c++)
3421       {
3422          for(v : cflagsVariations)
3423          {
3424             if(v == c)
3425             {
3426                if(v == 1)
3427                   f.Printf("%s +=", variableName);
3428                else
3429                   f.Printf("CUSTOM%d_%s =", v-1, variableName);
3430                f.Puts(&v ? &v : "");
3431                f.Puts("\n");
3432                f.Puts("\n");
3433                break;
3434             }
3435          }
3436       }
3437       f.Puts("\n");
3438    }
3439
3440    void MatchProjectAndConfigPlatformOptions(ProjectConfig config, Platform platform,
3441          PlatformOptions * projectPlatformOptions, PlatformOptions * configPlatformOptions)
3442    {
3443       *projectPlatformOptions = null;
3444       *configPlatformOptions = null;
3445       if(platforms)
3446       {
3447          for(p : platforms)
3448          {
3449             if(!strcmpi(p.name, platform))
3450             {
3451                *projectPlatformOptions = p;
3452                break;
3453             }
3454          }
3455       }
3456       if(config && config.platforms)
3457       {
3458          for(p : config.platforms)
3459          {
3460             if(!strcmpi(p.name, platform))
3461             {
3462                *configPlatformOptions = p;
3463                break;
3464             }
3465          }
3466       }
3467    }
3468 }
3469
3470 Project LegacyBinaryLoadProject(File f, char * filePath)
3471 {
3472    Project project = null;
3473    char signature[sizeof(epjSignature)];
3474
3475    f.Read(signature, sizeof(signature), 1);
3476    if(!strncmp(signature, (char *)epjSignature, sizeof(epjSignature)))
3477    {
3478       char topNodePath[MAX_LOCATION];
3479       /*ProjectConfig newConfig
3480       {
3481          name = CopyString("Default");
3482          makingModified = true;
3483          compilingModified = true;
3484          linkingModified = true;
3485          options = { };
3486       };*/
3487
3488       project = Project { options = { } };
3489       LegacyBinaryLoadNode(project.topNode, f);
3490       delete project.topNode.path;
3491       GetWorkingDir(topNodePath, sizeof(topNodePath)-1);
3492       MakeSlashPath(topNodePath);
3493
3494       PathCatSlash(topNodePath, filePath);
3495       project.filePath = topNodePath;
3496       
3497       /* THIS IS ALREADY DONE BY filePath property
3498       StripLastDirectory(topNodePath, topNodePath);
3499       project.topNode.path = CopyString(topNodePath);
3500       */
3501       // Shouldn't this be done BEFORE the StripLastDirectory? project.filePath = topNodePath;
3502       
3503       // newConfig.options.defaultNameSpace = "";
3504       /*newConfig.objDir.dir = "obj";
3505       newConfig.targetDir.dir = "";*/
3506
3507       //project.configurations = { [ newConfig ] };
3508       //project.config = newConfig;
3509
3510       // Project Settings
3511       if(!f.Eof())
3512       {
3513          int temp;
3514          int len,c, count;
3515          String targetFileName, targetDirectory, objectsDirectory;
3516
3517          // { executable = 0, sharedLibrary = 1, staticLibrary = 2 };
3518          f.Read(&temp, sizeof(int),1);
3519          switch(temp)
3520          {
3521             case 0: project.options.targetType = executable; break;
3522             case 1: project.options.targetType = sharedLibrary; break;
3523             case 2: project.options.targetType = staticLibrary; break;
3524          }
3525
3526          f.Read(&len, sizeof(int),1);
3527          targetFileName = new char[len+1];
3528          f.Read(targetFileName, sizeof(char), len+1);
3529          project.options.targetFileName = targetFileName;
3530          delete targetFileName;
3531
3532          f.Read(&len, sizeof(int),1);
3533          targetDirectory = new char[len+1];
3534          f.Read(targetDirectory, sizeof(char), len+1);
3535          project.options.targetDirectory = targetDirectory;
3536          delete targetDirectory;
3537
3538          f.Read(&len, sizeof(int),1);
3539          objectsDirectory = new byte[len+1];
3540          f.Read(objectsDirectory, sizeof(char), len+1);
3541          project.options.objectsDirectory = objectsDirectory;
3542          delete objectsDirectory;
3543
3544          f.Read(&temp, sizeof(int),1);
3545          project./*config.*/options.debug = temp ? true : false;
3546          f.Read(&temp, sizeof(int),1);         
3547          project./*config.*/options.optimization = temp ? speed : none;
3548          f.Read(&temp, sizeof(int),1);
3549          project./*config.*/options.profile = temp ? true : false;
3550          f.Read(&temp, sizeof(int),1);
3551          project.options.warnings = temp ? all : unset;
3552
3553          f.Read(&count, sizeof(int),1);
3554          if(count)
3555          {
3556             project.options.includeDirs = { };
3557             for(c = 0; c < count; c++)
3558             {
3559                char * name;
3560                f.Read(&len, sizeof(int),1);
3561                name = new char[len+1];
3562                f.Read(name, sizeof(char), len+1);
3563                project.options.includeDirs.Add(name);
3564             }
3565          }
3566
3567          f.Read(&count, sizeof(int),1);
3568          if(count)
3569          {
3570             project.options.libraryDirs = { };
3571             for(c = 0; c < count; c++)
3572             {
3573                char * name;            
3574                f.Read(&len, sizeof(int),1);
3575                name = new char[len+1];
3576                f.Read(name, sizeof(char), len+1);
3577                project.options.libraryDirs.Add(name);
3578             }
3579          }
3580
3581          f.Read(&count, sizeof(int),1);
3582          if(count)
3583          {
3584             project.options.libraries = { };
3585             for(c = 0; c < count; c++)
3586             {
3587                char * name;
3588                f.Read(&len, sizeof(int),1);
3589                name = new char[len+1];
3590                f.Read(name, sizeof(char), len+1);
3591                project.options.libraries.Add(name);
3592             }
3593          }
3594
3595          f.Read(&count, sizeof(int),1);
3596          if(count)
3597          {
3598             project.options.preprocessorDefinitions = { };
3599             for(c = 0; c < count; c++)
3600             {
3601                char * name;
3602                f.Read(&len, sizeof(int),1);
3603                name = new char[len+1];
3604                f.Read(name, sizeof(char), len+1);
3605                project.options.preprocessorDefinitions.Add(name);
3606             }
3607          }
3608
3609          f.Read(&temp, sizeof(int),1);
3610          project.options.console = temp ? true : false;
3611       }
3612
3613       for(node : project.topNode.files)
3614       {
3615          if(node.type == resources)
3616          {
3617             project.resNode = node;
3618             break;
3619          }
3620       }
3621    }
3622    else
3623       f.Seek(0, start);
3624    return project;
3625 }
3626
3627 void ProjectConfig::LegacyProjectConfigLoad(File f)
3628 {  
3629    delete options;
3630    options = { };
3631    while(!f.Eof())
3632    {
3633       char buffer[65536];
3634       char section[128];
3635       char subSection[128];
3636       char * equal;
3637       int len;
3638       uint pos;
3639       
3640       pos = f.Tell();
3641       f.GetLine(buffer, 65536 - 1);
3642       TrimLSpaces(buffer, buffer);
3643       TrimRSpaces(buffer, buffer);
3644       if(strlen(buffer))
3645       {
3646          if(buffer[0] == '-')
3647          {
3648             equal = &buffer[0];
3649             equal[0] = ' ';
3650             TrimLSpaces(equal, equal);
3651             if(!strcmpi(subSection, "LibraryDirs"))
3652             {
3653                if(!options.libraryDirs)
3654                   options.libraryDirs = { [ CopyString(equal) ] };
3655                else
3656                   options.libraryDirs.Add(CopyString(equal));
3657             }
3658             else if(!strcmpi(subSection, "IncludeDirs"))
3659             {
3660                if(!options.includeDirs)
3661                   options.includeDirs = { [ CopyString(equal) ] };
3662                else
3663                   options.includeDirs.Add(CopyString(equal));
3664             }
3665          }
3666          else if(buffer[0] == '+')
3667          {
3668             if(name)
3669             {
3670                f.Seek(pos, start);
3671                break;
3672             }
3673             else
3674             {
3675                equal = &buffer[0];
3676                equal[0] = ' ';
3677                TrimLSpaces(equal, equal);
3678                delete name; name = CopyString(equal); // property::name = equal;
3679             }
3680          }
3681          else if(!strcmpi(buffer, "Compiler Options"))
3682             strcpy(section, buffer);
3683          else if(!strcmpi(buffer, "IncludeDirs"))
3684             strcpy(subSection, buffer);
3685          else if(!strcmpi(buffer, "Linker Options"))
3686             strcpy(section, buffer);
3687          else if(!strcmpi(buffer, "LibraryDirs"))
3688             strcpy(subSection, buffer);
3689          else if(!strcmpi(buffer, "Files") || !strcmpi(buffer, "Resources"))
3690          {
3691             f.Seek(pos, start);
3692             break;
3693          }
3694          else
3695          {
3696             equal = strstr(buffer, "=");
3697             if(equal)
3698             {
3699                equal[0] = '\0';
3700                TrimRSpaces(buffer, buffer);
3701                equal++;
3702                TrimLSpaces(equal, equal);
3703                if(!strcmpi(buffer, "Target Name"))
3704                   options.targetFileName = /*CopyString(*/equal/*)*/;
3705                else if(!strcmpi(buffer, "Target Type"))
3706                {
3707                   if(!strcmpi(equal, "Executable"))
3708                      options.targetType = executable;
3709                   else if(!strcmpi(equal, "Shared"))
3710                      options.targetType = sharedLibrary;
3711                   else if(!strcmpi(equal, "Static"))
3712                      options.targetType = staticLibrary;
3713                   else
3714                      options.targetType = executable;
3715                }
3716                else if(!strcmpi(buffer, "Target Directory"))
3717                   options.targetDirectory = /*CopyString(*/equal/*)*/;
3718                else if(!strcmpi(buffer, "Console"))
3719                   options.console = ParseTrueFalseValue(equal);
3720                else if(!strcmpi(buffer, "Libraries"))
3721                {
3722                   if(!options.libraries) options.libraries = { };
3723                   ParseArrayValue(options.libraries, equal);
3724                }
3725                else if(!strcmpi(buffer, "Intermediate Directory"))
3726                   options.objectsDirectory = /*CopyString(*/equal/*)*/; //objDir.expression = equal;
3727                else if(!strcmpi(buffer, "Debug"))
3728                   options.debug = ParseTrueFalseValue(equal);
3729                else if(!strcmpi(buffer, "Optimize"))
3730                {
3731                   if(!strcmpi(equal, "None"))
3732                      options.optimization = none;
3733                   else if(!strcmpi(equal, "Speed") || !strcmpi(equal, "True"))
3734                      options.optimization = speed;
3735                   else if(!strcmpi(equal, "Size"))
3736                      options.optimization = size;
3737                   else
3738                      options.optimization = none;
3739                }
3740                else if(!strcmpi(buffer, "Compress"))
3741                   options.compress = ParseTrueFalseValue(equal);
3742                else if(!strcmpi(buffer, "Profile"))
3743                   options.profile = ParseTrueFalseValue(equal);
3744                else if(!strcmpi(buffer, "AllWarnings"))
3745                   options.warnings = ParseTrueFalseValue(equal) ? all : unset;
3746                else if(!strcmpi(buffer, "MemoryGuard"))
3747                   options.memoryGuard = ParseTrueFalseValue(equal);
3748                else if(!strcmpi(buffer, "Default Name Space"))
3749                   options.defaultNameSpace = CopyString(equal);
3750                else if(!strcmpi(buffer, "Strict Name Spaces"))
3751                   options.strictNameSpaces = ParseTrueFalseValue(equal);
3752                else if(!strcmpi(buffer, "Preprocessor Definitions"))
3753                {
3754                   if(!options.preprocessorDefinitions) options.preprocessorDefinitions = { };
3755                   ParseArrayValue(options.preprocessorDefinitions, equal);
3756                }
3757             }
3758          }
3759       }
3760    }
3761    if(!options.targetDirectory && options.objectsDirectory)
3762       options.targetDirectory = /*CopyString(*/options.objectsDirectory/*)*/;
3763    //if(!objDir.dir) objDir.dir = "obj";
3764    //if(!targetDir.dir) targetDir.dir = "";
3765    // if(!targetName) property::targetName = "";   // How can a targetFileName be nothing???
3766    // if(!defaultNameSpace) property::defaultNameSpace = "";
3767    makingModified = true;
3768 }
3769
3770 Project LegacyAsciiLoadProject(File f, char * filePath)
3771 {
3772    Project project = null;
3773    ProjectNode node = null;
3774    int pos;
3775    char parentPath[MAX_LOCATION];
3776    char section[128] = "";
3777    char subSection[128] = "";
3778    ProjectNode parent;
3779    bool configurationsPresent = false;
3780
3781    f.Seek(0, start);
3782    while(!f.Eof())
3783    {
3784       char buffer[65536];
3785       //char version[16];
3786       char * equal;
3787       int len;
3788       pos = f.Tell();
3789       f.GetLine(buffer, 65536 - 1);
3790       TrimLSpaces(buffer, buffer);
3791       TrimRSpaces(buffer, buffer);
3792       if(strlen(buffer))
3793       {
3794          if(buffer[0] == '-' || buffer[0] == '=')
3795          {
3796             bool simple = buffer[0] == '-';
3797             equal = &buffer[0];
3798             equal[0] = ' ';
3799             TrimLSpaces(equal, equal);
3800             if(!strcmpi(section, "Target") && !strcmpi(subSection, "LibraryDirs"))
3801             {
3802                if(!project.config.options.libraryDirs)
3803                   project.config.options.libraryDirs = { [ CopyString(equal) ] };
3804                else
3805                   project.config.options.libraryDirs.Add(CopyString(equal));
3806             }
3807             else if(!strcmpi(section, "Target") && !strcmpi(subSection, "IncludeDirs"))
3808             {
3809                if(!project.config.options.includeDirs)
3810                   project.config.options.includeDirs = { [ CopyString(equal) ] };
3811                else
3812                   project.config.options.includeDirs.Add(CopyString(equal));
3813             }
3814             else if(!strcmpi(section, "Target") && (!strcmpi(subSection, "Files") || !strcmpi(subSection, "Resources")))
3815             {
3816                len = strlen(equal);
3817                if(len)
3818                {
3819                   char temp[MAX_LOCATION];
3820                   ProjectNode child { };
3821                   // We don't need to do this anymore, fileName is just a property that sets name & path
3822                   // child.fileName = CopyString(equal);
3823                   if(simple)
3824                   {
3825                      child.name = CopyString(equal);
3826                      child.path = CopyString(parentPath);
3827                   }
3828                   else
3829                   {
3830                      GetLastDirectory(equal, temp);
3831                      child.name = CopyString(temp);
3832                      StripLastDirectory(equal, temp);
3833                      child.path = CopyString(temp);
3834                   }
3835                   child.nodeType = file;
3836                   child.parent = parent;
3837                   child.indent = parent.indent + 1;
3838                   child.type = file;
3839                   child.icon = NodeIcons::SelectFileIcon(child.name);
3840                   parent.files.Add(child);
3841                   node = child;
3842                   //child = null;
3843                }
3844                else
3845                {
3846                   StripLastDirectory(parentPath, parentPath);
3847                   parent = parent.parent;
3848                }
3849             }
3850          }
3851          else if(buffer[0] == '+')
3852          {
3853             equal = &buffer[0];
3854             equal[0] = ' ';
3855             TrimLSpaces(equal, equal);
3856             if(!strcmpi(section, "Target") && (!strcmpi(subSection, "Files") || !strcmpi(subSection, "Resources")))
3857             {
3858                char temp[MAX_LOCATION];
3859                ProjectNode child { };
3860                // NEW: Folders now have a path set like files
3861                child.name = CopyString(equal);
3862                strcpy(temp, parentPath);
3863                PathCatSlash(temp, child.name);
3864                child.path = CopyString(temp);
3865
3866                child.parent = parent;
3867                child.indent = parent.indent + 1;
3868                child.type = folder;
3869                child.nodeType = folder;
3870                child.files = { };
3871                child.icon = folder;
3872                PathCatSlash(parentPath, child.name);
3873                parent.files.Add(child);
3874                parent = child;
3875                node = child;
3876                //child = null;
3877             }
3878             else if(!strcmpi(section, "Configurations"))
3879             {
3880                ProjectConfig newConfig
3881                {
3882                   makingModified = true;
3883                   options = { };
3884                };
3885                f.Seek(pos, start);
3886                LegacyProjectConfigLoad(newConfig, f);
3887                project.configurations.Add(newConfig);
3888             }
3889          }
3890          else if(!strcmpi(buffer, "ECERE Project File"));
3891          else if(!strcmpi(buffer, "Version 0a"))
3892             ; //strcpy(version, "0a");
3893          else if(!strcmpi(buffer, "Version 0.1a"))
3894             ; //strcpy(version, "0.1a");
3895          else if(!strcmpi(buffer, "Configurations"))
3896          {
3897             project.configurations.Free();
3898             project.config = null;
3899             strcpy(section, buffer);
3900             configurationsPresent = true;
3901          }
3902          else if(!strcmpi(buffer, "Target") || !strnicmp(buffer, "Target \"", strlen("Target \"")))
3903          {
3904             ProjectConfig newConfig { name = CopyString("Default"), options = { } };
3905             char topNodePath[MAX_LOCATION];
3906             // newConfig.defaultNameSpace = "";
3907             //newConfig.objDir.dir = "obj";
3908             //newConfig.targetDir.dir = "";
3909             project = Project { /*options = { }*/ };
3910             project.configurations = { [ newConfig ] };
3911             project.config = newConfig;
3912             // if(project.topNode.path) delete project.topNode.path;
3913             GetWorkingDir(topNodePath, sizeof(topNodePath)-1);
3914             MakeSlashPath(topNodePath);
3915             PathCatSlash(topNodePath, filePath);
3916             project.filePath = topNodePath;
3917             parentPath[0] = '\0';
3918             parent = project.topNode;
3919             node = parent;
3920             strcpy(section, "Target");
3921             equal = &buffer[6];
3922             if(equal[0] == ' ')
3923             {
3924                equal++;
3925                if(equal[0] == '\"')
3926                {
3927                   StripQuotes(equal, equal);
3928                   delete project.moduleName; project.moduleName = CopyString(equal);
3929                }
3930             }
3931          }
3932          else if(!strcmpi(buffer, "Compiler Options"));
3933          else if(!strcmpi(buffer, "IncludeDirs"))
3934             strcpy(subSection, buffer);
3935          else if(!strcmpi(buffer, "Linker Options"));
3936          else if(!strcmpi(buffer, "LibraryDirs"))
3937             strcpy(subSection, buffer);
3938          else if(!strcmpi(buffer, "Files"))
3939          {
3940             strcpy(section, "Target");
3941             strcpy(subSection, buffer);
3942          }
3943          else if(!strcmpi(buffer, "Resources"))
3944          {
3945             ProjectNode child { };
3946             parent.files.Add(child);
3947             child.parent = parent;
3948             child.indent = parent.indent + 1;
3949             child.name = CopyString(buffer);
3950             child.path = CopyString("");
3951             child.type = resources;
3952             child.files = { };
3953             child.icon = archiveFile;
3954             project.resNode = child;
3955             parent = child;
3956             node = child;
3957             strcpy(subSection, buffer);
3958          }
3959          else
3960          {
3961             equal = strstr(buffer, "=");
3962             if(equal)
3963             {
3964                equal[0] = '\0';
3965                TrimRSpaces(buffer, buffer);
3966                equal++;
3967                TrimLSpaces(equal, equal);
3968
3969                if(!strcmpi(section, "Target"))
3970                {
3971                   if(!strcmpi(buffer, "Build Exclusions"))
3972                   {
3973                      if(!strcmpi(section, "Target") && !strcmpi(subSection, "Files"))
3974                      {
3975                         /*if(node && node.type != NodeTypes::project)
3976                            ParseListValue(node.buildExclusions, equal);*/
3977                      }
3978                   }
3979                   else if(!strcmpi(buffer, "Path") && !strcmpi(subSection, "Resources"))
3980                   {
3981                      delete project.resNode.path;
3982                      project.resNode.path = CopyString(equal);
3983                      PathCatSlash(parentPath, equal);
3984                   }
3985
3986                   // Config Settings
3987                   else if(!strcmpi(buffer, "Intermediate Directory"))
3988                      project.config.options.objectsDirectory = /*CopyString(*/equal/*)*/; //objDir.expression = equal;
3989                   else if(!strcmpi(buffer, "Debug"))
3990                      project.config.options.debug = ParseTrueFalseValue(equal);
3991                   else if(!strcmpi(buffer, "Optimize"))
3992                   {
3993                      if(!strcmpi(equal, "None"))
3994                         project.config.options.optimization = none;
3995                      else if(!strcmpi(equal, "Speed") || !strcmpi(equal, "True"))
3996                         project.config.options.optimization = speed;
3997                      else if(!strcmpi(equal, "Size"))
3998                         project.config.options.optimization = size;
3999                      else
4000                         project.config.options.optimization = none;
4001                   }
4002                   else if(!strcmpi(buffer, "Profile"))
4003                      project.config.options.profile = ParseTrueFalseValue(equal);
4004                   else if(!strcmpi(buffer, "MemoryGuard"))
4005                      project.config.options.memoryGuard = ParseTrueFalseValue(equal);
4006                   else
4007                   {
4008                      if(!project.options) project.options = { };
4009
4010                      // Project Wide Settings (All configs)
4011                      if(!strcmpi(buffer, "Target Name"))
4012                         project.options.targetFileName = /*CopyString(*/equal/*)*/;
4013                      else if(!strcmpi(buffer, "Target Type"))
4014                      {
4015                         if(!strcmpi(equal, "Executable"))
4016                            project.options.targetType = executable;
4017                         else if(!strcmpi(equal, "Shared"))
4018                            project.options.targetType = sharedLibrary;
4019                         else if(!strcmpi(equal, "Static"))
4020                            project.options.targetType = staticLibrary;
4021                         else
4022                            project.options.targetType = executable;
4023                      }
4024                      else if(!strcmpi(buffer, "Target Directory"))
4025                         project.options.targetDirectory = /*CopyString(*/equal/*)*/;
4026                      else if(!strcmpi(buffer, "Console"))
4027                         project.options.console = ParseTrueFalseValue(equal);
4028                      else if(!strcmpi(buffer, "Libraries"))
4029                      {
4030                         if(!project.options.libraries) project.options.libraries = { };
4031                         ParseArrayValue(project.options.libraries, equal);
4032                      }
4033                      else if(!strcmpi(buffer, "AllWarnings"))
4034                         project.options.warnings = ParseTrueFalseValue(equal) ? all : unset;
4035                      else if(!strcmpi(buffer, "Preprocessor Definitions"))
4036                      {
4037                         if(!strcmpi(section, "Target") && !strcmpi(subSection, "Files"))
4038                         {
4039                            /*if(node && (node.type == NodeTypes::project || (node.type == file && !node.isInResources) || node.type == folder))
4040                               ParseListValue(node.preprocessorDefs, equal);*/
4041                         }
4042                         else
4043                         {
4044                            if(!project.options.preprocessorDefinitions) project.options.preprocessorDefinitions = { };
4045                            ParseArrayValue(project.options.preprocessorDefinitions, equal);
4046                         }
4047                      }
4048                   }
4049                }
4050             }
4051          }
4052       }
4053    }
4054    parent = null;
4055
4056    SplitPlatformLibraries(project);
4057
4058    if(configurationsPresent)
4059       CombineIdenticalConfigOptions(project);
4060    return project;
4061 }
4062
4063 void SplitPlatformLibraries(Project project)
4064 {
4065    if(project && project.configurations)
4066    {
4067       for(cfg : project.configurations)
4068       {
4069          if(cfg.options.libraries && cfg.options.libraries.count)
4070          {
4071             Iterator<String> it { cfg.options.libraries };
4072             while(it.Next())
4073             {
4074                String l = it.data;
4075                char * platformName = strstr(l, ":");
4076                if(platformName)
4077                {
4078                   PlatformOptions platform = null;
4079                   platformName++;
4080                   if(!cfg.platforms) cfg.platforms = { };
4081                   for(p : cfg.platforms)
4082                   {
4083                      if(!strcmpi(platformName, p.name))
4084                      {
4085                         platform = p;
4086                         break;
4087                      }
4088                   }
4089                   if(!platform)
4090                   {
4091                      platform = { name = CopyString(platformName), options = { libraries = { } } };
4092                      cfg.platforms.Add(platform);
4093                   }
4094                   *(platformName-1) = 0;
4095                   platform.options.libraries.Add(CopyString(l));
4096
4097                   cfg.options.libraries.Delete(it.pointer);
4098                   it.pointer = null;
4099                }
4100             }
4101          }
4102       }      
4103    }
4104 }
4105
4106 void CombineIdenticalConfigOptions(Project project)
4107 {
4108    if(project && project.configurations && project.configurations.count)
4109    {
4110       DataMember member;
4111       ProjectOptions nullOptions { };
4112       ProjectConfig firstConfig = null;
4113       for(cfg : project.configurations)
4114       {
4115          if(cfg.options.targetType != staticLibrary)
4116          {
4117             firstConfig = cfg;
4118             break;
4119          }
4120       }
4121       if(!firstConfig)
4122          firstConfig = project.configurations.firstIterator.data;
4123
4124       for(member = class(ProjectOptions).membersAndProperties.first; member; member = member.next)
4125       {
4126          if(!member.isProperty)
4127          {
4128             Class type = eSystem_FindClass(__thisModule, member.dataTypeString);
4129             if(type)
4130             {
4131                bool same = true;
4132
4133                for(cfg : project.configurations)
4134                {
4135                   if(cfg != firstConfig)
4136                   {
4137                      if(cfg.options.targetType != staticLibrary)
4138                      {
4139                         int result;
4140                         
4141                         if(type.type == noHeadClass || type.type == normalClass)
4142                         {
4143                            result = ((int (*)(void *, void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnCompare])(type, 
4144                               *(void **)((byte *)firstConfig.options + member.offset + member._class.offset),
4145                               *(void **)((byte *)cfg.options         + member.offset + member._class.offset));
4146                         }
4147                         else
4148                         {
4149                            result = ((int (*)(void *, void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnCompare])(type, 
4150                               (byte *)firstConfig.options + member.offset + member._class.offset,
4151                               (byte *)cfg.options         + member.offset + member._class.offset);
4152                         }
4153                         if(result)
4154                         {
4155                            same = false;
4156                            break;
4157                         }
4158                      }
4159                   }                  
4160                }
4161                if(same)
4162                {
4163                   if(type.type == noHeadClass || type.type == normalClass)
4164                   {
4165                      if(!((int (*)(void *, void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnCompare])(type, 
4166                         *(void **)((byte *)firstConfig.options + member.offset + member._class.offset),
4167                         *(void **)((byte *)nullOptions         + member.offset + member._class.offset)))
4168                         continue;
4169                   }
4170                   else
4171                   {
4172                      if(!((int (*)(void *, void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnCompare])(type, 
4173                         (byte *)firstConfig.options + member.offset + member._class.offset,
4174                         (byte *)nullOptions         + member.offset + member._class.offset))
4175                         continue;
4176                   }
4177
4178                   if(!project.options) project.options = { };
4179                   
4180                   /*if(type.type == noHeadClass || type.type == normalClass)
4181                   {
4182                      ((void (*)(void *, void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnCopy])(type, 
4183                         (byte *)project.options + member.offset + member._class.offset,
4184                         *(void **)((byte *)firstConfig.options + member.offset + member._class.offset));
4185                   }
4186                   else
4187                   {
4188                      void * address = (byte *)firstConfig.options + member.offset + member._class.offset;
4189                      // TOFIX: ListBox::SetData / OnCopy mess
4190                      ((void (*)(void *, void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnCopy])(type, 
4191                         (byte *)project.options + member.offset + member._class.offset,
4192                         (type.typeSize > 4) ? address : 
4193                            ((type.typeSize == 4) ? (void *)*(uint32 *)address : 
4194                               ((type.typeSize == 2) ? (void *)*(uint16*)address : 
4195                                  (void *)*(byte *)address )));                              
4196                   }*/
4197                   memcpy(
4198                      (byte *)project.options + member.offset + member._class.offset,
4199                      (byte *)firstConfig.options + member.offset + member._class.offset, type.typeSize);
4200
4201                   for(cfg : project.configurations)
4202                   {
4203                      if(cfg.options.targetType == staticLibrary)
4204                      {
4205                         int result;
4206                         
4207                         if(type.type == noHeadClass || type.type == normalClass)
4208                         {
4209                            result = ((int (*)(void *, void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnCompare])(type, 
4210                               *(void **)((byte *)firstConfig.options + member.offset + member._class.offset),
4211                               *(void **)((byte *)cfg.options         + member.offset + member._class.offset));
4212                         }
4213                         else
4214                         {
4215                            result = ((int (*)(void *, void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnCompare])(type, 
4216                               (byte *)firstConfig.options + member.offset + member._class.offset,
4217                               (byte *)cfg.options         + member.offset + member._class.offset);
4218                         }
4219                         if(result)
4220                            continue;
4221                      }
4222                      if(cfg != firstConfig)
4223                      {
4224                         if(type.type == noHeadClass || type.type == normalClass)
4225                         {
4226                            ((void (*)(void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnFree])(type, 
4227                               *(void **)((byte *)cfg.options + member.offset + member._class.offset));
4228                         }
4229                         else
4230                         {
4231                            ((void (*)(void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnFree])(type, 
4232                               (byte *)cfg.options + member.offset + member._class.offset);
4233                         }
4234                         memset((byte *)cfg.options + member.offset + member._class.offset, 0, type.typeSize);
4235                      }                     
4236                   }
4237                   memset((byte *)firstConfig.options + member.offset + member._class.offset, 0, type.typeSize);
4238                }
4239             }
4240          }
4241       }
4242       delete nullOptions;
4243
4244       // Compare Platform Specific Settings
4245       {
4246          bool same = true;
4247          for(cfg : project.configurations)
4248          {
4249             if(cfg != firstConfig && cfg.options.targetType != staticLibrary && (firstConfig.platforms || cfg.platforms) &&
4250                ((!firstConfig.platforms && cfg.platforms) || firstConfig.platforms.OnCompare(cfg.platforms)))
4251             {
4252                same = false;
4253                break;
4254             }
4255          }
4256          if(same && firstConfig.platforms)
4257          {
4258             for(cfg : project.configurations)
4259             {
4260                if(cfg.options.targetType == staticLibrary && firstConfig.platforms.OnCompare(cfg.platforms))
4261                   continue;
4262                if(cfg != firstConfig)
4263                {
4264                   cfg.platforms.Free();
4265                   delete cfg.platforms;
4266                }
4267             }
4268             project.platforms = firstConfig.platforms;
4269             firstConfig.platforms = null;
4270          }
4271       }
4272
4273       // Static libraries can't contain libraries
4274       for(cfg : project.configurations)
4275       {
4276          if(cfg.options.targetType == staticLibrary)
4277          {
4278             if(!cfg.options.libraries) cfg.options.libraries = { };
4279             cfg.options.libraries.Free();
4280          }
4281       }
4282    }
4283 }
4284
4285 Project LoadProject(char * filePath, char * activeConfigName)
4286 {
4287    Project project = null;
4288    File f = FileOpen(filePath, read);
4289    if(f)
4290    {
4291       project = LegacyBinaryLoadProject(f, filePath);
4292       if(!project)
4293       {
4294          JSONParser parser { f = f };
4295          JSONResult result = parser.GetObject(class(Project), &project);
4296          if(project)
4297          {
4298             char insidePath[MAX_LOCATION];
4299
4300             delete project.topNode.files;
4301             if(!project.files) project.files = { };
4302             project.topNode.files = project.files;
4303             project.resNode = project.topNode.Add(project, "Resources", project.topNode.files.last, resources, archiveFile, false);
4304             delete project.resNode.path;
4305             project.resNode.path = project.resourcesPath;
4306             project.resourcesPath = null;
4307             project.resNode.nodeType = (ProjectNodeType)-1;
4308             delete project.resNode.files;
4309             project.resNode.files = project.resources;
4310             project.files = null;
4311             project.resources = null;
4312             if(!project.configurations) project.configurations = { };
4313
4314             {
4315                char topNodePath[MAX_LOCATION];
4316                GetWorkingDir(topNodePath, sizeof(topNodePath)-1);
4317                MakeSlashPath(topNodePath);
4318                PathCatSlash(topNodePath, filePath);
4319                project.filePath = topNodePath;//filePath;
4320             }
4321
4322             project.topNode.FixupNode(insidePath);
4323          }
4324          delete parser;
4325       }
4326       if(!project)
4327          project = LegacyAsciiLoadProject(f, filePath);
4328
4329       delete f;
4330
4331       if(project)
4332       {
4333          if(!project.options) project.options = { };
4334          if(activeConfigName && activeConfigName[0] && project.configurations)
4335          {
4336             for(cfg : project.configurations)
4337             {
4338                if(!strcmpi(cfg.name, activeConfigName))
4339                {
4340                   project.config = cfg;
4341                   break;
4342                }
4343             }
4344          }
4345          if(!project.config && project.configurations)
4346             project.config = project.configurations.firstIterator.data;
4347
4348          if(!project.resNode)
4349          {
4350             project.resNode = project.topNode.Add(project, "Resources", project.topNode.files.last, resources, archiveFile, false);
4351          }
4352          
4353          if(!project.moduleName)
4354             project.moduleName = CopyString(project.name);
4355          if(project.config && 
4356             (!project.options || !project.options.targetFileName || !project.options.targetFileName[0]) &&
4357             (!project.config.options.targetFileName || !project.config.options.targetFileName[0]))
4358          {
4359             //delete project.config.options.targetFileName;
4360             
4361             project.options.targetFileName = /*CopyString(*/project.moduleName/*)*/;
4362             project.config.options.optimization = none;
4363             project.config.options.debug = true;
4364             //project.config.options.warnings = unset;
4365             project.config.options.memoryGuard = false;
4366             project.config.compilingModified = true;
4367             project.config.linkingModified = true;
4368          }
4369          else if(!project.topNode.name && project.config)
4370          {
4371             project.topNode.name = CopyString(project.config.options.targetFileName);
4372          }
4373
4374          /* // THIS IS NOW AUTOMATED WITH A project CHECK IN ProjectNode
4375          project.topNode.configurations = project.configurations;
4376          project.topNode.platforms = project.platforms;
4377          project.topNode.options = project.options;*/
4378       }
4379    }
4380    return project;
4381 }