Portals0.7.0 · dev (544a5c68c72e · 2026-11-28 UTC)
Loading...
Searching...
No Matches
application.hpp
1// Copyright (c) 2026 ttldtor.
2// SPDX-License-Identifier: BSL-1.0
3#pragma once
4
5#include <portals/action.hpp>
6#include <portals/background_options.hpp>
7#include <portals/diff.hpp>
8#include <portals/layout.hpp>
9#include <portals/layout_snapshot.hpp>
10#include <portals/render.hpp>
11
12namespace portals {
13
28
40
43 std::variant<ApplicationFailure, TerminalError, SchedulerError, TreeError, InputError, RenderError, FrameError>;
44
49 std::optional<TerminalError> restoration;
50 std::optional<BackgroundError> background{};
51};
52
64 using Callback = void (*)(void *context, ApplicationPhase phase, std::chrono::nanoseconds elapsed);
66 void *context{};
67};
68
74
97
100 std::uint64_t iterations{};
101 std::uint64_t frames{};
102 std::uint64_t flushes{};
103 std::uint64_t bytes{};
104 std::uint64_t inputs{};
105};
106
113public:
123 virtual TerminalRead read(TerminalDeadline deadline, std::stop_token stop) = 0;
128 virtual std::expected<void, TerminalError> protocol(const InputProtocolEvent &report);
133 virtual std::expected<void, TerminalError> pointerMetrics(bool usable);
135 virtual bool terminalReports() const noexcept;
136
138 virtual std::expected<CellSize, TerminalError> size() const = 0;
143 virtual std::expected<void, TerminalError> close() noexcept = 0;
144};
145
151
163public:
164 virtual ~ApplicationReadyTerminal() = default;
172 virtual TerminalRead poll(std::stop_token stop) = 0;
176 virtual std::expected<void, TerminalError> protocol(const InputProtocolEvent &report);
180 virtual std::expected<void, TerminalError> pointerMetrics(bool usable);
181
183 virtual std::expected<CellSize, TerminalError> size() const = 0;
187 virtual std::expected<void, TerminalError> submit(std::string bytes) = 0;
191 virtual TerminalWrite flushReady(std::stop_token stop) = 0;
193 virtual std::expected<void, TerminalError> close() noexcept = 0;
194};
195
231[[nodiscard]] std::expected<std::unique_ptr<ApplicationTerminal>, TerminalError>
233 std::chrono::milliseconds modeTimeout = std::chrono::milliseconds{2000},
234 bool mouseReporting = true, NativeScreenMode screen = NativeScreenMode::ALTERNATE_SCREEN);
235
249[[nodiscard]] std::expected<std::unique_ptr<ApplicationTerminal>, TerminalError>
251 std::chrono::milliseconds modeTimeout, bool mouseReporting, NativeScreenMode screen,
252 bool buttonMotion);
253
269[[nodiscard]] std::expected<std::unique_ptr<ApplicationTerminal>, TerminalError>
271 std::chrono::milliseconds modeTimeout, bool mouseReporting, NativeScreenMode screen,
272 bool buttonMotion, NativePointerOptions pointer);
273
274class Application;
275
282public:
283 virtual ~ApplicationScene() = default;
293 virtual std::expected<void, TreeError> prepare(Application &application, CellSize size);
299 virtual std::expected<bool, TreeError> input(Application &application, const InputEvent &event);
303 virtual void stop(Application &application);
307 virtual bool usesPreparedLayout() const noexcept;
311 virtual bool usesGeometrySnapshot() const noexcept;
316 virtual bool requiresPointerMotion() const noexcept;
321 virtual bool requiresBackgroundExecutor() const noexcept;
334 virtual std::expected<void, TreeError> prepareViews(Application &application, const LayoutSnapshot &snapshot);
340 virtual std::expected<void, TreeError> completedLayout(Application &application);
346 virtual std::expected<void, TreeError> afterDispatch(Application &application);
350 virtual bool hasPendingLayout() const noexcept;
351};
352
358class Application {
359public:
365 static std::expected<std::unique_ptr<Application>, ApplicationError> create(ApplicationOptions options = {},
366 SchedulerClock clock = {});
372 Application(const Application &) = delete;
373 Application &operator=(const Application &) = delete;
375 Scheduler &scheduler() noexcept;
377 WidgetTree &tree() noexcept;
379 EventRouter &router() noexcept;
381 Node<Widget> root() const noexcept;
383 SchedulerTime now() const noexcept;
385 WidthPolicy widthPolicy() const noexcept;
392 void requestStop() noexcept;
400 std::expected<void, ApplicationError> start(ApplicationScene &scene, ApplicationReadyTerminal &terminal,
401 std::stop_token stop = {});
409 std::expected<ApplicationStep, ApplicationError> step();
411 ApplicationStats stats() const noexcept;
422 std::expected<ApplicationStats, ApplicationError> run(ApplicationScene &scene, std::stop_token stop = {});
433 std::expected<ApplicationStats, ApplicationError> run(ApplicationScene &scene, ApplicationTerminal &terminal,
434 std::stop_token stop = {});
435
436private:
437 struct State;
438 explicit Application(std::unique_ptr<State> state);
439 void prepareBackground(const ApplicationScene &scene, bool hosted);
440 void finishBackground() noexcept;
441 void finishSession() noexcept;
442 std::unique_ptr<State> state_;
443};
444} // namespace portals
Exclusive ready-only transport borrowed by an application session. Every operation must return withou...
Definition application.hpp:162
virtual std::expected< CellSize, TerminalError > size() const =0
virtual std::expected< void, TerminalError > pointerMetrics(bool usable)
virtual PointerCaptureCapabilities pointerCaptureCapabilities() const noexcept
virtual std::expected< void, TerminalError > close() noexcept=0
virtual TerminalRead poll(std::stop_token stop)=0
virtual std::expected< void, TerminalError > protocol(const InputProtocolEvent &report)
virtual ~ApplicationReadyTerminal()=default
Destroy after session cleanup.
virtual std::expected< void, TerminalError > submit(std::string bytes)=0
virtual TerminalWrite flushReady(std::stop_token stop)=0
Borrowed scene extension; bindings/models/providers belong to the caller. Construct the Application f...
Definition application.hpp:281
virtual std::expected< void, TreeError > afterDispatch(Application &application)
Retry deferred publication after existing scheduler work has freed queue capacity.
virtual bool usesPreparedLayout() const noexcept
Opt into bounded layout-driven view preparation; default is false.
virtual ~ApplicationScene()=default
virtual std::expected< void, TreeError > prepare(Application &application, CellSize size)
Synchronize controls and pin each model once for a dirty frame. Called only when a dirty frame can be...
virtual bool hasPendingLayout() const noexcept
virtual std::expected< void, TreeError > completedLayout(Application &application)
Publish owning observations of the successful final frame, outside tree.frame.
virtual bool usesGeometrySnapshot() const noexcept
virtual std::expected< void, TreeError > prepareViews(Application &application, const LayoutSnapshot &snapshot)
Prepare views from one owning layout snapshot; default is a no-op. Called only for opt-in scenes,...
virtual bool requiresBackgroundExecutor() const noexcept
virtual std::expected< bool, TreeError > input(Application &application, const InputEvent &event)
Optional global command interception inside the bounded CONTROL callback.
virtual bool requiresPointerMotion() const noexcept
virtual void stop(Application &application)
Stop and join only scene-owned producers; called once before terminal restoration.
Custom/replay terminal borrowed for exactly one run; no competing I/O is allowed. The owner retains i...
Definition application.hpp:112
virtual bool terminalReports() const noexcept
virtual PointerCaptureCapabilities pointerCaptureCapabilities() const noexcept
virtual std::expected< void, TerminalError > protocol(const InputProtocolEvent &report)
Handle an ordered terminal report without performing I/O; default ignores it.
virtual std::expected< void, TerminalError > close() noexcept=0
Restore owned native screen/modes and close; custom transports define their policy....
virtual std::expected< CellSize, TerminalError > size() const =0
virtual std::expected< void, TerminalError > pointerMetrics(bool usable)
Request bounded fallback when pixel dimensions cease to be usable; default is a no-op.
virtual TerminalRead read(TerminalDeadline deadline, std::stop_token stop)=0
One UI owner for scheduler, tree, routing and a single terminal run. All calls/destruction except req...
Definition application.hpp:358
~Application()
Finish an active session, then release routing/tree before the scheduler. Destroy on the UI owner thr...
std::expected< void, ApplicationError > start(ApplicationScene &scene, ApplicationReadyTerminal &terminal, std::stop_token stop={})
Start the single permitted ready-only session, without waiting or running a frame.
void requestStop() noexcept
Worker-safe while this owner lives; wakes scheduler and cancels terminal waits.
std::expected< ApplicationStep, ApplicationError > step()
Service one bounded input/dispatch/render/output cycle without waiting. Uses existing input/scheduler...
BackgroundExecutor * background() noexcept
std::expected< ApplicationStats, ApplicationError > run(ApplicationScene &scene, std::stop_token stop={})
Open standard input/output and restore them before returning. Requires the default steady clock; an i...
Scheduler & scheduler() noexcept
WidgetTree & tree() noexcept
WidthPolicy widthPolicy() const noexcept
EventRouter & router() noexcept
Node< Widget > root() const noexcept
static std::expected< std::unique_ptr< Application >, ApplicationError > create(ApplicationOptions options={}, SchedulerClock clock={})
SchedulerTime now() const noexcept
ApplicationStats stats() const noexcept
std::expected< ApplicationStats, ApplicationError > run(ApplicationScene &scene, ApplicationTerminal &terminal, std::stop_token stop={})
Run against a borrowed custom terminal; always close before returning once accepted....
Borrowed host service. A scene never owns, stops or joins this executor. UI integration calls service...
Definition background.hpp:72
UI-owned focus and synchronous bubbling over an existing WidgetTree. Tree and Scheduler must outlive ...
Definition action.hpp:169
Exclusive transport boundary, borrowed by FrameWriter for its lifetime. Implementations own submitted...
Definition diff.hpp:58
Owning immutable identities and local sizes from one completed layout pass. Copies share immutable va...
Definition layout_snapshot.hpp:43
Copyable typed observer; never owns or exposes an unchecked widget pointer.
Definition widget.hpp:92
One UI executor; call dispatch only between frames, never during layout/paint. create captures its ca...
Definition scheduler.hpp:238
Exclusive parent/child ownership on Scheduler's UI thread. Scheduler must outlive this object....
Definition widget.hpp:179
UI-owned extension object. Hooks borrow their arguments for one call. Models are separate explicit ow...
Definition widget.hpp:32
Public Portals API.
Definition action.hpp:8
NativeScreenMode
Screen ownership for the native application transport.
Definition application.hpp:70
@ ALTERNATE_SCREEN
Own an alternate screen and return to the caller's main screen on close.
Definition application.hpp:72
@ MAIN_SCREEN
Paint the caller's screen directly; its contents and cursor are not restored.
Definition application.hpp:71
std::variant< ApplicationFailure, TerminalError, SchedulerError, TreeError, InputError, RenderError, FrameError > ApplicationCause
Original component error; no formatted text or borrowed exception is retained.
Definition application.hpp:42
std::variant< KeyEvent, TextInputEvent, MouseInputEvent, PasteInputEvent, InputProbeCandidate, InputIssue > InputEvent
Independent owning result, usable beyond decoder reset/destruction.
Definition input.hpp:378
ApplicationFailure
Failures introduced by the runner itself.
Definition application.hpp:30
@ NOT_STARTED
A step was requested before an accepted start.
Definition application.hpp:36
@ CALLBACK_FAILED
A non-allocation exception escaped into a runner callback boundary.
Definition application.hpp:34
@ OBSERVER_FAILED
The optional measurement observer threw an exception.
Definition application.hpp:35
@ ALREADY_RUN
This application has already entered its single permitted run.
Definition application.hpp:32
@ INVALID_OPTIONS
Runner options are invalid, or a native run was requested with an injected clock.
Definition application.hpp:31
@ REENTRANT_OPERATION
A lifecycle operation was requested from an active operation or callback.
Definition application.hpp:37
@ BACKGROUND_FAILED
Background startup/admission failed; ApplicationError::background retains the cause.
Definition application.hpp:38
@ NO_MEMORY
Allocation failed at a runner exception boundary.
Definition application.hpp:33
std::variant< InputSizeReport, InputModeReport > InputProtocolEvent
Terminal protocol data kept separate from user input and single-use probe windows.
Definition input.hpp:416
std::expected< std::unique_ptr< ApplicationTerminal >, TerminalError > openNativeApplicationTerminal(NativeTerminalHandles handles, TerminalOptions options={}, std::chrono::milliseconds modeTimeout=std::chrono::milliseconds{2000}, bool mouseReporting=true, NativeScreenMode screen=NativeScreenMode::ALTERNATE_SCREEN)
Open an exclusive native transport with managed screen and optional mouse reporting.
std::chrono::steady_clock::time_point TerminalDeadline
Absolute monotonic time used by terminal waits.
Definition terminal.hpp:22
std::uint64_t SchedulerTime
Monotonic milliseconds; the clock must not move backwards.
Definition scheduler.hpp:18
ApplicationPhase
Application runner phase, also used to identify a failure boundary.
Definition application.hpp:15
@ FLUSH
Advance encoded output through ready operations or the native deadline driver.
Definition application.hpp:23
@ CREATE
Validate options and construct the application and its core services.
Definition application.hpp:16
@ STOP
Request cancellation, stop the scheduler and invoke the scene's stop hook.
Definition application.hpp:24
@ CLOSE
Close the transport and attempt restoration of terminal state.
Definition application.hpp:25
@ CONTROL_LATENCY
Observer-only logical queue delay for the runner's input/resize channel, not a work phase.
Definition application.hpp:26
@ SUBMIT
Give the owning frame to FrameWriter for diff encoding; no transport write occurs here.
Definition application.hpp:22
@ OPEN
Enter a run and initialize its transport and runner state.
Definition application.hpp:17
@ INPUT
Read, decode and enqueue terminal input or resize events.
Definition application.hpp:18
@ PREPARE
Synchronize scene state and, when enabled, prepare views after preliminary layout.
Definition application.hpp:20
@ RENDER
Lay out and paint the final frame, then consume commands into an owning cell buffer.
Definition application.hpp:21
@ DISPATCH
Deliver queued work through the existing scheduler.
Definition application.hpp:19
TreeError
Checked tree failures; rejected operations never start the requested callback.
Definition widget_types.hpp:26
Failure after orderly shutdown, including a separate restoration failure.
Definition application.hpp:46
std::optional< BackgroundError > background
Typed executor cause when failure is BACKGROUND_FAILED.
Definition application.hpp:50
ApplicationCause cause
Original failure, or explicit callback/allocation classification.
Definition application.hpp:48
ApplicationPhase phase
Operation which first failed.
Definition application.hpp:47
std::optional< TerminalError > restoration
Close failure retained even when an earlier operation failed.
Definition application.hpp:49
Optional synchronous measurement sink; disabled by default. The borrowed observer must outlive run or...
Definition application.hpp:57
Callback callback
Null disables measurements and their clock reads.
Definition application.hpp:65
void * context
Borrowed synchronous callback state.
Definition application.hpp:66
void(*)(void *context, ApplicationPhase phase, std::chrono::nanoseconds elapsed) Callback
Receive one completed phase duration; called outside tree frames.
Definition application.hpp:64
Finite runner and component policies; one owner services all I/O.
Definition application.hpp:76
bool nativeMouseReporting
Manage POSIX mouse reporting in the native run overload.
Definition application.hpp:81
InputOptions input
POSIX streaming decoder limits.
Definition application.hpp:82
WidthPolicy widthPolicy
Shared text/canvas/frame width policy.
Definition application.hpp:85
BackgroundOptions background
Default synchronous-session worker limits; used only by opt-in scenes.
Definition application.hpp:93
std::size_t maxPreparationPasses
Positive layout/view preparation budget for opt-in scenes per frame.
Definition application.hpp:91
RenderLimits render
Paint command and full-frame limits.
Definition application.hpp:84
NativeScreenMode nativeScreen
Preserve the caller's main screen in native run.
Definition application.hpp:79
std::chrono::milliseconds inputSlice
Positive future read deadline; never read(now).
Definition application.hpp:88
std::chrono::milliseconds outputSlice
Positive flush budget; Windows timeout can be uncertain.
Definition application.hpp:89
SchedulerOptions scheduler
Bounded existing scheduler queues and optional diagnostics.
Definition application.hpp:77
BackgroundExecutor * backgroundExecutor
Optional borrowed host executor; must outlive session cleanup.
Definition application.hpp:92
FrameWriterLimits writer
Output encoding and owned-frame limits.
Definition application.hpp:83
std::size_t inputBudget
Positive maximum decoder/native event pulls per iteration.
Definition application.hpp:87
std::uint32_t framesPerSecond
Positive cap, at most 1000; no catch-up frames.
Definition application.hpp:86
NativePointerOptions nativePointer
Advanced AUTO/OFF and declared host-ordering contract; defaults to cell fallback.
Definition application.hpp:95
TerminalOptions terminal
Native terminal batch and wait limits.
Definition application.hpp:78
ApplicationObserver observer
Optional borrowed measurement callback.
Definition application.hpp:90
Owning cumulative totals from a run or session, without samples or terminal data.
Definition application.hpp:99
std::uint64_t inputs
Events delivered through the runner CONTROL channel.
Definition application.hpp:104
std::uint64_t flushes
Calls which serviced pending output.
Definition application.hpp:102
std::uint64_t frames
Accepted frame submissions, including semantically unchanged frames.
Definition application.hpp:101
std::uint64_t bytes
Bytes confirmed by output flushes.
Definition application.hpp:103
std::uint64_t iterations
Bounded service cycles executed.
Definition application.hpp:100
One owning snapshot returned by a bounded session step.
Definition application.hpp:147
bool finished
True after orderly stop and cleanup; subsequent steps preserve this result.
Definition application.hpp:148
ApplicationStats stats
Cumulative progress, independent of the borrowed transport and scene.
Definition application.hpp:149
Count bounds, independent of the transitive byte size of inputs and results.
Definition background_options.hpp:24
An owning available extent in terminal columns/rows.
Definition geometry.hpp:44
Owning writer resource caps. At most two capped frames coexist.
Definition diff.hpp:101
Explicit resource and timing policy, independent of terminal capabilities.
Definition input.hpp:437
Advanced native pointer policy; no physical host qualification is inferred.
Definition terminal.hpp:43
Borrowed native descriptors supplied to open(); no Windows headers required.
Definition terminal.hpp:25
Host-declared input guarantees; this value does not enable terminal reporting modes.
Definition action.hpp:74
Owning full-frame resource caps; over-limit scenes fail without truncation.
Definition render.hpp:57
Borrowed clock service, invoked under the scheduler mutex on UI or producer threads....
Definition scheduler.hpp:57
Finite resource limits and maximum work per dispatch; all fields must be positive.
Definition scheduler.hpp:65
Owning error value, independent of session lifetime.
Definition terminal.hpp:79
Session resource bounds and cancellation/resize sampling cadence.
Definition terminal.hpp:50
Bounded owning transport result; earlier results are never invalidated.
Definition terminal.hpp:96
Owning output progress for this flush call, not a rendered-frame commit.
Definition terminal.hpp:107
Owning deterministic width policy; no font or terminal matching promise.
Definition text.hpp:42