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