Portals0.7.0 · dev (544a5c68c72e · 2026-11-28 UTC)
Loading...
Searching...
No Matches
Save a navigation position

Русская версия · Model bookmarks · Text anchors

A navigation checkpoint is an owning byte value containing saved locations and their purpose: current item, reading place, selection or edit destination. An application can keep these bytes in memory or pass them to its own storage adapter. The document or collection remains in its original model.

Include <portals/navigation_checkpoint.hpp> and link portals::core. The header is optional and is not included by ui.hpp.

Try two independent openings

The complete application opens the same immutable example text twice. Click Read middle, Save place, then Restore place. The second opening moves to the saved location. Back to start moves only the second opening; restoring again returns it to the saved place. F2 saves, F3 restores, and F10 exits. Restoring before the first save shows a prompt to save a place.

// Copyright (c) 2026 ttldtor.
// SPDX-License-Identifier: BSL-1.0
#include "navigation_checkpoint_provider.hpp"
#include <portals/ui.hpp>
#include <portals/ui_style.hpp>
#include <format>
#include <string>
using namespace portals;
using namespace checkpoint_example;
int main() {
auto original = ui::finiteTextDocument(NOTE);
auto reopened = ui::finiteTextDocument(NOTE);
auto status = ui::model(std::string("Save the reading place, then restore it in the second opening."));
auto marker = [](const ui::TextDocumentValue &value) {
return std::string(value.selection.cursor, ' ') + "^";
};
auto save = [&]() -> std::expected<void, ManagedError> {
auto result = remember(original, saved);
if (result) {
status.value() =
std::format("Saved {} bytes of location metadata. Document text is not included.", saved.bytes().size());
}
return result;
};
auto restore = [&]() -> std::expected<void, ManagedError> {
if (saved.bytes().empty()) {
status.value() = "Save a place first.";
return {};
}
auto result = resume(reopened, saved);
if (result) {
status.value() = "Restored the same place in an independently created document.";
}
return result;
};
// clang-format off
return ui::scene(ui::vbox(LinearOptions{.gap = 1},
ui::vbox(ui::label(original), ui::label(original.source(), marker))
.framed("rounded", "First opening"),
ui::vbox(ui::label(reopened), ui::label(reopened.source(), marker))
.framed("rounded", "Independent opening"),
ui::hbox(LinearOptions{.gap = 1},
ui::button("Read middle", [original] { return seek(original, READING_OFFSET); }),
ui::button("Save place", save),
ui::button("Restore place", restore),
ui::button("Back to start", [reopened] { return seek(reopened, 0); })),
ui::label(status),
ui::label("F2: save place | F3: restore place | F10: quit"))
.maxWidth(84).fitHeight().framed("rounded", "Portable reading place"))
| ui::theme(nordTheme())
| ui::onKey("F2", save)
| ui::onKey("F3", restore)
| ui::onKey("F10 | Ctrl+C", ui::quit)
| ui::runApp();
// clang-format on
}
Immutable owning checkpoint; copies share bytes and never retain providers or UI objects....
Definition navigation_checkpoint.hpp:99
std::span< const std::byte > bytes() const noexcept
Public Portals API.
Definition action.hpp:8
StyleSheet nordTheme()
Owning linear container options.
Definition layout.hpp:193
Owning finite-document presentation; never a window into an arbitrary file.
Definition ui_text_document.hpp:15
Save a reading place and restore it in an independent opening

The program copies and parses the encoded bytes in memory. It does not read or write files and does not persist between process runs. The portable resource key identifies this exact version of the immutable ASCII text. Each opening has its own in-memory resource namespace. The provider translates the saved offset into a bookmark qualified for the receiving opening.

The provider helper is part of the complete program. It validates the exact immutable text and revision before capture or restore. Its one-byte offset codec is specific to this short ASCII document; it is unsuitable for edited text or arbitrary files:

