Nostro/implementations/nostro-app.cpp
Jorijn van der Graaf d35c486424
All checks were successful
Flatpak / check (push) Has been skipped
Flatpak / publish (push) Successful in 6m51s
build(packaging): make the first release 0.0.0
The first release, which is also the first run of the workflow's publish
job, goes out as 0.0.0 and not as 0.1.0, as imsd-messages' first did.
NOSTRO_VERSION in project.cpp and the newest <release> of the app's
metainfo say so, the entry dated today, and the comment in nostro-app.cpp
that quotes the define follows.

packaging/flatpak/release-version.sh prints 0.0.0 for the tree and renders
the entry's notes, appstreamcli validates the metainfo, and the app builds
with the version in it. The Arch package of the system files keeps its own
pkgver.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-21 06:10:36 +01:00

671 lines
34 KiB
C++

// 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.0.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;
}
}