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