diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..8a6c241 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Preserve upstream document bytes and original whitespace on every platform. +upstream/** -text -whitespace diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..b03e68f --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,112 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +env: + # compat.slint 1.19.0 and mcpplibs.slintgen 1.19.0 are in an mcpp-index + # PR and not yet in the published index: until they are, the run resolves + # against that PR's candidate commit, the complete unchanged index layout + # installed as the built-in index of the run's home. Drop this pin and the step + # that reads it once the index publishes them. + MCPP_INDEX_CANDIDATE: "4191fe3e1193ae4ce4360201ae0a45ca1c2e5463" + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + + +jobs: + mcpp: + name: mcpp (${{ matrix.os }}, ${{ matrix.toolchain }}) + strategy: + fail-fast: false + matrix: + include: + - { os: ubuntu-24.04, toolchain: 'gcc@16.1.0' } + - { os: ubuntu-24.04, toolchain: 'llvm@23.1.3' } + # Linux arm64 waits for an aarch64 xim:fontconfig (compat.slint's payload needs it). + - { os: macos-15, toolchain: 'llvm@23.1.3' } + - { os: windows-2025, toolchain: 'llvm@23.1.3' } + runs-on: ${{ matrix.os }} + timeout-minutes: 90 + defaults: + run: + shell: bash + env: + XLINGS_NON_INTERACTIVE: 1 + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + + - name: Mwrap identity and bilingual README contract + run: python3 tools/check_mwrap_release.py + + - name: Install Xlings (Linux/macOS) + if: runner.os != 'Windows' + run: | + curl -fsSL https://raw.githubusercontent.com/openxlings/xlings/refs/heads/main/tools/other/quick_install.sh | bash + echo "$HOME/.xlings/subos/current/bin" >> "$GITHUB_PATH" + + - name: Install Xlings (Windows) + if: runner.os == 'Windows' + shell: pwsh + run: | + irm https://raw.githubusercontent.com/openxlings/xlings/main/tools/other/quick_install.ps1 | iex + "$env:USERPROFILE\.xlings\subos\current\bin" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append + + - name: Install project tools (.xlings.json) + run: | + for attempt in 1 2 3; do + xlings update > /dev/null 2>&1 || true + if xlings install; then break; fi + [ "$attempt" = 3 ] && exit 1 + sleep 30 + done + mcpp --version + + - name: Candidate index (compat.slint, slintgen) + run: | + mcpp index update + # No early exit in awk: mcpp would take SIGPIPE, and pipefail report it. + home=$(mcpp self env | awk -F'= *' '/^MCPP_HOME/ && !h {h = $2} END {print h}') + test -n "$home" + git init -q "$RUNNER_TEMP/index" + git -C "$RUNNER_TEMP/index" fetch -q --depth 1 https://github.com/mcpplibs/mcpp-index "$MCPP_INDEX_CANDIDATE" + git -C "$RUNNER_TEMP/index" checkout -q FETCH_HEAD + python3 "$RUNNER_TEMP/index/tests/prepare_builtin_index.py" --home "$home" + + - name: Select the toolchain + run: | + name="${{ matrix.toolchain }}" + mcpp toolchain install "${name%@*}" "${name#*@}" + mcpp toolchain default "$name" + + - name: Build the modules + run: mcpp build + + - name: Tests (the runtime types through the module; a component compiled at run time and driven headless) + run: mcpp test + + - name: Tests, release profile + run: mcpp test --profile release + + - name: mcpp.plugins.slint generates a component, its module, and runs it headless with the SDK the project declares + run: MCPP="$(command -v mcpp)" bash tests/rule-consumer/check-slint.sh + + - name: Export audit (the generated surface is fresh; every public name, key code and feature of the SDK's headers) + if: matrix.os == 'ubuntu-24.04' && matrix.toolchain == 'llvm@23.1.3' + run: | + export CLANGXX="$(ls -d "$HOME"/.mcpp/registry/data/xpkgs/xim-x-llvm/23.1.3/bin/clang++ "$HOME"/.xlings/data/xpkgs/xim-x-llvm/23.1.3/bin/clang++ 2>/dev/null | head -1)" + test -n "$CLANGXX" + python3 tools/check_exports.py diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..f0c6447 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,49 @@ +name: Release +on: + push: + tags: ["mwrap-*"] +permissions: + contents: read +jobs: + publish: + runs-on: ubuntu-latest + timeout-minutes: 30 + permissions: + contents: write + actions: read + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - name: Check tag, upstream version and bilingual entry pages + run: python3 tools/check_mwrap_release.py --tag "$GITHUB_REF_NAME" + - name: Require successful source CI at this exact commit + env: + GH_TOKEN: ${{ github.token }} + shell: bash + run: | + set -euo pipefail + result=$(gh run list --repo "$GITHUB_REPOSITORY" --workflow ci.yml --commit "$GITHUB_SHA" --limit 1 --json status,conclusion --jq '.[0] | .status == "completed" and .conclusion == "success"') + test "$result" = true || { echo 'No successful source CI at the tag commit'; exit 1; } + - name: Build immutable source asset and publish + env: + GH_TOKEN: ${{ github.token }} + shell: bash + run: | + set -euo pipefail + version="${GITHUB_REF_NAME#mwrap-}" + repo="${GITHUB_REPOSITORY#*/}" + asset="${repo}-${version}.tar.gz" + git archive --format=tar.gz --prefix="${repo}-${version}/" "$GITHUB_SHA" > "$RUNNER_TEMP/$asset" + (cd "$RUNNER_TEMP" && sha256sum "$asset" > "$asset.sha256") + if gh release view "$GITHUB_REF_NAME" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then + echo 'Release already exists; refusing to change immutable assets'; exit 1 + fi + extra=() + if [[ "$version" == *-rc* ]]; then extra+=(--prerelease); fi + gh release create "$GITHUB_REF_NAME" "$RUNNER_TEMP/$asset" "$RUNNER_TEMP/$asset.sha256" \ + --repo "$GITHUB_REPOSITORY" --verify-tag --title "$repo $version" \ + --notes "Module wrapper for upstream $version. New mwrap package identities become installable after mcpp-index publication; see the bilingual README for the tested support scope." "${extra[@]}" diff --git a/.github/workflows/templates.yml b/.github/workflows/templates.yml new file mode 100644 index 0000000..993f40b --- /dev/null +++ b/.github/workflows/templates.yml @@ -0,0 +1,37 @@ +name: Actual project templates +on: + push: + branches: [main] + pull_request: + workflow_dispatch: +permissions: + contents: read +concurrency: + group: templates-${{ github.ref }} + cancel-in-progress: true +env: + MCPP_VERSION: "2026.11.18.1" + # See ci.yml: the candidate index until compat.slint and mcpplibs.slintgen are published. + MCPP_INDEX_CANDIDATE: "4191fe3e1193ae4ce4360201ae0a45ca1c2e5463" +jobs: + templates: + runs-on: ubuntu-24.04 + timeout-minutes: 60 + steps: + - uses: actions/checkout@v4 + - name: Install the pinned mcpp + shell: bash + run: | + archive="mcpp-${MCPP_VERSION}-linux-x86_64.tar.gz" + curl -L -fsS -o "$archive" "https://github.com/mcpp-community/mcpp/releases/download/v${MCPP_VERSION}/$archive" + tar -xzf "$archive" + echo "$PWD/mcpp-${MCPP_VERSION}-linux-x86_64/bin" >> "$GITHUB_PATH" + - name: Candidate index + run: | + git init -q "$RUNNER_TEMP/index" + git -C "$RUNNER_TEMP/index" fetch -q --depth 1 https://github.com/mcpplibs/mcpp-index "$MCPP_INDEX_CANDIDATE" + git -C "$RUNNER_TEMP/index" checkout -q FETCH_HEAD + - name: Actual scaffold, strict build and headless run of the default template (hello) + env: + SLINT_HEADLESS: "1" + run: python3 tools/test_template.py --toolchain gcc@16.1.0 --index "$RUNNER_TEMP/index" diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b6dfbae --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +target +compile_commands.json +mcpp.lock +.mcpp/ +.xlings/ +doctor.log +__pycache__/ diff --git a/.xlings.json b/.xlings.json new file mode 100644 index 0000000..8aeb5c2 --- /dev/null +++ b/.xlings.json @@ -0,0 +1,5 @@ +{ + "workspace": { + "xim:mcpp": "2026.11.18.1" + } +} diff --git a/NOTICE b/NOTICE new file mode 100644 index 0000000..aa3a3a7 --- /dev/null +++ b/NOTICE @@ -0,0 +1,16 @@ +slint-m: C++ module wrapper +Copyright (c) 2026 mcpp-community contributors + +The wrapper contributions are licensed under the Apache License, Version 2.0. +Upstream code, copied interfaces and dependencies retain their original +licenses and copyright notices. Slint is available under the GNU GPLv3, the +Slint Royalty-free License 2.0 or the Slint Commercial License, at the user's +choice: + + Copyright © SixtyFPS GmbH + +Its README, LICENSE.md and the three license texts are retained in +upstream/slint/. The library and slint-compiler are compat.slint's (xim:slint, +built from the release tag); their own notices, including the third-party +crates linked, are the SDK's licenses/ directory, which compat.slint deploys. +Provenance and checksums are recorded in upstream/documents.json. diff --git a/README.md b/README.md new file mode 100644 index 0000000..0804f00 --- /dev/null +++ b/README.md @@ -0,0 +1,102 @@ +# Slint + +> Slint, the declarative GUI toolkit, through C++23 modules: its runtime API, the interpreter and `.slint` files compiled into modules. + +**English** · [简体中文](README.zh.md) · [Upstream](https://github.com/slint-ui/slint) · [Releases](https://github.com/mcpplibs/slint-m/releases) · [mcpp](https://github.com/mcpp-community/mcpp) · [Index](https://github.com/mcpplibs/mcpp-index) + +[![C++23](https://img.shields.io/badge/C%2B%2B-23-blue.svg)](https://en.cppreference.com/w/cpp/23) +[![License](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](LICENSE) +[![mcpp-community](https://img.shields.io/badge/mcpp--community-mwrap-blue)](https://github.com/mcpp-community) +[![CI](https://github.com/mcpplibs/slint-m/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/mcpplibs/slint-m/actions/workflows/ci.yml) + +The upstream API is unchanged: `slint::ComponentHandle`, `slint::SharedString`, +`slint::VectorModel`, `slint::interpreter::ComponentCompiler` are the names of +``. The SDK is `compat.slint` 1.19.0 (xim:slint: `libslint_cpp`, its +headers and `slint-compiler`, built from the release tag with upstream CMake's +default features). A `.slint` file is compiled by `mcpp.plugins.slint` (package +`mcpplibs.slintgen`, in `rules/` of this repository), which the project's `build.mcpp` +imports; with `module` set, each file becomes a module the program imports. + +## Modules + +- `import mcpplibs.mwrap.slint;`: `slint::` -- windows and components, `SharedString`, `SharedVector`, models, `Color`, `Brush`, `Image`, timers, the event loop, `slint::language` +- `import mcpplibs.mwrap.slint.interpreter;`: `slint::interpreter` -- `.slint` sources loaded at run time +- `import mcpplibs.mwrap.slint.platform;`: `slint::platform` -- a custom platform, the software renderer (Clang; with GCC include ``) +- `import mcpplibs.mwrap.slint.macros;`: `SLINT_FEATURE_*` as `constexpr bool` in `mcpplibs::mwrap::slint::macros` +- `import app.ui;`: a component of yours, from `ui/app.slint` (`mcpp.plugins.slint`, `options::module`) + +> More Modules API -> [Usage and API](docs/usage.md) + +## Getting started + +```sh +mcpp new counter --template mcpplibs.mwrap.slint@1.19.0 +cd counter +mcpp run +``` + +The default template opens a window with a counter; without a display (or with +`SLINT_HEADLESS=1`) it runs on Slint's software renderer and prints the counter. + +```toml +[dependencies] +mcpplibs.mwrap.slint = "1.19.0" + +[build-dependencies] +mcpplibs.slintgen = { version = "1.19.0", features = ["slint"] } # claims `.slint` + +[build] +sources = ["src/*.cpp", "ui/app.slint"] +``` + +```cpp +// build.mcpp +import mcpp; +import mcpp.plugins.slint; +int main() { + mcpp::plugins::slint::options o; + o.module = "app.ui"; + return mcpp::plugins::slint::compile(o) ? 0 : 1; +} +``` + +```cpp +// src/main.cpp +import mcpplibs.mwrap.slint; +import app.ui; + +int main() { + auto ui = AppWindow::create(); + ui->on_increase([&] { ui->set_counter(ui->get_counter() + 1); }); + ui->run(); +} +``` + +## Features of the SDK + +`compat.slint` 1.19.0 is upstream CMake's default desktop set: `interpreter`, +`backend-winit` (X11, Wayland, Windows, macOS), `renderer-femtovg` (OpenGL), +`renderer-software`, `accessibility`, `system-tray`, `testing`, and the compiler. +Skia, LinuxKMS, Qt and gettext are not in it. On Linux the library needs +fontconfig (xim:fontconfig) and the C runtime only; X11, Wayland and GL are loaded +when used. `mcpplibs::mwrap::slint::macros::SLINT_FEATURE_RENDERER_SKIA` and the +others say which features are present. + +## Build and testing + +Linux, macOS and Windows CI build the modules with GCC and Clang and run the tests: +the runtime types through the module, and a component compiled at run time by +`slint::interpreter` and driven headless through its properties and callbacks. The +export audit ([tools/check_exports.py](tools/check_exports.py)) reads clang's AST of +the SDK's headers: every public name exported, the key codes and features mapped, +the SDK's features upstream CMake's defaults. A separate job scaffolds the default +template as an installed package, builds it with `mcpp.plugins.slint` and runs it +headless. + +## License + +[Apache-2.0](LICENSE) for the wrapper, by mcpp-community ([NOTICE](NOTICE)). Slint is +available under the GNU GPLv3, the Slint Royalty-free License 2.0 (desktop, mobile +and web; not embedded) or the Slint Commercial License, at your choice +([upstream/slint/LICENSE.md](upstream/slint/LICENSE.md), [LICENSES](upstream/slint/LICENSES)). +The SDK's own notices, including the Rust crates it links, are deployed with programs. diff --git a/README.zh.md b/README.zh.md new file mode 100644 index 0000000..0a661c0 --- /dev/null +++ b/README.zh.md @@ -0,0 +1,94 @@ +# Slint + +> 通过 C++23 模块使用声明式 GUI 工具包 Slint:运行时 API、解释器,以及把 `.slint` 文件编译为模块。 + +[English](README.md) · **简体中文** · [上游](https://github.com/slint-ui/slint) · [发布](https://github.com/mcpplibs/slint-m/releases) · [mcpp](https://github.com/mcpp-community/mcpp) · [索引](https://github.com/mcpplibs/mcpp-index) + +[![C++23](https://img.shields.io/badge/C%2B%2B-23-blue.svg)](https://en.cppreference.com/w/cpp/23) +[![License](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](LICENSE) +[![mcpp-community](https://img.shields.io/badge/mcpp--community-mwrap-blue)](https://github.com/mcpp-community) +[![CI](https://github.com/mcpplibs/slint-m/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/mcpplibs/slint-m/actions/workflows/ci.yml) + +上游 API 保持不变:`slint::ComponentHandle`、`slint::SharedString`、`slint::VectorModel`、 +`slint::interpreter::ComponentCompiler` 就是 `` 里的名字。SDK 是 `compat.slint` +1.19.0(xim:slint:`libslint_cpp`、头文件和 `slint-compiler`,由发布 tag 按上游 CMake +默认功能构建)。`.slint` 文件由 `mcpp.plugins.slint`(包 `mcpplibs.slintgen`,在本仓库的 `rules/`)编译, +由工程的 `build.mcpp` 导入;设置 `module` 后,每个文件都成为程序可以 import 的模块。 + +## 模块 + +- `import mcpplibs.mwrap.slint;`:`slint::`,即窗口与组件、`SharedString`、`SharedVector`、模型、`Color`、`Brush`、`Image`、定时器、事件循环、`slint::language` +- `import mcpplibs.mwrap.slint.interpreter;`:`slint::interpreter`,运行时加载 `.slint` 源码 +- `import mcpplibs.mwrap.slint.platform;`:`slint::platform`,自定义平台与软件渲染器(Clang;GCC 下请 include ``) +- `import mcpplibs.mwrap.slint.macros;`:`SLINT_FEATURE_*` 映射为 `constexpr bool`,位于 `mcpplibs::mwrap::slint::macros` +- `import app.ui;`:你自己的组件,来自 `ui/app.slint`(`mcpp.plugins.slint` 的 `options::module`) + +> 更多模块 API -> [用法和 API](docs/usage.md) + +## 快速开始 + +```sh +mcpp new counter --template mcpplibs.mwrap.slint@1.19.0 +cd counter +mcpp run +``` + +默认模板打开一个带计数器的窗口;没有显示环境(或设置 `SLINT_HEADLESS=1`)时,用 Slint +的软件渲染器运行并打印计数。 + +```toml +[dependencies] +mcpplibs.mwrap.slint = "1.19.0" + +[build-dependencies] +mcpplibs.slintgen = { version = "1.19.0", features = ["slint"] } # 认领 `.slint` + +[build] +sources = ["src/*.cpp", "ui/app.slint"] +``` + +```cpp +// build.mcpp +import mcpp; +import mcpp.plugins.slint; +int main() { + mcpp::plugins::slint::options o; + o.module = "app.ui"; + return mcpp::plugins::slint::compile(o) ? 0 : 1; +} +``` + +```cpp +// src/main.cpp +import mcpplibs.mwrap.slint; +import app.ui; + +int main() { + auto ui = AppWindow::create(); + ui->on_increase([&] { ui->set_counter(ui->get_counter() + 1); }); + ui->run(); +} +``` + +## SDK 的功能 + +`compat.slint` 1.19.0 即上游 CMake 的桌面默认功能集:`interpreter`、`backend-winit` +(X11、Wayland、Windows、macOS)、`renderer-femtovg`(OpenGL)、`renderer-software`、 +`accessibility`、`system-tray`、`testing`,以及编译器。不含 Skia、LinuxKMS、Qt 与 gettext。 +Linux 上该库只依赖 fontconfig(xim:fontconfig)和 C 运行时;X11、Wayland 与 GL 在用到时 +动态加载。`mcpplibs::mwrap::slint::macros::SLINT_FEATURE_RENDERER_SKIA` 等常量说明哪些功能存在。 + +## 构建与测试 + +Linux、macOS 与 Windows 的 CI 用 GCC 和 Clang 构建模块并运行测试:经模块使用运行时类型, +以及由 `slint::interpreter` 在运行时编译组件、在无头平台上通过属性和回调驱动它。导出审计 +([tools/check_exports.py](tools/check_exports.py))读取 SDK 头文件的 clang AST:每个公开名字都已导出, +按键码与功能都已映射,SDK 的功能即上游 CMake 默认值。另有一个任务把默认模板当作已安装包生成项目, +经 `mcpp.plugins.slint` 构建并无头运行。 + +## 许可 + +封装层为 [Apache-2.0](LICENSE),作者 mcpp-community([NOTICE](NOTICE))。Slint 可在 GNU GPLv3、 +Slint 免版税许可 2.0(桌面、移动与 Web,不含嵌入式)或 Slint 商业许可中任选其一 +([upstream/slint/LICENSE.md](upstream/slint/LICENSE.md)、[LICENSES](upstream/slint/LICENSES))。 +SDK 自带的通知(含其链接的 Rust crate)随程序部署。 diff --git a/docs/rules.md b/docs/rules.md new file mode 100644 index 0000000..4d82d94 --- /dev/null +++ b/docs/rules.md @@ -0,0 +1,80 @@ +# `mcpp.plugins.slint` + +`mcpp.plugins.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. Package `mcpplibs.slintgen` (`rules/` of this repository), module `mcpp.plugins.slint`; engine floor 2026.10.1.3. + +## Use + +```toml +[build-dependencies] +mcpplibs.slintgen = { version = "1.19.0", features = ["slint"] } + +[dependencies] +mcpplibs.mwrap.slint = "1.19.0" # or compat.slint: the SDK as a package + +[build] +sources = ["src/*.cpp", "ui/app.slint"] +``` + +The project names the feature itself: `.slint` becomes a source the rule claims through the feature (`device_extensions`), and a claim made by a package another package re-exports does not reach the project. The module name `mcpp.plugins.slint` is the maintainers' choice; SPEC-007 R9.6 keeps `mcpp.plugins.*` for the mcpp project's namespace, so the engine prints one warning per build that a package outside it provides the module ("Nothing breaks"). + +```cpp +// build.mcpp +import mcpp.plugins.slint; + +int main() { + mcpp::plugins::slint::options o; + o.module = "app.ui"; // also write `export module app.ui;` + return mcpp::plugins::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 `mcpp.plugins.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/docs/usage.md b/docs/usage.md new file mode 100644 index 0000000..bac9eb2 --- /dev/null +++ b/docs/usage.md @@ -0,0 +1,35 @@ +# Using mcpplibs.mwrap.slint + +`import mcpplibs.mwrap.slint;` declares Slint 1.19.0's C++ API as `` does: every name is upstream's, the very same entity as the header's, so a translation unit may include the header too (before its imports). The SDK is `compat.slint` 1.19.0, a binding of `xim:slint`: `libslint_cpp`, its headers and `slint-compiler`, built from the release tag with upstream CMake's default features (xim-pkgindex `.agents/tools/slint/build-slint.sh`, published to xlings-res/slint). + +## Modules + +| Module | What it holds | +|---|---| +| `mcpplibs.mwrap.slint` | `slint::` (53 names): `ComponentHandle`, `ComponentWeakHandle`, `Window`, `SharedString`, `SharedVector`, `SharedPixelBuffer`, `Model`, `VectorModel`, `FilterModel`, `MapModel`, `SortModel`, `ReverseModel`, `Color`, `RgbaColor`, `HsvaColor`, `OklchColor`, `Brush`, `Image`, `StyledText`, `Timer`, `TimerMode`, `LogicalPosition` / `Size`, `PhysicalPosition` / `Size`, `run_event_loop`, `quit_event_loop`, `invoke_from_event_loop`, `blocking_invoke_from_event_loop`, `select_backend`, the translation functions …; and `slint::language` (18: `KeyEvent`, `PointerEvent`, `StandardListViewItem`, `TableColumn`, `SortOrder` …). Re-exports `.macros`. | +| `mcpplibs.mwrap.slint.interpreter` | `slint::interpreter`: `ComponentCompiler`, `ComponentDefinition`, `ComponentInstance`, `Value`, `Struct`, `Diagnostic` … | +| `mcpplibs.mwrap.slint.platform` | `slint::platform`: `Platform`, `WindowAdapter`, `AbstractRenderer`, `SoftwareRenderer`, `set_platform`, `update_timers_and_animations` …; the key codes (below). Clang only. | +| `mcpplibs.mwrap.slint.macros` | the 13 `SLINT_FEATURE_*` the headers test, as `inline constexpr bool` in `mcpplibs::mwrap::slint::macros` | + +`slint::private_api` and `slint::cbindgen_private` are what the headers' inline functions and generated code reach; they are reachable through the public types and exported by nothing. The source is generated by [tools/gen_exports.py](../tools/gen_exports.py) from clang's AST of the SDK's headers and audited by [tools/check_exports.py](../tools/check_exports.py). + +### GCC and the platform API + +GCC 16 reports "exposes TU-local entity" for `SoftwareRenderer::render_by_line` (a lambda in its requires-clause) and, with that class left out, crashes with an internal compiler error importing any module built over `slint-platform.h`. So `mcpplibs.mwrap.slint.platform` is empty under GCC; include `` before the imports, which is the same API under every compiler: + +```cpp +#include +import mcpplibs.mwrap.slint; +``` + +### Key codes + +`slint::platform::key_codes::A` and its 122 siblings are `constexpr char32_t` constants, whose internal linkage a module cannot export; each is defined, of its type and value, as `mcpplibs::mwrap::slint::platform::key_codes::A`. + +## Components from `.slint` files + +`mcpp.plugins.slint` (package `mcpplibs.slintgen`, `rules/` of this repository; declared in `[build-dependencies]` with `features = ["slint"]`, which also makes `.slint` a source the rule claims, and compat.slint re-exports `slint-compiler`) runs `slint-compiler` on each `.slint` file of `[build] sources`: one action per file, regenerated when the file or one it imports changes. Its options are upstream CMake's `slint_target_sources` and target properties (`ns`, `library_paths`, `compilation_units`, `edition`, `style`, `embed_resources`, `scale_factor`, `translation_domain`, `bundle_translations`); with `module = "app.ui"` each file also becomes a module exporting its windows, structs, enums and globals. See [rules.md](rules.md). + +## The SDK's features + +Upstream CMake's desktop defaults: `interpreter`, `backend-winit`, `renderer-femtovg`, `renderer-software`, `accessibility`, `system-tray`, `testing`, and the compiler. `SLINT_FEATURE_RENDERER_SKIA`, `BACKEND_QT`, `EXPERIMENTAL`, `FREESTANDING`, `LIVE_PREVIEW` and the image pixel formats are `false`; `slint::testing` is declared only with `EXPERIMENTAL`, so it is not here. On Linux the library NEEDs `libfontconfig.so.1` (xim:fontconfig) and the C runtime; X11, Wayland and GL are loaded when a window needs them. diff --git a/include/mwrap/slint/macros.hpp b/include/mwrap/slint/macros.hpp new file mode 100644 index 0000000..29fdca0 --- /dev/null +++ b/include/mwrap/slint/macros.hpp @@ -0,0 +1,5 @@ +// -- Slint's macros as macros: the SLINT_FEATURE_* +// tests (also `inline constexpr bool` in mcpplibs::mwrap::slint::macros) for +// #if. It is ; include it before the imports. +#pragma once +#include diff --git a/mcpp.toml b/mcpp.toml new file mode 100644 index 0000000..13a3727 --- /dev/null +++ b/mcpp.toml @@ -0,0 +1,55 @@ +# Module wrapper; upstream API preserved. Policy: mcpp-index/docs/mwrap.md. +[package] +namespace = "mcpplibs.mwrap" +name = "slint" +version = "1.19.0" +description = "Slint 1.19.0 C++ modules for mcpp (import mcpplibs.mwrap.slint;): the runtime API, the interpreter and the platform API over compat.slint, the features as constants; .slint files compile with mcpp.plugins.slint" +license = "Apache-2.0" +authors = ["mcpp-community"] +repo = "https://github.com/mcpplibs/slint-m" +platforms = ["linux", "macos", "windows"] + +[targets.slint] +kind = "lib" + +[build] +sources = ["src/*.cppm"] +# : 's macros (SLINT_FEATURE_*) for #if. +include_dirs = ["include"] + +[dependencies] +# The SDK: libslint_cpp, its headers and slint-compiler. Re-exported, so a +# consumer's build program finds slint-compiler in it (the rule +# mcpp.plugins.slint, package mcpplibs.slintgen, is rules/ of this repository). +compat.slint = { version = "1.19.0", reexport = true } + +[package.metadata.mwrap] +upstream-version = "1.19.0" + +[[runtime.deploy]] +from = "LICENSE" +to = "licenses/slint" + +[[runtime.deploy]] +from = "NOTICE" +to = "licenses/slint" + +[[runtime.deploy]] +from = "upstream/slint/README.md" +to = "licenses/slint/upstream/slint" + +[[runtime.deploy]] +from = "upstream/slint/LICENSE.md" +to = "licenses/slint/upstream/slint" + +[[runtime.deploy]] +from = "upstream/slint/LICENSES/GPL-3.0-only.txt" +to = "licenses/slint/upstream/slint/LICENSES" + +[[runtime.deploy]] +from = "upstream/slint/LICENSES/LicenseRef-Slint-Royalty-free-2.0.md" +to = "licenses/slint/upstream/slint/LICENSES" + +[[runtime.deploy]] +from = "upstream/slint/LICENSES/LicenseRef-Slint-Software-3.0.md" +to = "licenses/slint/upstream/slint/LICENSES" diff --git a/rules/mcpp.toml b/rules/mcpp.toml new file mode 100644 index 0000000..1e339a7 --- /dev/null +++ b/rules/mcpp.toml @@ -0,0 +1,45 @@ +# slintgen — how a `.slint` file becomes part of a C++ program, as a package. +# +# The module is `mcpp.plugins.slint` (rules/src/slint.cppm). A consumer's +# build.mcpp imports it: +# +# import mcpp; +# import mcpp.plugins.slint; +# int main() { return mcpp::plugins::slint::compile({}) ? 0 : 1; } +# +# It lives here, beside the modules whose Slint SDK it drives, as grpcgen lives +# in grpc-m: mcpp-plugins holds the rules that are not tied to one library's +# release, this repository the one that is. SPEC-007 R9.6 keeps `mcpp.plugins.*` +# for the mcpp project's own namespace, so the engine warns once per build that +# a package outside it provides this module; the name is the maintainer's +# choice and the warning is its price. +# +# Versioned with slint-m (and so with the Slint it is built against). +[package] +name = "slintgen" +version = "1.19.0" +standard = "c++23" +description = "slint-compiler as an importable mcpp build rule (module mcpp.plugins.slint)" +license = "Apache-2.0" +repo = "https://github.com/mcpplibs/slint-m" +platforms = ["linux", "macos", "windows"] + +# The rule reuses mcpp.plugins' tool resolution (`mcpp.plugins.tool`, feature +# `plugins-core`) and records its version as a fact. What a rule's module +# imports is in its `[dependencies]` (mcpp 2026.10.11.1+); a consumer's build +# program compiles it with the module. +[dependencies] +mcpp.plugins = { version = "0.26.1", features = ["plugins-core"] } + +# `.slint` is no extension the engine knows: the feature claims it, so a project +# lists `ui/app.slint` in `[build] sources` and the rule submits its action. +[features] +default = [] + +[features.slint] +sources = ["src/slint.cppm"] +rule_module = "mcpp.plugins.slint" +device_extensions = [".slint"] + +[targets.slintgen] +kind = "lib" diff --git a/rules/src/slint.cppm b/rules/src/slint.cppm new file mode 100644 index 0000000..1fd9f3e --- /dev/null +++ b/rules/src/slint.cppm @@ -0,0 +1,456 @@ +// mcpp.plugins.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("mcpp.plugins.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 mcpp.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.plugins.slint; + +import std; +import mcpp; +import mcpp.plugins; +import mcpp.plugins.tool; + +export namespace mcpp::plugins::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; +}; + +// The directory of the SDK package in the resolved graph. `dep_dir` answers for +// a dependency the project declares itself; a project that depends on +// `mcpplibs.mwrap.slint` reaches compat.slint through it, and only the graph +// document (`mcpp::graph_file()`, the root program's) names it. +inline std::string sdk_dir(const std::string& package) { + if (std::string dir = mcpp::dep_dir(package.c_str()); !dir.empty()) return dir; + const std::string graph = mcpp::graph_file(); + if (graph.empty()) return {}; + std::ifstream in{fs::path(graph), std::ios::binary}; + const std::string text{std::istreambuf_iterator(in), {}}; + const std::string key = "\"" + package + "@"; + const auto at = text.find(key); + if (at == std::string::npos) return {}; + // The entry's own `manifest_dir`: the first one after its canonical name. + static const std::regex dir_re(R"re("manifest_dir"\s*:\s*"((?:[^"\\]|\\.)*)")re"); + std::smatch m; + const auto from = text.cbegin() + static_cast(at); + if (!std::regex_search(from, text.cend(), m, dir_re)) return {}; + std::string out; + const std::string raw = m[1]; + for (std::size_t i = 0; i < raw.size(); ++i) { + if (raw[i] == '\\' && i + 1 < raw.size()) ++i; + out += raw[i]; + } + return out; +} + +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.plugins.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 = sdk_dir(opt.sdk_package); !dir.empty()) { + std::error_code ec; + // compat.slint links the SDK's bin/ into its directory; the links are followed. + for (auto it = fs::recursive_directory_iterator(dir, fs::directory_options::follow_directory_symlink, 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.plugins.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.plugins.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("mcpp.plugins.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.plugins.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::plugins::slint diff --git a/src/interpreter.cppm b/src/interpreter.cppm new file mode 100644 index 0000000..9e89ebe --- /dev/null +++ b/src/interpreter.cppm @@ -0,0 +1,25 @@ +// Generated by tools/gen_exports.py from Slint 1.19.0's SDK headers -- do not +// edit by hand. +// +// mcpplibs.mwrap.slint.interpreter -- loading `.slint` files at run time +// (ComponentCompiler, ComponentDefinition, ComponentInstance, Value …); needs +// the SDK's `interpreter` feature (SLINT_FEATURE_INTERPRETER). +module; +#include +#include + +export module mcpplibs.mwrap.slint.interpreter; + +export import mcpplibs.mwrap.slint; + +export namespace slint::interpreter { +using slint::interpreter::ComponentCompiler; +using slint::interpreter::ComponentDefinition; +using slint::interpreter::ComponentInstance; +using slint::interpreter::Diagnostic; +using slint::interpreter::DiagnosticLevel; +using slint::interpreter::PropertyDescriptor; +using slint::interpreter::Struct; +using slint::interpreter::Value; +using slint::interpreter::ValueType; +} // namespace slint::interpreter diff --git a/src/macros.cppm b/src/macros.cppm new file mode 100644 index 0000000..e693d05 --- /dev/null +++ b/src/macros.cppm @@ -0,0 +1,108 @@ +// Generated by tools/gen_exports.py from Slint 1.19.0's SDK headers -- do not +// edit by hand. +// +// mcpplibs.mwrap.slint.macros -- the SDK's features as `inline constexpr bool` +// in mcpplibs::mwrap::slint::macros, each true exactly when its SLINT_FEATURE_* +// macro is defined by the headers compat.slint provides; for `if constexpr`. +// (= ) keeps the macros for #if. +module; +#include + +namespace mwrap_slint_features { +#ifdef SLINT_FEATURE_ACCESSIBILITY +inline constexpr bool value_SLINT_FEATURE_ACCESSIBILITY = true; +#else +inline constexpr bool value_SLINT_FEATURE_ACCESSIBILITY = false; +#endif +#ifdef SLINT_FEATURE_BACKEND_QT +inline constexpr bool value_SLINT_FEATURE_BACKEND_QT = true; +#else +inline constexpr bool value_SLINT_FEATURE_BACKEND_QT = false; +#endif +#ifdef SLINT_FEATURE_BACKEND_WINIT +inline constexpr bool value_SLINT_FEATURE_BACKEND_WINIT = true; +#else +inline constexpr bool value_SLINT_FEATURE_BACKEND_WINIT = false; +#endif +#ifdef SLINT_FEATURE_EXPERIMENTAL +inline constexpr bool value_SLINT_FEATURE_EXPERIMENTAL = true; +#else +inline constexpr bool value_SLINT_FEATURE_EXPERIMENTAL = false; +#endif +#ifdef SLINT_FEATURE_FREESTANDING +inline constexpr bool value_SLINT_FEATURE_FREESTANDING = true; +#else +inline constexpr bool value_SLINT_FEATURE_FREESTANDING = false; +#endif +#ifdef SLINT_FEATURE_IMAGE_PIXEL_FORMAT_GRAY8 +inline constexpr bool value_SLINT_FEATURE_IMAGE_PIXEL_FORMAT_GRAY8 = true; +#else +inline constexpr bool value_SLINT_FEATURE_IMAGE_PIXEL_FORMAT_GRAY8 = false; +#endif +#ifdef SLINT_FEATURE_IMAGE_PIXEL_FORMAT_RGB565 +inline constexpr bool value_SLINT_FEATURE_IMAGE_PIXEL_FORMAT_RGB565 = true; +#else +inline constexpr bool value_SLINT_FEATURE_IMAGE_PIXEL_FORMAT_RGB565 = false; +#endif +#ifdef SLINT_FEATURE_INTERPRETER +inline constexpr bool value_SLINT_FEATURE_INTERPRETER = true; +#else +inline constexpr bool value_SLINT_FEATURE_INTERPRETER = false; +#endif +#ifdef SLINT_FEATURE_LIVE_PREVIEW +inline constexpr bool value_SLINT_FEATURE_LIVE_PREVIEW = true; +#else +inline constexpr bool value_SLINT_FEATURE_LIVE_PREVIEW = false; +#endif +#ifdef SLINT_FEATURE_RENDERER_FEMTOVG +inline constexpr bool value_SLINT_FEATURE_RENDERER_FEMTOVG = true; +#else +inline constexpr bool value_SLINT_FEATURE_RENDERER_FEMTOVG = false; +#endif +#ifdef SLINT_FEATURE_RENDERER_SKIA +inline constexpr bool value_SLINT_FEATURE_RENDERER_SKIA = true; +#else +inline constexpr bool value_SLINT_FEATURE_RENDERER_SKIA = false; +#endif +#ifdef SLINT_FEATURE_RENDERER_SOFTWARE +inline constexpr bool value_SLINT_FEATURE_RENDERER_SOFTWARE = true; +#else +inline constexpr bool value_SLINT_FEATURE_RENDERER_SOFTWARE = false; +#endif +#ifdef SLINT_FEATURE_TESTING +inline constexpr bool value_SLINT_FEATURE_TESTING = true; +#else +inline constexpr bool value_SLINT_FEATURE_TESTING = false; +#endif +} // namespace mwrap_slint_features +#undef SLINT_FEATURE_ACCESSIBILITY +#undef SLINT_FEATURE_BACKEND_QT +#undef SLINT_FEATURE_BACKEND_WINIT +#undef SLINT_FEATURE_EXPERIMENTAL +#undef SLINT_FEATURE_FREESTANDING +#undef SLINT_FEATURE_IMAGE_PIXEL_FORMAT_GRAY8 +#undef SLINT_FEATURE_IMAGE_PIXEL_FORMAT_RGB565 +#undef SLINT_FEATURE_INTERPRETER +#undef SLINT_FEATURE_LIVE_PREVIEW +#undef SLINT_FEATURE_RENDERER_FEMTOVG +#undef SLINT_FEATURE_RENDERER_SKIA +#undef SLINT_FEATURE_RENDERER_SOFTWARE +#undef SLINT_FEATURE_TESTING + +export module mcpplibs.mwrap.slint.macros; + +export namespace mcpplibs::mwrap::slint::macros { +inline constexpr bool SLINT_FEATURE_ACCESSIBILITY = mwrap_slint_features::value_SLINT_FEATURE_ACCESSIBILITY; +inline constexpr bool SLINT_FEATURE_BACKEND_QT = mwrap_slint_features::value_SLINT_FEATURE_BACKEND_QT; +inline constexpr bool SLINT_FEATURE_BACKEND_WINIT = mwrap_slint_features::value_SLINT_FEATURE_BACKEND_WINIT; +inline constexpr bool SLINT_FEATURE_EXPERIMENTAL = mwrap_slint_features::value_SLINT_FEATURE_EXPERIMENTAL; +inline constexpr bool SLINT_FEATURE_FREESTANDING = mwrap_slint_features::value_SLINT_FEATURE_FREESTANDING; +inline constexpr bool SLINT_FEATURE_IMAGE_PIXEL_FORMAT_GRAY8 = mwrap_slint_features::value_SLINT_FEATURE_IMAGE_PIXEL_FORMAT_GRAY8; +inline constexpr bool SLINT_FEATURE_IMAGE_PIXEL_FORMAT_RGB565 = mwrap_slint_features::value_SLINT_FEATURE_IMAGE_PIXEL_FORMAT_RGB565; +inline constexpr bool SLINT_FEATURE_INTERPRETER = mwrap_slint_features::value_SLINT_FEATURE_INTERPRETER; +inline constexpr bool SLINT_FEATURE_LIVE_PREVIEW = mwrap_slint_features::value_SLINT_FEATURE_LIVE_PREVIEW; +inline constexpr bool SLINT_FEATURE_RENDERER_FEMTOVG = mwrap_slint_features::value_SLINT_FEATURE_RENDERER_FEMTOVG; +inline constexpr bool SLINT_FEATURE_RENDERER_SKIA = mwrap_slint_features::value_SLINT_FEATURE_RENDERER_SKIA; +inline constexpr bool SLINT_FEATURE_RENDERER_SOFTWARE = mwrap_slint_features::value_SLINT_FEATURE_RENDERER_SOFTWARE; +inline constexpr bool SLINT_FEATURE_TESTING = mwrap_slint_features::value_SLINT_FEATURE_TESTING; +} // namespace mcpplibs::mwrap::slint::macros diff --git a/src/platform.cppm b/src/platform.cppm new file mode 100644 index 0000000..8b5c1d4 --- /dev/null +++ b/src/platform.cppm @@ -0,0 +1,287 @@ +// Generated by tools/gen_exports.py from Slint 1.19.0's SDK headers -- do not +// edit by hand. +// +// mcpplibs.mwrap.slint.platform -- the platform API: a Platform that creates +// window adapters, the software renderer, timers. Clang only (see +// tools/gen_exports.py): under GCC 16 the module is empty and a program +// includes before its imports. +// +// slint::platform::key_codes are `constexpr char32_t` constants, which have +// internal linkage and cannot be exported: each is captured here and +// defined, of its type and value, under its name in +// mcpplibs::mwrap::slint::platform::key_codes. +module; +#if defined(__clang__) +#include +#include + +namespace mwrap_slint_keys { +inline constexpr auto value_A = slint::platform::key_codes::A; +inline constexpr auto value_Alt = slint::platform::key_codes::Alt; +inline constexpr auto value_AltGr = slint::platform::key_codes::AltGr; +inline constexpr auto value_Ampersand = slint::platform::key_codes::Ampersand; +inline constexpr auto value_Asterisk = slint::platform::key_codes::Asterisk; +inline constexpr auto value_At = slint::platform::key_codes::At; +inline constexpr auto value_B = slint::platform::key_codes::B; +inline constexpr auto value_Back = slint::platform::key_codes::Back; +inline constexpr auto value_BackQuote = slint::platform::key_codes::BackQuote; +inline constexpr auto value_BackSlash = slint::platform::key_codes::BackSlash; +inline constexpr auto value_Backspace = slint::platform::key_codes::Backspace; +inline constexpr auto value_Backtab = slint::platform::key_codes::Backtab; +inline constexpr auto value_C = slint::platform::key_codes::C; +inline constexpr auto value_CapsLock = slint::platform::key_codes::CapsLock; +inline constexpr auto value_Circumflex = slint::platform::key_codes::Circumflex; +inline constexpr auto value_CloseBracket = slint::platform::key_codes::CloseBracket; +inline constexpr auto value_CloseCurlyBracket = slint::platform::key_codes::CloseCurlyBracket; +inline constexpr auto value_CloseParen = slint::platform::key_codes::CloseParen; +inline constexpr auto value_Colon = slint::platform::key_codes::Colon; +inline constexpr auto value_Comma = slint::platform::key_codes::Comma; +inline constexpr auto value_Control = slint::platform::key_codes::Control; +inline constexpr auto value_ControlR = slint::platform::key_codes::ControlR; +inline constexpr auto value_D = slint::platform::key_codes::D; +inline constexpr auto value_Delete = slint::platform::key_codes::Delete; +inline constexpr auto value_Digit0 = slint::platform::key_codes::Digit0; +inline constexpr auto value_Digit1 = slint::platform::key_codes::Digit1; +inline constexpr auto value_Digit2 = slint::platform::key_codes::Digit2; +inline constexpr auto value_Digit3 = slint::platform::key_codes::Digit3; +inline constexpr auto value_Digit4 = slint::platform::key_codes::Digit4; +inline constexpr auto value_Digit5 = slint::platform::key_codes::Digit5; +inline constexpr auto value_Digit6 = slint::platform::key_codes::Digit6; +inline constexpr auto value_Digit7 = slint::platform::key_codes::Digit7; +inline constexpr auto value_Digit8 = slint::platform::key_codes::Digit8; +inline constexpr auto value_Digit9 = slint::platform::key_codes::Digit9; +inline constexpr auto value_Dollar = slint::platform::key_codes::Dollar; +inline constexpr auto value_DoubleQuote = slint::platform::key_codes::DoubleQuote; +inline constexpr auto value_DownArrow = slint::platform::key_codes::DownArrow; +inline constexpr auto value_E = slint::platform::key_codes::E; +inline constexpr auto value_End = slint::platform::key_codes::End; +inline constexpr auto value_Equals = slint::platform::key_codes::Equals; +inline constexpr auto value_Escape = slint::platform::key_codes::Escape; +inline constexpr auto value_Exclamation = slint::platform::key_codes::Exclamation; +inline constexpr auto value_F = slint::platform::key_codes::F; +inline constexpr auto value_F1 = slint::platform::key_codes::F1; +inline constexpr auto value_F10 = slint::platform::key_codes::F10; +inline constexpr auto value_F11 = slint::platform::key_codes::F11; +inline constexpr auto value_F12 = slint::platform::key_codes::F12; +inline constexpr auto value_F13 = slint::platform::key_codes::F13; +inline constexpr auto value_F14 = slint::platform::key_codes::F14; +inline constexpr auto value_F15 = slint::platform::key_codes::F15; +inline constexpr auto value_F16 = slint::platform::key_codes::F16; +inline constexpr auto value_F17 = slint::platform::key_codes::F17; +inline constexpr auto value_F18 = slint::platform::key_codes::F18; +inline constexpr auto value_F19 = slint::platform::key_codes::F19; +inline constexpr auto value_F2 = slint::platform::key_codes::F2; +inline constexpr auto value_F20 = slint::platform::key_codes::F20; +inline constexpr auto value_F21 = slint::platform::key_codes::F21; +inline constexpr auto value_F22 = slint::platform::key_codes::F22; +inline constexpr auto value_F23 = slint::platform::key_codes::F23; +inline constexpr auto value_F24 = slint::platform::key_codes::F24; +inline constexpr auto value_F3 = slint::platform::key_codes::F3; +inline constexpr auto value_F4 = slint::platform::key_codes::F4; +inline constexpr auto value_F5 = slint::platform::key_codes::F5; +inline constexpr auto value_F6 = slint::platform::key_codes::F6; +inline constexpr auto value_F7 = slint::platform::key_codes::F7; +inline constexpr auto value_F8 = slint::platform::key_codes::F8; +inline constexpr auto value_F9 = slint::platform::key_codes::F9; +inline constexpr auto value_G = slint::platform::key_codes::G; +inline constexpr auto value_GreaterThan = slint::platform::key_codes::GreaterThan; +inline constexpr auto value_H = slint::platform::key_codes::H; +inline constexpr auto value_Hash = slint::platform::key_codes::Hash; +inline constexpr auto value_Home = slint::platform::key_codes::Home; +inline constexpr auto value_HyphenMinus = slint::platform::key_codes::HyphenMinus; +inline constexpr auto value_I = slint::platform::key_codes::I; +inline constexpr auto value_Insert = slint::platform::key_codes::Insert; +inline constexpr auto value_J = slint::platform::key_codes::J; +inline constexpr auto value_K = slint::platform::key_codes::K; +inline constexpr auto value_L = slint::platform::key_codes::L; +inline constexpr auto value_LeftArrow = slint::platform::key_codes::LeftArrow; +inline constexpr auto value_LessThan = slint::platform::key_codes::LessThan; +inline constexpr auto value_M = slint::platform::key_codes::M; +inline constexpr auto value_Menu = slint::platform::key_codes::Menu; +inline constexpr auto value_Meta = slint::platform::key_codes::Meta; +inline constexpr auto value_MetaR = slint::platform::key_codes::MetaR; +inline constexpr auto value_N = slint::platform::key_codes::N; +inline constexpr auto value_O = slint::platform::key_codes::O; +inline constexpr auto value_OpenBracket = slint::platform::key_codes::OpenBracket; +inline constexpr auto value_OpenCurlyBracket = slint::platform::key_codes::OpenCurlyBracket; +inline constexpr auto value_OpenParen = slint::platform::key_codes::OpenParen; +inline constexpr auto value_P = slint::platform::key_codes::P; +inline constexpr auto value_PageDown = slint::platform::key_codes::PageDown; +inline constexpr auto value_PageUp = slint::platform::key_codes::PageUp; +inline constexpr auto value_Pause = slint::platform::key_codes::Pause; +inline constexpr auto value_Percent = slint::platform::key_codes::Percent; +inline constexpr auto value_Period = slint::platform::key_codes::Period; +inline constexpr auto value_Pipe = slint::platform::key_codes::Pipe; +inline constexpr auto value_Plus = slint::platform::key_codes::Plus; +inline constexpr auto value_Q = slint::platform::key_codes::Q; +inline constexpr auto value_QuestionMark = slint::platform::key_codes::QuestionMark; +inline constexpr auto value_Quote = slint::platform::key_codes::Quote; +inline constexpr auto value_R = slint::platform::key_codes::R; +inline constexpr auto value_Return = slint::platform::key_codes::Return; +inline constexpr auto value_RightArrow = slint::platform::key_codes::RightArrow; +inline constexpr auto value_S = slint::platform::key_codes::S; +inline constexpr auto value_ScrollLock = slint::platform::key_codes::ScrollLock; +inline constexpr auto value_Semicolon = slint::platform::key_codes::Semicolon; +inline constexpr auto value_Shift = slint::platform::key_codes::Shift; +inline constexpr auto value_ShiftR = slint::platform::key_codes::ShiftR; +inline constexpr auto value_Slash = slint::platform::key_codes::Slash; +inline constexpr auto value_Space = slint::platform::key_codes::Space; +inline constexpr auto value_Stop = slint::platform::key_codes::Stop; +inline constexpr auto value_SysReq = slint::platform::key_codes::SysReq; +inline constexpr auto value_T = slint::platform::key_codes::T; +inline constexpr auto value_Tab = slint::platform::key_codes::Tab; +inline constexpr auto value_Tilde = slint::platform::key_codes::Tilde; +inline constexpr auto value_U = slint::platform::key_codes::U; +inline constexpr auto value_Underscore = slint::platform::key_codes::Underscore; +inline constexpr auto value_UpArrow = slint::platform::key_codes::UpArrow; +inline constexpr auto value_V = slint::platform::key_codes::V; +inline constexpr auto value_W = slint::platform::key_codes::W; +inline constexpr auto value_X = slint::platform::key_codes::X; +inline constexpr auto value_Y = slint::platform::key_codes::Y; +inline constexpr auto value_Z = slint::platform::key_codes::Z; +} // namespace mwrap_slint_keys +#endif + +export module mcpplibs.mwrap.slint.platform; + +export import mcpplibs.mwrap.slint; + +#if defined(__clang__) +export namespace slint::platform { +using slint::platform::AbstractRenderer; +using slint::platform::Platform; +using slint::platform::Rgb565Pixel; +using slint::platform::SkiaRenderer; +using slint::platform::SoftwareRenderer; +using slint::platform::WindowAdapter; +using slint::platform::duration_until_next_timer_update; +using slint::platform::set_platform; +using slint::platform::update_timers_and_animations; +} // namespace slint::platform + +export namespace mcpplibs::mwrap::slint::platform::key_codes { +inline constexpr auto A = mwrap_slint_keys::value_A; +inline constexpr auto Alt = mwrap_slint_keys::value_Alt; +inline constexpr auto AltGr = mwrap_slint_keys::value_AltGr; +inline constexpr auto Ampersand = mwrap_slint_keys::value_Ampersand; +inline constexpr auto Asterisk = mwrap_slint_keys::value_Asterisk; +inline constexpr auto At = mwrap_slint_keys::value_At; +inline constexpr auto B = mwrap_slint_keys::value_B; +inline constexpr auto Back = mwrap_slint_keys::value_Back; +inline constexpr auto BackQuote = mwrap_slint_keys::value_BackQuote; +inline constexpr auto BackSlash = mwrap_slint_keys::value_BackSlash; +inline constexpr auto Backspace = mwrap_slint_keys::value_Backspace; +inline constexpr auto Backtab = mwrap_slint_keys::value_Backtab; +inline constexpr auto C = mwrap_slint_keys::value_C; +inline constexpr auto CapsLock = mwrap_slint_keys::value_CapsLock; +inline constexpr auto Circumflex = mwrap_slint_keys::value_Circumflex; +inline constexpr auto CloseBracket = mwrap_slint_keys::value_CloseBracket; +inline constexpr auto CloseCurlyBracket = mwrap_slint_keys::value_CloseCurlyBracket; +inline constexpr auto CloseParen = mwrap_slint_keys::value_CloseParen; +inline constexpr auto Colon = mwrap_slint_keys::value_Colon; +inline constexpr auto Comma = mwrap_slint_keys::value_Comma; +inline constexpr auto Control = mwrap_slint_keys::value_Control; +inline constexpr auto ControlR = mwrap_slint_keys::value_ControlR; +inline constexpr auto D = mwrap_slint_keys::value_D; +inline constexpr auto Delete = mwrap_slint_keys::value_Delete; +inline constexpr auto Digit0 = mwrap_slint_keys::value_Digit0; +inline constexpr auto Digit1 = mwrap_slint_keys::value_Digit1; +inline constexpr auto Digit2 = mwrap_slint_keys::value_Digit2; +inline constexpr auto Digit3 = mwrap_slint_keys::value_Digit3; +inline constexpr auto Digit4 = mwrap_slint_keys::value_Digit4; +inline constexpr auto Digit5 = mwrap_slint_keys::value_Digit5; +inline constexpr auto Digit6 = mwrap_slint_keys::value_Digit6; +inline constexpr auto Digit7 = mwrap_slint_keys::value_Digit7; +inline constexpr auto Digit8 = mwrap_slint_keys::value_Digit8; +inline constexpr auto Digit9 = mwrap_slint_keys::value_Digit9; +inline constexpr auto Dollar = mwrap_slint_keys::value_Dollar; +inline constexpr auto DoubleQuote = mwrap_slint_keys::value_DoubleQuote; +inline constexpr auto DownArrow = mwrap_slint_keys::value_DownArrow; +inline constexpr auto E = mwrap_slint_keys::value_E; +inline constexpr auto End = mwrap_slint_keys::value_End; +inline constexpr auto Equals = mwrap_slint_keys::value_Equals; +inline constexpr auto Escape = mwrap_slint_keys::value_Escape; +inline constexpr auto Exclamation = mwrap_slint_keys::value_Exclamation; +inline constexpr auto F = mwrap_slint_keys::value_F; +inline constexpr auto F1 = mwrap_slint_keys::value_F1; +inline constexpr auto F10 = mwrap_slint_keys::value_F10; +inline constexpr auto F11 = mwrap_slint_keys::value_F11; +inline constexpr auto F12 = mwrap_slint_keys::value_F12; +inline constexpr auto F13 = mwrap_slint_keys::value_F13; +inline constexpr auto F14 = mwrap_slint_keys::value_F14; +inline constexpr auto F15 = mwrap_slint_keys::value_F15; +inline constexpr auto F16 = mwrap_slint_keys::value_F16; +inline constexpr auto F17 = mwrap_slint_keys::value_F17; +inline constexpr auto F18 = mwrap_slint_keys::value_F18; +inline constexpr auto F19 = mwrap_slint_keys::value_F19; +inline constexpr auto F2 = mwrap_slint_keys::value_F2; +inline constexpr auto F20 = mwrap_slint_keys::value_F20; +inline constexpr auto F21 = mwrap_slint_keys::value_F21; +inline constexpr auto F22 = mwrap_slint_keys::value_F22; +inline constexpr auto F23 = mwrap_slint_keys::value_F23; +inline constexpr auto F24 = mwrap_slint_keys::value_F24; +inline constexpr auto F3 = mwrap_slint_keys::value_F3; +inline constexpr auto F4 = mwrap_slint_keys::value_F4; +inline constexpr auto F5 = mwrap_slint_keys::value_F5; +inline constexpr auto F6 = mwrap_slint_keys::value_F6; +inline constexpr auto F7 = mwrap_slint_keys::value_F7; +inline constexpr auto F8 = mwrap_slint_keys::value_F8; +inline constexpr auto F9 = mwrap_slint_keys::value_F9; +inline constexpr auto G = mwrap_slint_keys::value_G; +inline constexpr auto GreaterThan = mwrap_slint_keys::value_GreaterThan; +inline constexpr auto H = mwrap_slint_keys::value_H; +inline constexpr auto Hash = mwrap_slint_keys::value_Hash; +inline constexpr auto Home = mwrap_slint_keys::value_Home; +inline constexpr auto HyphenMinus = mwrap_slint_keys::value_HyphenMinus; +inline constexpr auto I = mwrap_slint_keys::value_I; +inline constexpr auto Insert = mwrap_slint_keys::value_Insert; +inline constexpr auto J = mwrap_slint_keys::value_J; +inline constexpr auto K = mwrap_slint_keys::value_K; +inline constexpr auto L = mwrap_slint_keys::value_L; +inline constexpr auto LeftArrow = mwrap_slint_keys::value_LeftArrow; +inline constexpr auto LessThan = mwrap_slint_keys::value_LessThan; +inline constexpr auto M = mwrap_slint_keys::value_M; +inline constexpr auto Menu = mwrap_slint_keys::value_Menu; +inline constexpr auto Meta = mwrap_slint_keys::value_Meta; +inline constexpr auto MetaR = mwrap_slint_keys::value_MetaR; +inline constexpr auto N = mwrap_slint_keys::value_N; +inline constexpr auto O = mwrap_slint_keys::value_O; +inline constexpr auto OpenBracket = mwrap_slint_keys::value_OpenBracket; +inline constexpr auto OpenCurlyBracket = mwrap_slint_keys::value_OpenCurlyBracket; +inline constexpr auto OpenParen = mwrap_slint_keys::value_OpenParen; +inline constexpr auto P = mwrap_slint_keys::value_P; +inline constexpr auto PageDown = mwrap_slint_keys::value_PageDown; +inline constexpr auto PageUp = mwrap_slint_keys::value_PageUp; +inline constexpr auto Pause = mwrap_slint_keys::value_Pause; +inline constexpr auto Percent = mwrap_slint_keys::value_Percent; +inline constexpr auto Period = mwrap_slint_keys::value_Period; +inline constexpr auto Pipe = mwrap_slint_keys::value_Pipe; +inline constexpr auto Plus = mwrap_slint_keys::value_Plus; +inline constexpr auto Q = mwrap_slint_keys::value_Q; +inline constexpr auto QuestionMark = mwrap_slint_keys::value_QuestionMark; +inline constexpr auto Quote = mwrap_slint_keys::value_Quote; +inline constexpr auto R = mwrap_slint_keys::value_R; +inline constexpr auto Return = mwrap_slint_keys::value_Return; +inline constexpr auto RightArrow = mwrap_slint_keys::value_RightArrow; +inline constexpr auto S = mwrap_slint_keys::value_S; +inline constexpr auto ScrollLock = mwrap_slint_keys::value_ScrollLock; +inline constexpr auto Semicolon = mwrap_slint_keys::value_Semicolon; +inline constexpr auto Shift = mwrap_slint_keys::value_Shift; +inline constexpr auto ShiftR = mwrap_slint_keys::value_ShiftR; +inline constexpr auto Slash = mwrap_slint_keys::value_Slash; +inline constexpr auto Space = mwrap_slint_keys::value_Space; +inline constexpr auto Stop = mwrap_slint_keys::value_Stop; +inline constexpr auto SysReq = mwrap_slint_keys::value_SysReq; +inline constexpr auto T = mwrap_slint_keys::value_T; +inline constexpr auto Tab = mwrap_slint_keys::value_Tab; +inline constexpr auto Tilde = mwrap_slint_keys::value_Tilde; +inline constexpr auto U = mwrap_slint_keys::value_U; +inline constexpr auto Underscore = mwrap_slint_keys::value_Underscore; +inline constexpr auto UpArrow = mwrap_slint_keys::value_UpArrow; +inline constexpr auto V = mwrap_slint_keys::value_V; +inline constexpr auto W = mwrap_slint_keys::value_W; +inline constexpr auto X = mwrap_slint_keys::value_X; +inline constexpr auto Y = mwrap_slint_keys::value_Y; +inline constexpr auto Z = mwrap_slint_keys::value_Z; +} // namespace mcpplibs::mwrap::slint::platform::key_codes +#endif diff --git a/src/slint.cppm b/src/slint.cppm new file mode 100644 index 0000000..64a74c2 --- /dev/null +++ b/src/slint.cppm @@ -0,0 +1,91 @@ +// Generated by tools/gen_exports.py from Slint 1.19.0's SDK headers -- do not +// edit by hand. +// +// mcpplibs.mwrap.slint -- Slint's C++ runtime API: windows and components, +// properties' types (SharedString, SharedVector, Color, Brush, Image …), models, +// timers and the event loop, and slint::language. The names are upstream's; +// the library is compat.slint's libslint_cpp. A component compiled from a +// `.slint` file (mcpp.plugins.slint) is used beside this module. +module; +#include + +export module mcpplibs.mwrap.slint; + +export import mcpplibs.mwrap.slint.macros; + +export namespace slint { +using slint::BackendRequirements; +using slint::Brush; +using slint::CloseRequestResponse; +using slint::Color; +using slint::ComponentHandle; +using slint::ComponentWeakHandle; +using slint::DataTransfer; +using slint::EventLoopMode; +using slint::FilterModel; +using slint::GraphicsAPI; +using slint::Gray8Pixel; +using slint::HsvaColor; +using slint::Image; +using slint::Keys; +using slint::LogicalPosition; +using slint::LogicalSize; +using slint::MapModel; +using slint::Model; +using slint::OklchColor; +using slint::PhysicalPosition; +using slint::PhysicalSize; +using slint::Point; +using slint::PointerEventButton; +using slint::PointerEventKind; +using slint::RenderingState; +using slint::ReverseModel; +using slint::Rgb565Pixel; +using slint::Rgb8Pixel; +using slint::Rgba8Pixel; +using slint::RgbaColor; +using slint::SetRenderingNotifierError; +using slint::SharedPixelBuffer; +using slint::SharedString; +using slint::SharedVector; +using slint::Size; +using slint::SortModel; +using slint::StandardListViewItem; +using slint::StyledText; +using slint::Timer; +using slint::TimerMode; +using slint::VectorModel; +using slint::Window; +using slint::WindowKind; +using slint::blocking_invoke_from_event_loop; +using slint::invoke_from_event_loop; +using slint::operator!=; +using slint::operator==; +using slint::quit_event_loop; +using slint::run_event_loop; +using slint::select_backend; +using slint::select_bundled_translation; +using slint::set_xdg_app_id; +using slint::update_all_translations; + +namespace language { +using slint::language::AccessibleLiveness; +using slint::language::AccessibleRole; +using slint::language::CapitalizationMode; +using slint::language::ColorScheme; +using slint::language::DragAction; +using slint::language::DropEvent; +using slint::language::InputMethodHints; +using slint::language::KeyEvent; +using slint::language::KeyboardModifiers; +using slint::language::Orientation; +using slint::language::PointerEvent; +using slint::language::PointerEventButton; +using slint::language::PointerEventKind; +using slint::language::PointerScrollEvent; +using slint::language::ScrollBehavior; +using slint::language::SortOrder; +using slint::language::StandardListViewItem; +using slint::language::TableColumn; +} // namespace language +} // namespace slint diff --git a/templates/hello/build.mcpp.in b/templates/hello/build.mcpp.in new file mode 100644 index 0000000..9947966 --- /dev/null +++ b/templates/hello/build.mcpp.in @@ -0,0 +1,11 @@ +// ui/app.slint -> app.h and `export module app.ui;` (mcpp.plugins.slint, which +// package mcpplibs.slintgen runs on the SDK compat.slint provides). +import mcpp; +import mcpp.plugins.slint; + +int main() { + mcpp::plugins::slint::options o; + o.module = "app.ui"; + o.edition = "1.19"; + return mcpp::plugins::slint::compile(o) ? 0 : 1; +} diff --git a/templates/hello/mcpp.toml.in b/templates/hello/mcpp.toml.in new file mode 100644 index 0000000..7e24807 --- /dev/null +++ b/templates/hello/mcpp.toml.in @@ -0,0 +1,19 @@ +[package] +name = "{{project.name}}" +version = "0.1.0" + +[targets.{{project.name}}] +kind = "bin" +main = "src/main.cpp" + +[build] +# ui/app.slint reaches mcpp.plugins.slint, which writes app.h and the module app.ui. +sources = ["src/*.cpp", "ui/app.slint"] + +[dependencies] +{{self.name}} = "{{self.version}}" + +# The build rule: ui/app.slint -> app.h and the module app.ui. Its feature +# classifies `.slint` as a source the rule claims. +[build-dependencies] +mcpplibs.slintgen = { version = "{{self.version}}", features = ["slint"] } diff --git a/templates/hello/src/main.cpp.in b/templates/hello/src/main.cpp.in new file mode 100644 index 0000000..d50eb6c --- /dev/null +++ b/templates/hello/src/main.cpp.in @@ -0,0 +1,51 @@ +// {{project.name}} -- a Slint window: ui/app.slint is compiled into the module +// app.ui (mcpp.plugins.slint), the counter lives in C++. +// +// Without a display (Linux with neither DISPLAY nor WAYLAND_DISPLAY, or +// SLINT_HEADLESS=1) the program uses Slint's software renderer behind a +// headless platform, presses the button three times and prints the counter. +#include // before the imports (the platform API, under every compiler) + +import std; +import mcpplibs.mwrap.slint; +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 = 200 }); } +}; + +struct HeadlessPlatform : slint::platform::Platform { + std::unique_ptr create_window_adapter() override { + return std::make_unique(); + } +}; + +bool headless() { + if (const char* v = std::getenv("SLINT_HEADLESS"); v && *v && std::string_view(v) != "0") return true; +#if defined(__linux__) + return !std::getenv("DISPLAY") && !std::getenv("WAYLAND_DISPLAY"); +#else + return false; +#endif +} + +} // namespace + +int main() { + const bool offscreen = headless(); + if (offscreen) slint::platform::set_platform(std::make_unique()); + + auto ui = AppWindow::create(); + ui->on_increase([&] { ui->set_counter(ui->get_counter() + 1); }); + + if (offscreen) { + for (int i = 0; i < 3; ++i) ui->invoke_increase(); + std::println("{{project.name}}: headless, counter = {}", ui->get_counter()); + return ui->get_counter() == 3 ? 0 : 1; + } + ui->run(); +} diff --git a/templates/hello/template.toml b/templates/hello/template.toml new file mode 100644 index 0000000..e3a7070 --- /dev/null +++ b/templates/hello/template.toml @@ -0,0 +1,4 @@ +[template] +description = "A Slint window with import mcpplibs.mwrap.slint: ui/app.slint compiled by mcpp.plugins.slint into the module app.ui, a counter driven from C++" +default = true +post_message = "Run `mcpp run`: a window with a counter. Without a display (or with SLINT_HEADLESS=1) it runs on Slint's software renderer and prints the counter." diff --git a/templates/hello/ui/app.slint b/templates/hello/ui/app.slint new file mode 100644 index 0000000..45930ee --- /dev/null +++ b/templates/hello/ui/app.slint @@ -0,0 +1,12 @@ +import { Button, VerticalBox } from "std-widgets.slint"; + +export component AppWindow inherits Window { + title: "Hello, Slint"; + in-out property counter: 0; + callback increase(); + + VerticalBox { + Text { text: "Pressed \{root.counter} times"; horizontal-alignment: center; } + Button { text: "Press"; clicked => { root.increase(); } } + } +} diff --git a/tests/core_test.cpp b/tests/core_test.cpp new file mode 100644 index 0000000..c4947da --- /dev/null +++ b/tests/core_test.cpp @@ -0,0 +1,46 @@ +// Slint's runtime types through `import mcpplibs.mwrap.slint;` alone: strings, +// vectors, models, colours, brushes and geometry are the library's (every call +// below reaches libslint_cpp), and the SDK's features are constants. +import std; +import mcpplibs.mwrap.slint; + +namespace { +int failures = 0; +void check(bool ok, std::string_view what) { + std::println("{} {}", ok ? "ok " : "FAIL", what); + failures += !ok; +} +} // namespace + +int main() { + slint::SharedString s("Hello"); + s += ", Slint"; + check(std::string_view(s) == "Hello, Slint", "SharedString concatenates"); + check(slint::SharedString::from_number(42.5) == "42.5", "SharedString::from_number"); + + slint::SharedVector v{1, 2, 3}; + v.push_back(4); + check(v.size() == 4 && v[3] == 4, "SharedVector grows"); + + auto model = std::make_shared>(); + model->push_back("a"); + model->push_back("b"); + model->set_row_data(1, "c"); + check(model->row_count() == 2 && *model->row_data(1) == "c", "VectorModel rows"); + + auto red = slint::Color::from_rgb_uint8(255, 0, 0); + auto blue = slint::Color::from_rgb_uint8(0, 0, 255); + auto purple = red.mix(blue, 0.5f); + check(red.red() == 255 && purple.red() > 100 && purple.blue() > 100, "Color mixes"); + check(red.brighter(0.5f).red() == 255, "Color::brighter"); + check(slint::Brush(red).color() == red, "Brush of a colour"); + + slint::LogicalSize size({ .width = 3.f, .height = 4.f }); + check(size.width == 3.f && size.height == 4.f, "LogicalSize"); + + namespace m = mcpplibs::mwrap::slint::macros; + check(m::SLINT_FEATURE_INTERPRETER && m::SLINT_FEATURE_RENDERER_SOFTWARE && m::SLINT_FEATURE_BACKEND_WINIT, + "the default features are on"); + check(!m::SLINT_FEATURE_RENDERER_SKIA && !m::SLINT_FEATURE_EXPERIMENTAL, "Skia and the experimental API are off"); + return failures ? 1 : 0; +} diff --git a/tests/interpreter_test.cpp b/tests/interpreter_test.cpp new file mode 100644 index 0000000..90948e3 --- /dev/null +++ b/tests/interpreter_test.cpp @@ -0,0 +1,59 @@ +// A `.slint` source compiled at run time by slint::interpreter, instantiated +// on a headless platform (Slint's own software renderer) and driven through +// its properties and callbacks -- no generated code, no display. +#if !defined(__clang__) +#include // GCC 16: the platform module is Clang's (tools/gen_exports.py) +#endif + +import std; +import mcpplibs.mwrap.slint; +import mcpplibs.mwrap.slint.interpreter; +#if defined(__clang__) +import mcpplibs.mwrap.slint.platform; +#endif + +namespace { +int failures = 0; +void check(bool ok, std::string_view what) { + std::println("{} {}", ok ? "ok " : "FAIL", what); + failures += !ok; +} + +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 = 200, .height = 100 }); } +}; +struct HeadlessPlatform : slint::platform::Platform { + std::unique_ptr create_window_adapter() override { + return std::make_unique(); + } +}; + +constexpr std::string_view source = R"( +export component Counter inherits Window { + in-out property count: 1; + in property label: "clicks"; + callback bump(int) -> int; + bump(n) => { count += n; return count; } + Text { text: "\{label}: \{count}"; } +} +)"; +} // namespace + +int main() { + slint::platform::set_platform(std::make_unique()); + slint::interpreter::ComponentCompiler compiler; + auto definition = compiler.build_from_source(std::string(source), ""); + for (auto const& d : compiler.diagnostics()) std::println("diagnostic: {}", std::string_view(d.message)); + check(definition.has_value(), "the source compiles"); + if (!definition) return 1; + auto instance = definition->create(); + check(instance->get_property("count")->to_number() == 1.0, "the property's initial value"); + check(instance->set_property("label", slint::SharedString("taps")), "a property is set"); + auto result = instance->invoke("bump", std::array{slint::interpreter::Value(41.0)}); + check(result && result->to_number() == 42.0, "a callback runs and returns"); + check(instance->get_property("count")->to_number() == 42.0, "the callback changed the property"); + check(*instance->get_property("label")->to_string() == "taps", "the string property"); + return failures ? 1 : 0; +} diff --git a/tests/rule-consumer/build.mcpp b/tests/rule-consumer/build.mcpp new file mode 100644 index 0000000..d316865 --- /dev/null +++ b/tests/rule-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.plugins.slint; + +int main() { + mcpp::plugins::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::plugins::slint::compile(o) ? 0 : 1; +} diff --git a/tests/rule-consumer/check-slint.sh b/tests/rule-consumer/check-slint.sh new file mode 100755 index 0000000..f274ff0 --- /dev/null +++ b/tests/rule-consumer/check-slint.sh @@ -0,0 +1,30 @@ +#!/usr/bin/env bash +# mcpp.plugins.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/rule-consumer/mcpp.toml b/tests/rule-consumer/mcpp.toml new file mode 100644 index 0000000..0092f73 --- /dev/null +++ b/tests/rule-consumer/mcpp.toml @@ -0,0 +1,35 @@ +# Fixture: a Slint user interface compiled by mcpp.plugins.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 mcpp.plugins.slint" +license = "Apache-2.0" +authors = ["mcpp-community"] + +[language] +standard = "c++23" +modules = true +import_std = false + +[build-dependencies] +mcpplibs.slintgen = { path = "../../rules", features = ["slint"] } + +# 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/rule-consumer/src/main.cpp b/tests/rule-consumer/src/main.cpp new file mode 100644 index 0000000..df0d68c --- /dev/null +++ b/tests/rule-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/rule-consumer/ui/app.slint b/tests/rule-consumer/ui/app.slint new file mode 100644 index 0000000..2087d6d --- /dev/null +++ b/tests/rule-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/rule-consumer/ui/palette.slint b/tests/rule-consumer/ui/palette.slint new file mode 100644 index 0000000..d4442e3 --- /dev/null +++ b/tests/rule-consumer/ui/palette.slint @@ -0,0 +1 @@ +export global Palette { out property background: #202020; } diff --git a/tools/check_exports.py b/tools/check_exports.py new file mode 100644 index 0000000..bbb2464 --- /dev/null +++ b/tools/check_exports.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Audit the module surface against Slint's SDK headers. + +- src/*.cppm are what tools/gen_exports.py writes from the headers of the SDK + compat.slint binds (upstream/documents.json pins the archive): every name + declared directly in slint, slint::language, slint::interpreter and + slint::platform is exported, and every slint::platform::key_codes constant + (internal linkage) is defined in mcpplibs::mwrap::slint::platform::key_codes. +- Every SLINT_FEATURE_* the headers test is a constant of the macros module, + and the features the SDK defines are exactly upstream CMake's defaults. + +Reads clang's AST: pass --clang or set CLANGXX if clang++ is not on PATH or in +the toolchain mcpp installed. +""" +import argparse +from pathlib import Path +import re +import subprocess +import sys + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from inventory import fetch, find_clang, surface # noqa: E402 + +# api/cpp/cmake/SlintFeatures.cmake, desktop defaults, as the headers spell them +# (system-tray and the compiler state no macro). +DEFAULTS = {'SLINT_FEATURE_ACCESSIBILITY', 'SLINT_FEATURE_BACKEND_WINIT', 'SLINT_FEATURE_INTERPRETER', + 'SLINT_FEATURE_RENDERER_FEMTOVG', 'SLINT_FEATURE_RENDERER_SOFTWARE', 'SLINT_FEATURE_TESTING'} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--clang') + parser.add_argument('--sdk') + args = parser.parse_args() + root = Path(__file__).resolve().parents[1] + clang = find_clang(args.clang) + problems = [] + command = [sys.executable, str(root / 'tools/gen_exports.py'), '--check', '--clang', clang] + if args.sdk: + command += ['--sdk', args.sdk] + generated = subprocess.run(command, capture_output=True, text=True) + if generated.returncode != 0: + problems.append(generated.stderr.strip() or generated.stdout.strip()) + sf = surface(fetch(root, args.sdk), clang) + units = {ns: (root / f).read_text(encoding='utf-8') for ns, f in ( + ('slint', 'src/slint.cppm'), ('slint::language', 'src/slint.cppm'), + ('slint::interpreter', 'src/interpreter.cppm'), ('slint::platform', 'src/platform.cppm'))} + for ns, text in units.items(): + exported = set(re.findall(rf'^\s*using {re.escape(ns)}::(\w+(?:[=!<>]+)?);', text, flags=re.M)) + if set(sf.names[ns]) != exported: + problems.append(f'{ns}: missing {sorted(set(sf.names[ns]) - exported)}, extra {sorted(exported - set(sf.names[ns]))}') + keys = set(re.findall(r'^inline constexpr auto (\w+) = mwrap_slint_keys::', units['slint::platform'], flags=re.M)) + if keys != set(sf.names['slint::platform::key_codes']): + problems.append('key_codes differ from the header') + mapped = set(re.findall(r'^inline constexpr bool (SLINT_FEATURE_\w+) =', + (root / 'src/macros.cppm').read_text(encoding='utf-8'), flags=re.M)) + if mapped != set(sf.feature_universe): + problems.append(f'features: missing {sorted(set(sf.feature_universe) - mapped)}, extra {sorted(mapped - set(sf.feature_universe))}') + if set(sf.features) != DEFAULTS: + problems.append(f'the SDK defines {sf.features}, not upstream CMake\'s defaults {sorted(DEFAULTS)}') + if problems: + sys.exit('\n'.join(problems)) + print(f"slint {len(sf.names['slint'])}, slint::language {len(sf.names['slint::language'])}, " + f"slint::interpreter {len(sf.names['slint::interpreter'])}, slint::platform {len(sf.names['slint::platform'])} " + f"names exported; {len(keys)} key codes defined; {len(mapped)} features mapped, " + f"{len(sf.features)} defined (upstream CMake's defaults)") + + +if __name__ == '__main__': + main() diff --git a/tools/check_mwrap_release.py b/tools/check_mwrap_release.py new file mode 100644 index 0000000..9bedddb --- /dev/null +++ b/tools/check_mwrap_release.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python3 +"""Check the immutable mwrap release coordinate and bilingual entry pages.""" +import argparse +import hashlib +import json +from pathlib import Path +import re +import tomllib + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--tag', help='release tag; omitted during PR checks') + args = parser.parse_args() + root = Path(__file__).resolve().parents[1] + package = tomllib.loads((root / 'mcpp.toml').read_text(encoding="utf-8"))['package'] + assert package['namespace'] == 'mcpplibs.mwrap', package + assert re.fullmatch(r'[A-Za-z_][A-Za-z_0-9]*', package['name']), package['name'] + upstream = package['metadata']['mwrap']['upstream-version'] + version = package['version'] + assert version == upstream or re.fullmatch(re.escape(upstream) + r'\.[1-9][0-9]*', version), (version, upstream) + if args.tag: + assert args.tag == 'mwrap-' + version, (args.tag, version) + assert package['license'] == 'Apache-2.0', package['license'] + assert package['authors'] == ['mcpp-community'], package.get('authors') + license_text = (root / 'LICENSE').read_text(encoding='utf-8') + assert 'Apache License' in license_text and 'Version 2.0' in license_text + assert 'mcpp-community' in (root / 'NOTICE').read_text(encoding='utf-8') + documents = json.loads((root / 'upstream/documents.json').read_text(encoding='utf-8'))['documents'] + assert any(Path(d['path']).name.startswith('README') for d in documents) + assert any(Path(d['path']).name.startswith(('LICENSE', 'COPYING')) for d in documents) + deployed = {entry['from'] for entry in tomllib.loads((root / 'mcpp.toml').read_text(encoding='utf-8')).get('runtime', {}).get('deploy', [])} + assert {'LICENSE', 'NOTICE'} <= deployed + for document in documents: + path = Path(document['path']) + assert not path.is_absolute() and '..' not in path.parts and path.parts[0] == 'upstream' + assert hashlib.sha256((root / path).read_bytes()).hexdigest() == document['sha256'], path + assert document['source'] and path.as_posix() in deployed, path + identity = package['namespace'] + '.' + package['name'] + for name, other in [('README.md', 'README.zh.md'), ('README.zh.md', 'README.md')]: + text = (root / name).read_text(encoding="utf-8") + assert len(text.splitlines()) <= 150, name + assert '](' + other + ')' in '\n'.join(text.splitlines()[:12]), name + assert identity in text and version in text, name + assert text.count('```') % 2 == 0, name + print(identity + '@' + version) + + +if __name__ == '__main__': + main() diff --git a/tools/gen_exports.py b/tools/gen_exports.py new file mode 100644 index 0000000..717ae36 --- /dev/null +++ b/tools/gen_exports.py @@ -0,0 +1,140 @@ +#!/usr/bin/env python3 +"""Write the module units of mcpplibs.mwrap.slint from the SDK's headers. + + src/slint.cppm mcpplibs.mwrap.slint: namespace slint and + slint::language, by `using` (upstream's names) + src/interpreter.cppm mcpplibs.mwrap.slint.interpreter: slint::interpreter + src/platform.cppm mcpplibs.mwrap.slint.platform: slint::platform and + slint::platform::key_codes -- Clang only (below) + src/macros.cppm mcpplibs.mwrap.slint.macros: every SLINT_FEATURE_* the + headers test, as `inline constexpr bool` + +THE PLATFORM MODULE IS CLANG'S. GCC 16 reports "exposes TU-local entity" +for SoftwareRenderer::render_by_line (a lambda in its requires-clause), and, +with that class left out, crashes importing any module built over +slint-platform.h (an internal compiler error). Under GCC the unit declares the +module and nothing else; a program includes before its +imports, which is the same API. + +With --check, nothing is written and a difference fails. +""" +import argparse +from pathlib import Path +import sys + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from inventory import fetch, find_clang, surface # noqa: E402 + +BANNER = '// Generated by tools/gen_exports.py from Slint 1.19.0\'s SDK headers -- do not\n// edit by hand.' + + +def using_block(ns: str, names: list[str], indent: str = '') -> list[str]: + return [f'{indent}using {ns}::{n};' for n in names] + + +def core_unit(sf) -> str: + out = [BANNER, '//', + '// mcpplibs.mwrap.slint -- Slint\'s C++ runtime API: windows and components,', + '// properties\' types (SharedString, SharedVector, Color, Brush, Image …), models,', + '// timers and the event loop, and slint::language. The names are upstream\'s;', + '// the library is compat.slint\'s libslint_cpp. A component compiled from a', + '// `.slint` file (mcpp.plugins.slint) is used beside this module.', + 'module;', '#include ', '', 'export module mcpplibs.mwrap.slint;', '', + 'export import mcpplibs.mwrap.slint.macros;', '', 'export namespace slint {'] + out += using_block('slint', sf.names['slint']) + out += ['', 'namespace language {'] + out += using_block('slint::language', sf.names['slint::language']) + out += ['} // namespace language', '} // namespace slint'] + return '\n'.join(out) + '\n' + + +def interpreter_unit(sf) -> str: + out = [BANNER, '//', + '// mcpplibs.mwrap.slint.interpreter -- loading `.slint` files at run time', + '// (ComponentCompiler, ComponentDefinition, ComponentInstance, Value …); needs', + '// the SDK\'s `interpreter` feature (SLINT_FEATURE_INTERPRETER).', + 'module;', '#include ', '#include ', '', + 'export module mcpplibs.mwrap.slint.interpreter;', '', 'export import mcpplibs.mwrap.slint;', '', + 'export namespace slint::interpreter {'] + out += using_block('slint::interpreter', sf.names['slint::interpreter']) + out += ['} // namespace slint::interpreter'] + return '\n'.join(out) + '\n' + + +def platform_unit(sf) -> str: + keys = sf.names['slint::platform::key_codes'] + out = [BANNER, '//', + '// mcpplibs.mwrap.slint.platform -- the platform API: a Platform that creates', + '// window adapters, the software renderer, timers. Clang only (see', + '// tools/gen_exports.py): under GCC 16 the module is empty and a program', + '// includes before its imports.', + '//', + '// slint::platform::key_codes are `constexpr char32_t` constants, which have', + '// internal linkage and cannot be exported: each is captured here and', + '// defined, of its type and value, under its name in', + '// mcpplibs::mwrap::slint::platform::key_codes.', + 'module;', '#if defined(__clang__)', '#include ', '#include ', '', + 'namespace mwrap_slint_keys {'] + out += [f'inline constexpr auto value_{k} = slint::platform::key_codes::{k};' for k in keys] + out += ['} // namespace mwrap_slint_keys', '#endif', '', + 'export module mcpplibs.mwrap.slint.platform;', '', 'export import mcpplibs.mwrap.slint;', '', + '#if defined(__clang__)', 'export namespace slint::platform {'] + out += using_block('slint::platform', sf.names['slint::platform']) + out += ['} // namespace slint::platform', '', + 'export namespace mcpplibs::mwrap::slint::platform::key_codes {'] + out += [f'inline constexpr auto {k} = mwrap_slint_keys::value_{k};' for k in keys] + out += ['} // namespace mcpplibs::mwrap::slint::platform::key_codes', '#endif'] + return '\n'.join(out) + '\n' + + +def macros_unit(sf) -> str: + out = [BANNER, '//', + '// mcpplibs.mwrap.slint.macros -- the SDK\'s features as `inline constexpr bool`', + '// in mcpplibs::mwrap::slint::macros, each true exactly when its SLINT_FEATURE_*', + '// macro is defined by the headers compat.slint provides; for `if constexpr`.', + '// (= ) keeps the macros for #if.', + 'module;', '#include ', '', 'namespace mwrap_slint_features {'] + for f in sf.feature_universe: + out += [f'#ifdef {f}', f'inline constexpr bool value_{f} = true;', '#else', + f'inline constexpr bool value_{f} = false;', '#endif'] + out.append('} // namespace mwrap_slint_features') + out += [f'#undef {f}' for f in sf.feature_universe] + out += ['', 'export module mcpplibs.mwrap.slint.macros;', '', + 'export namespace mcpplibs::mwrap::slint::macros {'] + out += [f'inline constexpr bool {f} = mwrap_slint_features::value_{f};' for f in sf.feature_universe] + out.append('} // namespace mcpplibs::mwrap::slint::macros') + return '\n'.join(out) + '\n' + + +def render(sf) -> dict[str, str]: + return {'src/slint.cppm': core_unit(sf), 'src/interpreter.cppm': interpreter_unit(sf), + 'src/platform.cppm': platform_unit(sf), 'src/macros.cppm': macros_unit(sf)} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--check', action='store_true') + parser.add_argument('--clang') + parser.add_argument('--sdk') + args = parser.parse_args() + root = Path(__file__).resolve().parents[1] + files = render(surface(fetch(root, args.sdk), find_clang(args.clang))) + stale = [] + for relative, text in files.items(): + path = root / relative + if path.exists() and path.read_text(encoding='utf-8') == text: + continue + if args.check: + stale.append(relative) + else: + path.write_text(text, encoding='utf-8', newline='\n') + print('wrote', relative) + extra = sorted(p.relative_to(root).as_posix() for p in (root / 'src').glob('*.cppm') + if p.relative_to(root).as_posix() not in files) + stale += [f'{e} (not generated)' for e in extra] + if stale: + sys.exit('not what tools/gen_exports.py writes: ' + ', '.join(stale)) + + +if __name__ == '__main__': + main() diff --git a/tools/inventory.py b/tools/inventory.py new file mode 100644 index 0000000..bcf9546 --- /dev/null +++ b/tools/inventory.py @@ -0,0 +1,149 @@ +#!/usr/bin/env python3 +"""The public C++ surface of Slint's SDK headers, read by clang. + +Shared by tools/gen_exports.py (which writes the module units) and +tools/check_exports.py (which audits them). The headers are those of the SDK +compat.slint binds (xim:slint, built from the release tag): the pinned +payload is downloaded once into target/upstream and checked against +upstream/documents.json, or `--sdk ` names an extracted SDK. + +`clang++ -Xclang -ast-dump=json -Xclang -ast-dump-filter=slint` over +slint.h, slint-interpreter.h and slint-platform.h; the declarations directly +in each PUBLIC namespace are the surface: + + slint the runtime API (and slint::language, the types of + the language's built-in elements generated code uses) + slint::interpreter loading `.slint` files at run time + slint::platform the platform API (a window adapter, a renderer) + slint::platform::key_codes + +`slint::private_api` and `slint::cbindgen_private` are the implementation +generated code and the inline functions reach; they are reachable through the +public types and exported by nothing. Out-of-class member definitions at +namespace scope are not declarations of their own. +""" +from dataclasses import dataclass, field +import hashlib +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import sys +import tarfile +import tempfile +import urllib.request + +PUBLIC = ('slint', 'slint::language', 'slint::interpreter', 'slint::platform', 'slint::platform::key_codes') +KINDS = {'CXXRecordDecl', 'ClassTemplateDecl', 'EnumDecl', 'FunctionDecl', 'FunctionTemplateDecl', + 'TypeAliasDecl', 'TypeAliasTemplateDecl', 'TypedefDecl', 'VarDecl', 'UsingDecl'} +HEADERS = ('slint.h', 'slint-interpreter.h', 'slint-platform.h') + + +def fetch(root: Path, sdk: str | None = None) -> Path: + """The SDK root (bin/, lib/, include/slint/).""" + if sdk: + return Path(sdk) + pins = json.loads((root / 'upstream/documents.json').read_text(encoding='utf-8'))['sdk'] + cache = root / 'target/upstream' + cache.mkdir(parents=True, exist_ok=True) + archive = cache / Path(pins['url']).name + if not archive.exists() or hashlib.sha256(archive.read_bytes()).hexdigest() != pins['sha256']: + print('+ fetch', pins['url'], flush=True) + with urllib.request.urlopen(pins['url'], timeout=300) as response: + archive.write_bytes(response.read()) + digest = hashlib.sha256(archive.read_bytes()).hexdigest() + if digest != pins['sha256']: + sys.exit(f'SDK archive checksum {digest} != {pins["sha256"]}') + with tarfile.open(archive) as tar: + top = tar.getmembers()[0].name.split('/')[0] + if not (cache / top / 'include/slint/slint.h').exists(): + tar.extractall(cache, filter='data') + return cache / top + + +def find_clang(explicit: str | None = None) -> str: + for candidate in (explicit, os.environ.get('CLANGXX'), shutil.which('clang++')): + if candidate: + return candidate + for home in [Path(os.environ[v]) for v in ('MCPP_HOME', 'XLINGS_HOME') if os.environ.get(v)] + \ + [Path.home() / '.mcpp', Path.home() / '.xlings']: + found = sorted(home.glob('**/xim-x-llvm/*/bin/clang++*')) + if found: + return str(found[-1]) + sys.exit("clang++ not found: pass --clang or set CLANGXX (the audit reads clang's AST)") + + +@dataclass +class Surface: + names: dict[str, list[str]] = field(default_factory=dict) # namespace -> declared names + features: list[str] = field(default_factory=list) # SLINT_FEATURE_* the headers define + feature_universe: list[str] = field(default_factory=list) # every SLINT_FEATURE_* the headers test + + +def surface(sdk: Path, clang: str) -> Surface: + include = sdk / 'include/slint' + with tempfile.TemporaryDirectory() as tmp: + tu = Path(tmp) / 'surface.cc' + tu.write_text(''.join(f'#include <{h}>\n' for h in HEADERS)) + out = subprocess.run([clang, '-std=c++23', '-fsyntax-only', '-I', str(include), + '-Xclang', '-ast-dump=json', '-Xclang', '-ast-dump-filter=slint', str(tu)], + capture_output=True, text=True, check=True).stdout + decoder = json.JSONDecoder() + objects, i = [], 0 + while (j := out.find('{', i)) >= 0: + obj, i = decoder.raw_decode(out, j) + objects.append(obj) + nested = set() + + def mark(node): + for child in node.get('inner') or []: + nested.add(child.get('id')) + mark(child) + for o in objects: + mark(o) + s = Surface({ns: [] for ns in PUBLIC}) + + def visit(node, prefix): + for child in node.get('inner') or []: + kind = child['kind'] + if kind == 'NamespaceDecl': + visit(child, f"{prefix}::{child.get('name', '')}") + continue + if prefix not in s.names or kind not in KINDS or child.get('isImplicit'): + continue + name = child.get('name') + if not name: + continue + name = name.split('::')[-1] # `using cbindgen_private::TimerMode;` + if name.startswith('~') or name.startswith('operator'): + if not name.startswith('operator'): + continue + s.names[prefix].append(name) + for o in objects: + if o.get('id') not in nested and o['kind'] == 'NamespaceDecl' and o.get('name') == 'slint': + visit(o, 'slint') + for ns in s.names: + s.names[ns] = sorted(set(s.names[ns])) + generated = (include / 'private/slint_generated_public.h').read_text(encoding='utf-8') + s.features = sorted(set(re.findall(r'#define (SLINT_FEATURE_\w+)', generated))) + tested = set() + for h in include.rglob('*.h'): + tested |= set(re.findall(r'\b(SLINT_FEATURE_[A-Z0-9_]+)', h.read_text(encoding='utf-8'))) + s.feature_universe = sorted(tested | set(s.features)) + return s + + +if __name__ == '__main__': + import argparse + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--clang') + parser.add_argument('--sdk') + args = parser.parse_args() + root = Path(__file__).resolve().parents[1] + sf = surface(fetch(root, args.sdk), find_clang(args.clang)) + for ns, names in sf.names.items(): + print(f'{ns}: {len(names)}: {" ".join(names[:60])}') + print('features defined:', sf.features) + print('features tested:', sf.feature_universe) diff --git a/tools/test_template.py b/tools/test_template.py new file mode 100644 index 0000000..49db38f --- /dev/null +++ b/tools/test_template.py @@ -0,0 +1,98 @@ +#!/usr/bin/env python3 +"""Render an installed candidate's default mcpp template, then build and run it.""" +import argparse +import json +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import tomllib + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--mcpp", default="mcpp") + parser.add_argument("--namespace", help="index namespace for legacy manifests without package.namespace") + parser.add_argument("--toolchain", default="llvm@23.1.3") + parser.add_argument("--template", help="named template; omit for the package default") + parser.add_argument("--run-arg", action="append", default=[]) + parser.add_argument("--index", type=Path, help="candidate SDK/wrapper index for unpublished feature dependencies") + args = parser.parse_args() + root = Path(__file__).resolve().parents[1] + metadata = tomllib.loads((root / "mcpp.toml").read_text())["package"] + namespace = metadata.get("namespace", args.namespace) + assert namespace, "Supply the published index namespace for this legacy manifest" + name, version = metadata["name"], metadata["version"] + identity = namespace + "." + name + with tempfile.TemporaryDirectory(prefix=name + "-template-") as directory: + temporary = Path(directory) + home = temporary / "home" + package = home / "registry/data/xpkgs" / (namespace + "-x-" + name) / version / (name + "-" + version) + shutil.copytree(root, package, ignore=shutil.ignore_patterns( + ".git", "target", ".mcpp", ".xlings", ".candidate-index", "__pycache__", "mcpp.lock", "compile_commands.json", "mcpp-2026.*")) + index = home / "indices/mcpplibs/pkgs/mwrap" + index.mkdir(parents=True) + entry = '{url="https://example.invalid/candidate.tar.gz",sha256="fixture"}' + descriptor = ('package={spec="1",namespace=' + json.dumps(namespace) + ',name=' + json.dumps(name) + + ',description="Installed template fixture",type="package",xpm={') + descriptor += ",".join(platform + "={[" + json.dumps(version) + "]=" + entry + "}" + for platform in ("linux", "macosx", "windows")) + "}}\n" + (index / (identity + ".lua")).write_text(descriptor) + env = dict(os.environ, MCPP_HOME=str(home)) + selector = identity + "@" + version + for command in ([args.mcpp, "new", "--list-templates", selector], + [args.mcpp, "new", "quickstart", "--template", selector + (":" + args.template if args.template else "")]): + print("+", " ".join(command), flush=True) + subprocess.run(command, cwd=temporary, env=env, check=True) + project = temporary / "quickstart" + manifest = project / "mcpp.toml" + text = manifest.read_text() + dependency = tomllib.loads(text)["dependencies"] + for part in identity.split("."): + dependency = dependency[part] + options = {"version": dependency} if isinstance(dependency, str) else dependency + assert options["version"] == version, options + replacement = '{ path = ' + json.dumps(package.as_posix()) + if options.get("features"): + replacement += ', features = ' + json.dumps(options["features"]) + replacement += ' }' + lines = text.splitlines() + # The selector as one dotted key, unquoted (mcpp 2026.11.8.1 and later read a quoted one as deprecated). + matches = [i for i, line in enumerate(lines) if line.startswith(identity + " =")] + assert len(matches) == 1, "Expected exactly one qualified dependency from self.name" + lines[matches[0]] = identity + " = " + replacement + # The build rule is this repository's rules/: the scaffold's dependency on it, which + # names the index version a published release has, is the checkout's own copy here. + rule = tomllib.loads(text).get("build-dependencies", {}).get("mcpplibs", {}).get("slintgen") + if rule is not None: + rule = {"version": rule} if isinstance(rule, str) else rule + rule_line = 'mcpplibs.slintgen = { path = ' + json.dumps((package / "rules").as_posix()) + if rule.get("features"): + rule_line += ', features = ' + json.dumps(rule["features"]) + rule_line += ' }' + rule_at = [i for i, line in enumerate(lines) if line.startswith("mcpplibs.slintgen =")] + assert len(rule_at) == 1, "Expected exactly one mcpplibs.slintgen build dependency" + lines[rule_at[0]] = rule_line + manifest.write_text("\n".join(lines) + "\n") + if args.index: + candidate_index = args.index.resolve() + subprocess.run([os.sys.executable, str(candidate_index / "tests/prepare_mwrap_indices.py")], + cwd=candidate_index, check=True) + with manifest.open("a") as out: + out.write("\n[indices]\n") + for namespace in ("compat", "mcpplibs.mwrap"): + view = candidate_index / "tests/mwrap/.indices" / namespace + out.write(json.dumps(namespace) + ' = { path = ' + json.dumps(view.as_posix()) + ' }\n') + command = [args.mcpp, "build", "--toolchain", args.toolchain, "--strict"] + print("+", " ".join(command), flush=True) + subprocess.run(command, cwd=project, check=True) + command = [args.mcpp, "run", "--toolchain", args.toolchain] + if args.run_arg: + command += ["--", *args.run_arg] + print("+", " ".join(command), flush=True) + subprocess.run(command, cwd=project, check=True) + + +if __name__ == "__main__": + main() diff --git a/upstream/documents.json b/upstream/documents.json new file mode 100644 index 0000000..1da1784 --- /dev/null +++ b/upstream/documents.json @@ -0,0 +1,36 @@ +{ + "upstream": "https://github.com/slint-ui/slint/archive/refs/tags/v1.19.0.tar.gz", + "upstream_sha256": "9c15a9f6dfe94fbe96cb97dcb38207907403a67c9b23d8a93468ea1bb132246c", + "sdk": { + "url": "https://github.com/xlings-res/slint/releases/download/1.19.0/slint-1.19.0-default-linux-x86_64.tar.gz", + "sha256": "447194e4238f16249eb323cba9190a7deff38fc089617c614116b9aaaf17b43f" + }, + "pruning": "Nothing of Slint is vendored: the library is compat.slint 1.19.0, a binding of xim:slint, the C++ SDK built from the tag with upstream CMake's default features (xlings-res/slint). The module surface is generated from that SDK's headers (tools/gen_exports.py; `sdk` above is the archive it reads). Slint's README, LICENSE.md and the three license texts it offers are retained here.", + "documents": [ + { + "path": "upstream/slint/README.md", + "source": "https://github.com/slint-ui/slint/blob/v1.19.0/README.md", + "sha256": "63dbdb3575864dfc9382e5b9fbdb8b4f9d0e9d2193176b90699fadedd9724960" + }, + { + "path": "upstream/slint/LICENSE.md", + "source": "https://github.com/slint-ui/slint/blob/v1.19.0/LICENSE.md", + "sha256": "d767912198851eaeaabb8390515ae4eb7e2954f8b39e9cbc4711a5b057b26be0" + }, + { + "path": "upstream/slint/LICENSES/GPL-3.0-only.txt", + "source": "https://github.com/slint-ui/slint/blob/v1.19.0/LICENSES/GPL-3.0-only.txt", + "sha256": "b6a8bf63ae2c95b0aa256ee774680d7bd18f21f457da75466f7610b3b16acc4e" + }, + { + "path": "upstream/slint/LICENSES/LicenseRef-Slint-Royalty-free-2.0.md", + "source": "https://github.com/slint-ui/slint/blob/v1.19.0/LICENSES/LicenseRef-Slint-Royalty-free-2.0.md", + "sha256": "5167f5056e850419106ab6265efbdca7cba4d99c849d1445ca0bbf6a1e2315fe" + }, + { + "path": "upstream/slint/LICENSES/LicenseRef-Slint-Software-3.0.md", + "source": "https://github.com/slint-ui/slint/blob/v1.19.0/LICENSES/LicenseRef-Slint-Software-3.0.md", + "sha256": "a235744b92f4453fe18e081e54f29468a6a9db6a44e9a8f6364a48001ba4f10f" + } + ] +} diff --git a/upstream/slint/LICENSE.md b/upstream/slint/LICENSE.md new file mode 100644 index 0000000..ae09ae8 --- /dev/null +++ b/upstream/slint/LICENSE.md @@ -0,0 +1,58 @@ + +# Slint License + +This repository contains several parts under different licenses: + +- The **Slint framework** (the runtime libraries and the language tooling) is triple-licensed. + See below. +- The **documentation and examples** are under the [MIT License](LICENSES/MIT.txt), + so you can reuse them in any project, including proprietary ones. +- Some **third-party assets and code** keep their own licenses. + +The exact license of each file is documented in its header or, where that's not possible, via [REUSE](https://reuse.software/) metadata in `REUSE.toml`. +The full text of every license used is in the `LICENSES` folder. + +## Licenses of the Slint Framework + +You can use the Slint framework under ***any*** of the following licenses, at your choice: + +1. [Royalty-free License](LICENSES/LicenseRef-Slint-Royalty-free-2.0.md) - Permits use in **proprietary** desktop, mobile, and web applications **at no cost**. Use in embedded systems is excluded. +2. [GNU GPLv3](LICENSES/GPL-3.0-only.txt) - Permits use in **open source software** under GPL-compatible terms, **at no cost**, for desktop, mobile, and web applications, as well as for embedded systems. +3. [Commercial license](LICENSES/LicenseRef-Slint-Software-3.0.md) - Permits use in **proprietary** applications, including desktop, mobile, web, and embedded systems. + See the [pricing page](https://slint.dev/pricing) for the available plans. + +### What This Means in Practice + +- **Do you want to build an open-source application?** + Use Slint for free under the GPLv3 on any platform; your own files can stay MIT or Apache-2.0. + You're not tied to the GPL, though — the Royalty-free or Commercial license works too. +- **Do you want to keep your application proprietary?** + Both the Royalty-free and Commercial licenses cover proprietary desktop, mobile, and web applications. + The Royalty-free License is free, as long as you disclose that you use Slint (for example with the `AboutSlint` widget or the Slint badge); without that disclosure, use the Commercial license. + A Commercial license is required for embedded systems, regardless of disclosure. + +The Royalty-free License is meant for applications that run on a user's own general-purpose computer or phone, installed as one application among many. +It does not cover embedded systems — computer systems that perform a specific task within a larger mechanical or electrical system — which need the Commercial license. + +See the [Licensing FAQ](FAQ.md#licensing) for the details and common scenarios. + +## Definitions + +A ***Desktop Application*** is a computer program that is designed to run on a general-purpose computer (PC or notebook), typically installed and executed locally on the computer's operating system. + +A ***Mobile Application*** is a computer program that is designed to run on a general-purpose mobile computer (mobile phone or tablet), typically installed and executed locally on the computer's operating system. + +A ***Web Application*** is a computer program that is designed to run in the sandbox environment provided by a web browser. + +An ***Embedded System*** is a computer system designed to perform a specific task within a larger mechanical or electrical system. + +## Contributions + +Contributions to this repository are licensed under the [MIT No Attribution license (MIT-0)](https://opensource.org/license/mit-0). +This does not assign copyright or transfer ownership; contributors keep full rights to their own code. +See [CONTRIBUTING.md](CONTRIBUTING.md) for details. + +## Additional Info + +See the [Slint licensing options on the website](https://slint.dev/pricing) and the [Licensing FAQ](FAQ.md#licensing). +Contact us at [info@slint.dev](mailto:info@slint.dev) if you have any questions regarding licensing. diff --git a/upstream/slint/LICENSES/GPL-3.0-only.txt b/upstream/slint/LICENSES/GPL-3.0-only.txt new file mode 100644 index 0000000..d41c0bd --- /dev/null +++ b/upstream/slint/LICENSES/GPL-3.0-only.txt @@ -0,0 +1,232 @@ +GNU GENERAL PUBLIC LICENSE +Version 3, 29 June 2007 + +Copyright © 2007 Free Software Foundation, Inc. + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + +Preamble + +The GNU General Public License is a free, copyleft license for software and other kinds of works. + +The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. + +When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. + +To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. + +For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. + +Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. + +For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. + +Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. + +Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. + +The precise terms and conditions for copying, distribution and modification follow. + +TERMS AND CONDITIONS + +0. Definitions. + +“This License” refers to version 3 of the GNU General Public License. + +“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. + +“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations. + +To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work. + +A “covered work” means either the unmodified Program or a work based on the Program. + +To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. + +To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. + +An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. + +1. Source Code. +The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work. + +A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. + +The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. + +The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same work. + +2. Basic Permissions. +All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. + +3. Protecting Users' Legal Rights From Anti-Circumvention Law. +No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. + +When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. + +4. Conveying Verbatim Copies. +You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. + +5. Conveying Modified Source Versions. +You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”. + + c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. + +A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. + +6. Conveying Non-Source Forms. +You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: + + a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. + + d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. + +A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. + +“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. + +If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). + +The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. + +Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. + +7. Additional Terms. +“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or authors of the material; or + + e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. + +All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. + +8. Termination. +You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). + +However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. + +Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. + +9. Acceptance Not Required for Having Copies. +You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. + +10. Automatic Licensing of Downstream Recipients. +Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. + +An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. + +11. Patents. +A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”. + +A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. + +In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. + +If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. + +A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. + +12. No Surrender of Others' Freedom. +If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. + +13. Use with the GNU Affero General Public License. +Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. + +14. Revised Versions of this License. +The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. + +Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. + +15. Disclaimer of Warranty. +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. Limitation of Liability. +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +17. Interpretation of Sections 15 and 16. +If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. + +END OF TERMS AND CONDITIONS + +How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + +If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”. + +You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . + +The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . diff --git a/upstream/slint/LICENSES/LicenseRef-Slint-Royalty-free-2.0.md b/upstream/slint/LICENSES/LicenseRef-Slint-Royalty-free-2.0.md new file mode 100644 index 0000000..f087009 --- /dev/null +++ b/upstream/slint/LICENSES/LicenseRef-Slint-Royalty-free-2.0.md @@ -0,0 +1,43 @@ +# Slint Royalty-free Desktop, Mobile, and Web Applications License + +Version 2.0 + +## Preamble + +Slint is a toolkit that can be used to build user interfaces for applications. Slint (hereafter referred to as **Software**) is made available under different licenses by SixtyFPS GmbH incorporated at Oranienburger Str. 44, 16540 Hohen Neuendorf, Germany (**SixtyFPS**). The **Slint Royalty-free Desktop, Mobile, and Web Applications License** is suitable for those who develop desktop, mobile, or web applications and do not want to use open source components under copyleft licenses. + +## 1. Grant of Rights + +SixtyFPS hereby grants You a world-wide, royalty-free, non-exclusive license to use, reproduce, make available, modify, display, perform, distribute the Software as part of a Desktop, Mobile, or Web Application. + +A **Desktop Application** is a computer program that is designed to run on a general-purpose computer (PC or notebook), typically installed and executed locally on the computer's operating system. + +A **Mobile Application** is a computer program that is designed to run on a general-purpose mobile computer (mobile phone or tablet), typically installed and executed locally on the computer's operating system. + +A **Web Application** is a computer program that is designed to run in the sandbox environment provided by a web browser. + +Desktop Application, Mobile Application, and Web Application are hereafter referred to as **Application**. + +## 2. License Conditions - Attribution + +You may distribute the Software as part of an Application, modified or unmodified, provided that You do either of the following: + +(a) Display the [`AboutSlint`](https://docs.slint.dev/latest/docs/slint/reference/std-widgets/misc/aboutslint/) widget in an "About" screen or dialog that is accessible from the top level menu of the Application. In the absence of such a screen or dialog, display the widget in the "Splash Screen" of the Application. + +(b) Display the [Slint attribution badge](https://github.com/slint-ui/slint/tree/master/logo/MadeWithSlint-logo-whitebg.png) on a public webpage, preferably where the binaries of your Application can be downloaded from, in such a way that it can be easily found by any visitor to that page. + +## 3. Limitations + +The License does not permit to distribute or make the Software publicly available alone and without integration into an Application. For this purpose you may use the Software under the GNU General Public License, version 3. + +The License does not permit the use of the Software within Embedded Systems. An **Embedded System** is a computer system designed to perform a specific task within a larger mechanical or electrical system. + +The License does not permit the distribution of Application that exposes the APIs, in part or in total, of the Software. + +You may not remove or alter any license notices (including copyright notices, disclaimers of warranty, or limitations of liability) contained within the source code form of the Software. + +## 4. Warranty and Liability + +SixtyFPS is only liable for conflicting rights of third parties if SixtyFPS was aware of these rights without informing you. Unless required by applicable law or agreed to in writing, SixtyFPS provides the Software on an "as is" basis, without warranties or conditions of any kind, either express or implied, including, without limitation, any warranties or conditions of merchantability, or fitness for a particular purpose. + +Unless required by law, SixtyFPS won't be liable for any direct, indirect, incidental, or consequential damages arising in any way out of the use of the Software. diff --git a/upstream/slint/LICENSES/LicenseRef-Slint-Software-3.0.md b/upstream/slint/LICENSES/LicenseRef-Slint-Software-3.0.md new file mode 100644 index 0000000..e5db7d0 --- /dev/null +++ b/upstream/slint/LICENSES/LicenseRef-Slint-Software-3.0.md @@ -0,0 +1,117 @@ +# Slint Software License + +Version 3.0.5 + +## Preamble + +Slint is a toolkit that can be used to build user interfaces for applications. Slint (hereafter referred to as **Software**) is made available under different licenses by SixtyFPS GmbH incorporated at Oranienburger Str. 44, 16540 Hohen Neuendorf, Germany (**SixtyFPS**). The **Slint Software License** is suitable for those who do not want to use open source components under copyleft licenses. + +## 1. Grant of Rights + +SixtyFPS hereby grants You a world-wide, non-exclusive license to use, reproduce, make available, modify, display, perform, distribute the Software as part of a Desktop, Mobile, or Web Application or as part of an Embedded System (each of which is defined below). + +A **Desktop Application** is a computer program that is designed to run on a general-purpose computer (PC or notebook), typically installed and executed locally on the computer's operating system. + +A **Mobile Application** is a computer program that is designed to run on a general-purpose mobile computer (mobile phone or tablet), typically installed and executed locally on the computer's operating system. + +A **Web Application** is a computer program that is designed to run in the sandbox environment provided by a web browser. + +An **Embedded System** is a computer system designed to perform a specific task within a larger mechanical or electrical system. + +Desktop Application, Mobile Application, and Web Application are hereafter referred to as **Application**. + +## 2. License Conditions + +The grant of rights in section 1 are conditional, provided that You do all of the following: + +(a) You have purchased an appropriate **Paid License Plan** ([see Annex 1](#annex-1-paid-license-plans)) and the required amount of seats to cover all individual users of the Software associated with the designing, developing, or testing your Application or Embedded System. For clarity, each individual user is counted as one seat. + +(b) In the case that You are distributing the Software as part of an Embedded System, You have purchased an appropriate quantity of **Royalties**, one Royalty for each Embedded System. Royalties become due and payable upon manufacture of the Embedded System, regardless of whether such is subsequently sold, shipped, returned, replaced under warranty, or recalled. Payment of royalties is non-refundable under any circumstances. Royalties are not necessary for non-commercial projects, personal projects, and open source projects. + +## 3. Limitations + +The License does not permit to distribute or make the Software publicly available alone and without integration into an Application or into an Embedded System. For this purpose you may use the Software under the GNU General Public License, version 3. + +The License is limited to only the versions of Software that were made available to you under the Paid License Plan. For all other versions, you may use the Software under either the GNU General Public License, version 3 or the Slint Royalty-free Desktop, Mobile, and Web Applications License. + +The License does not permit the distribution of Application that exposes the APIs, in part or in total, of the Software. + +You may not remove or alter any license notices (including copyright notices, disclaimers of warranty, or limitations of liability) contained within the source code form of the Software. + +## 4. Audit Rights + +SixtyFPS or an independent certified auditor on SixtyFPS's behalf, may, upon its reasonable request, with 30 (thirty) days written notice, and at its sole expense, examine your books and records solely with respect to your use of the Software. Any such audit shall be conducted during regular business hours at your facilities and shall not unreasonably interfere with your business activities. The auditor shall not remove, copy, or redistribute any electronic material during an audit. If an audit reveals that you are using the Software in a way that is in material violation of the terms of this License, then you shall pay SixtyFPS reasonable costs of conducting the audit. The auditor shall only be allowed to report violations of the terms of this License, with a copy to you. You shall be provided the right to provide comments to the report before it is finalized. + +## 5. Termination + +(a) SixtyFPS may terminate this License if You materially breach any obligation hereunder, provided You have been provided notice of such breach and an opportunity to cure such breach during a period of not less than sixty (60) days following such notice. + +(b) You may terminate this License with or without cause upon no less than thirty (30) days advance written notice to SixtyFPS. + +(c) Upon termination of this License, You will immediately cease using, reproducing, making available, modifying, displaying, performing, distributing the Software and pay immediately any unpaid Fees and contractual penalties. + +(d) Sections 3 through 8 of this License will survive any termination of the License to the extent necessary to implement their objectives. + +## 6. Assignment + +You may assign this License, in whole or in part (whether by operation of law or otherwise), with prior consent from SixtyFPS, which shall not be unreasonably withheld or delayed. SixtyFPS may assign any of its rights or delegate any of its obligations hereunder with prior notice to You, provided that the successor maintains at least the same level of security, confidentiality, and data protection measures as in place at the time of assignment or delegation. Any attempt to assign this License other than in accordance with this Section 6 shall be null and void. + +## 7. Severability + +In the event that any provision of this License will, for any reason, be determined by any court of competent jurisdiction to be invalid, illegal or unenforceable in any respect, such invalidity, illegality or unenforceability will be interpreted as closely as possible so as not affect any other provision of this License, and such provision will further be modified by said court to permit its enforcement to the maximum extent permitted by law. + +## 8. Governing Law + +This Agreement shall be construed, interpreted, and governed by the laws of the Federal Republic of Germany. + +## Annex 1: Paid License Plans + +### Enterprise Plan + +The following is included as part of the plan + +(a) No restriction on the number of applications that are developed with Slint. + +(b) Live Preview. + +(c) Standard Support that includes addressing technical queries, troubleshooting, and rectifying bugs or errors (faults) present in the latest official stable release. + +(d) Perpetual Fallback License that allows continued use of a specific Slint version, including all bugfix updates (i.e., all Z releases within the X.Y.Z version), without an active subscription. This license applies only to those versions of Slint for which at least 12 consecutive months of subscription have been paid. + +(e) GUI Test Framework. + +### Small Enterprise Plan + +This plan is limited to individual companies with a staff headcount of upto 50 and either a turnover or balance sheet total of 10 million EUR or less. If You are a Small Enterprise, You are required to submit the self-assessment report generated from the EU SME Self-Assessment Tool (https://ec.europa.eu/info/funding-tenders/opportunities/portal/sme/public/organisation-name). + +The following is included as part of the plan + +(a) No restriction on the number of applications that are developed with Slint. + +(b) Live Preview. + +(c) Standard Support that includes addressing technical queries, troubleshooting, and rectifying bugs or errors (faults) present in the latest official stable release. + +The following can be purchased as an Add-On + +(a) Perpetual Fallback License that allows continued use of a specific Slint version, including all bugfix updates (i.e., all Z releases within the X.Y.Z version), without an active subscription. This license applies only to those versions of Slint for which at least 12 consecutive months of subscription have been paid. + +(b) GUI Test Framework. + +### Startup & Individual Plan + +This plan is limited to individuals and individual companies with a staff headcount of less than 10 and either a turnover or balance sheet total of 2 million EUR or less. If You are a Startup, you are required to submit the self-assessment report generated from the EU SME Self-Assessment Tool (https://ec.europa.eu/info/funding-tenders/opportunities/portal/sme/public/organisation-name). + +The following is included as part of the plan + +(a) No restriction on the number of applications that are developed with Slint. + +(b) Live Preview. + +The following can be purchased as an Add-On + +(a) Standard Support that includes addressing technical queries, troubleshooting, and rectifying bugs or errors (faults) present in the latest official stable release. + +(b) Perpetual Fallback License that allows continued use of a specific Slint version, including all bugfix updates (i.e., all Z releases within the X.Y.Z version), without an active subscription. This license applies only to those versions of Slint for which at least 12 consecutive months of subscription have been paid. + +(c) GUI Test Framework. diff --git a/upstream/slint/README.md b/upstream/slint/README.md new file mode 100644 index 0000000..22b2692 --- /dev/null +++ b/upstream/slint/README.md @@ -0,0 +1,241 @@ + +![Slint](./logo/slint-logo-full-light.svg#gh-light-mode-only) ![Slint](./logo/slint-logo-full-dark.svg#gh-dark-mode-only) + +[![Build Status](https://github.com/slint-ui/slint/actions/workflows/ci.yaml/badge.svg?branch=master)](https://github.com/slint-ui/slint/actions/workflows/ci.yaml) +[![REUSE status](https://api.reuse.software/badge/github.com/slint-ui/slint)](https://api.reuse.software/info/github.com/slint-ui/slint) +[![Discussions](https://img.shields.io/github/discussions/slint-ui/slint)](https://github.com/slint-ui/slint/discussions) + +**Slint** is an open-source declarative GUI toolkit to build native user interfaces for any device. +Write your UI in `.slint`, a simple markup language, and connect it to business logic written in Rust, C++, JavaScript, or Python. +Slint scales from desktop apps to mobile apps on Android and iOS, +and down to embedded Linux and microcontrollers such as STM32, ESP32, and RP2040. + +## Why Slint? + +The name *Slint* is derived from our design goals: + +- **Scalable**: Slint should support responsive UI design, allow cross-platform + usage across operating systems and processor architectures and support + multiple programming languages. +- **Lightweight**: Slint should require minimal resources, in terms of memory + and processing power, and yet deliver a smooth, smartphone-like user + experience on any device. +- **Intuitive**: Designers and developers should feel productive while enjoying + the GUI design and development process. The design creation tools should be + intuitive to use for the designers. Similarly for the developers, the APIs + should be consistent and easy to use, no matter which programming language + they choose. +- **Native**: GUI built with Slint should match the end users' expectations of a + native application irrespective of the platform - desktop, mobile, web or + embedded system. The UI design should be compiled to machine code and provide + flexibility that only a native application can offer: Access full operating + system APIs, utilize all CPU and GPU cores, connect to any peripheral. + +Beyond the design goals, here’s what makes Slint stand out: + +- **Independent UI Design**: Use a declarative language to separate your UI from business logic. Designers can work in parallel with developers. +- **Tooling**: Iterate quickly with our Live Preview & editor integrations. Integrate from Figma with the [Figma to Slint plugin](https://www.figma.com/community/plugin/1474418299182276871/figma-to-slint). +- **Stable APIs**: Slint follows a stable 1.x API. We evolve carefully without breaking your code. + +See what others have built: [#MadeWithSlint](https://madewithslint.com) + +## Examples + +### Embedded + +| RaspberryPi | STM32 | RP2040 | +| ------------------------------------ | ----------------------------- | ------------------------------ | +| [Video of Slint on Raspberry Pi][#1] | [Video of Slint on STM32][#2] | [Video of Slint on RP2040][#3] | + +### Desktop + +| Windows | macOS | Linux | +| ------------------------------------------- | ----------------------------------------- | ----------------------------------------- | +| ![Screenshot of the Gallery on Windows][#4] | ![Screenshot of the Gallery on macOS][#5] | ![Screenshot of the Gallery on Linux][#6] | + +### Web using WebAssembly + +| Printer Demo | Slide Puzzle | Energy Monitor | Widget Gallery | Weather demo | +| ------------------------------------------- | -------------------------------------------- | ---------------------------------------------------- | --------------------------------------------- | --------------------------------------------- | +| [![Screenshot of the Printer Demo][#7]][#8] | [![Screenshot of the Slide Puzzle][#9]][#10] | [![Screenshot of the Energy Monitor Demo][#11]][#12] | [![Screenshot of the Gallery Demo][#13]][#14] | [![Screenshot of the weather Demo][#29]][#30] | + +More examples and demos in the [examples folder](examples#examples) + +## Get Started + +### Hello World + +The UI is defined in a Domain Specific Language that is declarative, easy to use, +intuitive, and provides a powerful way to describe graphical elements, their +placement, their hierarchy, property bindings, and the flow of data through the +different states. + +Here's the obligatory "Hello World": + +```slint +export component HelloWorld inherits Window { + width: 400px; + height: 400px; + + Text { + y: parent.width / 2; + x: parent.x + 200px; + text: "Hello, world"; + color: blue; + } +} +``` + +### Documentation + +For more details, check out the [Slint Documentation](https://docs.slint.dev). + +The [examples](examples) folder contains examples and demos, showing how to +use the Slint markup language and how to interact with a Slint user interface +from supported programming languages. + +The `docs` folder contains a lot more information, including +[build instructions](docs/building.md), and +[internal developer docs](docs/development.md). + +Refer to the README of each language directory in the `api` folder: + +- [C++](api/cpp) ([Documentation][#15] | [Getting Started Template][#17]) +- [Rust](api/rs/slint) [![Crates.io][#18]][#19] ([Documentation][#20] | [Tutorial Video][#22] | [Getting Started Template][#23]) +- [JavaScript/NodeJS (Beta)](api/node) [![npm][#24]][#25] ([Documentation][#26] | [Getting Started Template][#28]) +- [Python (Beta)](api/python/slint) [![pypi][#31]][#32] ([Documentation][#33] | [Getting Started Template][#34]) + +## Architecture + +An application is composed of the business logic written in Rust, C++, Python, or +JavaScript and the `.slint` user interface design markup, which is compiled to +native code. + +![Architecture Overview](https://slint.dev/resources/slint_architecture_block_diagram.svg) + +### Compiler + +The `.slint` files are compiled ahead of time. The expressions in the `.slint` +are pure functions that the compiler can optimize. For example, the compiler +could choose to "inline" properties and remove those that are constant or +unchanged. + +The compiler uses the typical compiler phases of lexing, parsing, optimization, +and finally code generation. It provides different back-ends for code generation +in the target language. The C++ code generator produces a C++ header file, the +Rust generator produces Rust code, and so on. An interpreter for dynamic +languages is also included. + +### Runtime + +The runtime library consists of an engine that supports properties declared in +the `.slint` language. Components with their elements, items, and properties are +laid out in a single memory region, to reduce memory allocations. + +Rendering backends and styles are configurable at compile time: + +- The `femtovg` renderer uses OpenGL ES 2.0 for rendering. +- The `skia` renderer uses [Skia](https://skia.org) for rendering. +- The `software` renderer uses the CPU with no additional dependencies. + +NOTE: When Qt is installed on the system, the `qt` style becomes available, +using Qt's QStyle to achieve native looking widgets. + +### Tooling + +We have a few tools to help with the development of .slint files: + +- A [**LSP Server**](./tools/lsp) that adds features like auto-complete and live + preview of the .slint files to many editors. +- It is bundled in a [**Visual Studio Code Extension**](./editors/vscode) + available from the market place. +- A [**slint-viewer**](./tools/viewer) tool which displays the .slint files. The + `--auto-reload` argument makes it easy to preview your UI while you are + working on it (when using the LSP preview is not possible). +- [**SlintPad**](https://slintpad.com/), an online editor to try out .slint syntax + without installing anything ([sources](./tools/slintpad)). +- A [**Figma to Slint**](https://www.figma.com/community/plugin/1474418299182276871/figma-to-slint) plugin. + +Please check our [Editors README](./editors/README.md) for tips on how to +configure your favorite editor to work well with Slint. + +## License + +See [LICENSE.md](LICENSE.md) for the licensing terms of the whole repository, including documentation and examples. + +You can use Slint under ***any*** of the following licenses, at your choice: + +1. Build proprietary desktop, mobile, or web applications for free with the [Royalty-free License](LICENSES/LicenseRef-Slint-Royalty-free-2.0.md), +2. Build open source embedded, desktop, mobile, or web applications for free with the [GNU GPLv3](LICENSES/GPL-3.0-only.txt), +3. Build proprietary embedded, desktop, mobile, or web applications with the [Commercial license](LICENSES/LicenseRef-Slint-Software-3.0.md). + +See the [Slint licensing options on the website](https://slint.dev/pricing) and the [Licensing FAQ](FAQ.md#licensing). + +## Contributions + +We welcome your contributions: in the form of code, bug reports or feedback. +For contribution guidelines see [CONTRIBUTING.md](CONTRIBUTING.md). + +## Frequently Asked Questions + +Please see our separate [FAQ](FAQ.md). + +## About us (SixtyFPS GmbH) + +We are passionate about software - API design, cross-platform software +development and user interface components. Our aim is to make developing user +interfaces fun for everyone: from Python, JavaScript, C++, or Rust developers all the +way to UI/UX designers. We believe that software grows organically and keeping +it open source is the best way to sustain that growth. Our team members are +located remotely in Germany, Finland, and US. + +### Stay up to date + +- Follow [@slint_ui](https://twitter.com/slint_ui) on X/Twitter. +- Follow [@slint@fosstodon.org](https://fosstodon.org/@slint) on Mastodon. +- Follow [@slint-ui](https://www.linkedin.com/company/slint-ui/) on LinkedIn. +- Follow [@slint.dev](https://bsky.app/profile/slint.dev) on Bluesky +- Subscribe to our [YouTube channel](https://www.youtube.com/@Slint-UI) + +### Contact us + +Feel free to join [Github discussions](https://github.com/slint-ui/slint/discussions) +for general chat or questions. Use [Github issues](https://github.com/slint-ui/slint/issues) +to report public suggestions or bugs. + +We chat in [our Mattermost instance](https://chat.slint.dev) where you are +welcome to listen in or ask your questions. + +You can of course also contact us privately via email to [info@slint.dev](mailto:info@slint.dev). + +[#1]: https://www.youtube.com/watch?v=_BDbNHrjK7g +[#2]: https://www.youtube.com/watch?v=NNNOJJsOAis +[#3]: https://www.youtube.com/watch?v=dkBwNocItGs +[#4]: https://slint.dev/resources/gallery_win_screenshot.png "Gallery" +[#5]: https://slint.dev/resources/gallery_mac_screenshot.png "Gallery" +[#6]: https://slint.dev/resources/gallery_linux_screenshot.png "Gallery" +[#7]: https://slint.dev/resources/printerdemo_screenshot.png "Printer Demo" +[#8]: https://slint.dev/demos/printerdemo/ +[#9]: https://slint.dev/resources/puzzle_screenshot.png "Slide Puzzle" +[#10]: https://slint.dev/demos/slide_puzzle/ +[#11]: https://slint.dev/resources/energy-monitor-screenshot.png "Energy Monitor Demo" +[#12]: https://slint.dev/demos/energy-monitor/ +[#13]: https://slint.dev/resources/gallery_screenshot.png "Gallery Demo" +[#14]: https://slint.dev/demos/gallery/ +[#15]: https://docs.slint.dev/latest/docs/cpp/ +[#17]: https://github.com/slint-ui/slint-cpp-template +[#18]: https://img.shields.io/crates/v/slint +[#19]: https://crates.io/crates/slint +[#20]: https://docs.slint.dev/latest/docs/rust/slint/ +[#22]: https://youtu.be/WBcv4V-whHk +[#23]: https://github.com/slint-ui/slint-rust-template +[#24]: https://img.shields.io/npm/v/slint-ui +[#25]: https://www.npmjs.com/package/slint-ui +[#26]: https://docs.slint.dev/latest/docs/node/ +[#28]: https://github.com/slint-ui/slint-nodejs-template +[#29]: ./demos/weather-demo/docs/img/desktop-preview.png "Weather Demo" +[#30]: https://slint.dev/demos/weather-demo/ +[#31]: https://img.shields.io/pypi/v/slint +[#32]: https://pypi.org/project/slint/ +[#33]: https://docs.slint.dev/latest/docs/python/slint/ +[#34]: https://github.com/slint-ui/slint-python-template