diff --git a/.github/workflows/build-vs.yml b/.github/workflows/build-vs.yml index 8628aee3..518ef68b 100644 --- a/.github/workflows/build-vs.yml +++ b/.github/workflows/build-vs.yml @@ -84,6 +84,10 @@ jobs: run: ../openFrameworks/apps/projectGenerator/scripts/vs/test_cmdline.sh + - name: Test existing-project GUI settings and update arguments + shell: pwsh + run: node --test ../openFrameworks/apps/projectGenerator/scripts/test_gui_project_settings.cjs + - name: Build emptyExample and allAddonsExample if: github.event_name == 'pull_request' || github.ref == 'refs/heads/master' shell: bash diff --git a/commandLine/src/defines.h b/commandLine/src/defines.h index 38e25556..f253d10b 100644 --- a/commandLine/src/defines.h +++ b/commandLine/src/defines.h @@ -1,5 +1,5 @@ #define OFPROJECTGENERATOR_MAJOR_VERSION "0" -#define OFPROJECTGENERATOR_MINOR_VERSION "124" +#define OFPROJECTGENERATOR_MINOR_VERSION "125" #define OFPROJECTGENERATOR_PATCH_VERSION "0" #define PG_VERSION (OFPROJECTGENERATOR_MAJOR_VERSION "." OFPROJECTGENERATOR_MINOR_VERSION "." OFPROJECTGENERATOR_PATCH_VERSION) diff --git a/commandLine/src/main.cpp b/commandLine/src/main.cpp index 0acf1678..e43eef20 100644 --- a/commandLine/src/main.cpp +++ b/commandLine/src/main.cpp @@ -11,6 +11,7 @@ #include #include #include +#include enum optionIndex { UNKNOWN, HELP, @@ -68,7 +69,7 @@ constexpr option::Descriptor usage[] = { { CLEANNAME_DISABLE, 0, "n", "cleanname", option::Arg::Optional, " --cleanname, -n \tcleanname" }, - { DEFINES, 0, "D", "defines", option::Arg::Optional, " --defines, -D \tpreprocessor defines list (such as OF_USE_ANGLE=1,MY_FLAG)" }, + { DEFINES, 0, "D", "defines", option::Arg::Optional, " --defines, -D \tpreprocessor defines list (such as OF_USE_ANGLE=1,MY_FLAG); --defines= clears saved project defines" }, { POSTBUILD, 0, "P", "postbuild", option::Arg::Optional, " --postbuild, -P \tscript to run after the project compiles (Xcode run script / VS post-build event)" }, { MSYS2ENV, 0, "k", "msys2env", option::Arg::Optional, " --msys2env, -k \tMSYS2 environment for the msys2 / VSCode targets: ucrt64 (default) | mingw64 | clang64 | clangarm64" }, { EMSCRIPTEN_WASM, 0, "W", "emscripten-wasm", option::Arg::Optional, " --emscripten-wasm, -W \temscripten WebAssembly: 32 (default) | 64 (wasm64, MEMORY64), written to config.make PROJECT_EMSCRIPTEN_WASM" }, @@ -107,6 +108,7 @@ bool bFrameworksPassedIn = false; vector systemLibs; bool bSystemLibsPassedIn = false; vector defines; +bool bDefinesPassedIn = false; string postBuildScript; string emscriptenWasm; // empty keeps the project's config.make value string appVersion; // empty keeps the project's value @@ -288,8 +290,9 @@ void updateProject(const fs::path & path, const string & target, bool bConsiderP project->setEmscriptenWasm(emscriptenWasm); project->setAppVersion(appVersion, appBuild); project->setAppBundleId(appBundleId); + project->setProjectDefinesPassed(bDefinesPassedIn); project->setSystemFrameworks(frameworks, bFrameworksPassedIn, systemLibs, bSystemLibsPassedIn); - project->create(path, templateName); + if (!project->create(path, templateName)) throw std::runtime_error("could not update project: " + path.string()); if (bConsiderParameterAddons && bAddonsPassedIn) { for (auto & addon : addons) { @@ -313,7 +316,7 @@ void updateProject(const fs::path & path, const string & target, bool bConsiderP for (auto & srcPath : srcPaths) { project->addSrcRecursively(srcPath); } - project->save(); + if (!project->save()) throw std::runtime_error("could not save project: " + path.string()); } } @@ -728,8 +731,13 @@ int pgMain(int argc, char ** argv) { } } - if (options[DEFINES].count() > 0 && options[DEFINES].arg != NULL) { - defines = ofSplitString(options[DEFINES].arg, ",", true, true); + if (options[DEFINES].count() > 0) { + if (options[DEFINES].arg != NULL) { + bDefinesPassedIn = true; + defines = ofSplitString(options[DEFINES].arg, ",", true, true); + } else { + ofLogWarning() << "missing defines value; keeping the project's defines (use --defines= to clear them)"; + } } if (options[EMSCRIPTEN_WASM].count() > 0 && options[EMSCRIPTEN_WASM].arg != NULL) { @@ -938,8 +946,9 @@ int pgMain(int argc, char ** argv) { project->setEmscriptenWasm(emscriptenWasm); project->setAppVersion(appVersion, appBuild); project->setAppBundleId(appBundleId); + project->setProjectDefinesPassed(bDefinesPassedIn); project->setSystemFrameworks(frameworks, bFrameworksPassedIn, systemLibs, bSystemLibsPassedIn); - project->create(projectPath, templateName); + if (!project->create(projectPath, templateName)) return EXIT_FAILURE; if(bAddonsPassedIn){ for (auto & addon : addons) { project->addAddon(addon); @@ -960,7 +969,7 @@ int pgMain(int argc, char ** argv) { for (auto & s : srcPaths) { project->addSrcRecursively(s); } - project->save(); + if (!project->save()) return EXIT_FAILURE; } ofLogNotice() << "project created! "; nProjectsCreated += 1; diff --git a/commandLine/src/projects/XcodeSettings.h b/commandLine/src/projects/XcodeSettings.h new file mode 100644 index 00000000..aed0419c --- /dev/null +++ b/commandLine/src/projects/XcodeSettings.h @@ -0,0 +1,492 @@ +#pragma once + +#include +#include "pugixml.hpp" +#include +#include +#include +#include +#include +#include +#ifdef __APPLE__ +#include +#endif + +namespace xcodeSettings { +using nlohmann::json; + +inline std::string trim(const std::string & text) { + auto first = text.find_first_not_of(" \t\r\n"); + return first == std::string::npos ? "" : text.substr(first, text.find_last_not_of(" \t\r\n") - first + 1); +} + +// Three-way merge. A deletion is an edit too; arrays are kept as a whole, not concatenated. +inline json merge(const json & base, const json & user, const json & next) { + if (user == base) return next; + if (!user.is_object() || !next.is_object()) return user; + json result = next; + if (base.is_object()) { + for (auto it = base.begin(); it != base.end(); ++it) if (!user.contains(it.key())) result.erase(it.key()); + } + for (auto it = user.begin(); it != user.end(); ++it) { + if (!base.is_object() || !base.contains(it.key())) { + result[it.key()] = next.contains(it.key()) && it->is_object() + ? merge(json::object(), *it, next[it.key()]) : *it; + } else if (*it != base[it.key()]) { + result[it.key()] = next.contains(it.key()) ? merge(base[it.key()], *it, next[it.key()]) : *it; + } + } + return result; +} + +// Retain plist types, especially booleans, arrays, dates and binary data. +inline json readPlistNode(pugi::xml_node node) { + std::string type = node.name(); + json value; + if (type == "dict") { + value = json::object(); + for (auto key = node.first_child(); key; key = key.next_sibling()) { + if (key.type() != pugi::node_element) continue; + if (std::string(key.name()) != "key") throw std::runtime_error("expected a plist dictionary key"); + auto entry = key.next_sibling(); + while (entry && entry.type() != pugi::node_element) entry = entry.next_sibling(); + if (!entry || value.contains(key.child_value())) throw std::runtime_error("missing or duplicate plist value"); + value[key.child_value()] = readPlistNode(entry); + key = entry; + } + } else if (type == "array") { + value = json::array(); + for (auto child : node.children()) if (child.type() == pugi::node_element) value.push_back(readPlistNode(child)); + } else if (type == "true" || type == "false" || type == "string" || type == "integer" + || type == "real" || type == "data" || type == "date") { + value = node.child_value(); + } else throw std::runtime_error("unsupported plist value: " + type); + return { { "type", type }, { "value", value } }; +} + +inline pugi::xml_node plistRoot(pugi::xml_document & doc) { + for (auto node : doc.child("plist").children()) if (node.type() == pugi::node_element) return node; + return {}; +} + +inline json readPlist(const std::string & text) { + pugi::xml_document doc; + if (doc.load_buffer(text.data(), text.size()) && plistRoot(doc)) return readPlistNode(plistRoot(doc)); +#ifdef __APPLE__ + // Real Xcode edits use OpenStep project files; user Info.plists may be binary. + auto data = CFDataCreate(nullptr, reinterpret_cast(text.data()), text.size()); + auto plist = CFPropertyListCreateWithData(nullptr, data, kCFPropertyListImmutable, nullptr, nullptr); + CFRelease(data); + if (plist) { + auto xml = CFPropertyListCreateData(nullptr, plist, kCFPropertyListXMLFormat_v1_0, 0, nullptr); + CFRelease(plist); + if (xml) { + bool parsed = doc.load_buffer(CFDataGetBytePtr(xml), CFDataGetLength(xml)); + CFRelease(xml); + if (parsed && plistRoot(doc)) return readPlistNode(plistRoot(doc)); + } + } +#endif + throw std::runtime_error("cannot read property list (OpenStep/binary formats require macOS)"); +} + +inline json plainPlist(const json & node) { + const auto type = node.at("type").get(); + const auto & value = node.at("value"); + if (type == "dict" || type == "array") { + json result = type == "dict" ? json::object() : json::array(); + for (auto it = value.begin(); it != value.end(); ++it) { + if (type == "dict") result[it.key()] = plainPlist(*it); + else result.push_back(plainPlist(*it)); + } + return result; + } + if (type == "true" || type == "false") return type == "true"; + return value; +} + +inline json readProject(const std::string & text) { + json result = json::parse(text, nullptr, false); + if (result.is_discarded()) result = plainPlist(readPlist(text)); + if (!result.is_object() || !result.contains("objects") || !result["objects"].is_object() + || !result.contains("rootObject") || !result["rootObject"].is_string() + || !result["objects"].contains(result["rootObject"].get())) { + throw std::runtime_error("invalid Xcode project"); + } + return result; +} + +inline void writePlistNode(pugi::xml_node parent, const json & node) { + const auto type = node.at("type").get(); + const auto & value = node.at("value"); + auto child = parent.append_child(type.c_str()); + if (type == "dict") { + for (auto it = value.begin(); it != value.end(); ++it) { + child.append_child("key").text().set(it.key().c_str()); + writePlistNode(child, *it); + } + } else if (type == "array") { + for (auto & entry : value) writePlistNode(child, entry); + } else if (type != "true" && type != "false") child.text().set(value.get().c_str()); +} + +inline std::string writePlist(const json & node) { + pugi::xml_document doc; + auto declaration = doc.append_child(pugi::node_declaration); + declaration.append_attribute("version") = "1.0"; + declaration.append_attribute("encoding") = "UTF-8"; + doc.append_child(pugi::node_doctype).set_value("plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\""); + auto plist = doc.append_child("plist"); + plist.append_attribute("version") = "1.0"; + writePlistNode(plist, node); + std::ostringstream out; + doc.save(out, "\t"); + return out.str(); +} + +inline json mergePlist(const json & base, const json & user, const json & next) { + if (user == base) return next; + if (user.at("type") != "dict" || next.at("type") != "dict") return user; + json values = next.at("value"); + const auto & old = base.at("value"); + const auto & current = user.at("value"); + if (base.at("type") == "dict") { + for (auto it = old.begin(); it != old.end(); ++it) if (!current.contains(it.key())) values.erase(it.key()); + } + for (auto it = current.begin(); it != current.end(); ++it) { + if (!old.is_object() || !old.contains(it.key())) { + json empty = { { "type", "dict" }, { "value", json::object() } }; + values[it.key()] = values.contains(it.key()) ? mergePlist(empty, *it, values[it.key()]) : *it; + } else if (*it != old[it.key()]) { + values[it.key()] = values.contains(it.key()) ? mergePlist(old[it.key()], *it, values[it.key()]) : *it; + } + } + return { { "type", "dict" }, { "value", values } }; +} + +inline std::string settingName(const std::string & key) { return trim(key.substr(0, key.find('['))); } + +inline bool listSetting(const std::string & key) { + static const std::set lists { + "HEADER_SEARCH_PATHS", "LIBRARY_SEARCH_PATHS", "FRAMEWORK_SEARCH_PATHS", "OTHER_LDFLAGS", + "OTHER_CFLAGS", "OTHER_CPLUSPLUSFLAGS", "GCC_PREPROCESSOR_DEFINITIONS", "USER_PREPROCESSOR_DEFINITIONS" + }; + return lists.count(settingName(key)); +} + +inline std::vector words(const std::string & text) { + std::vector result; + std::string word; + char quote = 0; + bool escape = false; + for (char c : text) { + if (!quote && !escape && (c == ' ' || c == '\t' || c == '\n' || c == '\r')) { + if (!word.empty()) { result.push_back(word); word.clear(); } + } else { + word += c; + if (!escape && (c == '\'' || c == '"')) { + if (!quote) quote = c; + else if (quote == c) quote = 0; + } + } + escape = !escape && c == '\\'; + } + if (!word.empty()) result.push_back(word); + return result; +} + +inline std::vector> flagUnits(const std::string & key, const json & value) { + std::vector tokens; + if (value.is_array()) { + for (auto & part : value) { + if (!part.is_string()) continue; + if (settingName(key).find("SEARCH_PATHS") != std::string::npos) tokens.push_back(part.get()); + else { + auto parsed = words(part.get()); + tokens.insert(tokens.end(), parsed.begin(), parsed.end()); + } + } + } else if (value.is_string()) tokens = words(value.get()); + static const std::set withArgument { + "-framework", "-weak_framework", "-force_load", "-I", "-F", "-L", "-l", "-D", "-U", + "-isystem", "-iquote", "-include", "-Xclang", "-Xlinker" + }; + std::vector> result; + for (size_t i = 0; i < tokens.size(); ++i) { + std::vector unit { tokens[i] }; + if (withArgument.count(tokens[i]) && i + 1 < tokens.size()) unit.push_back(tokens[++i]); + result.push_back(unit); + } + return result; +} + +// Refresh generated flags, then carry only additions made by the user to the previous output. +// This retains a custom -framework pair without reviving flags from a removed addon. +inline json mergeListSetting(const std::string & key, const json & base, const json & user, const json & next) { + auto previous = flagUnits(key, base.is_null() ? next : base); + auto current = flagUnits(key, user); + auto result = flagUnits(key, next); + for (auto & unit : current) { + if (std::find(previous.begin(), previous.end(), unit) == previous.end() + && std::find(result.begin(), result.end(), unit) == result.end()) result.push_back(unit); + } + if (result.empty()) return nullptr; + if (next.is_null() && std::find(result.begin(), result.end(), std::vector{ "$(inherited)" }) == result.end()) { + result.insert(result.begin(), { "$(inherited)" }); + } + if (next.is_array() || (next.is_null() && user.is_array())) { + json array = json::array(); + for (auto & unit : result) for (auto & token : unit) array.push_back(token); + return array; + } + std::string text; + for (auto & unit : result) for (auto & token : unit) { if (!text.empty()) text += ' '; text += token; } + return text; +} + +inline bool generatedSetting(const std::string & key) { + const auto name = settingName(key); + static const std::set generated { + "OF_PATH", "OF_CORE_BUILD_COMMAND", "SDKROOT", "SUPPORTED_PLATFORMS", "VALID_ARCHS", "CLANG_CXX_LIBRARY", + "HEADER_SEARCH_PATHS", "LIBRARY_SEARCH_PATHS", "FRAMEWORK_SEARCH_PATHS", "OTHER_LDFLAGS", + "OTHER_CFLAGS", "OTHER_CPLUSPLUSFLAGS", "GCC_PREPROCESSOR_DEFINITIONS", "USER_PREPROCESSOR_DEFINITIONS", + "OF_NO_FMOD", "LIB_FMOD", "ENABLE_USER_SCRIPT_SANDBOXING" + }; + return generated.count(name) || name.rfind("OF_CORE_", 0) == 0; +} + +inline std::vector version(const std::string & value) { + std::vector result; + std::istringstream parts(value); + std::string part; + while (std::getline(parts, part, '.')) { + if (part.empty() || part.find_first_not_of("0123456789") != std::string::npos) return {}; + try { result.push_back(std::stoi(part)); } catch (...) { return {}; } + } + if (result.empty()) return {}; + result.resize(4); + return result; +} + +inline std::string literal(std::string value) { + value = trim(value); + if (value.empty()) return value; + if (value.front() == '"' || value.front() == '\'') { + return value.substr(1, value.find(value.front(), 1) - 1); + } + return value.substr(0, value.find_first_of(" \t/")); +} + +inline int languageVersion(std::string value) { + value = literal(value); + if (value.rfind("gnu++", 0) == 0) value = value.substr(5); + else if (value.rfind("c++", 0) == 0) value = value.substr(3); + else if (value.rfind("gnu", 0) == 0) value = value.substr(3); + else if (value.rfind("c", 0) == 0) value = value.substr(1); + if (value == "2a") return 2020; + if (value == "2b") return 2023; + if (value == "2c") return 2026; + if (value == "2y") return 2029; + try { + if (value.find_first_not_of("0123456789") != std::string::npos) return 0; + int year = std::stoi(value); + return year > 50 ? 1900 + year : 2000 + year; + } catch (...) { return 0; } +} + +inline bool minimumSetting(const std::string & key) { + const auto name = settingName(key); + return name == "CLANG_CXX_LANGUAGE_STANDARD" || name == "CLANG_C_LANGUAGE_STANDARD" + || name == "MACOSX_DEPLOYMENT_TARGET" || name == "IPHONEOS_DEPLOYMENT_TARGET" + || name == "TVOS_DEPLOYMENT_TARGET" || name == "XROS_DEPLOYMENT_TARGET"; +} + +inline json requiredSetting(const std::string & key, const json & user, const json & next) { + if (generatedSetting(key)) return next; + const auto name = settingName(key); + if (minimumSetting(key) && user.is_string() && next.is_string()) { + if (name == "CLANG_CXX_LANGUAGE_STANDARD" || name == "CLANG_C_LANGUAGE_STANDARD") { + return languageVersion(user.get()) >= languageVersion(next.get()) ? user : next; + } + const auto current = version(literal(user.get())), minimum = version(literal(next.get())); + return !current.empty() && !minimum.empty() && current >= minimum ? user : next; + } + return user; +} + +inline json mergeBuildSettings(const json & base, const json & user, const json & next, const json & minimums) { + auto result = merge(base, user, next); + for (auto it = next.begin(); it != next.end(); ++it) { + if (generatedSetting(it.key())) result[it.key()] = *it; + else if (result.contains(it.key())) result[it.key()] = requiredSetting(it.key(), result[it.key()], *it); + } + for (auto it = result.begin(); it != result.end();) { + if (generatedSetting(it.key()) && !listSetting(it.key()) && !next.contains(it.key())) it = result.erase(it); + else { + auto name = settingName(it.key()); + if (minimums.contains(name)) *it = requiredSetting(it.key(), *it, minimums[name]); + ++it; + } + } + std::set lists; + for (auto it = user.begin(); it != user.end(); ++it) if (listSetting(it.key())) lists.insert(it.key()); + for (auto it = next.begin(); it != next.end(); ++it) if (listSetting(it.key())) lists.insert(it.key()); + for (auto & key : lists) { + auto value = mergeListSetting(key, base.value(key, json()), user.value(key, json()), next.value(key, json())); + if (value.is_null()) result.erase(key); + else result[key] = value; + } + return result; +} + +struct configLine { std::string key, op, value, text; }; + +inline std::vector configLines(const std::string & text) { + static const std::regex assignment(R"(^\s*([A-Za-z_][A-Za-z0-9_]*(?:\[[^\]]+\])*)\s*(\+=|\?=|:=|=)\s*(.*)$)"); + std::vector result; + std::istringstream in(text); + std::string line; + while (std::getline(in, line)) { + configLine block; + block.text = line + "\n"; + std::smatch match; + if (std::regex_match(line, match, assignment)) { + block.key = match[1]; block.op = match[2]; block.value = trim(match[3]); + while (!trim(line).empty() && trim(line).back() == '\\' && std::getline(in, line)) { + block.text += line + "\n"; block.value += "\n" + trim(line); + } + } + result.push_back(block); + } + return result; +} + +inline json configSettings(const std::vector & lines) { + json result = json::object(); + for (auto & line : lines) { + if (line.key.empty()) continue; + if (!result.contains(line.key)) result[line.key] = json::array(); + result[line.key].push_back({ { "op", line.op }, { "value", line.value } }); + } + return result; +} + +inline json configValue(const json & settings, const std::string & key) { + if (!settings.contains(key)) return nullptr; + std::string value; + for (auto & assignment : settings[key]) { + if (assignment["op"] != "+=" && assignment["op"] != "?=") value.clear(); + if (assignment["op"] == "?=" && !value.empty()) continue; + if (!value.empty()) value += ' '; + value += assignment["value"].get(); + } + return value; +} + +inline std::string configAnchor(const configLine & line) { + if (!line.key.empty()) return "key:" + line.key; + auto text = trim(line.text); + if (text.rfind("#include", 0) != 0) return ""; + return text.find("CoreOF.xcconfig") != std::string::npos ? "include:CoreOF" : "include:" + text; +} + +inline std::string mergeConfig(const std::string & baseline, const std::string & current, const std::string & fresh, const json & minimums) { + auto oldLines = configLines(baseline), userLines = configLines(current), newLines = configLines(fresh); + auto base = configSettings(oldLines), user = configSettings(userLines), next = configSettings(newLines); + auto merged = merge(base, user, next); + std::set anchors; + for (auto & line : newLines) if (!configAnchor(line).empty()) anchors.insert(configAnchor(line)); + std::map> additions; + std::vector pending; + std::set seenUserAnchors; + for (auto & line : userLines) { + auto anchor = configAnchor(line); + if (!anchor.empty() && anchors.count(anchor)) { + if (seenUserAnchors.insert(anchor).second) { + auto & before = additions[anchor]; + before.insert(before.end(), pending.begin(), pending.end()); + pending.clear(); + } + } else if (!line.key.empty()) { + if ((merged.contains(line.key) && !generatedSetting(line.key)) || listSetting(line.key)) pending.push_back(line); + } else if (!trim(line.text).empty() && line.text.find("CoreOF.xcconfig") == std::string::npos) { + bool known = false; + for (auto & entry : newLines) if (trim(entry.text) == trim(line.text)) known = true; + for (auto & entry : oldLines) if (trim(entry.text) == trim(line.text)) known = true; + if (!known) pending.push_back(line); + } + } + additions[""] = pending; + std::set written; + std::set extraLists; + std::string out; + auto addUserLines = [&](const std::string & anchor) { + for (auto & line : additions[anchor]) { + if (listSetting(line.key)) { + if (!extraLists.insert(line.key).second) continue; + auto value = mergeListSetting(line.key, configValue(base, line.key), configValue(user, line.key), nullptr); + if (!value.is_null()) out += line.key + " = " + value.get() + "\n"; + } else out += line.text; + } + additions.erase(anchor); + }; + for (auto & line : newLines) { + if (!configAnchor(line).empty()) addUserLines(configAnchor(line)); + if (line.key.empty()) { out += line.text; continue; } + if (!written.insert(line.key).second) continue; + if (listSetting(line.key)) { + auto value = mergeListSetting(line.key, configValue(base, line.key), configValue(user, line.key), configValue(next, line.key)); + out += line.key + " = " + (value.is_null() ? "" : value.get()) + "\n"; + continue; + } + bool useUser = merged.contains(line.key) && user.contains(line.key) && merged[line.key] == user[line.key]; + if (generatedSetting(line.key)) useUser = false; + if (useUser && minimumSetting(line.key)) { + for (auto & saved : userLines) if (saved.key == line.key) { + if (requiredSetting(line.key, saved.value, line.value) != saved.value) useUser = false; + } + } + if (useUser) { + for (auto & saved : userLines) if (saved.key == line.key) out += saved.text; + } else if (merged.contains(line.key) || generatedSetting(line.key) || minimumSetting(line.key)) { + for (auto & entry : newLines) if (entry.key == line.key) out += entry.text; + } + } + // Keep extra includes near the setting they preceded: moving one after a user override + // would change its effective value even if the assignment itself was retained. + addUserLines(""); + // A per-project override must not lower a minimum inherited from CoreOF.xcconfig. + std::string checked; + for (auto & line : configLines(out)) { + auto name = settingName(line.key); + if (minimums.contains(name) && requiredSetting(line.key, line.value, minimums[name]) != line.value) { + checked += line.key + " = " + minimums[name].get() + "\n"; + } else checked += line.text; + } + return checked; +} + +inline json configurations(const json & project) { + json result = json::object(); + const auto & objects = project.at("objects"); + for (auto owner = objects.begin(); owner != objects.end(); ++owner) { + if (!owner->is_object() || !owner->contains("buildConfigurationList")) continue; + auto list = objects.find(owner->at("buildConfigurationList").get()); + if (list == objects.end() || !list->contains("buildConfigurations")) continue; + std::string scope = owner->value("isa", "") + "/" + owner->value("name", ""); + for (auto & id : list->at("buildConfigurations")) { + auto config = objects.find(id.get()); + if (config == objects.end()) continue; + result[id.get()] = { { "scope", scope + "/" + config->value("name", "") }, + { "settings", config->value("buildSettings", json::object()) } }; + } + } + return result; +} + +inline json matchingConfiguration(const json & configs, const std::string & id, const json & config) { + if (configs.contains(id)) return configs[id].at("settings"); + for (auto & candidate : configs) if (candidate.at("scope") == config.at("scope")) return candidate.at("settings"); + return nullptr; +} +} // namespace xcodeSettings diff --git a/commandLine/src/projects/baseProject.cpp b/commandLine/src/projects/baseProject.cpp index 944ab2a9..a9ec3954 100644 --- a/commandLine/src/projects/baseProject.cpp +++ b/commandLine/src/projects/baseProject.cpp @@ -633,7 +633,7 @@ bool baseProject::save(){ writeMakeList(str, "PROJECT_EXTERNAL_SOURCE_PATHS", paths, bWroteExtSrcPaths); } // make builds (emscripten, linux, msys2) only see defines through config.make - else if( projectDefines.size() && (str.rfind("# PROJECT_DEFINES =", 0) == 0 || str.rfind("PROJECT_DEFINES =", 0) == 0) ){ + else if( (projectDefines.size() || projectDefinesPassed) && isMakeVar(str, "PROJECT_DEFINES") ){ if (!bWroteDefines) { saveConfig << "PROJECT_DEFINES = " << ofJoinString(projectDefines, " ") << std::endl; bWroteDefines = true; @@ -674,7 +674,7 @@ bool baseProject::save(){ saveConfig << str << std::endl; } } - if (projectDefines.size() && !bWroteDefines && lines.size()) { + if ((projectDefines.size() || projectDefinesPassed) && !bWroteDefines && lines.size()) { saveConfig << "PROJECT_DEFINES = " << ofJoinString(projectDefines, " ") << std::endl; } if (emscriptenWasm == "64" && !bWroteWasm && lines.size()) { diff --git a/commandLine/src/projects/baseProject.h b/commandLine/src/projects/baseProject.h index 1d3d720b..15b3d435 100644 --- a/commandLine/src/projects/baseProject.h +++ b/commandLine/src/projects/baseProject.h @@ -113,6 +113,7 @@ class baseProject { addDefine(define, libType); projectDefines.emplace_back(define); } + void setProjectDefinesPassed(bool passed) { projectDefinesPassed = passed; } // project-level post-build script (-P/--postbuild) void addProjectAfterRule(const std::string & script) { addAfterRule(script); } // MSYS2 environment (ucrt64 | mingw64 | clang64) - only meaningful for VSCodeProject, @@ -197,6 +198,7 @@ class baseProject { std::vector extSrcPaths; std::vector savedExtSrcPaths; // config.make PROJECT_EXTERNAL_SOURCE_PATHS, read before the template copies std::vector projectDefines; // also written to config.make PROJECT_DEFINES for make builds + bool projectDefinesPassed = false; // an explicitly empty --defines clears saved project defines std::vector missingAddons; // not found, still written to addons.make (#258) std::vector systemFrameworks, systemLibs; // value for this project std::vector systemFrameworksOption, systemLibsOption; // from the CLI diff --git a/commandLine/src/projects/xcodeProject.cpp b/commandLine/src/projects/xcodeProject.cpp index 65b21a1b..6b08af84 100644 --- a/commandLine/src/projects/xcodeProject.cpp +++ b/commandLine/src/projects/xcodeProject.cpp @@ -1,4 +1,5 @@ #include "xcodeProject.h" +#include "XcodeSettings.h" #include "Utils.h" #include "ofUtils.h" #include @@ -14,6 +15,345 @@ using nlohmann::json; string xcodeProject::LOG_NAME = "xcodeProjectFile"; +namespace { +string readSettingsFile(const fs::path & path) { + std::ifstream in(path, std::ios::binary); + if (!in) throw std::runtime_error("cannot read " + path.string()); + return string(std::istreambuf_iterator(in), std::istreambuf_iterator()); +} + +void writeSettingsFile(const fs::path & path, const string & text) { + std::ofstream out(path, std::ios::binary); + if (!out || !(out << text)) throw std::runtime_error("cannot write " + path.string()); +} + +json targetAttributes(const json & project) { + json result = json::object(); + const auto & objects = project.at("objects"); + const auto & root = objects.at(project.at("rootObject").get()); + if (!root.contains("attributes") || !root["attributes"].contains("TargetAttributes")) return result; + for (auto it = root["attributes"]["TargetAttributes"].begin(); it != root["attributes"]["TargetAttributes"].end(); ++it) { + if (!objects.contains(it.key())) continue; + result[it.key()] = { { "scope", objects[it.key()].value("name", "") }, { "settings", *it } }; + } + return result; +} + +string sdkKey(const json & file) { + string path = file.value("path", file.value("name", "")); + if (file.value("sourceTree", "") != "SDKROOT" && path.find("SDKROOT") == string::npos + && path.find("System/Library/Frameworks/") == string::npos && path.find("/usr/lib/") == string::npos) return ""; + std::smatch match; + static const std::regex framework(R"((?:^|/)([^/]+)\.framework(?:/.*)?$)"); + static const std::regex library(R"((?:^|/)lib([^/]+)\.(?:tbd|dylib)$)"); + if (std::regex_search(path, match, framework)) return "frameworks:" + match[1].str(); + if (std::regex_search(path, match, library)) return "libs:" + match[1].str(); + return ""; +} + +json sdkFiles(const json & project, const json & target) { + json result = json::object(); + const auto & objects = project.at("objects"); + for (auto & phaseId : target.value("buildPhases", json::array())) { + if (!objects.contains(phaseId.get())) continue; + const auto & phase = objects.at(phaseId.get()); + if (phase.value("isa", "") != "PBXFrameworksBuildPhase") continue; + for (auto & buildId : phase.value("files", json::array())) { + if (!objects.contains(buildId.get())) continue; + const auto & build = objects.at(buildId.get()); + string fileId = build.value("fileRef", ""); + if (!objects.contains(fileId)) continue; + string key = sdkKey(objects.at(fileId)); + json properties = build; + properties.erase("fileRef"); + if (!key.empty()) result[key] = { { "fileId", fileId }, { "buildId", buildId }, + { "file", objects.at(fileId) }, { "build", properties }, { "settings", build.value("settings", json::object()) } }; + } + } + return result; +} + +json withoutDefines(const string & key, const json & value) { + json tokens = json::array(); + for (auto & unit : xcodeSettings::flagUnits(key, value)) { + if (!unit.empty() && unit[0].rfind("-D", 0) == 0) continue; + for (auto & token : unit) tokens.push_back(token); + } + if (value.is_array()) return tokens; + string text; + for (auto & token : tokens) { if (!text.empty()) text += ' '; text += token.get(); } + return text; +} + +bool installedSDKItem(const string & key) { +#ifdef __APPLE__ + static const vector roots = [] { + vector found; + for (const string sdk : { "macosx", "iphoneos", "appletvos" }) { + string root = xcodeSettings::trim(ofSystem("/usr/bin/xcrun --sdk " + sdk + " --show-sdk-path 2>/dev/null")); + if (!root.empty() && fs::is_directory(root)) found.emplace_back(root); + } + return found; + }(); + for (auto & root : roots) { + if (key.rfind("frameworks:", 0) == 0 && fs::exists(root / "System/Library/Frameworks" / (key.substr(11) + ".framework"))) return true; + if (key.rfind("libs:", 0) == 0 && (fs::exists(root / "usr/lib" / ("lib" + key.substr(5) + ".tbd")) || fs::exists(root / "usr/lib" / ("lib" + key.substr(5) + ".dylib")))) return true; + } +#endif + return false; +} + +json withoutSystemLinks(const json & value, bool frameworks, bool libs, const std::set & known) { + json kept = json::array(); + for (auto & unit : xcodeSettings::flagUnits("OTHER_LDFLAGS", value)) { + string key; + if (frameworks && unit.size() == 2 && (unit[0] == "-framework" || unit[0] == "-weak_framework")) key = "frameworks:" + unit[1]; + if (libs && unit[0].rfind("-l", 0) == 0) key = "libs:" + (unit[0] == "-l" && unit.size() == 2 ? unit[1] : unit[0].substr(2)); + if (libs && key.empty()) key = sdkKey({ { "path", unit[0] } }); + if (!key.empty() && (known.count(key) || installedSDKItem(key))) continue; + for (auto & token : unit) kept.push_back(token); + } + if (value.is_array()) return kept; + string result; + for (auto & token : kept) { if (!result.empty()) result += ' '; result += token.get(); } + return result; +} +} + +bool xcodeProject::readAppleSettings() { + appleProject = json::object(); + appleFiles = json::object(); + appleDefaults = json::object(); + nextAppleDefaults = json::object(); + appleMinimums = json::object(); + appleState = { { "format", 1 }, { "platforms", json::object() } }; + try { + auto stateFile = projectDir / ".ofprojectgenerator" / "apple-settings.json"; + if (fs::exists(stateFile.parent_path()) && !fs::is_directory(stateFile.parent_path())) { + throw std::runtime_error("settings baseline directory is a file: " + stateFile.parent_path().string()); + } + if (fs::exists(stateFile)) { + appleState = json::parse(readSettingsFile(stateFile)); + if (appleState.value("format", 0) != 1 || !appleState.at("platforms").is_object()) { + throw std::runtime_error("unsupported Apple settings baseline: " + stateFile.string()); + } + appleDefaults = appleState["platforms"].value(target, json::object()); + for (auto name : { "configurations", "targetAttributes" }) { + auto entries = appleDefaults.value(name, json::object()); + if (!entries.is_object()) throw std::runtime_error("invalid Apple settings baseline"); + for (auto & config : entries) { + if (!config.at("scope").is_string() || !config.at("settings").is_object()) throw std::runtime_error("invalid Apple settings baseline"); + } + } + auto files = appleDefaults.value("files", json::object()); + if (!files.is_object()) throw std::runtime_error("invalid Apple settings baseline files"); + for (auto it = files.begin(); it != files.end(); ++it) { + if (it.key() != "Project.xcconfig") xcodeSettings::readPlist(it.value().get()); + } + auto sdk = appleDefaults.value("systemReferences", json::object()); + if (!sdk.is_object()) throw std::runtime_error("invalid SDK reference baseline"); + for (auto & record : sdk) { + if (!record.at("scope").is_string() || !record.at("references").is_object()) throw std::runtime_error("invalid SDK reference baseline"); + } + } + xcodeSettings::configurations(xcodeSettings::readProject(readSettingsFile(templatePath / "emptyExample.xcodeproj/project.pbxproj"))); + auto projectFile = projectDir / (projectName + ".xcodeproj") / "project.pbxproj"; + if (fs::exists(projectFile)) { + appleProject = xcodeSettings::readProject(readSettingsFile(projectFile)); + xcodeSettings::configurations(appleProject); + targetAttributes(appleProject); + } + for (auto name : { "Project.xcconfig", "openFrameworks-Info.plist", "of.entitlements", "ofxiOS-Info.plist" }) { + if (!fs::exists(templatePath / name)) continue; + if (string(name) != "Project.xcconfig") xcodeSettings::readPlist(readSettingsFile(templatePath / name)); + if (!fs::exists(projectDir / name)) continue; + string text = readSettingsFile(projectDir / name); + // Validate before any template copy can replace a user's files. + if (string(name) != "Project.xcconfig") xcodeSettings::readPlist(text); + appleFiles[name] = text; + } + for (auto path : { getOFRoot() / "libs/openFrameworksCompiled/project" / target / "CoreOF.xcconfig", templatePath / "Project.xcconfig" }) { + if (!fs::exists(path)) continue; + for (auto & line : xcodeSettings::configLines(readSettingsFile(path))) { + if (!xcodeSettings::minimumSetting(line.key)) continue; + string name = xcodeSettings::settingName(line.key); + // Conditional SDK values are checked against their own template setting later. + if (name != line.key) continue; + appleMinimums[name] = appleMinimums.contains(name) + ? xcodeSettings::requiredSetting(name, appleMinimums[name], line.value) : json(line.value); + } + } + if (!appleProject.empty() && appleDefaults.empty()) { + ofLogNotice() << "Apple settings: no previous template baseline; keeping existing values and adding new defaults"; + } + } catch (const std::exception & e) { + ofLogError(LOG_NAME) << "Cannot preserve Apple settings; original settings kept: " << e.what(); + return false; + } + return true; +} + +void xcodeProject::mergeAppleSettings(json & project) { + mergeSystemReferences(project); + appleSDKKeys.clear(); + if (!appleProject.empty() && (systemFrameworksPassed || systemLibsPassed)) { + for (auto & object : appleProject.at("objects")) { + if (!object.is_object() || object.value("isa", "") != "PBXNativeTarget") continue; + auto refs = sdkFiles(appleProject, object); + for (auto it = refs.begin(); it != refs.end(); ++it) appleSDKKeys.insert(it.key()); + } + } + auto fresh = xcodeSettings::configurations(project); + auto attributes = targetAttributes(project); + nextAppleDefaults["configurations"] = fresh; + nextAppleDefaults["targetAttributes"] = attributes; + if (appleProject.empty()) return; + auto previous = xcodeSettings::configurations(appleProject); + auto baseline = appleDefaults.value("configurations", json::object()); + for (auto it = fresh.begin(); it != fresh.end(); ++it) { + auto user = xcodeSettings::matchingConfiguration(previous, it.key(), *it); + if (user.is_null()) continue; + auto base = xcodeSettings::matchingConfiguration(baseline, it.key(), *it); + if (base.is_null()) base = json::object(); + if ((systemFrameworksPassed || systemLibsPassed) && user.contains("OTHER_LDFLAGS")) user["OTHER_LDFLAGS"] = withoutSystemLinks(user["OTHER_LDFLAGS"], systemFrameworksPassed, systemLibsPassed, appleSDKKeys); + if (projectDefinesPassed) { + for (auto key : { "GCC_PREPROCESSOR_DEFINITIONS", "USER_PREPROCESSOR_DEFINITIONS" }) { + if (base.contains(key)) user[key] = base[key]; + else user.erase(key); + } + for (auto key : { "OTHER_CFLAGS", "OTHER_CPLUSPLUSFLAGS" }) if (user.contains(key)) user[key] = withoutDefines(key, user[key]); + } + auto merged = xcodeSettings::mergeBuildSettings(base, user, it->at("settings"), appleMinimums); + if (it->at("scope").get().rfind("PBXNativeTarget/", 0) == 0) { + if (!appVersionOption.empty()) merged["MARKETING_VERSION"] = appVersion; + if (!appBuildOption.empty()) merged["CURRENT_PROJECT_VERSION"] = appBuild; + if (!appBundleIdOption.empty()) merged["PRODUCT_BUNDLE_IDENTIFIER"] = appBundleId; + } + project["objects"][it.key()]["buildSettings"] = merged; + } + + auto userAttributes = targetAttributes(appleProject); + auto oldAttributes = appleDefaults.value("targetAttributes", json::object()); + auto & root = project["objects"][project["rootObject"].get()]; + for (auto & targetId : root.value("targets", json::array())) { + string id = targetId; + json entry = { { "scope", project["objects"][id].value("name", "") } }; + auto user = xcodeSettings::matchingConfiguration(userAttributes, id, entry); + if (user.is_null()) continue; + auto base = xcodeSettings::matchingConfiguration(oldAttributes, id, entry); + if (base.is_null()) base = json::object(); + auto next = attributes.contains(id) ? attributes[id]["settings"] : json::object(); + auto merged = xcodeSettings::merge(base, user, next); + for (auto key : { "CreatedOnToolsVersion", "LastSwiftMigration" }) { + if (next.contains(key)) merged[key] = next[key]; + else merged.erase(key); + } + root["attributes"]["TargetAttributes"][id] = merged; + } +} + +void xcodeProject::mergeSystemReferences(json & project) { + auto & objects = project["objects"]; + auto & root = objects[project["rootObject"].get()]; + json generated = json::object(); + for (auto & targetId : root.value("targets", json::array())) { + string id = targetId; + auto & target = objects[id]; + if (target.value("productType", "") != "com.apple.product-type.application") continue; + auto current = sdkFiles(project, target); + json refs = json::object(); + for (auto it = current.begin(); it != current.end(); ++it) refs[it.key()] = { { "file", it->at("file") }, { "build", it->at("build") }, { "settings", it->at("settings") } }; + generated[id] = { { "scope", target.value("name", "") }, { "references", refs } }; + if (appleProject.empty()) continue; + string oldId = id; + const auto & oldObjects = appleProject.at("objects"); + if (!oldObjects.contains(oldId)) { + oldId.clear(); + for (auto it = oldObjects.begin(); it != oldObjects.end(); ++it) { + if (it->is_object() && it->value("isa", "") == "PBXNativeTarget" && it->value("name", "") == target.value("name", "")) { oldId = it.key(); break; } + } + } + if (oldId.empty()) continue; + auto old = sdkFiles(appleProject, oldObjects.at(oldId)); + auto records = appleDefaults.value("systemReferences", json::object()); + json previous = json::object(); + if (records.contains(oldId)) previous = records[oldId].at("references"); + else for (auto & record : records) if (record.value("scope", "") == target.value("name", "")) previous = record.at("references"); + string frameworkPhase; + for (auto & phaseId : target.value("buildPhases", json::array())) { + if (objects[phaseId.get()].value("isa", "") == "PBXFrameworksBuildPhase") frameworkPhase = phaseId; + } + for (auto it = old.begin(); it != old.end(); ++it) { + if (current.contains(it.key())) { + json before = previous.contains(it.key()) ? previous[it.key()].value("build", json::object()) : json::object(); + json merged = xcodeSettings::merge(before, it->at("build"), current[it.key()]["build"]); + merged["isa"] = "PBXBuildFile"; + merged["fileRef"] = current[it.key()]["fileId"]; + objects[current[it.key()]["buildId"].get()] = merged; + continue; + } + if (previous.contains(it.key()) || (it.key().rfind("frameworks:", 0) == 0 ? systemFrameworksPassed : systemLibsPassed)) continue; + if (frameworkPhase.empty()) { + frameworkPhase = generateUUID(string("preserved-sdk-phase")); + objects[frameworkPhase] = { { "isa", "PBXFrameworksBuildPhase" }, { "buildActionMask", "2147483647" }, { "runOnlyForDeploymentPostprocessing", "0" }, { "files", json::array() } }; + target["buildPhases"].push_back(frameworkPhase); + } + string fileId = it->at("fileId"), buildId = it->at("buildId"); + if (objects.contains(fileId) && objects[fileId] != it->at("file")) fileId = generateUUID(string("preserved-sdk-file")); + if (objects.contains(buildId)) buildId = generateUUID(string("preserved-sdk-build")); + bool newFile = !objects.contains(fileId); + objects[fileId] = it->at("file"); + objects[buildId] = it->at("build"); + objects[buildId]["fileRef"] = fileId; + objects[frameworkPhase]["files"].push_back(buildId); + string group = root.value("mainGroup", ""); + if (newFile && objects.contains(group)) objects[group]["children"].push_back(fileId); + } + } + nextAppleDefaults["systemReferences"] = generated; +} + +void xcodeProject::saveAppleSettings() { + json files = json::object(); + std::map outputs; + for (auto name : { "Project.xcconfig", "openFrameworks-Info.plist", "of.entitlements", "ofxiOS-Info.plist" }) { + if (!fs::exists(templatePath / name) || !fs::exists(projectDir / name)) continue; + string fresh = readSettingsFile(projectDir / name); + // JSON stores a text baseline even when a template or user's plist is binary. + files[name] = string(name) == "Project.xcconfig" ? fresh : xcodeSettings::writePlist(xcodeSettings::readPlist(fresh)); + if (!appleFiles.contains(name)) continue; + string user = appleFiles[name]; + string base = appleDefaults.value("files", json::object()).value(name, ""); + if (string(name) == "Project.xcconfig") { + if (projectDefinesPassed || systemFrameworksPassed || systemLibsPassed) { + string filtered; + for (auto & line : xcodeSettings::configLines(user)) { + string key = xcodeSettings::settingName(line.key); + if (projectDefinesPassed && (key == "GCC_PREPROCESSOR_DEFINITIONS" || key == "USER_PREPROCESSOR_DEFINITIONS")) continue; + if (projectDefinesPassed && (key == "OTHER_CFLAGS" || key == "OTHER_CPLUSPLUSFLAGS")) filtered += line.key + " " + line.op + " " + withoutDefines(key, line.value).get() + "\n"; + else if (key == "OTHER_LDFLAGS" && (systemFrameworksPassed || systemLibsPassed)) filtered += line.key + " " + line.op + " " + withoutSystemLinks(line.value, systemFrameworksPassed, systemLibsPassed, appleSDKKeys).get() + "\n"; + else filtered += line.text; + } + user = filtered; + } + outputs[projectDir / name] = xcodeSettings::mergeConfig(base, user, fresh, appleMinimums); + } + else { + auto previous = base.empty() ? json { { "type", "dict" }, { "value", json::object() } } : xcodeSettings::readPlist(base); + auto current = xcodeSettings::readPlist(user); + auto merged = xcodeSettings::mergePlist(previous, current, xcodeSettings::readPlist(fresh)); + outputs[projectDir / name] = merged == current ? user : xcodeSettings::writePlist(merged); + } + } + nextAppleDefaults["files"] = files; + for (auto & output : outputs) writeSettingsFile(output.first, output.second); + if (!appVersionOption.empty() || !appBuildOption.empty()) saveAppVersionFiles(); + if (!appBundleIdOption.empty()) saveAppBundleIdFiles(); + appleState["platforms"][target] = nextAppleDefaults; + fs::create_directories(projectDir / ".ofprojectgenerator"); + writeSettingsFile(projectDir / ".ofprojectgenerator" / "apple-settings.json", appleState.dump(1, '\t') + "\n"); +} + xcodeProject::xcodeProject(const string & target) : baseProject(target) { // TODO: remove unused variables @@ -71,9 +411,11 @@ xcodeProject::xcodeProject(const string & target) }; bool xcodeProject::createProjectFile() { + if (!readAppleSettings()) return false; // PROJECT_DEFINES is a makefile setting. Xcode needs each value copied - // into GCC_PREPROCESSOR_DEFINITIONS when the project is generated. - for (const auto & line : fileToStrings(projectDir / "config.make")) { + // into GCC_PREPROCESSOR_DEFINITIONS, after readTemplateUUIDs finds the current app targets. + savedMakeDefines.clear(); + for (const auto & line : projectDefinesPassed ? vector{} : fileToStrings(projectDir / "config.make")) { auto config = ofTrim(line); if (config.empty() || config[0] == '#') continue; auto eq = config.find('='); @@ -84,9 +426,12 @@ bool xcodeProject::createProjectFile() { variable = ofTrim(variable.substr(0, variable.size() - 1)); } if (variable != "PROJECT_DEFINES") continue; - if (!append) projectDefines.clear(); + if (!append) { + projectDefines.clear(); + savedMakeDefines.clear(); + } for (const auto & define : ofSplitString(ofTrim(config.substr(eq + 1)), " ", true, true)) { - addDefine(define); + savedMakeDefines.push_back(define); } } @@ -137,11 +482,13 @@ bool xcodeProject::createProjectFile() { if (backupProjectFiles) { createBackup({ xcodeProject / "project.pbxproj" }, projectDir); createBackup({ projectDir / "openFrameworks-Info.plist" }, projectDir); + createBackup({ projectDir / "ofxiOS-Info.plist" }, projectDir); createBackup({ projectDir / "Project.xcconfig" }, projectDir); createBackup({ projectDir / "of.entitlements" }, projectDir); createBackup({ projectDir / "addons.make" }, projectDir); createBackup({ projectDir / "config.make" }, projectDir); createBackup({ projectDir / "Makefile" }, projectDir); + createBackup({ projectDir / ".ofprojectgenerator" / "apple-settings.json" }, projectDir); } saveScheme(); @@ -153,7 +500,11 @@ bool xcodeProject::createProjectFile() { // Execute all file copy and replacements, including ones in saveScheme, saveMakefile for (auto & c : copyTemplateFiles) { try { - c.run(); + if (fs::exists(c.from) && (c.to.extension() == ".plist" || c.to.extension() == ".entitlements")) { + // update_existing can skip a newer user plist. Start from the actual template + // here; its validated original is in appleFiles and is merged back on save. + writeSettingsFile(c.to, readSettingsFile(c.from)); + } else c.run(); } catch (const std::exception & e) { std::cerr << "Error running copy template files: " << e.what() << std::endl; return false; @@ -195,8 +546,10 @@ void xcodeProject::saveScheme() { { { "emptyExample", projectName } } }); } - copyTemplateFiles.push_back({ projectDir / (projectName + ".xcodeproj/project.xcworkspace"), - templatePath / "emptyExample.xcodeproj/project.xcworkspace" }); + auto workspace = projectDir / (projectName + ".xcodeproj/project.xcworkspace"); + if (!fs::exists(workspace)) { + copyTemplateFiles.push_back({ templatePath / "emptyExample.xcodeproj/project.xcworkspace", workspace }); + } } else { // MARK:- IOS sector; @@ -327,6 +680,7 @@ void xcodeProject::readTemplateUUIDs() { bool xcodeProject::loadProjectFile() { //base readTemplateUUIDs(); + for (auto & define : savedMakeDefines) addDefine(define); addCommand("# ---- PG VERSION " + getPGVersion()); addCommand("Add :_OFProjectGeneratorVersion string " + getPGVersion()); @@ -1205,6 +1559,12 @@ bool xcodeProject::saveProjectFile() { ofLogError(xcodeProject::LOG_NAME) << "app version: " << e.what(); } + try { + mergeAppleSettings(j); + } catch (const std::exception & e) { + ofLogError(LOG_NAME) << "Cannot merge Apple settings: " << e.what(); + return false; + } std::ofstream jsonFile(fileName); // This is not pretty but address some differences in nlohmann json 3.11.2 to 3.11.3 @@ -1223,6 +1583,12 @@ bool xcodeProject::saveProjectFile() { return false; } jsonFile.close(); + try { + saveAppleSettings(); + } catch (const std::exception & e) { + ofLogError(LOG_NAME) << "Cannot save Apple settings: " << e.what(); + return false; + } } // for (auto & c : commands) cout << c << endl; diff --git a/commandLine/src/projects/xcodeProject.h b/commandLine/src/projects/xcodeProject.h index 35486f87..e59b57d4 100644 --- a/commandLine/src/projects/xcodeProject.h +++ b/commandLine/src/projects/xcodeProject.h @@ -7,6 +7,8 @@ #include #include #include +#include +#include using std::string; class xcodeProject : public baseProject { @@ -18,6 +20,13 @@ class xcodeProject : public baseProject { bool loadProjectFile() override; bool saveProjectFile() override; void saveMakefile(); + bool readAppleSettings(); + void mergeAppleSettings(nlohmann::json & project); + void mergeSystemReferences(nlohmann::json & project); + void saveAppleSettings(); + nlohmann::json appleProject, appleFiles, appleState, appleDefaults, nextAppleDefaults, appleMinimums; + std::set appleSDKKeys; + std::vector savedMakeDefines; bool debugCommands = false; bool bAddedDylibRunpath = false; diff --git a/frontend/app.js b/frontend/app.js index bd3ac181..aec0406d 100644 --- a/frontend/app.js +++ b/frontend/app.js @@ -8,6 +8,7 @@ const webUtils = { getPathForFile: window.ipcWrapper.getPathForFile }; let platforms; let templates; let lastGeneratedProject = null; +let loadedProjectSettings = null; // var platforms = { // "osx": "macOS (OSX) (Xcode)", @@ -217,32 +218,37 @@ ipcRenderer.on('setGenerateMode', (event, arg) => { if (arg === 'createMode') { $('#wasmDropdown').dropdown('set selected', '32'); $('#wasmNote').hide(); - $('#appVersion').val(''); - $('#appBuild').val(''); - $('#appVersionNote').hide(); - $('#bundleId').val(''); - $('#systemFrameworks').val(''); - $('#systemLibs').val(''); } }); -//------------------------------------------- -// existing project's app version / build, so updating keeps them -ipcRenderer.on('setAppVersion', (event, { version, build, differs, bundleId }) => { - $('#appVersion').val(version || ''); - $('#appBuild').val(build || ''); - $('#bundleId').val(bundleId || ''); - const note = (differs || []).map((d) => t('note.appVersionDiffers', { file: d.file, value: d.value })).join(' '); - $('#appVersionNote').text(note).toggle(!!defaultSettings.advancedMode && note.length > 0); -}); +function clearProjectSettings() { + for (const id of ['appVersion', 'appBuild', 'bundleId', 'systemFrameworks', 'systemLibs', 'customDefines']) $('#' + id).val(''); + $('#appVersionNote').text('').hide(); + $('#rendererDropdown, #glDropdown, #webglDropdown, #glesDropdown').dropdown('set exactly', 'default'); + loadedProjectSettings = null; +} //------------------------------------------- -// existing project's config.make PROJECT_FRAMEWORKS / PROJECT_SYSTEM_LIBS, so updating keeps them -ipcRenderer.on('setSystemFrameworks', (event, { frameworks, libs }) => { - $('#systemFrameworks').val((frameworks || []).join(',')); - $('#systemLibs').val((libs || []).join(',')); +// Populate from the selected project. Unedited fields are displayed without becoming CLI overrides. +ipcRenderer.on('setProjectSettings', (event, values) => { + if (values.projectName !== $('#projectName').val() || values.projectPath !== $('#projectPath').val()) return; + const fields = { appVersion: values.version || '', appBuild: values.build || '', bundleId: values.bundleId || '', + systemFrameworks: (values.frameworks || []).join(','), systemLibs: (values.libs || []).join(','), customDefines: (values.defines || []).join(',') }; + const keepEdits = values.preserveEdits && loadedProjectSettings?.projectName === values.projectName && loadedProjectSettings?.projectPath === values.projectPath; + for (const [id, value] of Object.entries(fields)) { + if (!keepEdits || $('#' + id).val().trim() === loadedProjectSettings[id]) $('#' + id).val(value); + } + $('#appVersionNote').text('').hide(); + if (!keepEdits) $('#rendererDropdown, #glDropdown, #webglDropdown, #glesDropdown').dropdown('set exactly', 'default'); + loadedProjectSettings = { projectName: values.projectName, projectPath: values.projectPath, ...fields }; }); +function projectFieldValue(id) { + const value = $('#' + id).val().trim(); + if (loadedProjectSettings && (loadedProjectSettings.projectName !== $('#projectName').val() || loadedProjectSettings.projectPath !== $('#projectPath').val())) return null; + return loadedProjectSettings && loadedProjectSettings[id] === value ? null : value; +} + //------------------------------------------- // existing project's PROJECT_EMSCRIPTEN_WASM, so updating keeps it ipcRenderer.on('setEmscriptenWasm', (event, bits) => { @@ -794,8 +800,11 @@ function setup() { const project = { projectName: $("#projectName").val(), - projectPath: $("#projectPath").val() + projectPath: $("#projectPath").val(), + platformList: getPlatformList(), + ofPath: $("#ofPath").val() }; + if (loadedProjectSettings && (loadedProjectSettings.projectName !== project.projectName || loadedProjectSettings.projectPath !== project.projectPath)) clearProjectSettings(); // a template pick belongs to the project it was made for - clear it as // soon as the user points at a different project (rather than right after @@ -1068,6 +1077,8 @@ function setup() { ipcRenderer.send('refreshTemplateList', arg); updateRendererFieldVisibility(); + ipcRenderer.send('readProjectSettings', { projectName: $('#projectName').val(), projectPath: $('#projectPath').val(), + platformList: selectedPlatformArray, ofPath: $('#ofPath').val(), preserveEdits: true }); }) $("#platformsDropdownMulti").on('change', () => { const selectedPlatforms = $("#platformsDropdownMulti input").val(); @@ -1266,21 +1277,26 @@ function generate() { }; const rendererChoice = $('#rendererDropdown').dropdown('get value'); const customDefinesText = $('#customDefines').val().trim(); - const definesArr = customDefinesText ? customDefinesText.split(',').map((s) => s.trim()).filter(Boolean) : []; + let definesArr = customDefinesText ? customDefinesText.split(',').map((s) => s.trim()).filter(Boolean) : []; if (rendererDefines[rendererChoice]) { - definesArr.push(rendererDefines[rendererChoice]); + const rendererKeys = new Set(['OF_USE_ANGLE', 'OF_USE_DAWN', 'OF_USE_GLON12', 'OF_USE_GLON12_WARP']); + definesArr = definesArr.filter((define) => !rendererKeys.has(define.split('=')[0])); + definesArr.push(...rendererDefines[rendererChoice].split(',')); } const gl = $('#glDropdown').dropdown('get value'); if ($('#glField').css('display') !== 'none' && gl !== 'default') { + definesArr = definesArr.filter((define) => !/^OF_GL_VERSION_(MAJOR|MINOR)=/.test(define)); const [major, minor] = gl.split('.'); definesArr.push('OF_GL_VERSION_MAJOR=' + major, 'OF_GL_VERSION_MINOR=' + minor); } const webgl = $('#webglDropdown').dropdown('get value'); if ($('#webglField').css('display') !== 'none' && webgl !== 'default') { + definesArr = definesArr.filter((define) => !define.startsWith('OF_WEBGL_VERSION=')); definesArr.push('OF_WEBGL_VERSION=' + webgl); } const gles = $('#glesDropdown').dropdown('get value'); if ($('#glesField').css('display') !== 'none' && gles !== 'default') { + definesArr = definesArr.filter((define) => !define.startsWith('OF_GLES_VERSION=')); definesArr.push('OF_GLES_VERSION=' + gles); } @@ -1294,16 +1310,16 @@ function generate() { addonList: addonValueArray, //$("#addonsDropdown").val(); ofPath: $("#ofPath").val(), verbose: bVerbose, - defines: definesArr.join(','), + defines: projectFieldValue('customDefines') === null && rendererChoice === 'default' && gl === 'default' && webgl === 'default' && gles === 'default' ? null : [...new Set(definesArr)].join(','), postBuild: $('#postBuildScript').val().trim(), msys2Env: $('#msys2EnvField').css('display') !== 'none' ? $('#msys2EnvDropdown').dropdown('get value') : '', emscriptenWasm: $('#wasmField').css('display') !== 'none' ? $('#wasmDropdown').dropdown('get value') : '', - appVersion: $('#appVersion').val().trim(), - appBuild: $('#appBuild').val().trim(), - appBundleId: $('#bundleId').val().trim(), + appVersion: projectFieldValue('appVersion') || '', + appBuild: projectFieldValue('appBuild') || '', + appBundleId: projectFieldValue('bundleId') || '', // only for Apple targets; hidden = keep the project's config.make values - systemFrameworks: $('#systemFrameworksField').css('display') !== 'none' ? $('#systemFrameworks').val().split(/[\s,]+/).filter(Boolean) : null, - systemLibs: $('#systemFrameworksField').css('display') !== 'none' ? $('#systemLibs').val().split(/[\s,]+/).filter(Boolean) : null + systemFrameworks: $('#systemFrameworksField').css('display') !== 'none' && projectFieldValue('systemFrameworks') !== null ? $('#systemFrameworks').val().split(/[\s,]+/).filter(Boolean) : null, + systemLibs: $('#systemFrameworksField').css('display') !== 'none' && projectFieldValue('systemLibs') !== null ? $('#systemLibs').val().split(/[\s,]+/).filter(Boolean) : null }; // console.log(gen); @@ -1404,6 +1420,7 @@ function switchGenerateMode(mode) { } // [default]: switch to createMode (generate new projects) else { + clearProjectSettings(); // if previously in update mode, deselect Addons if( $("#updateButton").is(":visible") ){ clearAddonSelection(); diff --git a/frontend/index.js b/frontend/index.js index 897eb2f2..3f1de930 100644 --- a/frontend/index.js +++ b/frontend/index.js @@ -5,6 +5,7 @@ const moniker = require('moniker'); const process = require('process'); const os = require("os"); const { execFile, spawn } = require('child_process'); +const { readProjectSettings } = require('./project-settings'); const { app, @@ -67,100 +68,6 @@ const templateSettings = { -/** - * App version / build of an existing project, read like the commandLine does: - * config.make, then CMakeLists.txt, then the .xcodeproj, then the android ofApp/build.gradle. - * @param {string} folder - The project folder. - * @returns {{version: string, build: string, differs: Array<{file: string, value: string}>}} - */ -function readProjectAppVersion(folder) { - const read = (file) => { - try { - return fs.readFileSync(path.join(folder, file), 'utf8'); - } catch (e) { - return ''; - } - }; - const last = (text, re) => { - let value = ''; - for (const m of text.matchAll(re)) value = m[1]; - return value; - }; - const name = path.basename(folder); - const pbxproj = read(path.join(`${name}.xcodeproj`, 'project.pbxproj')); - const sources = [ - { file: 'config.make', text: read('config.make'), version: /^[ \t]*APP_VERSION[ \t]*[?:+]?=[ \t]*([0-9.]+)/gm, build: /^[ \t]*APP_BUILD[ \t]*[?:+]?=[ \t]*([0-9]+)/gm }, - { file: 'CMakeLists.txt', text: read('CMakeLists.txt'), version: /^[ \t]*set\([ \t]*APP_VERSION[ \t]+"?([0-9.]+)/gm, build: /^[ \t]*set\([ \t]*APP_BUILD[ \t]+"?([0-9]+)/gm }, - { file: `${name}.xcodeproj`, text: pbxproj, version: /"?MARKETING_VERSION"?\s*[:=]\s*"?([0-9.]+)/g, build: /"?CURRENT_PROJECT_VERSION"?\s*[:=]\s*"?([0-9]+)/g }, - { file: 'ofApp/build.gradle', text: read(path.join('ofApp', 'build.gradle')), version: /^\s*versionName\s+['"]([0-9.]+)['"]/gm, build: /^\s*versionCode\s+([0-9]+)/gm }, - ].map((s) => ({ file: s.file, version: s.text ? last(s.text, s.version) : '', build: s.text ? last(s.text, s.build) : '' })); - const version = (sources.find((s) => s.version) || {}).version || ''; - const build = (sources.find((s) => s.build) || {}).build || ''; - const differs = []; - for (const s of sources) { - if ((s.version && s.version !== version) || (s.build && s.build !== build)) { - differs.push({ file: s.file, value: `${s.version || version} (${s.build || build})` }); - } - } - return { version, build, differs }; -} - -/** - * PROJECT_FRAMEWORKS / PROJECT_SYSTEM_LIBS of an existing project's config.make, read like the commandLine does. - * @param {string} folder - The project folder. - * @returns {{frameworks: Array, libs: Array}} - */ -function readProjectSystemFrameworks(folder) { - const lists = { PROJECT_FRAMEWORKS: [], PROJECT_SYSTEM_LIBS: [] }; - let text = ''; - try { - text = fs.readFileSync(path.join(folder, 'config.make'), 'utf8'); - } catch (e) { - return { frameworks: [], libs: [] }; - } - for (const m of text.matchAll(/^[ \t]*(PROJECT_FRAMEWORKS|PROJECT_SYSTEM_LIBS)[ \t]*([?:+]?)=(.*)$/gm)) { - const values = m[3].trim().split(/\s+/).filter(Boolean); - lists[m[1]] = m[2] === '+' ? lists[m[1]].concat(values) : values; - } - return { frameworks: lists.PROJECT_FRAMEWORKS, libs: lists.PROJECT_SYSTEM_LIBS }; -} - -/** - * Bundle id of an existing project, read like the commandLine does: config.make APP_BUNDLE_ID, CMakeLists.txt, - * the .xcodeproj, Project.xcconfig, then the android applicationId; the templates' default ids don't count. - * @param {string} folder - The project folder. - * @returns {string} The bundle id, or '' for the template's cc.openFrameworks.. - */ -function readProjectBundleId(folder) { - const read = (file) => { - try { - return fs.readFileSync(path.join(folder, file), 'utf8'); - } catch (e) { - return ''; - } - }; - const name = path.basename(folder); - const isTemplate = (id) => { - if (!id || id.includes('$')) return true; - const m = /^(cc|com)\.openframeworks\.(.+)$/i.exec(id); - return !!m && ['emptyexample', 'androidassimpexample', name.toLowerCase(), name.toLowerCase() + 'debug'].includes(m[2].toLowerCase()); - }; - const lastMatch = (text, re) => { - let value = ''; - for (const m of text.matchAll(re)) value = m[1]; - return value; - }; - const firstMatch = (text, re) => (re.exec(text) || [])[1] || ''; - const found = [ - lastMatch(read('config.make'), /^[ \t]*APP_BUNDLE_ID[ \t]*[?:+]?=[ \t]*(\S+)/gm), - lastMatch(read('CMakeLists.txt'), /^\s*set\(\s*APP_BUNDLE_ID\s+"?([^\s")]+)/gm), - firstMatch(read(path.join(`${name}.xcodeproj`, 'project.pbxproj')), /^\s*"?PRODUCT_BUNDLE_IDENTIFIER"?\s*[:=]\s*"?([^\s";]+)/m), - firstMatch(read('Project.xcconfig'), /^\s*PRODUCT_BUNDLE_IDENTIFIER\s*=\s*(\S+)/m), - firstMatch(read(path.join('ofApp', 'build.gradle')), /^\s*applicationId\s+['"]([^'"]+)['"]/m), - ]; - return found.find((id) => !isTemplate(id)) || ''; -} - // mirrors isGoodOFPath() in commandLine/src/main.cpp function isGoodOFPath(p) { try { @@ -962,6 +869,19 @@ function getDirectories(srcpath, acceptedPrefix) { //----------------------------------------------------------- ipc +function sendProjectSettings(event, project) { + const folder = path.join(project.projectPath, project.projectName); + try { + if (!fs.statSync(path.join(folder, 'src')).isDirectory()) return; + } catch { return; } + event.sender.send('setProjectSettings', { + projectPath: project.projectPath, projectName: project.projectName, preserveEdits: !!project.preserveEdits, + ...readProjectSettings(folder, { platforms: project.platformList || [], ofPath: project.ofPath || settings.defaultOfPath }) + }); +} + +ipcMain.on('readProjectSettings', sendProjectSettings); + ipcMain.on('isOFProjectFolder', (event, project) => { const { projectPath, @@ -977,6 +897,7 @@ ipcMain.on('isOFProjectFolder', (event, project) => { try { const tmpFiles = fs.readdirSync(folder); if (!tmpFiles || tmpFiles.length <= 1) { + event.sender.send('setGenerateMode', 'createMode'); return false; } // we need at least 2 files/folders within @@ -1081,8 +1002,7 @@ ipcMain.on('isOFProjectFolder', (event, project) => { if (fs.existsSync(cmakeLists) && /^\s*set\(\s*PROJECT_EMSCRIPTEN_WASM\s+64\b/m.test(fs.readFileSync(cmakeLists, 'utf8'))) { event.sender.send('setEmscriptenWasm', '64'); } - event.sender.send('setAppVersion', { ...readProjectAppVersion(folder), bundleId: readProjectBundleId(folder) }); - event.sender.send('setSystemFrameworks', readProjectSystemFrameworks(folder)); + sendProjectSettings(event, project); } else { event.sender.send('setGenerateMode', 'createMode'); @@ -1844,7 +1764,7 @@ ipcMain.on('downloadModularLibs', async (event, { ofPath, tag, names }) => { * addonList: Array, * ofPath: string, * verbose: boolean, - * defines: string, + * defines: string|null, * postBuild: string, * msys2Env: string, * emscriptenWasm: string, @@ -1907,8 +1827,9 @@ function generateFunction(event, generate) { args.push(`-t${templateList.join(",")}`); } - if (defines != null && defines.length > 0) { - args.push(`-D${defines}`); + if (typeof defines === 'string') { + // null keeps existing defines; an explicitly edited empty field clears them. + args.push(`--defines=${defines}`); } if (postBuild != null && postBuild.length > 0) { diff --git a/frontend/npm-shrinkwrap.json b/frontend/npm-shrinkwrap.json index aadafd3f..5db72abe 100644 --- a/frontend/npm-shrinkwrap.json +++ b/frontend/npm-shrinkwrap.json @@ -1,12 +1,12 @@ { "name": "projectGenerator", - "version": "0.119.0", + "version": "0.120.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "projectGenerator", - "version": "0.119.0", + "version": "0.120.0", "license": "MIT", "dependencies": { "@types/jquery": "^3.5.34", @@ -15,7 +15,7 @@ }, "devDependencies": { "@electron/packager": "^20.3.0", - "electron": "^45.2.0", + "electron": "45.2.3", "electron-builder": "^26.18.0" }, "engines": { @@ -1662,9 +1662,9 @@ } }, "node_modules/electron": { - "version": "45.2.0", - "resolved": "https://registry.npmjs.org/electron/-/electron-45.2.0.tgz", - "integrity": "sha512-OLQ7ct4TEbXfIctVwId+3RlWGrHr/hVJdCJqwnFWmfsttWAyHdwUhSvJHr/k6j4K+3HxSWg6agFizEv8IHqEBw==", + "version": "45.2.3", + "resolved": "https://registry.npmjs.org/electron/-/electron-45.2.3.tgz", + "integrity": "sha512-Vurzu5UOA5nTGT4LqIwXD16QFGrOZdiXxF+1UP4KNsAOo/YtDcT3/u0jhP4WSwNJ0iLrLDi85hzBJ0arnGDhyw==", "dev": true, "license": "MIT", "dependencies": { diff --git a/frontend/package.json b/frontend/package.json index 9c940ef4..4c2d76ff 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,7 +1,7 @@ { "name": "projectGenerator", "productName": "projectGenerator", - "version": "0.119.0", + "version": "0.120.0", "description": "Build electron GUI openFrameworks projectGenerator", "license": "MIT", "main": "index.js", @@ -21,11 +21,11 @@ "dist:mac:arm64": " electron-builder --macos --arm64 --publish never", "dist:mac:universal": " electron-builder --mac --universal --publish never", "dist:win64": "electron-builder --win --x64 --publish never", - "dist:win:arm64": "electron-builder --win --arm64 --publish never", + "dist:win:arm64": "electron-builder --win --arm64 --publish never", "dist:linux": "electron-builder --linux --publish never", "dist:linux64": "electron-builder --linux --x64 --publish never", "dist:linux:arm64": "electron-builder --linux --arm64 --publish never", - "build:linux64": "electron-packager . $npm_package_productName --icon=static/icon/of.icns --out=dist --ignore='dist' --ignore='readme.md' --prune --overwrite --electron-version=45.0.0 --platform=linux --arch=x64" + "build:linux64": "electron-packager . $npm_package_productName --icon=static/icon/of.icns --out=dist --ignore='dist' --ignore='readme.md' --prune --overwrite --electron-version=45.2.3 --platform=linux --arch=x64" }, "build": { "appId": "cc.openframeworks.projectGenerator", @@ -66,6 +66,7 @@ "static/**/*", "index.js", "app.js", + "project-settings.js", "preload.js", "console-window.html", "app-console-window.js", @@ -92,7 +93,7 @@ "n-readlines": "^3.4.1" }, "devDependencies": { - "electron": "^45.2.0", + "electron": "45.2.3", "electron-builder": "^26.18.0", "@electron/packager": "^20.3.0" } diff --git a/frontend/project-settings.js b/frontend/project-settings.js new file mode 100644 index 00000000..cc135984 --- /dev/null +++ b/frontend/project-settings.js @@ -0,0 +1,313 @@ +const fs = require('node:fs'); +const path = require('node:path'); +const { execFileSync } = require('node:child_process'); + +const applePlatforms = new Set(['osx', 'macos', 'ios', 'tvos']); +const unique = (items) => [...new Set(items.filter(Boolean))]; +const text = (file) => { try { return fs.readFileSync(file, 'utf8'); } catch { return ''; } }; +const scalar = (value) => Array.isArray(value) ? value.join(' ') : String(value ?? ''); +const unquote = (value) => String(value).replace(/^(["'])(.*)\1$/, '$2'); +let sdkRoots; + +function installedSDKItem(type, name) { + if (process.platform !== 'darwin') return false; + if (!sdkRoots) sdkRoots = ['macosx', 'iphoneos', 'appletvos'].flatMap((sdk) => { + try { + const root = execFileSync('/usr/bin/xcrun', ['--sdk', sdk, '--show-sdk-path'], + { encoding: 'utf8', timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'] }).trim(); + return root ? [root] : []; + } catch { return []; } + }); + return sdkRoots.some((root) => type === 'frameworks' + ? fs.existsSync(path.join(root, 'System/Library/Frameworks', name + '.framework')) + : ['.tbd', '.dylib'].some((ext) => fs.existsSync(path.join(root, 'usr/lib', 'lib' + name + ext)))); +} + +function words(value) { + return (scalar(value).match(/(?:[^\s"']|"(?:\\.|[^"\\])*"|'[^']*')+/g) || []).map(unquote); +} + +function expand(value, settings) { + let result = scalar(value); + for (let i = 0; i < 10; i++) { + const next = result.replace(/\$\(([^)]+)\)|\$\{([^}]+)\}/g, (original, a, b) => { + const [key, modifier] = (a || b).split(':'); + if (!(key in settings)) return original; + const resolved = scalar(settings[key]); + return modifier === 'rfc1034identifier' ? resolved.replace(/[^A-Za-z0-9.-]/g, '-') : resolved; + }); + if (next === result || next.length > 1024 * 1024) break; + result = next; + } + return unquote(result.trim()); +} + +function apply(settings, key, value, context = {}) { + const name = key.split('[')[0].trim(); + for (const condition of key.matchAll(/\[([^=]+)=([^\]]+)\]/g)) { + const actual = condition[1] === 'config' ? context.configuration : condition[1] === 'sdk' ? context.sdk : null; + if (actual == null) continue; + const pattern = condition[2].replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.'); + if (!new RegExp('^' + pattern + '$').test(actual)) return; + } + const previous = scalar(settings[name]); + settings[name] = Array.isArray(value) + ? value.flatMap((item) => /^\$\(inherited\)$|^\$\{inherited\}$/.test(item) ? words(previous) : [item]) + : scalar(value).replace(/\$\(inherited\)|\$\{inherited\}/g, previous); +} + +function assignments(contents, settings = {}, { file = '', context = {}, baseline = false, seen = new Set() } = {}) { + for (const line of contents.replace(/\\\r?\n/g, ' ').split(/\r?\n/)) { + const include = /^\s*#include\??\s*["<]([^">]+)[">]/.exec(line); + if (include && file && (!baseline || path.basename(include[1]) === 'CoreOF.xcconfig')) { + const included = path.resolve(path.dirname(file), expand(include[1], settings)); + if (!seen.has(included) && seen.size < 32) { + seen.add(included); + assignments(text(included), settings, { file: included, context, baseline, seen }); + } + continue; + } + const match = /^\s*([A-Za-z_][A-Za-z0-9_]*(?:\s*\[[^\]]+\])*)\s*(\+=|:=|\?=|=)\s*(.*)$/.exec(line); + if (!match) continue; + const key = match[1].trim(); + // Comments begin outside quoted strings; a # in a quoted define remains data. + const value = (match[3].match(/(?:"(?:\\.|[^"\\])*"|'[^']*'|[^#])*/)?.[0] || '').replace(/\s+\/\/.*$/, '').trim(); + if (match[2] === '?=' && key in settings) continue; + const assigned = match[2] === '+=' ? scalar(settings[key]) + ' ' + value : value; + apply(settings, key, assigned.trim(), context); + } + return settings; +} + +function propertyList(file) { + const contents = text(file).replace(/^\uFEFF/, ''); + try { return JSON.parse(contents); } catch { /* Xcode saves OpenStep; plutil reads it without running the project. */ } + if (process.platform === 'darwin' && contents) { + try { + return JSON.parse(execFileSync('/usr/bin/plutil', ['-convert', 'json', '-o', '-', '--', file], + { encoding: 'utf8', timeout: 5000, maxBuffer: 32 * 1024 * 1024, stdio: ['ignore', 'pipe', 'ignore'] })); + } catch { /* Metadata fallback below still reads xcconfig / plist values. */ } + } + return null; +} + +function plistString(file, key) { + if (!file || !fs.existsSync(file)) return ''; + const json = propertyList(file); + if (json && typeof json[key] === 'string') return json[key]; + const xml = text(file); + const match = new RegExp('\\s*' + key + '\\s*\\s*([\\s\\S]*?)').exec(xml); + if (match) return match[1].replace(/&#(?:x([0-9a-f]+)|(\d+));/gi, (original, hex, decimal) => { + const code = parseInt(hex || decimal, hex ? 16 : 10); + return code <= 0x10ffff ? String.fromCodePoint(code) : original; + }).replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, "'").replace(/&/g, '&'); + if (process.platform === 'darwin') { + try { return execFileSync('/usr/bin/plutil', ['-extract', key, 'raw', '-o', '-', '--', file], + { encoding: 'utf8', timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'] }).trim(); } catch { /* Absent key. */ } + } + return ''; +} + +function projectFile(folder) { + const expected = path.join(folder, path.basename(folder) + '.xcodeproj', 'project.pbxproj'); + if (fs.existsSync(expected)) return expected; + try { + const projects = fs.readdirSync(folder).filter((name) => name.endsWith('.xcodeproj')).sort(); + if (projects.length === 1) return path.join(folder, projects[0], 'project.pbxproj'); + } catch { /* Not an existing project. */ } + return ''; +} + +function configurations(project) { + const objects = project?.objects || {}; + const root = objects[project?.rootObject] || {}; + const result = []; + for (const targetId of root.targets || []) { + const target = objects[targetId]; + if (target?.productType !== 'com.apple.product-type.application') continue; + const list = objects[target.buildConfigurationList]?.buildConfigurations || []; + const ordered = [...list].sort((a, b) => (objects[a]?.name === 'Release' ? -1 : objects[b]?.name === 'Release' ? 1 : 0)); + for (const id of ordered) if (objects[id]) result.push({ id, targetId, target, configuration: objects[id], root }); + } + return result; +} + +function configFile(folder, objects, reference, settings) { + const ref = objects[reference]; + if (!ref) return path.join(folder, 'Project.xcconfig'); + const filename = expand(ref.path || ref.name || 'Project.xcconfig', settings); + if (path.isAbsolute(filename) || ref.sourceTree === 'SOURCE_ROOT' || fs.existsSync(path.resolve(folder, filename))) return path.resolve(folder, filename); + const main = Object.values(objects).find((object) => object.isa === 'PBXProject')?.mainGroup; + const pending = [[main, folder]], seen = new Set(); + while (pending.length) { + const [id, base] = pending.pop(); + if (seen.has(id)) continue; + seen.add(id); + for (const childId of objects[id]?.children || []) { + if (childId === reference) return path.resolve(base, filename); + const child = objects[childId]; + if (child?.isa === 'PBXGroup') pending.push([childId, path.resolve(child.sourceTree === 'SOURCE_ROOT' ? folder : base, expand(child.path || '', settings))]); + } + } + return path.resolve(folder, filename); +} + +function effectiveSettings(folder, project, entry, baseline = null, platform = '') { + const objects = project.objects; + const context = { configuration: entry.configuration.name, + sdk: platform === 'ios' ? 'iphoneos' : platform === 'tvos' ? 'appletvos' : 'macosx' }; + const settings = { SRCROOT: folder, PROJECT_DIR: folder, TARGET_NAME: entry.target.name || path.basename(folder), + PRODUCT_NAME: entry.target.productName || entry.target.name || path.basename(folder), CONFIGURATION: context.configuration }; + const rootList = objects[entry.root.buildConfigurationList]?.buildConfigurations || []; + const rootId = rootList.find((id) => objects[id]?.name === context.configuration); + const rootConfig = objects[rootId]; + if (rootConfig?.baseConfigurationReference) { + const rootFile = configFile(folder, objects, rootConfig.baseConfigurationReference, settings); + assignments(text(rootFile), settings, { file: rootFile, context, baseline: !!baseline }); + } + const rootValues = baseline ? baseline.configurations?.[rootId]?.settings || {} : rootConfig?.buildSettings || {}; + for (const [key, value] of Object.entries(rootValues)) apply(settings, key, value, context); + const file = baseline ? path.join(folder, 'Project.xcconfig') : configFile(folder, objects, entry.configuration.baseConfigurationReference, settings); + const contents = baseline ? baseline.files?.['Project.xcconfig'] || '' : text(file); + assignments(contents, settings, { file, context, baseline: !!baseline }); + let values = entry.configuration.buildSettings || {}; + if (baseline) { + values = baseline.configurations?.[entry.id]?.settings + || Object.values(baseline.configurations || {}).find((config) => config.scope === `PBXNativeTarget/${entry.target.name}/${context.configuration}`)?.settings || {}; + } + for (const [key, value] of Object.entries(values)) apply(settings, key, value, context); + return settings; +} + +function sdkReference(ref) { + const file = String(ref?.path || ref?.name || '').replaceAll('\\', '/'); + const sdk = ref?.sourceTree === 'SDKROOT' || /(?:\$\(SDKROOT\)|\$\{SDKROOT\}|System\/Library\/Frameworks|\/usr\/lib\/)/.test(file); + if (!sdk) return null; + const framework = /(?:^|\/)([^/]+)\.framework(?:\/.*)?$/.exec(file); + if (framework) return { type: 'frameworks', name: framework[1] }; + const library = /(?:^|\/)lib([^/]+)\.(?:tbd|dylib)$/.exec(file); + return library ? { type: 'libs', name: library[1] } : null; +} + +function linkedSDK(project, target) { + const objects = project?.objects || {}; + const found = { frameworks: [], libs: [] }; + for (const id of target?.buildPhases || []) { + if (objects[id]?.isa !== 'PBXFrameworksBuildPhase') continue; + for (const buildId of objects[id].files || []) { + const ref = sdkReference(objects[objects[buildId]?.fileRef]); + if (ref) found[ref.type].push(ref.name); + } + } + return found; +} + +function cleanLibrary(value) { return path.basename(unquote(unquote(value).replace(/^-l/, ''))).replace(/^lib/, '').replace(/\.(?:tbd|dylib)$/, ''); } +function cleanFramework(value) { return path.basename(unquote(value)).replace(/\.framework$/, ''); } +function defineWords(value, settings) { + const values = Array.isArray(value) ? value.flatMap((part) => words(expand(part, settings))) : words(expand(value, settings)); + return values.filter((define) => /^[A-Za-z_][A-Za-z0-9_]*(?:=.*)?$/.test(define)); +} + +function cflagDefines(value, settings) { + const flags = words(expand(value, settings)), found = []; + for (let i = 0; i < flags.length; i++) { + if (flags[i] === '-D' && flags[i + 1]) found.push(flags[++i]); + else if (flags[i].startsWith('-D')) found.push(flags[i].slice(2)); + } + return found; +} + +function readProjectSettings(folder, { platforms = [], ofPath = '' } = {}) { + const make = assignments(text(path.join(folder, 'config.make'))); + const result = { version: '', build: '', bundleId: '', defines: words(make.PROJECT_DEFINES), frameworks: [], libs: [] }; + for (const item of words(make.PROJECT_FRAMEWORKS)) { + if (/^-l|^lib|\.(?:tbd|dylib)$/.test(item)) result.libs.push(cleanLibrary(item)); + else result.frameworks.push(cleanFramework(item)); + } + result.libs.push(...words(make.PROJECT_SYSTEM_LIBS).map(cleanLibrary)); + const native = (!platforms.length || platforms.some((p) => applePlatforms.has(p))) ? propertyList(projectFile(folder)) : null; + const entries = configurations(native); + if (entries.length) { + const state = propertyList(path.join(folder, '.ofprojectgenerator/apple-settings.json'))?.platforms || {}; + const platform = platforms.find((p) => applePlatforms.has(p)) || Object.keys(state)[0] || 'osx'; + const effective = new Map(entries.map((entry) => [entry.id, effectiveSettings(folder, native, entry, null, platform)])); + const sdk = platform === 'ios' ? 'iphoneos' : platform === 'tvos' ? 'appletvos' : 'macosx'; + const score = (entry) => { + const values = effective.get(entry.id); + return scalar(values.SDKROOT) === sdk ? 3 : scalar(values.SUPPORTED_PLATFORMS).includes(sdk) ? 2 : 0; + }; + entries.sort((a, b) => score(b) - score(a)); + let baseline = state[platform] || Object.values(state)[0] || {}; + const templateName = platform === 'tvos' ? 'tvOS' : platform; + const template = ofPath ? propertyList(path.join(ofPath, 'scripts/templates', templateName, 'emptyExample.xcodeproj/project.pbxproj')) : null; + if (!baseline.files && template) { + const defaults = configurations(template); + baseline = { files: { 'Project.xcconfig': text(path.join(ofPath, 'scripts/templates', templateName, 'Project.xcconfig')).replaceAll('../../..', ofPath) }, configurations: {} }; + for (const entry of entries) { + const match = defaults.find((candidate) => candidate.id === entry.id) + || defaults.find((candidate) => candidate.configuration.name === entry.configuration.name); + if (match) baseline.configurations[entry.id] = { settings: match.configuration.buildSettings || {} }; + } + } + const templateSDK = { frameworks: [], libs: [] }; + for (const entry of configurations(template)) { + const linked = linkedSDK(template, entry.target); + templateSDK.frameworks.push(...linked.frameworks); templateSDK.libs.push(...linked.libs); + } + for (const [index, entry] of entries.entries()) { + const settings = effective.get(entry.id); + const defaults = effectiveSettings(folder, native, entry, baseline, platform); + if (index === 0) { + const infoFile = path.resolve(folder, expand(settings.INFOPLIST_FILE || (fs.existsSync(path.join(folder, 'ofxiOS-Info.plist')) ? 'ofxiOS-Info.plist' : 'openFrameworks-Info.plist'), settings)); + result.version = expand(plistString(infoFile, 'CFBundleShortVersionString') || settings.MARKETING_VERSION, settings); + result.build = expand(plistString(infoFile, 'CFBundleVersion') || settings.CURRENT_PROJECT_VERSION, settings); + result.bundleId = expand(plistString(infoFile, 'CFBundleIdentifier') || settings.PRODUCT_BUNDLE_IDENTIFIER, settings); + } + if (entry.targetId !== entries[0].targetId) continue; + const generated = defineWords(defaults.GCC_PREPROCESSOR_DEFINITIONS, defaults); + for (const define of defineWords(settings.GCC_PREPROCESSOR_DEFINITIONS, settings)) if (!generated.includes(define)) result.defines.push(define); + for (const key of ['OTHER_CFLAGS', 'OTHER_CPLUSPLUSFLAGS']) { + const generatedDefines = cflagDefines(defaults[key], defaults); + for (const define of cflagDefines(settings[key], settings)) if (!generatedDefines.includes(define)) result.defines.push(define); + } + const linked = linkedSDK(native, entry.target); + const recorded = baseline.systemReferences?.[entry.targetId]?.references || {}; + const isSDK = (type, name) => linked[type].includes(name) || result[type].includes(name) || installedSDKItem(type, name); + const generatedSDK = (type, name) => templateSDK[type].includes(name) || !!recorded[`${type}:${name}`]; + for (const type of ['frameworks', 'libs']) { + for (const name of linked[type]) if (!templateSDK[type].includes(name) && !recorded[`${type}:${name}`]) result[type].push(name); + } + const flags = words(expand(settings.OTHER_LDFLAGS, settings)); + const defaultFlags = words(expand(defaults.OTHER_LDFLAGS, defaults)); + for (let i = 0; i < flags.length; i++) { + const flag = flags[i]; + if (flag === '-framework' || flag === '-weak_framework') { + const name = flags[++i]; + if (name && !defaultFlags.includes(name) && !generatedSDK('frameworks', name) && isSDK('frameworks', name)) result.frameworks.push(cleanFramework(name)); + } else if (flag === '-l' && flags[i + 1]) { + const name = cleanLibrary(flags[++i]); + if (!defaultFlags.includes(name) && !generatedSDK('libs', name) && isSDK('libs', name)) result.libs.push(name); + } else if (/^-l.+/.test(flag) && !defaultFlags.includes(flag)) { + const name = cleanLibrary(flag); + if (!generatedSDK('libs', name) && isSDK('libs', name)) result.libs.push(name); + } + else if (/^(?:\/|\$\(?SDKROOT).*\/lib[^/]+\.(?:tbd|dylib)$/.test(flag) && !defaultFlags.includes(flag)) result.libs.push(cleanLibrary(flag)); + } + } + } + const xcconfig = assignments(text(path.join(folder, 'Project.xcconfig'))); + const appConfig = assignments(text(path.join(folder, 'App.xcconfig')), { ...xcconfig }); + const cmake = text(path.join(folder, 'CMakeLists.txt')); + const gradle = text(path.join(folder, 'ofApp/build.gradle')); + const last = (contents, regex) => [...contents.matchAll(regex)].at(-1)?.[1] || ''; + result.version ||= unquote(make.APP_VERSION || last(cmake, /^\s*set\(\s*APP_VERSION\s+"?([0-9.]+)/gm) || appConfig.MARKETING_VERSION || last(gradle, /^\s*versionName\s+['"]([^'"]+)/gm)); + result.build ||= unquote(make.APP_BUILD || last(cmake, /^\s*set\(\s*APP_BUILD\s+"?([0-9]+)/gm) || appConfig.CURRENT_PROJECT_VERSION || last(gradle, /^\s*versionCode\s+([0-9]+)/gm)); + result.bundleId ||= unquote(make.APP_BUNDLE_ID || last(cmake, /^\s*set\(\s*APP_BUNDLE_ID\s+"?([^\s")]+)/gm) || appConfig.PRODUCT_BUNDLE_IDENTIFIER || last(gradle, /^\s*applicationId\s+['"]([^'"]+)/gm)); + for (const key of ['version', 'build', 'bundleId']) if (result[key].includes('$')) result[key] = ''; + result.defines = unique(result.defines.filter((define) => !define.includes('$'))); + result.frameworks = unique(result.frameworks); result.libs = unique(result.libs); + return result; +} + +module.exports = { readProjectSettings }; diff --git a/scripts/linux/test_cmdline.sh b/scripts/linux/test_cmdline.sh index 8a32dedc..d575e63d 100755 --- a/scripts/linux/test_cmdline.sh +++ b/scripts/linux/test_cmdline.sh @@ -48,4 +48,10 @@ fi echo "Test command line arguments" "${CURRENT_DIR}/../test_cmdline_args.sh" ./projectGenerator ../../../../ linux64 +echo "Test preserve Apple settings across project updates" +python3 "${CURRENT_DIR}/../test_xcode_settings.py" ./projectGenerator ../../../../ + +echo "Test existing-project GUI settings and update arguments" +node --test "${CURRENT_DIR}/../test_gui_project_settings.cjs" + echo "Successful projectGenerator tests for [linux64]"; diff --git a/scripts/osx/test_cmdline.sh b/scripts/osx/test_cmdline.sh index d0e66221..95329f11 100755 --- a/scripts/osx/test_cmdline.sh +++ b/scripts/osx/test_cmdline.sh @@ -46,6 +46,12 @@ echo "Test 3: addon defines / cflags / sources - success" echo "Test 4: command line arguments" "${CURRENT_DIR}/../test_cmdline_args.sh" ./projectGenerator "${PG_DIR}/../.." osx || exit 1 +echo "Test 5: preserve Apple settings across project updates" +python3 "${CURRENT_DIR}/../test_xcode_settings.py" ./projectGenerator "${PG_DIR}/../.." || exit 1 + +echo "Test 6: existing-project GUI settings and update arguments" +node --test "${CURRENT_DIR}/../test_gui_project_settings.cjs" || exit 1 + # echo "test out of folder -o [vs]"; # rm -rf ../../../../../pg2 # mkdir -p ../../../../../pg2 diff --git a/scripts/test_gui_project_settings.cjs b/scripts/test_gui_project_settings.cjs new file mode 100644 index 00000000..5d3af993 --- /dev/null +++ b/scripts/test_gui_project_settings.cjs @@ -0,0 +1,183 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const vm = require('node:vm'); +const { execFileSync } = require('node:child_process'); +const { readProjectSettings } = require('../frontend/project-settings'); + +function fixture(t) { + const folder = fs.mkdtempSync(path.join(os.tmpdir(), 'pg-gui-settings-')); + t.after(() => fs.rmSync(folder, { recursive: true, force: true })); + const write = (name, value) => { const file = path.join(folder, name); fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, value); }; + const defaults = { rootDebug: { scope: 'PBXProject//Debug', settings: {} }, rootRelease: { scope: 'PBXProject//Release', settings: {} }, + debug: { scope: 'PBXNativeTarget/demo/Debug', settings: { GCC_PREPROCESSOR_DEFINITIONS: ['$(inherited)', 'ADDON_GENERATED=1'] } }, + release: { scope: 'PBXNativeTarget/demo/Release', settings: { GCC_PREPROCESSOR_DEFINITIONS: ['$(inherited)', 'ADDON_GENERATED=1'] } } }; + const xcconfig = 'MARKETING_VERSION = 1.2\nCURRENT_PROJECT_VERSION = 7\nPRODUCT_BUNDLE_IDENTIFIER = com.example.from_config\nUSER_PREPROCESSOR_DEFINITIONS = CORE_DEFAULT=1\nGCC_PREPROCESSOR_DEFINITIONS = $(inherited) $(USER_PREPROCESSOR_DEFINITIONS)\n#include? "App.xcconfig"\n'; + const project = { rootObject: 'project', objects: { + project: { isa: 'PBXProject', targets: ['app'], buildConfigurationList: 'projectConfigs' }, + projectConfigs: { isa: 'XCConfigurationList', buildConfigurations: ['rootDebug', 'rootRelease'] }, + rootDebug: { isa: 'XCBuildConfiguration', name: 'Debug', buildSettings: { GCC_PREPROCESSOR_DEFINITIONS: ['ROOT_CUSTOM=1'] } }, + rootRelease: { isa: 'XCBuildConfiguration', name: 'Release', buildSettings: { GCC_PREPROCESSOR_DEFINITIONS: ['ROOT_CUSTOM=1'], MARKETING_VERSION: '9.9' } }, + app: { isa: 'PBXNativeTarget', name: 'demo', productType: 'com.apple.product-type.application', buildConfigurationList: 'appConfigs', buildPhases: ['frameworks'] }, + appConfigs: { isa: 'XCConfigurationList', buildConfigurations: ['debug', 'release'] }, + configFile: { isa: 'PBXFileReference', path: 'Project.xcconfig', sourceTree: '' }, + frameworks: { isa: 'PBXFrameworksBuildPhase', files: ['cocoaBuild', 'sqliteBuild', 'bluetoothBuild', 'addonBuild'] }, + cocoaBuild: { isa: 'PBXBuildFile', fileRef: 'cocoa' }, cocoa: { isa: 'PBXFileReference', path: 'System/Library/Frameworks/Cocoa.framework', sourceTree: 'SDKROOT' }, + sqliteBuild: { isa: 'PBXBuildFile', fileRef: 'sqlite' }, sqlite: { isa: 'PBXFileReference', path: 'usr/lib/libsqlite3.tbd', sourceTree: 'SDKROOT' }, + bluetoothBuild: { isa: 'PBXBuildFile', fileRef: 'bluetooth' }, bluetooth: { isa: 'PBXFileReference', path: 'System/Library/Frameworks/CoreBluetooth.framework', sourceTree: 'SDKROOT' }, + addonBuild: { isa: 'PBXBuildFile', fileRef: 'addon' }, addon: { isa: 'PBXFileReference', path: 'local_addons/ThirdParty.framework', sourceTree: 'SOURCE_ROOT' }, + } }; + for (const [id, version, build, define] of [['debug', '0.2', '3', 'DEBUG_CUSTOM=1'], ['release', '0.1', '2', 'RELEASE_CUSTOM=1']]) { + project.objects[id] = { isa: 'XCBuildConfiguration', name: id === 'debug' ? 'Debug' : 'Release', baseConfigurationReference: 'configFile', + buildSettings: { MARKETING_VERSION: version, CURRENT_PROJECT_VERSION: build, PRODUCT_BUNDLE_IDENTIFIER: 'com.example.native', INFOPLIST_FILE: 'Info.plist', + GCC_PREPROCESSOR_DEFINITIONS: ['$(inherited)', 'ADDON_GENERATED=1', define] } }; + } + write('config.make', 'APP_VERSION = 1.0\nAPP_BUILD = 1\nAPP_BUNDLE_ID = com.example.stale\nPROJECT_DEFINES = MAKE_ONLY=1\nPROJECT_DEFINES += MAKE_APPEND=1 # comment\nPROJECT_FRAMEWORKS = Security.framework\nPROJECT_SYSTEM_LIBS = libz.tbd\n'); + write('Project.xcconfig', xcconfig); + write('App.xcconfig', 'USER_PREPROCESSOR_DEFINITIONS = CORE_DEFAULT=1 APP_CUSTOM=1\n'); + write('Info.plist', 'CFBundleShortVersionString$(MARKETING_VERSION)CFBundleVersion$(CURRENT_PROJECT_VERSION)CFBundleIdentifier$(PRODUCT_BUNDLE_IDENTIFIER)CustomDate2025-01-01T00:00:00Z'); + // A renamed .xcodeproj must be found even when it does not match the folder name. + const projectPath = path.join(folder, 'Renamed.xcodeproj/project.pbxproj'); + write('Renamed.xcodeproj/project.pbxproj', JSON.stringify(project)); + write('.ofprojectgenerator/apple-settings.json', JSON.stringify({ format: 1, platforms: { osx: { + files: { 'Project.xcconfig': xcconfig }, configurations: defaults, + systemReferences: { app: { scope: 'demo', references: { 'frameworks:Cocoa': {} } } }, + } } })); + return { folder, write, project, projectPath }; +} + +test('existing Xcode values populate the fields ahead of stale config.make values', (t) => { + const f = fixture(t); + const values = readProjectSettings(f.folder, { platforms: ['osx'] }); + assert.equal(values.version, '0.1'); assert.equal(values.build, '2'); assert.equal(values.bundleId, 'com.example.native'); + assert.deepEqual(new Set(values.defines), new Set(['MAKE_ONLY=1', 'MAKE_APPEND=1', 'ROOT_CUSTOM=1', 'APP_CUSTOM=1', 'DEBUG_CUSTOM=1', 'RELEASE_CUSTOM=1'])); + assert.deepEqual(new Set(values.frameworks), new Set(['Security', 'CoreBluetooth'])); + assert.deepEqual(new Set(values.libs), new Set(['z', 'sqlite3'])); +}); + +test('target xcconfig and App.xcconfig override project-level defaults', (t) => { + const f = fixture(t); + delete f.project.objects.release.buildSettings.MARKETING_VERSION; + delete f.project.objects.release.buildSettings.CURRENT_PROJECT_VERSION; + f.write('App.xcconfig', 'MARKETING_VERSION = 0.9\nCURRENT_PROJECT_VERSION = 12\n'); + f.write('Renamed.xcodeproj/project.pbxproj', JSON.stringify(f.project)); + const values = readProjectSettings(f.folder, { platforms: ['osx'] }); + assert.equal(values.version, '0.9'); assert.equal(values.build, '12'); +}); + +test('literal Info.plist values and binary/OpenStep projects are read without rewriting files', { skip: process.platform !== 'darwin' }, (t) => { + const f = fixture(t); + f.write('Info.plist', 'CFBundleShortVersionString0.4CFBundleVersion8CFBundleIdentifiercom.example.literalCustomDate2025-01-01T00:00:00Z'); + const openstep = (value) => Array.isArray(value) ? '(' + value.map(openstep).join(',') + ')' + : value && typeof value === 'object' ? '{' + Object.entries(value).map(([key, item]) => JSON.stringify(key) + '=' + openstep(item) + ';').join('\n') + '}' : JSON.stringify(String(value)); + f.write('Renamed.xcodeproj/project.pbxproj', '// !$*UTF8*$!\n' + openstep(f.project)); + const info = path.join(f.folder, 'Info.plist'); + execFileSync('/usr/bin/plutil', ['-convert', 'binary1', '--', info]); + const before = fs.readFileSync(info); + const values = readProjectSettings(f.folder, { platforms: ['osx'] }); + assert.equal(values.version, '0.4'); assert.equal(values.build, '8'); assert.equal(values.bundleId, 'com.example.literal'); + assert.deepEqual(fs.readFileSync(info), before); +}); + +test('make projects load their libraries, defines and bundle ID without an Xcode project', (t) => { + const f = fixture(t); + const values = readProjectSettings(f.folder, { platforms: ['linux64'] }); + assert.equal(values.version, '1.0'); assert.equal(values.build, '1'); assert.equal(values.bundleId, 'com.example.stale'); + assert.deepEqual(values.defines, ['MAKE_ONLY=1', 'MAKE_APPEND=1']); + assert.deepEqual(values.frameworks, ['Security']); assert.deepEqual(values.libs, ['z']); +}); + +test('metadata follows the app target matching the selected Apple platform', (t) => { + const f = fixture(t); + f.project.objects.release.buildSettings.SDKROOT = 'macosx'; + f.project.objects.project.targets.push('iosApp'); + f.project.objects.iosApp = { ...f.project.objects.app, name: 'iosApp', buildConfigurationList: 'iosConfigs' }; + f.project.objects.iosConfigs = { isa: 'XCConfigurationList', buildConfigurations: ['iosRelease'] }; + f.project.objects.iosRelease = { ...f.project.objects.release, buildSettings: { ...f.project.objects.release.buildSettings, + SDKROOT: 'iphoneos', MARKETING_VERSION: '0.8', CURRENT_PROJECT_VERSION: '20', PRODUCT_BUNDLE_IDENTIFIER: 'com.example.ios' } }; + f.write('Renamed.xcodeproj/project.pbxproj', JSON.stringify(f.project)); + assert.equal(readProjectSettings(f.folder, { platforms: ['osx'] }).version, '0.1'); + const ios = readProjectSettings(f.folder, { platforms: ['ios'] }); + assert.equal(ios.version, '0.8'); assert.equal(ios.build, '20'); assert.equal(ios.bundleId, 'com.example.ios'); +}); + +test('separate -D arguments load custom defines while generated addon flags stay excluded', (t) => { + const f = fixture(t); + f.project.objects.release.buildSettings.OTHER_CFLAGS = ['-D', 'GENERATED=1', '-D', 'USER_CFLAG=1']; + f.write('Renamed.xcodeproj/project.pbxproj', JSON.stringify(f.project)); + const file = path.join(f.folder, '.ofprojectgenerator/apple-settings.json'); + const state = JSON.parse(fs.readFileSync(file)); + state.platforms.osx.configurations.release.settings.OTHER_CFLAGS = ['-D', 'GENERATED=1']; + fs.writeFileSync(file, JSON.stringify(state)); + const values = readProjectSettings(f.folder, { platforms: ['osx'] }); + assert.ok(values.defines.includes('USER_CFLAG=1')); assert.ok(!values.defines.includes('GENERATED=1')); +}); + +test('renderer populates fields, keeps unedited values implicit, and sends deliberate edits', () => { + const handlers = {}, elements = new Map(), sent = []; + const element = (selector) => { + if (elements.has(selector)) return elements.get(selector); + const state = { value: '', dropdownValue: 'default', label: '', length: 0, + val(value) { if (value === undefined) return this.value; this.value = value; return this; }, + text(value) { if (value === undefined) return this.label; this.label = value; return this; }, + dropdown(action, value) { if (action === 'get value') return this.dropdownValue; if (value !== undefined) this.dropdownValue = value; return this; }, + css() { return selector === '#systemFrameworksField' ? 'flex' : 'none'; }, + hide() { return this; }, show() { return this; }, toggle() { return this; }, oneTimeTooltip() { throw new Error('Unexpected form validation error'); }, + }; + elements.set(selector, state); return state; + }; + const ipc = { on(channel, handler) { handlers[channel] = handler; }, send(channel, data) { sent.push({ channel, data }); }, path, fs }; + const context = vm.createContext({ window: { ipcWrapper: ipc }, document: {}, console, setTimeout, clearTimeout, $: element }); + vm.runInContext(fs.readFileSync(path.join(__dirname, '../frontend/app.js'), 'utf8'), context); + vm.runInContext('getPlatformList = () => ["osx"]; openConsoleForOperation = () => {};', context); + element('#projectName').val('demo'); element('#projectPath').val('/tmp'); + handlers.setProjectSettings(null, { projectName: 'demo', projectPath: '/tmp', version: '0.1', build: '2', bundleId: 'com.example.demo', defines: ['CUSTOM=1'], frameworks: ['CoreBluetooth'], libs: ['sqlite3'] }); + assert.equal(element('#appVersion').val(), '0.1'); assert.equal(element('#appBuild').val(), '2'); + assert.equal(element('#bundleId').val(), 'com.example.demo'); assert.equal(element('#customDefines').val(), 'CUSTOM=1'); + assert.equal(element('#systemLibs').val(), 'sqlite3'); assert.equal(element('#appVersionNote').text(), ''); + vm.runInContext('generate()', context); + const first = sent.findLast((entry) => entry.channel === 'generate').data; + assert.equal(first.appVersion, ''); assert.equal(first.appBuild, ''); assert.equal(first.appBundleId, ''); + assert.equal(first.defines, null); assert.equal(first.systemFrameworks, null); assert.equal(first.systemLibs, null); + element('#appVersion').val('0.2'); element('#customDefines').val(''); element('#systemLibs').val('z'); + vm.runInContext('generate()', context); + const edited = sent.findLast((entry) => entry.channel === 'generate').data; + assert.equal(edited.appVersion, '0.2'); assert.equal(edited.appBuild, ''); assert.equal(edited.defines, ''); + assert.deepEqual(Array.from(edited.systemLibs), ['z']); + handlers.setProjectSettings(null, { projectName: 'demo', projectPath: '/tmp', preserveEdits: true, + version: '0.3', build: '4', bundleId: 'com.example.refreshed', defines: ['UPDATED=1'], frameworks: ['Security'], libs: ['c++'] }); + assert.equal(element('#appVersion').val(), '0.2'); assert.equal(element('#appBuild').val(), '4'); + assert.equal(element('#customDefines').val(), ''); assert.equal(element('#systemLibs').val(), 'z'); + assert.equal(element('#systemFrameworks').val(), 'Security'); + vm.runInContext('generate()', context); + const refreshed = sent.findLast((entry) => entry.channel === 'generate').data; + assert.equal(refreshed.appVersion, '0.2'); assert.equal(refreshed.appBuild, ''); + assert.equal(refreshed.defines, ''); assert.equal(refreshed.systemFrameworks, null); + // A late response from a previously selected project cannot replace the current fields. + handlers.setProjectSettings(null, { projectName: 'other', projectPath: '/tmp', version: '99' }); + assert.equal(element('#appVersion').val(), '0.2'); + handlers.setProjectSettings(null, { projectName: 'demo', projectPath: '/tmp', defines: ['CUSTOM=1', 'OF_USE_ANGLE=1'] }); + element('#rendererDropdown').dropdownValue = 'dawn'; + vm.runInContext('generate()', context); + const renderer = sent.findLast((entry) => entry.channel === 'generate').data.defines; + assert.ok(renderer.includes('OF_USE_DAWN=1')); assert.ok(!renderer.includes('OF_USE_ANGLE=1')); + vm.runInContext('clearProjectSettings()', context); + assert.equal(element('#customDefines').val(), ''); assert.equal(element('#bundleId').val(), ''); +}); + +test('main process omits implicit overrides and passes an explicitly empty defines field', () => { + const contents = fs.readFileSync(path.join(__dirname, '../frontend/index.js'), 'utf8'); + const start = contents.indexOf('function generateFunction('); + const end = contents.indexOf("ipcMain.on('generate'", start); + let args; + const context = vm.createContext({ path, runPG(value) { args = value; } }); + vm.runInContext(contents.slice(start, end), context); + context.request = { projectName: 'demo', projectPath: '/tmp', platformList: ['osx'], ofPath: '/of', defines: null, appVersion: '', appBuild: '', appBundleId: '', systemLibs: null, systemFrameworks: null }; + vm.runInContext('generateFunction({}, request)', context); + assert.ok(!args.some((arg) => /^(--defines|--app-version|--app-build|--bundle-id|--system-libs|-f)/.test(arg))); + context.request.defines = ''; context.request.systemLibs = []; + vm.runInContext('generateFunction({}, request)', context); + assert.ok(args.includes('--defines=')); assert.ok(args.includes('--system-libs=')); +}); diff --git a/scripts/test_xcode_settings.py b/scripts/test_xcode_settings.py new file mode 100644 index 00000000..b0d5f8a8 --- /dev/null +++ b/scripts/test_xcode_settings.py @@ -0,0 +1,317 @@ +#!/usr/bin/env python3 +"""Generate, customize, upgrade and update Apple projects in an isolated OF fixture. + +Usage: test_xcode_settings.py +""" +import datetime +import json +import os +import pathlib +import plistlib +import shutil +import subprocess +import sys +import tempfile +import uuid + + +def read_json(path): + return json.loads(path.read_text()) + + +def write_json(path, value): + path.write_text(json.dumps(value, indent=2) + "\n") + + +def read_plist(path): + return plistlib.loads(path.read_bytes()) + + +def write_plist(path, value, binary=False): + path.write_bytes(plistlib.dumps(value, fmt=plistlib.FMT_BINARY if binary else plistlib.FMT_XML)) + + +def configs(project): + return {key: obj for key, obj in project["objects"].items() if obj.get("isa") == "XCBuildConfiguration"} + + +def linked_sdk(project, target_id): + objects = project["objects"] + files = {} + for phase_id in objects[target_id]["buildPhases"]: + phase = objects[phase_id] + if phase.get("isa") != "PBXFrameworksBuildPhase": + continue + for build_id in phase.get("files", []): + build = objects[build_id] + ref = objects.get(build.get("fileRef"), {}) + if ref.get("sourceTree") == "SDKROOT": + files[ref.get("path", ref.get("name", ""))] = build.get("settings", {}) + return files + + +def openstep(value): + if isinstance(value, dict): + return "{\n" + "\n".join(json.dumps(k) + " = " + openstep(v) + ";" for k, v in value.items()) + "\n}" + if isinstance(value, list): + return "(" + ",".join(openstep(v) for v in value) + ")" + return json.dumps(str(value)) + + +def run(pg, root, platform, project, *extra, success=True): + result = subprocess.run([str(pg), "-o" + str(root), "-p" + platform, *extra, str(project)], + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, + env={**os.environ, "TZ": "UTC0"}) + if (result.returncode == 0) != success: + raise AssertionError(result.stdout) + return result.stdout + + +def exercise(pg, root, platform): + print("testing [" + platform + "]", flush=True) + template = root / "scripts/templates" / platform + plist_name = "openFrameworks-Info.plist" if platform in ("osx", "macos") else "ofxiOS-Info.plist" + plist_template = template / plist_name + template_project = template / "emptyExample.xcodeproj/project.pbxproj" + + # Known defaults make this a real template upgrade test, rather than just another update. + defaults = read_plist(plist_template) + defaults["PGTemplateDefault"] = "before" + defaults["PGNested"] = {"unchanged": "before", "custom": "before"} + write_plist(plist_template, defaults) + config_template = template / "Project.xcconfig" + config_template.write_text(config_template.read_text() + "\nPG_TEMPLATE_DEFAULT = before\n") + pbx_defaults = read_json(template_project) + for obj in configs(pbx_defaults).values(): + obj.setdefault("buildSettings", {})["PG_TEMPLATE_DEFAULT"] = "before" + write_json(template_project, pbx_defaults) + + project = root / "apps" / ("settings_" + platform) + run(pg, root, platform, project) + pbx_path = project / (project.name + ".xcodeproj/project.pbxproj") + plist_path = project / plist_name + config_path = project / "Project.xcconfig" + state = project / ".ofprojectgenerator/apple-settings.json" + assert state.is_file(), "new projects must record a baseline" + workspace = project / (project.name + ".xcodeproj/project.xcworkspace/contents.xcworkspacedata") + workspace.parent.mkdir(parents=True, exist_ok=True) + workspace.write_text('\n') + template_workspace = template / "emptyExample.xcodeproj/project.xcworkspace/contents.xcworkspacedata" + template_workspace_before = template_workspace.read_bytes() if template_workspace.exists() else None + + settings = read_plist(plist_path) + settings["NSHighResolutionCapable"] = True + settings["NSCameraUsageDescription"] = "Camera access for my installation" + settings["PGNested"]["custom"] = "mine" + settings["PGCustomTypes"] = {"data": b"\x00\xff\x01", "date": datetime.datetime(2025, 1, 2), + "number": 42, "real": 1.25, "array": [True, "mine", 7]} + settings.pop("CFBundleSignature", None) + if platform == "ios": + settings["UISupportedInterfaceOrientations"] = ["UIInterfaceOrientationLandscapeLeft"] + write_plist(plist_path, settings) + + xcconfig = config_path.read_text().replace("HIGH_RESOLUTION_CAPABLE = NO", "HIGH_RESOLUTION_CAPABLE = YES") + if platform in ("osx", "macos"): + if "HIGH_RESOLUTION_CAPABLE = YES" not in xcconfig: + xcconfig += "\nHIGH_RESOLUTION_CAPABLE = YES\n" + xcconfig = xcconfig.replace("HIGH_RESOLUTION_CAPABLE = YES", + '#include? "Retina.xcconfig"\nHIGH_RESOLUTION_CAPABLE = YES') + (project / "Retina.xcconfig").write_text("HIGH_RESOLUTION_CAPABLE = NO\n") + xcconfig += '\n// My conditional setting\nMY_SETTING[sdk=iphoneos*][config=Debug] = one \\\n two\n#include? "Custom.xcconfig"\n' + config_path.write_text(xcconfig) + with config_path.open("a") as out: + out.write("OTHER_CFLAGS += -DMY_XCCONFIG_FLAG\nOTHER_LDFLAGS += -framework MySettingsFramework\n") + out.write("OTHER_LDFLAGS += -lsqlite3 -framework CoreBluetooth\n") + (project / "App.xcconfig").write_text("MY_APP_SETTING = stays\n") + (project / "Custom.xcconfig").write_text("MY_CUSTOM_SETTING = stays\n") + with (project / "config.make").open("a") as out: + out.write("\nPROJECT_DEFINES = PG_FROM_CONFIG_MAKE=1\n") + + existing = read_json(pbx_path) + for key, obj in configs(existing).items(): + build = obj.setdefault("buildSettings", {}) + build["DEVELOPMENT_TEAM"] = "TEAM_" + obj["name"] + build["INFOPLIST_KEY_NSHighResolutionCapable"] = "YES" + build["PG_USER_SETTING"] = obj["name"] + build["ARCHS"] = "arm64" + build["OTHER_CFLAGS"] = ["$(inherited)", "-DPG_USER_FLAG=1"] + build["OTHER_LDFLAGS"] = ["$(inherited)", "-framework", "MyCustomFramework"] + build["CLANG_CXX_LANGUAGE_STANDARD"] = "c++26" if obj["name"] == "Debug" else "c++11" + build["MACOSX_DEPLOYMENT_TARGET"] = "14.0" if obj["name"] == "Debug" else "10.9" + build["IPHONEOS_DEPLOYMENT_TARGET"] = "17.0" if obj["name"] == "Debug" else "8.0" + native_targets = [key for key, obj in existing["objects"].items() if obj.get("isa") == "PBXNativeTarget"] + sdk_target = native_targets[0] + sdk_phase = next(key for key in existing["objects"][sdk_target]["buildPhases"] if existing["objects"][key]["isa"] == "PBXFrameworksBuildPhase") + for config_id in existing["objects"][existing["objects"][sdk_target]["buildConfigurationList"]]["buildConfigurations"]: + existing["objects"][config_id]["buildSettings"]["OTHER_LDFLAGS"] += ["-lsqlite3", "-framework", "CoreBluetooth"] + for name in ("System/Library/Frameworks/CoreBluetooth.framework", "usr/lib/libsqlite3.tbd"): + file_id = uuid.uuid5(uuid.NAMESPACE_URL, name + "/file").hex.upper()[:24] + build_id = uuid.uuid5(uuid.NAMESPACE_URL, name + "/build").hex.upper()[:24] + existing["objects"][file_id] = {"isa": "PBXFileReference", "path": name, "sourceTree": "SDKROOT"} + existing["objects"][build_id] = {"isa": "PBXBuildFile", "fileRef": file_id, "settings": {"ATTRIBUTES": ["Weak"]}} + existing["objects"][build_id]["platformFilters"] = ["ios" if platform == "ios" else "macos"] + existing["objects"][sdk_phase]["files"].append(build_id) + root_object = existing["objects"][existing["rootObject"]] + attributes = root_object.setdefault("attributes", {}).setdefault("TargetAttributes", {}) + for key in native_targets: + attributes.setdefault(key, {}).update({"DevelopmentTeam": "MY_TEAM", "ProvisioningStyle": "Manual", + "SystemCapabilities": {"com.apple.Push": {"enabled": "1"}}}) + write_json(pbx_path, existing) + if (project / "of.entitlements").exists(): + entitlements = read_plist(project / "of.entitlements") + entitlements["com.apple.security.application-groups"] = ["group.my.installation"] + write_plist(project / "of.entitlements", entitlements) + + defaults["PGTemplateDefault"] = "after" + defaults["PGNewDefault"] = True + defaults["PGNested"] = {"unchanged": "after", "custom": "new default", "added": True} + defaults["NSCameraUsageDescription"] = "New template camera text" + write_plist(plist_template, defaults) + config_template.write_text(config_template.read_text().replace("PG_TEMPLATE_DEFAULT = before", "PG_TEMPLATE_DEFAULT = after")) + for obj in configs(pbx_defaults).values(): + obj["buildSettings"]["PG_TEMPLATE_DEFAULT"] = "after" + changed_ids = {key: uuid.uuid5(uuid.NAMESPACE_URL, key + "/PGSettings").hex.upper()[:24] + for key in configs(pbx_defaults)} + + def replace_ids(value): + if isinstance(value, dict): + return {changed_ids.get(key, key): replace_ids(item) for key, item in value.items()} + if isinstance(value, list): + return [replace_ids(item) for item in value] + return changed_ids.get(value, value) if isinstance(value, str) else value + + pbx_defaults = replace_ids(pbx_defaults) + write_json(template_project, pbx_defaults) + + # A regenerated addon must be refreshed as well as the template, not restored from the old project. + addon_config = root / "addons/ofxPGSettingsTest/addon_config.mk" + addon_config.parent.mkdir(parents=True, exist_ok=True) + addon_config.write_text("meta:\n\tADDON_NAME = ofxPGSettingsTest\ncommon:\n\tADDON_DEFINES = PG_ADDON_BEFORE=1\n") + (project / "src/extra.cpp").write_text("int pgExtraSource() { return 1; }\n") + run(pg, root, platform, project, "-aofxPGSettingsTest") + + updated = read_plist(plist_path) + assert "CustomPackage.xcodeproj" in workspace.read_text() + assert template_workspace_before == (template_workspace.read_bytes() if template_workspace.exists() else None), "updates must never copy workspace settings back into OF templates" + assert updated["NSHighResolutionCapable"] is True + assert updated["NSCameraUsageDescription"] == settings["NSCameraUsageDescription"] + assert updated["PGCustomTypes"] == settings["PGCustomTypes"] + assert "CFBundleSignature" not in updated, "a user deletion must stay deleted" + assert updated["PGTemplateDefault"] == "after" and updated["PGNewDefault"] is True + assert updated["PGNested"] == {"unchanged": "after", "custom": "mine", "added": True} + if platform == "ios": + assert updated["UISupportedInterfaceOrientations"] == settings["UISupportedInterfaceOrientations"] + xcconfig = config_path.read_text() + if platform in ("osx", "macos"): + assert "HIGH_RESOLUTION_CAPABLE = YES" in xcconfig + assert xcconfig.index('#include? "Retina.xcconfig"') < xcconfig.index("HIGH_RESOLUTION_CAPABLE = YES") + assert "PG_TEMPLATE_DEFAULT = after" in xcconfig + assert "-DMY_XCCONFIG_FLAG" in xcconfig and "-framework MySettingsFramework" in xcconfig + assert "$(OF_CORE_LIBS)" in xcconfig, "required OF linker settings must remain" + assert xcconfig.count('MY_SETTING[sdk=iphoneos*][config=Debug] = one \\\n two') == 1 + assert xcconfig.count('#include? "Custom.xcconfig"') == 1 + assert (project / "App.xcconfig").read_text() == "MY_APP_SETTING = stays\n" + + updated_project = read_json(pbx_path) + for key, obj in configs(updated_project).items(): + build = obj["buildSettings"] + assert build["DEVELOPMENT_TEAM"] == "TEAM_" + obj["name"] + assert build["PG_USER_SETTING"] == obj["name"] + assert build["PG_TEMPLATE_DEFAULT"] == "after" + assert build["ARCHS"] == "arm64" + assert "-DPG_USER_FLAG=1" in build["OTHER_CFLAGS"] + assert "MyCustomFramework" in str(build["OTHER_LDFLAGS"]) + assert build["CLANG_CXX_LANGUAGE_STANDARD"] == ("c++26" if obj["name"] == "Debug" else "c++23") + if platform in ("osx", "macos"): + assert float(build["MACOSX_DEPLOYMENT_TARGET"]) >= 12.0 + if platform == "ios": + assert float(build["IPHONEOS_DEPLOYMENT_TARGET"]) >= 15.0 + for key in native_targets: + saved = updated_project["objects"][updated_project["rootObject"]]["attributes"]["TargetAttributes"][key] + assert saved["DevelopmentTeam"] == "MY_TEAM" and saved["ProvisioningStyle"] == "Manual" + assert saved["SystemCapabilities"]["com.apple.Push"]["enabled"] == "1" + for config in updated_project["objects"][updated_project["objects"][key]["buildConfigurationList"]]["buildConfigurations"]: + assert "PG_FROM_CONFIG_MAKE=1" in updated_project["objects"][config]["buildSettings"]["GCC_PREPROCESSOR_DEFINITIONS"] + assert all("isa" in obj for obj in updated_project["objects"].values()), "settings must not create orphan configuration objects" + assert "extra.cpp" in pbx_path.read_text() + assert linked_sdk(updated_project, sdk_target)["usr/lib/libsqlite3.tbd"] == {"ATTRIBUTES": ["Weak"]} + assert "System/Library/Frameworks/CoreBluetooth.framework" in linked_sdk(updated_project, sdk_target) + for phase_id in updated_project["objects"][sdk_target]["buildPhases"]: + for build_id in updated_project["objects"][phase_id].get("files", []): + build = updated_project["objects"][build_id] + ref = updated_project["objects"].get(build.get("fileRef"), {}) + if ref.get("path") == "usr/lib/libsqlite3.tbd": + assert build.get("platformFilters") == ["ios" if platform == "ios" else "macos"] + for target_id in native_targets[1:]: + assert "usr/lib/libsqlite3.tbd" not in linked_sdk(updated_project, target_id), "per-target libraries must not leak to other targets" + if (project / "of.entitlements").exists(): + assert read_plist(project / "of.entitlements")["com.apple.security.application-groups"] == ["group.my.installation"] + + addon_config.write_text(addon_config.read_text().replace("PG_ADDON_BEFORE", "PG_ADDON_AFTER")) + run(pg, root, platform, project) + assert "PG_ADDON_AFTER=1" in pbx_path.read_text() and "PG_ADDON_BEFORE=1" not in pbx_path.read_text() + before = {path: path.read_bytes() for path in (plist_path, config_path, state)} + before_configs = configs(read_json(pbx_path)) + run(pg, root, platform, project) + assert before == {path: path.read_bytes() for path in before}, "repeated settings updates must be stable" + # Source/file UUIDs are randomly regenerated by the existing generator. + assert before_configs == configs(read_json(pbx_path)), "repeated build settings must be stable" + + if sys.platform == "darwin": + pbx_path.write_text("// !$*UTF8*$!\n" + openstep(read_json(pbx_path))) + write_plist(plist_path, read_plist(plist_path), binary=True) + run(pg, root, platform, project) + assert read_plist(plist_path)["PGCustomTypes"] == settings["PGCustomTypes"] + assert configs(read_json(pbx_path)) + + # No baseline (older PG): preserve existing user values, then record the first baseline. + state.unlink() + run(pg, root, platform, project) + assert read_plist(plist_path)["NSHighResolutionCapable"] is True + assert "PG_USER_SETTING" in pbx_path.read_text() and state.exists() + + run(pg, root, platform, project, "--defines") + assert "PG_FROM_CONFIG_MAKE=1" in pbx_path.read_text(), "a missing defines argument must not clear saved values" + run(pg, root, platform, project, "--defines=GUI_EDITED=1") + assert "GUI_EDITED=1" in pbx_path.read_text() and "PG_FROM_CONFIG_MAKE=1" not in pbx_path.read_text() + assert "-DPG_USER_FLAG=1" not in pbx_path.read_text() + assert "PG_ADDON_AFTER=1" in pbx_path.read_text(), "editing project defines must keep addon defines" + run(pg, root, platform, project, "--defines=", "--frameworks=", "--system-libs=") + assert "GUI_EDITED=1" not in pbx_path.read_text() + assert "PG_ADDON_AFTER=1" in pbx_path.read_text() + assert "usr/lib/libsqlite3.tbd" not in linked_sdk(read_json(pbx_path), sdk_target) + assert "System/Library/Frameworks/CoreBluetooth.framework" not in linked_sdk(read_json(pbx_path), sdk_target) + assert "-lsqlite3" not in pbx_path.read_text() and "CoreBluetooth" not in pbx_path.read_text() + assert "-lsqlite3" not in config_path.read_text() and "CoreBluetooth" not in config_path.read_text() + assert "MyCustomFramework" in pbx_path.read_text(), "SDK edits must keep unrelated third-party flags" + + run(pg, root, platform, project, "--app-version=3.2.1", "--app-build=42", "--bundle-id=com.example.test") + for obj in configs(read_json(pbx_path)).values(): + # Version options apply to native target configurations, as before. + if obj["buildSettings"].get("PRODUCT_BUNDLE_IDENTIFIER") == "com.example.test": + assert obj["buildSettings"]["MARKETING_VERSION"] == "3.2.1" + assert obj["buildSettings"]["CURRENT_PROJECT_VERSION"] == "42" + + plist_path.write_text("this is not a property list") + before = {path: path.read_bytes() for path in (pbx_path, plist_path, config_path, state)} + output = run(pg, root, platform, project, success=False) + assert "original settings kept" in output + assert before == {path: path.read_bytes() for path in before}, "unreadable settings must not be overwritten" + print("ok [" + platform + "] custom settings, template upgrade, required minimums, addon regeneration, repeated updates, legacy projects and invalid input") + + +def main(): + pg, source = (pathlib.Path(arg).resolve() for arg in sys.argv[1:3]) + with tempfile.TemporaryDirectory(prefix="pg-apple-settings-") as folder: + root = pathlib.Path(folder) + for name in ("apps", "addons", "libs/openFrameworks"): + (root / name).mkdir(parents=True, exist_ok=True) + shutil.copytree(source / "scripts/templates", root / "scripts/templates") + shutil.copytree(source / "libs/openFrameworksCompiled/project", root / "libs/openFrameworksCompiled/project") + for platform in ("osx", "macos", "ios"): + exercise(pg, root, platform) + print("Apple settings preservation tests passed") + + +if __name__ == "__main__": + main()