// Copyright (c) 2026 ttldtor.
// SPDX-License-Identifier: BSL-1.0
#pragma once
#include <portals/navigation_checkpoint.hpp>
#include <portals/ui.hpp>
#include <portals/ui_text_document.hpp>
#include <array>
namespace checkpoint_example {
using namespace portals;
// This codec is only for this exact immutable ASCII document, version one.
// Changing its contents requires a new portable resource key and a migration policy.
inline constexpr std::string_view NOTE = "One document. Two openings. The same reading place.";
inline constexpr std::size_t READING_OFFSET = 27;
class NoteCodec final : public NavigationBookmarkCodec {
public:
explicit NoteCodec(ModelResource resource) : resource_(resource) {
}
NavigationCodecDescriptor descriptor() const noexcept override {
return {"example-ascii-offset", 1, "example:immutable-note:v1"};
}
ModelResource resource() const noexcept override {
return resource_;
}
std::expected<std::size_t, NavigationCheckpointError>
encode(const NavigationCheckpointEntry &entry, std::span<std::byte> output, std::stop_token) const override {
const auto point = entry.bookmark.position();
if (point.kind != PositionKind::TEXT || point.revision != 1 || point.offset > NOTE.size()) {
return std::unexpected(NavigationCheckpointError::UNSUPPORTED);
}
if (output.empty()) {
return std::unexpected(NavigationCheckpointError::TOO_LARGE);
}
output.front() = static_cast<std::byte>(point.offset);
return 1;
}
std::expected<ModelBookmark, NavigationCheckpointError> decode(std::span<const std::byte> payload, PositionKind kind,
PositionAffinity affinity, NavigationCheckpointRole,
std::stop_token) const override {
if (kind != PositionKind::TEXT || payload.size() != 1 || std::to_integer<unsigned>(payload.front()) > NOTE.size()) {
return std::unexpected(NavigationCheckpointError::CORRUPT_INPUT);
}
// Every byte boundary in this fixed ASCII document is a grapheme boundary.
return ModelBookmark::create(resource_,
{PositionKind::TEXT, {}, std::to_integer<unsigned>(payload.front()), 1, affinity})
.transform_error([](SourceError error) {
return error == SourceError::NO_MEMORY ? NavigationCheckpointError::NO_MEMORY
: NavigationCheckpointError::CORRUPT_INPUT;
});
}
private:
ModelResource resource_;
};
inline ManagedError commandError(SourceError error) {
return {ManagedPhase::STATE,
{},
error == SourceError::NO_MEMORY ? TreeError::NO_MEMORY : TreeError::INVALID_ARGUMENT,
{},
{}};
}
inline ManagedError commandError(NavigationCheckpointError error) {
return {ManagedPhase::STATE,
{},
error == NavigationCheckpointError::NO_MEMORY ? TreeError::NO_MEMORY : TreeError::INVALID_ARGUMENT,
{},
{}};
}
// The app uses only immutable revision-one documents; no file or source data is exported.
inline std::expected<void, ManagedError> seek(const ui::FiniteTextDocument &note, std::size_t offset) {
auto point = note.bookmark(offset);
if (!point) {
return std::unexpected(commandError(point.error()));
}
return note.restore(*point);
}
inline std::expected<void, ManagedError> remember(const ui::FiniteTextDocument &note, NavigationCheckpoint &saved) {
auto value = note.source().value().snapshot();
if (!value) {
return std::unexpected(value.error());
}
if ((*value)->value.revision != 1 || (*value)->value.text != NOTE) {
return std::unexpected(commandError(NavigationCheckpointError::WRONG_RESOURCE));
}
auto point = note.bookmark((*value)->value.selection.cursor);
if (!point) {
return std::unexpected(commandError(point.error()));
}
const std::array entries{NavigationCheckpointEntry{NavigationCheckpointRole::READING_ANCHOR, *point}};
auto checkpoint = NavigationCheckpoint::capture(entries, NoteCodec(point->resource()));
if (!checkpoint) {
return std::unexpected(commandError(checkpoint.error()));
}
saved = std::move(*checkpoint);
return {};
}
inline std::expected<void, ManagedError> resume(const ui::FiniteTextDocument &note, const NavigationCheckpoint &saved) {
auto value = note.source().value().snapshot();
if (!value) {
return std::unexpected(value.error());
}
if ((*value)->value.revision != 1 || (*value)->value.text != NOTE) {
return std::unexpected(commandError(NavigationCheckpointError::WRONG_RESOURCE));
}
auto origin = note.bookmark(0);
if (!origin) {
return std::unexpected(commandError(origin.error()));
}
// parse copies the bytes as a new owner, as when bytes arrive from application storage.
auto parsed = NavigationCheckpoint::parse(saved.bytes());
if (!parsed) {
return std::unexpected(commandError(parsed.error()));
}
auto positions = parsed->restore(NoteCodec(origin->resource()));
if (!positions) {
return std::unexpected(commandError(positions.error()));
}
if (positions->size() != 1 || positions->front().role != NavigationCheckpointRole::READING_ANCHOR) {
return std::unexpected(commandError(NavigationCheckpointError::CORRUPT_INPUT));
}
return note.restore(positions->front().bookmark);
}
} // namespace checkpoint_example
ModelPosition position() const noexcept
Explicit provider conversion; no generic serializer for process-local RowId/SourceStamp exists....
Definition navigation_checkpoint.hpp:66
Model< TextDocumentValue > source() const
Definition ui_text_document.hpp:120
std::expected< ModelBookmark, SourceError > bookmark(std::size_t offset, PositionAffinity affinity=PositionAffinity::FORWARD) const
Definition ui_text_document.hpp:127
std::expected< void, ManagedError > restore(const ModelBookmark &bookmark) const
Definition ui_text_document.hpp:178
Logical resource namespace, distinct from its current delivery session. Reuse an existing SourceStamp...
Definition model_position.hpp:21
ModelBookmark bookmark
Qualified in-memory position; provider codecs translate its resource identity.
Definition navigation_checkpoint.hpp:22
Provider-issued durable identity; not a path inferred by the checkpoint library.
Definition navigation_checkpoint.hpp:52

