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:
Jorijn van der Graaf 2026-11-19 12:27:14 +01:00
commit 5b4037955b
106 changed files with 17804 additions and 289 deletions

View file

@ -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)));
});
// 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.Flush();
}

View file

@ -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 {
schedule.Check();

View file

@ -27,7 +27,7 @@ std::deque<BunqConnector> BunqConnector::connectors;
namespace {
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.
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));
}
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) {
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");
}
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 {
return std::format("{}/{}/{}", connectorId, environment == BunqEnvironment::Production ? "production" : "sandbox", id);
}

View file

@ -515,6 +515,9 @@ void Bus::AppendQuery(sd_bus_message* message, const TransactionQuery& query) {
entry("to", "x", query.to);
}
entry("limit", "t", static_cast<std::uint64_t>(query.limit));
if(query.stored) {
entry("stored", "b", true);
}
Close(message);
}
@ -544,6 +547,10 @@ TransactionQuery Bus::ReadQuery(sd_bus_message* message) {
Enter(message, 'v', "t");
query.limit = Bus::Read<std::uint64_t>(message);
Leave(message);
} else if(key == "stored") {
Enter(message, 'v', "b");
query.stored = Bus::Read<bool>(message);
Leave(message);
} else {
ThrowOnSdBus(sd_bus_message_skip(message, "v"), "skip an unknown query key");
}

View file

