Portals0.7.0 · dev (544a5c68c72e · 2026-11-28 UTC)
Loading...
Searching...
No Matches
line_edit.hpp
1// Copyright (c) 2026 ttldtor.
2// SPDX-License-Identifier: BSL-1.0
3#pragma once
4
5#include <portals/controls.hpp>
6#include <portals/text_history.hpp>
7
8#include <source_location>
9
10namespace portals {
11enum class AsyncError;
12enum class BackgroundError;
13
14namespace detail {
15struct LineEditValidationAccess;
16struct LineEditSourceAccess;
17struct LineEditValidationGate;
18struct EditTextDraft;
19} // namespace detail
20
21namespace ui::detail {
22struct RefAccess;
23struct Access;
24} // namespace ui::detail
25
32
39
45
52
54inline constexpr std::size_t LINE_EDIT_REDO_CHORD_COUNT = 2;
55
58 std::optional<EditorChord> undo{EditorChord{InputKey::CHARACTER, U'z', {.control = true}}};
59 std::array<std::optional<EditorChord>, LINE_EDIT_REDO_CHORD_COUNT> redo{
60 EditorChord{InputKey::CHARACTER, U'y', {.control = true}},
61 EditorChord{InputKey::CHARACTER, U'z', {.shift = true, .control = true}}};
62};
63
66 bool canUndo{};
67 bool canRedo{};
68};
69
70namespace detail {
73 bool active{};
74 bool reported{};
75 std::string_view operation;
76 std::source_location origin;
77};
78} // namespace detail
79
94
102
106 std::optional<PropertyUpdate<std::string>> commit{};
107 std::optional<TreeError> error{};
109 std::optional<AsyncError> async{};
110 std::optional<BackgroundError> background{};
111 std::optional<TextError> text{};
112 const char *operation{};
113 bool recoverable{};
114};
115
120
126
137
144
150 std::function<void(const TextEditedEvent &)> textEdited;
151 std::function<void(const EditingFinishedEvent &)> editingFinished;
152};
153
159public:
161 virtual ~Clipboard() = default;
166 virtual std::expected<std::string, TreeError> read(std::size_t maxBytes) = 0;
171 virtual std::expected<void, TreeError> write(std::string_view bytes) = 0;
172};
173
190
191namespace detail {
194 std::unique_ptr<GraphemeText> text;
195};
196} // namespace detail
197
205class LineEdit : public SizedWidget {
206public:
208 ~LineEdit() override;
212 LineEdit(LineEdit &&other) = default;
216 LineEdit &operator=(LineEdit &&other) = default;
237 std::expected<CellSize, TreeError> measure(CellSize available) override;
242 std::expected<void, TreeError> arrange(CellRect local) override;
247 std::expected<void, TreeError> paint(PaintContext &context) override;
251 const GraphemeText &text() const;
255 std::size_t cursor() const;
259 std::size_t anchor() const;
263 bool dirty() const;
264
266 ComputedStyle styleDefaults() const override;
267
268private:
269 friend class LineEditBinding;
270 friend struct detail::LineEditValidationAccess;
271 friend struct detail::LineEditSourceAccess;
272 friend class ManagedScene;
273 friend struct ui::detail::RefAccess;
274 GraphemeText &editText() noexcept;
275 const GraphemeText &editText() const noexcept;
276 std::unique_ptr<GraphemeText> &editMask() noexcept;
277 const std::unique_ptr<GraphemeText> &editMask() const noexcept;
278 std::size_t &editCursor() noexcept;
279 std::size_t editCursor() const noexcept;
280 std::size_t &editAnchor() noexcept;
281 std::size_t editAnchor() const noexcept;
282 std::int32_t &editScroll() noexcept;
283 std::int32_t editScroll() const noexcept;
284 bool &editDirty() noexcept;
285 bool editDirty() const noexcept;
286 void revealCursor();
287 std::int32_t cellAt(std::size_t byte) const;
288 LineEditOptions options_;
289 std::shared_ptr<detail::LineEditValidationGate> validationGate_;
290 GraphemeText text_;
291 std::unique_ptr<GraphemeText> placeholder_;
292 std::unique_ptr<GraphemeText> masked_;
293 CellRect bounds_;
294 std::size_t cursor_{};
295 std::size_t anchor_{};
296 std::int32_t scroll_{};
297 bool dirty_{};
298 bool focused_{};
299 bool enabled_{true};
300};
301
309public:
321 LineEditBinding(const LineEditBinding &) = delete;
322 LineEditBinding &operator=(const LineEditBinding &) = delete;
329 std::expected<void, TreeError> sync(Node<Widget> focused);
330
334
335 std::expected<void, TreeError> undo();
336
338
339 std::expected<void, TreeError> redo();
340
346 std::expected<void, TreeError> clear();
347
349
350 std::expected<void, TreeError> stopGrouping();
351
353
354 std::expected<HistoryAvailability, TreeError> historyAvailability() const;
355
357 bool canUndo() const;
358
360 bool canRedo() const;
361
362private:
363 friend struct detail::LineEditValidationAccess;
364 friend struct detail::LineEditSourceAccess;
365 friend struct ui::detail::RefAccess;
366 friend struct ui::detail::Access;
367 std::expected<std::uint64_t, TreeError> draftRevision() const;
368 std::expected<std::shared_ptr<const PropertyChange<std::string>>, TreeError> modelSnapshot() const;
369
370 friend class ManagedScene;
371 std::expected<void, TreeError> setDraft(GraphemeText text, std::uint64_t revision,
372
373 std::optional<ProgrammaticChange> change = {},
374 LineEditResult *receipt = nullptr);
375
376 void commandFeedback(std::shared_ptr<detail::EditorCommandFeedback> feedback);
377 std::pair<std::expected<void, TreeError>, bool>
378 historyCommand(bool redo, std::source_location origin = std::source_location::current());
379 std::pair<std::expected<void, TreeError>, bool> clearCommand(std::source_location origin);
380 std::pair<std::expected<void, TreeError>, bool> editorCommand(bool redo, bool clear, std::source_location origin);
381 struct State;
382 friend std::expected<LineEditBinding, TreeError>
384 std::function<void(LineEditResult)>, std::shared_ptr<Clipboard>,
385 std::function<bool(std::string_view)>, LineEditEvents);
386 LineEditBinding(std::shared_ptr<State> state, ActionBinding action, Subscription subscription);
387 std::shared_ptr<State> state_;
388 ActionBinding action_;
389 Subscription subscription_;
390};
391
417std::expected<LineEditBinding, TreeError> bindLineEdit(WidgetTree &tree, EventRouter &router, Node<LineEdit> node,
418 std::shared_ptr<Property<std::string>> model,
419 std::function<void(LineEditResult)> result,
420 std::shared_ptr<Clipboard> clipboard = {},
421 std::function<bool(std::string_view)> validate = {});
422
426std::expected<LineEditBinding, TreeError>
428 std::shared_ptr<Property<std::string>> model, std::function<void(LineEditResult)> result,
429 std::shared_ptr<Clipboard> clipboard, std::function<bool(std::string_view)> validate,
430 LineEditEvents events);
431} // namespace portals
Move-only scoped disconnect token; never owns a tree or widget. Disconnect/destruction may run on any...
Definition action.hpp:96
An owning, invariant-preserving half-open cell rectangle.
Definition geometry.hpp:81
Injected UI clipboard boundary; called only from input handling, never from a frame....
Definition line_edit.hpp:158
virtual ~Clipboard()=default
Release the service on the UI owner after admitted calls finish.
virtual std::expected< void, TreeError > write(std::string_view bytes)=0
Copy selected bytes into the service.
virtual std::expected< std::string, TreeError > read(std::size_t maxBytes)=0
Obtain an owning bounded payload.
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
~LineEditBinding()
Disconnect subscription/action; admitted calls retain their owners.
std::expected< void, TreeError > sync(Node< Widget > focused)
Synchronize latest clean model and focus presentation between frames.
std::expected< void, TreeError > redo()
std::expected< void, TreeError > clear()
Clear a writable eligible editor as one separate user edit, applying its EditMode.
std::expected< HistoryAvailability, TreeError > historyAvailability() const
friend std::expected< LineEditBinding, TreeError > bindLineEditWithEvents(WidgetTree &, EventRouter &, Node< LineEdit >, std::shared_ptr< Property< std::string > >, std::function< void(LineEditResult)>, std::shared_ptr< Clipboard >, std::function< bool(std::string_view)>, LineEditEvents)
Bind a one-line editor and adopt its initial model on UI outside frames.
std::expected< void, TreeError > undo()
LineEditBinding & operator=(LineEditBinding &&other) noexcept
Install replacement before retiring old captures, which may reenter UI.
LineEditBinding(LineEditBinding &&other) noexcept
Transfer ownership on UI.
std::expected< void, TreeError > stopGrouping()
bool dirty() const
Inspect whether visible text awaits successful publication or cancellation.
~LineEdit() override
Notify an optional weak validation gate after widget borrows drain; cancellation never joins.
LineEdit(LineEdit &&other)=default
Preserve owning movement before attachment; attached widgets remain stationary.
LineEdit(LineEditOptions options, SizePolicy policy, detail::LineEditPlaceholder placeholder)
Internal prepared-presentation construction used by checked recipes.
LineEdit(LineEditOptions options={}, SizePolicy policy=DEFAULT_EDITOR_POLICY)
Construct an empty editor; binding adopts its initial model snapshot.
LineEdit & operator=(LineEdit &&other)=default
std::expected< void, TreeError > arrange(CellRect local) override
Store local bounds and scroll by whole graphemes to expose the caret.
const GraphemeText & text() const
Borrow validated draft only inside tree.read.
ComputedStyle styleDefaults() const override
std::expected< CellSize, TreeError > measure(CellSize available) override
Measure displayed content plus one caret cell; NO_ECHO always measures one cell.
std::expected< void, TreeError > paint(PaintContext &context) override
Submit bounded local commands; software caret and selection never split a grapheme.
std::size_t anchor() const
Inspect the fixed selection endpoint.
std::size_t cursor() const
Inspect the active selection endpoint.
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
Exclusive parent/child ownership on Scheduler's UI thread. Scheduler must outlive this object....
Definition widget.hpp:179
Public Portals API.
Definition action.hpp:8
@ PENDING
Complete or abandon the owning session before submitting another frame.
Definition diff.hpp:108
LineEditDisplayMode
Immutable presentation and outbound clipboard policy; plaintext model/history remain application-owne...
Definition line_edit.hpp:34
@ NORMAL
Render the draft using its actual grapheme widths; copying and cutting retain normal behavior.
Definition line_edit.hpp:35
@ NO_ECHO
Render no value or selection, with a fixed-origin caret and intrinsic width one; suppress copy/cut.
Definition line_edit.hpp:37
@ PASSWORD
Render one ASCII '*' per grapheme, revealing its count; suppress outbound copy/cut.
Definition line_edit.hpp:36
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
@ EXPLICIT
Preserve low-level overlapping cells in sibling paint/input order.
Definition grid.hpp:60
@ FAILED
The coroutine returned an error or threw.
Definition async.hpp:46
constexpr SizePolicy DEFAULT_EDITOR_POLICY
Single-line editors retain one cell even during shortage; text length is not a flex basis.
Definition layout.hpp:50
@ INVALID_TEXT
Projected row is not admitted UTF-8 under the scene text policy.
Definition find_bar.hpp:53
AsyncError
Failures of the optional single-frame UI coroutine adapter.
Definition async.hpp:25
@ CANCELLED
Explicit cancellation or replacement stopped the invocation.
Definition async.hpp:29
BackgroundError
Executor admission and startup failures; domain errors stay in the result value.
Definition background_options.hpp:11
@ LIMIT_EXCEEDED
A storage request cannot fit its configured aggregate budget.
Definition background_options.hpp:19
LineEditStatus
Observable editing or service outcome; rejection preserves the draft.
Definition line_edit.hpp:81
@ CLIPBOARD_FAILED
The injected service was absent or rejected the operation.
Definition line_edit.hpp:90
@ COMMITTED
Confirmation completed Property::set; inspect its exact receipt.
Definition line_edit.hpp:83
@ EDITED
A local draft or selection changed.
Definition line_edit.hpp:82
@ VALIDATION_FAILED
The commit validator rejected the complete draft.
Definition line_edit.hpp:89
@ CONFLICT
The model revision changed since this draft began.
Definition line_edit.hpp:86
@ COPIED
Selected bytes were accepted by the clipboard service.
Definition line_edit.hpp:85
constexpr std::size_t LINE_EDIT_REDO_CHORD_COUNT
Number of independently configurable Redo aliases.
Definition line_edit.hpp:54
EditingFinishedReason
Boundary at which the user finishes an editing operation.
Definition line_edit.hpp:122
@ ENTER
Enter or the equivalent Action::ACTIVATE command.
Definition line_edit.hpp:123
@ FOCUS_LOST
Synchronous loss of this editor's focus.
Definition line_edit.hpp:124
EditingFinishedOutcome
Outcome of the existing publication policy at an editing boundary.
Definition line_edit.hpp:128
@ UNCHANGED
An equal set succeeded, or a clean editor lost focus without attempting publication.
Definition line_edit.hpp:130
@ VALIDATION_REJECTED
The existing validator rejected the retained draft.
Definition line_edit.hpp:132
@ APPLIED
Property::set changed the committed model value.
Definition line_edit.hpp:129
@ DEFERRED
Focus loss retained a dirty draft without attempting publication in this mode.
Definition line_edit.hpp:131
std::expected< LineEditBinding, TreeError > bindLineEdit(WidgetTree &tree, EventRouter &router, Node< LineEdit > node, std::shared_ptr< Property< std::string > > model, std::function< void(LineEditResult)> result, std::shared_ptr< Clipboard > clipboard={}, std::function< bool(std::string_view)> validate={})
Bind a one-line editor and adopt its initial model on UI outside frames.
LineEditTrigger
Entry path that produced an editing or confirmation outcome.
Definition line_edit.hpp:96
@ FLUENT
Accepted fluent text mutation.
Definition line_edit.hpp:98
@ ASYNC_VALIDATION
Final result of an earlier asynchronous publication intent; no synthetic input event.
Definition line_edit.hpp:100
@ INPUT
Routed input or programmatic activation.
Definition line_edit.hpp:97
@ BLUR
Confirmation on synchronous focus loss.
Definition line_edit.hpp:99
std::expected< LineEditBinding, TreeError > bindLineEditWithEvents(WidgetTree &tree, EventRouter &router, Node< LineEdit > node, std::shared_ptr< Property< std::string > > model, std::function< void(LineEditResult)> result, std::shared_ptr< Clipboard > clipboard, std::function< bool(std::string_view)> validate, LineEditEvents events)
Bind a one-line editor and adopt its initial model on UI outside frames.
InputKey
Semantic key identities; character uses KeyEvent::scalar.
Definition input.hpp:64
@ CHARACTER
Character key identified by KeyEvent::scalar; VT uses this for control combinations.
Definition input.hpp:65
ProgrammaticChange
History policy of an explicit programmatic text change.
Definition line_edit.hpp:41
@ RESET_BASELINE
Discard history after accepting this baseline, even when bytes are equal.
Definition line_edit.hpp:43
@ RECORD
Record one separate reversible operation; equal text preserves Redo.
Definition line_edit.hpp:42
@ INPUT
Read, decode and enqueue terminal input or resize events.
Definition application.hpp:18
TreeError
Checked tree failures; rejected operations never start the requested callback.
Definition widget_types.hpp:26
@ NORMAL
Unclassified source and whitespace.
Definition document_highlight_types.hpp:53
EditMode
When an accepted editing candidate is validated and published to its model.
Definition line_edit.hpp:27
@ ON_COMPLETION
Keep a draft until Enter, programmatic activation or focus loss.
Definition line_edit.hpp:29
@ IMMEDIATE
Publish each semantic-valid text change; invalid intermediate text remains visible.
Definition line_edit.hpp:28
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 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
Owning completion observation; does not perform another validation or model update.
Definition line_edit.hpp:139
EditingFinishedReason reason
Independent completion boundary.
Definition line_edit.hpp:140
EditingFinishedOutcome outcome
Publication policy outcome.
Definition line_edit.hpp:141
std::optional< LineEditResult > result
Exact attempted operation, absent when blur performed no attempt.
Definition line_edit.hpp:142
Owning exact editor shortcut; only identities surviving router key translation are accepted.
Definition line_edit.hpp:47
char32_t scalar
Valid Unicode scalar for CHARACTER; zero for other keys.
Definition line_edit.hpp:49
InputModifiers modifiers
Exact modifiers; ASCII character case is normalized.
Definition line_edit.hpp:50
InputKey key
CHARACTER, INSERT, PAGE_UP/DOWN or F1 through F12.
Definition line_edit.hpp:48
Effective history commands available without adopting a model revision or changing presentation.
Definition line_edit.hpp:65
bool canUndo
Enabled writable live editor has an Undo operation and an unchanged external baseline.
Definition line_edit.hpp:66
bool canRedo
Enabled writable live editor has a Redo operation and an unchanged external baseline.
Definition line_edit.hpp:67
Observed modifiers, also usable by a native input adapter.
Definition input.hpp:34
Optional owning UI callbacks delivered after the legacy result, while the node remains live....
Definition line_edit.hpp:149
std::function< void(const TextEditedEvent &)> textEdited
Actual accepted user byte changes only.
Definition line_edit.hpp:150
std::function< void(const EditingFinishedEvent &)> editingFinished
Enter and focus-loss boundaries in every mode.
Definition line_edit.hpp:151
Fixed-size owning shortcuts; nullopt disables an individual binding.
Definition line_edit.hpp:57
std::optional< EditorChord > undo
Default Ctrl+Z.
Definition line_edit.hpp:58
std::array< std::optional< EditorChord >, LINE_EDIT_REDO_CHORD_COUNT > redo
Ctrl+Y and Ctrl+Shift+Z.
Definition line_edit.hpp:59
Owning bounds and appearances for a one-line editor.
Definition line_edit.hpp:175
WidthPolicy widthPolicy
Immutable cell-width policy for this editor.
Definition line_edit.hpp:177
ControlStyle style
Normal, focused and disabled appearance.
Definition line_edit.hpp:178
TextLimits limits
Whole draft limits, never silent truncation.
Definition line_edit.hpp:176
CellStyle cursor
Software caret cell; whole wide glyph when it fits.
Definition line_edit.hpp:180
EditMode editMode
Confirmation policy shared by input, paste and fluent text edits.
Definition line_edit.hpp:181
bool readOnly
User edits and history commands are blocked; explicit programmatic text changes remain allowed.
Definition line_edit.hpp:183
TextHistoryOptions history
Enabled by default: 128 combined groups, 1 MiB retained snapshots.
Definition line_edit.hpp:182
ProgrammaticChange programmaticChange
Default fluent mutation history policy.
Definition line_edit.hpp:184
CellStyle selection
Whole selected grapheme appearance.
Definition line_edit.hpp:179
LineEditDisplayMode displayMode
Remount to change this presentation policy.
Definition line_edit.hpp:186
LineEditHistoryShortcuts historyShortcuts
Exact owning Undo/Redo shortcuts, validated at bind.
Definition line_edit.hpp:185
std::optional< std::string > placeholder
Owned single-line UTF-8 shown only for an empty draft, never model data.
Definition line_edit.hpp:188
Exact editing or confirmation result delivered on the UI thread.
Definition line_edit.hpp:104
LineEditTrigger trigger
Entry path; independent of the confirmation status.
Definition line_edit.hpp:108
std::optional< TextError > text
Original candidate/result text error, when present.
Definition line_edit.hpp:111
std::optional< AsyncError > async
Exact asynchronous transport/worker failure, when present.
Definition line_edit.hpp:109
const char * operation
Static library operation label; never borrows user message storage.
Definition line_edit.hpp:112
std::optional< PropertyUpdate< std::string > > commit
Exact successful set receipt, including notification loss.
Definition line_edit.hpp:106
std::optional< BackgroundError > background
Exact background admission failure, when present.
Definition line_edit.hpp:110
LineEditStatus status
Meaning of this operation.
Definition line_edit.hpp:105
std::optional< TreeError > error
Underlying tree, allocation, callback or clipboard service failure.
Definition line_edit.hpp:107
bool recoverable
Report an asynchronous gate's technical failure without stopping the managed application.
Definition line_edit.hpp:113
Owning independent policies for width and height.
Definition layout.hpp:35
Accepted user text delta, including history commands; owns the exact existing operation result.
Definition line_edit.hpp:117
LineEditResult result
Original result, including semantic rejection after accepting a draft.
Definition line_edit.hpp:118
Configurable bounds and explicit-boundary grouping for text history.
Definition text_history.hpp:22
Owning limits checked without silently truncating input or clusters.
Definition text.hpp:57
Owning deterministic width policy; no font or terminal matching promise.
Definition text.hpp:42
Private admission receipt retained until the managed wrapper reports its own command failure.
Definition line_edit.hpp:72
bool reported
Its exact failure was actually recorded; independent callback errors do not set this flag.
Definition line_edit.hpp:74
bool active
One command is admitted under the existing binding reentry guard.
Definition line_edit.hpp:73
std::string_view operation
Compiler/static-owned command label, without dynamic allocation.
Definition line_edit.hpp:75
std::source_location origin
Public command call site, retained through outcome delivery.
Definition line_edit.hpp:76
Already checked owning placeholder transferred by declarative construction before state publication.
Definition line_edit.hpp:193
std::unique_ptr< GraphemeText > text
Validated under the receiving editor's width policy and limits.
Definition line_edit.hpp:194
Internal bridge for checked access to managed scene and recipe state.
Definition ui_recipe_access.hpp:28