Supply the provider conversion

Implement NavigationBookmarkCodec for a model that supports persistence:

Operation Provider responsibility
descriptor() Supply a stable codec name, positive version and portable resource key, including compatible lineage. Keep its strings valid through the outer operation.
resource() Identify the current in-memory resource domain.
encode() Write location metadata into the supplied bounded output span and return the number of bytes written.
decode() Validate payload, kind, affinity and role, then return an owning bookmark in the receiving resource domain.

The library does not infer durable identity from a filename, row ordinal or runtime SourceStamp, RowId or SourceCursor. The provider must translate a stable business key or version-qualified text location into its current model. For text, it must also validate or resolve grapheme boundaries.

NavigationCheckpoint::capture(entries, codec) returns a new immutable envelope. bytes() borrows its encoded bytes while that value or a copy survives. parse(bytes) validates and copies incoming bytes. restore(codec) returns a complete owning vector of locations; it does not apply them to a navigation context. Apply an appropriate successful result through the existing checked navigation or document API, which can still reject a stale or unavailable location. Applying several channels separately does not provide a group transaction.

One checkpoint belongs to one portable resource domain. Save separate checkpoints for unrelated models. Copies share immutable bytes and retain no codec, storage, model, page, scene or widget.

Preserve meaning without granting access

Each NavigationCheckpointEntry carries a NavigationCheckpointRole:

  • CURRENT: current item or caret location.
  • READING_ANCHOR: reading place independent of current selection.
  • SELECTION: one selected location; several entries preserve their declared order.
  • EDIT_ANCHOR: a prospective edit location. Reacquire write capability, field identity and current expected version before submitting a write.

An imported location is not an EditTarget and cannot authorize a commit. A nearest read result does not authorize writing to the neighboring record. The envelope contains no model values, password, draft, Undo/Redo history or credentials by default; provider payloads must follow the same restriction.

Bound memory and handle errors

NavigationCheckpointOptions defaults to 64 KiB of encoded envelope, 128 entries, 4096 provider bytes per entry and 1024 bytes for each codec/resource identity. bookmarks uses the existing 4096-byte charged limit for each decoded bookmark. These limits describe metadata, independently of logical model size.

Capture reserves the configured envelope capacity and stages owning entry copies. Parse retains the actual encoded size; load can temporarily hold a maximum-size read buffer and the parsed value together. Restoring owns an entry vector and its decoded bookmarks. Allocator bookkeeping and memory allocated inside provider callbacks are additional costs; an encoded byte count is not a process-memory peak.

Malformed structure or checksum reports CORRUPT_INPUT; a limit violation reports TOO_LARGE. Unknown envelope and codec versions report UNSUPPORTED_VERSION and UNSUPPORTED_CODEC_VERSION. A mismatched codec name reports UNSUPPORTED_CODEC; a mismatched resource reports WRONG_RESOURCE. Invalid local options or entries report INVALID_ARGUMENT. Storage I/O failures use STORAGE_FAILURE. Providers and storage can report UNSUPPORTED, CLOSED or their typed failures. Cancellation returns CANCELLED; allocation failure returns NO_MEMORY. An unexpected exception from encode, decode, read or write becomes PROVIDER_FAILURE. The descriptor and resource getters are declared noexcept and must not throw. Keep the original checkpoint until a replacement succeeds.

The version-one envelope includes a checksum for accidental corruption. It does not authenticate bytes or make an untrusted provider trustworthy. A structurally valid envelope still needs the correct codec, resource and live resolution.

Use application storage off the UI thread

NavigationCheckpointStorage is an optional synchronous adapter with bounded read(output, stop) and write(bytes, stop) operations. The library installs no filesystem backend or scheduler. A storage read must return one complete encoded record or a typed failure; if the complete record does not fit, return TOO_LARGE rather than a truncated prefix. Invoke loadNavigationCheckpoint and saveNavigationCheckpoint on the application's existing worker path whenever the adapter can block. These functions do not dispatch work or enforce UI affinity.

Keep the codec/storage object alive and serialize operations for their entire call. Check cancellation in blocking provider/storage work. A failed or cancelled load returns no replacement and cannot erase the caller's in-memory position. A failed write also preserves the checkpoint, but external storage may have changed: atomic file replacement and durability belong to the adapter's contract. Apply the restored navigation on the UI thread using its normal live handle.

Encoding and checksum work scale with encoded metadata. Use the worker path for expensive codecs or large configured budgets. The functions stage their own result and do not assign application navigation state; they do not roll back side effects performed explicitly by provider or storage callbacks.