feat(app): add the Nostro app, a window for phones and desktops
Linux phones have no banking apps, and a command line is no answer on a phone. The app does everything the nostro command does and, like it, only talks to nostrod: it holds no key and no token. - Nostro.Ui, a toolkit whose screens are functions that fill a frame, ported from imsd-messages ca5cd72d; Nostro.App, the app's state, forms and screens; Nostro.Ui.Shell, which puts them on a Wayland window with Crafter.Graphics; nostro-app; and Nostro.DebugCommands for the --debug-api build. - Client: every method also in an asynchronous form for an sd-event loop, with DaemonMissing and OutcomeUnknown. - nostrod's Flatpak is net.catcrafts.Nostrod now and the app takes net.catcrafts.Nostro; install.sh moves the state. The app's Flatpak, both Flatpaks cross-built for aarch64, and the licence texts they carry. - nostro-fake-system, a made-up bus and bank with a real nostrod on them, to look at the app against. The README's screenshots are taken on it. - The nostro command: an API key's environment is the key's own to say, so --sandbox is for bunq-oauth alone, and a virtual card is listed as VIRTUAL. The published contract changes in three places, before any release (design rule 10): - Transactions' query takes `stored`: answered from what nostrod has stored, without asking the bank. The app searches with it; before, every search was a call to bunq. - AddBunq's `environment` no longer chooses over what the key says of itself: a key of the other environment is refused. - SetCardStatus refuses to freeze or unfreeze a virtual card. bunq reports one as DEACTIVATED however well it pays, and leaves it as it is when asked, without an error. The app is GPL-3.0-only, the library stays LGPL-3.0-only, and no code moved from one to the other (design rule 13). Transaction's schema is unchanged. Verified: the 17 tests pass with every line, function and region of what they link run, and the five lint runs are clean. Every screen was looked at on the made-up system, at a phone's and a desktop's sizes in the light and the dark look, on Plasma under Wayland. What is said of bunq's cards comes from its sandbox, with throwaway users, and from one real virtual card. Known to have been used against production: connecting, and reading accounts, payments and cards. Not known to have been tried: a payment from the app against bunq, OAuth against bunq, and anything on a phone. Building the app takes --graphics=, a Crafter.Graphics checkout on its branch claude/nostro-app, until that branch is merged and pinned here. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
parent
1ea50c50bc
commit
5b4037955b
106 changed files with 17804 additions and 289 deletions
|
|
@ -1,6 +1,6 @@
|
||||||
## nostro
|
## nostro
|
||||||
|
|
||||||
nostro is a banking client for Linux in three parts. The library is a C++26 module, `import Nostro;`, that talks to a bank's API directly (bunq so far), keeps the credentials in one private JSON file, caches transactions in Crafter.DB tables, and lists, syncs, pays, requests and schedules. nostrod is a system daemon that runs that library for every local user, one worker process each, behind D-Bus and polkit. The `nostro` CLI is a client of nostrod. A consumer does one of three things:
|
nostro is a banking client for Linux in four parts. The library is a C++26 module, `import Nostro;`, that talks to a bank's API directly (bunq so far), keeps the credentials in one private JSON file, caches transactions in Crafter.DB tables, and lists, syncs, pays, requests and schedules. nostrod is a system daemon that runs that library for every local user, one worker process each, behind D-Bus and polkit. The `nostro` CLI and the Nostro app, a window for a phone or a desktop, are clients of nostrod. The app's own modules (`Nostro.Ui`, `Nostro.App`, `Nostro.Ui.Shell`) are built for the app and its tests alone, and are GPL-3.0-only where the library is LGPL-3.0-only: `--lib` does not hand them to a consumer. A consumer does one of three things:
|
||||||
|
|
||||||
- links the library and holds the credentials itself, in its own process (`--lib --banks=bunq`);
|
- links the library and holds the credentials itself, in its own process (`--lib --banks=bunq`);
|
||||||
- talks to nostrod through `Nostro::Client` (`--lib --banks=bunq --dbus`), as the CLI does;
|
- talks to nostrod through `Nostro::Client` (`--lib --banks=bunq --dbus`), as the CLI does;
|
||||||
|
|
@ -12,7 +12,8 @@ Everything is in `namespace Nostro`: the OpenSSL helpers in `Nostro::Crypto`, th
|
||||||
|
|
||||||
- `GitProject` with nostro's repository, or `LocalProject({ .projectFile = "<checkout>/project.cpp", .args = nostroArgs })` for a checkout, into `cfg.dependencies`. `nostroArgs` is your own `ProjectArgs()` plus `--lib` and `--banks=bunq`, built once inside `CrafterBuildProject`: without `--lib` nostro's `project.cpp` returns the CLI executable configuration (with the library as its dependency, which you cannot import from), and without `--banks=` it throws "must enable atleast one bank" and the whole build stops at load. `--banks=` is a comma-separated list and `bunq` is the only name it accepts.
|
- `GitProject` with nostro's repository, or `LocalProject({ .projectFile = "<checkout>/project.cpp", .args = nostroArgs })` for a checkout, into `cfg.dependencies`. `nostroArgs` is your own `ProjectArgs()` plus `--lib` and `--banks=bunq`, built once inside `CrafterBuildProject`: without `--lib` nostro's `project.cpp` returns the CLI executable configuration (with the library as its dependency, which you cannot import from), and without `--banks=` it throws "must enable atleast one bank" and the whole build stops at load. `--banks=` is a comma-separated list and `bunq` is the only name it accepts.
|
||||||
- `--dbus` with `--lib` adds the partitions that talk to nostrod, `:Bus`, `:Client` and `:Daemon`, and links `-lsystemd` (sd-bus) for you; it needs bunq on, since the wire carries bunq's types. Without it the library does not depend on libsystemd. `--product=checkout` instead returns the `nostro-checkout` library alone: the module `Nostro.Checkout`, needing neither `--lib` nor `--banks=`, and linking libsystemd and nothing else of nostro's (no OpenSSL, Crafter.Network or Crafter.DB).
|
- `--dbus` with `--lib` adds the partitions that talk to nostrod, `:Bus`, `:Client` and `:Daemon`, and links `-lsystemd` (sd-bus) for you; it needs bunq on, since the wire carries bunq's types. Without it the library does not depend on libsystemd. `--product=checkout` instead returns the `nostro-checkout` library alone: the module `Nostro.Checkout`, needing neither `--lib` nor `--banks=`, and linking libsystemd and nothing else of nostro's (no OpenSSL, Crafter.Network or Crafter.DB).
|
||||||
- nostro strips its own args (`--lib`, `--banks=`, `--dbus`, `--product=`, `--coverage`, `--profile-runtime=`) from what it hands its dependencies and forwards the rest, adding `--no-quic` for Crafter.Network: nostro speaks HTTP/1.1 only, and msquic would tie the binary to the building user's cache. A consumer that also loads Crafter.Network gives it that same list, `--no-quic` included, and Crafter.DB the list without it, or the build stops with two loads that disagree on their args.
|
- nostro strips its own args (`--lib`, `--banks=`, `--dbus`, `--product=`, `--graphics=`, `--debug-api`, `--coverage`, `--profile-runtime=`) from what it hands its dependencies and forwards the rest, adding `--no-quic` for Crafter.Network: nostro speaks HTTP/1.1 only, and msquic would tie the binary to the building user's cache. A consumer that also loads Crafter.Network gives it that same list, `--no-quic` included, and Crafter.DB the list without it, or the build stops with two loads that disagree on their args.
|
||||||
|
- nostro's `project.cpp` loads two build helpers by `#pragma crafter dependency`, Crafter.LintRules and, at a pinned commit, Crafter.Debug's: loading nostro fetches and builds both for the host, whatever is built of it. Crafter.Debug's library itself is only in nostro's own app, under `--debug-api`.
|
||||||
- What comes with it: Crafter.Network (with Crafter.Thread behind it), Crafter.DB, `-lssl -lcrypto`, and with `--dbus` `-lsystemd`, all as link flags you do not declare. Nothing in nostro uses the thread pool, so `ThreadPool::Start()` is not needed for it.
|
- What comes with it: Crafter.Network (with Crafter.Thread behind it), Crafter.DB, `-lssl -lcrypto`, and with `--dbus` `-lsystemd`, all as link flags you do not declare. Nothing in nostro uses the thread pool, so `ThreadPool::Start()` is not needed for it.
|
||||||
- Defines do not cross a dependency. nostro compiles with `NOSTRO_BUNQ_ENABLED`, `NOSTRO_OPENSSL_ENABLED` and, under `--dbus`, `NOSTRO_DBUS_ENABLED`, and the PCMs carry the result: `import Nostro;` exports `BunqConnector` and `Client`, and `EnabledBanks` lists bunq, whatever your configuration defines (nostro's own CLI compiles without them). Your own `#ifdef NOSTRO_BUNQ_ENABLED` sees it only when you push the same `Define` into your `cfg.defines`, as nostro's CLI configuration does with `execfg.defines = libcfg.defines`.
|
- Defines do not cross a dependency. nostro compiles with `NOSTRO_BUNQ_ENABLED`, `NOSTRO_OPENSSL_ENABLED` and, under `--dbus`, `NOSTRO_DBUS_ENABLED`, and the PCMs carry the result: `import Nostro;` exports `BunqConnector` and `Client`, and `EnabledBanks` lists bunq, whatever your configuration defines (nostro's own CLI compiles without them). Your own `#ifdef NOSTRO_BUNQ_ENABLED` sees it only when you push the same `Define` into your `cfg.defines`, as nostro's CLI configuration does with `execfg.defines = libcfg.defines`.
|
||||||
- `import Nostro;` is enough for everything below; nothing exposed needs `import Crafter.Network;` or `import Crafter.DB;`. The raw bunq calls (`Get`, `Post`, `Put`, `Delete`, `List`) take and return `nlohmann::json`: hold the result in `auto`, and include `lib/json.hpp` where you have to name or build one.
|
- `import Nostro;` is enough for everything below; nothing exposed needs `import Crafter.Network;` or `import Crafter.DB;`. The raw bunq calls (`Get`, `Post`, `Put`, `Delete`, `List`) take and return `nlohmann::json`: hold the result in `auto`, and include `lib/json.hpp` where you have to name or build one.
|
||||||
|
|
@ -23,7 +24,7 @@ Everything is in `namespace Nostro`: the OpenSSL helpers in `Nostro::Crypto`, th
|
||||||
- `Currency` is an `enum class` with `Euro` alone. `GetCurrency("EUR")` (or `"eur"`) is the only parse; anything else throws `std::runtime_error("unsupported currency '…'")`. `RefreshAccounts` skips a bank account in another currency with a `Note` instead. `GetCurrencyCode` gives `"EUR"`, `GetCurrencySymbol` `"€"`, `GetCurrencyDecimals` 2; `std::format("{}", Currency::Euro)` is the symbol. All `constexpr`.
|
- `Currency` is an `enum class` with `Euro` alone. `GetCurrency("EUR")` (or `"eur"`) is the only parse; anything else throws `std::runtime_error("unsupported currency '…'")`. `RefreshAccounts` skips a bank account in another currency with a `Note` instead. `GetCurrencyCode` gives `"EUR"`, `GetCurrencySymbol` `"€"`, `GetCurrencyDecimals` 2; `std::format("{}", Currency::Euro)` is the symbol. All `constexpr`.
|
||||||
- Amounts and balances are `std::int64_t` in the minor unit, so `1250` is €12.50, outgoing negative. `ParseAmount("12.50", Currency::Euro)` is `1250`: an optional leading `-`, digits, an optional `.` with at most `decimals` digits, nothing else, or `std::runtime_error("malformed amount '…'")`. `FormatAmount(1250, Currency::Euro)` is `"12.50"`, `FormatAmount(-5, …)` `"-0.05"`, and `FormatMoney(-102, …)` `"-€1.02"`, the sign before the symbol. All `constexpr`.
|
- Amounts and balances are `std::int64_t` in the minor unit, so `1250` is €12.50, outgoing negative. `ParseAmount("12.50", Currency::Euro)` is `1250`: an optional leading `-`, digits, an optional `.` with at most `decimals` digits, nothing else, or `std::runtime_error("malformed amount '…'")`. `FormatAmount(1250, Currency::Euro)` is `"12.50"`, `FormatAmount(-5, …)` `"-0.05"`, and `FormatMoney(-102, …)` `"-€1.02"`, the sign before the symbol. All `constexpr`.
|
||||||
- `ParseTimestamp("2026-10-31 12:34:56.123456")` is a `std::chrono::system_clock::time_point`, read as UTC: exactly `YYYY-MM-DD HH:MM:SS`, optionally `.` and one to six fraction digits, no zone, or `std::runtime_error("malformed timestamp '…'")`. `FormatTimestamp` is its inverse, bunq's format. libc++'s `system_clock` ticks in microseconds, which is also what the tables store.
|
- `ParseTimestamp("2026-10-31 12:34:56.123456")` is a `std::chrono::system_clock::time_point`, read as UTC: exactly `YYYY-MM-DD HH:MM:SS`, optionally `.` and one to six fraction digits, no zone, or `std::runtime_error("malformed timestamp '…'")`. `FormatTimestamp` is its inverse, bunq's format. libc++'s `system_clock` ticks in microseconds, which is also what the tables store.
|
||||||
- For dates a person types: `ParseLocalDate("2026-10-31")` or `ParseLocalDate("2026-10-31 09:30")` in the local time zone (through `mktime`), or `std::runtime_error` naming the format; `ParseLocalDate(day, 1)` is the midnight that ends `day`, counted by the calendar, so a day the clocks change is 23 or 25 hours. `FormatLocalTime(time)` is `"YYYY-MM-DD hh:mm"` in local time.
|
- For dates a person types: `ParseLocalDate("2026-10-31")` or `ParseLocalDate("2026-10-31 09:30")` in the local time zone (through `mktime`), or `std::runtime_error` naming the format; `ParseLocalDate(day, 1)` is the midnight that ends `day`, counted by the calendar, so a day the clocks change is 23 or 25 hours, and `ParseLocalDateEnd(text)` the last moment a range ending at `text` includes (the end of that day for a date alone). `FormatLocalTime(time)` is `"YYYY-MM-DD hh:mm"` in local time.
|
||||||
- `UrlEncode` percent-encodes all but RFC 3986's unreserved characters; `UrlDecode` undoes it and reads `+` as a space; `QueryParameter(url, name)` is the decoded value from the query string, or `std::nullopt`. `EscB(text)` escapes text for inside a JSON string literal; nostro itself no longer builds JSON by hand.
|
- `UrlEncode` percent-encodes all but RFC 3986's unreserved characters; `UrlDecode` undoes it and reads `+` as a space; `QueryParameter(url, name)` is the decoded value from the query string, or `std::nullopt`. `EscB(text)` escapes text for inside a JSON string literal; nostro itself no longer builds JSON by hand.
|
||||||
|
|
||||||
### Connectors, the config file and the process
|
### Connectors, the config file and the process
|
||||||
|
|
@ -37,26 +38,26 @@ Everything is in `namespace Nostro`: the OpenSSL helpers in `Nostro::Crypto`, th
|
||||||
- Generic code over the enabled banks is `tuple_for<EnabledBanks>([&]<typename Bank>() { for (Bank& bank : Bank::connectors) { … } });`, a template lambda. Every `Bank` has `static constexpr std::string connectorId` (`"bunq"`), `static std::deque<Bank> connectors`, `using Account`, `std::vector<Account> accounts`, `std::string name`, `TestConnector()`, `RefreshAccounts()`, `RefreshSession()`, `GetNewTransactions()` and `GetNewTransactions(account)`, `Logout()`, `StorageKey()`, a static `Create(…)` and `Remove(bank)`, and formats as its name. Its accounts have `StorageKey()` and format as `name<TAB>bic iban<TAB>€12.50` (`std::format` works on `Account` and on every type derived from it). Anything else, such as requests or cards, is bunq's own; `if constexpr (requires { account.Requests(); })` is how nostro's CLI asks.
|
- Generic code over the enabled banks is `tuple_for<EnabledBanks>([&]<typename Bank>() { for (Bank& bank : Bank::connectors) { … } });`, a template lambda. Every `Bank` has `static constexpr std::string connectorId` (`"bunq"`), `static std::deque<Bank> connectors`, `using Account`, `std::vector<Account> accounts`, `std::string name`, `TestConnector()`, `RefreshAccounts()`, `RefreshSession()`, `GetNewTransactions()` and `GetNewTransactions(account)`, `Logout()`, `StorageKey()`, a static `Create(…)` and `Remove(bank)`, and formats as its name. Its accounts have `StorageKey()` and format as `name<TAB>bic iban<TAB>€12.50` (`std::format` works on `Account` and on every type derived from it). Anything else, such as requests or cards, is bunq's own; `if constexpr (requires { account.Requests(); })` is how nostro's CLI asks.
|
||||||
- `Account { name, bic, iban, currency, balance }` plus the transaction store, keyed by a storage key you pass as the `connector` argument. For bunq that is `account.StorageKey()`, `bunq/<production|sandbox>/<user id>/<account id>`.
|
- `Account { name, bic, iban, currency, balance }` plus the transaction store, keyed by a storage key you pass as the `connector` argument. For bunq that is `account.StorageKey()`, `bunq/<production|sandbox>/<user id>/<account id>`.
|
||||||
- `GetLastTransactionTime(key)`: the newest stored `timePoint`, `time_point::min()` for an empty or new table.
|
- `GetLastTransactionTime(key)`: the newest stored `timePoint`, `time_point::min()` for an empty or new table.
|
||||||
- `SaveTransactions(key, std::vector<Transaction>)`: sorts by time, appends the rows newer than the last stored one, flushes. At the last stored timestamp a row is appended when its `id` is not stored there yet. When a row stored there has no id (version 1 data), everything at that timestamp is taken as stored. Older rows are dropped silently.
|
- `SaveTransactions(key, std::vector<Transaction>)`: sorts by time, appends the rows newer than the last stored one and flushes; a call that brings nothing new writes nothing. At the last stored timestamp a row is appended when its `id` is not stored there yet. When a row stored there has no id (version 1 data), everything at that timestamp is taken as stored. Older rows are dropped silently.
|
||||||
- `FindTransactions(key, TransactionQuery)`: newest first, at most `limit`. `TransactionQuery` takes designated initialisers: `.search` (ASCII case-insensitive substring of the counterparty name, the description or the IBAN; empty matches all), `.amount` (`std::optional<std::int64_t>`, exact, minor units, negative for outgoing), `.from` and `.to` (inclusive `time_point`s, the whole range by default), `.limit` (100). The time range is a binary search on the ordered table; the rest is a backwards scan that stops at `limit`.
|
- `FindTransactions(key, TransactionQuery)`: newest first, at most `limit`. `TransactionQuery` takes designated initialisers: `.search` (ASCII case-insensitive substring of the counterparty name, the description or the IBAN; empty matches all), `.amount` (`std::optional<std::int64_t>`, exact, minor units, negative for outgoing), `.from` and `.to` (inclusive `time_point`s, the whole range by default), `.limit` (100), and `.stored` (false), which is for nostrod and which `FindTransactions` does not look at: it never asks a bank. The time range is a binary search on the ordered table; the rest is a backwards scan that stops at `limit`: measured at 1.5 µs over 20 rows and 4 ms over 100 000 when nothing matches.
|
||||||
- The tables are `<cache>/transactions/<key>/<account name>.cdb`, with a `/` in the name written as `_`, opened on first use and kept open for the rest of the process, or until `Account::ForgetTransactions(key)` closes and deletes every table under `key` (a connector's storage key covers all its accounts; `Remove` calls it). A renamed account starts a new table and syncs again. Tables written before 2026-10-31 sit at `<cache>/transactions/bunq/<account name>.cdb` and are no longer read.
|
- The tables are `<cache>/transactions/<key>/<account name>.cdb`, with a `/` in the name written as `_`, opened on first use and kept open for the rest of the process, or until `Account::ForgetTransactions(key)` closes and deletes every table under `key` (a connector's storage key covers all its accounts; `Remove` calls it). A renamed account starts a new table and syncs again. Tables written before 2026-10-31 sit at `<cache>/transactions/bunq/<account name>.cdb` and are no longer read.
|
||||||
- `Transaction { name, bic, iban, description, currency, amount, timePoint, id, kind }` is an aggregate and the on-disk row type (`version = 2`, `orderedBy = timePoint`, 120 bytes). `id` is the bank's own id as text and `kind` its classification (bunq's `"MASTERCARD/PAYMENT"`, `"EBA_SDD/SDD"`); both are empty in rows migrated from version 1. A version 1 table migrates on its first open and keeps `<file>.v1.bak`. Do not add members to it from outside.
|
- `Transaction { name, bic, iban, description, currency, amount, timePoint, id, kind }` is an aggregate and the on-disk row type (`version = 2`, `orderedBy = timePoint`, 120 bytes). `id` is the bank's own id as text and `kind` its classification (bunq's `"MASTERCARD/PAYMENT"`, `"EBA_SDD/SDD"`); both are empty in rows migrated from version 1. A version 1 table migrates on its first open and keeps `<file>.v1.bak`. Do not add members to it from outside.
|
||||||
|
|
||||||
### The bunq connector
|
### The bunq connector
|
||||||
|
|
||||||
- **Two environments.** `BunqConnector::environment` is `BunqEnvironment::Production` (`api.bunq.com`, real money) or `Sandbox` (`public-api.sandbox.bunq.com`). `BunqConnector::EnvironmentOfKey(key)` is `Sandbox` for a key starting `sandbox_`; an OAuth token does not say, so the caller decides. Only the sandbox has been exercised (2026-10-31). `BunqConnector::Endpoint(environment)` is the `BunqEndpoint` (`host`, `port`, `caPem`) its calls go to. Each endpoint has one `ClientHTTP1`, shared by its connectors; every call is synchronous on the calling thread and the client serves one caller at a time, so keep bunq calls on one thread.
|
- **Two environments.** `BunqConnector::environment` is `BunqEnvironment::Production` (`api.bunq.com`, real money) or `Sandbox` (`public-api.sandbox.bunq.com`). `BunqConnector::EnvironmentOfKey(key)` is `Sandbox` for a key starting `sandbox_`; an OAuth token does not say, so the caller decides. Production has been used to connect and to read since 2026-11-19; before that only the sandbox was. `BunqConnector::Endpoint(environment)` is the `BunqEndpoint` (`host`, `port`, `caPem`) its calls go to. Each endpoint has one `ClientHTTP1`, shared by its connectors; every call is synchronous on the calling thread and the client serves one caller at a time, so keep bunq calls on one thread.
|
||||||
- **For tests:** `BunqConnector::RedirectTo(BunqEndpoint{.host = "127.0.0.1", .port = …, .caPem = …})` sends every API and OAuth token call there for the rest of the process, whatever the environment. nostro's own tests point it at `tests/Support/FakeBunq.inc`, an in-process bunq that a consumer's test can include as well (after `lib/json.hpp`, `import std;`, `import Nostro;` and `import Crafter.Network;`).
|
- **For tests:** `BunqConnector::RedirectTo(BunqEndpoint{.host = "127.0.0.1", .port = …, .caPem = …})` sends every API and OAuth token call there for the rest of the process, whatever the environment. nostro's own tests point it at `tests/Support/FakeBunq.inc`, an in-process bunq that a consumer's test can include as well (after `lib/json.hpp`, `import std;`, `import Nostro;` and `import Crafter.Network;`).
|
||||||
- `BunqConnector::Create(std::string&& apiKey, std::string_view allowedIps, BunqEnvironment environment)` registers an installation with a fresh RSA-2048 key, the device with the key and opens a session. `allowedIps` is a plain comma-separated list (`"203.0.113.4, 198.51.100.7"`), `"*"` for any address (it makes the key a wildcard key, which a phone with a changing address needs), or empty for the address the call comes from. It returns a reference into `BunqConnector::connectors`, a `std::deque`, so a later `Create` leaves earlier references and every account's `connector` pointer valid. The same bunq user (`ownerId`) in the same environment connected the same way replaces the old connector, logging its session out: that is how a key is renewed. Connected the other way (API key against OAuth), `Create` logs the new session out and throws, because every account would otherwise be listed twice. Follow it with `Connector::SaveConnectors()` or the connector is gone at exit.
|
- `BunqConnector::Create(std::string&& apiKey, std::string_view allowedIps, BunqEnvironment environment)` registers an installation with a fresh RSA-2048 key, the device with the key and opens a session. `allowedIps` is a plain comma-separated list (`"203.0.113.4, 198.51.100.7"`), `"*"` for any address (it makes the key a wildcard key, which a phone with a changing address needs), or empty for the address the call comes from. It returns a reference into `BunqConnector::connectors`, a `std::deque`, so a later `Create` leaves earlier references and every account's `connector` pointer valid. The same bunq user (`ownerId`) in the same environment connected the same way replaces the old connector, logging its session out: that is how a key is renewed. Connected the other way (API key against OAuth), `Create` logs the new session out and throws, because every account would otherwise be listed twice. Follow it with `Connector::SaveConnectors()` or the connector is gone at exit.
|
||||||
- `BunqConnector::Remove(connector)` deletes its stored transactions (through `Account::ForgetTransactions`, which first closes the tables this process has open, so the same user added again syncs into new files) and erases it from `connectors`, re-pointing the remaining accounts; references to other connectors you held are invalidated, as with any `deque::erase` in the middle. It does not log out: call `Logout()` first (`DELETE /v1/session/{sessionId}`, not renewed; a session already gone counts as logged out). Then `SaveConnectors()`.
|
- `BunqConnector::Remove(connector)` deletes its stored transactions (through `Account::ForgetTransactions`, which first closes the tables this process has open, so the same user added again syncs into new files) and erases it from `connectors`, re-pointing the remaining accounts; references to other connectors you held are invalidated, as with any `deque::erase` in the middle. It does not log out: call `Logout()` first (`DELETE /v1/session/{sessionId}`, not renewed; a session already gone counts as logged out). Then `SaveConnectors()`.
|
||||||
- After `LoadConnectors` or `Create` a connector has `environment`, `name` (bunq's `display_name` of the user; for OAuth of the user who granted access), `id` (the user id in API paths; for OAuth the `UserApiKey`'s own), `ownerId`, `userType` (`UserPerson`, `UserCompany`, `UserApiKey` or `UserPaymentServiceProvider`; `IsOAuth()` is `UserApiKey`), `sessionToken`, `sessionId`, `installationToken`, `privateKey` and `serverPublicKey` (`Crypto::Key`, a `std::shared_ptr<EVP_PKEY>`), `apiKey`, and `accounts` of `BunqAccount` (`Account` plus `id`, bunq's object `type` such as `MonetaryAccountSavings`, and a `connector` back-pointer).
|
- After `LoadConnectors` or `Create` a connector has `environment`, `name` (bunq's `display_name` of the user; for OAuth of the user who granted access), `id` (the user id in API paths; for OAuth the `UserApiKey`'s own), `ownerId`, `userType` (`UserPerson`, `UserCompany`, `UserApiKey` or `UserPaymentServiceProvider`; `IsOAuth()` is `UserApiKey`), `sessionToken`, `sessionId`, `installationToken`, `privateKey` and `serverPublicKey` (`Crypto::Key`, a `std::shared_ptr<EVP_PKEY>`), `apiKey`, and `accounts` of `BunqAccount` (`Account` plus `id`, bunq's object `type` such as `MonetaryAccountSavings`, and a `connector` back-pointer).
|
||||||
- Every call goes through `Get`, `Post`, `Put` or `Delete` (a path below `/v1`, or a pagination URL) and `List` (every item of a listing, pages of 200 followed through `older_url`, newest first). Bodies are signed. Every 2xx must carry a valid `x-bunq-server-signature` for the stored server key, which an old connector fetches before its first call, or the call throws. A 429 is waited out: 3 s up to five times, 31 s up to twice for `session-server`. A 401, or a 403 "Insufficient authentication.", opens a new session once, saves, and retries. A POST, PUT or DELETE goes over a new connection, because `ClientHTTP1` would replay one on a reused connection after a read timeout. When the outcome of such a write is unknown (a transport error, a 5xx, an unreadable or unverifiable answer), the error ends in `; the request may have been carried out, check before trying again`. Any other error response is a `BunqError`.
|
- Every call goes through `Get`, `Post`, `Put` or `Delete` (a path below `/v1`, or a pagination URL) and `List` (every item of a listing, pages of 200 followed through `older_url`, newest first). Bodies are signed. Every 2xx must carry a valid `x-bunq-server-signature` for the stored server key, which an old connector fetches before its first call, or the call throws. A 429 is waited out: 3 s up to five times, 31 s up to twice for `session-server`. A 401, or a 403 "Insufficient authentication.", opens a new session once, saves, and retries. A POST, PUT or DELETE goes over a new connection, because `ClientHTTP1` would replay one on a reused connection after a read timeout. When the outcome of such a write is unknown (a transport error, a 5xx, an unreadable or unverifiable answer), the error ends in `; the request may have been carried out, check before trying again`, which is `BunqError::maybeCarriedOut`. Any other error response is a `BunqError`.
|
||||||
- `RefreshAccounts()` rebuilds `accounts` from scratch (references into it go stale): every `MonetaryAccount…` type whose status is `ACTIVE` or `BLOCKED`, the IBAN alias as `iban`, `BUNQNL2A` as `bic` for a bunq IBAN. `TestConnector()` is `GET /v1/user/{id}` and returns `false` on any exception rather than throwing. `GetNewTransactions(account)` (and `GetNewTransactions()` for all) pages the payments newest first until one older than the last stored row, fills `id` and `kind` (`"<type>/<sub_type>"`), and calls `SaveTransactions(account.StorageKey(), …)`; the first sync walks the whole history, 200 a call.
|
- `RefreshAccounts()` rebuilds `accounts` from scratch (references into it go stale): every `MonetaryAccount…` type whose status is `ACTIVE` or `BLOCKED`, the IBAN alias as `iban`, `BUNQNL2A` as `bic` for a bunq IBAN. `TestConnector()` is `GET /v1/user/{id}` and returns `false` on any exception rather than throwing. `GetNewTransactions(account)` (and `GetNewTransactions()` for all) pages the payments newest first until one older than the last stored row, fills `id` and `kind` (`"<type>/<sub_type>"`), and calls `SaveTransactions(account.StorageKey(), …)`; the first sync walks the whole history, 200 a call.
|
||||||
- On a `BunqAccount`, amounts are positive minor units, or `std::invalid_argument`. Counterparties go through `BunqCounterparty::Parse(value, name)`: an `@` makes an e-mail address, a leading `+` a phone number (spaces, dashes and brackets dropped), anything else an IBAN. An IBAN is upper-cased, has its spaces removed and its check digits verified, so a typo throws `std::invalid_argument` before anything is sent. bunq needs `name` for an IBAN outside bunq.
|
- On a `BunqAccount`, amounts are positive minor units, or `std::invalid_argument`. Counterparties go through `BunqCounterparty::Parse(value, name)`: an `@` makes an e-mail address, a leading `+` a phone number (spaces, dashes and brackets dropped), anything else an IBAN. An IBAN is upper-cased, has its spaces removed and its check digits verified, so a typo throws `std::invalid_argument` before anything is sent. bunq needs `name` for an IBAN outside bunq.
|
||||||
- `Send`, `Draft` (one-entry draft payment, paid once someone accepts it) and `Schedule(…, BunqSchedule)` return bunq's id. `BunqSchedule { start, end, unit ("ONCE", "HOURLY", "DAILY", "WEEKLY", "MONTHLY", "YEARLY"), every }` is UTC; an unknown unit or `every == 0` throws `std::invalid_argument`.
|
- `Send`, `Draft` (one-entry draft payment, paid once someone accepts it) and `Schedule(…, BunqSchedule)` return bunq's id. `BunqSchedule { start, end, unit ("ONCE", "HOURLY", "DAILY", "WEEKLY", "MONTHLY", "YEARLY"), every }` is UTC; an unknown unit or `every == 0` throws `std::invalid_argument`. `BunqSchedule::UnitFromWord("monthly")` is `"MONTHLY"`, for a unit a person typed.
|
||||||
- `Request(from, name, amount, currency, description)` asks for money with bunq.me allowed and returns a `BunqPaymentRequest`, whose `shareUrl` anyone can pay through. When reading it back fails, the request still exists: it comes back `PENDING` without a share URL, with a `Note`.
|
- `Request(from, name, amount, currency, description)` asks for money with bunq.me allowed and returns a `BunqPaymentRequest`, whose `shareUrl` anyone can pay through. When reading it back fails, the request still exists: it comes back `PENDING` without a share URL, with a `Note`.
|
||||||
- The listings, newest first: `Requests()` (sent, `BunqPaymentRequest`), `IncomingRequests()` (`BunqIncomingRequest`, incoming SEPA direct debits included as `DIRECT_DEBIT`), `ScheduledPayments()`, `DraftPayments()`. One of each, as bunq has it now: `IncomingRequest(id)` and `DraftPayment(id)`. The answers: `RevokeRequest(id)`, `CancelScheduledPayment(id)`, and two that take the object you showed the user: `RespondToRequest(shown, accept)` pays `shown.amount` and `shown.currency`, whatever the request asks by then, and `RespondToDraftPayment(shown, accept)` sends `shown.updated` (bunq's own timestamp, kept as text), so bunq refuses an answer to a draft that changed since. Read it, show it, answer with what you read. A request has one id on each side: the asker's inquiry id is not the payer's response id.
|
- The listings, newest first: `Requests()` (sent, `BunqPaymentRequest`), `IncomingRequests()` (`BunqIncomingRequest`, incoming SEPA direct debits included as `DIRECT_DEBIT`), `ScheduledPayments()`, `DraftPayments()`. One of each, as bunq has it now: `IncomingRequest(id)` and `DraftPayment(id)`. The answers: `RevokeRequest(id)`, `CancelScheduledPayment(id)`, and two that take the object you showed the user: `RespondToRequest(shown, accept)` pays `shown.amount` and `shown.currency`, whatever the request asks by then, and `RespondToDraftPayment(shown, accept)` sends `shown.updated` (bunq's own timestamp, kept as text), so bunq refuses an answer to a draft that changed since. Read it, show it, answer with what you read. A request has one id on each side: the asker's inquiry id is not the payer's response id.
|
||||||
- `Cards()` lists the user's cards (`BunqCard`: `id`, `status`, `productType`, `lastFour`, `expiry`, the paying `iban`, …). `SetCardStatus(id, "DEACTIVATED" | "ACTIVE" | "LOST" | "STOLEN")` returns the card as bunq has it afterwards, which can differ from the request without an error: a card that was never activated stays `DEACTIVATED`.
|
- `Cards()` lists the user's cards (`BunqCard`: `id`, `status`, `orderStatus`, `productType`, `lastFour`, `expiry`, the paying `iban`, …). `status` is bunq's, and is about the plastic: `card.State()` is how the card stands in one word, which is `status` except for a virtual card (`card.Virtual()`: its `orderStatus` is `VIRTUAL_DELIVERY`), which is `VIRTUAL` until it is gone for good. bunq has a virtual card as `DEACTIVATED` however well it pays, and nothing says whether one is frozen. The `std::formatter` prints `State()`. `SetCardStatus(id, "DEACTIVATED" | "ACTIVE" | "LOST" | "STOLEN")` returns the card as bunq has it afterwards, which can differ from the request without an error: a card that was never activated stays `DEACTIVATED`, and a virtual card is left as it is when asked to freeze or unfreeze. `card.ExpectStatus(asked)` throws `std::runtime_error` saying so in either case. Through nostrod, `Client::SetCardStatus` refuses to freeze or unfreeze a virtual card with `std::invalid_argument`, before anyone is asked for a password.
|
||||||
- OAuth instead of an API key: `OAuthAuthorizationUrl(environment, clientId, redirectUri, state)` is where the user approves with the bunq app. bunq then redirects to `redirectUri` with `code` and `state` (check `state` yourself). `OAuthExchangeCode(environment, clientId, clientSecret, redirectUri, code)` returns the access token, which `Create` takes in place of an API key. bunq grants OAuth payments between the user's own accounts, draft payments, cards, and creating requests, but no paying of incoming ones. The exchange was verified up to bunq refusing a fake code; a full approval needs a person and the bunq app.
|
- OAuth instead of an API key: `OAuthAuthorizationUrl(environment, clientId, redirectUri, state)` is where the user approves with the bunq app. bunq then redirects to `redirectUri` with `code` and `state`: `OAuthCodeFromRedirect(redirectedAddress, state)` returns the code, or throws `std::runtime_error` when bunq did not authorize (`error=`), the address has no code, or its `state` is another. `OAuthExchangeCode(environment, clientId, clientSecret, redirectUri, code)` returns the access token, which `Create` takes in place of an API key. bunq grants OAuth payments between the user's own accounts, draft payments, cards, and creating requests, but no paying of incoming ones. The exchange was verified up to bunq refusing a fake code; a full approval needs a person and the bunq app.
|
||||||
- Every type above formats with `std::format` as one tab-separated line (a draft adds a line per entry), the way nostro's CLI prints them.
|
- Every type above formats with `std::format` as one tab-separated line (a draft adds a line per entry), the way nostro's CLI prints them.
|
||||||
|
|
||||||
### nostrod, through Nostro::Client
|
### nostrod, through Nostro::Client
|
||||||
|
|
@ -64,9 +65,10 @@ Everything is in `namespace Nostro`: the OpenSSL helpers in `Nostro::Crypto`, th
|
||||||
nostrod is the system daemon that holds every local user's connectors, in a worker process per user under its own state directory, which the users cannot read. It answers `net.catcrafts.Nostro1` on the system bus (published as `packaging/dbus/net.catcrafts.Nostro1.xml`), for the calling user only, after asking polkit: viewing and the changes that move no money pass in an active session, while paying, scheduling, accepting a request or a draft, unfreezing or blocking a card, changing the connectors and choosing the checkout account ask for the user's password each time. A front end that should not hold the credentials itself (`--dbus`) talks to it through `Nostro::Client`:
|
nostrod is the system daemon that holds every local user's connectors, in a worker process per user under its own state directory, which the users cannot read. It answers `net.catcrafts.Nostro1` on the system bus (published as `packaging/dbus/net.catcrafts.Nostro1.xml`), for the calling user only, after asking polkit: viewing and the changes that move no money pass in an active session, while paying, scheduling, accepting a request or a draft, unfreezing or blocking a card, changing the connectors and choosing the checkout account ask for the user's password each time. A front end that should not hold the credentials itself (`--dbus`) talks to it through `Nostro::Client`:
|
||||||
|
|
||||||
- `Client::System(timeout = 10min)` connects to the system bus with interactive authorization allowed, so polkit can ask for the password, and a call timeout long enough for the user and for bunq's rate limits. D-Bus starts nostrod with the first call. Keep one `Client` per thread; it is not shared between threads.
|
- `Client::System(timeout = 10min)` connects to the system bus with interactive authorization allowed, so polkit can ask for the password, and a call timeout long enough for the user and for bunq's rate limits. D-Bus starts nostrod with the first call. Keep one `Client` per thread; it is not shared between threads.
|
||||||
- One method per D-Bus method, with nostro's own types: `Connectors()` (`ConnectorSummary`: `name`, `bank`, `environment`, `auth` "api key" or "oauth", `working`), `AddBunq(apiKey, allowedIps, environment)` and `AddBunqOAuth(environment, clientId, clientSecret, redirectUri, code)` (`AddedConnector`; an empty environment takes the key's), `RemoveConnector(name or number)`, `Accounts()` (`ConnectorAccounts`), `Transactions(account, TransactionQuery)` (synced first), `Send`, `Schedule`, `Draft` (`Created`: bunq's `id` and the `currency`), `Request` (`BunqPaymentRequest`), the listings, `RevokeRequest`, `RespondToRequest(account, id, accept)`, `CancelScheduledPayment`, `RespondToDraftPayment(account, id, accept)`, `Cards()` (`ConnectorCards`), `SetCardStatus(card, status)`, `DefaultCheckoutAccount()` (`std::optional<Account>`) and `SetDefaultCheckoutAccount(account)`. `account` is an account's name or IBAN. Accepting a request or a draft pays it as nostrod read it to show the user.
|
- One method per D-Bus method, with nostro's own types: `Connectors()` (`ConnectorSummary`: `name`, `bank`, `environment`, `auth` "api key" or "oauth", `working`), `AddBunq(apiKey, allowedIps, environment)` and `AddBunqOAuth(environment, clientId, clientSecret, redirectUri, code)` (`AddedConnector`; for `AddBunq` leave the environment empty: nostrod takes the one the key is of, and naming one only has a key of the other refused with `std::invalid_argument`, before anything is sent), `RemoveConnector(name or number)`, `Accounts()` (`ConnectorAccounts`), `Transactions(account, TransactionQuery)` (nostrod asks the bank for what is new first, a call to the bank that takes its time and that the bank counts; with `.stored = true` it answers from what it has stored alone, in milliseconds: for a search in a list just read, or more of it. A nostrod from before 2026-11-19 ignores `stored` and asks the bank), `Send`, `Schedule`, `Draft` (`Created`: bunq's `id` and the `currency`), `Request` (`BunqPaymentRequest`), the listings, `RevokeRequest`, `RespondToRequest(account, id, accept)`, `CancelScheduledPayment`, `RespondToDraftPayment(account, id, accept)`, `Cards()` (`ConnectorCards`), `SetCardStatus(card, status)`, `DefaultCheckoutAccount()` (`std::optional<Account>`) and `SetDefaultCheckoutAccount(account)`. `account` is an account's name or IBAN. Accepting a request or a draft pays it as nostrod read it to show the user.
|
||||||
- `TakeNotes()` returns, and clears, the library's warnings from the calls so far (a connector unavailable, a request made but not read back): show them.
|
- `TakeNotes()` returns, and clears, the library's warnings from the calls so far (a connector unavailable, a request made but not read back): show them.
|
||||||
- Errors: `std::invalid_argument` for what nostrod refused before doing anything (it names the problem, as the library's own messages do); `DaemonError`, a `std::runtime_error` with the D-Bus error `name`, for the rest: `Bus::errorBank` (bunq's refusal, as bunq said it), `Bus::errorOAuthCannotPay`, `Bus::errorCancelled` (the user closed the password dialog), `Bus::errorNoCheckoutAccount`, `Bus::errorFailed`, `org.freedesktop.DBus.Error.AccessDenied` (the system's policy, or polkit not answering) and `InteractiveAuthorizationRequired`. A missing nostrod is a `std::runtime_error` saying it is not running; a call that moves money or changes something and gets no answer in time is a `std::runtime_error` saying it may have been carried out; text that is not UTF-8 is a `std::invalid_argument` before anything is sent.
|
- Every method also has an asynchronous form, for a program with an event loop that must not wait minutes on a password dialog: `client.Attach(sd_event*)` once (a second `Attach` throws), then call the method with a last argument `Then<T>` (`std::function<void(Answer<T>)>`; `std::monostate` for a method that answers nothing). It returns a `[[nodiscard]] Client::Pending` at once and calls `then` from the loop when nostrod answers. `Answer<T>` holds the `result` or the `std::exception_ptr` the blocking call would have thrown (`Get()` returns the one or rethrows the other, `Failed()`, `Error()`), and that call's `notes`; an error answer carries none, and notes are collected per user by nostrod's worker, so they can be another call's of the same user. Destroying the `Pending`, or `Cancel()`, drops the answer (`then` is not called) without undoing the call, which nostrod and bunq carry on with; `Active()` says whether `then` is still to come. A `then` that throws is reported through `Note`. Calling one without `Attach` throws `std::logic_error`. Once the connection is gone (`Connected()` false), make a new client: a closed connection answers nothing it still awaited.
|
||||||
|
- Errors: `std::invalid_argument` for what nostrod refused before doing anything (it names the problem, as the library's own messages do); `DaemonError`, a `std::runtime_error` with the D-Bus error `name`, for the rest: `Bus::errorBank` (bunq's refusal, as bunq said it), `Bus::errorOAuthCannotPay`, `Bus::errorCancelled` (the user closed the password dialog), `Bus::errorNoCheckoutAccount`, `Bus::errorFailed`, `org.freedesktop.DBus.Error.AccessDenied` (the system's policy, or polkit not answering) and `InteractiveAuthorizationRequired`. A missing nostrod is `DaemonMissing`, a `std::runtime_error` saying it is not running. A call that moves money or changes something and gets no answer in time, or that bunq answered with an error ending in `BunqError::maybeCarriedOut` (a 5xx: the payment may have been made), is `OutcomeUnknown`, a `std::runtime_error` saying it may have been carried out: check before trying again. Text that is not UTF-8 is a `std::invalid_argument` before anything is sent.
|
||||||
- The API key and the OAuth client secret travel once, in messages marked sensitive. Read them with `ReadSecret`, never from `argv`, which every local user can read and polkit logs.
|
- The API key and the OAuth client secret travel once, in messages marked sensitive. Read them with `ReadSecret`, never from `argv`, which every local user can read and polkit logs.
|
||||||
|
|
||||||
### Checkout
|
### Checkout
|
||||||
|
|
@ -102,14 +104,14 @@ An app that only needs a customer to pay an order links `Nostro.Checkout` (`--pr
|
||||||
|
|
||||||
### Names to get right
|
### Names to get right
|
||||||
|
|
||||||
`Connector::LoadConnectors` and `SaveConnectors` are statics on a struct with nothing else. On `BunqConnector`: `connectorId` is `"bunq"`, `connectors` the static deque, `Create` and `Remove` the static constructor and remover, plus `EnvironmentOfKey`, `OAuthAuthorizationUrl` and `OAuthExchangeCode`, `Get`/`Post`/`Put`/`Delete`/`List`, `RefreshSession`, `RefreshAccounts`, `GetNewTransactions`, `TestConnector`, `Logout`, `Cards`, `SetCardStatus`, `StorageKey`, `IsOAuth`, `Endpoint` and `RedirectTo`. On `BunqAccount`: `Send`, `Draft`, `Schedule`, `Request`, `Requests`, `IncomingRequests`, `ScheduledPayments`, `DraftPayments`, `IncomingRequest`, `DraftPayment`, `RevokeRequest`, `RespondToRequest`, `CancelScheduledPayment`, `RespondToDraftPayment`, `Path` and `StorageKey`. On `Account`, the static `ForgetTransactions`. The warnings: `Note` and `noteSink`. Other names:
|
`Connector::LoadConnectors` and `SaveConnectors` are statics on a struct with nothing else. On `BunqConnector`: `connectorId` is `"bunq"`, `connectors` the static deque, `Create` and `Remove` the static constructor and remover, plus `EnvironmentOfKey`, `OAuthAuthorizationUrl`, `OAuthCodeFromRedirect` and `OAuthExchangeCode`, `Get`/`Post`/`Put`/`Delete`/`List`, `RefreshSession`, `RefreshAccounts`, `GetNewTransactions`, `TestConnector`, `Logout`, `Cards`, `SetCardStatus`, `StorageKey`, `IsOAuth`, `Endpoint` and `RedirectTo`. On `BunqAccount`: `Send`, `Draft`, `Schedule`, `Request`, `Requests`, `IncomingRequests`, `ScheduledPayments`, `DraftPayments`, `IncomingRequest`, `DraftPayment`, `RevokeRequest`, `RespondToRequest`, `CancelScheduledPayment`, `RespondToDraftPayment`, `Path` and `StorageKey`. On `Account`, the static `ForgetTransactions`. The warnings: `Note` and `noteSink`. Other names:
|
||||||
- the bunq types: `BunqEnvironment`, `BunqEndpoint`, `BunqError`, `BunqCounterparty`, `BunqLabel`, `BunqPaymentRequest`, `BunqIncomingRequest`, `BunqSchedule`, `BunqScheduledPayment`, `BunqDraftPayment`, `BunqCard`;
|
- the bunq types: `BunqEnvironment`, `BunqEndpoint`, `BunqError`, `BunqCounterparty`, `BunqLabel`, `BunqPaymentRequest`, `BunqIncomingRequest`, `BunqSchedule`, `BunqScheduledPayment`, `BunqDraftPayment`, `BunqCard`;
|
||||||
- `EnabledBanks` and `tuple_for` in `:Banks`;
|
- `EnabledBanks` and `tuple_for` in `:Banks`;
|
||||||
- `ParseAmount`, `FormatAmount`, `FormatMoney`, `GetCurrency`, `GetCurrencyCode`, `GetCurrencySymbol` and `GetCurrencyDecimals`;
|
- `ParseAmount`, `FormatAmount`, `FormatMoney`, `GetCurrency`, `GetCurrencyCode`, `GetCurrencySymbol` and `GetCurrencyDecimals`;
|
||||||
- in `:Utils`: `ParseTimestamp`, `FormatTimestamp`, `ParseLocalDate`, `FormatLocalTime`, `UrlEncode`, `UrlDecode`, `QueryParameter` and `EscB`;
|
- in `:Utils`: `ParseTimestamp`, `FormatTimestamp`, `ParseLocalDate`, `ParseLocalDateEnd`, `FormatLocalTime`, `UrlEncode`, `UrlDecode`, `QueryParameter` and `EscB`;
|
||||||
- `FindTransactions` (not Query, Load or List), `SaveTransactions` and `GetLastTransactionTime`;
|
- `FindTransactions` (not Query, Load or List), `SaveTransactions` and `GetLastTransactionTime`;
|
||||||
- `TransactionQuery` with `search`, `amount`, `from`, `to` and `limit`;
|
- `TransactionQuery` with `search`, `amount`, `from`, `to`, `limit` and `stored`;
|
||||||
- in `Nostro::Crypto`: `Key`, `OwnKey`, `SignBody`, `VerifyBody`, `CreateKey` (a `std::tuple<EVP_PKEY*, std::string>`, the public PEM second), `LoadKeyFromPem`, `LoadPublicKeyFromPem`, `PrivateKeyToPem`, `PublicKeyToPem`, `RandomHex` and `ThrowOnOpenssl`;
|
- in `Nostro::Crypto`: `Key`, `OwnKey`, `SignBody`, `VerifyBody`, `CreateKey` (a `std::tuple<EVP_PKEY*, std::string>`, the public PEM second), `LoadKeyFromPem`, `LoadPublicKeyFromPem`, `PrivateKeyToPem`, `PublicKeyToPem`, `RandomHex` and `ThrowOnOpenssl`;
|
||||||
- `configPath`, `cachePath`, `CreatePrivateFile` and `ReadSecret`;
|
- `configPath`, `cachePath`, `CreatePrivateFile` and `ReadSecret`;
|
||||||
- for nostrod: `Client` (`System`, `TakeNotes`, `DefaultCheckoutAccount`, `SetDefaultCheckoutAccount`), `DaemonError`, `ConnectorSummary`, `AddedConnector`, `ConnectorAccounts`, `ConnectorCards`, `Created`, and `Bus::busName`, `Bus::errorBank` and the other `Bus::error…` names;
|
- for nostrod: `Client` (`System`, `Attach`, `Connected`, `TakeNotes`, `DefaultCheckoutAccount`, `SetDefaultCheckoutAccount`, and `Client::Pending` and `Client::Then`), `Answer`, `DaemonError`, `DaemonMissing`, `OutcomeUnknown`, `ConnectorSummary`, `AddedConnector`, `ConnectorAccounts`, `ConnectorCards`, `Created`, and `Bus::busName`, `Bus::errorBank` and the other `Bus::error…` names;
|
||||||
- for checkout: `Nostro::Checkout::Pay`, `Order`, `Paid`, `Error`, `Cancelled`, `NoCheckoutAccount`, and the module `Nostro.Checkout`, with a dot.
|
- for checkout: `Nostro::Checkout::Pay`, `Order`, `Paid`, `Error`, `Cancelled`, `NoCheckoutAccount`, and the module `Nostro.Checkout`, with a dot.
|
||||||
|
|
|
||||||
|
|
@ -1,10 +1,21 @@
|
||||||
# AGENTS.md
|
# AGENTS.md
|
||||||
|
|
||||||
Guidance for coding agents and contributors working on nostro itself. The [README](README.md) is the user-facing manual (what nostro is for, the CLI, how to contribute a bank), and [AGENTS.consumer.md](AGENTS.consumer.md) is what agents working in a *consumer* of the library read: crafter-build copies it into the dependency-notes section of the consumer's `AGENTS.md` on every build. When any of the three disagrees with the code, the code wins; the interfaces under `interfaces/` are the contract, `Transaction` in `interfaces/Nostro-Transaction.cppm` is the contract for the bytes on disk, and `packaging/dbus/*.xml` with `packaging/system/net.catcrafts.Nostro1.policy` are the contract on the system bus, which a test holds to what nostrod serves. This file is written by crafter-build from `AGENTS.template.md`; the section at its end holds the notes of the libraries nostro builds against (Crafter.Network, Crafter.DB), straight from their repositories.
|
Guidance for coding agents and contributors working on nostro itself. The [README](README.md) is the user-facing manual (what nostro is for, the CLI, how to contribute a bank), and [AGENTS.consumer.md](AGENTS.consumer.md) is what agents working in a *consumer* of the library read: crafter-build copies it into the dependency-notes section of the consumer's `AGENTS.md` on every build. When any of the three disagrees with the code, the code wins; the interfaces under `interfaces/` are the contract, `Transaction` in `interfaces/Nostro-Transaction.cppm` is the contract for the bytes on disk, and `packaging/dbus/*.xml` with `packaging/system/net.catcrafts.Nostro1.policy` are the contract on the system bus, which a test holds to what nostrod serves. This file is written by crafter-build from `AGENTS.template.md`; the section at its end holds the notes of what the last build loaded, straight from their repositories: Crafter.Network, Crafter.DB and Crafter.Debug on every build (the debug flag Crafter.Debug's notes speak of is `--debug-api`, and it is the app's alone), and Crafter.Graphics with Crafter.Math and Crafter.Asset after a build of the app.
|
||||||
|
|
||||||
## Project overview
|
## Project overview
|
||||||
|
|
||||||
nostro is a banking client for Linux, phones first: a library that talks to bank APIs directly; nostrod, a system daemon that runs it for every local user behind D-Bus and polkit, so no program of the user's can read the bank's secrets or move money without the user's password; and a small CLI that only talks to nostrod. Linux phones have no banking apps; nostro is the open-source answer, one connector per bank. One C++26 module, `Nostro`, with twelve partitions behind the umbrella and ten implementation units, and a second module, `Nostro.Checkout`, for apps that have nostrod pay an order. `project.cpp` makes one product per build: the static library `nostro` with the CLI `nostro` (`implementations/main.cpp`), `nostrod` (`--product=daemon`, `implementations/nostrod.cpp`), or the static library `nostro-checkout` (`--product=checkout`). The bunq connector is the only bank so far and the model for the next one. It depends on Crafter.Network (HTTPS to the bank), Crafter.DB (the local transaction tables and the checkout record), OpenSSL (request signing, response verification), libsystemd (sd-bus and sd-event, for nostrod and its clients) and a vendored nlohmann/json. It ships as a Flatpak, `net.catcrafts.Nostro`, that systemd runs nostrod from as the system user `nostro`.
|
nostro is a banking client for Linux, phones first: a library that talks to bank APIs directly; nostrod, a system daemon that runs it for every local user behind D-Bus and polkit, so no program of the user's can read the bank's secrets or move money without the user's password; a small CLI that only talks to nostrod; and the app, a window for a phone or a desktop that only talks to nostrod too and does everything the CLI does. Linux phones have no banking apps; nostro is the open-source answer, one connector per bank.
|
||||||
|
|
||||||
|
Five C++26 modules, and a sixth in one build:
|
||||||
|
|
||||||
|
- `Nostro`, the library: twelve partitions behind the umbrella and ten implementation units.
|
||||||
|
- `Nostro.Checkout`, for apps that have nostrod pay an order.
|
||||||
|
- `Nostro.Ui`, the toolkit the app's screens are built with. It imports `std` alone.
|
||||||
|
- `Nostro.App`, the app without its window: what it knows, what is filled in, and its screens.
|
||||||
|
- `Nostro.Ui.Shell`, which puts the toolkit on a display, on Crafter.Graphics and one sd-event loop.
|
||||||
|
- `Nostro.DebugCommands`, what an agent drives the app with: in the app's `--debug-api` build and no other.
|
||||||
|
|
||||||
|
`project.cpp` makes one product per build: the static library `nostro` with the CLI `nostro` (`implementations/main.cpp`), `nostrod` (`--product=daemon`, `implementations/nostrod.cpp`), the app `nostro-app` (`--product=app`, `implementations/nostro-app.cpp`), the static library `nostro-checkout` (`--product=checkout`), or `nostro-fake-system` (`--product=fake-system`, `tests/FakeSystem/main.cpp`), a made-up system to look at the app against. The bunq connector is the only bank so far and the model for the next one. The library depends on Crafter.Network (HTTPS to the bank), Crafter.DB (the local transaction tables and the checkout record), OpenSSL (request signing, response verification), libsystemd (sd-bus and sd-event, for nostrod and its clients) and a vendored nlohmann/json; the app adds Crafter.Graphics (a Wayland window, Vulkan, the input) and two Noto Sans fonts. It ships as two Flatpaks: `net.catcrafts.Nostrod`, that systemd runs nostrod from as the system user `nostro` and that holds the CLI, and `net.catcrafts.Nostro`, the app.
|
||||||
|
|
||||||
| Path | What lives there |
|
| Path | What lives there |
|
||||||
|---|---|
|
|---|---|
|
||||||
|
|
@ -14,34 +25,64 @@ nostro is a banking client for Linux, phones first: a library that talks to bank
|
||||||
| `interfaces/Nostro.Checkout.cppm`, `implementations/Nostro.Checkout.cpp` | The module `Nostro.Checkout`: the checkout's names and wire, and a blocking `Pay` over sd-bus. A module of its own, so `--product=checkout` builds it without the rest. |
|
| `interfaces/Nostro.Checkout.cppm`, `implementations/Nostro.Checkout.cpp` | The module `Nostro.Checkout`: the checkout's names and wire, and a blocking `Pay` over sd-bus. A module of its own, so `--product=checkout` builds it without the rest. |
|
||||||
| `implementations/main.cpp` | The CLI, a client of nostrod: `argv` parsing (positional arguments, `--name value` options, `--sandbox`), one function per command over `Client`, output through the `std::formatter`s, the notes on stderr, errors caught in `main` and printed with exit status 1. |
|
| `implementations/main.cpp` | The CLI, a client of nostrod: `argv` parsing (positional arguments, `--name value` options, `--sandbox`), one function per command over `Client`, output through the `std::formatter`s, the notes on stderr, errors caught in `main` and printed with exit status 1. |
|
||||||
| `implementations/nostrod.cpp` | nostrod's `main`: `--state`, `--idle`, `--prompt-timeout`, and `--worker <uid> <name>` for the worker processes it starts itself. |
|
| `implementations/nostrod.cpp` | nostrod's `main`: `--state`, `--idle`, `--prompt-timeout`, and `--worker <uid> <name>` for the worker processes it starts itself. |
|
||||||
| `project.cpp` | The build description: reads `--banks=`, `--lib`, `--dbus`, `--product=`, `--coverage` and `--profile-runtime=`, forwards the other args to the dependencies (with `--no-quic` for Crafter.Network), returns the product. |
|
| `interfaces/Nostro.Ui.cppm`, `interfaces/Nostro.Ui-<Partition>.cppm`, `implementations/Nostro.Ui-<Partition>.cpp` | The toolkit, `Nostro.Ui`: ten partitions, seven of them with an implementation unit. Ported from imsd-messages (ca5cd72d), which is Catcrafts' and GPL-3.0-only like it. |
|
||||||
|
| `interfaces/Nostro.App.cppm`, `interfaces/Nostro.App-<Partition>.cppm`, `implementations/Nostro.App-<Partition>.cpp` | `Nostro.App`: `:Banks`, `:Format`, `:Forms`, `:Errors` and `:App`. `:App` has three implementation units: `Nostro.App-App.cpp` (state, nostrod's answers, navigation, actions), `Nostro.App-Screens.cpp` (the screens) and `Nostro.App-Bunq.cpp` (bunq's two forms for adding a connection, and what their buttons do). |
|
||||||
|
| `interfaces/Nostro.Ui.Shell.cppm`, `interfaces/Nostro.Ui.Shell-<Partition>.cppm`, `implementations/Nostro.Ui.Shell-<Partition>.cpp` | `Nostro.Ui.Shell`: `:Loop`, `:Canvas`, `:Window` and `:Portal`. The one part that needs a compositor and a graphics device. |
|
||||||
|
| `implementations/nostro-app.cpp` | The app's `main`: the command line, the parts put together, the toolkit's gallery (`--gallery`) and a player of input scripts (`--poke`). |
|
||||||
|
| `interfaces/Nostro.DebugCommands.cppm`, `implementations/Nostro.DebugCommands.cpp` | The commands, watches, events and checks of the app's `--debug-api` build; see "Looking at the app". |
|
||||||
|
| `assets/` | Noto Sans Regular and Medium with their licence (`OFL.txt`); the app's build puts the fonts beside the executable. |
|
||||||
|
| `project.cpp` | The build description: reads `--banks=`, `--lib`, `--dbus`, `--product=`, `--graphics=`, `--debug-api`, `--coverage` and `--profile-runtime=`, forwards the other args to the dependencies (with `--no-quic` for Crafter.Network, except in the app's debug build), returns the product. It also holds what the app is as a Flatpak (`app.flatpak`) and the `fake` run script. |
|
||||||
| `packaging/dbus/` | The published D-Bus interfaces, `net.catcrafts.Nostro1.xml` and `net.catcrafts.Nostro1.Checkout.xml`. |
|
| `packaging/dbus/` | The published D-Bus interfaces, `net.catcrafts.Nostro1.xml` and `net.catcrafts.Nostro1.Checkout.xml`. |
|
||||||
| `packaging/system/` | What a Flatpak cannot install: the polkit policy, the D-Bus policy and activation files, `nostrod.service`, the sysusers entry, the `nostro` command, `install.sh` and `uninstall.sh`. |
|
| `packaging/system/` | What a Flatpak cannot install: the polkit policy, the D-Bus policy and activation files, `nostrod.service`, the sysusers entry, the `nostro` command, `install.sh` and `uninstall.sh`. |
|
||||||
| `packaging/flatpak/`, `packaging/arch/` | The Flatpak manifest (on crafter-build's Flatpak as its base app), metainfo and `.flatpakref`; the Arch package of the system files, `nostro-system`. |
|
| `packaging/flatpak/`, `packaging/licenses/`, `packaging/arch/` | nostrod's Flatpak manifest (on crafter-build's Flatpak as its base app), each Flatpak's metainfo and `.flatpakref`, the app's desktop entry and icon, and the two scripts that cross-build both Flatpaks for aarch64; the licence texts the Flatpaks carry, with a `NOTICE` of what each covers; the Arch package of the system files, `nostro-system`. |
|
||||||
| `lib/json.hpp` | nlohmann/json 3.12.0 (MIT), included in the global module fragment of `:Bunq` and of the `Connector`, `Bunq` and `BunqPayments` implementation units. |
|
| `lib/json.hpp` | nlohmann/json 3.12.0 (MIT), included in the global module fragment of `:Bunq` and of the `Connector`, `Bunq` and `BunqPayments` implementation units. |
|
||||||
| `tests/<Name>/main.cpp`, `tests/Support/`, `tests/coverage.sh` | The tests, their checks, fake bunq and fake system bus, and the coverage run; see "Testing instructions". |
|
| `tests/<Name>/main.cpp`, `tests/Support/`, `tests/FakeSystem/`, `tests/coverage.sh` | The tests, their checks, fake bunq and fake system bus, the made-up system built from those, and the coverage run; see "Testing instructions". |
|
||||||
| `README.md`, `LICENSE`, `LICENSE.GPL` | The manual; LGPL-3.0-only and the GPL it incorporates. |
|
| `docs/screenshots/` | The README's pictures of the app, on a phone's screen and in a desktop window, and `take.sh`, which takes them again on the made-up system; see "Looking at the app". |
|
||||||
|
| `README.md`, `LICENSE`, `LICENSE.GPL` | The manual; the LGPL version 3, which the library, nostrod and the CLI are under, and the GPL version 3, which the LGPL adds its permissions to and which the app is under (design rule 13). |
|
||||||
| `AGENTS.template.md`, `AGENTS.consumer.md` | The source of this file, and the notes for consumers. `AGENTS.md` is gitignored: edit the template. |
|
| `AGENTS.template.md`, `AGENTS.consumer.md` | The source of this file, and the notes for consumers. `AGENTS.md` is gitignored: edit the template. |
|
||||||
| `.vscode/` | A build task and an lldb launch configuration, both stale; see "Gotchas". |
|
| `.vscode/` | A build task and an lldb launch configuration, both stale; see "Gotchas". |
|
||||||
| `bin/`, `build/` | Generated and gitignored. The library and the CLI are both named `nostro`, so one build leaves two `bin/nostro-<target>-<march>-<mtune>-<hash>/` directories: the library's (`libnostro.a`, the PCMs, `std.pcm`) and the executable's (`nostro`). Glob for the one holding `nostro`. nostrod builds into `bin/nostrod-…/`, the checkout library into `bin/nostro-checkout-…/`. |
|
| `bin/`, `build/` | Generated and gitignored. The library and the CLI are both named `nostro`, so one build leaves two `bin/nostro-<target>-<march>-<mtune>-<hash>/` directories: the library's (`libnostro.a`, the PCMs, `std.pcm`) and the executable's (`nostro`). Glob for the one holding `nostro`. nostrod builds into `bin/nostrod-…/`, the checkout library into `bin/nostro-checkout-…/`, the app into `bin/nostro-app-…/` with its fonts and Crafter.Graphics' shaders beside it (`bin/nostro-app-core-…/` is `Nostro.App`'s library), or under `files/bin/` there when it is packaged as a Flatpak. `build/crafter-debug` is the launcher of Crafter.Debug's client, `build/fake-system/` the state of the made-up system `run fake` starts, `build/flatpak-apps/` what `install` and `bundle` make of the app. |
|
||||||
|
|
||||||
Partitions, from the bottom up (each imports only the ones above it):
|
Partitions, from the bottom up (each imports only the ones above it):
|
||||||
|
|
||||||
- `:Currency`: `Currency` (an `enum class : std::uint16_t` with `Euro` alone), `GetCurrency` (from `"EUR"` or `"eur"`, throws for anything else), `GetCurrencyCode`, `GetCurrencySymbol`, `GetCurrencyDecimals`, `ParseAmount` (decimal string to minor units), `FormatAmount` (back) and `FormatMoney` (`-€1.02`), all `constexpr`, and `std::formatter<Currency>`, which prints the symbol.
|
- `:Currency`: `Currency` (an `enum class : std::uint16_t` with `Euro` alone), `GetCurrency` (from `"EUR"` or `"eur"`, throws for anything else), `GetCurrencyCode`, `GetCurrencySymbol`, `GetCurrencyDecimals`, `ParseAmount` (decimal string to minor units), `FormatAmount` (back) and `FormatMoney` (`-€1.02`), all `constexpr`, and `std::formatter<Currency>`, which prints the symbol.
|
||||||
- `:Utils`: `ParseTimestamp` and `FormatTimestamp` (bunq's `YYYY-MM-DD HH:MM:SS[.ffffff]`, UTC), `ParseLocalDate` and `FormatLocalTime` (dates a person types and reads, local time through `mktime`/`localtime`), `UrlEncode`, `UrlDecode` and `QueryParameter` (for OAuth), `EscB` (JSON string escaping, no longer used by nostro itself), and `Note` with its replaceable `noteSink`, where every warning of the library goes (stderr by default).
|
- `:Utils`: `ParseTimestamp` and `FormatTimestamp` (bunq's `YYYY-MM-DD HH:MM:SS[.ffffff]`, UTC), `ParseLocalDate`, `ParseLocalDateEnd` and `FormatLocalTime` (dates a person types and reads, local time through `mktime`/`localtime`), `UrlEncode`, `UrlDecode` and `QueryParameter` (for OAuth), `EscB` (JSON string escaping, no longer used by nostro itself), and `Note` with its replaceable `noteSink`, where every warning of the library goes (stderr by default).
|
||||||
- `:Transaction`: the `Transaction` aggregate, which is also the row type of the Crafter.DB tables: `version = 2` (`id` and `kind` added on 2026-10-31), `orderedBy = &Transaction::timePoint`, `using Previous = TransactionV1` (unexported, kept for the migration), and its `std::formatter` (one tab-separated line).
|
- `:Transaction`: the `Transaction` aggregate, which is also the row type of the Crafter.DB tables: `version = 2` (`id` and `kind` added on 2026-10-31), `orderedBy = &Transaction::timePoint`, `using Previous = TransactionV1` (unexported, kept for the migration), and its `std::formatter` (one tab-separated line).
|
||||||
- `:Account`: `TransactionQuery` and `Account` (`name`, `bic`, `iban`, `currency`, `balance` in minor units) with the three methods over the transaction store and the static `ForgetTransactions` (which closes this process's open tables under a storage key before deleting them), and the `std::formatter` for `Account` and everything derived from it. The implementation unit owns the Crafter.DB tables and pins the schema with two `static_assert`s.
|
- `:Account`: `TransactionQuery` and `Account` (`name`, `bic`, `iban`, `currency`, `balance` in minor units) with the three methods over the transaction store and the static `ForgetTransactions` (which closes this process's open tables under a storage key before deleting them), and the `std::formatter` for `Account` and everything derived from it. The implementation unit owns the Crafter.DB tables and pins the schema with two `static_assert`s.
|
||||||
- `:File`: `GetConfigPath`, `GetCachePath`, the globals `configPath` and `cachePath` they initialise at static-init time, `CreatePrivateFile` (a `0600` file in a `0700` directory), and `ReadSecret` (a line from stdin, not echoed on a terminal).
|
- `:File`: `GetConfigPath`, `GetCachePath`, the globals `configPath` and `cachePath` they initialise at static-init time, `CreatePrivateFile` (a `0600` file in a `0700` directory), and `ReadSecret` (a line from stdin, not echoed on a terminal).
|
||||||
- `:Crypto` (under `NOSTRO_OPENSSL_ENABLED`; OpenSSL headers in the global module fragment), in `namespace Nostro::Crypto`: `ThrowOnOpenssl`, `Key` (`std::shared_ptr<EVP_PKEY>` freeing itself) and `OwnKey`, `SignBody` (RSA SHA-256, base64) and `VerifyBody` (its check against a public key), `CreateKey` (RSA 2048 and its public PEM), `LoadKeyFromPem`, `LoadPublicKeyFromPem`, `PrivateKeyToPem`, `PublicKeyToPem`, `RandomHex` (the OAuth `state`).
|
- `:Crypto` (under `NOSTRO_OPENSSL_ENABLED`; OpenSSL headers in the global module fragment), in `namespace Nostro::Crypto`: `ThrowOnOpenssl`, `Key` (`std::shared_ptr<EVP_PKEY>` freeing itself) and `OwnKey`, `SignBody` (RSA SHA-256, base64) and `VerifyBody` (its check against a public key), `CreateKey` (RSA 2048 and its public PEM), `LoadKeyFromPem`, `LoadPublicKeyFromPem`, `PrivateKeyToPem`, `PublicKeyToPem`, `RandomHex` (the OAuth `state`).
|
||||||
- `:Bunq` (under `NOSTRO_BUNQ_ENABLED`; `json.hpp` and `openssl/types.h` in the global module fragment; the implementation units import Crafter.Network): `BunqEnvironment`, `BunqError`, `BunqCounterparty`, the listing types (`BunqLabel`, `BunqPaymentRequest`, `BunqIncomingRequest`, `BunqSchedule`, `BunqScheduledPayment`, `BunqDraftPayment`, `BunqCard`) and their formatters, `BunqAccount : Account` (`id`, `type`, `connector`, the payment calls), `BunqConnector` (environment, keys, tokens, user, `accounts`, the raw `Get`/`Post`/`Put`/`Delete`/`List`, the static deque `connectors`, `Create`, `Remove`, the OAuth helpers, and `Endpoint`/`RedirectTo` with `BunqEndpoint`), `to_json`/`from_json`, and the unexported `BunqJson` helpers both implementation units share.
|
- `:Bunq` (under `NOSTRO_BUNQ_ENABLED`; `json.hpp` and `openssl/types.h` in the global module fragment; the implementation units import Crafter.Network): `BunqEnvironment`, `BunqError` (with `maybeCarriedOut`, the end of an error to a write that may have happened all the same), `BunqCounterparty`, the listing types (`BunqLabel`, `BunqPaymentRequest`, `BunqIncomingRequest`, `BunqSchedule`, `BunqScheduledPayment`, `BunqDraftPayment`, `BunqCard`) and their formatters, `BunqAccount : Account` (`id`, `type`, `connector`, the payment calls), `BunqConnector` (environment, keys, tokens, user, `accounts`, the raw `Get`/`Post`/`Put`/`Delete`/`List`, the static deque `connectors`, `Create`, `Remove`, the OAuth helpers, and `Endpoint`/`RedirectTo` with `BunqEndpoint`), `to_json`/`from_json`, and the unexported `BunqJson` helpers both implementation units share.
|
||||||
- `:Banks`: `tuple_for<Tuple>(f)` and `EnabledBanks`, the `std::tuple` of enabled connector types; every generic loop in the CLI and in `:Connector` is a `tuple_for<EnabledBanks>`.
|
- `:Banks`: `tuple_for<Tuple>(f)` and `EnabledBanks`, the `std::tuple` of enabled connector types; every generic loop in the CLI and in `:Connector` is a `tuple_for<EnabledBanks>`.
|
||||||
- `:Connector`: `Connector::SaveConnectors()` and `LoadConnectors()`, `connectors.json` out (synced, then renamed into place) and in, both under the process-wide `connectors.lock`.
|
- `:Connector`: `Connector::SaveConnectors()` and `LoadConnectors()`, `connectors.json` out (synced, then renamed into place) and in, both under the process-wide `connectors.lock`.
|
||||||
- `:Bus` (under `NOSTRO_DBUS_ENABLED`; `sd-bus.h` in the global module fragment): the wire nostrod and its clients share. The names, the error names (the checkout's from `Nostro.Checkout`), the polkit actions, the method tables `methods` and `checkoutMethods` (member, signatures, argument names, sensitive), the result structs (`ConnectorSummary`, `AddedConnector`, `ConnectorAccounts`, `ConnectorCards`, `Created`), `Wire<T>` with `Append` and `Read` for every type that travels (a struct as its members, a time as microseconds, a currency as its code, an optional as an array of zero or one), `AppendQuery`/`ReadQuery`, `Vtable`, `ThrowOnSdBus`, and the `BusPtr`/`MessagePtr`/`Error` owners.
|
- `:Bus` (under `NOSTRO_DBUS_ENABLED`; `sd-bus.h` in the global module fragment): the wire nostrod and its clients share. The names, the error names (the checkout's from `Nostro.Checkout`), the polkit actions, the method tables `methods` and `checkoutMethods` (member, signatures, argument names, sensitive), the result structs (`ConnectorSummary`, `AddedConnector`, `ConnectorAccounts`, `ConnectorCards`, `Created`), `Wire<T>` with `Append` and `Read` for every type that travels (a struct as its members, a time as microseconds, a currency as its code, an optional as an array of zero or one), `AppendQuery`/`ReadQuery`, `Vtable`, `ThrowOnSdBus`, and the `BusPtr`/`MessagePtr`/`Error` owners.
|
||||||
- `:Client`: `Client::System()`, one method per method of `net.catcrafts.Nostro1`, `TakeNotes()`, and `DaemonError`.
|
- `:Client`: `Client::System()`, one method per method of `net.catcrafts.Nostro1` in a blocking and an asynchronous form (`Attach`, `Client::Pending`, `Answer`), `TakeNotes()`, `DaemonError`, `DaemonMissing` and `OutcomeUnknown`.
|
||||||
- `:Daemon`: `DaemonOptions`, `RunDaemon` (the front) and `RunWorker` (one user's worker).
|
- `:Daemon`: `DaemonOptions`, `RunDaemon` (the front) and `RunWorker` (one user's worker).
|
||||||
|
|
||||||
`Nostro.Checkout`, a module of its own that imports nothing of `Nostro`: the checkout's bus name, interface, `Pay`'s signatures and argument names, the error names apps tell apart, `Order`, `Paid`, `Error` with `Cancelled` and `NoCheckoutAccount`, and `Pay`. `:Bus` and the daemon take their names from it.
|
`Nostro.Checkout`, a module of its own that imports nothing of `Nostro`: the checkout's bus name, interface, `Pay`'s signatures and argument names, the error names apps tell apart, `Order`, `Paid`, `Error` with `Cancelled` and `NoCheckoutAccount`, and `Pay`. `:Bus` and the daemon take their names from it.
|
||||||
|
|
||||||
|
`Nostro.Ui`, in `namespace Nostro::Ui`, draws nothing and reads no device: a screen is a function that fills a `Frame`. Its partitions, from the bottom up:
|
||||||
|
|
||||||
|
- `:Geometry`: `Point`, `Box`, `Insets`, `Color`, `Metrics` (the display's scale, `Dp()`) and `SizeClass`: compact under 600 dp wide, medium under 900, expanded from there. Everything is in physical pixels; dp exists in the design's constants and is turned into pixels where it is used (`frame.Dp()`).
|
||||||
|
- `:Text`: UTF-8 by code point, `TextMeasure` (three functions, which the window supplies and a test fixes), `TextWidth`, `Ellipsize`, `CenteredBaseline`, and `WordWrapper` with its cache.
|
||||||
|
- `:Edit`: `EditState`, a field's text with its cursor, its selection and the word an input method is composing, and `FieldKind` (`Text`, `Plain`, `Decimal`, `Digits`, `Secret`). A `Secret` is never copied or shown, and wipes its buffer when it goes.
|
||||||
|
- `:Gesture`: `GestureDetector` (tap, long press, drag, fling), `ScrollState`, `EventClock`, `FrameWait`.
|
||||||
|
- `:Draw`: `DrawList`: boxes, circles and text in five layers (`Background`, `Content`, `Chrome`, `Overlay`, `Popup`), split into batches at a clip and wherever a shape follows text it overlaps, since the window draws a batch's shapes before its text.
|
||||||
|
- `:Theme`: `Theme::Light()`, `Dark()` and `Accent()`, and the design's sizes (`TextSize`, `Size`).
|
||||||
|
- `:Input`: `Key`, `Modifiers`, `TextPurpose`, `TextHint`, `TextInputRequest`.
|
||||||
|
- `:Context`: `Region` (a box, a key that names it across frames, a role, what a press does), `Frame` (one frame's draw list, regions, shortcuts and scrolling areas), and `Context`, which keeps what outlives a frame (the focus, each list's position, the press that is down, a menu, a notice, what was put off with `At`) and turns pointer, key and text events into the regions' actions. `Take()` says what the window is to do next (`Wants`: a frame, a timer, the on-screen keyboard, the clipboard). What a sheet covers is out of reach of a finger and of the keyboard alike: a frame that puts a sheet (a scrim below the topmost layer) over what had the focus takes the focus from it, so neither Enter nor typing reaches under a sheet; a menu is no sheet, and leaves its field the focus. A scrolling area a screen marks `Refreshable` gives way when it is dragged down at its top (`Pulled()`), and runs its action when it is let go 64 dp down. `Tap(key)` and `LongPress(key)` are for a test or a debugger.
|
||||||
|
- `:Layout`: `Column`, `Row`, `Centered`.
|
||||||
|
- `:Widgets`: functions that draw into a frame and name its regions: `Label`, `Paragraph`, `Button`, `ListRow`, `ValueRow`, `TextField`, `Segmented`, `Tabs`, `Banner`, `Chip`, `Skeleton`, `TopBar`, `NavBar`, `Sidebar`, `Sheet`.
|
||||||
|
|
||||||
|
`Nostro.App`, in `namespace Nostro::App`, imports `Nostro` and `Nostro.Ui`:
|
||||||
|
|
||||||
|
- `:Banks`: what is a bank's own, for each bank the app can connect: `Bank` (what nostrod calls it, its name, its ways in) and `Way` (a way to connect: its title, the form it is filled in on, where what was given is revoked, and whether a connection made that way pays between the user's own accounts only). They are found by nostrod's names for them (`Banks`, `FindBank`, `FindWay`, `BankName`, `WayName`, `OwnAccountsOnly`, `Revoking`); a bank or a way that nostrod has and the app does not know is said by nostrod's name for it. Not the library's `Nostro:Banks`, which is the banks a build has.
|
||||||
|
- `:Format`: how the app words what a bank gives it: `Money` (`€12,500.00`), `GroupIban`, `PartyName`, `DayLabel`, `ShortDate`, `KindLabel`, `StatusLabel`, `CardExpiry`, `ScheduleLabel`, `Fingerprint`. English only; every such wording is here, and none of it names a bank.
|
||||||
|
- `:Forms`: what is typed, read (`ReadAmount`, `ReadParty`, `ReadDay`, `ReadCount`), and the forms with their checks: `PaymentForm`, `RequestForm` and `FilterForm`, which are any bank's, and the two a connection to bunq is made with, `BunqKeyForm` and `BunqOAuthForm`.
|
||||||
|
- `:Errors`: `Operation`, the polkit action of each (`ActionOf`, `AsksPassword`, `MovesMoney`), and `Explain(error, operation)`, which turns an answer's error into `Guidance`.
|
||||||
|
- `:App`: `Host` (what the program around the app gives it), `Loadable<T>`, `Connection`, and the class `App`.
|
||||||
|
|
||||||
|
`Nostro.Ui.Shell`, in `namespace Nostro::Ui::Shell`, imports Crafter.Graphics and `Nostro.Ui`, and nothing of the library or the app: `:Loop` (`Loop`, `Timer`, `Defer`, `WaylandSource`, `FrameDriver`), `:Canvas` (`Fonts`, `Canvas`), `:Window` and `:Portal`.
|
||||||
|
|
||||||
The bunq connector end to end:
|
The bunq connector end to end:
|
||||||
|
|
||||||
- **Requests** (`implementations/Nostro-Bunq.cpp`): every call goes through the private `BunqConnector::Call`, behind the public `Get`, `Post`, `Put`, `Delete` and `List`. It talks to `BunqConnector::Endpoint(environment)`: `api.bunq.com` or `public-api.sandbox.bunq.com` by the connector's environment, or wherever `RedirectTo` sent everything (the tests' fake), with one `ClientHTTP1` per endpoint.
|
- **Requests** (`implementations/Nostro-Bunq.cpp`): every call goes through the private `BunqConnector::Call`, behind the public `Get`, `Post`, `Put`, `Delete` and `List`. It talks to `BunqConnector::Endpoint(environment)`: `api.bunq.com` or `public-api.sandbox.bunq.com` by the connector's environment, or wherever `RedirectTo` sent everything (the tests' fake), with one `ClientHTTP1` per endpoint.
|
||||||
|
|
@ -53,6 +94,7 @@ The bunq connector end to end:
|
||||||
- **Connecting:** `Create(apiKey, allowedIps, environment)` makes an RSA key, then `POST /installation` (installation token and server key), `POST /device-server` with `permitted_ips` as a JSON array, and `RefreshSession()`. The session is `POST /session-server`, signed: the token, the session id, and the user from `UserPerson`, `UserCompany`, `UserPaymentServiceProvider` or, for OAuth, `UserApiKey` (its own id in paths, `ownerId` and the name from `granted_by_user`).
|
- **Connecting:** `Create(apiKey, allowedIps, environment)` makes an RSA key, then `POST /installation` (installation token and server key), `POST /device-server` with `permitted_ips` as a JSON array, and `RefreshSession()`. The session is `POST /session-server`, signed: the token, the session id, and the user from `UserPerson`, `UserCompany`, `UserPaymentServiceProvider` or, for OAuth, `UserApiKey` (its own id in paths, `ownerId` and the name from `granted_by_user`).
|
||||||
- **Accounts and history:** `RefreshAccounts()` lists every `MonetaryAccount…` type that is `ACTIVE` or `BLOCKED`. `GetNewTransactions(account)` pages the payments newest first until one older than the last stored row, and hands them to `Account::SaveTransactions` under `account.StorageKey()`.
|
- **Accounts and history:** `RefreshAccounts()` lists every `MonetaryAccount…` type that is `ACTIVE` or `BLOCKED`. `GetNewTransactions(account)` pages the payments newest first until one older than the last stored row, and hands them to `Account::SaveTransactions` under `account.StorageKey()`.
|
||||||
- **Payments** (`implementations/Nostro-Bunq-Payments.cpp`): `BunqCounterparty::Parse` reads an IBAN (check digits verified), an e-mail address or a phone number. `Send`, `Draft`, `Schedule` and `Request` build their bodies from it, the listings read bunq's objects into the listing types, and the responses are PUTs or a DELETE. Accepting a request or a draft takes the object as it was read and shown (`IncomingRequest(id)`, `DraftPayment(id)`), so what gets paid is what the user saw.
|
- **Payments** (`implementations/Nostro-Bunq-Payments.cpp`): `BunqCounterparty::Parse` reads an IBAN (check digits verified), an e-mail address or a phone number. `Send`, `Draft`, `Schedule` and `Request` build their bodies from it, the listings read bunq's objects into the listing types, and the responses are PUTs or a DELETE. Accepting a request or a draft takes the object as it was read and shown (`IncomingRequest(id)`, `DraftPayment(id)`), so what gets paid is what the user saw.
|
||||||
|
- **Cards:** a card is read with bunq's `status` and `order_status`, and `BunqCard::State()` is what to call how it stands: bunq's status, but `VIRTUAL` for a virtual card (`Virtual()`: its order status is `VIRTUAL_DELIVERY`) that is not gone for good, since bunq has one as `DEACTIVATED` however well it pays. The CLI and the app show that. bunq leaves a virtual card as it is when asked to freeze or unfreeze it, and answers as if it had been done: nostrod refuses that before anyone is asked for a password, and `ExpectStatus` does not take the unchanged card for a frozen one.
|
||||||
- **OAuth:** `OAuthAuthorizationUrl` and `OAuthExchangeCode` (the token endpoint reads query parameters only). The token then goes to `Create` like an API key.
|
- **OAuth:** `OAuthAuthorizationUrl` and `OAuthExchangeCode` (the token endpoint reads query parameters only). The token then goes to `Create` like an API key.
|
||||||
|
|
||||||
nostrod end to end:
|
nostrod end to end:
|
||||||
|
|
@ -60,15 +102,34 @@ nostrod end to end:
|
||||||
- **The front** (`implementations/Nostro-Daemon.cpp`, `RunDaemon`) is one sd-event loop with two system bus connections. One owns `net.catcrafts.Nostro1` and serves that interface. The other owns `net.catcrafts.Nostro1.Checkout` and serves the checkout alone: a Flatpak allowed to talk to that name can call its owner's unique name too, and on that connection there is nothing else. Every method of both is one forwarding handler. It asks the bus for the caller's uid (`GetConnectionCredentials`), and logind for that uid's name, starts the uid's worker if there is none (`posix_spawn` of `/proc/self/exe --worker <uid> <name> …`, a socketpair end as fd 3, D-Bus peer to peer over it), and passes a copy of the call on, from the caller's unique name and allowing a dialog only when the caller did. The answer is relayed when it comes, so one user's open dialog holds up nobody. A worker that dies under a call is answered `Failed` with "may have been carried out". It holds no connector and no secret. It ends once idle with no worker left, on SIGTERM, or when the bus goes; D-Bus activation starts it again.
|
- **The front** (`implementations/Nostro-Daemon.cpp`, `RunDaemon`) is one sd-event loop with two system bus connections. One owns `net.catcrafts.Nostro1` and serves that interface. The other owns `net.catcrafts.Nostro1.Checkout` and serves the checkout alone: a Flatpak allowed to talk to that name can call its owner's unique name too, and on that connection there is nothing else. Every method of both is one forwarding handler. It asks the bus for the caller's uid (`GetConnectionCredentials`), and logind for that uid's name, starts the uid's worker if there is none (`posix_spawn` of `/proc/self/exe --worker <uid> <name> …`, a socketpair end as fd 3, D-Bus peer to peer over it), and passes a copy of the call on, from the caller's unique name and allowing a dialog only when the caller did. The answer is relayed when it comes, so one user's open dialog holds up nobody. A worker that dies under a call is answered `Failed` with "may have been carried out". It holds no connector and no secret. It ends once idle with no worker left, on SIGTERM, or when the bus goes; D-Bus activation starts it again.
|
||||||
- **A worker** (`implementations/Nostro-Daemon-Worker.cpp`, `RunWorker`) is one user's library: `configPath` and `cachePath` are `<state>/users/<uid>`, the connectors are read on the first call, and it is not dumpable. A directory records whose it is (`owner`): a uid that logind now names differently, after a user was deleted and another given their uid, is refused. Every handler reads and checks the call first (the account, the counterparty, what is to be paid, or for a request or a draft the object as bunq has it), builds a `Prompt` (the polkit action, a summary from its own data, and details for polkit rules), and hands it to `Gate`. `Gate` asks polkit asynchronously (`CheckAuthorization` about the caller's bus name, cancelled if it does not answer in time) and runs the call's work only once polkit says yes. It fails closed: no polkit, an error or a timeout is `AccessDenied`. A dialog the user closed is `Cancelled`, which polkit says with `polkit.dismissed` or, from Plasma's agent, `polkit.result` `auth_…`. A challenge to a call that allowed no dialog is `InteractiveAuthorizationRequired`. Every answer of the main interface ends with the notes. A summary's text from a caller or the bank goes through `Shown()` (no control, invisible or direction characters, `<` and `>` replaced, `$(` broken, 64 characters at most) and names the address before the name. The worker ends once idle with no dialog open, on SIGTERM, or when the front goes.
|
- **A worker** (`implementations/Nostro-Daemon-Worker.cpp`, `RunWorker`) is one user's library: `configPath` and `cachePath` are `<state>/users/<uid>`, the connectors are read on the first call, and it is not dumpable. A directory records whose it is (`owner`): a uid that logind now names differently, after a user was deleted and another given their uid, is refused. Every handler reads and checks the call first (the account, the counterparty, what is to be paid, or for a request or a draft the object as bunq has it), builds a `Prompt` (the polkit action, a summary from its own data, and details for polkit rules), and hands it to `Gate`. `Gate` asks polkit asynchronously (`CheckAuthorization` about the caller's bus name, cancelled if it does not answer in time) and runs the call's work only once polkit says yes. It fails closed: no polkit, an error or a timeout is `AccessDenied`. A dialog the user closed is `Cancelled`, which polkit says with `polkit.dismissed` or, from Plasma's agent, `polkit.result` `auth_…`. A challenge to a call that allowed no dialog is `InteractiveAuthorizationRequired`. Every answer of the main interface ends with the notes. A summary's text from a caller or the bank goes through `Shown()` (no control, invisible or direction characters, `<` and `>` replaced, `$(` broken, 64 characters at most) and names the address before the name. The worker ends once idle with no dialog open, on SIGTERM, or when the front goes.
|
||||||
- **Checkout** (the same file): `Order::Read` refuses a payee that is not an IBAN, an amount that is not positive, an unknown currency or an empty reference. An order already in `checkouts.cdb` (a Crafter.DB table, `CheckoutRecord`) is answered with its payment, `repeated`, without a dialog, or refused when its amount differs, or when its payment is still 0: a payment whose outcome was lost. An order being paid makes the next call for it wait, and `Settle` gives it the first call's answer. `ChooseAccount` picks the account (the one in `checkout-account`, set by `SetDefaultCheckoutAccount`; an account of an OAuth connector is refused there) and answers through a continuation, so an account picker can take its place later. The dialog (`net.catcrafts.Nostro1.Checkout`) shows the order and that account. `PayOrder` records the order, with no payment, before it pays, and takes the record away again only when bunq refused before doing anything, below 500.
|
- **Checkout** (the same file): `Order::Read` refuses a payee that is not an IBAN, an amount that is not positive, an unknown currency or an empty reference. An order already in `checkouts.cdb` (a Crafter.DB table, `CheckoutRecord`) is answered with its payment, `repeated`, without a dialog, or refused when its amount differs, or when its payment is still 0: a payment whose outcome was lost. An order being paid makes the next call for it wait, and `Settle` gives it the first call's answer. `ChooseAccount` picks the account (the one in `checkout-account`, set by `SetDefaultCheckoutAccount`; an account of an OAuth connector is refused there) and answers through a continuation, so an account picker can take its place later. The dialog (`net.catcrafts.Nostro1.Checkout`) shows the order and that account. `PayOrder` records the order, with no payment, before it pays, and takes the record away again only when bunq refused before doing anything, below 500.
|
||||||
- **The client** (`implementations/Nostro-Client.cpp`) allows interactive authorization and waits 10 minutes by default; nostrod's `InvalidArgument` becomes `std::invalid_argument`, `ServiceUnknown` a "not running" message, a write without an answer "may have been carried out", and the rest a `DaemonError` with its name. `Nostro.Checkout`'s `Pay` does the same for the checkout with its own types.
|
- **The client** (`implementations/Nostro-Client.cpp`) allows interactive authorization and waits 10 minutes by default. Each method is one `MethodCall` (member, whether it changes anything, how its answer is read) and one append helper, shared by the blocking form (`Run`: `sd_bus_call`) and the asynchronous one (`Start`: `sd_bus_call_async` on a bus attached to the caller's sd-event loop, whose non-floating slot the returned `Pending` owns; the slot frees what waits for the answer, and `OnReply` reads the answer into an `Answer` and calls `then`, never throwing into sd-bus). nostrod's `InvalidArgument` becomes `std::invalid_argument`, `ServiceUnknown` `DaemonMissing`, a write without an answer, or one bunq answered with an error ending in `BunqError::maybeCarriedOut`, `OutcomeUnknown`, and the rest a `DaemonError` with its name. `Nostro.Checkout`'s `Pay` does the same for the checkout with its own types.
|
||||||
|
|
||||||
|
The app end to end:
|
||||||
|
|
||||||
|
- **The app** (`App::App(Ui::Context&, Host)`) asks nostrod through the asynchronous `Client` and never waits for it: an answer changes its state and invalidates the frame. `Build(frame)` builds the screen the user is on, `Screen()` names it (`accounts`, `account:<IBAN>+filter`), `Navigate(route)` goes to one, and `Busy()` and `Changing()` say what is under way.
|
||||||
|
- Of each kind of reading one call is in flight, and the newest asked for meanwhile waits for it: dropping a call does not stop the worker's HTTPS, and bunq allows 3 GETs per 3 seconds.
|
||||||
|
- The bank is asked for an account's payments when its list is first shown, when it is read again (Refresh, F5, the pull) and after a change to the account. A search, a filter and "Show more" are questions about that list, put to what nostrod has stored (`LoadActivity(key, true)`, the query's `stored`): they are answered in milliseconds, so a search runs with every letter typed. Where no list is shown, because none was read yet or the reading failed, a search does go to the bank, once the typing has stopped for 400 ms or at Enter. A search therefore finds what the list had when it was last read, not what the bank has had since.
|
||||||
|
- One change at a time: a sheet shows it under way and then its outcome, and nothing else can be asked for meanwhile, so nothing is sent twice. Three things hold that: the sheet covers the screen and cannot be sent away; the toolkit takes the focus from whatever a sheet covers, so the key that pressed a button does not press it again from under the sheet; and `Navigate` refuses while a change is under way.
|
||||||
|
- The pay form sends on its button (`SubmitPayment`, the region `pay.submit`, named for what it does: Pay, Schedule or Save as draft), with no question of the app's own before it. A payment and a schedule are confirmed in polkit's dialog, which nostrod words from its own data; a draft is saved at once, since accepting it is what gets confirmed. The app's own review of a payment was taken out on 2026-11-19, as a second confirmation of what the dialog confirms: do not put one back. Closing polkit's dialog is how a payment is backed out of: nothing is paid, and the form stays as it was filled in.
|
||||||
|
- What the app does ask about first, in an `Ask` sheet built from the values that are then sent: a request before it is sent, which polkit confirms with no password in an active session, and what a detail sheet offers (revoking, accepting, rejecting, cancelling, a card reported lost, a connection removed). While a change is under way its sheet says where to confirm it when its action asks for a password (`AsksPassword`), and `ShouldDriveTheApp` holds that to the action nostrod's check names.
|
||||||
|
- An answer that leaves open whether money moved says so, shows the way to the account's activity, and offers no button to try again.
|
||||||
|
- An action names what it is about by value, an IBAN or the bank's id, never by a place in a list: a press acts on what it went down on, and a list changes under the finger when an answer arrives.
|
||||||
|
- Accounts go to nostrod by IBAN, by name where the bank gave none; a connection by name, or by its number from a fresh `Accounts` listing when two share a name.
|
||||||
|
- Which bank an account is with makes no difference outside the settings. No screen there names a bank, or a way to connect to one, in the app's own words: it says "your bank". `ShouldDriveTheApp` fails on a frame that does, excepting what nostrod and the bank say themselves: a note about a connector, a refusal with the call it refused, a link the bank made. What does differ by bank is asked of `:Banks`: a connection that pays between the user's own accounts only, as bunq's through OAuth, is `Connection::ownAccountsOnly`. It is marked Limited, a payment from it to anyone else is saved as a draft, and it cannot pay a request or a shop.
|
||||||
|
- Adding a connection is three pages, from the settings and from the welcome alike: the banks (`add`), the bank's ways (`add:bunq`) and the way's form (`add:bunq:key`). The first two are built from `:Banks`. The form is the bank's own to draw and to check, in a file of the bank's (`Nostro.App-Bunq.cpp`), and its button ends in `App::Connect`, which is every bank's.
|
||||||
|
- **The screens** (`implementations/Nostro.App-Screens.cpp`, and a bank's own forms in that bank's file) are functions from that state to a frame. A window under 600 dp wide shows one page at a time, with the app's places along its bottom; a wider one has them down its left side, and from 900 dp the accounts too. A screen that shows the bank's own state (the accounts, an account, the cards) reads it again four ways, all one action (`Refresher`): Refresh in the bar, F5, Ctrl+R, and the page pulled down at its top. The README's "The app" says what each screen is for.
|
||||||
|
- **The window** (`Nostro.Ui.Shell`) is one sd-event loop that carries the compositor's connection, nostrod's bus, the desktop portal's bus and the timers. `Window` turns Crafter.Graphics' events into the `Context`'s, bringing time up to each and building a stale frame again first, and does what the `Context` wants afterwards (`Settle`, which the loop calls from a post source after every source that ran). A frame is drawn only when the compositor asks for one after something changed: an idle window draws nothing. `Canvas` turns a `DrawList` into Crafter.Graphics' items, one dispatch per batch, from a pool of buffers per frame in flight. `Portal` reads the desktop's colour scheme and accent, and asks the desktop to open an address.
|
||||||
|
- **`nostro-app`** puts them together, and has what looking at the window without a hand on it takes: `--size`, `--scale` (a phone's density on a desktop's display), `--theme`, `--route`, `--screenshot`, `--poke` and `--gallery`. It makes itself undumpable once the portal has seen it. Closing the window while a change is under way takes the window down and keeps the process until the answer has come.
|
||||||
|
|
||||||
## Dev environment
|
## Dev environment
|
||||||
|
|
||||||
crafter-build is the only build tool. It compiles with its clang 23 and libc++, `-std=c++26` and `import std;`, and links `-lssl -lcrypto`, and `-lsystemd` for anything with D-Bus in it (libsystemd's `sd-bus.h` and `sd-event.h`; crafter-build's Flatpak SDK has them). Packaging uses flatpak-builder.
|
crafter-build is the only build tool. It compiles with its clang 23 and libc++, `-std=c++26` and `import std;`, and links `-lssl -lcrypto`, and `-lsystemd` for anything with D-Bus in it (libsystemd's `sd-bus.h` and `sd-event.h`; crafter-build's Flatpak SDK has them). nostrod's Flatpak is made by flatpak-builder, the app's by crafter-build itself (`--packaging=flatpak`; `project.cpp` was written against crafter-build 6.3.0), and the aarch64 ones by the two scripts in `packaging/flatpak/`.
|
||||||
|
|
||||||
- Every build needs the network: Crafter.Network (with Crafter.Thread behind it; nostro builds it `--no-quic`, so without msquic) and Crafter.DB are `GitProject`s on their default branches, and Crafter.LintRules a `#pragma crafter dependency` of `project.cpp`, so each build `git pull`s them from `forgejo.catcrafts.net`, and the notes at the end of this file follow their HEAD. A `.commit` (in the pragma, `commit "<sha>"`) would pin them.
|
- Every build needs the network: Crafter.Network (with Crafter.Thread behind it; nostro builds it `--no-quic`, so without msquic) and Crafter.DB are `GitProject`s on their default branches, and Crafter.LintRules a `#pragma crafter dependency` of `project.cpp`, so each build `git pull`s them from `forgejo.catcrafts.net`, and the notes at the end of this file follow their HEAD. A `.commit` (in the pragma, `commit "<sha>"`) would pin them, as Crafter.Debug's build helper is, the second pragma.
|
||||||
- Where the connectors live depends on who runs the library. nostrod's worker keeps each user's under `<state>/users/<uid>/`: `connectors.json`, the transaction tables, `checkouts.cdb`, `checkout-account` and `owner`, with `<state>` from `--state`, else `$XDG_DATA_HOME`, else `$HOME/.local/share`. Installed, that is `/var/lib/nostro/.var/app/net.catcrafts.Nostro/data/`, readable by the user `nostro` alone. The library used directly reads `connectors.json` from `$XDG_CONFIG_HOME/.config/nostro/` (sic, see "Gotchas") or `$HOME/.config/nostro/`, and keeps the transaction tables under `$XDG_CACHE_HOME/nostro/transactions/` or `$HOME/.cache/nostro/transactions/`. A real connectors file holds a real API key: point every experiment elsewhere.
|
- The app needs a Wayland compositor and a Vulkan device to run, and nothing else of nostro does. No test opens a window. `--product=app` takes `--graphics=<a Crafter.Graphics checkout's project.cpp>` for now: the app asks the input method for a field's purpose and hints, which Crafter.Graphics has on its branch `claude/nostro-app` and not yet on master. Once that is merged, name it as a `GitProject` at a pinned commit in `project.cpp` and drop the flag.
|
||||||
- No test uses the system bus: they run on `tests/Support/FakeBus.inc`. Running anything by hand that talks to `net.catcrafts.Nostro1` reaches the installed nostrod, if there is one, and its dialogs. A Flatpak sandbox with the system bus (`flatpak run`, `flatpak build`) sets `DBUS_SYSTEM_BUS_ADDRESS` itself, over an `--env` of yours: keep a sandboxed experiment off the bus with `--nosocket=system-bus`.
|
- The app's `--debug-api` build links Crafter.Debug, which talks QUIC: that one build has Crafter.Network with msquic (crafter-build builds it with CMake once, for minutes, and keeps it in its cache), and its binaries carry a runpath into that cache.
|
||||||
|
- Where the connectors live depends on who runs the library. nostrod's worker keeps each user's under `<state>/users/<uid>/`: `connectors.json`, the transaction tables, `checkouts.cdb`, `checkout-account` and `owner`, with `<state>` from `--state`, else `$XDG_DATA_HOME`, else `$HOME/.local/share`. Installed, that is `/var/lib/nostro/.var/app/net.catcrafts.Nostrod/data/`, readable by the user `nostro` alone. The library used directly reads `connectors.json` from `$XDG_CONFIG_HOME/.config/nostro/` (sic, see "Gotchas") or `$HOME/.config/nostro/`, and keeps the transaction tables under `$XDG_CACHE_HOME/nostro/transactions/` or `$HOME/.cache/nostro/transactions/`. A real connectors file holds a real API key: point every experiment elsewhere.
|
||||||
|
- No test uses the system bus: they run on `tests/Support/FakeBus.inc`. Running anything by hand that talks to `net.catcrafts.Nostro1` reaches the installed nostrod, if there is one, and its dialogs: the CLI, and the app, which reads the accounts as soon as it starts. A Flatpak sandbox with the system bus (`flatpak run`) sets `DBUS_SYSTEM_BUS_ADDRESS` itself, over an `--env` of yours: keep a sandboxed experiment off the bus with `--nosocket=system-bus`. To look at the app, run it on the made-up system, `nostro-fake-system`, which sets that address for what it starts ("Looking at the app").
|
||||||
- To read a `constexpr` value such as `DB::Layout<Transaction>::fingerprint`, `static_assert(x == 0)` it and read "expression evaluates to" in the error.
|
- To read a `constexpr` value such as `DB::Layout<Transaction>::fingerprint`, `static_assert(x == 0)` it and read "expression evaluates to" in the error.
|
||||||
|
|
||||||
## Build, test and style commands
|
## Build, test and style commands
|
||||||
|
|
@ -79,20 +140,29 @@ crafter-build --banks=bunq --product=daemon # nostrod: bin/nostrod-<variant>/n
|
||||||
crafter-build --product=checkout # the Nostro.Checkout library alone; no bank needed
|
crafter-build --product=checkout # the Nostro.Checkout library alone; no bank needed
|
||||||
crafter-build --banks=bunq --lib # the library alone (what a consumer builds), without D-Bus
|
crafter-build --banks=bunq --lib # the library alone (what a consumer builds), without D-Bus
|
||||||
crafter-build --banks=bunq --lib --dbus # the library with :Bus, :Client and :Daemon
|
crafter-build --banks=bunq --lib --dbus # the library with :Bus, :Client and :Daemon
|
||||||
|
crafter-build --banks=bunq --product=app --graphics=<Crafter.Graphics>/project.cpp # the app: bin/nostro-app-<variant>/nostro-app
|
||||||
|
crafter-build --banks=bunq --product=fake-system # nostro-fake-system: a fake bus and a fake bunq with nostrod on them
|
||||||
|
crafter-build --banks=bunq --product=app --graphics=… --debug-api # the app with Crafter.Debug, the fake system, and build/crafter-debug
|
||||||
|
crafter-build --banks=bunq --product=app --graphics=… --debug-api run fake [-- <the app's options>] # that app on the fake system
|
||||||
crafter-build --debug --banks=bunq # debug build
|
crafter-build --debug --banks=bunq # debug build
|
||||||
crafter-build -v --banks=bunq # with the compiler commands
|
crafter-build -v --banks=bunq # with the compiler commands
|
||||||
crafter-build clean # delete bin/ and build/
|
crafter-build clean # delete bin/ and build/
|
||||||
crafter-build test --banks=bunq # the tests in tests/, against a fake bunq; none talks to bunq itself
|
crafter-build test --banks=bunq # the tests in tests/, against a fake bunq; none talks to bunq itself
|
||||||
tests/coverage.sh [profile runtime] # the tests with coverage: a report per file and every line no test ran
|
tests/coverage.sh [profile runtime] # the tests with coverage: a report per file and every line no test ran
|
||||||
crafter-build lint --banks=bunq # the Crafter.LintRules lite rules project.cpp registers, report only
|
crafter-build lint --banks=bunq # the Crafter.LintRules lite rules project.cpp registers, report only
|
||||||
flatpak run --filesystem=<dir> org.flatpak.Builder --user --force-clean --repo=<dir>/repo --state-dir=<dir>/state <dir>/build packaging/flatpak/net.catcrafts.Nostro.yaml
|
crafter-build lint --banks=bunq --product=app --graphics=… [--debug-api] # the same over the toolkit, the app and its window
|
||||||
|
flatpak run --filesystem=<dir> org.flatpak.Builder --user --force-clean --repo=<dir>/repo --state-dir=<dir>/state <dir>/build packaging/flatpak/net.catcrafts.Nostrod.yaml
|
||||||
|
crafter-build --banks=bunq --product=app --graphics=… --packaging=flatpak --march=x86-64-v3 --mtune=generic bundle # the app's Flatpak as one file; `install` installs it for you instead
|
||||||
|
packaging/flatpak/make-aarch64-sysroot.sh && packaging/flatpak/build-aarch64.sh <repo> # both Flatpaks for aarch64, into a repository
|
||||||
```
|
```
|
||||||
|
|
||||||
`--banks=` is mandatory except for `--product=checkout`: without it `project.cpp` throws "must enable atleast one bank" and nothing is built; an unknown name throws "unknown connector", an unknown product "unknown product". flatpak-builder needs crafter-build's own Flatpak (`net.catcrafts.CrafterBuild`, stable) installed as its base app, the network during the build, and, run as a Flatpak itself, `--filesystem=` for a build directory outside your home, or the build commands cannot find it. Install the result for a test with `sudo packaging/system/install.sh --repo <dir>/repo`. There is no CI. The tests run every line, function and region of nostro's own sources (2026-11-01), and a change keeps them doing so; the README's rule for contributed connectors applies on top: not blind, also tried against the sandbox or the live API ("Testing instructions").
|
`--banks=` is mandatory except for `--product=checkout`: without it `project.cpp` throws "must enable atleast one bank" and nothing is built; an unknown name throws "unknown connector", an unknown product "unknown product". flatpak-builder needs crafter-build's own Flatpak (`net.catcrafts.CrafterBuild`, stable) installed as its base app, the network during the build, and, run as a Flatpak itself, `--filesystem=` for a build directory outside your home, or the build commands cannot find it. Install the result for a test with `sudo packaging/system/install.sh --repo <dir>/repo`. There is no CI. The tests run every line, function and region of the library, the CLI, nostrod, the toolkit and the app without its window (2026-11-19), and a change keeps them doing so; the README's rule for contributed connectors applies on top: not blind, also tried against the sandbox or the live API ("Testing instructions").
|
||||||
|
|
||||||
|
The app's packaging: `--packaging=flatpak` makes `bin/nostro-app-<variant>/files/` (the program with its fonts and shaders in `bin/`, the C++ runtime in `lib/`, the desktop entry, icon, metainfo and licences in `share/`), `bundle` a `.flatpak` beside it and `install` an installation for the user who runs it; both print the permissions, which `project.cpp` lists. That is x86_64, on the Platform crafter-build's Flatpak runs on. For aarch64, a phone, there is no crafter-build to build with, so both Flatpaks are cross builds: `make-aarch64-sysroot.sh` makes a sysroot of the Freedesktop Sdk for aarch64 with LLVM's libc++ (in `~/.cache/nostro-flatpak`, or `$NOSTRO_FLATPAK_CACHE`), and `build-aarch64.sh <repo>` builds the CLI, nostrod and the app against it and assembles `net.catcrafts.Nostrod` and `net.catcrafts.Nostro` into an OSTree repository, which `install.sh --repo <repo> --app` installs on the phone. The app's permissions are in two places because of it, `project.cpp` and that script: change them together.
|
||||||
|
|
||||||
## Testing instructions
|
## Testing instructions
|
||||||
|
|
||||||
`crafter-build test --banks=bunq` builds and runs `tests/<Name>/main.cpp` for each name in `project.cpp`'s list, each linked against the library, in parallel; a test exits 0 when every check passed and prints each failed one with its line. They are:
|
`crafter-build test --banks=bunq` builds and runs `tests/<Name>/main.cpp` for each name in `project.cpp`'s lists, each linked against what it tests (the library, the toolkit, or the app without its window), in parallel; a test exits 0 when every check passed and prints each failed one with its line. None needs Crafter.Graphics, a compositor or a graphics device. They are:
|
||||||
|
|
||||||
| Test | What it covers |
|
| Test | What it covers |
|
||||||
|---|---|
|
|---|---|
|
||||||
|
|
@ -105,36 +175,66 @@ flatpak run --filesystem=<dir> org.flatpak.Builder --user --force-clean --repo=<
|
||||||
| `ShouldMoveMoney` | payments, drafts, schedules and requests, and their formatters |
|
| `ShouldMoveMoney` | payments, drafts, schedules and requests, and their formatters |
|
||||||
| `ShouldRunCommands` | the CLI: `implementations/main.cpp` compiled in with its `main` renamed, every command run in-process against a real nostrod on the fake bus |
|
| `ShouldRunCommands` | the CLI: `implementations/main.cpp` compiled in with its `main` renamed, every command run in-process against a real nostrod on the fake bus |
|
||||||
| `ShouldServeEveryUser` | nostrod: users kept apart, a uid handed to a new user, every polkit answer and what each dialog says, calls that wait on each other or do not, the checkout and its retries, the checkout client, workers that die, idle exits, every error as the client gets it, and the published contract (the XML and the polkit policy) |
|
| `ShouldServeEveryUser` | nostrod: users kept apart, a uid handed to a new user, every polkit answer and what each dialog says, calls that wait on each other or do not, the checkout and its retries, the checkout client, workers that die, idle exits, every error as the client gets it, and the published contract (the XML and the polkit policy) |
|
||||||
|
| `ShouldAnswerAsynchronously` | the client's asynchronous calls from an sd-event loop: each method once against a real nostrod on the fake bus, every way an answer fails (refused, cancelled, bunq's refusal, a 5xx to a payment, no answer in time, no nostrod, an answer that cannot be read), notes in the answer, and dropping, cancelling, moving and assigning a `Pending` |
|
||||||
|
| `ShouldWrapText` | `Nostro.Ui:Text`: UTF-8, measuring, cutting with an ellipsis, wrapping and its cache |
|
||||||
|
| `ShouldEditText` | `:Edit`: typing, the cursor and the selection, each kind of field and what it refuses, the composing text, a secret wiped |
|
||||||
|
| `ShouldRecognizeGestures` | `:Gesture`: taps, long presses, drags and flings, a list's motion and its ends, the event clock |
|
||||||
|
| `ShouldBuildFrames` | `:Draw`, `:Theme` and `:Context`: batches, regions and what a press on each does, the focus and the keyboard, fields with the input method and the clipboard, scrolling, menus, notices, what is put off |
|
||||||
|
| `ShouldLayOutWidgets` | `:Layout` and `:Widgets`: each widget in every state it has: what it draws, where, in which colours, and what a press on it does |
|
||||||
|
| `ShouldValidateForms` | `Nostro.App`'s `:Banks`, `:Format`, `:Forms` and `:Errors`: every wording, every reading with what it refuses, each form's checks, what each error means for each operation, and what the app knows of each bank and says of one it does not know |
|
||||||
|
| `ShouldDriveTheApp` | the app against a real nostrod on the fake bus: every screen and every flow tapped by key and read as text, each polkit answer, each operation's action, the steps of adding a connection, nostrod missing, late, dying and coming back, an account that vanishes, the three window sizes, and that no screen outside the settings names a bank |
|
||||||
|
|
||||||
How they are built:
|
How they are built:
|
||||||
|
|
||||||
- `tests/Support/Check.inc` holds the checks (`Check`, `Equal`, `Throws`) and a temporary `Directory`; `tests/Support/FakeBunq.inc` is a bunq in the test's own process, HTTPS on 127.0.0.1 with Crafter.Network's self-signed certificate. It signs what it answers, checks the client's signatures, keeps users, accounts, payments, requests, schedules, drafts and cards, and fails on request (`Fake::Fault`). `BunqConnector::RedirectTo` points nostro at it; each test has a port of its own (47301 to 47305), and port 443 on 127.0.0.1 stands for a host that refuses the connection.
|
- `tests/Support/Check.inc` holds the checks (`Check`, `Equal`, `Throws`) and a temporary `Directory`; `tests/Support/FakeBunq.inc` is a bunq in the test's own process, HTTPS on 127.0.0.1 with Crafter.Network's self-signed certificate. It signs what it answers, checks the client's signatures, keeps users, accounts, payments, requests, schedules, drafts and cards, and fails on request (`Fake::Fault`). `BunqConnector::RedirectTo` points nostro at it; each test has a port of its own (47301 to 47307; `nostro-fake-system` takes 47390 unless told another), and port 443 on 127.0.0.1 stands for a host that refuses the connection.
|
||||||
|
- `tests/Support/Ui.inc` is what the toolkit's and the app's tests build frames with: a font of known sizes (`Test::FixedMeasure`: every code point half its size wide), so every position is exact, and the reading of a frame (`Shows`, `Hides`, `Said`, `TapAt`). A test builds a frame (`Context::Begin`, the screen, `End`), reads the draw list's text and the regions, and acts by key (`Context::Tap`) or by point.
|
||||||
|
- `ShouldDriveTheApp` runs the app as a window would, without one: a `Context` of a phone's size, a `Client` on an sd-event loop, nostrod on the fake bus with the fake bunq behind it. A tap is by a region's key, and what a screen says is the draw list's text. Every frame it builds on a phone's size is also held to one rule of the design: whatever can be pressed is at least 48 dp wide and tall.
|
||||||
- `tests/Support/FakeBus.inc` is a system bus in the test's own process, an sd-bus server on a unix socket: it routes calls by name with the caller's unique name, and plays the bus driver (`GetConnectionCredentials` with the uid the test chose for a connection of its own process, the real one for nostrod's), logind (`GetUser` and the user's `Name`) and polkit (each check recorded; allow, a password, deny, a closed dialog, absent, silent or slow, per action). The two nostrod tests start their own executable again as nostrod (`Fake::StartNostrod`, with `NOSTRO_TEST_ROLE` set; its `main` then runs `implementations/nostrod.cpp`'s, compiled in with `main` renamed), which finds the fake bunq through the environment (`Fake::Bunq::ExportRedirect`, `RedirectFromEnvironment`). Everything a child reads from the environment is set before any thread starts. A worker that cannot be spawned is made with `prlimit` on nostrod (`Fake::Limit`), and workers are stopped with SIGTERM, which they handle, so their coverage counts are written.
|
- `tests/Support/FakeBus.inc` is a system bus in the test's own process, an sd-bus server on a unix socket: it routes calls by name with the caller's unique name, and plays the bus driver (`GetConnectionCredentials` with the uid the test chose for a connection of its own process, the real one for nostrod's), logind (`GetUser` and the user's `Name`) and polkit (each check recorded; allow, a password, deny, a closed dialog, absent, silent or slow, per action). The two nostrod tests start their own executable again as nostrod (`Fake::StartNostrod`, with `NOSTRO_TEST_ROLE` set; its `main` then runs `implementations/nostrod.cpp`'s, compiled in with `main` renamed), which finds the fake bunq through the environment (`Fake::Bunq::ExportRedirect`, `RedirectFromEnvironment`). Everything a child reads from the environment is set before any thread starts. A worker that cannot be spawned is made with `prlimit` on nostrod (`Fake::Limit`), and workers are stopped with SIGTERM, which they handle, so their coverage counts are written.
|
||||||
- What a disk or a kernel will not do on demand (`flock` failing or interrupted, `fsync` failing, a chosen OAuth state from `RAND_bytes`) the test defines itself as an `extern "C"` function: the linker takes it over libc's or OpenSSL's, and it calls the real one through `dlsym(RTLD_NEXT, …)` when nothing is scripted. A file size limit (`RLIMIT_FSIZE`) makes a write fail part way.
|
- What a disk or a kernel will not do on demand (`flock` failing or interrupted, `fsync` failing, a chosen OAuth state from `RAND_bytes`) the test defines itself as an `extern "C"` function: the linker takes it over libc's or OpenSSL's, and it calls the real one through `dlsym(RTLD_NEXT, …)` when nothing is scripted. A file size limit (`RLIMIT_FSIZE`) makes a write fail part way.
|
||||||
- Each test sets `configPath` and `cachePath` to a temporary directory first, and `TZ` where it formats local time.
|
- Each test sets `configPath` and `cachePath` to a temporary directory first, and `TZ` where it formats local time.
|
||||||
|
|
||||||
Coverage is clang's source-based coverage: `tests/coverage.sh` builds with `--coverage`, runs the tests with `LLVM_PROFILE_FILE` set (with `%p`, so nostrod and every worker write their own), merges the profiles and reports with `llvm-cov`, leaving `build/coverage/sources.txt` annotated. A toolchain without compiler-rt's profile library, which crafter-build's Flatpak lacks, takes one as the script's argument (`--profile-runtime=` to `project.cpp`). On 2026-11-01 lines, functions and regions were all at 100% and branches at 95%: what is left is mostly defensive checks no input can flip and per-instantiation counts in `main.cpp`'s templates.
|
Coverage is clang's source-based coverage: `tests/coverage.sh` builds with `--coverage`, runs the tests with `LLVM_PROFILE_FILE` set (with `%p`, so nostrod and every worker write their own), merges the profiles and reports with `llvm-cov`, leaving `build/coverage/sources.txt` annotated. A toolchain without compiler-rt's profile library, which crafter-build's Flatpak lacks, takes one as the script's argument (`--profile-runtime=` to `project.cpp`). On 2026-11-19 lines, functions and regions were all at 100% and branches at 96%: what is left is mostly defensive checks no input can flip and per-instantiation counts in templates.
|
||||||
|
|
||||||
|
The figure covers what a test links: the library, the CLI, nostrod, `Nostro.Ui` and `Nostro.App`, and the script fails when a source of those two is missing from the report. It leaves out what needs a compositor and a graphics device, by design rule 11: `Nostro.Ui.Shell`, `implementations/nostro-app.cpp` and `Nostro.DebugCommands`, and with them `tests/FakeSystem/main.cpp`. Those are looked at instead, see "Looking at the app". A few things clang's coverage does that cost time once: an `if` without an `else` has no region for the missing arm, only a branch; each arm of a `?:` is a region; a template or a generic lambda is counted per instantiation; and an inline function in a module interface that assigns an aggregate from a temporary leaves an uncovered implicit `operator=` record, so such bodies go into implementation units.
|
||||||
|
|
||||||
The bunq sandbox is still the check for what a fake cannot show. Since nostrod (2026-11-01) the CLI needs an installed nostrod: build the Flatpak, install it with `sudo packaging/system/install.sh --repo <dir>/repo`, and use the CLI as yourself; real polkit dialogs then ask for your password. A second local user shows the separation. The library alone still runs from an isolated config and cache, never from `~/.config/nostro`. The recipe, as it worked on 2026-10-31 with the CLI of then, which held the connectors itself:
|
The bunq sandbox is still the check for what a fake cannot show. Since nostrod (2026-11-01) the CLI needs an installed nostrod: build the Flatpak, install it with `sudo packaging/system/install.sh --repo <dir>/repo`, and use the CLI as yourself; real polkit dialogs then ask for your password. A second local user shows the separation. The library alone still runs from an isolated config and cache, never from `~/.config/nostro`. The recipe, as it worked on 2026-10-31 with the CLI of then, which held the connectors itself:
|
||||||
|
|
||||||
1. Build (in place or in a scratch copy made with `rsync -a --exclude build/ --exclude bin/ --exclude .git/`) and run the binary with `XDG_CONFIG_HOME` and `XDG_CACHE_HOME` pointing into a scratch directory. No `connectors.json` needs seeding.
|
1. Build (in place or in a scratch copy made with `rsync -a --exclude build/ --exclude bin/ --exclude .git/`) and run the binary with `XDG_CONFIG_HOME` and `XDG_CACHE_HOME` pointing into a scratch directory. No `connectors.json` needs seeding.
|
||||||
2. Throwaway users: `POST https://public-api.sandbox.bunq.com/v1/sandbox-user-person` (or `-company`) with no authentication returns `Response[0].ApiKey.api_key`; `nostro connectors add bunq`, given the key on stdin, recognises the sandbox by its prefix. The response also holds the user's e-mail and phone aliases, for paying by those. Make two, so there is someone to pay; sandbox accounts are all called "Bank Account", so name them by IBAN.
|
2. Throwaway users: `POST https://public-api.sandbox.bunq.com/v1/sandbox-user-person` (or `-company`) with no authentication returns `Response[0].ApiKey.api_key`; `nostro connectors add bunq`, given the key on stdin, recognises the sandbox by its prefix. The response also holds the user's e-mail and phone aliases, for paying by those. Make two, so there is someone to pay; sandbox accounts are all called "Bank Account", so name them by IBAN.
|
||||||
3. The CLI reaches every bunq call (`nostro help` lists them). Session renewal is tried by ending the session behind nostro's back (`DELETE /v1/session/0` with the stored `sessionToken`), signature checking by putting another public key in `serverPublicKey`.
|
3. The CLI reaches every bunq call (`nostro help` lists them). Session renewal is tried by ending the session behind nostro's back (`DELETE /v1/session/0` with the stored `sessionToken`), signature checking by putting another public key in `serverPublicKey`.
|
||||||
4. A new sandbox account holds €0 and no payments. Fund it with `nostro request <iban> sugardaddy@bunq.com "Sugar Daddy" 50000`: it is paid within seconds. A hundred rows at once: `POST …/payment-batch` with `{"payments": […]}` (more than 200 exercises the paging). `curl` can call as the same user with the `sessionToken` from the scratch file, and sign with `openssl dgst -sha256 -sign` over the body using its `privateKey` PEM, base64, in `X-Bunq-Client-Signature`. A sandbox virtual card (`POST /v1/user/{id}/card-debit` with `order_status: VIRTUAL_DELIVERY`) cannot be activated through the API, so `cards unfreeze` can only show bunq keeping it `DEACTIVATED`. OAuth stops at the token exchange: approving needs a person and the bunq app.
|
4. A new sandbox account holds €0 and no payments. Fund it with `nostro request <iban> sugardaddy@bunq.com "Sugar Daddy" 50000`: it is paid within seconds. A hundred rows at once: `POST …/payment-batch` with `{"payments": […]}` (more than 200 exercises the paging). `curl` can call as the same user with the `sessionToken` from the scratch file, and sign with `openssl dgst -sha256 -sign` over the body using its `privateKey` PEM, base64, in `X-Bunq-Client-Signature`. A sandbox card (`POST /v1/user/{id}/card-debit` with `type: MASTERCARD`, `product_type: MASTERCARD_DEBIT`, a `name_on_card` out of `GET /v1/user/{id}/card-name` and a `pin_code_assignment`) stays a virtual one, `DEACTIVATED` at `VIRTUAL_DELIVERY`, whatever it is set to: `nostro cards` lists it as `VIRTUAL`, `cards freeze` and `unfreeze` are refused for it, and `cards lost` and `stolen` can be tried on it. OAuth stops at the token exchange: approving needs a person and the bunq app.
|
||||||
5. bunq allows 3 GETs, 5 POSTs and 2 PUTs per three seconds per endpoint and one session per 30 seconds; nostro waits a 429 out, so a burst of runs is slow rather than failing. Concurrent nostro processes queue on `connectors.lock`, so two never hold the same account's table.
|
5. bunq allows 3 GETs, 5 POSTs and 2 PUTs per three seconds per endpoint and one session per 30 seconds; nostro waits a 429 out, so a burst of runs is slow rather than failing. Concurrent nostro processes queue on `connectors.lock`, so two never hold the same account's table.
|
||||||
|
|
||||||
|
The app against the sandbox takes both Flatpaks installed and a hand on the window: every row of the README's "The app" from the window, with real polkit dialogs. That had not been done on 2026-11-19; nor had anything on a phone.
|
||||||
|
|
||||||
A bug fix comes with a test that fails without it, and states in its commit how it was reproduced; a new bank comes with tests against a fake of it and with the same check against its sandbox or live API.
|
A bug fix comes with a test that fails without it, and states in its commit how it was reproduced; a new bank comes with tests against a fake of it and with the same check against its sandbox or live API.
|
||||||
|
|
||||||
|
### Looking at the app
|
||||||
|
|
||||||
|
What a test cannot show (that the window draws what the frame says, in the right place, on a real display; the pointer, a finger, the keyboard, the input method) is looked at, on a made-up system so that nobody's bank is in it:
|
||||||
|
|
||||||
|
- `nostro-fake-system` (`--product=fake-system`, `tests/FakeSystem/main.cpp`) is the tests' fake bus and fake bunq with a real nostrod on them: `nostro-fake-system [--dir <directory>] [--port <port>] [--polkit allow|password|deny|dismiss|absent|silent|slow] [--empty] [--run <program> <arguments…>]`. It fills the bank with a made-up user (three accounts, three months of payments, three cards of which one is frozen and one virtual, a request sent and one received, a schedule, a draft, and a second connection through OAuth), and runs the program with `DBUS_SYSTEM_BUS_ADDRESS` pointing at the fake bus. `--empty` starts from the welcome and prints the made-up bank's API key; `--polkit` is what every request for a password is answered with; `--bank-delay <milliseconds>` is how long the made-up bank takes over each answer.
|
||||||
|
- Without a hand on it: `nostro-app --size 420x760 --theme light --route account:<IBAN> --poke "wait:2500;tap:110,200;shot:<file.png>"` plays input into the window library's own events, so the window's listeners run as for a real pointer, and writes screenshots. Steps are separated by `;` and positions are in dp: `tap:x,y`, `hold:x,y,ms`, `drag:x1,y1,x2,y2,ms`, `move:x,y`, `press:x,y` and `release` (a finger kept down between them), `right:x,y`, `wheel:x,y,detents`, `key:Name`, `text:…`, `preedit:…`, `delete:before,after`, `resize:w,h`, `wait:ms`, `shot:file`. `--scale 3 --size 360x760` draws a phone's screen on a desktop's display. `--gallery widgets|list|text` shows the toolkit's widgets in the app's place and asks nostrod nothing.
|
||||||
|
- With an agent's hand on it: the `--debug-api` build and `./build/crafter-debug` (the Crafter.Debug notes at the end of this file). `crafter-build … --debug-api run fake [the fake system's options] [-- the app's options]` starts the app on the fake system, in the background since it does not exit. Then:
|
||||||
|
- `get app.screen`, `get ui.texts` (every line the screen shows), `get ui.regions` (what can be pressed, by key, in dp), `get 'window.*'`;
|
||||||
|
- `call Ui_Tap key=account.pay`, `Ui_Type text=…` into the field that has the focus, `Ui_Key key=Tab`, `Ui_LongPress`, `Ui_Focus`, `Ui_TapAt`, `Ui_Drag`, `Ui_Wheel`, `App_Navigate route=cards`, `Ui_Theme scheme=dark`, `Window_Resize width= height=`;
|
||||||
|
- `wait 'app.busy == false'` after anything that asks nostrod, `wait 'app.changing == false'` after a change; the events are `Screen`, `AnswerArrived`, `Changing` and `FrameRendered`;
|
||||||
|
- `screenshot`, and `log --level warn` for the checks: a frame that overflowed the window's buffers, something pressable under 48 dp on a phone's size.
|
||||||
|
- The README's screenshots are taken that way too, on the made-up system so that nobody's bank is in them: `docs/screenshots/take.sh <nostro-fake-system> <nostro-app>` plays one `--poke` script per picture and writes the five files beside itself. It names what it taps by its place, so it is looked over, picture by picture, after a change to a screen it shows. The made-up bank dates its payments back from now: every taking has other days and times in it. Four of the five are in the dark look and one in the light one, and everything the made-up bank holds is in English, people's names too, as the app is: both as asked for on 2026-11-19, so new made-up data is written in English.
|
||||||
|
- A region's key is its name in the tests too: `nav.accounts`, `account.<IBAN>`, `account.pay`, `tabs.1`, `pay.to`, `pay.submit`, `request.review`, `review.confirm`, `done.close`, `card.<id>`, `settings.connections`, `connections.add`, `bank.bunq`, `way.key`, and `copy.<label>` for a line of a sheet (`copy.IBAN`), which a press copies. `get ui.regions` lists a screen's.
|
||||||
|
|
||||||
## Code style
|
## Code style
|
||||||
|
|
||||||
- `crafter-build lint --banks=bunq` reports nothing. A finding at a C boundary (`main`'s `argv`, a `char*` an OpenSSL or POSIX call hands out) is suppressed with `// lint-disable-next-line <rule>` and a comment saying why; anything else is fixed. The rules that need an AST cannot parse a file that `#include`s a standard header before `import std;` (the nine that include `json.hpp`: four in the library, five tests), so lint exits 1 for those alone until Crafter.Build issue #46 is fixed: check them by hand, and prefer C headers (`<errno.h>`, not `<cerrno>`) elsewhere. Tests are linted like the rest.
|
- `crafter-build lint --banks=bunq` reports nothing, and neither does it with `--product=app --graphics=…`, with `--debug-api` added, and with `--product=fake-system`: the first reaches the library, the CLI and the tests, and only the others the toolkit's, the app's and the window's sources. A finding at a C boundary (`main`'s `argv`, a `char*` an OpenSSL or POSIX call hands out) is suppressed with `// lint-disable-next-line <rule>` and a comment saying why; anything else is fixed. The rules that need an AST cannot parse a file that `#include`s a standard header before `import std;` (the twelve that include `json.hpp`: four in the library, seven tests and the fake system), because the lint's libclang does not find libc++'s headers, so lint exits 1 for those alone until Crafter.Build issue #46 is fixed. Until then, name the headers through the environment and every rule runs on every file: `CPLUS_INCLUDE_PATH=<libc++'s include directory>`, which is `/app/include/c++/v1` in crafter-build's Flatpak (`flatpak run --env=CPLUS_INCLUDE_PATH=/app/include/c++/v1 net.catcrafts.CrafterBuild lint …`). Prefer C headers (`<errno.h>`, not `<cerrno>`) elsewhere. Tests are linted like the rest. `const-local` sees `bool` and the built-in types, not `std::size_t` or `std::int32_t`: those are made `const` by hand. Lint a product after building it: the AST rules read that product's module files, and against ones from before a change they report nonsense, such as a vector of a type they do not find yet as a local that is never modified.
|
||||||
- The first two lines of every source are `// SPDX-License-Identifier: LGPL-3.0-only` and `// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®`, then a blank line. `project.cpp` carries them too.
|
- The first two lines of every source are `// SPDX-License-Identifier: LGPL-3.0-only`, or `GPL-3.0-only` in a source of the app (design rule 13 says which is which), and `// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®`, then a blank line. `project.cpp` carries them too.
|
||||||
- Four-space indentation, LF, K&R braces with `} else {`, one declaration per statement. `if(`, `for(`, `while(`, `switch(` without a space in most files (`:Utils` has the space; match the file). Lines run long rather than wrap.
|
- Four-space indentation, LF, K&R braces with `} else {`, one declaration per statement. `if(`, `for(`, `while(`, `switch(` without a space in most files (`:Utils` has the space; match the file). Lines run long rather than wrap.
|
||||||
- `import std;` everywhere; `#include`s only in a global module fragment (`module;` first), and only for OpenSSL, the vendored `json.hpp`, sd-bus and sd-event, and the POSIX calls of `:File`, `:Connector` and nostrod. `namespace fs = std::filesystem;` where paths appear.
|
- `import std;` everywhere; `#include`s only in a global module fragment (`module;` first), and only for OpenSSL, the vendored `json.hpp`, sd-bus and sd-event, and the POSIX calls of `:File`, `:Connector` and nostrod. `namespace fs = std::filesystem;` where paths appear.
|
||||||
- Interfaces are `export module Nostro:<P>;` with `export namespace Nostro { … }` when the partition is free functions (`:Currency`, `:Utils`, `:File`, `:Crypto`) and `namespace Nostro { export struct … }` when it is types. A `std::formatter` specialisation sits after the namespace, unexported, which importers still find. Implementation units are `module Nostro:<P>_impl;` followed by `import :<P>;`. `Nostro.Checkout` is a module of its own (`export module Nostro.Checkout;`, implemented in `module Nostro.Checkout;`) because a shop app links it without the rest.
|
- Interfaces are `export module Nostro:<P>;` with `export namespace Nostro { … }` when the partition is free functions (`:Currency`, `:Utils`, `:File`, `:Crypto`) and `namespace Nostro { export struct … }` when it is types. A `std::formatter` specialisation sits after the namespace, unexported, which importers still find. Implementation units are `module Nostro:<P>_impl;` followed by `import :<P>;`. `Nostro.Checkout` is a module of its own (`export module Nostro.Checkout;`, implemented in `module Nostro.Checkout;`) because a shop app links it without the rest. The app's modules follow the same shape (`export module Nostro.Ui:<P>;`, `module Nostro.Ui:<P>_impl;`), with definitions in implementation units.
|
||||||
|
- In the toolkit and the app: geometry is in physical pixels, and a size of the design is a dp constant turned into pixels where it is used (`frame.Dp(Size::gutter)`). A widget is a function that draws into a frame and names its regions; it keeps nothing. A region's key names it across frames, for the focus, a press, a test and a debugger: a row of a list has what it is about in its key, never its place. A press acts on a frame that is still true: whoever changes what the screens are built from calls `Context::Invalidate`.
|
||||||
|
- In the window (`Nostro.Ui.Shell`): everything sd-event or libwayland calls back runs under `Loop::Guard`, for the same reason. What cannot be done inside a listener waits for the loop (`Defer`): reading the clipboard, taking the window down.
|
||||||
- An sd-bus callback returns 0 or more and never throws: a negative result closes the connection it came on, and an exception would unwind through C. Every worker handler catches everything (`Handle`) and answers with an error instead.
|
- An sd-bus callback returns 0 or more and never throws: a negative result closes the connection it came on, and an exception would unwind through C. Every worker handler catches everything (`Handle`) and answers with an error instead.
|
||||||
- `PascalCase` for types, functions and member functions; `camelCase` for variables, members and constants (`sessionToken`, `connectorId`, `configPath`); `enum class` only; fixed-width integers (`std::int64_t` for money, `std::uint64_t` for bunq ids, `std::uint16_t` under `Currency`). `tuple_for`, `to_json` and `from_json` are the snake_case exceptions, the last two because nlohmann/json looks them up by that name.
|
- `PascalCase` for types, functions and member functions; `camelCase` for variables, members and constants (`sessionToken`, `connectorId`, `configPath`); `enum class` only; fixed-width integers (`std::int64_t` for money, `std::uint64_t` for bunq ids, `std::uint16_t` under `Currency`). `tuple_for`, `to_json` and `from_json` are the snake_case exceptions, the last two because nlohmann/json looks them up by that name.
|
||||||
- Parameters are `std::string_view`, or `std::string&&` where the callee stores them (the account constructors, `Create`). `std::format` and `std::println` for all text; iostreams only for `connectors.json`.
|
- Parameters are `std::string_view`, or `std::string&&` where the callee stores them (the account constructors, `Create`). `std::format` and `std::println` for all text; iostreams only for `connectors.json`, and in the debug build for a screenshot's bytes.
|
||||||
- Errors are exceptions with a `std::format`ted message that names the thing: `std::runtime_error` (`"malformed amount '{}'"`), `BunqError` with the HTTP status for a bunq error response (`"bunq {} {}: {} ({})"`, method, path, description, status), `std::invalid_argument` for input refused before anything is sent. Every OpenSSL return goes through `ThrowOnOpenssl`, which prints OpenSSL's error stack to stderr first. No error codes, no `std::expected`.
|
- Errors are exceptions with a `std::format`ted message that names the thing: `std::runtime_error` (`"malformed amount '{}'"`), `BunqError` with the HTTP status for a bunq error response (`"bunq {} {}: {} ({})"`, method, path, description, status), `std::invalid_argument` for input refused before anything is sent. Every OpenSSL return goes through `ThrowOnOpenssl`, which prints OpenSSL's error stack to stderr first. No error codes, no `std::expected`.
|
||||||
- Comments say why, and are kept: the table cache in `Nostro-Account.cpp`, the schema warning on `Transaction`, the `opensslEnabled` line in `project.cpp`. New non-obvious code gets the same.
|
- Comments say why, and are kept: the table cache in `Nostro-Account.cpp`, the schema warning on `Transaction`, the `opensslEnabled` line in `project.cpp`. New non-obvious code gets the same.
|
||||||
|
|
||||||
|
|
@ -144,12 +244,17 @@ A bug fix comes with a test that fails without it, and states in its commit how
|
||||||
2. **A connector is a struct with a known shape.** `static constexpr std::string connectorId`, `static std::deque<Self> connectors` (a deque, so an account's `connector` pointer survives the next `Create`), `using Account = <Bank>Account`, `std::vector<Account> accounts`, `name`, `TestConnector()`, `RefreshAccounts()`, `GetNewTransactions()` and `GetNewTransactions(account)`, `Logout()`, `StorageKey()`, static `Create(…)` and `Remove(connector)`, `to_json`/`from_json` for `connectors.json`, and a `std::formatter` that prints its name; its account derives from `Account` and has `StorageKey()` and `Send(to, name, amount, currency, description)`. `main.cpp` and `:Connector` compile against that shape; anything a bank offers beyond it (bunq's requests, schedules, drafts and cards) the CLI reaches through `if constexpr (requires { … })`. (Revised 2026-10-31 for the MVP connector: the deque, `Logout`, `Remove` and the storage keys.)
|
2. **A connector is a struct with a known shape.** `static constexpr std::string connectorId`, `static std::deque<Self> connectors` (a deque, so an account's `connector` pointer survives the next `Create`), `using Account = <Bank>Account`, `std::vector<Account> accounts`, `name`, `TestConnector()`, `RefreshAccounts()`, `GetNewTransactions()` and `GetNewTransactions(account)`, `Logout()`, `StorageKey()`, static `Create(…)` and `Remove(connector)`, `to_json`/`from_json` for `connectors.json`, and a `std::formatter` that prints its name; its account derives from `Account` and has `StorageKey()` and `Send(to, name, amount, currency, description)`. `main.cpp` and `:Connector` compile against that shape; anything a bank offers beyond it (bunq's requests, schedules, drafts and cards) the CLI reaches through `if constexpr (requires { … })`. (Revised 2026-10-31 for the MVP connector: the deque, `Logout`, `Remove` and the storage keys.)
|
||||||
3. **Money is an integer.** Amounts and balances are `std::int64_t` in the currency's minor unit, outgoing negative, with the `Currency` beside them; decimal strings exist only at the API boundary and go through `ParseAmount` and `FormatAmount`. No floating point anywhere near an amount.
|
3. **Money is an integer.** Amounts and balances are `std::int64_t` in the currency's minor unit, outgoing negative, with the `Currency` beside them; decimal strings exist only at the API boundary and go through `ParseAmount` and `FormatAmount`. No floating point anywhere near an amount.
|
||||||
4. **Secrets live in one private file, out of the user's reach.** `connectors.json` holds the API key or OAuth token, both tokens and the RSA private key, `0600` under a `0700` directory made by `CreatePrivateFile`; nothing prints them, nothing else persists them. Installed, the file is nostrod's, under the state directory of the system user `nostro`, so no program the user runs can read it; the CLI reads a key or a client secret at a prompt (`ReadSecret`), never from `argv`, which every local user can read and polkit logs, and passes it to nostrod once, in a message marked sensitive. (Revised 2026-11-01 for nostrod.)
|
4. **Secrets live in one private file, out of the user's reach.** `connectors.json` holds the API key or OAuth token, both tokens and the RSA private key, `0600` under a `0700` directory made by `CreatePrivateFile`; nothing prints them, nothing else persists them. Installed, the file is nostrod's, under the state directory of the system user `nostro`, so no program the user runs can read it; the CLI reads a key or a client secret at a prompt (`ReadSecret`), never from `argv`, which every local user can read and polkit logs, and passes it to nostrod once, in a message marked sensitive. (Revised 2026-11-01 for nostrod.)
|
||||||
5. **Transactions are a local, append-only cache in Crafter.DB.** One table per account, under a storage key the connector chooses (bunq's: environment, user id, account id), ordered by `timePoint`; a sync appends what is newer than the last stored row, and at that last timestamp what has an `id` not stored yet; queries are answered from the table, never from the bank. `Transaction` is the on-disk schema: a change to its members bumps `version` and keeps the old struct as `Previous` (see the Crafter.DB notes below), and the `static_assert`s on `rowSize` (120) and `fingerprint` in `Nostro-Account.cpp`, and those pinning the previous version, are updated in the same commit.
|
5. **Transactions are a local, append-only cache in Crafter.DB.** One table per account, under a storage key the connector chooses (bunq's: environment, user id, account id), ordered by `timePoint`; a sync appends what is newer than the last stored row, and at that last timestamp what has an `id` not stored yet; queries are answered from the table, never from the bank. nostrod's `Transactions` does both in turn: the sync, which is a call to the bank (hundreds of milliseconds, and three of them in three seconds before bunq answers 429 and the worker waits three seconds), and then the query, which is microseconds. A query that says `stored` skips the sync: that is how the app searches and pages through a list it has just read. `Transaction` is the on-disk schema: a change to its members bumps `version` and keeps the old struct as `Previous` (see the Crafter.DB notes below), and the `static_assert`s on `rowSize` (120) and `fingerprint` in `Nostro-Account.cpp`, and those pinning the previous version, are updated in the same commit.
|
||||||
6. **Synchronous HTTPS, one client per bank host.** `ClientHTTP1::Send` on the calling thread, a persistent connection for reads and a fresh one for every write, no thread pool, default TLS verification. A bank's own request function owns the protocol: signing, verifying, waiting out rate limits and renewing an expired session once. Every other error is an exception; whether to retry a write is the caller's decision, and an unknown outcome is reported as such. (Revised 2026-10-31: the retries moved from the transaction sync into the request function.)
|
6. **Synchronous HTTPS, one client per bank host.** `ClientHTTP1::Send` on the calling thread, a persistent connection for reads and a fresh one for every write, no thread pool, default TLS verification. A bank's own request function owns the protocol: signing, verifying, waiting out rate limits and renewing an expired session once. Every other error is an exception; whether to retry a write is the caller's decision, and an unknown outcome is reported as such. (Revised 2026-10-31: the retries moved from the transaction sync into the request function.)
|
||||||
7. **Signing is opt-in per bank.** `:Crypto` and `-lssl -lcrypto` are pulled in by `opensslEnabled`, the OR of the banks that sign; a bank that does not sign must not make the build depend on OpenSSL.
|
7. **Signing is opt-in per bank.** `:Crypto` and `-lssl -lcrypto` are pulled in by `opensslEnabled`, the OR of the banks that sign; a bank that does not sign must not make the build depend on OpenSSL.
|
||||||
8. **The library is the product, the CLI is a thin client.** `--lib` returns the library configuration; the CLI adds `main.cpp` alone, which parses `argv`, calls nostrod through `Client` and prints through the formatters, and nostrod adds `nostrod.cpp` alone. Logic goes into a partition (the daemon's into `:Daemon`), not into `main.cpp`. (Revised 2026-11-01: the CLI talks to nostrod, not to the bank.)
|
8. **The library is the product; the CLI and the app are thin clients.** `--lib` returns the library configuration; the CLI adds `main.cpp` alone, which parses `argv`, calls nostrod through `Client` and prints through the formatters, and nostrod adds `nostrod.cpp` alone. Logic goes into a partition (the daemon's into `:Daemon`), not into `main.cpp`. What the CLI and the app both need is the library's, not written twice: reading the address an OAuth redirect lands on, the end of a day a person typed, a card's status as bunq kept it (the check; what the app then says it words itself, in no bank's name). The app decides nothing nostrod should: what an account, a payee or an amount may be is nostrod's to refuse, and the app's own checks only spare the user a round trip. (Revised 2026-11-01: the CLI talks to nostrod, not to the bank. Revised 2026-11-19 for the app.)
|
||||||
9. **nostrod answers each caller for their own money, and asks polkit first.** The front maps a caller's uid, asked of the bus, to that uid's own worker process; nothing of one user's is ever in another's process. Every method has one polkit action, decided by what the call does (`View`, `Change`, `Pay`, `UnfreezeCard`, `BlockCard`, `Connectors`, `Checkout`), and the dialog's summary and details are built from the worker's own data after the call is read and checked, never from text the caller formatted: what the dialog shows is what gets paid. Every action is owned by `unix-user:nostro` in the policy, or polkit refuses nostrod's checks. Every method is `SD_BUS_VTABLE_UNPRIVILEGED`, since polkit decides, not sd-bus. It fails closed. No action keeps an authorization: polkit keeps one per process, so the CLI would ask every time anyway.
|
9. **nostrod answers each caller for their own money, and asks polkit first.** The front maps a caller's uid, asked of the bus, to that uid's own worker process; nothing of one user's is ever in another's process. Every method has one polkit action, decided by what the call does (`View`, `Change`, `Pay`, `UnfreezeCard`, `BlockCard`, `Connectors`, `Checkout`), and the dialog's summary and details are built from the worker's own data after the call is read and checked, never from text the caller formatted: what the dialog shows is what gets paid. Every action is owned by `unix-user:nostro` in the policy, or polkit refuses nostrod's checks. Every method is `SD_BUS_VTABLE_UNPRIVILEGED`, since polkit decides, not sd-bus. It fails closed. No action keeps an authorization: polkit keeps one per process, so the CLI would ask every time anyway, and the app, which lives for hours, would not: an administrator's rule that keeps one (`auth_self_keep`) lets a running app pay for minutes without a password.
|
||||||
10. **The wire is a published contract.** `packaging/dbus/*.xml` is what nostrod serves (`ShouldServeEveryUser` compares them with its introspection), and apps in other languages generate their proxies from it. A method may be added; changing a method's signature or meaning means a new interface (`…Nostro2`). The checkout's `options` and `results` are dictionaries so that it can grow without one: unknown options are ignored, unknown results skipped.
|
10. **The wire is a published contract.** `packaging/dbus/*.xml` is what nostrod serves (`ShouldServeEveryUser` compares them with its introspection), and apps in other languages generate their proxies from it. A method may be added; changing a method's signature or meaning means a new interface (`…Nostro2`). The checkout's `options` and `results` are dictionaries so that it can grow without one: unknown options are ignored, unknown results skipped. So is the query of `Transactions`: `stored` was added to it on 2026-11-19, and a nostrod from before ignores it and asks the bank, which is slower and no less right. A client must not lean on a new key for anything but speed. One meaning was narrowed all the same, on 2026-11-19, while no release had been published: `AddBunq`'s `environment` used to choose the environment over what the key says, and now only has a key of the other one refused. After a release that would have been `…Nostro2`'s to do.
|
||||||
|
|
||||||
|
11. **The app's logic is pure, and its window is thin.** `Nostro.Ui` and `Nostro.App` import no window library and read no device: a screen is a function from state to a frame, so a test builds it, reads what it says and taps it by name, and both stay at the coverage the library has. `Nostro.Ui.Shell`, `nostro-app.cpp` and the debug commands are the only code that needs a compositor. They decide nothing about money, are checked by looking ("Looking at the app"), and are outside the coverage figure. What would need a decision there goes into the toolkit or the app as a function a test can call. Crafter.Debug stays in the executable: `Debug::Use` reaches that configuration alone, and the window and the app only offer hooks.
|
||||||
|
12. **The app holds no secret and no say.** It has no key, no token and no file of its own, and its Flatpak no network. A key typed into it lives in a `Secret` field, which is drawn as dots, shown otherwise only as a fingerprint, never copied, and wiped when the form goes; it is passed to nostrod once, in a message marked sensitive. What moves money is confirmed in polkit's dialog, which nostrod words from its own data, and nowhere else: the pay form's button sends, and a program that drove the window would still meet the dialog. So what stands between a press and a payment is the system's policy for the `Pay` action, which asks for the password every time as shipped. Under an administrator's rule that answers it without asking, one press on Pay pays.
|
||||||
|
|
||||||
|
13. **The library is LGPL, the app is GPL.** LGPL-3.0-only: the module `Nostro`, `Nostro.Checkout`, the CLI, nostrod, their tests, the tests' fakes and the fake system, `project.cpp` and the packaging. A program under any licence can be built on the library and the checkout. GPL-3.0-only: `Nostro.Ui`, `Nostro.App`, `Nostro.Ui.Shell`, `nostro-app.cpp`, `Nostro.DebugCommands`, their seven tests and `tests/Support/Ui.inc`, the app's desktop entry and icon, and `docs/screenshots/`, the pictures of the app and the script that takes them: a program built from any of it is under the GPL as a whole. A new file gets the licence of what it is part of, in its first line. The dependency runs one way, and has to: nothing of the library imports or includes anything of the app, or the library could no longer be used under the LGPL. Code moves from the library into the app as it is; the other way it changes licence, which is Catcrafts' to decide for what Catcrafts wrote, and the author's for a patch that came in under the GPL alone. (Decided 2026-11-19.)
|
||||||
|
|
||||||
## Adding a bank
|
## Adding a bank
|
||||||
|
|
||||||
|
|
@ -158,16 +263,19 @@ The checklist, from the bunq connector:
|
||||||
1. `interfaces/Nostro-<Bank>.cppm`: `export module Nostro:<Bank>;` with everything under `#ifdef NOSTRO_<BANK>_ENABLED`, defining `<Bank>Account : Account` and `<Bank>Connector` to design rule 2; `implementations/Nostro-<Bank>.cpp` as `module Nostro:<Bank>_impl;`.
|
1. `interfaces/Nostro-<Bank>.cppm`: `export module Nostro:<Bank>;` with everything under `#ifdef NOSTRO_<BANK>_ENABLED`, defining `<Bank>Account : Account` and `<Bank>Connector` to design rule 2; `implementations/Nostro-<Bank>.cpp` as `module Nostro:<Bank>_impl;`.
|
||||||
2. `interfaces/Nostro.cppm`: `export import :<Bank>;` under the define. `interfaces/Nostro-Banks.cppm`: `import :<Bank>;` under the define and the type in `EnabledBanks`; with two optional entries the comma between them needs a condition of its own, or the tuple does not parse when only one bank is on.
|
2. `interfaces/Nostro.cppm`: `export import :<Bank>;` under the define. `interfaces/Nostro-Banks.cppm`: `import :<Bank>;` under the define and the type in `EnabledBanks`; with two optional entries the comma between them needs a condition of its own, or the tuple does not parse when only one bank is on.
|
||||||
3. `project.cpp`: the name in the `--banks=` loop, its define, its implementation unit, and `opensslEnabled` if it signs. Both configurations get the defines (`execfg.defines = libcfg.defines`).
|
3. `project.cpp`: the name in the `--banks=` loop, its define, its implementation unit, and `opensslEnabled` if it signs. Both configurations get the defines (`execfg.defines = libcfg.defines`).
|
||||||
4. `implementations/main.cpp`: the `connectors add <bank> …` branch, plus any command for what the bank offers beyond design rule 2, behind `if constexpr (requires { … })`. `README.md`: the CLI lines and the supported-banks list. `AGENTS.consumer.md`: what consumers need to know about the bank.
|
4. `implementations/main.cpp`: the `connectors add <bank> …` branch, plus any command for what the bank offers beyond design rule 2, behind `if constexpr (requires { … })`. `README.md`: the CLI lines and the supported-banks list. `AGENTS.consumer.md`: what consumers need to know about the bank. The app: an entry in `implementations/Nostro.App-Banks.cpp` (what nostrod calls the bank, its name, its ways in and what each lets a connection do), a `ConnectForm` and a form in `:Forms` for each way, and `implementations/Nostro.App-<Bank>.cpp` with the pages of those forms and what their buttons do, each ending in `App::Connect`; `Content` in `Nostro.App-Screens.cpp` gets the forms' cases. Nothing else in the app names a bank, and that stays so. What the app shows of an account is what bunq offers and the wire has, for every account alike and in the wire's bunq types: requests, schedules, drafts, and paying an e-mail address or a phone number. A bank that offers less needs that said in its `Bank` and asked for by the screens, and on the wire a shape shared with bunq's or types of its own.
|
||||||
5. A fake of the bank in `tests/Support/` and tests that run every line of its connector, as `FakeBunq.inc` and the bunq tests do; then try it against the bank's sandbox or live API, and say in the commit how. The README refuses blind connector submissions.
|
5. A fake of the bank in `tests/Support/` and tests that run every line of its connector, as `FakeBunq.inc` and the bunq tests do; then try it against the bank's sandbox or live API, and say in the commit how. The README refuses blind connector submissions.
|
||||||
|
|
||||||
## Commit and PR guidelines
|
## Commit and PR guidelines
|
||||||
|
|
||||||
- Patches go by mail to jorijnvdgraaf@catcrafts.net, as the README says. Branch off `master`.
|
- Patches go by mail to jorijnvdgraaf@catcrafts.net, as the README says. Branch off `master`.
|
||||||
- Take the commit voice from the sibling Crafter repositories: `type(scope): imperative summary` with `feat`, `fix`, `refactor`, `docs` or `build`, and the partition or the CLI as the scope (`bunq`, `account`, `currency`, `connector`, `file`, `bus`, `client`, `daemon`, `checkout`, `cli`, `build`, `packaging`). The body says what was wrong, why, and how it was verified against the sandbox. Add a `Co-Authored-By:` trailer when an agent wrote it.
|
- Take the commit voice from the sibling Crafter repositories: `type(scope): imperative summary` with `feat`, `fix`, `refactor`, `docs` or `build`, and the partition or the CLI as the scope (`bunq`, `account`, `currency`, `connector`, `file`, `bus`, `client`, `daemon`, `checkout`, `cli`, `ui`, `app`, `shell`, `debug`, `build`, `packaging`). The body says what was wrong, why, and how it was verified against the sandbox. Add a `Co-Authored-By:` trailer when an agent wrote it.
|
||||||
- The README is the manual: keep its CLI section true to `main.cpp`. Update `AGENTS.consumer.md` in the same change when a signature, a path, a default, a file format or an error behaviour consumers lean on changes; consumers pick it up on their next build.
|
- The README is the manual: keep its CLI section true to `main.cpp` and "The app" true to the screens: what the one can do, the other can. Update `AGENTS.consumer.md` in the same change when a signature, a path, a default, a file format or an error behaviour consumers lean on changes; consumers pick it up on their next build.
|
||||||
|
- A change to how the app looks or is laid out says in its commit how it was looked at: which screens, at which sizes, on what. When it changes a screen the README shows, the pictures are taken again (`docs/screenshots/take.sh`) in the same commit.
|
||||||
|
- The app's version is `NOSTRO_VERSION` in `project.cpp`, and the newest release in `packaging/flatpak/net.catcrafts.Nostro.metainfo.xml` is the same.
|
||||||
- A change to `Transaction` is a schema change (design rule 5), and the commit message says so.
|
- A change to `Transaction` is a schema change (design rule 5), and the commit message says so.
|
||||||
- A change to the D-Bus interfaces or the polkit policy changes the published contract (design rule 10); the XML, the policy and the test that holds them change together.
|
- A change to the D-Bus interfaces or the polkit policy changes the published contract (design rule 10); the XML, the policy and the test that holds them change together.
|
||||||
|
- A change that moves code between the library and the app moves it between two licences (design rule 13), and its commit message says so.
|
||||||
- Never commit `bin/`, `build/`, `AGENTS.md`, or a `connectors.json`.
|
- Never commit `bin/`, `build/`, `AGENTS.md`, or a `connectors.json`.
|
||||||
|
|
||||||
## Security considerations
|
## Security considerations
|
||||||
|
|
@ -175,26 +283,41 @@ The checklist, from the bunq connector:
|
||||||
- `connectors.json` is the crown jewels: the bunq API key or OAuth token, the installation and session tokens and the unencrypted RSA private key, as plain text. Its protection is `0600` in a `0700` directory, and installed, the directory of a system user of its own (`/var/lib/nostro`) under a service that keeps the rest of the system read-only to it; it is replaced by a synced rename, never rewritten in place. There is no encryption at rest: root, and a disk taken out of the machine, read it. Never print it, never log a token or a signature, never copy a real one into a scratch directory or a commit. The transaction tables are the user's financial history, kept private the same way by Crafter.DB.
|
- `connectors.json` is the crown jewels: the bunq API key or OAuth token, the installation and session tokens and the unencrypted RSA private key, as plain text. Its protection is `0600` in a `0700` directory, and installed, the directory of a system user of its own (`/var/lib/nostro`) under a service that keeps the rest of the system read-only to it; it is replaced by a synced rename, never rewritten in place. There is no encryption at rest: root, and a disk taken out of the machine, read it. Never print it, never log a token or a signature, never copy a real one into a scratch directory or a commit. The transaction tables are the user's financial history, kept private the same way by Crafter.DB.
|
||||||
- What nostrod does not stop: a program running as the user can still draw a dialog that looks like polkit's and ask for the password; only the system's own agent is the real one. On a session without a polkit agent (SSH, a TTY without one) nothing can confirm, so every call that needs a password is `Cancelled`. polkit logs the calling process's command line, which is why no secret is ever an argument.
|
- What nostrod does not stop: a program running as the user can still draw a dialog that looks like polkit's and ask for the password; only the system's own agent is the real one. On a session without a polkit agent (SSH, a TTY without one) nothing can confirm, so every call that needs a password is `Cancelled`. polkit logs the calling process's command line, which is why no secret is ever an argument.
|
||||||
- A worker makes itself undumpable, and the service sets `LimitCORE=0`: a core dump would hold the keys. A text that reaches a dialog goes through `Shown()`, so neither a payee's name nor a description can fake another amount or payee in it.
|
- A worker makes itself undumpable, and the service sets `LimitCORE=0`: a core dump would hold the keys. A text that reaches a dialog goes through `Shown()`, so neither a payee's name nor a description can fake another amount or payee in it.
|
||||||
|
- The app is one of the programs nostrod keeps the user's bank from: it sees accounts and payments, which `View` allows any program of the user's in an active session, and nothing that could move money without the dialog. Its Flatpak has the compositor, the graphics device and `net.catcrafts.Nostro1` on the system bus, and no network, no files and no session bus beyond the portals. It makes itself undumpable, so another program of the user's cannot read a key out of it while it is typed. It writes no amount, IBAN or name to its log, which lands in the user's journal.
|
||||||
|
- A build with `--debug-api` is none of that: every program of the user's can drive it and read what it shows, it logs what it is told, and a debugger can attach to it. It is for the made-up system and bunq's sandbox. `Ui_Type` refuses to type into a field that hides what it holds unless the text is a sandbox key (`sandbox_…`); nothing stops a hand from typing a real one into such a build, so do not. No Flatpak is made of it.
|
||||||
- The checkout answers a repeated order with its payment id without a dialog, so any app with access to the checkout can learn whether the user paid an order whose IBAN, reference and amount it knows (README, "Checkout for apps").
|
- The checkout answers a repeated order with its payment id without a dialog, so any app with access to the checkout can learn whether the user paid an order whose IBAN, reference and amount it knows (README, "Checkout for apps").
|
||||||
- A connector's `environment` decides between `api.bunq.com`, where `send` moves real money, and the sandbox. Sandbox API keys are recognised by their `sandbox_` prefix; anything else is production. Only the sandbox has been exercised; test production with small amounts first.
|
- A connector's `environment` decides between `api.bunq.com`, where `send` moves real money, and the sandbox. An API key says itself which it is of: a sandbox key starts with `sandbox_`, and anything else is production. Nobody chooses it: nostrod takes the key's own, and refuses an environment named otherwise before the key goes anywhere, so a real key is not sent to the sandbox by a slip (`OnAddBunq`); the CLI has no flag for it and the app's form no choice. An OAuth client has no such mark, so there the environment is named (`--sandbox`, the form's Production or Sandbox). Since 2026-11-19 production has been used to connect and to read accounts, payments and cards; these notes record no payment made on it, so try that with small amounts first.
|
||||||
- Request bodies are `nlohmann::json` values serialised once (`dump` with invalid UTF-8 replaced), and the signature covers those exact bytes; nothing is spliced into JSON text by hand. Responses are used only after their server signature verifies.
|
- Request bodies are `nlohmann::json` values serialised once (`dump` with invalid UTF-8 replaced), and the signature covers those exact bytes; nothing is spliced into JSON text by hand. Responses are used only after their server signature verifies.
|
||||||
- A write is never replayed by the transport (fresh connection) and only resent by nostro after a 429, which bunq refuses before acting. An IBAN's check digits are verified before anything is sent.
|
- A write is never replayed by the transport (fresh connection) and only resent by nostro after a 429, which bunq refuses before acting. An IBAN's check digits are verified before anything is sent.
|
||||||
- TLS is Crafter.Network's default `TLSClientCredentials{}`: the chain against the system store and the hostname. Do not reach for `insecureNoServerValidation`.
|
- TLS is Crafter.Network's default `TLSClientCredentials{}`: the chain against the system store and the hostname. Do not reach for `insecureNoServerValidation`.
|
||||||
- The private key signs every request body (`SignBody`, RSA SHA-256). Key material lives in `Crypto::Key`s (freed with the last copy) for the process's life; there is no zeroisation.
|
- The private key signs every request body (`SignBody`, RSA SHA-256). Key material lives in `Crypto::Key`s (freed with the last copy) for the process's life; there is no zeroisation.
|
||||||
- `project.cpp` executes the `project.cpp` of three unpinned dependencies (Crafter.Network, Crafter.DB, Crafter.LintRules) on every build, fetched from the Catcrafts Forgejo at HEAD, and the Flatpak build does the same with the network on. Pin a commit on each for a build that is reproducible and offline after the first fetch.
|
- `project.cpp` executes the `project.cpp` of three unpinned dependencies (Crafter.Network, Crafter.DB, Crafter.LintRules) on every build, fetched from the Catcrafts Forgejo at HEAD, and the Flatpak build does the same with the network on; Crafter.Debug's build helper is the one that is pinned. The app's build adds Crafter.Graphics, which brings Crafter.Event, Crafter.Math, Crafter.Asset and the Khronos headers, unpinned, and its debug build Crafter.Debug's library with a Crafter.Network that has msquic in it. Pin a commit on each for a build that is reproducible and offline after the first fetch.
|
||||||
- `install.sh --repo` installs from an unsigned local repository, for a build of your own. A published Flatpak comes from the GPG-signed Catcrafts remote; `packaging/flatpak/net.catcrafts.Nostro.flatpakref` carries the same placeholder for the key as Crafter.Build's, for the publishing side to fill in.
|
- `install.sh --repo` installs from an unsigned local repository, for a build of your own, and so does a bundle crafter-build made. A published Flatpak comes from the GPG-signed Catcrafts remote, which is how the README installs both: the remote `catcrafts`, added from `https://flatpak.catcrafts.net/catcrafts.flatpakrepo`, Crafter.Build's own remote. `install.sh` without `--repo` installs from that remote in the system installation, where nostrod runs from, and does not add it itself. On 2026-11-19 the remote did not carry nostro's two Flatpaks yet: the README describes the channel they are to be published on. The two `.flatpakref`s in `packaging/flatpak/` carry the same placeholder for the key as Crafter.Build's, for the publishing side to fill in.
|
||||||
- Input from the bank is parsed with nlohmann/json's `at()` and `get()`, which throw on a missing key or a wrong type: a malformed response is an exception, not undefined behaviour. `ParseAmount` and `ParseTimestamp` reject anything outside their grammar.
|
- Input from the bank is parsed with nlohmann/json's `at()` and `get()`, which throw on a missing key or a wrong type: a malformed response is an exception, not undefined behaviour. `ParseAmount` and `ParseTimestamp` reject anything outside their grammar.
|
||||||
|
|
||||||
## Gotchas
|
## Gotchas
|
||||||
|
|
||||||
The state of the code on 2026-11-01; each is a fact to work with.
|
The state of the code on 2026-11-19; each is a fact to work with.
|
||||||
|
|
||||||
- crafter-build makes one configuration per run, so nostrod and the checkout library are products chosen with `--product=`, as in imsd. The library is one shared `Configuration*`: two configurations exporting the same module in one build are an error.
|
- `project.cpp` returns one configuration per run, so nostrod, the app, the checkout library and the fake system are products chosen with `--product=`, as in imsd. The library is one shared `Configuration*`: two configurations exporting the same module in one build are an error. The toolkit's and the app's libraries are declared in every product and built only for what depends on them: their tests, and the app.
|
||||||
|
- `crafter-build -r` passes the program it runs no arguments, and the app has a few: that is what the `fake` script is for, and `--poke` with `--screenshot` for a run without a hand on it.
|
||||||
|
- Crafter.Debug counts a frame each time it is given the loop's thread, every 50 ms, whatever the window drew: `wait --frames` measures time there. Wait for the event `FrameRendered` for a frame, and for a condition (`wait 'app.busy == false'`) for an answer: `wait --event AnswerArrived` only hears an answer that comes after it started, and nostrod's has often come by then.
|
||||||
|
- `crafter-debug screenshot -o <file>` writes inside the client's sandbox, whose `/tmp` is its own: leave `-o` out, for `build/crafter-debug-shots/`, or name a path the sandbox shares with the host.
|
||||||
|
- Crafter.Graphics' text size is the height from the top of the ascenders to the bottom of the descenders, not the em: the design's 16 dp body text is about 11.7 dp of em. `Nostro.Ui`'s sizes are in that measure, and a label drawn beside a larger text shares its baseline only when it is put there (`DialogSheet` does).
|
||||||
|
- Text on a screen cannot be selected: the toolkit has a selection inside a text field and nowhere else. What is worth taking along is copied whole by a press instead: a line of a sheet (`ValueRow`, `copy.<label>`), an account's IBAN, a request's link. Selecting part of a text would be a feature of the toolkit's own: text that knows where its glyphs are, a selection kept in the `Context`, a mouse's drag that selects where a finger's scrolls, and handles for a finger.
|
||||||
|
- The made-up bank answers at once, and a real one is a network away: a screen that asks the bank more than it has to looks fine on the fake system and is slow in use. That is how a search that asked the bank with every question went unnoticed until 2026-11-19. Look at anything that waits for the bank with `--bank-delay 300`, and count the bank's calls in a test (`bunq.Count`).
|
||||||
|
- A widget lower than a finger needs is given the room when it is pressed, not when it is drawn: `Button`'s region reaches as far above and below what is drawn as makes 48 dp, so two low buttons need that much between them. `ShouldDriveTheApp` fails on anything pressable under 48 dp on a phone's size.
|
||||||
|
- A line of a sheet (`ValueRow`) keeps a column of a fixed width for its label, 112 dp, and cuts a longer label with an ellipsis: fourteen characters fit in the tests' font, which is wider than Noto Sans. "The bank's number" came out as "The bank's nu…" there, which is why that line is "Bank's number". Read a new line's label in a test's "It says:".
|
||||||
|
- `flatpak build` gives the sandbox no system bus at all, whatever the app's metadata says, and no `WAYLAND_DISPLAY`. So the packaged app can be started for a look at the runtime it will run on, without reaching a nostrod: `flatpak build --runtime --readonly --env=WAYLAND_DISPLAY=<the compositor's socket> build/flatpak-apps/net.catcrafts.Nostro/build-dir nostro-app --gallery widgets`. `flatpak run` of an installed app does reach the installed nostrod.
|
||||||
|
- `--packaging=flatpak` is refused for a build against a sysroot, which is why aarch64 has scripts of its own. It names its output after `--march` and `--mtune`: without them a bundle is built for the building machine's CPU.
|
||||||
|
- The aarch64 scripts run crafter-build as `flatpak run net.catcrafts.CrafterBuild` (`$CRAFTER_REF`), since that is where the toolchain they cross-compile with is, and remove every `bin/*-aarch64-unknown-linux-gnu-armv8-a-generic-*` before they build: a directory's name ends in a hash, and an older one would be a second match.
|
||||||
|
- The notes of Crafter.Graphics, Crafter.Math and Crafter.Asset are in `AGENTS.md` only after a build of the app, and gone again after the next build of another product: crafter-build writes the section from what the build loaded.
|
||||||
- systemd's hardening and bubblewrap, which flatpak runs nostrod in, disagree in places, found on 2026-11-01 under `systemd-run --user`: bubblewrap needs `AF_NETLINK` (it brings up loopback), `@mount`, `unshare` and `setns`, and a `/proc` of its own; `RestrictSUIDSGID=` makes systemd answer `openat2()` with ENOSYS, which bubblewrap 0.13 does not fall back from. `nostrod.service` says which options are left out and why.
|
- systemd's hardening and bubblewrap, which flatpak runs nostrod in, disagree in places, found on 2026-11-01 under `systemd-run --user`: bubblewrap needs `AF_NETLINK` (it brings up loopback), `@mount`, `unshare` and `setns`, and a `/proc` of its own; `RestrictSUIDSGID=` makes systemd answer `openat2()` with ENOSYS, which bubblewrap 0.13 does not fall back from. `nostrod.service` says which options are left out and why.
|
||||||
- polkit as seen on that day (polkit 127, Plasma): closing Plasma's dialog sends no `polkit.dismissed`, only `polkit.result` `auth_self`, so `Cancelled` is read from either; a kept authorization is the calling process's alone; the command line of the process asking is logged.
|
- polkit as seen on that day (polkit 127, Plasma): closing Plasma's dialog sends no `polkit.dismissed`, only `polkit.result` `auth_self`, so `Cancelled` is read from either; a kept authorization is the calling process's alone; the command line of the process asking is logged.
|
||||||
- sd-bus holds a vtable method's answer to the signature the vtable declares: an answer of another shape becomes `System.Error.ENOMSG`. A test that must send a malformed answer (`FakeCheckout` in `ShouldServeEveryUser`) registers a plain object (`sd_bus_add_object`) instead.
|
- sd-bus holds a vtable method's answer to the signature the vtable declares: an answer of another shape becomes `System.Error.ENOMSG`. A test that must send a malformed answer (`FakeCheckout` in `ShouldServeEveryUser`) registers a plain object (`sd_bus_add_object`) instead.
|
||||||
- A worker or nostrod killed with SIGKILL writes no coverage counts; both handle SIGTERM (systemd's stop signal too) by ending the loop, and the tests stop them that way.
|
- A worker or nostrod killed with SIGKILL writes no coverage counts; both handle SIGTERM (systemd's stop signal too) by ending the loop, and the tests stop them that way.
|
||||||
- `--product=checkout` returns before the bank check, so it needs no `--banks=`; every other product does.
|
- `--product=checkout` returns before the bank check, so it needs no `--banks=`; every other product does.
|
||||||
|
- nostrod's Flatpak was `net.catcrafts.Nostro` until 2026-11-01, when the coming Nostro app took that id and nostrod's became `net.catcrafts.Nostrod`. flatpak keeps an app's data under its id, so nostrod's state followed: `install.sh` stops nostrod, moves `/var/lib/nostro/.var/app/net.catcrafts.Nostro` to `…/net.catcrafts.Nostrod` (refusing when both exist), and removes the old Flatpak, which it tells from the app by its command, `nostro`. The Arch package only prints those steps, since the package and the Flatpaks update independently.
|
||||||
|
|
||||||
- **`GetConfigPath()` with `XDG_CONFIG_HOME` set returns `$XDG_CONFIG_HOME/.config/nostro`**, not `$XDG_CONFIG_HOME/nostro`; the cache path has no such insertion. An open bug, kept as is so existing files are still found; the sandbox recipe above accounts for it.
|
- **`GetConfigPath()` with `XDG_CONFIG_HOME` set returns `$XDG_CONFIG_HOME/.config/nostro`**, not `$XDG_CONFIG_HOME/nostro`; the cache path has no such insertion. An open bug, kept as is so existing files are still found; the sandbox recipe above accounts for it.
|
||||||
- bunq's spec is not always what the API does. Verified in the sandbox:
|
- bunq's spec is not always what the API does. Verified in the sandbox:
|
||||||
|
|
@ -203,10 +326,11 @@ The state of the code on 2026-11-01; each is a fact to work with.
|
||||||
- The OAuth token endpoint ignores a form body: its parameters go in the query string.
|
- The OAuth token endpoint ignores a form body: its parameters go in the query string.
|
||||||
- `UserPerson` has no `name`; every user type has `display_name`.
|
- `UserPerson` has no `name`; every user type has `display_name`.
|
||||||
- `PUT …/card/{id}` answers with the card as it is, even when it ignored the status asked for.
|
- `PUT …/card/{id}` answers with the card as it is, even when it ignored the status asked for.
|
||||||
|
- A card's `status` is about its plastic. A card just ordered is `DEACTIVATED` with `order_status` `VIRTUAL_DELIVERY` and `sub_status` `PIN_SET_BEFORE_PRODUCTION`, a value the spec does not list, whether plastic was asked for or not. A virtual card stays so for good, also while it pays: seen on a real one on 2026-11-19. Asked to set such a card `ACTIVE` or `DEACTIVATED`, by its own `status` or by its number's, bunq answers 200 with the card unchanged; `LOST`, `STOLEN` and `CANCELLED` do take. There is no virtual type or product to order: a virtual card is an ordinary one left at `VIRTUAL_DELIVERY`. Nothing nostro reads says whether a virtual card is frozen; a card also has `is_card_frozen_payment_tokenized_allowed`, unread, which by its name is whether a phone may pay with a frozen card.
|
||||||
- Check a listing's object name against a real response before relying on it.
|
- Check a listing's object name against a real response before relying on it.
|
||||||
- The transaction cache moved on 2026-10-31 to `<cache>/transactions/bunq/<environment>/<user id>/<account id>/<name>.cdb`. Tables from before sit at `transactions/bunq/<name>.cdb`, are no longer read, and stay on disk until deleted by hand; a connector re-syncs its history on first use.
|
- The transaction cache moved on 2026-10-31 to `<cache>/transactions/bunq/<environment>/<user id>/<account id>/<name>.cdb`. Tables from before sit at `transactions/bunq/<name>.cdb`, are no longer read, and stay on disk until deleted by hand; a connector re-syncs its history on first use.
|
||||||
- `connectors.lock` is held for the whole process. Under nostrod that is the user's worker, which lives until it is idle; a program using the library directly on the same directory waits for it, and before nostrod a command waiting at a prompt held up the next one.
|
- `connectors.lock` is held for the whole process. Under nostrod that is the user's worker, which lives until it is idle; a program using the library directly on the same directory waits for it, and before nostrod a command waiting at a prompt held up the next one.
|
||||||
- A sandbox virtual card cannot be activated through the API: `cards unfreeze` reports bunq keeping it `DEACTIVATED`, which is the real answer, not a bug.
|
- A sandbox card never gets past `VIRTUAL_DELIVERY`, so every card in the sandbox is a virtual one to nostro (`BunqCard::Virtual`): listed as `VIRTUAL`, and refused by nostrod when it is to be frozen or unfrozen. Freezing plastic cannot be tried there; reporting a card lost or stolen can.
|
||||||
- `RespondToDraftPayment` sends the shown draft's `updated` as `previous_updated_timestamp`; bunq refuses a response to a draft that changed since it was read. `RespondToRequest` pays the shown request's amount, not what bunq holds by the time it runs.
|
- `RespondToDraftPayment` sends the shown draft's `updated` as `previous_updated_timestamp`; bunq refuses a response to a draft that changed since it was read. `RespondToRequest` pays the shown request's amount, not what bunq holds by the time it runs.
|
||||||
- The `std::formatter` for accounts is a constrained partial specialisation (`template<std::derived_from<Nostro::Account> T>`) because an explicit `std::formatter<Account>` does not apply to `BunqAccount`; every new account type is covered by it. Non-exported formatter specialisations in a partition are found by importers.
|
- The `std::formatter` for accounts is a constrained partial specialisation (`template<std::derived_from<Nostro::Account> T>`) because an explicit `std::formatter<Account>` does not apply to `BunqAccount`; every new account type is covered by it. Non-exported formatter specialisations in a partition are found by importers.
|
||||||
- `.vscode/tasks.json` runs `crafter-build build --debug --banks=bunq`: `build` is not a crafter-build verb, it passes through as a project arg, nostro forwards it to its dependencies, and everything builds into variant directories of its own. `.vscode/launch.json` names a variant directory and a `balance` command that no longer exist.
|
- `.vscode/tasks.json` runs `crafter-build build --debug --banks=bunq`: `build` is not a crafter-build verb, it passes through as a project arg, nostro forwards it to its dependencies, and everything builds into variant directories of its own. `.vscode/launch.json` names a variant directory and a `balance` command that no longer exist.
|
||||||
|
|
|
||||||
127
README.md
127
README.md
|
|
@ -1,64 +1,88 @@
|
||||||
## Nostro
|
## Nostro
|
||||||
|
|
||||||
The primary problem with linux phones is that they don't have banking apps, Nostro tries to change that.
|
A big problem linux phones have is that they don't have banking apps, Nostro tries to change that.
|
||||||
|
|
||||||
By making a open source app that interfaces with bank APIs.
|
By making a open source app that interfaces with bank APIs.
|
||||||
|
|
||||||
## How Nostro runs
|
## How Nostro runs
|
||||||
|
|
||||||
Nostro keeps your bank connections out of reach of the programs you run. Its daemon, nostrod, runs as a system user of its own and holds the bank connections of every user of the machine, each user's in a process of its own. The `nostro` command asks nostrod over the system bus, and nostrod asks polkit whether you may:
|
Nostro keeps your bank connections out of reach of the programs you run. Its daemon, nostrod, runs as a system user of its own and holds the bank connections of every user of the machine, each user's in a process of its own. The Nostro app and the `nostro` command ask nostrod over the system bus, and nostrod asks polkit whether you may:
|
||||||
|
|
||||||
- Looking at accounts, transactions, requests and cards needs nothing more in your desktop session.
|
- Looking at accounts, transactions, requests and cards needs nothing more in your desktop session.
|
||||||
- Paying, scheduling a payment, accepting a request or a draft payment, unfreezing or blocking a card, and changing your bank connections ask for your password every time.
|
- Paying, scheduling a payment, accepting a request or a draft payment, unfreezing or blocking a card, and changing your bank connections ask for your password every time.
|
||||||
|
|
||||||
Your desktop draws the password dialog, and it says what it is for: the amount, who is paid, and from which account. Nothing secret goes on the command line: Nostro asks for an API key at a prompt.
|
Your desktop draws the password dialog, and it says what it is for: the amount, who is paid, and from which account. Nothing secret goes on the command line: Nostro asks for an API key at a prompt. The app holds none of your keys either: one you type into it goes to nostrod and is forgotten.
|
||||||
|
|
||||||
|
## The app
|
||||||
|
|
||||||
|
The app is a window for a phone or a desktop. On a phone it shows one page at a time, with Accounts, Cards and Settings along the bottom; in a wider window those are down the side, with your accounts beside them. It follows your desktop's light or dark look and its accent colour.
|
||||||
|
|
||||||
|
On a phone, in the dark look:
|
||||||
|
|
||||||
|
| Accounts | An account | Pay |
|
||||||
|
|---|---|---|
|
||||||
|
|  |  |  |
|
||||||
|
|
||||||
|
In a desktop window, in the light look and in the dark one:
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
The accounts and the people in these pictures are made up.
|
||||||
|
|
||||||
|
It does everything the `nostro` command does:
|
||||||
|
|
||||||
|
| In the app | What it is for |
|
||||||
|
|---|---|
|
||||||
|
| Accounts | Your accounts by bank connection, with their balances. Pay and Request start from any of them. |
|
||||||
|
| An account, Activity | Its payments by day. Search a name, a description or an IBAN, or filter by an exact amount and by dates: that looks through the payments Nostro has read from the bank, as you type. A payment opens with all of its details, and can be paid again or asked back from there. |
|
||||||
|
| An account, Requests and Incoming | The requests for money you sent, each with its link to copy or open, which you can revoke; and the ones you received, to pay or reject. |
|
||||||
|
| An account, Scheduled and Drafts | The payments on a schedule, to cancel; and the draft payments, to accept or reject. |
|
||||||
|
| Pay | From which account, to an IBAN, an e-mail address or a phone number, how much, and what for: now, on a schedule, or as a draft. Its button sends it: a payment is confirmed in your system's password dialog, and a draft is saved at once, to be paid when it is accepted. |
|
||||||
|
| Request | Ask someone for money. The result has a link to send them. |
|
||||||
|
| Cards | Your cards and the account each pays from. Freeze or unfreeze one, or report it lost or stolen, which blocks it for good and is asked twice. |
|
||||||
|
| Settings, Bank connections | Your connections and whether they work. Add one in three steps: your bank, how to connect to it, and what that asks for. bunq connects with an API key or through OAuth. Remove one, which logs it out and deletes its stored payments. |
|
||||||
|
| Settings, Pay at checkout from | The account apps are paid from at their checkout, see Checkout for apps. |
|
||||||
|
| Settings, About and security | What Nostro protects you from, and its version. |
|
||||||
|
|
||||||
|
- Which bank an account is with makes no difference to how the app shows it or pays from it. Only adding a connection, in the settings, is each bank's own. Until a bank is connected the app offers to connect one.
|
||||||
|
- A connection that its bank lets pay between your own accounts only, as bunq does one made through OAuth, is marked Limited. A payment from it to anyone else is saved as a draft, to approve in your bank's app.
|
||||||
|
- The app asks no second question before a payment: Pay sends it, and your system's password dialog is where you confirm it. That dialog is your system's, not the app's, and says what is paid, to whom and from which account: read it. Closing it pays nothing, and leaves the form as you filled it in.
|
||||||
|
- A card's status is what its bank reports of it. A virtual card is shown as Virtual, and no more: the bank does not report whether one is frozen, and does not freeze or unfreeze one when Nostro asks, so do that in your bank's app. It can be reported lost or stolen like any card. For a plastic card, Deactivated is the bank's word for one that is frozen and for one that was never activated: the card's own sheet says so, and shows how far the bank is with the card.
|
||||||
|
- If the bank's answer to a payment gets lost on the way, the app says the payment may have been made and shows you the account's payments. It does not offer to try again.
|
||||||
|
- The app asks a phone's on-screen keyboard for digits at an amount, and to show and learn nothing of a key you type.
|
||||||
|
- Your accounts, an account's lists and your cards are read again when you pull the page down at its top and let go, or with Refresh in the bar at the top.
|
||||||
|
- Press a line of a payment's, a request's or a card's details to copy what it says. An IBAN is copied without its spaces.
|
||||||
|
- With a keyboard: Tab and Shift+Tab move between what can be pressed, Enter presses it, Escape goes back, F5 or Ctrl+R reads the screen again, and Ctrl+F goes to the search. A long press or the right mouse button on a field offers paste, copy and select all.
|
||||||
|
- The app needs nostrod installed (see Installing). Without it, it says so and how to get it.
|
||||||
|
|
||||||
## Installing
|
## Installing
|
||||||
|
|
||||||
Nostro comes as a Flatpak, `net.catcrafts.Nostro`, installed for the whole system. A Flatpak cannot install a few system files Nostro needs: nostrod's user, its D-Bus and polkit policies, its systemd unit, and the `nostro` command. Install both as root:
|
nostrod and the `nostro` command come as a Flatpak, `net.catcrafts.Nostrod`, installed for the whole system. A Flatpak cannot install a few system files Nostro needs: nostrod's user, its D-Bus and polkit policies, its systemd unit, and the `nostro` command. Install both as root. The Flatpak comes from the Catcrafts Flatpak repository, which the first line adds:
|
||||||
|
|
||||||
```
|
```
|
||||||
flatpak install --system packaging/flatpak/net.catcrafts.Nostro.flatpakref # the Flatpak, from the Catcrafts repository
|
flatpak remote-add --system --if-not-exists catcrafts https://flatpak.catcrafts.net/catcrafts.flatpakrepo
|
||||||
packaging/system/install.sh # the system files
|
flatpak install --system catcrafts net.catcrafts.Nostrod # the Flatpak
|
||||||
|
packaging/system/install.sh # the system files
|
||||||
```
|
```
|
||||||
|
|
||||||
To install a Flatpak you built yourself (see Building) instead, run `packaging/system/install.sh --repo <dir>/repo`. On Arch Linux, `makepkg -si` in `packaging/arch` installs the system files as the `nostro-system` package instead of `install.sh`. nostrod starts with the first `nostro` command and stops by itself once it has nothing to do.
|
The app is a Flatpak of its own, `net.catcrafts.Nostro`, in the same repository, which each user can install for themselves:
|
||||||
|
|
||||||
|
```
|
||||||
|
flatpak remote-add --user --if-not-exists catcrafts https://flatpak.catcrafts.net/catcrafts.flatpakrepo
|
||||||
|
flatpak install --user catcrafts net.catcrafts.Nostro
|
||||||
|
```
|
||||||
|
|
||||||
|
`packaging/system/install.sh --app` installs it for every user instead, together with the rest. The app can reach your display, your graphics card and nostrod, and nothing else: no network and none of your files.
|
||||||
|
|
||||||
`packaging/system/uninstall.sh` removes everything again. Your bank connections stay in `/var/lib/nostro` until you give it `--purge`.
|
`packaging/system/uninstall.sh` removes everything again. Your bank connections stay in `/var/lib/nostro` until you give it `--purge`.
|
||||||
|
|
||||||
## Moving from an older Nostro
|
|
||||||
|
|
||||||
Before nostrod, Nostro kept your bank connections in `~/.config/nostro/connectors.json`, where any program you ran could read your API key, and the `nostro` command warns while that file exists. To move:
|
|
||||||
|
|
||||||
1. Revoke the key in the bunq app, under Developers, then API keys.
|
|
||||||
2. Add a new key with `nostro connectors add bunq`.
|
|
||||||
3. Delete `~/.config/nostro` and `~/.cache/nostro`.
|
|
||||||
|
|
||||||
Nostro fetches your transaction history from bunq again.
|
|
||||||
|
|
||||||
## Building
|
|
||||||
|
|
||||||
This project uses [Crafter.Build](https://forgejo.catcrafts.net/Catcrafts/Crafter.Build) for its building system
|
|
||||||
|
|
||||||
```
|
|
||||||
crafter-build --banks={lists of banks you want to enable} # the library and the nostro command
|
|
||||||
crafter-build --banks=bunq --product=daemon # nostrod
|
|
||||||
crafter-build --product=checkout # the checkout library for apps, see Checkout for apps
|
|
||||||
```
|
|
||||||
|
|
||||||
The `nostro` command talks to an installed nostrod, so it needs one to do anything. The Flatpak builds on crafter-build's own Flatpak, which must be installed:
|
|
||||||
|
|
||||||
```
|
|
||||||
flatpak run --filesystem=<dir> org.flatpak.Builder --user --force-clean --repo=<dir>/repo --state-dir=<dir>/state <dir>/build packaging/flatpak/net.catcrafts.Nostro.yaml
|
|
||||||
```
|
|
||||||
|
|
||||||
`--filesystem=` is only needed for a `<dir>` outside your home.
|
|
||||||
|
|
||||||
## CLI
|
## CLI
|
||||||
|
|
||||||
```
|
```
|
||||||
nostro connectors # connectors, numbered, and whether they work
|
nostro connectors # connectors, numbered, and whether they work
|
||||||
nostro connectors add bunq [allowed ips, default *] [--sandbox] # asks for the API key
|
nostro connectors add bunq [allowed ips, default *] # asks for the API key; a sandbox key starts with sandbox_
|
||||||
nostro connectors add bunq-oauth {client id} {redirect uri} [--sandbox] # asks for the client secret
|
nostro connectors add bunq-oauth {client id} {redirect uri} [--sandbox] # asks for the client secret
|
||||||
nostro connectors remove {name or number} # logs out and deletes its stored transactions
|
nostro connectors remove {name or number} # logs out and deletes its stored transactions
|
||||||
nostro accounts # all accounts of all connectors
|
nostro accounts # all accounts of all connectors
|
||||||
|
|
@ -79,12 +103,7 @@ nostro checkout account [{account}] # the account apps may ask y
|
||||||
- `{to}` and `{from}` are an IBAN, an e-mail address, or a phone number starting with `+`. IBANs are checked before anything is sent.
|
- `{to}` and `{from}` are an IBAN, an e-mail address, or a phone number starting with `+`. IBANs are checked before anything is sent.
|
||||||
- Amounts are in the smallest unit of your currency, so for EUR `1250` is €12.50.
|
- Amounts are in the smallest unit of your currency, so for EUR `1250` is €12.50.
|
||||||
- Dates are `YYYY-MM-DD` or `"YYYY-MM-DD hh:mm"`, in local time.
|
- Dates are `YYYY-MM-DD` or `"YYYY-MM-DD hh:mm"`, in local time.
|
||||||
|
- `nostro cards` lists a virtual card as `VIRTUAL`. bunq does not say whether one is frozen and does not freeze or unfreeze one when asked, so `freeze` and `unfreeze` refuse it; `lost` and `stolen` work.
|
||||||
## bunq
|
|
||||||
|
|
||||||
Connect with an API key: in the bunq app's settings, open Developers, then API keys, and add one. Nostro asks for it without echoing it, or reads it from stdin, and never takes it from the command line, which every user of the machine can read. A key added with the default allowed IP `*` works from any address, which a phone needs. Sandbox keys start with `sandbox_` and connect to the sandbox automatically. Adding the same bunq user again replaces the connector, which is how you renew a key.
|
|
||||||
|
|
||||||
OAuth is the other way in. Any bunq user can create an OAuth client in the bunq app or at [bunq Developer](https://developer.bunq.com) and register a redirect URL for it. `nostro connectors add bunq-oauth` prints an address to open, where you approve the connection by scanning a QR code with the bunq app. Paste the address your browser lands on afterwards back into Nostro. bunq only lets OAuth connections pay between your own accounts. A payment to someone else has to be a draft payment (`nostro draft`) that you approve in the bunq app, and incoming requests can be read but not paid. An API key has none of these limits.
|
|
||||||
|
|
||||||
## Supported banks
|
## Supported banks
|
||||||
|
|
||||||
|
|
@ -92,7 +111,7 @@ OAuth is the other way in. Any bunq user can create an OAuth client in the bunq
|
||||||
|
|
||||||
## Checkout for apps
|
## Checkout for apps
|
||||||
|
|
||||||
An app, such as a shop, can have the user's Nostro pay an order. Nostro pays it from the account the user chose once with `nostro checkout account {account}`, after the user has confirmed the payment with their password at a prompt that shows the amount, the payee, the reference and that account. The app never names or sees the account, and gets back only the payment's id. An account connected through OAuth cannot pay a shop, so it cannot be chosen.
|
An app, such as a shop, can have the user's Nostro pay an order. Nostro pays it from the account the user chose once, in the app's settings or with `nostro checkout account {account}`, after the user has confirmed the payment with their password at a prompt that shows the amount, the payee, the reference and that account. The app never names or sees the account, and gets back only the payment's id. An account connected through OAuth cannot pay a shop, so it cannot be chosen.
|
||||||
|
|
||||||
Apps talk to `net.catcrafts.Nostro1.Checkout` on the system bus. A Flatpak app asks for it with `--system-talk-name=net.catcrafts.Nostro1.Checkout` in its finish-args, which reaches nothing else of Nostro. The interface is one method, documented in [packaging/dbus/net.catcrafts.Nostro1.Checkout.xml](packaging/dbus/net.catcrafts.Nostro1.Checkout.xml):
|
Apps talk to `net.catcrafts.Nostro1.Checkout` on the system bus. A Flatpak app asks for it with `--system-talk-name=net.catcrafts.Nostro1.Checkout` in its finish-args, which reaches nothing else of Nostro. The interface is one method, documented in [packaging/dbus/net.catcrafts.Nostro1.Checkout.xml](packaging/dbus/net.catcrafts.Nostro1.Checkout.xml):
|
||||||
|
|
||||||
|
|
@ -126,24 +145,15 @@ const Nostro::Checkout::Paid paid = Nostro::Checkout::Pay({.payeeIban = "NL91ABN
|
||||||
|
|
||||||
Any app the user runs with access to the checkout can ask whether an order was paid, by asking for it again with the same IBAN, reference and amount: it gets the payment id without a prompt. Nostro cannot tell which app is asking, so a reference should be hard to guess.
|
Any app the user runs with access to the checkout can ask whether an order was paid, by asking for it again with the same IBAN, reference and amount: it gets the payment id without a prompt. Nostro cannot tell which app is asking, so a reference should be hard to guess.
|
||||||
|
|
||||||
## Testing
|
|
||||||
|
|
||||||
```
|
|
||||||
crafter-build test --banks=bunq # every test, against a fake bunq and a fake system bus in the test itself
|
|
||||||
tests/coverage.sh # the same with coverage: a report per file, and every line no test ran
|
|
||||||
```
|
|
||||||
|
|
||||||
`tests/coverage.sh` needs `llvm-profdata` and `llvm-cov`, and a toolchain with compiler-rt's profile runtime; for one without it, pass the path of its `libclang_rt.profile` archive as the argument.
|
|
||||||
|
|
||||||
## Contributing
|
## Contributing
|
||||||
|
|
||||||
Nostro gladly accepts contributions to add more banks!
|
Nostro gladly accepts contributions to add more banks!
|
||||||
|
|
||||||
Please add a connector for the bank you want to add and send the patch to jorijnvdgraaf@catcrafts.net
|
Please add a connector for the bank you want to add and git send-email the patch to jorijnvdgraaf@catcrafts.net
|
||||||
|
|
||||||
Please add thorough testing coverage for te bank you are submitting.
|
Please add thorough testing coverage for te bank you are submitting.
|
||||||
|
|
||||||
For 100% certainity blind submissions for connectors are not be accepted, they must be tested against either the live or sandbox API.
|
For 100% certainity blind submissions for connectors are not accepted, they must be tested against either the live or sandbox API.
|
||||||
|
|
||||||
## Security
|
## Security
|
||||||
|
|
||||||
|
|
@ -151,7 +161,7 @@ Please report security vuneribilities to jorijnvdgraaf@catcrafts.net before publ
|
||||||
|
|
||||||
What Nostro protects you from, and what it does not:
|
What Nostro protects you from, and what it does not:
|
||||||
|
|
||||||
- Programs you run cannot read your bank connections, which belong to nostrod's own user, and cannot move money without your password.
|
- Programs you run cannot read your bank connections, which belong to nostrod's own user, and cannot move money without your password. The Nostro app is one of those programs: it holds no key and no token.
|
||||||
- The password dialog is your desktop's. A program running as you could still draw one that looks the same, so type your password only for something you asked for, and check what the dialog says.
|
- The password dialog is your desktop's. A program running as you could still draw one that looks the same, so type your password only for something you asked for, and check what the dialog says.
|
||||||
- Over SSH, or in any session without a polkit agent, nothing can ask for your password, so whatever needs it is refused.
|
- Over SSH, or in any session without a polkit agent, nothing can ask for your password, so whatever needs it is refused.
|
||||||
- The bank connections are not encrypted on disk: root, and anyone holding the disk, can read them. Use full-disk encryption.
|
- The bank connections are not encrypted on disk: root, and anyone holding the disk, can read them. Use full-disk encryption.
|
||||||
|
|
@ -159,7 +169,12 @@ What Nostro protects you from, and what it does not:
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
LGPL-3.0-only, see [LICENSE](LICENSE).
|
Nostro has two licences, and each source file says in its first line which one it is under:
|
||||||
|
|
||||||
|
- The library, nostrod, the `nostro` command and the checkout library are LGPL-3.0-only, see [LICENSE](LICENSE). A program under another licence can be built on the library or the checkout.
|
||||||
|
- The app is GPL-3.0-only, see [LICENSE.GPL](LICENSE.GPL): its screens, the toolkit they are built with and its window (the modules `Nostro.Ui`, `Nostro.App` and `Nostro.Ui.Shell`, and `nostro-app`). A program built from any of it is under the GPL as a whole.
|
||||||
|
|
||||||
|
The app is set in Noto Sans, under the SIL Open Font License ([assets/OFL.txt](assets/OFL.txt)); [packaging/licenses/NOTICE](packaging/licenses/NOTICE) lists what else the Flatpaks carry.
|
||||||
|
|
||||||
## Copyright
|
## Copyright
|
||||||
|
|
||||||
|
|
|
||||||
BIN
assets/NotoSans-Medium.ttf
Normal file
BIN
assets/NotoSans-Medium.ttf
Normal file
Binary file not shown.
BIN
assets/NotoSans-Regular.ttf
Normal file
BIN
assets/NotoSans-Regular.ttf
Normal file
Binary file not shown.
93
assets/OFL.txt
Normal file
93
assets/OFL.txt
Normal file
|
|
@ -0,0 +1,93 @@
|
||||||
|
Copyright 2022 The Noto Project Authors (https://github.com/notofonts/latin-greek-cyrillic)
|
||||||
|
|
||||||
|
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||||
|
This license is copied below, and is also available with a FAQ at:
|
||||||
|
http://scripts.sil.org/OFL
|
||||||
|
|
||||||
|
|
||||||
|
-----------------------------------------------------------
|
||||||
|
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||||
|
-----------------------------------------------------------
|
||||||
|
|
||||||
|
PREAMBLE
|
||||||
|
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||||
|
development of collaborative font projects, to support the font creation
|
||||||
|
efforts of academic and linguistic communities, and to provide a free and
|
||||||
|
open framework in which fonts may be shared and improved in partnership
|
||||||
|
with others.
|
||||||
|
|
||||||
|
The OFL allows the licensed fonts to be used, studied, modified and
|
||||||
|
redistributed freely as long as they are not sold by themselves. The
|
||||||
|
fonts, including any derivative works, can be bundled, embedded,
|
||||||
|
redistributed and/or sold with any software provided that any reserved
|
||||||
|
names are not used by derivative works. The fonts and derivatives,
|
||||||
|
however, cannot be released under any other type of license. The
|
||||||
|
requirement for fonts to remain under this license does not apply
|
||||||
|
to any document created using the fonts or their derivatives.
|
||||||
|
|
||||||
|
DEFINITIONS
|
||||||
|
"Font Software" refers to the set of files released by the Copyright
|
||||||
|
Holder(s) under this license and clearly marked as such. This may
|
||||||
|
include source files, build scripts and documentation.
|
||||||
|
|
||||||
|
"Reserved Font Name" refers to any names specified as such after the
|
||||||
|
copyright statement(s).
|
||||||
|
|
||||||
|
"Original Version" refers to the collection of Font Software components as
|
||||||
|
distributed by the Copyright Holder(s).
|
||||||
|
|
||||||
|
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||||
|
or substituting -- in part or in whole -- any of the components of the
|
||||||
|
Original Version, by changing formats or by porting the Font Software to a
|
||||||
|
new environment.
|
||||||
|
|
||||||
|
"Author" refers to any designer, engineer, programmer, technical
|
||||||
|
writer or other person who contributed to the Font Software.
|
||||||
|
|
||||||
|
PERMISSION & CONDITIONS
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining
|
||||||
|
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||||
|
redistribute, and sell modified and unmodified copies of the Font
|
||||||
|
Software, subject to the following conditions:
|
||||||
|
|
||||||
|
1) Neither the Font Software nor any of its individual components,
|
||||||
|
in Original or Modified Versions, may be sold by itself.
|
||||||
|
|
||||||
|
2) Original or Modified Versions of the Font Software may be bundled,
|
||||||
|
redistributed and/or sold with any software, provided that each copy
|
||||||
|
contains the above copyright notice and this license. These can be
|
||||||
|
included either as stand-alone text files, human-readable headers or
|
||||||
|
in the appropriate machine-readable metadata fields within text or
|
||||||
|
binary files as long as those fields can be easily viewed by the user.
|
||||||
|
|
||||||
|
3) No Modified Version of the Font Software may use the Reserved Font
|
||||||
|
Name(s) unless explicit written permission is granted by the corresponding
|
||||||
|
Copyright Holder. This restriction only applies to the primary font name as
|
||||||
|
presented to the users.
|
||||||
|
|
||||||
|
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||||
|
Software shall not be used to promote, endorse or advertise any
|
||||||
|
Modified Version, except to acknowledge the contribution(s) of the
|
||||||
|
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||||
|
permission.
|
||||||
|
|
||||||
|
5) The Font Software, modified or unmodified, in part or in whole,
|
||||||
|
must be distributed entirely under this license, and must not be
|
||||||
|
distributed under any other license. The requirement for fonts to
|
||||||
|
remain under this license does not apply to any document created
|
||||||
|
using the Font Software.
|
||||||
|
|
||||||
|
TERMINATION
|
||||||
|
This license becomes null and void if any of the above conditions are
|
||||||
|
not met.
|
||||||
|
|
||||||
|
DISCLAIMER
|
||||||
|
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||||
|
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||||
|
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||||
|
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||||
|
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||||
|
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||||
|
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||||
|
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||||
|
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||||
BIN
docs/screenshots/desktop-account.png
Normal file
BIN
docs/screenshots/desktop-account.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 88 KiB |
BIN
docs/screenshots/desktop-payment-dark.png
Normal file
BIN
docs/screenshots/desktop-payment-dark.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 88 KiB |
BIN
docs/screenshots/phone-account.png
Normal file
BIN
docs/screenshots/phone-account.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 89 KiB |
BIN
docs/screenshots/phone-accounts.png
Normal file
BIN
docs/screenshots/phone-accounts.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 74 KiB |
BIN
docs/screenshots/phone-pay.png
Normal file
BIN
docs/screenshots/phone-pay.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 51 KiB |
55
docs/screenshots/take.sh
Executable file
55
docs/screenshots/take.sh
Executable file
|
|
@ -0,0 +1,55 @@
|
||||||
|
#!/bin/sh
|
||||||
|
# SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
# SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
#
|
||||||
|
# Takes the README's screenshots again: the app on the made-up system (tests/FakeSystem), so that nobody's bank is in
|
||||||
|
# them.
|
||||||
|
#
|
||||||
|
# take.sh <nostro-fake-system> <nostro-app> [the directory to write them to; this one when left out]
|
||||||
|
#
|
||||||
|
# The two programs are what crafter-build makes of --product=fake-system and of --product=app. Run this where they run,
|
||||||
|
# in a session with a compositor: every shot shows the window for a few seconds. For a build made in crafter-build's
|
||||||
|
# Flatpak that is inside it, and kept off the real system bus:
|
||||||
|
# flatpak run --nosocket=system-bus --command=sh net.catcrafts.CrafterBuild docs/screenshots/take.sh <the two programs>
|
||||||
|
#
|
||||||
|
# What a --poke script taps is named by its place in dp, which holds at any --scale and moves with the layout: when a
|
||||||
|
# screen is laid out anew, look at what was shot and change the numbers to match. Before each shot the pointer is put on
|
||||||
|
# the bar's title, where it lights nothing up. The made-up bank dates its payments back from now, so the days and times
|
||||||
|
# in a shot are the day's it was taken on.
|
||||||
|
#
|
||||||
|
# The files kept in the repository were then made smaller, their pixels unchanged:
|
||||||
|
# magick mogrify -strip -alpha off -define png:compression-level=9 -define png:compression-filter=5 *.png
|
||||||
|
set -eu
|
||||||
|
usage='usage: take.sh <nostro-fake-system> <nostro-app> [directory]'
|
||||||
|
fake=${1:?$usage}
|
||||||
|
app=${2:?$usage}
|
||||||
|
out=$(cd "${3:-$(dirname "$0")}" && pwd)
|
||||||
|
state=$(mktemp -d)
|
||||||
|
trap 'rm -rf "$state"' EXIT
|
||||||
|
|
||||||
|
# The made-up user's current account, which has three months of payments, and a friend of theirs at the same bank.
|
||||||
|
account=NL54BUNQ2100000011
|
||||||
|
friend=NL36BUNQ2100000044
|
||||||
|
# A phone's screen, and a window wide enough for the places and the accounts down its side.
|
||||||
|
phone='--size 360x760 --scale 2'
|
||||||
|
desktop='--size 1200x750 --scale 1.5'
|
||||||
|
|
||||||
|
# shot <name> <the app's options> <the steps before the shot>: one run of the app on a made-up system of its own. The
|
||||||
|
# app ends when its script has been played.
|
||||||
|
shot() {
|
||||||
|
rm -f "$out/$1.png"
|
||||||
|
# The options are words, split here on purpose.
|
||||||
|
# shellcheck disable=SC2086
|
||||||
|
"$fake" --dir "$state/$1" --run "$app" $2 --poke "wait:3500;$3;wait:300;shot:$out/$1.png;wait:500"
|
||||||
|
[ -s "$out/$1.png" ] || { echo "take.sh: $1.png was not written" >&2; exit 1; }
|
||||||
|
}
|
||||||
|
|
||||||
|
# Four in the dark look and one in the light one.
|
||||||
|
shot phone-accounts "$phone --theme dark --route accounts" "move:180,28"
|
||||||
|
shot phone-account "$phone --theme dark --route account:$account" "move:180,28"
|
||||||
|
# The pay form, gone into by the account's Pay and filled in from its To down.
|
||||||
|
shot phone-pay "$phone --theme dark --route account:$account" "tap:95,200;wait:600;tap:180,224;text:$friend;key:Tab;text:Nora White;key:Tab;text:12.50;key:Tab;text:Dinner;move:180,28"
|
||||||
|
shot desktop-account "$desktop --theme light --route account:$account" "move:700,28"
|
||||||
|
# A payment's details: the friend's payments searched for, and the first of them opened.
|
||||||
|
shot desktop-payment-dark "$desktop --theme dark --route account:$account" "tap:740,320;text:Nora;wait:700;tap:740,470;wait:700;move:740,28"
|
||||||
|
echo "take.sh: five screenshots in $out"
|
||||||
|
|
@ -84,6 +84,10 @@ void Account::SaveTransactions(std::string_view connector, std::vector<Transacti
|
||||||
return transaction.timePoint < last || (transaction.timePoint == last && (unmatchable || transaction.id.empty() || std::ranges::contains(known, transaction.id)));
|
return transaction.timePoint < last || (transaction.timePoint == last && (unmatchable || transaction.id.empty() || std::ranges::contains(known, transaction.id)));
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Nothing new is what most syncs bring, and a flush syncs the file to disk whether anything was written or not.
|
||||||
|
if(transactions.empty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
table.Append(std::span<const Transaction>(transactions));
|
table.Append(std::span<const Transaction>(transactions));
|
||||||
table.Flush();
|
table.Flush();
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -231,6 +231,12 @@ void BunqSchedule::Check() const {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
std::string BunqSchedule::UnitFromWord(std::string_view word) {
|
||||||
|
std::string unit(word);
|
||||||
|
std::ranges::transform(unit, unit.begin(), [](char c) { return static_cast<char>(std::toupper(static_cast<std::uint8_t>(c))); });
|
||||||
|
return unit;
|
||||||
|
}
|
||||||
|
|
||||||
std::uint64_t BunqAccount::Schedule(std::string_view to, std::string_view name, std::int64_t amount, Currency currency, std::string_view description, const BunqSchedule& schedule) const {
|
std::uint64_t BunqAccount::Schedule(std::string_view to, std::string_view name, std::int64_t amount, Currency currency, std::string_view description, const BunqSchedule& schedule) const {
|
||||||
schedule.Check();
|
schedule.Check();
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -27,7 +27,7 @@ std::deque<BunqConnector> BunqConnector::connectors;
|
||||||
|
|
||||||
namespace {
|
namespace {
|
||||||
constexpr std::string_view userAgent = "Nostro";
|
constexpr std::string_view userAgent = "Nostro";
|
||||||
constexpr std::string_view maybeCarriedOut = "; the request may have been carried out, check before trying again";
|
constexpr std::string_view maybeCarriedOut = BunqError::maybeCarriedOut;
|
||||||
|
|
||||||
// Where BunqConnector::RedirectTo sends everything.
|
// Where BunqConnector::RedirectTo sends everything.
|
||||||
std::optional<BunqEndpoint>& Redirected() {
|
std::optional<BunqEndpoint>& Redirected() {
|
||||||
|
|
@ -424,6 +424,21 @@ std::string BunqConnector::OAuthAuthorizationUrl(BunqEnvironment environment, st
|
||||||
return std::format("https://{}/auth?response_type=code&client_id={}&redirect_uri={}&state={}", environment == BunqEnvironment::Production ? "oauth.bunq.com" : "oauth.sandbox.bunq.com", UrlEncode(clientId), UrlEncode(redirectUri), UrlEncode(state));
|
return std::format("https://{}/auth?response_type=code&client_id={}&redirect_uri={}&state={}", environment == BunqEnvironment::Production ? "oauth.bunq.com" : "oauth.sandbox.bunq.com", UrlEncode(clientId), UrlEncode(redirectUri), UrlEncode(state));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
std::string BunqConnector::OAuthCodeFromRedirect(std::string_view redirected, std::string_view state) {
|
||||||
|
if(const std::optional<std::string> error = QueryParameter(redirected, "error")) {
|
||||||
|
throw std::runtime_error(std::format("bunq did not authorize: {} {}", *error, QueryParameter(redirected, "error_description").value_or("")));
|
||||||
|
}
|
||||||
|
const std::optional<std::string> code = QueryParameter(redirected, "code");
|
||||||
|
if(!code || code->empty()) {
|
||||||
|
throw std::runtime_error("that address has no code= in it");
|
||||||
|
}
|
||||||
|
// `state` ties the redirect to this authorization.
|
||||||
|
if(QueryParameter(redirected, "state") != state) {
|
||||||
|
throw std::runtime_error("that address is not the answer to this authorization (its state differs): start again");
|
||||||
|
}
|
||||||
|
return *code;
|
||||||
|
}
|
||||||
|
|
||||||
BunqEndpoint BunqConnector::Endpoint(BunqEnvironment environment) {
|
BunqEndpoint BunqConnector::Endpoint(BunqEnvironment environment) {
|
||||||
return Redirected().value_or(BunqEndpoint{.host = environment == BunqEnvironment::Production ? "api.bunq.com" : "public-api.sandbox.bunq.com", .port = 443, .caPem = std::string()});
|
return Redirected().value_or(BunqEndpoint{.host = environment == BunqEnvironment::Production ? "api.bunq.com" : "public-api.sandbox.bunq.com", .port = 443, .caPem = std::string()});
|
||||||
}
|
}
|
||||||
|
|
@ -620,6 +635,27 @@ BunqCard BunqConnector::SetCardStatus(std::uint64_t card, std::string_view statu
|
||||||
throw std::runtime_error("bunq did not return the card it updated");
|
throw std::runtime_error("bunq did not return the card it updated");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
bool BunqCard::Virtual() const noexcept {
|
||||||
|
return orderStatus == "VIRTUAL_DELIVERY";
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string_view BunqCard::State() const noexcept {
|
||||||
|
// Gone for good is said of a virtual card as of any other; working or frozen is not said of it at all.
|
||||||
|
const bool undecided = status == "DEACTIVATED" || status == "ACTIVE";
|
||||||
|
return Virtual() && undecided ? std::string_view("VIRTUAL") : std::string_view(status);
|
||||||
|
}
|
||||||
|
|
||||||
|
void BunqCard::ExpectStatus(std::string_view wanted) const {
|
||||||
|
// A virtual card is DEACTIVATED before and after it is asked to freeze or to unfreeze: having the status that was
|
||||||
|
// asked for does not show that anything was done.
|
||||||
|
if(State() == "VIRTUAL" && (wanted == "ACTIVE" || wanted == "DEACTIVATED")) {
|
||||||
|
throw std::runtime_error(std::format("bunq left card {} as it was: it is a virtual card, which bunq does not freeze or unfreeze when asked. Do that in the bunq app", id));
|
||||||
|
}
|
||||||
|
if(status != wanted) {
|
||||||
|
throw std::runtime_error(std::format("bunq kept card {} {} (its order status is {}): a card can only be frozen or unfrozen once it has been activated", id, status, orderStatus));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
std::string BunqConnector::StorageKey() const {
|
std::string BunqConnector::StorageKey() const {
|
||||||
return std::format("{}/{}/{}", connectorId, environment == BunqEnvironment::Production ? "production" : "sandbox", id);
|
return std::format("{}/{}/{}", connectorId, environment == BunqEnvironment::Production ? "production" : "sandbox", id);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -515,6 +515,9 @@ void Bus::AppendQuery(sd_bus_message* message, const TransactionQuery& query) {
|
||||||
entry("to", "x", query.to);
|
entry("to", "x", query.to);
|
||||||
}
|
}
|
||||||
entry("limit", "t", static_cast<std::uint64_t>(query.limit));
|
entry("limit", "t", static_cast<std::uint64_t>(query.limit));
|
||||||
|
if(query.stored) {
|
||||||
|
entry("stored", "b", true);
|
||||||
|
}
|
||||||
Close(message);
|
Close(message);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -544,6 +547,10 @@ TransactionQuery Bus::ReadQuery(sd_bus_message* message) {
|
||||||
Enter(message, 'v', "t");
|
Enter(message, 'v', "t");
|
||||||
query.limit = Bus::Read<std::uint64_t>(message);
|
query.limit = Bus::Read<std::uint64_t>(message);
|
||||||
Leave(message);
|
Leave(message);
|
||||||
|
} else if(key == "stored") {
|
||||||
|
Enter(message, 'v', "b");
|
||||||
|
query.stored = Bus::Read<bool>(message);
|
||||||
|
Leave(message);
|
||||||
} else {
|
} else {
|
||||||
ThrowOnSdBus(sd_bus_message_skip(message, "v"), "skip an unknown query key");
|
ThrowOnSdBus(sd_bus_message_skip(message, "v"), "skip an unknown query key");
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -13,6 +13,7 @@ import :Account;
|
||||||
import :Bunq;
|
import :Bunq;
|
||||||
import :Currency;
|
import :Currency;
|
||||||
import :Transaction;
|
import :Transaction;
|
||||||
|
import :Utils;
|
||||||
|
|
||||||
using namespace Nostro;
|
using namespace Nostro;
|
||||||
using namespace Nostro::Bus;
|
using namespace Nostro::Bus;
|
||||||
|
|
@ -32,46 +33,149 @@ Client Client::System(std::chrono::seconds timeout) {
|
||||||
Client::Client(BusPtr bus) : bus(std::move(bus)) {
|
Client::Client(BusPtr bus) : bus(std::move(bus)) {
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void Client::Attach(sd_event* event) {
|
||||||
|
ThrowOnSdBus(sd_bus_attach_event(bus.get(), event, SD_EVENT_PRIORITY_NORMAL), "attach to an event loop");
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Client::Connected() const {
|
||||||
|
return sd_bus_is_open(bus.get()) > 0;
|
||||||
|
}
|
||||||
|
|
||||||
namespace {
|
namespace {
|
||||||
// nostrod's error, as an exception: input it refused as std::invalid_argument, the rest as a DaemonError.
|
// One method of nostrod's interface: its member, whether it changes anything (for what a lost answer means), and
|
||||||
|
// how its answer is read.
|
||||||
|
template<typename R>
|
||||||
|
struct MethodCall {
|
||||||
|
std::string_view member;
|
||||||
|
bool changes = false;
|
||||||
|
R (*read)(sd_bus_message*) = nullptr;
|
||||||
|
};
|
||||||
|
|
||||||
|
// What an asynchronous call keeps until its answer, freed with the call's slot.
|
||||||
|
struct Waiting {
|
||||||
|
bool answered = false;
|
||||||
|
virtual ~Waiting() = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
template<typename R>
|
||||||
|
struct WaitingFor : Waiting {
|
||||||
|
MethodCall<R> call;
|
||||||
|
Client::Then<R> then;
|
||||||
|
};
|
||||||
|
|
||||||
|
// nostrod's error, as an exception: input it refused as std::invalid_argument, the rest as a DaemonError, and what
|
||||||
|
// may or may not have happened as OutcomeUnknown.
|
||||||
[[noreturn]] void Throw(const sd_bus_error& error, bool changes) {
|
[[noreturn]] void Throw(const sd_bus_error& error, bool changes) {
|
||||||
const std::string name = ErrorName(error);
|
const std::string name = ErrorName(error);
|
||||||
const std::string message = ErrorMessage(error);
|
const std::string message = ErrorMessage(error);
|
||||||
if(name == SD_BUS_ERROR_SERVICE_UNKNOWN) {
|
if(name == SD_BUS_ERROR_SERVICE_UNKNOWN) {
|
||||||
throw std::runtime_error(std::format("nostrod is not running, and the system bus cannot start it: is it installed? ({})", message));
|
throw DaemonMissing(std::format("nostrod is not running, and the system bus cannot start it: is it installed? ({})", message));
|
||||||
}
|
}
|
||||||
if(name == errorInvalidArgument) {
|
if(name == errorInvalidArgument) {
|
||||||
throw std::invalid_argument(message);
|
throw std::invalid_argument(message);
|
||||||
}
|
}
|
||||||
if(changes && (name == SD_BUS_ERROR_NO_REPLY || name == SD_BUS_ERROR_TIMEOUT)) {
|
if(changes && (name == SD_BUS_ERROR_NO_REPLY || name == SD_BUS_ERROR_TIMEOUT)) {
|
||||||
throw std::runtime_error(std::format("nostrod did not answer in time ({}): what you asked for may have been carried out, check before trying again", message));
|
throw OutcomeUnknown(std::format("nostrod did not answer in time ({}): what you asked for may have been carried out, check before trying again", message));
|
||||||
|
}
|
||||||
|
// bunq's error to a write that may have gone through all the same says so at its end, as the checkout's
|
||||||
|
// published interface documents for net.catcrafts.Nostro1.Error.Bank.
|
||||||
|
if(changes && name == errorBank && message.ends_with(BunqError::maybeCarriedOut)) {
|
||||||
|
throw OutcomeUnknown(message);
|
||||||
}
|
}
|
||||||
throw DaemonError(name, message);
|
throw DaemonError(name, message);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Calls `member` with what `append` appends, reads the answer with `read`, and keeps the notes that end it.
|
std::exception_ptr ErrorOf(const sd_bus_error& error, bool changes) {
|
||||||
// `changes` says whether the call moves money or changes anything, for what a lost answer means.
|
try {
|
||||||
template<typename AppendArguments, typename ReadAnswer>
|
Throw(error, changes);
|
||||||
auto Call(sd_bus* bus, std::vector<std::string>& notes, std::string_view member, bool changes, AppendArguments&& append, ReadAnswer&& read) {
|
} catch(...) {
|
||||||
|
return std::current_exception();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
MessagePtr NewCall(sd_bus* bus, std::string_view member) {
|
||||||
sd_bus_message* raw = nullptr;
|
sd_bus_message* raw = nullptr;
|
||||||
ThrowOnSdBus(sd_bus_message_new_method_call(bus, &raw, busName.data(), objectPath.data(), interfaceName.data(), std::string(member).c_str()), "call nostrod");
|
ThrowOnSdBus(sd_bus_message_new_method_call(bus, &raw, busName.data(), objectPath.data(), interfaceName.data(), std::string(member).c_str()), "call nostrod");
|
||||||
const MessagePtr call(raw);
|
MessagePtr call(raw);
|
||||||
if(IsSensitive(member)) {
|
if(IsSensitive(member)) {
|
||||||
ThrowOnSdBus(sd_bus_message_sensitive(raw), "call nostrod");
|
ThrowOnSdBus(sd_bus_message_sensitive(raw), "call nostrod");
|
||||||
}
|
}
|
||||||
append(raw);
|
return call;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Calls `call` with what `append` appends and waits for the answer, keeping the notes that end it.
|
||||||
|
template<typename R, typename Append>
|
||||||
|
R Run(sd_bus* bus, std::vector<std::string>& notes, const MethodCall<R>& call, Append&& append) {
|
||||||
|
const MessagePtr message = NewCall(bus, call.member);
|
||||||
|
append(message.get());
|
||||||
Error error;
|
Error error;
|
||||||
sd_bus_message* answer = nullptr;
|
sd_bus_message* answer = nullptr;
|
||||||
if(sd_bus_call(bus, raw, 0, &error.error, &answer) < 0) {
|
if(sd_bus_call(bus, message.get(), 0, &error.error, &answer) < 0) {
|
||||||
Throw(error.error, changes);
|
Throw(error.error, call.changes);
|
||||||
}
|
}
|
||||||
const MessagePtr reply(answer);
|
const MessagePtr reply(answer);
|
||||||
auto result = read(answer);
|
R result = call.read(answer);
|
||||||
const std::vector<std::string> more = Read<std::vector<std::string>>(answer);
|
const std::vector<std::string> more = Read<std::vector<std::string>>(answer);
|
||||||
notes.insert(notes.end(), more.begin(), more.end());
|
notes.insert(notes.end(), more.begin(), more.end());
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
template<typename R>
|
||||||
|
Answer<R> Failure(std::exception_ptr error) {
|
||||||
|
return Answer<R>{std::variant<R, std::exception_ptr>(std::in_place_index<1>, std::move(error)), {}};
|
||||||
|
}
|
||||||
|
|
||||||
|
// An answer to an asynchronous call, read and handed to its `then`. It never throws: sd-bus calls it from C.
|
||||||
|
template<typename R>
|
||||||
|
std::int32_t OnReply(sd_bus_message* reply, void* userdata, sd_bus_error*) {
|
||||||
|
WaitingFor<R>& waiting = *static_cast<WaitingFor<R>*>(userdata);
|
||||||
|
waiting.answered = true;
|
||||||
|
Answer<R> answer = [&waiting, reply] {
|
||||||
|
try {
|
||||||
|
if(sd_bus_message_is_method_error(reply, nullptr)) {
|
||||||
|
return Failure<R>(ErrorOf(*sd_bus_message_get_error(reply), waiting.call.changes));
|
||||||
|
}
|
||||||
|
R result = waiting.call.read(reply);
|
||||||
|
std::vector<std::string> notes = Read<std::vector<std::string>>(reply);
|
||||||
|
return Answer<R>{std::variant<R, std::exception_ptr>(std::in_place_index<0>, std::move(result)), std::move(notes)};
|
||||||
|
} catch(...) {
|
||||||
|
return Failure<R>(std::current_exception());
|
||||||
|
}
|
||||||
|
}();
|
||||||
|
// sd-bus holds the slot while this runs, so `then` may cancel its own Pending.
|
||||||
|
try {
|
||||||
|
waiting.then(std::move(answer));
|
||||||
|
} catch(const std::exception& e) {
|
||||||
|
Note(std::format("nostrod's answer to {} could not be handled: {}", waiting.call.member, e.what()));
|
||||||
|
} catch(...) {
|
||||||
|
Note(std::format("nostrod's answer to {} could not be handled", waiting.call.member));
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
void DeleteWaiting(void* userdata) {
|
||||||
|
delete static_cast<Waiting*>(userdata);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sends `call` with what `append` appends, and returns the slot that waits for its answer.
|
||||||
|
template<typename R, typename Append>
|
||||||
|
sd_bus_slot* Start(sd_bus* bus, const MethodCall<R>& call, Append&& append, Client::Then<R>&& then) {
|
||||||
|
if(sd_bus_get_event(bus) == nullptr) {
|
||||||
|
throw std::logic_error(std::format("nostrod's {} was called to answer later, but the client is attached to no event loop: call Attach first", call.member));
|
||||||
|
}
|
||||||
|
const MessagePtr message = NewCall(bus, call.member);
|
||||||
|
append(message.get());
|
||||||
|
std::unique_ptr<WaitingFor<R>> waiting = std::make_unique<WaitingFor<R>>();
|
||||||
|
waiting->call = call;
|
||||||
|
waiting->then = std::move(then);
|
||||||
|
sd_bus_slot* slot = nullptr;
|
||||||
|
ThrowOnSdBus(sd_bus_call_async(bus, &slot, message.get(), OnReply<R>, waiting.get(), 0), "call nostrod");
|
||||||
|
// The slot frees what waits for the answer when it goes: once its Pending is destroyed or cancelled.
|
||||||
|
sd_bus_slot_set_destroy_callback(slot, DeleteWaiting);
|
||||||
|
waiting.release();
|
||||||
|
return slot;
|
||||||
|
}
|
||||||
|
|
||||||
void Nothing(sd_bus_message*) {
|
void Nothing(sd_bus_message*) {
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -95,6 +199,34 @@ namespace {
|
||||||
return created;
|
return created;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
template<typename T>
|
||||||
|
T ReadAs(sd_bus_message* reply) {
|
||||||
|
return Read<T>(reply);
|
||||||
|
}
|
||||||
|
|
||||||
|
constexpr MethodCall<std::vector<ConnectorSummary>> connectorsCall{"Connectors", false, ReadAs<std::vector<ConnectorSummary>>};
|
||||||
|
constexpr MethodCall<AddedConnector> addBunqCall{"AddBunq", true, ReadAdded};
|
||||||
|
constexpr MethodCall<AddedConnector> addBunqOAuthCall{"AddBunqOAuth", true, ReadAdded};
|
||||||
|
constexpr MethodCall<std::string> removeConnectorCall{"RemoveConnector", true, ReadAs<std::string>};
|
||||||
|
constexpr MethodCall<std::vector<ConnectorAccounts>> accountsCall{"Accounts", false, ReadAs<std::vector<ConnectorAccounts>>};
|
||||||
|
constexpr MethodCall<std::vector<Transaction>> transactionsCall{"Transactions", false, ReadAs<std::vector<Transaction>>};
|
||||||
|
constexpr MethodCall<Created> sendCall{"Send", true, ReadCreated};
|
||||||
|
constexpr MethodCall<Created> scheduleCall{"Schedule", true, ReadCreated};
|
||||||
|
constexpr MethodCall<Created> draftCall{"Draft", true, ReadCreated};
|
||||||
|
constexpr MethodCall<BunqPaymentRequest> requestCall{"Request", true, ReadAs<BunqPaymentRequest>};
|
||||||
|
constexpr MethodCall<std::vector<BunqPaymentRequest>> requestsCall{"Requests", false, ReadAs<std::vector<BunqPaymentRequest>>};
|
||||||
|
constexpr MethodCall<std::monostate> revokeRequestCall{"RevokeRequest", true, NoAnswer};
|
||||||
|
constexpr MethodCall<std::vector<BunqIncomingRequest>> incomingRequestsCall{"IncomingRequests", false, ReadAs<std::vector<BunqIncomingRequest>>};
|
||||||
|
constexpr MethodCall<std::monostate> respondToRequestCall{"RespondToRequest", true, NoAnswer};
|
||||||
|
constexpr MethodCall<std::vector<BunqScheduledPayment>> scheduledPaymentsCall{"ScheduledPayments", false, ReadAs<std::vector<BunqScheduledPayment>>};
|
||||||
|
constexpr MethodCall<std::monostate> cancelScheduledPaymentCall{"CancelScheduledPayment", true, NoAnswer};
|
||||||
|
constexpr MethodCall<std::vector<BunqDraftPayment>> draftPaymentsCall{"DraftPayments", false, ReadAs<std::vector<BunqDraftPayment>>};
|
||||||
|
constexpr MethodCall<std::monostate> respondToDraftPaymentCall{"RespondToDraftPayment", true, NoAnswer};
|
||||||
|
constexpr MethodCall<std::vector<ConnectorCards>> cardsCall{"Cards", false, ReadAs<std::vector<ConnectorCards>>};
|
||||||
|
constexpr MethodCall<BunqCard> setCardStatusCall{"SetCardStatus", true, ReadAs<BunqCard>};
|
||||||
|
constexpr MethodCall<std::optional<Account>> defaultCheckoutAccountCall{"DefaultCheckoutAccount", false, ReadAs<std::optional<Account>>};
|
||||||
|
constexpr MethodCall<Account> setDefaultCheckoutAccountCall{"SetDefaultCheckoutAccount", true, ReadAs<Account>};
|
||||||
|
|
||||||
// The arguments a payment, a draft, a schedule and a request share.
|
// The arguments a payment, a draft, a schedule and a request share.
|
||||||
auto PaymentArguments(std::string_view account, std::string_view counterparty, std::string_view name, std::int64_t amount, std::string_view description) {
|
auto PaymentArguments(std::string_view account, std::string_view counterparty, std::string_view name, std::int64_t amount, std::string_view description) {
|
||||||
return [=](sd_bus_message* call) {
|
return [=](sd_bus_message* call) {
|
||||||
|
|
@ -106,6 +238,13 @@ namespace {
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
auto ScheduleArguments(std::string_view account, std::string_view to, std::string_view name, std::int64_t amount, std::string_view description, const BunqSchedule& schedule) {
|
||||||
|
return [payment = PaymentArguments(account, to, name, amount, description), &schedule](sd_bus_message* call) {
|
||||||
|
payment(call);
|
||||||
|
Append(call, schedule);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
auto AccountArgument(std::string_view account) {
|
auto AccountArgument(std::string_view account) {
|
||||||
return [account](sd_bus_message* call) {
|
return [account](sd_bus_message* call) {
|
||||||
Append(call, std::string(account));
|
Append(call, std::string(account));
|
||||||
|
|
@ -119,126 +258,247 @@ namespace {
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
template<typename T>
|
auto ResponseArguments(std::string_view account, std::uint64_t id, bool accept) {
|
||||||
T ReadAs(sd_bus_message* reply) {
|
return [account, id, accept](sd_bus_message* call) {
|
||||||
return Read<T>(reply);
|
Append(call, std::string(account));
|
||||||
|
Append(call, id);
|
||||||
|
Append(call, accept);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
auto BunqKeyArguments(std::string_view apiKey, std::string_view allowedIps, std::string_view environment) {
|
||||||
|
return [=](sd_bus_message* call) {
|
||||||
|
Append(call, std::string(apiKey));
|
||||||
|
Append(call, std::string(allowedIps));
|
||||||
|
Append(call, std::string(environment));
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
auto OAuthArguments(std::string_view environment, std::string_view clientId, std::string_view clientSecret, std::string_view redirectUri, std::string_view code) {
|
||||||
|
return [=](sd_bus_message* call) {
|
||||||
|
Append(call, std::string(environment));
|
||||||
|
Append(call, std::string(clientId));
|
||||||
|
Append(call, std::string(clientSecret));
|
||||||
|
Append(call, std::string(redirectUri));
|
||||||
|
Append(call, std::string(code));
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
auto TransactionArguments(std::string_view account, const TransactionQuery& query) {
|
||||||
|
return [account, &query](sd_bus_message* call) {
|
||||||
|
Append(call, std::string(account));
|
||||||
|
AppendQuery(call, query);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
auto CardArguments(std::uint64_t card, std::string_view status) {
|
||||||
|
return [card, status](sd_bus_message* call) {
|
||||||
|
Append(call, card);
|
||||||
|
Append(call, std::string(status));
|
||||||
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Client::Pending::Pending(sd_bus_slot* slot) : slot(slot) {
|
||||||
|
}
|
||||||
|
|
||||||
|
Client::Pending::Pending(Pending&& other) noexcept : slot(std::exchange(other.slot, nullptr)) {
|
||||||
|
}
|
||||||
|
|
||||||
|
Client::Pending& Client::Pending::operator=(Pending&& other) noexcept {
|
||||||
|
// What this waited for is dropped with `moved`.
|
||||||
|
Pending moved(std::move(other));
|
||||||
|
std::swap(slot, moved.slot);
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
|
||||||
|
Client::Pending::~Pending() {
|
||||||
|
Cancel();
|
||||||
|
}
|
||||||
|
|
||||||
|
void Client::Pending::Cancel() {
|
||||||
|
// Freeing the slot takes the answer's callback off the bus, and frees what waited for it.
|
||||||
|
slot = sd_bus_slot_unref(slot);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Client::Pending::Active() const {
|
||||||
|
return slot != nullptr && !static_cast<const Waiting*>(sd_bus_slot_get_userdata(slot))->answered;
|
||||||
|
}
|
||||||
|
|
||||||
std::vector<ConnectorSummary> Client::Connectors() {
|
std::vector<ConnectorSummary> Client::Connectors() {
|
||||||
return Call(bus.get(), notes, "Connectors", false, Nothing, ReadAs<std::vector<ConnectorSummary>>);
|
return Run(bus.get(), notes, connectorsCall, Nothing);
|
||||||
|
}
|
||||||
|
|
||||||
|
Client::Pending Client::Connectors(Then<std::vector<ConnectorSummary>> then) {
|
||||||
|
return Pending(Start(bus.get(), connectorsCall, Nothing, std::move(then)));
|
||||||
}
|
}
|
||||||
|
|
||||||
AddedConnector Client::AddBunq(std::string_view apiKey, std::string_view allowedIps, std::string_view environment) {
|
AddedConnector Client::AddBunq(std::string_view apiKey, std::string_view allowedIps, std::string_view environment) {
|
||||||
return Call(bus.get(), notes, "AddBunq", true, [=](sd_bus_message* call) {
|
return Run(bus.get(), notes, addBunqCall, BunqKeyArguments(apiKey, allowedIps, environment));
|
||||||
Append(call, std::string(apiKey));
|
}
|
||||||
Append(call, std::string(allowedIps));
|
|
||||||
Append(call, std::string(environment));
|
Client::Pending Client::AddBunq(std::string_view apiKey, std::string_view allowedIps, std::string_view environment, Then<AddedConnector> then) {
|
||||||
}, ReadAdded);
|
return Pending(Start(bus.get(), addBunqCall, BunqKeyArguments(apiKey, allowedIps, environment), std::move(then)));
|
||||||
}
|
}
|
||||||
|
|
||||||
AddedConnector Client::AddBunqOAuth(std::string_view environment, std::string_view clientId, std::string_view clientSecret, std::string_view redirectUri, std::string_view code) {
|
AddedConnector Client::AddBunqOAuth(std::string_view environment, std::string_view clientId, std::string_view clientSecret, std::string_view redirectUri, std::string_view code) {
|
||||||
return Call(bus.get(), notes, "AddBunqOAuth", true, [=](sd_bus_message* call) {
|
return Run(bus.get(), notes, addBunqOAuthCall, OAuthArguments(environment, clientId, clientSecret, redirectUri, code));
|
||||||
Append(call, std::string(environment));
|
}
|
||||||
Append(call, std::string(clientId));
|
|
||||||
Append(call, std::string(clientSecret));
|
Client::Pending Client::AddBunqOAuth(std::string_view environment, std::string_view clientId, std::string_view clientSecret, std::string_view redirectUri, std::string_view code, Then<AddedConnector> then) {
|
||||||
Append(call, std::string(redirectUri));
|
return Pending(Start(bus.get(), addBunqOAuthCall, OAuthArguments(environment, clientId, clientSecret, redirectUri, code), std::move(then)));
|
||||||
Append(call, std::string(code));
|
|
||||||
}, ReadAdded);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
std::string Client::RemoveConnector(std::string_view connector) {
|
std::string Client::RemoveConnector(std::string_view connector) {
|
||||||
return Call(bus.get(), notes, "RemoveConnector", true, AccountArgument(connector), ReadAs<std::string>);
|
return Run(bus.get(), notes, removeConnectorCall, AccountArgument(connector));
|
||||||
|
}
|
||||||
|
|
||||||
|
Client::Pending Client::RemoveConnector(std::string_view connector, Then<std::string> then) {
|
||||||
|
return Pending(Start(bus.get(), removeConnectorCall, AccountArgument(connector), std::move(then)));
|
||||||
}
|
}
|
||||||
|
|
||||||
std::vector<ConnectorAccounts> Client::Accounts() {
|
std::vector<ConnectorAccounts> Client::Accounts() {
|
||||||
return Call(bus.get(), notes, "Accounts", false, Nothing, ReadAs<std::vector<ConnectorAccounts>>);
|
return Run(bus.get(), notes, accountsCall, Nothing);
|
||||||
|
}
|
||||||
|
|
||||||
|
Client::Pending Client::Accounts(Then<std::vector<ConnectorAccounts>> then) {
|
||||||
|
return Pending(Start(bus.get(), accountsCall, Nothing, std::move(then)));
|
||||||
}
|
}
|
||||||
|
|
||||||
std::vector<Transaction> Client::Transactions(std::string_view account, const TransactionQuery& query) {
|
std::vector<Transaction> Client::Transactions(std::string_view account, const TransactionQuery& query) {
|
||||||
return Call(bus.get(), notes, "Transactions", false, [account, &query](sd_bus_message* call) {
|
return Run(bus.get(), notes, transactionsCall, TransactionArguments(account, query));
|
||||||
Append(call, std::string(account));
|
}
|
||||||
AppendQuery(call, query);
|
|
||||||
}, ReadAs<std::vector<Transaction>>);
|
Client::Pending Client::Transactions(std::string_view account, const TransactionQuery& query, Then<std::vector<Transaction>> then) {
|
||||||
|
return Pending(Start(bus.get(), transactionsCall, TransactionArguments(account, query), std::move(then)));
|
||||||
}
|
}
|
||||||
|
|
||||||
Created Client::Send(std::string_view account, std::string_view to, std::string_view name, std::int64_t amount, std::string_view description) {
|
Created Client::Send(std::string_view account, std::string_view to, std::string_view name, std::int64_t amount, std::string_view description) {
|
||||||
return Call(bus.get(), notes, "Send", true, PaymentArguments(account, to, name, amount, description), ReadCreated);
|
return Run(bus.get(), notes, sendCall, PaymentArguments(account, to, name, amount, description));
|
||||||
|
}
|
||||||
|
|
||||||
|
Client::Pending Client::Send(std::string_view account, std::string_view to, std::string_view name, std::int64_t amount, std::string_view description, Then<Created> then) {
|
||||||
|
return Pending(Start(bus.get(), sendCall, PaymentArguments(account, to, name, amount, description), std::move(then)));
|
||||||
}
|
}
|
||||||
|
|
||||||
Created Client::Schedule(std::string_view account, std::string_view to, std::string_view name, std::int64_t amount, std::string_view description, const BunqSchedule& schedule) {
|
Created Client::Schedule(std::string_view account, std::string_view to, std::string_view name, std::int64_t amount, std::string_view description, const BunqSchedule& schedule) {
|
||||||
const auto payment = PaymentArguments(account, to, name, amount, description);
|
return Run(bus.get(), notes, scheduleCall, ScheduleArguments(account, to, name, amount, description, schedule));
|
||||||
return Call(bus.get(), notes, "Schedule", true, [&payment, &schedule](sd_bus_message* call) {
|
}
|
||||||
payment(call);
|
|
||||||
Append(call, schedule);
|
Client::Pending Client::Schedule(std::string_view account, std::string_view to, std::string_view name, std::int64_t amount, std::string_view description, const BunqSchedule& schedule, Then<Created> then) {
|
||||||
}, ReadCreated);
|
return Pending(Start(bus.get(), scheduleCall, ScheduleArguments(account, to, name, amount, description, schedule), std::move(then)));
|
||||||
}
|
}
|
||||||
|
|
||||||
Created Client::Draft(std::string_view account, std::string_view to, std::string_view name, std::int64_t amount, std::string_view description) {
|
Created Client::Draft(std::string_view account, std::string_view to, std::string_view name, std::int64_t amount, std::string_view description) {
|
||||||
return Call(bus.get(), notes, "Draft", true, PaymentArguments(account, to, name, amount, description), ReadCreated);
|
return Run(bus.get(), notes, draftCall, PaymentArguments(account, to, name, amount, description));
|
||||||
|
}
|
||||||
|
|
||||||
|
Client::Pending Client::Draft(std::string_view account, std::string_view to, std::string_view name, std::int64_t amount, std::string_view description, Then<Created> then) {
|
||||||
|
return Pending(Start(bus.get(), draftCall, PaymentArguments(account, to, name, amount, description), std::move(then)));
|
||||||
}
|
}
|
||||||
|
|
||||||
BunqPaymentRequest Client::Request(std::string_view account, std::string_view from, std::string_view name, std::int64_t amount, std::string_view description) {
|
BunqPaymentRequest Client::Request(std::string_view account, std::string_view from, std::string_view name, std::int64_t amount, std::string_view description) {
|
||||||
return Call(bus.get(), notes, "Request", true, PaymentArguments(account, from, name, amount, description), ReadAs<BunqPaymentRequest>);
|
return Run(bus.get(), notes, requestCall, PaymentArguments(account, from, name, amount, description));
|
||||||
|
}
|
||||||
|
|
||||||
|
Client::Pending Client::Request(std::string_view account, std::string_view from, std::string_view name, std::int64_t amount, std::string_view description, Then<BunqPaymentRequest> then) {
|
||||||
|
return Pending(Start(bus.get(), requestCall, PaymentArguments(account, from, name, amount, description), std::move(then)));
|
||||||
}
|
}
|
||||||
|
|
||||||
std::vector<BunqPaymentRequest> Client::Requests(std::string_view account) {
|
std::vector<BunqPaymentRequest> Client::Requests(std::string_view account) {
|
||||||
return Call(bus.get(), notes, "Requests", false, AccountArgument(account), ReadAs<std::vector<BunqPaymentRequest>>);
|
return Run(bus.get(), notes, requestsCall, AccountArgument(account));
|
||||||
|
}
|
||||||
|
|
||||||
|
Client::Pending Client::Requests(std::string_view account, Then<std::vector<BunqPaymentRequest>> then) {
|
||||||
|
return Pending(Start(bus.get(), requestsCall, AccountArgument(account), std::move(then)));
|
||||||
}
|
}
|
||||||
|
|
||||||
void Client::RevokeRequest(std::string_view account, std::uint64_t id) {
|
void Client::RevokeRequest(std::string_view account, std::uint64_t id) {
|
||||||
Call(bus.get(), notes, "RevokeRequest", true, AccountAndId(account, id), NoAnswer);
|
Run(bus.get(), notes, revokeRequestCall, AccountAndId(account, id));
|
||||||
|
}
|
||||||
|
|
||||||
|
Client::Pending Client::RevokeRequest(std::string_view account, std::uint64_t id, Then<std::monostate> then) {
|
||||||
|
return Pending(Start(bus.get(), revokeRequestCall, AccountAndId(account, id), std::move(then)));
|
||||||
}
|
}
|
||||||
|
|
||||||
std::vector<BunqIncomingRequest> Client::IncomingRequests(std::string_view account) {
|
std::vector<BunqIncomingRequest> Client::IncomingRequests(std::string_view account) {
|
||||||
return Call(bus.get(), notes, "IncomingRequests", false, AccountArgument(account), ReadAs<std::vector<BunqIncomingRequest>>);
|
return Run(bus.get(), notes, incomingRequestsCall, AccountArgument(account));
|
||||||
|
}
|
||||||
|
|
||||||
|
Client::Pending Client::IncomingRequests(std::string_view account, Then<std::vector<BunqIncomingRequest>> then) {
|
||||||
|
return Pending(Start(bus.get(), incomingRequestsCall, AccountArgument(account), std::move(then)));
|
||||||
}
|
}
|
||||||
|
|
||||||
void Client::RespondToRequest(std::string_view account, std::uint64_t id, bool accept) {
|
void Client::RespondToRequest(std::string_view account, std::uint64_t id, bool accept) {
|
||||||
Call(bus.get(), notes, "RespondToRequest", true, [account, id, accept](sd_bus_message* call) {
|
Run(bus.get(), notes, respondToRequestCall, ResponseArguments(account, id, accept));
|
||||||
Append(call, std::string(account));
|
}
|
||||||
Append(call, id);
|
|
||||||
Append(call, accept);
|
Client::Pending Client::RespondToRequest(std::string_view account, std::uint64_t id, bool accept, Then<std::monostate> then) {
|
||||||
}, NoAnswer);
|
return Pending(Start(bus.get(), respondToRequestCall, ResponseArguments(account, id, accept), std::move(then)));
|
||||||
}
|
}
|
||||||
|
|
||||||
std::vector<BunqScheduledPayment> Client::ScheduledPayments(std::string_view account) {
|
std::vector<BunqScheduledPayment> Client::ScheduledPayments(std::string_view account) {
|
||||||
return Call(bus.get(), notes, "ScheduledPayments", false, AccountArgument(account), ReadAs<std::vector<BunqScheduledPayment>>);
|
return Run(bus.get(), notes, scheduledPaymentsCall, AccountArgument(account));
|
||||||
|
}
|
||||||
|
|
||||||
|
Client::Pending Client::ScheduledPayments(std::string_view account, Then<std::vector<BunqScheduledPayment>> then) {
|
||||||
|
return Pending(Start(bus.get(), scheduledPaymentsCall, AccountArgument(account), std::move(then)));
|
||||||
}
|
}
|
||||||
|
|
||||||
void Client::CancelScheduledPayment(std::string_view account, std::uint64_t id) {
|
void Client::CancelScheduledPayment(std::string_view account, std::uint64_t id) {
|
||||||
Call(bus.get(), notes, "CancelScheduledPayment", true, AccountAndId(account, id), NoAnswer);
|
Run(bus.get(), notes, cancelScheduledPaymentCall, AccountAndId(account, id));
|
||||||
|
}
|
||||||
|
|
||||||
|
Client::Pending Client::CancelScheduledPayment(std::string_view account, std::uint64_t id, Then<std::monostate> then) {
|
||||||
|
return Pending(Start(bus.get(), cancelScheduledPaymentCall, AccountAndId(account, id), std::move(then)));
|
||||||
}
|
}
|
||||||
|
|
||||||
std::vector<BunqDraftPayment> Client::DraftPayments(std::string_view account) {
|
std::vector<BunqDraftPayment> Client::DraftPayments(std::string_view account) {
|
||||||
return Call(bus.get(), notes, "DraftPayments", false, AccountArgument(account), ReadAs<std::vector<BunqDraftPayment>>);
|
return Run(bus.get(), notes, draftPaymentsCall, AccountArgument(account));
|
||||||
|
}
|
||||||
|
|
||||||
|
Client::Pending Client::DraftPayments(std::string_view account, Then<std::vector<BunqDraftPayment>> then) {
|
||||||
|
return Pending(Start(bus.get(), draftPaymentsCall, AccountArgument(account), std::move(then)));
|
||||||
}
|
}
|
||||||
|
|
||||||
void Client::RespondToDraftPayment(std::string_view account, std::uint64_t id, bool accept) {
|
void Client::RespondToDraftPayment(std::string_view account, std::uint64_t id, bool accept) {
|
||||||
Call(bus.get(), notes, "RespondToDraftPayment", true, [account, id, accept](sd_bus_message* call) {
|
Run(bus.get(), notes, respondToDraftPaymentCall, ResponseArguments(account, id, accept));
|
||||||
Append(call, std::string(account));
|
}
|
||||||
Append(call, id);
|
|
||||||
Append(call, accept);
|
Client::Pending Client::RespondToDraftPayment(std::string_view account, std::uint64_t id, bool accept, Then<std::monostate> then) {
|
||||||
}, NoAnswer);
|
return Pending(Start(bus.get(), respondToDraftPaymentCall, ResponseArguments(account, id, accept), std::move(then)));
|
||||||
}
|
}
|
||||||
|
|
||||||
std::vector<ConnectorCards> Client::Cards() {
|
std::vector<ConnectorCards> Client::Cards() {
|
||||||
return Call(bus.get(), notes, "Cards", false, Nothing, ReadAs<std::vector<ConnectorCards>>);
|
return Run(bus.get(), notes, cardsCall, Nothing);
|
||||||
|
}
|
||||||
|
|
||||||
|
Client::Pending Client::Cards(Then<std::vector<ConnectorCards>> then) {
|
||||||
|
return Pending(Start(bus.get(), cardsCall, Nothing, std::move(then)));
|
||||||
}
|
}
|
||||||
|
|
||||||
BunqCard Client::SetCardStatus(std::uint64_t card, std::string_view status) {
|
BunqCard Client::SetCardStatus(std::uint64_t card, std::string_view status) {
|
||||||
return Call(bus.get(), notes, "SetCardStatus", true, [card, status](sd_bus_message* call) {
|
return Run(bus.get(), notes, setCardStatusCall, CardArguments(card, status));
|
||||||
Append(call, card);
|
}
|
||||||
Append(call, std::string(status));
|
|
||||||
}, ReadAs<BunqCard>);
|
Client::Pending Client::SetCardStatus(std::uint64_t card, std::string_view status, Then<BunqCard> then) {
|
||||||
|
return Pending(Start(bus.get(), setCardStatusCall, CardArguments(card, status), std::move(then)));
|
||||||
}
|
}
|
||||||
|
|
||||||
std::optional<Account> Client::DefaultCheckoutAccount() {
|
std::optional<Account> Client::DefaultCheckoutAccount() {
|
||||||
return Call(bus.get(), notes, "DefaultCheckoutAccount", false, Nothing, ReadAs<std::optional<Account>>);
|
return Run(bus.get(), notes, defaultCheckoutAccountCall, Nothing);
|
||||||
|
}
|
||||||
|
|
||||||
|
Client::Pending Client::DefaultCheckoutAccount(Then<std::optional<Account>> then) {
|
||||||
|
return Pending(Start(bus.get(), defaultCheckoutAccountCall, Nothing, std::move(then)));
|
||||||
}
|
}
|
||||||
|
|
||||||
Account Client::SetDefaultCheckoutAccount(std::string_view account) {
|
Account Client::SetDefaultCheckoutAccount(std::string_view account) {
|
||||||
return Call(bus.get(), notes, "SetDefaultCheckoutAccount", true, AccountArgument(account), ReadAs<Account>);
|
return Run(bus.get(), notes, setDefaultCheckoutAccountCall, AccountArgument(account));
|
||||||
|
}
|
||||||
|
|
||||||
|
Client::Pending Client::SetDefaultCheckoutAccount(std::string_view account, Then<Account> then) {
|
||||||
|
return Pending(Start(bus.get(), setDefaultCheckoutAccountCall, AccountArgument(account), std::move(then)));
|
||||||
}
|
}
|
||||||
|
|
||||||
std::vector<std::string> Client::TakeNotes() {
|
std::vector<std::string> Client::TakeNotes() {
|
||||||
|
|
|
||||||
|
|
@ -520,7 +520,13 @@ namespace {
|
||||||
std::string apiKey = Read<std::string>(call);
|
std::string apiKey = Read<std::string>(call);
|
||||||
std::string allowedIps = Read<std::string>(call);
|
std::string allowedIps = Read<std::string>(call);
|
||||||
const std::string requested = Read<std::string>(call);
|
const std::string requested = Read<std::string>(call);
|
||||||
const BunqEnvironment environment = requested.empty() ? BunqConnector::EnvironmentOfKey(apiKey) : ParseEnvironment(requested);
|
// The key says itself which environment it is of, by how it starts. One the caller names is held to that,
|
||||||
|
// before anyone is asked and before the key goes anywhere: sent to the environment it is not of, a key
|
||||||
|
// would only be refused there, after a real one had been shown to the sandbox.
|
||||||
|
const BunqEnvironment environment = BunqConnector::EnvironmentOfKey(apiKey);
|
||||||
|
if(!requested.empty() && ParseEnvironment(requested) != environment) {
|
||||||
|
throw std::invalid_argument(std::format("that API key is a {} key, not a {} one: a sandbox key starts with sandbox_, and no other key does", EnvironmentName(environment), requested));
|
||||||
|
}
|
||||||
const Prompt prompt{actionConnectors, std::format("add a bunq connector ({})", EnvironmentName(environment)), {{"environment", std::string(EnvironmentName(environment))}}};
|
const Prompt prompt{actionConnectors, std::format("add a bunq connector ({})", EnvironmentName(environment)), {{"environment", std::string(EnvironmentName(environment))}}};
|
||||||
return Gate(worker, call, prompt, [apiKey = std::move(apiKey), allowedIps = std::move(allowedIps), environment](sd_bus_message* reply) {
|
return Gate(worker, call, prompt, [apiKey = std::move(apiKey), allowedIps = std::move(allowedIps), environment](sd_bus_message* reply) {
|
||||||
AppendAdded(reply, BunqConnector::Create(std::string(apiKey), allowedIps, environment));
|
AppendAdded(reply, BunqConnector::Create(std::string(apiKey), allowedIps, environment));
|
||||||
|
|
@ -556,7 +562,7 @@ namespace {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if(matches.size() != 1) {
|
if(matches.size() != 1) {
|
||||||
throw std::invalid_argument(matches.empty() ? std::format("no connector is called or numbered '{}'", key) : std::format("{} connectors are called '{}': use the number `nostro connectors` shows", matches.size(), key));
|
throw std::invalid_argument(matches.empty() ? std::format("no connector is called or numbered '{}'", key) : std::format("{} connectors are called '{}': use its number in the list of connectors", matches.size(), key));
|
||||||
}
|
}
|
||||||
const std::string storageKey = matches.front()->StorageKey();
|
const std::string storageKey = matches.front()->StorageKey();
|
||||||
const Prompt prompt{actionConnectors, std::format("remove the bunq connector '{}' and its stored transactions", Shown(matches.front()->name)), {}};
|
const Prompt prompt{actionConnectors, std::format("remove the bunq connector '{}' and its stored transactions", Shown(matches.front()->name)), {}};
|
||||||
|
|
@ -595,7 +601,11 @@ namespace {
|
||||||
const AccountKey key = KeyOf(FindAccount(account));
|
const AccountKey key = KeyOf(FindAccount(account));
|
||||||
return Gate(worker, call, Prompt{actionView, "see your transactions", {}}, [key, query](sd_bus_message* reply) {
|
return Gate(worker, call, Prompt{actionView, "see your transactions", {}}, [key, query](sd_bus_message* reply) {
|
||||||
BunqAccount& found = AccountBy(key);
|
BunqAccount& found = AccountBy(key);
|
||||||
found.connector->GetNewTransactions(found);
|
// What is new at the bank first: a call to it, which takes its time and which it counts. Not for a
|
||||||
|
// question about what is stored alone, as a search in a list just given is: that is answered at once.
|
||||||
|
if(!query.stored) {
|
||||||
|
found.connector->GetNewTransactions(found);
|
||||||
|
}
|
||||||
Append(reply, found.FindTransactions(found.StorageKey(), query));
|
Append(reply, found.FindTransactions(found.StorageKey(), query));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
@ -812,6 +822,12 @@ namespace {
|
||||||
for(BunqConnector& bank : BunqConnector::connectors) {
|
for(BunqConnector& bank : BunqConnector::connectors) {
|
||||||
for(const BunqCard& found : bank.Cards()) {
|
for(const BunqCard& found : bank.Cards()) {
|
||||||
if(found.id == card) {
|
if(found.id == card) {
|
||||||
|
// bunq does not freeze or unfreeze a virtual card when asked, and answers as if nothing were
|
||||||
|
// wrong, with the card DEACTIVATED as it has it all along: a freeze answered so would look as
|
||||||
|
// if it had worked. Refused before anyone is asked for a password.
|
||||||
|
if(found.Virtual() && change->second.first != actionBlockCard) {
|
||||||
|
throw std::invalid_argument(std::format("card {} is a virtual card, which bunq does not freeze or unfreeze when asked: do that in the bunq app", card));
|
||||||
|
}
|
||||||
const std::string lastFour = Shown(found.lastFour);
|
const std::string lastFour = Shown(found.lastFour);
|
||||||
const Prompt prompt{change->second.first, std::vformat(change->second.second, std::make_format_args(lastFour)), {{"card", std::to_string(card)}, {"status", status}}};
|
const Prompt prompt{change->second.first, std::vformat(change->second.second, std::make_format_args(lastFour)), {{"card", std::to_string(card)}, {"status", status}}};
|
||||||
return Gate(worker, call, prompt, [storageKey = bank.StorageKey(), card, status](sd_bus_message* reply) {
|
return Gate(worker, call, prompt, [storageKey = bank.StorageKey(), card, status](sd_bus_message* reply) {
|
||||||
|
|
@ -1000,7 +1016,7 @@ namespace {
|
||||||
if(const BunqAccount* chosen = CheckoutAccount(worker)) {
|
if(const BunqAccount* chosen = CheckoutAccount(worker)) {
|
||||||
then(KeyOf(*chosen));
|
then(KeyOf(*chosen));
|
||||||
} else {
|
} else {
|
||||||
then(std::make_exception_ptr(NoCheckoutAccount("no account is chosen to pay checkouts from, or it is gone: `nostro checkout account <account>` chooses one")));
|
then(std::make_exception_ptr(NoCheckoutAccount("no account is chosen to pay checkouts from, or it is gone: choose one in Nostro's settings, or with `nostro checkout account`")));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
1139
implementations/Nostro.App-App.cpp
Normal file
1139
implementations/Nostro.App-App.cpp
Normal file
File diff suppressed because it is too large
Load diff
60
implementations/Nostro.App-Banks.cpp
Normal file
60
implementations/Nostro.App-Banks.cpp
Normal file
|
|
@ -0,0 +1,60 @@
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
module Nostro.App:Banks_impl;
|
||||||
|
import std;
|
||||||
|
import :Banks;
|
||||||
|
|
||||||
|
using namespace Nostro::App;
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
// bunq. An API key is the user's own, and a connection made with one does whatever bunq lets its user do. A
|
||||||
|
// connection through OAuth is an app's: bunq lets it pay between the user's own accounts, and make drafts for the
|
||||||
|
// user to approve in bunq's app.
|
||||||
|
constexpr std::array<Way, 2> bunqWays = {{
|
||||||
|
{.key = "key", .auth = "api key", .title = "API key", .about = "Full access, with a key you make in the bunq app", .revoke = "The API key itself stays valid until you revoke it in the bunq app.", .form = ConnectForm::BunqKey},
|
||||||
|
{.key = "oauth", .auth = "oauth", .title = "OAuth", .about = "Limited access, for an OAuth client of your own", .revoke = "The permission itself stays valid until you revoke it in the bunq app.", .form = ConnectForm::BunqOAuth, .ownAccountsOnly = true},
|
||||||
|
}};
|
||||||
|
|
||||||
|
constexpr std::array<Bank, 1> banks = {{
|
||||||
|
{.id = "bunq", .name = "bunq", .ways = bunqWays},
|
||||||
|
}};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::span<const Bank> Nostro::App::Banks() noexcept {
|
||||||
|
return banks;
|
||||||
|
}
|
||||||
|
|
||||||
|
const Bank* Nostro::App::FindBank(std::string_view id) noexcept {
|
||||||
|
const auto found = std::ranges::find(banks, id, &Bank::id);
|
||||||
|
return found != banks.end() ? &*found : nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
const Way* Nostro::App::FindWay(std::string_view bank, std::string_view auth) noexcept {
|
||||||
|
const Bank* const known = FindBank(bank);
|
||||||
|
if(known == nullptr) {
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
const auto found = std::ranges::find(known->ways, auth, &Way::auth);
|
||||||
|
return found != known->ways.end() ? &*found : nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string Nostro::App::BankName(std::string_view id) {
|
||||||
|
const Bank* const known = FindBank(id);
|
||||||
|
return std::string(known != nullptr ? known->name : id);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string Nostro::App::WayName(std::string_view bank, std::string_view auth) {
|
||||||
|
const Way* const known = FindWay(bank, auth);
|
||||||
|
return std::string(known != nullptr ? known->title : auth);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Nostro::App::OwnAccountsOnly(std::string_view bank, std::string_view auth) noexcept {
|
||||||
|
const Way* const known = FindWay(bank, auth);
|
||||||
|
return known != nullptr && known->ownAccountsOnly;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string Nostro::App::Revoking(std::string_view bank, std::string_view auth) {
|
||||||
|
const Way* const known = FindWay(bank, auth);
|
||||||
|
return std::string(known != nullptr ? known->revoke : "What it was connected with stays valid at the bank until you revoke it there.");
|
||||||
|
}
|
||||||
118
implementations/Nostro.App-Bunq.cpp
Normal file
118
implementations/Nostro.App-Bunq.cpp
Normal file
|
|
@ -0,0 +1,118 @@
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
module Nostro.App:Bunq_impl;
|
||||||
|
import std;
|
||||||
|
import Nostro;
|
||||||
|
import Nostro.Ui;
|
||||||
|
import :App;
|
||||||
|
import :Banks;
|
||||||
|
import :Format;
|
||||||
|
import :Forms;
|
||||||
|
import :Errors;
|
||||||
|
|
||||||
|
// bunq's part of the app: the two forms a connection to it is made with, which are the last step of adding a
|
||||||
|
// connection in the settings, and what their buttons do. What bunq is called, which ways it has and what each lets a
|
||||||
|
// connection do is in :Banks; what is filled in here, and how it is checked, in :Forms. Once the connection is made
|
||||||
|
// the app treats it like any bank's.
|
||||||
|
|
||||||
|
namespace Nostro::App {
|
||||||
|
namespace {
|
||||||
|
using namespace Ui;
|
||||||
|
}
|
||||||
|
|
||||||
|
// With an API key, made in bunq's own app. It is the user's own key, and does whatever bunq lets the user do.
|
||||||
|
void App::BunqKeyPage(Ui::Frame& frame, Ui::Column& column) {
|
||||||
|
column.Advance(Paragraph(frame, Padded(frame, column.Next()), "Make an API key in the bunq app, under Profile, Security, API keys, and enter it here. Nostro's service keeps it; this window forgets it once the connection is made.", Body(frame)));
|
||||||
|
// What was typed is never shown, only enough of it to tell one key from another.
|
||||||
|
column.Advance(TextField(frame, Padded(frame, column.Next()), bunqKey.key, {.key = "key.key", .label = "API key", .error = bunqKey.tried ? bunqKey.Check() : std::string(), .helper = bunqKey.key.value.empty() ? std::string() : std::format("Typed: {}", Fingerprint(bunqKey.key.value))}));
|
||||||
|
// Which of bunq's environments the key is of is the key's own to say, not something to choose here.
|
||||||
|
column.Advance(Paragraph(frame, Padded(frame, column.Next()), "A key that starts with sandbox_ connects to bunq's sandbox, where no real money moves.", Muted(frame)));
|
||||||
|
Button(frame, Padded(frame, column.Take(frame.Dp(Size::control - Size::unit * 2))), {.key = "key.advanced", .label = bunqKey.advanced ? "Fewer settings" : "More settings", .kind = ButtonKind::Plain, .onTap = [this] {
|
||||||
|
bunqKey.advanced = !bunqKey.advanced;
|
||||||
|
context.Invalidate();
|
||||||
|
}});
|
||||||
|
if(bunqKey.advanced) {
|
||||||
|
column.Advance(TextField(frame, Padded(frame, column.Next()), bunqKey.ips, {.key = "key.ips", .label = "Addresses the key may be used from", .helper = "* for any address; empty for this computer's address as it is now"}));
|
||||||
|
}
|
||||||
|
Button(frame, Padded(frame, column.Take(frame.Dp(Size::control))), {.key = "key.connect", .label = "Connect", .onTap = [this] { ConnectBunqKey(); }});
|
||||||
|
}
|
||||||
|
|
||||||
|
void App::ConnectBunqKey() {
|
||||||
|
bunqKey.tried = true;
|
||||||
|
context.Invalidate();
|
||||||
|
if(!bunqKey.Check().empty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// The key is read out of its field when the call is made, and kept there until the connection is: a mistyped
|
||||||
|
// password at the dialog should not cost typing it again.
|
||||||
|
Connect("AddBunq", [this](Client& bank, Client::Then<AddedConnector> then) { return bank.AddBunq(bunqKey.key.value, bunqKey.ips.value, {}, std::move(then)); });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Through OAuth, for an OAuth client the user registered with bunq: the client's registration first, then the
|
||||||
|
// address to approve at, and the address the browser ends up at once that is done.
|
||||||
|
void App::BunqOAuthPage(Ui::Frame& frame, Ui::Column& column) {
|
||||||
|
if(bunqOAuth.address.empty()) {
|
||||||
|
const BunqOAuthForm::Errors errors = bunqOAuth.tried ? bunqOAuth.Check() : BunqOAuthForm::Errors();
|
||||||
|
column.Advance(Paragraph(frame, Padded(frame, column.Next()), "For an OAuth client registered with bunq: enter what bunq gave it. A connection made this way can pay your own accounts and make draft payments, and nothing else.", Body(frame)));
|
||||||
|
column.Advance(TextField(frame, Padded(frame, column.Next()), bunqOAuth.clientId, {.key = "oauth.client", .label = "Client id", .error = errors.clientId}));
|
||||||
|
column.Advance(TextField(frame, Padded(frame, column.Next()), bunqOAuth.redirectUri, {.key = "oauth.redirect", .label = "Redirect address", .placeholder = "https://…", .error = errors.redirectUri, .purpose = TextPurpose::Url}));
|
||||||
|
column.Advance(TextField(frame, Padded(frame, column.Next()), bunqOAuth.secret, {.key = "oauth.secret", .label = "Client secret", .error = errors.secret, .helper = bunqOAuth.secret.value.empty() ? std::string() : std::format("Typed: {}", Fingerprint(bunqOAuth.secret.value))}));
|
||||||
|
Label(frame, Padded(frame, column.Take(frame.Dp(20))), "Environment", Muted(frame));
|
||||||
|
Segmented(frame, Padded(frame, column.Take(frame.Dp(Size::control))), {.key = "oauth.environment", .labels = {"Production", "Sandbox"}, .selected = bunqOAuth.sandbox ? std::size_t{1} : std::size_t{0}, .onSelect = [this](std::size_t chosen) {
|
||||||
|
bunqOAuth.sandbox = chosen == 1;
|
||||||
|
context.Invalidate();
|
||||||
|
}});
|
||||||
|
Button(frame, Padded(frame, column.Take(frame.Dp(Size::control))), {.key = "oauth.continue", .label = "Continue", .onTap = [this] { BeginBunqOAuth(); }});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
column.Advance(Paragraph(frame, Padded(frame, column.Next()), "Open this address and approve the connection with the bunq app, which may be on another device:", Body(frame)));
|
||||||
|
column.Advance(Paragraph(frame, Padded(frame, column.Next()), bunqOAuth.address, Muted(frame)));
|
||||||
|
Row open(Padded(frame, column.Take(frame.Dp(Size::control))), frame.Dp(Size::unit * 3));
|
||||||
|
Button(frame, open.TakeLeft((open.area.w - open.gap) / 2), {.key = "oauth.open", .label = "Open in browser", .enabled = host.openUri != nullptr, .onTap = [this] {
|
||||||
|
host.openUri(bunqOAuth.address, [this](bool taken) {
|
||||||
|
if(!taken) {
|
||||||
|
Tell("No browser could be opened: copy the address instead");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}});
|
||||||
|
Button(frame, open.Rest(), {.key = "oauth.copy", .label = "Copy the address", .kind = ButtonKind::Tonal, .onTap = [this] {
|
||||||
|
context.Copy(bunqOAuth.address);
|
||||||
|
Tell("Address copied");
|
||||||
|
}});
|
||||||
|
column.Advance(Paragraph(frame, Padded(frame, column.Next()), "Once you have approved, your browser is sent to the redirect address. Copy the whole address it ends up at and enter it here:", Body(frame)));
|
||||||
|
column.Advance(TextField(frame, Padded(frame, column.Next()), bunqOAuth.redirected, {.key = "oauth.redirected", .label = "The address your browser was sent to", .error = bunqOAuthError, .purpose = TextPurpose::Url, .onSubmit = [this] { ConnectBunqOAuth(); }}));
|
||||||
|
Button(frame, Padded(frame, column.Take(frame.Dp(Size::control))), {.key = "oauth.connect", .label = "Connect", .onTap = [this] { ConnectBunqOAuth(); }});
|
||||||
|
Button(frame, Padded(frame, column.Take(frame.Dp(Size::control - Size::unit * 2))), {.key = "oauth.restart", .label = "Start over", .kind = ButtonKind::Plain, .onTap = [this] {
|
||||||
|
bunqOAuth.address.clear();
|
||||||
|
bunqOAuth.redirected.Clear();
|
||||||
|
bunqOAuthError.clear();
|
||||||
|
context.Invalidate();
|
||||||
|
}});
|
||||||
|
}
|
||||||
|
|
||||||
|
void App::BeginBunqOAuth() {
|
||||||
|
bunqOAuth.tried = true;
|
||||||
|
context.Invalidate();
|
||||||
|
if(bunqOAuth.Check().Any()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
bunqOAuth.Begin(host.oauthState ? host.oauthState() : Crypto::RandomHex(16));
|
||||||
|
bunqOAuthError.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
void App::ConnectBunqOAuth() {
|
||||||
|
context.Invalidate();
|
||||||
|
std::string code;
|
||||||
|
try {
|
||||||
|
code = bunqOAuth.Code();
|
||||||
|
} catch(const std::runtime_error& e) {
|
||||||
|
// bunq did not authorize, the address has no code, or it answers another request than this one.
|
||||||
|
bunqOAuthError = e.what();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
bunqOAuthError.clear();
|
||||||
|
// nostrod trades the code for its token and keeps it: the token never comes here.
|
||||||
|
Connect("AddBunqOAuth", [this, code](Client& bank, Client::Then<AddedConnector> then) { return bank.AddBunqOAuth(bunqOAuth.sandbox ? "sandbox" : "production", bunqOAuth.clientId.value, bunqOAuth.secret.value, bunqOAuth.redirectUri.value, code, std::move(then)); });
|
||||||
|
}
|
||||||
|
}
|
||||||
99
implementations/Nostro.App-Errors.cpp
Normal file
99
implementations/Nostro.App-Errors.cpp
Normal file
|
|
@ -0,0 +1,99 @@
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
module Nostro.App:Errors_impl;
|
||||||
|
import std;
|
||||||
|
import Nostro;
|
||||||
|
import :Errors;
|
||||||
|
|
||||||
|
using namespace Nostro;
|
||||||
|
using namespace Nostro::App;
|
||||||
|
|
||||||
|
std::string_view App::ActionOf(Operation operation) noexcept {
|
||||||
|
switch(operation) {
|
||||||
|
case Operation::Send:
|
||||||
|
case Operation::Schedule:
|
||||||
|
case Operation::PayRequest:
|
||||||
|
case Operation::AcceptDraft: return Bus::actionPay;
|
||||||
|
case Operation::Draft:
|
||||||
|
case Operation::Request:
|
||||||
|
case Operation::RevokeRequest:
|
||||||
|
case Operation::RejectRequest:
|
||||||
|
case Operation::CancelSchedule:
|
||||||
|
case Operation::RejectDraft:
|
||||||
|
case Operation::FreezeCard: return Bus::actionChange;
|
||||||
|
case Operation::UnfreezeCard: return Bus::actionUnfreezeCard;
|
||||||
|
case Operation::BlockCard: return Bus::actionBlockCard;
|
||||||
|
case Operation::AddConnection:
|
||||||
|
case Operation::RemoveConnection:
|
||||||
|
case Operation::SetCheckoutAccount: return Bus::actionConnectors;
|
||||||
|
default: return Bus::actionView;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool App::AsksPassword(Operation operation) noexcept {
|
||||||
|
const std::string_view action = ActionOf(operation);
|
||||||
|
return action != Bus::actionView && action != Bus::actionChange;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool App::MovesMoney(Operation operation) noexcept {
|
||||||
|
return ActionOf(operation) == Bus::actionPay;
|
||||||
|
}
|
||||||
|
|
||||||
|
Guidance App::Explain(const std::exception_ptr& error, Operation operation) {
|
||||||
|
const bool reading = operation == Operation::Load;
|
||||||
|
const std::string where = MovesMoney(operation) ? "Look at the account's activity before trying again." : "Look at what is there before trying again.";
|
||||||
|
const auto unknown = [&where, operation](std::string_view said) {
|
||||||
|
return Guidance{Problem::Unknown, MovesMoney(operation) ? "It may have been paid" : "It may have been done", std::format("No clear answer came back: {}. {}", said, where), true, false};
|
||||||
|
};
|
||||||
|
const auto missing = [](std::string_view said) {
|
||||||
|
return Guidance{Problem::NoService, "Nostro's service is not running", std::format("Nostro keeps your bank connections in a service of its own, nostrod, which is not running and which the system could not start. Install nostrod and its system files as Nostro's README says, then try again. ({})", said), false, true};
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
std::rethrow_exception(error);
|
||||||
|
} catch(const DaemonMissing& e) {
|
||||||
|
return missing(e.what());
|
||||||
|
} catch(const NoSystemBus& e) {
|
||||||
|
return {Problem::NoService, "The system bus cannot be reached", std::format("Nostro talks to its service, nostrod, over the system bus, and cannot connect to it: {}. Nothing can be shown or done without it.", e.what()), false, true};
|
||||||
|
} catch(const OutcomeUnknown& e) {
|
||||||
|
return unknown(e.what());
|
||||||
|
} catch(const std::invalid_argument& e) {
|
||||||
|
return {Problem::Input, "That cannot be done", std::format("{}. Nothing was sent.", e.what()), false, false};
|
||||||
|
} catch(const DaemonError& e) {
|
||||||
|
if(e.name == Bus::errorCancelled) {
|
||||||
|
return {Problem::NotConfirmed, "Not confirmed", "Nothing was done. If no password dialog appeared, nothing in this session can ask for your password: the desktop's authentication agent is not running.", false, false};
|
||||||
|
}
|
||||||
|
if(e.name == "org.freedesktop.DBus.Error.AccessDenied") {
|
||||||
|
return {Problem::NotAllowed, "Not allowed", std::format("{}. Nothing was done. Try again, or ask whoever manages this computer.", e.what()), false, reading};
|
||||||
|
}
|
||||||
|
if(e.name == "org.freedesktop.DBus.Error.InteractiveAuthorizationRequired") {
|
||||||
|
return {Problem::CannotAsk, "Could not ask for your password", "nostrod was not allowed to have the system ask for your password, so nothing was done. Nostro's README says how the service is set up.", false, false};
|
||||||
|
}
|
||||||
|
if(e.name == Bus::errorOAuthCannotPay) {
|
||||||
|
// What a bank answers a connection that it lets pay between the user's own accounts only.
|
||||||
|
return {Problem::OwnAccountsOnly, "This connection cannot pay others", "Your bank lets it pay between your own accounts only. Save the payment as a draft instead, and approve it in your bank's app.", false, false};
|
||||||
|
}
|
||||||
|
if(e.name == Bus::errorBank) {
|
||||||
|
return {Problem::Bank, "The bank refused", e.what(), false, reading};
|
||||||
|
}
|
||||||
|
if(e.name.starts_with("org.freedesktop.systemd1.") || e.name.starts_with("org.freedesktop.DBus.Error.Spawn.") || e.name == "org.freedesktop.DBus.Error.NameHasNoOwner") {
|
||||||
|
return missing(e.what());
|
||||||
|
}
|
||||||
|
if(e.name == "org.freedesktop.DBus.Error.NoReply" || e.name == "org.freedesktop.DBus.Error.Timeout") {
|
||||||
|
return {Problem::Late, "No answer yet", "nostrod took too long to answer, which the bank's own limits can cause. Try again in a moment.", false, true};
|
||||||
|
}
|
||||||
|
// nostrod's own word for a payment that ended without a clear answer, such as one its worker died under.
|
||||||
|
if(e.name == Bus::errorFailed && MovesMoney(operation)) {
|
||||||
|
return unknown(e.what());
|
||||||
|
}
|
||||||
|
return {Problem::Failed, "That did not work", e.what(), false, reading};
|
||||||
|
} catch(const std::system_error& e) {
|
||||||
|
// An answer that could not be read, or a connection that broke under the call.
|
||||||
|
if(!reading) {
|
||||||
|
return unknown(e.what());
|
||||||
|
}
|
||||||
|
return {Problem::Failed, "That did not work", e.what(), false, true};
|
||||||
|
} catch(const std::exception& e) {
|
||||||
|
return {Problem::Failed, "That did not work", e.what(), false, reading};
|
||||||
|
}
|
||||||
|
}
|
||||||
208
implementations/Nostro.App-Format.cpp
Normal file
208
implementations/Nostro.App-Format.cpp
Normal file
|
|
@ -0,0 +1,208 @@
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
module Nostro.App:Format_impl;
|
||||||
|
import std;
|
||||||
|
import Nostro;
|
||||||
|
import :Format;
|
||||||
|
|
||||||
|
using namespace Nostro;
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
constexpr std::array<std::string_view, 12> months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
|
||||||
|
constexpr std::array<std::string_view, 7> weekdays = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
|
||||||
|
|
||||||
|
// A moment as the user's clock and calendar show it.
|
||||||
|
std::tm Local(std::chrono::system_clock::time_point time) {
|
||||||
|
const std::time_t seconds = std::chrono::system_clock::to_time_t(time);
|
||||||
|
return *std::localtime(&seconds);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::int64_t DayOf(const std::tm& local) {
|
||||||
|
return static_cast<std::int64_t>(local.tm_year + 1900) * 1000 + local.tm_yday;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string_view Month(const std::tm& local) {
|
||||||
|
return months[static_cast<std::size_t>(local.tm_mon)];
|
||||||
|
}
|
||||||
|
|
||||||
|
// The bank's capitals and underscores as words: "PIN_TRIES_EXCEEDED" is "Pin tries exceeded", and "sandbox" is
|
||||||
|
// "Sandbox".
|
||||||
|
std::string Words(std::string_view shouted) {
|
||||||
|
std::string words;
|
||||||
|
for(const char c : shouted) {
|
||||||
|
if(c == '_') {
|
||||||
|
words += ' ';
|
||||||
|
} else if(c >= 'A' && c <= 'Z' && !words.empty()) {
|
||||||
|
words += static_cast<char>(c - 'A' + 'a');
|
||||||
|
} else if(c >= 'a' && c <= 'z' && words.empty()) {
|
||||||
|
words += static_cast<char>(c - 'a' + 'A');
|
||||||
|
} else {
|
||||||
|
words += c;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return words;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string App::GroupIban(std::string_view iban) {
|
||||||
|
const auto letter = [](char c) { return c >= 'A' && c <= 'Z'; };
|
||||||
|
const auto digit = [](char c) { return c >= '0' && c <= '9'; };
|
||||||
|
// A country, two check digits, and letters and digits after them: an e-mail address or a name is left alone.
|
||||||
|
if(iban.size() < 5 || !letter(iban[0]) || !letter(iban[1]) || !digit(iban[2]) || !digit(iban[3]) || !std::ranges::all_of(iban, [&letter, &digit](char c) { return letter(c) || digit(c); })) {
|
||||||
|
return std::string(iban);
|
||||||
|
}
|
||||||
|
std::string grouped;
|
||||||
|
for(std::size_t i = 0; i < iban.size(); i++) {
|
||||||
|
if(i > 0 && i % 4 == 0) {
|
||||||
|
grouped += ' ';
|
||||||
|
}
|
||||||
|
grouped += iban[i];
|
||||||
|
}
|
||||||
|
return grouped;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string App::AccountKey(const Account& account) {
|
||||||
|
return account.iban.empty() ? account.name : account.iban;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string App::PartyName(const BunqLabel& party) {
|
||||||
|
if(!party.name.empty()) {
|
||||||
|
return party.name;
|
||||||
|
}
|
||||||
|
return party.iban.empty() ? std::string("Unknown") : GroupIban(party.iban);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string App::PartyName(const BunqCounterparty& party) {
|
||||||
|
return party.name.empty() ? GroupIban(party.value) : party.name;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string App::Money(std::int64_t minor, Currency currency) {
|
||||||
|
std::string money = FormatMoney(minor, currency);
|
||||||
|
// A comma before every three digits of the whole part, from its end.
|
||||||
|
const std::size_t point = std::min(money.find('.'), money.size());
|
||||||
|
std::size_t first = point;
|
||||||
|
while(first > 0 && money[first - 1] >= '0' && money[first - 1] <= '9') {
|
||||||
|
first--;
|
||||||
|
}
|
||||||
|
for(std::size_t at = point; at > first + 3;) {
|
||||||
|
at -= 3;
|
||||||
|
money.insert(at, 1, ',');
|
||||||
|
}
|
||||||
|
return money;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string App::SignedMoney(std::int64_t minor, Currency currency) {
|
||||||
|
return minor > 0 ? std::format("+{}", Money(minor, currency)) : Money(minor, currency);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::int64_t App::LocalDay(std::chrono::system_clock::time_point time) {
|
||||||
|
return DayOf(Local(time));
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string App::DayLabel(std::chrono::system_clock::time_point time, std::chrono::system_clock::time_point now) {
|
||||||
|
const std::tm local = Local(time);
|
||||||
|
const std::tm today = Local(now);
|
||||||
|
if(DayOf(local) == DayOf(today)) {
|
||||||
|
return "Today";
|
||||||
|
}
|
||||||
|
// The day before by the calendar, from its noon: a day is 23 or 25 hours long where the clocks change.
|
||||||
|
std::tm before = today;
|
||||||
|
before.tm_mday -= 1;
|
||||||
|
before.tm_hour = 12;
|
||||||
|
before.tm_isdst = -1;
|
||||||
|
std::mktime(&before);
|
||||||
|
if(DayOf(local) == DayOf(before)) {
|
||||||
|
return "Yesterday";
|
||||||
|
}
|
||||||
|
const std::string day = std::format("{} {} {}", weekdays[static_cast<std::size_t>(local.tm_wday)], local.tm_mday, Month(local));
|
||||||
|
return local.tm_year == today.tm_year ? day : std::format("{} {}", day, local.tm_year + 1900);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string App::ShortDate(std::chrono::system_clock::time_point time, std::chrono::system_clock::time_point now) {
|
||||||
|
const std::tm local = Local(time);
|
||||||
|
const std::string day = std::format("{} {}", local.tm_mday, Month(local).substr(0, 3));
|
||||||
|
return local.tm_year == Local(now).tm_year ? day : std::format("{} {}", day, local.tm_year + 1900);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string App::ClockTime(std::chrono::system_clock::time_point time) {
|
||||||
|
const std::tm local = Local(time);
|
||||||
|
return std::format("{:02}:{:02}", local.tm_hour, local.tm_min);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string App::FullTime(std::chrono::system_clock::time_point time) {
|
||||||
|
const std::tm local = Local(time);
|
||||||
|
return std::format("{} {} {}, {:02}:{:02}", local.tm_mday, Month(local), local.tm_year + 1900, local.tm_hour, local.tm_min);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string App::DateInput(std::chrono::system_clock::time_point time) {
|
||||||
|
const std::tm local = Local(time);
|
||||||
|
return std::format("{:04}-{:02}-{:02}", local.tm_year + 1900, local.tm_mon + 1, local.tm_mday);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string App::KindLabel(std::string_view kind) {
|
||||||
|
// A type and a sub type, "MASTERCARD/PAYMENT", as the bank's connector stored them: the type says how the money
|
||||||
|
// moved. These are the kinds the app has words for; any other is said as the bank says it.
|
||||||
|
const std::string_view type = kind.substr(0, kind.find('/'));
|
||||||
|
static constexpr std::array<std::pair<std::string_view, std::string_view>, 6> known = {{
|
||||||
|
{"MASTERCARD", "Card payment"}, {"EBA_SDD", "Direct debit"}, {"EBA_SCT", "Bank transfer"},
|
||||||
|
{"IDEAL", "iDEAL"}, {"SOFORT", "Sofort"}, {"SWIFT", "International transfer"},
|
||||||
|
}};
|
||||||
|
const auto found = std::ranges::find(known, type, &std::pair<std::string_view, std::string_view>::first);
|
||||||
|
if(found != known.end()) {
|
||||||
|
return std::string(found->second);
|
||||||
|
}
|
||||||
|
// bunq's own type, for what stays inside it: a payment between two of its accounts, or of a request.
|
||||||
|
if(type == "BUNQ") {
|
||||||
|
return kind == "BUNQ/REQUEST" ? "Paid request" : "Payment within the bank";
|
||||||
|
}
|
||||||
|
return std::string(kind);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string App::StatusLabel(std::string_view status) {
|
||||||
|
return Words(status);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string App::CardProduct(std::string_view productType) {
|
||||||
|
return Words(productType);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string App::CardExpiry(std::string_view expiry) {
|
||||||
|
// The bank's day, YYYY-MM-DD: a card's face has the month and the last two digits of the year.
|
||||||
|
static constexpr std::array<std::size_t, 8> digits = {0, 1, 2, 3, 5, 6, 8, 9};
|
||||||
|
const bool day = expiry.size() == 10 && expiry[4] == '-' && expiry[7] == '-' && std::ranges::all_of(digits, [expiry](std::size_t at) { return expiry[at] >= '0' && expiry[at] <= '9'; });
|
||||||
|
return day ? std::format("{}/{}", expiry.substr(5, 2), expiry.substr(2, 2)) : std::string(expiry);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string App::ScheduleLabel(const BunqSchedule& schedule, std::chrono::system_clock::time_point now) {
|
||||||
|
// The day, and the time on it when that is not its midnight.
|
||||||
|
const auto moment = [now](std::chrono::system_clock::time_point time) {
|
||||||
|
const std::tm local = Local(time);
|
||||||
|
return local.tm_hour == 0 && local.tm_min == 0 ? ShortDate(time, now) : std::format("{}, {}", ShortDate(time, now), ClockTime(time));
|
||||||
|
};
|
||||||
|
if(schedule.unit == "ONCE") {
|
||||||
|
return std::format("Once on {}", moment(schedule.start));
|
||||||
|
}
|
||||||
|
static constexpr std::array<std::pair<std::string_view, std::string_view>, 5> units = {{
|
||||||
|
{"HOURLY", "hour"}, {"DAILY", "day"}, {"WEEKLY", "week"}, {"MONTHLY", "month"}, {"YEARLY", "year"},
|
||||||
|
}};
|
||||||
|
const auto found = std::ranges::find(units, schedule.unit, &std::pair<std::string_view, std::string_view>::first);
|
||||||
|
// A unit the bank has and this does not know yet is said as the bank says it.
|
||||||
|
const std::string unit = found != units.end() ? std::string(found->second) : Words(schedule.unit);
|
||||||
|
std::string label = schedule.every == 1 ? std::format("Every {} from {}", unit, moment(schedule.start)) : std::format("Every {} {}s from {}", schedule.every, unit, moment(schedule.start));
|
||||||
|
if(schedule.end) {
|
||||||
|
label += std::format(" until {}", moment(*schedule.end));
|
||||||
|
}
|
||||||
|
return label;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string App::Fingerprint(std::string_view secret) {
|
||||||
|
// Too short to show a part of without showing most of it.
|
||||||
|
if(secret.size() < 16) {
|
||||||
|
return "••••";
|
||||||
|
}
|
||||||
|
// Up to its first underscore, which is where a bunq key says what it is for ("sandbox_"), or its first four.
|
||||||
|
const std::size_t mark = secret.find('_');
|
||||||
|
const std::string_view start = mark != std::string_view::npos && mark < 12 ? secret.substr(0, mark + 1) : secret.substr(0, 4);
|
||||||
|
return std::format("{}…{}", start, secret.substr(secret.size() - 4));
|
||||||
|
}
|
||||||
318
implementations/Nostro.App-Forms.cpp
Normal file
318
implementations/Nostro.App-Forms.cpp
Normal file
|
|
@ -0,0 +1,318 @@
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
module Nostro.App:Forms_impl;
|
||||||
|
import std;
|
||||||
|
import Nostro;
|
||||||
|
import Nostro.Ui;
|
||||||
|
import :Forms;
|
||||||
|
import :Format;
|
||||||
|
|
||||||
|
using namespace Nostro;
|
||||||
|
using namespace Nostro::App;
|
||||||
|
using Moment = std::chrono::system_clock::time_point;
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
std::string_view Trimmed(std::string_view text) {
|
||||||
|
while(text.starts_with(' ')) {
|
||||||
|
text.remove_prefix(1);
|
||||||
|
}
|
||||||
|
while(text.ends_with(' ')) {
|
||||||
|
text.remove_suffix(1);
|
||||||
|
}
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Read<std::int64_t> App::ReadAmount(std::string_view text, Currency currency) {
|
||||||
|
std::string amount(Trimmed(text));
|
||||||
|
if(amount.empty()) {
|
||||||
|
return {std::nullopt, "Enter an amount"};
|
||||||
|
}
|
||||||
|
// A comma is a decimal separator to most of Europe, and nostro's own amounts have a point.
|
||||||
|
std::ranges::replace(amount, ',', '.');
|
||||||
|
const std::size_t point = amount.find('.');
|
||||||
|
const std::size_t whole = std::min(point, amount.size());
|
||||||
|
const std::size_t decimals = point == std::string::npos ? 0 : amount.size() - point - 1;
|
||||||
|
if(amount.starts_with('-') || whole == 0 || !std::ranges::all_of(amount, [](char c) { return (c >= '0' && c <= '9') || c == '.'; }) || std::ranges::count(amount, '.') > 1) {
|
||||||
|
return {std::nullopt, "Not an amount: digits, as in 12,50"};
|
||||||
|
}
|
||||||
|
if(decimals > GetCurrencyDecimals(currency)) {
|
||||||
|
return {std::nullopt, std::format("At most {} decimals", GetCurrencyDecimals(currency))};
|
||||||
|
}
|
||||||
|
// Twelve digits is hundreds of billions: more is a slip of the finger, and far more would not fit the number.
|
||||||
|
if(whole > 12) {
|
||||||
|
return {std::nullopt, "That is too much"};
|
||||||
|
}
|
||||||
|
const std::int64_t minor = ParseAmount(amount, currency);
|
||||||
|
if(minor == 0) {
|
||||||
|
return {std::nullopt, "An amount above zero"};
|
||||||
|
}
|
||||||
|
return {minor, {}};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string App::PartyKind(std::string_view text) {
|
||||||
|
const std::string_view party = Trimmed(text);
|
||||||
|
if(party.empty()) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
if(party.contains('@')) {
|
||||||
|
return "E-mail address";
|
||||||
|
}
|
||||||
|
return party.starts_with('+') ? "Phone number" : "IBAN";
|
||||||
|
}
|
||||||
|
|
||||||
|
Read<BunqCounterparty> App::ReadParty(std::string_view text) {
|
||||||
|
const std::string_view party = Trimmed(text);
|
||||||
|
if(party.empty()) {
|
||||||
|
return {std::nullopt, "An IBAN, an e-mail address or a phone number"};
|
||||||
|
}
|
||||||
|
const std::size_t at = party.find('@');
|
||||||
|
if(at != std::string_view::npos && (at == 0 || at + 1 == party.size() || party.contains(' '))) {
|
||||||
|
return {std::nullopt, "Not an e-mail address"};
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return {BunqCounterparty::Parse(party, {}), {}};
|
||||||
|
} catch(const std::invalid_argument&) {
|
||||||
|
return {std::nullopt, party.starts_with('+') ? "Not a phone number: +31 6 12345678" : "Not a valid IBAN: check it for a slip"};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Read<Moment> App::ReadDay(std::string_view day, std::string_view time, bool end) {
|
||||||
|
const std::string_view date = Trimmed(day);
|
||||||
|
const std::string_view clock = Trimmed(time);
|
||||||
|
if(date.empty()) {
|
||||||
|
return {std::nullopt, "A day: YYYY-MM-DD"};
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
// The day by itself first, so that the error names the field that is wrong.
|
||||||
|
const Moment start = ParseLocalDate(date);
|
||||||
|
if(clock.empty()) {
|
||||||
|
return {end ? ParseLocalDateEnd(date) : start, {}};
|
||||||
|
}
|
||||||
|
} catch(const std::runtime_error&) {
|
||||||
|
return {std::nullopt, "Not a day: YYYY-MM-DD"};
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return {ParseLocalDate(std::format("{} {}", date, clock)), {}};
|
||||||
|
} catch(const std::runtime_error&) {
|
||||||
|
return {std::nullopt, "Not a time: hh:mm"};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Read<std::uint32_t> App::ReadCount(std::string_view text) {
|
||||||
|
const std::string_view digits = Trimmed(text);
|
||||||
|
std::uint32_t count = 0;
|
||||||
|
const std::from_chars_result result = std::from_chars(digits.data(), digits.data() + digits.size(), count);
|
||||||
|
if(digits.empty() || result.ec != std::errc() || result.ptr != digits.data() + digits.size() || count == 0) {
|
||||||
|
return {std::nullopt, "A whole number, 1 or more"};
|
||||||
|
}
|
||||||
|
return {count, {}};
|
||||||
|
}
|
||||||
|
|
||||||
|
bool PaymentForm::Errors::Any() const noexcept {
|
||||||
|
return !to.empty() || !name.empty() || !amount.empty() || !day.empty() || !time.empty() || !every.empty() || !until.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
PaymentForm::Errors PaymentForm::Check(Currency currency, Moment now, PaymentOrder& order) const {
|
||||||
|
Errors errors;
|
||||||
|
Read<BunqCounterparty> party = ReadParty(to.value);
|
||||||
|
errors.to = party.error;
|
||||||
|
const std::string_view holder = Trimmed(name.value);
|
||||||
|
// A bank wants the holder's name with an IBAN; an e-mail address or a phone number finds its own.
|
||||||
|
if(party.value && party.value->type == "IBAN" && holder.empty()) {
|
||||||
|
errors.name = "The name of the account's holder";
|
||||||
|
}
|
||||||
|
const Read<std::int64_t> sum = ReadAmount(amount.value, currency);
|
||||||
|
errors.amount = sum.error;
|
||||||
|
|
||||||
|
BunqSchedule schedule;
|
||||||
|
if(when == When::Scheduled) {
|
||||||
|
const Read<Moment> first = ReadDay(day.value);
|
||||||
|
errors.day = first.error;
|
||||||
|
if(first.value) {
|
||||||
|
const Read<Moment> start = ReadDay(day.value, time.value);
|
||||||
|
errors.time = start.error;
|
||||||
|
if(LocalDay(*first.value) < LocalDay(now)) {
|
||||||
|
errors.day = "Today or later";
|
||||||
|
}
|
||||||
|
schedule.start = start.value.value_or(*first.value);
|
||||||
|
}
|
||||||
|
schedule.unit = std::string(scheduleUnits[unit].unit);
|
||||||
|
// Once has nothing to repeat and nothing to end.
|
||||||
|
if(unit != 0) {
|
||||||
|
if(!Trimmed(every.value).empty()) {
|
||||||
|
const Read<std::uint32_t> count = ReadCount(every.value);
|
||||||
|
errors.every = count.error;
|
||||||
|
schedule.every = count.value.value_or(1);
|
||||||
|
}
|
||||||
|
if(!Trimmed(until.value).empty()) {
|
||||||
|
const Read<Moment> last = ReadDay(until.value, {}, true);
|
||||||
|
errors.until = last.error;
|
||||||
|
if(last.value && first.value && *last.value <= schedule.start) {
|
||||||
|
errors.until = "After the first payment";
|
||||||
|
}
|
||||||
|
schedule.end = last.value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if(!errors.Any()) {
|
||||||
|
party.value->name = std::string(holder);
|
||||||
|
order = PaymentOrder{std::move(*party.value), *sum.value, std::string(Trimmed(description.value)), when, std::move(schedule)};
|
||||||
|
}
|
||||||
|
return errors;
|
||||||
|
}
|
||||||
|
|
||||||
|
void PaymentForm::Clear() {
|
||||||
|
to.Clear();
|
||||||
|
name.Clear();
|
||||||
|
amount.Clear();
|
||||||
|
description.Clear();
|
||||||
|
when = When::Now;
|
||||||
|
day.Clear();
|
||||||
|
time.Clear();
|
||||||
|
unit = 0;
|
||||||
|
every.Clear();
|
||||||
|
until.Clear();
|
||||||
|
tried = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool RequestForm::Errors::Any() const noexcept {
|
||||||
|
return !from.empty() || !name.empty() || !amount.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
RequestForm::Errors RequestForm::Check(Currency currency, RequestOrder& order) const {
|
||||||
|
Errors errors;
|
||||||
|
Read<BunqCounterparty> party = ReadParty(from.value);
|
||||||
|
errors.from = party.error;
|
||||||
|
const std::string_view holder = Trimmed(name.value);
|
||||||
|
if(party.value && party.value->type == "IBAN" && holder.empty()) {
|
||||||
|
errors.name = "The name of the account's holder";
|
||||||
|
}
|
||||||
|
const Read<std::int64_t> sum = ReadAmount(amount.value, currency);
|
||||||
|
errors.amount = sum.error;
|
||||||
|
if(!errors.Any()) {
|
||||||
|
party.value->name = std::string(holder);
|
||||||
|
order = RequestOrder{std::move(*party.value), *sum.value, std::string(Trimmed(description.value))};
|
||||||
|
}
|
||||||
|
return errors;
|
||||||
|
}
|
||||||
|
|
||||||
|
void RequestForm::Clear() {
|
||||||
|
from.Clear();
|
||||||
|
name.Clear();
|
||||||
|
amount.Clear();
|
||||||
|
description.Clear();
|
||||||
|
tried = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool FilterForm::Errors::Any() const noexcept {
|
||||||
|
return !amount.empty() || !from.empty() || !to.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
FilterForm::Errors FilterForm::Check(Currency currency, TransactionQuery& query) const {
|
||||||
|
Errors errors;
|
||||||
|
TransactionQuery asked;
|
||||||
|
asked.limit = query.limit;
|
||||||
|
asked.search = std::string(Trimmed(search.value));
|
||||||
|
if(!Trimmed(amount.value).empty()) {
|
||||||
|
const Read<std::int64_t> sum = ReadAmount(amount.value, currency);
|
||||||
|
errors.amount = sum.error;
|
||||||
|
if(sum.value) {
|
||||||
|
// What went out is stored below zero.
|
||||||
|
asked.amount = received ? *sum.value : -*sum.value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if(!Trimmed(from.value).empty()) {
|
||||||
|
const Read<Moment> first = ReadDay(from.value);
|
||||||
|
errors.from = first.error;
|
||||||
|
asked.from = first.value.value_or(asked.from);
|
||||||
|
}
|
||||||
|
if(!Trimmed(to.value).empty()) {
|
||||||
|
const Read<Moment> last = ReadDay(to.value, {}, true);
|
||||||
|
errors.to = last.error;
|
||||||
|
if(last.value && *last.value < asked.from) {
|
||||||
|
errors.to = "On or after the first day";
|
||||||
|
}
|
||||||
|
asked.to = last.value.value_or(asked.to);
|
||||||
|
}
|
||||||
|
if(!errors.Any()) {
|
||||||
|
query = std::move(asked);
|
||||||
|
}
|
||||||
|
return errors;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<std::string> FilterForm::Chips(Currency currency, Moment now) const {
|
||||||
|
std::vector<std::string> chips;
|
||||||
|
if(const Read<std::int64_t> sum = ReadAmount(amount.value, currency); sum.value) {
|
||||||
|
chips.push_back(std::format("{} {}", received ? "Received" : "Paid", Money(*sum.value, currency)));
|
||||||
|
}
|
||||||
|
if(const Read<Moment> first = ReadDay(from.value); first.value) {
|
||||||
|
chips.push_back(std::format("From {}", ShortDate(*first.value, now)));
|
||||||
|
}
|
||||||
|
if(const Read<Moment> last = ReadDay(to.value); last.value) {
|
||||||
|
chips.push_back(std::format("Until {}", ShortDate(*last.value, now)));
|
||||||
|
}
|
||||||
|
return chips;
|
||||||
|
}
|
||||||
|
|
||||||
|
void FilterForm::Reset() {
|
||||||
|
amount.Clear();
|
||||||
|
received = false;
|
||||||
|
from.Clear();
|
||||||
|
to.Clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
BunqKeyForm::BunqKeyForm() {
|
||||||
|
ips.Set("*");
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string BunqKeyForm::Check() const {
|
||||||
|
return key.value.empty() ? "The API key, from the bunq app" : std::string();
|
||||||
|
}
|
||||||
|
|
||||||
|
void BunqKeyForm::Clear() {
|
||||||
|
key.Clear();
|
||||||
|
ips.Set("*");
|
||||||
|
advanced = false;
|
||||||
|
tried = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool BunqOAuthForm::Errors::Any() const noexcept {
|
||||||
|
return !clientId.empty() || !redirectUri.empty() || !secret.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
BunqOAuthForm::Errors BunqOAuthForm::Check() const {
|
||||||
|
Errors errors;
|
||||||
|
if(Trimmed(clientId.value).empty()) {
|
||||||
|
errors.clientId = "The client id bunq gave the OAuth client";
|
||||||
|
}
|
||||||
|
const std::string_view uri = Trimmed(redirectUri.value);
|
||||||
|
if(!uri.starts_with("https://") && !uri.starts_with("http://")) {
|
||||||
|
errors.redirectUri = "The redirect address registered with the client: https://…";
|
||||||
|
}
|
||||||
|
if(secret.value.empty()) {
|
||||||
|
errors.secret = "The client's secret";
|
||||||
|
}
|
||||||
|
return errors;
|
||||||
|
}
|
||||||
|
|
||||||
|
void BunqOAuthForm::Begin(std::string newState) {
|
||||||
|
state = std::move(newState);
|
||||||
|
address = BunqConnector::OAuthAuthorizationUrl(sandbox ? BunqEnvironment::Sandbox : BunqEnvironment::Production, Trimmed(clientId.value), Trimmed(redirectUri.value), state);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string BunqOAuthForm::Code() const {
|
||||||
|
return BunqConnector::OAuthCodeFromRedirect(Trimmed(redirected.value), state);
|
||||||
|
}
|
||||||
|
|
||||||
|
void BunqOAuthForm::Clear() {
|
||||||
|
clientId.Clear();
|
||||||
|
redirectUri.Clear();
|
||||||
|
secret.Clear();
|
||||||
|
sandbox = false;
|
||||||
|
redirected.Clear();
|
||||||
|
state.clear();
|
||||||
|
address.clear();
|
||||||
|
tried = false;
|
||||||
|
}
|
||||||
780
implementations/Nostro.App-Screens.cpp
Normal file
780
implementations/Nostro.App-Screens.cpp
Normal file
|
|
@ -0,0 +1,780 @@
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
module Nostro.App:Screens_impl;
|
||||||
|
import std;
|
||||||
|
import Nostro;
|
||||||
|
import Nostro.Ui;
|
||||||
|
import :App;
|
||||||
|
import :Banks;
|
||||||
|
import :Format;
|
||||||
|
import :Forms;
|
||||||
|
import :Errors;
|
||||||
|
|
||||||
|
// The app's screens: each a function from what the app knows to a frame. A window as narrow as a phone shows one
|
||||||
|
// page at a time, with the app's places along its bottom; a wider one keeps the places, and the accounts themselves
|
||||||
|
// where there is room, down its left side. A press's action is one of the app's own (Nostro.App-App.cpp), and names
|
||||||
|
// what it is about by value.
|
||||||
|
//
|
||||||
|
// No screen here names a bank, or a way to connect to one, in words of its own: an account's pages are the same
|
||||||
|
// whichever bank it is with. Where a bank is named, in the settings, the name is what :Banks has for it, and the last
|
||||||
|
// step of adding a connection, a way's form, is the bank's own to draw (Nostro.App-Bunq.cpp).
|
||||||
|
|
||||||
|
namespace Nostro::App {
|
||||||
|
namespace {
|
||||||
|
using namespace Ui;
|
||||||
|
|
||||||
|
// A box clear of the page's edges on either side.
|
||||||
|
Box Gutters(const Frame& frame, Box box) {
|
||||||
|
return box.Inset(Insets::Symmetric(frame.Dp(Size::gutter), 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
// A strip of tabs: from edge to edge on a phone, where its labels need the room, and in line with the page's
|
||||||
|
// fields in a wider window.
|
||||||
|
Box Strip(const Frame& frame, Box box) {
|
||||||
|
return frame.sizeClass == SizeClass::Compact ? box : Gutters(frame, box);
|
||||||
|
}
|
||||||
|
|
||||||
|
// A status with what was said about it, where anything was.
|
||||||
|
std::string Joined(std::string first, std::string_view second) {
|
||||||
|
return second.empty() ? first : std::format("{} · {}", first, second);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ui::Box App::Padded(const Ui::Frame& frame, Ui::Box box) {
|
||||||
|
return Gutters(frame, box);
|
||||||
|
}
|
||||||
|
|
||||||
|
void App::Build(Ui::Frame& frame) {
|
||||||
|
const Ui::Box area = Scaffold(frame);
|
||||||
|
Content(frame, area);
|
||||||
|
if(const std::optional<AccountRef> filtered = Find(filtering)) {
|
||||||
|
FilterSheet(frame, *filtered);
|
||||||
|
}
|
||||||
|
if(picking != Picking::None) {
|
||||||
|
PickSheet(frame);
|
||||||
|
}
|
||||||
|
if(dialog) {
|
||||||
|
DialogSheet(frame);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string App::Title() const {
|
||||||
|
if(stack.empty()) {
|
||||||
|
static constexpr std::array<std::string_view, 3> places = {"Accounts", "Cards", "Settings"};
|
||||||
|
return std::string(places[std::to_underlying(place)]);
|
||||||
|
}
|
||||||
|
const Route& top = stack.back();
|
||||||
|
static constexpr std::array<std::string_view, 9> pages = {"Account", "Pay", "Request", "Bank connections", "Add a connection", "", "", "Pay at checkout", "About and security"};
|
||||||
|
std::string title(pages[std::to_underlying(top.page)]);
|
||||||
|
// An account's page is called what the account is.
|
||||||
|
if(const std::optional<AccountRef> account = Find(top.account)) {
|
||||||
|
title = account->account->name;
|
||||||
|
}
|
||||||
|
// And the steps of adding a connection what was chosen: the bank, and then the way with it.
|
||||||
|
if(top.bank != nullptr) {
|
||||||
|
title = top.bank->name;
|
||||||
|
}
|
||||||
|
if(top.way != nullptr) {
|
||||||
|
title = std::format("{} · {}", top.bank->name, top.way->title);
|
||||||
|
}
|
||||||
|
return title;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ui::Box App::Scaffold(Ui::Frame& frame) {
|
||||||
|
Box area = frame.bounds;
|
||||||
|
const bool compact = frame.sizeClass == SizeClass::Compact;
|
||||||
|
std::vector<NavItem> items;
|
||||||
|
items.push_back({.key = "nav.accounts", .label = "Accounts", .selected = place == Place::Accounts && (compact || stack.empty()), .onTap = [this] { Go(Place::Accounts); }});
|
||||||
|
items.push_back({.key = "nav.cards", .label = "Cards", .selected = place == Place::Cards, .onTap = [this] { Go(Place::Cards); }});
|
||||||
|
items.push_back({.key = "nav.settings", .label = "Settings", .selected = place == Place::Settings && (compact || stack.empty()), .onTap = [this] { Go(Place::Settings); }});
|
||||||
|
if(frame.sizeClass == SizeClass::Expanded && !overview.value.empty()) {
|
||||||
|
// Where there is room, the accounts themselves are a press away.
|
||||||
|
items.push_back({.key = "side.accounts", .label = "Your accounts", .header = true});
|
||||||
|
const std::string open = !stack.empty() && stack.back().page == Page::Account ? stack.back().account : std::string();
|
||||||
|
for(const AccountRef& account : Accounts()) {
|
||||||
|
items.push_back({.key = std::format("side.{}", account.key), .label = account.account->name, .detail = Money(account.account->balance, account.account->currency), .selected = account.key == open, .onTap = [this, key = account.key] {
|
||||||
|
place = Place::Accounts;
|
||||||
|
stack.clear();
|
||||||
|
Push(Page::Account, key);
|
||||||
|
}});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if(!compact) {
|
||||||
|
area = Sidebar(frame, area, frame.sizeClass == SizeClass::Expanded ? 280.0f : 200.0f, items);
|
||||||
|
} else if(stack.empty()) {
|
||||||
|
// A page that was gone into is left by its way back, not sideways.
|
||||||
|
area = NavBar(frame, area, items);
|
||||||
|
}
|
||||||
|
|
||||||
|
const std::function<void()> refresh = Refresher();
|
||||||
|
std::vector<BarAction> actions;
|
||||||
|
if(refresh) {
|
||||||
|
actions.push_back({.key = "bar.refresh", .label = "Refresh", .onTap = refresh});
|
||||||
|
// And by the keys a browser has for it.
|
||||||
|
frame.Shortcut(Key::F5, {}, refresh);
|
||||||
|
frame.Shortcut(Key::R, {.control = true}, refresh);
|
||||||
|
}
|
||||||
|
return TopBar(frame, area, {.title = Title(), .onBack = stack.empty() ? std::function<void()>() : [this] { Back(); }, .actions = std::move(actions)});
|
||||||
|
}
|
||||||
|
|
||||||
|
// What a screen that shows the bank's own state reads again; nothing for one that does not.
|
||||||
|
std::function<void()> App::Refresher() {
|
||||||
|
if(!stack.empty() && stack.back().page == Page::Account) {
|
||||||
|
return [this, key = stack.back().account] {
|
||||||
|
Refresh();
|
||||||
|
LoadTab(key, Data(key).tab, true);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if(stack.empty() && place == Place::Accounts) {
|
||||||
|
return [this] { Refresh(); };
|
||||||
|
}
|
||||||
|
if(stack.empty() && place == Place::Cards) {
|
||||||
|
return [this] { LoadCards(true); };
|
||||||
|
}
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
void App::Content(Ui::Frame& frame, Ui::Box area) {
|
||||||
|
frame.draw.SetLayer(Layer::Content);
|
||||||
|
const std::string screen = Screen();
|
||||||
|
const float offset = frame.BeginScroll(std::format("page:{}", screen.substr(0, screen.find('+'))), area);
|
||||||
|
// By a finger too: pulled down at its top and let go.
|
||||||
|
if(const std::function<void()> refresh = Refresher()) {
|
||||||
|
frame.Refreshable(refresh);
|
||||||
|
}
|
||||||
|
const float pulled = frame.Pulled();
|
||||||
|
if(pulled > 0) {
|
||||||
|
Label(frame, {area.x, area.y, area.w, pulled}, pulled >= frame.Dp(Size::pull) ? "Let go to refresh" : "Pull down to refresh", {FontFace::Regular, TextSize::label, frame.Colors().muted, TextAlign::Center});
|
||||||
|
}
|
||||||
|
const float top = area.y - offset + pulled;
|
||||||
|
Column column(Centered({area.x, top, area.w, area.h}, frame.Dp(Size::contentMax)), frame.Dp(Size::unit * 3));
|
||||||
|
column.cursor = top + frame.Dp(Size::unit * 3);
|
||||||
|
Notes(frame, column);
|
||||||
|
if(stack.empty()) {
|
||||||
|
if(place == Place::Accounts) {
|
||||||
|
HomePage(frame, column);
|
||||||
|
} else if(place == Place::Cards) {
|
||||||
|
CardsPage(frame, column, area);
|
||||||
|
} else {
|
||||||
|
SettingsPage(frame, column);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
const Route& route = stack.back();
|
||||||
|
switch(route.page) {
|
||||||
|
case Page::Account:
|
||||||
|
if(const std::optional<AccountRef> account = Find(route.account)) {
|
||||||
|
AccountPage(frame, column, *account, area);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case Page::Pay: PayPage(frame, column); break;
|
||||||
|
case Page::Request: RequestPage(frame, column); break;
|
||||||
|
case Page::Connections: ConnectionsPage(frame, column); break;
|
||||||
|
case Page::Banks: BanksPage(frame, column); break;
|
||||||
|
case Page::Ways: WaysPage(frame, column, *route.bank); break;
|
||||||
|
case Page::Connect:
|
||||||
|
// The form is the bank's own, one for each of its ways.
|
||||||
|
switch(route.way->form) {
|
||||||
|
case ConnectForm::BunqKey: BunqKeyPage(frame, column); break;
|
||||||
|
case ConnectForm::BunqOAuth: BunqOAuthPage(frame, column); break;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case Page::Checkout: CheckoutPage(frame, column); break;
|
||||||
|
case Page::About: AboutPage(frame, column); break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
frame.EndScroll(column.cursor - top + frame.Dp(Size::gutter));
|
||||||
|
}
|
||||||
|
|
||||||
|
void App::Notes(Ui::Frame& frame, Ui::Column& column) {
|
||||||
|
if(notes.empty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// What the library warned of while it worked: a connection that could not be reached, an account it skipped.
|
||||||
|
std::string text;
|
||||||
|
for(const std::string& note : notes) {
|
||||||
|
if(!text.empty()) {
|
||||||
|
text += '\n';
|
||||||
|
}
|
||||||
|
text += note;
|
||||||
|
}
|
||||||
|
column.Advance(Banner(frame, Padded(frame, column.Next()), {.key = "notes", .kind = BannerKind::Warning, .text = std::move(text), .onDismiss = [this] {
|
||||||
|
notes.clear();
|
||||||
|
context.Invalidate();
|
||||||
|
}}));
|
||||||
|
}
|
||||||
|
|
||||||
|
void App::Trouble(Ui::Frame& frame, Ui::Column& column, const Guidance& guidance, std::string_view key, std::function<void()> retry) {
|
||||||
|
const bool again = guidance.retry && retry != nullptr;
|
||||||
|
column.Advance(Banner(frame, Padded(frame, column.Next()), {.key = std::string(key), .kind = BannerKind::Error, .text = std::format("{}\n{}", guidance.title, guidance.detail), .action = again ? "Try again" : "", .onAction = again ? std::move(retry) : std::function<void()>()}));
|
||||||
|
}
|
||||||
|
|
||||||
|
void App::Waiting(Ui::Frame& frame, Ui::Column& column, std::uint32_t rows) {
|
||||||
|
for(std::uint32_t i = 0; i < rows; i++) {
|
||||||
|
const Box row = Padded(frame, column.Take(frame.Dp(Size::row - Size::unit * 3)));
|
||||||
|
Skeleton(frame, {row.x, row.y + frame.Dp(6), row.w, frame.Dp(16)}, 0.5f + 0.1f * static_cast<float>(i % 3));
|
||||||
|
Skeleton(frame, {row.x, row.y + frame.Dp(30), row.w, frame.Dp(12)}, 0.3f);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void App::Empty(Ui::Frame& frame, Ui::Column& column, std::string_view text) {
|
||||||
|
Label(frame, Padded(frame, column.Take(frame.Dp(Size::row))), text, {FontFace::Regular, TextSize::body, frame.Colors().muted, TextAlign::Center});
|
||||||
|
}
|
||||||
|
|
||||||
|
void App::Section(Ui::Frame& frame, Ui::Column& column, std::string_view title) {
|
||||||
|
Label(frame, Padded(frame, column.Take(frame.Dp(28))), title, {FontFace::Medium, TextSize::label, frame.Colors().muted, TextAlign::Left});
|
||||||
|
}
|
||||||
|
|
||||||
|
void App::Welcome(Ui::Frame& frame, Ui::Column& column) {
|
||||||
|
const Theme& theme = frame.Colors();
|
||||||
|
Label(frame, Padded(frame, column.Take(frame.Dp(40))), "Welcome to Nostro", {FontFace::Medium, TextSize::title, theme.text, TextAlign::Left});
|
||||||
|
column.Advance(Paragraph(frame, Padded(frame, column.Next()), "Nostro shows your bank accounts and pays from them. It talks to your bank directly, and what it needs for that is kept by a service of its own, out of reach of every other program you run, this window included.", Body(frame)));
|
||||||
|
column.Advance(Paragraph(frame, Padded(frame, column.Next()), "Before money moves, your system's own password dialog says what is about to be paid, to whom and from which account, and asks you to confirm it.", Body(frame)));
|
||||||
|
column.Advance(Paragraph(frame, Padded(frame, column.Next()), "To begin, connect your bank.", Muted(frame)));
|
||||||
|
// Which bank, and how, is asked on the pages this leads to: the same ones the settings add a connection with.
|
||||||
|
// They are gone into from here, so the way back leads here.
|
||||||
|
Button(frame, Padded(frame, column.Take(frame.Dp(Size::control))), {.key = "welcome.connect", .label = "Connect a bank", .onTap = [this] { Push(Page::Banks); }});
|
||||||
|
}
|
||||||
|
|
||||||
|
void App::HomePage(Ui::Frame& frame, Ui::Column& column) {
|
||||||
|
const Theme& theme = frame.Colors();
|
||||||
|
if(overview.state == LoadState::Failed) {
|
||||||
|
Trouble(frame, column, overview.problem, "overview", [this] { Refresh(); });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if(overview.state != LoadState::Loaded) {
|
||||||
|
Waiting(frame, column, 4);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if(overview.value.empty()) {
|
||||||
|
Welcome(frame, column);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Row actions(Padded(frame, column.Take(frame.Dp(Size::control))), frame.Dp(Size::unit * 3));
|
||||||
|
const bool any = !Accounts().empty();
|
||||||
|
Button(frame, actions.TakeLeft((actions.area.w - actions.gap) / 2), {.key = "home.pay", .label = "Pay", .enabled = any, .onTap = [this] { OpenPay({}); }});
|
||||||
|
Button(frame, actions.Rest(), {.key = "home.request", .label = "Request", .kind = ButtonKind::Tonal, .enabled = any, .onTap = [this] { OpenRequest({}); }});
|
||||||
|
for(const Connection& connection : overview.value) {
|
||||||
|
// The connection's name, and what is unusual about it.
|
||||||
|
Row heading(Padded(frame, column.Take(frame.Dp(32))), frame.Dp(Size::unit * 2));
|
||||||
|
const TextStyle name{FontFace::Medium, TextSize::label, theme.muted, TextAlign::Left};
|
||||||
|
Label(frame, heading.TakeLeft(std::min(heading.area.w / 2, TextWidth(frame.Measure(), connection.name, name.face, frame.Dp(name.sizeDp)))), connection.name, name);
|
||||||
|
const auto chip = [&frame, &heading](std::string_view text, Color ground, Color color) {
|
||||||
|
const Box at = heading.TakeLeft(ChipWidth(frame, text));
|
||||||
|
Chip(frame, {at.x, at.Center().y - frame.Dp(10), at.w, frame.Dp(20)}, text, ground, color);
|
||||||
|
};
|
||||||
|
if(connection.environment == "sandbox") {
|
||||||
|
chip("Sandbox", theme.surfaceAlt, theme.muted);
|
||||||
|
}
|
||||||
|
// It cannot pay anyone but the user: an account's page and the pay form say so in full.
|
||||||
|
if(connection.ownAccountsOnly) {
|
||||||
|
chip("Limited", theme.surfaceAlt, theme.muted);
|
||||||
|
}
|
||||||
|
if(!connection.working) {
|
||||||
|
chip("Not working", theme.danger, theme.onDanger);
|
||||||
|
}
|
||||||
|
if(connection.accounts.empty()) {
|
||||||
|
Empty(frame, column, "No accounts");
|
||||||
|
}
|
||||||
|
for(const Account& account : connection.accounts) {
|
||||||
|
const std::string key = AccountKey(account);
|
||||||
|
ListRow(frame, column.Take(frame.Dp(Size::row)), {.key = std::format("account.{}", key), .title = account.name, .subtitle = GroupIban(account.iban), .trailing = Money(account.balance, account.currency), .chevron = true, .onTap = [this, key] { Push(Page::Account, key); }});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void App::AccountPage(Ui::Frame& frame, Ui::Column& column, const AccountRef& account, Ui::Box viewport) {
|
||||||
|
const Theme& theme = frame.Colors();
|
||||||
|
const std::string key = account.key;
|
||||||
|
AccountData& data = Data(key);
|
||||||
|
Label(frame, Padded(frame, column.Take(frame.Dp(48))), Money(account.account->balance, account.account->currency), {FontFace::Medium, TextSize::display, theme.text, TextAlign::Left});
|
||||||
|
if(!account.account->iban.empty()) {
|
||||||
|
Row line(Padded(frame, column.Take(frame.Dp(Size::touch - Size::unit * 3))), frame.Dp(Size::unit * 2));
|
||||||
|
Button(frame, line.TakeRight(ButtonWidth(frame, "Copy")), {.key = "account.copy", .label = "Copy", .kind = ButtonKind::Plain, .onTap = [this, iban = account.account->iban] {
|
||||||
|
context.Copy(iban);
|
||||||
|
Tell("IBAN copied");
|
||||||
|
}});
|
||||||
|
Label(frame, line.Rest(), GroupIban(account.account->iban), Muted(frame));
|
||||||
|
}
|
||||||
|
// What its connection cannot do is said before it is tried.
|
||||||
|
if(account.connection->ownAccountsOnly) {
|
||||||
|
column.Advance(Paragraph(frame, Padded(frame, column.Next()), "This account's connection pays between your own accounts only.", Muted(frame)));
|
||||||
|
}
|
||||||
|
Row actions(Padded(frame, column.Take(frame.Dp(Size::control))), frame.Dp(Size::unit * 3));
|
||||||
|
Button(frame, actions.TakeLeft((actions.area.w - actions.gap) / 2), {.key = "account.pay", .label = "Pay", .onTap = [this, key] { OpenPay(key); }});
|
||||||
|
Button(frame, actions.Rest(), {.key = "account.request", .label = "Request", .kind = ButtonKind::Tonal, .onTap = [this, key] { OpenRequest(key); }});
|
||||||
|
Tabs(frame, Strip(frame, column.Take(frame.Dp(Size::control))), {.key = "tabs", .labels = {"Activity", "Requests", "Incoming", "Scheduled", "Drafts"}, .selected = std::to_underlying(data.tab), .onSelect = [this, key](std::size_t chosen) {
|
||||||
|
Data(key).tab = static_cast<Tab>(chosen);
|
||||||
|
LoadTab(key, static_cast<Tab>(chosen));
|
||||||
|
context.Invalidate();
|
||||||
|
}});
|
||||||
|
const std::chrono::system_clock::time_point today = Today();
|
||||||
|
switch(data.tab) {
|
||||||
|
case Tab::Activity:
|
||||||
|
ActivityTab(frame, column, account, data, viewport);
|
||||||
|
break;
|
||||||
|
case Tab::Requests:
|
||||||
|
ListTab(frame, column, key, Tab::Requests, data.requests, "No requests sent from this account", viewport, [this, &key, today](const BunqPaymentRequest& asked) {
|
||||||
|
return RowOptions{.key = std::format("request.{}", asked.id), .title = PartyName(asked.counterparty), .subtitle = Joined(StatusLabel(asked.status), asked.description), .trailing = Money(asked.amount, asked.currency), .trailingSub = ShortDate(asked.created, today), .chevron = true, .onTap = [this, key, asked] { ShowRequest(key, asked); }};
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
case Tab::Incoming:
|
||||||
|
ListTab(frame, column, key, Tab::Incoming, data.incoming, "Nobody has asked this account for money", viewport, [this, &key, today](const BunqIncomingRequest& asked) {
|
||||||
|
return RowOptions{.key = std::format("incoming.{}", asked.id), .title = PartyName(asked.counterparty), .subtitle = Joined(StatusLabel(asked.status), asked.description), .trailing = Money(asked.amount, asked.currency), .trailingSub = ShortDate(asked.created, today), .chevron = true, .onTap = [this, key, asked] { ShowIncoming(key, asked); }};
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
case Tab::Scheduled:
|
||||||
|
ListTab(frame, column, key, Tab::Scheduled, data.scheduled, "No payments are scheduled from this account", viewport, [this, &key, today](const BunqScheduledPayment& scheduled) {
|
||||||
|
return RowOptions{.key = std::format("scheduled.{}", scheduled.id), .title = PartyName(scheduled.counterparty), .subtitle = ScheduleLabel(scheduled.schedule, today), .trailing = Money(scheduled.amount, scheduled.currency), .trailingSub = StatusLabel(scheduled.schedule.status), .chevron = true, .onTap = [this, key, scheduled] { ShowScheduled(key, scheduled); }};
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
case Tab::Drafts:
|
||||||
|
ListTab(frame, column, key, Tab::Drafts, data.drafts, "No draft payments wait for this account", viewport, [this, &key](const BunqDraftPayment& draft) {
|
||||||
|
// Its payments together, to the first of their payees and however many more.
|
||||||
|
std::int64_t total = 0;
|
||||||
|
Currency currency = Currency::Euro;
|
||||||
|
std::string to;
|
||||||
|
for(const BunqDraftPayment::Entry& entry : draft.entries) {
|
||||||
|
total += entry.amount;
|
||||||
|
currency = entry.currency;
|
||||||
|
if(to.empty()) {
|
||||||
|
to = PartyName(entry.counterparty);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if(draft.entries.size() > 1) {
|
||||||
|
to += std::format(" and {} more", draft.entries.size() - 1);
|
||||||
|
}
|
||||||
|
return RowOptions{.key = std::format("draft.{}", draft.id), .title = to, .subtitle = Joined(StatusLabel(draft.status), draft.createdBy), .trailing = Money(total, currency), .chevron = true, .onTap = [this, key, draft] { ShowDraft(key, draft); }};
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void App::ActivityTab(Ui::Frame& frame, Ui::Column& column, const AccountRef& account, AccountData& data, Ui::Box viewport) {
|
||||||
|
const Theme& theme = frame.Colors();
|
||||||
|
const std::string key = account.key;
|
||||||
|
const Currency currency = account.account->currency;
|
||||||
|
const std::chrono::system_clock::time_point today = Today();
|
||||||
|
column.Advance(TextField(frame, Padded(frame, column.Next()), data.filter.search, {.key = "search", .placeholder = "Search a name, a description or an IBAN", .onChange = [this, key] { Search(key, false); }, .onSubmit = [this, key] { Search(key, true); }}));
|
||||||
|
frame.Shortcut(Key::F, {.control = true}, [this] { context.Focus("search"); });
|
||||||
|
// What is asked for besides the search, and the way to change it.
|
||||||
|
Row filters(Padded(frame, column.Take(frame.Dp(Size::touch - Size::unit * 3))), frame.Dp(Size::unit * 2));
|
||||||
|
Button(frame, filters.TakeLeft(ButtonWidth(frame, "Filter")), {.key = "filter", .label = "Filter", .kind = ButtonKind::Tonal, .onTap = [this, key] {
|
||||||
|
filtering = key;
|
||||||
|
context.Invalidate();
|
||||||
|
}});
|
||||||
|
const std::vector<std::string> chips = data.filter.Chips(currency, today);
|
||||||
|
for(const std::string& chip : chips) {
|
||||||
|
const float width = ChipWidth(frame, chip);
|
||||||
|
if(width <= filters.Rest().w) {
|
||||||
|
const Box at = filters.TakeLeft(width);
|
||||||
|
Chip(frame, {at.x, at.Center().y - frame.Dp(10), at.w, frame.Dp(20)}, chip, theme.surfaceAlt, theme.text);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if(data.activity.state == LoadState::Failed) {
|
||||||
|
Trouble(frame, column, data.activity.problem, "activity.problem", [this, key] { LoadActivity(key); });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if(data.activity.state != LoadState::Loaded) {
|
||||||
|
Waiting(frame, column, 5);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if(data.activity.value.empty()) {
|
||||||
|
Empty(frame, column, chips.empty() && data.query.search.empty() ? "No payments yet" : "Nothing matches");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
std::optional<std::int64_t> day;
|
||||||
|
for(const Transaction& transaction : data.activity.value) {
|
||||||
|
if(const std::int64_t on = LocalDay(transaction.timePoint); day != on) {
|
||||||
|
day = on;
|
||||||
|
Section(frame, column, DayLabel(transaction.timePoint, today));
|
||||||
|
}
|
||||||
|
const Box row = column.Take(frame.Dp(Size::row));
|
||||||
|
// A long list is drawn as far as it is looked at.
|
||||||
|
if(!row.Overlaps(viewport)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const std::string what = transaction.description.empty() ? KindLabel(transaction.kind) : transaction.description;
|
||||||
|
// By the bank's own number, so a press cannot land on the payment that took this one's place in the list;
|
||||||
|
// and by its moment and amount, for the payments stored before the number was kept.
|
||||||
|
ListRow(frame, row, {.key = std::format("tx.{}.{}.{}", transaction.id, transaction.timePoint.time_since_epoch().count(), transaction.amount), .title = transaction.name.empty() ? what : transaction.name, .subtitle = transaction.name.empty() ? std::string() : what, .trailing = SignedMoney(transaction.amount, transaction.currency), .trailingSub = ClockTime(transaction.timePoint), .trailingColor = transaction.amount > 0 ? std::optional<Color>(theme.positive) : std::nullopt, .onTap = [this, key, transaction] { ShowTransaction(key, transaction); }});
|
||||||
|
}
|
||||||
|
if(data.more) {
|
||||||
|
Button(frame, Padded(frame, column.Take(frame.Dp(Size::control))), {.key = "more", .label = "Show more", .kind = ButtonKind::Tonal, .enabled = !data.activity.refreshing, .onTap = [this, key] {
|
||||||
|
// Older ones, which nostrod has stored: the bank is not asked for them again.
|
||||||
|
Data(key).query.limit += 100;
|
||||||
|
LoadActivity(key, true);
|
||||||
|
context.Invalidate();
|
||||||
|
}});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
template<typename T, typename Make>
|
||||||
|
void App::ListTab(Ui::Frame& frame, Ui::Column& column, const std::string& key, Tab tab, Loadable<std::vector<T>>& list, std::string_view none, Ui::Box viewport, Make&& row) {
|
||||||
|
if(list.state == LoadState::Failed) {
|
||||||
|
Trouble(frame, column, list.problem, "list.problem", [this, key, tab] { LoadTab(key, tab, true); });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if(list.state != LoadState::Loaded) {
|
||||||
|
Waiting(frame, column, 3);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if(list.value.empty()) {
|
||||||
|
Empty(frame, column, none);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for(const T& item : list.value) {
|
||||||
|
const Box at = column.Take(frame.Dp(Size::row));
|
||||||
|
if(at.Overlaps(viewport)) {
|
||||||
|
ListRow(frame, at, row(item));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void App::AccountField(Ui::Frame& frame, Ui::Column& column, std::string_view key, std::string_view label, const std::string& account, Picking which) {
|
||||||
|
const Theme& theme = frame.Colors();
|
||||||
|
Label(frame, Padded(frame, column.Take(frame.Dp(20))), label, Muted(frame));
|
||||||
|
const Box row = Padded(frame, column.Take(frame.Dp(Size::row)));
|
||||||
|
frame.draw.Rect(RectItem{.box = row, .color = theme.surface, .corners = Corners::All(frame.Dp(Size::controlRadius)), .outline = frame.Dp(1), .outlineColor = theme.divider});
|
||||||
|
const std::optional<AccountRef> chosen = Find(account);
|
||||||
|
const auto pick = [this, which] {
|
||||||
|
picking = which;
|
||||||
|
context.Invalidate();
|
||||||
|
};
|
||||||
|
if(chosen) {
|
||||||
|
ListRow(frame, row, {.key = std::string(key), .title = chosen->account->name, .subtitle = GroupIban(chosen->account->iban), .trailing = Money(chosen->account->balance, chosen->account->currency), .chevron = true, .divider = false, .onTap = pick});
|
||||||
|
} else {
|
||||||
|
ListRow(frame, row, {.key = std::string(key), .title = "Choose an account", .chevron = true, .enabled = !Accounts().empty(), .divider = false, .onTap = pick});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void App::PayPage(Ui::Frame& frame, Ui::Column& column) {
|
||||||
|
const std::optional<AccountRef> from = Find(payFrom);
|
||||||
|
Currency currency = Currency::Euro;
|
||||||
|
if(from) {
|
||||||
|
currency = from->account->currency;
|
||||||
|
}
|
||||||
|
PaymentOrder unused;
|
||||||
|
const PaymentForm::Errors errors = payment.tried ? payment.Check(currency, Today(), unused) : PaymentForm::Errors();
|
||||||
|
AccountField(frame, column, "pay.from", "From", payFrom, Picking::PayFrom);
|
||||||
|
column.Advance(TextField(frame, Padded(frame, column.Next()), payment.to, {.key = "pay.to", .label = "To", .placeholder = "An IBAN, an e-mail address or a phone number", .error = errors.to, .helper = PartyKind(payment.to.value)}));
|
||||||
|
column.Advance(TextField(frame, Padded(frame, column.Next()), payment.name, {.key = "pay.name", .label = "Name", .placeholder = "Who the account belongs to", .error = errors.name, .purpose = TextPurpose::Name}));
|
||||||
|
column.Advance(TextField(frame, Padded(frame, column.Next()), payment.amount, {.key = "pay.amount", .label = "Amount", .prefix = std::string(GetCurrencySymbol(currency)), .error = errors.amount}));
|
||||||
|
column.Advance(TextField(frame, Padded(frame, column.Next()), payment.description, {.key = "pay.description", .label = "Description", .placeholder = "What it is for"}));
|
||||||
|
|
||||||
|
// A connection that pays between the user's own accounts only cannot pay anybody else.
|
||||||
|
const Read<BunqCounterparty> party = ReadParty(payment.to.value);
|
||||||
|
const bool limited = from && from->connection->ownAccountsOnly && !(party.value && party.value->type == "IBAN" && Own(party.value->value));
|
||||||
|
// What the button will do: a payment of such an account to anyone else can only be a draft.
|
||||||
|
const std::size_t when = limited ? std::size_t{2} : std::to_underlying(payment.when);
|
||||||
|
Label(frame, Padded(frame, column.Take(frame.Dp(20))), "When", Muted(frame));
|
||||||
|
Segmented(frame, Padded(frame, column.Take(frame.Dp(Size::control))), {.key = "pay.when", .labels = {"Now", "Scheduled", "Draft"}, .selected = when, .enabled = !limited, .onSelect = [this](std::size_t chosen) {
|
||||||
|
payment.when = static_cast<When>(chosen);
|
||||||
|
context.Invalidate();
|
||||||
|
}});
|
||||||
|
if(limited) {
|
||||||
|
column.Advance(Paragraph(frame, Padded(frame, column.Next()), "This account's connection pays between your own accounts only. A payment to anyone else is saved as a draft, to approve in your bank's app.", Muted(frame)));
|
||||||
|
} else if(payment.when == When::Draft) {
|
||||||
|
column.Advance(Paragraph(frame, Padded(frame, column.Next()), "A draft is paid once it is accepted, here or in your bank's app.", Muted(frame)));
|
||||||
|
} else if(payment.when == When::Scheduled) {
|
||||||
|
column.Advance(TextField(frame, Padded(frame, column.Next()), payment.day, {.key = "pay.day", .label = "First payment", .placeholder = "YYYY-MM-DD", .error = errors.day}));
|
||||||
|
column.Advance(TextField(frame, Padded(frame, column.Next()), payment.time, {.key = "pay.time", .label = "At", .placeholder = "hh:mm", .error = errors.time, .helper = "Leave empty for the start of the day"}));
|
||||||
|
std::vector<std::string> units;
|
||||||
|
for(const ScheduleUnit& unit : scheduleUnits) {
|
||||||
|
units.emplace_back(unit.label);
|
||||||
|
}
|
||||||
|
Tabs(frame, Strip(frame, column.Take(frame.Dp(Size::control))), {.key = "pay.unit", .labels = std::move(units), .selected = payment.unit, .onSelect = [this](std::size_t chosen) {
|
||||||
|
payment.unit = chosen;
|
||||||
|
context.Invalidate();
|
||||||
|
}});
|
||||||
|
if(payment.unit != 0) {
|
||||||
|
column.Advance(TextField(frame, Padded(frame, column.Next()), payment.every, {.key = "pay.every", .label = "Every", .placeholder = "1", .error = errors.every, .helper = "2 with Weekly is every other week"}));
|
||||||
|
column.Advance(TextField(frame, Padded(frame, column.Next()), payment.until, {.key = "pay.until", .label = "Until", .placeholder = "YYYY-MM-DD", .error = errors.until, .helper = "Leave empty to go on until it is cancelled"}));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// It sends what is filled in, and is named for that. Nothing is asked in between: the system's password dialog
|
||||||
|
// is what confirms a payment.
|
||||||
|
static constexpr std::array<std::string_view, 3> does = {"Pay", "Schedule", "Save as draft"};
|
||||||
|
Button(frame, Padded(frame, column.Take(frame.Dp(Size::control))), {.key = "pay.submit", .label = std::string(does[when]), .enabled = from.has_value(), .onTap = [this] { SubmitPayment(); }});
|
||||||
|
}
|
||||||
|
|
||||||
|
void App::RequestPage(Ui::Frame& frame, Ui::Column& column) {
|
||||||
|
const std::optional<AccountRef> into = Find(requestInto);
|
||||||
|
Currency currency = Currency::Euro;
|
||||||
|
if(into) {
|
||||||
|
currency = into->account->currency;
|
||||||
|
}
|
||||||
|
RequestOrder unused;
|
||||||
|
const RequestForm::Errors errors = request.tried ? request.Check(currency, unused) : RequestForm::Errors();
|
||||||
|
AccountField(frame, column, "request.into", "Into", requestInto, Picking::RequestInto);
|
||||||
|
column.Advance(TextField(frame, Padded(frame, column.Next()), request.from, {.key = "request.from", .label = "From", .placeholder = "An IBAN, an e-mail address or a phone number", .error = errors.from, .helper = PartyKind(request.from.value)}));
|
||||||
|
column.Advance(TextField(frame, Padded(frame, column.Next()), request.name, {.key = "request.name", .label = "Name", .placeholder = "Who is asked", .error = errors.name, .purpose = TextPurpose::Name}));
|
||||||
|
column.Advance(TextField(frame, Padded(frame, column.Next()), request.amount, {.key = "request.amount", .label = "Amount", .prefix = std::string(GetCurrencySymbol(currency)), .error = errors.amount}));
|
||||||
|
column.Advance(TextField(frame, Padded(frame, column.Next()), request.description, {.key = "request.description", .label = "Description", .placeholder = "What it is for"}));
|
||||||
|
Button(frame, Padded(frame, column.Take(frame.Dp(Size::control))), {.key = "request.review", .label = "Review", .enabled = into.has_value(), .onTap = [this] { ReviewRequest(); }});
|
||||||
|
}
|
||||||
|
|
||||||
|
void App::CardsPage(Ui::Frame& frame, Ui::Column& column, Ui::Box viewport) {
|
||||||
|
const Theme& theme = frame.Colors();
|
||||||
|
if(cards.state == LoadState::Failed) {
|
||||||
|
Trouble(frame, column, cards.problem, "cards.problem", [this] { LoadCards(true); });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if(cards.state != LoadState::Loaded) {
|
||||||
|
Waiting(frame, column, 3);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
bool any = false;
|
||||||
|
for(const ConnectorCards& connection : cards.value) {
|
||||||
|
if(connection.cards.empty()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
any = true;
|
||||||
|
Section(frame, column, connection.name);
|
||||||
|
for(const BunqCard& card : connection.cards) {
|
||||||
|
const Box row = column.Take(frame.Dp(Size::row));
|
||||||
|
if(!row.Overlaps(viewport)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
ListRow(frame, row, {.key = std::format("card.{}", card.id), .title = std::format("{} •••• {}", CardProduct(card.productType), card.lastFour), .subtitle = Joined(card.nameOnCard, card.expiry.empty() ? std::string() : std::format("until {}", CardExpiry(card.expiry))), .trailing = StatusLabel(card.State()), .trailingColor = card.State() == "ACTIVE" ? std::optional<Color>(theme.positive) : std::nullopt, .chevron = true, .onTap = [this, card] { ShowCard(card); }});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if(!any) {
|
||||||
|
Empty(frame, column, "No cards");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void App::SettingsPage(Ui::Frame& frame, Ui::Column& column) {
|
||||||
|
const std::size_t connected = overview.value.size();
|
||||||
|
ListRow(frame, column.Take(frame.Dp(Size::row)), {.key = "settings.connections", .title = "Bank connections", .subtitle = connected == 1 ? std::string("1 connected") : std::format("{} connected", connected), .chevron = true, .onTap = [this] { Push(Page::Connections); }});
|
||||||
|
std::string paying = "…";
|
||||||
|
if(checkout.state == LoadState::Loaded) {
|
||||||
|
paying = checkout.value ? Joined(checkout.value->name, GroupIban(checkout.value->iban)) : "No account chosen";
|
||||||
|
} else if(checkout.state == LoadState::Failed) {
|
||||||
|
paying = checkout.problem.title;
|
||||||
|
}
|
||||||
|
ListRow(frame, column.Take(frame.Dp(Size::row)), {.key = "settings.checkout", .title = "Pay at checkout from", .subtitle = std::move(paying), .chevron = true, .onTap = [this] { Push(Page::Checkout); }});
|
||||||
|
ListRow(frame, column.Take(frame.Dp(Size::row)), {.key = "settings.about", .title = "About and security", .subtitle = host.version.empty() ? std::string("Nostro") : std::format("Nostro {}", host.version), .chevron = true, .onTap = [this] { Push(Page::About); }});
|
||||||
|
}
|
||||||
|
|
||||||
|
void App::ConnectionsPage(Ui::Frame& frame, Ui::Column& column) {
|
||||||
|
const Theme& theme = frame.Colors();
|
||||||
|
if(overview.state == LoadState::Failed) {
|
||||||
|
Trouble(frame, column, overview.problem, "overview", [this] { Refresh(); });
|
||||||
|
} else if(overview.state != LoadState::Loaded) {
|
||||||
|
Waiting(frame, column, 2);
|
||||||
|
} else if(overview.value.empty()) {
|
||||||
|
Empty(frame, column, "No bank is connected yet");
|
||||||
|
}
|
||||||
|
for(const Connection& connection : overview.value) {
|
||||||
|
// By what tells it from every other: two connections can have one name, and never one account.
|
||||||
|
ListRow(frame, column.Take(frame.Dp(Size::row)), {.key = std::format("connection.{}.{}", connection.name, connection.accounts.empty() ? std::string() : AccountKey(connection.accounts.front())), .title = connection.name, .subtitle = std::format("{} · {} · {}", BankName(connection.bank), StatusLabel(connection.environment), WayName(connection.bank, connection.auth)), .trailing = connection.working ? "Working" : "Not working", .trailingColor = connection.working ? std::optional<Color>(theme.positive) : std::optional<Color>(theme.danger), .chevron = true, .onTap = [this, connection] { ShowConnection(connection); }});
|
||||||
|
}
|
||||||
|
Button(frame, Padded(frame, column.Take(frame.Dp(Size::control))), {.key = "connections.add", .label = "Add a connection", .onTap = [this] { Push(Page::Banks); }});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Adding a connection, its first step: which bank it is with.
|
||||||
|
void App::BanksPage(Ui::Frame& frame, Ui::Column& column) {
|
||||||
|
column.Advance(Paragraph(frame, Padded(frame, column.Next()), "Which bank is the account with?", Body(frame)));
|
||||||
|
for(const Bank& bank : Banks()) {
|
||||||
|
// Under its name, the ways it can be connected.
|
||||||
|
std::string ways;
|
||||||
|
for(const Way& way : bank.ways) {
|
||||||
|
ways += ways.empty() ? std::string(way.title) : std::format(" · {}", way.title);
|
||||||
|
}
|
||||||
|
ListRow(frame, column.Take(frame.Dp(Size::row)), {.key = std::format("bank.{}", bank.id), .title = std::string(bank.name), .subtitle = std::move(ways), .chevron = true, .onTap = [this, chosen = &bank] { Push(Page::Ways, {}, chosen); }});
|
||||||
|
}
|
||||||
|
column.Advance(Paragraph(frame, Padded(frame, column.Next()), "A bank that is not listed here cannot be connected yet.", Muted(frame)));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Its second: how to connect to that bank. Each way leads to a form of its own, which is the bank's to draw.
|
||||||
|
void App::WaysPage(Ui::Frame& frame, Ui::Column& column, const Bank& bank) {
|
||||||
|
column.Advance(Paragraph(frame, Padded(frame, column.Next()), std::format("How do you want to connect to {}?", bank.name), Body(frame)));
|
||||||
|
for(const Way& way : bank.ways) {
|
||||||
|
ListRow(frame, column.Take(frame.Dp(Size::row)), {.key = std::format("way.{}", way.key), .title = std::string(way.title), .subtitle = std::string(way.about), .chevron = true, .onTap = [this, chosen = &bank, how = &way] { Push(Page::Connect, {}, chosen, how); }});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void App::CheckoutPage(Ui::Frame& frame, Ui::Column& column) {
|
||||||
|
column.Advance(Paragraph(frame, Padded(frame, column.Next()), "Other apps can ask Nostro to pay an order at their checkout. Every such payment still asks for your password, and says what is paid and to whom. This is the account they are paid from.", Body(frame)));
|
||||||
|
if(checkout.state == LoadState::Failed) {
|
||||||
|
Trouble(frame, column, checkout.problem, "checkout.problem", [this] { LoadCheckout(); });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if(checkout.state != LoadState::Loaded) {
|
||||||
|
Waiting(frame, column, 2);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if(Accounts().empty()) {
|
||||||
|
Empty(frame, column, "No accounts to choose from");
|
||||||
|
}
|
||||||
|
for(const AccountRef& account : Accounts()) {
|
||||||
|
const bool chosen = checkout.value && AccountKey(*checkout.value) == account.key;
|
||||||
|
// A shop is somebody else: not for a connection that pays between the user's own accounts only.
|
||||||
|
const bool ownOnly = account.connection->ownAccountsOnly;
|
||||||
|
ListRow(frame, column.Take(frame.Dp(Size::row)), {.key = std::format("checkout.{}", account.key), .title = account.account->name, .subtitle = ownOnly ? std::string("Pays your own accounts only, not a shop") : GroupIban(account.account->iban), .trailing = Money(account.account->balance, account.account->currency), .selected = chosen, .enabled = !ownOnly, .onTap = [this, key = account.key, name = account.account->name] { ChooseCheckout(key, name); }});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void App::AboutPage(Ui::Frame& frame, Ui::Column& column) {
|
||||||
|
static constexpr std::array<std::string_view, 5> said = {
|
||||||
|
"Nostro is a banking client for Linux, phones first. It talks to your bank directly.",
|
||||||
|
"Programs you run cannot read your bank connections, which belong to a service of Nostro's own, and cannot move money without your password. This window is one of those programs: it holds no key and no token.",
|
||||||
|
"The password dialog is your desktop's. A program running as you could draw one that looks the same, so type your password only for something you asked for, and read what the dialog says.",
|
||||||
|
"In a session where nothing can ask for your password, whatever needs it is refused.",
|
||||||
|
"The bank connections are not encrypted on disk: whoever holds the disk can read them. Use full-disk encryption.",
|
||||||
|
};
|
||||||
|
for(const std::string_view paragraph : said) {
|
||||||
|
column.Advance(Paragraph(frame, Padded(frame, column.Next()), paragraph, Body(frame)));
|
||||||
|
}
|
||||||
|
column.Advance(Paragraph(frame, Padded(frame, column.Next()), host.version.empty() ? std::string("Nostro, © 2026 Catcrafts. GPL-3.0-only. Set in Noto Sans, under the SIL Open Font License.") : std::format("Nostro {}, © 2026 Catcrafts. GPL-3.0-only. Set in Noto Sans, under the SIL Open Font License.", host.version), Muted(frame)));
|
||||||
|
}
|
||||||
|
|
||||||
|
void App::FilterSheet(Ui::Frame& frame, const AccountRef& account) {
|
||||||
|
const auto close = [this] {
|
||||||
|
filtering.clear();
|
||||||
|
context.Invalidate();
|
||||||
|
};
|
||||||
|
const std::string key = account.key;
|
||||||
|
const Currency currency = account.account->currency;
|
||||||
|
FilterForm& filter = Data(key).filter;
|
||||||
|
TransactionQuery unused;
|
||||||
|
const FilterForm::Errors errors = filter.Check(currency, unused);
|
||||||
|
const FieldOptions amount{.key = "filter.amount", .label = "An exact amount", .prefix = std::string(GetCurrencySymbol(currency)), .error = errors.amount};
|
||||||
|
const FieldOptions from{.key = "filter.from", .label = "From", .placeholder = "YYYY-MM-DD", .error = errors.from};
|
||||||
|
const FieldOptions to{.key = "filter.to", .label = "Until", .placeholder = "YYYY-MM-DD", .error = errors.to};
|
||||||
|
// As tall as what is in it: the three fields, each with what is wrong with it, the choice and the buttons.
|
||||||
|
const float gap = frame.Dp(Size::unit * 3);
|
||||||
|
const float width = SheetBodyWidth(frame);
|
||||||
|
const float height = FieldHeight(frame, width, amount) + FieldHeight(frame, width, from) + FieldHeight(frame, width, to) + frame.Dp(Size::control) * 2 + gap * 4;
|
||||||
|
Sheet(frame, {.key = "filter", .title = "Filter", .contentHeight = height, .onDismiss = close}, [&, this](Box body) {
|
||||||
|
const float offset = frame.BeginScroll("filter.scroll", body);
|
||||||
|
Column column({body.x, body.y - offset, body.w, body.h}, gap);
|
||||||
|
column.Advance(TextField(frame, column.Next(), filter.amount, amount));
|
||||||
|
Segmented(frame, column.Take(frame.Dp(Size::control)), {.key = "filter.direction", .labels = {"Paid", "Received"}, .selected = filter.received ? std::size_t{1} : std::size_t{0}, .onSelect = [this, key](std::size_t chosen) {
|
||||||
|
Data(key).filter.received = chosen == 1;
|
||||||
|
context.Invalidate();
|
||||||
|
}});
|
||||||
|
column.Advance(TextField(frame, column.Next(), filter.from, from));
|
||||||
|
column.Advance(TextField(frame, column.Next(), filter.to, to));
|
||||||
|
Row buttons(column.Take(frame.Dp(Size::control)), gap);
|
||||||
|
Button(frame, buttons.TakeLeft((buttons.area.w - buttons.gap) / 2), {.key = "filter.show", .label = "Show", .enabled = !errors.Any(), .onTap = [this, key] {
|
||||||
|
filtering.clear();
|
||||||
|
Search(key, true);
|
||||||
|
context.Invalidate();
|
||||||
|
}});
|
||||||
|
Button(frame, buttons.Rest(), {.key = "filter.clear", .label = "Clear", .kind = ButtonKind::Tonal, .onTap = [this, key] {
|
||||||
|
Data(key).filter.Reset();
|
||||||
|
filtering.clear();
|
||||||
|
Search(key, true);
|
||||||
|
context.Invalidate();
|
||||||
|
}});
|
||||||
|
frame.EndScroll(column.cursor - (body.y - offset));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
void App::PickSheet(Ui::Frame& frame) {
|
||||||
|
const std::vector<AccountRef> all = Accounts();
|
||||||
|
const std::string& current = picking == Picking::PayFrom ? payFrom : requestInto;
|
||||||
|
const auto close = [this] {
|
||||||
|
picking = Picking::None;
|
||||||
|
context.Invalidate();
|
||||||
|
};
|
||||||
|
Sheet(frame, {.key = "pick", .title = "Choose an account", .contentHeight = frame.Dp(Size::row) * static_cast<float>(all.size()), .onDismiss = close}, [&, this](Box body) {
|
||||||
|
const float offset = frame.BeginScroll("pick.scroll", body);
|
||||||
|
Column column({body.x, body.y - offset, body.w, body.h});
|
||||||
|
for(const AccountRef& account : all) {
|
||||||
|
ListRow(frame, column.Take(frame.Dp(Size::row)), {.key = std::format("pick.{}", account.key), .title = account.account->name, .subtitle = Joined(GroupIban(account.account->iban), account.connection->name), .trailing = Money(account.account->balance, account.account->currency), .selected = account.key == current, .onTap = [this, key = account.key] {
|
||||||
|
(picking == Picking::PayFrom ? payFrom : requestInto) = key;
|
||||||
|
picking = Picking::None;
|
||||||
|
context.Invalidate();
|
||||||
|
}});
|
||||||
|
}
|
||||||
|
frame.EndScroll(column.cursor - (body.y - offset));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
void App::DialogSheet(Ui::Frame& frame) {
|
||||||
|
const Dialog& shown = *dialog;
|
||||||
|
const float gap = frame.Dp(Size::unit * 3);
|
||||||
|
// How far a line's row reaches past the text on either side: what is drawn under a press on it.
|
||||||
|
const float reach = frame.Dp(Size::unit * 2);
|
||||||
|
const TextStyle label = Muted(frame);
|
||||||
|
const TextStyle value = Body(frame);
|
||||||
|
// The lines as rows: a press on one copies what it says.
|
||||||
|
std::vector<ValueOptions> rows;
|
||||||
|
for(const Line& line : shown.lines) {
|
||||||
|
// By what it says; a second line of one label, as a draft's two payments to one payee, by its turn too.
|
||||||
|
const std::ptrdiff_t earlier = std::ranges::count(std::span(shown.lines).first(rows.size()), line.label, &Line::label);
|
||||||
|
const auto copy = [this, text = line.copied.empty() ? line.value : line.copied] {
|
||||||
|
context.Copy(text);
|
||||||
|
Tell("Copied");
|
||||||
|
};
|
||||||
|
rows.push_back({.key = earlier == 0 ? std::format("copy.{}", line.label) : std::format("copy.{}.{}", line.label, earlier + 1), .label = line.label, .value = line.value, .onTap = copy, .onLongPress = copy});
|
||||||
|
}
|
||||||
|
// The body is laid out twice with the same sums: once for how tall the sheet is, once to draw it.
|
||||||
|
const auto layout = [&](Box body, bool draw) {
|
||||||
|
Column column(body, gap);
|
||||||
|
for(const std::string& text : shown.text) {
|
||||||
|
column.Advance(draw ? Paragraph(frame, column.Next(), text, value) : ParagraphHeight(frame, body.w, text, value));
|
||||||
|
}
|
||||||
|
if(!rows.empty()) {
|
||||||
|
// One under the other without the column's gap: each row has its own room.
|
||||||
|
const float width = body.w + reach * 2;
|
||||||
|
float tall = 0;
|
||||||
|
for(const ValueOptions& row : rows) {
|
||||||
|
tall += ValueRowHeight(frame, width, row);
|
||||||
|
}
|
||||||
|
Box at = column.Take(tall);
|
||||||
|
if(draw) {
|
||||||
|
for(const ValueOptions& row : rows) {
|
||||||
|
at.y += ValueRow(frame, {at.x - reach, at.y, width, 0}, row);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Said where a line is all there is to press: nothing about a line looks like a button.
|
||||||
|
if(shown.kind == Dialog::Kind::Detail) {
|
||||||
|
const std::string_view hint = "Press a line to copy it.";
|
||||||
|
column.Advance(draw ? Paragraph(frame, column.Next(), hint, Caption(frame)) : ParagraphHeight(frame, body.w, hint, Caption(frame)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if(!shown.link.empty()) {
|
||||||
|
const float height = ParagraphHeight(frame, body.w, shown.link, label);
|
||||||
|
const Box at = column.Take(height);
|
||||||
|
Row buttons(column.Take(frame.Dp(Size::control)), gap);
|
||||||
|
if(draw) {
|
||||||
|
Paragraph(frame, at, shown.link, label);
|
||||||
|
Button(frame, buttons.TakeLeft((buttons.area.w - buttons.gap) / 2), {.key = "dialog.copy", .label = "Copy the link", .kind = ButtonKind::Tonal, .onTap = [this, link = shown.link] {
|
||||||
|
context.Copy(link);
|
||||||
|
Tell("Link copied");
|
||||||
|
}});
|
||||||
|
Button(frame, buttons.Rest(), {.key = "dialog.open", .label = "Open", .kind = ButtonKind::Tonal, .enabled = host.openUri != nullptr, .onTap = [this, link = shown.link] {
|
||||||
|
host.openUri(link, [this](bool taken) {
|
||||||
|
if(!taken) {
|
||||||
|
Tell("No browser could be opened: copy the link instead");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for(const Choice& choice : shown.choices) {
|
||||||
|
const Box at = column.Take(frame.Dp(Size::control));
|
||||||
|
if(draw) {
|
||||||
|
Button(frame, at, {.key = choice.key, .label = choice.label, .kind = choice.kind, .enabled = choice.enabled, .onTap = choice.onTap});
|
||||||
|
}
|
||||||
|
// Why a thing cannot be done is said under it.
|
||||||
|
if(!choice.enabled && !choice.reason.empty()) {
|
||||||
|
column.Advance(draw ? Paragraph(frame, column.Next(), choice.reason, label) : ParagraphHeight(frame, body.w, choice.reason, label));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return column.Used();
|
||||||
|
};
|
||||||
|
// The change under way cannot be sent off: its answer is what says whether money moved.
|
||||||
|
const std::function<void()> dismiss = shown.kind == Dialog::Kind::Working ? std::function<void()>() : [this] { Close(); };
|
||||||
|
const float height = layout({0, 0, SheetBodyWidth(frame), 0}, false);
|
||||||
|
Sheet(frame, {.key = "dialog", .title = shown.title, .contentHeight = height, .onDismiss = dismiss}, [&](Box body) {
|
||||||
|
// Taller than the window: it scrolls. Its rows are drawn a little wider than its text.
|
||||||
|
const float offset = frame.BeginScroll("dialog.scroll", {body.x - reach, body.y, body.w + reach * 2, body.h});
|
||||||
|
frame.EndScroll(layout({body.x, body.y - offset, body.w, body.h}, true));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
388
implementations/Nostro.DebugCommands.cpp
Normal file
388
implementations/Nostro.DebugCommands.cpp
Normal file
|
|
@ -0,0 +1,388 @@
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
module Nostro.DebugCommands;
|
||||||
|
import std;
|
||||||
|
import Crafter.Debug;
|
||||||
|
import Crafter.Thread;
|
||||||
|
import Nostro.Ui;
|
||||||
|
import Nostro.Ui.Shell;
|
||||||
|
import Nostro.App;
|
||||||
|
|
||||||
|
namespace Debug = Crafter::Debug;
|
||||||
|
namespace fs = std::filesystem;
|
||||||
|
using namespace Nostro;
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
// How often Crafter.Debug is given the loop's thread. It answers what touches the app from there, and counts each
|
||||||
|
// time as a frame whatever the window drew: an agent waits for the event FrameRendered, not for frames.
|
||||||
|
constexpr std::int64_t pumpMs = 50;
|
||||||
|
// What a secret typed through here must begin with: a key of bunq's sandbox, which moves no money.
|
||||||
|
constexpr std::string_view sandboxPrefix = "sandbox_";
|
||||||
|
|
||||||
|
struct KeyArgs {
|
||||||
|
Debug::Required<std::string> key;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct TypeArgs {
|
||||||
|
Debug::Required<std::string> text;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct PressArgs {
|
||||||
|
Debug::Required<Ui::Key> key;
|
||||||
|
bool shift = false;
|
||||||
|
bool control = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct PointArgs {
|
||||||
|
Debug::Required<float> x;
|
||||||
|
Debug::Required<float> y;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct DragArgs {
|
||||||
|
Debug::Required<float> x1;
|
||||||
|
Debug::Required<float> y1;
|
||||||
|
Debug::Required<float> x2;
|
||||||
|
Debug::Required<float> y2;
|
||||||
|
std::int32_t ms = 300;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct WheelArgs {
|
||||||
|
Debug::Required<float> x;
|
||||||
|
Debug::Required<float> y;
|
||||||
|
float detents = 1;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct SizeArgs {
|
||||||
|
Debug::Required<std::uint32_t> width;
|
||||||
|
Debug::Required<std::uint32_t> height;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct RouteArgs {
|
||||||
|
Debug::Required<std::string> route;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct ThemeArgs {
|
||||||
|
Debug::Required<std::string> scheme;
|
||||||
|
};
|
||||||
|
|
||||||
|
// A region as an agent reads it, in dp, as the commands take positions.
|
||||||
|
struct RegionInfo {
|
||||||
|
std::string key;
|
||||||
|
std::string role;
|
||||||
|
std::string label;
|
||||||
|
float x = 0;
|
||||||
|
float y = 0;
|
||||||
|
float width = 0;
|
||||||
|
float height = 0;
|
||||||
|
bool enabled = true;
|
||||||
|
bool focusable = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct ScreenEvent {
|
||||||
|
std::string screen;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct AnswerEvent {
|
||||||
|
std::string member;
|
||||||
|
bool failed = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct FrameEvent {
|
||||||
|
std::uint64_t frame = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct ChangeEvent {
|
||||||
|
bool underWay = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
constexpr std::string_view RoleName(Ui::Role role) noexcept {
|
||||||
|
constexpr std::array<std::string_view, 6> names = {"button", "row", "field", "scroll", "scrim", "panel"};
|
||||||
|
return names[std::to_underlying(role)];
|
||||||
|
}
|
||||||
|
|
||||||
|
constexpr std::string_view LoadName(App::LoadState state) noexcept {
|
||||||
|
constexpr std::array<std::string_view, 4> names = {"idle", "loading", "loaded", "failed"};
|
||||||
|
return names[std::to_underlying(state)];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Debugger::Debugger(DebugTargets targets) : targets(std::move(targets)), pump(this->targets.loop, [this] { Pump(); }) {
|
||||||
|
// The session's transport runs on Crafter.Thread's pool, which nothing else in the app uses.
|
||||||
|
Crafter::ThreadPool::Start();
|
||||||
|
session.emplace(Debug::SessionOptions{.name = "nostro-app", .onQuit = [this] { this->targets.loop.Exit(0); }});
|
||||||
|
Register();
|
||||||
|
if(this->targets.window) {
|
||||||
|
frameBefore = this->targets.window->onFrame;
|
||||||
|
this->targets.window->onFrame = [this] {
|
||||||
|
if(frameBefore) {
|
||||||
|
frameBefore();
|
||||||
|
}
|
||||||
|
Drawn();
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if(this->targets.app != nullptr) {
|
||||||
|
answerBefore = this->targets.app->onAnswer;
|
||||||
|
this->targets.app->onAnswer = [this](std::string_view member, bool failed) {
|
||||||
|
if(answerBefore) {
|
||||||
|
answerBefore(member, failed);
|
||||||
|
}
|
||||||
|
Debug::Emit("AnswerArrived", AnswerEvent{std::string(member), failed});
|
||||||
|
};
|
||||||
|
}
|
||||||
|
pump.After(pumpMs);
|
||||||
|
}
|
||||||
|
|
||||||
|
Debugger::~Debugger() {
|
||||||
|
pump.Cancel();
|
||||||
|
if(targets.window) {
|
||||||
|
targets.window->onFrame = std::move(frameBefore);
|
||||||
|
}
|
||||||
|
if(targets.app != nullptr) {
|
||||||
|
targets.app->onAnswer = std::move(answerBefore);
|
||||||
|
}
|
||||||
|
// The session closes its connections before the pool they run on stops.
|
||||||
|
session.reset();
|
||||||
|
Crafter::ThreadPool::Stop();
|
||||||
|
}
|
||||||
|
|
||||||
|
Debug::Result<> Debugger::Ready() {
|
||||||
|
if(!targets.window) {
|
||||||
|
return Debug::Error{"NoWindow", "the window was closed; the app only waits for the answer to what it asked, and ends then"};
|
||||||
|
}
|
||||||
|
targets.window->Prepare();
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
void Debugger::Pump() {
|
||||||
|
if(targets.app != nullptr) {
|
||||||
|
// Said before the session looks at what is waited for, so that a wait for either is answered in this turn.
|
||||||
|
if(std::string now = targets.app->Screen(); now != screen) {
|
||||||
|
screen = std::move(now);
|
||||||
|
Debug::Emit("Screen", ScreenEvent{screen});
|
||||||
|
}
|
||||||
|
if(const bool now = targets.app->Changing(); now != changing) {
|
||||||
|
changing = now;
|
||||||
|
Debug::Emit("Changing", ChangeEvent{changing});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Debug::Pump();
|
||||||
|
pump.After(pumpMs);
|
||||||
|
}
|
||||||
|
|
||||||
|
void Debugger::Drawn() {
|
||||||
|
Ui::Shell::Canvas& surface = targets.window->Surface();
|
||||||
|
const Ui::Shell::Canvas::Stats& stats = surface.Last();
|
||||||
|
Debug::Check(!stats.overflowed, "ui", "a frame had more to draw than the window's buffers hold: {} boxes and {} glyphs in {} passes", stats.boxes, stats.glyphs, stats.batches);
|
||||||
|
// On a phone's screen, what can be pressed is as large as a finger needs.
|
||||||
|
const Ui::Frame& shown = targets.context.Shown();
|
||||||
|
if(shown.sizeClass == Ui::SizeClass::Compact) {
|
||||||
|
for(const Ui::Region& region : targets.context.Regions()) {
|
||||||
|
const float least = std::min(region.box.w, region.box.h) / surface.Scale();
|
||||||
|
Debug::Check(!region.onTap || !region.enabled || region.role == Ui::Role::Scrim || least >= Ui::Size::touch, "ui", "'{}' takes a press on {} by {} dp: less than a finger needs", region.key, region.box.w / surface.Scale(), region.box.h / surface.Scale());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Debug::Emit("FrameRendered", FrameEvent{surface.Frames()});
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<std::byte> Debugger::Capture() {
|
||||||
|
// Drawn and written at once, then read back: the app and whoever asked are in different sandboxes, so the picture
|
||||||
|
// travels over the session and not as a file's name.
|
||||||
|
fs::create_directories(targets.scratch);
|
||||||
|
const fs::path file = targets.scratch / "debug-capture.png";
|
||||||
|
targets.window->Screenshot(file);
|
||||||
|
std::vector<std::byte> png;
|
||||||
|
{
|
||||||
|
std::ifstream in(file, std::ios::binary);
|
||||||
|
const std::string bytes((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
|
||||||
|
png.resize(bytes.size());
|
||||||
|
std::ranges::transform(bytes, png.begin(), [](char byte) { return static_cast<std::byte>(byte); });
|
||||||
|
}
|
||||||
|
std::error_code ignored;
|
||||||
|
fs::remove(file, ignored);
|
||||||
|
return png;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Debugger::Register() {
|
||||||
|
Ui::Context& context = targets.context;
|
||||||
|
const auto scale = [this] { return targets.window->Surface().Scale(); };
|
||||||
|
|
||||||
|
// -- the window, by what is on it ----------------------------------------------------------------------------
|
||||||
|
Debug::Command("Ui_Tap", "Tap what has that key, as a finger on it; `get ui.regions` lists what the screen has.", [this, &context](const KeyArgs& args) -> Debug::Result<> {
|
||||||
|
if(Debug::Result<> ready = Ready(); !ready) {
|
||||||
|
return ready;
|
||||||
|
}
|
||||||
|
if(!context.Tap(*args.key)) {
|
||||||
|
return Debug::Error{"NoRegion", std::format("nothing with the key '{}' can be tapped now; `get ui.regions` lists what the screen has", *args.key)};
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
});
|
||||||
|
Debug::Command("Ui_LongPress", "Hold what has that key, as a finger kept on it or the secondary button.", [this, &context](const KeyArgs& args) -> Debug::Result<> {
|
||||||
|
if(Debug::Result<> ready = Ready(); !ready) {
|
||||||
|
return ready;
|
||||||
|
}
|
||||||
|
if(!context.LongPress(*args.key)) {
|
||||||
|
return Debug::Error{"NoRegion", std::format("nothing with the key '{}' answers to being held; `get ui.regions` lists what the screen has", *args.key)};
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
});
|
||||||
|
Debug::Command("Ui_Focus", "Give what has that key the keyboard's focus, as Tab reaching it; an empty key takes the focus away.", [this, &context](const KeyArgs& args) -> Debug::Result<> {
|
||||||
|
if(Debug::Result<> ready = Ready(); !ready) {
|
||||||
|
return ready;
|
||||||
|
}
|
||||||
|
const Ui::Region* const region = context.Find(*args.key);
|
||||||
|
if(!args.key->empty() && (region == nullptr || !region->focusable)) {
|
||||||
|
return Debug::Error{"NoRegion", std::format("nothing with the key '{}' takes the focus; `get ui.regions` says what does", *args.key)};
|
||||||
|
}
|
||||||
|
context.Focus(*args.key);
|
||||||
|
return {};
|
||||||
|
});
|
||||||
|
Debug::Command("Ui_Type", "Type text into the field that has the focus (Ui_Tap or Ui_Focus it first). A field that hides what it holds takes only a key of bunq's sandbox, sandbox_…: what is typed here is logged.", [this, &context](const TypeArgs& args) -> Debug::Result<> {
|
||||||
|
if(Debug::Result<> ready = Ready(); !ready) {
|
||||||
|
return ready;
|
||||||
|
}
|
||||||
|
const Ui::Region* const field = context.Find(context.Focused());
|
||||||
|
if(field == nullptr || field->edit == nullptr) {
|
||||||
|
return Debug::Error{"NoField", "no field has the focus; Ui_Tap one first"};
|
||||||
|
}
|
||||||
|
if(field->edit->kind == Ui::FieldKind::Secret && !std::format("{}{}", field->edit->value, *args.text).starts_with(sandboxPrefix)) {
|
||||||
|
return Debug::Error{"NotSandbox", std::format("'{}' hides what it holds, and takes only a key that begins with {} through here: a real key has no place in a build that logs what it is told", field->key, sandboxPrefix)};
|
||||||
|
}
|
||||||
|
context.Text(*args.text);
|
||||||
|
return {};
|
||||||
|
});
|
||||||
|
Debug::Command("Ui_Key", "Press a key: Enter, Escape, Tab, Space, Backspace, Delete, Left, Right, Up, Down, Home, End, PageUp, PageDown, F5, or A, C, F, R, V, X with control=true.", [this, &context](const PressArgs& args) -> Debug::Result<> {
|
||||||
|
if(Debug::Result<> ready = Ready(); !ready) {
|
||||||
|
return ready;
|
||||||
|
}
|
||||||
|
context.KeyDown(*args.key, {.shift = args.shift, .control = args.control});
|
||||||
|
return {};
|
||||||
|
});
|
||||||
|
|
||||||
|
// -- the window, by where things are; positions are in dp ----------------------------------------------------
|
||||||
|
Debug::Command("Ui_TapAt", "Tap a point of the window, in dp from its top left.", [this, &context, scale](const PointArgs& args) -> Debug::Result<> {
|
||||||
|
if(Debug::Result<> ready = Ready(); !ready) {
|
||||||
|
return ready;
|
||||||
|
}
|
||||||
|
const Ui::Point at{*args.x * scale(), *args.y * scale()};
|
||||||
|
const std::int64_t now = Ui::Shell::NowMs();
|
||||||
|
context.Pointer(Ui::PointerPhase::Down, at, now - 60);
|
||||||
|
context.Pointer(Ui::PointerPhase::Up, at, now);
|
||||||
|
return {};
|
||||||
|
});
|
||||||
|
Debug::Command("Ui_Drag", "Drag a finger from one point to another, in dp, over so many milliseconds; a quick one flings a list.", [this, &context, scale](const DragArgs& args) -> Debug::Result<> {
|
||||||
|
if(Debug::Result<> ready = Ready(); !ready) {
|
||||||
|
return ready;
|
||||||
|
}
|
||||||
|
// As if it had just happened: its last moment is now, so that what it sets moving goes on from here.
|
||||||
|
constexpr std::int64_t every = 16;
|
||||||
|
const std::int64_t moves = std::max<std::int64_t>(1, args.ms / every);
|
||||||
|
const std::int64_t start = Ui::Shell::NowMs() - moves * every;
|
||||||
|
const Ui::Point from{*args.x1 * scale(), *args.y1 * scale()};
|
||||||
|
const Ui::Point to{*args.x2 * scale(), *args.y2 * scale()};
|
||||||
|
context.Pointer(Ui::PointerPhase::Down, from, start);
|
||||||
|
for(std::int64_t i = 1; i <= moves; i++) {
|
||||||
|
const float part = static_cast<float>(i) / static_cast<float>(moves);
|
||||||
|
context.Pointer(Ui::PointerPhase::Move, {from.x + (to.x - from.x) * part, from.y + (to.y - from.y) * part}, start + i * every);
|
||||||
|
}
|
||||||
|
context.Pointer(Ui::PointerPhase::Up, to, start + moves * every);
|
||||||
|
return {};
|
||||||
|
});
|
||||||
|
Debug::Command("Ui_Wheel", "Turn the wheel over a point, in dp; positive detents scroll down.", [this, &context, scale](const WheelArgs& args) -> Debug::Result<> {
|
||||||
|
if(Debug::Result<> ready = Ready(); !ready) {
|
||||||
|
return ready;
|
||||||
|
}
|
||||||
|
context.Wheel({*args.x * scale(), *args.y * scale()}, args.detents);
|
||||||
|
return {};
|
||||||
|
});
|
||||||
|
Debug::Command("Window_Resize", "Ask for another size of the window, in dp. A compositor that tiles or maximises the window keeps its own; another scale takes a new start with --scale.", [this](const SizeArgs& args) -> Debug::Result<> {
|
||||||
|
if(Debug::Result<> ready = Ready(); !ready) {
|
||||||
|
return ready;
|
||||||
|
}
|
||||||
|
if(*args.width == 0 || *args.height == 0) {
|
||||||
|
return Debug::Error{"BadSize", "a width and a height above 0, in dp"};
|
||||||
|
}
|
||||||
|
targets.window->Surface().SetSize(*args.width, *args.height);
|
||||||
|
return {};
|
||||||
|
});
|
||||||
|
Debug::Command("Ui_Theme", "Set the look: light, dark, or system for the desktop's.", [this](const ThemeArgs& args) -> Debug::Result<> {
|
||||||
|
if(*args.scheme != "light" && *args.scheme != "dark" && *args.scheme != "system") {
|
||||||
|
return Debug::Error{"BadScheme", std::format("unknown look '{}': light, dark or system", *args.scheme)};
|
||||||
|
}
|
||||||
|
targets.setTheme(*args.scheme);
|
||||||
|
return {};
|
||||||
|
});
|
||||||
|
|
||||||
|
// -- the app -------------------------------------------------------------------------------------------------
|
||||||
|
Debug::Command("App_Navigate", "Go to a place of the app: accounts, cards, settings, connections, checkout, about, account:<IBAN> once the accounts are known, or a step of adding a connection: add, add:<bank>, add:<bank>:<way> (add:bunq:key).", [this](const RouteArgs& args) -> Debug::Result<> {
|
||||||
|
if(targets.app == nullptr) {
|
||||||
|
return Debug::Error{"NoApp", "the toolkit's gallery is shown, not the app; start without --gallery"};
|
||||||
|
}
|
||||||
|
if(Debug::Result<> ready = Ready(); !ready) {
|
||||||
|
return ready;
|
||||||
|
}
|
||||||
|
if(targets.app->Changing()) {
|
||||||
|
return Debug::Error{"Changing", "a change is under way, which the screen waits out; wait 'app.changing == false' first"};
|
||||||
|
}
|
||||||
|
if(!targets.app->Navigate(*args.route)) {
|
||||||
|
return Debug::Error{"NoRoute", std::format("'{}' is no place of the app, or an account it does not know (yet: wait for the event AnswerArrived)", *args.route)};
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
});
|
||||||
|
|
||||||
|
// -- what can be read ----------------------------------------------------------------------------------------
|
||||||
|
Debug::Watch("ui.regions", [this, &context, scale] {
|
||||||
|
std::vector<RegionInfo> regions;
|
||||||
|
if(!Ready()) {
|
||||||
|
return regions;
|
||||||
|
}
|
||||||
|
const float px = scale();
|
||||||
|
for(const Ui::Region& region : context.Regions()) {
|
||||||
|
regions.push_back({region.key, std::string(RoleName(region.role)), region.label, region.box.x / px, region.box.y / px, region.box.w / px, region.box.h / px, region.enabled, region.focusable});
|
||||||
|
}
|
||||||
|
return regions;
|
||||||
|
}, {.help = "what the screen has that can be pressed, from the bottom up, in dp"});
|
||||||
|
Debug::Watch("ui.texts", [this, &context] { return Ready() ? context.Shown().draw.Texts() : std::vector<std::string>(); }, {.help = "every line of text the screen shows, in the order it is drawn"});
|
||||||
|
Debug::Watch("ui.focus", [&context] { return std::string(context.Focused()); }, {.help = "the key of what has the keyboard's focus"});
|
||||||
|
Debug::Watch("ui.menu", [&context] { return context.MenuOpen(); }, {.help = "whether a menu is open; its choices are the regions menu.0, menu.1, …"});
|
||||||
|
Debug::Watch("ui.sizeClass", [this, &context] {
|
||||||
|
constexpr std::array<std::string_view, 3> names = {"compact", "medium", "expanded"};
|
||||||
|
return Ready() ? std::string(names[std::to_underlying(context.Shown().sizeClass)]) : std::string();
|
||||||
|
}, {.help = "compact under 600 dp wide, medium under 900, expanded from there"});
|
||||||
|
Debug::Watch("window.width", [this] { return targets.window ? targets.window->Surface().Bounds().w / targets.window->Surface().Scale() : 0.0f; }, {.help = "dp"});
|
||||||
|
Debug::Watch("window.height", [this] { return targets.window ? targets.window->Surface().Bounds().h / targets.window->Surface().Scale() : 0.0f; }, {.help = "dp"});
|
||||||
|
Debug::Watch("window.scale", [this] { return targets.window ? targets.window->Surface().Scale() : 0.0f; }, {.help = "pixels per dp"});
|
||||||
|
Debug::Watch("window.frames", [this] { return targets.window ? targets.window->Surface().Frames() : std::uint64_t{0}; }, {.help = "frames drawn so far; none is drawn while nothing changes"});
|
||||||
|
Debug::Watch("window.passes", [this] { return targets.window ? targets.window->Surface().Last().batches : std::uint32_t{0}; }, {.help = "of the last frame"});
|
||||||
|
Debug::Watch("window.boxes", [this] { return targets.window ? targets.window->Surface().Last().boxes : std::uint32_t{0}; }, {.help = "of the last frame"});
|
||||||
|
Debug::Watch("window.glyphs", [this] { return targets.window ? targets.window->Surface().Last().glyphs : std::uint32_t{0}; }, {.help = "of the last frame"});
|
||||||
|
if(targets.app != nullptr) {
|
||||||
|
const App::App& app = *targets.app;
|
||||||
|
Debug::Watch("app.screen", [&app] { return app.Screen(); }, {.help = "where the user is, with what is open over it after a +"});
|
||||||
|
Debug::Watch("app.busy", [&app] { return app.Busy(); }, {.help = "whether nostrod is being waited for"});
|
||||||
|
Debug::Watch("app.changing", [&app] { return app.Changing(); }, {.help = "whether a change is under way: its answer says whether money moved"});
|
||||||
|
Debug::Watch("app.overview", [&app] { return std::string(LoadName(app.Overview().state)); }, {.help = "how far the reading of the connections is: idle, loading, loaded or failed"});
|
||||||
|
Debug::Watch("app.connections", [&app] { return app.Overview().value.size(); }, {.help = "bank connections known"});
|
||||||
|
Debug::Watch("app.accounts", [&app] {
|
||||||
|
std::size_t accounts = 0;
|
||||||
|
for(const App::Connection& connection : app.Overview().value) {
|
||||||
|
accounts += connection.accounts.size();
|
||||||
|
}
|
||||||
|
return accounts;
|
||||||
|
}, {.help = "accounts known, over every connection"});
|
||||||
|
Debug::Watch("oauth.state", [&app] { return std::string(app.OAuthState()); }, {.help = "the state of the OAuth request being made, which the browser's answer must carry"});
|
||||||
|
}
|
||||||
|
|
||||||
|
Debug::SetCapture([this] {
|
||||||
|
return Debug::Async<std::vector<std::byte>>([this]() -> std::optional<Debug::Result<std::vector<std::byte>>> {
|
||||||
|
if(Debug::Result<> ready = Ready(); !ready) {
|
||||||
|
return Debug::Result<std::vector<std::byte>>(ready.GetError());
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return Debug::Result<std::vector<std::byte>>(Capture());
|
||||||
|
} catch(const std::exception& error) {
|
||||||
|
return Debug::Result<std::vector<std::byte>>(Debug::Error{"NoPicture", std::format("the window could not be drawn for a picture: {}", error.what())});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
907
implementations/Nostro.Ui-Context.cpp
Normal file
907
implementations/Nostro.Ui-Context.cpp
Normal file
|
|
@ -0,0 +1,907 @@
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
module Nostro.Ui:Context_impl;
|
||||||
|
import std;
|
||||||
|
import :Context;
|
||||||
|
import :Geometry;
|
||||||
|
import :Text;
|
||||||
|
import :Edit;
|
||||||
|
import :Gesture;
|
||||||
|
import :Draw;
|
||||||
|
import :Theme;
|
||||||
|
import :Input;
|
||||||
|
|
||||||
|
using namespace Nostro::Ui;
|
||||||
|
|
||||||
|
std::string Nostro::Ui::FieldText(const EditState& edit, bool masked) {
|
||||||
|
const std::string shown = edit.Shown();
|
||||||
|
if(!masked) {
|
||||||
|
return shown;
|
||||||
|
}
|
||||||
|
std::string dots;
|
||||||
|
for(std::size_t i = CountCodepoints(shown); i > 0; i--) {
|
||||||
|
dots += "•";
|
||||||
|
}
|
||||||
|
return dots;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Nostro::Ui::CaretFollowedGrowth(Box told, float toldHeight, Box caret, float height) noexcept {
|
||||||
|
const float grown = height - toldHeight;
|
||||||
|
if(grown <= 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const auto near = [](float a, float b) { return std::abs(a - b) <= 1.0f; };
|
||||||
|
return near(caret.x, told.x) && near(caret.w, told.w) && near(caret.h, told.h) && near(caret.y - told.y, grown);
|
||||||
|
}
|
||||||
|
|
||||||
|
Frame::Frame(Context& context, Box bounds, float scale, std::int64_t nowMs) : context(context), draw(context.Measure(), bounds), bounds(bounds), metrics{scale}, sizeClass(SizeClassFor(bounds.w, scale)), nowMs(nowMs) {
|
||||||
|
}
|
||||||
|
|
||||||
|
float Frame::Dp(float dp) const noexcept {
|
||||||
|
return metrics.Dp(dp);
|
||||||
|
}
|
||||||
|
|
||||||
|
const Theme& Frame::Colors() const noexcept {
|
||||||
|
return context.theme;
|
||||||
|
}
|
||||||
|
|
||||||
|
const TextMeasure& Frame::Measure() const noexcept {
|
||||||
|
return context.Measure();
|
||||||
|
}
|
||||||
|
|
||||||
|
WordWrapper& Frame::Wrapper() noexcept {
|
||||||
|
return context.Wrapper();
|
||||||
|
}
|
||||||
|
|
||||||
|
void Frame::Add(Region region) {
|
||||||
|
// What a scrim covers is out of the keyboard's reach as it is out of a finger's: the shortcuts named so far are
|
||||||
|
// the covered screen's.
|
||||||
|
if(region.role == Role::Scrim) {
|
||||||
|
shortcuts.clear();
|
||||||
|
}
|
||||||
|
region.layer = draw.CurrentLayer();
|
||||||
|
region.hit = region.box.Intersect(scrolls.empty() ? bounds : scrolls.back().viewport);
|
||||||
|
if(!scrolls.empty()) {
|
||||||
|
region.scroll = scrolls.back().key;
|
||||||
|
region.scrollTop = scrolls.back().viewport.y;
|
||||||
|
}
|
||||||
|
regions.push_back(std::move(region));
|
||||||
|
}
|
||||||
|
|
||||||
|
void Frame::Shortcut(Key key, Modifiers modifiers, std::function<void()> action) {
|
||||||
|
shortcuts.push_back({key, modifiers, std::move(action)});
|
||||||
|
}
|
||||||
|
|
||||||
|
float Frame::BeginScroll(std::string_view key, Box viewport) {
|
||||||
|
Region area;
|
||||||
|
area.box = viewport;
|
||||||
|
area.key = std::string(key);
|
||||||
|
area.role = Role::Scroll;
|
||||||
|
Add(std::move(area));
|
||||||
|
scrolls.push_back({std::string(key), viewport.Intersect(bounds)});
|
||||||
|
draw.PushClip(viewport);
|
||||||
|
ScrollState& state = context.Scroll(key);
|
||||||
|
state.viewport = viewport.h;
|
||||||
|
// By whole pixels: a list that came to rest between two would draw every row's text and hairline across both.
|
||||||
|
return std::round(state.offset);
|
||||||
|
}
|
||||||
|
|
||||||
|
void Frame::EndScroll(float contentHeight) {
|
||||||
|
ScrollState& state = context.Scroll(scrolls.back().key);
|
||||||
|
state.content = contentHeight;
|
||||||
|
const float before = state.offset;
|
||||||
|
state.Clamp();
|
||||||
|
if(state.offset != before) {
|
||||||
|
// Drawn at an offset the content no longer reaches: the next frame draws it where it belongs.
|
||||||
|
context.Redraw();
|
||||||
|
}
|
||||||
|
draw.PopClip();
|
||||||
|
scrolls.pop_back();
|
||||||
|
}
|
||||||
|
|
||||||
|
void Frame::Refreshable(std::function<void()> refresh) {
|
||||||
|
std::ranges::find(regions, scrolls.back().key, &Region::key)->onRefresh = std::move(refresh);
|
||||||
|
}
|
||||||
|
|
||||||
|
float Frame::Pulled() const noexcept {
|
||||||
|
return context.scrollKey == scrolls.back().key ? context.pull : 0.0f;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Frame::Hovered(std::string_view key) const noexcept {
|
||||||
|
return context.hoverKey == key;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Frame::Pressed(std::string_view key) const noexcept {
|
||||||
|
return !context.pressTaken && context.pressedKey == key;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Frame::Focused(std::string_view key) const noexcept {
|
||||||
|
return context.focusKey == key;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Frame::FocusRing(std::string_view key) const noexcept {
|
||||||
|
return context.focusByKeyboard && context.focusKey == key;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Frame::CaretOn() const noexcept {
|
||||||
|
const std::int64_t since = nowMs - context.caretSince;
|
||||||
|
return since >= Context::caretIdleMs || (since / 500) % 2 == 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
Context::Context(TextMeasure measure) : wrapper(std::move(measure)) {
|
||||||
|
}
|
||||||
|
|
||||||
|
const TextMeasure& Context::Measure() const noexcept {
|
||||||
|
return wrapper.Measure();
|
||||||
|
}
|
||||||
|
|
||||||
|
WordWrapper& Context::Wrapper() noexcept {
|
||||||
|
return wrapper;
|
||||||
|
}
|
||||||
|
|
||||||
|
float Context::Dp(float dp) const noexcept {
|
||||||
|
return std::round(dp * scale);
|
||||||
|
}
|
||||||
|
|
||||||
|
Frame& Context::Begin(Box bounds, float newScale, std::int64_t nowMs) {
|
||||||
|
scale = newScale > 0 ? newScale : 1.0f;
|
||||||
|
window = bounds;
|
||||||
|
now = nowMs;
|
||||||
|
frame.emplace(*this, bounds, scale, nowMs);
|
||||||
|
return *frame;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Context::End() {
|
||||||
|
Frame& ended = *frame;
|
||||||
|
// The notice first: a menu that is open at its place is over it.
|
||||||
|
if(!notice.empty()) {
|
||||||
|
DrawNotice(ended);
|
||||||
|
}
|
||||||
|
if(menu) {
|
||||||
|
DrawMenu(ended);
|
||||||
|
}
|
||||||
|
// From the bottom up: by layer, and within a layer in the order they were added.
|
||||||
|
std::ranges::stable_sort(ended.regions, {}, &Region::layer);
|
||||||
|
regions = std::exchange(ended.regions, {});
|
||||||
|
shortcuts = std::exchange(ended.shortcuts, {});
|
||||||
|
built = true;
|
||||||
|
const Region* const had = focusKey.empty() ? nullptr : Find(focusKey);
|
||||||
|
const Region* focused = FocusedRegion();
|
||||||
|
if(focused == nullptr) {
|
||||||
|
// What had the focus is not on this screen, cannot be used on it, or is under a sheet now: the focus is let go.
|
||||||
|
if(had != nullptr) {
|
||||||
|
// The word being composed in a field goes into it, as the field showed it: the input method is let go with
|
||||||
|
// the focus. And this frame still drew the focus where it was, so it is drawn again without.
|
||||||
|
if(had->edit != nullptr) {
|
||||||
|
had->edit->CommitPreedit();
|
||||||
|
}
|
||||||
|
wants.redraw = true;
|
||||||
|
}
|
||||||
|
focusKey.clear();
|
||||||
|
focusByKeyboard = false;
|
||||||
|
} else if(window.h != builtHeight && focused->edit != nullptr) {
|
||||||
|
// The window's height changed under a field, as when the on-screen keyboard comes: the field stays in view.
|
||||||
|
Reveal(*focused);
|
||||||
|
}
|
||||||
|
builtHeight = window.h;
|
||||||
|
UpdateTextInput(window.h);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Context::Built() const noexcept {
|
||||||
|
return built;
|
||||||
|
}
|
||||||
|
|
||||||
|
const Frame& Context::Shown() const {
|
||||||
|
return *frame;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::span<const Region> Context::Regions() const noexcept {
|
||||||
|
return regions;
|
||||||
|
}
|
||||||
|
|
||||||
|
const Region* Context::Find(std::string_view key) const noexcept {
|
||||||
|
const auto found = std::ranges::find(regions, key, &Region::key);
|
||||||
|
return found == regions.end() ? nullptr : &*found;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Context::Stale() {
|
||||||
|
regions.clear();
|
||||||
|
shortcuts.clear();
|
||||||
|
built = false;
|
||||||
|
wants.redraw = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Context::Invalidate() {
|
||||||
|
Stale();
|
||||||
|
menu.reset();
|
||||||
|
// The screen changed under the press that is down: its release is no tap on what the next frame draws there.
|
||||||
|
gestures.Feed(PointerPhase::Cancel, Point(), now);
|
||||||
|
pressedKey.clear();
|
||||||
|
scrollKey.clear();
|
||||||
|
pressTaken = false;
|
||||||
|
pull = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Context::Redraw() noexcept {
|
||||||
|
wants.redraw = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
const Region* Context::HitTest(Point at) const noexcept {
|
||||||
|
for(const Region& region : std::views::reverse(regions)) {
|
||||||
|
if(region.hit.Contains(at)) {
|
||||||
|
return ®ion;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The scrolling area a drag or the wheel at a point moves: the topmost one there, unless a sheet or a bar lies over it.
|
||||||
|
const Region* Context::ScrollUnder(Point at) const noexcept {
|
||||||
|
for(const Region& region : std::views::reverse(regions)) {
|
||||||
|
if(!region.hit.Contains(at)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if(region.role == Role::Scroll) {
|
||||||
|
return ®ion;
|
||||||
|
}
|
||||||
|
if(region.role == Role::Scrim || region.role == Role::Panel) {
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Whether a sheet covers a region: a scrim above it. A menu's scrim, in the topmost layer, is no sheet's: a menu
|
||||||
|
// belongs to what it was opened on, which keeps the focus under it.
|
||||||
|
bool Context::UnderSheet(const Region& region) const noexcept {
|
||||||
|
const std::span<const Region> above = std::span<const Region>(regions).subspan(static_cast<std::size_t>(®ion - regions.data()) + 1);
|
||||||
|
return std::ranges::any_of(above, [](const Region& other) { return other.role == Role::Scrim && other.layer != Layer::Popup; });
|
||||||
|
}
|
||||||
|
|
||||||
|
// What the keyboard acts on. Not something a sheet covers: that is out of the keyboard's reach as it is out of a
|
||||||
|
// finger's, so a key meant for the sheet presses nothing under it, the button that brought the sheet least of all, and
|
||||||
|
// nothing is typed there.
|
||||||
|
const Region* Context::FocusedRegion() const noexcept {
|
||||||
|
if(focusKey.empty()) {
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
const Region* region = Find(focusKey);
|
||||||
|
return region != nullptr && region->enabled && !UnderSheet(*region) ? region : nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Context::Pointer(PointerPhase phase, Point at, std::int64_t tMs) {
|
||||||
|
eventTime = tMs;
|
||||||
|
if(phase == PointerPhase::Down) {
|
||||||
|
// The slop and the fling's least speed follow the window's scale, like every other distance.
|
||||||
|
gestures.slopPx = Dp(8);
|
||||||
|
gestures.flingMinPxPerS = Dp(60);
|
||||||
|
pressTaken = false;
|
||||||
|
const Region* target = HitTest(at);
|
||||||
|
pressedKey = target != nullptr ? target->key : std::string();
|
||||||
|
// Only a region with something to open has a long press. A press on anything else stays that control's tap at
|
||||||
|
// its release, however long it was held: a slow finger presses the button all the same.
|
||||||
|
gestures.longPress = target != nullptr && target->enabled && (target->onLongPress != nullptr || target->edit != nullptr);
|
||||||
|
const Region* area = ScrollUnder(at);
|
||||||
|
scrollKey = area != nullptr ? area->key : std::string();
|
||||||
|
if(area != nullptr) {
|
||||||
|
// A finger down stops the fling under it.
|
||||||
|
Scroll(area->key).velocity = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Handle(gestures.Feed(phase, at, tMs));
|
||||||
|
if(phase == PointerPhase::Up || phase == PointerPhase::Cancel) {
|
||||||
|
// A list pulled far enough down and let go is read again, if the frame still has it so.
|
||||||
|
const Region* const area = Find(scrollKey);
|
||||||
|
if(phase == PointerPhase::Up && pull >= Dp(Size::pull) && area != nullptr && area->onRefresh) {
|
||||||
|
const std::function<void()> refresh = area->onRefresh;
|
||||||
|
refresh();
|
||||||
|
}
|
||||||
|
pull = 0;
|
||||||
|
pressedKey.clear();
|
||||||
|
scrollKey.clear();
|
||||||
|
pressTaken = false;
|
||||||
|
}
|
||||||
|
wants.redraw = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Context::Handle(const GestureEvent& event) {
|
||||||
|
if(event.kind == GestureEvent::Kind::Tap || event.kind == GestureEvent::Kind::LongPress) {
|
||||||
|
// A tap or a long press acts on what the press went down on. When a frame built meanwhile moved something else
|
||||||
|
// under the finger, the list having been read again, that names another region, and the release acts on nothing.
|
||||||
|
const Region* target = HitTest(event.at);
|
||||||
|
if(target == nullptr || target->key != pressedKey || !target->enabled) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if(event.kind == GestureEvent::Kind::Tap) {
|
||||||
|
Activate(*target, event.at);
|
||||||
|
} else {
|
||||||
|
pressTaken = true;
|
||||||
|
Held(*target, event.at);
|
||||||
|
}
|
||||||
|
} else if(event.kind == GestureEvent::Kind::DragStart || event.kind == GestureEvent::Kind::Drag) {
|
||||||
|
pressTaken = true;
|
||||||
|
// What moves under a pointer that drags it is not what the pointer rests on.
|
||||||
|
hoverKey.clear();
|
||||||
|
if(!scrollKey.empty()) {
|
||||||
|
ScrollState& state = Scroll(scrollKey);
|
||||||
|
const Region* const area = Find(scrollKey);
|
||||||
|
// A list that can be read again gives way when it is dragged down at its top, by half the finger's way, and
|
||||||
|
// comes back up the same way before it scrolls again.
|
||||||
|
if(area != nullptr && area->onRefresh && state.offset <= 0 && (pull > 0 || event.delta.y > 0)) {
|
||||||
|
pull = std::max(0.0f, pull + event.delta.y / 2);
|
||||||
|
} else {
|
||||||
|
state.ScrollBy(-event.delta.y);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if(event.kind == GestureEvent::Kind::Fling && !scrollKey.empty()) {
|
||||||
|
Scroll(scrollKey).Fling(-event.velocity.y);
|
||||||
|
// The fling moves on from the release's own time.
|
||||||
|
lastTick = eventTime;
|
||||||
|
wants.animating = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void Context::Activate(const Region& region, Point at) {
|
||||||
|
if(region.role == Role::Field) {
|
||||||
|
TapField(region, at);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if(region.role == Role::Scroll || region.role == Role::Panel) {
|
||||||
|
// Bare ground: the field that had the focus lets go of it, and the on-screen keyboard goes.
|
||||||
|
MoveFocus({}, false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// A press with the pointer shows no focus ring; a field keeps the focus it has, and its keyboard.
|
||||||
|
focusByKeyboard = false;
|
||||||
|
if(region.onTap) {
|
||||||
|
// A copy: the action may change the screen, and the regions go with it.
|
||||||
|
const std::function<void()> action = region.onTap;
|
||||||
|
pointed = at;
|
||||||
|
EndComposition();
|
||||||
|
action();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void Context::Held(const Region& region, Point at) {
|
||||||
|
if(region.edit != nullptr) {
|
||||||
|
FieldMenu(region, at);
|
||||||
|
} else if(region.onLongPress) {
|
||||||
|
const std::function<void()> action = region.onLongPress;
|
||||||
|
pointed = at;
|
||||||
|
EndComposition();
|
||||||
|
action();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The word the input method is composing goes into its field, as the field shows it, and the input method starts
|
||||||
|
// afresh. What runs next may read the field, which is then all of what it shows, and may change the screen, where the
|
||||||
|
// word would be left behind: shown, and gone at the next key.
|
||||||
|
void Context::EndComposition() {
|
||||||
|
if(const Region* field = FocusedRegion(); field != nullptr && field->edit != nullptr && !field->edit->preedit.empty()) {
|
||||||
|
field->edit->CommitPreedit();
|
||||||
|
inputSerial++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A tap places the cursor. Inside the composing text it stays where it is, that span being the input method's;
|
||||||
|
// outside, the word is taken into the field where it was typed and the input method starts afresh, so the half-typed
|
||||||
|
// word does not move to the tap.
|
||||||
|
void Context::TapField(const Region& region, Point at) {
|
||||||
|
EditState& edit = *region.edit;
|
||||||
|
const bool had = focusKey == region.key;
|
||||||
|
// Where in the shown text the tap lands, by the text the field drew.
|
||||||
|
const std::string drawn = FieldText(edit, region.field.masked);
|
||||||
|
const std::size_t first = std::min(region.field.first, drawn.size());
|
||||||
|
const std::size_t drawnByte = first + NearestByte(Measure(), std::string_view(drawn).substr(first), region.field.face, region.field.px, at.x - region.field.textX);
|
||||||
|
std::size_t shownByte = drawnByte;
|
||||||
|
if(region.field.masked) {
|
||||||
|
// A dot for each code point: the dots before the tap, counted off in the text itself.
|
||||||
|
const std::string shown = edit.Shown();
|
||||||
|
shownByte = 0;
|
||||||
|
for(std::size_t dots = CountCodepoints(std::string_view(drawn).substr(0, drawnByte)); dots > 0; dots--) {
|
||||||
|
shownByte = NextCodepoint(shown, shownByte);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if(!had) {
|
||||||
|
MoveFocus(region.key, false);
|
||||||
|
}
|
||||||
|
if(!edit.preedit.empty()) {
|
||||||
|
if(shownByte > edit.cursor && shownByte < edit.cursor + edit.preedit.size()) {
|
||||||
|
ShowCaret();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
edit.CommitPreedit();
|
||||||
|
inputSerial++;
|
||||||
|
}
|
||||||
|
edit.MoveTo(shownByte);
|
||||||
|
if(had && keyboardGone) {
|
||||||
|
// The field kept the focus while its keyboard went: a tap on it asks for the keyboard again.
|
||||||
|
inputSerial++;
|
||||||
|
}
|
||||||
|
ShowCaret();
|
||||||
|
}
|
||||||
|
|
||||||
|
// What a held press, or the secondary button, offers on a field: the clipboard, since an on-screen keyboard has no
|
||||||
|
// key for it.
|
||||||
|
void Context::FieldMenu(const Region& region, Point at) {
|
||||||
|
MoveFocus(region.key, false);
|
||||||
|
const EditState& edit = *region.edit;
|
||||||
|
std::vector<MenuItem> items;
|
||||||
|
items.push_back({"Paste", [this] { wants.paste = true; }});
|
||||||
|
if(!edit.Empty() && edit.kind != FieldKind::Secret) {
|
||||||
|
// By the field's name, not its address: it may be gone by the time the choice is made.
|
||||||
|
items.push_back({"Copy", [this, key = region.key] {
|
||||||
|
if(const Region* field = Find(key); field != nullptr && field->edit != nullptr) {
|
||||||
|
Copy(std::string(field->edit->HasSelection() ? field->edit->Selected() : std::string_view(field->edit->value)));
|
||||||
|
}
|
||||||
|
}});
|
||||||
|
}
|
||||||
|
if(!edit.Empty()) {
|
||||||
|
items.push_back({"Select all", [this, key = region.key] {
|
||||||
|
if(const Region* field = Find(key); field != nullptr && field->edit != nullptr) {
|
||||||
|
field->edit->CommitPreedit();
|
||||||
|
field->edit->SelectAll();
|
||||||
|
}
|
||||||
|
}});
|
||||||
|
}
|
||||||
|
OpenMenu(at, std::move(items));
|
||||||
|
}
|
||||||
|
|
||||||
|
void Context::MoveFocus(std::string_view key, bool byKeyboard) {
|
||||||
|
if(focusKey != key) {
|
||||||
|
// The word the input method is composing goes into the field that loses the focus, as that field showed it.
|
||||||
|
if(const Region* old = FocusedRegion(); old != nullptr && old->edit != nullptr) {
|
||||||
|
old->edit->CommitPreedit();
|
||||||
|
}
|
||||||
|
focusKey = std::string(key);
|
||||||
|
inputSerial++;
|
||||||
|
}
|
||||||
|
focusByKeyboard = byKeyboard;
|
||||||
|
ShowCaret();
|
||||||
|
if(const Region* region = FocusedRegion()) {
|
||||||
|
Reveal(*region);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void Context::StepFocus(std::int32_t by) {
|
||||||
|
// What Tab reaches: every region that takes the focus, or only a sheet's own while one is open.
|
||||||
|
std::vector<const Region*> order;
|
||||||
|
for(const Region& region : regions) {
|
||||||
|
if(region.role == Role::Scrim) {
|
||||||
|
order.clear();
|
||||||
|
} else if(region.focusable && region.enabled) {
|
||||||
|
order.push_back(®ion);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if(order.empty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const auto at = std::ranges::find(order, focusKey, [](const Region* region) -> const std::string& { return region->key; });
|
||||||
|
std::size_t next = by > 0 ? 0 : order.size() - 1;
|
||||||
|
if(at != order.end()) {
|
||||||
|
const std::size_t index = static_cast<std::size_t>(at - order.begin());
|
||||||
|
next = by > 0 ? (index + 1) % order.size() : (index + order.size() - 1) % order.size();
|
||||||
|
}
|
||||||
|
MoveFocus(order[next]->key, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
void Context::Reveal(const Region& region) {
|
||||||
|
if(region.scroll.empty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
ScrollState& state = Scroll(region.scroll);
|
||||||
|
const float top = region.box.y - region.scrollTop + state.offset;
|
||||||
|
if(state.EnsureVisible(top, top + region.box.h, Dp(16))) {
|
||||||
|
wants.redraw = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void Context::ShowCaret() noexcept {
|
||||||
|
caretSince = now;
|
||||||
|
caretPhase = 0;
|
||||||
|
wants.redraw = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Context::Edited(const Region& field) {
|
||||||
|
ShowCaret();
|
||||||
|
Reveal(field);
|
||||||
|
if(field.onChange) {
|
||||||
|
const std::function<void()> changed = field.onChange;
|
||||||
|
changed();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Context::EditKeyDown(const Region& field, Key key, Modifiers modifiers) {
|
||||||
|
EditState& edit = *field.edit;
|
||||||
|
if(modifiers.control) {
|
||||||
|
if(key == Key::A) {
|
||||||
|
edit.CommitPreedit();
|
||||||
|
edit.SelectAll();
|
||||||
|
ShowCaret();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if(key == Key::V) {
|
||||||
|
wants.paste = true;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if(key == Key::C || key == Key::X) {
|
||||||
|
// A secret is never copied.
|
||||||
|
if(edit.kind != FieldKind::Secret && edit.HasSelection()) {
|
||||||
|
wants.copy = std::string(edit.Selected());
|
||||||
|
if(key == Key::X) {
|
||||||
|
edit.DeleteSelection();
|
||||||
|
Edited(field);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
static constexpr std::array<std::pair<Key, EditKey>, 6> keys = {{
|
||||||
|
{Key::Backspace, EditKey::Backspace}, {Key::Delete, EditKey::Delete}, {Key::Left, EditKey::Left},
|
||||||
|
{Key::Right, EditKey::Right}, {Key::Home, EditKey::Home}, {Key::End, EditKey::End},
|
||||||
|
}};
|
||||||
|
const auto found = std::ranges::find(keys, key, &std::pair<Key, EditKey>::first);
|
||||||
|
if(found == keys.end()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const bool deletes = found->second == EditKey::Backspace || found->second == EditKey::Delete;
|
||||||
|
if(edit.Apply(found->second, modifiers.shift) && deletes) {
|
||||||
|
Edited(field);
|
||||||
|
} else {
|
||||||
|
ShowCaret();
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Context::Hover(std::optional<Point> at) {
|
||||||
|
const Region* over = at ? HitTest(*at) : nullptr;
|
||||||
|
// Only what a press acts on shows the pointer over it.
|
||||||
|
const bool acts = over != nullptr && over->enabled && (over->role == Role::Button || over->role == Role::Row || over->role == Role::Field);
|
||||||
|
const std::string key = acts ? over->key : std::string();
|
||||||
|
if(key != hoverKey) {
|
||||||
|
hoverKey = key;
|
||||||
|
wants.redraw = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void Context::Secondary(Point at) {
|
||||||
|
const Region* target = HitTest(at);
|
||||||
|
if(target != nullptr && target->enabled) {
|
||||||
|
Held(*target, at);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void Context::Wheel(Point at, float detents) {
|
||||||
|
if(const Region* area = ScrollUnder(at)) {
|
||||||
|
Scroll(area->key).ScrollBy(detents * Dp(48));
|
||||||
|
wants.redraw = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void Context::KeyDown(Key key, Modifiers modifiers, bool repeat) {
|
||||||
|
if(menu) {
|
||||||
|
// A menu takes the keyboard: Escape sends it away.
|
||||||
|
if(key == Key::Escape && !repeat) {
|
||||||
|
CloseMenu();
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const Region* focused = FocusedRegion();
|
||||||
|
if(focused != nullptr && focused->onKey) {
|
||||||
|
const std::function<bool(Key, Modifiers)> handler = focused->onKey;
|
||||||
|
if(handler(key, modifiers)) {
|
||||||
|
wants.redraw = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
focused = FocusedRegion();
|
||||||
|
}
|
||||||
|
if(focused != nullptr && focused->edit != nullptr && EditKeyDown(*focused, key, modifiers)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if(key == Key::Tab || key == Key::Down || key == Key::Up) {
|
||||||
|
StepFocus(key == Key::Up || (key == Key::Tab && modifiers.shift) ? -1 : 1);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if(key == Key::PageDown || key == Key::PageUp) {
|
||||||
|
// The topmost scrolling area turns a page.
|
||||||
|
const auto area = std::ranges::find(std::views::reverse(regions), Role::Scroll, &Region::role);
|
||||||
|
if(area != std::views::reverse(regions).end()) {
|
||||||
|
Scroll(area->key).ScrollBy((key == Key::PageDown ? 0.9f : -0.9f) * area->box.h);
|
||||||
|
wants.redraw = true;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// What follows acts once for a press: a key held down is not a row of presses of a button, and its repeats would
|
||||||
|
// land on the screen the first one opened.
|
||||||
|
if(repeat) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if(focused != nullptr && key == Key::Enter && focused->edit != nullptr && focused->onSubmit) {
|
||||||
|
const std::function<void()> submit = focused->onSubmit;
|
||||||
|
EndComposition();
|
||||||
|
submit();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if(focused != nullptr && (key == Key::Enter || key == Key::Space) && focused->edit == nullptr && focused->onTap) {
|
||||||
|
const std::function<void()> action = focused->onTap;
|
||||||
|
pointed = focused->hit.Center();
|
||||||
|
action();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const auto shortcut = std::ranges::find_if(std::views::reverse(shortcuts), [key, modifiers](const Frame::KeyAction& candidate) { return candidate.key == key && candidate.modifiers == modifiers; });
|
||||||
|
if(shortcut != std::views::reverse(shortcuts).end()) {
|
||||||
|
const std::function<void()> action = shortcut->action;
|
||||||
|
EndComposition();
|
||||||
|
action();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void Context::Text(std::string_view utf8) {
|
||||||
|
if(const Region* field = FocusedRegion(); field != nullptr && field->edit != nullptr) {
|
||||||
|
field->edit->Commit(utf8);
|
||||||
|
Edited(*field);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void Context::Preedit(std::string_view utf8) {
|
||||||
|
if(const Region* field = FocusedRegion(); field != nullptr && field->edit != nullptr) {
|
||||||
|
field->edit->preedit = std::string(utf8);
|
||||||
|
ShowCaret();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void Context::DeleteAround(std::size_t beforeBytes, std::size_t afterBytes) {
|
||||||
|
if(const Region* field = FocusedRegion(); field != nullptr && field->edit != nullptr) {
|
||||||
|
field->edit->DeleteAround(beforeBytes, afterBytes);
|
||||||
|
Edited(*field);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void Context::Paste(std::string_view utf8) {
|
||||||
|
if(const Region* field = FocusedRegion(); field != nullptr && field->edit != nullptr) {
|
||||||
|
field->edit->Paste(utf8);
|
||||||
|
Edited(*field);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void Context::Tick(std::int64_t nowMs) {
|
||||||
|
// A step of at most a twentieth of a second: after a stall a flung list moves on, it does not jump.
|
||||||
|
const float dt = static_cast<float>(std::clamp<std::int64_t>(nowMs - lastTick, 0, 50)) / 1000.0f;
|
||||||
|
lastTick = nowMs;
|
||||||
|
now = nowMs;
|
||||||
|
if(const std::optional<std::int64_t> due = gestures.LongPressDue(); due && nowMs >= *due) {
|
||||||
|
Handle(gestures.Timeout(nowMs));
|
||||||
|
wants.redraw = true;
|
||||||
|
}
|
||||||
|
bool moving = false;
|
||||||
|
for(auto& [key, state] : scrolls) {
|
||||||
|
if(state.velocity != 0) {
|
||||||
|
moving = state.Tick(dt) || moving;
|
||||||
|
wants.redraw = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
wants.animating = moving;
|
||||||
|
if(!notice.empty() && nowMs >= noticeUntil) {
|
||||||
|
notice.clear();
|
||||||
|
Stale();
|
||||||
|
}
|
||||||
|
// What was put off until now, the earliest first. Taken out before it runs: it may put itself off again.
|
||||||
|
std::vector<Later> due;
|
||||||
|
for(auto later = laters.begin(); later != laters.end();) {
|
||||||
|
if(nowMs >= later->second.atMs) {
|
||||||
|
due.push_back(std::move(later->second));
|
||||||
|
later = laters.erase(later);
|
||||||
|
} else {
|
||||||
|
later++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
std::ranges::stable_sort(due, {}, &Later::atMs);
|
||||||
|
for(const Later& later : due) {
|
||||||
|
later.action();
|
||||||
|
wants.redraw = true;
|
||||||
|
}
|
||||||
|
if(const Region* field = FocusedRegion(); field != nullptr && field->edit != nullptr) {
|
||||||
|
const std::int64_t phase = std::min(nowMs - caretSince, caretIdleMs) / 500;
|
||||||
|
if(phase != caretPhase) {
|
||||||
|
caretPhase = phase;
|
||||||
|
wants.redraw = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Context::Tap(std::string_view key) {
|
||||||
|
const Region* region = Find(key);
|
||||||
|
// Only what a finger could reach: not a region that is disabled, scrolled out of sight, or under a sheet.
|
||||||
|
if(region == nullptr || !region->enabled || region->hit.Empty() || HitTest(region->hit.Center()) != region) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
// A field's cursor goes to the end of what it shows.
|
||||||
|
Activate(*region, region->edit != nullptr ? Point{region->hit.Right(), region->hit.Center().y} : region->hit.Center());
|
||||||
|
wants.redraw = true;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Context::LongPress(std::string_view key) {
|
||||||
|
const Region* region = Find(key);
|
||||||
|
if(region == nullptr || !region->enabled || region->hit.Empty() || HitTest(region->hit.Center()) != region) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
Held(*region, region->hit.Center());
|
||||||
|
wants.redraw = true;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Context::Focus(std::string_view key) {
|
||||||
|
MoveFocus(key, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string_view Context::Focused() const noexcept {
|
||||||
|
return focusKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
Point Context::Pointed() const noexcept {
|
||||||
|
return pointed;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Context::OpenMenu(Point at, std::vector<MenuItem> items) {
|
||||||
|
menu = Menu{at, std::move(items)};
|
||||||
|
// The regions under the menu are not to be reached from here on: a frame with the menu in it comes first.
|
||||||
|
Stale();
|
||||||
|
}
|
||||||
|
|
||||||
|
void Context::CloseMenu() {
|
||||||
|
if(menu) {
|
||||||
|
menu.reset();
|
||||||
|
Stale();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Context::MenuOpen() const noexcept {
|
||||||
|
return menu.has_value();
|
||||||
|
}
|
||||||
|
|
||||||
|
void Context::Notice(std::string text, std::int64_t forMs) {
|
||||||
|
notice = std::move(text);
|
||||||
|
noticeUntil = now + forMs;
|
||||||
|
Stale();
|
||||||
|
}
|
||||||
|
|
||||||
|
void Context::Copy(std::string text) {
|
||||||
|
wants.copy = std::move(text);
|
||||||
|
}
|
||||||
|
|
||||||
|
void Context::RestartInput() noexcept {
|
||||||
|
inputSerial++;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::int64_t Context::Now() const noexcept {
|
||||||
|
return now;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Context::At(std::string_view name, std::int64_t atMs, std::function<void()> action) {
|
||||||
|
laters.insert_or_assign(std::string(name), Later{atMs, std::move(action)});
|
||||||
|
}
|
||||||
|
|
||||||
|
void Context::Forget(std::string_view name) {
|
||||||
|
if(const auto found = laters.find(name); found != laters.end()) {
|
||||||
|
laters.erase(found);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ScrollState& Context::Scroll(std::string_view key) {
|
||||||
|
const auto found = scrolls.find(key);
|
||||||
|
return found != scrolls.end() ? found->second : scrolls.emplace(std::string(key), ScrollState()).first->second;
|
||||||
|
}
|
||||||
|
|
||||||
|
Context::Wants Context::Take() {
|
||||||
|
Wants taken = wants;
|
||||||
|
taken.textInput = told;
|
||||||
|
std::optional<std::int64_t> wake = gestures.LongPressDue();
|
||||||
|
const auto sooner = [&wake](std::int64_t at) { wake = wake ? std::min(*wake, at) : at; };
|
||||||
|
if(!notice.empty()) {
|
||||||
|
sooner(noticeUntil);
|
||||||
|
}
|
||||||
|
for(const auto& [name, later] : laters) {
|
||||||
|
sooner(later.atMs);
|
||||||
|
}
|
||||||
|
if(const Region* field = FocusedRegion(); field != nullptr && field->edit != nullptr && caretPhase * 500 < caretIdleMs) {
|
||||||
|
sooner(caretSince + (caretPhase + 1) * 500);
|
||||||
|
}
|
||||||
|
taken.wakeAtMs = wake;
|
||||||
|
wants.redraw = false;
|
||||||
|
wants.copy.reset();
|
||||||
|
wants.paste = false;
|
||||||
|
return taken;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tells the window which field has the focus and where its caret is, when that changed. A window taller than at the
|
||||||
|
// last telling has lost its on-screen keyboard (the keyboard's own hide key: the compositor gives the room back), and
|
||||||
|
// a caret that only followed that growth is not told: the telling would bring the keyboard straight back. A tap on
|
||||||
|
// the field asks for it (TapField).
|
||||||
|
void Context::UpdateTextInput(float windowHeight) {
|
||||||
|
TextInputRequest want;
|
||||||
|
if(const Region* field = FocusedRegion(); field != nullptr && field->edit != nullptr) {
|
||||||
|
want = {true, field->field.caret, field->field.purpose, field->field.hints, inputSerial};
|
||||||
|
}
|
||||||
|
if(want.active && told.active && want.field == told.field && want.purpose == told.purpose && want.hints == told.hints) {
|
||||||
|
if(windowHeight < toldHeight) {
|
||||||
|
// The keyboard is up, or up again.
|
||||||
|
toldHeight = windowHeight;
|
||||||
|
}
|
||||||
|
keyboardGone = windowHeight > toldHeight;
|
||||||
|
if(want.caret == told.caret || CaretFollowedGrowth(told.caret, toldHeight, want.caret, windowHeight)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
told = want;
|
||||||
|
toldHeight = windowHeight;
|
||||||
|
keyboardGone = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Context::DrawMenu(Frame& to) {
|
||||||
|
to.draw.SetLayer(Layer::Popup);
|
||||||
|
// A scrim that shows nothing: a tap beside the menu sends it away, and reaches nothing else.
|
||||||
|
Region scrim;
|
||||||
|
scrim.box = to.bounds;
|
||||||
|
scrim.key = "menu.scrim";
|
||||||
|
scrim.role = Role::Scrim;
|
||||||
|
scrim.onTap = [this] { CloseMenu(); };
|
||||||
|
to.Add(std::move(scrim));
|
||||||
|
|
||||||
|
const float px = to.Dp(TextSize::body);
|
||||||
|
const float rowHeight = to.Dp(Size::touch);
|
||||||
|
const float pad = to.Dp(Size::unit * 2);
|
||||||
|
const float margin = to.Dp(Size::unit * 2);
|
||||||
|
float width = to.Dp(160);
|
||||||
|
for(const MenuItem& item : menu->items) {
|
||||||
|
width = std::max(width, TextWidth(Measure(), item.label, FontFace::Regular, px) + to.Dp(Size::gutter) * 2);
|
||||||
|
}
|
||||||
|
const float height = rowHeight * static_cast<float>(menu->items.size()) + pad * 2;
|
||||||
|
// Beside the point it was asked for at, and inside the window.
|
||||||
|
const Box panel{
|
||||||
|
std::max(to.bounds.x + margin, std::min(menu->at.x, to.bounds.Right() - margin - width)),
|
||||||
|
std::max(to.bounds.y + margin, std::min(menu->at.y, to.bounds.Bottom() - margin - height)),
|
||||||
|
width, height,
|
||||||
|
};
|
||||||
|
to.draw.Rect(RectItem{.box = panel, .color = theme.surface, .corners = Corners::All(to.Dp(Size::radius)), .outline = to.Dp(1), .outlineColor = theme.divider});
|
||||||
|
Region ground;
|
||||||
|
ground.box = panel;
|
||||||
|
ground.key = "menu.panel";
|
||||||
|
ground.role = Role::Panel;
|
||||||
|
to.Add(std::move(ground));
|
||||||
|
for(std::size_t i = 0; i < menu->items.size(); i++) {
|
||||||
|
const MenuItem& item = menu->items[i];
|
||||||
|
const Box row{panel.x, panel.y + pad + rowHeight * static_cast<float>(i), panel.w, rowHeight};
|
||||||
|
const std::string key = std::format("menu.{}", i);
|
||||||
|
if(to.Pressed(key) || to.Hovered(key)) {
|
||||||
|
to.draw.Rect(row, to.Pressed(key) ? theme.Pressed(theme.surface) : theme.Hovered(theme.surface));
|
||||||
|
}
|
||||||
|
to.draw.Text(item.label, row.x + to.Dp(Size::gutter), CenteredBaseline(Measure(), row, FontFace::Regular, px), FontFace::Regular, px, item.danger ? theme.danger : theme.text);
|
||||||
|
Region choice;
|
||||||
|
choice.box = row;
|
||||||
|
choice.key = key;
|
||||||
|
choice.label = item.label;
|
||||||
|
choice.onTap = [this, i] {
|
||||||
|
// The menu goes before its choice acts, since the action may open another; the frame it was drawn in goes
|
||||||
|
// after, since the action may be about something in it.
|
||||||
|
const std::function<void()> action = menu->items[i].action;
|
||||||
|
menu.reset();
|
||||||
|
action();
|
||||||
|
Stale();
|
||||||
|
};
|
||||||
|
to.Add(std::move(choice));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void Context::DrawNotice(Frame& to) {
|
||||||
|
to.draw.SetLayer(Layer::Popup);
|
||||||
|
const float px = to.Dp(TextSize::label);
|
||||||
|
const float width = std::min(to.bounds.w - to.Dp(Size::gutter) * 2, TextWidth(Measure(), notice, FontFace::Regular, px) + to.Dp(Size::gutter) * 2);
|
||||||
|
const float height = to.Dp(40);
|
||||||
|
// Clear of a bar along the window's bottom.
|
||||||
|
const Box pill{to.bounds.x + (to.bounds.w - width) / 2, to.bounds.Bottom() - to.Dp(Size::bar) - to.Dp(Size::gutter) - height, width, height};
|
||||||
|
to.draw.Rect(pill, theme.text, height / 2);
|
||||||
|
to.draw.Text(Ellipsize(Measure(), notice, FontFace::Regular, px, width - to.Dp(Size::gutter) * 2), pill.Center().x, CenteredBaseline(Measure(), pill, FontFace::Regular, px), FontFace::Regular, px, theme.background, TextAlign::Center);
|
||||||
|
}
|
||||||
103
implementations/Nostro.Ui-Draw.cpp
Normal file
103
implementations/Nostro.Ui-Draw.cpp
Normal file
|
|
@ -0,0 +1,103 @@
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
module Nostro.Ui:Draw_impl;
|
||||||
|
import std;
|
||||||
|
import :Draw;
|
||||||
|
import :Geometry;
|
||||||
|
import :Text;
|
||||||
|
|
||||||
|
using namespace Nostro::Ui;
|
||||||
|
|
||||||
|
DrawList::DrawList(const TextMeasure& measure, Box bounds) : measure(&measure), bounds(bounds) {
|
||||||
|
}
|
||||||
|
|
||||||
|
void DrawList::SetLayer(Layer to) noexcept {
|
||||||
|
layer = to;
|
||||||
|
}
|
||||||
|
|
||||||
|
Layer DrawList::CurrentLayer() const noexcept {
|
||||||
|
return layer;
|
||||||
|
}
|
||||||
|
|
||||||
|
void DrawList::PushClip(Box box) {
|
||||||
|
clips.push_back(clips.empty() ? box.Intersect(bounds) : box.Intersect(clips.back()));
|
||||||
|
}
|
||||||
|
|
||||||
|
void DrawList::PopClip() {
|
||||||
|
clips.pop_back();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool DrawList::Visible(Box box) const noexcept {
|
||||||
|
return box.Overlaps(clips.empty() ? bounds : clips.back());
|
||||||
|
}
|
||||||
|
|
||||||
|
Batch& DrawList::BatchFor(std::optional<Box> shape) {
|
||||||
|
std::vector<Batch>& batches = layers[static_cast<std::size_t>(layer)];
|
||||||
|
const std::optional<Box> clip = clips.empty() ? std::nullopt : std::optional<Box>(clips.back());
|
||||||
|
bool fits = !batches.empty() && batches.back().clip == clip;
|
||||||
|
if(fits && shape) {
|
||||||
|
// In one pass the batch's text is drawn over all its shapes: a shape that comes after a text it touches needs the
|
||||||
|
// next pass to cover it.
|
||||||
|
fits = std::ranges::none_of(batches.back().texts, [&shape](const TextItem& text) { return text.bounds.Overlaps(*shape); });
|
||||||
|
}
|
||||||
|
if(!fits) {
|
||||||
|
batches.emplace_back().clip = clip;
|
||||||
|
}
|
||||||
|
return batches.back();
|
||||||
|
}
|
||||||
|
|
||||||
|
void DrawList::Rect(const RectItem& item) {
|
||||||
|
if(Visible(item.box)) {
|
||||||
|
BatchFor(item.box).rects.push_back(item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void DrawList::Rect(Box box, Color color, float radius) {
|
||||||
|
Rect(RectItem{.box = box, .color = color, .corners = Corners::All(radius)});
|
||||||
|
}
|
||||||
|
|
||||||
|
void DrawList::Circle(const CircleItem& item) {
|
||||||
|
const Box box{item.center.x - item.radius, item.center.y - item.radius, item.radius * 2, item.radius * 2};
|
||||||
|
if(Visible(box)) {
|
||||||
|
BatchFor(box).circles.push_back(item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void DrawList::Circle(Point center, float radius, Color color) {
|
||||||
|
Circle(CircleItem{.center = center, .radius = radius, .color = color});
|
||||||
|
}
|
||||||
|
|
||||||
|
float DrawList::Text(std::string_view text, float x, float baseline, FontFace face, float px, Color color, TextAlign align) {
|
||||||
|
const float width = TextWidth(*measure, text, face, px);
|
||||||
|
const float left = align == TextAlign::Left ? x : (align == TextAlign::Center ? x - width / 2 : x - width);
|
||||||
|
const Box box{left, baseline - measure->ascent(face, px), width, measure->lineHeight(face, px)};
|
||||||
|
if(!text.empty() && Visible(box)) {
|
||||||
|
BatchFor(std::nullopt).texts.push_back(TextItem{.text = std::string(text), .x = x, .baseline = baseline, .face = face, .px = px, .color = color, .align = align, .bounds = box});
|
||||||
|
}
|
||||||
|
return width;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::span<const Batch> DrawList::Batches(Layer of) const noexcept {
|
||||||
|
return layers[static_cast<std::size_t>(of)];
|
||||||
|
}
|
||||||
|
|
||||||
|
std::size_t DrawList::BatchCount() const noexcept {
|
||||||
|
std::size_t count = 0;
|
||||||
|
for(const std::vector<Batch>& batches : layers) {
|
||||||
|
count += batches.size();
|
||||||
|
}
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<std::string> DrawList::Texts() const {
|
||||||
|
std::vector<std::string> texts;
|
||||||
|
for(const std::vector<Batch>& batches : layers) {
|
||||||
|
for(const Batch& batch : batches) {
|
||||||
|
for(const TextItem& text : batch.texts) {
|
||||||
|
texts.push_back(text.text);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return texts;
|
||||||
|
}
|
||||||
223
implementations/Nostro.Ui-Edit.cpp
Normal file
223
implementations/Nostro.Ui-Edit.cpp
Normal file
|
|
@ -0,0 +1,223 @@
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
module;
|
||||||
|
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
module Nostro.Ui:Edit_impl;
|
||||||
|
import std;
|
||||||
|
import :Edit;
|
||||||
|
import :Text;
|
||||||
|
|
||||||
|
using namespace Nostro::Ui;
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
// Overwrites a string's whole buffer, the part past its length too, where what was deleted from it may still be,
|
||||||
|
// and empties it. explicit_bzero is the call a compiler may not take out as a write nobody reads.
|
||||||
|
void Wipe(std::string& text) {
|
||||||
|
text.resize(text.capacity());
|
||||||
|
explicit_bzero(text.data(), text.size());
|
||||||
|
text.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
// What of `utf8` a field of `kind` takes.
|
||||||
|
std::string Taken(std::string_view utf8, FieldKind kind) {
|
||||||
|
std::string taken;
|
||||||
|
for(std::size_t i = 0; i < utf8.size();) {
|
||||||
|
const std::size_t at = i;
|
||||||
|
const std::uint32_t codepoint = DecodeUtf8(utf8, i);
|
||||||
|
const std::string_view bytes = utf8.substr(at, i - at);
|
||||||
|
const bool digit = codepoint >= '0' && codepoint <= '9';
|
||||||
|
if(kind == FieldKind::Decimal || kind == FieldKind::Digits) {
|
||||||
|
if(digit || (kind == FieldKind::Decimal && (codepoint == '.' || codepoint == ','))) {
|
||||||
|
taken += bytes;
|
||||||
|
}
|
||||||
|
} else if(codepoint == '\n' || codepoint == '\t') {
|
||||||
|
// A field is one line: a break in prose that was pasted is a space, and one around a key or an address
|
||||||
|
// (the newline a terminal's selection ends with) is nothing.
|
||||||
|
if(kind == FieldKind::Text) {
|
||||||
|
taken += ' ';
|
||||||
|
}
|
||||||
|
} else if(codepoint == ' ') {
|
||||||
|
// A key has no space in it; an IBAN typed in groups keeps its own.
|
||||||
|
if(kind != FieldKind::Secret) {
|
||||||
|
taken += ' ';
|
||||||
|
}
|
||||||
|
} else if(codepoint >= 0x20 && codepoint != 0x7F && !(codepoint == 0xFFFD && bytes != "\xEF\xBF\xBD")) {
|
||||||
|
// No control characters, and no malformed sequence, which decodes as U+FFFD without being its bytes: the
|
||||||
|
// bus carries valid UTF-8 alone.
|
||||||
|
taken += bytes;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return taken;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
EditState::EditState(FieldKind kind) : kind(kind) {
|
||||||
|
if(kind == FieldKind::Secret) {
|
||||||
|
value.reserve(secretLimit);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
EditState::~EditState() {
|
||||||
|
Clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool EditState::Empty() const noexcept {
|
||||||
|
return value.empty() && preedit.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string EditState::Shown() const {
|
||||||
|
std::string shown = value;
|
||||||
|
shown.insert(cursor, preedit);
|
||||||
|
return shown;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::size_t EditState::ShownCursor() const noexcept {
|
||||||
|
return cursor + preedit.size();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool EditState::HasSelection() const noexcept {
|
||||||
|
return cursor != anchor;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::size_t EditState::SelectionBegin() const noexcept {
|
||||||
|
return std::min(cursor, anchor);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::size_t EditState::SelectionEnd() const noexcept {
|
||||||
|
return std::max(cursor, anchor);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string_view EditState::Selected() const noexcept {
|
||||||
|
return std::string_view(value).substr(SelectionBegin(), SelectionEnd() - SelectionBegin());
|
||||||
|
}
|
||||||
|
|
||||||
|
void EditState::Set(std::string_view text) {
|
||||||
|
Clear();
|
||||||
|
Insert(text);
|
||||||
|
}
|
||||||
|
|
||||||
|
void EditState::Clear() {
|
||||||
|
if(kind == FieldKind::Secret) {
|
||||||
|
Wipe(value);
|
||||||
|
Wipe(preedit);
|
||||||
|
}
|
||||||
|
value.clear();
|
||||||
|
preedit.clear();
|
||||||
|
cursor = 0;
|
||||||
|
anchor = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
void EditState::Commit(std::string_view utf8) {
|
||||||
|
preedit.clear();
|
||||||
|
Insert(utf8);
|
||||||
|
}
|
||||||
|
|
||||||
|
void EditState::Paste(std::string_view utf8) {
|
||||||
|
CommitPreedit();
|
||||||
|
Insert(utf8);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool EditState::Apply(EditKey key, bool extend) {
|
||||||
|
if(key == EditKey::Backspace || key == EditKey::Delete) {
|
||||||
|
if(DeleteSelection()) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
const std::size_t from = key == EditKey::Backspace ? PreviousCodepoint(value, cursor) : cursor;
|
||||||
|
const std::size_t to = key == EditKey::Backspace ? cursor : NextCodepoint(value, cursor);
|
||||||
|
if(from == to) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
value.erase(from, to - from);
|
||||||
|
cursor = from;
|
||||||
|
anchor = from;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
// A move that does not stretch a selection ends it: Left and Right at the side they point to.
|
||||||
|
const bool collapse = HasSelection() && !extend;
|
||||||
|
std::size_t to = value.size();
|
||||||
|
if(key == EditKey::Left) {
|
||||||
|
to = collapse ? SelectionBegin() : PreviousCodepoint(value, cursor);
|
||||||
|
} else if(key == EditKey::Right) {
|
||||||
|
to = collapse ? SelectionEnd() : NextCodepoint(value, cursor);
|
||||||
|
} else if(key == EditKey::Home) {
|
||||||
|
to = 0;
|
||||||
|
}
|
||||||
|
cursor = to;
|
||||||
|
if(!extend) {
|
||||||
|
anchor = to;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void EditState::DeleteAround(std::size_t beforeBytes, std::size_t afterBytes) {
|
||||||
|
std::size_t from = cursor;
|
||||||
|
while(from > 0 && cursor - from < beforeBytes) {
|
||||||
|
from = PreviousCodepoint(value, from);
|
||||||
|
}
|
||||||
|
std::size_t to = cursor;
|
||||||
|
while(to < value.size() && to - cursor < afterBytes) {
|
||||||
|
to = NextCodepoint(value, to);
|
||||||
|
}
|
||||||
|
value.erase(from, to - from);
|
||||||
|
cursor = from;
|
||||||
|
anchor = from;
|
||||||
|
}
|
||||||
|
|
||||||
|
void EditState::CommitPreedit() {
|
||||||
|
if(preedit.empty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
std::string composing = std::exchange(preedit, std::string());
|
||||||
|
Insert(composing);
|
||||||
|
if(kind == FieldKind::Secret) {
|
||||||
|
Wipe(composing);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void EditState::MoveTo(std::size_t byte) {
|
||||||
|
std::size_t at = std::min(byte, value.size());
|
||||||
|
while(at > 0 && at < value.size() && (static_cast<std::uint8_t>(value[at]) & 0xC0) == 0x80) {
|
||||||
|
at--;
|
||||||
|
}
|
||||||
|
cursor = at;
|
||||||
|
anchor = at;
|
||||||
|
}
|
||||||
|
|
||||||
|
void EditState::SelectAll() {
|
||||||
|
anchor = 0;
|
||||||
|
cursor = value.size();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool EditState::DeleteSelection() {
|
||||||
|
if(!HasSelection()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const std::size_t from = SelectionBegin();
|
||||||
|
value.erase(from, SelectionEnd() - from);
|
||||||
|
cursor = from;
|
||||||
|
anchor = from;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void EditState::Insert(std::string_view utf8) {
|
||||||
|
DeleteSelection();
|
||||||
|
std::string taken = Taken(utf8, kind);
|
||||||
|
// No more than the field holds, cut between code points.
|
||||||
|
const std::size_t room = (kind == FieldKind::Secret ? secretLimit : limit) - std::min(value.size(), kind == FieldKind::Secret ? secretLimit : limit);
|
||||||
|
if(taken.size() > room) {
|
||||||
|
std::size_t cut = room;
|
||||||
|
while(cut > 0 && (static_cast<std::uint8_t>(taken[cut]) & 0xC0) == 0x80) {
|
||||||
|
cut--;
|
||||||
|
}
|
||||||
|
taken.resize(cut);
|
||||||
|
}
|
||||||
|
value.insert(cursor, taken);
|
||||||
|
cursor += taken.size();
|
||||||
|
anchor = cursor;
|
||||||
|
if(kind == FieldKind::Secret) {
|
||||||
|
Wipe(taken);
|
||||||
|
}
|
||||||
|
}
|
||||||
207
implementations/Nostro.Ui-Gesture.cpp
Normal file
207
implementations/Nostro.Ui-Gesture.cpp
Normal file
|
|
@ -0,0 +1,207 @@
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
module Nostro.Ui:Gesture_impl;
|
||||||
|
import std;
|
||||||
|
import :Gesture;
|
||||||
|
import :Geometry;
|
||||||
|
|
||||||
|
using namespace Nostro::Ui;
|
||||||
|
|
||||||
|
GestureEvent GestureDetector::LongPressed() {
|
||||||
|
longPressed = true;
|
||||||
|
GestureEvent event;
|
||||||
|
event.kind = GestureEvent::Kind::LongPress;
|
||||||
|
event.at = down;
|
||||||
|
return event;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Keeps the last 100 ms of movement: a fling's speed is the finger's as it left, not as it travelled.
|
||||||
|
void GestureDetector::Forget(std::int64_t tMs) {
|
||||||
|
while(samples.size() > 1 && tMs - samples.front().tMs > 100) {
|
||||||
|
samples.erase(samples.begin());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
GestureEvent GestureDetector::Feed(PointerPhase phase, Point p, std::int64_t tMs) {
|
||||||
|
GestureEvent event;
|
||||||
|
if(phase == PointerPhase::Down) {
|
||||||
|
pressed = true;
|
||||||
|
dragging = false;
|
||||||
|
longPressed = false;
|
||||||
|
down = p;
|
||||||
|
downAt = tMs;
|
||||||
|
last = p;
|
||||||
|
samples.clear();
|
||||||
|
samples.push_back({p, tMs});
|
||||||
|
return event;
|
||||||
|
}
|
||||||
|
if(phase == PointerPhase::Cancel) {
|
||||||
|
pressed = false;
|
||||||
|
dragging = false;
|
||||||
|
longPressed = false;
|
||||||
|
return event;
|
||||||
|
}
|
||||||
|
if(!pressed) {
|
||||||
|
return event;
|
||||||
|
}
|
||||||
|
// Held past the long-press time with no Timeout yet, the events of a stall having been dispatched before the timer.
|
||||||
|
const bool overdue = longPress && !dragging && !longPressed && tMs - downAt >= longPressMs;
|
||||||
|
if(phase == PointerPhase::Move) {
|
||||||
|
if(overdue) {
|
||||||
|
// The long press, before any movement is read.
|
||||||
|
return LongPressed();
|
||||||
|
}
|
||||||
|
if(!dragging && !longPressed && (std::abs(p.x - down.x) > slopPx || std::abs(p.y - down.y) > slopPx)) {
|
||||||
|
dragging = true;
|
||||||
|
event.kind = GestureEvent::Kind::DragStart;
|
||||||
|
event.at = down;
|
||||||
|
event.delta = {p.x - down.x, p.y - down.y};
|
||||||
|
} else if(dragging) {
|
||||||
|
event.kind = GestureEvent::Kind::Drag;
|
||||||
|
event.at = p;
|
||||||
|
event.delta = {p.x - last.x, p.y - last.y};
|
||||||
|
}
|
||||||
|
last = p;
|
||||||
|
samples.push_back({p, tMs});
|
||||||
|
Forget(tMs);
|
||||||
|
return event;
|
||||||
|
}
|
||||||
|
// The release.
|
||||||
|
pressed = false;
|
||||||
|
if(dragging) {
|
||||||
|
dragging = false;
|
||||||
|
// A finger held still before letting go has no speed, whatever it did before: no event comes while it is still.
|
||||||
|
Forget(tMs);
|
||||||
|
const std::int64_t dt = tMs - samples.front().tMs;
|
||||||
|
Point velocity;
|
||||||
|
if(dt > 0) {
|
||||||
|
velocity = {(p.x - samples.front().p.x) * 1000.0f / static_cast<float>(dt), (p.y - samples.front().p.y) * 1000.0f / static_cast<float>(dt)};
|
||||||
|
}
|
||||||
|
event.at = p;
|
||||||
|
if(std::hypot(velocity.x, velocity.y) >= flingMinPxPerS) {
|
||||||
|
event.kind = GestureEvent::Kind::Fling;
|
||||||
|
event.velocity = velocity;
|
||||||
|
} else {
|
||||||
|
event.kind = GestureEvent::Kind::Release;
|
||||||
|
}
|
||||||
|
return event;
|
||||||
|
}
|
||||||
|
if(overdue) {
|
||||||
|
// The long press, at the release.
|
||||||
|
return LongPressed();
|
||||||
|
}
|
||||||
|
if(longPressed) {
|
||||||
|
event.kind = GestureEvent::Kind::Release;
|
||||||
|
event.at = p;
|
||||||
|
return event;
|
||||||
|
}
|
||||||
|
event.kind = GestureEvent::Kind::Tap;
|
||||||
|
event.at = down;
|
||||||
|
return event;
|
||||||
|
}
|
||||||
|
|
||||||
|
GestureEvent GestureDetector::Timeout(std::int64_t tMs) {
|
||||||
|
if(!longPress || !pressed || dragging || longPressed || tMs - downAt < longPressMs) {
|
||||||
|
return GestureEvent();
|
||||||
|
}
|
||||||
|
return LongPressed();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool GestureDetector::Pressed() const noexcept {
|
||||||
|
return pressed;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool GestureDetector::Dragging() const noexcept {
|
||||||
|
return dragging;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::optional<std::int64_t> GestureDetector::LongPressDue() const noexcept {
|
||||||
|
if(!longPress || !pressed || dragging || longPressed) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
return downAt + longPressMs;
|
||||||
|
}
|
||||||
|
|
||||||
|
float ScrollState::Max() const noexcept {
|
||||||
|
return std::max(0.0f, content - viewport);
|
||||||
|
}
|
||||||
|
|
||||||
|
void ScrollState::Clamp() noexcept {
|
||||||
|
offset = std::clamp(offset, 0.0f, Max());
|
||||||
|
}
|
||||||
|
|
||||||
|
void ScrollState::ScrollBy(float dy) noexcept {
|
||||||
|
offset += dy;
|
||||||
|
velocity = 0;
|
||||||
|
Clamp();
|
||||||
|
}
|
||||||
|
|
||||||
|
void ScrollState::Fling(float pxPerS) noexcept {
|
||||||
|
velocity = pxPerS;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ScrollState::Tick(float dt) noexcept {
|
||||||
|
if(std::abs(velocity) < 20.0f) {
|
||||||
|
velocity = 0;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const float before = offset;
|
||||||
|
offset += velocity * dt;
|
||||||
|
Clamp();
|
||||||
|
// Stopped by an end of the content, or going nowhere.
|
||||||
|
if(offset == before || offset == 0.0f || offset == Max()) {
|
||||||
|
velocity = 0;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
velocity *= std::exp(-4.0f * dt);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ScrollState::EnsureVisible(float top, float bottom, float margin) noexcept {
|
||||||
|
const float before = offset;
|
||||||
|
if(bottom + margin > offset + viewport) {
|
||||||
|
offset = bottom + margin - viewport;
|
||||||
|
}
|
||||||
|
// The top wins where the span is taller than the room: that is where reading starts.
|
||||||
|
if(top - margin < offset) {
|
||||||
|
offset = top - margin;
|
||||||
|
}
|
||||||
|
Clamp();
|
||||||
|
if(offset == before) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
velocity = 0;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::int64_t EventClock::At(std::uint32_t stamp, std::int64_t hostNowMs) noexcept {
|
||||||
|
if(stamp == 0) {
|
||||||
|
// The one millisecond in 2^32 that reads 0, and an event the compositor gave no time.
|
||||||
|
return hostNowMs;
|
||||||
|
}
|
||||||
|
// The difference of two stamps as a signed number takes the wrap in its stride.
|
||||||
|
unwrapped = lastStamp == 0 ? stamp : unwrapped + static_cast<std::int32_t>(stamp - lastStamp);
|
||||||
|
lastStamp = stamp;
|
||||||
|
ahead = ahead ? std::min(*ahead, hostNowMs - unwrapped) : hostNowMs - unwrapped;
|
||||||
|
return unwrapped + *ahead;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool FrameWait::Again(std::uint32_t waiting) noexcept {
|
||||||
|
if(waiting == 0) {
|
||||||
|
Reset();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if(last == 0 || waiting != last) {
|
||||||
|
gainless = 0;
|
||||||
|
} else {
|
||||||
|
gainless++;
|
||||||
|
}
|
||||||
|
last = waiting;
|
||||||
|
return gainless < patience;
|
||||||
|
}
|
||||||
|
|
||||||
|
void FrameWait::Reset() noexcept {
|
||||||
|
last = 0;
|
||||||
|
gainless = 0;
|
||||||
|
}
|
||||||
245
implementations/Nostro.Ui-Text.cpp
Normal file
245
implementations/Nostro.Ui-Text.cpp
Normal file
|
|
@ -0,0 +1,245 @@
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
module Nostro.Ui:Text_impl;
|
||||||
|
import std;
|
||||||
|
import :Text;
|
||||||
|
import :Geometry;
|
||||||
|
|
||||||
|
using namespace Nostro::Ui;
|
||||||
|
|
||||||
|
std::uint32_t Nostro::Ui::DecodeUtf8(std::string_view text, std::size_t& i) {
|
||||||
|
if(i >= text.size()) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
const std::uint8_t first = static_cast<std::uint8_t>(text[i]);
|
||||||
|
i++;
|
||||||
|
if(first < 0x80) {
|
||||||
|
return first;
|
||||||
|
}
|
||||||
|
std::size_t more = 0;
|
||||||
|
std::uint32_t codepoint = 0;
|
||||||
|
if((first & 0xE0) == 0xC0) {
|
||||||
|
more = 1;
|
||||||
|
codepoint = first & 0x1F;
|
||||||
|
} else if((first & 0xF0) == 0xE0) {
|
||||||
|
more = 2;
|
||||||
|
codepoint = first & 0x0F;
|
||||||
|
} else if((first & 0xF8) == 0xF0) {
|
||||||
|
more = 3;
|
||||||
|
codepoint = first & 0x07;
|
||||||
|
} else {
|
||||||
|
return 0xFFFD;
|
||||||
|
}
|
||||||
|
for(std::size_t k = 0; k < more; k++) {
|
||||||
|
// A sequence cut short, by the text's end or by a byte that continues nothing, leaves that byte for the next call.
|
||||||
|
if(i >= text.size() || (static_cast<std::uint8_t>(text[i]) & 0xC0) != 0x80) {
|
||||||
|
return 0xFFFD;
|
||||||
|
}
|
||||||
|
codepoint = (codepoint << 6) | (static_cast<std::uint8_t>(text[i]) & 0x3Fu);
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
return codepoint;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::size_t Nostro::Ui::PreviousCodepoint(std::string_view text, std::size_t at) {
|
||||||
|
if(at == 0) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
std::size_t i = std::min(at, text.size()) - 1;
|
||||||
|
while(i > 0 && (static_cast<std::uint8_t>(text[i]) & 0xC0) == 0x80) {
|
||||||
|
i--;
|
||||||
|
}
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::size_t Nostro::Ui::NextCodepoint(std::string_view text, std::size_t at) {
|
||||||
|
if(at >= text.size()) {
|
||||||
|
return text.size();
|
||||||
|
}
|
||||||
|
std::size_t i = at;
|
||||||
|
DecodeUtf8(text, i);
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::size_t Nostro::Ui::CountCodepoints(std::string_view text) {
|
||||||
|
std::size_t count = 0;
|
||||||
|
for(std::size_t i = 0; i < text.size(); count++) {
|
||||||
|
DecodeUtf8(text, i);
|
||||||
|
}
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
|
||||||
|
float Nostro::Ui::TextWidth(const TextMeasure& measure, std::string_view text, FontFace face, float px) {
|
||||||
|
float width = 0;
|
||||||
|
for(std::size_t i = 0; i < text.size();) {
|
||||||
|
const std::uint32_t codepoint = DecodeUtf8(text, i);
|
||||||
|
if(codepoint != '\n') {
|
||||||
|
width += measure.advance(face, codepoint, px);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return width;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::size_t Nostro::Ui::NearestByte(const TextMeasure& measure, std::string_view line, FontFace face, float px, float x) {
|
||||||
|
if(x <= 0) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
float width = 0;
|
||||||
|
float bestDistance = x;
|
||||||
|
std::size_t best = 0;
|
||||||
|
for(std::size_t i = 0; i < line.size();) {
|
||||||
|
width += measure.advance(face, DecodeUtf8(line, i), px);
|
||||||
|
const float distance = std::abs(x - width);
|
||||||
|
// The widths only grow, so the first offset further away ends the search; at a tie the later offset wins, which
|
||||||
|
// puts the cursor past a mark that has no width.
|
||||||
|
if(distance > bestDistance) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
bestDistance = distance;
|
||||||
|
best = i;
|
||||||
|
}
|
||||||
|
return best;
|
||||||
|
}
|
||||||
|
|
||||||
|
float Nostro::Ui::CenteredBaseline(const TextMeasure& measure, Box box, FontFace face, float px) {
|
||||||
|
return box.y + (box.h - measure.lineHeight(face, px)) / 2.0f + measure.ascent(face, px);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string Nostro::Ui::Ellipsize(const TextMeasure& measure, std::string_view text, FontFace face, float px, float maxWidthPx) {
|
||||||
|
const float ellipsis = measure.advance(face, 0x2026, px);
|
||||||
|
float width = 0;
|
||||||
|
std::size_t fit = 0; // the longest prefix that leaves room for the ellipsis
|
||||||
|
for(std::size_t i = 0; i < text.size();) {
|
||||||
|
const std::uint32_t codepoint = DecodeUtf8(text, i);
|
||||||
|
if(codepoint != '\n') {
|
||||||
|
width += measure.advance(face, codepoint, px);
|
||||||
|
}
|
||||||
|
if(codepoint == '\n' || width > maxWidthPx) {
|
||||||
|
return std::format("{}…", text.substr(0, fit));
|
||||||
|
}
|
||||||
|
if(width + ellipsis <= maxWidthPx) {
|
||||||
|
fit = i;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return std::string(text);
|
||||||
|
}
|
||||||
|
|
||||||
|
WordWrapper::WordWrapper(TextMeasure measure) : measure(std::move(measure)) {
|
||||||
|
}
|
||||||
|
|
||||||
|
const std::vector<WrappedLine>& WordWrapper::Wrap(std::string_view text, FontFace face, float px, float maxWidthPx) {
|
||||||
|
// The font, the size to a quarter pixel and the width, then the text itself.
|
||||||
|
std::string key = std::format("{} {} {} {}", static_cast<std::uint8_t>(face), std::lround(px * 4), std::lround(maxWidthPx), text);
|
||||||
|
if(const auto found = cache.find(key); found != cache.end()) {
|
||||||
|
return found->second;
|
||||||
|
}
|
||||||
|
// A bounded cache without bookkeeping: once full everything goes, and the next frame fills in what it needs.
|
||||||
|
if(cache.size() >= cacheLimit) {
|
||||||
|
cache.clear();
|
||||||
|
}
|
||||||
|
return cache.emplace(std::move(key), Compute(text, face, px, maxWidthPx)).first->second;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::size_t WordWrapper::CacheSize() const noexcept {
|
||||||
|
return cache.size();
|
||||||
|
}
|
||||||
|
|
||||||
|
const TextMeasure& WordWrapper::Measure() const noexcept {
|
||||||
|
return measure;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<WrappedLine> WordWrapper::Compute(std::string_view text, FontFace face, float px, float maxWidthPx) const {
|
||||||
|
struct Break {
|
||||||
|
std::size_t end; // where the line ends
|
||||||
|
std::size_t next; // where the next line begins
|
||||||
|
float width; // the line's width up to `end`
|
||||||
|
};
|
||||||
|
// Where the line after a break opens: past the spaces there. Spaces that end the text, or that a hard break
|
||||||
|
// follows, hang off the line just ended and open no line of their own: nothing is returned for the first, and the
|
||||||
|
// newline is passed over for the second.
|
||||||
|
const auto afterSpaces = [text](std::size_t from) -> std::optional<std::size_t> {
|
||||||
|
std::size_t begin = from;
|
||||||
|
while(begin < text.size() && text[begin] == ' ') {
|
||||||
|
begin++;
|
||||||
|
}
|
||||||
|
if(begin == text.size()) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
return text[begin] == '\n' ? begin + 1 : begin;
|
||||||
|
};
|
||||||
|
|
||||||
|
std::vector<WrappedLine> lines;
|
||||||
|
std::size_t lineBegin = 0;
|
||||||
|
float lineWidth = 0;
|
||||||
|
// A code point that is no space since lineBegin: before the first, a space is no break and opens no line.
|
||||||
|
bool lineHasText = false;
|
||||||
|
std::optional<Break> lastBreak;
|
||||||
|
std::size_t i = 0;
|
||||||
|
while(i < text.size()) {
|
||||||
|
const std::size_t at = i;
|
||||||
|
const std::uint32_t codepoint = DecodeUtf8(text, i);
|
||||||
|
if(codepoint == '\n') {
|
||||||
|
lines.push_back({lineBegin, at, lineWidth});
|
||||||
|
lineBegin = i;
|
||||||
|
lineWidth = 0;
|
||||||
|
lineHasText = false;
|
||||||
|
lastBreak.reset();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const float width = measure.advance(face, codepoint, px);
|
||||||
|
if(lineWidth + width > maxWidthPx && at > lineBegin) {
|
||||||
|
if(lastBreak && !(codepoint == ' ' && lineHasText && lastBreak->next != at)) {
|
||||||
|
// The line ends at its last break: before the run of spaces there, or after the hyphen. A space that
|
||||||
|
// overflows right behind that run is part of it.
|
||||||
|
lines.push_back({lineBegin, lastBreak->end, lastBreak->width});
|
||||||
|
if(codepoint == ' ' && lineHasText) {
|
||||||
|
const std::optional<std::size_t> next = afterSpaces(i);
|
||||||
|
if(!next) {
|
||||||
|
return lines;
|
||||||
|
}
|
||||||
|
lineBegin = *next;
|
||||||
|
i = lineBegin;
|
||||||
|
lineWidth = 0;
|
||||||
|
lineHasText = false;
|
||||||
|
} else {
|
||||||
|
// The next line starts after the break, which is past the spaces there, with what of it was already
|
||||||
|
// looked at: the code point that overflowed is looked at again, on its new line.
|
||||||
|
lineBegin = lastBreak->next;
|
||||||
|
i = at;
|
||||||
|
lineWidth = TextWidth(measure, text.substr(lineBegin, at - lineBegin), face, px);
|
||||||
|
lineHasText = at > lineBegin;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// No break to go back to, or the space itself overflows: the line ends here, with every word that fit, or
|
||||||
|
// in the middle of a word wider than the line.
|
||||||
|
lines.push_back({lineBegin, at, lineWidth});
|
||||||
|
const std::optional<std::size_t> next = afterSpaces(at);
|
||||||
|
if(!next) {
|
||||||
|
return lines;
|
||||||
|
}
|
||||||
|
lineBegin = *next;
|
||||||
|
i = lineBegin;
|
||||||
|
lineWidth = 0;
|
||||||
|
lineHasText = false;
|
||||||
|
}
|
||||||
|
lastBreak.reset();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
lineWidth += width;
|
||||||
|
if(codepoint != ' ') {
|
||||||
|
lineHasText = true;
|
||||||
|
}
|
||||||
|
if(codepoint == ' ' && lastBreak && lastBreak->next == at) {
|
||||||
|
// A run of spaces is one break: the line ends before the run.
|
||||||
|
lastBreak->next = i;
|
||||||
|
} else if(codepoint == ' ' && lineHasText) {
|
||||||
|
// Not before a line's first word: the line before such a break would be empty.
|
||||||
|
lastBreak = Break{at, i, lineWidth - width};
|
||||||
|
} else if(codepoint == '-') {
|
||||||
|
lastBreak = Break{i, i, lineWidth};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
lines.push_back({lineBegin, text.size(), lineWidth});
|
||||||
|
return lines;
|
||||||
|
}
|
||||||
54
implementations/Nostro.Ui-Theme.cpp
Normal file
54
implementations/Nostro.Ui-Theme.cpp
Normal file
|
|
@ -0,0 +1,54 @@
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
module Nostro.Ui:Theme_impl;
|
||||||
|
import std;
|
||||||
|
import :Theme;
|
||||||
|
import :Geometry;
|
||||||
|
|
||||||
|
using namespace Nostro::Ui;
|
||||||
|
|
||||||
|
Theme Theme::Light() {
|
||||||
|
return Theme();
|
||||||
|
}
|
||||||
|
|
||||||
|
Theme Theme::Dark() {
|
||||||
|
return Theme{
|
||||||
|
.background = {0.07f, 0.07f, 0.08f},
|
||||||
|
.surface = {0.12f, 0.12f, 0.13f},
|
||||||
|
.surfaceAlt = {0.18f, 0.18f, 0.20f},
|
||||||
|
.text = {0.93f, 0.93f, 0.94f},
|
||||||
|
.muted = {0.62f, 0.62f, 0.65f},
|
||||||
|
.accent = {0.36f, 0.58f, 0.98f},
|
||||||
|
.onAccent = {0.04f, 0.06f, 0.12f},
|
||||||
|
.divider = {0.20f, 0.20f, 0.22f},
|
||||||
|
.positive = {0.36f, 0.80f, 0.48f},
|
||||||
|
.warning = {0.30f, 0.26f, 0.10f},
|
||||||
|
.onWarning = {0.98f, 0.88f, 0.55f},
|
||||||
|
.danger = {0.95f, 0.42f, 0.42f},
|
||||||
|
.onDanger = {0.16f, 0.03f, 0.03f},
|
||||||
|
.scrim = {0.0f, 0.0f, 0.0f, 0.55f},
|
||||||
|
.dark = true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
void Theme::Accent(Color color) {
|
||||||
|
const Color opaque = color.WithAlpha(1.0f);
|
||||||
|
const Color onDark{1.0f, 1.0f, 1.0f};
|
||||||
|
const Color onBright{0.08f, 0.08f, 0.09f};
|
||||||
|
accent = opaque;
|
||||||
|
onAccent = opaque.Luminance() > 0.6f ? onBright : onDark;
|
||||||
|
}
|
||||||
|
|
||||||
|
Color Theme::Hovered(Color color) const {
|
||||||
|
return color.Mixed(text, 0.06f);
|
||||||
|
}
|
||||||
|
|
||||||
|
Color Theme::Pressed(Color color) const {
|
||||||
|
return color.Mixed(text, 0.14f);
|
||||||
|
}
|
||||||
|
|
||||||
|
Color Theme::Taken() const {
|
||||||
|
// A light theme's surface is the lighter of its two grounds; a dark theme's is the darker.
|
||||||
|
return dark ? surfaceAlt.Mixed(text, 0.12f) : surface;
|
||||||
|
}
|
||||||
664
implementations/Nostro.Ui-Widgets.cpp
Normal file
664
implementations/Nostro.Ui-Widgets.cpp
Normal file
|
|
@ -0,0 +1,664 @@
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
module Nostro.Ui:Widgets_impl;
|
||||||
|
import std;
|
||||||
|
import :Widgets;
|
||||||
|
import :Geometry;
|
||||||
|
import :Text;
|
||||||
|
import :Edit;
|
||||||
|
import :Draw;
|
||||||
|
import :Theme;
|
||||||
|
import :Input;
|
||||||
|
import :Context;
|
||||||
|
import :Layout;
|
||||||
|
|
||||||
|
using namespace Nostro::Ui;
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
// A line around a region that has the keyboard's focus.
|
||||||
|
void FocusRing(Frame& frame, Box box, std::string_view key, float radius) {
|
||||||
|
if(frame.FocusRing(key)) {
|
||||||
|
frame.draw.Rect(RectItem{.box = box, .color = frame.Colors().accent.WithAlpha(0), .corners = Corners::All(radius), .outline = frame.Dp(2), .outlineColor = frame.Colors().accent});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A ground's colour as the pointer has it: over it, or pressing it.
|
||||||
|
Color Felt(const Frame& frame, std::string_view key, Color ground) {
|
||||||
|
if(frame.Pressed(key)) {
|
||||||
|
return frame.Colors().Pressed(ground);
|
||||||
|
}
|
||||||
|
return frame.Hovered(key) ? frame.Colors().Hovered(ground) : ground;
|
||||||
|
}
|
||||||
|
|
||||||
|
float Width(const Frame& frame, std::string_view text, const TextStyle& style) {
|
||||||
|
return TextWidth(frame.Measure(), text, style.face, frame.Dp(style.sizeDp));
|
||||||
|
}
|
||||||
|
|
||||||
|
// The area that takes a press on a button: at least as tall as a finger needs, whatever is drawn, the rest taken
|
||||||
|
// evenly from above and below it.
|
||||||
|
Box Reach(const Frame& frame, Box box) {
|
||||||
|
const float more = std::max(0.0f, frame.Dp(Size::touch) - box.h);
|
||||||
|
return {box.x, box.y - more / 2, box.w, box.h + more};
|
||||||
|
}
|
||||||
|
|
||||||
|
// How wide a sheet is: the whole width of a window as narrow as a phone, a dialog's own width in a wider one.
|
||||||
|
float SheetWidth(const Frame& frame) {
|
||||||
|
return frame.sizeClass == SizeClass::Compact ? frame.bounds.w : std::min(frame.bounds.w - frame.Dp(Size::gutter) * 2, frame.Dp(480));
|
||||||
|
}
|
||||||
|
|
||||||
|
// A widget's segments or tabs: equal parts of a box, each a button.
|
||||||
|
void Choices(Frame& frame, Box box, const ChoiceOptions& options, const std::function<void(Box, std::size_t, const std::string&)>& draw) {
|
||||||
|
const float each = box.w / static_cast<float>(std::max<std::size_t>(1, options.labels.size()));
|
||||||
|
for(std::size_t i = 0; i < options.labels.size(); i++) {
|
||||||
|
const Box part{box.x + each * static_cast<float>(i), box.y, each, box.h};
|
||||||
|
const std::string key = std::format("{}.{}", options.key, i);
|
||||||
|
draw(part, i, key);
|
||||||
|
Region region;
|
||||||
|
region.box = part;
|
||||||
|
region.key = key;
|
||||||
|
region.label = options.labels[i];
|
||||||
|
region.enabled = options.enabled;
|
||||||
|
region.focusable = true;
|
||||||
|
if(options.onSelect) {
|
||||||
|
region.onTap = [select = options.onSelect, i] { select(i); };
|
||||||
|
}
|
||||||
|
frame.Add(std::move(region));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
TextStyle Nostro::Ui::Body(const Frame& frame) {
|
||||||
|
return {FontFace::Regular, TextSize::body, frame.Colors().text, TextAlign::Left};
|
||||||
|
}
|
||||||
|
|
||||||
|
TextStyle Nostro::Ui::Strong(const Frame& frame) {
|
||||||
|
return {FontFace::Medium, TextSize::body, frame.Colors().text, TextAlign::Left};
|
||||||
|
}
|
||||||
|
|
||||||
|
TextStyle Nostro::Ui::Muted(const Frame& frame) {
|
||||||
|
return {FontFace::Regular, TextSize::label, frame.Colors().muted, TextAlign::Left};
|
||||||
|
}
|
||||||
|
|
||||||
|
TextStyle Nostro::Ui::Caption(const Frame& frame) {
|
||||||
|
return {FontFace::Regular, TextSize::caption, frame.Colors().muted, TextAlign::Left};
|
||||||
|
}
|
||||||
|
|
||||||
|
TextStyle Nostro::Ui::Heading(const Frame& frame) {
|
||||||
|
return {FontFace::Medium, TextSize::heading, frame.Colors().text, TextAlign::Left};
|
||||||
|
}
|
||||||
|
|
||||||
|
void Nostro::Ui::Label(Frame& frame, Box box, std::string_view text, const TextStyle& style) {
|
||||||
|
const float px = frame.Dp(style.sizeDp);
|
||||||
|
const float x = style.align == TextAlign::Left ? box.x : (style.align == TextAlign::Center ? box.Center().x : box.Right());
|
||||||
|
frame.draw.Text(Ellipsize(frame.Measure(), text, style.face, px, box.w), x, CenteredBaseline(frame.Measure(), box, style.face, px), style.face, px, style.color, style.align);
|
||||||
|
}
|
||||||
|
|
||||||
|
float Nostro::Ui::Paragraph(Frame& frame, Box box, std::string_view text, const TextStyle& style) {
|
||||||
|
const float px = frame.Dp(style.sizeDp);
|
||||||
|
const float lineHeight = frame.Measure().lineHeight(style.face, px);
|
||||||
|
const float x = style.align == TextAlign::Left ? box.x : (style.align == TextAlign::Center ? box.Center().x : box.Right());
|
||||||
|
float baseline = box.y + frame.Measure().ascent(style.face, px);
|
||||||
|
// A copy of the lines: the wrapper's own are gone at its next call.
|
||||||
|
const std::vector<WrappedLine> lines = frame.Wrapper().Wrap(text, style.face, px, box.w);
|
||||||
|
for(const WrappedLine& line : lines) {
|
||||||
|
frame.draw.Text(text.substr(line.begin, line.end - line.begin), x, baseline, style.face, px, style.color, style.align);
|
||||||
|
baseline += lineHeight;
|
||||||
|
}
|
||||||
|
return lineHeight * static_cast<float>(lines.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
float Nostro::Ui::ParagraphHeight(Frame& frame, float width, std::string_view text, const TextStyle& style) {
|
||||||
|
const float px = frame.Dp(style.sizeDp);
|
||||||
|
return frame.Measure().lineHeight(style.face, px) * static_cast<float>(frame.Wrapper().Wrap(text, style.face, px, width).size());
|
||||||
|
}
|
||||||
|
|
||||||
|
void Nostro::Ui::Button(Frame& frame, Box box, const ButtonOptions& options) {
|
||||||
|
const Theme& theme = frame.Colors();
|
||||||
|
Color ground = theme.accent;
|
||||||
|
Color color = theme.onAccent;
|
||||||
|
if(!options.enabled) {
|
||||||
|
ground = theme.surfaceAlt;
|
||||||
|
color = theme.muted;
|
||||||
|
} else if(options.kind == ButtonKind::Tonal) {
|
||||||
|
ground = theme.surfaceAlt;
|
||||||
|
color = theme.text;
|
||||||
|
} else if(options.kind == ButtonKind::Danger) {
|
||||||
|
ground = theme.danger;
|
||||||
|
color = theme.onDanger;
|
||||||
|
} else if(options.kind == ButtonKind::Plain) {
|
||||||
|
ground = theme.surface;
|
||||||
|
color = theme.accent;
|
||||||
|
}
|
||||||
|
const float radius = frame.Dp(Size::controlRadius);
|
||||||
|
// Text alone has no ground until the pointer is on it.
|
||||||
|
if(options.kind != ButtonKind::Plain || frame.Pressed(options.key) || frame.Hovered(options.key)) {
|
||||||
|
frame.draw.Rect(box, options.enabled ? Felt(frame, options.key, ground) : ground, radius);
|
||||||
|
}
|
||||||
|
Label(frame, box, options.label, {FontFace::Medium, TextSize::body, color, TextAlign::Center});
|
||||||
|
FocusRing(frame, box, options.key, radius);
|
||||||
|
Region region;
|
||||||
|
region.box = Reach(frame, box);
|
||||||
|
region.key = options.key;
|
||||||
|
region.label = options.label;
|
||||||
|
region.enabled = options.enabled;
|
||||||
|
region.focusable = true;
|
||||||
|
region.onTap = options.onTap;
|
||||||
|
frame.Add(std::move(region));
|
||||||
|
}
|
||||||
|
|
||||||
|
float Nostro::Ui::ButtonWidth(const Frame& frame, std::string_view label) {
|
||||||
|
return TextWidth(frame.Measure(), label, FontFace::Medium, frame.Dp(TextSize::body)) + frame.Dp(Size::gutter) * 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Nostro::Ui::ListRow(Frame& frame, Box box, const RowOptions& options) {
|
||||||
|
const Theme& theme = frame.Colors();
|
||||||
|
const bool acts = options.enabled && options.onTap != nullptr;
|
||||||
|
if(acts && (frame.Pressed(options.key) || frame.Hovered(options.key))) {
|
||||||
|
frame.draw.Rect(box, Felt(frame, options.key, theme.surface));
|
||||||
|
}
|
||||||
|
float left = box.x + frame.Dp(Size::gutter);
|
||||||
|
float right = box.Right() - frame.Dp(Size::gutter);
|
||||||
|
if(options.selected) {
|
||||||
|
// A radio button: a ring, with a dot in the one that is chosen.
|
||||||
|
const Point center{left + frame.Dp(10), box.Center().y};
|
||||||
|
const Color ring = *options.selected ? theme.accent : theme.muted;
|
||||||
|
frame.draw.Circle(CircleItem{.center = center, .radius = frame.Dp(10), .color = ring.WithAlpha(0), .outline = frame.Dp(2), .outlineColor = ring});
|
||||||
|
if(*options.selected) {
|
||||||
|
frame.draw.Circle(center, frame.Dp(5), theme.accent);
|
||||||
|
}
|
||||||
|
left += frame.Dp(36);
|
||||||
|
}
|
||||||
|
if(options.chevron) {
|
||||||
|
frame.draw.Text("›", right, CenteredBaseline(frame.Measure(), box, FontFace::Regular, frame.Dp(TextSize::title)), FontFace::Regular, frame.Dp(TextSize::title), theme.muted, TextAlign::Right);
|
||||||
|
right -= frame.Dp(20);
|
||||||
|
}
|
||||||
|
const Color ink = options.enabled ? theme.text : theme.muted;
|
||||||
|
const bool twoLines = !options.subtitle.empty();
|
||||||
|
// Two lines sit above and below the row's middle, one in it.
|
||||||
|
const Box upper = twoLines ? Box{box.x, box.Center().y - frame.Dp(22), box.w, frame.Dp(22)} : box;
|
||||||
|
const Box lower{box.x, box.Center().y, box.w, frame.Dp(20)};
|
||||||
|
float trailingWidth = 0;
|
||||||
|
if(!options.trailing.empty()) {
|
||||||
|
const TextStyle style{FontFace::Medium, TextSize::body, options.trailingColor.value_or(ink), TextAlign::Right};
|
||||||
|
trailingWidth = Width(frame, options.trailing, style);
|
||||||
|
Label(frame, {left, options.trailingSub.empty() ? box.y : upper.y, right - left, options.trailingSub.empty() ? box.h : upper.h}, options.trailing, style);
|
||||||
|
}
|
||||||
|
if(!options.trailingSub.empty()) {
|
||||||
|
const TextStyle style{FontFace::Regular, TextSize::caption, theme.muted, TextAlign::Right};
|
||||||
|
trailingWidth = std::max(trailingWidth, Width(frame, options.trailingSub, style));
|
||||||
|
Label(frame, {left, options.trailing.empty() ? box.y : lower.y, right - left, options.trailing.empty() ? box.h : lower.h}, options.trailingSub, style);
|
||||||
|
}
|
||||||
|
if(trailingWidth > 0) {
|
||||||
|
right -= trailingWidth + frame.Dp(Size::unit * 3);
|
||||||
|
}
|
||||||
|
float titleRoom = std::max(0.0f, right - left);
|
||||||
|
if(!options.badge.empty()) {
|
||||||
|
// The mark follows the title, and the title makes room for it.
|
||||||
|
const float badgeWidth = ChipWidth(frame, options.badge);
|
||||||
|
titleRoom = std::max(0.0f, titleRoom - badgeWidth - frame.Dp(Size::unit * 2));
|
||||||
|
const float titleWidth = std::min(titleRoom, Width(frame, options.title, {FontFace::Regular, TextSize::body, ink, TextAlign::Left}));
|
||||||
|
Chip(frame, {left + titleWidth + frame.Dp(Size::unit * 2), upper.Center().y - frame.Dp(10), badgeWidth, frame.Dp(20)}, options.badge, theme.surfaceAlt, theme.muted);
|
||||||
|
}
|
||||||
|
Label(frame, {left, upper.y, titleRoom, upper.h}, options.title, {FontFace::Regular, TextSize::body, ink, TextAlign::Left});
|
||||||
|
if(twoLines) {
|
||||||
|
Label(frame, {left, lower.y, std::max(0.0f, right - left), lower.h}, options.subtitle, Muted(frame));
|
||||||
|
}
|
||||||
|
if(options.divider) {
|
||||||
|
// To the window's edge on a phone, as its lists have it; in a wider window as far as the row's text goes.
|
||||||
|
const float end = frame.sizeClass == SizeClass::Compact ? box.Right() : box.Right() - frame.Dp(Size::gutter);
|
||||||
|
Divider(frame, {left, box.y, end - left, box.h});
|
||||||
|
}
|
||||||
|
FocusRing(frame, box.Inset(Insets::All(frame.Dp(2))), options.key, frame.Dp(Size::controlRadius));
|
||||||
|
Region region;
|
||||||
|
region.box = box;
|
||||||
|
region.key = options.key;
|
||||||
|
region.role = Role::Row;
|
||||||
|
region.label = options.title;
|
||||||
|
region.enabled = options.enabled;
|
||||||
|
region.focusable = options.onTap != nullptr;
|
||||||
|
region.onTap = options.onTap;
|
||||||
|
region.onLongPress = options.onLongPress;
|
||||||
|
frame.Add(std::move(region));
|
||||||
|
}
|
||||||
|
|
||||||
|
float Nostro::Ui::ValueRowHeight(Frame& frame, float width, const ValueOptions& options) {
|
||||||
|
const float room = std::max(0.0f, width - frame.Dp(Size::unit * 4) - frame.Dp(options.labelWidth));
|
||||||
|
// A finger's height where a finger presses it; closer together under a pointer.
|
||||||
|
const float least = frame.Dp(frame.sizeClass == SizeClass::Compact ? Size::touch : 36.0f);
|
||||||
|
return std::max(least, ParagraphHeight(frame, room, options.value, Body(frame)) + frame.Dp(Size::unit * 3));
|
||||||
|
}
|
||||||
|
|
||||||
|
float Nostro::Ui::ValueRow(Frame& frame, Box box, const ValueOptions& options) {
|
||||||
|
const TextStyle label = Muted(frame);
|
||||||
|
const TextStyle value = Body(frame);
|
||||||
|
const Box row{box.x, box.y, box.w, ValueRowHeight(frame, box.w, options)};
|
||||||
|
const float radius = frame.Dp(Size::controlRadius);
|
||||||
|
const bool acts = options.onTap != nullptr;
|
||||||
|
if(acts && (frame.Pressed(options.key) || frame.Hovered(options.key))) {
|
||||||
|
frame.draw.Rect(row, Felt(frame, options.key, frame.Colors().surface), radius);
|
||||||
|
}
|
||||||
|
const float inset = frame.Dp(Size::unit * 2);
|
||||||
|
const float labelWidth = frame.Dp(options.labelWidth);
|
||||||
|
const float room = std::max(0.0f, row.w - inset * 2 - labelWidth);
|
||||||
|
// The value in the middle of the row's height, and the label on the line the value begins on, whatever their sizes.
|
||||||
|
const float top = row.y + (row.h - ParagraphHeight(frame, room, options.value, value)) / 2;
|
||||||
|
const float labelPx = frame.Dp(label.sizeDp);
|
||||||
|
frame.draw.Text(Ellipsize(frame.Measure(), options.label, label.face, labelPx, std::max(0.0f, labelWidth - inset)), row.x + inset, top + frame.Measure().ascent(value.face, frame.Dp(value.sizeDp)), label.face, labelPx, label.color);
|
||||||
|
Paragraph(frame, {row.x + inset + labelWidth, top, room, 0}, options.value, value);
|
||||||
|
if(acts) {
|
||||||
|
FocusRing(frame, row, options.key, radius);
|
||||||
|
Region region;
|
||||||
|
region.box = row;
|
||||||
|
region.key = options.key;
|
||||||
|
region.role = Role::Row;
|
||||||
|
region.label = options.label;
|
||||||
|
region.focusable = true;
|
||||||
|
region.onTap = options.onTap;
|
||||||
|
region.onLongPress = options.onLongPress;
|
||||||
|
frame.Add(std::move(region));
|
||||||
|
}
|
||||||
|
return row.h;
|
||||||
|
}
|
||||||
|
|
||||||
|
float Nostro::Ui::TextField(Frame& frame, Box box, EditState& edit, const FieldOptions& options) {
|
||||||
|
const Theme& theme = frame.Colors();
|
||||||
|
const TextMeasure& measure = frame.Measure();
|
||||||
|
float y = box.y;
|
||||||
|
if(!options.label.empty()) {
|
||||||
|
Label(frame, {box.x, y, box.w, frame.Dp(20)}, options.label, Muted(frame));
|
||||||
|
y += frame.Dp(20) + frame.Dp(Size::unit);
|
||||||
|
}
|
||||||
|
const Box control{box.x, y, box.w, frame.Dp(Size::control)};
|
||||||
|
const bool focused = frame.Focused(options.key) && options.enabled;
|
||||||
|
const Color edge = !options.error.empty() ? theme.danger : (focused ? theme.accent : theme.divider);
|
||||||
|
frame.draw.Rect(RectItem{.box = control, .color = options.enabled ? theme.surface : theme.surfaceAlt, .corners = Corners::All(frame.Dp(Size::controlRadius)), .outline = frame.Dp(focused ? 2 : 1), .outlineColor = edge});
|
||||||
|
|
||||||
|
const float px = frame.Dp(TextSize::body);
|
||||||
|
constexpr FontFace face = FontFace::Regular;
|
||||||
|
const float baseline = CenteredBaseline(measure, control, face, px);
|
||||||
|
float textX = control.x + frame.Dp(12);
|
||||||
|
if(!options.prefix.empty()) {
|
||||||
|
textX += frame.draw.Text(options.prefix, textX, baseline, face, px, theme.muted) + frame.Dp(6);
|
||||||
|
}
|
||||||
|
const float room = std::max(0.0f, control.Right() - frame.Dp(12) - textX);
|
||||||
|
|
||||||
|
// What the field shows, and where its cursor is in that: a secret is a dot for each of its code points.
|
||||||
|
const bool masked = edit.kind == FieldKind::Secret;
|
||||||
|
const std::string shown = edit.Shown();
|
||||||
|
const std::string drawn = FieldText(edit, masked);
|
||||||
|
const auto drawnOffset = [&shown, masked](std::size_t shownByte) {
|
||||||
|
return masked ? CountCodepoints(std::string_view(shown).substr(0, shownByte)) * std::string_view("•").size() : shownByte;
|
||||||
|
};
|
||||||
|
const std::size_t cursor = drawnOffset(edit.ShownCursor());
|
||||||
|
// A text too long for the field is shown from where the cursor still fits at its right end; without the focus,
|
||||||
|
// from its start.
|
||||||
|
std::size_t first = 0;
|
||||||
|
if(focused) {
|
||||||
|
while(first < cursor && TextWidth(measure, std::string_view(drawn).substr(first, cursor - first), face, px) > room) {
|
||||||
|
first = NextCodepoint(drawn, first);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
std::size_t last = first;
|
||||||
|
for(float width = 0; last < drawn.size();) {
|
||||||
|
std::size_t next = last;
|
||||||
|
width += measure.advance(face, DecodeUtf8(drawn, next), px);
|
||||||
|
if(width > room) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
last = next;
|
||||||
|
}
|
||||||
|
const auto xAt = [&](std::size_t drawnByte) {
|
||||||
|
const std::size_t to = std::clamp(drawnByte, first, last);
|
||||||
|
return textX + TextWidth(measure, std::string_view(drawn).substr(first, to - first), face, px);
|
||||||
|
};
|
||||||
|
|
||||||
|
if(drawn.empty()) {
|
||||||
|
frame.draw.Text(Ellipsize(measure, options.placeholder, face, px, room), textX, baseline, face, px, theme.muted);
|
||||||
|
} else {
|
||||||
|
if(focused && edit.HasSelection() && edit.preedit.empty()) {
|
||||||
|
const float from = xAt(drawnOffset(edit.SelectionBegin()));
|
||||||
|
frame.draw.Rect({from, control.y + frame.Dp(10), xAt(drawnOffset(edit.SelectionEnd())) - from, control.h - frame.Dp(20)}, theme.accent.WithAlpha(0.3f));
|
||||||
|
}
|
||||||
|
// Up to three runs: before, inside and after the composing text, which shows in the accent colour until the input
|
||||||
|
// method commits it. Without one the text is a single run.
|
||||||
|
const std::size_t composingFrom = edit.preedit.empty() ? last : std::clamp(drawnOffset(edit.cursor), first, last);
|
||||||
|
const std::array<std::size_t, 4> bounds = {first, composingFrom, edit.preedit.empty() ? last : std::clamp(cursor, first, last), last};
|
||||||
|
float x = textX;
|
||||||
|
for(std::size_t run = 0; run < 3; run++) {
|
||||||
|
if(bounds[run + 1] > bounds[run]) {
|
||||||
|
x += frame.draw.Text(std::string_view(drawn).substr(bounds[run], bounds[run + 1] - bounds[run]), x, baseline, face, px, run == 1 ? theme.accent : (options.enabled ? theme.text : theme.muted));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const Box caret{xAt(cursor), control.y + frame.Dp(12), frame.Dp(2), control.h - frame.Dp(24)};
|
||||||
|
if(focused && frame.CaretOn()) {
|
||||||
|
frame.draw.Rect(caret, theme.accent);
|
||||||
|
}
|
||||||
|
|
||||||
|
Region region;
|
||||||
|
region.box = control;
|
||||||
|
region.key = options.key;
|
||||||
|
region.role = Role::Field;
|
||||||
|
region.label = options.label;
|
||||||
|
region.enabled = options.enabled;
|
||||||
|
region.focusable = true;
|
||||||
|
region.onChange = options.onChange;
|
||||||
|
region.onSubmit = options.onSubmit;
|
||||||
|
region.edit = &edit;
|
||||||
|
// What an on-screen keyboard is asked for, by what the field holds.
|
||||||
|
static constexpr std::array<std::pair<TextPurpose, std::uint32_t>, 5> byKind = {{
|
||||||
|
{TextPurpose::Normal, TextHint::prose}, {TextPurpose::Normal, TextHint::none}, {TextPurpose::Number, TextHint::none},
|
||||||
|
{TextPurpose::Digits, TextHint::none}, {TextPurpose::Password, TextHint::secret},
|
||||||
|
}};
|
||||||
|
const std::pair<TextPurpose, std::uint32_t>& asked = byKind[static_cast<std::size_t>(edit.kind)];
|
||||||
|
region.field = {textX, face, px, first, masked, caret, options.purpose.value_or(asked.first), options.hints.value_or(asked.second)};
|
||||||
|
frame.Add(std::move(region));
|
||||||
|
|
||||||
|
const std::string& under = options.error.empty() ? options.helper : options.error;
|
||||||
|
if(!under.empty()) {
|
||||||
|
TextStyle style = Caption(frame);
|
||||||
|
if(!options.error.empty()) {
|
||||||
|
style.color = theme.danger;
|
||||||
|
}
|
||||||
|
Paragraph(frame, {box.x, control.Bottom() + frame.Dp(Size::unit), box.w, 0}, under, style);
|
||||||
|
}
|
||||||
|
return FieldHeight(frame, box.w, options);
|
||||||
|
}
|
||||||
|
|
||||||
|
float Nostro::Ui::FieldHeight(Frame& frame, float width, const FieldOptions& options) {
|
||||||
|
float height = frame.Dp(Size::control);
|
||||||
|
if(!options.label.empty()) {
|
||||||
|
height += frame.Dp(20) + frame.Dp(Size::unit);
|
||||||
|
}
|
||||||
|
const std::string& under = options.error.empty() ? options.helper : options.error;
|
||||||
|
if(!under.empty()) {
|
||||||
|
height += frame.Dp(Size::unit) + ParagraphHeight(frame, width, under, Caption(frame));
|
||||||
|
}
|
||||||
|
return height;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Nostro::Ui::Segmented(Frame& frame, Box box, const ChoiceOptions& options) {
|
||||||
|
const Theme& theme = frame.Colors();
|
||||||
|
const float radius = frame.Dp(Size::controlRadius);
|
||||||
|
frame.draw.Rect(box, theme.surfaceAlt, radius);
|
||||||
|
Choices(frame, box, options, [&](Box part, std::size_t i, const std::string& key) {
|
||||||
|
const bool selected = i == options.selected;
|
||||||
|
const Box inner = part.Inset(Insets::All(frame.Dp(3)));
|
||||||
|
if(selected) {
|
||||||
|
frame.draw.Rect(inner, theme.Taken(), radius - frame.Dp(2));
|
||||||
|
} else if(options.enabled && (frame.Pressed(key) || frame.Hovered(key))) {
|
||||||
|
frame.draw.Rect(inner, Felt(frame, key, theme.surfaceAlt), radius - frame.Dp(2));
|
||||||
|
}
|
||||||
|
Label(frame, inner, options.labels[i], {selected ? FontFace::Medium : FontFace::Regular, TextSize::label, options.enabled ? theme.text : theme.muted, TextAlign::Center});
|
||||||
|
FocusRing(frame, inner, key, radius - frame.Dp(2));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
void Nostro::Ui::Tabs(Frame& frame, Box box, const ChoiceOptions& options) {
|
||||||
|
const Theme& theme = frame.Colors();
|
||||||
|
Divider(frame, box);
|
||||||
|
// The labels a size down where they would not all fit beside each other.
|
||||||
|
const float each = box.w / static_cast<float>(std::max<std::size_t>(1, options.labels.size()));
|
||||||
|
float size = TextSize::caption;
|
||||||
|
if(std::ranges::all_of(options.labels, [&](const std::string& label) { return TextWidth(frame.Measure(), label, FontFace::Medium, frame.Dp(TextSize::label)) + frame.Dp(Size::unit * 2) <= each; })) {
|
||||||
|
size = TextSize::label;
|
||||||
|
}
|
||||||
|
Choices(frame, box, options, [&](Box part, std::size_t i, const std::string& key) {
|
||||||
|
const bool selected = i == options.selected;
|
||||||
|
if(options.enabled && (frame.Pressed(key) || frame.Hovered(key))) {
|
||||||
|
frame.draw.Rect(part, Felt(frame, key, theme.surface));
|
||||||
|
}
|
||||||
|
Label(frame, part, options.labels[i], {FontFace::Medium, size, selected ? theme.accent : theme.muted, TextAlign::Center});
|
||||||
|
if(selected) {
|
||||||
|
frame.draw.Rect({part.x + frame.Dp(Size::unit * 2), part.Bottom() - frame.Dp(3), std::max(0.0f, part.w - frame.Dp(Size::unit * 4)), frame.Dp(3)}, theme.accent, frame.Dp(1.5f));
|
||||||
|
}
|
||||||
|
FocusRing(frame, part.Inset(Insets::All(frame.Dp(2))), key, frame.Dp(Size::controlRadius));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
float Nostro::Ui::Banner(Frame& frame, Box box, const BannerOptions& options) {
|
||||||
|
const Theme& theme = frame.Colors();
|
||||||
|
Color ground = theme.surfaceAlt;
|
||||||
|
Color ink = theme.text;
|
||||||
|
if(options.kind == BannerKind::Warning) {
|
||||||
|
ground = theme.warning;
|
||||||
|
ink = theme.onWarning;
|
||||||
|
} else if(options.kind == BannerKind::Error) {
|
||||||
|
ground = theme.danger;
|
||||||
|
ink = theme.onDanger;
|
||||||
|
}
|
||||||
|
const float pad = frame.Dp(12);
|
||||||
|
const float close = options.onDismiss ? frame.Dp(Size::touch) : 0.0f;
|
||||||
|
TextStyle style = Muted(frame);
|
||||||
|
style.color = ink;
|
||||||
|
const float textWidth = std::max(0.0f, box.w - pad * 2 - close);
|
||||||
|
const float textHeight = ParagraphHeight(frame, textWidth, options.text, style);
|
||||||
|
const float actionHeight = options.action.empty() ? 0.0f : frame.Dp(40);
|
||||||
|
const float height = std::max(pad * 2 + textHeight + actionHeight, close);
|
||||||
|
const Box ground_{box.x, box.y, box.w, height};
|
||||||
|
frame.draw.Rect(ground_, ground, frame.Dp(Size::controlRadius));
|
||||||
|
Paragraph(frame, {box.x + pad, box.y + pad, textWidth, 0}, options.text, style);
|
||||||
|
if(!options.action.empty()) {
|
||||||
|
const float width = ButtonWidth(frame, options.action);
|
||||||
|
const Box button{box.x + pad, box.y + pad + textHeight + frame.Dp(Size::unit), width, frame.Dp(36)};
|
||||||
|
// The action in the notice's own ink: an accent on a warning's ground would not be read.
|
||||||
|
frame.draw.Rect(RectItem{.box = button, .color = Felt(frame, std::format("{}.action", options.key), ground), .corners = Corners::All(frame.Dp(Size::controlRadius)), .outline = frame.Dp(1), .outlineColor = ink});
|
||||||
|
Label(frame, button, options.action, {FontFace::Medium, TextSize::label, ink, TextAlign::Center});
|
||||||
|
FocusRing(frame, button, std::format("{}.action", options.key), frame.Dp(Size::controlRadius));
|
||||||
|
Region region;
|
||||||
|
region.box = Reach(frame, button);
|
||||||
|
region.key = std::format("{}.action", options.key);
|
||||||
|
region.label = options.action;
|
||||||
|
region.focusable = true;
|
||||||
|
region.onTap = options.onAction;
|
||||||
|
frame.Add(std::move(region));
|
||||||
|
}
|
||||||
|
if(options.onDismiss) {
|
||||||
|
const Box button{box.Right() - close, box.y, close, close};
|
||||||
|
Label(frame, button, "×", {FontFace::Regular, TextSize::title, ink, TextAlign::Center});
|
||||||
|
FocusRing(frame, button.Inset(Insets::All(frame.Dp(6))), std::format("{}.dismiss", options.key), frame.Dp(Size::controlRadius));
|
||||||
|
Region region;
|
||||||
|
region.box = button;
|
||||||
|
region.key = std::format("{}.dismiss", options.key);
|
||||||
|
region.label = "Dismiss";
|
||||||
|
region.focusable = true;
|
||||||
|
region.onTap = options.onDismiss;
|
||||||
|
frame.Add(std::move(region));
|
||||||
|
}
|
||||||
|
return height;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Nostro::Ui::Chip(Frame& frame, Box box, std::string_view text, Color ground, Color color) {
|
||||||
|
frame.draw.Rect(box, ground, box.h / 2);
|
||||||
|
Label(frame, box, text, {FontFace::Medium, TextSize::caption, color, TextAlign::Center});
|
||||||
|
}
|
||||||
|
|
||||||
|
float Nostro::Ui::ChipWidth(const Frame& frame, std::string_view text) {
|
||||||
|
return TextWidth(frame.Measure(), text, FontFace::Medium, frame.Dp(TextSize::caption)) + frame.Dp(Size::unit * 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
void Nostro::Ui::Divider(Frame& frame, Box box) {
|
||||||
|
frame.draw.Rect({box.x, box.Bottom() - frame.Dp(1), box.w, frame.Dp(1)}, frame.Colors().divider);
|
||||||
|
}
|
||||||
|
|
||||||
|
void Nostro::Ui::Skeleton(Frame& frame, Box box, float fraction) {
|
||||||
|
frame.draw.Rect({box.x, box.y, box.w * fraction, box.h}, frame.Colors().surfaceAlt, box.h / 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
Box Nostro::Ui::TopBar(Frame& frame, Box area, const TopBarOptions& options) {
|
||||||
|
const Theme& theme = frame.Colors();
|
||||||
|
const Layer before = frame.draw.CurrentLayer();
|
||||||
|
frame.draw.SetLayer(Layer::Chrome);
|
||||||
|
const Box bar{area.x, area.y, area.w, frame.Dp(Size::bar)};
|
||||||
|
frame.draw.Rect(bar, theme.surface);
|
||||||
|
Divider(frame, bar);
|
||||||
|
Region ground;
|
||||||
|
ground.box = bar;
|
||||||
|
ground.key = "bar";
|
||||||
|
ground.role = Role::Panel;
|
||||||
|
frame.Add(std::move(ground));
|
||||||
|
Row row(bar.Inset(Insets::Symmetric(frame.Dp(Size::unit), 0)), frame.Dp(Size::unit));
|
||||||
|
if(options.onBack) {
|
||||||
|
const Box button = row.TakeLeft(frame.Dp(Size::touch));
|
||||||
|
const Box felt = button.Inset(Insets::Symmetric(0, frame.Dp(Size::unit)));
|
||||||
|
if(frame.Pressed("bar.back") || frame.Hovered("bar.back")) {
|
||||||
|
frame.draw.Rect(felt, Felt(frame, "bar.back", theme.surface), frame.Dp(Size::controlRadius));
|
||||||
|
}
|
||||||
|
Label(frame, button, "‹", {FontFace::Regular, TextSize::display, theme.accent, TextAlign::Center});
|
||||||
|
FocusRing(frame, felt, "bar.back", frame.Dp(Size::controlRadius));
|
||||||
|
Region region;
|
||||||
|
region.box = button;
|
||||||
|
region.key = "bar.back";
|
||||||
|
region.label = "Back";
|
||||||
|
region.focusable = true;
|
||||||
|
region.onTap = options.onBack;
|
||||||
|
frame.Add(std::move(region));
|
||||||
|
frame.Shortcut(Key::Escape, {}, options.onBack);
|
||||||
|
} else {
|
||||||
|
row.TakeLeft(frame.Dp(Size::gutter - Size::unit * 2));
|
||||||
|
}
|
||||||
|
// From the right, in the order they are named.
|
||||||
|
for(const BarAction& action : std::views::reverse(options.actions)) {
|
||||||
|
Button(frame, row.TakeRight(ButtonWidth(frame, action.label)).Inset(Insets::Symmetric(0, frame.Dp(Size::unit))), {.key = action.key, .label = action.label, .kind = ButtonKind::Plain, .enabled = action.enabled, .onTap = action.onTap});
|
||||||
|
}
|
||||||
|
Label(frame, row.Rest(), options.title, {FontFace::Medium, TextSize::heading, theme.text, TextAlign::Left});
|
||||||
|
frame.draw.SetLayer(before);
|
||||||
|
return {area.x, bar.Bottom(), area.w, std::max(0.0f, area.h - bar.h)};
|
||||||
|
}
|
||||||
|
|
||||||
|
Box Nostro::Ui::NavBar(Frame& frame, Box area, std::span<const NavItem> items) {
|
||||||
|
const Theme& theme = frame.Colors();
|
||||||
|
const Layer before = frame.draw.CurrentLayer();
|
||||||
|
frame.draw.SetLayer(Layer::Chrome);
|
||||||
|
const float height = std::min(area.h, frame.Dp(Size::bar));
|
||||||
|
const Box bar{area.x, area.Bottom() - height, area.w, height};
|
||||||
|
frame.draw.Rect(bar, theme.surface);
|
||||||
|
frame.draw.Rect({bar.x, bar.y, bar.w, frame.Dp(1)}, theme.divider);
|
||||||
|
Region ground;
|
||||||
|
ground.box = bar;
|
||||||
|
ground.key = "nav";
|
||||||
|
ground.role = Role::Panel;
|
||||||
|
frame.Add(std::move(ground));
|
||||||
|
const float each = bar.w / static_cast<float>(std::max<std::size_t>(1, items.size()));
|
||||||
|
for(std::size_t i = 0; i < items.size(); i++) {
|
||||||
|
const NavItem& item = items[i];
|
||||||
|
const Box part{bar.x + each * static_cast<float>(i), bar.y, each, bar.h};
|
||||||
|
// The place the window is at stands on a pill.
|
||||||
|
const float pillWidth = std::min(part.w - frame.Dp(Size::unit * 2), TextWidth(frame.Measure(), item.label, FontFace::Medium, frame.Dp(TextSize::label)) + frame.Dp(Size::gutter * 2));
|
||||||
|
const Box pill{part.Center().x - pillWidth / 2, part.Center().y - frame.Dp(16), pillWidth, frame.Dp(32)};
|
||||||
|
if(item.selected) {
|
||||||
|
frame.draw.Rect(pill, theme.accent.WithAlpha(theme.dark ? 0.28f : 0.14f), frame.Dp(16));
|
||||||
|
} else if(frame.Pressed(item.key) || frame.Hovered(item.key)) {
|
||||||
|
frame.draw.Rect(pill, Felt(frame, item.key, theme.surface), frame.Dp(16));
|
||||||
|
}
|
||||||
|
Label(frame, part, item.label, {FontFace::Medium, TextSize::label, item.selected ? theme.accent : theme.muted, TextAlign::Center});
|
||||||
|
FocusRing(frame, pill, item.key, frame.Dp(16));
|
||||||
|
Region region;
|
||||||
|
region.box = part;
|
||||||
|
region.key = item.key;
|
||||||
|
region.label = item.label;
|
||||||
|
region.focusable = true;
|
||||||
|
region.onTap = item.onTap;
|
||||||
|
frame.Add(std::move(region));
|
||||||
|
}
|
||||||
|
frame.draw.SetLayer(before);
|
||||||
|
return {area.x, area.y, area.w, area.h - height};
|
||||||
|
}
|
||||||
|
|
||||||
|
Box Nostro::Ui::Sidebar(Frame& frame, Box area, float widthDp, std::span<const NavItem> items) {
|
||||||
|
const Theme& theme = frame.Colors();
|
||||||
|
const Layer before = frame.draw.CurrentLayer();
|
||||||
|
frame.draw.SetLayer(Layer::Chrome);
|
||||||
|
const float width = std::min(area.w, frame.Dp(widthDp));
|
||||||
|
const Box bar{area.x, area.y, width, area.h};
|
||||||
|
frame.draw.Rect(bar, theme.surface);
|
||||||
|
frame.draw.Rect({bar.Right() - frame.Dp(1), bar.y, frame.Dp(1), bar.h}, theme.divider);
|
||||||
|
Region ground;
|
||||||
|
ground.box = bar;
|
||||||
|
ground.key = "side";
|
||||||
|
ground.role = Role::Panel;
|
||||||
|
frame.Add(std::move(ground));
|
||||||
|
// A long list of accounts scrolls within the bar.
|
||||||
|
const float offset = frame.BeginScroll("side.scroll", bar);
|
||||||
|
Column column({bar.x, bar.y - offset + frame.Dp(Size::unit * 2), bar.w, bar.h});
|
||||||
|
for(const NavItem& item : items) {
|
||||||
|
if(item.header) {
|
||||||
|
Label(frame, column.Take(frame.Dp(32)).Inset(Insets::Symmetric(frame.Dp(Size::gutter), 0)), item.label, Caption(frame));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const Box row = column.Take(frame.Dp(44));
|
||||||
|
const Box pill = row.Inset(Insets::Symmetric(frame.Dp(Size::unit * 2), frame.Dp(2)));
|
||||||
|
if(item.selected) {
|
||||||
|
frame.draw.Rect(pill, theme.accent.WithAlpha(theme.dark ? 0.28f : 0.14f), frame.Dp(Size::controlRadius));
|
||||||
|
} else if(frame.Pressed(item.key) || frame.Hovered(item.key)) {
|
||||||
|
frame.draw.Rect(pill, Felt(frame, item.key, theme.surface), frame.Dp(Size::controlRadius));
|
||||||
|
}
|
||||||
|
const Box text = pill.Inset(Insets::Symmetric(frame.Dp(Size::unit * 2), 0));
|
||||||
|
float detailWidth = 0;
|
||||||
|
if(!item.detail.empty()) {
|
||||||
|
const TextStyle style{FontFace::Regular, TextSize::caption, theme.muted, TextAlign::Right};
|
||||||
|
detailWidth = Width(frame, item.detail, style) + frame.Dp(Size::unit * 2);
|
||||||
|
// The detail gives way where the bar is too narrow for both.
|
||||||
|
if(detailWidth * 2 < text.w) {
|
||||||
|
Label(frame, text, item.detail, style);
|
||||||
|
} else {
|
||||||
|
detailWidth = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Label(frame, {text.x, text.y, text.w - detailWidth, text.h}, item.label, {item.selected ? FontFace::Medium : FontFace::Regular, TextSize::label, item.selected ? theme.accent : theme.text, TextAlign::Left});
|
||||||
|
FocusRing(frame, pill, item.key, frame.Dp(Size::controlRadius));
|
||||||
|
Region region;
|
||||||
|
region.box = row;
|
||||||
|
region.key = item.key;
|
||||||
|
region.label = item.label;
|
||||||
|
region.focusable = true;
|
||||||
|
region.onTap = item.onTap;
|
||||||
|
frame.Add(std::move(region));
|
||||||
|
}
|
||||||
|
frame.EndScroll(column.Used() + frame.Dp(Size::unit * 4));
|
||||||
|
frame.draw.SetLayer(before);
|
||||||
|
return {area.x + width, area.y, area.w - width, area.h};
|
||||||
|
}
|
||||||
|
|
||||||
|
void Nostro::Ui::Sheet(Frame& frame, const SheetOptions& options, const std::function<void(Box)>& body) {
|
||||||
|
const Theme& theme = frame.Colors();
|
||||||
|
const Layer before = frame.draw.CurrentLayer();
|
||||||
|
frame.draw.SetLayer(Layer::Overlay);
|
||||||
|
frame.draw.Rect(frame.bounds, theme.scrim);
|
||||||
|
Region scrim;
|
||||||
|
scrim.box = frame.bounds;
|
||||||
|
scrim.key = std::format("{}.scrim", options.key);
|
||||||
|
scrim.role = Role::Scrim;
|
||||||
|
scrim.onTap = options.onDismiss;
|
||||||
|
frame.Add(std::move(scrim));
|
||||||
|
if(options.onDismiss) {
|
||||||
|
frame.Shortcut(Key::Escape, {}, options.onDismiss);
|
||||||
|
}
|
||||||
|
|
||||||
|
const float pad = frame.Dp(Size::gutter);
|
||||||
|
const float titleHeight = options.title.empty() ? 0.0f : frame.Dp(40);
|
||||||
|
const bool narrow = frame.sizeClass == SizeClass::Compact;
|
||||||
|
const float width = SheetWidth(frame);
|
||||||
|
// No taller than the window leaves room for: the body scrolls what does not fit.
|
||||||
|
const float height = std::min(options.contentHeight + titleHeight + pad * 2, frame.bounds.h - frame.Dp(Size::touch));
|
||||||
|
const Box panel = narrow
|
||||||
|
? Box{frame.bounds.x, frame.bounds.Bottom() - height, width, height}
|
||||||
|
: Box{frame.bounds.Center().x - width / 2, frame.bounds.Center().y - height / 2, width, height};
|
||||||
|
const float radius = frame.Dp(Size::radius);
|
||||||
|
frame.draw.Rect(RectItem{.box = panel, .color = theme.surface, .corners = narrow ? Corners::Top(radius) : Corners::All(radius)});
|
||||||
|
Region ground;
|
||||||
|
ground.box = panel;
|
||||||
|
ground.key = std::format("{}.panel", options.key);
|
||||||
|
ground.role = Role::Panel;
|
||||||
|
frame.Add(std::move(ground));
|
||||||
|
if(!options.title.empty()) {
|
||||||
|
Label(frame, {panel.x + pad, panel.y + pad, panel.w - pad * 2, frame.Dp(28)}, options.title, Heading(frame));
|
||||||
|
}
|
||||||
|
body({panel.x + pad, panel.y + pad + titleHeight, panel.w - pad * 2, std::max(0.0f, panel.h - pad * 2 - titleHeight)});
|
||||||
|
frame.draw.SetLayer(before);
|
||||||
|
}
|
||||||
|
|
||||||
|
float Nostro::Ui::SheetBodyWidth(const Frame& frame) {
|
||||||
|
return SheetWidth(frame) - frame.Dp(Size::gutter) * 2;
|
||||||
|
}
|
||||||
325
implementations/Nostro.Ui.Shell-Canvas.cpp
Normal file
325
implementations/Nostro.Ui.Shell-Canvas.cpp
Normal file
|
|
@ -0,0 +1,325 @@
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
module;
|
||||||
|
#include "vulkan/vulkan.h"
|
||||||
|
module Nostro.Ui.Shell:Canvas_impl;
|
||||||
|
import std;
|
||||||
|
import Crafter.Graphics;
|
||||||
|
import Crafter.Event;
|
||||||
|
import Nostro.Ui;
|
||||||
|
import :Canvas;
|
||||||
|
|
||||||
|
using namespace Nostro::Ui;
|
||||||
|
using namespace Nostro::Ui::Shell;
|
||||||
|
namespace fs = std::filesystem;
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
// A font's file, or the error that names it: the window library reads a file that is not there as an empty font.
|
||||||
|
fs::path Existing(fs::path file) {
|
||||||
|
std::error_code ignored;
|
||||||
|
if(!fs::is_regular_file(file, ignored)) {
|
||||||
|
throw std::runtime_error(std::format("the font {} is missing", file.string()));
|
||||||
|
}
|
||||||
|
return file;
|
||||||
|
}
|
||||||
|
|
||||||
|
constexpr Crafter::TextAlign Align(TextAlign align) noexcept {
|
||||||
|
switch(align) {
|
||||||
|
case TextAlign::Center: return Crafter::TextAlign::Center;
|
||||||
|
case TextAlign::Right: return Crafter::TextAlign::Right;
|
||||||
|
default: return Crafter::TextAlign::Left;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Fonts::Fonts(const fs::path& directory) : regular(Existing(directory / "NotoSans-Regular.ttf")), medium(Existing(directory / "NotoSans-Medium.ttf")) {
|
||||||
|
}
|
||||||
|
|
||||||
|
Crafter::Font& Fonts::Face(FontFace face) noexcept {
|
||||||
|
// There is no font of symbols yet: what asks for one is set in the text font, which has the few marks in use.
|
||||||
|
return face == FontFace::Medium ? medium : regular;
|
||||||
|
}
|
||||||
|
|
||||||
|
TextMeasure Fonts::Measure() {
|
||||||
|
return {
|
||||||
|
.advance = [this](FontFace face, std::uint32_t codepoint, float px) {
|
||||||
|
Crafter::Font& font = Face(face);
|
||||||
|
return static_cast<float>(font.AdvanceUnits(codepoint)) * font.ScaleForSize(px);
|
||||||
|
},
|
||||||
|
.ascent = [this](FontFace face, float px) { return Face(face).AscentPx(px); },
|
||||||
|
.lineHeight = [this](FontFace face, float px) { return Face(face).LineHeight(px); },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
Canvas::Parts::Parts(std::uint32_t width, std::uint32_t height, std::string_view title) : window(width, height, title) {
|
||||||
|
}
|
||||||
|
|
||||||
|
Canvas::Canvas(Fonts& fonts, const CanvasOptions& options) : fonts(fonts), logicalWidth(static_cast<std::int32_t>(options.widthDp)), logicalHeight(static_cast<std::int32_t>(options.heightDp)), pretend(options.scale) {
|
||||||
|
// The device is the process's own and is set up once, whatever number of windows the process makes.
|
||||||
|
static bool deviceReady = false;
|
||||||
|
if(!deviceReady) {
|
||||||
|
std::error_code ignored;
|
||||||
|
fs::create_directories(options.cache, ignored);
|
||||||
|
Crafter::Device::pipelineCachePath = options.cache / "pipeline_cache.bin";
|
||||||
|
Crafter::Device::Initialize();
|
||||||
|
deviceReady = true;
|
||||||
|
}
|
||||||
|
// In pixels at a scale of 1; the display's scale is known only once the window is there.
|
||||||
|
parts.emplace(options.widthDp, options.heightDp, options.title);
|
||||||
|
try {
|
||||||
|
Crafter::Window& window = parts->window;
|
||||||
|
window.SetAppId(options.appId);
|
||||||
|
// Before anything is made for the window's size.
|
||||||
|
Reconcile();
|
||||||
|
const VkCommandBuffer init = window.StartInit();
|
||||||
|
// A slot for every buffer of the pool, and a few to spare; the renderer's own images and its sampler.
|
||||||
|
constexpr std::uint16_t bufferSlots = (smallPairs + largePairs) * 2 * Crafter::Window::numFrames + 16;
|
||||||
|
parts->heap.Initialize(16, bufferSlots, 4);
|
||||||
|
window.descriptorHeap = &parts->heap;
|
||||||
|
parts->atlas.Initialize(init);
|
||||||
|
parts->renderer.fontAtlas = &parts->atlas;
|
||||||
|
// By their full paths: the library looks for its shaders in the working directory, which is the user's.
|
||||||
|
parts->renderer.Initialize(window, parts->heap, init, options.assets / "ui-quads.comp.spv", options.assets / "ui-circles.comp.spv", options.assets / "ui-images.comp.spv", options.assets / "ui-text.comp.spv", options.assets / "ui-fused.comp.spv");
|
||||||
|
window.passes.push_back(&parts->renderer);
|
||||||
|
for(FrameSet& set : parts->pool) {
|
||||||
|
MakePairs(set.small, smallPairs, smallBoxes, smallGlyphs);
|
||||||
|
MakePairs(set.large, largePairs, largeBoxes, largeGlyphs);
|
||||||
|
}
|
||||||
|
parts->build.emplace(&parts->renderer.onBuild, [this](Crafter::UIBuildArgs args) { Build(args.cmd, args.frameIdx); });
|
||||||
|
window.FinishInit();
|
||||||
|
} catch(...) {
|
||||||
|
Release();
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Canvas::~Canvas() {
|
||||||
|
Release();
|
||||||
|
}
|
||||||
|
|
||||||
|
void Canvas::Release() noexcept {
|
||||||
|
if(!parts) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// The frames still on the GPU read the pool's buffers as they run.
|
||||||
|
vkDeviceWaitIdle(Crafter::Device::device);
|
||||||
|
parts.reset();
|
||||||
|
// What the parts held is queued for a later frame to free, and none comes.
|
||||||
|
Crafter::Device::DrainDeletions();
|
||||||
|
}
|
||||||
|
|
||||||
|
void Canvas::MakePairs(std::vector<Pair>& pairs, std::uint32_t count, std::uint32_t boxCap, std::uint32_t glyphCap) {
|
||||||
|
constexpr VkBufferUsageFlags2 usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT;
|
||||||
|
pairs.reserve(count);
|
||||||
|
for(std::uint32_t i = 0; i < count; i++) {
|
||||||
|
Pair& pair = pairs.emplace_back();
|
||||||
|
// Memory the host writes, on the device too where there is such a kind: a GPU with memory of its own need not
|
||||||
|
// have one.
|
||||||
|
pair.boxes.Create(usage, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, boxCap, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
|
||||||
|
pair.glyphs.Create(usage, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, glyphCap, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
|
||||||
|
pair.boxSlot.emplace(parts->renderer.RegisterBuffer(pair.boxes));
|
||||||
|
pair.glyphSlot.emplace(parts->renderer.RegisterBuffer(pair.glyphs));
|
||||||
|
pair.boxCap = boxCap;
|
||||||
|
pair.glyphCap = glyphCap;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Crafter::Window& Canvas::Native() noexcept {
|
||||||
|
return parts->window;
|
||||||
|
}
|
||||||
|
|
||||||
|
const Crafter::Window& Canvas::Native() const noexcept {
|
||||||
|
return parts->window;
|
||||||
|
}
|
||||||
|
|
||||||
|
float Canvas::Scale() const noexcept {
|
||||||
|
const float scale = pretend.value_or(parts->window.scale);
|
||||||
|
return scale > 0 ? scale : 1.0f;
|
||||||
|
}
|
||||||
|
|
||||||
|
Box Canvas::Bounds() const noexcept {
|
||||||
|
return {0, 0, static_cast<float>(parts->window.width), static_cast<float>(parts->window.height)};
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Canvas::Reconcile() {
|
||||||
|
Crafter::Window& window = parts->window;
|
||||||
|
// A frame being recorded draws at the size it began with, and the library sizes the window after it by itself.
|
||||||
|
if(window.recording) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
// What the compositor said since the last look: a size it asks for is the window's from here, and (0, 0), which
|
||||||
|
// leaves the choice to the app, changes nothing. Only its newest word counts, so a size the app asked for after
|
||||||
|
// it stands. At a scale that is not the display's the compositor's sizes mean something else, and are passed over.
|
||||||
|
if(!pretend && (window.pendingLogicalWidth != askedWidth || window.pendingLogicalHeight != askedHeight)) {
|
||||||
|
askedWidth = window.pendingLogicalWidth;
|
||||||
|
askedHeight = window.pendingLogicalHeight;
|
||||||
|
if(askedWidth > 0) {
|
||||||
|
logicalWidth = askedWidth;
|
||||||
|
}
|
||||||
|
if(askedHeight > 0) {
|
||||||
|
logicalHeight = askedHeight;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// In pixels by the library's own sum, so that a size the library did apply is found applied.
|
||||||
|
const float scale = Scale();
|
||||||
|
const std::uint32_t width = static_cast<std::uint32_t>(std::ceil(static_cast<float>(logicalWidth) * scale));
|
||||||
|
const std::uint32_t height = static_cast<std::uint32_t>(std::ceil(static_cast<float>(logicalHeight) * scale));
|
||||||
|
if(width == 0 || height == 0 || (width == window.width && height == window.height)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
window.Resize(width, height);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Canvas::SetSize(std::uint32_t widthDp, std::uint32_t heightDp) noexcept {
|
||||||
|
logicalWidth = static_cast<std::int32_t>(widthDp);
|
||||||
|
logicalHeight = static_cast<std::int32_t>(heightDp);
|
||||||
|
}
|
||||||
|
|
||||||
|
void Canvas::Render(const DrawList& list, Color ground) {
|
||||||
|
drawing = &list;
|
||||||
|
background = ground;
|
||||||
|
try {
|
||||||
|
parts->window.Update();
|
||||||
|
} catch(...) {
|
||||||
|
drawing = nullptr;
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
drawing = nullptr;
|
||||||
|
frames++;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Canvas::Capture(const fs::path& png) {
|
||||||
|
parts->window.CaptureNextFrame(png);
|
||||||
|
}
|
||||||
|
|
||||||
|
const Canvas::Stats& Canvas::Last() const noexcept {
|
||||||
|
return stats;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::uint64_t Canvas::Frames() const noexcept {
|
||||||
|
return frames;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string Canvas::Device() const {
|
||||||
|
// The name is a C array of the driver's.
|
||||||
|
const std::string_view name(Crafter::Device::deviceProperties.deviceName);
|
||||||
|
return std::format("{} ({})", name, Crafter::Device::descriptorHeapSupported ? "descriptor heap" : "descriptor sets");
|
||||||
|
}
|
||||||
|
|
||||||
|
void Canvas::Build(VkCommandBuffer commands, std::uint32_t frameIndex) {
|
||||||
|
FrameSet& set = parts->pool[frameIndex];
|
||||||
|
set.smallUsed = 0;
|
||||||
|
set.largeUsed = 0;
|
||||||
|
stats = {};
|
||||||
|
// Nothing clears the window's image, so the ground is the first thing drawn: under the first batch where that
|
||||||
|
// covers the whole window, which saves a pass over it, and by itself otherwise.
|
||||||
|
const RectItem ground{.box = Bounds(), .color = background};
|
||||||
|
bool grounded = false;
|
||||||
|
if(drawing != nullptr) {
|
||||||
|
for(std::size_t layer = 0; layer < layerCount; layer++) {
|
||||||
|
for(const Batch& batch : drawing->Batches(static_cast<Layer>(layer))) {
|
||||||
|
if(!grounded && batch.clip) {
|
||||||
|
Submit(commands, set, Batch(), &ground);
|
||||||
|
}
|
||||||
|
Submit(commands, set, batch, grounded ? nullptr : &ground);
|
||||||
|
grounded = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if(!grounded) {
|
||||||
|
Submit(commands, set, Batch(), &ground);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Canvas::Pair* Canvas::Take(FrameSet& set, std::size_t boxes, std::size_t glyphs) noexcept {
|
||||||
|
if(boxes <= smallBoxes && glyphs <= smallGlyphs && set.smallUsed < set.small.size()) {
|
||||||
|
return &set.small[set.smallUsed++];
|
||||||
|
}
|
||||||
|
if(set.largeUsed < set.large.size()) {
|
||||||
|
return &set.large[set.largeUsed++];
|
||||||
|
}
|
||||||
|
// No large pair left for a batch that wants one: a small one shows the start of it.
|
||||||
|
if(set.smallUsed < set.small.size()) {
|
||||||
|
return &set.small[set.smallUsed++];
|
||||||
|
}
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Canvas::Submit(VkCommandBuffer commands, FrameSet& set, const Batch& batch, const RectItem* under) {
|
||||||
|
// A glyph per code point at most: enough to choose the buffers by.
|
||||||
|
std::size_t glyphsNeeded = 0;
|
||||||
|
for(const TextItem& text : batch.texts) {
|
||||||
|
glyphsNeeded += CountCodepoints(text.text);
|
||||||
|
}
|
||||||
|
const std::size_t boxesNeeded = batch.rects.size() + batch.circles.size() + (under != nullptr ? 1 : 0);
|
||||||
|
if(boxesNeeded == 0 && glyphsNeeded == 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Pair* const pair = Take(set, boxesNeeded, glyphsNeeded);
|
||||||
|
if(pair == nullptr) {
|
||||||
|
stats.overflowed = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::uint32_t boxes = 0;
|
||||||
|
const auto box = [this, pair, &boxes](Box at, Color color, Corners corners, float outline, Color outlineColor) {
|
||||||
|
if(boxes >= pair->boxCap) {
|
||||||
|
stats.overflowed = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// On whole pixels, edge by edge: boxes that share an edge still do, and a hairline is one row of pixels, not
|
||||||
|
// two half-lit ones.
|
||||||
|
const float left = std::round(at.x);
|
||||||
|
const float top = std::round(at.y);
|
||||||
|
const float right = std::round(at.Right());
|
||||||
|
const float bottom = std::round(at.Bottom());
|
||||||
|
pair->boxes.value[boxes] = Crafter::QuadItem{left, top, right - left, bottom - top, color.r, color.g, color.b, color.a, corners.topLeft, corners.topRight, corners.bottomRight, corners.bottomLeft, outline, outlineColor.r, outlineColor.g, outlineColor.b};
|
||||||
|
boxes++;
|
||||||
|
};
|
||||||
|
if(under != nullptr) {
|
||||||
|
box(under->box, under->color, under->corners, under->outline, under->outlineColor);
|
||||||
|
}
|
||||||
|
for(const RectItem& rect : batch.rects) {
|
||||||
|
box(rect.box, rect.color, rect.corners, rect.outline, rect.outlineColor);
|
||||||
|
}
|
||||||
|
// A circle is a square with its corners rounded all the way, which leaves the batch one kind of shape and one
|
||||||
|
// buffer for it.
|
||||||
|
for(const CircleItem& circle : batch.circles) {
|
||||||
|
box({circle.center.x - circle.radius, circle.center.y - circle.radius, circle.radius * 2, circle.radius * 2}, circle.color, Corners::All(circle.radius), circle.outline, circle.outlineColor);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::uint32_t glyphs = 0;
|
||||||
|
for(const TextItem& text : batch.texts) {
|
||||||
|
Crafter::Font& font = fonts.Face(text.face);
|
||||||
|
// The baseline on a whole pixel, so that a line of text looks the same wherever it is.
|
||||||
|
glyphs += parts->renderer.ShapeText(font, text.px, text.x, std::round(text.baseline), text.text, {text.color.r, text.color.g, text.color.b, text.color.a}, pair->glyphs.value + glyphs, pair->glyphCap - glyphs, nullptr, Align(text.align));
|
||||||
|
// A glyph with ink that found no cell in the atlas drew blank, and gets one when a later frame begins: counted,
|
||||||
|
// so that the frame is asked for.
|
||||||
|
for(std::size_t i = 0; i < text.text.size();) {
|
||||||
|
const std::uint32_t codepoint = DecodeUtf8(text.text, i);
|
||||||
|
if(const Crafter::Glyph* glyph = parts->atlas.Lookup(font, codepoint); glyph != nullptr && glyph->w > 0 && !glyph->Resident()) {
|
||||||
|
stats.glyphsWaiting++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if(glyphsNeeded > pair->glyphCap) {
|
||||||
|
stats.overflowed = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if(boxes == 0 && glyphs == 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if(boxes > 0) {
|
||||||
|
pair->boxes.FlushDevice(commands, VK_ACCESS_SHADER_READ_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
|
||||||
|
}
|
||||||
|
if(glyphs > 0) {
|
||||||
|
pair->glyphs.FlushDevice(commands, VK_ACCESS_SHADER_READ_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
|
||||||
|
}
|
||||||
|
const std::array<float, 4> clip = batch.clip ? std::array<float, 4>{batch.clip->x, batch.clip->y, batch.clip->w, batch.clip->h} : std::array<float, 4>{0.0f, 0.0f, 1e9f, 1e9f};
|
||||||
|
parts->renderer.DispatchFused(commands, {*pair->boxSlot, boxes, clip}, {}, {}, {*pair->glyphSlot, glyphs, clip});
|
||||||
|
stats.batches++;
|
||||||
|
stats.boxes += boxes;
|
||||||
|
stats.glyphs += glyphs;
|
||||||
|
}
|
||||||
285
implementations/Nostro.Ui.Shell-Loop.cpp
Normal file
285
implementations/Nostro.Ui.Shell-Loop.cpp
Normal file
|
|
@ -0,0 +1,285 @@
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
module;
|
||||||
|
#include <errno.h>
|
||||||
|
#include <signal.h>
|
||||||
|
#include <sys/epoll.h>
|
||||||
|
#include <systemd/sd-event.h>
|
||||||
|
#include <time.h>
|
||||||
|
#include <wayland-client.h>
|
||||||
|
module Nostro.Ui.Shell:Loop_impl;
|
||||||
|
import std;
|
||||||
|
import :Loop;
|
||||||
|
|
||||||
|
using namespace Nostro::Ui::Shell;
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
// sd-event's answer, or what it could not do.
|
||||||
|
std::int32_t Checked(std::int32_t result, std::string_view what) {
|
||||||
|
if(result < 0) {
|
||||||
|
throw std::system_error(-result, std::generic_category(), std::format("cannot {}", what));
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::int64_t Nostro::Ui::Shell::NowMs() noexcept {
|
||||||
|
timespec now{};
|
||||||
|
clock_gettime(CLOCK_MONOTONIC, &now);
|
||||||
|
return static_cast<std::int64_t>(now.tv_sec) * 1000 + now.tv_nsec / 1000000;
|
||||||
|
}
|
||||||
|
|
||||||
|
Loop::Loop() {
|
||||||
|
Checked(sd_event_new(&event), "make an event loop");
|
||||||
|
try {
|
||||||
|
// A signal is a source like the rest once it is blocked, and a thread started later inherits the mask.
|
||||||
|
sigset_t ending{};
|
||||||
|
sigemptyset(&ending);
|
||||||
|
sigaddset(&ending, SIGINT);
|
||||||
|
sigaddset(&ending, SIGTERM);
|
||||||
|
sigprocmask(SIG_BLOCK, &ending, nullptr);
|
||||||
|
Checked(sd_event_add_signal(event, nullptr, SIGINT, nullptr, nullptr), "watch for SIGINT");
|
||||||
|
Checked(sd_event_add_signal(event, nullptr, SIGTERM, nullptr, nullptr), "watch for SIGTERM");
|
||||||
|
Checked(sd_event_add_post(event, &post, OnPost, this), "follow the event loop");
|
||||||
|
} catch(...) {
|
||||||
|
sd_event_unref(event);
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Loop::~Loop() {
|
||||||
|
sd_event_source_unref(post);
|
||||||
|
sd_event_unref(event);
|
||||||
|
}
|
||||||
|
|
||||||
|
sd_event* Loop::Event() const noexcept {
|
||||||
|
return event;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::int32_t Loop::Run() {
|
||||||
|
return Checked(sd_event_loop(event), "run the event loop");
|
||||||
|
}
|
||||||
|
|
||||||
|
void Loop::Exit(std::int32_t status) noexcept {
|
||||||
|
sd_event_exit(event, status);
|
||||||
|
}
|
||||||
|
|
||||||
|
void Loop::Guard(std::string_view what, const std::function<void()>& body) noexcept {
|
||||||
|
try {
|
||||||
|
body();
|
||||||
|
} catch(const std::exception& error) {
|
||||||
|
Failed(std::format("{} failed: {}", what, error.what()));
|
||||||
|
} catch(...) {
|
||||||
|
Failed(std::format("{} failed", what));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void Loop::Failed(std::string_view line) noexcept {
|
||||||
|
if(onError) {
|
||||||
|
onError(line);
|
||||||
|
} else {
|
||||||
|
std::println(std::cerr, "{}", line);
|
||||||
|
}
|
||||||
|
Exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::int32_t Loop::OnPost(sd_event_source*, void* data) {
|
||||||
|
Loop& self = *static_cast<Loop*>(data);
|
||||||
|
if(self.onSettle) {
|
||||||
|
self.Guard("settling after an event", self.onSettle);
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
Timer::Timer(Loop& loop, std::function<void()> fire) : loop(loop), fire(std::move(fire)) {
|
||||||
|
// Accurate to a millisecond: left to itself sd-event lets a timer slip by up to a quarter of a second, to wake less
|
||||||
|
// often, which a caret's blink and a held key's repeat would show.
|
||||||
|
Checked(sd_event_add_time(loop.Event(), &source, CLOCK_MONOTONIC, 0, 1000, OnTime, this), "make a timer");
|
||||||
|
sd_event_source_set_enabled(source, SD_EVENT_OFF);
|
||||||
|
}
|
||||||
|
|
||||||
|
Timer::~Timer() {
|
||||||
|
sd_event_source_disable_unref(source);
|
||||||
|
}
|
||||||
|
|
||||||
|
void Timer::At(std::int64_t ms) {
|
||||||
|
Checked(sd_event_source_set_time(source, static_cast<std::uint64_t>(std::max<std::int64_t>(ms, 0)) * 1000), "set a timer");
|
||||||
|
Checked(sd_event_source_set_enabled(source, SD_EVENT_ONESHOT), "set a timer");
|
||||||
|
armed = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Timer::After(std::int64_t ms) {
|
||||||
|
At(NowMs() + ms);
|
||||||
|
}
|
||||||
|
|
||||||
|
void Timer::Cancel() noexcept {
|
||||||
|
sd_event_source_set_enabled(source, SD_EVENT_OFF);
|
||||||
|
armed = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Timer::Armed() const noexcept {
|
||||||
|
return armed;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::int32_t Timer::OnTime(sd_event_source*, std::uint64_t, void* data) {
|
||||||
|
Timer& self = *static_cast<Timer*>(data);
|
||||||
|
// Before the callback, which may set the timer again.
|
||||||
|
self.armed = false;
|
||||||
|
self.loop.Guard("a timer", self.fire);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
Defer::Defer(Loop& loop, std::function<void()> run) : loop(loop), run(std::move(run)) {
|
||||||
|
Checked(sd_event_add_defer(loop.Event(), &source, OnDefer, this), "make a deferred call");
|
||||||
|
sd_event_source_set_enabled(source, SD_EVENT_OFF);
|
||||||
|
}
|
||||||
|
|
||||||
|
Defer::~Defer() {
|
||||||
|
sd_event_source_disable_unref(source);
|
||||||
|
}
|
||||||
|
|
||||||
|
void Defer::Schedule() noexcept {
|
||||||
|
sd_event_source_set_enabled(source, SD_EVENT_ONESHOT);
|
||||||
|
}
|
||||||
|
|
||||||
|
void Defer::Cancel() noexcept {
|
||||||
|
sd_event_source_set_enabled(source, SD_EVENT_OFF);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::int32_t Defer::OnDefer(sd_event_source*, void* data) {
|
||||||
|
Defer& self = *static_cast<Defer*>(data);
|
||||||
|
self.loop.Guard("a deferred call", self.run);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
WaylandSource::WaylandSource(Loop& loop, wl_display* display) : loop(loop), display(display) {
|
||||||
|
Checked(sd_event_add_io(loop.Event(), &source, wl_display_get_fd(display), EPOLLIN, OnReady, this), "watch the compositor's connection");
|
||||||
|
Checked(sd_event_source_set_prepare(source, OnPrepare), "watch the compositor's connection");
|
||||||
|
Checked(sd_event_add_defer(loop.Event(), &nudge, OnNudge, this), "watch the compositor's connection");
|
||||||
|
sd_event_source_set_enabled(nudge, SD_EVENT_OFF);
|
||||||
|
}
|
||||||
|
|
||||||
|
WaylandSource::~WaylandSource() {
|
||||||
|
sd_event_source_disable_unref(nudge);
|
||||||
|
sd_event_source_disable_unref(source);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::int32_t WaylandSource::OnPrepare(sd_event_source*, void* data) {
|
||||||
|
WaylandSource& self = *static_cast<WaylandSource*>(data);
|
||||||
|
self.loop.Guard("the compositor's events", [&self] {
|
||||||
|
if(self.lost) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// What a read by someone else on this thread left queued for it. Their listeners ran outside any source, so one
|
||||||
|
// is made to run: the loop then settles after them as after any other, and goes round once more before it
|
||||||
|
// waits, which every other source's own preparation needs after what the listeners may have asked of it.
|
||||||
|
const std::int32_t dispatched = wl_display_dispatch_pending(self.display);
|
||||||
|
if(dispatched < 0) {
|
||||||
|
self.Lost();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if(dispatched > 0) {
|
||||||
|
sd_event_source_set_enabled(self.nudge, SD_EVENT_ONESHOT);
|
||||||
|
}
|
||||||
|
self.Flush();
|
||||||
|
});
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::int32_t WaylandSource::OnNudge(sd_event_source*, void*) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::int32_t WaylandSource::OnReady(sd_event_source*, std::int32_t, std::uint32_t revents, void* data) {
|
||||||
|
WaylandSource& self = *static_cast<WaylandSource*>(data);
|
||||||
|
self.loop.Guard("the compositor's events", [&self, revents] {
|
||||||
|
// Room to write alone is the next preparation's to use.
|
||||||
|
if((revents & (EPOLLIN | EPOLLHUP | EPOLLERR)) != 0) {
|
||||||
|
self.Pump();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
void WaylandSource::Pump() {
|
||||||
|
if(lost) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Announce, read and dispatch, all here. The announcement is refused while events are queued, which are dispatched
|
||||||
|
// first; the read itself never waits, and fails once the connection is gone.
|
||||||
|
while(wl_display_prepare_read(display) != 0) {
|
||||||
|
if(wl_display_dispatch_pending(display) < 0) {
|
||||||
|
Lost();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if(wl_display_read_events(display) < 0 || wl_display_dispatch_pending(display) < 0) {
|
||||||
|
Lost();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void WaylandSource::Flush() {
|
||||||
|
// What does not fit in the socket goes when it has room again. A connection that broke is found by the next read.
|
||||||
|
const bool full = wl_display_flush(display) < 0 && errno == EAGAIN;
|
||||||
|
if(full != writing) {
|
||||||
|
writing = full;
|
||||||
|
Checked(sd_event_source_set_io_events(source, full ? EPOLLIN | EPOLLOUT : EPOLLIN), "watch the compositor's connection");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void WaylandSource::Lost() {
|
||||||
|
lost = true;
|
||||||
|
sd_event_source_set_enabled(source, SD_EVENT_OFF);
|
||||||
|
if(onLost) {
|
||||||
|
onLost();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
FrameDriver::FrameDriver(Loop& loop, wl_surface* surface) : loop(loop), surface(surface) {
|
||||||
|
}
|
||||||
|
|
||||||
|
FrameDriver::~FrameDriver() {
|
||||||
|
if(pending != nullptr) {
|
||||||
|
wl_callback_destroy(pending);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void FrameDriver::RequestRedraw() {
|
||||||
|
dirty = true;
|
||||||
|
if(pending != nullptr) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
pending = wl_surface_frame(surface);
|
||||||
|
wl_callback_add_listener(pending, &listener, this);
|
||||||
|
wl_surface_commit(surface);
|
||||||
|
}
|
||||||
|
|
||||||
|
void FrameDriver::SetAnimating(bool on) {
|
||||||
|
animating = on;
|
||||||
|
if(on) {
|
||||||
|
RequestRedraw();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool FrameDriver::Animating() const noexcept {
|
||||||
|
return animating;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool FrameDriver::Waiting() const noexcept {
|
||||||
|
return pending != nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
void FrameDriver::OnDone(void* data, wl_callback* callback, std::uint32_t) {
|
||||||
|
FrameDriver& self = *static_cast<FrameDriver*>(data);
|
||||||
|
wl_callback_destroy(callback);
|
||||||
|
self.pending = nullptr;
|
||||||
|
self.dirty = false;
|
||||||
|
if(self.onFrame) {
|
||||||
|
self.loop.Guard("a frame", self.onFrame);
|
||||||
|
}
|
||||||
|
// What the frame itself asked for, or what is still moving.
|
||||||
|
if(self.animating || self.dirty) {
|
||||||
|
self.RequestRedraw();
|
||||||
|
}
|
||||||
|
}
|
||||||
198
implementations/Nostro.Ui.Shell-Portal.cpp
Normal file
198
implementations/Nostro.Ui.Shell-Portal.cpp
Normal file
|
|
@ -0,0 +1,198 @@
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
module;
|
||||||
|
#include <systemd/sd-bus.h>
|
||||||
|
#include <systemd/sd-event.h>
|
||||||
|
module Nostro.Ui.Shell:Portal_impl;
|
||||||
|
import std;
|
||||||
|
import Nostro.Ui;
|
||||||
|
import :Portal;
|
||||||
|
import :Loop;
|
||||||
|
|
||||||
|
using namespace Nostro::Ui;
|
||||||
|
using namespace Nostro::Ui::Shell;
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
constexpr std::string_view portalName = "org.freedesktop.portal.Desktop";
|
||||||
|
constexpr std::string_view portalPath = "/org/freedesktop/portal/desktop";
|
||||||
|
constexpr std::string_view settingsInterface = "org.freedesktop.portal.Settings";
|
||||||
|
constexpr std::string_view openInterface = "org.freedesktop.portal.OpenURI";
|
||||||
|
constexpr std::string_view appearanceSettings = "org.freedesktop.appearance";
|
||||||
|
|
||||||
|
// The string a message has next; empty when it has none.
|
||||||
|
std::string ReadString(sd_bus_message* message) {
|
||||||
|
// sd-bus hands out a C string of the message's own.
|
||||||
|
// lint-disable-next-line no-char-pointer
|
||||||
|
const char* text = nullptr;
|
||||||
|
if(sd_bus_message_read_basic(message, 's', &text) < 0 || text == nullptr) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Portal::Portal(Loop& loop, std::chrono::milliseconds patience) : loop(loop) {
|
||||||
|
if(sd_bus_open_user(&bus) < 0) {
|
||||||
|
bus = nullptr;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// The subscription before the read, so that a change between the two is not missed.
|
||||||
|
sd_bus_match_signal(bus, &changed, portalName.data(), portalPath.data(), settingsInterface.data(), "SettingChanged", OnChanged, this);
|
||||||
|
// One call for all of it: ReadAll is in every version of the portal.
|
||||||
|
if(sd_bus_call_method_async(bus, &late, portalName.data(), portalPath.data(), settingsInterface.data(), "ReadAll", OnSettings, this, "as", 1, appearanceSettings.data()) >= 0) {
|
||||||
|
// The bus is served by hand until the answer is in or the patience is out; the loop is not running yet. A
|
||||||
|
// portal that is still starting, as at a login, answers later through the loop.
|
||||||
|
const std::int64_t deadline = NowMs() + patience.count();
|
||||||
|
while(!answered && NowMs() < deadline) {
|
||||||
|
const std::int32_t processed = sd_bus_process(bus, nullptr);
|
||||||
|
if(processed < 0 || (processed == 0 && sd_bus_wait(bus, static_cast<std::uint64_t>(deadline - NowMs()) * 1000) < 0)) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sd_bus_attach_event(bus, loop.Event(), SD_EVENT_PRIORITY_NORMAL);
|
||||||
|
}
|
||||||
|
|
||||||
|
Portal::~Portal() {
|
||||||
|
for(Opening& opening : openings) {
|
||||||
|
sd_bus_slot_unref(opening.slot);
|
||||||
|
}
|
||||||
|
sd_bus_slot_unref(late);
|
||||||
|
sd_bus_slot_unref(changed);
|
||||||
|
sd_bus_flush_close_unref(bus);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Portal::Connected() const noexcept {
|
||||||
|
return bus != nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
const Appearance& Portal::Current() const noexcept {
|
||||||
|
return current;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Portal::Told() {
|
||||||
|
if(onAppearance) {
|
||||||
|
onAppearance(current);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::int32_t Portal::OnSettings(sd_bus_message* reply, void* data, sd_bus_error*) {
|
||||||
|
Portal& self = *static_cast<Portal*>(data);
|
||||||
|
self.answered = true;
|
||||||
|
self.loop.Guard("reading the system's appearance", [&self, reply] {
|
||||||
|
if(!sd_bus_message_is_method_error(reply, nullptr) && self.TakeSettings(reply)) {
|
||||||
|
self.Told();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::int32_t Portal::OnChanged(sd_bus_message* signal, void* data, sd_bus_error*) {
|
||||||
|
Portal& self = *static_cast<Portal*>(data);
|
||||||
|
self.loop.Guard("a change of the system's appearance", [&self, signal] {
|
||||||
|
const std::string space = ReadString(signal);
|
||||||
|
const std::string key = ReadString(signal);
|
||||||
|
if(space == appearanceSettings && self.TakeSetting(key, signal)) {
|
||||||
|
self.Told();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReadAll's answer: every setting of every namespace asked for, a{sa{sv}}.
|
||||||
|
bool Portal::TakeSettings(sd_bus_message* reply) {
|
||||||
|
bool any = false;
|
||||||
|
if(sd_bus_message_enter_container(reply, 'a', "{sa{sv}}") <= 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
while(sd_bus_message_enter_container(reply, 'e', "sa{sv}") > 0) {
|
||||||
|
const std::string space = ReadString(reply);
|
||||||
|
if(sd_bus_message_enter_container(reply, 'a', "{sv}") > 0) {
|
||||||
|
while(sd_bus_message_enter_container(reply, 'e', "sv") > 0) {
|
||||||
|
const std::string key = ReadString(reply);
|
||||||
|
if(space == appearanceSettings) {
|
||||||
|
any = TakeSetting(key, reply) || any;
|
||||||
|
} else {
|
||||||
|
sd_bus_message_skip(reply, "v");
|
||||||
|
}
|
||||||
|
sd_bus_message_exit_container(reply);
|
||||||
|
}
|
||||||
|
sd_bus_message_exit_container(reply);
|
||||||
|
}
|
||||||
|
sd_bus_message_exit_container(reply);
|
||||||
|
}
|
||||||
|
sd_bus_message_exit_container(reply);
|
||||||
|
return any;
|
||||||
|
}
|
||||||
|
|
||||||
|
// One setting, with the message at its value: a variant, in which the portal's older Read wrapped the value once more.
|
||||||
|
bool Portal::TakeSetting(std::string_view key, sd_bus_message* value) {
|
||||||
|
const Appearance before = current;
|
||||||
|
std::int32_t depth = 0;
|
||||||
|
char type = 0;
|
||||||
|
// sd-bus hands out the signature as a C string of the message's own.
|
||||||
|
// lint-disable-next-line no-char-pointer
|
||||||
|
const char* contents = nullptr;
|
||||||
|
while(sd_bus_message_peek_type(value, &type, &contents) > 0 && type == 'v' && sd_bus_message_enter_container(value, 'v', contents) >= 0) {
|
||||||
|
depth++;
|
||||||
|
}
|
||||||
|
const std::string_view inside = contents != nullptr ? std::string_view(contents) : std::string_view();
|
||||||
|
if(key == "color-scheme" && type == 'u') {
|
||||||
|
// 1 prefers dark; 0 has no preference and 2 prefers light.
|
||||||
|
std::uint32_t scheme = 0;
|
||||||
|
if(sd_bus_message_read_basic(value, 'u', &scheme) >= 0) {
|
||||||
|
current.known = true;
|
||||||
|
current.dark = scheme == 1;
|
||||||
|
}
|
||||||
|
} else if(key == "accent-color" && type == 'r' && inside == "ddd") {
|
||||||
|
double red = 0;
|
||||||
|
double green = 0;
|
||||||
|
double blue = 0;
|
||||||
|
if(sd_bus_message_read(value, "(ddd)", &red, &green, &blue) >= 0) {
|
||||||
|
// Out of range is how the portal says there is none.
|
||||||
|
const auto valid = [](double part) { return part >= 0 && part <= 1; };
|
||||||
|
if(valid(red) && valid(green) && valid(blue)) {
|
||||||
|
current.accent = Color{static_cast<float>(red), static_cast<float>(green), static_cast<float>(blue)};
|
||||||
|
} else {
|
||||||
|
current.accent.reset();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Whatever it is, one value of it.
|
||||||
|
sd_bus_message_skip(value, nullptr);
|
||||||
|
}
|
||||||
|
for(; depth > 0; depth--) {
|
||||||
|
sd_bus_message_exit_container(value);
|
||||||
|
}
|
||||||
|
return !(current == before);
|
||||||
|
}
|
||||||
|
|
||||||
|
void Portal::OpenUri(std::string_view uri, std::function<void(bool)> then) {
|
||||||
|
Opening& opening = openings.emplace_back();
|
||||||
|
opening.portal = this;
|
||||||
|
opening.then = std::move(then);
|
||||||
|
const std::string address(uri);
|
||||||
|
// No parent window, and no options: the desktop asks the user which program where it needs to.
|
||||||
|
if(bus == nullptr || sd_bus_call_method_async(bus, &opening.slot, portalName.data(), portalPath.data(), openInterface.data(), "OpenURI", OnOpened, &opening, "ssa{sv}", "", address.c_str(), 0) < 0) {
|
||||||
|
const std::function<void(bool)> refused = std::move(opening.then);
|
||||||
|
openings.pop_back();
|
||||||
|
if(refused) {
|
||||||
|
refused(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::int32_t Portal::OnOpened(sd_bus_message* reply, void* data, sd_bus_error*) {
|
||||||
|
Opening& opening = *static_cast<Opening*>(data);
|
||||||
|
Portal& self = *opening.portal;
|
||||||
|
const bool taken = !sd_bus_message_is_method_error(reply, nullptr);
|
||||||
|
const std::function<void(bool)> then = std::move(opening.then);
|
||||||
|
// sd-bus holds the slot while this runs, so it may be let go of here.
|
||||||
|
sd_bus_slot_unref(opening.slot);
|
||||||
|
self.openings.remove_if([&opening](const Opening& other) { return &other == &opening; });
|
||||||
|
if(then) {
|
||||||
|
self.loop.Guard("opening an address", [&then, taken] { then(taken); });
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
489
implementations/Nostro.Ui.Shell-Window.cpp
Normal file
489
implementations/Nostro.Ui.Shell-Window.cpp
Normal file
|
|
@ -0,0 +1,489 @@
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
module;
|
||||||
|
#include <string.h>
|
||||||
|
#include <xkbcommon/xkbcommon.h>
|
||||||
|
module Nostro.Ui.Shell:Window_impl;
|
||||||
|
import std;
|
||||||
|
import Crafter.Graphics;
|
||||||
|
import Crafter.Event;
|
||||||
|
import Nostro.Ui;
|
||||||
|
import :Window;
|
||||||
|
import :Loop;
|
||||||
|
import :Canvas;
|
||||||
|
|
||||||
|
using namespace Nostro::Ui;
|
||||||
|
using namespace Nostro::Ui::Shell;
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
// The window library repeats a held key only while its own frames run; with frames drawn on demand a timer asks
|
||||||
|
// it to, this often while a key is down.
|
||||||
|
constexpr std::int64_t repeatMs = 30;
|
||||||
|
|
||||||
|
Key Letter(xkb_keysym_t symbol) noexcept {
|
||||||
|
switch(xkb_keysym_to_lower(symbol)) {
|
||||||
|
case XKB_KEY_a: return Key::A;
|
||||||
|
case XKB_KEY_c: return Key::C;
|
||||||
|
case XKB_KEY_f: return Key::F;
|
||||||
|
case XKB_KEY_r: return Key::R;
|
||||||
|
case XKB_KEY_v: return Key::V;
|
||||||
|
case XKB_KEY_x: return Key::X;
|
||||||
|
default: return Key::None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The key by what it types on the user's layout, so that Ctrl+A is the key marked A wherever that is.
|
||||||
|
Key Translate(Crafter::KeyCode code) noexcept {
|
||||||
|
xkb_state* const state = Crafter::Device::xkb_state;
|
||||||
|
if(state == nullptr) {
|
||||||
|
return Key::None;
|
||||||
|
}
|
||||||
|
// The window library's code is the kernel's; xkb's is that and 8.
|
||||||
|
const xkb_keycode_t keycode = code + 8;
|
||||||
|
const xkb_keysym_t symbol = xkb_state_key_get_one_sym(state, keycode);
|
||||||
|
switch(symbol) {
|
||||||
|
case XKB_KEY_Return:
|
||||||
|
case XKB_KEY_KP_Enter: return Key::Enter;
|
||||||
|
case XKB_KEY_Escape: return Key::Escape;
|
||||||
|
case XKB_KEY_Tab:
|
||||||
|
case XKB_KEY_ISO_Left_Tab: return Key::Tab;
|
||||||
|
case XKB_KEY_space: return Key::Space;
|
||||||
|
case XKB_KEY_BackSpace: return Key::Backspace;
|
||||||
|
case XKB_KEY_Delete:
|
||||||
|
case XKB_KEY_KP_Delete: return Key::Delete;
|
||||||
|
case XKB_KEY_Left:
|
||||||
|
case XKB_KEY_KP_Left: return Key::Left;
|
||||||
|
case XKB_KEY_Right:
|
||||||
|
case XKB_KEY_KP_Right: return Key::Right;
|
||||||
|
case XKB_KEY_Up:
|
||||||
|
case XKB_KEY_KP_Up: return Key::Up;
|
||||||
|
case XKB_KEY_Down:
|
||||||
|
case XKB_KEY_KP_Down: return Key::Down;
|
||||||
|
case XKB_KEY_Home:
|
||||||
|
case XKB_KEY_KP_Home: return Key::Home;
|
||||||
|
case XKB_KEY_End:
|
||||||
|
case XKB_KEY_KP_End: return Key::End;
|
||||||
|
case XKB_KEY_Page_Up:
|
||||||
|
case XKB_KEY_KP_Page_Up: return Key::PageUp;
|
||||||
|
case XKB_KEY_Page_Down:
|
||||||
|
case XKB_KEY_KP_Page_Down: return Key::PageDown;
|
||||||
|
case XKB_KEY_F5: return Key::F5;
|
||||||
|
default: break;
|
||||||
|
}
|
||||||
|
if(const Key letter = Letter(symbol); letter != Key::None) {
|
||||||
|
return letter;
|
||||||
|
}
|
||||||
|
// A layout without Latin letters (Greek, Cyrillic) has no key marked A: the shortcuts are then the keys of the
|
||||||
|
// first of the user's layouts that has them, as other toolkits have it.
|
||||||
|
xkb_keymap* const keymap = xkb_state_get_keymap(state);
|
||||||
|
for(xkb_layout_index_t layout = 0; layout < xkb_keymap_num_layouts_for_key(keymap, keycode); layout++) {
|
||||||
|
const xkb_keysym_t* symbols = nullptr;
|
||||||
|
if(xkb_keymap_key_get_syms_by_level(keymap, keycode, layout, 0, &symbols) == 1) {
|
||||||
|
if(const Key letter = Letter(symbols[0]); letter != Key::None) {
|
||||||
|
return letter;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Key::None;
|
||||||
|
}
|
||||||
|
|
||||||
|
Modifiers HeldModifiers() noexcept {
|
||||||
|
xkb_state* const state = Crafter::Device::xkb_state;
|
||||||
|
if(state == nullptr) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
.shift = xkb_state_mod_name_is_active(state, XKB_MOD_NAME_SHIFT, XKB_STATE_MODS_EFFECTIVE) > 0,
|
||||||
|
.control = xkb_state_mod_name_is_active(state, XKB_MOD_NAME_CTRL, XKB_STATE_MODS_EFFECTIVE) > 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// The text a key types as the keyboard stands, as the window library reports it: nothing for a key that types a
|
||||||
|
// control character.
|
||||||
|
std::string Typed(Crafter::KeyCode code) {
|
||||||
|
xkb_state* const state = Crafter::Device::xkb_state;
|
||||||
|
if(state == nullptr) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
std::array<char, 16> buffer{};
|
||||||
|
const std::int32_t length = xkb_state_key_get_utf8(state, code + 8, buffer.data(), buffer.size());
|
||||||
|
if(length <= 0 || static_cast<std::uint8_t>(buffer[0]) < 0x20 || buffer[0] == 0x7f) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
return std::string(buffer.data(), std::min<std::size_t>(static_cast<std::size_t>(length), buffer.size() - 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
constexpr Crafter::TextInputPurpose Purpose(TextPurpose purpose) noexcept {
|
||||||
|
switch(purpose) {
|
||||||
|
case TextPurpose::Digits: return Crafter::TextInputPurpose::Digits;
|
||||||
|
case TextPurpose::Number: return Crafter::TextInputPurpose::Number;
|
||||||
|
case TextPurpose::Phone: return Crafter::TextInputPurpose::Phone;
|
||||||
|
case TextPurpose::Url: return Crafter::TextInputPurpose::Url;
|
||||||
|
case TextPurpose::Email: return Crafter::TextInputPurpose::Email;
|
||||||
|
case TextPurpose::Name: return Crafter::TextInputPurpose::Name;
|
||||||
|
case TextPurpose::Password: return Crafter::TextInputPurpose::Password;
|
||||||
|
default: return Crafter::TextInputPurpose::Normal;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Window::Window(Loop& loop, Context& context, Fonts& fonts, const CanvasOptions& options)
|
||||||
|
: loop(loop), context(context), canvas(fonts, options), source(loop, Crafter::Device::display), frames(loop, canvas.Native().surface),
|
||||||
|
wake(loop, [this] {
|
||||||
|
// What the compositor has already sent comes first: a release waiting to be read happened before this time,
|
||||||
|
// and the press it ends is not a long one.
|
||||||
|
source.Pump();
|
||||||
|
Before(NowMs());
|
||||||
|
}),
|
||||||
|
repeat(loop, [this] {
|
||||||
|
if(canvas.Native().heldKeys.empty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Crafter::Device::TickKeyRepeats();
|
||||||
|
repeat.After(repeatMs);
|
||||||
|
}),
|
||||||
|
paste(loop, [this] { Paste(); }) {
|
||||||
|
Crafter::Window& window = canvas.Native();
|
||||||
|
source.onLost = [this] { Fail("the connection to the compositor is gone"); };
|
||||||
|
frames.onFrame = [this] { DrawFrame(); };
|
||||||
|
|
||||||
|
// The listeners run inside libwayland's dispatch, which nothing may be thrown through.
|
||||||
|
const auto listen = [this](Crafter::Event<void>& event, std::function<void()> body) {
|
||||||
|
plain.emplace_back(&event, [this, body = std::move(body)] { this->loop.Guard("an event of the window", body); });
|
||||||
|
};
|
||||||
|
listen(window.onMouseLeftClick, [this] { Press(PointerPhase::Down); });
|
||||||
|
touchDown.emplace(&window.onTouchDown, [this](Crafter::TouchPoint point) {
|
||||||
|
// Before the library makes it the pointer: the first finger.
|
||||||
|
if(canvas.Native().primaryTouchId < 0) {
|
||||||
|
touch = point.id;
|
||||||
|
touchLifted = false;
|
||||||
|
resting.reset();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
touchUp.emplace(&window.onTouchUp, [this](Crafter::TouchPoint point) {
|
||||||
|
if(touch && point.id == *touch) {
|
||||||
|
touchLifted = true;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
listen(window.onMouseLeftRelease, [this] {
|
||||||
|
const bool cancelled = touch && !touchLifted;
|
||||||
|
touch.reset();
|
||||||
|
Press(cancelled ? PointerPhase::Cancel : PointerPhase::Up);
|
||||||
|
// What the pointer is over once the release has acted, which may be another screen.
|
||||||
|
Before(NowMs());
|
||||||
|
this->context.Hover(resting);
|
||||||
|
});
|
||||||
|
listen(window.onTouchCancel, [this] {
|
||||||
|
touch.reset();
|
||||||
|
if(down) {
|
||||||
|
Press(PointerPhase::Cancel);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
listen(window.onMouseMove, [this] {
|
||||||
|
if(!touch) {
|
||||||
|
resting = Pointer();
|
||||||
|
}
|
||||||
|
if(down) {
|
||||||
|
Press(PointerPhase::Move);
|
||||||
|
} else {
|
||||||
|
Before(EventTime());
|
||||||
|
this->context.Hover(resting);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
listen(window.onMouseLeave, [this] {
|
||||||
|
resting.reset();
|
||||||
|
Before(NowMs());
|
||||||
|
this->context.Hover(std::nullopt);
|
||||||
|
});
|
||||||
|
listen(window.onMouseRightClick, [this] {
|
||||||
|
Before(EventTime());
|
||||||
|
this->context.Secondary(Pointer());
|
||||||
|
});
|
||||||
|
scroll.emplace(&window.onMouseScroll, [this](std::uint32_t detents) {
|
||||||
|
this->loop.Guard("the wheel", [this, detents] {
|
||||||
|
Before(EventTime());
|
||||||
|
// Whole detents, signed, in an unsigned payload.
|
||||||
|
this->context.Wheel(Pointer(), static_cast<float>(static_cast<std::int32_t>(detents)));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
keyDown.emplace(&window.onRawKeyDown, [this](Crafter::KeyCode code) {
|
||||||
|
this->loop.Guard("a key", [this, code] { OnKey(code); });
|
||||||
|
});
|
||||||
|
keyUp.emplace(&window.onRawKeyUp, [this](Crafter::KeyCode code) {
|
||||||
|
if(spent && spent->code == code) {
|
||||||
|
spent.reset();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
text.emplace(&window.onTextInput, [this](const std::string_view utf8) {
|
||||||
|
this->loop.Guard("typed text", [this, utf8] { OnText(utf8); });
|
||||||
|
});
|
||||||
|
preedit.emplace(&window.onPreedit, [this](const std::string_view utf8) {
|
||||||
|
this->loop.Guard("the input method", [this, utf8] {
|
||||||
|
Before(NowMs());
|
||||||
|
this->context.Preedit(utf8);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
textDelete.emplace(&window.onTextInputDelete, [this](Crafter::TextDelete range) {
|
||||||
|
this->loop.Guard("the input method", [this, range] {
|
||||||
|
Before(NowMs());
|
||||||
|
this->context.DeleteAround(range.beforeBytes, range.afterBytes);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
listen(window.onResize, [this] {
|
||||||
|
if(failed) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// The screens at the new size at once, so that the next event finds them where they are. The frame is built
|
||||||
|
// again and not thrown away: a resize is no change of screen, and a menu that is open stays open. An on-screen
|
||||||
|
// keyboard resizes the window as it comes, which is when a field's own menu is up.
|
||||||
|
Layout();
|
||||||
|
atlasWait.Reset();
|
||||||
|
frames.RequestRedraw();
|
||||||
|
});
|
||||||
|
listen(window.onClose, [this] {
|
||||||
|
if(onClose) {
|
||||||
|
onClose();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
Window::~Window() {
|
||||||
|
// The compositor's input method is told the field is gone, so that it carries no composition into whatever window
|
||||||
|
// comes next.
|
||||||
|
if(applied.active) {
|
||||||
|
canvas.Native().SetTextInput(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Canvas& Window::Surface() noexcept {
|
||||||
|
return canvas;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Window::Failed() const noexcept {
|
||||||
|
return failed;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Window::Log(std::string_view line) const {
|
||||||
|
if(onLog) {
|
||||||
|
onLog(line);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void Window::Layout() {
|
||||||
|
Frame& frame = context.Begin(canvas.Bounds(), canvas.Scale(), NowMs());
|
||||||
|
if(onBuild) {
|
||||||
|
onBuild(frame);
|
||||||
|
}
|
||||||
|
context.End();
|
||||||
|
// What is under the pointer now, unless it is pressing something: a press stays on what it went down on.
|
||||||
|
if(!down) {
|
||||||
|
context.Hover(resting);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void Window::Before(std::int64_t atMs) {
|
||||||
|
context.Tick(atMs);
|
||||||
|
if(!context.Built()) {
|
||||||
|
Layout();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void Window::Prepare() {
|
||||||
|
Before(NowMs());
|
||||||
|
}
|
||||||
|
|
||||||
|
// The time the event being handled happened at, on the host's clock: the compositor's own stamp of it, which an event
|
||||||
|
// that waited in the queue keeps. By the host's clock at dispatch a backlog of a swipe would be a burst, read as a
|
||||||
|
// fling at many times the finger's speed, and a tap that waited out a stall would be a long press.
|
||||||
|
std::int64_t Window::EventTime() {
|
||||||
|
return clock.At(canvas.Native().lastInputTime, NowMs());
|
||||||
|
}
|
||||||
|
|
||||||
|
Point Window::Pointer() const noexcept {
|
||||||
|
const Crafter::Window& window = canvas.Native();
|
||||||
|
return {window.currentMousePos.x, window.currentMousePos.y};
|
||||||
|
}
|
||||||
|
|
||||||
|
void Window::Press(PointerPhase phase) {
|
||||||
|
const std::int64_t at = EventTime();
|
||||||
|
Before(at);
|
||||||
|
if(phase == PointerPhase::Down) {
|
||||||
|
down = true;
|
||||||
|
} else if(phase != PointerPhase::Move) {
|
||||||
|
down = false;
|
||||||
|
}
|
||||||
|
context.Pointer(phase, Pointer(), at);
|
||||||
|
}
|
||||||
|
|
||||||
|
void Window::OnKey(Crafter::KeyCode code) {
|
||||||
|
const Crafter::KeyRepeatState& repeating = Crafter::Device::keyRepeat;
|
||||||
|
// The library sends a held key down again and again; only its first is a press.
|
||||||
|
const bool repeated = repeating.active && repeating.key == code;
|
||||||
|
if(!repeated && spent && spent->code == code) {
|
||||||
|
spent.reset();
|
||||||
|
}
|
||||||
|
if(!repeat.Armed()) {
|
||||||
|
repeat.After(repeatMs);
|
||||||
|
}
|
||||||
|
const Key key = Translate(code);
|
||||||
|
if(key == Key::None) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Before(NowMs());
|
||||||
|
const std::string focus(context.Focused());
|
||||||
|
context.KeyDown(key, HeldModifiers(), repeated);
|
||||||
|
if(!repeated && (!context.Built() || context.Focused() != focus)) {
|
||||||
|
// The press changed the screen or moved the focus: what the key types, now and held down, was meant for
|
||||||
|
// neither the new screen nor the field that has the focus now. Space on a button is the case.
|
||||||
|
if(std::string typed = Typed(code); !typed.empty()) {
|
||||||
|
spent = Spent{code, std::move(typed)};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void Window::OnText(std::string_view utf8) {
|
||||||
|
if(spent && utf8 == spent->text && canvas.Native().heldKeys.contains(spent->code)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Before(NowMs());
|
||||||
|
context.Text(utf8);
|
||||||
|
}
|
||||||
|
|
||||||
|
void Window::Start() {
|
||||||
|
Layout();
|
||||||
|
Apply(context.Take(), false);
|
||||||
|
canvas.Render(context.Shown().draw, context.theme.background);
|
||||||
|
AfterFrame();
|
||||||
|
// And one when the compositor first shows the window: its size and its scale may only be known by then.
|
||||||
|
frames.RequestRedraw();
|
||||||
|
}
|
||||||
|
|
||||||
|
void Window::Settle() {
|
||||||
|
if(failed) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// The size the compositor asked for, where the library left it; the resize builds the frame anew by itself.
|
||||||
|
canvas.Reconcile();
|
||||||
|
// A frame the events left stale is built now: the next event acts on the screens as they are.
|
||||||
|
if(!context.Built()) {
|
||||||
|
Layout();
|
||||||
|
}
|
||||||
|
Apply(context.Take(), true);
|
||||||
|
}
|
||||||
|
|
||||||
|
void Window::Apply(const Context::Wants& wants, bool redraw) {
|
||||||
|
if(wants.copy) {
|
||||||
|
// Refused before the pointer or a finger has been in the window: the compositor takes a selection only from
|
||||||
|
// whoever it has just sent input.
|
||||||
|
if(!Crafter::Clipboard::SetText(*wants.copy)) {
|
||||||
|
Log("the clipboard did not take the copy");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if(wants.paste) {
|
||||||
|
pasteInto = std::string(context.Focused());
|
||||||
|
paste.Schedule();
|
||||||
|
}
|
||||||
|
ApplyTextInput(wants.textInput);
|
||||||
|
if(redraw && wants.redraw) {
|
||||||
|
// What is drawn may have changed, so the wait for the atlas starts over.
|
||||||
|
atlasWait.Reset();
|
||||||
|
frames.RequestRedraw();
|
||||||
|
}
|
||||||
|
if(wants.animating != frames.Animating()) {
|
||||||
|
frames.SetAnimating(wants.animating);
|
||||||
|
}
|
||||||
|
if(wants.wakeAtMs) {
|
||||||
|
wake.At(*wants.wakeAtMs);
|
||||||
|
} else {
|
||||||
|
wake.Cancel();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void Window::ApplyTextInput(const TextInputRequest& want) {
|
||||||
|
if(want == applied) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Crafter::Window& window = canvas.Native();
|
||||||
|
// Another field, or none: the input method drops what it was composing and starts afresh, which turning the input
|
||||||
|
// off does whatever the next field is. The Context took the composed word into its field before it asked.
|
||||||
|
if(applied.active && (!want.active || want.field != applied.field)) {
|
||||||
|
window.SetTextInput(false);
|
||||||
|
}
|
||||||
|
if(want.active) {
|
||||||
|
window.SetTextInput(true, static_cast<std::int32_t>(want.caret.x), static_cast<std::int32_t>(want.caret.y), static_cast<std::int32_t>(want.caret.w), static_cast<std::int32_t>(want.caret.h), Purpose(want.purpose), want.hints);
|
||||||
|
}
|
||||||
|
applied = want;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Window::DrawFrame() {
|
||||||
|
if(failed) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
context.Tick(NowMs());
|
||||||
|
// Everything asked for so far but the frame, which this is.
|
||||||
|
Apply(context.Take(), false);
|
||||||
|
Layout();
|
||||||
|
try {
|
||||||
|
canvas.Render(context.Shown().draw, context.theme.background);
|
||||||
|
} catch(const std::exception& error) {
|
||||||
|
Fail(error.what());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
AfterFrame();
|
||||||
|
}
|
||||||
|
|
||||||
|
void Window::AfterFrame() {
|
||||||
|
const Canvas::Stats& stats = canvas.Last();
|
||||||
|
if(stats.overflowed && !overflowSaid) {
|
||||||
|
overflowSaid = true;
|
||||||
|
Log("a frame had more to draw than the window's buffers hold; part of it was left out");
|
||||||
|
}
|
||||||
|
// A glyph that found no cell in the font atlas drew blank and gets one when a later frame begins, and a frame
|
||||||
|
// comes only when asked for.
|
||||||
|
atlasWait.patience = Canvas::atlasPatience;
|
||||||
|
if(atlasWait.Again(stats.glyphsWaiting)) {
|
||||||
|
frames.RequestRedraw();
|
||||||
|
}
|
||||||
|
if(onFrame) {
|
||||||
|
onFrame();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void Window::Screenshot(const std::filesystem::path& png) {
|
||||||
|
context.Tick(NowMs());
|
||||||
|
Layout();
|
||||||
|
canvas.Capture(png);
|
||||||
|
canvas.Render(context.Shown().draw, context.theme.background);
|
||||||
|
AfterFrame();
|
||||||
|
}
|
||||||
|
|
||||||
|
// From the loop, never from inside a listener: the library waits for the clipboard's owner, for up to a second, and
|
||||||
|
// serves the compositor meanwhile, so its events run the listeners here from inside the read. Asked for from the loop
|
||||||
|
// that is all that happens; asked for from a listener they would run inside one another.
|
||||||
|
void Window::Paste() {
|
||||||
|
if(failed) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
std::optional<std::string> clipboard = Crafter::Clipboard::GetText();
|
||||||
|
if(!clipboard) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Not into another field than the one that asked, if the focus moved on while the clipboard was read.
|
||||||
|
if(!clipboard->empty() && context.Focused() == pasteInto) {
|
||||||
|
Before(NowMs());
|
||||||
|
context.Paste(*clipboard);
|
||||||
|
}
|
||||||
|
// It may have been a key for a bank.
|
||||||
|
explicit_bzero(clipboard->data(), clipboard->size());
|
||||||
|
}
|
||||||
|
|
||||||
|
void Window::Fail(std::string_view why) {
|
||||||
|
failed = true;
|
||||||
|
wake.Cancel();
|
||||||
|
repeat.Cancel();
|
||||||
|
frames.SetAnimating(false);
|
||||||
|
if(onFailed) {
|
||||||
|
onFailed(why);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -9,7 +9,7 @@ using namespace Nostro;
|
||||||
namespace {
|
namespace {
|
||||||
constexpr std::string_view usage = R"(usage:
|
constexpr std::string_view usage = R"(usage:
|
||||||
nostro connectors list connectors and whether they work
|
nostro connectors list connectors and whether they work
|
||||||
nostro connectors add bunq [allowed ips] [--sandbox] asks for the API key; ips default to *
|
nostro connectors add bunq [allowed ips] asks for the API key; ips default to *
|
||||||
nostro connectors add bunq-oauth <client id> <redirect uri> [--sandbox] asks for the client secret
|
nostro connectors add bunq-oauth <client id> <redirect uri> [--sandbox] asks for the client secret
|
||||||
nostro connectors remove <name or number> log out and forget a connector and its stored transactions
|
nostro connectors remove <name or number> log out and forget a connector and its stored transactions
|
||||||
nostro accounts
|
nostro accounts
|
||||||
|
|
@ -89,11 +89,6 @@ nostrod does the work, and asks for your password before anything that moves mon
|
||||||
return ParseNumber<std::int64_t>(text, "amount");
|
return ParseNumber<std::int64_t>(text, "amount");
|
||||||
}
|
}
|
||||||
|
|
||||||
// The end of the day for a date without a time, so "--to 2026-10-31" includes that day.
|
|
||||||
std::chrono::system_clock::time_point ParseEnd(std::string_view text) {
|
|
||||||
return text.size() == 10 ? ParseLocalDate(text, 1) - std::chrono::microseconds(1) : ParseLocalDate(text);
|
|
||||||
}
|
|
||||||
|
|
||||||
// The arguments a payment, a draft, a schedule and a request share, read in order so a missing one is named the
|
// The arguments a payment, a draft, a schedule and a request share, read in order so a missing one is named the
|
||||||
// same way every time.
|
// same way every time.
|
||||||
struct Payment {
|
struct Payment {
|
||||||
|
|
@ -120,10 +115,15 @@ nostrod does the work, and asks for your password before anything that moves mon
|
||||||
}
|
}
|
||||||
|
|
||||||
void AddBunq(Client& client, const Arguments& args) {
|
void AddBunq(Client& client, const Arguments& args) {
|
||||||
|
// An API key says itself which environment it is of, by how it starts: there is nothing to choose, and a
|
||||||
|
// real key is not to be sent to the sandbox by a flag. Said before the key is asked for.
|
||||||
|
if(args.sandbox) {
|
||||||
|
throw std::invalid_argument("--sandbox goes with bunq-oauth: an API key is a sandbox key when it starts with sandbox_");
|
||||||
|
}
|
||||||
// Read at a prompt, or from stdin, never from the command line: every local user can read a process's
|
// Read at a prompt, or from stdin, never from the command line: every local user can read a process's
|
||||||
// arguments, and polkit writes them to the journal.
|
// arguments, and polkit writes them to the journal.
|
||||||
const std::string key = ReadSecret("bunq API key: ");
|
const std::string key = ReadSecret("bunq API key: ");
|
||||||
const AddedConnector added = client.AddBunq(key, args.Or(3, "*"), args.sandbox ? "sandbox" : "");
|
const AddedConnector added = client.AddBunq(key, args.Or(3, "*"), "");
|
||||||
std::println("added {} ({}, {} accounts)", added.name, added.environment, added.accounts);
|
std::println("added {} ({}, {} accounts)", added.name, added.environment, added.accounts);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -142,19 +142,10 @@ nostrod does the work, and asks for your password before anything that moves mon
|
||||||
if(!std::getline(std::cin, redirected)) {
|
if(!std::getline(std::cin, redirected)) {
|
||||||
throw std::runtime_error("no address given");
|
throw std::runtime_error("no address given");
|
||||||
}
|
}
|
||||||
if(const std::optional<std::string> error = QueryParameter(redirected, "error")) {
|
const std::string code = BunqConnector::OAuthCodeFromRedirect(redirected, state);
|
||||||
throw std::runtime_error(std::format("bunq did not authorize: {} {}", *error, QueryParameter(redirected, "error_description").value_or("")));
|
|
||||||
}
|
|
||||||
const std::optional<std::string> code = QueryParameter(redirected, "code");
|
|
||||||
if(!code || code->empty()) {
|
|
||||||
throw std::runtime_error("that address has no code= in it");
|
|
||||||
}
|
|
||||||
if(QueryParameter(redirected, "state") != state) {
|
|
||||||
throw std::runtime_error("that address is not the answer to this authorization (its state differs): start again");
|
|
||||||
}
|
|
||||||
|
|
||||||
// nostrod exchanges the code for its token and keeps it; the token never comes here.
|
// nostrod exchanges the code for its token and keeps it; the token never comes here.
|
||||||
const AddedConnector added = client.AddBunqOAuth(args.sandbox ? "sandbox" : "production", clientId, clientSecret, redirectUri, *code);
|
const AddedConnector added = client.AddBunqOAuth(args.sandbox ? "sandbox" : "production", clientId, clientSecret, redirectUri, code);
|
||||||
std::println("added {} through OAuth ({}, {} accounts)", added.name, added.environment, added.accounts);
|
std::println("added {} through OAuth ({}, {} accounts)", added.name, added.environment, added.accounts);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -197,7 +188,7 @@ nostrod does the work, and asks for your password before anything that moves mon
|
||||||
query.from = ParseLocalDate(*from);
|
query.from = ParseLocalDate(*from);
|
||||||
}
|
}
|
||||||
if(const std::optional<std::string_view> to = args.Option("--to")) {
|
if(const std::optional<std::string_view> to = args.Option("--to")) {
|
||||||
query.to = ParseEnd(*to);
|
query.to = ParseLocalDateEnd(*to);
|
||||||
}
|
}
|
||||||
if(const std::optional<std::string_view> limit = args.Option("--limit")) {
|
if(const std::optional<std::string_view> limit = args.Option("--limit")) {
|
||||||
query.limit = ParseNumber<std::size_t>(*limit, "limit");
|
query.limit = ParseNumber<std::size_t>(*limit, "limit");
|
||||||
|
|
@ -255,13 +246,12 @@ nostrod does the work, and asks for your password before anything that moves mon
|
||||||
const Payment payment(args, "recipient", "recipient name", 7);
|
const Payment payment(args, "recipient", "recipient name", 7);
|
||||||
BunqSchedule schedule;
|
BunqSchedule schedule;
|
||||||
schedule.start = ParseLocalDate(args.At(5, "start date"));
|
schedule.start = ParseLocalDate(args.At(5, "start date"));
|
||||||
schedule.unit = std::string(args.At(6, "recurrence"));
|
schedule.unit = BunqSchedule::UnitFromWord(args.At(6, "recurrence"));
|
||||||
std::ranges::transform(schedule.unit, schedule.unit.begin(), [](char c) { return static_cast<char>(std::toupper(static_cast<std::uint8_t>(c))); });
|
|
||||||
if(const std::optional<std::string_view> every = args.Option("--every")) {
|
if(const std::optional<std::string_view> every = args.Option("--every")) {
|
||||||
schedule.every = ParseNumber<std::uint32_t>(*every, "--every");
|
schedule.every = ParseNumber<std::uint32_t>(*every, "--every");
|
||||||
}
|
}
|
||||||
if(const std::optional<std::string_view> until = args.Option("--until")) {
|
if(const std::optional<std::string_view> until = args.Option("--until")) {
|
||||||
schedule.end = ParseEnd(*until);
|
schedule.end = ParseLocalDateEnd(*until);
|
||||||
}
|
}
|
||||||
const Created scheduled = client.Schedule(payment.account, payment.counterparty, payment.name, payment.amount, payment.description, schedule);
|
const Created scheduled = client.Schedule(payment.account, payment.counterparty, payment.name, payment.amount, payment.description, schedule);
|
||||||
std::println("scheduled {} to {} (schedule {})", FormatMoney(payment.amount, scheduled.currency), payment.name, scheduled.id);
|
std::println("scheduled {} to {} (schedule {})", FormatMoney(payment.amount, scheduled.currency), payment.name, scheduled.id);
|
||||||
|
|
@ -317,9 +307,7 @@ nostrod does the work, and asks for your password before anything that moves mon
|
||||||
}
|
}
|
||||||
const std::uint64_t id = ParseNumber<std::uint64_t>(args.At(2, "card id"), "card id");
|
const std::uint64_t id = ParseNumber<std::uint64_t>(args.At(2, "card id"), "card id");
|
||||||
const BunqCard card = client.SetCardStatus(id, status->second);
|
const BunqCard card = client.SetCardStatus(id, status->second);
|
||||||
if(card.status != status->second) {
|
card.ExpectStatus(status->second);
|
||||||
throw std::runtime_error(std::format("bunq kept card {} {} (its order status is {}): a card can only be frozen or unfrozen once it has been activated", id, card.status, card.orderStatus));
|
|
||||||
}
|
|
||||||
std::println("card {} is now {}", id, card.status);
|
std::println("card {} is now {}", id, card.status);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
671
implementations/nostro-app.cpp
Normal file
671
implementations/nostro-app.cpp
Normal file
|
|
@ -0,0 +1,671 @@
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
// nostro-app: Nostro's window. This file reads the command line and puts the parts together: the event loop, the
|
||||||
|
// fonts, the toolkit's Context, the desktop portal, the app (Nostro.App) and the window that shows it.
|
||||||
|
// nostro-app [--size <width>x<height>] [--scale <scale>] [--theme light|dark] [--route <place>] [--verbose]
|
||||||
|
// [--screenshot <file.png>] [--screenshot-after <seconds>] [--poke <script>] [--quit-after <seconds>]
|
||||||
|
// [--gallery <widgets|list|text>]
|
||||||
|
// --size is in dp and holds where the compositor leaves the size to the app. --route starts on a place of the app:
|
||||||
|
// accounts, cards, settings, connections, checkout, about, account:<IBAN>, or a step of adding a connection: add,
|
||||||
|
// add:<bank> or add:<bank>:<way>, as in add:bunq:key. The rest is for looking at the window without a hand on it.
|
||||||
|
// --scale draws as on a display of that scale in a window of that size times it in pixels, whatever the display at
|
||||||
|
// hand: a phone's screen on a desktop. --poke plays input into the window as if the compositor had sent it (see
|
||||||
|
// Poker). --gallery shows every widget of the toolkit in place of the app, and asks nostrod nothing. The fonts and
|
||||||
|
// the window library's shaders sit beside the executable; NOSTRO_APP_ASSETS names another directory.
|
||||||
|
//
|
||||||
|
// Built with --debug-api (NOSTRO_DEBUG_API), the window can also be driven and read while it runs, through
|
||||||
|
// Crafter.Debug: Nostro.DebugCommands has what an agent can ask of it. No other build has any of that.
|
||||||
|
|
||||||
|
#include <sys/prctl.h>
|
||||||
|
|
||||||
|
// The version comes from the build as bare text, NOSTRO_VERSION=0.1.0, which this makes a string of.
|
||||||
|
#define NOSTRO_TEXT_OF(text) #text
|
||||||
|
#define NOSTRO_TEXT(text) NOSTRO_TEXT_OF(text)
|
||||||
|
|
||||||
|
import std;
|
||||||
|
import Crafter.Graphics;
|
||||||
|
import Nostro;
|
||||||
|
import Nostro.Ui;
|
||||||
|
import Nostro.Ui.Shell;
|
||||||
|
import Nostro.App;
|
||||||
|
#ifdef NOSTRO_DEBUG_API
|
||||||
|
import Nostro.DebugCommands;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
namespace fs = std::filesystem;
|
||||||
|
using namespace Nostro;
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
// An environment variable's value; nothing when it is not set or empty.
|
||||||
|
std::optional<std::string> Environment(std::string_view name) {
|
||||||
|
// getenv answers with a char*, null when the variable is not set.
|
||||||
|
// lint-disable-next-line no-char-pointer
|
||||||
|
const char* const value = std::getenv(std::string(name).c_str());
|
||||||
|
if(value == nullptr || *value == '\0') {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
return std::string(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
fs::path AssetDirectory() {
|
||||||
|
if(const std::optional<std::string> named = Environment("NOSTRO_APP_ASSETS")) {
|
||||||
|
return *named;
|
||||||
|
}
|
||||||
|
std::error_code failed;
|
||||||
|
const fs::path executable = fs::read_symlink("/proc/self/exe", failed);
|
||||||
|
return failed ? fs::current_path() : executable.parent_path();
|
||||||
|
}
|
||||||
|
|
||||||
|
fs::path CacheDirectory() {
|
||||||
|
if(const std::optional<std::string> cache = Environment("XDG_CACHE_HOME")) {
|
||||||
|
return fs::path(*cache) / "nostro-app";
|
||||||
|
}
|
||||||
|
return fs::path(Environment("HOME").value_or("/tmp")) / ".cache" / "nostro-app";
|
||||||
|
}
|
||||||
|
|
||||||
|
// Every widget of the toolkit on one screen, with something behind each: what shows a change to the toolkit on a
|
||||||
|
// real display, without a bank or nostrod behind it.
|
||||||
|
class Gallery {
|
||||||
|
public:
|
||||||
|
Gallery(Ui::Context& context, Ui::Shell::Portal& portal) : context(context), portal(portal) {
|
||||||
|
amount.Set("12,50");
|
||||||
|
}
|
||||||
|
|
||||||
|
void Build(Ui::Frame& frame) {
|
||||||
|
using namespace Ui;
|
||||||
|
const Theme& theme = frame.Colors();
|
||||||
|
Box area = frame.bounds;
|
||||||
|
const std::array<NavItem, 3> places = {{
|
||||||
|
{.key = "nav.widgets", .label = "Widgets", .selected = place == 0, .onTap = [this] { Go(0); }},
|
||||||
|
{.key = "nav.list", .label = "List", .detail = "40 rows", .selected = place == 1, .onTap = [this] { Go(1); }},
|
||||||
|
{.key = "nav.text", .label = "Text", .selected = place == 2, .onTap = [this] { Go(2); }},
|
||||||
|
}};
|
||||||
|
if(frame.sizeClass == SizeClass::Compact) {
|
||||||
|
area = NavBar(frame, area, places);
|
||||||
|
} else {
|
||||||
|
area = Sidebar(frame, area, frame.sizeClass == SizeClass::Expanded ? 260.0f : 200.0f, places);
|
||||||
|
}
|
||||||
|
area = TopBar(frame, area, {
|
||||||
|
.title = std::string(places[place].label),
|
||||||
|
.onBack = place == 0 ? std::function<void()>() : [this] { Go(0); },
|
||||||
|
.actions = {{.key = "bar.notice", .label = "Notice", .onTap = [this] { this->context.Notice(std::format("Notice number {}", ++notices)); }}},
|
||||||
|
});
|
||||||
|
|
||||||
|
frame.draw.SetLayer(Layer::Content);
|
||||||
|
const float gutter = frame.Dp(Size::gutter);
|
||||||
|
const float offset = frame.BeginScroll("content", area);
|
||||||
|
Column column(Centered(area, frame.Dp(Size::contentMax)).Inset(Insets::Symmetric(gutter, 0)), frame.Dp(Size::unit * 3));
|
||||||
|
column.cursor = area.y + gutter - offset;
|
||||||
|
if(place == 0) {
|
||||||
|
Widgets(frame, column);
|
||||||
|
} else if(place == 1) {
|
||||||
|
Rows(frame, column, area);
|
||||||
|
} else {
|
||||||
|
Texts(frame, column);
|
||||||
|
}
|
||||||
|
frame.EndScroll(column.Used() + gutter * 2);
|
||||||
|
|
||||||
|
if(sheet) {
|
||||||
|
Sheet(frame, {.key = "sheet", .title = "A sheet", .contentHeight = frame.Dp(160), .onDismiss = [this] { Close(); }}, [this, &frame, &theme](Box body) {
|
||||||
|
Column inside(body, frame.Dp(Size::unit * 3));
|
||||||
|
inside.Advance(Paragraph(frame, inside.Next(), "A sheet from the bottom edge in a narrow window, a dialog in the middle of a wider one. What it covers is dimmed and out of reach.", {FontFace::Regular, TextSize::body, theme.text}));
|
||||||
|
Button(frame, inside.Take(frame.Dp(Size::control)), {.key = "sheet.done", .label = "Done", .onTap = [this] { Close(); }});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// "widgets", "list" or "text"; false for any other name.
|
||||||
|
bool Route(std::string_view name) {
|
||||||
|
constexpr std::array<std::string_view, 3> names = {"widgets", "list", "text"};
|
||||||
|
const auto found = std::ranges::find(names, name);
|
||||||
|
if(found == names.end()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
Go(static_cast<std::size_t>(found - names.begin()));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
void Go(std::size_t to) {
|
||||||
|
place = to;
|
||||||
|
context.Invalidate();
|
||||||
|
}
|
||||||
|
|
||||||
|
void Close() {
|
||||||
|
sheet = false;
|
||||||
|
context.Invalidate();
|
||||||
|
}
|
||||||
|
|
||||||
|
void Widgets(Ui::Frame& frame, Ui::Column& column) {
|
||||||
|
using namespace Ui;
|
||||||
|
const Theme& theme = frame.Colors();
|
||||||
|
const float control = frame.Dp(Size::control);
|
||||||
|
if(banner) {
|
||||||
|
column.Advance(Banner(frame, column.Next(), {.key = "banner", .kind = BannerKind::Warning, .text = "A notice across the screen, with something to do about it and a way to send it off.", .action = "Do it", .onAction = [this] { this->context.Notice("Done"); }, .onDismiss = [this] {
|
||||||
|
banner = false;
|
||||||
|
this->context.Invalidate();
|
||||||
|
}}));
|
||||||
|
}
|
||||||
|
Label(frame, column.Take(frame.Dp(28)), "Fields", Heading(frame));
|
||||||
|
column.Advance(TextField(frame, column.Next(), name, {.key = "field.name", .label = "Name", .placeholder = "As on the account", .helper = "Prose: the keyboard completes and capitalises."}));
|
||||||
|
column.Advance(TextField(frame, column.Next(), amount, {.key = "field.amount", .label = "Amount", .prefix = "€", .error = amount.value == "0" ? "An amount above zero" : "", .helper = "Digits and one separator.", .purpose = TextPurpose::Number, .hints = TextHint::none}));
|
||||||
|
column.Advance(TextField(frame, column.Next(), secret, {.key = "field.secret", .label = "API key", .placeholder = "Shown as dots", .helper = "Never completed, learnt or copied."}));
|
||||||
|
|
||||||
|
Label(frame, column.Take(frame.Dp(28)), "Choices", Heading(frame));
|
||||||
|
Segmented(frame, column.Take(control), {.key = "when", .labels = {"Now", "Scheduled", "Draft"}, .selected = when, .onSelect = [this](std::size_t chosen) {
|
||||||
|
when = chosen;
|
||||||
|
this->context.Invalidate();
|
||||||
|
}});
|
||||||
|
Tabs(frame, column.Take(control), {.key = "tab", .labels = {"Activity", "Requests", "Incoming", "Scheduled", "Drafts"}, .selected = tab, .onSelect = [this](std::size_t chosen) {
|
||||||
|
tab = chosen;
|
||||||
|
this->context.Invalidate();
|
||||||
|
}});
|
||||||
|
|
||||||
|
Label(frame, column.Take(frame.Dp(28)), "Buttons", Heading(frame));
|
||||||
|
Button(frame, column.Take(control), {.key = "button.sheet", .label = "Open a sheet", .onTap = [this] {
|
||||||
|
sheet = true;
|
||||||
|
this->context.Invalidate();
|
||||||
|
}});
|
||||||
|
Button(frame, column.Take(control), {.key = "button.browser", .label = "Open catcrafts.net in the browser", .kind = ButtonKind::Tonal, .onTap = [this] {
|
||||||
|
portal.OpenUri("https://catcrafts.net/", [this](bool taken) { this->context.Notice(taken ? "Asked the desktop to open it" : "No desktop portal to open it with"); });
|
||||||
|
}});
|
||||||
|
Ui::Row pair(column.Take(control), frame.Dp(Size::unit * 3));
|
||||||
|
Button(frame, pair.TakeLeft((pair.area.w - pair.gap) / 2), {.key = "button.copy", .label = "Copy the amount", .kind = ButtonKind::Plain, .onTap = [this] {
|
||||||
|
this->context.Copy(amount.value);
|
||||||
|
this->context.Notice("Copied");
|
||||||
|
}});
|
||||||
|
Button(frame, pair.Rest(), {.key = "button.danger", .label = "Remove", .kind = ButtonKind::Danger, .enabled = banner, .onTap = [this] {
|
||||||
|
banner = false;
|
||||||
|
this->context.Invalidate();
|
||||||
|
}});
|
||||||
|
|
||||||
|
Label(frame, column.Take(frame.Dp(28)), "Marks", Heading(frame));
|
||||||
|
Ui::Row chips(column.Take(frame.Dp(24)), frame.Dp(Size::unit * 2));
|
||||||
|
Chip(frame, chips.TakeLeft(ChipWidth(frame, "Sandbox")), "Sandbox", theme.surfaceAlt, theme.muted);
|
||||||
|
Chip(frame, chips.TakeLeft(ChipWidth(frame, "Failing")), "Failing", theme.danger, theme.onDanger);
|
||||||
|
Chip(frame, chips.TakeLeft(ChipWidth(frame, "Paid")), "Paid", theme.positive, theme.onAccent);
|
||||||
|
Skeleton(frame, column.Take(frame.Dp(16)), 0.6f);
|
||||||
|
}
|
||||||
|
|
||||||
|
void Rows(Ui::Frame& frame, Ui::Column& column, Ui::Box viewport) {
|
||||||
|
using namespace Ui;
|
||||||
|
const Theme& theme = frame.Colors();
|
||||||
|
const float height = frame.Dp(Size::row);
|
||||||
|
for(std::uint32_t i = 0; i < 40; i++) {
|
||||||
|
const Box row = column.Take(height);
|
||||||
|
// Only what the window shows: a long list is drawn as far as it is looked at.
|
||||||
|
if(!row.Overlaps(viewport)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const bool in = i % 3 == 0;
|
||||||
|
ListRow(frame, row, {
|
||||||
|
.key = std::format("row.{}", i),
|
||||||
|
.title = std::format("Counterparty number {}", i + 1),
|
||||||
|
.subtitle = i % 4 == 0 ? "NL91 ABNA 0417 1643 00 · a description that is long enough to be cut where the row ends" : "NL91 ABNA 0417 1643 00",
|
||||||
|
.trailing = std::format("{}€{}.{:02}", in ? "+" : "-", (i + 1) * 13, (i * 37) % 100),
|
||||||
|
.trailingSub = std::format("{} Nov", 1 + i % 28),
|
||||||
|
.trailingColor = in ? std::optional<Color>(theme.positive) : std::nullopt,
|
||||||
|
.badge = i == 1 ? "Sandbox" : "",
|
||||||
|
.selected = i < 3 ? std::optional<bool>(i == chosen) : std::nullopt,
|
||||||
|
.chevron = i >= 3,
|
||||||
|
.onTap = [this, i] {
|
||||||
|
if(i < 3) {
|
||||||
|
chosen = i;
|
||||||
|
this->context.Invalidate();
|
||||||
|
} else {
|
||||||
|
this->context.Notice(std::format("Row {}", i + 1));
|
||||||
|
}
|
||||||
|
},
|
||||||
|
.onLongPress = [this, i] {
|
||||||
|
this->context.OpenMenu(this->context.Pointed(), {
|
||||||
|
{.label = "Pay again", .action = [this, i] { this->context.Notice(std::format("Pay row {} again", i + 1)); }},
|
||||||
|
{.label = "Copy the IBAN", .action = [this] { this->context.Copy("NL91ABNA0417164300"); }},
|
||||||
|
{.label = "Remove", .action = [this] { this->context.Notice("Removed"); }, .danger = true},
|
||||||
|
});
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void Texts(Ui::Frame& frame, Ui::Column& column) {
|
||||||
|
using namespace Ui;
|
||||||
|
const Theme& theme = frame.Colors();
|
||||||
|
Label(frame, column.Take(frame.Dp(44)), "€1,234.56", {FontFace::Medium, TextSize::display, theme.text});
|
||||||
|
Label(frame, column.Take(frame.Dp(32)), "A screen's title, 22", {FontFace::Medium, TextSize::title, theme.text});
|
||||||
|
Label(frame, column.Take(frame.Dp(28)), "A heading, 18", Heading(frame));
|
||||||
|
Label(frame, column.Take(frame.Dp(24)), "Body text, 16: the quick brown fox jumps over the lazy dog", Body(frame));
|
||||||
|
Label(frame, column.Take(frame.Dp(24)), "Strong text, 16: the quick brown fox jumps over the lazy dog", Strong(frame));
|
||||||
|
Label(frame, column.Take(frame.Dp(20)), "Muted text, 14: the quick brown fox jumps over the lazy dog", Muted(frame));
|
||||||
|
Label(frame, column.Take(frame.Dp(18)), "A caption, 12: the quick brown fox jumps over the lazy dog", Caption(frame));
|
||||||
|
column.Advance(Paragraph(frame, column.Next(), "Nostro is a banking client for Linux, phones first. It talks to your bank directly, keeps what it needs for that out of every other program's reach, and asks for your password before it moves money. Sending, scheduling and accepting a request are confirmed in your system's own password dialog; nothing in this window can confirm them for you.", Body(frame)));
|
||||||
|
column.Advance(Paragraph(frame, column.Next(), "Ça coûte 12,50 €. Größe, naïve, façade, Ελληνικά, кириллица: accents and other alphabets, with a hyphen-ated word and a verylongwordwithoutanybreakinitthatmustbesplitbetweenitslettersbecauseitiswiderthantheline.", Muted(frame)));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ui::Context& context;
|
||||||
|
Ui::Shell::Portal& portal;
|
||||||
|
std::size_t place = 0;
|
||||||
|
std::size_t when = 0;
|
||||||
|
std::size_t tab = 0;
|
||||||
|
std::uint32_t chosen = 0;
|
||||||
|
std::uint32_t notices = 0;
|
||||||
|
bool sheet = false;
|
||||||
|
bool banner = true;
|
||||||
|
Ui::EditState name{Ui::FieldKind::Text};
|
||||||
|
Ui::EditState amount{Ui::FieldKind::Decimal};
|
||||||
|
Ui::EditState secret{Ui::FieldKind::Secret};
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
// Plays a script of input into the window, at the place the window library hands the compositor's events on: the
|
||||||
|
// listeners run as they do for a hand on the mouse. Steps are separated by ';' and positions are in dp:
|
||||||
|
// tap:x,y hold:x,y,ms drag:x1,y1,x2,y2,ms move:x,y right:x,y wheel:x,y,detents
|
||||||
|
// press:x,y release (a finger put down and kept there, for a look at what a drag shows on its way)
|
||||||
|
// key:Name text:what is typed preedit:what is being composed delete:before,after
|
||||||
|
// resize:width,height wait:ms shot:file.png
|
||||||
|
class Poker {
|
||||||
|
public:
|
||||||
|
Poker(Ui::Shell::Loop& loop, Ui::Shell::Window& window, std::string_view script) : window(window), timer(loop, [this] { Next(); }) {
|
||||||
|
for(const auto part : std::views::split(script, ';')) {
|
||||||
|
const std::string_view step(part.begin(), part.end());
|
||||||
|
if(!step.empty()) {
|
||||||
|
Parse(step);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The script is played out.
|
||||||
|
std::function<void()> onDone;
|
||||||
|
|
||||||
|
void Start() {
|
||||||
|
timer.After(settleMs);
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
static constexpr std::int64_t settleMs = 200; // between steps: time for the frames a step asks for
|
||||||
|
|
||||||
|
struct Step {
|
||||||
|
std::int64_t thenMs = settleMs;
|
||||||
|
std::function<void()> act;
|
||||||
|
};
|
||||||
|
|
||||||
|
Crafter::Window& Native() {
|
||||||
|
return window.Surface().Native();
|
||||||
|
}
|
||||||
|
|
||||||
|
void Stamp() {
|
||||||
|
Native().lastInputTime = static_cast<std::uint32_t>(Ui::Shell::NowMs());
|
||||||
|
}
|
||||||
|
|
||||||
|
void Move(float x, float y) {
|
||||||
|
const float scale = window.Surface().Scale();
|
||||||
|
Native().currentMousePos.x = x * scale;
|
||||||
|
Native().currentMousePos.y = y * scale;
|
||||||
|
Stamp();
|
||||||
|
Native().onMouseMove.Invoke();
|
||||||
|
}
|
||||||
|
|
||||||
|
void Down() {
|
||||||
|
Stamp();
|
||||||
|
Native().mouseLeftHeld = true;
|
||||||
|
Native().onMouseLeftClick.Invoke();
|
||||||
|
}
|
||||||
|
|
||||||
|
void Up() {
|
||||||
|
Stamp();
|
||||||
|
Native().mouseLeftHeld = false;
|
||||||
|
Native().onMouseLeftRelease.Invoke();
|
||||||
|
}
|
||||||
|
|
||||||
|
static std::vector<float> Numbers(std::string_view text, std::size_t count) {
|
||||||
|
std::vector<float> numbers;
|
||||||
|
for(const auto part : std::views::split(text, ',')) {
|
||||||
|
float number = 0;
|
||||||
|
const std::string_view piece(part.begin(), part.end());
|
||||||
|
const std::from_chars_result result = std::from_chars(piece.data(), piece.data() + piece.size(), number);
|
||||||
|
if(result.ec != std::errc() || result.ptr != piece.data() + piece.size()) {
|
||||||
|
throw std::invalid_argument(std::format("'{}' is not a number", piece));
|
||||||
|
}
|
||||||
|
numbers.push_back(number);
|
||||||
|
}
|
||||||
|
if(numbers.size() != count) {
|
||||||
|
throw std::invalid_argument(std::format("'{}' is not {} numbers", text, count));
|
||||||
|
}
|
||||||
|
return numbers;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Parse(std::string_view step) {
|
||||||
|
const std::size_t colon = step.find(':');
|
||||||
|
const std::string_view verb = step.substr(0, colon);
|
||||||
|
const std::string rest(colon == std::string_view::npos ? std::string_view() : step.substr(colon + 1));
|
||||||
|
if(verb == "tap") {
|
||||||
|
const std::vector<float> at = Numbers(rest, 2);
|
||||||
|
steps.push_back({30, [this, at] { Move(at[0], at[1]); }});
|
||||||
|
steps.push_back({60, [this] { Down(); }});
|
||||||
|
steps.push_back({settleMs, [this] { Up(); }});
|
||||||
|
} else if(verb == "hold") {
|
||||||
|
const std::vector<float> at = Numbers(rest, 3);
|
||||||
|
steps.push_back({30, [this, at] { Move(at[0], at[1]); }});
|
||||||
|
steps.push_back({static_cast<std::int64_t>(at[2]), [this] { Down(); }});
|
||||||
|
steps.push_back({settleMs, [this] { Up(); }});
|
||||||
|
} else if(verb == "drag") {
|
||||||
|
const std::vector<float> at = Numbers(rest, 5);
|
||||||
|
constexpr std::int64_t every = 16;
|
||||||
|
const std::int64_t moves = std::max<std::int64_t>(1, static_cast<std::int64_t>(at[4]) / every);
|
||||||
|
steps.push_back({30, [this, at] { Move(at[0], at[1]); }});
|
||||||
|
steps.push_back({every, [this] { Down(); }});
|
||||||
|
for(std::int64_t i = 1; i <= moves; i++) {
|
||||||
|
const float part = static_cast<float>(i) / static_cast<float>(moves);
|
||||||
|
steps.push_back({every, [this, at, part] { Move(at[0] + (at[2] - at[0]) * part, at[1] + (at[3] - at[1]) * part); }});
|
||||||
|
}
|
||||||
|
// A release right behind the last move, as a finger that flicks: slower and the list has stopped.
|
||||||
|
steps.back().thenMs = 1;
|
||||||
|
steps.push_back({settleMs * 4, [this] { Up(); }});
|
||||||
|
} else if(verb == "move") {
|
||||||
|
const std::vector<float> at = Numbers(rest, 2);
|
||||||
|
steps.push_back({settleMs, [this, at] { Move(at[0], at[1]); }});
|
||||||
|
} else if(verb == "press") {
|
||||||
|
const std::vector<float> at = Numbers(rest, 2);
|
||||||
|
steps.push_back({30, [this, at] { Move(at[0], at[1]); }});
|
||||||
|
steps.push_back({settleMs, [this] { Down(); }});
|
||||||
|
} else if(verb == "release") {
|
||||||
|
steps.push_back({settleMs, [this] { Up(); }});
|
||||||
|
} else if(verb == "right") {
|
||||||
|
const std::vector<float> at = Numbers(rest, 2);
|
||||||
|
steps.push_back({30, [this, at] { Move(at[0], at[1]); }});
|
||||||
|
steps.push_back({settleMs, [this] {
|
||||||
|
Stamp();
|
||||||
|
Native().onMouseRightClick.Invoke();
|
||||||
|
}});
|
||||||
|
} else if(verb == "wheel") {
|
||||||
|
const std::vector<float> at = Numbers(rest, 3);
|
||||||
|
steps.push_back({30, [this, at] { Move(at[0], at[1]); }});
|
||||||
|
steps.push_back({settleMs, [this, at] {
|
||||||
|
Stamp();
|
||||||
|
Native().onMouseScroll.Invoke(static_cast<std::uint32_t>(static_cast<std::int32_t>(at[2])));
|
||||||
|
}});
|
||||||
|
} else if(verb == "key") {
|
||||||
|
using Crafter::CrafterKeys;
|
||||||
|
static const std::map<std::string_view, Crafter::KeyCode> keys = {
|
||||||
|
{"Tab", Crafter::Key(CrafterKeys::Tab)}, {"Enter", Crafter::Key(CrafterKeys::Enter)}, {"Escape", Crafter::Key(CrafterKeys::Escape)},
|
||||||
|
{"Space", Crafter::Key(CrafterKeys::Space)}, {"Backspace", Crafter::Key(CrafterKeys::Backspace)}, {"Delete", Crafter::Key(CrafterKeys::Delete)},
|
||||||
|
{"Left", Crafter::Key(CrafterKeys::Left)}, {"Right", Crafter::Key(CrafterKeys::Right)}, {"Up", Crafter::Key(CrafterKeys::Up)},
|
||||||
|
{"Down", Crafter::Key(CrafterKeys::Down)}, {"Home", Crafter::Key(CrafterKeys::Home)}, {"End", Crafter::Key(CrafterKeys::End)},
|
||||||
|
{"PageUp", Crafter::Key(CrafterKeys::PageUp)}, {"PageDown", Crafter::Key(CrafterKeys::PageDown)},
|
||||||
|
};
|
||||||
|
const auto found = keys.find(rest);
|
||||||
|
if(found == keys.end()) {
|
||||||
|
throw std::invalid_argument(std::format("unknown key '{}'", rest));
|
||||||
|
}
|
||||||
|
steps.push_back({settleMs, [this, code = found->second] {
|
||||||
|
Native().heldKeys.insert(code);
|
||||||
|
Native().onRawKeyDown.Invoke(code);
|
||||||
|
Native().heldKeys.erase(code);
|
||||||
|
Native().onRawKeyUp.Invoke(code);
|
||||||
|
}});
|
||||||
|
} else if(verb == "text") {
|
||||||
|
steps.push_back({settleMs, [this, rest] { Native().onTextInput.Invoke(rest); }});
|
||||||
|
} else if(verb == "preedit") {
|
||||||
|
steps.push_back({settleMs, [this, rest] { Native().onPreedit.Invoke(rest); }});
|
||||||
|
} else if(verb == "delete") {
|
||||||
|
const std::vector<float> bytes = Numbers(rest, 2);
|
||||||
|
steps.push_back({settleMs, [this, bytes] { Native().onTextInputDelete.Invoke({static_cast<std::uint32_t>(bytes[0]), static_cast<std::uint32_t>(bytes[1])}); }});
|
||||||
|
} else if(verb == "resize") {
|
||||||
|
const std::vector<float> size = Numbers(rest, 2);
|
||||||
|
steps.push_back({settleMs * 2, [this, size] { window.Surface().SetSize(static_cast<std::uint32_t>(size[0]), static_cast<std::uint32_t>(size[1])); }});
|
||||||
|
} else if(verb == "wait") {
|
||||||
|
steps.push_back({static_cast<std::int64_t>(Numbers(rest, 1)[0]), [] {}});
|
||||||
|
} else if(verb == "shot") {
|
||||||
|
steps.push_back({settleMs, [this, rest] {
|
||||||
|
window.Screenshot(rest);
|
||||||
|
std::println("nostro-app: screenshot written to {} ({}x{} px)", rest, Native().width, Native().height);
|
||||||
|
}});
|
||||||
|
} else {
|
||||||
|
throw std::invalid_argument(std::format("unknown step '{}' in --poke", step));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void Next() {
|
||||||
|
if(at >= steps.size()) {
|
||||||
|
if(onDone) {
|
||||||
|
onDone();
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const Step& step = steps[at];
|
||||||
|
at++;
|
||||||
|
step.act();
|
||||||
|
timer.After(step.thenMs);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ui::Shell::Window& window;
|
||||||
|
Ui::Shell::Timer timer;
|
||||||
|
std::vector<Step> steps;
|
||||||
|
std::size_t at = 0;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// main's signature is C's; past it the arguments are string views.
|
||||||
|
// lint-disable-next-line no-char-pointer
|
||||||
|
int main(int argc, char* argv[]) {
|
||||||
|
const std::vector<std::string_view> args(argv + 1, argv + argc);
|
||||||
|
try {
|
||||||
|
const auto value = [&args](std::size_t index) {
|
||||||
|
if(index >= args.size()) {
|
||||||
|
throw std::invalid_argument(std::format("{} needs a value", args[index - 1]));
|
||||||
|
}
|
||||||
|
return args[index];
|
||||||
|
};
|
||||||
|
const auto number = [](std::string_view text) {
|
||||||
|
float amount = 0;
|
||||||
|
const std::from_chars_result result = std::from_chars(text.data(), text.data() + text.size(), amount);
|
||||||
|
if(result.ec != std::errc() || result.ptr != text.data() + text.size() || amount <= 0) {
|
||||||
|
throw std::invalid_argument(std::format("'{}' is not a number above zero", text));
|
||||||
|
}
|
||||||
|
return amount;
|
||||||
|
};
|
||||||
|
|
||||||
|
Ui::Shell::CanvasOptions options;
|
||||||
|
options.title = "Nostro";
|
||||||
|
options.appId = "net.catcrafts.Nostro";
|
||||||
|
std::optional<bool> dark;
|
||||||
|
std::optional<fs::path> screenshot;
|
||||||
|
float screenshotAfter = 1;
|
||||||
|
std::optional<float> quitAfter;
|
||||||
|
std::string route;
|
||||||
|
std::string galleryPlace;
|
||||||
|
std::string poke;
|
||||||
|
bool verbose = false;
|
||||||
|
for(std::size_t i = 0; i < args.size(); i++) {
|
||||||
|
if(args[i] == "--size") {
|
||||||
|
const std::string_view size = value(++i);
|
||||||
|
const std::size_t by = size.find('x');
|
||||||
|
if(by == std::string_view::npos) {
|
||||||
|
throw std::invalid_argument(std::format("'{}' is not a size: <width>x<height>", size));
|
||||||
|
}
|
||||||
|
options.widthDp = static_cast<std::uint32_t>(number(size.substr(0, by)));
|
||||||
|
options.heightDp = static_cast<std::uint32_t>(number(size.substr(by + 1)));
|
||||||
|
} else if(args[i] == "--scale") {
|
||||||
|
options.scale = number(value(++i));
|
||||||
|
} else if(args[i] == "--theme") {
|
||||||
|
const std::string_view theme = value(++i);
|
||||||
|
if(theme != "light" && theme != "dark") {
|
||||||
|
throw std::invalid_argument(std::format("unknown theme '{}': light or dark", theme));
|
||||||
|
}
|
||||||
|
dark = theme == "dark";
|
||||||
|
} else if(args[i] == "--screenshot") {
|
||||||
|
screenshot = value(++i);
|
||||||
|
} else if(args[i] == "--screenshot-after") {
|
||||||
|
screenshotAfter = number(value(++i));
|
||||||
|
} else if(args[i] == "--quit-after") {
|
||||||
|
quitAfter = number(value(++i));
|
||||||
|
} else if(args[i] == "--route") {
|
||||||
|
route = value(++i);
|
||||||
|
} else if(args[i] == "--gallery") {
|
||||||
|
galleryPlace = value(++i);
|
||||||
|
} else if(args[i] == "--poke") {
|
||||||
|
poke = value(++i);
|
||||||
|
} else if(args[i] == "--verbose") {
|
||||||
|
verbose = true;
|
||||||
|
} else {
|
||||||
|
throw std::invalid_argument(std::format("unknown argument '{}'", args[i]));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
options.assets = AssetDirectory();
|
||||||
|
options.cache = CacheDirectory();
|
||||||
|
|
||||||
|
// First, before anything starts a thread: the loop blocks the signals it ends on.
|
||||||
|
Ui::Shell::Loop loop;
|
||||||
|
loop.onError = [](std::string_view line) { std::println(std::cerr, "nostro-app: {}", line); };
|
||||||
|
Ui::Shell::Fonts fonts(options.assets);
|
||||||
|
Ui::Context context(fonts.Measure());
|
||||||
|
|
||||||
|
// The system's look, or the one asked for; the accent is the system's either way.
|
||||||
|
Ui::Shell::Portal portal(loop);
|
||||||
|
const auto look = [&context, &dark](const Ui::Shell::Appearance& appearance) {
|
||||||
|
context.theme = dark.value_or(appearance.dark) ? Ui::Theme::Dark() : Ui::Theme::Light();
|
||||||
|
if(appearance.accent) {
|
||||||
|
context.theme.Accent(*appearance.accent);
|
||||||
|
}
|
||||||
|
context.Redraw();
|
||||||
|
};
|
||||||
|
look(portal.Current());
|
||||||
|
portal.onAppearance = look;
|
||||||
|
|
||||||
|
// From here on no other program of the user's can read this one's memory, where a key for a bank is while it is
|
||||||
|
// typed, and a crash leaves no dump of it. After the portal was first spoken to: it finds out which app is
|
||||||
|
// calling by looking at the caller's process, which this closes to it. Not in a build with --debug-api, which
|
||||||
|
// is there to be looked into, by a debugger too.
|
||||||
|
#ifndef NOSTRO_DEBUG_API
|
||||||
|
prctl(PR_SET_DUMPABLE, 0);
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// What the window shows: the app, or the toolkit's gallery.
|
||||||
|
std::optional<Gallery> gallery;
|
||||||
|
std::optional<App::App> app;
|
||||||
|
if(!galleryPlace.empty()) {
|
||||||
|
gallery.emplace(context, portal);
|
||||||
|
if(!gallery->Route(galleryPlace)) {
|
||||||
|
throw std::invalid_argument(std::format("unknown place '{}' in --gallery", galleryPlace));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
App::Host host;
|
||||||
|
host.connect = [&loop] {
|
||||||
|
Client client = Client::System();
|
||||||
|
client.Attach(loop.Event());
|
||||||
|
return client;
|
||||||
|
};
|
||||||
|
host.openUri = [&portal](std::string_view uri, std::function<void(bool)> then) { portal.OpenUri(uri, std::move(then)); };
|
||||||
|
host.version = NOSTRO_TEXT(NOSTRO_VERSION);
|
||||||
|
app.emplace(context, std::move(host));
|
||||||
|
}
|
||||||
|
|
||||||
|
std::int32_t status = 0;
|
||||||
|
{
|
||||||
|
std::optional<Ui::Shell::Window> window;
|
||||||
|
window.emplace(loop, context, fonts, options);
|
||||||
|
window->onBuild = [&gallery, &app](Ui::Frame& frame) {
|
||||||
|
if(app) {
|
||||||
|
app->Build(frame);
|
||||||
|
} else {
|
||||||
|
gallery->Build(frame);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
window->onFailed = [&loop](std::string_view why) {
|
||||||
|
std::println(std::cerr, "nostro-app: the window failed: {}", why);
|
||||||
|
loop.Exit(1);
|
||||||
|
};
|
||||||
|
window->onLog = [](std::string_view line) { std::println(std::cerr, "nostro-app: {}", line); };
|
||||||
|
loop.onSettle = [&window] {
|
||||||
|
if(window) {
|
||||||
|
window->Settle();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Closing the window ends the program, unless a change is under way: its answer says whether money moved,
|
||||||
|
// so the window goes and the program waits for the answer. The window is taken down from the loop, not
|
||||||
|
// from inside its own event.
|
||||||
|
bool closing = false;
|
||||||
|
Ui::Shell::Defer leave(loop, [&window] { window.reset(); });
|
||||||
|
window->onClose = [&loop, &app, &closing, &leave] {
|
||||||
|
if(app && app->Changing()) {
|
||||||
|
std::println(std::cerr, "nostro-app: the window is closed; waiting for the answer to what was asked");
|
||||||
|
closing = true;
|
||||||
|
leave.Schedule();
|
||||||
|
} else {
|
||||||
|
loop.Exit(0);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if(app) {
|
||||||
|
app->onSettled = [&loop, &closing] {
|
||||||
|
if(closing) {
|
||||||
|
loop.Exit(0);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
// A place that needs the accounts to be known, an account's own page, is gone to once they are.
|
||||||
|
app->onAnswer = [&app, &route, verbose](std::string_view member, bool failed) {
|
||||||
|
if(verbose) {
|
||||||
|
std::println(std::cerr, "nostro-app: {} {}", member, failed ? "failed" : "answered");
|
||||||
|
}
|
||||||
|
if(!route.empty() && app->Navigate(route)) {
|
||||||
|
route.clear();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
app->Start();
|
||||||
|
if(!route.empty() && app->Navigate(route)) {
|
||||||
|
route.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
window->Start();
|
||||||
|
|
||||||
|
#ifdef NOSTRO_DEBUG_API
|
||||||
|
// What an agent drives and reads the window with, from here until the loop ends.
|
||||||
|
Debugger debugger({.loop = loop, .context = context, .window = window, .app = app ? &*app : nullptr, .scratch = options.cache, .setTheme = [&dark, &look, &portal](std::string_view scheme) {
|
||||||
|
dark = scheme == "system" ? std::optional<bool>() : std::optional<bool>(scheme == "dark");
|
||||||
|
look(portal.Current());
|
||||||
|
}});
|
||||||
|
std::println(std::cerr, "nostro-app: built with --debug-api: every program of yours can drive this window and read what it shows");
|
||||||
|
#endif
|
||||||
|
|
||||||
|
Ui::Shell::Timer shoot(loop, [&window, &screenshot, &quitAfter, &loop] {
|
||||||
|
if(window) {
|
||||||
|
window->Screenshot(*screenshot);
|
||||||
|
std::println("nostro-app: screenshot written to {} ({}x{} px)", screenshot->string(), window->Surface().Native().width, window->Surface().Native().height);
|
||||||
|
}
|
||||||
|
if(!quitAfter) {
|
||||||
|
loop.Exit(0);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if(screenshot) {
|
||||||
|
shoot.After(static_cast<std::int64_t>(screenshotAfter * 1000));
|
||||||
|
}
|
||||||
|
Ui::Shell::Timer quit(loop, [&loop] { loop.Exit(0); });
|
||||||
|
if(quitAfter) {
|
||||||
|
quit.After(static_cast<std::int64_t>(*quitAfter * 1000));
|
||||||
|
}
|
||||||
|
Poker poker(loop, *window, poke);
|
||||||
|
poker.onDone = [&loop, &quitAfter] {
|
||||||
|
if(!quitAfter) {
|
||||||
|
loop.Exit(0);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if(!poke.empty()) {
|
||||||
|
poker.Start();
|
||||||
|
}
|
||||||
|
if(verbose) {
|
||||||
|
std::println(std::cerr, "nostro-app: {}x{} px at scale {}, drawn by {}", window->Surface().Native().width, window->Surface().Native().height, window->Surface().Scale(), window->Surface().Device());
|
||||||
|
}
|
||||||
|
status = loop.Run();
|
||||||
|
loop.onSettle = nullptr;
|
||||||
|
if(verbose && window) {
|
||||||
|
const Ui::Shell::Canvas::Stats& last = window->Surface().Last();
|
||||||
|
std::println(std::cerr, "nostro-app: {} frames drawn; the last one {} boxes and {} glyphs in {} passes", window->Surface().Frames(), last.boxes, last.glyphs, last.batches);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return status;
|
||||||
|
} catch(const std::exception& e) {
|
||||||
|
std::println(std::cerr, "nostro-app: {}", e.what());
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -15,6 +15,10 @@ namespace Nostro {
|
||||||
std::chrono::system_clock::time_point from = std::chrono::system_clock::time_point::min();
|
std::chrono::system_clock::time_point from = std::chrono::system_clock::time_point::min();
|
||||||
std::chrono::system_clock::time_point to = std::chrono::system_clock::time_point::max();
|
std::chrono::system_clock::time_point to = std::chrono::system_clock::time_point::max();
|
||||||
std::size_t limit = 100;
|
std::size_t limit = 100;
|
||||||
|
// For nostrod, which asks the bank for what is new before it answers: true has it answer from what it has stored
|
||||||
|
// alone, at once and without a call to the bank, as for a search in a list it has just given. FindTransactions
|
||||||
|
// only ever reads what is stored, and does not look at this.
|
||||||
|
bool stored = false;
|
||||||
};
|
};
|
||||||
|
|
||||||
export struct Account {
|
export struct Account {
|
||||||
|
|
|
||||||
|
|
@ -37,6 +37,10 @@ namespace Nostro {
|
||||||
|
|
||||||
// An error response from bunq, with its HTTP status (bunq also uses 466, 490 and 491) and error_description.
|
// An error response from bunq, with its HTTP status (bunq also uses 466, 490 and 491) and error_description.
|
||||||
export struct BunqError : std::runtime_error {
|
export struct BunqError : std::runtime_error {
|
||||||
|
// What ends the message of an error to a write that may have been carried out all the same: a 5xx, a lost
|
||||||
|
// connection or an unreadable answer. It travels with nostrod's errors, so its clients can tell.
|
||||||
|
static constexpr std::string_view maybeCarriedOut = "; the request may have been carried out, check before trying again";
|
||||||
|
|
||||||
std::uint16_t status;
|
std::uint16_t status;
|
||||||
BunqError(std::uint16_t status, const std::string& message);
|
BunqError(std::uint16_t status, const std::string& message);
|
||||||
};
|
};
|
||||||
|
|
@ -94,6 +98,8 @@ namespace Nostro {
|
||||||
|
|
||||||
// Throws std::invalid_argument for a unit bunq does not know or `every` of 0, as Schedule would.
|
// Throws std::invalid_argument for a unit bunq does not know or `every` of 0, as Schedule would.
|
||||||
void Check() const;
|
void Check() const;
|
||||||
|
// A unit as a person writes it, "monthly", as bunq names it: "MONTHLY". Check() decides whether bunq knows it.
|
||||||
|
static std::string UnitFromWord(std::string_view word);
|
||||||
};
|
};
|
||||||
|
|
||||||
// A payment bunq makes on a schedule (a bunq SchedulePayment).
|
// A payment bunq makes on a schedule (a bunq SchedulePayment).
|
||||||
|
|
@ -126,13 +132,28 @@ namespace Nostro {
|
||||||
std::uint64_t id;
|
std::uint64_t id;
|
||||||
std::string kind; // bunq's object: CardDebit, CardCredit, ...
|
std::string kind; // bunq's object: CardDebit, CardCredit, ...
|
||||||
std::string productType; // MASTERCARD_DEBIT, MAESTRO_DEBIT, ...
|
std::string productType; // MASTERCARD_DEBIT, MAESTRO_DEBIT, ...
|
||||||
std::string status; // ACTIVE, DEACTIVATED, LOST, STOLEN, CANCELLED, EXPIRED or PIN_TRIES_EXCEEDED
|
std::string status; // ACTIVE, DEACTIVATED, LOST, STOLEN, CANCELLED, EXPIRED or PIN_TRIES_EXCEEDED: of the plastic, see State()
|
||||||
std::string orderStatus;
|
std::string orderStatus; // how far bunq is with making and delivering it: VIRTUAL_DELIVERY, ACCEPTED_FOR_PRODUCTION, DELIVERED_TO_CUSTOMER, ...
|
||||||
std::string nameOnCard;
|
std::string nameOnCard;
|
||||||
std::string secondLine;
|
std::string secondLine;
|
||||||
std::string lastFour; // last four digits of the card number
|
std::string lastFour; // last four digits of the card number
|
||||||
std::string expiry; // YYYY-MM-DD
|
std::string expiry; // YYYY-MM-DD
|
||||||
std::string iban; // the account it pays from
|
std::string iban; // the account it pays from
|
||||||
|
|
||||||
|
// Whether the card is a virtual one: bunq delivered it as a number and went no further, so there is no plastic
|
||||||
|
// of it, or none yet.
|
||||||
|
bool Virtual() const noexcept;
|
||||||
|
// How the card stands, in one word: bunq's status, except that a virtual card that is not gone for good is
|
||||||
|
// VIRTUAL. bunq has such a card as DEACTIVATED however well it pays, and leaves it so when it is asked to
|
||||||
|
// freeze or to unfreeze it, without an error (a real card and the sandbox, 2026-11-19): DEACTIVATED is its
|
||||||
|
// word for plastic that was not activated, and it gives a virtual card no status that says whether it is
|
||||||
|
// frozen. Reporting one LOST or STOLEN does take.
|
||||||
|
std::string_view State() const noexcept;
|
||||||
|
// Throws std::runtime_error when bunq did not do what was asked: it kept another status than `wanted`, as it
|
||||||
|
// does for a card that was never activated, or the card is a virtual one asked to freeze or unfreeze, which
|
||||||
|
// bunq has as DEACTIVATED before and after. SetCardStatus answers with the card as bunq has it, which is not
|
||||||
|
// always what was asked.
|
||||||
|
void ExpectStatus(std::string_view wanted) const;
|
||||||
};
|
};
|
||||||
|
|
||||||
export struct BunqAccount : public Account {
|
export struct BunqAccount : public Account {
|
||||||
|
|
@ -238,6 +259,10 @@ namespace Nostro {
|
||||||
// OAuth: send the user to this URL, where they approve with the bunq app; bunq then redirects to
|
// OAuth: send the user to this URL, where they approve with the bunq app; bunq then redirects to
|
||||||
// `redirectUri` with `code` and `state` in the query. `redirectUri` must be registered with the OAuth client.
|
// `redirectUri` with `code` and `state` in the query. `redirectUri` must be registered with the OAuth client.
|
||||||
static std::string OAuthAuthorizationUrl(BunqEnvironment environment, std::string_view clientId, std::string_view redirectUri, std::string_view state);
|
static std::string OAuthAuthorizationUrl(BunqEnvironment environment, std::string_view clientId, std::string_view redirectUri, std::string_view state);
|
||||||
|
// The code in the address the browser was redirected to after that approval. Throws std::runtime_error when
|
||||||
|
// bunq did not authorize (error= in it), when it has no code, or when its state is not `state`: a code from
|
||||||
|
// anyone else's authorization is refused.
|
||||||
|
static std::string OAuthCodeFromRedirect(std::string_view redirected, std::string_view state);
|
||||||
// Exchanges the code from that redirect for an access token, which Create takes in place of an API key.
|
// Exchanges the code from that redirect for an access token, which Create takes in place of an API key.
|
||||||
static std::string OAuthExchangeCode(BunqEnvironment environment, std::string_view clientId, std::string_view clientSecret, std::string_view redirectUri, std::string_view code);
|
static std::string OAuthExchangeCode(BunqEnvironment environment, std::string_view clientId, std::string_view clientSecret, std::string_view redirectUri, std::string_view code);
|
||||||
|
|
||||||
|
|
@ -347,7 +372,7 @@ struct std::formatter<Nostro::BunqDraftPayment> : std::formatter<std::string> {
|
||||||
template<>
|
template<>
|
||||||
struct std::formatter<Nostro::BunqCard> : std::formatter<std::string> {
|
struct std::formatter<Nostro::BunqCard> : std::formatter<std::string> {
|
||||||
auto format(const Nostro::BunqCard& obj, std::format_context& ctx) const {
|
auto format(const Nostro::BunqCard& obj, std::format_context& ctx) const {
|
||||||
return std::formatter<std::string>::format(std::format("{}\t{}\t{}\t**** {}\t{}\t{}\t{}\texpires {}", obj.id, obj.status, obj.productType, obj.lastFour, obj.nameOnCard, obj.secondLine, obj.iban, obj.expiry), ctx);
|
return std::formatter<std::string>::format(std::format("{}\t{}\t{}\t**** {}\t{}\t{}\t{}\texpires {}", obj.id, obj.State(), obj.productType, obj.lastFour, obj.nameOnCard, obj.secondLine, obj.iban, obj.expiry), ctx);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,12 @@
|
||||||
// SPDX-License-Identifier: LGPL-3.0-only
|
// SPDX-License-Identifier: LGPL-3.0-only
|
||||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
module;
|
||||||
|
|
||||||
|
#ifdef NOSTRO_DBUS_ENABLED
|
||||||
|
#include <systemd/sd-bus.h>
|
||||||
|
#endif
|
||||||
|
|
||||||
export module Nostro:Client;
|
export module Nostro:Client;
|
||||||
#ifdef NOSTRO_DBUS_ENABLED
|
#ifdef NOSTRO_DBUS_ENABLED
|
||||||
|
|
||||||
|
|
@ -19,49 +25,143 @@ namespace Nostro {
|
||||||
DaemonError(std::string name, const std::string& message);
|
DaemonError(std::string name, const std::string& message);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// nostrod is not running, and the system bus cannot start it: not installed, or not set up.
|
||||||
|
export struct DaemonMissing : std::runtime_error {
|
||||||
|
using std::runtime_error::runtime_error;
|
||||||
|
};
|
||||||
|
|
||||||
|
// A call that changes something got no answer in time, or bunq answered it with an error that leaves open whether
|
||||||
|
// it was carried out (a 5xx, BunqError::maybeCarriedOut): what was asked may have happened. Check before asking again.
|
||||||
|
export struct OutcomeUnknown : std::runtime_error {
|
||||||
|
using std::runtime_error::runtime_error;
|
||||||
|
};
|
||||||
|
|
||||||
|
// What an asynchronous call answers: its result, or the exception the blocking call would have thrown, and the
|
||||||
|
// library's warnings that came with it. An error answer carries no notes.
|
||||||
|
export template<typename T>
|
||||||
|
struct Answer {
|
||||||
|
std::variant<T, std::exception_ptr> result;
|
||||||
|
std::vector<std::string> notes;
|
||||||
|
|
||||||
|
// The result, or the exception rethrown.
|
||||||
|
T& Get() {
|
||||||
|
if(const std::exception_ptr* error = std::get_if<std::exception_ptr>(&result)) {
|
||||||
|
std::rethrow_exception(*error);
|
||||||
|
}
|
||||||
|
return std::get<T>(result);
|
||||||
|
}
|
||||||
|
bool Failed() const {
|
||||||
|
return std::holds_alternative<std::exception_ptr>(result);
|
||||||
|
}
|
||||||
|
// The exception, or null when the call worked.
|
||||||
|
std::exception_ptr Error() const {
|
||||||
|
const std::exception_ptr* error = std::get_if<std::exception_ptr>(&result);
|
||||||
|
return error ? *error : nullptr;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
// nostrod over the system bus: each method of its interface (Bus::methods), with nostro's own types. `account` is
|
// nostrod over the system bus: each method of its interface (Bus::methods), with nostro's own types. `account` is
|
||||||
// an account's name or IBAN. A call may wait for a password dialog, which nostrod has polkit show, and for the
|
// an account's name or IBAN. A call may wait for a password dialog, which nostrod has polkit show, and for the
|
||||||
// bank. The library's warnings during the calls come out of TakeNotes().
|
// bank. The library's warnings during the calls come out of TakeNotes().
|
||||||
|
//
|
||||||
|
// Each method also has an asynchronous form, for a program with an event loop that must not wait: Attach() the
|
||||||
|
// client to an sd-event loop, and the method returns at once with a Pending, and calls `then` from that loop once
|
||||||
|
// nostrod answered, with an Answer. Notes are collected per user by nostrod's worker, so an answer's notes can be
|
||||||
|
// another call's of the same user, the CLI's included.
|
||||||
export class Client {
|
export class Client {
|
||||||
public:
|
public:
|
||||||
|
// An asynchronous call whose answer is awaited. Destroying it, or Cancel(), drops the answer: `then` is not
|
||||||
|
// called. It does not undo the call, which nostrod and the bank carry on with.
|
||||||
|
class Pending {
|
||||||
|
public:
|
||||||
|
Pending() = default;
|
||||||
|
Pending(Pending&& other) noexcept;
|
||||||
|
Pending& operator=(Pending&& other) noexcept;
|
||||||
|
Pending(const Pending&) = delete;
|
||||||
|
Pending& operator=(const Pending&) = delete;
|
||||||
|
~Pending();
|
||||||
|
|
||||||
|
void Cancel();
|
||||||
|
// Whether `then` is still to be called.
|
||||||
|
bool Active() const;
|
||||||
|
|
||||||
|
private:
|
||||||
|
friend class Client;
|
||||||
|
explicit Pending(sd_bus_slot* slot);
|
||||||
|
sd_bus_slot* slot = nullptr;
|
||||||
|
};
|
||||||
|
|
||||||
|
template<typename T>
|
||||||
|
using Then = std::function<void(Answer<T>)>;
|
||||||
|
|
||||||
// Connects to the system bus; D-Bus starts nostrod with the first call. A call waits up to `timeout` for its
|
// Connects to the system bus; D-Bus starts nostrod with the first call. A call waits up to `timeout` for its
|
||||||
// answer: long enough for the user to type a password, and for the bank's rate limits. Throws when there is
|
// answer: long enough for the user to type a password, and for the bank's rate limits. Throws when there is
|
||||||
// no system bus.
|
// no system bus.
|
||||||
static Client System(std::chrono::seconds timeout = std::chrono::minutes(10));
|
static Client System(std::chrono::seconds timeout = std::chrono::minutes(10));
|
||||||
|
|
||||||
|
// Hands the connection to `event`, whose loop then sends the asynchronous calls and delivers their answers.
|
||||||
|
// Throws when the client is attached already.
|
||||||
|
void Attach(sd_event* event);
|
||||||
|
// Whether the connection to the bus is still open; once it is not, make a new client.
|
||||||
|
bool Connected() const;
|
||||||
|
|
||||||
std::vector<ConnectorSummary> Connectors();
|
std::vector<ConnectorSummary> Connectors();
|
||||||
// `environment` is "production", "sandbox", or empty for the one the key's prefix says.
|
[[nodiscard]] Pending Connectors(Then<std::vector<ConnectorSummary>> then);
|
||||||
|
// The key says itself which environment it is of, by its prefix: leave `environment` empty. Naming one,
|
||||||
|
// "production" or "sandbox", only has a key of the other refused (std::invalid_argument), before anything is sent.
|
||||||
AddedConnector AddBunq(std::string_view apiKey, std::string_view allowedIps, std::string_view environment);
|
AddedConnector AddBunq(std::string_view apiKey, std::string_view allowedIps, std::string_view environment);
|
||||||
|
[[nodiscard]] Pending AddBunq(std::string_view apiKey, std::string_view allowedIps, std::string_view environment, Then<AddedConnector> then);
|
||||||
AddedConnector AddBunqOAuth(std::string_view environment, std::string_view clientId, std::string_view clientSecret, std::string_view redirectUri, std::string_view code);
|
AddedConnector AddBunqOAuth(std::string_view environment, std::string_view clientId, std::string_view clientSecret, std::string_view redirectUri, std::string_view code);
|
||||||
|
[[nodiscard]] Pending AddBunqOAuth(std::string_view environment, std::string_view clientId, std::string_view clientSecret, std::string_view redirectUri, std::string_view code, Then<AddedConnector> then);
|
||||||
// By name, or by its number in Connectors(); returns the name.
|
// By name, or by its number in Connectors(); returns the name.
|
||||||
std::string RemoveConnector(std::string_view connector);
|
std::string RemoveConnector(std::string_view connector);
|
||||||
|
[[nodiscard]] Pending RemoveConnector(std::string_view connector, Then<std::string> then);
|
||||||
std::vector<ConnectorAccounts> Accounts();
|
std::vector<ConnectorAccounts> Accounts();
|
||||||
// Fetches what is new first, then answers from the stored history.
|
[[nodiscard]] Pending Accounts(Then<std::vector<ConnectorAccounts>> then);
|
||||||
|
// Fetches what is new from the bank first, then answers from the stored history; with `query.stored` from the
|
||||||
|
// stored history alone, at once and without the bank.
|
||||||
std::vector<Transaction> Transactions(std::string_view account, const TransactionQuery& query);
|
std::vector<Transaction> Transactions(std::string_view account, const TransactionQuery& query);
|
||||||
|
[[nodiscard]] Pending Transactions(std::string_view account, const TransactionQuery& query, Then<std::vector<Transaction>> then);
|
||||||
|
|
||||||
Created Send(std::string_view account, std::string_view to, std::string_view name, std::int64_t amount, std::string_view description);
|
Created Send(std::string_view account, std::string_view to, std::string_view name, std::int64_t amount, std::string_view description);
|
||||||
|
[[nodiscard]] Pending Send(std::string_view account, std::string_view to, std::string_view name, std::int64_t amount, std::string_view description, Then<Created> then);
|
||||||
Created Schedule(std::string_view account, std::string_view to, std::string_view name, std::int64_t amount, std::string_view description, const BunqSchedule& schedule);
|
Created Schedule(std::string_view account, std::string_view to, std::string_view name, std::int64_t amount, std::string_view description, const BunqSchedule& schedule);
|
||||||
|
[[nodiscard]] Pending Schedule(std::string_view account, std::string_view to, std::string_view name, std::int64_t amount, std::string_view description, const BunqSchedule& schedule, Then<Created> then);
|
||||||
Created Draft(std::string_view account, std::string_view to, std::string_view name, std::int64_t amount, std::string_view description);
|
Created Draft(std::string_view account, std::string_view to, std::string_view name, std::int64_t amount, std::string_view description);
|
||||||
|
[[nodiscard]] Pending Draft(std::string_view account, std::string_view to, std::string_view name, std::int64_t amount, std::string_view description, Then<Created> then);
|
||||||
BunqPaymentRequest Request(std::string_view account, std::string_view from, std::string_view name, std::int64_t amount, std::string_view description);
|
BunqPaymentRequest Request(std::string_view account, std::string_view from, std::string_view name, std::int64_t amount, std::string_view description);
|
||||||
|
[[nodiscard]] Pending Request(std::string_view account, std::string_view from, std::string_view name, std::int64_t amount, std::string_view description, Then<BunqPaymentRequest> then);
|
||||||
|
|
||||||
std::vector<BunqPaymentRequest> Requests(std::string_view account);
|
std::vector<BunqPaymentRequest> Requests(std::string_view account);
|
||||||
|
[[nodiscard]] Pending Requests(std::string_view account, Then<std::vector<BunqPaymentRequest>> then);
|
||||||
void RevokeRequest(std::string_view account, std::uint64_t id);
|
void RevokeRequest(std::string_view account, std::uint64_t id);
|
||||||
|
[[nodiscard]] Pending RevokeRequest(std::string_view account, std::uint64_t id, Then<std::monostate> then);
|
||||||
std::vector<BunqIncomingRequest> IncomingRequests(std::string_view account);
|
std::vector<BunqIncomingRequest> IncomingRequests(std::string_view account);
|
||||||
|
[[nodiscard]] Pending IncomingRequests(std::string_view account, Then<std::vector<BunqIncomingRequest>> then);
|
||||||
void RespondToRequest(std::string_view account, std::uint64_t id, bool accept);
|
void RespondToRequest(std::string_view account, std::uint64_t id, bool accept);
|
||||||
|
[[nodiscard]] Pending RespondToRequest(std::string_view account, std::uint64_t id, bool accept, Then<std::monostate> then);
|
||||||
std::vector<BunqScheduledPayment> ScheduledPayments(std::string_view account);
|
std::vector<BunqScheduledPayment> ScheduledPayments(std::string_view account);
|
||||||
|
[[nodiscard]] Pending ScheduledPayments(std::string_view account, Then<std::vector<BunqScheduledPayment>> then);
|
||||||
void CancelScheduledPayment(std::string_view account, std::uint64_t id);
|
void CancelScheduledPayment(std::string_view account, std::uint64_t id);
|
||||||
|
[[nodiscard]] Pending CancelScheduledPayment(std::string_view account, std::uint64_t id, Then<std::monostate> then);
|
||||||
std::vector<BunqDraftPayment> DraftPayments(std::string_view account);
|
std::vector<BunqDraftPayment> DraftPayments(std::string_view account);
|
||||||
|
[[nodiscard]] Pending DraftPayments(std::string_view account, Then<std::vector<BunqDraftPayment>> then);
|
||||||
void RespondToDraftPayment(std::string_view account, std::uint64_t id, bool accept);
|
void RespondToDraftPayment(std::string_view account, std::uint64_t id, bool accept);
|
||||||
|
[[nodiscard]] Pending RespondToDraftPayment(std::string_view account, std::uint64_t id, bool accept, Then<std::monostate> then);
|
||||||
std::vector<ConnectorCards> Cards();
|
std::vector<ConnectorCards> Cards();
|
||||||
|
[[nodiscard]] Pending Cards(Then<std::vector<ConnectorCards>> then);
|
||||||
// "ACTIVE", "DEACTIVATED", "LOST" or "STOLEN"; returns the card as bunq has it afterwards.
|
// "ACTIVE", "DEACTIVATED", "LOST" or "STOLEN"; returns the card as bunq has it afterwards.
|
||||||
BunqCard SetCardStatus(std::uint64_t card, std::string_view status);
|
BunqCard SetCardStatus(std::uint64_t card, std::string_view status);
|
||||||
|
[[nodiscard]] Pending SetCardStatus(std::uint64_t card, std::string_view status, Then<BunqCard> then);
|
||||||
|
|
||||||
// The account apps' checkouts (Nostro.Checkout) pay from: none until one is chosen, or once it is gone.
|
// The account apps' checkouts (Nostro.Checkout) pay from: none until one is chosen, or once it is gone.
|
||||||
std::optional<Account> DefaultCheckoutAccount();
|
std::optional<Account> DefaultCheckoutAccount();
|
||||||
|
[[nodiscard]] Pending DefaultCheckoutAccount(Then<std::optional<Account>> then);
|
||||||
// Chooses it, and returns it. An account reached through OAuth cannot pay a shop, and is refused.
|
// Chooses it, and returns it. An account reached through OAuth cannot pay a shop, and is refused.
|
||||||
Account SetDefaultCheckoutAccount(std::string_view account);
|
Account SetDefaultCheckoutAccount(std::string_view account);
|
||||||
|
[[nodiscard]] Pending SetDefaultCheckoutAccount(std::string_view account, Then<Account> then);
|
||||||
|
|
||||||
// The library's warnings from the calls so far, taken out.
|
// The library's warnings from the blocking calls so far, taken out.
|
||||||
std::vector<std::string> TakeNotes();
|
std::vector<std::string> TakeNotes();
|
||||||
|
|
||||||
private:
|
private:
|
||||||
|
|
|
||||||
|
|
@ -102,6 +102,12 @@ export namespace Nostro {
|
||||||
return std::chrono::system_clock::from_time_t(std::mktime(&local));
|
return std::chrono::system_clock::from_time_t(std::mktime(&local));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The last moment a date ends a range at: for "YYYY-MM-DD" the end of that day, so a range up to 2026-10-31 includes
|
||||||
|
// that day; for "YYYY-MM-DD hh:mm" that minute.
|
||||||
|
inline std::chrono::system_clock::time_point ParseLocalDateEnd(std::string_view text) {
|
||||||
|
return text.size() == 10 ? ParseLocalDate(text, 1) - std::chrono::microseconds(1) : ParseLocalDate(text);
|
||||||
|
}
|
||||||
|
|
||||||
// "YYYY-MM-DD hh:mm" in the local time zone.
|
// "YYYY-MM-DD hh:mm" in the local time zone.
|
||||||
inline std::string FormatLocalTime(std::chrono::system_clock::time_point time) {
|
inline std::string FormatLocalTime(std::chrono::system_clock::time_point time) {
|
||||||
const std::time_t seconds = std::chrono::system_clock::to_time_t(time);
|
const std::time_t seconds = std::chrono::system_clock::to_time_t(time);
|
||||||
|
|
|
||||||
341
interfaces/Nostro.App-App.cppm
Normal file
341
interfaces/Nostro.App-App.cppm
Normal file
|
|
@ -0,0 +1,341 @@
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
export module Nostro.App:App;
|
||||||
|
|
||||||
|
import std;
|
||||||
|
import Nostro;
|
||||||
|
import Nostro.Ui;
|
||||||
|
import :Banks;
|
||||||
|
import :Format;
|
||||||
|
import :Forms;
|
||||||
|
import :Errors;
|
||||||
|
|
||||||
|
// Nostro's window without the window: what it knows of the user's banks, where the user is in it, what is being
|
||||||
|
// filled in and what is under way, and the screens built from that. It asks nostrod through the asynchronous Client
|
||||||
|
// and never waits for it: a call's answer changes the state and asks for a new frame. Nothing here draws or reads a
|
||||||
|
// device (that is Nostro.Ui.Shell's), so a test builds a frame, reads what it says and taps it by name.
|
||||||
|
//
|
||||||
|
// The rules that keep a bank's client honest are here. A press acts on what it went down on, and every action names
|
||||||
|
// what it is about by value: an IBAN or the bank's id, never a place in a list. One change at a time: while one is
|
||||||
|
// under way its sheet covers the screen, so nothing else can be asked for and nothing is sent twice. A payment from
|
||||||
|
// the form is sent by the form's own button, with no question of the app's before it: what confirms it is the system's
|
||||||
|
// password dialog, which nostrod words itself. What the app does ask about first (a request to send, a request or a
|
||||||
|
// draft to accept, a card to report) it shows built from the same values that are then sent. And an answer that leaves
|
||||||
|
// open whether money moved says so, and offers no button to try again.
|
||||||
|
//
|
||||||
|
// Which bank an account is with makes no difference to any of it. A bank's own is in two places: what :Banks says of
|
||||||
|
// it, and the forms a connection to it is made with, which are the last pages of adding a connection in the settings
|
||||||
|
// (Nostro.App-Bunq.cpp has bunq's). Everything else says "your bank", and asks :Banks what a connection can do.
|
||||||
|
|
||||||
|
export namespace Nostro::App {
|
||||||
|
// What the app needs of the program around it.
|
||||||
|
struct Host {
|
||||||
|
// A client for nostrod, attached to the program's event loop. Throws when there is no system bus.
|
||||||
|
std::function<Client()> connect;
|
||||||
|
// Asks the desktop to open an address in the user's browser; `then` hears whether it took the request.
|
||||||
|
std::function<void(std::string_view uri, std::function<void(bool taken)> then)> openUri;
|
||||||
|
// The time, for "today" and for what is in the past. The system's clock when left empty.
|
||||||
|
std::function<std::chrono::system_clock::time_point()> now;
|
||||||
|
// A new state for an OAuth request, which ties the browser's answer to it. Random when left empty.
|
||||||
|
std::function<std::string()> oauthState;
|
||||||
|
std::string version;
|
||||||
|
};
|
||||||
|
|
||||||
|
// How far the asking for something is.
|
||||||
|
enum class LoadState : std::uint8_t {
|
||||||
|
Idle, // not asked for yet
|
||||||
|
Loading,
|
||||||
|
Loaded,
|
||||||
|
Failed
|
||||||
|
};
|
||||||
|
|
||||||
|
// Something nostrod is asked for.
|
||||||
|
template<typename T>
|
||||||
|
struct Loadable {
|
||||||
|
LoadState state = LoadState::Idle;
|
||||||
|
T value{};
|
||||||
|
Guidance problem; // why it failed
|
||||||
|
bool refreshing = false; // loaded, and asked for again: the old value shows meanwhile
|
||||||
|
};
|
||||||
|
|
||||||
|
// A bank connection with its accounts: Connectors() and Accounts() joined.
|
||||||
|
struct Connection {
|
||||||
|
std::string name;
|
||||||
|
std::string bank; // as nostrod calls it; BankName() says it as the bank does
|
||||||
|
std::string environment; // "production" or "sandbox"
|
||||||
|
std::string auth; // the way it was made, as nostrod calls that; WayName() says it in words
|
||||||
|
bool working = false;
|
||||||
|
std::vector<Account> accounts;
|
||||||
|
// It pays between the user's own accounts and nobody else, by what :Banks knows of the way it was made.
|
||||||
|
bool ownAccountsOnly = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
// One account, found by its key.
|
||||||
|
struct AccountRef {
|
||||||
|
const Connection* connection = nullptr;
|
||||||
|
const Account* account = nullptr;
|
||||||
|
std::string key; // names it in the app: its IBAN, or its name where the bank gave none
|
||||||
|
};
|
||||||
|
|
||||||
|
class App {
|
||||||
|
public:
|
||||||
|
App(Ui::Context& context, Host host);
|
||||||
|
App(const App&) = delete;
|
||||||
|
App& operator=(const App&) = delete;
|
||||||
|
|
||||||
|
// Asks nostrod for the connections and accounts; the first frame shows them loading.
|
||||||
|
void Start();
|
||||||
|
// Builds the screen the user is on.
|
||||||
|
void Build(Ui::Frame& frame);
|
||||||
|
|
||||||
|
// Whether nostrod is still being waited for: for whoever runs the loop until the app has settled.
|
||||||
|
bool Busy() const noexcept;
|
||||||
|
// Whether a change is under way. The window may close then, and the process must not: the answer says whether
|
||||||
|
// money moved. onSettled is called when it has come.
|
||||||
|
bool Changing() const noexcept;
|
||||||
|
std::function<void()> onSettled;
|
||||||
|
// An answer came, to the method of that name, and whether it was an error: for a log or a debugger. Called once
|
||||||
|
// the app has taken the answer in, so what it shows is what the answer led to.
|
||||||
|
std::function<void(std::string_view member, bool failed)> onAnswer;
|
||||||
|
|
||||||
|
// Goes to a place by name: "accounts", "cards", "settings", "connections", "checkout", "about", "account:<IBAN>",
|
||||||
|
// or one of the steps of adding a connection: "add" for the banks, "add:<bank>" for a bank's ways and
|
||||||
|
// "add:<bank>:<way>" for a way's form, as in "add:bunq:key". False for a name that is none of them, and while
|
||||||
|
// a change is under way, which the screen waits out.
|
||||||
|
bool Navigate(std::string_view route);
|
||||||
|
// Where the user is, as a name of the same kind, with what is open over it after a '+': "account:NL…+filter".
|
||||||
|
std::string Screen() const;
|
||||||
|
// The connections and accounts as they are known.
|
||||||
|
const Loadable<std::vector<Connection>>& Overview() const noexcept;
|
||||||
|
// The state of the OAuth request that is being made, for a test that plays the browser.
|
||||||
|
std::string_view OAuthState() const noexcept;
|
||||||
|
|
||||||
|
private:
|
||||||
|
// -- where the user is ---------------------------------------------------------------------------------------
|
||||||
|
enum class Place : std::uint8_t {
|
||||||
|
Accounts,
|
||||||
|
Cards,
|
||||||
|
Settings
|
||||||
|
};
|
||||||
|
enum class Page : std::uint8_t {
|
||||||
|
Account,
|
||||||
|
Pay,
|
||||||
|
Request,
|
||||||
|
Connections,
|
||||||
|
Banks, // adding a connection: the banks to choose from
|
||||||
|
Ways, // the ways to connect to the bank that was chosen
|
||||||
|
Connect, // the form of the way that was chosen
|
||||||
|
Checkout,
|
||||||
|
About
|
||||||
|
};
|
||||||
|
struct Route {
|
||||||
|
Page page = Page::Account;
|
||||||
|
std::string account; // the key of the account it is about
|
||||||
|
const Bank* bank = nullptr; // of Ways and Connect
|
||||||
|
const Way* way = nullptr; // of Connect
|
||||||
|
};
|
||||||
|
enum class Tab : std::uint8_t {
|
||||||
|
Activity,
|
||||||
|
Requests,
|
||||||
|
Incoming,
|
||||||
|
Scheduled,
|
||||||
|
Drafts
|
||||||
|
};
|
||||||
|
|
||||||
|
// -- what is known -------------------------------------------------------------------------------------------
|
||||||
|
// One account's lists, each asked for when its tab is first shown.
|
||||||
|
struct AccountData {
|
||||||
|
Tab tab = Tab::Activity;
|
||||||
|
FilterForm filter;
|
||||||
|
TransactionQuery query; // the filter as it was last asked for
|
||||||
|
Loadable<std::vector<Transaction>> activity;
|
||||||
|
bool more = false; // the list is as long as was asked for: there may be more
|
||||||
|
Loadable<std::vector<BunqPaymentRequest>> requests;
|
||||||
|
Loadable<std::vector<BunqIncomingRequest>> incoming;
|
||||||
|
Loadable<std::vector<BunqScheduledPayment>> scheduled;
|
||||||
|
Loadable<std::vector<BunqDraftPayment>> drafts;
|
||||||
|
};
|
||||||
|
|
||||||
|
// One kind of call at a time, and at most one waiting behind it: the newest. nostrod's worker makes its calls
|
||||||
|
// to the bank one after another, and an answer dropped here does not stop it, so a queue of searches the user
|
||||||
|
// has already typed past would only use up the bank's patience.
|
||||||
|
struct Lane {
|
||||||
|
Client::Pending pending;
|
||||||
|
bool busy = false;
|
||||||
|
std::function<void()> next;
|
||||||
|
};
|
||||||
|
|
||||||
|
// -- what is open over the screen ----------------------------------------------------------------------------
|
||||||
|
struct Line {
|
||||||
|
std::string label;
|
||||||
|
std::string value;
|
||||||
|
// What a press on the line puts on the clipboard, where that is not the value as it is shown: an IBAN
|
||||||
|
// without the spaces it is read with.
|
||||||
|
std::string copied;
|
||||||
|
};
|
||||||
|
struct Choice {
|
||||||
|
std::string key;
|
||||||
|
std::string label;
|
||||||
|
Ui::ButtonKind kind = Ui::ButtonKind::Tonal;
|
||||||
|
bool enabled = true;
|
||||||
|
std::string reason; // why it cannot be chosen
|
||||||
|
std::function<void()> onTap;
|
||||||
|
};
|
||||||
|
// What is asked or told over the screen: a thing to look at with what can be done about it, a question before
|
||||||
|
// a change, the wait for its answer, and how it went.
|
||||||
|
struct Dialog {
|
||||||
|
enum class Kind : std::uint8_t {
|
||||||
|
Detail, // a row's own sheet
|
||||||
|
Ask, // before a change: what will be done, to confirm
|
||||||
|
Working, // the change is under way
|
||||||
|
Done, // it worked
|
||||||
|
Problem // it did not, or may not have
|
||||||
|
};
|
||||||
|
Kind kind = Kind::Detail;
|
||||||
|
std::string name; // for Screen(): "transaction", "confirm", "working"
|
||||||
|
std::string title;
|
||||||
|
std::vector<std::string> text;
|
||||||
|
std::vector<Line> lines;
|
||||||
|
std::vector<Choice> choices;
|
||||||
|
std::string link; // an address to copy or open
|
||||||
|
std::function<void()> onClose; // after it is sent away
|
||||||
|
};
|
||||||
|
enum class Picking : std::uint8_t {
|
||||||
|
None,
|
||||||
|
PayFrom,
|
||||||
|
RequestInto
|
||||||
|
};
|
||||||
|
|
||||||
|
// -- nostrod -------------------------------------------------------------------------------------------------
|
||||||
|
Client& Nostrod();
|
||||||
|
void Reconnect();
|
||||||
|
void Note(const std::vector<std::string>& notes);
|
||||||
|
void Answered(std::string_view member, bool failed);
|
||||||
|
// A reading: `start` makes the call, given what to do with its answer, in the lane of that name.
|
||||||
|
template<typename T>
|
||||||
|
void Fetch(std::string lane, std::string member, std::function<Client::Pending(Client&, Client::Then<T>)> start, std::function<void(Answer<T>)> then);
|
||||||
|
// A change: shows the wait, makes the call, and shows how it went. `done` says what to tell the user; what it
|
||||||
|
// throws is told as the change having failed. `account` is the account it is about, if any.
|
||||||
|
template<typename T>
|
||||||
|
void Change(Operation operation, std::string member, std::string title, std::string account, std::function<Client::Pending(Client&, Client::Then<T>)> start, std::function<void(T&)> done);
|
||||||
|
void Failed(const Guidance& guidance, Operation operation, const std::string& account);
|
||||||
|
void Wait(Operation operation, std::string title);
|
||||||
|
|
||||||
|
void Refresh(bool again = false);
|
||||||
|
void LoadAccounts(std::vector<ConnectorSummary> summaries, bool again);
|
||||||
|
void OverviewFailed(const Guidance& guidance);
|
||||||
|
void ListFailed(const Guidance& guidance);
|
||||||
|
void LoadActivity(const std::string& key, bool stored = false);
|
||||||
|
template<typename T>
|
||||||
|
void LoadList(const std::string& key, std::string_view member, Loadable<std::vector<T>> AccountData::* list, Client::Pending (Client::* call)(std::string_view, Client::Then<std::vector<T>>));
|
||||||
|
void LoadTab(const std::string& key, Tab tab, bool again = false);
|
||||||
|
void LoadCards(bool again = false);
|
||||||
|
void LoadCheckout();
|
||||||
|
void Changed(const std::string& key);
|
||||||
|
|
||||||
|
// -- going places --------------------------------------------------------------------------------------------
|
||||||
|
void Go(Place to);
|
||||||
|
void Push(Page page, std::string account = {}, const Bank* bank = nullptr, const Way* way = nullptr);
|
||||||
|
void Back();
|
||||||
|
void Show(Dialog shown);
|
||||||
|
void Close();
|
||||||
|
void Tell(std::string_view notice);
|
||||||
|
std::chrono::system_clock::time_point Today() const;
|
||||||
|
std::optional<AccountRef> Find(std::string_view key) const;
|
||||||
|
std::vector<AccountRef> Accounts() const;
|
||||||
|
AccountData& Data(const std::string& key);
|
||||||
|
bool Own(std::string_view iban) const;
|
||||||
|
|
||||||
|
// -- what the user asks for ----------------------------------------------------------------------------------
|
||||||
|
void OpenPay(std::string account);
|
||||||
|
void OpenRequest(std::string account);
|
||||||
|
void SubmitPayment();
|
||||||
|
void SendPayment(const std::string& key, Currency currency, const PaymentOrder& order);
|
||||||
|
void ReviewRequest();
|
||||||
|
void SendRequest(const std::string& key, Currency currency, const RequestOrder& order);
|
||||||
|
void ShowTransaction(const std::string& key, const Transaction& transaction);
|
||||||
|
void ShowRequest(const std::string& key, const BunqPaymentRequest& request);
|
||||||
|
void ShowIncoming(const std::string& key, const BunqIncomingRequest& request);
|
||||||
|
void ShowScheduled(const std::string& key, const BunqScheduledPayment& scheduled);
|
||||||
|
void ShowDraft(const std::string& key, const BunqDraftPayment& draft);
|
||||||
|
void ShowCard(const BunqCard& card);
|
||||||
|
void ShowConnection(const Connection& connection);
|
||||||
|
// A change that needs a yes and no more: asks `question`, makes the change, and tells `told`.
|
||||||
|
void Simple(Operation operation, std::string member, std::string question, std::string detail, std::string confirm, std::string told, std::string account, std::function<Client::Pending(Client&, Client::Then<std::monostate>)> start);
|
||||||
|
void SetCard(std::uint64_t card, std::string lastFour, Operation operation, std::string status);
|
||||||
|
void RemoveConnection(const Connection& connection);
|
||||||
|
// What every way's form ends in: nostrod is asked to add the connection, as `start` asks it, and the user is
|
||||||
|
// told how that went. For the form's own button: which bank and which way it is are the page's that is open.
|
||||||
|
void Connect(std::string member, std::function<Client::Pending(Client&, Client::Then<AddedConnector>)> start);
|
||||||
|
void Connected(const AddedConnector& added, const Way& way);
|
||||||
|
void ForgetConnecting();
|
||||||
|
// bunq's two ways (Nostro.App-Bunq.cpp).
|
||||||
|
void ConnectBunqKey();
|
||||||
|
void BeginBunqOAuth();
|
||||||
|
void ConnectBunqOAuth();
|
||||||
|
void ChooseCheckout(const std::string& key, const std::string& name);
|
||||||
|
void Search(const std::string& key, bool now);
|
||||||
|
|
||||||
|
// -- the screens ---------------------------------------------------------------------------------------------
|
||||||
|
// A form's column inside a page: the page's rows run from edge to edge, a field keeps clear of the edges.
|
||||||
|
static Ui::Box Padded(const Ui::Frame& frame, Ui::Box box);
|
||||||
|
Ui::Box Scaffold(Ui::Frame& frame);
|
||||||
|
std::function<void()> Refresher();
|
||||||
|
std::string Title() const;
|
||||||
|
void Content(Ui::Frame& frame, Ui::Box area);
|
||||||
|
void Notes(Ui::Frame& frame, Ui::Column& column);
|
||||||
|
void Trouble(Ui::Frame& frame, Ui::Column& column, const Guidance& guidance, std::string_view key, std::function<void()> retry);
|
||||||
|
void Waiting(Ui::Frame& frame, Ui::Column& column, std::uint32_t rows);
|
||||||
|
void Empty(Ui::Frame& frame, Ui::Column& column, std::string_view text);
|
||||||
|
void Section(Ui::Frame& frame, Ui::Column& column, std::string_view title);
|
||||||
|
void HomePage(Ui::Frame& frame, Ui::Column& column);
|
||||||
|
void Welcome(Ui::Frame& frame, Ui::Column& column);
|
||||||
|
void AccountPage(Ui::Frame& frame, Ui::Column& column, const AccountRef& account, Ui::Box viewport);
|
||||||
|
void ActivityTab(Ui::Frame& frame, Ui::Column& column, const AccountRef& account, AccountData& data, Ui::Box viewport);
|
||||||
|
template<typename T, typename Make>
|
||||||
|
void ListTab(Ui::Frame& frame, Ui::Column& column, const std::string& key, Tab tab, Loadable<std::vector<T>>& list, std::string_view none, Ui::Box viewport, Make&& row);
|
||||||
|
void PayPage(Ui::Frame& frame, Ui::Column& column);
|
||||||
|
void RequestPage(Ui::Frame& frame, Ui::Column& column);
|
||||||
|
void AccountField(Ui::Frame& frame, Ui::Column& column, std::string_view key, std::string_view label, const std::string& account, Picking picking);
|
||||||
|
void CardsPage(Ui::Frame& frame, Ui::Column& column, Ui::Box viewport);
|
||||||
|
void SettingsPage(Ui::Frame& frame, Ui::Column& column);
|
||||||
|
void ConnectionsPage(Ui::Frame& frame, Ui::Column& column);
|
||||||
|
void BanksPage(Ui::Frame& frame, Ui::Column& column);
|
||||||
|
void WaysPage(Ui::Frame& frame, Ui::Column& column, const Bank& bank);
|
||||||
|
void BunqKeyPage(Ui::Frame& frame, Ui::Column& column);
|
||||||
|
void BunqOAuthPage(Ui::Frame& frame, Ui::Column& column);
|
||||||
|
void CheckoutPage(Ui::Frame& frame, Ui::Column& column);
|
||||||
|
void AboutPage(Ui::Frame& frame, Ui::Column& column);
|
||||||
|
void FilterSheet(Ui::Frame& frame, const AccountRef& account);
|
||||||
|
void PickSheet(Ui::Frame& frame);
|
||||||
|
void DialogSheet(Ui::Frame& frame);
|
||||||
|
|
||||||
|
Ui::Context& context;
|
||||||
|
Host host;
|
||||||
|
std::optional<Client> client;
|
||||||
|
std::map<std::string, Lane, std::less<>> lanes;
|
||||||
|
Client::Pending change; // the one change under way
|
||||||
|
bool changing = false;
|
||||||
|
std::vector<std::string> notes;
|
||||||
|
|
||||||
|
Loadable<std::vector<Connection>> overview;
|
||||||
|
std::map<std::string, AccountData, std::less<>> accounts;
|
||||||
|
Loadable<std::vector<ConnectorCards>> cards;
|
||||||
|
Loadable<std::optional<Account>> checkout;
|
||||||
|
|
||||||
|
Place place = Place::Accounts;
|
||||||
|
std::vector<Route> stack;
|
||||||
|
std::optional<Dialog> dialog;
|
||||||
|
std::string filtering; // the account whose filter sheet is open
|
||||||
|
Picking picking = Picking::None;
|
||||||
|
|
||||||
|
PaymentForm payment;
|
||||||
|
std::string payFrom;
|
||||||
|
RequestForm request;
|
||||||
|
std::string requestInto;
|
||||||
|
BunqKeyForm bunqKey;
|
||||||
|
BunqOAuthForm bunqOAuth;
|
||||||
|
std::string bunqOAuthError; // what was wrong with the address the browser was sent to
|
||||||
|
};
|
||||||
|
}
|
||||||
57
interfaces/Nostro.App-Banks.cppm
Normal file
57
interfaces/Nostro.App-Banks.cppm
Normal file
|
|
@ -0,0 +1,57 @@
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
export module Nostro.App:Banks;
|
||||||
|
|
||||||
|
import std;
|
||||||
|
|
||||||
|
// The banks the app can connect, and what is a bank's own: its name, the ways a connection to it is made, and what
|
||||||
|
// each way lets a connection do. The settings are built from this: adding a connection lists the banks, a bank lists
|
||||||
|
// its ways, and each way has a form of its own (bunq's are in Nostro.App-Bunq.cpp). Nothing else in the app names a
|
||||||
|
// bank or a way: every other screen says "your bank", and asks here what a connection can do. A bank and a way are
|
||||||
|
// found by what nostrod calls them, and one that nostrod has and this app does not know is shown by that name.
|
||||||
|
|
||||||
|
export namespace Nostro::App {
|
||||||
|
// The form a way is filled in on. One for each way of each bank: what a bank asks for is its own.
|
||||||
|
enum class ConnectForm : std::uint8_t {
|
||||||
|
BunqKey,
|
||||||
|
BunqOAuth
|
||||||
|
};
|
||||||
|
|
||||||
|
// One way to connect to a bank.
|
||||||
|
struct Way {
|
||||||
|
std::string_view key; // names it in a route and a region: "key"
|
||||||
|
std::string_view auth; // what nostrod calls a connection made this way (ConnectorSummary::auth): "api key"
|
||||||
|
std::string_view title; // "API key"
|
||||||
|
std::string_view about; // what it gives and what it takes, in a line for under its title
|
||||||
|
std::string_view revoke; // what stays valid at the bank once a connection is removed, and where it is revoked
|
||||||
|
ConnectForm form = ConnectForm::BunqKey;
|
||||||
|
// A connection made this way pays between the user's own accounts and nobody else. What it cannot pay it can
|
||||||
|
// save as a draft, so this is for a bank that has drafts.
|
||||||
|
bool ownAccountsOnly = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Bank {
|
||||||
|
std::string_view id; // what nostrod calls it (ConnectorSummary::bank): "bunq"
|
||||||
|
std::string_view name; // as the bank writes its own name
|
||||||
|
std::span<const Way> ways;
|
||||||
|
};
|
||||||
|
|
||||||
|
// The banks the app can connect, in the order they are offered.
|
||||||
|
std::span<const Bank> Banks() noexcept;
|
||||||
|
// The bank nostrod calls `id`; null for one this app does not know.
|
||||||
|
const Bank* FindBank(std::string_view id) noexcept;
|
||||||
|
// The way a connection to that bank was made, by what nostrod calls the bank and the way; null for one this app
|
||||||
|
// does not know.
|
||||||
|
const Way* FindWay(std::string_view bank, std::string_view auth) noexcept;
|
||||||
|
|
||||||
|
// A bank's name as it writes it, and what nostrod calls it for one this app does not know.
|
||||||
|
std::string BankName(std::string_view id);
|
||||||
|
// How a connection was made, in words: "API key", and what nostrod calls it for a way this app does not know.
|
||||||
|
std::string WayName(std::string_view bank, std::string_view auth);
|
||||||
|
// Whether a connection made that way pays between the user's own accounts only. Not that the app knows of, for a
|
||||||
|
// way it does not know: nostrod refuses what such a connection cannot do.
|
||||||
|
bool OwnAccountsOnly(std::string_view bank, std::string_view auth) noexcept;
|
||||||
|
// What a connection was made with stays valid at the bank when the connection is removed: where to revoke it.
|
||||||
|
std::string Revoking(std::string_view bank, std::string_view auth);
|
||||||
|
}
|
||||||
73
interfaces/Nostro.App-Errors.cppm
Normal file
73
interfaces/Nostro.App-Errors.cppm
Normal file
|
|
@ -0,0 +1,73 @@
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
export module Nostro.App:Errors;
|
||||||
|
|
||||||
|
import std;
|
||||||
|
import Nostro;
|
||||||
|
|
||||||
|
// What went wrong, said so that the user knows what happened to their money and what to do next. nostrod's errors
|
||||||
|
// are told apart by their names and by what was being done: a payment that got no clear answer may have been made,
|
||||||
|
// which a listing that got none never is.
|
||||||
|
|
||||||
|
export namespace Nostro::App {
|
||||||
|
// What nostrod is asked to do, as far as that decides whether it asks for a password and what an error to it means.
|
||||||
|
enum class Operation : std::uint8_t {
|
||||||
|
Load, // any reading: accounts, payments, cards
|
||||||
|
Send,
|
||||||
|
Schedule,
|
||||||
|
Draft,
|
||||||
|
Request,
|
||||||
|
RevokeRequest,
|
||||||
|
PayRequest,
|
||||||
|
RejectRequest,
|
||||||
|
CancelSchedule,
|
||||||
|
AcceptDraft,
|
||||||
|
RejectDraft,
|
||||||
|
FreezeCard,
|
||||||
|
UnfreezeCard,
|
||||||
|
BlockCard,
|
||||||
|
AddConnection,
|
||||||
|
RemoveConnection,
|
||||||
|
SetCheckoutAccount
|
||||||
|
};
|
||||||
|
|
||||||
|
// The polkit action nostrod checks before it does that (Bus::action…).
|
||||||
|
std::string_view ActionOf(Operation operation) noexcept;
|
||||||
|
// Whether the system asks for the user's password before it, by the policy nostro installs: in the user's own
|
||||||
|
// session only what moves money, unfreezes or blocks a card, or changes the connections. An administrator's rules
|
||||||
|
// may ask for more or less; this decides nothing but what the user is told to expect.
|
||||||
|
bool AsksPassword(Operation operation) noexcept;
|
||||||
|
// Whether money leaves an account by it.
|
||||||
|
bool MovesMoney(Operation operation) noexcept;
|
||||||
|
|
||||||
|
enum class Problem : std::uint8_t {
|
||||||
|
Input, // refused before anything was sent
|
||||||
|
NotConfirmed, // no password was given, or nothing could ask for one
|
||||||
|
NotAllowed, // the system's policy refused
|
||||||
|
CannotAsk, // nostrod was not allowed to show a password dialog
|
||||||
|
OwnAccountsOnly, // the bank lets this connection pay between the user's own accounts only
|
||||||
|
Bank, // the bank refused
|
||||||
|
Unknown, // no clear answer: it may have been carried out
|
||||||
|
NoService, // nostrod is not there and cannot be started
|
||||||
|
Late, // a reading that got no answer in time
|
||||||
|
Failed // anything else
|
||||||
|
};
|
||||||
|
|
||||||
|
// There is no connecting to the system bus, which nostrod is talked to over: what the app's host threw when asked
|
||||||
|
// for a client.
|
||||||
|
struct NoSystemBus : std::runtime_error {
|
||||||
|
using std::runtime_error::runtime_error;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Guidance {
|
||||||
|
Problem problem = Problem::Failed;
|
||||||
|
std::string title;
|
||||||
|
std::string detail;
|
||||||
|
bool mayHaveHappened = false; // look before asking again
|
||||||
|
bool retry = false; // asking again is safe, and may work
|
||||||
|
};
|
||||||
|
|
||||||
|
// What an answer's error means for what was asked.
|
||||||
|
Guidance Explain(const std::exception_ptr& error, Operation operation);
|
||||||
|
}
|
||||||
53
interfaces/Nostro.App-Format.cppm
Normal file
53
interfaces/Nostro.App-Format.cppm
Normal file
|
|
@ -0,0 +1,53 @@
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
export module Nostro.App:Format;
|
||||||
|
|
||||||
|
import std;
|
||||||
|
import Nostro;
|
||||||
|
|
||||||
|
// How the app words what a bank gives it: money, dates as a person reads them in their own time zone, and a
|
||||||
|
// bank's capitals in plain words. English only; every such wording is here, and none of it names a bank.
|
||||||
|
|
||||||
|
export namespace Nostro::App {
|
||||||
|
// An IBAN in groups of four, as it is printed on a card; anything else as it is.
|
||||||
|
std::string GroupIban(std::string_view iban);
|
||||||
|
// What an account is found by, in the app and by nostrod: its IBAN, or its name where the bank gave it none.
|
||||||
|
std::string AccountKey(const Account& account);
|
||||||
|
// Who a payment is to or from, as a person would say it: by name, else by IBAN or address, and "Unknown" where
|
||||||
|
// the bank gives neither, as it does for someone it knows by a phone number alone.
|
||||||
|
std::string PartyName(const BunqLabel& party);
|
||||||
|
std::string PartyName(const BunqCounterparty& party);
|
||||||
|
// An amount as a person reads it, its thousands apart: "€12,500.00", "-€3.00".
|
||||||
|
std::string Money(std::int64_t minor, Currency currency);
|
||||||
|
// The same with a plus on what came in, as a list of payments shows it: "+€12.50", "-€3.00", "€0.00".
|
||||||
|
std::string SignedMoney(std::int64_t minor, Currency currency);
|
||||||
|
|
||||||
|
// The day a moment falls on in local time, as one number: moments of one day have the same.
|
||||||
|
std::int64_t LocalDay(std::chrono::system_clock::time_point time);
|
||||||
|
// That day as a list's heading: "Today", "Yesterday", "Monday 3 November", and with its year when that is not
|
||||||
|
// `now`'s.
|
||||||
|
std::string DayLabel(std::chrono::system_clock::time_point time, std::chrono::system_clock::time_point now);
|
||||||
|
// "3 Nov", and with its year when that is not `now`'s.
|
||||||
|
std::string ShortDate(std::chrono::system_clock::time_point time, std::chrono::system_clock::time_point now);
|
||||||
|
// "14:05".
|
||||||
|
std::string ClockTime(std::chrono::system_clock::time_point time);
|
||||||
|
// "3 November 2026, 14:05".
|
||||||
|
std::string FullTime(std::chrono::system_clock::time_point time);
|
||||||
|
// "2026-11-03", as a date field takes it.
|
||||||
|
std::string DateInput(std::chrono::system_clock::time_point time);
|
||||||
|
|
||||||
|
// What kind of payment the bank says one is ("MASTERCARD/PAYMENT"), in words; the bank's own for one not known.
|
||||||
|
std::string KindLabel(std::string_view kind);
|
||||||
|
// A status as the bank writes it ("PIN_TRIES_EXCEEDED"), in words: "Pin tries exceeded".
|
||||||
|
std::string StatusLabel(std::string_view status);
|
||||||
|
// A card's product ("MASTERCARD_DEBIT"), in words: "Mastercard debit".
|
||||||
|
std::string CardProduct(std::string_view productType);
|
||||||
|
// When a card expires, as its face has it: "11/30" for the bank's "2030-11-30"; anything else as the bank says it.
|
||||||
|
std::string CardExpiry(std::string_view expiry);
|
||||||
|
// When a scheduled payment runs: "Once on 3 Nov", "Every 2 weeks from 3 Nov until 1 Jan 2027".
|
||||||
|
std::string ScheduleLabel(const BunqSchedule& schedule, std::chrono::system_clock::time_point now);
|
||||||
|
|
||||||
|
// A secret said without saying it: how it begins and its last four characters, enough to tell two keys apart.
|
||||||
|
std::string Fingerprint(std::string_view secret);
|
||||||
|
}
|
||||||
175
interfaces/Nostro.App-Forms.cppm
Normal file
175
interfaces/Nostro.App-Forms.cppm
Normal file
|
|
@ -0,0 +1,175 @@
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
export module Nostro.App:Forms;
|
||||||
|
|
||||||
|
import std;
|
||||||
|
import Nostro;
|
||||||
|
import Nostro.Ui;
|
||||||
|
|
||||||
|
// What the user fills in, and what it is read as. A form keeps its fields as they were typed and is checked as a
|
||||||
|
// whole: each field's error is a line for under that field, and a form without errors gives an order, the values
|
||||||
|
// nostrod is asked with. Nothing here talks to nostrod; nostrod checks everything again. The forms a payment, a
|
||||||
|
// request and a filter are filled in on are any bank's; what a bank asks for to be connected is its own, and so is
|
||||||
|
// the form for it, named for its bank.
|
||||||
|
|
||||||
|
export namespace Nostro::App {
|
||||||
|
// What a field's text was read as, or why it could not be.
|
||||||
|
template<typename T>
|
||||||
|
struct Read {
|
||||||
|
std::optional<T> value;
|
||||||
|
std::string error;
|
||||||
|
};
|
||||||
|
|
||||||
|
// An amount as a person writes it, "12,50", "12.50" or "12", in the currency's smallest unit; above zero.
|
||||||
|
Read<std::int64_t> ReadAmount(std::string_view text, Currency currency);
|
||||||
|
// Who is paid or asked: an IBAN, an e-mail address or a phone number starting with +.
|
||||||
|
Read<BunqCounterparty> ReadParty(std::string_view text);
|
||||||
|
// What kind of address that is, in words, for beside the field while it is typed; empty for none yet.
|
||||||
|
std::string PartyKind(std::string_view text);
|
||||||
|
// A day "YYYY-MM-DD" in local time, with a time "hh:mm" on it when one is given; the day's last moment when
|
||||||
|
// `end` and no time is given.
|
||||||
|
Read<std::chrono::system_clock::time_point> ReadDay(std::string_view day, std::string_view time = {}, bool end = false);
|
||||||
|
// A whole number above zero.
|
||||||
|
Read<std::uint32_t> ReadCount(std::string_view text);
|
||||||
|
|
||||||
|
// How often a scheduled payment runs, as the form offers it and as nostrod is told it.
|
||||||
|
struct ScheduleUnit {
|
||||||
|
std::string_view label;
|
||||||
|
std::string_view unit;
|
||||||
|
};
|
||||||
|
inline constexpr std::array<ScheduleUnit, 6> scheduleUnits = {{
|
||||||
|
{"Once", "ONCE"}, {"Hourly", "HOURLY"}, {"Daily", "DAILY"}, {"Weekly", "WEEKLY"}, {"Monthly", "MONTHLY"}, {"Yearly", "YEARLY"},
|
||||||
|
}};
|
||||||
|
|
||||||
|
enum class When : std::uint8_t {
|
||||||
|
Now,
|
||||||
|
Scheduled,
|
||||||
|
Draft // made now, paid once someone accepts it
|
||||||
|
};
|
||||||
|
|
||||||
|
// A payment as nostrod is asked for it.
|
||||||
|
struct PaymentOrder {
|
||||||
|
BunqCounterparty to;
|
||||||
|
std::int64_t amount = 0;
|
||||||
|
std::string description;
|
||||||
|
When when = When::Now;
|
||||||
|
BunqSchedule schedule; // for When::Scheduled
|
||||||
|
};
|
||||||
|
|
||||||
|
struct PaymentForm {
|
||||||
|
Ui::EditState to{Ui::FieldKind::Plain};
|
||||||
|
Ui::EditState name{Ui::FieldKind::Text};
|
||||||
|
Ui::EditState amount{Ui::FieldKind::Decimal};
|
||||||
|
Ui::EditState description{Ui::FieldKind::Text};
|
||||||
|
When when = When::Now;
|
||||||
|
Ui::EditState day{Ui::FieldKind::Plain};
|
||||||
|
Ui::EditState time{Ui::FieldKind::Plain};
|
||||||
|
std::size_t unit = 0; // of scheduleUnits
|
||||||
|
Ui::EditState every{Ui::FieldKind::Digits};
|
||||||
|
Ui::EditState until{Ui::FieldKind::Plain};
|
||||||
|
// Errors show once the user has tried to go on: an empty form is not a list of mistakes.
|
||||||
|
bool tried = false;
|
||||||
|
|
||||||
|
struct Errors {
|
||||||
|
std::string to;
|
||||||
|
std::string name;
|
||||||
|
std::string amount;
|
||||||
|
std::string day;
|
||||||
|
std::string time;
|
||||||
|
std::string every;
|
||||||
|
std::string until;
|
||||||
|
bool Any() const noexcept;
|
||||||
|
};
|
||||||
|
// Every field's error, and into `order` what the form asks for when there is none.
|
||||||
|
Errors Check(Currency currency, std::chrono::system_clock::time_point now, PaymentOrder& order) const;
|
||||||
|
void Clear();
|
||||||
|
};
|
||||||
|
|
||||||
|
// A request for money as nostrod is asked for it.
|
||||||
|
struct RequestOrder {
|
||||||
|
BunqCounterparty from;
|
||||||
|
std::int64_t amount = 0;
|
||||||
|
std::string description;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct RequestForm {
|
||||||
|
Ui::EditState from{Ui::FieldKind::Plain};
|
||||||
|
Ui::EditState name{Ui::FieldKind::Text};
|
||||||
|
Ui::EditState amount{Ui::FieldKind::Decimal};
|
||||||
|
Ui::EditState description{Ui::FieldKind::Text};
|
||||||
|
bool tried = false;
|
||||||
|
|
||||||
|
struct Errors {
|
||||||
|
std::string from;
|
||||||
|
std::string name;
|
||||||
|
std::string amount;
|
||||||
|
bool Any() const noexcept;
|
||||||
|
};
|
||||||
|
Errors Check(Currency currency, RequestOrder& order) const;
|
||||||
|
void Clear();
|
||||||
|
};
|
||||||
|
|
||||||
|
// Which of an account's payments are listed.
|
||||||
|
struct FilterForm {
|
||||||
|
Ui::EditState search{Ui::FieldKind::Text};
|
||||||
|
Ui::EditState amount{Ui::FieldKind::Decimal};
|
||||||
|
bool received = false; // the amount came in; it went out otherwise
|
||||||
|
Ui::EditState from{Ui::FieldKind::Plain};
|
||||||
|
Ui::EditState to{Ui::FieldKind::Plain};
|
||||||
|
|
||||||
|
struct Errors {
|
||||||
|
std::string amount;
|
||||||
|
std::string from;
|
||||||
|
std::string to;
|
||||||
|
bool Any() const noexcept;
|
||||||
|
};
|
||||||
|
// The errors, and into `query` what the form asks for when there is none; its limit is left as it is.
|
||||||
|
Errors Check(Currency currency, TransactionQuery& query) const;
|
||||||
|
// What is asked for besides the search, each as a few words: "Paid €12.50", "From 3 Nov".
|
||||||
|
std::vector<std::string> Chips(Currency currency, std::chrono::system_clock::time_point now) const;
|
||||||
|
// Empties everything but the search.
|
||||||
|
void Reset();
|
||||||
|
};
|
||||||
|
|
||||||
|
// A connection to bunq made with an API key. The key says itself which of bunq's environments it is of, by how it
|
||||||
|
// starts, so there is none to choose: nostrod takes the key's own.
|
||||||
|
struct BunqKeyForm {
|
||||||
|
Ui::EditState key{Ui::FieldKind::Secret};
|
||||||
|
Ui::EditState ips{Ui::FieldKind::Plain};
|
||||||
|
bool advanced = false; // the allowed addresses are shown
|
||||||
|
bool tried = false;
|
||||||
|
|
||||||
|
BunqKeyForm();
|
||||||
|
// Why the form cannot be sent; empty when it can.
|
||||||
|
std::string Check() const;
|
||||||
|
void Clear();
|
||||||
|
};
|
||||||
|
|
||||||
|
// A connection to bunq made through OAuth: the client's registration first, then the address the browser ends
|
||||||
|
// up at.
|
||||||
|
struct BunqOAuthForm {
|
||||||
|
Ui::EditState clientId{Ui::FieldKind::Plain};
|
||||||
|
Ui::EditState redirectUri{Ui::FieldKind::Plain};
|
||||||
|
Ui::EditState secret{Ui::FieldKind::Secret};
|
||||||
|
bool sandbox = false;
|
||||||
|
Ui::EditState redirected{Ui::FieldKind::Plain};
|
||||||
|
// Ties the browser's answer to this request; made when the address to open is.
|
||||||
|
std::string state;
|
||||||
|
std::string address; // where the user approves, once the first step is filled in
|
||||||
|
bool tried = false;
|
||||||
|
|
||||||
|
struct Errors {
|
||||||
|
std::string clientId;
|
||||||
|
std::string redirectUri;
|
||||||
|
std::string secret;
|
||||||
|
bool Any() const noexcept;
|
||||||
|
};
|
||||||
|
Errors Check() const;
|
||||||
|
// Makes the address to open, with a new state. The form must be without errors.
|
||||||
|
void Begin(std::string newState);
|
||||||
|
// The code in the address the browser was sent to; throws what BunqConnector::OAuthCodeFromRedirect does.
|
||||||
|
std::string Code() const;
|
||||||
|
void Clear();
|
||||||
|
};
|
||||||
|
}
|
||||||
15
interfaces/Nostro.App.cppm
Normal file
15
interfaces/Nostro.App.cppm
Normal file
|
|
@ -0,0 +1,15 @@
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
export module Nostro.App;
|
||||||
|
|
||||||
|
// Nostro's window as far as it can be without one: what the app knows, what the user fills in, how an error is
|
||||||
|
// worded, and every screen, built with Nostro.Ui from what nostrod answers through the asynchronous Client. The
|
||||||
|
// tests drive it against a real nostrod on a fake bus; a window (Nostro.Ui.Shell) only shows what it builds. What is
|
||||||
|
// a bank's own is :Banks' to say and its forms' to ask for; nothing else in the app tells one bank from another.
|
||||||
|
|
||||||
|
export import :Banks;
|
||||||
|
export import :Format;
|
||||||
|
export import :Forms;
|
||||||
|
export import :Errors;
|
||||||
|
export import :App;
|
||||||
62
interfaces/Nostro.DebugCommands.cppm
Normal file
62
interfaces/Nostro.DebugCommands.cppm
Normal file
|
|
@ -0,0 +1,62 @@
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
export module Nostro.DebugCommands;
|
||||||
|
|
||||||
|
import std;
|
||||||
|
import Crafter.Debug;
|
||||||
|
import Nostro.Ui;
|
||||||
|
import Nostro.Ui.Shell;
|
||||||
|
import Nostro.App;
|
||||||
|
|
||||||
|
// What an agent can call, read and wait for in a build with --debug-api: the window driven by the names of what is on
|
||||||
|
// it, what a screen says as text, and what the app is doing said as it happens. project.cpp builds this module only
|
||||||
|
// then, so no other build has any of it, or of Crafter.Debug.
|
||||||
|
//
|
||||||
|
// A build with it can be driven and read by every program of the user's, and what it is told is kept in a log. It is
|
||||||
|
// for the made-up system (`crafter-build … run fake`) and for bunq's sandbox, never for a real key: a field that hides
|
||||||
|
// what it holds takes only a key of the sandbox's kind through here.
|
||||||
|
|
||||||
|
export namespace Nostro {
|
||||||
|
// What the debugger acts on. All of it outlives the Debugger.
|
||||||
|
struct DebugTargets {
|
||||||
|
Ui::Shell::Loop& loop;
|
||||||
|
Ui::Context& context;
|
||||||
|
// Gone once it was closed while a change was under way.
|
||||||
|
std::optional<Ui::Shell::Window>& window;
|
||||||
|
// Nothing where the toolkit's gallery is shown in the app's place.
|
||||||
|
App::App* app = nullptr;
|
||||||
|
// A directory of the app's own, for a screenshot on its way to whoever asked.
|
||||||
|
std::filesystem::path scratch;
|
||||||
|
// Sets the look: "light", "dark", or "system" for the desktop's.
|
||||||
|
std::function<void(std::string_view scheme)> setTheme;
|
||||||
|
};
|
||||||
|
|
||||||
|
class Debugger {
|
||||||
|
public:
|
||||||
|
// Starts Crafter.Debug's session, and the thread pool its transport runs on, registers the commands and the
|
||||||
|
// watches, and takes the window's and the app's hooks, after whoever had them. Throws what the session does.
|
||||||
|
explicit Debugger(DebugTargets targets);
|
||||||
|
// Hands the hooks back, and ends the session before the pool it runs on.
|
||||||
|
~Debugger();
|
||||||
|
Debugger(const Debugger&) = delete;
|
||||||
|
Debugger& operator=(const Debugger&) = delete;
|
||||||
|
|
||||||
|
private:
|
||||||
|
void Register();
|
||||||
|
// Gives Crafter.Debug the loop's thread, and says what changed since the last time.
|
||||||
|
void Pump();
|
||||||
|
// The screens as they are now, to act on or to read; an error where the window is gone.
|
||||||
|
Crafter::Debug::Result<> Ready();
|
||||||
|
void Drawn();
|
||||||
|
std::vector<std::byte> Capture();
|
||||||
|
|
||||||
|
DebugTargets targets;
|
||||||
|
std::optional<Crafter::Debug::Session> session;
|
||||||
|
Ui::Shell::Timer pump;
|
||||||
|
std::function<void()> frameBefore;
|
||||||
|
std::function<void(std::string_view, bool)> answerBefore;
|
||||||
|
std::string screen; // as it was last said
|
||||||
|
bool changing = false;
|
||||||
|
};
|
||||||
|
}
|
||||||
310
interfaces/Nostro.Ui-Context.cppm
Normal file
310
interfaces/Nostro.Ui-Context.cppm
Normal file
|
|
@ -0,0 +1,310 @@
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
export module Nostro.Ui:Context;
|
||||||
|
|
||||||
|
import std;
|
||||||
|
import :Geometry;
|
||||||
|
import :Text;
|
||||||
|
import :Edit;
|
||||||
|
import :Gesture;
|
||||||
|
import :Draw;
|
||||||
|
import :Theme;
|
||||||
|
import :Input;
|
||||||
|
|
||||||
|
// A window's screens without the window. A screen is built into a Frame: it draws into the frame's list and names
|
||||||
|
// the regions that can be pressed, each with what a press does. The Context keeps what outlives a frame (the focus,
|
||||||
|
// each list's scroll position, the press that is down, a menu that is open) and turns what the window reports, in
|
||||||
|
// pixels and key names, into those regions' actions. Nothing here draws to a screen or reads a device, so a test
|
||||||
|
// builds a frame, reads what it says and taps it by name.
|
||||||
|
//
|
||||||
|
// A region's action runs at once, from the event that asks for it, against the frame built last. So a frame must
|
||||||
|
// still be true when it is used: whoever changes what the screens are built from calls Invalidate, which drops the
|
||||||
|
// frame's regions (an event in between acts on nothing), and builds a new frame before the next event is read. An
|
||||||
|
// action names what it acts on by value, an IBAN or an id, never by its place in a list that may be read again.
|
||||||
|
// Before an action runs, the word an input method is still composing is taken into its field: the action reads every
|
||||||
|
// field as the user sees it.
|
||||||
|
//
|
||||||
|
// What a sheet covers is out of reach, of a finger and of the keyboard alike: a frame that puts a sheet over what had
|
||||||
|
// the focus takes the focus from it. So a button whose press brings a sheet, such as one that sends something and then
|
||||||
|
// shows it under way, cannot be pressed again from under that sheet, by a second Enter either.
|
||||||
|
|
||||||
|
export namespace Nostro::Ui {
|
||||||
|
// What a region is: what a press on it means, and what is under it.
|
||||||
|
enum class Role : std::uint8_t {
|
||||||
|
Button, // acts when tapped
|
||||||
|
Row, // a list's row: acts when tapped, may open a menu when held
|
||||||
|
Field, // a text field
|
||||||
|
Scroll, // an area whose content a drag or the wheel moves; what is drawn in it is above it
|
||||||
|
Scrim, // what a sheet covers: a tap there closes the sheet, and nothing under it is reached
|
||||||
|
Panel // a sheet's or a bar's own ground: inert, and nothing under it is reached
|
||||||
|
};
|
||||||
|
|
||||||
|
// Where a field's text sits, for the tap that places the cursor and for the input method.
|
||||||
|
struct FieldGeometry {
|
||||||
|
float textX = 0; // where the first code point shown starts
|
||||||
|
FontFace face = FontFace::Regular;
|
||||||
|
float px = 0;
|
||||||
|
std::size_t first = 0; // the byte of the shown text the field starts drawing at, when it is too long for it
|
||||||
|
bool masked = false; // drawn as one dot per code point
|
||||||
|
Box caret;
|
||||||
|
TextPurpose purpose = TextPurpose::Normal;
|
||||||
|
std::uint32_t hints = TextHint::none;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Region {
|
||||||
|
Box box;
|
||||||
|
std::string key; // names it across frames: the focus, a press and a test go by it
|
||||||
|
Role role = Role::Button;
|
||||||
|
std::string label; // what it says, for whoever lists a screen's controls
|
||||||
|
bool enabled = true;
|
||||||
|
bool focusable = false; // reached with Tab
|
||||||
|
std::function<void()> onTap;
|
||||||
|
std::function<void()> onLongPress; // held, or the secondary button
|
||||||
|
std::function<bool(Key, Modifiers)> onKey; // a key while it has the focus; true when it took it
|
||||||
|
// A field: what it shows changed. Not called when the word being composed is taken into the field's value, which
|
||||||
|
// changes nothing of what it shows; an action reads its fields when it runs, and finds them whole (see Context).
|
||||||
|
std::function<void()> onChange;
|
||||||
|
std::function<void()> onSubmit; // a field: Enter
|
||||||
|
std::function<void()> onRefresh; // a scrolling area: pulled down at its top, and let go
|
||||||
|
EditState* edit = nullptr; // a field's text
|
||||||
|
FieldGeometry field;
|
||||||
|
// Set as the frame takes it:
|
||||||
|
Box hit; // the part of the box that can be pressed: what its scrolling area shows of it
|
||||||
|
Layer layer = Layer::Background;
|
||||||
|
std::string scroll; // the scrolling area it is in, if any,
|
||||||
|
float scrollTop = 0; // and where that area's viewport begins
|
||||||
|
};
|
||||||
|
|
||||||
|
// The text a field shows: what it holds with the composing text at the cursor, or a dot for each of its code points.
|
||||||
|
std::string FieldText(const EditState& edit, bool masked);
|
||||||
|
// Whether a caret moved only because the window grew under it: its box as it was but for its place, which went
|
||||||
|
// down by what the window gained. That is a field at the window's lower edge after the on-screen keyboard gave its
|
||||||
|
// room back (the keyboard's own hide key). Told at once, the move would be a new text-input state, and a state
|
||||||
|
// committed while the input is on brings the keyboard straight back (seen on Plasma Mobile), so it is held until the
|
||||||
|
// caret moves for another reason.
|
||||||
|
bool CaretFollowedGrowth(Box told, float toldHeight, Box caret, float height) noexcept;
|
||||||
|
|
||||||
|
struct MenuItem {
|
||||||
|
std::string label;
|
||||||
|
std::function<void()> action;
|
||||||
|
bool danger = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
class Context;
|
||||||
|
|
||||||
|
// One frame, as a screen builds it.
|
||||||
|
class Frame {
|
||||||
|
public:
|
||||||
|
Frame(Context& context, Box bounds, float scale, std::int64_t nowMs);
|
||||||
|
|
||||||
|
Context& context;
|
||||||
|
DrawList draw;
|
||||||
|
Box bounds; // the window
|
||||||
|
Metrics metrics;
|
||||||
|
SizeClass sizeClass;
|
||||||
|
std::int64_t nowMs;
|
||||||
|
|
||||||
|
float Dp(float dp) const noexcept;
|
||||||
|
const Theme& Colors() const noexcept;
|
||||||
|
const TextMeasure& Measure() const noexcept;
|
||||||
|
WordWrapper& Wrapper() noexcept;
|
||||||
|
|
||||||
|
// A region, in the layer being drawn and the scrolling area that is open.
|
||||||
|
void Add(Region region);
|
||||||
|
// A key that acts whatever has the focus, unless that took the key itself. The one added last wins, and a scrim
|
||||||
|
// added after it takes it away: a sheet's keys are its own.
|
||||||
|
void Shortcut(Key key, Modifiers modifiers, std::function<void()> action);
|
||||||
|
// Opens a scrolling area: what is drawn and added until EndScroll is cut to `viewport` and moves with the area's
|
||||||
|
// offset, which is returned, in whole pixels. EndScroll says how tall the content turned out to be.
|
||||||
|
float BeginScroll(std::string_view key, Box viewport);
|
||||||
|
void EndScroll(float contentHeight);
|
||||||
|
// Between the two: the area that is open can be read again by a finger. Dragged down while it is at its top it
|
||||||
|
// gives way, by half the finger's way, and let go at Size::pull or further it runs `refresh`.
|
||||||
|
void Refreshable(std::function<void()> refresh);
|
||||||
|
// How far the area that is open is pulled down, in pixels: its content is drawn that much lower, and what shows
|
||||||
|
// above it says what letting go will do.
|
||||||
|
float Pulled() const noexcept;
|
||||||
|
|
||||||
|
bool Hovered(std::string_view key) const noexcept;
|
||||||
|
bool Pressed(std::string_view key) const noexcept;
|
||||||
|
bool Focused(std::string_view key) const noexcept;
|
||||||
|
// Whether the focus is to be shown on something that is no field: it came by the keyboard.
|
||||||
|
bool FocusRing(std::string_view key) const noexcept;
|
||||||
|
// The caret's blink: whether it is in its lit half.
|
||||||
|
bool CaretOn() const noexcept;
|
||||||
|
|
||||||
|
struct KeyAction {
|
||||||
|
Key key = Key::None;
|
||||||
|
Modifiers modifiers;
|
||||||
|
std::function<void()> action;
|
||||||
|
};
|
||||||
|
std::vector<Region> regions;
|
||||||
|
std::vector<KeyAction> shortcuts;
|
||||||
|
|
||||||
|
private:
|
||||||
|
struct OpenScroll {
|
||||||
|
std::string key;
|
||||||
|
Box viewport;
|
||||||
|
};
|
||||||
|
std::vector<OpenScroll> scrolls;
|
||||||
|
};
|
||||||
|
|
||||||
|
class Context {
|
||||||
|
public:
|
||||||
|
// What the window is to do after an event or a frame.
|
||||||
|
struct Wants {
|
||||||
|
bool redraw = false; // what is shown is no longer what a frame would draw
|
||||||
|
bool animating = false; // and will not be at the next frame either: a list is moving
|
||||||
|
std::optional<std::int64_t> wakeAtMs; // call Tick then, if nothing comes before
|
||||||
|
TextInputRequest textInput;
|
||||||
|
std::optional<std::string> copy; // put this on the clipboard
|
||||||
|
bool paste = false; // fetch the clipboard and hand it to Paste
|
||||||
|
};
|
||||||
|
|
||||||
|
explicit Context(TextMeasure measure);
|
||||||
|
Context(const Context&) = delete;
|
||||||
|
Context& operator=(const Context&) = delete;
|
||||||
|
|
||||||
|
Theme theme;
|
||||||
|
|
||||||
|
// A frame to build into, and its end: the regions it named are the ones events act on from here.
|
||||||
|
Frame& Begin(Box bounds, float scale, std::int64_t nowMs);
|
||||||
|
void End();
|
||||||
|
// Whether a frame was ended since the last Invalidate.
|
||||||
|
bool Built() const noexcept;
|
||||||
|
// The frame ended last: what the window shows.
|
||||||
|
const Frame& Shown() const;
|
||||||
|
// Its regions, from the bottom up.
|
||||||
|
std::span<const Region> Regions() const noexcept;
|
||||||
|
const Region* Find(std::string_view key) const noexcept;
|
||||||
|
|
||||||
|
// What the screens are built from changed: the regions go, with the press that is down and a menu that is open.
|
||||||
|
void Invalidate();
|
||||||
|
void Redraw() noexcept;
|
||||||
|
|
||||||
|
// -- what the window reports ---------------------------------------------------------------------------------
|
||||||
|
void Pointer(PointerPhase phase, Point at, std::int64_t tMs);
|
||||||
|
// The pointer moved with no button down, or left the window: what it is over is drawn so.
|
||||||
|
void Hover(std::optional<Point> at);
|
||||||
|
// The secondary button: what a long press does.
|
||||||
|
void Secondary(Point at);
|
||||||
|
// Wheel motion, in detents: positive scrolls down.
|
||||||
|
void Wheel(Point at, float detents);
|
||||||
|
// A key went down; `repeat` when it is still held from before. A held key edits and moves on, and acts once.
|
||||||
|
void KeyDown(Key key, Modifiers modifiers, bool repeat = false);
|
||||||
|
// Text a key typed or the input method committed, its composing text, and its deletion around the cursor.
|
||||||
|
void Text(std::string_view utf8);
|
||||||
|
void Preedit(std::string_view utf8);
|
||||||
|
void DeleteAround(std::size_t beforeBytes, std::size_t afterBytes);
|
||||||
|
// The clipboard's text, asked for through Wants::paste.
|
||||||
|
void Paste(std::string_view utf8);
|
||||||
|
// Time passed: a held press becomes a long press, the caret blinks, a flung list moves on, a notice goes.
|
||||||
|
void Tick(std::int64_t nowMs);
|
||||||
|
|
||||||
|
// -- for a screen, a test or a debugger ----------------------------------------------------------------------
|
||||||
|
// As a tap, or a long press, on the region of that name; false when there is none that can take it.
|
||||||
|
bool Tap(std::string_view key);
|
||||||
|
bool LongPress(std::string_view key);
|
||||||
|
// Gives a region the focus, as Tab reaching it would; it need not be built yet. An empty key takes the focus away.
|
||||||
|
void Focus(std::string_view key);
|
||||||
|
std::string_view Focused() const noexcept;
|
||||||
|
// Where the press is that the action now running answers to: where a menu it opens belongs. The middle of the
|
||||||
|
// region for an action that a key or a name asked for.
|
||||||
|
Point Pointed() const noexcept;
|
||||||
|
// A list of choices at a point, above everything, until one is taken or it is dismissed.
|
||||||
|
void OpenMenu(Point at, std::vector<MenuItem> items);
|
||||||
|
void CloseMenu();
|
||||||
|
bool MenuOpen() const noexcept;
|
||||||
|
// A line shown over the window's bottom for a moment.
|
||||||
|
void Notice(std::string text, std::int64_t forMs = 2500);
|
||||||
|
void Copy(std::string text);
|
||||||
|
// The input method starts afresh on the field that has the focus: its text was replaced by something else than
|
||||||
|
// its own edits.
|
||||||
|
void RestartInput() noexcept;
|
||||||
|
ScrollState& Scroll(std::string_view key);
|
||||||
|
// The time of the last Tick or frame: what "in a moment" is counted from.
|
||||||
|
std::int64_t Now() const noexcept;
|
||||||
|
// Runs `action` once from the Tick that reaches `atMs`, which the window is woken for: what a screen puts off, as
|
||||||
|
// a search until the typing has stopped. One of the same name that was still waiting is replaced, and Forget
|
||||||
|
// drops one.
|
||||||
|
void At(std::string_view name, std::int64_t atMs, std::function<void()> action);
|
||||||
|
void Forget(std::string_view name);
|
||||||
|
|
||||||
|
// What the window is to do, taken out: the next call says only what came since.
|
||||||
|
Wants Take();
|
||||||
|
|
||||||
|
const TextMeasure& Measure() const noexcept;
|
||||||
|
WordWrapper& Wrapper() noexcept;
|
||||||
|
|
||||||
|
private:
|
||||||
|
friend class Frame;
|
||||||
|
|
||||||
|
const Region* HitTest(Point at) const noexcept;
|
||||||
|
const Region* ScrollUnder(Point at) const noexcept;
|
||||||
|
const Region* FocusedRegion() const noexcept;
|
||||||
|
bool UnderSheet(const Region& region) const noexcept;
|
||||||
|
void Stale();
|
||||||
|
void Handle(const GestureEvent& event);
|
||||||
|
void Activate(const Region& region, Point at);
|
||||||
|
void Held(const Region& region, Point at);
|
||||||
|
void TapField(const Region& region, Point at);
|
||||||
|
void FieldMenu(const Region& region, Point at);
|
||||||
|
void EndComposition();
|
||||||
|
void MoveFocus(std::string_view key, bool byKeyboard);
|
||||||
|
void StepFocus(std::int32_t by);
|
||||||
|
void Reveal(const Region& region);
|
||||||
|
void Edited(const Region& field);
|
||||||
|
bool EditKeyDown(const Region& field, Key key, Modifiers modifiers);
|
||||||
|
void ShowCaret() noexcept;
|
||||||
|
void DrawMenu(Frame& frame);
|
||||||
|
void DrawNotice(Frame& frame);
|
||||||
|
void UpdateTextInput(float windowHeight);
|
||||||
|
float Dp(float dp) const noexcept;
|
||||||
|
|
||||||
|
WordWrapper wrapper;
|
||||||
|
std::optional<Frame> frame; // the frame being built, then the one shown
|
||||||
|
std::vector<Region> regions; // the shown frame's, from the bottom up
|
||||||
|
std::vector<Frame::KeyAction> shortcuts;
|
||||||
|
bool built = false;
|
||||||
|
float scale = 1;
|
||||||
|
Box window;
|
||||||
|
float builtHeight = 0; // the window's height at the frame before
|
||||||
|
std::int64_t now = 0;
|
||||||
|
std::int64_t eventTime = 0; // the time of the pointer event being handled
|
||||||
|
|
||||||
|
GestureDetector gestures;
|
||||||
|
std::string pressedKey; // what the press that is down went down on
|
||||||
|
std::string scrollKey; // the scrolling area under it
|
||||||
|
float pull = 0; // how far that area is pulled down past its top
|
||||||
|
bool pressTaken = false; // the press became a long press or a drag: its release is no tap
|
||||||
|
std::string hoverKey;
|
||||||
|
Point pointed; // where the press is that the running action answers to
|
||||||
|
std::string focusKey;
|
||||||
|
bool focusByKeyboard = false;
|
||||||
|
std::map<std::string, ScrollState, std::less<>> scrolls;
|
||||||
|
std::int64_t lastTick = 0;
|
||||||
|
std::int64_t caretSince = 0; // when the caret was last shown at once: it blinks from there
|
||||||
|
std::int64_t caretPhase = 0; // the half second of its blink the last tick found it in
|
||||||
|
static constexpr std::int64_t caretIdleMs = 10000; // it stops blinking so long after, lit
|
||||||
|
|
||||||
|
struct Menu {
|
||||||
|
Point at;
|
||||||
|
std::vector<MenuItem> items;
|
||||||
|
};
|
||||||
|
std::optional<Menu> menu;
|
||||||
|
std::string notice;
|
||||||
|
std::int64_t noticeUntil = 0;
|
||||||
|
struct Later {
|
||||||
|
std::int64_t atMs = 0;
|
||||||
|
std::function<void()> action;
|
||||||
|
};
|
||||||
|
std::map<std::string, Later, std::less<>> laters;
|
||||||
|
|
||||||
|
std::size_t inputSerial = 1; // one per time a field's input starts afresh
|
||||||
|
TextInputRequest told; // what the window was last asked for
|
||||||
|
float toldHeight = 0; // the window's height then: lower since, the on-screen keyboard is up
|
||||||
|
bool keyboardGone = false; // taller since: the keyboard gave its room back while the field kept the focus
|
||||||
|
Wants wants;
|
||||||
|
};
|
||||||
|
}
|
||||||
120
interfaces/Nostro.Ui-Draw.cppm
Normal file
120
interfaces/Nostro.Ui-Draw.cppm
Normal file
|
|
@ -0,0 +1,120 @@
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
export module Nostro.Ui:Draw;
|
||||||
|
|
||||||
|
import std;
|
||||||
|
import :Geometry;
|
||||||
|
import :Text;
|
||||||
|
|
||||||
|
// What a frame draws, as a list the window turns into its own items and the tests read: rounded boxes, circles and
|
||||||
|
// lines of text, in layers. The window library draws a batch in one pass in which every shape comes before every
|
||||||
|
// text, so a shape meant to cover text drawn earlier needs a pass of its own; and a pass is cut to one box. The list
|
||||||
|
// keeps the order things were drawn in by starting a new batch where one pass could not show it: where the clip
|
||||||
|
// changes, and where a shape would land on text already in the batch. Each batch is a pass over the whole window, so
|
||||||
|
// a screen is drawn with few of them: its layers, and a clip per scrolling area.
|
||||||
|
|
||||||
|
export namespace Nostro::Ui {
|
||||||
|
enum class TextAlign : std::uint8_t {
|
||||||
|
Left, // x is where the text starts
|
||||||
|
Center, // x is its middle
|
||||||
|
Right // x is where it ends
|
||||||
|
};
|
||||||
|
|
||||||
|
// Drawn in this order, whatever order a screen draws them in.
|
||||||
|
enum class Layer : std::uint8_t {
|
||||||
|
Background,
|
||||||
|
Content, // what scrolls
|
||||||
|
Chrome, // the bars around it
|
||||||
|
Overlay, // a sheet or a dialog, and the scrim under it
|
||||||
|
Popup // a menu or a notice, above everything
|
||||||
|
};
|
||||||
|
inline constexpr std::size_t layerCount = 5;
|
||||||
|
|
||||||
|
// A box's corner radii, clockwise from the top left.
|
||||||
|
struct Corners {
|
||||||
|
float topLeft = 0;
|
||||||
|
float topRight = 0;
|
||||||
|
float bottomRight = 0;
|
||||||
|
float bottomLeft = 0;
|
||||||
|
|
||||||
|
static constexpr Corners All(float radius) noexcept {
|
||||||
|
return {radius, radius, radius, radius};
|
||||||
|
}
|
||||||
|
static constexpr Corners Top(float radius) noexcept {
|
||||||
|
return {radius, radius, 0, 0};
|
||||||
|
}
|
||||||
|
friend bool operator==(const Corners&, const Corners&) = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct RectItem {
|
||||||
|
Box box;
|
||||||
|
Color color;
|
||||||
|
Corners corners;
|
||||||
|
float outline = 0; // the width of a line along its edge, inside the box
|
||||||
|
Color outlineColor;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct CircleItem {
|
||||||
|
Point center;
|
||||||
|
float radius = 0;
|
||||||
|
Color color;
|
||||||
|
float outline = 0;
|
||||||
|
Color outlineColor;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct TextItem {
|
||||||
|
std::string text;
|
||||||
|
float x = 0;
|
||||||
|
float baseline = 0;
|
||||||
|
FontFace face = FontFace::Regular;
|
||||||
|
float px = 0;
|
||||||
|
Color color;
|
||||||
|
TextAlign align = TextAlign::Left;
|
||||||
|
Box bounds; // the line's box: its width, from its ascent to a line's height below that
|
||||||
|
};
|
||||||
|
|
||||||
|
// One pass: the shapes, then the text over them, all cut to `clip`.
|
||||||
|
struct Batch {
|
||||||
|
std::optional<Box> clip; // nothing: the whole window
|
||||||
|
std::vector<RectItem> rects;
|
||||||
|
std::vector<CircleItem> circles;
|
||||||
|
std::vector<TextItem> texts;
|
||||||
|
};
|
||||||
|
|
||||||
|
class DrawList {
|
||||||
|
public:
|
||||||
|
// `bounds` is the window: what lies outside it, or outside the clip, is not kept.
|
||||||
|
DrawList(const TextMeasure& measure, Box bounds);
|
||||||
|
|
||||||
|
// What is drawn from here on goes to this layer.
|
||||||
|
void SetLayer(Layer layer) noexcept;
|
||||||
|
Layer CurrentLayer() const noexcept;
|
||||||
|
// Cuts what is drawn from here on, in any layer, to `box` within the clip there was, until the matching PopClip.
|
||||||
|
void PushClip(Box box);
|
||||||
|
void PopClip();
|
||||||
|
|
||||||
|
void Rect(const RectItem& item);
|
||||||
|
void Rect(Box box, Color color, float radius = 0);
|
||||||
|
void Circle(const CircleItem& item);
|
||||||
|
void Circle(Point center, float radius, Color color);
|
||||||
|
// One line; returns its width.
|
||||||
|
float Text(std::string_view text, float x, float baseline, FontFace face, float px, Color color, TextAlign align = TextAlign::Left);
|
||||||
|
|
||||||
|
std::span<const Batch> Batches(Layer layer) const noexcept;
|
||||||
|
std::size_t BatchCount() const noexcept;
|
||||||
|
// Every line of text in the list, in the order it is drawn: what a screen says.
|
||||||
|
std::vector<std::string> Texts() const;
|
||||||
|
|
||||||
|
private:
|
||||||
|
// The batch a shape that covers `box`, or a text, goes into.
|
||||||
|
Batch& BatchFor(std::optional<Box> shape);
|
||||||
|
bool Visible(Box box) const noexcept;
|
||||||
|
|
||||||
|
const TextMeasure* measure;
|
||||||
|
Box bounds;
|
||||||
|
Layer layer = Layer::Background;
|
||||||
|
std::vector<Box> clips;
|
||||||
|
std::array<std::vector<Batch>, layerCount> layers;
|
||||||
|
};
|
||||||
|
}
|
||||||
86
interfaces/Nostro.Ui-Edit.cppm
Normal file
86
interfaces/Nostro.Ui-Edit.cppm
Normal file
|
|
@ -0,0 +1,86 @@
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
export module Nostro.Ui:Edit;
|
||||||
|
|
||||||
|
import std;
|
||||||
|
import :Text;
|
||||||
|
|
||||||
|
// A text field's content and its editing, by code point: an edit that took a single byte would leave half a character
|
||||||
|
// behind. A field is one line. The window draws the state, places the cursor where a tap lands and turns its keys into
|
||||||
|
// EditKeys; what an input method is still composing is shown at the cursor and is not yet part of the value.
|
||||||
|
|
||||||
|
export namespace Nostro::Ui {
|
||||||
|
// What a field holds, which decides what can be typed or pasted into it.
|
||||||
|
enum class FieldKind : std::uint8_t {
|
||||||
|
Text, // a line of prose: a name, a description
|
||||||
|
Plain, // a line taken as typed: an IBAN, an e-mail address, a web address
|
||||||
|
Decimal, // an amount: digits and one of , or .
|
||||||
|
Digits, // a whole number
|
||||||
|
Secret // a key or a password: shown as dots, never copied, wiped from memory when it goes
|
||||||
|
};
|
||||||
|
|
||||||
|
enum class EditKey : std::uint8_t {
|
||||||
|
Backspace,
|
||||||
|
Delete,
|
||||||
|
Left,
|
||||||
|
Right,
|
||||||
|
Home,
|
||||||
|
End
|
||||||
|
};
|
||||||
|
|
||||||
|
// One field. It stays where it is made (a form's member), so what draws it and what types into it can point at it,
|
||||||
|
// and a secret has no copy elsewhere to forget.
|
||||||
|
struct EditState {
|
||||||
|
// The most a field holds, in bytes. A secret's buffer is that large from the start, so growing never leaves a
|
||||||
|
// copy behind.
|
||||||
|
static constexpr std::size_t limit = 2048;
|
||||||
|
static constexpr std::size_t secretLimit = 512;
|
||||||
|
|
||||||
|
std::string value;
|
||||||
|
std::size_t cursor = 0; // a byte offset on a code point boundary
|
||||||
|
std::size_t anchor = 0; // where the selection began; the cursor when nothing is selected
|
||||||
|
std::string preedit; // the input method's composing text
|
||||||
|
FieldKind kind;
|
||||||
|
|
||||||
|
explicit EditState(FieldKind kind = FieldKind::Text);
|
||||||
|
EditState(const EditState&) = delete;
|
||||||
|
EditState& operator=(const EditState&) = delete;
|
||||||
|
~EditState();
|
||||||
|
|
||||||
|
// Nothing typed, and nothing being composed.
|
||||||
|
bool Empty() const noexcept;
|
||||||
|
// The text as shown, the composing text at the cursor, and where the cursor is in it.
|
||||||
|
std::string Shown() const;
|
||||||
|
std::size_t ShownCursor() const noexcept;
|
||||||
|
bool HasSelection() const noexcept;
|
||||||
|
std::size_t SelectionBegin() const noexcept;
|
||||||
|
std::size_t SelectionEnd() const noexcept;
|
||||||
|
std::string_view Selected() const noexcept;
|
||||||
|
|
||||||
|
// Replaces everything with `text`, as far as the kind takes it; the cursor goes to its end.
|
||||||
|
void Set(std::string_view text);
|
||||||
|
// Empties the field. A secret's bytes are overwritten first.
|
||||||
|
void Clear();
|
||||||
|
// What a key typed or the input method committed: it takes the place of the selection and of the composing text.
|
||||||
|
void Commit(std::string_view utf8);
|
||||||
|
// What was pasted: the composing text is kept, as part of the value, and the pasted text follows it.
|
||||||
|
void Paste(std::string_view utf8);
|
||||||
|
// Applies one key. With `extend` (Shift held) a move stretches the selection instead of ending it. False when
|
||||||
|
// Backspace or Delete had nothing to delete; a move is true even where the cursor cannot go further.
|
||||||
|
bool Apply(EditKey key, bool extend = false);
|
||||||
|
// The input method's deletion: so many bytes before and after the cursor, rounded out to code points. The
|
||||||
|
// composing text stays; the input method replaces it when it changes.
|
||||||
|
void DeleteAround(std::size_t beforeBytes, std::size_t afterBytes);
|
||||||
|
// Takes the composing text into the value at the cursor, as the input method would commit it.
|
||||||
|
void CommitPreedit();
|
||||||
|
// Puts the cursor at a byte offset of the value (brought to a code point boundary), with nothing selected.
|
||||||
|
void MoveTo(std::size_t byte);
|
||||||
|
void SelectAll();
|
||||||
|
// Removes what is selected; false when nothing was.
|
||||||
|
bool DeleteSelection();
|
||||||
|
|
||||||
|
private:
|
||||||
|
void Insert(std::string_view utf8);
|
||||||
|
};
|
||||||
|
}
|
||||||
126
interfaces/Nostro.Ui-Geometry.cppm
Normal file
126
interfaces/Nostro.Ui-Geometry.cppm
Normal file
|
|
@ -0,0 +1,126 @@
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
export module Nostro.Ui:Geometry;
|
||||||
|
|
||||||
|
import std;
|
||||||
|
|
||||||
|
// Points, boxes and colours, and the two things that decide how a screen is laid out: the scale that turns the design's
|
||||||
|
// sizes into the window's pixels, and how wide the window is. Everything the toolkit positions is in the window's
|
||||||
|
// physical pixels; a size in the design's units (dp) exists only as a constant, turned into pixels by Metrics::Dp.
|
||||||
|
|
||||||
|
export namespace Nostro::Ui {
|
||||||
|
struct Point {
|
||||||
|
float x = 0;
|
||||||
|
float y = 0;
|
||||||
|
friend bool operator==(const Point&, const Point&) = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Space taken off a box's sides.
|
||||||
|
struct Insets {
|
||||||
|
float left = 0;
|
||||||
|
float top = 0;
|
||||||
|
float right = 0;
|
||||||
|
float bottom = 0;
|
||||||
|
|
||||||
|
static constexpr Insets All(float each) noexcept {
|
||||||
|
return {each, each, each, each};
|
||||||
|
}
|
||||||
|
static constexpr Insets Symmetric(float horizontal, float vertical) noexcept {
|
||||||
|
return {horizontal, vertical, horizontal, vertical};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Box {
|
||||||
|
float x = 0;
|
||||||
|
float y = 0;
|
||||||
|
float w = 0;
|
||||||
|
float h = 0;
|
||||||
|
|
||||||
|
constexpr float Right() const noexcept {
|
||||||
|
return x + w;
|
||||||
|
}
|
||||||
|
constexpr float Bottom() const noexcept {
|
||||||
|
return y + h;
|
||||||
|
}
|
||||||
|
constexpr Point Center() const noexcept {
|
||||||
|
return {x + w / 2, y + h / 2};
|
||||||
|
}
|
||||||
|
constexpr bool Empty() const noexcept {
|
||||||
|
return w <= 0 || h <= 0;
|
||||||
|
}
|
||||||
|
// The left and top edges are inside, the right and bottom ones are not, so boxes that share an edge share no point.
|
||||||
|
constexpr bool Contains(Point p) const noexcept {
|
||||||
|
return p.x >= x && p.x < x + w && p.y >= y && p.y < y + h;
|
||||||
|
}
|
||||||
|
// The box within the insets; one they leave nothing of is empty at its place, never inside out.
|
||||||
|
constexpr Box Inset(Insets by) const noexcept {
|
||||||
|
return {x + by.left, y + by.top, std::max(0.0f, w - by.left - by.right), std::max(0.0f, h - by.top - by.bottom)};
|
||||||
|
}
|
||||||
|
// What two boxes share, or an empty box when they share nothing.
|
||||||
|
constexpr Box Intersect(Box other) const noexcept {
|
||||||
|
const float left = std::max(x, other.x);
|
||||||
|
const float top = std::max(y, other.y);
|
||||||
|
const float right = std::min(Right(), other.Right());
|
||||||
|
const float bottom = std::min(Bottom(), other.Bottom());
|
||||||
|
if(right <= left || bottom <= top) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
return {left, top, right - left, bottom - top};
|
||||||
|
}
|
||||||
|
constexpr bool Overlaps(Box other) const noexcept {
|
||||||
|
return !Intersect(other).Empty();
|
||||||
|
}
|
||||||
|
friend bool operator==(const Box&, const Box&) = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Red, green, blue and opacity, each from 0 to 1.
|
||||||
|
struct Color {
|
||||||
|
float r = 0;
|
||||||
|
float g = 0;
|
||||||
|
float b = 0;
|
||||||
|
float a = 1;
|
||||||
|
|
||||||
|
constexpr Color WithAlpha(float alpha) const noexcept {
|
||||||
|
return {r, g, b, alpha};
|
||||||
|
}
|
||||||
|
// This colour with `over` laid on it at `amount` of its strength: how a pressed or hovered control is tinted.
|
||||||
|
constexpr Color Mixed(Color over, float amount) const noexcept {
|
||||||
|
return {r + (over.r - r) * amount, g + (over.g - g) * amount, b + (over.b - b) * amount, a};
|
||||||
|
}
|
||||||
|
// How bright the eye takes it for, from 0 to 1: what decides whether text on it is dark or light.
|
||||||
|
constexpr float Luminance() const noexcept {
|
||||||
|
return 0.2126f * r + 0.7152f * g + 0.0722f * b;
|
||||||
|
}
|
||||||
|
friend bool operator==(const Color&, const Color&) = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
// The window's scale: how many of its pixels one of the design's units (dp) is.
|
||||||
|
struct Metrics {
|
||||||
|
float scale = 1;
|
||||||
|
|
||||||
|
// A size of the design in whole pixels, so edges land on the pixel grid and stay sharp.
|
||||||
|
float Dp(float dp) const noexcept {
|
||||||
|
return std::round(dp * scale);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// How much room a window gives its screens: a phone held upright, a phone on its side or a narrow window, a desktop.
|
||||||
|
enum class SizeClass : std::uint8_t {
|
||||||
|
Compact,
|
||||||
|
Medium,
|
||||||
|
Expanded
|
||||||
|
};
|
||||||
|
|
||||||
|
inline constexpr float mediumFromDp = 600;
|
||||||
|
inline constexpr float expandedFromDp = 900;
|
||||||
|
|
||||||
|
// The class of a window `widthPx` pixels wide at `scale`.
|
||||||
|
constexpr SizeClass SizeClassFor(float widthPx, float scale) noexcept {
|
||||||
|
const float dp = widthPx / (scale > 0 ? scale : 1.0f);
|
||||||
|
if(dp < mediumFromDp) {
|
||||||
|
return SizeClass::Compact;
|
||||||
|
}
|
||||||
|
return dp < expandedFromDp ? SizeClass::Medium : SizeClass::Expanded;
|
||||||
|
}
|
||||||
|
}
|
||||||
124
interfaces/Nostro.Ui-Gesture.cppm
Normal file
124
interfaces/Nostro.Ui-Gesture.cppm
Normal file
|
|
@ -0,0 +1,124 @@
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
export module Nostro.Ui:Gesture;
|
||||||
|
|
||||||
|
import std;
|
||||||
|
import :Geometry;
|
||||||
|
|
||||||
|
// What a finger or a mouse did, decided from raw pointer phases; the scroll physics of a list; and the frames a
|
||||||
|
// window that draws only on demand still owes. Pure arithmetic over points and times, so the tests feed it by hand.
|
||||||
|
|
||||||
|
export namespace Nostro::Ui {
|
||||||
|
enum class PointerPhase : std::uint8_t {
|
||||||
|
Down,
|
||||||
|
Move,
|
||||||
|
Up,
|
||||||
|
Cancel // the compositor took the touch for a gesture of its own: nothing was tapped
|
||||||
|
};
|
||||||
|
|
||||||
|
struct GestureEvent {
|
||||||
|
enum class Kind : std::uint8_t {
|
||||||
|
None,
|
||||||
|
Tap,
|
||||||
|
LongPress,
|
||||||
|
DragStart,
|
||||||
|
Drag,
|
||||||
|
Fling,
|
||||||
|
Release
|
||||||
|
};
|
||||||
|
Kind kind = Kind::None;
|
||||||
|
Point at; // the press for Tap, LongPress and DragStart; the current position for Drag, Fling and Release
|
||||||
|
Point delta; // DragStart and Drag: the movement since the previous event
|
||||||
|
Point velocity; // Fling: pixels per second
|
||||||
|
};
|
||||||
|
|
||||||
|
// One pointer at a time. A press that ends within the slop and before the long-press time is a tap. A press held
|
||||||
|
// past that time without moving is a long press: the host runs the timer and calls Timeout, or the first move or the
|
||||||
|
// release past that time is, when it comes before the timer could (the host's loop dispatched the press and what
|
||||||
|
// followed it together, behind a stall, each with its own time). Movement past the slop starts a drag, whose release
|
||||||
|
// is a fling when it was fast enough. Where the host says that what the press landed on has no long press, a press
|
||||||
|
// held as long is still a tap at its release.
|
||||||
|
class GestureDetector {
|
||||||
|
public:
|
||||||
|
float slopPx = 8;
|
||||||
|
std::int64_t longPressMs = 500;
|
||||||
|
float flingMinPxPerS = 60;
|
||||||
|
// Whether the press that follows can be a long press: the host's word, before each Down.
|
||||||
|
bool longPress = true;
|
||||||
|
|
||||||
|
GestureEvent Feed(PointerPhase phase, Point p, std::int64_t tMs);
|
||||||
|
// The host's timer at Down + longPressMs.
|
||||||
|
GestureEvent Timeout(std::int64_t tMs);
|
||||||
|
bool Pressed() const noexcept;
|
||||||
|
bool Dragging() const noexcept;
|
||||||
|
// When the timer for the press that is down is due; nothing while no press waits for one.
|
||||||
|
std::optional<std::int64_t> LongPressDue() const noexcept;
|
||||||
|
|
||||||
|
private:
|
||||||
|
struct Sample {
|
||||||
|
Point p;
|
||||||
|
std::int64_t tMs;
|
||||||
|
};
|
||||||
|
|
||||||
|
GestureEvent LongPressed();
|
||||||
|
void Forget(std::int64_t tMs);
|
||||||
|
|
||||||
|
bool pressed = false;
|
||||||
|
bool dragging = false;
|
||||||
|
bool longPressed = false;
|
||||||
|
Point down;
|
||||||
|
Point last;
|
||||||
|
std::int64_t downAt = 0;
|
||||||
|
std::vector<Sample> samples;
|
||||||
|
};
|
||||||
|
|
||||||
|
// A scrollable extent: the offset is how far the content moved up.
|
||||||
|
struct ScrollState {
|
||||||
|
float offset = 0;
|
||||||
|
float velocity = 0; // pixels per second, positive scrolls further down
|
||||||
|
float content = 0;
|
||||||
|
float viewport = 0;
|
||||||
|
|
||||||
|
float Max() const noexcept;
|
||||||
|
void Clamp() noexcept;
|
||||||
|
void ScrollBy(float dy) noexcept;
|
||||||
|
void Fling(float pxPerS) noexcept;
|
||||||
|
// Advances the fling by dt seconds; true while still moving.
|
||||||
|
bool Tick(float dt) noexcept;
|
||||||
|
// Scrolls as little as it takes to bring the span from `top` to `bottom` of the content into view, `margin`
|
||||||
|
// clear of the viewport's edges where the content allows it: what keeps a field that got the focus on screen
|
||||||
|
// when the on-screen keyboard takes half the window. True when that moved anything.
|
||||||
|
bool EnsureVisible(float top, float bottom, float margin) noexcept;
|
||||||
|
};
|
||||||
|
|
||||||
|
// The time of a pointer or touch event on the host's own clock. The compositor stamps each event with the time it
|
||||||
|
// happened, in milliseconds from a base of its own, wrapping at 2^32; events queued while the loop was busy are
|
||||||
|
// dispatched together when it comes back, so by the host's clock at dispatch a swipe's backlog is a burst, read as a
|
||||||
|
// fling at many times the finger's speed, and a press and its release that both waited out a stall happen at once.
|
||||||
|
// The stamps, unwrapped, tick like the host's clock a constant apart, and no event is dispatched before it
|
||||||
|
// happened: the smallest difference seen is the nearest to that constant.
|
||||||
|
struct EventClock {
|
||||||
|
// `stamp` is the compositor's time of the event, 0 when it gave none; `hostNowMs` the host's clock now.
|
||||||
|
std::int64_t At(std::uint32_t stamp, std::int64_t hostNowMs) noexcept;
|
||||||
|
|
||||||
|
private:
|
||||||
|
std::uint32_t lastStamp = 0;
|
||||||
|
std::int64_t unwrapped = 0;
|
||||||
|
std::optional<std::int64_t> ahead; // the host's clock minus the unwrapped stamps
|
||||||
|
};
|
||||||
|
|
||||||
|
// The frames a screen owes the font atlas. A glyph that found no cell drew blank and gets one when a later frame
|
||||||
|
// begins, from the glyphs not drawn in the last `patience` frames (the frames in flight plus one), and a frame comes
|
||||||
|
// only when asked for: Again(waiting) after each frame asks for another while glyphs wait, until `patience` frames in
|
||||||
|
// a row gained no cell, when the screen needs more cells than the atlas holds. A change in the count (a gain, a
|
||||||
|
// screen change) starts the count over; Reset does on any other change of what is drawn.
|
||||||
|
struct FrameWait {
|
||||||
|
std::uint32_t patience = 4;
|
||||||
|
std::uint32_t last = 0; // the previous frame's waiting glyphs
|
||||||
|
std::uint32_t gainless = 0; // frames in a row that gained no cell
|
||||||
|
|
||||||
|
bool Again(std::uint32_t waiting) noexcept;
|
||||||
|
void Reset() noexcept;
|
||||||
|
};
|
||||||
|
}
|
||||||
82
interfaces/Nostro.Ui-Input.cppm
Normal file
82
interfaces/Nostro.Ui-Input.cppm
Normal file
|
|
@ -0,0 +1,82 @@
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
export module Nostro.Ui:Input;
|
||||||
|
|
||||||
|
import std;
|
||||||
|
import :Geometry;
|
||||||
|
|
||||||
|
// What the window tells the toolkit of the keyboard, and what the toolkit tells the window of the text field that
|
||||||
|
// has the focus, in terms of neither: the window's own key codes and the compositor's protocol stay on its side.
|
||||||
|
|
||||||
|
export namespace Nostro::Ui {
|
||||||
|
// The keys the toolkit acts on. A letter is the key that types it on the user's layout, not a place on the keyboard.
|
||||||
|
enum class Key : std::uint8_t {
|
||||||
|
None,
|
||||||
|
Enter,
|
||||||
|
Escape,
|
||||||
|
Tab,
|
||||||
|
Space,
|
||||||
|
Backspace,
|
||||||
|
Delete,
|
||||||
|
Left,
|
||||||
|
Right,
|
||||||
|
Up,
|
||||||
|
Down,
|
||||||
|
Home,
|
||||||
|
End,
|
||||||
|
PageUp,
|
||||||
|
PageDown,
|
||||||
|
F5,
|
||||||
|
A,
|
||||||
|
C,
|
||||||
|
F,
|
||||||
|
R,
|
||||||
|
V,
|
||||||
|
X
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Modifiers {
|
||||||
|
bool shift = false;
|
||||||
|
bool control = false;
|
||||||
|
friend bool operator==(const Modifiers&, const Modifiers&) = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
// What a text field holds, by which an on-screen keyboard picks its layout.
|
||||||
|
enum class TextPurpose : std::uint8_t {
|
||||||
|
Normal,
|
||||||
|
Digits, // a whole number
|
||||||
|
Number, // a number with a decimal separator
|
||||||
|
Phone,
|
||||||
|
Url,
|
||||||
|
Email,
|
||||||
|
Name,
|
||||||
|
Password
|
||||||
|
};
|
||||||
|
|
||||||
|
// How an input method treats what is typed, or-ed together. The values are text-input-v3's content hints, so the
|
||||||
|
// window passes them on as they are.
|
||||||
|
namespace TextHint {
|
||||||
|
inline constexpr std::uint32_t none = 0x0;
|
||||||
|
inline constexpr std::uint32_t completion = 0x1;
|
||||||
|
inline constexpr std::uint32_t spellcheck = 0x2;
|
||||||
|
inline constexpr std::uint32_t autoCapitalization = 0x4;
|
||||||
|
inline constexpr std::uint32_t lowercase = 0x8;
|
||||||
|
inline constexpr std::uint32_t hiddenText = 0x40; // show nothing of what is typed
|
||||||
|
inline constexpr std::uint32_t sensitiveData = 0x80; // store and learn nothing of it
|
||||||
|
inline constexpr std::uint32_t prose = completion | spellcheck | autoCapitalization;
|
||||||
|
inline constexpr std::uint32_t secret = hiddenText | sensitiveData;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The text field that has the focus, for the compositor's input method: whether there is one, where its caret is
|
||||||
|
// (an on-screen keyboard keeps clear of it), and what it holds. `field` tells one field from the next: when it
|
||||||
|
// changes, the input method starts afresh.
|
||||||
|
struct TextInputRequest {
|
||||||
|
bool active = false;
|
||||||
|
Box caret;
|
||||||
|
TextPurpose purpose = TextPurpose::Normal;
|
||||||
|
std::uint32_t hints = TextHint::none;
|
||||||
|
std::size_t field = 0;
|
||||||
|
friend bool operator==(const TextInputRequest&, const TextInputRequest&) = default;
|
||||||
|
};
|
||||||
|
}
|
||||||
73
interfaces/Nostro.Ui-Layout.cppm
Normal file
73
interfaces/Nostro.Ui-Layout.cppm
Normal file
|
|
@ -0,0 +1,73 @@
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
export module Nostro.Ui:Layout;
|
||||||
|
|
||||||
|
import std;
|
||||||
|
import :Geometry;
|
||||||
|
|
||||||
|
// Boxes handed out one after the other: all the layout a screen of rows and forms needs. A screen says how tall each
|
||||||
|
// thing is, or asks the thing itself, and the cursor moves on.
|
||||||
|
|
||||||
|
export namespace Nostro::Ui {
|
||||||
|
// Down a column: each box is as wide as the column and starts where the one before ended, plus the gap.
|
||||||
|
struct Column {
|
||||||
|
Box area;
|
||||||
|
float gap = 0;
|
||||||
|
float cursor = 0; // the top of the next box
|
||||||
|
|
||||||
|
constexpr Column(Box area, float gap = 0) noexcept : area(area), gap(gap), cursor(area.y) {
|
||||||
|
}
|
||||||
|
|
||||||
|
// The box the next thing may use: from the cursor down to the area's end.
|
||||||
|
constexpr Box Next() const noexcept {
|
||||||
|
return {area.x, cursor, area.w, std::max(0.0f, area.Bottom() - cursor)};
|
||||||
|
}
|
||||||
|
// The next thing turned out this tall.
|
||||||
|
constexpr void Advance(float height) noexcept {
|
||||||
|
cursor += height + gap;
|
||||||
|
}
|
||||||
|
// The next box, `height` tall. It may reach past the area's end: a column that scrolls is as long as its content.
|
||||||
|
constexpr Box Take(float height) noexcept {
|
||||||
|
const Box box{area.x, cursor, area.w, height};
|
||||||
|
Advance(height);
|
||||||
|
return box;
|
||||||
|
}
|
||||||
|
// How tall everything taken so far is, without the gap after the last.
|
||||||
|
constexpr float Used() const noexcept {
|
||||||
|
return std::max(0.0f, cursor - gap - area.y);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Along a row: boxes are taken from its left or its right end, and what is left between them is the rest.
|
||||||
|
struct Row {
|
||||||
|
Box area;
|
||||||
|
float gap = 0;
|
||||||
|
float left = 0;
|
||||||
|
float right = 0;
|
||||||
|
|
||||||
|
constexpr Row(Box area, float gap = 0) noexcept : area(area), gap(gap), left(area.x), right(area.Right()) {
|
||||||
|
}
|
||||||
|
|
||||||
|
constexpr Box TakeLeft(float width) noexcept {
|
||||||
|
const Box box{left, area.y, width, area.h};
|
||||||
|
left += width + gap;
|
||||||
|
return box;
|
||||||
|
}
|
||||||
|
constexpr Box TakeRight(float width) noexcept {
|
||||||
|
right -= width;
|
||||||
|
const Box box{right, area.y, width, area.h};
|
||||||
|
right -= gap;
|
||||||
|
return box;
|
||||||
|
}
|
||||||
|
constexpr Box Rest() const noexcept {
|
||||||
|
return {left, area.y, std::max(0.0f, right - left), area.h};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// A box at most `maxWidth` wide in the middle of an area's width: what keeps a form readable in a wide window.
|
||||||
|
constexpr Box Centered(Box area, float maxWidth) noexcept {
|
||||||
|
const float width = std::min(area.w, maxWidth);
|
||||||
|
return {area.x + (area.w - width) / 2, area.y, width, area.h};
|
||||||
|
}
|
||||||
|
}
|
||||||
74
interfaces/Nostro.Ui-Text.cppm
Normal file
74
interfaces/Nostro.Ui-Text.cppm
Normal file
|
|
@ -0,0 +1,74 @@
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
export module Nostro.Ui:Text;
|
||||||
|
|
||||||
|
import std;
|
||||||
|
import :Geometry;
|
||||||
|
|
||||||
|
// Text as the toolkit handles it: UTF-8 by code point, measured through a font the window supplies, wrapped and cut
|
||||||
|
// to a width. The window library shapes one line at a time and knows no line breaks, so the lines are broken here; and
|
||||||
|
// since the font's advances come through TextMeasure, the tests pass a constant one and know every offset and width.
|
||||||
|
|
||||||
|
export namespace Nostro::Ui {
|
||||||
|
// Which of the app's fonts a text is set in.
|
||||||
|
enum class FontFace : std::uint8_t {
|
||||||
|
Regular,
|
||||||
|
Medium, // the same family, heavier: titles, amounts, buttons
|
||||||
|
Icons // a symbol font: one code point is one icon
|
||||||
|
};
|
||||||
|
|
||||||
|
// The code point at text[i], advancing i past it: 0 at the end, U+FFFD for a malformed sequence (at least one byte
|
||||||
|
// consumed, so a loop always ends).
|
||||||
|
std::uint32_t DecodeUtf8(std::string_view text, std::size_t& i);
|
||||||
|
// The byte offset of the code point before `at`, and of the one after it; `at` at either end stays there.
|
||||||
|
std::size_t PreviousCodepoint(std::string_view text, std::size_t at);
|
||||||
|
std::size_t NextCodepoint(std::string_view text, std::size_t at);
|
||||||
|
std::size_t CountCodepoints(std::string_view text);
|
||||||
|
|
||||||
|
// A font's sizes at a size in pixels, as the window's fonts give them: how far a code point moves the pen, how far
|
||||||
|
// the baseline is below a line's top, and how far apart baselines are.
|
||||||
|
struct TextMeasure {
|
||||||
|
std::function<float(FontFace face, std::uint32_t codepoint, float px)> advance;
|
||||||
|
std::function<float(FontFace face, float px)> ascent;
|
||||||
|
std::function<float(FontFace face, float px)> lineHeight;
|
||||||
|
};
|
||||||
|
|
||||||
|
// A line's width as it is drawn: the font's advances as they are, none for a newline, so a caret or a run that
|
||||||
|
// follows lands where the glyphs end.
|
||||||
|
float TextWidth(const TextMeasure& measure, std::string_view text, FontFace face, float px);
|
||||||
|
// The byte offset in a line nearest to `x` pixels from its start, by the same widths: where a tap puts the cursor.
|
||||||
|
std::size_t NearestByte(const TextMeasure& measure, std::string_view line, FontFace face, float px, float x);
|
||||||
|
// The baseline that puts one line of text in the middle of a box's height.
|
||||||
|
float CenteredBaseline(const TextMeasure& measure, Box box, FontFace face, float px);
|
||||||
|
// The text that fits in the width, "…" in place of what was cut; a line break cuts too, since this is for one line.
|
||||||
|
std::string Ellipsize(const TextMeasure& measure, std::string_view text, FontFace face, float px, float maxWidthPx);
|
||||||
|
|
||||||
|
struct WrappedLine {
|
||||||
|
std::size_t begin = 0; // byte offsets into the text
|
||||||
|
std::size_t end = 0; // exclusive; a space or a newline broken at is not part of the line, a hyphen is
|
||||||
|
float width = 0;
|
||||||
|
friend bool operator==(const WrappedLine&, const WrappedLine&) = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Greedy word wrap: a break after a space or a hyphen, a hard break at '\n', a word wider than the line split
|
||||||
|
// between code points; the run of spaces where a line wraps goes to neither line. Results are kept per text, font,
|
||||||
|
// size and width, since a screen wraps the same texts every frame.
|
||||||
|
class WordWrapper {
|
||||||
|
public:
|
||||||
|
static constexpr std::size_t cacheLimit = 512;
|
||||||
|
|
||||||
|
explicit WordWrapper(TextMeasure measure);
|
||||||
|
|
||||||
|
// Valid until the next Wrap: a full cache is emptied.
|
||||||
|
const std::vector<WrappedLine>& Wrap(std::string_view text, FontFace face, float px, float maxWidthPx);
|
||||||
|
std::size_t CacheSize() const noexcept;
|
||||||
|
const TextMeasure& Measure() const noexcept;
|
||||||
|
|
||||||
|
private:
|
||||||
|
std::vector<WrappedLine> Compute(std::string_view text, FontFace face, float px, float maxWidthPx) const;
|
||||||
|
|
||||||
|
TextMeasure measure;
|
||||||
|
std::map<std::string, std::vector<WrappedLine>> cache;
|
||||||
|
};
|
||||||
|
}
|
||||||
66
interfaces/Nostro.Ui-Theme.cppm
Normal file
66
interfaces/Nostro.Ui-Theme.cppm
Normal file
|
|
@ -0,0 +1,66 @@
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
export module Nostro.Ui:Theme;
|
||||||
|
|
||||||
|
import std;
|
||||||
|
import :Geometry;
|
||||||
|
|
||||||
|
// The colours and sizes every widget draws with. The colours follow the system: light or dark, and its accent
|
||||||
|
// colour. The sizes are the design's (dp), turned into pixels where they are used.
|
||||||
|
|
||||||
|
export namespace Nostro::Ui {
|
||||||
|
struct Theme {
|
||||||
|
Color background{0.96f, 0.96f, 0.97f}; // behind everything
|
||||||
|
Color surface{1.0f, 1.0f, 1.0f}; // bars, cards, sheets, fields
|
||||||
|
Color surfaceAlt{0.93f, 0.93f, 0.94f}; // what stands out from a surface: a chip, a selected tab
|
||||||
|
Color text{0.11f, 0.11f, 0.12f};
|
||||||
|
Color muted{0.43f, 0.43f, 0.45f}; // secondary text
|
||||||
|
Color accent{0.18f, 0.44f, 0.93f};
|
||||||
|
Color onAccent{1.0f, 1.0f, 1.0f}; // text on the accent colour
|
||||||
|
Color divider{0.88f, 0.88f, 0.89f};
|
||||||
|
Color positive{0.10f, 0.53f, 0.25f}; // money coming in
|
||||||
|
Color warning{1.0f, 0.95f, 0.80f}; // a notice's ground
|
||||||
|
Color onWarning{0.40f, 0.30f, 0.01f};
|
||||||
|
Color danger{0.80f, 0.16f, 0.16f}; // an error, a step that cannot be undone
|
||||||
|
Color onDanger{1.0f, 1.0f, 1.0f};
|
||||||
|
Color scrim{0.0f, 0.0f, 0.0f, 0.35f}; // over what a sheet covers
|
||||||
|
bool dark = false;
|
||||||
|
|
||||||
|
static Theme Light();
|
||||||
|
static Theme Dark();
|
||||||
|
// The system's accent colour, with text on it dark or light as its brightness asks.
|
||||||
|
void Accent(Color color);
|
||||||
|
// A control's colour while the pointer is over it, and while it is pressed: tinted towards the text colour, so
|
||||||
|
// the change shows on a light theme and on a dark one.
|
||||||
|
Color Hovered(Color color) const;
|
||||||
|
Color Pressed(Color color) const;
|
||||||
|
// The one taken of a few choices that stand on the quiet ground: lighter than that ground, as what is raised
|
||||||
|
// from it would be, on a light theme and on a dark one.
|
||||||
|
Color Taken() const;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Text sizes, in dp.
|
||||||
|
namespace TextSize {
|
||||||
|
inline constexpr float display = 32; // a balance
|
||||||
|
inline constexpr float title = 22; // a screen's title
|
||||||
|
inline constexpr float heading = 18;
|
||||||
|
inline constexpr float body = 16;
|
||||||
|
inline constexpr float label = 14;
|
||||||
|
inline constexpr float caption = 12;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Distances, in dp.
|
||||||
|
namespace Size {
|
||||||
|
inline constexpr float unit = 4; // every gap is a multiple of it
|
||||||
|
inline constexpr float gutter = 16; // between content and the window's edge
|
||||||
|
inline constexpr float touch = 48; // the least a finger can hit
|
||||||
|
inline constexpr float control = 48; // a button's and a field's height
|
||||||
|
inline constexpr float row = 64; // a list row with two lines
|
||||||
|
inline constexpr float bar = 56; // the top and bottom bars
|
||||||
|
inline constexpr float radius = 12; // cards and sheets
|
||||||
|
inline constexpr float controlRadius = 8;
|
||||||
|
inline constexpr float contentMax = 640; // a form or a list does not grow wider than this
|
||||||
|
inline constexpr float pull = 64; // how far down a list is pulled before letting go reads it again
|
||||||
|
}
|
||||||
|
}
|
||||||
188
interfaces/Nostro.Ui-Widgets.cppm
Normal file
188
interfaces/Nostro.Ui-Widgets.cppm
Normal file
|
|
@ -0,0 +1,188 @@
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
export module Nostro.Ui:Widgets;
|
||||||
|
|
||||||
|
import std;
|
||||||
|
import :Geometry;
|
||||||
|
import :Text;
|
||||||
|
import :Edit;
|
||||||
|
import :Draw;
|
||||||
|
import :Theme;
|
||||||
|
import :Input;
|
||||||
|
import :Context;
|
||||||
|
|
||||||
|
// What a screen is built from. Each widget is a function: given a frame and a box, it draws itself there and names
|
||||||
|
// the regions that can be pressed. It keeps nothing; what must outlive the frame (a field's text, the focus, a
|
||||||
|
// list's position) is the caller's or the Context's. Sizes are the design's, turned into pixels by the frame.
|
||||||
|
|
||||||
|
export namespace Nostro::Ui {
|
||||||
|
struct TextStyle {
|
||||||
|
FontFace face = FontFace::Regular;
|
||||||
|
float sizeDp = TextSize::body;
|
||||||
|
Color color;
|
||||||
|
TextAlign align = TextAlign::Left;
|
||||||
|
};
|
||||||
|
|
||||||
|
// The styles most text is set in, in the frame's colours.
|
||||||
|
TextStyle Body(const Frame& frame);
|
||||||
|
TextStyle Strong(const Frame& frame); // the body's size, heavier
|
||||||
|
TextStyle Muted(const Frame& frame); // secondary text, a size down
|
||||||
|
TextStyle Caption(const Frame& frame);
|
||||||
|
TextStyle Heading(const Frame& frame);
|
||||||
|
|
||||||
|
// One line in the middle of the box's height, cut with an ellipsis where it does not fit. A Center or Right
|
||||||
|
// alignment sets it against the box's middle or its right edge.
|
||||||
|
void Label(Frame& frame, Box box, std::string_view text, const TextStyle& style);
|
||||||
|
// Text wrapped to the box's width from its top; returns how tall it came out, whatever the box's height.
|
||||||
|
float Paragraph(Frame& frame, Box box, std::string_view text, const TextStyle& style);
|
||||||
|
float ParagraphHeight(Frame& frame, float width, std::string_view text, const TextStyle& style);
|
||||||
|
|
||||||
|
enum class ButtonKind : std::uint8_t {
|
||||||
|
Filled, // the one thing to do here
|
||||||
|
Tonal, // another thing to do
|
||||||
|
Plain, // text alone: an action in a bar or beside a button
|
||||||
|
Danger // a step that cannot be undone
|
||||||
|
};
|
||||||
|
|
||||||
|
struct ButtonOptions {
|
||||||
|
std::string key;
|
||||||
|
std::string label;
|
||||||
|
ButtonKind kind = ButtonKind::Filled;
|
||||||
|
bool enabled = true;
|
||||||
|
std::function<void()> onTap;
|
||||||
|
};
|
||||||
|
// Drawn in the box. The area that takes a press is the box and, for one lower than a finger needs, as much above
|
||||||
|
// and below it as makes up for that: leave that room between two of them.
|
||||||
|
void Button(Frame& frame, Box box, const ButtonOptions& options);
|
||||||
|
// How wide a button is at least, for its label.
|
||||||
|
float ButtonWidth(const Frame& frame, std::string_view label);
|
||||||
|
|
||||||
|
struct RowOptions {
|
||||||
|
std::string key;
|
||||||
|
std::string title;
|
||||||
|
std::string subtitle; // a second line, muted
|
||||||
|
std::string trailing; // at the right: an amount
|
||||||
|
std::string trailingSub; // under it: a date
|
||||||
|
std::optional<Color> trailingColor;
|
||||||
|
std::string badge; // a small mark after the title: "Sandbox"
|
||||||
|
std::optional<bool> selected; // a choice among rows, drawn as a radio button
|
||||||
|
bool chevron = false; // leads somewhere
|
||||||
|
bool enabled = true;
|
||||||
|
bool divider = true;
|
||||||
|
std::function<void()> onTap;
|
||||||
|
std::function<void()> onLongPress;
|
||||||
|
};
|
||||||
|
void ListRow(Frame& frame, Box box, const RowOptions& options);
|
||||||
|
|
||||||
|
struct ValueOptions {
|
||||||
|
std::string key;
|
||||||
|
std::string label;
|
||||||
|
std::string value;
|
||||||
|
float labelWidth = 112; // the room the label has before the value, in dp
|
||||||
|
std::function<void()> onTap; // nothing: it is only read
|
||||||
|
std::function<void()> onLongPress;
|
||||||
|
};
|
||||||
|
// A label and beside it what it stands for, wrapped to the room there is: a line of a sheet that says what
|
||||||
|
// something is. With an action it is a row that can be pressed, a finger tall in a window as narrow as a phone and
|
||||||
|
// closer to the next under a pointer. The text keeps clear of the box's sides, which a press is drawn up to. Drawn
|
||||||
|
// at the box's top and as wide as it; returns how tall it came out, which ValueRowHeight says beforehand.
|
||||||
|
float ValueRow(Frame& frame, Box box, const ValueOptions& options);
|
||||||
|
float ValueRowHeight(Frame& frame, float width, const ValueOptions& options);
|
||||||
|
|
||||||
|
struct FieldOptions {
|
||||||
|
std::string key;
|
||||||
|
std::string label;
|
||||||
|
std::string placeholder;
|
||||||
|
std::string prefix; // before the text, inside the field: a currency's symbol
|
||||||
|
std::string error; // under the field, in place of the helper
|
||||||
|
std::string helper;
|
||||||
|
std::optional<TextPurpose> purpose; // by default what the field's kind asks for
|
||||||
|
std::optional<std::uint32_t> hints;
|
||||||
|
bool enabled = true;
|
||||||
|
std::function<void()> onChange;
|
||||||
|
std::function<void()> onSubmit;
|
||||||
|
};
|
||||||
|
// A text field with its label above and its error or helper below, at the box's top and as wide as it; returns how
|
||||||
|
// tall it came out.
|
||||||
|
float TextField(Frame& frame, Box box, EditState& edit, const FieldOptions& options);
|
||||||
|
// How tall a field with these options comes out in a box that wide, for what must know before it is drawn.
|
||||||
|
float FieldHeight(Frame& frame, float width, const FieldOptions& options);
|
||||||
|
|
||||||
|
struct ChoiceOptions {
|
||||||
|
std::string key;
|
||||||
|
std::vector<std::string> labels;
|
||||||
|
std::size_t selected = 0;
|
||||||
|
bool enabled = true;
|
||||||
|
std::function<void(std::size_t)> onSelect;
|
||||||
|
};
|
||||||
|
// A few choices side by side, one of them taken: a box of segments.
|
||||||
|
void Segmented(Frame& frame, Box box, const ChoiceOptions& options);
|
||||||
|
// The sections of a screen, one of them shown: a strip with a line under the one that is.
|
||||||
|
void Tabs(Frame& frame, Box box, const ChoiceOptions& options);
|
||||||
|
|
||||||
|
enum class BannerKind : std::uint8_t {
|
||||||
|
Info,
|
||||||
|
Warning,
|
||||||
|
Error
|
||||||
|
};
|
||||||
|
|
||||||
|
struct BannerOptions {
|
||||||
|
std::string key;
|
||||||
|
BannerKind kind = BannerKind::Info;
|
||||||
|
std::string text;
|
||||||
|
std::string action; // a thing to do about it
|
||||||
|
std::function<void()> onAction;
|
||||||
|
std::function<void()> onDismiss; // nothing: it cannot be closed
|
||||||
|
};
|
||||||
|
// A notice across the box's width at its top; returns how tall it came out.
|
||||||
|
float Banner(Frame& frame, Box box, const BannerOptions& options);
|
||||||
|
|
||||||
|
// A small rounded mark: a status. ChipWidth is how wide it comes out.
|
||||||
|
void Chip(Frame& frame, Box box, std::string_view text, Color ground, Color color);
|
||||||
|
float ChipWidth(const Frame& frame, std::string_view text);
|
||||||
|
// A line along the box's bottom edge.
|
||||||
|
void Divider(Frame& frame, Box box);
|
||||||
|
// The ground where something is still being fetched: a bar of the box's width, less for a `fraction` under 1.
|
||||||
|
void Skeleton(Frame& frame, Box box, float fraction = 1.0f);
|
||||||
|
|
||||||
|
struct BarAction {
|
||||||
|
std::string key;
|
||||||
|
std::string label;
|
||||||
|
bool enabled = true;
|
||||||
|
std::function<void()> onTap;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct TopBarOptions {
|
||||||
|
std::string title;
|
||||||
|
std::function<void()> onBack; // nothing: no way back from here
|
||||||
|
std::vector<BarAction> actions;
|
||||||
|
};
|
||||||
|
// The bar along an area's top; returns the area under it.
|
||||||
|
Box TopBar(Frame& frame, Box area, const TopBarOptions& options);
|
||||||
|
|
||||||
|
struct NavItem {
|
||||||
|
std::string key;
|
||||||
|
std::string label;
|
||||||
|
std::string detail; // beside the label, where there is room: a balance
|
||||||
|
bool selected = false;
|
||||||
|
bool header = false; // names a group, and cannot be pressed
|
||||||
|
std::function<void()> onTap;
|
||||||
|
};
|
||||||
|
// The app's places along an area's bottom, for a window as narrow as a phone; returns the area above it.
|
||||||
|
Box NavBar(Frame& frame, Box area, std::span<const NavItem> items);
|
||||||
|
// The same down an area's left side, `widthDp` wide, for a wider window; returns the area beside it.
|
||||||
|
Box Sidebar(Frame& frame, Box area, float widthDp, std::span<const NavItem> items);
|
||||||
|
|
||||||
|
struct SheetOptions {
|
||||||
|
std::string key;
|
||||||
|
std::string title;
|
||||||
|
float contentHeight = 0; // how tall the body wants to be, in pixels
|
||||||
|
std::function<void()> onDismiss; // a tap beside it, or Escape
|
||||||
|
};
|
||||||
|
// What is asked or shown over a screen: a sheet from the bottom edge in a narrow window, a dialog in the middle of a
|
||||||
|
// wider one, with what it covers dimmed and out of reach. `body` draws into the box it is given.
|
||||||
|
void Sheet(Frame& frame, const SheetOptions& options, const std::function<void(Box)>& body);
|
||||||
|
// How wide the box is that a sheet gives its body in this frame, for working out how tall the body wants to be.
|
||||||
|
float SheetBodyWidth(const Frame& frame);
|
||||||
|
}
|
||||||
157
interfaces/Nostro.Ui.Shell-Canvas.cppm
Normal file
157
interfaces/Nostro.Ui.Shell-Canvas.cppm
Normal file
|
|
@ -0,0 +1,157 @@
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
module;
|
||||||
|
#include "vulkan/vulkan.h"
|
||||||
|
export module Nostro.Ui.Shell:Canvas;
|
||||||
|
|
||||||
|
import std;
|
||||||
|
import Crafter.Graphics;
|
||||||
|
import Crafter.Event;
|
||||||
|
import Nostro.Ui;
|
||||||
|
|
||||||
|
// The window and what turns a frame's draw list into what the window library draws. The library draws from compute
|
||||||
|
// shaders, one pass over the whole window per dispatch, in which every box comes before every glyph and everything is
|
||||||
|
// cut to one box: that is a Batch of the draw list, so a frame is one dispatch per batch, in the list's order. A
|
||||||
|
// dispatch reads its items from buffers of its own, from their start, so each batch needs a pair of buffers, and a
|
||||||
|
// frame still on the GPU reads its buffers as it runs, so each frame in flight has a set of pairs: a pool, made once.
|
||||||
|
|
||||||
|
export namespace Nostro::Ui::Shell {
|
||||||
|
// The app's fonts. They are read from files and measured without a window, so the toolkit's Context, which
|
||||||
|
// measures every text through them, is made before the window and may outlive it.
|
||||||
|
class Fonts {
|
||||||
|
public:
|
||||||
|
// Reads NotoSans-Regular.ttf and NotoSans-Medium.ttf from the directory; throws when one is not there.
|
||||||
|
explicit Fonts(const std::filesystem::path& directory);
|
||||||
|
Fonts(const Fonts&) = delete;
|
||||||
|
Fonts& operator=(const Fonts&) = delete;
|
||||||
|
|
||||||
|
Crafter::Font& Face(FontFace face) noexcept;
|
||||||
|
// The fonts' sizes for the toolkit; good for as long as the fonts are.
|
||||||
|
TextMeasure Measure();
|
||||||
|
|
||||||
|
private:
|
||||||
|
Crafter::Font regular;
|
||||||
|
Crafter::Font medium;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct CanvasOptions {
|
||||||
|
// The window's size where the compositor leaves it to the app, as a desktop does and a phone does not.
|
||||||
|
std::uint32_t widthDp = 1024;
|
||||||
|
std::uint32_t heightDp = 720;
|
||||||
|
std::string title;
|
||||||
|
std::string appId; // what the compositor finds the desktop file, and so the icon, by
|
||||||
|
std::filesystem::path assets; // where the window library's shaders are
|
||||||
|
std::filesystem::path cache; // where compiled shaders are kept between runs
|
||||||
|
// For looking at another kind of display than the one at hand, a phone's on a desktop: everything is drawn as
|
||||||
|
// at this scale, in a window of the size above times it in pixels, whatever the display's own scale is and
|
||||||
|
// whatever size the compositor asks for.
|
||||||
|
std::optional<float> scale;
|
||||||
|
};
|
||||||
|
|
||||||
|
class Canvas {
|
||||||
|
public:
|
||||||
|
// Sets the graphics device up, once per process, and makes the window. Throws when there is no compositor to
|
||||||
|
// connect to, no graphics device that can draw, or a shader is missing.
|
||||||
|
Canvas(Fonts& fonts, const CanvasOptions& options);
|
||||||
|
// Waits for the frames still being drawn, then lets go of everything.
|
||||||
|
~Canvas();
|
||||||
|
Canvas(const Canvas&) = delete;
|
||||||
|
Canvas& operator=(const Canvas&) = delete;
|
||||||
|
|
||||||
|
Crafter::Window& Native() noexcept;
|
||||||
|
const Crafter::Window& Native() const noexcept;
|
||||||
|
// How many pixels a dp is: the scale of the display the window is on, or the one it was told to draw at.
|
||||||
|
float Scale() const noexcept;
|
||||||
|
// The window, in pixels.
|
||||||
|
Box Bounds() const noexcept;
|
||||||
|
// Gives the window the size it should have at the display's scale, where the window library has not: the size
|
||||||
|
// the compositor asked for last, or the app's own until it asks for one. The library passes over the size that
|
||||||
|
// comes with a new window, which is the whole screen on a phone, and applies a new scale only with the next
|
||||||
|
// new size. True when the size changed, which the library says through onResize too.
|
||||||
|
bool Reconcile();
|
||||||
|
// Asks for another size, in dp: the window takes it at the next Reconcile, and keeps it until the compositor
|
||||||
|
// asks for one of its own, which a compositor that tiles or maximises the window does at once.
|
||||||
|
void SetSize(std::uint32_t widthDp, std::uint32_t heightDp) noexcept;
|
||||||
|
// Draws one frame: the list over the background colour. Throws what the window library does at a graphics
|
||||||
|
// error, after which the window draws nothing more.
|
||||||
|
void Render(const DrawList& list, Color background);
|
||||||
|
// The next frame is also written to this file, as a PNG.
|
||||||
|
void Capture(const std::filesystem::path& png);
|
||||||
|
|
||||||
|
// What the last frame took, for whoever watches the pool: a frame that needed more than there is drew less
|
||||||
|
// than it was given.
|
||||||
|
struct Stats {
|
||||||
|
std::uint32_t batches = 0;
|
||||||
|
std::uint32_t boxes = 0;
|
||||||
|
std::uint32_t glyphs = 0;
|
||||||
|
std::uint32_t glyphsWaiting = 0; // drawn blank for want of a cell in the font atlas: there after a later frame
|
||||||
|
bool overflowed = false;
|
||||||
|
};
|
||||||
|
const Stats& Last() const noexcept;
|
||||||
|
std::uint64_t Frames() const noexcept;
|
||||||
|
// The graphics device's name, and how it reaches what it draws: for a log.
|
||||||
|
std::string Device() const;
|
||||||
|
|
||||||
|
// The frames a glyph without a cell waits at most: the frames in flight and one.
|
||||||
|
static constexpr std::uint32_t atlasPatience = Crafter::Window::numFrames + 1;
|
||||||
|
|
||||||
|
private:
|
||||||
|
// A batch's buffers: boxes (circles are boxes with round corners) and glyphs.
|
||||||
|
struct Pair {
|
||||||
|
Crafter::GraphicsBuffer<Crafter::QuadItem, true> boxes;
|
||||||
|
Crafter::GraphicsBuffer<Crafter::GlyphItem, true> glyphs;
|
||||||
|
std::optional<Crafter::BufferSlot> boxSlot;
|
||||||
|
std::optional<Crafter::BufferSlot> glyphSlot;
|
||||||
|
std::uint32_t boxCap = 0;
|
||||||
|
std::uint32_t glyphCap = 0;
|
||||||
|
};
|
||||||
|
// Most batches are a bar or a sheet; a list is one batch of many items. So a frame has many small pairs and a
|
||||||
|
// few large ones.
|
||||||
|
static constexpr std::uint32_t smallPairs = 20;
|
||||||
|
static constexpr std::uint32_t smallBoxes = 128;
|
||||||
|
static constexpr std::uint32_t smallGlyphs = 1024;
|
||||||
|
static constexpr std::uint32_t largePairs = 4;
|
||||||
|
static constexpr std::uint32_t largeBoxes = 2048;
|
||||||
|
static constexpr std::uint32_t largeGlyphs = 8192;
|
||||||
|
struct FrameSet {
|
||||||
|
std::vector<Pair> small;
|
||||||
|
std::vector<Pair> large;
|
||||||
|
std::size_t smallUsed = 0;
|
||||||
|
std::size_t largeUsed = 0;
|
||||||
|
};
|
||||||
|
// In the order they are made, which is the reverse of the order they go in: the pairs hand their slots back to
|
||||||
|
// the heap, the renderer holds slots of its own, and the heap holds a view of the atlas's image.
|
||||||
|
struct Parts {
|
||||||
|
Parts(std::uint32_t width, std::uint32_t height, std::string_view title);
|
||||||
|
|
||||||
|
Crafter::Window window;
|
||||||
|
Crafter::FontAtlas atlas;
|
||||||
|
Crafter::GraphicsDescriptorHeap heap;
|
||||||
|
Crafter::UIRenderer renderer;
|
||||||
|
std::optional<Crafter::EventListener<Crafter::UIBuildArgs>> build;
|
||||||
|
std::array<FrameSet, Crafter::Window::numFrames> pool;
|
||||||
|
};
|
||||||
|
|
||||||
|
void Release() noexcept;
|
||||||
|
void MakePairs(std::vector<Pair>& pairs, std::uint32_t count, std::uint32_t boxCap, std::uint32_t glyphCap);
|
||||||
|
void Build(VkCommandBuffer commands, std::uint32_t frameIndex);
|
||||||
|
// One dispatch: the batch, over `under` when there is one.
|
||||||
|
void Submit(VkCommandBuffer commands, FrameSet& set, const Batch& batch, const RectItem* under = nullptr);
|
||||||
|
Pair* Take(FrameSet& set, std::size_t boxes, std::size_t glyphs) noexcept;
|
||||||
|
|
||||||
|
Fonts& fonts;
|
||||||
|
// The size the window should have, in the compositor's units, and the size the compositor was last seen to ask
|
||||||
|
// for, (0, 0) when it left the choice to the app.
|
||||||
|
std::int32_t logicalWidth;
|
||||||
|
std::int32_t logicalHeight;
|
||||||
|
std::int32_t askedWidth = 0;
|
||||||
|
std::int32_t askedHeight = 0;
|
||||||
|
std::optional<float> pretend; // CanvasOptions::scale
|
||||||
|
std::optional<Parts> parts;
|
||||||
|
const DrawList* drawing = nullptr; // the list of the frame being drawn
|
||||||
|
Color background;
|
||||||
|
Stats stats;
|
||||||
|
std::uint64_t frames = 0;
|
||||||
|
};
|
||||||
|
}
|
||||||
164
interfaces/Nostro.Ui.Shell-Loop.cppm
Normal file
164
interfaces/Nostro.Ui.Shell-Loop.cppm
Normal file
|
|
@ -0,0 +1,164 @@
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
module;
|
||||||
|
#include <systemd/sd-event.h>
|
||||||
|
#include <wayland-client.h>
|
||||||
|
export module Nostro.Ui.Shell:Loop;
|
||||||
|
|
||||||
|
import std;
|
||||||
|
|
||||||
|
// One thread and one sd-event loop serve everything the app waits for: the compositor, nostrod's answers on the
|
||||||
|
// system bus, the portal on the session bus, and every timer. The window library's own loop (Window::StartSync) serves
|
||||||
|
// the compositor alone and would starve the buses, so the Wayland display is a source of this loop instead, and the
|
||||||
|
// app asks for its own frames: a frame is drawn when the compositor says the window is about to be shown, and only
|
||||||
|
// when something asked for one. An idle window, a hidden one and a locked phone draw nothing.
|
||||||
|
//
|
||||||
|
// A callback sd-event or libwayland calls must not throw: the exception would unwind through C. Every callback here
|
||||||
|
// runs through Loop::Guard, which turns what is thrown into a line on stderr and the loop's end with status 1.
|
||||||
|
|
||||||
|
export namespace Nostro::Ui::Shell {
|
||||||
|
// The clock timers are set by and frames are dated with: milliseconds, monotonic.
|
||||||
|
std::int64_t NowMs() noexcept;
|
||||||
|
|
||||||
|
class Loop {
|
||||||
|
public:
|
||||||
|
// Blocks SIGINT and SIGTERM for the process, which is why a Loop is made before anything starts a thread, and
|
||||||
|
// ends the loop with status 0 when one arrives.
|
||||||
|
Loop();
|
||||||
|
~Loop();
|
||||||
|
Loop(const Loop&) = delete;
|
||||||
|
Loop& operator=(const Loop&) = delete;
|
||||||
|
|
||||||
|
sd_event* Event() const noexcept;
|
||||||
|
// Runs until Exit; returns what Exit was given.
|
||||||
|
std::int32_t Run();
|
||||||
|
void Exit(std::int32_t status) noexcept;
|
||||||
|
// Runs `body`. What it throws is said on stderr, with `what` for what was being done, and ends the loop.
|
||||||
|
void Guard(std::string_view what, const std::function<void()>& body) noexcept;
|
||||||
|
|
||||||
|
// Called after every source of the loop that ran, whoever's it was, before the loop waits again: where the
|
||||||
|
// window looks at what the callbacks left to do.
|
||||||
|
std::function<void()> onSettle;
|
||||||
|
// Where Guard says what was thrown; stderr without one.
|
||||||
|
std::function<void(std::string_view line)> onError;
|
||||||
|
|
||||||
|
private:
|
||||||
|
static std::int32_t OnPost(sd_event_source* source, void* data);
|
||||||
|
void Failed(std::string_view line) noexcept;
|
||||||
|
|
||||||
|
sd_event* event = nullptr;
|
||||||
|
sd_event_source* post = nullptr;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Calls back once at a time on the loop's clock, until it is set again.
|
||||||
|
class Timer {
|
||||||
|
public:
|
||||||
|
Timer(Loop& loop, std::function<void()> fire);
|
||||||
|
~Timer();
|
||||||
|
Timer(const Timer&) = delete;
|
||||||
|
Timer& operator=(const Timer&) = delete;
|
||||||
|
|
||||||
|
// At that time by NowMs, at once when it has passed; replaces the time set before.
|
||||||
|
void At(std::int64_t ms);
|
||||||
|
void After(std::int64_t ms);
|
||||||
|
void Cancel() noexcept;
|
||||||
|
bool Armed() const noexcept;
|
||||||
|
|
||||||
|
private:
|
||||||
|
static std::int32_t OnTime(sd_event_source* source, std::uint64_t usec, void* data);
|
||||||
|
|
||||||
|
Loop& loop;
|
||||||
|
std::function<void()> fire;
|
||||||
|
sd_event_source* source = nullptr;
|
||||||
|
bool armed = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Calls back once from the loop itself, soon: for what must not run inside the callback that asks for it.
|
||||||
|
class Defer {
|
||||||
|
public:
|
||||||
|
Defer(Loop& loop, std::function<void()> run);
|
||||||
|
~Defer();
|
||||||
|
Defer(const Defer&) = delete;
|
||||||
|
Defer& operator=(const Defer&) = delete;
|
||||||
|
|
||||||
|
void Schedule() noexcept;
|
||||||
|
void Cancel() noexcept;
|
||||||
|
|
||||||
|
private:
|
||||||
|
static std::int32_t OnDefer(sd_event_source* source, void* data);
|
||||||
|
|
||||||
|
Loop& loop;
|
||||||
|
std::function<void()> run;
|
||||||
|
sd_event_source* source = nullptr;
|
||||||
|
};
|
||||||
|
|
||||||
|
// The compositor's connection as a source of the loop.
|
||||||
|
//
|
||||||
|
// libwayland wants a reader to announce itself (prepare_read), wait for the socket, and then read or step back, and
|
||||||
|
// two readers on one thread deadlock: the second waits for the first to read. The window library and the Vulkan
|
||||||
|
// driver both read the display themselves, from inside this thread's callbacks (a clipboard read, a swapchain
|
||||||
|
// waiting for the compositor). So no announced read here outlives a callback: when the socket is readable, one
|
||||||
|
// callback announces, reads and dispatches; and before the loop waits, what such a foreign read left queued for
|
||||||
|
// this thread is dispatched and what was written is sent.
|
||||||
|
class WaylandSource {
|
||||||
|
public:
|
||||||
|
WaylandSource(Loop& loop, wl_display* display);
|
||||||
|
~WaylandSource();
|
||||||
|
WaylandSource(const WaylandSource&) = delete;
|
||||||
|
WaylandSource& operator=(const WaylandSource&) = delete;
|
||||||
|
|
||||||
|
// The connection broke, which a process cannot mend: called once, and the source stops.
|
||||||
|
std::function<void()> onLost;
|
||||||
|
|
||||||
|
// Reads and dispatches what the compositor has already sent, without waiting for more: for a timer that must
|
||||||
|
// not get ahead of an event that is waiting to be read.
|
||||||
|
void Pump();
|
||||||
|
|
||||||
|
private:
|
||||||
|
static std::int32_t OnPrepare(sd_event_source* source, void* data);
|
||||||
|
static std::int32_t OnReady(sd_event_source* source, std::int32_t fd, std::uint32_t revents, void* data);
|
||||||
|
static std::int32_t OnNudge(sd_event_source* source, void* data);
|
||||||
|
void Flush();
|
||||||
|
void Lost();
|
||||||
|
|
||||||
|
Loop& loop;
|
||||||
|
wl_display* display;
|
||||||
|
sd_event_source* source = nullptr;
|
||||||
|
sd_event_source* nudge = nullptr; // a source that does nothing, for the loop to go round once more
|
||||||
|
bool writing = false; // the socket was full: its room to write is waited for too
|
||||||
|
bool lost = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Frames when the compositor wants them: a request is a frame callback and a commit that changes nothing else, the
|
||||||
|
// compositor's answer draws one frame, and nothing asks again unless something changed meanwhile or is moving. A
|
||||||
|
// surface that is not shown is never answered, so it draws nothing.
|
||||||
|
class FrameDriver {
|
||||||
|
public:
|
||||||
|
FrameDriver(Loop& loop, wl_surface* surface);
|
||||||
|
~FrameDriver();
|
||||||
|
FrameDriver(const FrameDriver&) = delete;
|
||||||
|
FrameDriver& operator=(const FrameDriver&) = delete;
|
||||||
|
|
||||||
|
// Draws one frame.
|
||||||
|
std::function<void()> onFrame;
|
||||||
|
|
||||||
|
// A frame as soon as the compositor allows one.
|
||||||
|
void RequestRedraw();
|
||||||
|
// Frames keep coming while on: something on the screen is moving.
|
||||||
|
void SetAnimating(bool on);
|
||||||
|
bool Animating() const noexcept;
|
||||||
|
// Whether a request is out that the compositor has not answered.
|
||||||
|
bool Waiting() const noexcept;
|
||||||
|
|
||||||
|
private:
|
||||||
|
static void OnDone(void* data, wl_callback* callback, std::uint32_t time);
|
||||||
|
static constexpr wl_callback_listener listener = {OnDone};
|
||||||
|
|
||||||
|
Loop& loop;
|
||||||
|
wl_surface* surface;
|
||||||
|
wl_callback* pending = nullptr;
|
||||||
|
bool dirty = false;
|
||||||
|
bool animating = false;
|
||||||
|
};
|
||||||
|
}
|
||||||
65
interfaces/Nostro.Ui.Shell-Portal.cppm
Normal file
65
interfaces/Nostro.Ui.Shell-Portal.cppm
Normal file
|
|
@ -0,0 +1,65 @@
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
module;
|
||||||
|
#include <systemd/sd-bus.h>
|
||||||
|
export module Nostro.Ui.Shell:Portal;
|
||||||
|
|
||||||
|
import std;
|
||||||
|
import Nostro.Ui;
|
||||||
|
import :Loop;
|
||||||
|
|
||||||
|
// The desktop portal on the session bus, for what an app in a sandbox may ask of the desktop without a permission of
|
||||||
|
// its own: how the system looks (dark or light, and its accent colour), and opening an address in the user's browser.
|
||||||
|
// Without a session bus or a portal nothing is known and nothing opens, and the app goes on as it is.
|
||||||
|
|
||||||
|
export namespace Nostro::Ui::Shell {
|
||||||
|
struct Appearance {
|
||||||
|
bool known = false; // the portal gave a colour scheme
|
||||||
|
bool dark = false;
|
||||||
|
std::optional<Color> accent; // none: the system has no accent colour, or says none
|
||||||
|
friend bool operator==(const Appearance&, const Appearance&) = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
class Portal {
|
||||||
|
public:
|
||||||
|
// Connects to the session bus and reads the appearance, waiting up to `patience` for the portal's answer: a
|
||||||
|
// window drawn before it would open light and turn dark. An answer that comes later is told as a change.
|
||||||
|
explicit Portal(Loop& loop, std::chrono::milliseconds patience = std::chrono::milliseconds(1000));
|
||||||
|
~Portal();
|
||||||
|
Portal(const Portal&) = delete;
|
||||||
|
Portal& operator=(const Portal&) = delete;
|
||||||
|
|
||||||
|
bool Connected() const noexcept;
|
||||||
|
const Appearance& Current() const noexcept;
|
||||||
|
// The appearance changed, or was learnt after the start.
|
||||||
|
std::function<void(const Appearance&)> onAppearance;
|
||||||
|
|
||||||
|
// Asks the desktop to open an address with the user's own program for it. `then` hears whether the desktop
|
||||||
|
// took the request, from the loop; it hears false at once when there is no portal to ask.
|
||||||
|
void OpenUri(std::string_view uri, std::function<void(bool taken)> then);
|
||||||
|
|
||||||
|
private:
|
||||||
|
static std::int32_t OnSettings(sd_bus_message* reply, void* data, sd_bus_error* error);
|
||||||
|
static std::int32_t OnChanged(sd_bus_message* signal, void* data, sd_bus_error* error);
|
||||||
|
static std::int32_t OnOpened(sd_bus_message* reply, void* data, sd_bus_error* error);
|
||||||
|
// Takes ReadAll's answer in; true when it changed what is known.
|
||||||
|
bool TakeSettings(sd_bus_message* reply);
|
||||||
|
bool TakeSetting(std::string_view key, sd_bus_message* value);
|
||||||
|
void Told();
|
||||||
|
|
||||||
|
struct Opening {
|
||||||
|
Portal* portal = nullptr;
|
||||||
|
std::function<void(bool)> then;
|
||||||
|
sd_bus_slot* slot = nullptr;
|
||||||
|
};
|
||||||
|
|
||||||
|
Loop& loop;
|
||||||
|
sd_bus* bus = nullptr;
|
||||||
|
sd_bus_slot* changed = nullptr;
|
||||||
|
sd_bus_slot* late = nullptr; // a ReadAll the start did not wait out
|
||||||
|
std::list<Opening> openings;
|
||||||
|
Appearance current;
|
||||||
|
bool answered = false; // ReadAll's answer came, whatever it was
|
||||||
|
};
|
||||||
|
}
|
||||||
118
interfaces/Nostro.Ui.Shell-Window.cppm
Normal file
118
interfaces/Nostro.Ui.Shell-Window.cppm
Normal file
|
|
@ -0,0 +1,118 @@
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
export module Nostro.Ui.Shell:Window;
|
||||||
|
|
||||||
|
import std;
|
||||||
|
import Crafter.Graphics;
|
||||||
|
import Crafter.Event;
|
||||||
|
import Nostro.Ui;
|
||||||
|
import :Loop;
|
||||||
|
import :Canvas;
|
||||||
|
|
||||||
|
// The app's window: a toolkit Context shown on a Canvas and fed from it. What the compositor reports of the pointer,
|
||||||
|
// the fingers, the keys and the input method becomes the Context's events, in pixels and key names; what the Context
|
||||||
|
// wants of the window afterwards (a frame, a timer, the on-screen keyboard, the clipboard) is done here. Nothing in
|
||||||
|
// here knows what the screens are: they are built through onBuild.
|
||||||
|
//
|
||||||
|
// Three rules hold it together. An event acts on a frame that is true: before one is handed on, time is brought up to
|
||||||
|
// it and a frame that went stale is built again. A frame is drawn only when the compositor asks for one, after
|
||||||
|
// something changed. And what cannot be done inside a listener waits for the loop: the clipboard is read from there.
|
||||||
|
|
||||||
|
export namespace Nostro::Ui::Shell {
|
||||||
|
class Window {
|
||||||
|
public:
|
||||||
|
// Makes the window; throws what Canvas does. Nothing is drawn before Start.
|
||||||
|
Window(Loop& loop, Context& context, Fonts& fonts, const CanvasOptions& options);
|
||||||
|
~Window();
|
||||||
|
Window(const Window&) = delete;
|
||||||
|
Window& operator=(const Window&) = delete;
|
||||||
|
|
||||||
|
// Builds the screens into a frame. Called for every frame drawn, and whenever an event needs a true one.
|
||||||
|
std::function<void(Frame&)> onBuild;
|
||||||
|
// The user closed the window. Called from inside the compositor's events: whoever takes the window down for it
|
||||||
|
// does so from the loop, not from here.
|
||||||
|
std::function<void()> onClose;
|
||||||
|
// The window can draw no more, and why: a graphics error in a frame, or the compositor's connection gone.
|
||||||
|
// Nothing is drawn on it from here.
|
||||||
|
std::function<void(std::string_view why)> onFailed;
|
||||||
|
// A frame was drawn.
|
||||||
|
std::function<void()> onFrame;
|
||||||
|
// A line for whoever keeps a log.
|
||||||
|
std::function<void(std::string_view line)> onLog;
|
||||||
|
|
||||||
|
// Draws the first frame, which shows the window. Throws when it cannot be drawn.
|
||||||
|
void Start();
|
||||||
|
// Looks at what the Context wants since the last time and does it. The loop calls this after every source
|
||||||
|
// that ran (Loop::onSettle), which covers the window's own events and whatever else changed the screens.
|
||||||
|
void Settle();
|
||||||
|
// Draws a frame now and writes it to the file as a PNG. Throws when that fails.
|
||||||
|
void Screenshot(const std::filesystem::path& png);
|
||||||
|
// Brings the screens up to now, as before an event of the window's own: time has passed for them, and a frame
|
||||||
|
// that went stale is built again. For what acts on the Context from outside the window, a debugger's command:
|
||||||
|
// it then acts on what the window shows, and Settle does what it led to.
|
||||||
|
void Prepare();
|
||||||
|
|
||||||
|
Canvas& Surface() noexcept;
|
||||||
|
bool Failed() const noexcept;
|
||||||
|
|
||||||
|
private:
|
||||||
|
void Layout();
|
||||||
|
// Brings time up to an event and makes the frame true, before the event is handed to the Context.
|
||||||
|
void Before(std::int64_t atMs);
|
||||||
|
std::int64_t EventTime();
|
||||||
|
Point Pointer() const noexcept;
|
||||||
|
void Press(PointerPhase phase);
|
||||||
|
void OnKey(Crafter::KeyCode code);
|
||||||
|
void OnText(std::string_view text);
|
||||||
|
void Apply(const Context::Wants& wants, bool redraw);
|
||||||
|
void ApplyTextInput(const TextInputRequest& want);
|
||||||
|
void DrawFrame();
|
||||||
|
void AfterFrame();
|
||||||
|
void Paste();
|
||||||
|
void Fail(std::string_view why);
|
||||||
|
void Log(std::string_view line) const;
|
||||||
|
|
||||||
|
Loop& loop;
|
||||||
|
Context& context;
|
||||||
|
Canvas canvas;
|
||||||
|
WaylandSource source;
|
||||||
|
FrameDriver frames;
|
||||||
|
Timer wake; // the Context's own: a long press, a caret's blink, a notice's end
|
||||||
|
Timer repeat; // a held key's repeats
|
||||||
|
Defer paste;
|
||||||
|
bool failed = false;
|
||||||
|
bool overflowSaid = false;
|
||||||
|
bool down = false; // the pointer's button, or the first finger
|
||||||
|
// Where the mouse is, while it is in the window; a finger is nowhere once it lifts. What is under a pointer that
|
||||||
|
// rests changes when the screens do or a list moves, so it is looked up again with every frame built.
|
||||||
|
std::optional<Point> resting;
|
||||||
|
|
||||||
|
EventClock clock;
|
||||||
|
FrameWait atlasWait;
|
||||||
|
TextInputRequest applied; // what the compositor was last told
|
||||||
|
std::string pasteInto; // the field that asked for the clipboard
|
||||||
|
// The first finger drives the pointer. A touch the compositor takes over for a gesture of its own arrives as a
|
||||||
|
// release without the finger's lifting: that is a cancel, which taps nothing.
|
||||||
|
std::optional<std::int32_t> touch;
|
||||||
|
bool touchLifted = false;
|
||||||
|
// A key whose press changed the screen or moved the focus, and the text it types: that text is the old
|
||||||
|
// screen's, at the press and at every repeat while the key stays down.
|
||||||
|
struct Spent {
|
||||||
|
Crafter::KeyCode code = 0;
|
||||||
|
std::string text;
|
||||||
|
};
|
||||||
|
std::optional<Spent> spent;
|
||||||
|
|
||||||
|
// The listeners on the window library's events; they go before the canvas does.
|
||||||
|
std::deque<Crafter::EventListener<void>> plain;
|
||||||
|
std::optional<Crafter::EventListener<Crafter::TouchPoint>> touchDown;
|
||||||
|
std::optional<Crafter::EventListener<Crafter::TouchPoint>> touchUp;
|
||||||
|
std::optional<Crafter::EventListener<std::uint32_t>> scroll;
|
||||||
|
std::optional<Crafter::EventListener<Crafter::KeyCode>> keyDown;
|
||||||
|
std::optional<Crafter::EventListener<Crafter::KeyCode>> keyUp;
|
||||||
|
std::optional<Crafter::EventListener<const std::string_view>> text;
|
||||||
|
std::optional<Crafter::EventListener<const std::string_view>> preedit;
|
||||||
|
std::optional<Crafter::EventListener<Crafter::TextDelete>> textDelete;
|
||||||
|
};
|
||||||
|
}
|
||||||
14
interfaces/Nostro.Ui.Shell.cppm
Normal file
14
interfaces/Nostro.Ui.Shell.cppm
Normal file
|
|
@ -0,0 +1,14 @@
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
export module Nostro.Ui.Shell;
|
||||||
|
|
||||||
|
// What puts the toolkit's screens (Nostro.Ui) on a display: one event loop, a window on the Catcrafts window library,
|
||||||
|
// and the desktop portal. It is the one part of the app that needs a compositor and a graphics device to run, so it
|
||||||
|
// is kept thin: it holds no state of the screens and decides nothing about them. The toolkit and the app's own logic
|
||||||
|
// are tested without it; this is checked by looking at what it draws.
|
||||||
|
|
||||||
|
export import :Loop;
|
||||||
|
export import :Canvas;
|
||||||
|
export import :Window;
|
||||||
|
export import :Portal;
|
||||||
19
interfaces/Nostro.Ui.cppm
Normal file
19
interfaces/Nostro.Ui.cppm
Normal file
|
|
@ -0,0 +1,19 @@
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
export module Nostro.Ui;
|
||||||
|
|
||||||
|
// The toolkit the Nostro app's screens are built with: text, editing, gestures, a list of what a frame draws, and the
|
||||||
|
// frame's regions with what a press on each does. It knows nothing of banks and nothing of a window, so its tests
|
||||||
|
// need neither; Nostro.Ui.Shell puts it on a Crafter.Graphics window.
|
||||||
|
|
||||||
|
export import :Geometry;
|
||||||
|
export import :Text;
|
||||||
|
export import :Edit;
|
||||||
|
export import :Gesture;
|
||||||
|
export import :Draw;
|
||||||
|
export import :Theme;
|
||||||
|
export import :Input;
|
||||||
|
export import :Context;
|
||||||
|
export import :Layout;
|
||||||
|
export import :Widgets;
|
||||||
|
|
@ -2,7 +2,7 @@
|
||||||
# SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
# SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
#
|
#
|
||||||
# The system half of nostro for Arch Linux: nostrod's user, its D-Bus and polkit policies, its systemd unit and the
|
# The system half of nostro for Arch Linux: nostrod's user, its D-Bus and polkit policies, its systemd unit and the
|
||||||
# nostro command. nostrod and the CLI come from the net.catcrafts.Nostro Flatpak, installed system-wide
|
# nostro command. nostrod and the CLI come from the net.catcrafts.Nostrod Flatpak, installed system-wide
|
||||||
# (nostro-system.install says how). pacman's hooks create the user and reload systemd and D-Bus.
|
# (nostro-system.install says how). pacman's hooks create the user and reload systemd and D-Bus.
|
||||||
# Build in this directory: makepkg -si
|
# Build in this directory: makepkg -si
|
||||||
pkgname=nostro-system
|
pkgname=nostro-system
|
||||||
|
|
|
||||||
|
|
@ -2,14 +2,25 @@
|
||||||
# SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
# SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
post_install() {
|
post_install() {
|
||||||
echo "nostrod and the nostro CLI come from a Flatpak; install it system-wide:"
|
echo "nostrod and the nostro CLI come from a Flatpak; install it system-wide, from the Catcrafts Flatpak repository:"
|
||||||
echo " flatpak install --system net.catcrafts.Nostro.flatpakref"
|
echo " flatpak remote-add --system --if-not-exists catcrafts https://flatpak.catcrafts.net/catcrafts.flatpakrepo"
|
||||||
echo "(packaging/flatpak/ in nostro's source), or from a local build: flatpak install --system <repo> net.catcrafts.Nostro"
|
echo " flatpak install --system catcrafts net.catcrafts.Nostrod"
|
||||||
|
echo "or from a local build: flatpak install --system <repo> net.catcrafts.Nostrod"
|
||||||
}
|
}
|
||||||
|
|
||||||
post_upgrade() {
|
post_upgrade() {
|
||||||
# A nostrod still running keeps the old files until it ends.
|
# A nostrod still running keeps the old files until it ends.
|
||||||
systemctl try-restart nostrod.service
|
systemctl try-restart nostrod.service
|
||||||
|
# nostrod's Flatpak was net.catcrafts.Nostro until the Nostro app took that id, and flatpak keeps an app's data under
|
||||||
|
# its id. The package and the Flatpaks update independently, so the move is left to the administrator.
|
||||||
|
if [ -d /var/lib/nostro/.var/app/net.catcrafts.Nostro ]; then
|
||||||
|
echo "nostrod's Flatpak is now net.catcrafts.Nostrod. Move its state once, as root:"
|
||||||
|
echo " systemctl stop nostrod.service"
|
||||||
|
echo " mv /var/lib/nostro/.var/app/net.catcrafts.Nostro /var/lib/nostro/.var/app/net.catcrafts.Nostrod"
|
||||||
|
echo " flatpak uninstall --system net.catcrafts.Nostro # only the old nostrod; the app has that id now"
|
||||||
|
echo " flatpak remote-add --system --if-not-exists catcrafts https://flatpak.catcrafts.net/catcrafts.flatpakrepo"
|
||||||
|
echo " flatpak install --system catcrafts net.catcrafts.Nostrod"
|
||||||
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
pre_remove() {
|
pre_remove() {
|
||||||
|
|
|
||||||
|
|
@ -23,8 +23,16 @@
|
||||||
Types:
|
Types:
|
||||||
connectors (Connectors) a(ssssb): name, bank ("bunq"), environment ("production" or "sandbox"),
|
connectors (Connectors) a(ssssb): name, bank ("bunq"), environment ("production" or "sandbox"),
|
||||||
auth ("api key" or "oauth"), whether a call to the bank works now
|
auth ("api key" or "oauth"), whether a call to the bank works now
|
||||||
|
environment (AddBunq) empty: an API key says itself which it is of, a sandbox key by starting with
|
||||||
|
sandbox_. "production" or "sandbox" only has a key of the other one refused
|
||||||
|
(InvalidArgument), before anyone is asked and before the key goes anywhere.
|
||||||
|
AddBunqOAuth needs it named: nothing of an OAuth client says which it is of
|
||||||
connectors (Accounts) a(ssa(ssssx)): connector name, bank, accounts: name, BIC, IBAN, currency, balance
|
connectors (Accounts) a(ssa(ssssx)): connector name, bank, accounts: name, BIC, IBAN, currency, balance
|
||||||
query (Transactions) a{sv}, each key optional: search s, amount x, from x, to x, limit t (100)
|
query (Transactions) a{sv}, each key optional: search s, amount x, from x, to x, limit t (100),
|
||||||
|
stored b (false). Transactions asks the bank for what is new before it
|
||||||
|
answers; with stored true it answers from what nostrod has stored alone, at
|
||||||
|
once and without the bank: for a search in a list it has just given. A key
|
||||||
|
nostrod does not know is ignored, so one from before `stored` asks the bank.
|
||||||
transactions a(sssssxxss): name, BIC, IBAN, description, currency, amount, time, the bank's
|
transactions a(sssssxxss): name, BIC, IBAN, description, currency, amount, time, the bank's
|
||||||
id, the bank's kind ("MASTERCARD/PAYMENT")
|
id, the bank's kind ("MASTERCARD/PAYMENT")
|
||||||
schedule (xaxsusax): start, end, unit (ONCE, HOURLY, DAILY, WEEKLY, MONTHLY, YEARLY),
|
schedule (xaxsusax): start, end, unit (ONCE, HOURLY, DAILY, WEEKLY, MONTHLY, YEARLY),
|
||||||
|
|
@ -37,7 +45,11 @@
|
||||||
drafts a(tssa((ss)sxs)s): id, status, created by, entries (counterparty, currency,
|
drafts a(tssa((ss)sxs)s): id, status, created by, entries (counterparty, currency,
|
||||||
amount, description), bunq's time of its last change
|
amount, description), bunq's time of its last change
|
||||||
cards / updated (tsssssssss): id, kind, product type, status, order status, name on card,
|
cards / updated (tsssssssss): id, kind, product type, status, order status, name on card,
|
||||||
second line, last four digits, expiry, IBAN it pays from
|
second line, last four digits, expiry, IBAN it pays from. A card whose order
|
||||||
|
status is VIRTUAL_DELIVERY is a virtual one: bunq has it as DEACTIVATED however
|
||||||
|
well it pays, so that status says nothing of it until it is LOST, STOLEN,
|
||||||
|
CANCELLED or EXPIRED. SetCardStatus refuses to set such a card ACTIVE or
|
||||||
|
DEACTIVATED (InvalidArgument): bunq would leave it as it is, without an error
|
||||||
account / chosen (ssssx): the account apps' checkouts pay from (net.catcrafts.Nostro1.Checkout),
|
account / chosen (ssssx): the account apps' checkouts pay from (net.catcrafts.Nostro1.Checkout),
|
||||||
as in Accounts; DefaultCheckoutAccount has none until one is chosen, or once
|
as in Accounts; DefaultCheckoutAccount has none until one is chosen, or once
|
||||||
it is gone. An account reached through OAuth cannot pay a shop, and is refused.
|
it is gone. An account reached through OAuth cannot pay a shop, and is refused.
|
||||||
|
|
|
||||||
139
packaging/flatpak/build-aarch64.sh
Executable file
139
packaging/flatpak/build-aarch64.sh
Executable file
|
|
@ -0,0 +1,139 @@
|
||||||
|
#!/bin/sh
|
||||||
|
# SPDX-License-Identifier: LGPL-3.0-only
|
||||||
|
# SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
# build-aarch64.sh: Nostro's two Flatpaks for aarch64, a phone's architecture, into an OSTree repository: the app
|
||||||
|
# (net.catcrafts.Nostro) and the service with the nostro command (net.catcrafts.Nostrod). crafter-build cross-compiles
|
||||||
|
# the executables against the sysroot of make-aarch64-sysroot.sh (run that first), and flatpak's build commands
|
||||||
|
# assemble them on org.freedesktop.Platform 26.08, with the libc++ they were linked against in /app/lib.
|
||||||
|
#
|
||||||
|
# packaging/flatpak/build-aarch64.sh <repo> [branch] # branch: stable by default
|
||||||
|
#
|
||||||
|
# The repository is created when it does not exist. On the phone, as root, with the repository copied over:
|
||||||
|
# packaging/system/install.sh --repo <repo> --app. The cache and $CRAFTER_REF are make-aarch64-sysroot.sh's.
|
||||||
|
# $NOSTRO_GRAPHICS names a Crafter.Graphics checkout's project.cpp for the app, for as long as project.cpp asks for one
|
||||||
|
# (--graphics=). Needs flatpak, flock, readelf and appstreamcli.
|
||||||
|
set -eu
|
||||||
|
|
||||||
|
REPO=${1:?usage: build-aarch64.sh <repo> [branch]}
|
||||||
|
BRANCH=${2:-stable}
|
||||||
|
APP_ID=net.catcrafts.Nostro
|
||||||
|
SERVICE_ID=net.catcrafts.Nostrod
|
||||||
|
ARCH=aarch64
|
||||||
|
TRIPLE=aarch64-unknown-linux-gnu
|
||||||
|
MULTIARCH=aarch64-linux-gnu
|
||||||
|
RUNTIME_VERSION=26.08
|
||||||
|
CRAFTER_REF=${CRAFTER_REF:-net.catcrafts.CrafterBuild//stable}
|
||||||
|
CACHE=${NOSTRO_FLATPAK_CACHE:-${XDG_CACHE_HOME:-$HOME/.cache}/nostro-flatpak}
|
||||||
|
INSTALLATION="$CACHE/installation"
|
||||||
|
SYSROOT="$CACHE/sysroot-$ARCH"
|
||||||
|
LIBCXX="$CACHE/libcxx-$ARCH"
|
||||||
|
SRC=$(CDPATH= cd -- "$(dirname "$0")/../.." && pwd)
|
||||||
|
# flatpak commands that need the aarch64 Sdk and Platform see their installation; crafter-build runs from wherever it
|
||||||
|
# is installed.
|
||||||
|
withsdk() { FLATPAK_USER_DIR="$INSTALLATION" "$@"; }
|
||||||
|
|
||||||
|
command -v readelf >/dev/null 2>&1 || { echo "readelf (binutils) is needed: the NEEDED checks below run on it" >&2; exit 1; }
|
||||||
|
# One build at a time on this cache: the build directories are removed and made again by every run.
|
||||||
|
mkdir -p "$CACHE"
|
||||||
|
exec 9>"$CACHE/lock"; flock 9
|
||||||
|
[ -f "$SYSROOT/.made-from" ] || { echo "no sysroot at $SYSROOT: run packaging/flatpak/make-aarch64-sysroot.sh first" >&2; exit 1; } # under the lock: a sysroot being made is not missing
|
||||||
|
|
||||||
|
# Generic armv8-a: a Flatpak is for any aarch64 machine, not one SoC. An output directory's name ends in a hash of the
|
||||||
|
# configuration, and an older variant left in bin/ would be a second match below: this run's are the only ones.
|
||||||
|
rm -rf "$SRC/bin/"*"-$TRIPLE-armv8-a-generic-"*
|
||||||
|
crafter() { (cd "$SRC" && flatpak run "$CRAFTER_REF" --march=armv8-a --mtune=generic --banks=bunq "$@" -- --target="$TRIPLE" --sysroot="$SYSROOT"); }
|
||||||
|
# The one executable of that name this run built. The library and the command are both called nostro, so a directory
|
||||||
|
# is told by what it holds.
|
||||||
|
built() {
|
||||||
|
name=$1
|
||||||
|
set -- "$SRC/bin/$name-$TRIPLE-armv8-a-generic-"*/"$name"
|
||||||
|
[ $# = 1 ] && [ -x "$1" ] || { echo "expected one $name for $TRIPLE under $SRC/bin, found: $*" >&2; exit 1; }
|
||||||
|
echo "$1"
|
||||||
|
}
|
||||||
|
|
||||||
|
echo ">> the executables for $TRIPLE"
|
||||||
|
crafter
|
||||||
|
crafter --product=daemon
|
||||||
|
crafter --product=app ${NOSTRO_GRAPHICS:+"--graphics=$NOSTRO_GRAPHICS"}
|
||||||
|
cli=$(built nostro)
|
||||||
|
daemon=$(built nostrod)
|
||||||
|
app=$(built nostro-app)
|
||||||
|
|
||||||
|
platform=$(withsdk flatpak --user info --show-location --arch="$ARCH" "org.freedesktop.Platform//$RUNTIME_VERSION")/files
|
||||||
|
# Every library an executable and the libraries it carries need is in the Platform or in /app/lib, or the first start
|
||||||
|
# would fail on the phone. And one unwinder: LLVM's libunwind, which the carried libc++abi uses, never the Platform's
|
||||||
|
# libunwind 8 beside it.
|
||||||
|
checked() {
|
||||||
|
files=$1
|
||||||
|
shift
|
||||||
|
missing=0
|
||||||
|
for elf in "$@" "$files/lib/"lib*.so.1; do
|
||||||
|
for lib in $(readelf -d "$elf" | sed -n 's/.*(NEEDED).*\[\(.*\)\]/\1/p'); do
|
||||||
|
if [ ! -e "$platform/lib/$MULTIARCH/$lib" ] && [ ! -e "$platform/lib/$lib" ] && [ ! -e "$files/lib/$lib" ]; then
|
||||||
|
echo "$(basename "$elf") needs $lib, which neither the Platform nor /app/lib has" >&2
|
||||||
|
missing=1
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
if readelf -d "$elf" | grep -q 'NEEDED.*\[libunwind\.so\.8\]'; then
|
||||||
|
echo "$(basename "$elf") links libunwind 8, not LLVM's libunwind" >&2
|
||||||
|
missing=1
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
[ "$missing" = 0 ] || exit 1
|
||||||
|
}
|
||||||
|
# What both carry: the C++ runtime they were linked against, and the licences of what is in them, which
|
||||||
|
# packaging/licenses/NOTICE names.
|
||||||
|
carried() {
|
||||||
|
files=$1
|
||||||
|
id=$2
|
||||||
|
mkdir -p "$files/lib"
|
||||||
|
cp -a "$LIBCXX/usr/lib/"libc++.so.1* "$LIBCXX/usr/lib/"libc++abi.so.1* "$LIBCXX/usr/lib/"libunwind.so.1* "$files/lib/"
|
||||||
|
install -Dm644 "$SRC/packaging/flatpak/$id.metainfo.xml" "$files/share/metainfo/$id.metainfo.xml"
|
||||||
|
install -Dm644 -t "$files/share/licenses/$id" "$SRC/LICENSE" "$SRC/LICENSE.GPL" "$SRC/packaging/licenses/NOTICE" \
|
||||||
|
"$SRC/packaging/licenses/nlohmann-json-MIT.txt" "$SRC/packaging/licenses/LLVM-LICENSE.TXT"
|
||||||
|
}
|
||||||
|
# The AppStream catalogue entry software centres list an app by, with PNG icons: appstreamcli's default, JPEG XL, is
|
||||||
|
# not read by older clients.
|
||||||
|
catalogued() {
|
||||||
|
appstreamcli compose --prefix=/ --origin="$2" --image-format=png \
|
||||||
|
--result-root="$1" --data-dir="$1/share/app-info/xmls" --icons-dir="$1/share/app-info/icons/flatpak" "$1"
|
||||||
|
}
|
||||||
|
mkdir -p "$(dirname "$REPO")"
|
||||||
|
|
||||||
|
echo ">> $SERVICE_ID from $cli and $daemon"
|
||||||
|
build="$CACHE/build-service-$ARCH"
|
||||||
|
rm -rf "$build"
|
||||||
|
withsdk flatpak build-init --arch="$ARCH" "$build" "$SERVICE_ID" org.freedesktop.Sdk org.freedesktop.Platform "$RUNTIME_VERSION"
|
||||||
|
files="$build/files"
|
||||||
|
install -Dm755 "$cli" "$files/bin/nostro"
|
||||||
|
install -Dm755 "$daemon" "$files/bin/nostrod"
|
||||||
|
carried "$files" "$SERVICE_ID"
|
||||||
|
checked "$files" "$files/bin/nostro" "$files/bin/nostrod"
|
||||||
|
catalogued "$files" "$SERVICE_ID"
|
||||||
|
# nostrod talks to the bank, and to the bus, logind and polkit on the system bus; the command talks to nostrod there.
|
||||||
|
# As packaging/flatpak/net.catcrafts.Nostrod.yaml has it for x86_64.
|
||||||
|
withsdk flatpak build-finish "$build" --command=nostro --share=network --socket=system-bus
|
||||||
|
withsdk flatpak build-export --arch="$ARCH" "$REPO" "$build" "$BRANCH"
|
||||||
|
|
||||||
|
echo ">> $APP_ID from $app"
|
||||||
|
build="$CACHE/build-app-$ARCH"
|
||||||
|
rm -rf "$build"
|
||||||
|
withsdk flatpak build-init --arch="$ARCH" "$build" "$APP_ID" org.freedesktop.Sdk org.freedesktop.Platform "$RUNTIME_VERSION"
|
||||||
|
files="$build/files"
|
||||||
|
# The app finds its fonts and the window library's shaders beside itself.
|
||||||
|
mkdir -p "$files/bin"
|
||||||
|
cp -a "$(dirname "$app")/." "$files/bin/"
|
||||||
|
carried "$files" "$APP_ID"
|
||||||
|
install -Dm644 "$SRC/packaging/flatpak/$APP_ID.desktop" "$files/share/applications/$APP_ID.desktop"
|
||||||
|
install -Dm644 "$SRC/packaging/flatpak/$APP_ID.svg" "$files/share/icons/hicolor/scalable/apps/$APP_ID.svg"
|
||||||
|
install -Dm644 -t "$files/share/licenses/$APP_ID" "$SRC/assets/OFL.txt" "$SRC/packaging/licenses/stb-LICENSE.txt" \
|
||||||
|
"$SRC/packaging/licenses/wayland-protocols-NOTICE.txt" "$SRC/packaging/licenses/Vulkan-Utility-Libraries-Apache-2.0.txt" \
|
||||||
|
"$SRC/packaging/licenses/libevdev-COPYING.txt"
|
||||||
|
checked "$files" "$files/bin/nostro-app"
|
||||||
|
catalogued "$files" "$APP_ID"
|
||||||
|
# The compositor, the graphics device, and nostrod on the system bus; the desktop's portals need no permission. As
|
||||||
|
# project.cpp has it for the x86_64 Flatpak crafter-build makes.
|
||||||
|
withsdk flatpak build-finish "$build" --command=nostro-app --socket=wayland --device=dri --system-talk-name=net.catcrafts.Nostro1
|
||||||
|
withsdk flatpak build-export --arch="$ARCH" "$REPO" "$build" "$BRANCH"
|
||||||
|
echo ">> done: app/$SERVICE_ID/$ARCH/$BRANCH and app/$APP_ID/$ARCH/$BRANCH in $REPO"
|
||||||
138
packaging/flatpak/make-aarch64-sysroot.sh
Executable file
138
packaging/flatpak/make-aarch64-sysroot.sh
Executable file
|
|
@ -0,0 +1,138 @@
|
||||||
|
#!/bin/sh
|
||||||
|
# SPDX-License-Identifier: LGPL-3.0-only
|
||||||
|
# SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
# make-aarch64-sysroot.sh: what Nostro's aarch64 executables are cross-compiled against, for a phone. crafter-build's
|
||||||
|
# own Flatpak, which the x86_64 Flatpaks are built with, exists for x86_64 alone, so an aarch64 build is a cross build
|
||||||
|
# from it against this sysroot: the Freedesktop Sdk for aarch64 (glibc, OpenSSL, libsystemd, Wayland, xkbcommon, udev
|
||||||
|
# and the Vulkan loader, the libraries the Platform runtime has at run time) plus LLVM's libc++ of the release
|
||||||
|
# crafter-build itself carries, built for aarch64, which the runtime does not have.
|
||||||
|
#
|
||||||
|
# packaging/flatpak/make-aarch64-sysroot.sh
|
||||||
|
#
|
||||||
|
# Everything goes under $NOSTRO_FLATPAK_CACHE (default ${XDG_CACHE_HOME:-~/.cache}/nostro-flatpak), outside /tmp, which
|
||||||
|
# the crafter-build sandbox does not share:
|
||||||
|
# installation/ a flatpak installation of the aarch64 Sdk and Platform (build-aarch64.sh builds the apps on it)
|
||||||
|
# sysroot-aarch64/ the Sdk's files as usr/, with libc++ added
|
||||||
|
# libcxx-aarch64/ libc++, libc++abi and libunwind as installed, which the Flatpaks carry in /app/lib
|
||||||
|
# A sysroot made from the same Sdk commit, LLVM release and recipe is kept.
|
||||||
|
#
|
||||||
|
# Needs flatpak, flock, curl, tar, xz and sha256sum; crafter-build ($CRAFTER_REF, the Crafter.Build Flatpak) provides
|
||||||
|
# clang, cmake and ninja. Network: Flathub and the LLVM release on GitHub.
|
||||||
|
set -eu
|
||||||
|
|
||||||
|
ARCH=aarch64
|
||||||
|
TRIPLE=aarch64-unknown-linux-gnu
|
||||||
|
MULTIARCH=aarch64-linux-gnu
|
||||||
|
MARCH=armv8-a
|
||||||
|
RUNTIME_VERSION=26.08
|
||||||
|
# The LLVM release crafter-build itself carries, whose std module source it ships. The tarball and hash are the ones
|
||||||
|
# Crafter.Build's manifest builds that LLVM from.
|
||||||
|
LLVM_VERSION=23.1.2
|
||||||
|
LLVM_SHA256=c98bbef08a2b4c2613cd50e9aa9ae7b69b1fe6c16b2c40373bc0ab6116fdf78a
|
||||||
|
CRAFTER_REF=${CRAFTER_REF:-net.catcrafts.CrafterBuild//stable}
|
||||||
|
CACHE=${NOSTRO_FLATPAK_CACHE:-${XDG_CACHE_HOME:-$HOME/.cache}/nostro-flatpak}
|
||||||
|
|
||||||
|
INSTALLATION="$CACHE/installation"
|
||||||
|
SYSROOT="$CACHE/sysroot-$ARCH"
|
||||||
|
LIBCXX="$CACHE/libcxx-$ARCH"
|
||||||
|
# The Sdk and the Platform for aarch64 go into a flatpak installation of their own; crafter-build is run from wherever
|
||||||
|
# it is installed.
|
||||||
|
sdkpak() { FLATPAK_USER_DIR="$INSTALLATION" flatpak --user "$@"; }
|
||||||
|
# Flathub's CDN answers 502 now and then, and flatpak reports a summary it could not fetch as a runtime that does not
|
||||||
|
# exist.
|
||||||
|
retry() {
|
||||||
|
for attempt in 1 2 3 4 5; do
|
||||||
|
"$@" && return 0
|
||||||
|
echo "attempt $attempt of 5 failed: $*" >&2
|
||||||
|
[ "$attempt" = 5 ] || sleep 30
|
||||||
|
done
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
mkdir -p "$CACHE"
|
||||||
|
# One run at a time on this cache: the sysroot and the LLVM build are removed and made again by a run that finds them
|
||||||
|
# stale.
|
||||||
|
exec 9>"$CACHE/lock"; flock 9
|
||||||
|
echo ">> the $ARCH Sdk and Platform $RUNTIME_VERSION into $INSTALLATION"
|
||||||
|
retry sdkpak remote-add --if-not-exists flathub https://dl.flathub.org/repo/flathub.flatpakrepo
|
||||||
|
retry sdkpak install -y --noninteractive --no-related --arch="$ARCH" flathub \
|
||||||
|
"org.freedesktop.Sdk//$RUNTIME_VERSION" "org.freedesktop.Platform//$RUNTIME_VERSION"
|
||||||
|
retry sdkpak update -y --noninteractive --no-related --arch="$ARCH"
|
||||||
|
sdk=$(sdkpak info --show-location --arch="$ARCH" "org.freedesktop.Sdk//$RUNTIME_VERSION")
|
||||||
|
sdk_commit=$(sdkpak info --show-commit --arch="$ARCH" "org.freedesktop.Sdk//$RUNTIME_VERSION")
|
||||||
|
# A sysroot is kept while the Sdk commit, the LLVM release and this recipe stay the same.
|
||||||
|
stamp="sdk $sdk_commit llvm $LLVM_VERSION recipe $(sha256sum "$0" | cut -c1-16)"
|
||||||
|
if [ -f "$SYSROOT/.made-from" ] && [ "$(cat "$SYSROOT/.made-from")" = "$stamp" ] && [ -f "$LIBCXX/usr/lib/libc++.so.1" ]; then
|
||||||
|
echo ">> $SYSROOT is current ($stamp)"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo ">> $SYSROOT from the Sdk at $sdk_commit"
|
||||||
|
rm -rf "$SYSROOT" "$LIBCXX"
|
||||||
|
mkdir -p "$SYSROOT"
|
||||||
|
# A copy: libc++ is installed into it, and the installation's files are hard links into its object store.
|
||||||
|
cp -a --reflink=auto "$sdk/files" "$SYSROOT/usr"
|
||||||
|
# Linker scripts and the dynamic linker's path name /lib.
|
||||||
|
ln -s usr/lib "$SYSROOT/lib"
|
||||||
|
# libc++'s linker script adds -lunwind, which would find the Sdk's libunwind 8 (in the multiarch directory, searched
|
||||||
|
# first) beside the LLVM libunwind its libc++abi uses: without the Sdk's link name it finds LLVM's.
|
||||||
|
rm "$SYSROOT/usr/lib/$MULTIARCH/libunwind.so"
|
||||||
|
|
||||||
|
src="$CACHE/llvm-project-$LLVM_VERSION.src"
|
||||||
|
tarball="$CACHE/llvm-project-$LLVM_VERSION.src.tar.xz"
|
||||||
|
if [ ! -d "$src/runtimes" ] || [ ! -d "$src/libc/shared" ]; then
|
||||||
|
echo ">> LLVM $LLVM_VERSION's runtimes source"
|
||||||
|
retry curl -fsSL -o "$tarball" "https://github.com/llvm/llvm-project/releases/download/llvmorg-$LLVM_VERSION/llvm-project-$LLVM_VERSION.src.tar.xz"
|
||||||
|
got=$(sha256sum "$tarball" | cut -d' ' -f1)
|
||||||
|
[ "$got" = "$LLVM_SHA256" ] || { echo "llvm-project-$LLVM_VERSION.src.tar.xz: sha256 $got, expected $LLVM_SHA256" >&2; exit 1; }
|
||||||
|
rm -rf "$src" "$src.part"
|
||||||
|
mkdir -p "$src.part"
|
||||||
|
# Only part of the tree is unpacked; libc is among it because libc++'s from_chars parses floating point with LLVM
|
||||||
|
# libc's shared headers. It lands under $src only once complete: a tar cut short leaves nothing a later run would
|
||||||
|
# take for the source.
|
||||||
|
tar -xJf "$tarball" -C "$src.part" --strip-components=1 \
|
||||||
|
"llvm-project-$LLVM_VERSION.src/runtimes" "llvm-project-$LLVM_VERSION.src/libcxx" \
|
||||||
|
"llvm-project-$LLVM_VERSION.src/libcxxabi" "llvm-project-$LLVM_VERSION.src/libunwind" \
|
||||||
|
"llvm-project-$LLVM_VERSION.src/cmake" "llvm-project-$LLVM_VERSION.src/llvm/cmake" \
|
||||||
|
"llvm-project-$LLVM_VERSION.src/llvm/utils" "llvm-project-$LLVM_VERSION.src/third-party" \
|
||||||
|
"llvm-project-$LLVM_VERSION.src/libc"
|
||||||
|
mv "$src.part" "$src"
|
||||||
|
rm -f "$tarball"
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo ">> libc++, libc++abi and libunwind $LLVM_VERSION for $TRIPLE"
|
||||||
|
build="$CACHE/libcxx-build-$ARCH"
|
||||||
|
rm -rf "$build"
|
||||||
|
# The classic layout (include/c++/v1, lib/) is where crafter-build looks in a sysroot. libc++abi unwinds with LLVM's
|
||||||
|
# libunwind, as crafter-build's own libc++ does. Programs come from the sandbox, never from the sysroot: the Sdk's own
|
||||||
|
# ninja and tools are aarch64 binaries. The C++ compiler cannot link a test program before there is a libc++ to link;
|
||||||
|
# the C compiler's check still runs.
|
||||||
|
flatpak run --command=sh "$CRAFTER_REF" -eu -c '
|
||||||
|
cmake -S "$1/runtimes" -B "$2" -G Ninja \
|
||||||
|
-DCMAKE_BUILD_TYPE=Release \
|
||||||
|
-DCMAKE_SYSTEM_NAME=Linux -DCMAKE_SYSTEM_PROCESSOR="$3" \
|
||||||
|
-DCMAKE_SYSROOT="$4" \
|
||||||
|
-DCMAKE_MAKE_PROGRAM=/usr/bin/ninja \
|
||||||
|
-DCMAKE_FIND_ROOT_PATH_MODE_PROGRAM=NEVER -DCMAKE_FIND_ROOT_PATH_MODE_LIBRARY=ONLY \
|
||||||
|
-DCMAKE_FIND_ROOT_PATH_MODE_INCLUDE=ONLY -DCMAKE_FIND_ROOT_PATH_MODE_PACKAGE=ONLY \
|
||||||
|
-DCMAKE_C_COMPILER=/app/bin/clang -DCMAKE_CXX_COMPILER=/app/bin/clang++ -DCMAKE_ASM_COMPILER=/app/bin/clang \
|
||||||
|
-DCMAKE_CXX_COMPILER_WORKS=ON \
|
||||||
|
-DCMAKE_C_COMPILER_TARGET="$5" -DCMAKE_CXX_COMPILER_TARGET="$5" -DCMAKE_ASM_COMPILER_TARGET="$5" \
|
||||||
|
-DCMAKE_AR=/app/bin/llvm-ar -DCMAKE_RANLIB=/app/bin/llvm-ranlib -DCMAKE_NM=/app/bin/llvm-nm \
|
||||||
|
-DCMAKE_C_FLAGS="-march=$6" -DCMAKE_CXX_FLAGS="-march=$6" \
|
||||||
|
-DCMAKE_INSTALL_PREFIX="$7/usr" \
|
||||||
|
"-DLLVM_ENABLE_RUNTIMES=libcxx;libcxxabi;libunwind" \
|
||||||
|
-DLLVM_ENABLE_PER_TARGET_RUNTIME_DIR=OFF \
|
||||||
|
-DLIBCXXABI_USE_LLVM_UNWINDER=ON \
|
||||||
|
-DLIBCXX_INSTALL_MODULES=ON \
|
||||||
|
-DLLVM_INCLUDE_TESTS=OFF -DLIBCXX_INCLUDE_TESTS=OFF -DLIBCXXABI_INCLUDE_TESTS=OFF \
|
||||||
|
-DLIBUNWIND_INCLUDE_TESTS=OFF -DLIBCXX_INCLUDE_BENCHMARKS=OFF
|
||||||
|
ninja -C "$2" install
|
||||||
|
' sh "$src" "$build" "$ARCH" "$SYSROOT" "$TRIPLE" "$MARCH" "$LIBCXX"
|
||||||
|
rm -rf "$build"
|
||||||
|
|
||||||
|
grep -q "_LIBCPP_VERSION 230102" "$LIBCXX/usr/include/c++/v1/__config" || { echo "the installed libc++ headers are not $LLVM_VERSION" >&2; exit 1; }
|
||||||
|
cp -a "$LIBCXX/usr/." "$SYSROOT/usr/"
|
||||||
|
echo "$stamp" > "$SYSROOT/.made-from"
|
||||||
|
echo ">> done: $SYSROOT ($stamp)"
|
||||||
17
packaging/flatpak/net.catcrafts.Nostro.desktop
Normal file
17
packaging/flatpak/net.catcrafts.Nostro.desktop
Normal file
|
|
@ -0,0 +1,17 @@
|
||||||
|
# SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
# SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
[Desktop Entry]
|
||||||
|
Type=Application
|
||||||
|
Name=Nostro
|
||||||
|
GenericName=Banking
|
||||||
|
Comment=See your bank accounts and pay from them
|
||||||
|
Exec=nostro-app
|
||||||
|
Icon=net.catcrafts.Nostro
|
||||||
|
Terminal=false
|
||||||
|
Categories=Office;Finance;
|
||||||
|
Keywords=bank;banking;bunq;payment;money;IBAN;
|
||||||
|
StartupNotify=false
|
||||||
|
SingleMainWindow=true
|
||||||
|
X-KDE-FormFactor=handset;tablet;desktop;
|
||||||
|
X-Purism-FormFactor=Workstation;Mobile;
|
||||||
|
|
@ -5,8 +5,8 @@ Branch=stable
|
||||||
Url=https://flatpak.catcrafts.net/repo/
|
Url=https://flatpak.catcrafts.net/repo/
|
||||||
SuggestRemoteName=catcrafts
|
SuggestRemoteName=catcrafts
|
||||||
Homepage=https://catcrafts.net
|
Homepage=https://catcrafts.net
|
||||||
Comment=Banking client for Linux
|
Comment=Your bank accounts on a Linux phone or desktop
|
||||||
Description=nostro and nostrod, its daemon; install it system-wide with the system files from packaging/system
|
Description=The Nostro app; it needs Nostro's service, net.catcrafts.Nostrod, installed system-wide with its system files
|
||||||
Icon=
|
Icon=
|
||||||
RuntimeRepo=https://dl.flathub.org/repo/flathub.flatpakrepo
|
RuntimeRepo=https://dl.flathub.org/repo/flathub.flatpakrepo
|
||||||
IsRuntime=false
|
IsRuntime=false
|
||||||
|
|
|
||||||
|
|
@ -1,27 +1,50 @@
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<!-- SPDX-License-Identifier: CC0-1.0 -->
|
<!-- SPDX-License-Identifier: CC0-1.0 -->
|
||||||
<component type="console-application">
|
<component type="desktop-application">
|
||||||
<id>net.catcrafts.Nostro</id>
|
<id>net.catcrafts.Nostro</id>
|
||||||
<name>Nostro</name>
|
<name>Nostro</name>
|
||||||
<summary>Banking client for Linux</summary>
|
<summary>Your bank accounts on a Linux phone or desktop</summary>
|
||||||
<metadata_license>CC0-1.0</metadata_license>
|
<metadata_license>CC0-1.0</metadata_license>
|
||||||
<project_license>LGPL-3.0-only</project_license>
|
<project_license>GPL-3.0-only AND OFL-1.1</project_license>
|
||||||
<developer id="net.catcrafts">
|
<developer id="net.catcrafts">
|
||||||
<name>Catcrafts</name>
|
<name>Catcrafts</name>
|
||||||
</developer>
|
</developer>
|
||||||
<description>
|
<description>
|
||||||
<p>
|
<p>
|
||||||
Nostro talks to your bank's API directly: accounts, transactions, payments, requests, schedules, draft payments
|
Nostro shows your bank accounts and pays from them, by talking to your bank's API directly: accounts and their
|
||||||
and cards, for bunq so far. Its daemon, nostrod, runs as a system user of its own and keeps every local user's
|
payments, paying now or on a schedule, requests for money, draft payments and cards. bunq is the bank it knows
|
||||||
bank connections where no program of theirs can read them; the nostro command asks it over the system bus, and
|
so far.
|
||||||
your password is asked for before anything moves money.
|
|
||||||
</p>
|
</p>
|
||||||
<p>
|
<p>
|
||||||
Apps can have Nostro pay an order at checkout, from an account you chose, once you have confirmed the payment.
|
This is the app. It holds no key of yours: your bank connections are kept by Nostro's service, where no program
|
||||||
|
you run can read them, and your system asks for your password before anything moves money. The service,
|
||||||
|
net.catcrafts.Nostrod, is installed for the whole system together with a few system files; Nostro's README says
|
||||||
|
how.
|
||||||
</p>
|
</p>
|
||||||
</description>
|
</description>
|
||||||
<provides>
|
<launchable type="desktop-id">net.catcrafts.Nostro.desktop</launchable>
|
||||||
<binary>nostro</binary>
|
<url type="homepage">https://catcrafts.net</url>
|
||||||
</provides>
|
<supports>
|
||||||
|
<control>touch</control>
|
||||||
|
<control>pointing</control>
|
||||||
|
<control>keyboard</control>
|
||||||
|
</supports>
|
||||||
|
<recommends>
|
||||||
|
<display_length compare="ge">360</display_length>
|
||||||
|
</recommends>
|
||||||
<content_rating type="oars-1.1"/>
|
<content_rating type="oars-1.1"/>
|
||||||
|
<releases>
|
||||||
|
<release version="0.1.0" date="2026-11-19">
|
||||||
|
<description>
|
||||||
|
<p>The first release: everything the nostro command does, in a window that fits a phone and a desktop.</p>
|
||||||
|
<ul>
|
||||||
|
<li>Accounts and their payments, with search and filters</li>
|
||||||
|
<li>Paying now, on a schedule or as a draft, and asking for money</li>
|
||||||
|
<li>Requests sent and received, scheduled payments and drafts</li>
|
||||||
|
<li>Cards: freeze, unfreeze, report lost or stolen</li>
|
||||||
|
<li>Bank connections with an API key or through OAuth, and the account apps are paid from at checkout</li>
|
||||||
|
</ul>
|
||||||
|
</description>
|
||||||
|
</release>
|
||||||
|
</releases>
|
||||||
</component>
|
</component>
|
||||||
|
|
|
||||||
13
packaging/flatpak/net.catcrafts.Nostro.svg
Normal file
13
packaging/flatpak/net.catcrafts.Nostro.svg
Normal file
|
|
@ -0,0 +1,13 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<!-- SPDX-License-Identifier: GPL-3.0-only -->
|
||||||
|
<!-- SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® -->
|
||||||
|
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="128" height="128" viewBox="0 0 128 128">
|
||||||
|
<rect x="8" y="8" width="112" height="112" rx="28" fill="#2e70ed"/>
|
||||||
|
<!-- A bank: a roof, the columns under it and the ground they stand on. -->
|
||||||
|
<path d="M64 27 102 47v7H26v-7z" fill="#ffffff"/>
|
||||||
|
<rect x="34" y="60" width="12" height="26" rx="2" fill="#ffffff"/>
|
||||||
|
<rect x="58" y="60" width="12" height="26" rx="2" fill="#ffffff"/>
|
||||||
|
<rect x="82" y="60" width="12" height="26" rx="2" fill="#ffffff"/>
|
||||||
|
<rect x="26" y="92" width="76" height="9" rx="3" fill="#ffffff"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 721 B |
13
packaging/flatpak/net.catcrafts.Nostrod.flatpakref
Normal file
13
packaging/flatpak/net.catcrafts.Nostrod.flatpakref
Normal file
|
|
@ -0,0 +1,13 @@
|
||||||
|
[Flatpak Ref]
|
||||||
|
Title=Nostro service
|
||||||
|
Name=net.catcrafts.Nostrod
|
||||||
|
Branch=stable
|
||||||
|
Url=https://flatpak.catcrafts.net/repo/
|
||||||
|
SuggestRemoteName=catcrafts
|
||||||
|
Homepage=https://catcrafts.net
|
||||||
|
Comment=The daemon and command behind the Nostro banking client
|
||||||
|
Description=nostrod and the nostro command; install it system-wide with the system files from packaging/system
|
||||||
|
Icon=
|
||||||
|
RuntimeRepo=https://dl.flathub.org/repo/flathub.flatpakrepo
|
||||||
|
IsRuntime=false
|
||||||
|
GPGKey=GPG_KEY_BASE64_PLACEHOLDER
|
||||||
28
packaging/flatpak/net.catcrafts.Nostrod.metainfo.xml
Normal file
28
packaging/flatpak/net.catcrafts.Nostrod.metainfo.xml
Normal file
|
|
@ -0,0 +1,28 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<!-- SPDX-License-Identifier: CC0-1.0 -->
|
||||||
|
<component type="console-application">
|
||||||
|
<id>net.catcrafts.Nostrod</id>
|
||||||
|
<name>Nostro service</name>
|
||||||
|
<summary>The daemon and command behind the Nostro banking client</summary>
|
||||||
|
<metadata_license>CC0-1.0</metadata_license>
|
||||||
|
<project_license>LGPL-3.0-only</project_license>
|
||||||
|
<developer id="net.catcrafts">
|
||||||
|
<name>Catcrafts</name>
|
||||||
|
</developer>
|
||||||
|
<description>
|
||||||
|
<p>
|
||||||
|
Nostro talks to your bank's API directly: accounts, transactions, payments, requests, schedules, draft payments
|
||||||
|
and cards, for bunq so far. Its daemon, nostrod, runs as a system user of its own and keeps every local user's
|
||||||
|
bank connections where no program of theirs can read them; the nostro command and the Nostro app ask it over the
|
||||||
|
system bus, and your password is asked for before anything moves money.
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
Apps can have Nostro pay an order at checkout, from an account you chose, once you have confirmed the payment.
|
||||||
|
</p>
|
||||||
|
</description>
|
||||||
|
<url type="homepage">https://catcrafts.net</url>
|
||||||
|
<provides>
|
||||||
|
<binary>nostro</binary>
|
||||||
|
</provides>
|
||||||
|
<content_rating type="oars-1.1"/>
|
||||||
|
</component>
|
||||||
|
|
@ -1,13 +1,15 @@
|
||||||
# SPDX-License-Identifier: LGPL-3.0-only
|
# SPDX-License-Identifier: LGPL-3.0-only
|
||||||
# SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
# SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
#
|
#
|
||||||
# nostro as a Flatpak: the CLI, which is the command, and nostrod, which systemd runs from it as the system user nostro
|
# nostrod and the nostro command as a Flatpak: the CLI, which is the command, and nostrod, which systemd runs from it as
|
||||||
# (packaging/system/nostrod.service). Install it system-wide, with the system files packaging/system/install.sh or
|
# the system user nostro (packaging/system/nostrod.service). Install it system-wide, with the system files
|
||||||
# packaging/arch/PKGBUILD put in place; a Flatpak cannot install those itself.
|
# packaging/system/install.sh or packaging/arch/PKGBUILD put in place; a Flatpak cannot install those itself. Its id was
|
||||||
|
# net.catcrafts.Nostro until the Nostro app took that name; install.sh moves the state of a nostrod installed under it.
|
||||||
#
|
#
|
||||||
# Built with crafter-build's own Flatpak as the base app, for its clang 23 and libc++, then stripped back to the two
|
# Built with crafter-build's own Flatpak as the base app, for its clang 23 and libc++, then stripped back to the two
|
||||||
# binaries and the three C++ runtime libraries they link. libssl, libcrypto and libsystemd come from the Platform.
|
# binaries and the three C++ runtime libraries they link. libssl, libcrypto and libsystemd come from the Platform. That
|
||||||
app-id: net.catcrafts.Nostro
|
# base app exists for x86_64 alone: the aarch64 Flatpak, for a phone, is a cross build, packaging/flatpak/build-aarch64.sh.
|
||||||
|
app-id: net.catcrafts.Nostrod
|
||||||
runtime: org.freedesktop.Platform
|
runtime: org.freedesktop.Platform
|
||||||
runtime-version: '26.08'
|
runtime-version: '26.08'
|
||||||
sdk: org.freedesktop.Sdk
|
sdk: org.freedesktop.Sdk
|
||||||
|
|
@ -24,23 +26,19 @@ modules:
|
||||||
- name: nostro
|
- name: nostro
|
||||||
buildsystem: simple
|
buildsystem: simple
|
||||||
build-options:
|
build-options:
|
||||||
# crafter-build fetches Crafter.Network, Crafter.Thread, Crafter.DB and Crafter.LintRules from git, unpinned (see
|
# crafter-build fetches Crafter.Network, Crafter.Thread, Crafter.DB and Crafter.LintRules from git, unpinned, and
|
||||||
# AGENTS.md).
|
# Crafter.Debug's build helper at a pinned commit (see AGENTS.md).
|
||||||
build-args:
|
build-args:
|
||||||
- --share=network
|
- --share=network
|
||||||
# A baseline CPU: crafter-build builds for the building machine's own (-march=native) unless told otherwise.
|
|
||||||
env:
|
|
||||||
NOSTRO_MARCH: x86-64-v2
|
|
||||||
arch:
|
|
||||||
aarch64:
|
|
||||||
env:
|
|
||||||
NOSTRO_MARCH: armv8-a
|
|
||||||
build-commands:
|
build-commands:
|
||||||
- HOME="$PWD/.home" crafter-build --banks=bunq --march=$NOSTRO_MARCH --mtune=generic
|
# A baseline CPU: crafter-build builds for the building machine's own (-march=native) unless told otherwise.
|
||||||
- HOME="$PWD/.home" crafter-build --banks=bunq --product=daemon --march=$NOSTRO_MARCH --mtune=generic
|
- HOME="$PWD/.home" crafter-build --banks=bunq --march=x86-64-v2 --mtune=generic
|
||||||
|
- HOME="$PWD/.home" crafter-build --banks=bunq --product=daemon --march=x86-64-v2 --mtune=generic
|
||||||
- install -Dm755 "$(ls -t bin/nostro-*/nostro | head -n1)" /app/bin/nostro
|
- install -Dm755 "$(ls -t bin/nostro-*/nostro | head -n1)" /app/bin/nostro
|
||||||
- install -Dm755 "$(ls -t bin/nostrod-*/nostrod | head -n1)" /app/bin/nostrod
|
- install -Dm755 "$(ls -t bin/nostrod-*/nostrod | head -n1)" /app/bin/nostrod
|
||||||
- install -Dm644 packaging/flatpak/net.catcrafts.Nostro.metainfo.xml -t /app/share/metainfo/
|
- install -Dm644 packaging/flatpak/net.catcrafts.Nostrod.metainfo.xml -t /app/share/metainfo/
|
||||||
|
# The licences of what it carries besides Nostro itself; packaging/licenses/NOTICE says what each text covers.
|
||||||
|
- install -Dm644 packaging/licenses/NOTICE packaging/licenses/nlohmann-json-MIT.txt packaging/licenses/LLVM-LICENSE.TXT -t /app/share/licenses/net.catcrafts.Nostrod/
|
||||||
sources:
|
sources:
|
||||||
- type: dir
|
- type: dir
|
||||||
path: ../..
|
path: ../..
|
||||||
|
|
@ -51,13 +49,12 @@ modules:
|
||||||
- build
|
- build
|
||||||
cleanup-commands:
|
cleanup-commands:
|
||||||
# The base app's toolchain is in /app too: keep what nostro needs at run time, its metainfo, and the licenses of what
|
# The base app's toolchain is in /app too: keep what nostro needs at run time, its metainfo, and the licenses of what
|
||||||
# it ships: its own, which flatpak-builder recorded, and LLVM's, for libc++, libc++abi and libunwind.
|
# it ships: its own, which flatpak-builder recorded, and the ones the build put beside them.
|
||||||
- mkdir -p /var/tmp/keep/bin /var/tmp/keep/lib /var/tmp/keep/share/metainfo /var/tmp/keep/share/licenses
|
- mkdir -p /var/tmp/keep/bin /var/tmp/keep/lib /var/tmp/keep/share/metainfo /var/tmp/keep/share/licenses
|
||||||
- cp -a /app/bin/nostro /app/bin/nostrod /var/tmp/keep/bin/
|
- cp -a /app/bin/nostro /app/bin/nostrod /var/tmp/keep/bin/
|
||||||
- cp -a /app/lib/libc++.so.1* /app/lib/libc++abi.so.1* /app/lib/libunwind.so.1* /var/tmp/keep/lib/
|
- cp -a /app/lib/libc++.so.1* /app/lib/libc++abi.so.1* /app/lib/libunwind.so.1* /var/tmp/keep/lib/
|
||||||
- cp -a /app/share/metainfo/net.catcrafts.Nostro.metainfo.xml /var/tmp/keep/share/metainfo/
|
- cp -a /app/share/metainfo/net.catcrafts.Nostrod.metainfo.xml /var/tmp/keep/share/metainfo/
|
||||||
- cp -a /app/share/licenses/net.catcrafts.Nostro /var/tmp/keep/share/licenses/
|
- cp -a /app/share/licenses/net.catcrafts.Nostrod /var/tmp/keep/share/licenses/
|
||||||
- install -Dm644 /app/share/licenses/net.catcrafts.CrafterBuild/llvm/LICENSE.TXT /var/tmp/keep/share/licenses/net.catcrafts.Nostro/llvm/LICENSE.TXT
|
|
||||||
- find /app -mindepth 1 -maxdepth 1 -exec rm -rf {} +
|
- find /app -mindepth 1 -maxdepth 1 -exec rm -rf {} +
|
||||||
- cp -a /var/tmp/keep/. /app/
|
- cp -a /var/tmp/keep/. /app/
|
||||||
- rm -rf /var/tmp/keep
|
- rm -rf /var/tmp/keep
|
||||||
279
packaging/licenses/LLVM-LICENSE.TXT
Normal file
279
packaging/licenses/LLVM-LICENSE.TXT
Normal file
|
|
@ -0,0 +1,279 @@
|
||||||
|
==============================================================================
|
||||||
|
The LLVM Project is under the Apache License v2.0 with LLVM Exceptions:
|
||||||
|
==============================================================================
|
||||||
|
|
||||||
|
Apache License
|
||||||
|
Version 2.0, January 2004
|
||||||
|
http://www.apache.org/licenses/
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||||
|
|
||||||
|
1. Definitions.
|
||||||
|
|
||||||
|
"License" shall mean the terms and conditions for use, reproduction,
|
||||||
|
and distribution as defined by Sections 1 through 9 of this document.
|
||||||
|
|
||||||
|
"Licensor" shall mean the copyright owner or entity authorized by
|
||||||
|
the copyright owner that is granting the License.
|
||||||
|
|
||||||
|
"Legal Entity" shall mean the union of the acting entity and all
|
||||||
|
other entities that control, are controlled by, or are under common
|
||||||
|
control with that entity. For the purposes of this definition,
|
||||||
|
"control" means (i) the power, direct or indirect, to cause the
|
||||||
|
direction or management of such entity, whether by contract or
|
||||||
|
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||||
|
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||||
|
|
||||||
|
"You" (or "Your") shall mean an individual or Legal Entity
|
||||||
|
exercising permissions granted by this License.
|
||||||
|
|
||||||
|
"Source" form shall mean the preferred form for making modifications,
|
||||||
|
including but not limited to software source code, documentation
|
||||||
|
source, and configuration files.
|
||||||
|
|
||||||
|
"Object" form shall mean any form resulting from mechanical
|
||||||
|
transformation or translation of a Source form, including but
|
||||||
|
not limited to compiled object code, generated documentation,
|
||||||
|
and conversions to other media types.
|
||||||
|
|
||||||
|
"Work" shall mean the work of authorship, whether in Source or
|
||||||
|
Object form, made available under the License, as indicated by a
|
||||||
|
copyright notice that is included in or attached to the work
|
||||||
|
(an example is provided in the Appendix below).
|
||||||
|
|
||||||
|
"Derivative Works" shall mean any work, whether in Source or Object
|
||||||
|
form, that is based on (or derived from) the Work and for which the
|
||||||
|
editorial revisions, annotations, elaborations, or other modifications
|
||||||
|
represent, as a whole, an original work of authorship. For the purposes
|
||||||
|
of this License, Derivative Works shall not include works that remain
|
||||||
|
separable from, or merely link (or bind by name) to the interfaces of,
|
||||||
|
the Work and Derivative Works thereof.
|
||||||
|
|
||||||
|
"Contribution" shall mean any work of authorship, including
|
||||||
|
the original version of the Work and any modifications or additions
|
||||||
|
to that Work or Derivative Works thereof, that is intentionally
|
||||||
|
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||||
|
or by an individual or Legal Entity authorized to submit on behalf of
|
||||||
|
the copyright owner. For the purposes of this definition, "submitted"
|
||||||
|
means any form of electronic, verbal, or written communication sent
|
||||||
|
to the Licensor or its representatives, including but not limited to
|
||||||
|
communication on electronic mailing lists, source code control systems,
|
||||||
|
and issue tracking systems that are managed by, or on behalf of, the
|
||||||
|
Licensor for the purpose of discussing and improving the Work, but
|
||||||
|
excluding communication that is conspicuously marked or otherwise
|
||||||
|
designated in writing by the copyright owner as "Not a Contribution."
|
||||||
|
|
||||||
|
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||||
|
on behalf of whom a Contribution has been received by Licensor and
|
||||||
|
subsequently incorporated within the Work.
|
||||||
|
|
||||||
|
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
copyright license to reproduce, prepare Derivative Works of,
|
||||||
|
publicly display, publicly perform, sublicense, and distribute the
|
||||||
|
Work and such Derivative Works in Source or Object form.
|
||||||
|
|
||||||
|
3. Grant of Patent License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
(except as stated in this section) patent license to make, have made,
|
||||||
|
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||||
|
where such license applies only to those patent claims licensable
|
||||||
|
by such Contributor that are necessarily infringed by their
|
||||||
|
Contribution(s) alone or by combination of their Contribution(s)
|
||||||
|
with the Work to which such Contribution(s) was submitted. If You
|
||||||
|
institute patent litigation against any entity (including a
|
||||||
|
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||||
|
or a Contribution incorporated within the Work constitutes direct
|
||||||
|
or contributory patent infringement, then any patent licenses
|
||||||
|
granted to You under this License for that Work shall terminate
|
||||||
|
as of the date such litigation is filed.
|
||||||
|
|
||||||
|
4. Redistribution. You may reproduce and distribute copies of the
|
||||||
|
Work or Derivative Works thereof in any medium, with or without
|
||||||
|
modifications, and in Source or Object form, provided that You
|
||||||
|
meet the following conditions:
|
||||||
|
|
||||||
|
(a) You must give any other recipients of the Work or
|
||||||
|
Derivative Works a copy of this License; and
|
||||||
|
|
||||||
|
(b) You must cause any modified files to carry prominent notices
|
||||||
|
stating that You changed the files; and
|
||||||
|
|
||||||
|
(c) You must retain, in the Source form of any Derivative Works
|
||||||
|
that You distribute, all copyright, patent, trademark, and
|
||||||
|
attribution notices from the Source form of the Work,
|
||||||
|
excluding those notices that do not pertain to any part of
|
||||||
|
the Derivative Works; and
|
||||||
|
|
||||||
|
(d) If the Work includes a "NOTICE" text file as part of its
|
||||||
|
distribution, then any Derivative Works that You distribute must
|
||||||
|
include a readable copy of the attribution notices contained
|
||||||
|
within such NOTICE file, excluding those notices that do not
|
||||||
|
pertain to any part of the Derivative Works, in at least one
|
||||||
|
of the following places: within a NOTICE text file distributed
|
||||||
|
as part of the Derivative Works; within the Source form or
|
||||||
|
documentation, if provided along with the Derivative Works; or,
|
||||||
|
within a display generated by the Derivative Works, if and
|
||||||
|
wherever such third-party notices normally appear. The contents
|
||||||
|
of the NOTICE file are for informational purposes only and
|
||||||
|
do not modify the License. You may add Your own attribution
|
||||||
|
notices within Derivative Works that You distribute, alongside
|
||||||
|
or as an addendum to the NOTICE text from the Work, provided
|
||||||
|
that such additional attribution notices cannot be construed
|
||||||
|
as modifying the License.
|
||||||
|
|
||||||
|
You may add Your own copyright statement to Your modifications and
|
||||||
|
may provide additional or different license terms and conditions
|
||||||
|
for use, reproduction, or distribution of Your modifications, or
|
||||||
|
for any such Derivative Works as a whole, provided Your use,
|
||||||
|
reproduction, and distribution of the Work otherwise complies with
|
||||||
|
the conditions stated in this License.
|
||||||
|
|
||||||
|
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||||
|
any Contribution intentionally submitted for inclusion in the Work
|
||||||
|
by You to the Licensor shall be under the terms and conditions of
|
||||||
|
this License, without any additional terms or conditions.
|
||||||
|
Notwithstanding the above, nothing herein shall supersede or modify
|
||||||
|
the terms of any separate license agreement you may have executed
|
||||||
|
with Licensor regarding such Contributions.
|
||||||
|
|
||||||
|
6. Trademarks. This License does not grant permission to use the trade
|
||||||
|
names, trademarks, service marks, or product names of the Licensor,
|
||||||
|
except as required for reasonable and customary use in describing the
|
||||||
|
origin of the Work and reproducing the content of the NOTICE file.
|
||||||
|
|
||||||
|
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||||
|
agreed to in writing, Licensor provides the Work (and each
|
||||||
|
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||||
|
implied, including, without limitation, any warranties or conditions
|
||||||
|
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||||
|
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||||
|
appropriateness of using or redistributing the Work and assume any
|
||||||
|
risks associated with Your exercise of permissions under this License.
|
||||||
|
|
||||||
|
8. Limitation of Liability. In no event and under no legal theory,
|
||||||
|
whether in tort (including negligence), contract, or otherwise,
|
||||||
|
unless required by applicable law (such as deliberate and grossly
|
||||||
|
negligent acts) or agreed to in writing, shall any Contributor be
|
||||||
|
liable to You for damages, including any direct, indirect, special,
|
||||||
|
incidental, or consequential damages of any character arising as a
|
||||||
|
result of this License or out of the use or inability to use the
|
||||||
|
Work (including but not limited to damages for loss of goodwill,
|
||||||
|
work stoppage, computer failure or malfunction, or any and all
|
||||||
|
other commercial damages or losses), even if such Contributor
|
||||||
|
has been advised of the possibility of such damages.
|
||||||
|
|
||||||
|
9. Accepting Warranty or Additional Liability. While redistributing
|
||||||
|
the Work or Derivative Works thereof, You may choose to offer,
|
||||||
|
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||||
|
or other liability obligations and/or rights consistent with this
|
||||||
|
License. However, in accepting such obligations, You may act only
|
||||||
|
on Your own behalf and on Your sole responsibility, not on behalf
|
||||||
|
of any other Contributor, and only if You agree to indemnify,
|
||||||
|
defend, and hold each Contributor harmless for any liability
|
||||||
|
incurred by, or claims asserted against, such Contributor by reason
|
||||||
|
of your accepting any such warranty or additional liability.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
APPENDIX: How to apply the Apache License to your work.
|
||||||
|
|
||||||
|
To apply the Apache License to your work, attach the following
|
||||||
|
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||||
|
replaced with your own identifying information. (Don't include
|
||||||
|
the brackets!) The text should be enclosed in the appropriate
|
||||||
|
comment syntax for the file format. We also recommend that a
|
||||||
|
file or class name and description of purpose be included on the
|
||||||
|
same "printed page" as the copyright notice for easier
|
||||||
|
identification within third-party archives.
|
||||||
|
|
||||||
|
Copyright [yyyy] [name of copyright owner]
|
||||||
|
|
||||||
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
you may not use this file except in compliance with the License.
|
||||||
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
|
http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
|
Unless required by applicable law or agreed to in writing, software
|
||||||
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
See the License for the specific language governing permissions and
|
||||||
|
limitations under the License.
|
||||||
|
|
||||||
|
|
||||||
|
---- LLVM Exceptions to the Apache 2.0 License ----
|
||||||
|
|
||||||
|
As an exception, if, as a result of your compiling your source code, portions
|
||||||
|
of this Software are embedded into an Object form of such source code, you
|
||||||
|
may redistribute such embedded portions in such Object form without complying
|
||||||
|
with the conditions of Sections 4(a), 4(b) and 4(d) of the License.
|
||||||
|
|
||||||
|
In addition, if you combine or link compiled forms of this Software with
|
||||||
|
software that is licensed under the GPLv2 ("Combined Software") and if a
|
||||||
|
court of competent jurisdiction determines that the patent provision (Section
|
||||||
|
3), the indemnity provision (Section 9) or other Section of the License
|
||||||
|
conflicts with the conditions of the GPLv2, you may retroactively and
|
||||||
|
prospectively choose to deem waived or otherwise exclude such Section(s) of
|
||||||
|
the License, but only in their entirety and only with respect to the Combined
|
||||||
|
Software.
|
||||||
|
|
||||||
|
==============================================================================
|
||||||
|
Software from third parties included in the LLVM Project:
|
||||||
|
==============================================================================
|
||||||
|
The LLVM Project contains third party software which is under different license
|
||||||
|
terms. All such code will be identified clearly using at least one of two
|
||||||
|
mechanisms:
|
||||||
|
1) It will be in a separate directory tree with its own `LICENSE.txt` or
|
||||||
|
`LICENSE` file at the top containing the specific license and restrictions
|
||||||
|
which apply to that software, or
|
||||||
|
2) It will contain specific license and restriction terms at the top of every
|
||||||
|
file.
|
||||||
|
|
||||||
|
==============================================================================
|
||||||
|
Legacy LLVM License (https://llvm.org/docs/DeveloperPolicy.html#legacy):
|
||||||
|
==============================================================================
|
||||||
|
University of Illinois/NCSA
|
||||||
|
Open Source License
|
||||||
|
|
||||||
|
Copyright (c) 2003-2019 University of Illinois at Urbana-Champaign.
|
||||||
|
All rights reserved.
|
||||||
|
|
||||||
|
Developed by:
|
||||||
|
|
||||||
|
LLVM Team
|
||||||
|
|
||||||
|
University of Illinois at Urbana-Champaign
|
||||||
|
|
||||||
|
http://llvm.org
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||||
|
this software and associated documentation files (the "Software"), to deal with
|
||||||
|
the Software without restriction, including without limitation the rights to
|
||||||
|
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||||
|
of the Software, and to permit persons to whom the Software is furnished to do
|
||||||
|
so, subject to the following conditions:
|
||||||
|
|
||||||
|
* Redistributions of source code must retain the above copyright notice,
|
||||||
|
this list of conditions and the following disclaimers.
|
||||||
|
|
||||||
|
* Redistributions in binary form must reproduce the above copyright notice,
|
||||||
|
this list of conditions and the following disclaimers in the
|
||||||
|
documentation and/or other materials provided with the distribution.
|
||||||
|
|
||||||
|
* Neither the names of the LLVM Team, University of Illinois at
|
||||||
|
Urbana-Champaign, nor the names of its contributors may be used to
|
||||||
|
endorse or promote products derived from this Software without specific
|
||||||
|
prior written permission.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||||
|
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
|
||||||
|
SOFTWARE.
|
||||||
|
|
||||||
36
packaging/licenses/NOTICE
Normal file
36
packaging/licenses/NOTICE
Normal file
|
|
@ -0,0 +1,36 @@
|
||||||
|
/app/share/licenses/<app-id> in Nostro's Flatpaks holds the licences of
|
||||||
|
what they carry.
|
||||||
|
|
||||||
|
The service with the nostro command (net.catcrafts.Nostrod):
|
||||||
|
|
||||||
|
- LICENSE and LICENSE.GPL (under nostro/ where flatpak-builder put them):
|
||||||
|
nostrod, the nostro command and the library they are built from
|
||||||
|
(LGPL-3.0-only: the GNU LGPL version 3, and the GNU GPL version 3 it adds
|
||||||
|
its permissions to). The Crafter libraries linked in statically are under
|
||||||
|
the same licence: Crafter.Network with Crafter.Thread, and Crafter.DB.
|
||||||
|
Their source: https://forgejo.catcrafts.net/Catcrafts/<name>.
|
||||||
|
- nlohmann-json-MIT.txt: nlohmann/json 3.12.0, which Nostro carries
|
||||||
|
(lib/json.hpp) and compiles in.
|
||||||
|
- LLVM-LICENSE.TXT: LLVM's libc++, libc++abi and libunwind in /app/lib
|
||||||
|
(the Apache License 2.0 with LLVM Exceptions, and for older code the
|
||||||
|
University of Illinois/NCSA licence).
|
||||||
|
|
||||||
|
The app (net.catcrafts.Nostro) carries those three, and:
|
||||||
|
|
||||||
|
- LICENSE.GPL: the app itself (GPL-3.0-only: the GNU GPL version 3).
|
||||||
|
Nostro's library is linked into it under the LGPL in LICENSE, as above,
|
||||||
|
and so are the Crafter libraries: those two, and Crafter.Graphics with
|
||||||
|
Crafter.Event, Crafter.Math and Crafter.Asset.
|
||||||
|
- OFL.txt: the Noto Sans font (the SIL Open Font License 1.1).
|
||||||
|
- stb-LICENSE.txt: stb_truetype and stb_image_write, which
|
||||||
|
Crafter.Graphics carries and compiles in.
|
||||||
|
- wayland-protocols-NOTICE.txt: the code wayland-scanner generated for
|
||||||
|
the xdg-shell, xdg-decoration-unstable-v1, fractional-scale-v1,
|
||||||
|
viewporter and text-input-unstable-v3 protocols, which Crafter.Graphics
|
||||||
|
carries and compiles in.
|
||||||
|
- Vulkan-Utility-Libraries-Apache-2.0.txt: vk_enum_string_helper.h of the
|
||||||
|
Vulkan Utility Libraries (Copyright 2023-2025 The Khronos Group Inc.,
|
||||||
|
Valve Corporation, LunarG, Inc.), which Crafter.Graphics compiles in:
|
||||||
|
the Apache License 2.0.
|
||||||
|
- libevdev-COPYING.txt: libevdev, which Crafter.Graphics carries and
|
||||||
|
builds as a static library (MIT).
|
||||||
202
packaging/licenses/Vulkan-Utility-Libraries-Apache-2.0.txt
Normal file
202
packaging/licenses/Vulkan-Utility-Libraries-Apache-2.0.txt
Normal file
|
|
@ -0,0 +1,202 @@
|
||||||
|
|
||||||
|
Apache License
|
||||||
|
Version 2.0, January 2004
|
||||||
|
http://www.apache.org/licenses/
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||||
|
|
||||||
|
1. Definitions.
|
||||||
|
|
||||||
|
"License" shall mean the terms and conditions for use, reproduction,
|
||||||
|
and distribution as defined by Sections 1 through 9 of this document.
|
||||||
|
|
||||||
|
"Licensor" shall mean the copyright owner or entity authorized by
|
||||||
|
the copyright owner that is granting the License.
|
||||||
|
|
||||||
|
"Legal Entity" shall mean the union of the acting entity and all
|
||||||
|
other entities that control, are controlled by, or are under common
|
||||||
|
control with that entity. For the purposes of this definition,
|
||||||
|
"control" means (i) the power, direct or indirect, to cause the
|
||||||
|
direction or management of such entity, whether by contract or
|
||||||
|
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||||
|
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||||
|
|
||||||
|
"You" (or "Your") shall mean an individual or Legal Entity
|
||||||
|
exercising permissions granted by this License.
|
||||||
|
|
||||||
|
"Source" form shall mean the preferred form for making modifications,
|
||||||
|
including but not limited to software source code, documentation
|
||||||
|
source, and configuration files.
|
||||||
|
|
||||||
|
"Object" form shall mean any form resulting from mechanical
|
||||||
|
transformation or translation of a Source form, including but
|
||||||
|
not limited to compiled object code, generated documentation,
|
||||||
|
and conversions to other media types.
|
||||||
|
|
||||||
|
"Work" shall mean the work of authorship, whether in Source or
|
||||||
|
Object form, made available under the License, as indicated by a
|
||||||
|
copyright notice that is included in or attached to the work
|
||||||
|
(an example is provided in the Appendix below).
|
||||||
|
|
||||||
|
"Derivative Works" shall mean any work, whether in Source or Object
|
||||||
|
form, that is based on (or derived from) the Work and for which the
|
||||||
|
editorial revisions, annotations, elaborations, or other modifications
|
||||||
|
represent, as a whole, an original work of authorship. For the purposes
|
||||||
|
of this License, Derivative Works shall not include works that remain
|
||||||
|
separable from, or merely link (or bind by name) to the interfaces of,
|
||||||
|
the Work and Derivative Works thereof.
|
||||||
|
|
||||||
|
"Contribution" shall mean any work of authorship, including
|
||||||
|
the original version of the Work and any modifications or additions
|
||||||
|
to that Work or Derivative Works thereof, that is intentionally
|
||||||
|
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||||
|
or by an individual or Legal Entity authorized to submit on behalf of
|
||||||
|
the copyright owner. For the purposes of this definition, "submitted"
|
||||||
|
means any form of electronic, verbal, or written communication sent
|
||||||
|
to the Licensor or its representatives, including but not limited to
|
||||||
|
communication on electronic mailing lists, source code control systems,
|
||||||
|
and issue tracking systems that are managed by, or on behalf of, the
|
||||||
|
Licensor for the purpose of discussing and improving the Work, but
|
||||||
|
excluding communication that is conspicuously marked or otherwise
|
||||||
|
designated in writing by the copyright owner as "Not a Contribution."
|
||||||
|
|
||||||
|
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||||
|
on behalf of whom a Contribution has been received by Licensor and
|
||||||
|
subsequently incorporated within the Work.
|
||||||
|
|
||||||
|
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
copyright license to reproduce, prepare Derivative Works of,
|
||||||
|
publicly display, publicly perform, sublicense, and distribute the
|
||||||
|
Work and such Derivative Works in Source or Object form.
|
||||||
|
|
||||||
|
3. Grant of Patent License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
(except as stated in this section) patent license to make, have made,
|
||||||
|
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||||
|
where such license applies only to those patent claims licensable
|
||||||
|
by such Contributor that are necessarily infringed by their
|
||||||
|
Contribution(s) alone or by combination of their Contribution(s)
|
||||||
|
with the Work to which such Contribution(s) was submitted. If You
|
||||||
|
institute patent litigation against any entity (including a
|
||||||
|
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||||
|
or a Contribution incorporated within the Work constitutes direct
|
||||||
|
or contributory patent infringement, then any patent licenses
|
||||||
|
granted to You under this License for that Work shall terminate
|
||||||
|
as of the date such litigation is filed.
|
||||||
|
|
||||||
|
4. Redistribution. You may reproduce and distribute copies of the
|
||||||
|
Work or Derivative Works thereof in any medium, with or without
|
||||||
|
modifications, and in Source or Object form, provided that You
|
||||||
|
meet the following conditions:
|
||||||
|
|
||||||
|
(a) You must give any other recipients of the Work or
|
||||||
|
Derivative Works a copy of this License; and
|
||||||
|
|
||||||
|
(b) You must cause any modified files to carry prominent notices
|
||||||
|
stating that You changed the files; and
|
||||||
|
|
||||||
|
(c) You must retain, in the Source form of any Derivative Works
|
||||||
|
that You distribute, all copyright, patent, trademark, and
|
||||||
|
attribution notices from the Source form of the Work,
|
||||||
|
excluding those notices that do not pertain to any part of
|
||||||
|
the Derivative Works; and
|
||||||
|
|
||||||
|
(d) If the Work includes a "NOTICE" text file as part of its
|
||||||
|
distribution, then any Derivative Works that You distribute must
|
||||||
|
include a readable copy of the attribution notices contained
|
||||||
|
within such NOTICE file, excluding those notices that do not
|
||||||
|
pertain to any part of the Derivative Works, in at least one
|
||||||
|
of the following places: within a NOTICE text file distributed
|
||||||
|
as part of the Derivative Works; within the Source form or
|
||||||
|
documentation, if provided along with the Derivative Works; or,
|
||||||
|
within a display generated by the Derivative Works, if and
|
||||||
|
wherever such third-party notices normally appear. The contents
|
||||||
|
of the NOTICE file are for informational purposes only and
|
||||||
|
do not modify the License. You may add Your own attribution
|
||||||
|
notices within Derivative Works that You distribute, alongside
|
||||||
|
or as an addendum to the NOTICE text from the Work, provided
|
||||||
|
that such additional attribution notices cannot be construed
|
||||||
|
as modifying the License.
|
||||||
|
|
||||||
|
You may add Your own copyright statement to Your modifications and
|
||||||
|
may provide additional or different license terms and conditions
|
||||||
|
for use, reproduction, or distribution of Your modifications, or
|
||||||
|
for any such Derivative Works as a whole, provided Your use,
|
||||||
|
reproduction, and distribution of the Work otherwise complies with
|
||||||
|
the conditions stated in this License.
|
||||||
|
|
||||||
|
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||||
|
any Contribution intentionally submitted for inclusion in the Work
|
||||||
|
by You to the Licensor shall be under the terms and conditions of
|
||||||
|
this License, without any additional terms or conditions.
|
||||||
|
Notwithstanding the above, nothing herein shall supersede or modify
|
||||||
|
the terms of any separate license agreement you may have executed
|
||||||
|
with Licensor regarding such Contributions.
|
||||||
|
|
||||||
|
6. Trademarks. This License does not grant permission to use the trade
|
||||||
|
names, trademarks, service marks, or product names of the Licensor,
|
||||||
|
except as required for reasonable and customary use in describing the
|
||||||
|
origin of the Work and reproducing the content of the NOTICE file.
|
||||||
|
|
||||||
|
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||||
|
agreed to in writing, Licensor provides the Work (and each
|
||||||
|
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||||
|
implied, including, without limitation, any warranties or conditions
|
||||||
|
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||||
|
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||||
|
appropriateness of using or redistributing the Work and assume any
|
||||||
|
risks associated with Your exercise of permissions under this License.
|
||||||
|
|
||||||
|
8. Limitation of Liability. In no event and under no legal theory,
|
||||||
|
whether in tort (including negligence), contract, or otherwise,
|
||||||
|
unless required by applicable law (such as deliberate and grossly
|
||||||
|
negligent acts) or agreed to in writing, shall any Contributor be
|
||||||
|
liable to You for damages, including any direct, indirect, special,
|
||||||
|
incidental, or consequential damages of any character arising as a
|
||||||
|
result of this License or out of the use or inability to use the
|
||||||
|
Work (including but not limited to damages for loss of goodwill,
|
||||||
|
work stoppage, computer failure or malfunction, or any and all
|
||||||
|
other commercial damages or losses), even if such Contributor
|
||||||
|
has been advised of the possibility of such damages.
|
||||||
|
|
||||||
|
9. Accepting Warranty or Additional Liability. While redistributing
|
||||||
|
the Work or Derivative Works thereof, You may choose to offer,
|
||||||
|
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||||
|
or other liability obligations and/or rights consistent with this
|
||||||
|
License. However, in accepting such obligations, You may act only
|
||||||
|
on Your own behalf and on Your sole responsibility, not on behalf
|
||||||
|
of any other Contributor, and only if You agree to indemnify,
|
||||||
|
defend, and hold each Contributor harmless for any liability
|
||||||
|
incurred by, or claims asserted against, such Contributor by reason
|
||||||
|
of your accepting any such warranty or additional liability.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
APPENDIX: How to apply the Apache License to your work.
|
||||||
|
|
||||||
|
To apply the Apache License to your work, attach the following
|
||||||
|
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||||
|
replaced with your own identifying information. (Don't include
|
||||||
|
the brackets!) The text should be enclosed in the appropriate
|
||||||
|
comment syntax for the file format. We also recommend that a
|
||||||
|
file or class name and description of purpose be included on the
|
||||||
|
same "printed page" as the copyright notice for easier
|
||||||
|
identification within third-party archives.
|
||||||
|
|
||||||
|
Copyright [yyyy] [name of copyright owner]
|
||||||
|
|
||||||
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
you may not use this file except in compliance with the License.
|
||||||
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
|
http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
|
Unless required by applicable law or agreed to in writing, software
|
||||||
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
See the License for the specific language governing permissions and
|
||||||
|
limitations under the License.
|
||||||
32
packaging/licenses/libevdev-COPYING.txt
Normal file
32
packaging/licenses/libevdev-COPYING.txt
Normal file
|
|
@ -0,0 +1,32 @@
|
||||||
|
SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
Copyright © 2013 Red Hat, Inc.
|
||||||
|
Copyright © 2013 David Herrmann <dh.herrmann@gmail.com>
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to
|
||||||
|
deal in the Software without restriction, including without limitation the
|
||||||
|
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
||||||
|
sell copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice (including the next
|
||||||
|
paragraph) shall be included in all copies or substantial portions of the
|
||||||
|
Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||||
|
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
||||||
|
IN THE SOFTWARE.
|
||||||
|
|
||||||
|
The following license is from a Linux kernel header file and there is no GPL
|
||||||
|
code this package links to.
|
||||||
|
|
||||||
|
Copyright (c) 1999-2002 Vojtech Pavlik
|
||||||
|
|
||||||
|
This program is free software; you can redistribute it and/or modify it
|
||||||
|
under the terms of the GNU General Public License version 2 as published by
|
||||||
|
the Free Software Foundation.
|
||||||
27
packaging/licenses/nlohmann-json-MIT.txt
Normal file
27
packaging/licenses/nlohmann-json-MIT.txt
Normal file
|
|
@ -0,0 +1,27 @@
|
||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2013-2026 Niels Lohmann
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
|
|
||||||
|
nlohmann/json contains the UTF-8 decoder of Bjoern Hoehrmann
|
||||||
|
(Copyright (c) 2008-2009 Bjoern Hoehrmann <bjoern@hoehrmann.de>) and a
|
||||||
|
modified version of the Grisu2 algorithm of Florian Loitsch
|
||||||
|
(Copyright (c) 2009 Florian Loitsch), both under the MIT License above, and
|
||||||
|
a copy of Hedley of Evan Nemerson, which is in the public domain (CC0).
|
||||||
47
packaging/licenses/stb-LICENSE.txt
Normal file
47
packaging/licenses/stb-LICENSE.txt
Normal file
|
|
@ -0,0 +1,47 @@
|
||||||
|
stb_truetype.h v1.26, Sean Barrett (lib/stb_truetype.h of Crafter.Graphics):
|
||||||
|
|
||||||
|
------------------------------------------------------------------------------
|
||||||
|
This software is available under 2 licenses -- choose whichever you prefer.
|
||||||
|
------------------------------------------------------------------------------
|
||||||
|
ALTERNATIVE A - MIT License
|
||||||
|
Copyright (c) 2017 Sean Barrett
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||||
|
this software and associated documentation files (the "Software"), to deal in
|
||||||
|
the Software without restriction, including without limitation the rights to
|
||||||
|
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||||
|
of the Software, and to permit persons to whom the Software is furnished to do
|
||||||
|
so, subject to the following conditions:
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
|
------------------------------------------------------------------------------
|
||||||
|
ALTERNATIVE B - Public Domain (www.unlicense.org)
|
||||||
|
This is free and unencumbered software released into the public domain.
|
||||||
|
Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
|
||||||
|
software, either in source code form or as a compiled binary, for any purpose,
|
||||||
|
commercial or non-commercial, and by any means.
|
||||||
|
In jurisdictions that recognize copyright laws, the author or authors of this
|
||||||
|
software dedicate any and all copyright interest in the software to the public
|
||||||
|
domain. We make this dedication for the benefit of the public at large and to
|
||||||
|
the detriment of our heirs and successors. We intend this dedication to be an
|
||||||
|
overt act of relinquishment in perpetuity of all present and future rights to
|
||||||
|
this software under copyright law.
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
|
||||||
|
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||||
|
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||||
|
------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
stb_image_write.h v1.02, Sean Barrett (lib/stb_image_write.h of Crafter.Graphics):
|
||||||
|
|
||||||
|
This software is dual-licensed to the public domain and under the following
|
||||||
|
license: you are granted a perpetual, irrevocable license to copy, modify,
|
||||||
|
publish, and distribute this file as you see fit.
|
||||||
127
packaging/licenses/wayland-protocols-NOTICE.txt
Normal file
127
packaging/licenses/wayland-protocols-NOTICE.txt
Normal file
|
|
@ -0,0 +1,127 @@
|
||||||
|
The copyright and permission notices of the Wayland protocols whose
|
||||||
|
wayland-scanner code Crafter.Graphics carries and compiles in.
|
||||||
|
|
||||||
|
xdg-shell:
|
||||||
|
|
||||||
|
Copyright © 2008-2013 Kristian Høgsberg
|
||||||
|
Copyright © 2013 Rafael Antognolli
|
||||||
|
Copyright © 2013 Jasper St. Pierre
|
||||||
|
Copyright © 2010-2013 Intel Corporation
|
||||||
|
Copyright © 2015-2017 Samsung Electronics Co., Ltd
|
||||||
|
Copyright © 2015-2017 Red Hat Inc.
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a
|
||||||
|
copy of this software and associated documentation files (the "Software"),
|
||||||
|
to deal in the Software without restriction, including without limitation
|
||||||
|
the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||||
|
and/or sell copies of the Software, and to permit persons to whom the
|
||||||
|
Software is furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice (including the next
|
||||||
|
paragraph) shall be included in all copies or substantial portions of the
|
||||||
|
Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
|
||||||
|
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||||
|
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||||
|
DEALINGS IN THE SOFTWARE.
|
||||||
|
|
||||||
|
xdg-decoration-unstable-v1:
|
||||||
|
|
||||||
|
Copyright © 2018 Simon Ser
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a
|
||||||
|
copy of this software and associated documentation files (the "Software"),
|
||||||
|
to deal in the Software without restriction, including without limitation
|
||||||
|
the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||||
|
and/or sell copies of the Software, and to permit persons to whom the
|
||||||
|
Software is furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice (including the next
|
||||||
|
paragraph) shall be included in all copies or substantial portions of the
|
||||||
|
Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
|
||||||
|
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||||
|
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||||
|
DEALINGS IN THE SOFTWARE.
|
||||||
|
|
||||||
|
fractional-scale-v1:
|
||||||
|
|
||||||
|
Copyright © 2022 Kenny Levinsen
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a
|
||||||
|
copy of this software and associated documentation files (the "Software"),
|
||||||
|
to deal in the Software without restriction, including without limitation
|
||||||
|
the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||||
|
and/or sell copies of the Software, and to permit persons to whom the
|
||||||
|
Software is furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice (including the next
|
||||||
|
paragraph) shall be included in all copies or substantial portions of the
|
||||||
|
Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
|
||||||
|
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||||
|
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||||
|
DEALINGS IN THE SOFTWARE.
|
||||||
|
|
||||||
|
viewporter:
|
||||||
|
|
||||||
|
Copyright © 2013-2016 Collabora, Ltd.
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a
|
||||||
|
copy of this software and associated documentation files (the "Software"),
|
||||||
|
to deal in the Software without restriction, including without limitation
|
||||||
|
the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||||
|
and/or sell copies of the Software, and to permit persons to whom the
|
||||||
|
Software is furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice (including the next
|
||||||
|
paragraph) shall be included in all copies or substantial portions of the
|
||||||
|
Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
|
||||||
|
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||||
|
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||||
|
DEALINGS IN THE SOFTWARE.
|
||||||
|
|
||||||
|
text-input-unstable-v3:
|
||||||
|
|
||||||
|
Copyright © 2012, 2013 Intel Corporation
|
||||||
|
Copyright © 2015, 2016 Jan Arne Petersen
|
||||||
|
Copyright © 2017, 2018 Red Hat, Inc.
|
||||||
|
Copyright © 2018 Purism SPC
|
||||||
|
|
||||||
|
Permission to use, copy, modify, distribute, and sell this
|
||||||
|
software and its documentation for any purpose is hereby granted
|
||||||
|
without fee, provided that the above copyright notice appear in
|
||||||
|
all copies and that both that copyright notice and this permission
|
||||||
|
notice appear in supporting documentation, and that the name of
|
||||||
|
the copyright holders not be used in advertising or publicity
|
||||||
|
pertaining to distribution of the software without specific,
|
||||||
|
written prior permission. The copyright holders make no
|
||||||
|
representations about the suitability of this software for any
|
||||||
|
purpose. It is provided "as is" without express or implied
|
||||||
|
warranty.
|
||||||
|
|
||||||
|
THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
|
||||||
|
SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
|
||||||
|
FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||||
|
SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||||
|
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
|
||||||
|
AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
|
||||||
|
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
|
||||||
|
THIS SOFTWARE.
|
||||||
|
|
@ -3,20 +3,29 @@
|
||||||
# SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
# SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
#
|
#
|
||||||
# Installs nostro for every user of this machine: the system files nostrod needs (its user, its D-Bus and polkit
|
# Installs nostro for every user of this machine: the system files nostrod needs (its user, its D-Bus and polkit
|
||||||
# policies, its systemd unit, the nostro command) and the net.catcrafts.Nostro Flatpak, system-wide. Run as root.
|
# policies, its systemd unit, the nostro command) and the net.catcrafts.Nostrod Flatpak, system-wide. Run as root.
|
||||||
#
|
#
|
||||||
# install.sh the Flatpak from the system remote "catcrafts" (packaging/flatpak/net.catcrafts.Nostro.flatpakref
|
# install.sh the Flatpaks from the system remote "catcrafts", the Catcrafts Flatpak repository, added with
|
||||||
# sets it up: flatpak install --system net.catcrafts.Nostro.flatpakref)
|
# flatpak remote-add --system --if-not-exists catcrafts https://flatpak.catcrafts.net/catcrafts.flatpakrepo
|
||||||
# install.sh --repo DIR the Flatpak from a local repository, as flatpak-builder --repo=DIR makes one, for testing
|
# install.sh --repo DIR the Flatpaks from a local repository, as flatpak-builder --repo=DIR makes one, for testing
|
||||||
|
# install.sh --app the Nostro app too, net.catcrafts.Nostro, for every user (each user can install it for
|
||||||
|
# themselves instead)
|
||||||
#
|
#
|
||||||
# Running it again updates. packaging/arch/PKGBUILD installs the same files from a package; uninstall.sh removes them.
|
# Running it again updates. nostrod's Flatpak was net.catcrafts.Nostro until the app took that id: this moves the state a
|
||||||
|
# nostrod installed under it kept, and removes that Flatpak. packaging/arch/PKGBUILD installs the same system files from
|
||||||
|
# a package; uninstall.sh removes them.
|
||||||
set -eu
|
set -eu
|
||||||
here=$(cd "$(dirname "$0")" && pwd)
|
here=$(cd "$(dirname "$0")" && pwd)
|
||||||
|
|
||||||
repo=
|
repo=
|
||||||
if [ "${1:-}" = --repo ]; then
|
app=false
|
||||||
repo=$(cd "${2:?--repo needs a directory}" && pwd)
|
while [ $# -gt 0 ]; do
|
||||||
fi
|
case "$1" in
|
||||||
|
--repo) repo=$(cd "${2:?--repo needs a directory}" && pwd); shift 2 ;;
|
||||||
|
--app) app=true; shift ;;
|
||||||
|
*) echo "install.sh: unknown argument '$1'" >&2; exit 2 ;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
install -Dm644 "$here/nostro.sysusers" /usr/lib/sysusers.d/nostro.conf
|
install -Dm644 "$here/nostro.sysusers" /usr/lib/sysusers.d/nostro.conf
|
||||||
systemd-sysusers /usr/lib/sysusers.d/nostro.conf
|
systemd-sysusers /usr/lib/sysusers.d/nostro.conf
|
||||||
|
|
@ -26,17 +35,39 @@ install -Dm644 "$here/net.catcrafts.Nostro1.Checkout.service" /usr/share/dbus-1/
|
||||||
install -Dm644 "$here/net.catcrafts.Nostro1.policy" /usr/share/polkit-1/actions/net.catcrafts.Nostro1.policy
|
install -Dm644 "$here/net.catcrafts.Nostro1.policy" /usr/share/polkit-1/actions/net.catcrafts.Nostro1.policy
|
||||||
install -Dm644 "$here/nostrod.service" /etc/systemd/system/nostrod.service
|
install -Dm644 "$here/nostrod.service" /etc/systemd/system/nostrod.service
|
||||||
install -Dm755 "$here/nostro" /usr/local/bin/nostro
|
install -Dm755 "$here/nostro" /usr/local/bin/nostro
|
||||||
|
systemctl daemon-reload
|
||||||
|
|
||||||
if [ -n "$repo" ]; then
|
# A nostrod already running keeps the old files until it ends: stop it, and the next call starts the new one. Stopped, it
|
||||||
# A local repository is unsigned: for a build of your own, never for one from elsewhere.
|
# also leaves its state alone while that moves.
|
||||||
flatpak remote-add --system --if-not-exists --no-gpg-verify nostro-local "file://$repo"
|
systemctl stop nostrod.service
|
||||||
flatpak install --system -y --noninteractive --or-update nostro-local net.catcrafts.Nostro//stable
|
|
||||||
else
|
# flatpak keeps an app's data under the app's id, so nostrod's state followed the Flatpak's old id.
|
||||||
flatpak install --system -y --noninteractive --or-update catcrafts net.catcrafts.Nostro//stable
|
apps=/var/lib/nostro/.var/app
|
||||||
|
if [ -d "$apps/net.catcrafts.Nostro" ]; then
|
||||||
|
if [ -e "$apps/net.catcrafts.Nostrod" ]; then
|
||||||
|
echo "install.sh: both $apps/net.catcrafts.Nostro and $apps/net.catcrafts.Nostrod exist; keep the one that holds the bank connections as net.catcrafts.Nostrod, remove the other, and run this again" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
mv "$apps/net.catcrafts.Nostro" "$apps/net.catcrafts.Nostrod"
|
||||||
|
echo "moved nostrod's state from $apps/net.catcrafts.Nostro to $apps/net.catcrafts.Nostrod"
|
||||||
|
fi
|
||||||
|
# The app's Flatpak runs nostro-app; the old nostrod Flatpak ran nostro.
|
||||||
|
if flatpak info --system --show-metadata net.catcrafts.Nostro 2>/dev/null | grep -qx 'command=nostro'; then
|
||||||
|
flatpak uninstall --system -y --noninteractive net.catcrafts.Nostro
|
||||||
|
fi
|
||||||
|
|
||||||
|
remote=catcrafts
|
||||||
|
if [ -n "$repo" ]; then
|
||||||
|
# A local repository is unsigned: for a build of your own, never for one from elsewhere. The remote may be left from
|
||||||
|
# an earlier run with another directory.
|
||||||
|
remote=nostro-local
|
||||||
|
flatpak remote-add --system --if-not-exists --no-gpg-verify nostro-local "file://$repo"
|
||||||
|
flatpak remote-modify --system --no-gpg-verify --url="file://$repo" nostro-local
|
||||||
|
fi
|
||||||
|
flatpak install --system -y --noninteractive --or-update "$remote" net.catcrafts.Nostrod//stable
|
||||||
|
if [ "$app" = true ]; then
|
||||||
|
flatpak install --system -y --noninteractive --or-update "$remote" net.catcrafts.Nostro//stable
|
||||||
fi
|
fi
|
||||||
|
|
||||||
systemctl daemon-reload
|
|
||||||
busctl call org.freedesktop.DBus /org/freedesktop/DBus org.freedesktop.DBus ReloadConfig
|
busctl call org.freedesktop.DBus /org/freedesktop/DBus org.freedesktop.DBus ReloadConfig
|
||||||
# A nostrod already running keeps the old files until it ends; stop it, and the next call starts the new one.
|
|
||||||
systemctl try-restart nostrod.service
|
|
||||||
echo "nostro is installed: nostrod starts with the first call, such as 'nostro connectors add bunq'"
|
echo "nostro is installed: nostrod starts with the first call, such as 'nostro connectors add bunq'"
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@
|
||||||
# SPDX-License-Identifier: LGPL-3.0-only
|
# SPDX-License-Identifier: LGPL-3.0-only
|
||||||
# SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
# SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
#
|
#
|
||||||
# The nostro command: the CLI from the net.catcrafts.Nostro Flatpak, run as you. It asks nostrod over the system bus,
|
# The nostro command: the CLI from the net.catcrafts.Nostrod Flatpak, run as you. It asks nostrod over the system bus,
|
||||||
# and your session's polkit agent asks for your password before anything moves money. Install: /usr/bin/nostro (a
|
# and your session's polkit agent asks for your password before anything moves money. Install: /usr/bin/nostro (a
|
||||||
# package) or /usr/local/bin/nostro (install.sh).
|
# package) or /usr/local/bin/nostro (install.sh).
|
||||||
|
|
||||||
|
|
@ -16,4 +16,4 @@ for old in "${XDG_CONFIG_HOME:-$HOME/.config}/nostro/connectors.json" "${XDG_CON
|
||||||
fi
|
fi
|
||||||
done
|
done
|
||||||
|
|
||||||
exec /usr/bin/flatpak run --system net.catcrafts.Nostro//stable "$@"
|
exec /usr/bin/flatpak run --system net.catcrafts.Nostrod//stable "$@"
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,7 @@
|
||||||
#
|
#
|
||||||
# nostrod: every local user's bank connections, one worker process per user, behind net.catcrafts.Nostro1 and
|
# nostrod: every local user's bank connections, one worker process per user, behind net.catcrafts.Nostro1 and
|
||||||
# net.catcrafts.Nostro1.Checkout on the system bus. The first call starts it (D-Bus activation), and it ends by itself
|
# net.catcrafts.Nostro1.Checkout on the system bus. The first call starts it (D-Bus activation), and it ends by itself
|
||||||
# once idle, so an updated Flatpak takes over at the next call. It runs from the net.catcrafts.Nostro Flatpak as the
|
# once idle, so an updated Flatpak takes over at the next call. It runs from the net.catcrafts.Nostrod Flatpak as the
|
||||||
# system user nostro, whose home, the state directory, holds the connections: no other user can read it.
|
# system user nostro, whose home, the state directory, holds the connections: no other user can read it.
|
||||||
#
|
#
|
||||||
# The hardening is what bubblewrap, which flatpak runs the daemon in, works under. Not here, because it breaks it:
|
# The hardening is what bubblewrap, which flatpak runs the daemon in, works under. Not here, because it breaks it:
|
||||||
|
|
@ -20,7 +20,7 @@ Type=dbus
|
||||||
BusName=net.catcrafts.Nostro1
|
BusName=net.catcrafts.Nostro1
|
||||||
User=nostro
|
User=nostro
|
||||||
Group=nostro
|
Group=nostro
|
||||||
ExecStart=/usr/bin/flatpak run --system --no-session-bus --die-with-parent --command=nostrod net.catcrafts.Nostro//stable
|
ExecStart=/usr/bin/flatpak run --system --no-session-bus --die-with-parent --command=nostrod net.catcrafts.Nostrod//stable
|
||||||
StateDirectory=nostro
|
StateDirectory=nostro
|
||||||
StateDirectoryMode=0700
|
StateDirectoryMode=0700
|
||||||
# flatpak run needs a runtime directory, which a system user does not have.
|
# flatpak run needs a runtime directory, which a system user does not have.
|
||||||
|
|
|
||||||
|
|
@ -8,7 +8,12 @@
|
||||||
set -u
|
set -u
|
||||||
|
|
||||||
systemctl stop nostrod.service 2>/dev/null
|
systemctl stop nostrod.service 2>/dev/null
|
||||||
flatpak uninstall --system -y --noninteractive net.catcrafts.Nostro 2>/dev/null
|
flatpak uninstall --system -y --noninteractive net.catcrafts.Nostrod 2>/dev/null
|
||||||
|
# A nostrod installed before the Nostro app took its id, net.catcrafts.Nostro. The app itself stays: it is an app like
|
||||||
|
# any other, removed with flatpak uninstall.
|
||||||
|
if flatpak info --system --show-metadata net.catcrafts.Nostro 2>/dev/null | grep -qx 'command=nostro'; then
|
||||||
|
flatpak uninstall --system -y --noninteractive net.catcrafts.Nostro 2>/dev/null
|
||||||
|
fi
|
||||||
flatpak remote-delete --system nostro-local 2>/dev/null
|
flatpak remote-delete --system nostro-local 2>/dev/null
|
||||||
rm -f /usr/share/dbus-1/system.d/net.catcrafts.Nostro1.conf \
|
rm -f /usr/share/dbus-1/system.d/net.catcrafts.Nostro1.conf \
|
||||||
/usr/share/dbus-1/system-services/net.catcrafts.Nostro1.service \
|
/usr/share/dbus-1/system-services/net.catcrafts.Nostro1.service \
|
||||||
|
|
|
||||||
261
project.cpp
261
project.cpp
|
|
@ -5,6 +5,9 @@ import std;
|
||||||
import Crafter.Build;
|
import Crafter.Build;
|
||||||
#pragma crafter dependency "https://forgejo.catcrafts.net/Catcrafts/Crafter.LintRules.git"
|
#pragma crafter dependency "https://forgejo.catcrafts.net/Catcrafts/Crafter.LintRules.git"
|
||||||
import Crafter.LintRules;
|
import Crafter.LintRules;
|
||||||
|
// What puts Crafter.Debug into the app under --debug-api, and into no other build.
|
||||||
|
#pragma crafter dependency "https://forgejo.catcrafts.net/Catcrafts/Crafter.Debug.git" commit "98e92c1976f32c6f9beb6ea38a0522a3bbdabed7" project "tooling/project.cpp"
|
||||||
|
import Crafter.Debug.Build;
|
||||||
namespace fs = std::filesystem;
|
namespace fs = std::filesystem;
|
||||||
using namespace Crafter;
|
using namespace Crafter;
|
||||||
|
|
||||||
|
|
@ -27,6 +30,143 @@ static Configuration CheckoutLibrary(std::span<const std::string_view> args, con
|
||||||
return checkout;
|
return checkout;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Nostro.Ui: the toolkit the app's screens are built with. It imports std alone, so its tests need no window, no bank
|
||||||
|
// and no bus, and it is built only for what depends on it: those tests, and the app.
|
||||||
|
static Configuration UiLibrary(std::span<const std::string_view> args, const std::vector<std::string>& compileFlags) {
|
||||||
|
Configuration ui;
|
||||||
|
ui.path = "./";
|
||||||
|
ui.name = "nostro-ui";
|
||||||
|
ui.outputName = "nostro-ui";
|
||||||
|
ui.type = ConfigurationType::LibraryStatic;
|
||||||
|
ApplyStandardArgs(ui, args);
|
||||||
|
ui.compileFlags.insert(ui.compileFlags.end(), compileFlags.begin(), compileFlags.end());
|
||||||
|
std::array<fs::path, 11> interfaces = {
|
||||||
|
"interfaces/Nostro.Ui",
|
||||||
|
"interfaces/Nostro.Ui-Geometry",
|
||||||
|
"interfaces/Nostro.Ui-Text",
|
||||||
|
"interfaces/Nostro.Ui-Edit",
|
||||||
|
"interfaces/Nostro.Ui-Gesture",
|
||||||
|
"interfaces/Nostro.Ui-Draw",
|
||||||
|
"interfaces/Nostro.Ui-Theme",
|
||||||
|
"interfaces/Nostro.Ui-Input",
|
||||||
|
"interfaces/Nostro.Ui-Context",
|
||||||
|
"interfaces/Nostro.Ui-Layout",
|
||||||
|
"interfaces/Nostro.Ui-Widgets",
|
||||||
|
};
|
||||||
|
std::array<fs::path, 7> implementations = {
|
||||||
|
"implementations/Nostro.Ui-Text",
|
||||||
|
"implementations/Nostro.Ui-Edit",
|
||||||
|
"implementations/Nostro.Ui-Gesture",
|
||||||
|
"implementations/Nostro.Ui-Draw",
|
||||||
|
"implementations/Nostro.Ui-Theme",
|
||||||
|
"implementations/Nostro.Ui-Context",
|
||||||
|
"implementations/Nostro.Ui-Widgets",
|
||||||
|
};
|
||||||
|
ui.GetInterfacesAndImplementations(interfaces, implementations);
|
||||||
|
LintRules::AddLiteRules(ui);
|
||||||
|
return ui;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Nostro.App: the app without its window: what it knows, what is filled in, and its screens, built with the toolkit
|
||||||
|
// over the library's client. Like the toolkit it is built only for what depends on it: its tests, and the app.
|
||||||
|
static Configuration AppLibrary(std::span<const std::string_view> args, const std::vector<std::string>& compileFlags, Configuration* library, Configuration* ui) {
|
||||||
|
Configuration app;
|
||||||
|
app.path = "./";
|
||||||
|
app.name = "nostro-app-core";
|
||||||
|
app.outputName = "nostro-app-core";
|
||||||
|
app.type = ConfigurationType::LibraryStatic;
|
||||||
|
app.dependencies = {library, ui};
|
||||||
|
ApplyStandardArgs(app, args);
|
||||||
|
app.compileFlags.insert(app.compileFlags.end(), compileFlags.begin(), compileFlags.end());
|
||||||
|
std::array<fs::path, 6> interfaces = {
|
||||||
|
"interfaces/Nostro.App",
|
||||||
|
"interfaces/Nostro.App-Banks",
|
||||||
|
"interfaces/Nostro.App-Format",
|
||||||
|
"interfaces/Nostro.App-Forms",
|
||||||
|
"interfaces/Nostro.App-Errors",
|
||||||
|
"interfaces/Nostro.App-App",
|
||||||
|
};
|
||||||
|
std::array<fs::path, 7> implementations = {
|
||||||
|
"implementations/Nostro.App-Banks",
|
||||||
|
"implementations/Nostro.App-Format",
|
||||||
|
"implementations/Nostro.App-Forms",
|
||||||
|
"implementations/Nostro.App-Errors",
|
||||||
|
"implementations/Nostro.App-App",
|
||||||
|
"implementations/Nostro.App-Screens",
|
||||||
|
"implementations/Nostro.App-Bunq",
|
||||||
|
};
|
||||||
|
app.GetInterfacesAndImplementations(interfaces, implementations);
|
||||||
|
LintRules::AddLiteRules(app);
|
||||||
|
return app;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Nostro.Ui.Shell: what puts the toolkit's screens on a display, on Crafter.Graphics and one sd-event loop. The one part
|
||||||
|
// of the app that needs a compositor and a graphics device, so only the app is built with it and no test is.
|
||||||
|
static Configuration ShellLibrary(std::span<const std::string_view> args, Configuration* ui, Configuration* graphics) {
|
||||||
|
Configuration shell;
|
||||||
|
shell.path = "./";
|
||||||
|
shell.name = "nostro-ui-shell";
|
||||||
|
shell.outputName = "nostro-ui-shell";
|
||||||
|
shell.type = ConfigurationType::LibraryStatic;
|
||||||
|
shell.linkFlags.push_back("-lsystemd");
|
||||||
|
shell.dependencies = {ui, graphics};
|
||||||
|
ApplyStandardArgs(shell, args);
|
||||||
|
std::array<fs::path, 5> interfaces = {
|
||||||
|
"interfaces/Nostro.Ui.Shell",
|
||||||
|
"interfaces/Nostro.Ui.Shell-Loop",
|
||||||
|
"interfaces/Nostro.Ui.Shell-Canvas",
|
||||||
|
"interfaces/Nostro.Ui.Shell-Window",
|
||||||
|
"interfaces/Nostro.Ui.Shell-Portal",
|
||||||
|
};
|
||||||
|
std::array<fs::path, 4> implementations = {
|
||||||
|
"implementations/Nostro.Ui.Shell-Loop",
|
||||||
|
"implementations/Nostro.Ui.Shell-Canvas",
|
||||||
|
"implementations/Nostro.Ui.Shell-Window",
|
||||||
|
"implementations/Nostro.Ui.Shell-Portal",
|
||||||
|
};
|
||||||
|
shell.GetInterfacesAndImplementations(interfaces, implementations);
|
||||||
|
LintRules::AddLiteRules(shell);
|
||||||
|
return shell;
|
||||||
|
}
|
||||||
|
|
||||||
|
// nostro-fake-system: the tests' fake bus and fake bunq with nostrod on them, as a program to run the app against.
|
||||||
|
static Configuration FakeSystem(std::span<const std::string_view> args, const std::vector<Define>& defines, const std::vector<Configuration*>& dependencies) {
|
||||||
|
Configuration fake;
|
||||||
|
fake.path = "./";
|
||||||
|
fake.name = "nostro-fake-system";
|
||||||
|
fake.outputName = "nostro-fake-system";
|
||||||
|
fake.defines = defines;
|
||||||
|
ApplyStandardArgs(fake, args);
|
||||||
|
fake.dependencies = dependencies;
|
||||||
|
std::array<fs::path, 0> interfaces = {};
|
||||||
|
std::array<fs::path, 1> implementations = {"tests/FakeSystem/main"};
|
||||||
|
fake.GetInterfacesAndImplementations(interfaces, implementations);
|
||||||
|
LintRules::AddLiteRules(fake);
|
||||||
|
return fake;
|
||||||
|
}
|
||||||
|
|
||||||
|
// `crafter-build … --product=app --debug-api run fake [the fake system's options] [-- the app's options]`: the app on
|
||||||
|
// the made-up system, both as the build before left them. `-r` passes a program no arguments, and the app has a few.
|
||||||
|
static std::int32_t RunOnFakeSystem(ScriptContext& ctx) {
|
||||||
|
const auto harness = std::ranges::find(ctx.project.dependencies, std::string_view("nostro-fake-system"), [](const Configuration* dependency) { return std::string_view(dependency->name); });
|
||||||
|
if(harness == ctx.project.dependencies.end()) {
|
||||||
|
throw std::runtime_error("the fake system is built with the app under --debug-api: name both before `run`");
|
||||||
|
}
|
||||||
|
const auto separator = std::ranges::find(ctx.args, std::string_view("--"));
|
||||||
|
std::string command = ShellQuote(((*harness)->BinDir() / (*harness)->outputName).string());
|
||||||
|
command += std::format(" --dir {}", ShellQuote((ctx.projectDir / "build" / "fake-system").string()));
|
||||||
|
for(const std::string& arg : std::ranges::subrange(ctx.args.begin(), separator)) {
|
||||||
|
command += std::format(" {}", ShellQuote(arg));
|
||||||
|
}
|
||||||
|
command += std::format(" --run {}", ShellQuote((ctx.project.ProgramDir() / ctx.project.outputName).string()));
|
||||||
|
if(separator != ctx.args.end()) {
|
||||||
|
for(const std::string& arg : std::ranges::subrange(separator + 1, ctx.args.end())) {
|
||||||
|
command += std::format(" {}", ShellQuote(arg));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ctx.Run(command);
|
||||||
|
}
|
||||||
|
|
||||||
extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> args) {
|
extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> args) {
|
||||||
constexpr std::string_view bankArgName = "--banks=";
|
constexpr std::string_view bankArgName = "--banks=";
|
||||||
|
|
||||||
|
|
@ -36,9 +176,16 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
|
||||||
bool coverage = false;
|
bool coverage = false;
|
||||||
std::string profileRuntime;
|
std::string profileRuntime;
|
||||||
constexpr std::string_view profileRuntimeArgName = "--profile-runtime=";
|
constexpr std::string_view profileRuntimeArgName = "--profile-runtime=";
|
||||||
// What a build makes: the CLI by default, "daemon" for nostrod, or "checkout" for the checkout client library.
|
// What a build makes: the CLI by default, "daemon" for nostrod, "app" for the window, "checkout" for the checkout
|
||||||
|
// client library, or "fake-system" for a made-up system to look at the app against.
|
||||||
std::string product;
|
std::string product;
|
||||||
constexpr std::string_view productArgName = "--product=";
|
constexpr std::string_view productArgName = "--product=";
|
||||||
|
// Crafter.Graphics from a checkout: the project.cpp to build the app against, in place of the forge's.
|
||||||
|
std::string graphicsProject;
|
||||||
|
constexpr std::string_view graphicsArgName = "--graphics=";
|
||||||
|
// The app with Crafter.Debug in it, for an agent to drive: nostro's own flag, which no dependency is handed.
|
||||||
|
bool debugApiRequested = false;
|
||||||
|
constexpr std::string_view debugApiArgName = "--debug-api";
|
||||||
|
|
||||||
std::vector<std::string> depArgs;
|
std::vector<std::string> depArgs;
|
||||||
|
|
||||||
|
|
@ -51,6 +198,10 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
|
||||||
dbusRequested = true;
|
dbusRequested = true;
|
||||||
} else if(arg.starts_with(productArgName)) {
|
} else if(arg.starts_with(productArgName)) {
|
||||||
product = arg.substr(productArgName.size());
|
product = arg.substr(productArgName.size());
|
||||||
|
} else if(arg.starts_with(graphicsArgName)) {
|
||||||
|
graphicsProject = arg.substr(graphicsArgName.size());
|
||||||
|
} else if(arg == debugApiArgName) {
|
||||||
|
debugApiRequested = true;
|
||||||
} else if(arg == "--coverage") {
|
} else if(arg == "--coverage") {
|
||||||
coverage = true;
|
coverage = true;
|
||||||
} else if(arg.starts_with(profileRuntimeArgName)) {
|
} else if(arg.starts_with(profileRuntimeArgName)) {
|
||||||
|
|
@ -88,7 +239,7 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
|
||||||
if(product == "checkout") {
|
if(product == "checkout") {
|
||||||
return CheckoutLibrary(args, coverageCompileFlags);
|
return CheckoutLibrary(args, coverageCompileFlags);
|
||||||
}
|
}
|
||||||
if(!product.empty() && product != "daemon") {
|
if(!product.empty() && product != "daemon" && product != "app" && product != "fake-system") {
|
||||||
throw std::runtime_error(std::format("unknown product '{}' in {}", product, productArgName));
|
throw std::runtime_error(std::format("unknown product '{}' in {}", product, productArgName));
|
||||||
}
|
}
|
||||||
if(!bunqEnabled) {
|
if(!bunqEnabled) {
|
||||||
|
|
@ -109,11 +260,17 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
|
||||||
libcfg.defines.push_back({"NOSTRO_DBUS_ENABLED"});
|
libcfg.defines.push_back({"NOSTRO_DBUS_ENABLED"});
|
||||||
}
|
}
|
||||||
Configuration* checkout = new Configuration(CheckoutLibrary(args, coverageCompileFlags));
|
Configuration* checkout = new Configuration(CheckoutLibrary(args, coverageCompileFlags));
|
||||||
|
Configuration* ui = new Configuration(UiLibrary(args, coverageCompileFlags));
|
||||||
|
|
||||||
// nostro uses Crafter.Network's HTTP/1.1 client alone: --no-quic leaves out msquic, its CMake build, and the runpath
|
// nostro uses Crafter.Network's HTTP/1.1 client alone: --no-quic leaves out msquic, its CMake build, and the runpath
|
||||||
// into the building user's cache that a binary linked against it carries.
|
// into the building user's cache that a binary linked against it carries. Crafter.Debug talks QUIC, and takes
|
||||||
|
// Crafter.Network with the args it is handed: a dependency two paths share gets one list of them, so the app's
|
||||||
|
// debug build has QUIC in.
|
||||||
|
const bool debugApi = debugApiRequested && product == "app";
|
||||||
std::vector<std::string> networkArgs = depArgs;
|
std::vector<std::string> networkArgs = depArgs;
|
||||||
networkArgs.emplace_back("--no-quic");
|
if(!debugApi) {
|
||||||
|
networkArgs.emplace_back("--no-quic");
|
||||||
|
}
|
||||||
Configuration* network = GitProject({
|
Configuration* network = GitProject({
|
||||||
.source = { .url = "https://forgejo.catcrafts.net/Catcrafts/Crafter.Network.git" },
|
.source = { .url = "https://forgejo.catcrafts.net/Catcrafts/Crafter.Network.git" },
|
||||||
.args = networkArgs,
|
.args = networkArgs,
|
||||||
|
|
@ -189,6 +346,7 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
|
||||||
// configurations exporting the same module in one build are an error.
|
// configurations exporting the same module in one build are an error.
|
||||||
const auto defines = libcfg.defines;
|
const auto defines = libcfg.defines;
|
||||||
Configuration* library = new Configuration(std::move(libcfg));
|
Configuration* library = new Configuration(std::move(libcfg));
|
||||||
|
Configuration* appCore = new Configuration(AppLibrary(args, coverageCompileFlags, library, ui));
|
||||||
|
|
||||||
// nostrod: the daemon that holds the connectors and answers the CLI over the system bus.
|
// nostrod: the daemon that holds the connectors and answers the CLI over the system bus.
|
||||||
if(product == "daemon") {
|
if(product == "daemon") {
|
||||||
|
|
@ -208,6 +366,60 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
|
||||||
return daemon;
|
return daemon;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if(product == "fake-system") {
|
||||||
|
return FakeSystem(args, defines, { library, network, db, checkout });
|
||||||
|
}
|
||||||
|
|
||||||
|
// nostro-app: the window. Its fonts go beside it, where the window library's shaders are put too.
|
||||||
|
if(product == "app") {
|
||||||
|
// The app asks the input method for a field's purpose and hints, which Crafter.Graphics has on its branch
|
||||||
|
// claude/nostro-app and not yet on master: until that is merged and pinned here, a checkout of it is named.
|
||||||
|
if(graphicsProject.empty()) {
|
||||||
|
throw std::runtime_error(std::format("--product=app needs {}<a Crafter.Graphics checkout's project.cpp> for now: the branch claude/nostro-app", graphicsArgName));
|
||||||
|
}
|
||||||
|
Configuration* graphics = LocalProject({ .projectFile = graphicsProject, .args = depArgs });
|
||||||
|
Configuration* shell = new Configuration(ShellLibrary(args, ui, graphics));
|
||||||
|
Configuration app;
|
||||||
|
app.path = "./";
|
||||||
|
app.name = "nostro-app";
|
||||||
|
app.outputName = "nostro-app";
|
||||||
|
app.defines = defines;
|
||||||
|
// What the app says its version is: the metainfo's release is the same.
|
||||||
|
app.defines.push_back({"NOSTRO_VERSION", "0.1.0"});
|
||||||
|
ApplyStandardArgs(app, args);
|
||||||
|
app.dependencies = { library, ui, appCore, shell };
|
||||||
|
app.files.push_back("assets/NotoSans-Regular.ttf");
|
||||||
|
app.files.push_back("assets/NotoSans-Medium.ttf");
|
||||||
|
// What the app is as a Flatpak (--packaging=flatpak, with `install` or `bundle`): the compositor, the graphics
|
||||||
|
// device, and nostrod on the system bus. No network and no files: it talks to no bank itself and keeps
|
||||||
|
// nothing. The desktop's portals, for the look and for opening a browser, need no permission.
|
||||||
|
app.flatpak.appId = "net.catcrafts.Nostro";
|
||||||
|
app.flatpak.permissions = {"--socket=wayland", "--device=dri", "--system-talk-name=net.catcrafts.Nostro1"};
|
||||||
|
app.flatpak.desktopFile = "packaging/flatpak/net.catcrafts.Nostro.desktop";
|
||||||
|
app.flatpak.metainfo = "packaging/flatpak/net.catcrafts.Nostro.metainfo.xml";
|
||||||
|
app.flatpak.icons = {"packaging/flatpak/net.catcrafts.Nostro.svg"};
|
||||||
|
// The licences of what it carries; packaging/licenses/NOTICE says what each text covers.
|
||||||
|
app.flatpak.share = {
|
||||||
|
{"LICENSE", "licenses/net.catcrafts.Nostro/LICENSE"},
|
||||||
|
{"LICENSE.GPL", "licenses/net.catcrafts.Nostro/LICENSE.GPL"},
|
||||||
|
{"assets/OFL.txt", "licenses/net.catcrafts.Nostro/OFL.txt"},
|
||||||
|
{"packaging/licenses", "licenses/net.catcrafts.Nostro"},
|
||||||
|
};
|
||||||
|
std::vector<fs::path> appInterfaces;
|
||||||
|
std::vector<fs::path> appImplementations = {"implementations/nostro-app"};
|
||||||
|
// With --debug-api: Crafter.Debug, what an agent drives the app with, and the made-up system to drive it on,
|
||||||
|
// built in the same pass. Any process of the user's can drive and read such a build: it is no build to ship.
|
||||||
|
if(Debug::Use(app, { .enabled = debugApi, .flag = std::string(debugApiArgName), .define = "NOSTRO_DEBUG_API", .args = depArgs })) {
|
||||||
|
appInterfaces.emplace_back("interfaces/Nostro.DebugCommands");
|
||||||
|
appImplementations.emplace_back("implementations/Nostro.DebugCommands");
|
||||||
|
app.dependencies.push_back(new Configuration(FakeSystem(args, defines, { library, network, db, checkout })));
|
||||||
|
app.scripts.push_back({"fake", RunOnFakeSystem});
|
||||||
|
}
|
||||||
|
app.GetInterfacesAndImplementations(appInterfaces, appImplementations);
|
||||||
|
LintRules::AddLiteRules(app);
|
||||||
|
return app;
|
||||||
|
}
|
||||||
|
|
||||||
Configuration execfg;
|
Configuration execfg;
|
||||||
execfg.path = "./";
|
execfg.path = "./";
|
||||||
execfg.name = "nostro";
|
execfg.name = "nostro";
|
||||||
|
|
@ -228,9 +440,20 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
|
||||||
execfg.dependencies = { library };
|
execfg.dependencies = { library };
|
||||||
execfg.GetInterfacesAndImplementations(exeInterfaces, exeImplementations);
|
execfg.GetInterfacesAndImplementations(exeInterfaces, exeImplementations);
|
||||||
|
|
||||||
// `crafter-build test --banks=bunq`: each test is tests/<Name>/main.cpp, linked against the library. The ones that
|
// `crafter-build test --banks=bunq`: each test is tests/<Name>/main.cpp, linked against what it tests. The ones that
|
||||||
// talk to bunq talk to a fake of it on 127.0.0.1 (tests/Support/FakeBunq.inc), never to bunq itself.
|
// talk to bunq talk to a fake of it on 127.0.0.1 (tests/Support/FakeBunq.inc), never to bunq itself.
|
||||||
constexpr std::array<std::string_view, 9> tests = {
|
const auto addTests = [&execfg, &coverageCompileFlags, &coverageLinkFlags](std::span<const std::string_view> names, const std::vector<Configuration*>& dependencies) {
|
||||||
|
for(const std::string_view name : names) {
|
||||||
|
TestBuilder test = execfg.AddTest(name).Dependencies(dependencies).Timeout(std::chrono::seconds(180));
|
||||||
|
for(const std::string& flag : coverageCompileFlags) {
|
||||||
|
test.CompileFlag(flag);
|
||||||
|
}
|
||||||
|
for(const std::string& flag : coverageLinkFlags) {
|
||||||
|
test.LinkFlag(flag);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
constexpr std::array<std::string_view, 10> libraryTests = {
|
||||||
"ShouldHandleMoneyAndText",
|
"ShouldHandleMoneyAndText",
|
||||||
"ShouldSignAndVerify",
|
"ShouldSignAndVerify",
|
||||||
"ShouldStoreTransactions",
|
"ShouldStoreTransactions",
|
||||||
|
|
@ -240,16 +463,24 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
|
||||||
"ShouldMoveMoney",
|
"ShouldMoveMoney",
|
||||||
"ShouldRunCommands",
|
"ShouldRunCommands",
|
||||||
"ShouldServeEveryUser",
|
"ShouldServeEveryUser",
|
||||||
|
"ShouldAnswerAsynchronously",
|
||||||
};
|
};
|
||||||
for(const std::string_view name : tests) {
|
addTests(libraryTests, { library, network, db, checkout });
|
||||||
TestBuilder test = execfg.AddTest(name).Dependencies({ library, network, db, checkout }).Timeout(std::chrono::seconds(180));
|
// The toolkit's, which need the toolkit alone.
|
||||||
for(const std::string& flag : coverageCompileFlags) {
|
constexpr std::array<std::string_view, 5> uiTests = {
|
||||||
test.CompileFlag(flag);
|
"ShouldWrapText",
|
||||||
}
|
"ShouldEditText",
|
||||||
for(const std::string& flag : coverageLinkFlags) {
|
"ShouldRecognizeGestures",
|
||||||
test.LinkFlag(flag);
|
"ShouldBuildFrames",
|
||||||
}
|
"ShouldLayOutWidgets",
|
||||||
}
|
};
|
||||||
|
addTests(uiTests, { ui });
|
||||||
|
// The app's, which drive it against a real nostrod on the fake bus.
|
||||||
|
constexpr std::array<std::string_view, 2> appTests = {
|
||||||
|
"ShouldValidateForms",
|
||||||
|
"ShouldDriveTheApp",
|
||||||
|
};
|
||||||
|
addTests(appTests, { appCore, ui, library, network, db, checkout });
|
||||||
|
|
||||||
LintRules::AddLiteRules(execfg);
|
LintRules::AddLiteRules(execfg);
|
||||||
|
|
||||||
|
|
|
||||||
266
tests/FakeSystem/main.cpp
Normal file
266
tests/FakeSystem/main.cpp
Normal file
|
|
@ -0,0 +1,266 @@
|
||||||
|
// SPDX-License-Identifier: LGPL-3.0-only
|
||||||
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
// nostro-fake-system: a whole system for the app to be looked at against, with no bank, no real bus and nobody's
|
||||||
|
// money in it. It runs the tests' fake system bus and fake bunq (tests/Support), starts nostrod on them (this
|
||||||
|
// executable again, with nostrod's main compiled in), fills the bank with a made-up user, and then runs a program
|
||||||
|
// with DBUS_SYSTEM_BUS_ADDRESS pointing at the fake bus, or waits for one to be started by hand.
|
||||||
|
// nostro-fake-system [--dir <directory>] [--port <port>] [--polkit allow|password|deny|dismiss|absent|silent|slow]
|
||||||
|
// [--bank-delay <milliseconds>] [--empty] [--run <program> <arguments…>]
|
||||||
|
// --dir is where the bus's socket and nostrod's state go (a temporary directory by default). --polkit is what every
|
||||||
|
// request for a password is answered with: allow by default, as if the user typed it at once. --bank-delay is how
|
||||||
|
// long the made-up bank takes over each answer: none by default, where a real bank is a network away and takes a few
|
||||||
|
// hundred milliseconds, which is what shows whether a screen waits for the bank more than it has to. --empty leaves
|
||||||
|
// the user without a bank connection, to start from the welcome; the made-up bank's API key is printed, to add it by
|
||||||
|
// hand. Everything after --run is the program and its arguments.
|
||||||
|
|
||||||
|
#include "../../lib/json.hpp"
|
||||||
|
#include <poll.h>
|
||||||
|
#include <signal.h>
|
||||||
|
#include <spawn.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <sys/resource.h>
|
||||||
|
#include <sys/socket.h>
|
||||||
|
#include <sys/un.h>
|
||||||
|
#include <sys/wait.h>
|
||||||
|
#include <systemd/sd-bus.h>
|
||||||
|
#include <systemd/sd-event.h>
|
||||||
|
#include <systemd/sd-id128.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
|
||||||
|
import std;
|
||||||
|
import Nostro;
|
||||||
|
import Crafter.Network;
|
||||||
|
|
||||||
|
#define main NostrodMain
|
||||||
|
#include "../../implementations/nostrod.cpp"
|
||||||
|
#undef main
|
||||||
|
|
||||||
|
#include "../Support/FakeBunq.inc"
|
||||||
|
#include "../Support/FakeBus.inc"
|
||||||
|
|
||||||
|
using namespace Nostro;
|
||||||
|
using json = nlohmann::json;
|
||||||
|
namespace fs = std::filesystem;
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
constexpr std::string_view busName = "net.catcrafts.Nostro1";
|
||||||
|
// A key of the sandbox's kind: the app's own guard against real keys in a build open to a debugger lets it by.
|
||||||
|
const std::string demoKey = "sandbox_demo_0123456789abcdef0123456789abcdef";
|
||||||
|
const std::string currentIban = "NL54BUNQ2100000011";
|
||||||
|
const std::string savingsIban = "NL48BUNQ2100000022";
|
||||||
|
const std::string holidayIban = "NL42BUNQ2100000033";
|
||||||
|
const std::string friendIban = "NL36BUNQ2100000044";
|
||||||
|
const std::string sharedIban = "NL06BUNQ2100000099";
|
||||||
|
|
||||||
|
// The made-up user's bank: three accounts, three months of payments, three cards, and one of everything else. All of
|
||||||
|
// it is in English, as the app is: the README's pictures are of this (docs/screenshots/take.sh).
|
||||||
|
void Fill(Fake::Bunq& bunq) {
|
||||||
|
const std::uint64_t robin = bunq.AddPerson("Robin Walker", demoKey);
|
||||||
|
const std::uint64_t current = bunq.AddAccount(robin, currentIban, "Current account", 84210);
|
||||||
|
bunq.AddAccount(robin, savingsIban, "Savings", 1250000, "MonetaryAccountSavings");
|
||||||
|
bunq.AddAccount(robin, holidayIban, "Holiday", 43050, "MonetaryAccountSavings");
|
||||||
|
const std::uint64_t nora = bunq.AddPerson("Nora White", "sandbox_demo_friend");
|
||||||
|
bunq.AddAccount(nora, friendIban, "Nora", 150000);
|
||||||
|
const std::uint64_t sam = bunq.AddPerson("Sam Johnson", "sandbox_demo_shared");
|
||||||
|
bunq.AddAccount(sam, sharedIban, "Household", 96400);
|
||||||
|
bunq.AddGrant(sam, "demo-code", "sandbox_demo_token");
|
||||||
|
|
||||||
|
struct Regular {
|
||||||
|
std::string_view name;
|
||||||
|
std::string_view iban;
|
||||||
|
std::string_view description;
|
||||||
|
std::int64_t amount;
|
||||||
|
std::int32_t every; // days between two of them
|
||||||
|
std::string_view type;
|
||||||
|
std::string_view subType;
|
||||||
|
};
|
||||||
|
static constexpr std::array<Regular, 9> regulars = {{
|
||||||
|
{"Maple Court Housing", "NL35RABO0300000055", "Rent", -98500, 30, "EBA_SDD", "SDD"},
|
||||||
|
{"Employer Ltd", "NL20INGB0001234567", "Salary", 285000, 30, "EBA_SCT", "SCT"},
|
||||||
|
{"Northern Energy", "NL69ABNA0500000077", "Monthly instalment", -14200, 30, "EBA_SDD", "SDD"},
|
||||||
|
{"Corner Supermarket", "", "", -4350, 3, "MASTERCARD", "PAYMENT"},
|
||||||
|
{"Sunflower Bakery", "", "", -685, 4, "MASTERCARD", "PAYMENT"},
|
||||||
|
{"Nora White", "NL36BUNQ2100000044", "Groceries", -2250, 11, "BUNQ", "PAYMENT"},
|
||||||
|
{"Swift Cycles", "NL96TRIO0200000088", "Repair", -6500, 41, "IDEAL", "PAYMENT"},
|
||||||
|
{"Eastside Sports Club", "NL43KNAB0600000100", "Membership", -2750, 30, "EBA_SDD", "SDD"},
|
||||||
|
{"Nora White", "NL36BUNQ2100000044", "Dinner, paid back", 3100, 17, "BUNQ", "PAYMENT"},
|
||||||
|
}};
|
||||||
|
// Oldest first, as a bank makes them: ninety days up to an hour ago.
|
||||||
|
const std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
|
||||||
|
std::vector<std::pair<std::chrono::system_clock::time_point, const Regular*>> made;
|
||||||
|
for(std::size_t r = 0; r < regulars.size(); r++) {
|
||||||
|
for(std::int32_t day = 90 - static_cast<std::int32_t>(r) % 5; day >= 0; day -= regulars[r].every) {
|
||||||
|
made.emplace_back(now - std::chrono::hours(24 * day + 1 + static_cast<std::int32_t>(r) * 2), ®ulars[r]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
std::ranges::sort(made, {}, [](const auto& entry) { return entry.first; });
|
||||||
|
for(const auto& [at, regular] : made) {
|
||||||
|
bunq.AddPayment(current, regular->amount, regular->name, regular->iban, regular->description, json{{"created", FormatTimestamp(at)}, {"type", regular->type}, {"sub_type", regular->subType}});
|
||||||
|
}
|
||||||
|
{
|
||||||
|
// What the bank makes from here on is made now, after all of that.
|
||||||
|
std::lock_guard lock(bunq.mutex);
|
||||||
|
bunq.clock = static_cast<std::uint32_t>(std::chrono::duration_cast<std::chrono::minutes>(now - ParseTimestamp("2026-10-01 10:00:00")).count());
|
||||||
|
}
|
||||||
|
bunq.AddCard(robin, "ACTIVE", json{{"name_on_card", "R. Walker"}, {"second_line", ""}, {"label_monetary_account_current", json{{"iban", currentIban}}}});
|
||||||
|
bunq.AddCard(robin, "DEACTIVATED", json{{"name_on_card", "R. Walker"}, {"second_line", "Travel"}, {"product_type", "MAESTRO_DEBIT"}, {"primary_account_numbers", json::array({json{{"four_digit", "8841"}}})}, {"label_monetary_account_current", json{{"iban", holidayIban}}}});
|
||||||
|
// And a virtual one, which bunq has as deactivated however well it pays.
|
||||||
|
bunq.AddCard(robin, "DEACTIVATED", json{{"order_status", "VIRTUAL_DELIVERY"}, {"name_on_card", "R. Walker"}, {"second_line", "Online"}, {"primary_account_numbers", json::array({json{{"four_digit", "5512"}}})}, {"label_monetary_account_current", json{{"iban", currentIban}}}});
|
||||||
|
}
|
||||||
|
|
||||||
|
// What a connected user has besides payments: a request sent, one received, a schedule and a draft.
|
||||||
|
void Furnish(Client& robin) {
|
||||||
|
robin.AddBunq("sandbox_demo_friend", "*", "");
|
||||||
|
robin.Request(friendIban, currentIban, "Robin Walker", 1875, "Concert tickets");
|
||||||
|
robin.RemoveConnector("Nora White");
|
||||||
|
robin.Request(currentIban, friendIban, "Nora White", 1250, "Lunch");
|
||||||
|
robin.Schedule(currentIban, savingsIban, "Robin Walker", 20000, "Savings", BunqSchedule{.start = std::chrono::system_clock::now() + std::chrono::hours(24 * 5), .unit = "MONTHLY"});
|
||||||
|
robin.Draft(currentIban, "NL70ASNB0700000111", "Millbrook Dental", 8900, "Check-up");
|
||||||
|
robin.AddBunqOAuth("sandbox", "fake-client", "fake-secret", "http://127.0.0.1/cb", "demo-code");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// main's signature is C's; past it the arguments are string views.
|
||||||
|
// lint-disable-next-line no-char-pointer
|
||||||
|
int main(int argc, char* argv[]) {
|
||||||
|
// nostrod, and each of its workers, is this executable again.
|
||||||
|
if(Fake::IsNostrod()) {
|
||||||
|
Fake::Bunq::RedirectFromEnvironment();
|
||||||
|
return NostrodMain(argc, argv);
|
||||||
|
}
|
||||||
|
|
||||||
|
const std::vector<std::string_view> args(argv + 1, argv + argc);
|
||||||
|
try {
|
||||||
|
fs::path directory = fs::temp_directory_path() / std::format("nostro-fake-system-{}", getpid());
|
||||||
|
std::uint16_t port = 47390;
|
||||||
|
Fake::Polkit polkit = Fake::Polkit::Allow;
|
||||||
|
std::uint32_t bankDelay = 0;
|
||||||
|
bool empty = false;
|
||||||
|
std::vector<std::string> run;
|
||||||
|
const auto value = [&args](std::size_t index) {
|
||||||
|
if(index >= args.size()) {
|
||||||
|
throw std::invalid_argument(std::format("{} needs a value", args[index - 1]));
|
||||||
|
}
|
||||||
|
return args[index];
|
||||||
|
};
|
||||||
|
for(std::size_t i = 0; i < args.size(); i++) {
|
||||||
|
if(args[i] == "--dir") {
|
||||||
|
directory = value(++i);
|
||||||
|
} else if(args[i] == "--port") {
|
||||||
|
const std::string_view text = value(++i);
|
||||||
|
if(std::from_chars(text.data(), text.data() + text.size(), port).ec != std::errc()) {
|
||||||
|
throw std::invalid_argument(std::format("'{}' is not a port", text));
|
||||||
|
}
|
||||||
|
} else if(args[i] == "--polkit") {
|
||||||
|
static constexpr std::array<std::pair<std::string_view, Fake::Polkit>, 7> answers = {{
|
||||||
|
{"allow", Fake::Polkit::Allow}, {"password", Fake::Polkit::Password}, {"deny", Fake::Polkit::Deny}, {"dismiss", Fake::Polkit::Dismiss},
|
||||||
|
{"absent", Fake::Polkit::Absent}, {"silent", Fake::Polkit::Silent}, {"slow", Fake::Polkit::Slow},
|
||||||
|
}};
|
||||||
|
const auto found = std::ranges::find(answers, value(++i), &std::pair<std::string_view, Fake::Polkit>::first);
|
||||||
|
if(found == answers.end()) {
|
||||||
|
throw std::invalid_argument(std::format("unknown answer '{}' in --polkit", args[i]));
|
||||||
|
}
|
||||||
|
polkit = found->second;
|
||||||
|
} else if(args[i] == "--bank-delay") {
|
||||||
|
const std::string_view text = value(++i);
|
||||||
|
if(std::from_chars(text.data(), text.data() + text.size(), bankDelay).ec != std::errc()) {
|
||||||
|
throw std::invalid_argument(std::format("'{}' is not a number of milliseconds", text));
|
||||||
|
}
|
||||||
|
} else if(args[i] == "--empty") {
|
||||||
|
empty = true;
|
||||||
|
} else if(args[i] == "--run") {
|
||||||
|
run.assign(args.begin() + static_cast<std::ptrdiff_t>(i) + 1, args.end());
|
||||||
|
if(run.empty()) {
|
||||||
|
throw std::invalid_argument("--run needs a program");
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
} else {
|
||||||
|
throw std::invalid_argument(std::format("unknown argument '{}'", args[i]));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fs::create_directories(directory);
|
||||||
|
const fs::path socket = directory / "bus";
|
||||||
|
fs::remove(socket);
|
||||||
|
// What nostrod and the program read from the environment, and the signals this waits for, are set before any
|
||||||
|
// thread starts.
|
||||||
|
setenv("XDG_DATA_HOME", (directory / "data").c_str(), 1);
|
||||||
|
Fake::Bunq::ExportRedirect(port, directory / "bunq.pem");
|
||||||
|
setenv("DBUS_SYSTEM_BUS_ADDRESS", Fake::Bus::Address(socket).c_str(), 1);
|
||||||
|
sigset_t ending{};
|
||||||
|
sigemptyset(&ending);
|
||||||
|
sigaddset(&ending, SIGINT);
|
||||||
|
sigaddset(&ending, SIGTERM);
|
||||||
|
sigprocmask(SIG_BLOCK, &ending, nullptr);
|
||||||
|
|
||||||
|
std::int32_t status = 0;
|
||||||
|
{
|
||||||
|
Fake::Bus bus(socket);
|
||||||
|
{
|
||||||
|
// Whoever runs this is the one user of the fake system, under the name "you".
|
||||||
|
std::lock_guard lock(bus.mutex);
|
||||||
|
bus.clientUid = getuid();
|
||||||
|
bus.logindNames = {{getuid(), "you"}};
|
||||||
|
}
|
||||||
|
Fake::Bunq bunq(port);
|
||||||
|
Fill(bunq);
|
||||||
|
const pid_t nostrod = Fake::StartNostrod({"--state", (directory / "state").string(), "--idle", "3600", "--prompt-timeout", "120"});
|
||||||
|
if(!bus.WaitForName(busName)) {
|
||||||
|
throw std::runtime_error("nostrod did not come up on the fake bus");
|
||||||
|
}
|
||||||
|
if(!empty) {
|
||||||
|
Client robin = Client::System();
|
||||||
|
robin.AddBunq(demoKey, "*", "");
|
||||||
|
Furnish(robin);
|
||||||
|
}
|
||||||
|
{
|
||||||
|
std::lock_guard lock(bus.mutex);
|
||||||
|
bus.polkit = polkit;
|
||||||
|
}
|
||||||
|
{
|
||||||
|
// From here on, once the user is furnished: the bank takes its time.
|
||||||
|
std::lock_guard lock(bunq.mutex);
|
||||||
|
bunq.latency = std::chrono::milliseconds(bankDelay);
|
||||||
|
}
|
||||||
|
std::println("nostro-fake-system: DBUS_SYSTEM_BUS_ADDRESS={}", Fake::Bus::Address(socket));
|
||||||
|
if(empty) {
|
||||||
|
std::println("nostro-fake-system: nothing is connected; the made-up bank's API key is {}", demoKey);
|
||||||
|
}
|
||||||
|
std::fflush(stdout);
|
||||||
|
|
||||||
|
if(run.empty()) {
|
||||||
|
std::int32_t signal = 0;
|
||||||
|
sigwait(&ending, &signal);
|
||||||
|
} else {
|
||||||
|
// posix_spawn takes C strings.
|
||||||
|
// lint-disable-next-line no-char-pointer
|
||||||
|
std::vector<char*> arguments;
|
||||||
|
for(std::string& argument : run) {
|
||||||
|
arguments.push_back(argument.data());
|
||||||
|
}
|
||||||
|
arguments.push_back(nullptr);
|
||||||
|
// The program ends on the signals this waits for, by itself.
|
||||||
|
posix_spawnattr_t attributes{};
|
||||||
|
posix_spawnattr_init(&attributes);
|
||||||
|
sigset_t none{};
|
||||||
|
sigemptyset(&none);
|
||||||
|
posix_spawnattr_setsigmask(&attributes, &none);
|
||||||
|
posix_spawnattr_setflags(&attributes, POSIX_SPAWN_SETSIGMASK);
|
||||||
|
pid_t program = -1;
|
||||||
|
const std::int32_t spawned = posix_spawnp(&program, arguments.front(), nullptr, &attributes, arguments.data(), environ);
|
||||||
|
posix_spawnattr_destroy(&attributes);
|
||||||
|
if(spawned != 0) {
|
||||||
|
throw std::system_error(spawned, std::generic_category(), std::format("cannot run {}", run.front()));
|
||||||
|
}
|
||||||
|
status = Fake::Wait(program);
|
||||||
|
}
|
||||||
|
bus.Disconnect(busName);
|
||||||
|
Fake::Wait(nostrod);
|
||||||
|
}
|
||||||
|
return status;
|
||||||
|
} catch(const std::exception& e) {
|
||||||
|
std::println(std::cerr, "nostro-fake-system: {}", e.what());
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
398
tests/ShouldAnswerAsynchronously/main.cpp
Normal file
398
tests/ShouldAnswerAsynchronously/main.cpp
Normal file
|
|
@ -0,0 +1,398 @@
|
||||||
|
// SPDX-License-Identifier: LGPL-3.0-only
|
||||||
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
// Nostro::Client's asynchronous calls, as a program with an event loop makes them: each method once, every way an answer
|
||||||
|
// fails, and what a Pending does. nostrod is this executable again (nostrod's main is compiled in), on a fake system bus
|
||||||
|
// (tests/Support/FakeBus.inc) in front of a fake bunq (tests/Support/FakeBunq.inc), and every answer arrives through an
|
||||||
|
// sd-event loop.
|
||||||
|
|
||||||
|
#include "../../lib/json.hpp"
|
||||||
|
#include <poll.h>
|
||||||
|
#include <signal.h>
|
||||||
|
#include <spawn.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <sys/resource.h>
|
||||||
|
#include <sys/socket.h>
|
||||||
|
#include <sys/un.h>
|
||||||
|
#include <sys/wait.h>
|
||||||
|
#include <systemd/sd-bus.h>
|
||||||
|
#include <systemd/sd-event.h>
|
||||||
|
#include <systemd/sd-id128.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
|
||||||
|
import std;
|
||||||
|
import Nostro;
|
||||||
|
import Crafter.Network;
|
||||||
|
|
||||||
|
#define main NostrodMain
|
||||||
|
#include "../../implementations/nostrod.cpp"
|
||||||
|
#undef main
|
||||||
|
|
||||||
|
#include "../Support/Check.inc"
|
||||||
|
#include "../Support/FakeBunq.inc"
|
||||||
|
#include "../Support/FakeBus.inc"
|
||||||
|
|
||||||
|
using namespace Nostro;
|
||||||
|
using Test::Check;
|
||||||
|
using Test::Equal;
|
||||||
|
using Test::Throws;
|
||||||
|
using json = nlohmann::json;
|
||||||
|
using Fault = Fake::Fault;
|
||||||
|
namespace fs = std::filesystem;
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
constexpr std::uint16_t port = 47306;
|
||||||
|
constexpr std::uint32_t aliceUid = 4242;
|
||||||
|
constexpr std::uint32_t bobUid = 4343;
|
||||||
|
constexpr std::string_view name = "net.catcrafts.Nostro1";
|
||||||
|
const std::string aliceMain = "NL23BUNQ2025123456";
|
||||||
|
const std::string bobIban = "NL67BUNQ2025654321";
|
||||||
|
const std::string carolIban = "NL65BUNQ2025222222";
|
||||||
|
|
||||||
|
using Summaries = std::vector<ConnectorSummary>;
|
||||||
|
|
||||||
|
// A client for user `uid`: the fake bus gives each new connection the uid it is set to.
|
||||||
|
Client As(Fake::Bus& bus, std::uint32_t uid, std::chrono::seconds timeout = std::chrono::minutes(10)) {
|
||||||
|
{
|
||||||
|
std::lock_guard lock(bus.mutex);
|
||||||
|
bus.clientUid = uid;
|
||||||
|
}
|
||||||
|
return Client::System(timeout);
|
||||||
|
}
|
||||||
|
|
||||||
|
void SetPolkit(Fake::Bus& bus, Fake::Polkit outcome, std::string_view action = {}) {
|
||||||
|
std::lock_guard lock(bus.mutex);
|
||||||
|
if(action.empty()) {
|
||||||
|
bus.polkit = outcome;
|
||||||
|
bus.polkitByAction.clear();
|
||||||
|
} else {
|
||||||
|
bus.polkitByAction[std::string(action)] = outcome;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Runs the loop until `done` says so, for at most `limit`; whether it did.
|
||||||
|
template<typename Done>
|
||||||
|
bool RunUntil(sd_event* loop, Done&& done, std::chrono::seconds limit = std::chrono::seconds(60)) {
|
||||||
|
const std::chrono::steady_clock::time_point deadline = std::chrono::steady_clock::now() + limit;
|
||||||
|
while(!done()) {
|
||||||
|
if(std::chrono::steady_clock::now() >= deadline) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
sd_event_run(loop, 100000);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// What the call `start` makes (given its `then`, it returns its Pending) answers, once the loop has delivered it.
|
||||||
|
template<typename T, typename Start>
|
||||||
|
Answer<T> Await(sd_event* loop, Start&& start, std::source_location where = std::source_location::current()) {
|
||||||
|
std::optional<Answer<T>> answer;
|
||||||
|
const Client::Pending pending = start([&answer](Answer<T> got) { answer = std::move(got); });
|
||||||
|
Check(pending.Active(), "a call waits for its answer", where);
|
||||||
|
Check(RunUntil(loop, [&answer] { return answer.has_value(); }), "and gets it", where);
|
||||||
|
Check(!pending.Active(), "and waits no more once it has", where);
|
||||||
|
if(!answer) {
|
||||||
|
std::exit(Test::Result());
|
||||||
|
}
|
||||||
|
return std::move(*answer);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The result of the call `start` makes, which must work.
|
||||||
|
template<typename T, typename Start>
|
||||||
|
T Result(sd_event* loop, Start&& start, std::source_location where = std::source_location::current()) {
|
||||||
|
Answer<T> answer = Await<T>(loop, std::forward<Start>(start), where);
|
||||||
|
Check(!answer.Failed() && answer.Error() == nullptr, "the call works", where);
|
||||||
|
try {
|
||||||
|
return std::move(answer.Get());
|
||||||
|
} catch(const std::exception& e) {
|
||||||
|
Check(false, e.what(), where);
|
||||||
|
std::exit(Test::Result());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The D-Bus name of the DaemonError an answer failed with; "other" for another exception, "none" when it worked.
|
||||||
|
template<typename T>
|
||||||
|
std::string NameOf(Answer<T>& answer) {
|
||||||
|
try {
|
||||||
|
answer.Get();
|
||||||
|
} catch(const DaemonError& e) {
|
||||||
|
return e.name;
|
||||||
|
} catch(const std::exception&) {
|
||||||
|
return "other";
|
||||||
|
}
|
||||||
|
return "none";
|
||||||
|
}
|
||||||
|
|
||||||
|
// A stand-in for nostrod that answers every call with a string, an answer of another shape than any method's. A
|
||||||
|
// plain object rather than a vtable, whose answers sd-bus would hold to their signature.
|
||||||
|
class StandIn {
|
||||||
|
public:
|
||||||
|
StandIn() {
|
||||||
|
sd_bus_open_system(&bus);
|
||||||
|
sd_bus_add_object(bus, nullptr, "/net/catcrafts/Nostro1", OnCall, nullptr);
|
||||||
|
sd_bus_request_name(bus, "net.catcrafts.Nostro1", 0);
|
||||||
|
thread = std::thread([this] {
|
||||||
|
while(!stop) {
|
||||||
|
while(sd_bus_process(bus, nullptr) > 0) {
|
||||||
|
}
|
||||||
|
sd_bus_wait(bus, 20000);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
StandIn(const StandIn&) = delete;
|
||||||
|
StandIn& operator=(const StandIn&) = delete;
|
||||||
|
|
||||||
|
~StandIn() {
|
||||||
|
stop = true;
|
||||||
|
thread.join();
|
||||||
|
sd_bus_flush_close_unref(bus);
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
static std::int32_t OnCall(sd_bus_message* call, void*, sd_bus_error*) {
|
||||||
|
return sd_bus_reply_method_return(call, "s", "not what was asked");
|
||||||
|
}
|
||||||
|
|
||||||
|
sd_bus* bus = nullptr;
|
||||||
|
std::atomic<bool> stop = false;
|
||||||
|
std::thread thread;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Before nostrod runs: calls the client refuses itself, no daemon, and an answer that cannot be read.
|
||||||
|
void WithoutNostrod(Fake::Bus& bus, sd_event* loop) {
|
||||||
|
Client unattached = As(bus, aliceUid);
|
||||||
|
Throws<std::logic_error>([&unattached] { const Client::Pending pending = unattached.Connectors([](Answer<Summaries>) {}); }, "attached to no event loop", "an answer to wait for needs a loop to wait in");
|
||||||
|
|
||||||
|
Client client = As(bus, aliceUid);
|
||||||
|
client.Attach(loop);
|
||||||
|
Check(client.Connected(), "a new client is connected");
|
||||||
|
Throws<std::system_error>([&client, loop] { client.Attach(loop); }, "attach to an event loop", "and attached once");
|
||||||
|
|
||||||
|
Answer<Summaries> missing = Await<Summaries>(loop, [&client](auto then) { return client.Connectors(std::move(then)); });
|
||||||
|
Throws<DaemonMissing>([&missing] { missing.Get(); }, "nostrod is not running", "nostrod not on the bus");
|
||||||
|
|
||||||
|
{
|
||||||
|
const StandIn stand;
|
||||||
|
Check(bus.WaitForName(name), "a stand-in owns nostrod's name");
|
||||||
|
Answer<Summaries> odd = Await<Summaries>(loop, [&client](auto then) { return client.Connectors(std::move(then)); });
|
||||||
|
Check(odd.Failed() && odd.notes.empty(), "an answer that cannot be read fails");
|
||||||
|
Throws<std::system_error>([&odd] { odd.Get(); }, "cannot read", "with what reading it threw");
|
||||||
|
}
|
||||||
|
Check(bus.WaitForName(name, false), "the stand-in lets go of the name");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Each method once, with what it answers.
|
||||||
|
void EveryMethod(Fake::Bus& bus, Fake::Bunq& bunq, std::uint64_t alice, sd_event* loop) {
|
||||||
|
Client client = As(bus, aliceUid);
|
||||||
|
client.Attach(loop);
|
||||||
|
Check(Result<Summaries>(loop, [&client](auto then) { return client.Connectors(std::move(then)); }).empty(), "a new user has no connectors");
|
||||||
|
const AddedConnector added = Result<AddedConnector>(loop, [&client](auto then) { return client.AddBunq("key-alice", "*", "", std::move(then)); });
|
||||||
|
Check(added.name == "Alice" && added.environment == "production" && added.accounts == 1, "a connector added");
|
||||||
|
Equal(Result<Summaries>(loop, [&client](auto then) { return client.Connectors(std::move(then)); }).size(), std::size_t{1}, "and listed");
|
||||||
|
const std::vector<ConnectorAccounts> accounts = Result<std::vector<ConnectorAccounts>>(loop, [&client](auto then) { return client.Accounts(std::move(then)); });
|
||||||
|
Check(accounts.size() == 1 && accounts.at(0).accounts.at(0).iban == aliceMain, "its accounts");
|
||||||
|
Check(Result<std::vector<Transaction>>(loop, [&client](auto then) { return client.Transactions(aliceMain, TransactionQuery{}, std::move(then)); }).empty(), "no transactions yet");
|
||||||
|
|
||||||
|
const Created sent = Result<Created>(loop, [&client](auto then) { return client.Send(aliceMain, bobIban, "Bob", 1250, "lunch", std::move(then)); });
|
||||||
|
Check(sent.id != 0 && sent.currency == Currency::Euro, "a payment");
|
||||||
|
const BunqSchedule schedule{.start = std::chrono::sys_days(std::chrono::year(2027) / 1 / 1), .unit = "MONTHLY"};
|
||||||
|
Check(Result<Created>(loop, [&client, &schedule](auto then) { return client.Schedule(aliceMain, bobIban, "Bob", 300, "rent", schedule, std::move(then)); }).id != 0, "a schedule");
|
||||||
|
Check(Result<Created>(loop, [&client](auto then) { return client.Draft(aliceMain, bobIban, "Bob", 200, "", std::move(then)); }).id != 0, "a draft");
|
||||||
|
const BunqPaymentRequest asked = Result<BunqPaymentRequest>(loop, [&client](auto then) { return client.Request(aliceMain, bobIban, "Bob", 500, "back", std::move(then)); });
|
||||||
|
Check(asked.id != 0 && asked.amount == 500, "a request");
|
||||||
|
Equal(Result<std::vector<BunqPaymentRequest>>(loop, [&client](auto then) { return client.Requests(aliceMain, std::move(then)); }).size(), std::size_t{1}, "the request listed");
|
||||||
|
Result<std::monostate>(loop, [&client, &asked](auto then) { return client.RevokeRequest(aliceMain, asked.id, std::move(then)); });
|
||||||
|
|
||||||
|
Client bob = As(bus, bobUid);
|
||||||
|
bob.AddBunq("key-bob", "*", "");
|
||||||
|
bob.Request(bobIban, aliceMain, "Alice", 700, "rent");
|
||||||
|
const std::vector<BunqIncomingRequest> owed = Result<std::vector<BunqIncomingRequest>>(loop, [&client](auto then) { return client.IncomingRequests(aliceMain, std::move(then)); });
|
||||||
|
Check(!owed.empty() && owed.at(0).amount == 700, "a request received");
|
||||||
|
Result<std::monostate>(loop, [&client, &owed](auto then) { return client.RespondToRequest(aliceMain, owed.at(0).id, false, std::move(then)); });
|
||||||
|
|
||||||
|
const std::vector<BunqScheduledPayment> scheduled = Result<std::vector<BunqScheduledPayment>>(loop, [&client](auto then) { return client.ScheduledPayments(aliceMain, std::move(then)); });
|
||||||
|
Check(!scheduled.empty() && scheduled.at(0).schedule.unit == "MONTHLY", "the schedule listed");
|
||||||
|
Result<std::monostate>(loop, [&client, &scheduled](auto then) { return client.CancelScheduledPayment(aliceMain, scheduled.at(0).id, std::move(then)); });
|
||||||
|
const std::vector<BunqDraftPayment> drafts = Result<std::vector<BunqDraftPayment>>(loop, [&client](auto then) { return client.DraftPayments(aliceMain, std::move(then)); });
|
||||||
|
Check(!drafts.empty(), "the draft listed");
|
||||||
|
Result<std::monostate>(loop, [&client, &drafts](auto then) { return client.RespondToDraftPayment(aliceMain, drafts.at(0).id, false, std::move(then)); });
|
||||||
|
|
||||||
|
const std::uint64_t card = bunq.AddCard(alice, "ACTIVE");
|
||||||
|
Check(!Result<std::vector<ConnectorCards>>(loop, [&client](auto then) { return client.Cards(std::move(then)); }).at(0).cards.empty(), "the cards");
|
||||||
|
Equal(Result<BunqCard>(loop, [&client, card](auto then) { return client.SetCardStatus(card, "DEACTIVATED", std::move(then)); }).status, std::string("DEACTIVATED"), "a card frozen");
|
||||||
|
|
||||||
|
Check(!Result<std::optional<Account>>(loop, [&client](auto then) { return client.DefaultCheckoutAccount(std::move(then)); }).has_value(), "no account pays checkouts yet");
|
||||||
|
Equal(Result<Account>(loop, [&client](auto then) { return client.SetDefaultCheckoutAccount(aliceMain, std::move(then)); }).iban, aliceMain, "until one is chosen");
|
||||||
|
|
||||||
|
const AddedConnector oauth = Result<AddedConnector>(loop, [&client, &bunq](auto then) { return client.AddBunqOAuth("production", bunq.clientId, bunq.clientSecret, "http://127.0.0.1/cb", "code-carol", std::move(then)); });
|
||||||
|
Equal(oauth.name, std::string("Carol"), "a connector through OAuth");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Every way an answer fails, as the blocking calls throw it.
|
||||||
|
void Failures(Fake::Bus& bus, Fake::Bunq& bunq, sd_event* loop) {
|
||||||
|
Client client = As(bus, aliceUid);
|
||||||
|
client.Attach(loop);
|
||||||
|
Answer<Created> unknown = Await<Created>(loop, [&client](auto then) { return client.Send("Nope", bobIban, "Bob", 100, "", std::move(then)); });
|
||||||
|
Check(unknown.Failed() && unknown.Error() != nullptr && unknown.notes.empty(), "a refusal is a failed answer, without notes");
|
||||||
|
Throws<std::invalid_argument>([&unknown] { unknown.Get(); }, "no account is called or has IBAN 'Nope'", "input nostrod refuses");
|
||||||
|
|
||||||
|
SetPolkit(bus, Fake::Polkit::Dismiss, Bus::actionPay);
|
||||||
|
Answer<Created> dismissed = Await<Created>(loop, [&client](auto then) { return client.Send(aliceMain, bobIban, "Bob", 100, "", std::move(then)); });
|
||||||
|
Equal(NameOf(dismissed), std::string(Bus::errorCancelled), "a dialog closed without a password");
|
||||||
|
SetPolkit(bus, Fake::Polkit::Allow);
|
||||||
|
|
||||||
|
bunq.Fail(Fault{.method = "POST", .path = "/user/", .status = 400, .body = R"({"Error":[{"error_description":"Not enough money."}]})"});
|
||||||
|
Answer<Created> poor = Await<Created>(loop, [&client](auto then) { return client.Send(aliceMain, bobIban, "Bob", 100, "", std::move(then)); });
|
||||||
|
Equal(NameOf(poor), std::string(Bus::errorBank), "bunq's refusal");
|
||||||
|
|
||||||
|
// bunq's 5xx to a payment leaves open whether it was made, which the Bank error's message says at its end.
|
||||||
|
bunq.Fail(Fault{.method = "POST", .path = "/user/", .status = 500, .body = R"({"Error":[{"error_description":"Hiccup."}]})"});
|
||||||
|
Answer<Created> hiccup = Await<Created>(loop, [&client](auto then) { return client.Send(aliceMain, bobIban, "Bob", 100, "", std::move(then)); });
|
||||||
|
Throws<OutcomeUnknown>([&hiccup] { hiccup.Get(); }, "Hiccup. (500); the request may have been carried out", "a payment bunq answered with a 5xx may have been made");
|
||||||
|
|
||||||
|
bunq.Fail(Fault{.method = "POST", .path = "/user/", .status = 403, .body = R"({"Error":[{"error_description":"Not allowed for this user."}]})"});
|
||||||
|
Answer<Created> oauth = Await<Created>(loop, [&client](auto then) { return client.Send(carolIban, bobIban, "Bob", 100, "", std::move(then)); });
|
||||||
|
Equal(NameOf(oauth), std::string(Bus::errorOAuthCannotPay), "an OAuth connector paying someone else");
|
||||||
|
|
||||||
|
// No answer in time: a payment may have been made, a listing is only late.
|
||||||
|
Client hurried = As(bus, aliceUid, std::chrono::seconds(1));
|
||||||
|
hurried.Attach(loop);
|
||||||
|
SetPolkit(bus, Fake::Polkit::Silent);
|
||||||
|
Answer<Created> lost = Await<Created>(loop, [&hurried](auto then) { return hurried.Send(aliceMain, bobIban, "Bob", 100, "", std::move(then)); });
|
||||||
|
Throws<OutcomeUnknown>([&lost] { lost.Get(); }, "may have been carried out", "a payment without an answer");
|
||||||
|
Answer<Summaries> late = Await<Summaries>(loop, [&hurried](auto then) { return hurried.Connectors(std::move(then)); });
|
||||||
|
const std::string lateName = NameOf(late);
|
||||||
|
Check(lateName == SD_BUS_ERROR_NO_REPLY || lateName == SD_BUS_ERROR_TIMEOUT, std::format("a listing without an answer is only that: {}", lateName));
|
||||||
|
SetPolkit(bus, Fake::Polkit::Allow);
|
||||||
|
}
|
||||||
|
|
||||||
|
// A Pending dropped, cancelled, moved or assigned over: only the one that still waits gets the answer.
|
||||||
|
void Pendings(Fake::Bus& bus, sd_event* loop) {
|
||||||
|
Client client = As(bus, aliceUid);
|
||||||
|
client.Attach(loop);
|
||||||
|
// Authorized a second later, so each call is still waiting while this looks at it.
|
||||||
|
SetPolkit(bus, Fake::Polkit::Slow, Bus::actionView);
|
||||||
|
bool dropped = false;
|
||||||
|
Client::Pending cancelled = client.Connectors([&dropped](Answer<Summaries>) { dropped = true; });
|
||||||
|
Check(cancelled.Active(), "a call waits");
|
||||||
|
cancelled.Cancel();
|
||||||
|
Check(!cancelled.Active(), "until it is cancelled");
|
||||||
|
cancelled.Cancel();
|
||||||
|
{
|
||||||
|
const Client::Pending forgotten = client.Connectors([&dropped](Answer<Summaries>) { dropped = true; });
|
||||||
|
}
|
||||||
|
|
||||||
|
bool delivered = false;
|
||||||
|
Client::Pending first = client.Connectors([&delivered](Answer<Summaries>) { delivered = true; });
|
||||||
|
Client::Pending second(std::move(first));
|
||||||
|
Check(!first.Active() && second.Active(), "a moved Pending waits in its new place");
|
||||||
|
Client::Pending third;
|
||||||
|
Check(!third.Active(), "an empty one waits for nothing");
|
||||||
|
third = std::move(second);
|
||||||
|
Client::Pending overwritten = client.Connectors([&dropped](Answer<Summaries>) { dropped = true; });
|
||||||
|
overwritten = std::move(third);
|
||||||
|
Check(overwritten.Active(), "assigned over, it waits for what it was given");
|
||||||
|
Check(RunUntil(loop, [&delivered] { return delivered; }), "which is delivered");
|
||||||
|
// The others would have been answered by now, had they not been dropped.
|
||||||
|
RunUntil(loop, [] { return false; }, std::chrono::seconds(2));
|
||||||
|
Check(!dropped, "and nothing that was dropped is");
|
||||||
|
SetPolkit(bus, Fake::Polkit::Allow);
|
||||||
|
}
|
||||||
|
|
||||||
|
struct NotAnException {
|
||||||
|
};
|
||||||
|
|
||||||
|
// A `then` that throws: what it threw goes to the notes, never into sd-bus.
|
||||||
|
void Throwing(Fake::Bus& bus, sd_event* loop) {
|
||||||
|
std::vector<std::string> notes;
|
||||||
|
const std::function<void(std::string_view)> sink = noteSink;
|
||||||
|
noteSink = [¬es](std::string_view note) { notes.emplace_back(note); };
|
||||||
|
Client client = As(bus, aliceUid);
|
||||||
|
client.Attach(loop);
|
||||||
|
bool reached = false;
|
||||||
|
{
|
||||||
|
const Client::Pending pending = client.Connectors([&reached](Answer<Summaries>) {
|
||||||
|
reached = true;
|
||||||
|
throw std::runtime_error("the handler broke");
|
||||||
|
});
|
||||||
|
Check(RunUntil(loop, [&reached] { return reached; }), "a then that throws is called");
|
||||||
|
}
|
||||||
|
reached = false;
|
||||||
|
{
|
||||||
|
const Client::Pending pending = client.Connectors([&reached](Answer<Summaries>) {
|
||||||
|
reached = true;
|
||||||
|
throw NotAnException();
|
||||||
|
});
|
||||||
|
Check(RunUntil(loop, [&reached] { return reached; }), "and one that throws something else");
|
||||||
|
}
|
||||||
|
noteSink = sink;
|
||||||
|
Check(notes.size() == 2 && notes.at(0) == "nostrod's answer to Connectors could not be handled: the handler broke" && notes.at(1) == "nostrod's answer to Connectors could not be handled", "what they threw is noted");
|
||||||
|
}
|
||||||
|
|
||||||
|
void Remove(Fake::Bus& bus, sd_event* loop) {
|
||||||
|
Client client = As(bus, aliceUid);
|
||||||
|
client.Attach(loop);
|
||||||
|
Equal(Result<std::string>(loop, [&client](auto then) { return client.RemoveConnector("Carol", std::move(then)); }), std::string("Carol"), "a connector removed");
|
||||||
|
}
|
||||||
|
|
||||||
|
// The library's warnings come with the answer of the call they were given during, not into the client's own notes.
|
||||||
|
void Notes(Fake::Bus& bus, Fake::Bunq& bunq, sd_event* loop) {
|
||||||
|
Client bob = As(bus, bobUid);
|
||||||
|
bob.Attach(loop);
|
||||||
|
{
|
||||||
|
std::lock_guard lock(bunq.mutex);
|
||||||
|
bunq.keys.erase("key-bob");
|
||||||
|
}
|
||||||
|
bunq.ExpireSessions();
|
||||||
|
const Answer<std::vector<ConnectorAccounts>> answer = Await<std::vector<ConnectorAccounts>>(loop, [&bob](auto then) { return bob.Accounts(std::move(then)); });
|
||||||
|
Check(!answer.Failed() && !answer.notes.empty() && std::ranges::all_of(answer.notes, [](const std::string& note) { return note.contains("bunq connector 'Bob' is unavailable"); }), "a connector that cannot be reached comes with the answer as a note");
|
||||||
|
Check(bob.TakeNotes().empty(), "and not into the client's notes");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// main's signature is C's.
|
||||||
|
// lint-disable-next-line no-char-pointer
|
||||||
|
int main(int argc, char* argv[]) {
|
||||||
|
// nostrod, and each of its workers, is this executable again.
|
||||||
|
if(Fake::IsNostrod()) {
|
||||||
|
Fake::Bunq::RedirectFromEnvironment();
|
||||||
|
return NostrodMain(argc, argv);
|
||||||
|
}
|
||||||
|
|
||||||
|
const Test::Directory directory("async");
|
||||||
|
const fs::path state = directory.path / "state";
|
||||||
|
// What nostrod reads from the environment is set before any thread starts.
|
||||||
|
setenv("XDG_DATA_HOME", (directory.path / "data").c_str(), 1);
|
||||||
|
Fake::Bunq::ExportRedirect(port, directory.path / "bunq.pem");
|
||||||
|
setenv("DBUS_SYSTEM_BUS_ADDRESS", Fake::Bus::Address(directory.path / "bus").c_str(), 1);
|
||||||
|
Fake::Bus bus(directory.path / "bus");
|
||||||
|
{
|
||||||
|
std::lock_guard lock(bus.mutex);
|
||||||
|
bus.logindNames = {{aliceUid, "alice"}, {bobUid, "bob"}};
|
||||||
|
}
|
||||||
|
|
||||||
|
Fake::Bunq bunq(port);
|
||||||
|
const std::uint64_t alice = bunq.AddPerson("Alice", "key-alice");
|
||||||
|
bunq.AddAccount(alice, aliceMain, "Main", 100000);
|
||||||
|
bunq.AddAccount(bunq.AddPerson("Bob", "key-bob"), bobIban, "Bob's", 0);
|
||||||
|
const std::uint64_t carol = bunq.AddPerson("Carol", "key-carol");
|
||||||
|
bunq.AddAccount(carol, carolIban, "Shared", 500);
|
||||||
|
bunq.AddGrant(carol, "code-carol", "token-carol");
|
||||||
|
|
||||||
|
sd_event* loop = nullptr;
|
||||||
|
sd_event_new(&loop);
|
||||||
|
WithoutNostrod(bus, loop);
|
||||||
|
const pid_t nostrod = Fake::StartNostrod({"--state", state.string(), "--idle", "60", "--prompt-timeout", "2"});
|
||||||
|
Check(bus.WaitForName(name), "nostrod owns its name");
|
||||||
|
EveryMethod(bus, bunq, alice, loop);
|
||||||
|
Failures(bus, bunq, loop);
|
||||||
|
Pendings(bus, loop);
|
||||||
|
Throwing(bus, loop);
|
||||||
|
Remove(bus, loop);
|
||||||
|
Notes(bus, bunq, loop);
|
||||||
|
bus.Disconnect(name);
|
||||||
|
Equal(Fake::Wait(nostrod), 0, "nostrod ends when the bus goes");
|
||||||
|
sd_event_unref(loop);
|
||||||
|
return Test::Result();
|
||||||
|
}
|
||||||
1236
tests/ShouldBuildFrames/main.cpp
Normal file
1236
tests/ShouldBuildFrames/main.cpp
Normal file
File diff suppressed because it is too large
Load diff
1870
tests/ShouldDriveTheApp/main.cpp
Normal file
1870
tests/ShouldDriveTheApp/main.cpp
Normal file
File diff suppressed because it is too large
Load diff
195
tests/ShouldEditText/main.cpp
Normal file
195
tests/ShouldEditText/main.cpp
Normal file
|
|
@ -0,0 +1,195 @@
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
// A text field's editing by code point: one to four bytes of UTF-8, the selection, what each kind of field takes,
|
||||||
|
// the input method's composing text and its deletions, and a secret that is wiped when it goes.
|
||||||
|
|
||||||
|
import std;
|
||||||
|
import Nostro.Ui;
|
||||||
|
|
||||||
|
#include "../Support/Check.inc"
|
||||||
|
|
||||||
|
using namespace Nostro::Ui;
|
||||||
|
using Test::Check;
|
||||||
|
using Test::Equal;
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
// a, é, € and 😀: one, two, three and four bytes; boundaries 0 1 3 6 10.
|
||||||
|
const std::string mixed = "aé€\U0001F600";
|
||||||
|
|
||||||
|
void Put(EditState& field, std::string_view value, std::size_t cursor) {
|
||||||
|
field.Set(value);
|
||||||
|
field.MoveTo(cursor);
|
||||||
|
}
|
||||||
|
|
||||||
|
void Keys() {
|
||||||
|
EditState field;
|
||||||
|
Check(field.Empty() && field.kind == FieldKind::Text, "a new field is empty, and takes prose");
|
||||||
|
Put(field, mixed, 10);
|
||||||
|
Check(field.Apply(EditKey::Backspace) && field.cursor == 6 && field.value == "aé€", "Backspace takes the four-byte emoji");
|
||||||
|
Put(field, mixed, 1);
|
||||||
|
Check(field.Apply(EditKey::Delete) && field.cursor == 1 && field.value == "a€\U0001F600", "Delete takes the two-byte é");
|
||||||
|
Put(field, "abc", 0);
|
||||||
|
Check(!field.Apply(EditKey::Backspace) && field.value == "abc" && field.cursor == 0, "Backspace at the start deletes nothing and says so");
|
||||||
|
Put(field, "abc", 3);
|
||||||
|
Check(!field.Apply(EditKey::Delete) && field.value == "abc" && field.cursor == 3, "Delete at the end deletes nothing and says so");
|
||||||
|
|
||||||
|
Put(field, mixed, 6);
|
||||||
|
Check(field.Apply(EditKey::Left) && field.cursor == 3, "Left moves back over the three-byte €");
|
||||||
|
Check(field.Apply(EditKey::Right) && field.cursor == 6, "Right moves over it again");
|
||||||
|
Put(field, "ab", 0);
|
||||||
|
Check(field.Apply(EditKey::Left) && field.cursor == 0, "Left at the start stays, and is still a move");
|
||||||
|
Put(field, "ab", 2);
|
||||||
|
Check(field.Apply(EditKey::Right) && field.cursor == 2, "Right at the end stays, and is still a move");
|
||||||
|
Put(field, "hello", 2);
|
||||||
|
Check(field.Apply(EditKey::Home) && field.cursor == 0 && field.Apply(EditKey::End) && field.cursor == 5, "Home and End go to the line's ends");
|
||||||
|
|
||||||
|
Put(field, mixed, 2);
|
||||||
|
Equal(field.cursor, std::size_t{1}, "a cursor asked for inside a character goes to its start");
|
||||||
|
Put(field, mixed, 99);
|
||||||
|
Equal(field.cursor, std::size_t{10}, "and one past the end to the end");
|
||||||
|
}
|
||||||
|
|
||||||
|
void Selecting() {
|
||||||
|
EditState field;
|
||||||
|
Put(field, "hello world", 5);
|
||||||
|
Check(!field.HasSelection() && field.Selected().empty(), "a cursor alone selects nothing");
|
||||||
|
field.Apply(EditKey::Right, true);
|
||||||
|
field.Apply(EditKey::End, true);
|
||||||
|
Check(field.HasSelection() && field.Selected() == " world" && field.SelectionBegin() == 5 && field.SelectionEnd() == 11, "Shift with a move stretches the selection from where it began");
|
||||||
|
field.Apply(EditKey::Home, true);
|
||||||
|
Check(field.Selected() == "hello" && field.cursor == 0 && field.anchor == 5, "back past where it began, it selects the other way");
|
||||||
|
field.Apply(EditKey::Left);
|
||||||
|
Check(!field.HasSelection() && field.cursor == 0, "Left without Shift ends a selection at its start");
|
||||||
|
field.SelectAll();
|
||||||
|
Check(field.Selected() == "hello world" && field.cursor == 11, "everything selected, the cursor at the end");
|
||||||
|
field.Apply(EditKey::Right);
|
||||||
|
Check(!field.HasSelection() && field.cursor == 11, "Right ends a selection at its end");
|
||||||
|
field.SelectAll();
|
||||||
|
field.Apply(EditKey::Left);
|
||||||
|
Equal(field.cursor, std::size_t{0}, "and Left at its start, wherever the cursor was");
|
||||||
|
field.SelectAll();
|
||||||
|
field.Apply(EditKey::Home);
|
||||||
|
Check(!field.HasSelection() && field.cursor == 0, "Home ends it at the start of the line");
|
||||||
|
|
||||||
|
Put(field, "hello world", 5);
|
||||||
|
field.Apply(EditKey::End, true);
|
||||||
|
Check(field.Apply(EditKey::Backspace) && field.value == "hello" && field.cursor == 5 && !field.HasSelection(), "Backspace deletes what is selected, and only that");
|
||||||
|
field.SelectAll();
|
||||||
|
Check(field.Apply(EditKey::Delete) && field.Empty(), "so does Delete");
|
||||||
|
Check(!field.DeleteSelection(), "with nothing selected there is nothing to delete");
|
||||||
|
Put(field, "hello world", 0);
|
||||||
|
field.Apply(EditKey::End, true);
|
||||||
|
field.Commit("x");
|
||||||
|
Check(field.value == "x" && field.cursor == 1, "what is typed takes the place of the selection");
|
||||||
|
field.SelectAll();
|
||||||
|
field.MoveTo(0);
|
||||||
|
Check(!field.HasSelection(), "a tap ends a selection");
|
||||||
|
}
|
||||||
|
|
||||||
|
void Kinds() {
|
||||||
|
EditState prose;
|
||||||
|
prose.Commit("a\tb\nc d\x01\x7f");
|
||||||
|
Equal(prose.value, std::string("a b c d"), "a line of prose: a tab or a line break is a space, a control character nothing");
|
||||||
|
prose.Set("\xff" "ok\xe2\x82");
|
||||||
|
Equal(prose.value, std::string("ok"), "malformed UTF-8 is dropped");
|
||||||
|
prose.Set("a\xEF\xBF\xBD" "b");
|
||||||
|
Equal(prose.value, std::string("a\xEF\xBF\xBD" "b"), "a replacement character that is one is kept");
|
||||||
|
|
||||||
|
EditState plain(FieldKind::Plain);
|
||||||
|
plain.Paste("NL23 BUNQ 2025\n");
|
||||||
|
Equal(plain.value, std::string("NL23 BUNQ 2025"), "a line taken as typed keeps its spaces and drops a line break around it");
|
||||||
|
|
||||||
|
EditState decimal(FieldKind::Decimal);
|
||||||
|
decimal.Paste("€ 1.234,50 EUR");
|
||||||
|
Equal(decimal.value, std::string("1.234,50"), "an amount takes digits and separators");
|
||||||
|
|
||||||
|
EditState digits(FieldKind::Digits);
|
||||||
|
digits.Commit("12,5 x");
|
||||||
|
Equal(digits.value, std::string("125"), "a whole number takes digits");
|
||||||
|
|
||||||
|
EditState secret(FieldKind::Secret);
|
||||||
|
secret.Paste(" sandbox_abc 123\n");
|
||||||
|
Equal(secret.value, std::string("sandbox_abc123"), "a key has no space in it");
|
||||||
|
|
||||||
|
EditState full;
|
||||||
|
full.Set(std::string(EditState::limit - 1, 'a'));
|
||||||
|
full.Commit("é!");
|
||||||
|
Check(full.value.size() == EditState::limit - 1 && full.cursor == full.value.size(), "a field takes no more than it holds, and no half character");
|
||||||
|
full.Commit("b");
|
||||||
|
Equal(full.value.size(), EditState::limit, "what still fits is taken");
|
||||||
|
full.Commit("c");
|
||||||
|
Equal(full.value.size(), EditState::limit, "and nothing after that");
|
||||||
|
}
|
||||||
|
|
||||||
|
void Composing() {
|
||||||
|
EditState field;
|
||||||
|
Put(field, "hello", 2);
|
||||||
|
field.preedit = "XY";
|
||||||
|
Check(field.Shown() == "heXYllo" && field.ShownCursor() == 4 && !field.Empty(), "the composing text shows at the cursor");
|
||||||
|
field.Commit("Z");
|
||||||
|
Check(field.value == "heZllo" && field.preedit.empty() && field.cursor == 3, "what the input method commits takes the place of what it composed");
|
||||||
|
field.preedit = "W";
|
||||||
|
field.Paste("!");
|
||||||
|
Check(field.value == "heZW!llo" && field.preedit.empty(), "what is pasted follows the composing word, which is kept");
|
||||||
|
|
||||||
|
// The input method's deletions: byte counts around the cursor, rounded out to code points.
|
||||||
|
Put(field, mixed, 6);
|
||||||
|
field.preedit = "z";
|
||||||
|
field.DeleteAround(1, 1);
|
||||||
|
Check(field.cursor == 3 && field.preedit == "z" && field.value == "aé", "one byte each side takes the € before and the 😀 after; the composing text stays");
|
||||||
|
Put(field, "abc", 1);
|
||||||
|
field.DeleteAround(5, 0);
|
||||||
|
Check(field.cursor == 0 && field.value == "bc", "a deletion past the start stops at the start");
|
||||||
|
Put(field, "abc", 2);
|
||||||
|
field.DeleteAround(0, 9);
|
||||||
|
Check(field.cursor == 2 && field.value == "ab", "and one past the end at the end");
|
||||||
|
field.DeleteAround(0, 0);
|
||||||
|
Check(field.cursor == 2 && field.value == "ab", "a deletion of nothing leaves the text");
|
||||||
|
|
||||||
|
Put(field, "hello wor", 9);
|
||||||
|
field.preedit = "ld";
|
||||||
|
field.CommitPreedit();
|
||||||
|
Check(field.cursor == 11 && field.preedit.empty() && field.value == "hello world", "the composing text taken into the value, the cursor past it");
|
||||||
|
field.CommitPreedit();
|
||||||
|
Equal(field.value, std::string("hello world"), "with no composing text nothing changes");
|
||||||
|
|
||||||
|
EditState empty;
|
||||||
|
empty.preedit = "x";
|
||||||
|
Check(!empty.Empty(), "a field with only a composing text is not empty");
|
||||||
|
empty.Clear();
|
||||||
|
Check(empty.Empty() && empty.cursor == 0 && empty.anchor == 0, "cleared, nothing is left");
|
||||||
|
}
|
||||||
|
|
||||||
|
void Secrets() {
|
||||||
|
EditState secret(FieldKind::Secret);
|
||||||
|
Check(secret.value.capacity() >= EditState::secretLimit, "a secret's buffer is its full size from the start");
|
||||||
|
// libc++'s string keeps its buffer when it is cleared, so its address can still be read: the bytes of the key
|
||||||
|
// must be gone from it.
|
||||||
|
const std::string_view buffer(secret.value.data(), EditState::secretLimit);
|
||||||
|
secret.Commit("sandbox_0123456789abcdef");
|
||||||
|
Check(secret.value.data() == buffer.data(), "typing into it moves nothing");
|
||||||
|
secret.Apply(EditKey::Backspace);
|
||||||
|
secret.preedit = "composing";
|
||||||
|
secret.CommitPreedit();
|
||||||
|
Check(secret.value == "sandbox_0123456789abcdecomposing" && secret.value.data() == buffer.data(), "nor does an edit");
|
||||||
|
secret.Commit(std::string(600, 'k'));
|
||||||
|
Check(secret.value.size() == EditState::secretLimit && secret.value.data() == buffer.data(), "it takes no more than its buffer holds");
|
||||||
|
secret.Clear();
|
||||||
|
Check(secret.Empty() && buffer.find_first_not_of('\0') == std::string_view::npos, "cleared, no byte of it is left in memory");
|
||||||
|
{
|
||||||
|
EditState gone(FieldKind::Secret);
|
||||||
|
gone.Commit("another-key");
|
||||||
|
}
|
||||||
|
Check(true, "a secret that goes out of scope is cleared first");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
Keys();
|
||||||
|
Selecting();
|
||||||
|
Kinds();
|
||||||
|
Composing();
|
||||||
|
Secrets();
|
||||||
|
return Test::Result();
|
||||||
|
}
|
||||||
466
tests/ShouldLayOutWidgets/main.cpp
Normal file
466
tests/ShouldLayOutWidgets/main.cpp
Normal file
|
|
@ -0,0 +1,466 @@
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
// Nostro.Ui's layout cursors and its widgets, each in every state it has: what it draws, where, in which colours, and
|
||||||
|
// what a press on it does. The font is a fixed one (Ui.inc); the window is 400 by 800 at a scale of one unless a
|
||||||
|
// check says otherwise, so a size of the design is that many pixels.
|
||||||
|
|
||||||
|
import std;
|
||||||
|
import Nostro.Ui;
|
||||||
|
|
||||||
|
#include "../Support/Check.inc"
|
||||||
|
#include "../Support/Ui.inc"
|
||||||
|
|
||||||
|
using namespace Nostro::Ui;
|
||||||
|
using Test::Check;
|
||||||
|
using Test::Equal;
|
||||||
|
using Test::Hides;
|
||||||
|
using Test::Shows;
|
||||||
|
using Test::TapAt;
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
constexpr Box window{0, 0, 400, 800};
|
||||||
|
|
||||||
|
template<typename Scene>
|
||||||
|
void Build(Context& ui, Scene&& scene, Box bounds = window, float scale = 1) {
|
||||||
|
Frame& frame = ui.Begin(bounds, scale, 0);
|
||||||
|
scene(frame);
|
||||||
|
ui.End();
|
||||||
|
}
|
||||||
|
|
||||||
|
// The line of text that reads `text`, or nothing.
|
||||||
|
const TextItem* Line(const Context& ui, std::string_view text) {
|
||||||
|
for(std::size_t layer = 0; layer < layerCount; layer++) {
|
||||||
|
for(const Batch& batch : ui.Shown().draw.Batches(static_cast<Layer>(layer))) {
|
||||||
|
for(const TextItem& item : batch.texts) {
|
||||||
|
if(item.text == text) {
|
||||||
|
return &item;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The boxes drawn in a colour, in the order they are drawn.
|
||||||
|
std::vector<RectItem> Rects(const Context& ui, Color color) {
|
||||||
|
std::vector<RectItem> rects;
|
||||||
|
for(std::size_t layer = 0; layer < layerCount; layer++) {
|
||||||
|
for(const Batch& batch : ui.Shown().draw.Batches(static_cast<Layer>(layer))) {
|
||||||
|
for(const RectItem& item : batch.rects) {
|
||||||
|
if(item.color == color) {
|
||||||
|
rects.push_back(item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return rects;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::size_t Circles(const Context& ui) {
|
||||||
|
std::size_t count = 0;
|
||||||
|
for(std::size_t layer = 0; layer < layerCount; layer++) {
|
||||||
|
for(const Batch& batch : ui.Shown().draw.Batches(static_cast<Layer>(layer))) {
|
||||||
|
count += batch.circles.size();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Whether a line is drawn around a box: the keyboard's focus on it.
|
||||||
|
bool Ringed(const Context& ui, Box box) {
|
||||||
|
const std::vector<RectItem> rings = Rects(ui, ui.theme.accent.WithAlpha(0));
|
||||||
|
return std::ranges::any_of(rings, [box](const RectItem& ring) { return ring.box == box && ring.outline == 2; });
|
||||||
|
}
|
||||||
|
|
||||||
|
void Cursors() {
|
||||||
|
Column column({10, 20, 100, 300}, 8);
|
||||||
|
Check(column.Next() == Box{10, 20, 100, 300} && column.Used() == 0, "a column starts at its area's top, with nothing used");
|
||||||
|
Check(column.Take(40) == Box{10, 20, 100, 40} && column.Take(60) == Box{10, 68, 100, 60}, "each box starts under the one before, the gap between them");
|
||||||
|
Check(column.Next() == Box{10, 136, 100, 184} && column.Used() == 108, "what is used is the boxes and the gaps between them, not the gap after the last");
|
||||||
|
column.Advance(500);
|
||||||
|
Check(column.Next().h == 0 && column.Take(10).y == 644, "a column may run past its area: one that scrolls is as long as its content");
|
||||||
|
|
||||||
|
Row row({10, 20, 300, 40}, 4);
|
||||||
|
Check(row.TakeLeft(50) == Box{10, 20, 50, 40} && row.TakeRight(60) == Box{250, 20, 60, 40} && row.Rest() == Box{64, 20, 182, 40}, "a row gives boxes from its ends, and the rest between them");
|
||||||
|
row.TakeLeft(400);
|
||||||
|
Equal(row.Rest().w, 0.0f, "nothing is left of a row that is taken up");
|
||||||
|
|
||||||
|
Check(Centered({0, 0, 1000, 50}, 640) == Box{180, 0, 640, 50} && Centered({20, 0, 300, 50}, 640) == Box{20, 0, 300, 50}, "a box no wider than asked, in the middle of the area");
|
||||||
|
}
|
||||||
|
|
||||||
|
void Words() {
|
||||||
|
Context ui(Test::FixedMeasure());
|
||||||
|
float tall = 0;
|
||||||
|
float measured = 0;
|
||||||
|
Build(ui, [&](Frame& frame) {
|
||||||
|
Check(Body(frame).sizeDp == 16 && Strong(frame).face == FontFace::Medium && Muted(frame).color == ui.theme.muted && Caption(frame).sizeDp == 12 && Heading(frame).sizeDp == 18, "the styles text is set in");
|
||||||
|
Label(frame, {10, 0, 200, 40}, "left", Body(frame));
|
||||||
|
Label(frame, {10, 40, 200, 40}, "middle", {FontFace::Regular, 16, ui.theme.text, TextAlign::Center});
|
||||||
|
Label(frame, {10, 80, 200, 40}, "right", {FontFace::Regular, 16, ui.theme.text, TextAlign::Right});
|
||||||
|
Label(frame, {10, 120, 64, 40}, "much too long", Body(frame));
|
||||||
|
tall = Paragraph(frame, {10, 200, 80, 0}, "one two three four", Body(frame));
|
||||||
|
Paragraph(frame, {10, 400, 200, 0}, "in the middle", {FontFace::Regular, 16, ui.theme.text, TextAlign::Center});
|
||||||
|
Paragraph(frame, {10, 440, 200, 0}, "at the end", {FontFace::Regular, 16, ui.theme.text, TextAlign::Right});
|
||||||
|
measured = ParagraphHeight(frame, 80, "one two three four", Body(frame));
|
||||||
|
});
|
||||||
|
Check(Line(ui, "left")->x == 10 && Line(ui, "left")->baseline == 10 + 12.8f && Line(ui, "middle")->x == 110 && Line(ui, "right")->x == 210, "a label sits in the middle of its box's height, at the edge its alignment names");
|
||||||
|
Shows(ui, "much to…", "and is cut where it does not fit");
|
||||||
|
Check(Line(ui, "one two") != nullptr && Line(ui, "three four") != nullptr && Line(ui, "three four")->baseline == Line(ui, "one two")->baseline + 20 && tall == 40 && measured == 40, "a paragraph wraps to its box's width, and says how tall it came out");
|
||||||
|
Check(Line(ui, "in the middle")->x == 110 && Line(ui, "at the end")->x == 210, "its lines go by the same alignment");
|
||||||
|
}
|
||||||
|
|
||||||
|
void Buttons() {
|
||||||
|
Context ui(Test::FixedMeasure());
|
||||||
|
std::int32_t taps = 0;
|
||||||
|
const auto scene = [&](Frame& frame) {
|
||||||
|
frame.draw.SetLayer(Layer::Content);
|
||||||
|
Button(frame, {10, 10, 120, 48}, {.key = "filled", .label = "Pay", .onTap = [&taps] { taps++; }});
|
||||||
|
Button(frame, {10, 70, 120, 48}, {.key = "tonal", .label = "Request", .kind = ButtonKind::Tonal});
|
||||||
|
Button(frame, {10, 130, 120, 48}, {.key = "plain", .label = "Cancel", .kind = ButtonKind::Plain});
|
||||||
|
Button(frame, {10, 190, 120, 48}, {.key = "danger", .label = "Remove", .kind = ButtonKind::Danger});
|
||||||
|
Button(frame, {10, 250, 120, 48}, {.key = "off", .label = "Not yet", .enabled = false, .onTap = [&taps] { taps++; }});
|
||||||
|
Button(frame, {10, 328, 120, 32}, {.key = "low", .label = "More", .kind = ButtonKind::Plain, .onTap = [&taps] { taps += 10; }});
|
||||||
|
Check(ButtonWidth(frame, "Pay") == 3 * 8 + 32, "a button is as wide as its label and a gutter each side");
|
||||||
|
};
|
||||||
|
Build(ui, scene);
|
||||||
|
const Theme& theme = ui.theme;
|
||||||
|
Check(Rects(ui, theme.accent).size() == 1 && Rects(ui, theme.accent)[0].box == Box{10, 10, 120, 48} && Line(ui, "Pay")->color == theme.onAccent && Line(ui, "Pay")->face == FontFace::Medium && Line(ui, "Pay")->x == 70, "a filled button: the accent, its label in the middle");
|
||||||
|
Check(Rects(ui, theme.surfaceAlt).size() == 2 && Line(ui, "Request")->color == theme.text && Line(ui, "Not yet")->color == theme.muted, "a tonal button and a disabled one stand on the quiet ground");
|
||||||
|
Check(Rects(ui, theme.surface).empty() && Line(ui, "Cancel")->color == theme.accent, "a plain one is its label alone");
|
||||||
|
Check(Rects(ui, theme.danger).size() == 1 && Line(ui, "Remove")->color == theme.onDanger, "a dangerous one says so by its colour");
|
||||||
|
Check(ui.Find("filled")->focusable && ui.Find("filled")->label == "Pay" && !ui.Find("off")->enabled && ui.Find("filled")->box == Box{10, 10, 120, 48}, "each is a region with its label, as large as it is drawn");
|
||||||
|
|
||||||
|
TapAt(ui, {50, 30});
|
||||||
|
TapAt(ui, {50, 270});
|
||||||
|
Equal(taps, 1, "a tap presses it, unless it is disabled");
|
||||||
|
TapAt(ui, {50, 322});
|
||||||
|
TapAt(ui, {50, 366});
|
||||||
|
TapAt(ui, {50, 370});
|
||||||
|
Check(taps == 21 && ui.Find("low")->box == Box{10, 320, 120, 48}, "a button lower than a finger needs takes a press from as much above and below it as makes up for that");
|
||||||
|
ui.Hover(Point{50, 150});
|
||||||
|
Build(ui, scene);
|
||||||
|
Equal(Rects(ui, theme.Hovered(theme.surface)).size(), std::size_t{1}, "under the pointer a plain button gets a ground");
|
||||||
|
ui.Pointer(PointerPhase::Down, {50, 30}, 0);
|
||||||
|
ui.Hover(Point{50, 270});
|
||||||
|
Build(ui, scene);
|
||||||
|
Check(Rects(ui, theme.Pressed(theme.accent)).size() == 1 && Rects(ui, theme.accent).empty() && Rects(ui, theme.surfaceAlt).size() == 2, "a pressed button is drawn pressed; a disabled one feels nothing");
|
||||||
|
ui.Pointer(PointerPhase::Cancel, {50, 30}, 10);
|
||||||
|
ui.Focus("tonal");
|
||||||
|
Build(ui, scene);
|
||||||
|
Check(Ringed(ui, {10, 70, 120, 48}) && !Ringed(ui, {10, 10, 120, 48}), "the keyboard's focus is a line around it");
|
||||||
|
}
|
||||||
|
|
||||||
|
void Rows() {
|
||||||
|
Context ui(Test::FixedMeasure());
|
||||||
|
std::vector<std::string> seen;
|
||||||
|
const Color green{0, 0.5f, 0};
|
||||||
|
// 43 characters, and room for 37 beside the mark: the row is 368 wide within its gutters, the mark 58 and a gap of 8.
|
||||||
|
const std::string longTitle = "A connection with quite a long name, indeed";
|
||||||
|
const std::string cutTitle = Ellipsize(Test::FixedMeasure(), longTitle, FontFace::Regular, 16, 302);
|
||||||
|
const auto scene = [&](Frame& frame) {
|
||||||
|
frame.draw.SetLayer(Layer::Content);
|
||||||
|
ListRow(frame, {0, 0, 400, 64}, {.key = "main", .title = "Main account", .subtitle = "NL23 BUNQ 2025 1234 56", .trailing = "€12.50", .trailingSub = "today", .chevron = true, .onTap = [&seen] { seen.push_back("main"); }, .onLongPress = [&seen] { seen.push_back("main held"); }});
|
||||||
|
ListRow(frame, {0, 64, 400, 56}, {.key = "plain", .title = "Just a title", .divider = false});
|
||||||
|
ListRow(frame, {0, 120, 400, 64}, {.key = "in", .title = "Bob", .trailing = "+€5.00", .trailingColor = green});
|
||||||
|
ListRow(frame, {0, 184, 400, 64}, {.key = "dated", .title = "Carol", .trailingSub = "1 Nov"});
|
||||||
|
ListRow(frame, {0, 248, 400, 64}, {.key = "sandbox", .title = longTitle, .badge = "Sandbox"});
|
||||||
|
ListRow(frame, {0, 312, 400, 64}, {.key = "chosen", .title = "Savings", .selected = true, .onTap = [&seen] { seen.push_back("chosen"); }});
|
||||||
|
ListRow(frame, {0, 376, 400, 64}, {.key = "other", .title = "Joint", .selected = false, .enabled = false, .onTap = [&seen] { seen.push_back("other"); }});
|
||||||
|
};
|
||||||
|
Build(ui, scene);
|
||||||
|
const Theme& theme = ui.theme;
|
||||||
|
Check(Line(ui, "Main account")->x == 16 && Line(ui, "NL23 BUNQ 2025 1234 56")->color == theme.muted && Line(ui, "NL23 BUNQ 2025 1234 56")->baseline > Line(ui, "Main account")->baseline, "a row's title, and under it its second line");
|
||||||
|
Check(Line(ui, "€12.50")->align == TextAlign::Right && Line(ui, "€12.50")->x == 400 - 16 - 20 && Line(ui, "today")->x == 364 && Line(ui, "today")->baseline > Line(ui, "€12.50")->baseline && Line(ui, "›") != nullptr, "what trails it at the right, before the mark that it leads somewhere");
|
||||||
|
Check(Line(ui, "Just a title")->baseline == 64 + (56 - 20) / 2.0f + 12.8f, "a title alone is in the middle of the row");
|
||||||
|
Check(Line(ui, "+€5.00")->color == green && Line(ui, "+€5.00")->baseline == Line(ui, "Bob")->baseline && Line(ui, "1 Nov")->baseline == 184 + (64 - 15) / 2.0f + 9.6f, "an amount in its own colour; one trailing line alone is in the row's middle");
|
||||||
|
Check(cutTitle != longTitle && Line(ui, cutTitle) != nullptr && Line(ui, "Sandbox") != nullptr && Line(ui, "Sandbox")->bounds.x > Line(ui, cutTitle)->bounds.Right(), "a mark follows the title, which makes room for it");
|
||||||
|
Check(Circles(ui) == 3 && Line(ui, "Savings")->x == 16 + 36 && Line(ui, "Joint")->color == theme.muted, "a choice among rows is a ring, with a dot in the one chosen; a disabled row is muted");
|
||||||
|
Check(Rects(ui, theme.divider).size() == 6 && Rects(ui, theme.divider)[0].box == Box{16, 63, 384, 1}, "a line under every row but the one that asked for none, from its title to the edge of a window as narrow as a phone");
|
||||||
|
Check(ui.Find("main")->role == Role::Row && ui.Find("main")->focusable && !ui.Find("plain")->focusable && ui.Find("main")->label == "Main account", "a row is a region; one that does nothing takes no focus");
|
||||||
|
|
||||||
|
TapAt(ui, {200, 30});
|
||||||
|
TapAt(ui, {200, 400});
|
||||||
|
Check(ui.LongPress("main") && seen == std::vector<std::string>{"main", "main held"}, "a tap and a long press act; a disabled row does not");
|
||||||
|
ui.Hover(Point{200, 30});
|
||||||
|
Build(ui, scene);
|
||||||
|
Check(Rects(ui, theme.Hovered(theme.surface)).size() == 1 && Rects(ui, theme.Hovered(theme.surface))[0].box == Box{0, 0, 400, 64}, "the pointer over a row that acts tints it");
|
||||||
|
ui.Hover(Point{200, 90});
|
||||||
|
ui.Pointer(PointerPhase::Down, {200, 340}, 0);
|
||||||
|
Build(ui, scene);
|
||||||
|
Check(Rects(ui, theme.Hovered(theme.surface)).empty() && Rects(ui, theme.Pressed(theme.surface)).size() == 1, "one that does nothing is not; a pressed one is drawn pressed");
|
||||||
|
ui.Pointer(PointerPhase::Cancel, {200, 340}, 10);
|
||||||
|
ui.Focus("chosen");
|
||||||
|
Build(ui, scene);
|
||||||
|
Check(Ringed(ui, {2, 314, 396, 60}), "the keyboard's focus is a line just inside it");
|
||||||
|
|
||||||
|
Build(ui, scene, {0, 0, 1000, 800});
|
||||||
|
Check(Rects(ui, theme.divider)[0].box == Box{16, 63, 368, 1}, "in a wider window the line under a row ends where the row's text does");
|
||||||
|
}
|
||||||
|
|
||||||
|
// A line of a sheet that says what something is: a label, and beside it a value that a press can copy.
|
||||||
|
void Values() {
|
||||||
|
Context ui(Test::FixedMeasure());
|
||||||
|
std::vector<std::string> seen;
|
||||||
|
std::array<float, 3> heights{};
|
||||||
|
float foretold = 0;
|
||||||
|
// 74 characters, and room for 34 on a line: the row is 400 wide, its text 8 clear of either side, the label 112.
|
||||||
|
const std::string longValue = "A description that is long enough to need a second line in the room it has";
|
||||||
|
const std::string longLabel = "A label that is too long for its room";
|
||||||
|
const auto scene = [&](Frame& frame) {
|
||||||
|
frame.draw.SetLayer(Layer::Content);
|
||||||
|
const ValueOptions iban{.key = "iban", .label = "IBAN", .value = "NL23 BUNQ 2025 1234 56", .onTap = [&seen] { seen.push_back("tap"); }, .onLongPress = [&seen] { seen.push_back("held"); }};
|
||||||
|
foretold = ValueRowHeight(frame, frame.bounds.w, iban);
|
||||||
|
heights[0] = ValueRow(frame, {0, 0, frame.bounds.w, 0}, iban);
|
||||||
|
heights[1] = ValueRow(frame, {0, 100, 400, 0}, {.key = "long", .label = "Description", .value = longValue, .onTap = [&seen] { seen.push_back("long"); }});
|
||||||
|
heights[2] = ValueRow(frame, {0, 300, 400, 0}, {.key = "read", .label = longLabel, .value = "Read only"});
|
||||||
|
};
|
||||||
|
Build(ui, scene);
|
||||||
|
const Theme& theme = ui.theme;
|
||||||
|
Check(heights[0] == 48 && foretold == 48 && heights[2] == 48, "on a phone a line is as tall as a finger needs, which can be asked beforehand");
|
||||||
|
Check(Line(ui, "IBAN")->x == 8 && Line(ui, "IBAN")->px == 14 && Line(ui, "IBAN")->color == theme.muted && Line(ui, "NL23 BUNQ 2025 1234 56")->x == 8 + 112, "the label, and beside it the value, clear of the row's sides");
|
||||||
|
Check(Line(ui, "NL23 BUNQ 2025 1234 56")->baseline == 14 + 12.8f && Line(ui, "IBAN")->baseline == 14 + 12.8f, "the value in the middle of the row's height, the label on its line");
|
||||||
|
Check(heights[1] == 3 * 20 + 12 && Line(ui, "A description that is long enough") != nullptr && Line(ui, "it has")->baseline == 100 + 6 + 40 + 12.8f && Line(ui, "Description")->baseline == 100 + 6 + 12.8f, "a value too long for its room wraps, the row grows with it, and the label stays on its first line");
|
||||||
|
Check(Line(ui, Ellipsize(Test::FixedMeasure(), longLabel, FontFace::Regular, 14, 104)) != nullptr && Line(ui, longLabel) == nullptr, "a label too long for its room is cut");
|
||||||
|
Check(ui.Find("iban")->role == Role::Row && ui.Find("iban")->focusable && ui.Find("iban")->box == Box{0, 0, 400, 48} && ui.Find("iban")->label == "IBAN" && ui.Find("read") == nullptr, "a line with something to do is a region; one that is only read is not");
|
||||||
|
Check(ui.Tap("iban") && ui.LongPress("iban") && ui.Tap("long") && seen == std::vector<std::string>{"tap", "held", "long"}, "a tap and a long press act");
|
||||||
|
|
||||||
|
ui.Hover(Point{200, 20});
|
||||||
|
Build(ui, scene);
|
||||||
|
Check(Rects(ui, theme.Hovered(theme.surface)).size() == 1 && Rects(ui, theme.Hovered(theme.surface))[0].box == Box{0, 0, 400, 48}, "under the pointer the whole row is tinted");
|
||||||
|
ui.Hover(Point{200, 320});
|
||||||
|
ui.Pointer(PointerPhase::Down, {200, 120}, 0);
|
||||||
|
Build(ui, scene);
|
||||||
|
Check(Rects(ui, theme.Hovered(theme.surface)).empty() && Rects(ui, theme.Pressed(theme.surface)).size() == 1, "a line that is only read is not; a pressed one is drawn pressed");
|
||||||
|
ui.Pointer(PointerPhase::Cancel, {200, 120}, 10);
|
||||||
|
ui.Focus("long");
|
||||||
|
Build(ui, scene);
|
||||||
|
Check(Ringed(ui, {0, 100, 400, 72}), "the keyboard's focus is a line around the row");
|
||||||
|
|
||||||
|
Build(ui, scene, {0, 0, 1000, 800});
|
||||||
|
Check(heights[0] == 36 && foretold == 36 && ui.Find("iban")->box == Box{0, 0, 1000, 36}, "in a wider window, under a pointer, the lines are closer together");
|
||||||
|
}
|
||||||
|
|
||||||
|
void Choosing() {
|
||||||
|
Context ui(Test::FixedMeasure());
|
||||||
|
std::vector<std::size_t> picked;
|
||||||
|
std::size_t selected = 1;
|
||||||
|
bool enabled = true;
|
||||||
|
const auto scene = [&](Frame& frame) {
|
||||||
|
frame.draw.SetLayer(Layer::Content);
|
||||||
|
Segmented(frame, {10, 10, 300, 40}, {.key = "when", .labels = {"Now", "Scheduled", "Draft"}, .selected = selected, .enabled = enabled, .onSelect = [&](std::size_t i) { picked.push_back(i); }});
|
||||||
|
Segmented(frame, {10, 60, 300, 40}, {.key = "idle", .labels = {"One", "Two"}});
|
||||||
|
Tabs(frame, {0, 200, 400, 48}, {.key = "tabs", .labels = {"Activity", "Requests", "Incoming", "Scheduled", "Drafts"}, .selected = selected, .enabled = enabled, .onSelect = [&](std::size_t i) { picked.push_back(i); }});
|
||||||
|
Tabs(frame, {0, 300, 300, 48}, {.key = "tight", .labels = {"Activity", "Requests", "Incoming", "Scheduled", "Drafts"}, .selected = 0});
|
||||||
|
Segmented(frame, {10, 400, 300, 40}, {.key = "none"});
|
||||||
|
};
|
||||||
|
Build(ui, scene);
|
||||||
|
const Theme& theme = ui.theme;
|
||||||
|
Check(Line(ui, "Scheduled")->face == FontFace::Medium && Line(ui, "Now")->face == FontFace::Regular && Rects(ui, theme.surface).size() == 2, "of a row of segments the one taken stands out");
|
||||||
|
Check(ui.Find("when.0")->box == Box{10, 10, 100, 40} && ui.Find("when.2")->box == Box{210, 10, 100, 40} && ui.Find("when.1")->label == "Scheduled" && ui.Find("none.0") == nullptr, "each segment is an equal part, and a region");
|
||||||
|
Check(ui.Tap("when.2") && ui.Tap("tabs.4") && picked == std::vector<std::size_t>{2, 4} && ui.Tap("idle.1"), "a tap on one says which; one nobody listens to can still be pressed");
|
||||||
|
|
||||||
|
// The tabs: 80 wide each in the wide strip, 60 in the tight one, where "Scheduled" at 14 pixels wants 71.
|
||||||
|
const std::span<const Batch> content = ui.Shown().draw.Batches(Layer::Content);
|
||||||
|
std::vector<float> sizes;
|
||||||
|
for(const Batch& batch : content) {
|
||||||
|
for(const TextItem& item : batch.texts) {
|
||||||
|
if(item.text == "Scheduled" && item.baseline > 200) {
|
||||||
|
sizes.push_back(item.px);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Equal(sizes == std::vector<float>{14, 12}, true, "tabs whose labels do not all fit beside each other are set a size down");
|
||||||
|
Check(Rects(ui, theme.accent).size() == 2 && Rects(ui, theme.accent)[0].box == Box{80 + 8, 245, 64, 3}, "a line under the tab that is shown");
|
||||||
|
|
||||||
|
ui.Hover(Point{50, 30});
|
||||||
|
ui.Pointer(PointerPhase::Down, {40, 220}, 0);
|
||||||
|
Build(ui, scene);
|
||||||
|
Check(Rects(ui, theme.Hovered(theme.surfaceAlt)).size() == 1 && Rects(ui, theme.Pressed(theme.surface)).size() == 1, "a segment under the pointer and a tab that is pressed are drawn so");
|
||||||
|
ui.Pointer(PointerPhase::Cancel, {40, 220}, 10);
|
||||||
|
ui.Hover(Point{160, 30});
|
||||||
|
Build(ui, scene);
|
||||||
|
Check(Rects(ui, theme.Hovered(theme.surfaceAlt)).empty(), "the segment that is taken does not change under the pointer");
|
||||||
|
ui.Focus("when.0");
|
||||||
|
Build(ui, scene);
|
||||||
|
Check(Ringed(ui, {13, 13, 94, 34}), "the focus on a segment");
|
||||||
|
ui.Focus("tabs.2");
|
||||||
|
Build(ui, scene);
|
||||||
|
Check(Ringed(ui, {162, 202, 76, 44}), "and on a tab");
|
||||||
|
|
||||||
|
enabled = false;
|
||||||
|
ui.Hover(Point{50, 30});
|
||||||
|
ui.Pointer(PointerPhase::Down, {40, 220}, 0);
|
||||||
|
Build(ui, scene);
|
||||||
|
Check(Line(ui, "Now")->color == theme.muted && Rects(ui, theme.Hovered(theme.surfaceAlt)).empty() && Rects(ui, theme.Pressed(theme.surface)).empty() && !ui.Tap("when.0"), "disabled, they are muted, feel nothing and take no tap");
|
||||||
|
ui.Pointer(PointerPhase::Cancel, {40, 220}, 10);
|
||||||
|
|
||||||
|
// A dark theme's surface is darker than the ground the segments stand on: the one taken is lighter than both.
|
||||||
|
ui.theme = Theme::Dark();
|
||||||
|
Build(ui, scene);
|
||||||
|
Check(Rects(ui, ui.theme.Taken()).size() == 2 && Rects(ui, ui.theme.surface).empty(), "on a dark theme the segment taken still stands out as the lighter");
|
||||||
|
}
|
||||||
|
|
||||||
|
void Notices() {
|
||||||
|
Context ui(Test::FixedMeasure());
|
||||||
|
std::vector<std::string> seen;
|
||||||
|
std::array<float, 4> heights{};
|
||||||
|
const auto scene = [&](Frame& frame) {
|
||||||
|
frame.draw.SetLayer(Layer::Content);
|
||||||
|
heights[0] = Banner(frame, {10, 0, 380, 0}, {.key = "info", .text = "A connection could not be reached"});
|
||||||
|
heights[1] = Banner(frame, {10, 100, 380, 0}, {.key = "warn", .kind = BannerKind::Warning, .text = "It may have been carried out: check your activity before trying again", .action = "Open activity", .onAction = [&seen] { seen.push_back("action"); }, .onDismiss = [&seen] { seen.push_back("dismiss"); }});
|
||||||
|
heights[2] = Banner(frame, {10, 300, 380, 0}, {.key = "error", .kind = BannerKind::Error, .text = "bunq refused", .onDismiss = [&seen] { seen.push_back("gone"); }});
|
||||||
|
heights[3] = Banner(frame, {10, 400, 380, 0}, {.key = "act", .text = "Nothing is connected yet", .action = "Add a bank"});
|
||||||
|
Chip(frame, {10, 600, ChipWidth(frame, "PENDING"), 20}, "PENDING", ui.theme.surfaceAlt, ui.theme.muted);
|
||||||
|
Divider(frame, {0, 700, 400, 20});
|
||||||
|
Skeleton(frame, {10, 740, 200, 16});
|
||||||
|
Skeleton(frame, {10, 770, 200, 16}, 0.5f);
|
||||||
|
};
|
||||||
|
Build(ui, scene);
|
||||||
|
const Theme& theme = ui.theme;
|
||||||
|
Check(heights[0] == 24 + 17.5f && Rects(ui, theme.surfaceAlt)[0].box == Box{10, 0, 380, 41.5f} && Line(ui, "A connection could not be reached")->color == theme.text, "a notice is as tall as its text and its padding");
|
||||||
|
Check(Rects(ui, theme.warning).size() == 2 && Line(ui, "×") != nullptr && Line(ui, "Open activity")->color == theme.onWarning && heights[1] == 24 + 35 + 40, "a warning in its own colours, wrapped beside the mark that closes it, its action under the text");
|
||||||
|
Check(Rects(ui, theme.danger).size() == 1 && Line(ui, "bunq refused")->color == theme.onDanger && heights[2] == 48, "an error; a notice that can be closed is at least as tall as the mark");
|
||||||
|
Check(ui.Tap("warn.action") && ui.Tap("warn.dismiss") && ui.Tap("error.dismiss") && ui.Tap("act.action") && seen == std::vector<std::string>{"action", "dismiss", "gone"}, "its action and its closing can be pressed");
|
||||||
|
Check(ui.Find("info.dismiss") == nullptr && ui.Find("info.action") == nullptr && ui.Find("warn.dismiss")->label == "Dismiss", "a notice without them has neither");
|
||||||
|
Check(Line(ui, "PENDING")->px == 12 && Rects(ui, theme.surfaceAlt)[3].corners == Corners::All(10) && ChipWidth(ui.Shown(), "PENDING") == 7 * 6 + 16, "a chip is a rounded mark around its text");
|
||||||
|
Check(Rects(ui, theme.divider)[0].box == Box{0, 719, 400, 1}, "a divider is a line along its box's bottom edge");
|
||||||
|
Check(Rects(ui, theme.surfaceAlt)[4].box == Box{10, 740, 200, 16} && Rects(ui, theme.surfaceAlt)[5].box == Box{10, 770, 100, 16}, "a skeleton is a bar, or part of one");
|
||||||
|
|
||||||
|
ui.Focus("warn.action");
|
||||||
|
ui.Hover(Point{50, 170});
|
||||||
|
Build(ui, scene);
|
||||||
|
Check(Ringed(ui, ui.Find("warn.action")->box.Inset(Insets::Symmetric(0, 6))) && ui.Find("warn.action")->box.h == 48 && Rects(ui, theme.Hovered(theme.warning)).size() == 1, "the action takes the focus and feels the pointer, and a press from a little above and below what is drawn: a finger's height");
|
||||||
|
ui.Focus("warn.dismiss");
|
||||||
|
Build(ui, scene);
|
||||||
|
Check(Ringed(ui, ui.Find("warn.dismiss")->box.Inset(Insets::All(6))), "and so does the mark");
|
||||||
|
}
|
||||||
|
|
||||||
|
void Bars() {
|
||||||
|
Context ui(Test::FixedMeasure());
|
||||||
|
std::vector<std::string> seen;
|
||||||
|
bool back = true;
|
||||||
|
Box under;
|
||||||
|
Box above;
|
||||||
|
Box beside;
|
||||||
|
float sideWidth = 240;
|
||||||
|
const std::vector<NavItem> places = {
|
||||||
|
{.key = "nav.accounts", .label = "Accounts", .selected = true, .onTap = [&seen] { seen.push_back("accounts"); }},
|
||||||
|
{.key = "nav.cards", .label = "Cards", .onTap = [&seen] { seen.push_back("cards"); }},
|
||||||
|
{.key = "nav.settings", .label = "Settings", .onTap = [&seen] { seen.push_back("settings"); }},
|
||||||
|
};
|
||||||
|
const std::vector<NavItem> side = {
|
||||||
|
{.key = "side.accounts", .label = "Accounts", .selected = true, .onTap = [&seen] { seen.push_back("side accounts"); }},
|
||||||
|
{.key = "side.head", .label = "Alice at bunq", .header = true},
|
||||||
|
{.key = "side.main", .label = "Main", .detail = "€1,000.00", .onTap = [&seen] { seen.push_back("side main"); }},
|
||||||
|
};
|
||||||
|
const auto scene = [&](Frame& frame) {
|
||||||
|
frame.draw.SetLayer(Layer::Content);
|
||||||
|
under = TopBar(frame, frame.bounds, {.title = "A title that is far too long to fit beside two actions", .onBack = back ? std::function<void()>([&seen] { seen.push_back("back"); }) : nullptr, .actions = {{.key = "bar.refresh", .label = "Refresh", .onTap = [&seen] { seen.push_back("refresh"); }}, {.key = "bar.add", .label = "Add", .enabled = false}}});
|
||||||
|
above = NavBar(frame, under, places);
|
||||||
|
beside = Sidebar(frame, above, sideWidth, side);
|
||||||
|
Check(frame.draw.CurrentLayer() == Layer::Content, "a bar leaves the layer as it found it");
|
||||||
|
};
|
||||||
|
Build(ui, scene);
|
||||||
|
const Theme& theme = ui.theme;
|
||||||
|
Check(under == Box{0, 56, 400, 744} && above == Box{0, 56, 400, 688} && beside == Box{240, 56, 160, 688}, "each bar returns the area it leaves");
|
||||||
|
Check(ui.Find("bar")->role == Role::Panel && ui.Find("bar")->layer == Layer::Chrome && ui.Find("bar.back")->box == Box{4, 0, 48, 56} && Line(ui, "‹") != nullptr, "the top bar, with the way back at its left");
|
||||||
|
Check(ui.Find("bar.add")->box.Right() == 396 && ui.Find("bar.refresh")->box.Right() == ui.Find("bar.add")->box.x - 4 && !ui.Find("bar.add")->enabled, "its actions from the right, in the order they were named");
|
||||||
|
Shows(ui, "…", "and its title in what room is left");
|
||||||
|
Check(ui.Tap("bar.back") && ui.Tap("bar.refresh") && seen == std::vector<std::string>{"back", "refresh"}, "which can be pressed");
|
||||||
|
ui.KeyDown(Key::Escape, {});
|
||||||
|
Equal(seen.back(), std::string("back"), "Escape is the way back");
|
||||||
|
|
||||||
|
Check(ui.Find("nav")->box == Box{0, 744, 400, 56} && ui.Find("nav.cards")->box == Box{400 / 3.0f, 744, 400 / 3.0f, 56}, "the places along the bottom, in equal parts");
|
||||||
|
Check(Line(ui, "Cards")->color == theme.muted && Rects(ui, theme.accent.WithAlpha(0.14f)).size() == 2, "the place the window is at stands out, in each bar");
|
||||||
|
Check(ui.Tap("nav.cards") && seen.back() == "cards", "a place can be pressed");
|
||||||
|
|
||||||
|
Check(ui.Find("side")->box == Box{0, 56, 240, 688} && ui.Find("side.scroll")->role == Role::Scroll && ui.Find("side.head") == nullptr && Line(ui, "Alice at bunq")->px == 12, "the places down the side, a heading among them that is no region");
|
||||||
|
Check(Line(ui, "€1,000.00") != nullptr && Line(ui, "€1,000.00")->align == TextAlign::Right && ui.Tap("side.main") && seen.back() == "side main", "a place with its detail beside it");
|
||||||
|
|
||||||
|
ui.Hover(Point{20, 20});
|
||||||
|
Build(ui, scene);
|
||||||
|
Equal(Rects(ui, theme.Hovered(theme.surface)).size(), std::size_t{1}, "the way back feels the pointer");
|
||||||
|
ui.Hover(Point{200, 770});
|
||||||
|
Build(ui, scene);
|
||||||
|
Equal(Rects(ui, theme.Hovered(theme.surface)).size(), std::size_t{1}, "so does a place along the bottom");
|
||||||
|
ui.Pointer(PointerPhase::Down, {100, 160}, 0);
|
||||||
|
ui.Hover(std::nullopt);
|
||||||
|
Build(ui, scene);
|
||||||
|
Equal(Rects(ui, theme.Pressed(theme.surface)).size(), std::size_t{1}, "and one down the side a press");
|
||||||
|
ui.Pointer(PointerPhase::Cancel, {100, 160}, 10);
|
||||||
|
ui.Focus("bar.back");
|
||||||
|
Build(ui, scene);
|
||||||
|
Check(Ringed(ui, {4, 4, 48, 48}), "the focus on the way back");
|
||||||
|
ui.Focus("nav.cards");
|
||||||
|
Build(ui, scene);
|
||||||
|
Check(Rects(ui, theme.accent.WithAlpha(0)).size() == 1, "on a place along the bottom");
|
||||||
|
ui.Focus("side.main");
|
||||||
|
Build(ui, scene);
|
||||||
|
Check(Rects(ui, theme.accent.WithAlpha(0)).size() == 1, "and on one down the side");
|
||||||
|
|
||||||
|
back = false;
|
||||||
|
sideWidth = 120;
|
||||||
|
Build(ui, scene);
|
||||||
|
Check(ui.Find("bar.back") == nullptr && Line(ui, "‹") == nullptr, "a screen with no way back shows none");
|
||||||
|
Check(Line(ui, "€1,000.00") == nullptr && Line(ui, "Main") != nullptr, "a detail gives way where the side bar is too narrow for both");
|
||||||
|
seen.clear();
|
||||||
|
ui.KeyDown(Key::Escape, {});
|
||||||
|
Check(seen.empty(), "and Escape goes nowhere");
|
||||||
|
|
||||||
|
// The dark theme tints the place the window is at more strongly.
|
||||||
|
ui.theme = Theme::Dark();
|
||||||
|
Build(ui, scene);
|
||||||
|
Equal(Rects(ui, ui.theme.accent.WithAlpha(0.28f)).size(), std::size_t{2}, "on a dark ground it stands out more strongly");
|
||||||
|
}
|
||||||
|
|
||||||
|
void Sheets() {
|
||||||
|
Context ui(Test::FixedMeasure());
|
||||||
|
std::vector<std::string> seen;
|
||||||
|
Box content;
|
||||||
|
std::string title = "Report this card stolen?";
|
||||||
|
bool dismissable = true;
|
||||||
|
float wanted = 200;
|
||||||
|
const auto scene = [&](Frame& frame) {
|
||||||
|
frame.draw.SetLayer(Layer::Content);
|
||||||
|
Button(frame, {10, 10, 100, 48}, {.key = "under", .label = "Under", .onTap = [&seen] { seen.push_back("under"); }});
|
||||||
|
Sheet(frame, {.key = "sheet", .title = title, .contentHeight = wanted, .onDismiss = dismissable ? std::function<void()>([&seen] { seen.push_back("dismissed"); }) : nullptr}, [&](Box box) {
|
||||||
|
content = box;
|
||||||
|
Button(frame, {box.x, box.y, 100, 48}, {.key = "sheet.ok", .label = "Report", .kind = ButtonKind::Danger, .onTap = [&seen] { seen.push_back("ok"); }});
|
||||||
|
});
|
||||||
|
Check(frame.draw.CurrentLayer() == Layer::Content, "a sheet leaves the layer as it found it");
|
||||||
|
};
|
||||||
|
Build(ui, scene);
|
||||||
|
const Theme& theme = ui.theme;
|
||||||
|
Check(ui.Find("sheet.panel")->box == Box{0, 800 - 272, 400, 272} && content == Box{16, 528 + 16 + 40, 368, 200} && ui.Find("sheet.panel")->layer == Layer::Overlay && SheetBodyWidth(ui.Shown()) == 368, "in a narrow window a sheet rises from the bottom edge, as tall as its title and its body");
|
||||||
|
Check(Rects(ui, theme.scrim).size() == 1 && Rects(ui, theme.surface).back().corners == Corners::Top(12), "over a scrim, its top corners rounded");
|
||||||
|
Shows(ui, "Report this card stolen?", "with its title");
|
||||||
|
Check(!ui.Tap("under") && ui.Tap("sheet.ok") && seen.back() == "ok", "what it covers is out of reach; its own button is not");
|
||||||
|
TapAt(ui, {200, 100});
|
||||||
|
ui.KeyDown(Key::Escape, {});
|
||||||
|
Equal(seen == std::vector<std::string>{"ok", "dismissed", "dismissed"}, true, "a tap beside it or Escape dismisses it");
|
||||||
|
|
||||||
|
title.clear();
|
||||||
|
dismissable = false;
|
||||||
|
wanted = 5000;
|
||||||
|
Build(ui, scene, {0, 0, 1000, 700});
|
||||||
|
Check(ui.Find("sheet.panel")->box == Box{260, 24, 480, 652} && content == Box{276, 40, 448, 620} && Rects(ui, theme.surface).back().corners == Corners::All(12), "in a wide window it is a dialog in the middle, no taller than the window leaves room for");
|
||||||
|
Check(SheetBodyWidth(ui.Shown()) == 448, "how wide its body is can be asked beforehand");
|
||||||
|
TapAt(ui, {50, 50});
|
||||||
|
ui.KeyDown(Key::Escape, {});
|
||||||
|
Equal(seen.size(), std::size_t{3}, "one that cannot be dismissed stays");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
Cursors();
|
||||||
|
Words();
|
||||||
|
Buttons();
|
||||||
|
Rows();
|
||||||
|
Values();
|
||||||
|
Choosing();
|
||||||
|
Notices();
|
||||||
|
Bars();
|
||||||
|
Sheets();
|
||||||
|
return Test::Result();
|
||||||
|
}
|
||||||
150
tests/ShouldRecognizeGestures/main.cpp
Normal file
150
tests/ShouldRecognizeGestures/main.cpp
Normal file
|
|
@ -0,0 +1,150 @@
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
// What a pointer did, from its phases and their times: taps, long presses, drags and flings; a list's scrolling and
|
||||||
|
// what keeps a field in view; the compositor's event times on the host's clock; and the frames owed to the font atlas.
|
||||||
|
|
||||||
|
import std;
|
||||||
|
import Nostro.Ui;
|
||||||
|
|
||||||
|
#include "../Support/Check.inc"
|
||||||
|
|
||||||
|
using namespace Nostro::Ui;
|
||||||
|
using Test::Check;
|
||||||
|
using Test::Equal;
|
||||||
|
using Kind = GestureEvent::Kind;
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
void Gestures() {
|
||||||
|
GestureDetector g;
|
||||||
|
Check(!g.Pressed() && !g.LongPressDue(), "nothing is pressed at first");
|
||||||
|
Check(g.Feed(PointerPhase::Move, {5, 5}, 0).kind == Kind::None && g.Feed(PointerPhase::Up, {5, 5}, 1).kind == Kind::None, "a move or a release without a press is nothing");
|
||||||
|
g.Feed(PointerPhase::Down, {10, 10}, 0);
|
||||||
|
Check(g.Pressed() && g.LongPressDue() == std::optional<std::int64_t>(500), "a press waits for its long-press time");
|
||||||
|
Check(g.Feed(PointerPhase::Move, {13, 12}, 50).kind == Kind::None, "movement within the slop is not a drag");
|
||||||
|
const GestureEvent tap = g.Feed(PointerPhase::Up, {13, 12}, 120);
|
||||||
|
Check(tap.kind == Kind::Tap && tap.at == Point{10, 10} && !g.Pressed(), "a short press is a tap at the press position");
|
||||||
|
|
||||||
|
g.Feed(PointerPhase::Down, {10, 10}, 1000);
|
||||||
|
Check(g.Timeout(1400).kind == Kind::None, "the timer before the long-press time decides nothing");
|
||||||
|
const GestureEvent held = g.Timeout(1500);
|
||||||
|
Check(held.kind == Kind::LongPress && held.at == Point{10, 10} && !g.LongPressDue(), "the timer at the long-press time is a long press");
|
||||||
|
Check(g.Feed(PointerPhase::Move, {40, 40}, 1600).kind == Kind::None, "movement after a long press is not a drag");
|
||||||
|
Check(g.Feed(PointerPhase::Up, {40, 40}, 1700).kind == Kind::Release, "the release after a long press is a plain release");
|
||||||
|
|
||||||
|
g.Feed(PointerPhase::Down, {100, 100}, 2000);
|
||||||
|
const GestureEvent start = g.Feed(PointerPhase::Move, {100, 120}, 2016);
|
||||||
|
Check(start.kind == Kind::DragStart && start.at == Point{100, 100} && start.delta == Point{0, 20}, "movement past the slop starts a drag with the whole movement as its delta");
|
||||||
|
const GestureEvent drag = g.Feed(PointerPhase::Move, {100, 150}, 2032);
|
||||||
|
Check(drag.kind == Kind::Drag && drag.delta == Point{0, 30} && drag.at == Point{100, 150}, "a drag reports the movement since the event before");
|
||||||
|
Check(g.Dragging() && !g.LongPressDue(), "dragging, and no long press to wait for");
|
||||||
|
const GestureEvent fling = g.Feed(PointerPhase::Up, {100, 200}, 2048);
|
||||||
|
Check(fling.kind == Kind::Fling && fling.velocity.y > 1000 && fling.velocity.x == 0 && fling.at == Point{100, 200}, "a fast release is a fling with a velocity in pixels per second");
|
||||||
|
Check(g.Timeout(2500).kind == Kind::None && !g.Dragging(), "the timer after a drag decides nothing");
|
||||||
|
|
||||||
|
g.Feed(PointerPhase::Down, {100, 100}, 3000);
|
||||||
|
g.Feed(PointerPhase::Move, {100, 150}, 3016);
|
||||||
|
g.Feed(PointerPhase::Move, {100, 200}, 3032);
|
||||||
|
Check(g.Feed(PointerPhase::Up, {100, 200}, 3500).kind == Kind::Release, "a release after the finger was held still is not a fling, however fast it moved before");
|
||||||
|
g.Feed(PointerPhase::Down, {0, 0}, 3000);
|
||||||
|
g.Feed(PointerPhase::Move, {0, 30}, 3100);
|
||||||
|
g.Feed(PointerPhase::Move, {0, 31}, 3900);
|
||||||
|
Check(g.Feed(PointerPhase::Up, {0, 31}, 4000).kind == Kind::Release, "a slow release after a drag is a release, not a fling");
|
||||||
|
g.Feed(PointerPhase::Down, {0, 0}, 4500);
|
||||||
|
g.Feed(PointerPhase::Move, {30, 0}, 4500);
|
||||||
|
Check(g.Feed(PointerPhase::Up, {30, 0}, 4500).kind == Kind::Release, "a drag and its release in one instant have no speed to fling with");
|
||||||
|
|
||||||
|
g.Feed(PointerPhase::Down, {0, 0}, 5000);
|
||||||
|
g.Feed(PointerPhase::Cancel, {0, 0}, 5010);
|
||||||
|
Check(!g.Pressed() && g.Feed(PointerPhase::Up, {0, 0}, 5020).kind == Kind::None, "a cancel forgets the press");
|
||||||
|
g.Feed(PointerPhase::Down, {5, 5}, 6000);
|
||||||
|
const GestureEvent late = g.Feed(PointerPhase::Up, {5, 5}, 6600);
|
||||||
|
Check(late.kind == Kind::LongPress && late.at == Point{5, 5}, "a release past the long-press time with no timer fired, the press and its release dispatched together behind a stall, is the long press");
|
||||||
|
g.Feed(PointerPhase::Down, {5, 5}, 7000);
|
||||||
|
const GestureEvent stalled = g.Feed(PointerPhase::Move, {40, 40}, 7600);
|
||||||
|
Check(stalled.kind == Kind::LongPress && stalled.at == Point{5, 5}, "a move past the long-press time with no timer fired is the long press first: the finger was held that long before it moved");
|
||||||
|
Check(g.Feed(PointerPhase::Up, {40, 40}, 7700).kind == Kind::Release, "and its release a plain release, no drag");
|
||||||
|
|
||||||
|
// A press on what has no long press, the host's word before the Down: held as long, it is still a tap.
|
||||||
|
g.longPress = false;
|
||||||
|
g.Feed(PointerPhase::Down, {5, 5}, 8000);
|
||||||
|
Check(!g.LongPressDue() && g.Timeout(8600).kind == Kind::None, "without a long press the timer past the time gives nothing");
|
||||||
|
Check(g.Feed(PointerPhase::Move, {6, 5}, 8700).kind == Kind::None, "nor does a move within the slop");
|
||||||
|
const GestureEvent slow = g.Feed(PointerPhase::Up, {6, 5}, 9500);
|
||||||
|
Check(slow.kind == Kind::Tap && slow.at == Point{5, 5}, "and the release is the tap, however late");
|
||||||
|
g.Feed(PointerPhase::Down, {5, 5}, 10000);
|
||||||
|
Check(g.Feed(PointerPhase::Move, {5, 40}, 10800).kind == Kind::DragStart, "a finger that slides off past the time drags, as one that slides off before it");
|
||||||
|
Check(g.Feed(PointerPhase::Up, {5, 40}, 11500).kind == Kind::Release, "and its release taps nothing");
|
||||||
|
g.longPress = true;
|
||||||
|
g.Feed(PointerPhase::Down, {5, 5}, 12000);
|
||||||
|
Check(g.Timeout(12500).kind == Kind::LongPress, "a press the host gives a long press has it as before");
|
||||||
|
g.Feed(PointerPhase::Up, {5, 5}, 12600);
|
||||||
|
}
|
||||||
|
|
||||||
|
void Scrolling() {
|
||||||
|
ScrollState s;
|
||||||
|
s.content = 1000;
|
||||||
|
s.viewport = 400;
|
||||||
|
s.ScrollBy(100);
|
||||||
|
Check(s.offset == 100 && s.Max() == 600, "scroll by, and the furthest it goes");
|
||||||
|
s.ScrollBy(5000);
|
||||||
|
Equal(s.offset, 600.0f, "the offset stops at the end");
|
||||||
|
s.ScrollBy(-5000);
|
||||||
|
Equal(s.offset, 0.0f, "and at the start");
|
||||||
|
s.Fling(1000);
|
||||||
|
Check(s.Tick(0.1f) && s.offset > 0 && s.velocity < 1000, "a fling moves the content and slows down");
|
||||||
|
while(s.Tick(0.1f)) {
|
||||||
|
}
|
||||||
|
Check(s.velocity == 0 && s.offset > 0 && s.offset <= 600, "a fling comes to rest within the extent");
|
||||||
|
s.offset = 0;
|
||||||
|
s.Fling(-500);
|
||||||
|
Check(!s.Tick(0.1f) && s.offset == 0, "a fling against the edge stops at once");
|
||||||
|
s.Fling(10);
|
||||||
|
Check(!s.Tick(0.1f) && s.velocity == 0, "one too slow to see is none");
|
||||||
|
s.content = 300;
|
||||||
|
s.offset = 250;
|
||||||
|
s.Clamp();
|
||||||
|
Equal(s.offset, 0.0f, "content shorter than the viewport does not scroll");
|
||||||
|
|
||||||
|
// A field that got the focus, in a form of 1000 pixels shown 400 at a time.
|
||||||
|
s.content = 1000;
|
||||||
|
s.offset = 0;
|
||||||
|
Check(!s.EnsureVisible(100, 148, 16) && s.offset == 0, "what is in view stays where it is");
|
||||||
|
Check(s.EnsureVisible(500, 548, 16) && s.offset == 164, "what is below comes up to the bottom edge, the margin clear of it");
|
||||||
|
s.Fling(900);
|
||||||
|
Check(s.EnsureVisible(100, 148, 16) && s.offset == 84 && s.velocity == 0, "what is above comes down to the top edge, and a fling under it stops");
|
||||||
|
Check(s.EnsureVisible(980, 1000, 16) && s.offset == 600, "the margin gives way at the content's end");
|
||||||
|
Check(s.EnsureVisible(200, 900, 16) && s.offset == 184, "what is taller than the room shows its top");
|
||||||
|
}
|
||||||
|
|
||||||
|
void Clock() {
|
||||||
|
EventClock clock;
|
||||||
|
Equal(clock.At(0, 5000), std::int64_t{5000}, "an event without a time happened now");
|
||||||
|
Equal(clock.At(1000, 5000), std::int64_t{5000}, "the first stamped event too");
|
||||||
|
Equal(clock.At(1016, 5040), std::int64_t{5016}, "the next one when its stamp says, not when it was dispatched: it waited 24 ms");
|
||||||
|
Equal(clock.At(1100, 5095), std::int64_t{5095}, "one dispatched sooner than any before shows the clocks are nearer: the difference is the smallest seen");
|
||||||
|
Equal(clock.At(1200, 5300), std::int64_t{5195}, "and the later ones go by it");
|
||||||
|
EventClock wrapping;
|
||||||
|
wrapping.At(0xFFFFFFF0u, 100);
|
||||||
|
Equal(wrapping.At(0x10u, 132), std::int64_t{132}, "a stamp that wrapped at 2^32 is 32 ms on, not 4 billion back");
|
||||||
|
Equal(wrapping.At(0x8u, 140), std::int64_t{124}, "and one before it is before it");
|
||||||
|
}
|
||||||
|
|
||||||
|
void AtlasFrames() {
|
||||||
|
FrameWait wait{.patience = 4};
|
||||||
|
Check(!wait.Again(0), "no glyph waits: no frame owed");
|
||||||
|
Check(wait.Again(5) && wait.Again(5) && wait.Again(5) && wait.Again(5), "glyphs waiting: a frame is owed at the first sighting and at three gainless ones after it");
|
||||||
|
Check(!wait.Again(5), "the fourth gainless frame ends it: the screen needs more cells than the atlas holds");
|
||||||
|
wait.Reset();
|
||||||
|
Check(wait.Again(5) && wait.Again(3) && wait.Again(3) && wait.Again(1) && !wait.Again(0), "a gain starts the count over; none waiting ends it");
|
||||||
|
Check(wait.Again(2) && wait.Again(7) && wait.Again(7) && wait.Again(7) && wait.Again(7) && !wait.Again(7), "a changed count, as a screen change makes, starts the count over");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
Gestures();
|
||||||
|
Scrolling();
|
||||||
|
Clock();
|
||||||
|
AtlasFrames();
|
||||||
|
return Test::Result();
|
||||||
|
}
|
||||||
|
|
@ -153,9 +153,11 @@ namespace {
|
||||||
}
|
}
|
||||||
|
|
||||||
void Connecting(Fake::Bunq& bunq) {
|
void Connecting(Fake::Bunq& bunq) {
|
||||||
// The key comes from the prompt, here stdin, never from the command line.
|
// The key comes from the prompt, here stdin, never from the command line. It says itself which environment
|
||||||
Works({"connectors", "add", "bunq", "--sandbox"}, "added Ann (sandbox, 2 accounts)", "key-ann\n");
|
// it is of, by how it starts: there is no flag for that, and the one OAuth has is refused before a key is read.
|
||||||
|
Works({"connectors", "add", "bunq"}, "added Ann (sandbox, 2 accounts)", "sandbox_key-ann\n");
|
||||||
Works({"connectors", "add", "bunq", "*"}, "added Bob (production, 1 accounts)", "key-bob\n");
|
Works({"connectors", "add", "bunq", "*"}, "added Bob (production, 1 accounts)", "key-bob\n");
|
||||||
|
Fails({"connectors", "add", "bunq", "--sandbox"}, "--sandbox goes with bunq-oauth: an API key is a sandbox key when it starts with sandbox_");
|
||||||
Fails({"connectors", "add", "bunq"}, "nothing given for 'bunq API key: '");
|
Fails({"connectors", "add", "bunq"}, "nothing given for 'bunq API key: '");
|
||||||
Fails({"connectors", "add"}, "connector type not provided");
|
Fails({"connectors", "add"}, "connector type not provided");
|
||||||
Fails({"connectors", "add", "unknown"}, "unknown connector type 'unknown'");
|
Fails({"connectors", "add", "unknown"}, "unknown connector type 'unknown'");
|
||||||
|
|
@ -246,8 +248,17 @@ namespace {
|
||||||
std::lock_guard lock(bunq.mutex);
|
std::lock_guard lock(bunq.mutex);
|
||||||
bunq.cardsActivate = false;
|
bunq.cardsActivate = false;
|
||||||
}
|
}
|
||||||
Fails({"cards", "unfreeze", card}, std::format("bunq kept card {} DEACTIVATED (its order status is VIRTUAL_DELIVERY)", card));
|
Fails({"cards", "unfreeze", card}, std::format("bunq kept card {} DEACTIVATED (its order status is DELIVERED_TO_CUSTOMER)", card));
|
||||||
Works({"cards", "lost", card}, std::format("card {} is now LOST", card));
|
Works({"cards", "lost", card}, std::format("card {} is now LOST", card));
|
||||||
|
// A virtual card is listed as one, since bunq has it as DEACTIVATED however well it pays. It is not frozen or
|
||||||
|
// unfrozen: bunq would leave it as it is and answer as if it had been done.
|
||||||
|
const std::string number = std::to_string(bunq.AddCard(ann, "DEACTIVATED", json{{"order_status", "VIRTUAL_DELIVERY"}}));
|
||||||
|
Works({"cards"}, std::format("\t{}\tVIRTUAL\tMASTERCARD_DEBIT", number));
|
||||||
|
const std::size_t asked = bunq.Count("PUT", "/user/");
|
||||||
|
Fails({"cards", "freeze", number}, std::format("card {} is a virtual card, which bunq does not freeze or unfreeze when asked", number));
|
||||||
|
Fails({"cards", "unfreeze", number}, "do that in the bunq app");
|
||||||
|
Equal(bunq.Count("PUT", "/user/"), asked, "bunq is not asked to freeze a virtual card");
|
||||||
|
Works({"cards", "stolen", number}, std::format("card {} is now STOLEN", number));
|
||||||
Fails({"cards", "melt", card}, "unknown card action 'melt'");
|
Fails({"cards", "melt", card}, "unknown card action 'melt'");
|
||||||
Fails({"cards", "freeze", "1"}, "no card has id 1");
|
Fails({"cards", "freeze", "1"}, "no card has id 1");
|
||||||
Fails({"cards", "freeze"}, "card id not provided");
|
Fails({"cards", "freeze"}, "card id not provided");
|
||||||
|
|
@ -265,7 +276,7 @@ namespace {
|
||||||
void Removing(Fake::Bunq& bunq) {
|
void Removing(Fake::Bunq& bunq) {
|
||||||
bunq.AddAccount(bunq.AddPerson("Ann", "key-ann2"), "NL84BUNQ2025333333", "Other", 0);
|
bunq.AddAccount(bunq.AddPerson("Ann", "key-ann2"), "NL84BUNQ2025333333", "Other", 0);
|
||||||
Works({"connectors", "add", "bunq"}, "added Ann (production", "key-ann2\n");
|
Works({"connectors", "add", "bunq"}, "added Ann (production", "key-ann2\n");
|
||||||
Fails({"connectors", "remove", "Ann"}, "2 connectors are called 'Ann': use the number");
|
Fails({"connectors", "remove", "Ann"}, "2 connectors are called 'Ann': use its number");
|
||||||
Fails({"connectors", "remove", "Nobody"}, "no connector is called or numbered 'Nobody'");
|
Fails({"connectors", "remove", "Nobody"}, "no connector is called or numbered 'Nobody'");
|
||||||
Works({"connectors", "remove", "4"}, "removed Ann");
|
Works({"connectors", "remove", "4"}, "removed Ann");
|
||||||
|
|
||||||
|
|
@ -309,7 +320,7 @@ int main(int argc, char* argv[]) {
|
||||||
}
|
}
|
||||||
|
|
||||||
Fake::Bunq bunq(port);
|
Fake::Bunq bunq(port);
|
||||||
const std::uint64_t ann = bunq.AddPerson("Ann", "key-ann");
|
const std::uint64_t ann = bunq.AddPerson("Ann", "sandbox_key-ann");
|
||||||
const std::uint64_t annMain = bunq.AddAccount(ann, annIban, "Main", 100000);
|
const std::uint64_t annMain = bunq.AddAccount(ann, annIban, "Main", 100000);
|
||||||
bunq.AddAccount(ann, savingsIban, "Savings", 100);
|
bunq.AddAccount(ann, savingsIban, "Savings", 100);
|
||||||
bunq.AddAccount(bunq.AddPerson("Bob", "key-bob"), bobIban, "Main", 0);
|
bunq.AddAccount(bunq.AddPerson("Bob", "key-bob"), bobIban, "Main", 0);
|
||||||
|
|
|
||||||
|
|
@ -250,7 +250,17 @@ namespace {
|
||||||
|
|
||||||
Client bob = As(bus, bobUid);
|
Client bob = As(bus, bobUid);
|
||||||
Check(bob.Connectors().empty(), "another user sees none of them");
|
Check(bob.Connectors().empty(), "another user sees none of them");
|
||||||
Equal(bob.AddBunq("key-bob", "", "sandbox").environment, std::string("sandbox"), "an environment named by the caller");
|
// An API key says itself which environment it is of. One the caller names is held to that, before anyone is
|
||||||
|
// asked and before the key goes anywhere: a real key is not shown to the sandbox.
|
||||||
|
const auto prompted = [&bus] {
|
||||||
|
std::lock_guard lock(bus.mutex);
|
||||||
|
return bus.checks.size();
|
||||||
|
};
|
||||||
|
const std::size_t prompts = prompted();
|
||||||
|
Throws<std::invalid_argument>([&bob] { bob.AddBunq("key-bob", "", "sandbox"); }, "that API key is a production key, not a sandbox one", "a key that is not a sandbox key is not sent to the sandbox");
|
||||||
|
Throws<std::invalid_argument>([&bob] { bob.AddBunq("sandbox_key-bob", "", "production"); }, "that API key is a sandbox key, not a production one", "nor a sandbox key taken for a real one");
|
||||||
|
Check(prompted() == prompts && bob.Connectors().empty(), "nobody is asked for a password for either, and nothing is connected");
|
||||||
|
Equal(bob.AddBunq("key-bob", "", "production").environment, std::string("production"), "an environment named by the caller, which the key is of");
|
||||||
Equal(alice.Connectors().size(), std::size_t{1}, "each user sees their own connectors");
|
Equal(alice.Connectors().size(), std::size_t{1}, "each user sees their own connectors");
|
||||||
Equal(bob.Connectors().at(0).name, std::string("Bob"), "and only those");
|
Equal(bob.Connectors().at(0).name, std::string("Bob"), "and only those");
|
||||||
Equal(Slurp(state / "users" / std::to_string(aliceUid) / "owner"), std::string("alice\n"), "a user's directory says whose it is");
|
Equal(Slurp(state / "users" / std::to_string(aliceUid) / "owner"), std::string("alice\n"), "a user's directory says whose it is");
|
||||||
|
|
@ -279,8 +289,16 @@ namespace {
|
||||||
|
|
||||||
alice.Accounts();
|
alice.Accounts();
|
||||||
Check(bus.LastCheck().action == "net.catcrafts.Nostro1.View" && Summary(bus) == "see your accounts and balances", "listing is the View action");
|
Check(bus.LastCheck().action == "net.catcrafts.Nostro1.View" && Summary(bus) == "see your accounts and balances", "listing is the View action");
|
||||||
alice.Transactions(aliceMain, {});
|
const std::size_t listed = alice.Transactions(aliceMain, {}).size();
|
||||||
Equal(Summary(bus), std::string("see your transactions"), "so are the transactions");
|
Equal(Summary(bus), std::string("see your transactions"), "so are the transactions");
|
||||||
|
// From what nostrod has stored alone: the bank is not asked, so what it has had since is not among it.
|
||||||
|
bunq.AddPayment(bank.aliceMainId, 4200, "Carol", "NL65BUNQ2025222222", "since the last look");
|
||||||
|
const std::size_t calls = bunq.Count("GET", "/user/");
|
||||||
|
Equal(alice.Transactions(aliceMain, {.stored = true}).size(), listed, "a question about what is stored is answered from it");
|
||||||
|
Check(bunq.Count("GET", "/user/") == calls && Summary(bus) == "see your transactions", "without a call to the bank, and after the same check");
|
||||||
|
Equal(alice.Transactions(aliceMain, {.search = "since the last look", .stored = true}).size(), std::size_t{0}, "so a payment the bank has had since is not found there");
|
||||||
|
Check(alice.Transactions(aliceMain, {.search = "since the last look"}).size() == 1 && bunq.Count("GET", "/user/") == calls + 1, "any other question asks the bank first, and finds it");
|
||||||
|
Equal(alice.Transactions(aliceMain, {.search = "since the last look", .stored = true}).size(), std::size_t{1}, "after which it is stored");
|
||||||
|
|
||||||
alice.Request(aliceMain, bobIban, "Bob", 500, "back");
|
alice.Request(aliceMain, bobIban, "Bob", 500, "back");
|
||||||
Check(bus.LastCheck().action == "net.catcrafts.Nostro1.Change" && Summary(bus) == std::format("ask {} (Bob) for €5.00 into {} (Main)", bobIban, aliceMain), "asking for money is a Change");
|
Check(bus.LastCheck().action == "net.catcrafts.Nostro1.Change" && Summary(bus) == std::format("ask {} (Bob) for €5.00 into {} (Main)", bobIban, aliceMain), "asking for money is a Change");
|
||||||
|
|
@ -337,6 +355,22 @@ namespace {
|
||||||
Check(bus.LastCheck().action == "net.catcrafts.Nostro1.UnfreezeCard" && Summary(bus) == "unfreeze card **** 1234", "unfreezing one has an action of its own");
|
Check(bus.LastCheck().action == "net.catcrafts.Nostro1.UnfreezeCard" && Summary(bus) == "unfreeze card **** 1234", "unfreezing one has an action of its own");
|
||||||
alice.SetCardStatus(card, "STOLEN");
|
alice.SetCardStatus(card, "STOLEN");
|
||||||
Check(bus.LastCheck().action == "net.catcrafts.Nostro1.BlockCard" && Summary(bus) == "report card **** 1234 stolen, which blocks it for good", "and so does blocking one for good");
|
Check(bus.LastCheck().action == "net.catcrafts.Nostro1.BlockCard" && Summary(bus) == "report card **** 1234 stolen, which blocks it for good", "and so does blocking one for good");
|
||||||
|
|
||||||
|
// A virtual card is not frozen or unfrozen: bunq would leave it as it is and answer as if it had been done. It
|
||||||
|
// is refused before anyone is asked for a password, and bunq is not asked at all.
|
||||||
|
const std::uint64_t number = bunq.AddCard(bank.alice, "DEACTIVATED", json{{"order_status", "VIRTUAL_DELIVERY"}, {"primary_account_numbers", json::array({json{{"four_digit", "4321"}}})}});
|
||||||
|
const auto prompted = [&bus] {
|
||||||
|
std::lock_guard lock(bus.mutex);
|
||||||
|
return bus.checks.size();
|
||||||
|
};
|
||||||
|
const std::size_t prompts = prompted();
|
||||||
|
const std::size_t changes = bunq.Count("PUT", "/user/");
|
||||||
|
for(const std::string_view status : {"DEACTIVATED", "ACTIVE"}) {
|
||||||
|
Throws<std::invalid_argument>([&alice, number, status] { alice.SetCardStatus(number, status); }, std::format("card {} is a virtual card, which bunq does not freeze or unfreeze when asked", number), "a virtual card is not frozen or unfrozen");
|
||||||
|
}
|
||||||
|
Check(prompted() == prompts && bunq.Count("PUT", "/user/") == changes, "nobody is asked for a password for it, and bunq is not asked");
|
||||||
|
Equal(alice.SetCardStatus(number, "LOST").status, std::string("LOST"), "it is reported lost like any card");
|
||||||
|
Check(bus.LastCheck().action == "net.catcrafts.Nostro1.BlockCard" && Summary(bus) == "report card **** 4321 lost, which blocks it for good", "which blocks it for good, after the password for that");
|
||||||
}
|
}
|
||||||
|
|
||||||
void Outcomes(Fake::Bus& bus) {
|
void Outcomes(Fake::Bus& bus) {
|
||||||
|
|
|
||||||
|
|
@ -283,6 +283,29 @@ namespace {
|
||||||
Equal(std::format("{}", cards.at(0)), std::format("{}\tACTIVE\tMASTERCARD_DEBIT\t**** 1234\tJ. Tester\tNostro\tNL01BUNQ0000000001\texpires 2030-11-30", active), "a card formats as one line");
|
Equal(std::format("{}", cards.at(0)), std::format("{}\tACTIVE\tMASTERCARD_DEBIT\t**** 1234\tJ. Tester\tNostro\tNL01BUNQ0000000001\texpires 2030-11-30", active), "a card formats as one line");
|
||||||
|
|
||||||
Equal(connector.SetCardStatus(active, "DEACTIVATED").status, std::string("DEACTIVATED"), "freezing a card");
|
Equal(connector.SetCardStatus(active, "DEACTIVATED").status, std::string("DEACTIVATED"), "freezing a card");
|
||||||
|
Check(!cards.at(0).Virtual() && cards.at(0).State() == "ACTIVE" && cards.at(1).State() == "DEACTIVATED", "plastic stands as bunq says it does");
|
||||||
|
cards.at(0).ExpectStatus("ACTIVE");
|
||||||
|
Throws([&cards] { cards.at(0).ExpectStatus("DEACTIVATED"); }, "a card can only be frozen or unfrozen once it has been activated", "a card bunq kept as it was");
|
||||||
|
|
||||||
|
// A virtual card: bunq has it as DEACTIVATED however well it pays, and leaves it so when it is asked to freeze
|
||||||
|
// or to unfreeze it, without an error. That status says nothing of it, and having it after a freeze does not
|
||||||
|
// show the card was frozen.
|
||||||
|
const std::uint64_t number = bunq.AddCard(connector.id, "DEACTIVATED", json{{"order_status", "VIRTUAL_DELIVERY"}});
|
||||||
|
const std::vector<BunqCard> listed = connector.Cards();
|
||||||
|
const BunqCard& virtualCard = *std::ranges::find(listed, number, &BunqCard::id);
|
||||||
|
Check(virtualCard.Virtual() && virtualCard.status == "DEACTIVATED" && virtualCard.State() == "VIRTUAL", "a virtual card is said to be one, whatever bunq's status for it");
|
||||||
|
Check(std::format("{}", virtualCard).starts_with(std::format("{}\tVIRTUAL\tMASTERCARD_DEBIT", number)), "and listed as one");
|
||||||
|
for(const std::string_view asked : {"DEACTIVATED", "ACTIVE"}) {
|
||||||
|
const BunqCard kept = connector.SetCardStatus(number, asked);
|
||||||
|
Check(kept.status == "DEACTIVATED" && kept.State() == "VIRTUAL", "bunq leaves it as it is when asked to freeze or unfreeze it");
|
||||||
|
Throws([&kept, asked] { kept.ExpectStatus(asked); }, "it is a virtual card, which bunq does not freeze or unfreeze", "which is not taken for having been done");
|
||||||
|
}
|
||||||
|
const BunqCard gone = connector.SetCardStatus(number, "LOST");
|
||||||
|
Check(gone.Virtual() && gone.status == "LOST" && gone.State() == "LOST", "reported lost it is gone for good, as bunq then says");
|
||||||
|
gone.ExpectStatus("LOST");
|
||||||
|
const BunqCard paying{.id = 1, .kind = "CardDebit", .productType = "MASTERCARD_DEBIT", .status = "ACTIVE", .orderStatus = "VIRTUAL_DELIVERY", .nameOnCard = "", .secondLine = "", .lastFour = "", .expiry = "", .iban = ""};
|
||||||
|
Check(paying.State() == "VIRTUAL", "and should bunq ever call one active, that is not taken for more than it is");
|
||||||
|
Throws([&paying] { paying.ExpectStatus("ACTIVE"); }, "it is a virtual card", "nor for an unfreezing that worked");
|
||||||
{
|
{
|
||||||
std::lock_guard lock(bunq.mutex);
|
std::lock_guard lock(bunq.mutex);
|
||||||
bunq.cardsActivate = false;
|
bunq.cardsActivate = false;
|
||||||
|
|
|
||||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue