Nostro/implementations/Nostro.DebugCommands.cpp

388 lines
19 KiB
C++
Raw Normal View History

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>
2026-11-19 12:27:14 +01:00
// 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())});
}
});
});
}