diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e98e573..b6bb3ad 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1872,6 +1872,9 @@ jobs: - name: rules-qt runs moc, rcc, lupdate and lrelease, with the SDK the project declares run: bash .github/scripts/check-deps-and-qt.sh qt-consumer + - name: rules-slint generates a component, its module, and runs it headless, with the SDK the project declares + run: bash tests/slint-consumer/check-slint.sh + # The payload carries QtGui's runtime closure (libdbus, fontconfig, xcb, # ...), so a Widgets program links, runs offscreen and packs on Linux. - name: rules-qt builds a Widgets program with a .ui form, runs it offscreen and packs it @@ -2735,6 +2738,9 @@ jobs: - name: rules-qt runs moc, rcc, lupdate and lrelease, with the SDK the project declares run: bash .github/scripts/check-deps-and-qt.sh qt-consumer + - name: rules-slint generates a component, its module, and runs it headless, with the SDK the project declares + run: bash tests/slint-consumer/check-slint.sh + # Windows: the payload carries the VC++ runtime Qt's DLLs import, so the # program starts on a machine without the VC++ Redistributable. macOS: # Qt loads system frameworks only. diff --git a/README.md b/README.md index 25ecd39..e93ba8b 100644 --- a/README.md +++ b/README.md @@ -70,6 +70,7 @@ mcpp 2026.11.7.1 or later; cross configuration requires CMake 3.19 or later. | `rules-metal` | `mcpp.rules.metal` | 2026.9.8.1 | Compiles `.metal` shaders into Metal libraries with the host's Xcode and deploys them beside the program. | [rules](docs/rules.md#rules-metal) | | `rules-qt` | `mcpp.rules.qt` | 2026.10.1.3 | Runs `moc`, `uic`, `rcc` and Qt's Linguist tools as actions, links the Qt modules and places their runtime. | [rules-qt](docs/rules-qt.md) | | `rules-slang` | `mcpp.rules.slang` | 2026.10.1.3 | Compiles Slang (`*.slang`) and embeds or places the result. | [rules](docs/rules.md#rules-slang) | +| `rules-slint` | `mcpp.rules.slint` | 2026.10.1.3 | Compiles Slint user interfaces (`*.slint`) with `slint-compiler` into headers and, on request, C++ modules. | [rules-slint](docs/rules-slint.md) | | `rules-spirv` | `mcpp.rules.spirv` | 2026.10.1.3 | Compiles GLSL and HLSL shader stages to SPIR-V and embeds or places the result. | [rules](docs/rules.md#rules-spirv) | | `rules-swift` | `mcpp.rules.swift` | 2026.9.8.1 | Compiles a package's `.swift` sources into one module the C and C++ sources call. | [rules](docs/rules.md#rules-swift) | | `rules-sycl` | `mcpp.rules.sycl` | 2026.10.1.3 | Compiles SYCL (`*.sycl`) with DPC++. | [rules](docs/rules.md#rules-sycl) | diff --git a/docs/engine-and-rules.md b/docs/engine-and-rules.md index 28d25d5..fa67daf 100644 --- a/docs/engine-and-rules.md +++ b/docs/engine-and-rules.md @@ -97,6 +97,7 @@ Each rule therefore selects the extensions it claims and leaves the rest: | `rules-metal` | `.metal` | | `rules-qt` | `.ui`, `.qrc`, `.ts`; a header is found by what it declares, since `.h` is already C++ | | `rules-slang` | `.slang` | +| `rules-slint` | `.slint` | | `rules-swift` | `.swift` | | `rules-sycl` | `.sycl` | | `rules-spirv` | `.comp .vert .frag .geom .tesc .tese .mesh .task .rgen .rint .rahit .rchit .rmiss .rcall`, and `.glsl` / `.hlsl` so that a stage-less name is refused by name rather than by absence | diff --git a/docs/rules-slint.md b/docs/rules-slint.md new file mode 100644 index 0000000..9aa8ede --- /dev/null +++ b/docs/rules-slint.md @@ -0,0 +1,78 @@ +# `rules-slint` + +`mcpp.rules.slint` compiles [Slint](https://slint.dev) user interfaces: each `.slint` file becomes, through `slint-compiler`, a C++ header (and on request a number of `.cpp` units and a C++ module) the program uses. It is what upstream's CMake function `slint_target_sources` does. The rule declares no SDK and pins no version: the compiler and the runtime the program links come from one Slint SDK the project chooses. Module `mcpp.rules.slint`; engine floor 2026.10.1.3; from 0.27.0. + +## Use + +```toml +[build-dependencies.mcpp] +plugins = { version = "0.27.0", features = ["rules-slint"], host-module = true } + +[dependencies] +mcpplibs.mwrap.slint = "1.19.0" # or compat.slint: the SDK as a package + +[build] +sources = ["src/*.cpp", "ui/app.slint"] +``` + +```cpp +// build.mcpp +import mcpp.rules.slint; + +int main() { + mcpp::rules::slint::options o; + o.module = "app.ui"; // also write `export module app.ui;` + return mcpp::rules::slint::compile(o) ? 0 : 1; +} +``` + +```cpp +// src/main.cpp +import app.ui; // or: #include "app.h" + +int main() { + auto ui = AppWindow::create(); + ui->run(); +} +``` + +## Options and upstream CMake + +| `slint_target_sources` / target property | option | `slint-compiler` | +|---|---|---| +| the `.slint` inputs | `[build] sources`, `options::sources` | the input | +| `NAMESPACE` | `ns` | `--cpp-namespace` | +| `LIBRARY_PATHS name=path` | `library_paths` | `-L name=path` | +| — | `include_paths` | `-I` | +| `COMPILATION_UNITS n` | `compilation_units` | `--cpp-file` × n, each compiled | +| `EDITION` | `edition` | `--edition` | +| `SLINT_STYLE` | `style` | `--style` | +| `SLINT_EMBED_RESOURCES` | `embed_resources` | `--embed-resources` | +| `SLINT_SCALE_FACTOR` | `scale_factor` | `--scale-factor` | +| `SLINT_TRANSLATION_DOMAIN` | `translation_domain` | `--translation-domain` | +| `SLINT_BUNDLE_TRANSLATIONS` | `bundle_translations` | `--bundle-translations` | + +Each input is one action with the depfile `slint-compiler --depfile` writes, so an edit of the input or of a file it imports regenerates that input alone, and a build with nothing changed regenerates nothing. Two inputs with one stem are refused, since both would write `.h`. + +## The module + +With `options::module`, the rule writes a module interface unit per input (`module` for one input, `.` for several): the generated header in its global module fragment and `export using` for what the input exports and `slint-compiler` generates, under the exported names: + +- each exported component that inherits `Window` or `Dialog`, directly or through components of its own (`slint-compiler` generates nothing for an exported component that is not a window); +- each exported `struct`, `enum` and `global`; +- the aliases of `export { A as B }`, and what `export { … } from "…"` and `export * from "…"` re-export, read from the files they name (`library_paths` and `include_paths` resolve them; the built-in libraries such as `std-widgets.slint` export nothing of their own). + +The rule reads the `.slint` files while the build program runs, so a change to their exports re-plans the build. `options::exports` names the exports instead, for a file the reading does not cover. The header is not included inside `export { … }`: Clang refuses to export the out-of-class member definitions `slint-compiler` writes. + +## The SDK + +The first that answers decides, recorded as the fact `rules-slint.sdk`: + +| level | how | +|---|---| +| 1. build program | `options::compiler` (a tool choice: a path, `tool::on_path()`) or `options::root` (an SDK laid out as upstream's: `bin/`, `lib/`, `include/slint/`) | +| 2. environment | `SLINT_COMPILER`, the name of upstream CMake's cache variable | +| 3. a package of the graph | the directory of `compat.slint` (`options::sdk_package`), which the program depends on directly or through `mcpplibs.mwrap.slint` | +| 4. declared payload | `xim:slint`, at the version the project's `[xlings]` table states | + +At levels 1 and 4 the SDK is not a package, so the rule puts it on the build: `include/slint` on the include path, `slint_cpp` on the link and its directory among the program's run-time directories (`lib`, or `bin` on Windows, where the DLL is placed beside the program). At level 3 the package does that itself. With none, the rule warns and plans nothing. diff --git a/mcpp.toml b/mcpp.toml index be2f7bf..289605d 100644 --- a/mcpp.toml +++ b/mcpp.toml @@ -1,7 +1,7 @@ [package] name = "plugins" namespace = "mcpp" -version = "0.26.1" +version = "0.27.0" # The first mcpp release that speaks protocol 17 (SPEC-013, mcpp#847): the # platform's directives `mcpp.plugins.platform` states (`link_driver`, # `link_input`, `artifact_name`, `seal`, `run_host`), the `platform` phase, and @@ -212,6 +212,18 @@ implies = ["plugins-core"] rule_module = "mcpp.rules.qt" device_extensions = [".ui", ".qrc", ".ts"] +# Slint's `.slint -> C++` (slint-compiler), what upstream CMake's +# `slint_target_sources` does: one action per input with its depfile, and on +# request a module interface unit exporting what the input exports. `.slint` +# files named in `[build] sources` reach the rule through +# `mcpp::device_sources()`. The SDK is the project's choice (docs/rules-slint.md): +# `compat.slint` in the graph, `xim:slint` in `[xlings]`, or an explicit one. +[features.rules-slint] +sources = ["rules/slint.cppm"] +implies = ["plugins-core"] +rule_module = "mcpp.rules.slint" +device_extensions = [".slint"] + # WHERE QT COMES FROM IS THE PROJECT'S CHOICE, not a feature: `rules-qt` finds # the SDK from `options::root`, `QT_ROOT_DIR`, or a Qt payload the project # declares in its own `[xlings]` table at the version it chooses diff --git a/rules/slint.cppm b/rules/slint.cppm new file mode 100644 index 0000000..fd98639 --- /dev/null +++ b/rules/slint.cppm @@ -0,0 +1,427 @@ +// mcpp.rules.slint -- how a `.slint` file becomes part of a C++ program. +// +// Slint describes a user interface in its own language; `slint-compiler` +// turns each `.slint` file into a C++ header (and, with +// `compilation_units`, that many `.cpp` files) the program includes and +// compiles. One action per input, with the depfile the compiler writes, so an +// edited `.slint` file -- or one it imports -- regenerates that input alone. +// This is what upstream's CMake function `slint_target_sources` does, and its +// arguments and target properties are this rule's options: +// +// NAMESPACE options::ns --cpp-namespace +// LIBRARY_PATHS name=path options::library_paths -L +// COMPILATION_UNITS n options::compilation_units --cpp-file × n +// EDITION options::edition --edition +// SLINT_STYLE options::style --style +// SLINT_EMBED_RESOURCES options::embed_resources --embed-resources +// SLINT_SCALE_FACTOR options::scale_factor --scale-factor +// SLINT_TRANSLATION_DOMAIN options::translation_domain +// SLINT_BUNDLE_TRANSLATIONS options::bundle_translations +// +// A MODULE PER INPUT, IF ASKED. With `options::module`, the rule also writes +// a module interface unit for each input: the generated header in its global +// module fragment, and `export using` for what the `.slint` file exports and +// slint-compiler generates -- each component that inherits `Window` (through +// any chain of components), each exported struct, enum and global, under +// their exported names (`export { A as B }`), following `export … from` +// into the files it names. A program then writes `import app.ui;` instead of +// including the header. The header cannot simply be included inside +// `export { … }`: Clang refuses to export the out-of-class member +// definitions slint-compiler writes ("cannot export … not at namespace +// scope"). `options::exports` names the exports itself where the reading is +// not enough. +// +// WHERE SLINT COMES FROM IS THE PROJECT'S CHOICE, in this order; the first +// that answers decides, and `mcpp::fact("rules-slint.sdk", …)` records it: +// +// 1. `options::compiler` / `options::root` in the build program; +// 2. the environment variable `SLINT_COMPILER` (upstream CMake's cache +// variable of the same name); +// 3. a Slint SDK the program depends on: the directory of `compat.slint` +// (or `options::sdk_package`) in the dependency graph, whose include +// directories and library the package itself provides; +// 4. a Slint payload the project declares in its own `[xlings]` table +// (`xim:slint`), whose include directory, library and run-time +// directory the rule then puts on the build, as `rules-qt` does for Qt. +// +// The rule declares no SDK and pins no version: the compiler and the runtime +// a program links come from one SDK, so the generated code and the library +// always agree. +// +// A MISSING SDK IS A WARNING. `mcpp emit build-database` plans a project on +// machines that never built it; the rule says what it could not find and +// declares nothing, so the plan succeeds and the build is where it fails. +export module mcpp.rules.slint; + +import std; +import mcpp; +import mcpp.plugins; +import mcpp.plugins.tool; + +export namespace mcpp::rules::slint { + +struct library_path { + std::string name; // the name `import { X } from "@name"` uses + std::string path; // a directory or a `.slint` file, relative to the package root +}; + +struct options { + // `.slint` files, beside those named in `[build] sources`. + std::vector sources; + std::string ns; // --cpp-namespace + std::vector library_paths; // -L name=path + std::vector include_paths; // -I + unsigned compilation_units = 0; // 0: the header holds everything + std::string edition; // --edition + std::string style; // --style (fluent, material, cupertino, cosmic, qt, native) + std::string embed_resources; // as-absolute-path | embed-files | embed-for-software-renderer … + std::string scale_factor; // --scale-factor + std::string translation_domain; + std::string bundle_translations; // a directory of `/LC_MESSAGES/.po` + bool no_default_translation_context = false; + // A module interface unit per input: `module` for a single input, + // `.` for each of several. Empty writes no module. + std::string module; + // The names the module exports, when the reading of the `.slint` file is + // not to be used. Applies to every input. + std::vector exports; + // The SDK (see the header). `compiler` is a tool choice: a program path, + // `tool::on_path()`, `tool::root(dir)`. + mcpp::plugins::tool::choice compiler; + std::string root; + std::string sdk_package = "compat.slint"; + std::string out_dir = std::string(mcpp::out_dir()); +}; + +namespace detail { + +namespace fs = std::filesystem; + +inline std::string generic(const fs::path& p) { + std::string s = p.lexically_normal().generic_string(); + return s; +} + +inline void warn(const std::string& message) { + std::cerr << message << '\n'; + mcpp::warning(message.c_str()); +} + +inline bool is_windows() { return std::string_view(mcpp::target_os()) == "windows"; } + +inline fs::path absolute_from_root(const std::string& p) { + fs::path path(p); + return path.is_absolute() ? path : fs::path(mcpp::manifest_dir()) / path; +} + +inline std::vector device_slint() { + std::vector out; + const std::string all = mcpp::device_sources(); + std::size_t i = 0; + while (i <= all.size()) { + auto nl = all.find('\n', i); + std::string one = all.substr(i, nl == std::string::npos ? std::string::npos : nl - i); + i = nl == std::string::npos ? all.size() + 1 : nl + 1; + while (!one.empty() && (one.back() == ' ' || one.back() == '\r')) one.pop_back(); + if (one.size() > 6 && one.ends_with(".slint")) out.push_back(one); + } + return out; +} + +inline std::string read_file(const fs::path& p) { + std::ifstream in(p, std::ios::binary); + return {std::istreambuf_iterator(in), {}}; +} + +// ── what a `.slint` file exports and slint-compiler generates ────────────── + +// The text with comments removed and string literals emptied, so a keyword +// inside either is not read as one. The string of an `import`/`export … from` +// is kept, since it names a file. +inline std::string code_of(const std::string& text) { + std::string out; + out.reserve(text.size()); + for (std::size_t i = 0; i < text.size();) { + if (text.compare(i, 2, "//") == 0) { + while (i < text.size() && text[i] != '\n') ++i; + } else if (text.compare(i, 2, "/*") == 0) { + auto end = text.find("*/", i + 2); + i = end == std::string::npos ? text.size() : end + 2; + out += ' '; + } else if (text[i] == '"') { + std::size_t j = i + 1; + while (j < text.size() && text[j] != '"') j += text[j] == '\\' ? 2 : 1; + std::string literal = text.substr(i, std::min(j + 1, text.size()) - i); + const auto tail = std::string_view(out).substr(out.size() > 16 ? out.size() - 16 : 0); + out += tail.find("from") != std::string_view::npos ? literal : std::string("\"\""); + i = j + 1; + } else { + out += text[i++]; + } + } + return out; +} + +struct file_exports { + std::map components; // name -> base ("" when none) + std::set data; // exported struct, enum, global + std::vector> exported; // (local name, exported name) + std::vector> from; // (`{list}` or "*", file) + std::map imported; // local name -> file it comes from +}; + +inline fs::path resolve_import(const fs::path& from_dir, const std::string& spec, + const std::vector& libs, const std::vector& includes) { + if (spec.starts_with("@")) { + const auto slash = spec.find('/'); + const std::string name = spec.substr(1, slash == std::string::npos ? std::string::npos : slash - 1); + for (auto const& l : libs) + if (l.name == name) { + fs::path base = absolute_from_root(l.path); + return slash == std::string::npos ? base : base / spec.substr(slash + 1); + } + return {}; + } + fs::path rel = from_dir / spec; + std::error_code ec; + if (fs::exists(rel, ec)) return rel; + for (auto const& inc : includes) { + fs::path p = absolute_from_root(inc) / spec; + if (fs::exists(p, ec)) return p; + } + return {}; // std-widgets.slint and the other built-in libraries +} + +inline file_exports read_exports(const fs::path& file, const options& opt) { + file_exports fe; + const std::string code = code_of(read_file(file)); + const fs::path dir = file.parent_path(); + static const std::regex component(R"re(\b(export\s+)?component\s+([A-Za-z_][\w-]*)\s*(?:inherits\s+([A-Za-z_][\w-]*))?)re"); + static const std::regex data(R"re(\bexport\s+(struct|enum|global)\s+([A-Za-z_][\w-]*))re"); + static const std::regex list(R"re(\bexport\s*\{([^}]*)\}\s*(?:from\s*"([^"]*)")?)re"); + static const std::regex star(R"re(\bexport\s*\*\s*from\s*"([^"]*)")re"); + static const std::regex importing(R"re(\bimport\s*\{([^}]*)\}\s*from\s*"([^"]*)")re"); + for (std::sregex_iterator it(code.begin(), code.end(), component), end; it != end; ++it) { + fe.components[(*it)[2]] = (*it)[3]; + if ((*it)[1].matched) fe.exported.push_back({(*it)[2], (*it)[2]}); + } + for (std::sregex_iterator it(code.begin(), code.end(), data), end; it != end; ++it) { + fe.data.insert((*it)[2]); + fe.exported.push_back({(*it)[2], (*it)[2]}); + } + auto names = [](const std::string& body) { + std::vector> out; + static const std::regex item(R"re(([A-Za-z_][\w-]*)(?:\s+as\s+([A-Za-z_][\w-]*))?)re"); + for (std::sregex_iterator it(body.begin(), body.end(), item), end; it != end; ++it) + out.push_back({(*it)[1], (*it)[2].matched ? std::string((*it)[2]) : std::string((*it)[1])}); + return out; + }; + for (std::sregex_iterator it(code.begin(), code.end(), importing), end; it != end; ++it) { + fs::path target = resolve_import(dir, (*it)[2], opt.library_paths, opt.include_paths); + for (auto const& [name, local] : names((*it)[1])) fe.imported[local] = target; + } + for (std::sregex_iterator it(code.begin(), code.end(), list), end; it != end; ++it) { + const bool re_export = (*it)[2].matched; + fs::path target = re_export ? resolve_import(dir, (*it)[2], opt.library_paths, opt.include_paths) : fs::path{}; + for (auto const& [name, as] : names((*it)[1])) { + fe.exported.push_back({name, as}); + if (re_export) fe.imported[name] = target; + } + } + for (std::sregex_iterator it(code.begin(), code.end(), star), end; it != end; ++it) + fe.from.push_back({"*", resolve_import(dir, (*it)[1], opt.library_paths, opt.include_paths)}); + return fe; +} + +// The names slint-compiler generates for `file` (its exported windows, +// structs, enums and globals, under their exported names), every file it +// reads recorded in `read`. +inline std::vector generated_names(const fs::path& file, const options& opt, std::set& read) { + std::map files; + std::function load = [&](const fs::path& f) -> const file_exports& { + auto it = files.find(f); + if (it != files.end()) return it->second; + read.insert(f); + return files.emplace(f, read_exports(f, opt)).first->second; + }; + // Is `name`, as known in `f`, a component that (eventually) inherits Window? + std::function is_window = [&](const fs::path& f, const std::string& name, int depth) -> bool { + if (depth > 32) return false; + if (name == "Window" || name == "Dialog") return true; + const auto& fe = load(f); + if (auto c = fe.components.find(name); c != fe.components.end()) + return !c->second.empty() && is_window(f, c->second, depth + 1); + if (auto i = fe.imported.find(name); i != fe.imported.end() && !i->second.empty()) + return is_window(i->second, name, depth + 1); + return false; + }; + std::function is_data = [&](const fs::path& f, const std::string& name, int depth) -> bool { + if (depth > 32) return false; + const auto& fe = load(f); + if (fe.data.contains(name)) return true; + if (auto i = fe.imported.find(name); i != fe.imported.end() && !i->second.empty()) + return is_data(i->second, name, depth + 1); + return false; + }; + std::vector out; + std::function collect = [&](const fs::path& f, int depth) { + if (depth > 32) return; + const auto& fe = load(f); + for (auto const& [local, as] : fe.exported) + if (is_window(f, local, 0) || is_data(f, local, 0)) out.push_back(as); + for (auto const& [what, target] : fe.from) + if (!target.empty()) collect(target, depth + 1); + }; + collect(file, 0); + std::ranges::sort(out); + out.erase(std::unique(out.begin(), out.end()), out.end()); + // slint-compiler names C++ entities as written, with `-` as `_`. + for (auto& n : out) std::ranges::replace(n, '-', '_'); + return out; +} + +// ── the SDK ──────────────────────────────────────────────────────────────── + +struct sdk { + std::string compiler; + std::string root; // set when the SDK is not a package of the graph + std::string level; +}; + +inline sdk locate(const options& opt) { + namespace tool = mcpp::plugins::tool; + sdk out; + const std::string exe = is_windows() ? "slint-compiler.exe" : "slint-compiler"; + if (!opt.compiler.is_default() || !opt.root.empty()) { + tool::spec s{.who = "mcpp.rules.slint", .ns = "xim", .package = "slint", + .programs = {"slint-compiler"}, .bin_dirs = {"bin", ""}, + .option = "options::compiler", .legacy_env = "", .request = false}; + auto f = tool::resolve(s, opt.root.empty() ? opt.compiler : tool::root(opt.root)); + if (f) return {f.program, opt.root.empty() ? f.root : opt.root, "options"}; + } + if (const char* env = std::getenv("SLINT_COMPILER"); env && *env) + return {generic(env), {}, "SLINT_COMPILER"}; + if (const std::string dir = mcpp::dep_dir(opt.sdk_package.c_str()); !dir.empty()) { + std::error_code ec; + for (auto it = fs::recursive_directory_iterator(dir, ec); !ec && it != fs::recursive_directory_iterator(); it.increment(ec)) + if (it->path().filename() == exe && it->path().parent_path().filename() == "bin") + return {generic(it->path()), {}, opt.sdk_package}; + } + tool::spec s{.who = "mcpp.rules.slint", .ns = "xim", .package = "slint", + .programs = {"slint-compiler"}, .bin_dirs = {"bin"}, + .option = "options::compiler", .legacy_env = "", .request = false}; + if (auto f = tool::resolve(s); f) return {f.program, f.root, "xim:slint"}; + return out; +} + +} // namespace detail + +inline bool compile(options opt = {}) { + namespace fs = std::filesystem; + using detail::generic; + const char* who = "mcpp.rules.slint"; + mcpp::fact("mcpp.plugins", std::string(mcpp::plugins::version).c_str()); + + std::vector inputs = detail::device_slint(); + for (auto const& s : opt.sources) inputs.push_back(s); + if (inputs.empty()) return true; + + const detail::sdk sdk = detail::locate(opt); + if (sdk.compiler.empty()) { + detail::warn(std::format( + "{}: {} `.slint` file(s) and no slint-compiler: depend on `compat.slint` (or " + "`mcpplibs.mwrap.slint`), declare `xim:slint` in `[xlings]`, set SLINT_COMPILER, or " + "name it with options::compiler. Nothing is generated.", who, inputs.size())); + return true; + } + mcpp::fact("rules-slint.sdk", std::format("{}: {}", sdk.level, sdk.compiler).c_str()); + + // An SDK that is not a package of the graph: its headers, library and + // run-time directory are the rule's to put on the build. + if (!sdk.root.empty()) { + const fs::path root(sdk.root); + mcpp::include_dir(generic(root / "include" / "slint").c_str()); + mcpp::link_search(generic(root / "lib").c_str()); + mcpp::link_lib("slint_cpp"); + mcpp::runtime_search_dir(generic(root / (detail::is_windows() ? "bin" : "lib")).c_str()); + } + + const fs::path gen = fs::path(opt.out_dir) / "slint"; + std::error_code ec; + fs::create_directories(gen, ec); + mcpp::include_dir(generic(gen).c_str()); + + std::map claimed; + std::vector files; + for (auto const& i : inputs) files.push_back(detail::absolute_from_root(i)); + for (auto const& f : files) { + const std::string stem = f.stem().string(); + auto [it, fresh] = claimed.try_emplace(stem, f); + if (!fresh) { + std::cerr << std::format("{}: two inputs generate `{}.h`: {} and {}. Rename one.\n", + who, stem, generic(it->second), generic(f)); + return false; + } + const std::string in = generic(f); + const std::string out = generic(gen / (stem + ".h")); + const std::string dep = out + ".d"; + mcpp::action a; + const std::string id = "slint:" + stem; + const std::string desc = "SLINT " + f.filename().string(); + a.id = id.c_str(); + a.role = mcpp::roles::source; + a.description = desc.c_str(); + a.depfile = dep.c_str(); + a.arg(sdk.compiler.c_str()).arg(in.c_str()).arg("-o").arg(out.c_str()).arg("--depfile").arg(dep.c_str()); + std::vector keep; // the strings an action argument points into + auto add = [&](std::string flag, std::string value) { + keep.push_back(std::move(flag)); a.arg(keep.back().c_str()); + keep.push_back(std::move(value)); a.arg(keep.back().c_str()); + }; + keep.reserve(64); + if (!opt.ns.empty()) { keep.push_back("--cpp-namespace=" + opt.ns); a.arg(keep.back().c_str()); } + for (auto const& l : opt.library_paths) add("-L", l.name + "=" + generic(detail::absolute_from_root(l.path))); + for (auto const& p : opt.include_paths) add("-I", generic(detail::absolute_from_root(p))); + if (!opt.edition.empty()) add("--edition", opt.edition); + if (!opt.style.empty()) add("--style", opt.style); + if (!opt.embed_resources.empty()) add("--embed-resources", opt.embed_resources); + if (!opt.scale_factor.empty()) add("--scale-factor", opt.scale_factor); + if (!opt.translation_domain.empty()) add("--translation-domain", opt.translation_domain); + if (!opt.bundle_translations.empty()) add("--bundle-translations", generic(detail::absolute_from_root(opt.bundle_translations))); + if (opt.no_default_translation_context) a.arg("--no-default-translation-context"); + a.input(in.c_str()).output(out.c_str()); + std::vector units; + for (unsigned u = 0; u < opt.compilation_units; ++u) + units.push_back(generic(gen / std::format("{}_{}.cpp", stem, u))); + for (auto const& u : units) { add("--cpp-file", u); a.output(u.c_str()); } + a.submit(); + for (auto const& u : units) mcpp::source(u.c_str()); + mcpp::rerun_if_changed(in.c_str()); + + if (opt.module.empty()) continue; + std::set read; + std::vector names = opt.exports.empty() ? detail::generated_names(f, opt, read) : opt.exports; + for (auto const& r : read) mcpp::rerun_if_changed(generic(r).c_str()); + const std::string module = files.size() == 1 ? opt.module : opt.module + "." + stem; + std::string unit = std::format( + "// Generated by mcpp.rules.slint from {} -- do not edit.\n" + "module;\n#include \n#include \n#include \n#include \"{}.h\"\n\n" + "export module {};\n\n", f.filename().string(), stem, module); + if (opt.ns.empty()) { + for (auto const& n : names) unit += std::format("export using ::{};\n", n); + } else { + unit += std::format("export namespace {} {{\n", opt.ns); + for (auto const& n : names) unit += std::format("using {}::{};\n", opt.ns, n); + unit += "}\n"; + } + const fs::path unitPath = gen / (stem + ".cppm"); + if (detail::read_file(unitPath) != unit) { + std::ofstream os(unitPath, std::ios::binary); + os << unit; + } + mcpp::source(generic(unitPath).c_str()); + } + return true; +} + +} // namespace mcpp::rules::slint diff --git a/src/plugins.cppm b/src/plugins.cppm index 5918df7..2bcf6c6 100644 --- a/src/plugins.cppm +++ b/src/plugins.cppm @@ -46,7 +46,7 @@ export namespace mcpp::plugins { // // One package, one version: the number lives in mcpp.toml, and the CI step // `the collection states its own version` compares the two. -inline constexpr std::string_view version = "0.26.1"; +inline constexpr std::string_view version = "0.27.0"; } // namespace mcpp::plugins diff --git a/tests/all-rules-compile/build.mcpp b/tests/all-rules-compile/build.mcpp index bebcc60..07b3218 100644 --- a/tests/all-rules-compile/build.mcpp +++ b/tests/all-rules-compile/build.mcpp @@ -11,6 +11,7 @@ import mcpp.rules.hip; import mcpp.rules.metal; import mcpp.rules.qt; import mcpp.rules.slang; +import mcpp.rules.slint; import mcpp.rules.spirv; import mcpp.rules.swift; import mcpp.rules.sycl; @@ -44,6 +45,7 @@ int main() { && mcpp::rules::spirv::compile() // No `.swift` source is named, so the Swift rule plans nothing and // never asks `xcrun`, as the Metal rule above. + && mcpp::rules::slint::compile() && mcpp::rules::swift::compile() && mcpp::rules::sycl::compile(); // `tools::embed` has no accelerator gate, so it is asked the one question diff --git a/tests/all-rules-compile/mcpp.toml b/tests/all-rules-compile/mcpp.toml index 3931f93..4a04f58 100644 --- a/tests/all-rules-compile/mcpp.toml +++ b/tests/all-rules-compile/mcpp.toml @@ -40,7 +40,7 @@ import_std = true [build-dependencies.mcpp] plugins = { path = "../..", features = [ "rules-ascendc", "rules-cuda", "rules-hip", "rules-metal", "rules-qt", "rules-slang", - "rules-spirv", "rules-swift", "rules-sycl", + "rules-slint", "rules-spirv", "rules-swift", "rules-sycl", "tools-embed", "tools-island", "tools-steps", "dist-appimage", "dist-wix", "dist-apple", "dist-web", "dist-apk", "dist-apk-kotlin", "dist-apk-maven", "dist-linux-package", "dist-deb", "dist-rpm", diff --git a/tests/slint-consumer/build.mcpp b/tests/slint-consumer/build.mcpp new file mode 100644 index 0000000..18b8b91 --- /dev/null +++ b/tests/slint-consumer/build.mcpp @@ -0,0 +1,14 @@ +// `.slint` files reach the rule from `[build] sources`; the module `app.ui` +// exports what ui/app.slint exports and slint-compiler generates. +import std; +import mcpp; +import mcpp.rules.slint; + +int main() { + mcpp::rules::slint::options o; + o.module = "app.ui"; + o.style = "fluent"; + // CI declares xim:slint in [xlings]; a local run may point at an SDK. + if (const char* root = std::getenv("SLINT_SDK_ROOT"); root && *root) o.root = root; + return mcpp::rules::slint::compile(o) ? 0 : 1; +} diff --git a/tests/slint-consumer/check-slint.sh b/tests/slint-consumer/check-slint.sh new file mode 100755 index 0000000..edd5a1b --- /dev/null +++ b/tests/slint-consumer/check-slint.sh @@ -0,0 +1,30 @@ +#!/usr/bin/env bash +# rules-slint end to end: the fixture builds with the SDK the project declares +# (xim:slint), runs headless, and the rule's actions behave as one per input: +# the module exports what the input exports, an edit of a file the input +# imports regenerates it, a build with nothing changed regenerates nothing. +set -euo pipefail +: "${MCPP:?MCPP names the mcpp under test}" +fail() { echo "FAIL: $*"; exit 1; } +cd "$(dirname "$0")" +rm -rf target +mkdir -p target/ci +"$MCPP" build -v 2>&1 | tee target/ci/build.log +grep -qE '/slint-compiler[^ ]* .*app\.slint' target/ci/build.log || fail "slint-compiler did not run on ui/app.slint" +unit=$(find target -path '*slint/app.cppm' | head -1) +[ -n "$unit" ] || fail "no module unit was written" +for name in AppWindow Colors Mode Point Settings; do + grep -qx "export using ::$name;" "$unit" || fail "app.cppm does not export $name" +done +! grep -q 'Badge' "$unit" || fail "app.cppm exports Badge, which slint-compiler does not generate (not a window)" +echo "ok: the module exports the window (through its base), the struct, the enum, the global and the alias" +"$MCPP" run | tee target/ci/run.log +grep -qx 'counter=43 calls=1 origin=3,4 title=changed background=#202020 mode=1' target/ci/run.log || + fail "the program did not see the generated component" +echo "ok: the program imports app.ui and drives the component headless" +"$MCPP" build -v > target/ci/second.log 2>&1 || { cat target/ci/second.log; fail "the second build failed"; } +! grep -qE '/slint-compiler[^ ]* ' target/ci/second.log || fail "a build with nothing changed ran slint-compiler" +touch ui/palette.slint +"$MCPP" build -v > target/ci/third.log 2>&1 || { cat target/ci/third.log; fail "the build after the edit failed"; } +grep -qE '/slint-compiler[^ ]* .*app\.slint' target/ci/third.log || fail "an edit of palette.slint (imported by app.slint) did not regenerate app.h" +echo "ok: nothing changed regenerates nothing; an imported file's edit regenerates its importer" diff --git a/tests/slint-consumer/mcpp.toml b/tests/slint-consumer/mcpp.toml new file mode 100644 index 0000000..9ed16ad --- /dev/null +++ b/tests/slint-consumer/mcpp.toml @@ -0,0 +1,35 @@ +# Fixture: a Slint user interface compiled by rules-slint, run headless. +# +# ui/app.slint a window (through a base component), a struct, an +# enum, a global, a non-window export (no code), and a +# re-exported global under another name +# ui/palette.slint imported by app.slint: its edit regenerates app.h +# +# The program imports the generated module `app.ui` and checks properties, a +# callback, the struct, the global, the alias and the enum, with Slint's +# software renderer behind a headless platform. +[package] +name = "slint-consumer" +version = "0.1.0" +description = "Fixture: a Slint UI built through rules-slint" +license = "Apache-2.0" +authors = ["mcpp-community"] + +[language] +standard = "c++23" +modules = true +import_std = false + +[build-dependencies.mcpp] +plugins = { path = "../..", features = ["rules-slint"], host-module = true } + +# The SDK is the project's declaration, at the version it chooses. +[target.'cfg(any(windows, linux, macos))'.xlings.workspace] +"xim:slint" = "1.19.0" + +[build] +sources = ["src/*.cpp", "ui/app.slint"] + +[targets.slint-consumer] +kind = "bin" +main = "src/main.cpp" diff --git a/tests/slint-consumer/src/main.cpp b/tests/slint-consumer/src/main.cpp new file mode 100644 index 0000000..df0d68c --- /dev/null +++ b/tests/slint-consumer/src/main.cpp @@ -0,0 +1,37 @@ +// The component and its types through `import app.ui;` (the module the rule +// writes beside the header); Slint's own software renderer behind a headless +// platform, so the program runs on every host without a display. +#include +#include +#include // textual, before the import: GCC 16 refuses SoftwareRenderer in a module + +import app.ui; + +namespace { +struct HeadlessWindow : slint::platform::WindowAdapter { + slint::platform::SoftwareRenderer renderer_{slint::platform::SoftwareRenderer::RepaintBufferType::NewBuffer}; + slint::platform::AbstractRenderer& renderer() override { return renderer_; } + slint::PhysicalSize size() override { return slint::PhysicalSize({ .width = 320, .height = 240 }); } +}; +struct HeadlessPlatform : slint::platform::Platform { + std::unique_ptr create_window_adapter() override { + return std::make_unique(); + } +}; +} // namespace + +int main() { + slint::platform::set_platform(std::make_unique()); + auto ui = AppWindow::create(); + int calls = 0; + ui->on_request_increase_value([&] { ui->set_counter(ui->get_counter() + 1); ++calls; }); + ui->invoke_request_increase_value(); + ui->set_origin(Point{3, 4}); + ui->global().set_title("changed"); + const bool dark = ui->global().get_background() == slint::Color::from_rgb_uint8(0x20, 0x20, 0x20); + const Mode mode = Mode::Dark; + std::printf("counter=%d calls=%d origin=%d,%d title=%s background=%s mode=%d\n", ui->get_counter(), calls, + ui->get_origin().x, ui->get_origin().y, ui->global().get_title().data(), + dark ? "#202020" : "other", static_cast(mode)); + return (ui->get_counter() == 43 && calls == 1 && ui->get_origin().y == 4 && dark) ? 0 : 1; +} diff --git a/tests/slint-consumer/ui/app.slint b/tests/slint-consumer/ui/app.slint new file mode 100644 index 0000000..2087d6d --- /dev/null +++ b/tests/slint-consumer/ui/app.slint @@ -0,0 +1,24 @@ +import { Button, VerticalBox } from "std-widgets.slint"; +import { Palette } from "palette.slint"; + +export enum Mode { light, dark } +export struct Point { x: int, y: int } +export global Settings { in-out property title: "hello"; } + +// Not a window: slint-compiler generates nothing for it, and the module does not export it. +export component Badge inherits Rectangle { in property label; } + +component Base inherits Window { in-out property mode: Mode.light; } + +export component AppWindow inherits Base { + in-out property counter: 42; + in-out property origin; + callback request-increase-value(); + background: Palette.background; + VerticalBox { + Text { text: "Counter: \{root.counter}"; } + Button { text: "Increase value"; clicked => { root.request-increase-value(); } } + } +} + +export { Palette as Colors } diff --git a/tests/slint-consumer/ui/palette.slint b/tests/slint-consumer/ui/palette.slint new file mode 100644 index 0000000..d4442e3 --- /dev/null +++ b/tests/slint-consumer/ui/palette.slint @@ -0,0 +1 @@ +export global Palette { out property background: #202020; }