Portals0.7.0 · dev (544a5c68c72e · 2026-11-28 UTC)
Loading...
Searching...
No Matches
controls.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/layout.hpp>
7#include <portals/property.hpp>
8
9#include <optional>
10#include <span>
11
12namespace portals {
13class Menu;
14
15namespace detail {
16struct FindAccess;
17}
18
19namespace ui::detail {
20struct ActionAccess;
21}
22
26 CellStyle focused{{}, {}, true, false, false};
27 CellStyle disabled{{}, {}, false, true, false};
31 bool operator==(const ControlStyle &) const = default;
32};
33
39class Control : public SizedWidget {
40public:
46 std::expected<CellSize, TreeError> measure(CellSize available) override;
52 std::expected<void, TreeError> arrange(CellRect local) override;
62 std::expected<void, TreeError> paint(PaintContext &context) override;
66 const GraphemeText &text() const;
70 bool focused() const;
74 bool enabled() const;
75
77 ComputedStyle styleDefaults() const override;
78
79protected:
92 Control(GraphemeText text, std::string_view prefix, std::string_view suffix, ControlStyle style, SizePolicy policy);
106 std::expected<void, TreeError> paintCaption(PaintContext &context, bool stretchChrome);
111 void showChecked(bool checked);
115 bool shownChecked() const;
119 void showMixed(bool mixed);
120
121private:
122 friend struct detail::FindAccess;
123 friend struct ui::detail::ActionAccess;
124 friend class ManagedScene;
125 friend std::expected<void, TreeError> setControlText(WidgetTree &, Node<Control>, GraphemeText);
126 friend std::expected<void, TreeError> setControlStyle(WidgetTree &, Node<Control>, ControlStyle);
127 friend std::expected<void, TreeError> syncControl(WidgetTree &, Node<Control>, Node<Widget>);
128 GraphemeText text_;
129 GraphemeText prefix_;
130 GraphemeText checked_prefix_;
131 std::optional<GraphemeText> mixed_prefix_;
132 GraphemeText suffix_;
133 ControlStyle style_;
134 CellRect bounds_;
135 bool checked_{};
136 bool mixed_{};
137 bool focused_{};
138 bool enabled_{true};
139};
140
142class Label : public Control {
143public:
152};
153
159
161class Button : public Control {
162public:
181 std::expected<CellSize, TreeError> measure(CellSize available) override;
182
189 std::expected<void, TreeError> paint(PaintContext &context) override;
190
192 bool checked() const {
193 return shownChecked();
194 }
195
196private:
197 ButtonChrome chrome_;
198};
199
209
210namespace ui {
218public:
220 explicit ClickParams(const ClickEvent &click)
221 : target(click.target), mods(click.modifiers), source(sourceOf(click.event)), event(click.event) {
222 }
223
225 void stopPropagation() noexcept {
226 stopped_ = true;
227 }
228
230 void stop() noexcept {
232 }
233
235 bool propagationStopped() const noexcept {
236 return stopped_;
237 }
238
243
244private:
245 static ClickSource sourceOf(const RoutedEvent &event) {
246 return std::visit(
247 [](const auto &value) {
248 using T = std::remove_cvref_t<decltype(value)>;
249
250 if constexpr (std::same_as<T, ActionEvent>) {
251 return value.source;
252 } else if constexpr (std::same_as<T, MouseInputEvent>) {
253 return ClickSource::MOUSE;
254 } else {
256 }
257 },
258 event);
259 }
260
261 bool stopped_{};
262};
263} // namespace ui
264
271
277
282
288constexpr std::expected<CheckState, TreeError> aggregateCheckState(std::span<const CheckState> states) {
289 bool checked = false;
290 bool unchecked = false;
291 bool mixed = false;
292
293 for (const auto state : states) {
294 switch (state) {
296 unchecked = true;
297 break;
299 checked = true;
300 break;
302 mixed = true;
303 break;
304 default:
305 return std::unexpected(TreeError::INVALID_ARGUMENT);
306 }
307 }
308
309 return mixed || (checked && unchecked) ? CheckState::MIXED : checked ? CheckState::CHECKED : CheckState::UNCHECKED;
310}
311
313class CheckBox : public Control {
314public:
326 bool checked() const;
329
330protected:
336
337private:
338 friend class CheckBoxBinding;
339 friend class CheckStateBinding;
340 void display(bool value);
341 void display(CheckState value);
343};
344
349class ThreeState : public CheckBox {
350public:
351 using CheckBox::CheckBox;
352};
353
354inline constexpr std::string_view DEFAULT_SWITCH_OFF_TEXT = "[off] ";
355inline constexpr std::string_view DEFAULT_SWITCH_ON_TEXT = "[on ] ";
356
358class SwitchChrome {
359public:
365 static std::expected<SwitchChrome, TreeError> from(std::string_view off, std::string_view on,
366 WidthPolicy policy = {});
367
370 return off_.policy();
371 }
372
373private:
374 friend class Switch;
375
376 SwitchChrome(GraphemeText off, GraphemeText on) : off_(std::move(off)), on_(std::move(on)) {
377 }
378
379 GraphemeText off_, on_;
380};
381
383class Switch : public CheckBox {
384public:
390 bool readOnly = false);
397 bool readOnly = false);
401 std::expected<CellSize, TreeError> measure(CellSize available) override;
402
404 bool readOnly() const {
405 return readOnly_;
406 }
407
408private:
409 bool readOnly_{};
410};
411
422std::expected<void, TreeError> setControlText(WidgetTree &tree, Node<Control> node, GraphemeText text);
430std::expected<void, TreeError> setControlStyle(WidgetTree &tree, Node<Control> node, ControlStyle style);
440std::expected<void, TreeError> syncControl(WidgetTree &tree, Node<Control> node, Node<Widget> focused);
458std::expected<ActionBinding, TreeError> bindButton(EventRouter &router, Node<Button> node,
459 std::function<void()> action);
460
470std::expected<ActionBinding, TreeError> bindButtonClick(EventRouter &router, Node<Button> node,
471 std::function<void(const ClickEvent &)> action,
472 bool allowModified = true);
474using CheckBoxResult = std::expected<PropertyUpdate<bool>, TreeError>;
475
477using CheckStateResult = std::expected<PropertyUpdate<CheckState>, TreeError>;
478
486public:
502 CheckStateBinding &operator=(CheckStateBinding &&) noexcept;
503 CheckStateBinding(const CheckStateBinding &) = delete;
504 CheckStateBinding &operator=(const CheckStateBinding &) = delete;
511 std::expected<void, TreeError> sync();
512
513private:
514 struct State;
516 std::shared_ptr<Property<CheckState>>,
517 std::function<void(CheckStateResult)>,
519 CheckStateBinding(std::shared_ptr<State> state, ActionBinding action, Subscription subscription);
520 std::shared_ptr<State> state_;
521 ActionBinding action_;
522 Subscription subscription_;
523};
524
539 std::shared_ptr<Property<CheckState>> model,
540 std::function<void(CheckStateResult)> changed,
541 CheckBoxOptions options = {});
542
543namespace detail {
545struct CheckBoxEndpoint {
546 std::function<std::expected<std::shared_ptr<const PropertyChange<bool>>, TreeError>()> read;
547 std::function<CheckBoxResult(bool)> write;
548};
549
551} // namespace detail
552
560public:
576 CheckBoxBinding &operator=(CheckBoxBinding &&) noexcept;
577 CheckBoxBinding(const CheckBoxBinding &) = delete;
578 CheckBoxBinding &operator=(const CheckBoxBinding &) = delete;
585 std::expected<void, TreeError> sync();
587 std::expected<bool, TreeError> value() const;
591 std::expected<PropertyUpdate<bool>, TreeError> set(bool value);
592
593private:
594 struct State;
595 friend std::expected<CheckBoxBinding, TreeError> bindCheckbox(WidgetTree &, EventRouter &, Node<CheckBox>,
596 std::unique_ptr<detail::CheckBoxEndpoint>,
597 std::function<void(CheckBoxResult)>);
598 friend std::expected<CheckBoxBinding, TreeError> bindCheckbox(WidgetTree &, EventRouter &, Node<CheckBox>,
599 std::shared_ptr<Property<bool>>,
600 std::function<void(CheckBoxResult)>);
601 CheckBoxBinding(std::shared_ptr<State> state, ActionBinding action, Subscription subscription);
602 std::shared_ptr<State> state_;
603 ActionBinding action_;
604 Subscription subscription_;
605};
606
628std::expected<CheckBoxBinding, TreeError> bindCheckbox(WidgetTree &, EventRouter &, Node<CheckBox>,
629 std::unique_ptr<detail::CheckBoxEndpoint>,
630 std::function<void(CheckBoxResult)>);
633 std::shared_ptr<Property<bool>> model,
634 std::function<void(CheckBoxResult)> changed);
635} // namespace portals
Move-only scoped disconnect token; never owns a tree or widget. Disconnect/destruction may run on any...
Definition action.hpp:96
bool checked() const
Definition controls.hpp:192
Button(GraphemeText text, ControlStyle style={}, SizePolicy policy=DEFAULT_CONTENT_POLICY)
Construct an owning button with ASCII brackets on UI, normally through tree.emplace.
Button(GraphemeText text, ControlStyle style, SizePolicy policy, ButtonChrome chrome)
std::expected< void, TreeError > paint(PaintContext &context) override
Paint bracket chrome at the allocated edges with a centered, independently clipped caption.
std::expected< CellSize, TreeError > measure(CellSize available) override
An owning, invariant-preserving half-open cell rectangle.
Definition geometry.hpp:81
Own one checkbox's action, subscription and shared UI model owner. Tree, router and scheduler must ou...
Definition controls.hpp:559
std::expected< void, TreeError > sync()
Read the latest committed model snapshot on UI between frames and synchronize presentation.
CheckBoxBinding(CheckBoxBinding &&) noexcept
Transfer all ownership from the unnamed source binding argument on UI. The source becomes empty; its ...
std::expected< PropertyUpdate< bool >, TreeError > set(bool value)
std::expected< bool, TreeError > value() const
~CheckBoxBinding()
Disconnect subscription/action and release model ownership on UI. Admitted callbacks retain their cap...
Checkbox presentation; its bound boolean or explicit-state Property remains authoritative.
Definition controls.hpp:313
CheckState checkState() const
CheckBox(GraphemeText text, GraphemeText off, GraphemeText on, ControlStyle style, SizePolicy policy)
Construct a boolean subtype with owning validated decorations.
CheckBox(GraphemeText text, ControlStyle style={}, SizePolicy policy=DEFAULT_CONTENT_POLICY)
Construct an owning initially unchecked view on UI, normally through tree.emplace.
bool checked() const
Inspect the last synchronized model value on UI inside tree.read.
Own one checkbox's action, subscription and shared UI model owner. Tree, router and scheduler must ou...
Definition controls.hpp:485
~CheckStateBinding()
Disconnect subscription/action and release model ownership on UI. Admitted callbacks retain their cap...
std::expected< void, TreeError > sync()
Read the latest committed model snapshot on UI between frames and synchronize presentation.
friend std::expected< CheckStateBinding, TreeError > bindCheckbox(WidgetTree &, EventRouter &, Node< CheckBox >, std::shared_ptr< Property< CheckState > >, std::function< void(CheckStateResult)>, CheckBoxOptions)
Bind an explicit checkbox state on UI, preserving Property commit receipts.
CheckStateBinding(CheckStateBinding &&) noexcept
Transfer all ownership from the unnamed source binding argument on UI. The source becomes empty; its ...
bool booleanChromeMatches() const
const GraphemeText & text() const
Inspect the control's owning Unicode text on UI.
friend std::expected< void, TreeError > setControlStyle(WidgetTree &, Node< Control >, ControlStyle)
Replace owning paint values on UI between frames; equal is a no-op, changes invalidate paint.
std::expected< void, TreeError > paint(PaintContext &context) override
Submit local fill/text commands from the synchronized presentation snapshot.
bool shownChecked() const
Inspect the single checked presentation flag on UI.
ComputedStyle styleDefaults() const override
friend std::expected< void, TreeError > syncControl(WidgetTree &, Node< Control >, Node< Widget >)
Copy focus and ancestor eligibility on UI between frames; changes invalidate paint.
bool enabled() const
Inspect the last synchronized subtree eligibility presentation on UI.
Control(GraphemeText text, std::string_view prefix, std::string_view suffix, ControlStyle style, SizePolicy policy)
Own text/options and create fixed ASCII decorations under the text's validated width policy.
std::expected< void, TreeError > arrange(CellRect local) override
Retain a zero-origin rectangle with the allocated local extent.
void showChecked(bool checked)
Select a same-width prefix between frames; used only by the checkbox binding.
bool focused() const
Inspect the last synchronized focus presentation on UI.
friend std::expected< void, TreeError > setControlText(WidgetTree &, Node< Control >, GraphemeText)
Replace owning text between frames; equal bytes/policy are a no-op, changes invalidate layout.
std::expected< void, TreeError > paintCaption(PaintContext &context, bool stretchChrome)
Paint the synchronized caption with intrinsic or allocated-width decorations.
std::expected< CellSize, TreeError > measure(CellSize available) override
Report intrinsic text and decoration width, with height one.
void showMixed(bool mixed)
Select the fixed mixed decoration after caller-owned paint invalidation.
Control(GraphemeText text, GraphemeText prefix, GraphemeText checkedPrefix, ControlStyle style, SizePolicy policy)
Own explicitly validated equal-width boolean decorations; no additional retained fields.
UI-owned focus and synchronous bubbling over an existing WidgetTree. Tree and Scheduler must outlive ...
Definition action.hpp:169
Owning validated UTF-8 and immutable extended grapheme measurements.
Definition text.hpp:145
Label(GraphemeText text, ControlStyle style={}, SizePolicy policy=DEFAULT_CONTENT_POLICY)
Construct an owning undecorated label on UI, normally through tree.emplace.
Initially visible action-backed command list, without popup or submenu behavior. Actions own callback...
Definition menu.hpp:21
Copyable typed observer; never owns or exposes an unchecked widget pointer.
Definition widget.hpp:92
Borrowed synchronous command sink supplied by the frame owner. submit must consume commands immediate...
Definition widget_types.hpp:66
UI-owned typed value with node-scoped observers and explicit partial delivery. WidgetTree and its Sch...
Definition property.hpp:62
SizedWidget(SizePolicy policy={})
Own the supplied policies; checked by layout.
UI-owned move-only cancellation token. Release before Scheduler. Disconnect is immediate logically; a...
Definition scheduler.hpp:121
Owning validated switch decorations, independent of any widget or scene.
Definition controls.hpp:358
WidthPolicy policy() const
Definition controls.hpp:369
static std::expected< SwitchChrome, TreeError > from(std::string_view off, std::string_view on, WidthPolicy policy={})
Validate same-width single-line off/on decorations under the receiving policy.
One-line boolean switch using the ordinary CheckBox binding and theme.
Definition controls.hpp:383
bool readOnly() const
Definition controls.hpp:404
Switch(GraphemeText text, ControlStyle style={}, SizePolicy policy=DEFAULT_CONTENT_POLICY, bool readOnly=false)
Initially false, plain ASCII [off]/[on ] presentation; bind a bool model for input.
std::expected< CellSize, TreeError > measure(CellSize available) override
Switch(GraphemeText text, SwitchChrome chrome, ControlStyle style={}, SizePolicy policy=DEFAULT_CONTENT_POLICY, bool readOnly=false)
Own custom equal-width decorations; policy mismatch is rejected by measure.
Named checkbox presentation using the existing CheckBox runtime. ui::threeState binds the fixed three...
Definition controls.hpp:349
CheckBox(GraphemeText text, ControlStyle style={}, SizePolicy policy=DEFAULT_CONTENT_POLICY)
Construct an owning initially unchecked view on UI, normally through tree.emplace.
Exclusive parent/child ownership on Scheduler's UI thread. Scheduler must outlive this object....
Definition widget.hpp:179
void stop() noexcept
Short alias for stopPropagation, affecting the same synchronous chain context.
Definition controls.hpp:230
bool propagationStopped() const noexcept
Definition controls.hpp:235
const RoutedEvent event
Owning original routed value; keyboard translation preserves its source.
Definition controls.hpp:242
void stopPropagation() noexcept
Stop remaining callbacks of this activation; the button already consumes router bubbling.
Definition controls.hpp:225
ClickParams(const ClickEvent &click)
Definition controls.hpp:220
const Node< Button > target
Observing activated identity; may become stale after a callback.
Definition controls.hpp:239
const ClickSource source
Actual admitted event origin.
Definition controls.hpp:241
const InputModifiers mods
Original semantic modifiers, queryable with key tags.
Definition controls.hpp:240
Public Portals API.
Definition action.hpp:8
std::expected< void, TreeError > setControlStyle(WidgetTree &tree, Node< Control > node, ControlStyle style)
Replace owning paint values on UI between frames; equal is a no-op, changes invalidate paint.
constexpr std::expected< CheckState, TreeError > aggregateCheckState(std::span< const CheckState > states)
Combine borrowed states without allocation or retained references.
Definition controls.hpp:288
ui::ValueText text(std::format_string< const ui::detail::TextArgumentValue< Args > &... > pattern, Args &&...args)
Declare live formatted text over explicit scalar roots, fields or value properties.
Definition ui_value_text.hpp:567
std::expected< PropertyUpdate< CheckState >, TreeError > CheckStateResult
Exact typed Property set receipt; successful commits can reject notifications.
Definition controls.hpp:477
CheckState
Explicit checkbox value; MIXED describes an aggregate or an opt-in user choice.
Definition controls.hpp:266
@ MIXED
Partial selection, displayed independently of color.
Definition controls.hpp:269
@ CHECKED
Complete selection.
Definition controls.hpp:268
@ UNCHECKED
No selection.
Definition controls.hpp:267
std::expected< ActionBinding, TreeError > bindButtonClick(EventRouter &router, Node< Button > node, std::function< void(const ClickEvent &)> action, bool allowModified=true)
Bind activation with owning parameters through the existing scoped router token.
constexpr SizePolicy DEFAULT_CONTENT_POLICY
Intrinsic content on both axes; explicit policies remain authoritative.
Definition layout.hpp:44
std::variant< ActionEvent, KeyEvent, TextInputEvent, PasteInputEvent, MouseInputEvent > RoutedEvent
Synchronous input value; callback borrows it only until return.
Definition action.hpp:47
std::expected< CheckStateBinding, TreeError > bindCheckbox(WidgetTree &tree, EventRouter &router, Node< CheckBox > node, std::shared_ptr< Property< CheckState > > model, std::function< void(CheckStateResult)> changed, CheckBoxOptions options={})
Bind an explicit checkbox state on UI, preserving Property commit receipts.
CheckCycle
User activation policy for an explicitly typed checkbox binding.
Definition controls.hpp:273
@ TWO_STATE
Unchecked/checked toggle; mixed activates to checked.
Definition controls.hpp:274
@ THREE_STATE
Unchecked, checked, mixed, then unchecked.
Definition controls.hpp:275
constexpr std::string_view DEFAULT_SWITCH_OFF_TEXT
Plain off decoration.
Definition controls.hpp:354
ClickSource
Origin of an admitted activation, without inferred physical input.
Definition action.hpp:24
@ MOUSE
Mouse input supplied by the existing router.
Definition action.hpp:27
@ KEYBOARD
Keyboard input, including a key translated into a semantic action.
Definition action.hpp:26
std::expected< ActionBinding, TreeError > bindButton(EventRouter &router, Node< Button > node, std::function< void()> action)
Bind one activation callback on UI outside a frame; the caller owns the returned disconnect token.
ButtonChrome
Button caption decoration; action routing and identity remain unchanged.
Definition controls.hpp:155
@ BRACKETS
ASCII bracket contour spanning the allocated button width.
Definition controls.hpp:156
@ NONE
Caption only, including a single-glyph action button.
Definition controls.hpp:157
std::expected< void, TreeError > setControlText(WidgetTree &tree, Node< Control > node, GraphemeText text)
Replace owning text between frames; equal bytes/policy are a no-op, changes invalidate layout.
std::expected< void, TreeError > syncControl(WidgetTree &tree, Node< Control > node, Node< Widget > focused)
Copy focus and ancestor eligibility on UI between frames; changes invalidate paint.
std::expected< PropertyUpdate< bool >, TreeError > CheckBoxResult
Exact Property set outcome; errors mean no commit, successful receipts can reject notifications.
Definition controls.hpp:474
TreeError
Checked tree failures; rejected operations never start the requested callback.
Definition widget_types.hpp:26
@ INVALID_ARGUMENT
An option, enum value or operation argument is invalid.
Definition widget_types.hpp:27
constexpr std::string_view DEFAULT_SWITCH_ON_TEXT
Plain on decoration.
Definition controls.hpp:355
An owning available extent in terminal columns/rows.
Definition geometry.hpp:44
Small owning paint value, independent of themes and text metrics.
Definition cell_buffer.hpp:35
Owning typed checkbox input configuration.
Definition controls.hpp:279
CheckCycle cycle
Default preserves the boolean input cycle.
Definition controls.hpp:280
Owning activation parameters copied from the existing router delivery. target is the activated button...
Definition controls.hpp:204
Node< Button > target
Activated button; does not retain the widget.
Definition controls.hpp:205
RoutedEvent event
Owning action, Space or left mouse press that activated the button.
Definition controls.hpp:207
InputModifiers modifiers
Modifiers supplied by the routed event.
Definition controls.hpp:206
Owning resolved presentation; no actions or model state are encoded.
Definition style_types.hpp:169
Owning paint values; no theme engine or behavior is encoded here.
Definition controls.hpp:24
CellStyle normal
Ordinary appearance.
Definition controls.hpp:25
CellStyle focused
Keyboard or mouse focus appearance.
Definition controls.hpp:26
CellStyle disabled
Ineligible subtree appearance.
Definition controls.hpp:27
bool operator==(const ControlStyle &) const =default
Compare every appearance with the unnamed other style argument.
Observed modifiers, also usable by a native input adapter.
Definition input.hpp:34
A successful set result; notification rejection does not undo the committed value....
Definition property.hpp:38
Owning independent policies for width and height.
Definition layout.hpp:35
Owning deterministic width policy; no font or terminal matching promise.
Definition text.hpp:42