Portals0.7.0 · dev (544a5c68c72e · 2026-11-28 UTC)
Loading...
Searching...
No Matches
ui_text_document.hpp
1// Copyright (c) 2026 ttldtor.
2// SPDX-License-Identifier: BSL-1.0
3#pragma once
4
5#include <portals/text_document.hpp>
6#include <portals/ui_model.hpp>
7
8namespace portals::ui {
12inline constexpr FiniteTextDocumentOptions DEFAULT_FINITE_TEXT_DOCUMENT_OPTIONS{.limits = {4096, 4096, 4096, 8192}};
13
16 std::string text = std::string(0, '\0');
17 std::string target = std::string(0, '\0');
19 std::uint64_t refreshStamp{};
20 std::uint64_t revision{};
21 bool dirty{};
22 bool conflicted{};
23 bool canUndo{};
24 bool canRedo{};
26 bool operator==(const TextDocumentValue &other) const = default;
27};
28
29namespace detail {
31inline TreeError textDocumentCause(TextDocumentError error) noexcept {
32 switch (error) {
43 default:
45 }
46}
47
48struct UiTextDocumentState {
49 std::unique_ptr<portals::FiniteTextDocument> document;
51 std::thread::id owner{std::this_thread::get_id()};
52 NodeId scene;
53 ManagedScene *sceneOwner{};
54 std::weak_ptr<const void> sceneLifetime;
55 std::uint64_t refreshStamp{};
56 TreeError failure{TreeError::INVALID_ARGUMENT};
57 std::optional<TextDocumentError> lastError;
58
59 std::unexpected<ManagedError> error(TreeError cause) const {
60 return std::unexpected(ManagedError{ManagedPhase::TEXT, scene, cause, {}, {}});
61 }
62
63 std::expected<void, ManagedError> check() const {
64 if (owner != std::this_thread::get_id()) {
65 return error(TreeError::WRONG_THREAD);
66 }
67 if (!document) {
68 return error(failure);
69 }
70 if (scene != NodeId{}) {
71 if (sceneLifetime.expired() || Access::modelSceneClosed(*sceneOwner)) {
72 return error(TreeError::CLOSED);
73 }
74 auto current = presentation.snapshot();
75 if (!current) {
76 return error(current.error());
77 }
78 }
79
80 return {};
81 }
82
83 std::shared_ptr<const TextDocumentValue> snapshot() const {
84 auto value = std::make_shared<TextDocumentValue>();
85 value->text.assign(document->text().bytes());
86 value->target.assign(document->saveTarget());
87 value->selection = document->selection();
88 value->revision = document->revision();
89 value->refreshStamp = refreshStamp;
90 value->dirty = document->dirty();
91 value->conflicted = document->conflicted();
92 value->canUndo = document->canUndo();
93 value->canRedo = document->canRedo();
94
95 return value;
96 }
97};
98
100} // namespace detail
101
103FiniteTextDocument finiteTextDocument(std::string_view text, FiniteTextDocumentOptions options);
104
113public:
115 FiniteTextDocument(const FiniteTextDocument &other) = default;
118
121 return source_;
122 }
123
127 std::expected<ModelBookmark, SourceError> bookmark(std::size_t offset,
129 if (!state_ || state_->owner != std::this_thread::get_id() || !state_->document) {
130 return std::unexpected(SourceError::INVALID_ARGUMENT);
131 }
132
133 return state_->document->bookmark(offset, affinity);
134 }
135
140 std::expected<void, ManagedError> replace(std::size_t begin, std::size_t end, std::string_view text) const {
141 return apply([&](auto &document) {
142 return document.replace(begin, end, text);
143 });
144 }
145
149 std::expected<void, ManagedError> insert(std::size_t offset, std::string_view text) const {
150 return replace(offset, offset, text);
151 }
152
156 std::expected<void, ManagedError> undo() const {
157 return apply(
158 [](auto &document) {
159 return document.undo();
160 },
161 true);
162 }
163
167 std::expected<void, ManagedError> redo() const {
168 return apply(
169 [](auto &document) {
170 return document.redo();
171 },
172 true);
173 }
174
178 std::expected<void, ManagedError> restore(const ModelBookmark &bookmark) const {
179 return apply([&](auto &document) -> std::expected<void, TextDocumentError> {
180 PositionRequest request{document.session(), document.revision(), 1, bookmark};
181 auto resolved = document.resolve(request);
182 if (!resolved ||
183 (resolved->state != PositionResolution::EXACT && resolved->state != PositionResolution::NEAREST)) {
184 return std::unexpected(TextDocumentError::STALE);
185 }
186 const auto offset = static_cast<std::size_t>(resolved->position.offset);
187
188 return document.setSelection({offset, offset});
189 });
190 }
191
195 std::expected<void, ManagedError> restore(const std::expected<ModelBookmark, SourceError> &bookmark) const {
196 if (!bookmark) {
198 }
199
200 return restore(*bookmark);
201 }
202
206 std::expected<TextSaveTicket, ManagedError> beginSave(std::string_view target) const {
207 auto state = state_;
208 auto valid = state ? state->check() : std::expected<void, ManagedError>(failure(TreeError::NO_MEMORY));
209 if (!valid) {
210 return std::unexpected(valid.error());
211 }
212 auto ticket = state->document->beginSave(target);
213 if (!ticket) {
214 state->lastError = ticket.error();
215 return state->error(detail::textDocumentCause(ticket.error()));
216 }
217
218 return *ticket;
219 }
220
224 std::expected<void, ManagedError> acknowledgeSave(const TextSaveTicket &ticket) const {
225 return apply([&](auto &document) {
226 return document.acknowledgeSave(ticket);
227 });
228 }
229
233 std::expected<void, ManagedError> acknowledgeSave(const std::expected<TextSaveTicket, ManagedError> &ticket) const {
234 return ticket ? acknowledgeSave(*ticket) : std::expected<void, ManagedError>(std::unexpected(ticket.error()));
235 }
236
241 std::expected<void, ManagedError> savepoint(std::string_view target) const {
242 return acknowledgeSave(beginSave(target));
243 }
244
246 std::optional<TextDocumentError> lastError() const {
247 return state_ && state_->owner == std::this_thread::get_id() ? state_->lastError : std::nullopt;
248 }
249
253 std::expected<void, ManagedError> refresh() const {
254 return apply(
255 [](auto &) -> std::expected<void, TextDocumentError> {
256 return {};
257 },
258 false, true);
259 }
260
261private:
262 friend FiniteTextDocument finiteTextDocument(std::string_view, FiniteTextDocumentOptions);
263
264 FiniteTextDocument(std::shared_ptr<detail::UiTextDocumentState> state, Model<TextDocumentValue> source)
265 : state_(std::move(state)), source_(std::move(source)) {
266 }
267
268 std::unexpected<ManagedError> failure(TreeError cause) const {
269 return std::unexpected(ManagedError{ManagedPhase::TEXT, {}, cause, {}, {}});
270 }
271
272 template <class Operation>
273 std::expected<void, ManagedError> apply(Operation operation, bool emptyIsNoop = false,
274 bool forcePublication = false) const {
275 auto state = state_; // Pin the core and callable's owners across presentation callbacks.
276 if (!state) {
277 return failure(TreeError::NO_MEMORY);
278 }
279 auto valid = state->check();
280 if (!valid) {
281 return valid;
282 }
283 if (forcePublication && state->refreshStamp == std::numeric_limits<std::uint64_t>::max()) {
284 return state->error(TreeError::IDENTITY_EXHAUSTED);
285 }
286 try {
287 auto changed = operation(*state->document);
288 if (!changed && !(emptyIsNoop && changed.error() == TextDocumentError::EMPTY)) {
289 state->lastError = changed.error();
290 return state->error(detail::textDocumentCause(changed.error()));
291 }
292 state->lastError.reset();
293 if (forcePublication) {
294 ++state->refreshStamp;
295 }
296 if (state->scene != NodeId{}) {
297 auto value = state->snapshot();
298 auto published = state->presentation.set(*value);
299 if (!published) {
300 return state->error(published.error());
301 }
302 if (published->notification_error) {
303 ManagedError failure{ManagedPhase::TEXT, state->scene, TreeError::WOULD_BLOCK, {}, {}};
304 failure.application = ApplicationError{ApplicationPhase::DISPATCH, *published->notification_error, {}, {}};
305
306 return std::unexpected(failure);
307 }
308 }
309
310 return {};
311 } catch (const std::bad_alloc &) {
312 return state->error(TreeError::NO_MEMORY);
313 } catch (...) {
314 return state->error(TreeError::CALLBACK_FAILED);
315 }
316 }
317
318 std::shared_ptr<detail::UiTextDocumentState> state_;
319 Model<TextDocumentValue> source_;
320};
321
327inline FiniteTextDocument finiteTextDocument(std::string_view text,
328 FiniteTextDocumentOptions options = DEFAULT_FINITE_TEXT_DOCUMENT_OPTIONS) {
329 std::shared_ptr<detail::UiTextDocumentState> state;
330 try {
331 state = std::make_shared<detail::UiTextDocumentState>();
332 auto created = portals::FiniteTextDocument::create(text, options);
333 if (created) {
334 state->document = std::move(*created);
335 } else {
336 state->failure = detail::textDocumentCause(created.error());
337 state->lastError = created.error();
338 }
339 auto source = detail::ValueModelAccess::deferred<TextDocumentValue>(
340 [state](ManagedScene &scene,
342 auto valid = state->check();
343 if (!valid) {
344 return std::unexpected(valid.error());
345 }
346 auto value = state->snapshot();
347 auto handle = detail::Access::createValueState(scene, *value);
348 if (!handle) {
349 return std::unexpected(handle.error());
350 }
351 const auto owner = detail::Access::lifetime(scene);
352 try {
353 context.rollback.emplace_back([state, &scene, owner, handle = *handle]() mutable {
354 state->presentation = {};
355 state->scene = {};
356 state->sceneOwner = nullptr;
357 state->sceneLifetime.reset();
358 if (!owner.expired()) {
359 detail::Access::retireValueState(scene, handle);
360 }
361 });
362 } catch (...) {
363 detail::Access::retireValueState(scene, *handle);
364 throw;
365 }
366 state->presentation = *handle;
367 state->scene = scene.root().id();
368 state->sceneOwner = &scene;
369 state->sceneLifetime = owner;
370
371 return *handle;
372 });
373
374 return FiniteTextDocument(std::move(state), std::move(source));
375 } catch (const std::bad_alloc &) {
376 return FiniteTextDocument({}, detail::ModelAccess::failed<TextDocumentValue>(TreeError::NO_MEMORY));
377 } catch (...) {
378 return FiniteTextDocument({}, detail::ModelAccess::failed<TextDocumentValue>(TreeError::CALLBACK_FAILED));
379 }
380}
381
383inline Description<Label> label(const FiniteTextDocument &document) {
384 return label(document.source(), [](const TextDocumentValue &value) {
385 return value.text;
386 });
387}
388} // namespace portals::ui
static std::expected< std::unique_ptr< FiniteTextDocument >, TextDocumentError > create(std::string_view text, FiniteTextDocumentOptions options={})
Additive lifecycle owner over one existing Application subtree. UI affine and nonmovable....
Definition managed.hpp:530
Weak UI handle to a scene-owned Property, never an owning alias. Copies and destruction of the handle...
Definition managed.hpp:367
std::expected< std::shared_ptr< const PropertyChange< T > >, TreeError > snapshot() const
Definition managed.hpp:399
Copyable bookmark owning metadata only; never retains model, snapshot, view or page....
Definition model_position.hpp:66
Owning save acknowledgement qualification; retains target metadata, never document bytes....
Definition text_document.hpp:120
Single-use owning construction recipe; no mounted widget ownership.
Definition ui_description.hpp:48
Copyable UI-affine finite document using the existing read-only scalar binding runtime....
Definition ui_text_document.hpp:112
Model< TextDocumentValue > source() const
Definition ui_text_document.hpp:120
std::expected< void, ManagedError > replace(std::size_t begin, std::size_t end, std::string_view text) const
Definition ui_text_document.hpp:140
std::optional< TextDocumentError > lastError() const
Definition ui_text_document.hpp:246
std::expected< void, ManagedError > acknowledgeSave(const std::expected< TextSaveTicket, ManagedError > &ticket) const
Definition ui_text_document.hpp:233
std::expected< void, ManagedError > refresh() const
Retry presentation after a prior notification failure; does not edit content.
Definition ui_text_document.hpp:253
std::expected< void, ManagedError > undo() const
Undo through the existing document history; empty history is a UI no-op.
Definition ui_text_document.hpp:156
std::expected< ModelBookmark, SourceError > bookmark(std::size_t offset, PositionAffinity affinity=PositionAffinity::FORWARD) const
Definition ui_text_document.hpp:127
FiniteTextDocument & operator=(const FiniteTextDocument &other)=default
std::expected< void, ManagedError > acknowledgeSave(const TextSaveTicket &ticket) const
Definition ui_text_document.hpp:224
std::expected< TextSaveTicket, ManagedError > beginSave(std::string_view target) const
Definition ui_text_document.hpp:206
std::expected< void, ManagedError > restore(const std::expected< ModelBookmark, SourceError > &bookmark) const
Definition ui_text_document.hpp:195
std::expected< void, ManagedError > redo() const
Redo through existing history; empty history is a UI no-op.
Definition ui_text_document.hpp:167
std::expected< void, ManagedError > insert(std::size_t offset, std::string_view text) const
Definition ui_text_document.hpp:149
std::expected< void, ManagedError > savepoint(std::string_view target) const
Mark the current in-memory content saved; performs no physical write.
Definition ui_text_document.hpp:241
std::expected< void, ManagedError > restore(const ModelBookmark &bookmark) const
Definition ui_text_document.hpp:178
FiniteTextDocument(const FiniteTextDocument &other)=default
friend FiniteTextDocument finiteTextDocument(std::string_view, FiniteTextDocumentOptions)
Declare one finite in-memory document with a cold read-only presentation source.
Definition ui_text_document.hpp:327
Owning cold model declaration; copies share one single-scene registration. Construction does not read...
Definition ui_model.hpp:129
PositionAffinity
Preferred surviving side when a position is deleted or text is inserted beside a mark.
Definition model_position.hpp:42
@ FORWARD
Prefer the following item; an end boundary falls back to the preceding item.
Definition model_position.hpp:43
TextDocumentError
Finite document error; rejected operations preserve published state.
Definition text_document.hpp:88
@ STALE
Receipt belongs to another document or superseded save request.
Definition text_document.hpp:95
@ WOULD_BLOCK
One history operation exceeds its finite retention budget.
Definition text_document.hpp:93
@ EMPTY
No Undo/Redo is available.
Definition text_document.hpp:94
@ EXHAUSTED
A monotonic counter cannot advance.
Definition text_document.hpp:96
@ CONFLICT
External content was reported; explicit replacement acceptance is required.
Definition text_document.hpp:97
@ NO_MEMORY
Allocation/representation failure.
Definition text_document.hpp:89
@ NEAREST
The original item was removed; a declared surviving neighbor was selected.
Definition model_position.hpp:125
@ EXACT
The same item or a proven mapped gap/mark is present.
Definition model_position.hpp:124
@ TEXT
Read or mutate a fluent caption/editor draft through a checked observing reference.
Definition managed_diagnostics.hpp:57
@ INVALID_ARGUMENT
Invalid options, enum, identity or command shape.
Definition source_budget.hpp:15
@ NO_MEMORY
Allocation failed inside a fallible operation.
Definition source_budget.hpp:19
@ 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
@ CALLBACK_FAILED
A user extension or callback threw.
Definition widget_types.hpp:37
@ STALE_NODE
The observed node or model consumer is absent or retired.
Definition widget_types.hpp:30
@ WOULD_BLOCK
The current frame/reentry boundary or finite queue/work budget rejects this operation.
Definition widget_types.hpp:32
@ IDENTITY_EXHAUSTED
A session, generation or revision cannot advance without reuse.
Definition widget_types.hpp:34
@ INVALID_ARGUMENT
An option, enum value or operation argument is invalid.
Definition widget_types.hpp:27
@ NO_MEMORY
Allocation failed inside the operation boundary.
Definition widget_types.hpp:33
Explicit finite-buffer adapter configuration; not a windowed editor.
Definition text_document.hpp:109
Original error plus independent runner/restoration and cleanup failures.
Definition managed_diagnostics.hpp:62
Immutable qualified navigation request; does not start work by itself.
Definition model_position.hpp:134
Byte-boundary selection owned by the document session, independent of a view.
Definition text_document.hpp:101
Owning finite-document presentation; never a window into an arbitrary file.
Definition ui_text_document.hpp:15
bool canRedo
Existing document history has a Redo operation.
Definition ui_text_document.hpp:24
bool operator==(const TextDocumentValue &other) const =default
std::uint64_t refreshStamp
UI retry epoch; not a document revision.
Definition ui_text_document.hpp:19
std::string text
Current complete finite UTF-8 text.
Definition ui_text_document.hpp:16
bool dirty
Current content differs from its savepoint.
Definition ui_text_document.hpp:21
std::string target
Last acknowledged destination metadata; no I/O.
Definition ui_text_document.hpp:17
bool canUndo
Existing document history has an Undo operation.
Definition ui_text_document.hpp:23
std::uint64_t revision
Current text revision, independent of save requests.
Definition ui_text_document.hpp:20
TextSelection selection
Current byte-boundary selection.
Definition ui_text_document.hpp:18
bool conflicted
External replacement awaits explicit resolution.
Definition ui_text_document.hpp:22
static std::weak_ptr< const void > lifetime(ManagedScene &scene)
Definition ui_recipe_access.hpp:539
Stack-owned transaction bookkeeping, discarded after one description mount.
Definition ui_recipe_context.hpp:554
std::vector< portals::detail::MoveOnlyFunction< void()> > rollback
Explicit attempt-owned resources, never numeric checkpoints.
Definition ui_recipe_context.hpp:596