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