@ -13,6 +13,7 @@ import :Account;
import :Bunq;
import :Currency;
import :Transaction;
import :Utils;
using namespace Nostro;
using namespace Nostro::Bus;
@ -32,46 +33,149 @@ Client Client::System(std::chrono::seconds timeout) {
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 {
// 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) {
const std::string name = ErrorName(error);
const std::string message = ErrorMessage(error);
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) {
throw std::invalid_argument(message);
}
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);
}
// Calls `member` with what `append` appends, reads the answer with `read`, and keeps the notes that end it.
// `changes` says whether the call moves money or changes anything, for what a lost answer means.
template<typename AppendArguments, typename ReadAnswer>
auto Call(sd_bus* bus, std::vector<std::string>& notes, std::string_view member, bool changes, AppendArguments&& append, ReadAnswer&& read) {
std::exception_ptr ErrorOf(const sd_bus_error& error, bool changes) {
try {
Throw(error, changes);
} catch(...) {
return std::current_exception();
}
}
MessagePtr NewCall(sd_bus* bus, std::string_view member) {
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");
const MessagePtr call(raw);
MessagePtr call(raw);
if(IsSensitive(member)) {
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;
sd_bus_message* answer = nullptr;
if(sd_bus_call(bus, raw, 0, &error.error, &answer) < 0) {
Throw(error.error, changes);
if(sd_bus_call(bus, message.get(), 0, &error.error, &answer) < 0) {
Throw(error.error, call.changes);
}
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);
notes.insert(notes.end(), more.begin(), more.end());
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*) {
}
@ -95,6 +199,34 @@ namespace {
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.
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) {
@ -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) {
return [account](sd_bus_message* call) {
Append(call, std::string(account));
@ -119,126 +258,247 @@ namespace {
};
}
template<typename T>
T ReadAs(sd_bus_message* reply) {
return Read<T>(reply);
auto ResponseArguments(std::string_view account, std::uint64_t id, bool accept) {
return [account, id, accept](sd_bus_message* call) {
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() {
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) {
return Call(bus.get(), notes, "AddBunq", true, [=](sd_bus_message* call) {
Append(call, std::string(apiKey));
Append(call, std::string(allowedIps));
Append(call, std::string(environment));
}, ReadAdded);
return Run(bus.get(), notes, addBunqCall, BunqKeyArguments(apiKey, allowedIps, environment));
}
Client::Pending Client::AddBunq(std::string_view apiKey, std::string_view allowedIps, std::string_view environment, Then<AddedConnector> then) {
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) {
return Call(bus.get(), notes, "AddBunqOAuth", true, [=](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));
}, ReadAdded);
return Run(bus.get(), notes, addBunqOAuthCall, OAuthArguments(environment, clientId, clientSecret, redirectUri, code));
}
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) {
return Pending(Start(bus.get(), addBunqOAuthCall, OAuthArguments(environment, clientId, clientSecret, redirectUri, code), std::move(then)));
}
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() {
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) {
return Call(bus.get(), notes, "Transactions", false, [account, &query](sd_bus_message* call) {
Append(call, std::string(account));
AppendQuery(call, query);
}, ReadAs<std::vector<Transaction>>);
return Run(bus.get(), notes, transactionsCall, TransactionArguments(account, query));
}
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) {
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) {
const auto payment = PaymentArguments(account, to, name, amount, description);
return Call(bus.get(), notes, "Schedule", true, [&payment, &schedule](sd_bus_message* call) {
payment(call);
Append(call, schedule);
}, ReadCreated);
return Run(bus.get(), notes, scheduleCall, ScheduleArguments(account, to, name, amount, description, 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) {
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) {
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) {
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) {
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) {
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) {
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) {
Call(bus.get(), notes, "RespondToRequest", true, [account, id, accept](sd_bus_message* call) {
Append(call, std::string(account));
Append(call, id);
Append(call, accept);
}, NoAnswer);
Run(bus.get(), notes, respondToRequestCall, ResponseArguments(account, id, accept));
}
Client::Pending Client::RespondToRequest(std::string_view account, std::uint64_t id, bool accept, Then<std::monostate> then) {
return Pending(Start(bus.get(), respondToRequestCall, ResponseArguments(account, id, accept), std::move(then)));
}
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) {
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) {
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) {
Call(bus.get(), notes, "RespondToDraftPayment", true, [account, id, accept](sd_bus_message* call) {
Append(call, std::string(account));
Append(call, id);
Append(call, accept);
}, NoAnswer);
Run(bus.get(), notes, respondToDraftPaymentCall, ResponseArguments(account, id, accept));
}
Client::Pending Client::RespondToDraftPayment(std::string_view account, std::uint64_t id, bool accept, Then<std::monostate> then) {
return Pending(Start(bus.get(), respondToDraftPaymentCall, ResponseArguments(account, id, accept), std::move(then)));
}
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) {
return Call(bus.get(), notes, "SetCardStatus", true, [card, status](sd_bus_message* call) {
Append(call, card);
Append(call, std::string(status));
}, ReadAs<BunqCard>);
return Run(bus.get(), notes, setCardStatusCall, CardArguments(card, status));
}
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() {
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) {
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() {

View file

@ -520,7 +520,13 @@ namespace {
std::string apiKey = Read<std::string>(call);
std::string allowedIps = 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))}}};
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));
@ -556,7 +562,7 @@ namespace {
}
}
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 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));
return Gate(worker, call, Prompt{actionView, "see your transactions", {}}, [key, query](sd_bus_message* reply) {
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));
});
});
@ -812,6 +822,12 @@ namespace {
for(BunqConnector& bank : BunqConnector::connectors) {
for(const BunqCard& found : bank.Cards()) {
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 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) {
@ -1000,7 +1016,7 @@ namespace {
if(const BunqAccount* chosen = CheckoutAccount(worker)) {
then(KeyOf(*chosen));
} 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`")));
}
}

File diff suppressed because it is too large Load diff

View 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.");
}

View 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)); });
}
}

View 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};
}
}

View 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));
}

View 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;
}

View 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));
});
}
}

View 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())});
}
});
});
}

View 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 &region;
}
}
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 &region;
}
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>(&region - 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(&region);
}
}
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);
}

View 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;
}

View 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);
}
}

View 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;
}

View 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;
}

View 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;
}

View 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;
}

View 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;
}

View 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();
}
}

View 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;
}

View 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);
}
}

View file

@ -9,7 +9,7 @@ using namespace Nostro;
namespace {
constexpr std::string_view usage = R"(usage:
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 remove <name or number> log out and forget a connector and its stored transactions
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");
}
// 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
// same way every time.
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) {
// 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
// arguments, and polkit writes them to the journal.
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);
}
@ -142,19 +142,10 @@ nostrod does the work, and asks for your password before anything that moves mon
if(!std::getline(std::cin, redirected)) {
throw std::runtime_error("no address given");
}
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");
}
if(QueryParameter(redirected, "state") != state) {
throw std::runtime_error("that address is not the answer to this authorization (its state differs): start again");
}
const std::string code = BunqConnector::OAuthCodeFromRedirect(redirected, state);
// 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);
}
@ -197,7 +188,7 @@ nostrod does the work, and asks for your password before anything that moves mon
query.from = ParseLocalDate(*from);
}
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")) {
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);
BunqSchedule schedule;
schedule.start = ParseLocalDate(args.At(5, "start date"));
schedule.unit = std::string(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))); });
schedule.unit = BunqSchedule::UnitFromWord(args.At(6, "recurrence"));
if(const std::optional<std::string_view> every = args.Option("--every")) {
schedule.every = ParseNumber<std::uint32_t>(*every, "--every");
}
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);
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 BunqCard card = client.SetCardStatus(id, status->second);
if(card.status != 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));
}
card.ExpectStatus(status->second);
std::println("card {} is now {}", id, card.status);
}

View 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;
}
}