Portals0.7.0 · dev (544a5c68c72e · 2026-11-28 UTC)
Loading...
Searching...
No Matches
DocumentView

Русская версия · LogView · Scroll controls

Use DocumentView to read a text or hexadecimal document without loading its entire contents or a complete logical line. It reads and decodes bounded windows on the application's background executor. The UI paints the last immutable prepared window and remains available for input while a new window is being prepared.

Scroll a document, switch sources and return to the remembered position.

Complete application

Build portals_document_view_example with PORTALS_BUILD_EXAMPLES=ON and run it from the Portals source directory, where README.md and ReleaseNotes.md are present. The buttons switch the same view between both files, refresh its current source, and return to the beginning. Switching back remembers a byte position for each retained source descriptor. F10 or Ctrl+C closes the application through the standard runner.

Complete source

// Copyright (c) 2026 ttldtor.
// SPDX-License-Identifier: BSL-1.0
#include <portals/ui.hpp>
int main() {
using namespace portals;
auto readme = ui::documentFile("README.md");
auto releases = ui::documentFile("ReleaseNotes.md");
// clang-format off
return ui::scene(ui::vbox(
ui::label("Documents | Ctrl+arrows / Alt+wheel: fast | PgUp/PgDn | F10"),
ui::hbox(
ui::button("README").onClick([=] { reader.model(readme); }),
ui::button("Release notes").onClick([=] { reader.model(releases); }),
ui::button("Refresh").onClick([=] { reader.reload(); }),
ui::button("Top").onClick([=] { reader.home(); })),
ui::viewer(reader, readme).fastScroll().lineNumbers().framed("rounded", "Document")))
| ui::theme(nordTheme())
| ui::onKey("F10 | Ctrl+C", ui::quit)
| ui::runApp();
// clang-format on
}
Typed Widget observation; explicit composite specializations reuse their existing weak facades.
Definition ui_ref.hpp:761
bool reload(std::source_location origin=std::source_location::current()) const
Definition ui_ref.hpp:1447
bool home(std::source_location origin=std::source_location::current()) const
Admit a one-shot boundary navigation command.
Definition ui_ref.hpp:1533
bool model(const LogSource &source, std::source_location origin=std::source_location::current()) const
Definition ui_ref.hpp:1089
Public Portals API.
Definition action.hpp:8
StyleSheet nordTheme()

ui::viewer("README.md") is the shortest file-backed form. Keep a ui::Ref<DocumentView> when handlers need to replace its source or change its reading position. ui::documentFile(path) owns the UTF-8 path and performs no file I/O during recipe construction. Keep the same descriptor when switching back to its remembered position.

SQL and Markdown source colors

Build portals_document_highlight_example with PORTALS_BUILD_EXAMPLES=ON and run it from its executable directory. The build copies orders.sql and notes.md beside the executable. Both panes use the ordinary Viewer: Tab changes focus, wheel and PgUp/PgDn navigate, F6 requests exact colors, F7 returns to AUTO, and F10 or Ctrl+C closes the application.

Complete source

// Copyright (c) 2026 ttldtor.
// SPDX-License-Identifier: BSL-1.0
#include <portals/ui.hpp>
#include <portals/ui_style.hpp>
int main() {
using namespace portals;
// clang-format off
return ui::scene(ui::vbox(
ui::label("Source desk | Tab: panel | PgUp/PgDn: scroll | F6: exact | F7: auto | F10: quit"),
ui::hbox(
ui::viewer(sql, "orders.sql").language("mysql").lineNumbers().flex(1)
.framed("rounded", "SQL dump"),
ui::viewer(markdown, "notes.md").language("markdown").flex(1)
.framed("rounded", "Markdown source")).flex(1)))
| ui::theme(nordTheme())
| ui::onKey("F6", [sql, markdown] {
markdown.syntax(syntax::EXACT);
})
| ui::onKey("F7", [sql, markdown] {
markdown.syntax(syntax::AUTO);
})
| ui::onKey("F10 | Ctrl+C", ui::quit)
| ui::runApp();
// clang-format on
}
bool syntax(DocumentSyntaxPolicy policy, std::source_location origin=std::source_location::current()) const
Definition ui_ref.hpp:1688
constexpr auto EXACT
Explicit full recovery.
Definition document_highlight_types.hpp:48
constexpr auto AUTO
Bounded automatic refinement.
Definition document_highlight_types.hpp:46

Bundled SQL and Markdown inputs

-- Orders: a readable MySQL source example.
CREATE TABLE orders (
  id BIGINT PRIMARY KEY,
  city VARCHAR(80),
  amount DECIMAL(10, 2),
  confirmed BOOLEAN DEFAULT FALSE
);

/* A multiline comment retains its color
   when the viewer opens in the middle. */
INSERT INTO orders VALUES
  (1, 'Prague', 129.50, TRUE),
  (2, 'Bratislava', 82.00, FALSE),
  (3, 'Oslo', 319.25, TRUE);

SELECT city, SUM(amount) AS total
FROM orders
WHERE confirmed = TRUE
GROUP BY city
ORDER BY total DESC;

DELIMITER $$
CREATE PROCEDURE order_total(IN requested_id BIGINT)
BEGIN
  SELECT amount FROM orders WHERE id = requested_id;
END$$
DELIMITER ;

-- End of the example.
# Orders notebook

This viewer displays **Markdown source**.
The document stays editable outside the viewer.

## Review checklist

- Read the SQL schema on the left.
- Scroll each document independently.
- Use `Tab` to move keyboard focus.
- Press F10 to close the application.

## Query example

```mysql
SELECT city, SUM(amount) AS total
FROM orders
WHERE confirmed = TRUE
GROUP BY city;
```

## Source, not rendered HTML

Fences, headings and code have semantic colors.
The file is read in bounded windows on workers.
A cold seek shows plain text before exact color.

[Portals documentation](https://ttldtor.github.io/portals/)

## Closing note

The application does not load the whole file.
The selected theme supplies the syntax palette.

SQL and Markdown source colors with independent document navigation.

.language("mysql"), .language("sql") and .language("markdown") select bounded lexical profiles. Names are case-insensitive: postgres, postgresql and sql select PostgreSQL lexical rules; md aliases markdown. An unknown name selects plain text. The typed form accepts DocumentLanguage; .language(DocumentLanguage::PLAIN) disables syntax colors. HEX remains a raw-byte projection.

The Markdown profile colors source headings, punctuation, code spans and fenced regions, including SQL fences. It does not render Markdown as formatted HTML. The SQL profiles recognize lexical structure, not database schemas or query semantics. MySQL support includes bounded delimiter and SQL-mode handling; unsupported constructs and exhausted lexical policies leave readable text with an explicit syntax status.

Reading, decoding and lexical work run on workers. Choosing a language defaults to syntax::AUTO. The view shows a bounded local preview and uses proven exact context when it is available. A ~ suffix beside the position marks provisional colors. Exact replacement changes the colors together and removes the marker, preserving source text and byte anchors.

Policy Behavior
syntax::AUTO Quick local preview, then exact refinement within a bounded additional-read budget.
syntax::PREVIEW Local preview or already known exact colors; no long context scan.
syntax::EXACT Explicitly allow cancellable context computation from a qualified checkpoint or the source origin.

Use .syntax(syntax::EXACT) in a description or handler to request exact colors. .syntax(syntax::AUTO) restores the default policy. The initial AUTO cap is 512 KiB of additional source admission per displayed intent; DocumentViewConfig.maxAutoHighlightBytes changes that positive limit. It is a byte budget, not a wall-clock deadline. Painting or changing a palette does not renew an exhausted attempt.

A preview can misclassify text when the window starts inside a long string, comment or Markdown fence. If the visible fragment lies entirely inside a long comment, the whole window can appear as normal text until exact refinement completes. It is never a proof of enclosing lexical context and never becomes a qualified source checkpoint. Exact means lexical accuracy within the selected profile, not SQL validation or a complete CommonMark renderer. A distant exact request can read a large prefix and take substantial time; navigation supersedes obsolete work. AUTO does not start an unbounded prefix scan.

Source size does not determine resident memory: the view retains bounded windows, optional preview storage and a fixed exact-checkpoint cache, without a complete line or token index.

Customize syntax roles

Built-in themes supply foreground colors for syntax roles. DocumentView retains its normal background when focused. Override individual roles through PSS; changing a palette repaints existing ranges without reading or lexing the source again.

DocumentView {
role-keyword-foreground: #88c0d0;
role-keyword-bold: true;
role-string-foreground: #ebcb8b;
role-comment-foreground: #81a1c1;
}
Role Source meaning Built-in theme value
keyword SQL keyword Accent, bold
number SQL number Heading color
string SQL literal or Markdown code Accent
comment SQL comment Muted
identifier SQL identifier Foreground
operator SQL punctuation/operator Foreground
heading Markdown ATX heading Heading color, bold
markup Markdown delimiters/MySQL client directive Accent

Each role-<name>- prefix supports foreground, background, bold, italic and underline. Background overrides are optional. Ordinary text inherits body; gutter and position retain their existing meanings. Disabled syntax uses the theme's muted foreground without adding italic text.

document.language("md") collects a rejected command in the scene; document.setLanguage("md") returns a checked result. Loaded configuration scenes accept DocumentView { file="notes.md" language="markdown" }.

document.status() reports the requested syntax policy, displayed syntaxAccuracy, highlighting state and optional highlightErrorOffset. Accuracy is NONE, PREVIEW or EXACT. PENDING means exact context is not ready; terminal PREVIEW means bounded automatic refinement stopped with provisional colors; READY requires a fully proven exact projection. UNSUPPORTED_PROFILE, RESOURCE_LIMIT, REPLAY_UNAVAILABLE and UNAVAILABLE describe syntax limitations separately from source errors. Optional refinement failure preserves the readable frame and the accuracy of its actual colors. document.setSyntax(policy) returns a checked result; document.syntax(policy) collects a rejected command in the scene.

For a forward-only source, select the initial language in the description before mounting. Changing to another non-plain profile after attachment returns a checked unsupported-operation error. Disabling colors preserves accepted buffered bytes. History is bounded: reflow that needs bytes outside retained history is not an arbitrary rewind. A source span exceeding the retained-window budget can return PAGE_TOO_LARGE before the next unsafe read; this does not roll back earlier reads of that worker turn or promise automatic recovery of an irreversible source.

Choose a file

Build portals_document_files_example with PORTALS_BUILD_EXAMPLES=ON. Enter a path in the field and choose Open, or press Ctrl+O. F2 selects text, F3 selects hexadecimal bytes, and F5 refreshes the current source. F10 or Ctrl+C closes the application. Opening a source starts background preparation; the UI stays available.

Open README, show a missing-file error, then open release notes. The ring marks an injected mouse click.

Complete source · Build target · Windows manifest

// Copyright (c) 2026 ttldtor.
// SPDX-License-Identifier: BSL-1.0
#include <portals/ui.hpp>
#include <portals/ui_document_search.hpp>
#include <portals/ui_lyra.hpp>
int main(int argc, char **argv) {
using namespace portals;
// clang-format off
constexpr std::string_view HINTS = "Ctrl+O: open path | F2 Text | F3 Hex | F5 refresh | F6 next | Shift+F6 previous | F10 quit";
std::string initialPath = "README.md";
bool help{};
auto cli = ::lyra::cli()
| ::lyra::help(help).description(
"Read a text or binary file in bounded windows. Change the path and choose Open, "
"or press Ctrl+O. Relative paths use the working directory; paths are literal, "
"without environment or home expansion. No file contents are changed. "
"The interactive run temporarily changes terminal modes and restores them on orderly exit. "
"Exit status: 0 for success/help, 2 for invalid CLI, 1 for application failure.")
| ::lyra::arg(initialPath, "file")("Read-only file path (default: README.md)").optional();
return [&] {
auto open = [=]() -> std::expected<void, ManagedError> {
auto selected = path.text().get();
if (!selected) {
return std::unexpected(selected.error());
}
return reader.setModel(ui::documentFile(*selected));
};
return ui::scene(ui::vbox(
ui::hbox(ui::label("File: "), ui::lineEdit(path, initialPath), ui::button("Open").onClick(open)),
ui::findBar(search, reader),
ui::viewer(reader, initialPath).fastScroll().framed("rounded", "Document"),
ui::label(HINTS)))
| ui::theme(nordTheme())
| ui::onKey("Ctrl+O", open)
| ui::onKey("F5", [=] { reader.reload(); })
| ui::onKey("F2", [=] { reader.mode(DocumentViewMode::TEXT); })
| ui::onKey("F3", [=] { reader.mode(DocumentViewMode::HEX); })
| ui::onKey("F6", [=] { search.next(); })
| ui::onKey("Shift+F6", [=] { search.previous(); })
| ui::onKey("F10 | Ctrl+C", ui::quit)
| ui::reportOnError();
}
| ui::runApp(argc, argv, ui::lyra::cli(cli, {.automaticHelp = false, .helpRequested = &help}));
// clang-format on
}
TextProperty text(TextResolver resolver={}, std::source_location origin=std::source_location::current()) const
Definition ui_ref.hpp:1968
std::expected< void, ManagedError > setModel(const LogSource &source, std::source_location origin=std::source_location::current()) const
Definition ui_ref.hpp:1079
bool next(std::source_location origin=std::source_location::current()) const
Definition ui_ref.hpp:2085
bool mode(DocumentViewMode value, std::source_location origin=std::source_location::current()) const
Definition ui_ref.hpp:1592
bool previous(std::source_location origin=std::source_location::current()) const
Definition ui_ref.hpp:2097
std::expected< std::string, ManagedError > get() const
Copy validated UTF-8 text out of the live widget without retaining its storage.
@ HEX
Project raw fixed-width byte rows without decoding.
Definition document_view.hpp:39
@ TEXT
Decode and lay out text using retained text settings.
Definition document_view.hpp:38

The first positional argument supplies the initial path. Without it, the example uses README.md in the current working directory. From the executable directory on Windows, replace the following path with your document:

./portals_document_files_example.exe --help
./portals_document_files_example.exe "C:\logs\session.txt"

On Linux, use the executable name without .exe and a native filesystem path. Help prints the purpose and options without opening the terminal. Exit status is 0 for an orderly exit or help, 2 for a command-line parse error, and 1 for an application failure. A path beginning with - can be a literal filename; a second positional path is a parse error.

Relative paths use the application's working directory. The field accepts the path itself; shell quotes belong to command-line invocation. UTF-8 names, spaces and native absolute paths are supported. Windows extended paths are passed to the filesystem; network paths also depend on the share, permissions and availability. The example does not expand environment variables or ~. Its Windows manifest enables UTF-8 process arguments and long-path support for this executable.

Read failures appear inside the document frame and remain available in DocumentViewStatus::error through checked reader.status() access and the managed diagnostic channel. Correct the path and choose Open to try again. The caption uses the body style and does not become a document row, line number or progress value. Preparing the optional caption can fail under memory pressure; the original typed error still reaches diagnostics.

Each Open creates a source descriptor. Keep a descriptor when returning to its saved reading position; the previous example shows retained sources.

Reading and navigation

Input Result
Up / Down, mouse wheel Move through prepared visual rows.
PageUp / PageDown Move by a viewport with the configured overlap.
Home Request byte zero.
End Request the last full page; preparation can remain pending while the source is scanned.
Left / Right with wrapping disabled Move the horizontal cell window.
Vertical scrollbar Request a byte position when an exact byte extent is known.
F5 Refresh the current source.

The wheel moves one displayed row per normalized step by default. Rapid input accumulates while a window is loading. Pending movements in opposite directions can cancel each other; an attempt to move beyond a confirmed boundary does not create a debt against the next movement. Home, End, scrollbar seeks and source replacement establish a new navigation target. Low-level constructors accept ScrollAreaOptions::wheelStep for another step.

The scrollbar position is an approximate projection of the visible window across a known byte extent; it is not the footer coverage value. Intermediate thumb positions map across the range from byte zero to extent - visibleSpan. This range stays fixed during a drag, and arriving prepared windows do not move the held thumb away from the pointer. Dragging to the maximum endpoint requests the last full page, just like End. For a seekable source with a known exact extent, preparation first proves the encoding at the source origin, then searches backward for enough line boundaries and decodes the resulting suffix on a background worker. It retains a bounded row window without building a complete line index. Logical line numbers in a distant suffix remain unknown. A very long line without a preceding safe boundary can still require substantial background scanning. Sources without the required seeking or extent capabilities keep the cancellable forward path. Explicit seekByte(offset) commands keep the requested original-byte anchor and use bounded local seeks without scanning the entire preceding file.

End prepares intermediate chunks independently of the paint cadence; only the completed window needs the normal layout and rendering path. Managed seekable text-tail jobs reuse their unpublished working state across bounded preparation quanta. Wrapped printable ASCII is processed in spans while preserving the same rows and original byte positions. This bounds retained memory, not cumulative reading: tail preparation can read bytes more than once and may still scan substantial data when logical lines are very long. There is no constant-time EOF guarantee for arbitrary sources.

The footer reports approximate coverage through the original source bytes at the lower edge of the visible content. On the first screen, the percentage can already be greater than zero. It reaches 100.0% only when the final original source byte is visible; decoder read-ahead and decoded UTF-8 size do not count as visible coverage. A clipped right edge of an unwrapped line does not report 100% until the source's final byte is visible. With an unknown extent, the footer shows progress unknown until a visible final byte proves the end; a temporarily waiting provider is not EOF. A terminal line feed does not create an extra empty display row, while actual blank rows in the document remain visible. The original byte anchor and any proven logical line number remain available through reader.status(). Line numbers are optional, disabled by default, and only show counts proven by scanning. Wrapped fragments retain the same logical line number. The 9-cell gutter displays up to seven digits: ? marks an unproven line number and + marks a larger proven number; this display limit does not restrict 64-bit byte positions.

A seekable source can prepare a distant cold seek from a bounded local window without scanning the entire preceding prefix. The encoding decision is reused only when it was proven at the source origin; the requested original-byte anchor is retained. Logical line numbers and totals remain unknown until proven, and reaching local EOF does not establish the document-wide line total. At or beyond a known EOF, a nonempty source shows its available final row or fragment while the requested offset remains at EOF or one byte past it; a terminal line feed does not add an extra display row, while blank rows present in the source remain visible. An empty source remains empty. An empty read at an arbitrary distant offset does not establish EOF. The last prepared frame remains visible during preparation. A source which returns no bytes without final EOF enters a waiting state; call reload() or press F5 when more data becomes available. This control does not poll the file for live append; use file-backed LogView for follow-tail behavior.

Dragging to EOF keeps the final full screen. The marker indicates injected mouse input.

Fast scrolling and paging

Opt in to an eight-row fast step with .fastScroll(). Hold Ctrl with Up/Down, or Alt while scrolling the wheel. Ordinary arrows and wheel retain their one-row default. The fast step is an absolute number of visual rows: .scrollStep(3).fastScroll(8) selects steps of three and eight, rather than multiplying them. Pass other key::Modifier values as the second and third arguments to fastScroll to change its keyboard and wheel modifiers. Additional modifiers do not match.

PageUp/PageDown move by the useful viewport height minus .pageOverlap(rows), with at least one row per page. The default overlap is one row. The useful height excludes the frame and footer. A page command uses the arranged geometry when accepted; resizing does not reinterpret movement already accepted. The fast step does not change page size.

Ordinary wheel, eight-row fast steps, paging with two-row overlap and the final full page. The caption describes approximate injected input.

Complete navigation application, target portals_document_navigation_example:

// Copyright (c) 2026 ttldtor.
// SPDX-License-Identifier: BSL-1.0
#include <portals/ui.hpp>
int main() {
using namespace portals;
// clang-format off
return ui::scene(ui::vbox(
ui::label("Ctrl+arrows / Alt+wheel: fast | PgUp/PgDn: page | F10: quit"),
ui::hbox(
ui::button("Top").onClick([=] { reader.home(); }),
ui::button("Back 8").onClick([=] { reader.scroll(-8); }),
ui::button("Previous").onClick([=] { reader.page(-1); }),
ui::button("Next").onClick([=] { reader.page(1); }),
ui::button("End").onClick([=] { reader.end(); })),
ui::viewer(reader, "README.md").fastScroll().pageOverlap(2).framed("rounded", "Document")))
| ui::theme(nordTheme())
| ui::onKey("F10 | Ctrl+C", ui::quit)
| ui::runApp();
// clang-format on
}
bool end(std::source_location origin=std::source_location::current()) const
Admit a one-shot boundary navigation command.
Definition ui_ref.hpp:1562
bool page(std::int64_t pages, std::source_location origin=std::source_location::current()) const
Definition ui_ref.hpp:1504
bool scroll(std::int64_t rows, std::source_location origin=std::source_location::current()) const
Definition ui_ref.hpp:1473

Click inside the document to give it keyboard focus after using a button. The buttons and built-in input use the same navigation admission path. Command admission performs no source I/O. Pending row movements accumulate while preparation runs; opposite movements can cancel, and Home/End replace the relative target. Source replacement and cancellation keep their existing behavior.

A nonzero page command before usable geometry is arranged returns WOULD_BLOCK through the checked/collected error mechanism. Built-in PageUp/PageDown input is consumed without movement when the arranged body has zero width or height. Zero row/page commands still validate their reference and thread, then succeed without movement or redraw. Overflow is rejected before changing pending movement. Input respects disabled and read-only navigation settings; programmatic commands retain the same convention as seekByte and can move the view independently of those input restrictions.

The terminal may intercept shortcuts: Windows Terminal uses Ctrl+wheel for font zoom. The separate default Alt wheel modifier avoids choosing that shortcut for fast scrolling; Portals cannot override a host shortcut that is not forwarded. Buttons and custom ui::onKey handlers can call the same Ref commands.

Hexadecimal view

Use .hex() to inspect the original bytes in the same viewer. Each row contains a hexadecimal byte offset, grouped hexadecimal bytes and a safe character column. The character column shows printable ASCII; other bytes become dots. It does not decode UTF text or execute control sequences. Text decoding options and optional line numbers remain stored for a return to text mode.

Switch a UTF-16LE document between bytes and text, then use wheel, fast scrolling and End.

Complete text/hex application, target portals_document_hex_example:

// Copyright (c) 2026 ttldtor.
// SPDX-License-Identifier: BSL-1.0
#include <portals/ui.hpp>
#include <portals/ui_style.hpp>
int main() {
using namespace portals;
// clang-format off
return ui::scene(
ui::viewer(document, "README.md").hex().fastScroll()
.framed("rounded", "F2 Text | F3 Hex | F10 Quit"))
| ui::theme(nordTheme())
| ui::style(R"pss(
DocumentView {
role-hex-zero-foreground: #7d8797;
role-hex-control-foreground: #e5b567;
role-hex-high-byte-foreground: #b48ead;
}
)pss")
| ui::onKey("F2", [document] { document.mode(DocumentViewMode::TEXT); })
| ui::onKey("F3", [document] { document.mode(DocumentViewMode::HEX); })
| ui::onKey("F10 | Ctrl+C", ui::quit)
| ui::runApp();
// clang-format on
}

F2 selects text and F3 selects hexadecimal view. Both use the same source and requested byte position. The footer still measures the last visible byte against the source extent, so changing the representation can change its percentage without moving the requested anchor. A successful mode change cancels unresolved row movement from the previous representation, rather than interpreting text rows as hex rows. Assigning the existing mode again leaves pending movement intact. Rejected changes preserve the old mode, position, prepared frame, pending movement and palette.

The default is 16 bytes per row, groups of eight, uppercase digits and a visible character column. Fixed-width rows retain their configured byte count in a narrow window; the horizontal scrollbar exposes the remaining columns. .hex({.bytesPerRow = 32, .autoFit = true}) permits fewer byte slots to fit the available width. Resizing or changing row options does not rewrite the requested byte anchor. Empty files and incomplete final rows do not acquire invented bytes.

Option Meaning Default
bytesPerRow Configured byte slots per row, 1–4096 16
groupSize Byte slots per group, 1–4096; a larger group than the row adds no internal gap 8
uppercase Uppercase hexadecimal digits true
showAscii Safe character column true
autoFit Reduce the effective byte count to fit, up to bytesPerRow false

These are row/preparation limits, not file-size limits. Existing frame, work and source-memory budgets still apply. File-backed sources support random byte positions; a forward-only source cannot promise a switch or backward movement that requires bytes it has already discarded. Such unsupported operations return a typed error. Unknown extent stays unknown; the viewer does not scan an entire source to manufacture a percentage or row count.

In TEXT mode, changing HEX options only stores them for a later switch to HEX. It does not read the source, prepare another text frame or cancel pending text navigation.

For a forward-only source, choose the initial mode, bytesPerRow and autoFit in the description before mounting. Once the source is attached, runtime mode changes, and changes to these row settings while HEX is active, currently return a typed unsupported-operation error even when the required bytes remain cached. This is an implementation limit. Grouping, letter case and character-column visibility can change using retained rows. Fixed-grid width/height resizing remains supported. File-backed and other seekable sources support mode changes and all row options.

Command Collected form Checked form
Select representation document.mode(DocumentViewMode::HEX) document.setMode(DocumentViewMode::HEX)
Change row options document.hexOptions(options) document.setHexOptions(options)

Use DocumentViewMode::TEXT to return to text. DocumentViewStatus::mode reports the selected representation; hexadecimal rows are not reported as logical text lines.

Loaded scenes use mode="text" or mode="hex" and an optional hex block with the same five option names. Omitted properties keep their defaults; explicit false remains meaningful.

Complete resource application

// Copyright (c) 2026 ttldtor.
// SPDX-License-Identifier: BSL-1.0
#include <portals/ui.hpp>
int main() {
using namespace portals;
// clang-format off
auto scene = ui::scene(R"scene(
scene {
DocumentView#reader {
file="README.md" mode="hex" fastScroll=8
hex { bytesPerRow=16 groupSize=8 uppercase=true showAscii=true autoFit=true }
frame { enabled=true pattern=ROUNDED title="Hex document" }
}
}
)scene", {.format = ui::SceneResourceFormat::CONFIGURATION});
return scene
| ui::onKey("F10 | Ctrl+C", ui::quit)
| ui::runApp();
// clang-format on
}

Sources and commands

Files are one source family. ui::document(provider, budget) accepts a worker-safe ByteDocumentProvider; ui::document(sharedText) projects existing immutable storage without copying the entire input. A custom provider declares seeking and immutability capabilities and can leave its extent unknown. It must return an exact revision with each accepted read. Replacing a source discards incompatible prepared data; results from cancelled or superseded work cannot replace the active binding.

Operation Collected form Checked form
Move visual rows reader.scroll(rows) reader.scrollRows(rows)
Move pages reader.page(pages) reader.scrollPages(pages)
Beginning / final full page reader.home() / reader.end() reader.goHome() / reader.goEnd()
Replace source reader.model(source) reader.setModel(source)
Request original byte position reader.byte(offset) reader.seekByte(offset)
Refresh at the current anchor reader.reload() reader.refresh()
Show or hide line numbers reader.lineNumbers(enabled) reader.setLineNumbers(enabled)
Toggle line numbers reader.toggleLineNumbers() —
Observe cached status without I/O reader.currentStatus() reader.status()

Collected commands report failures through the receiving scene's existing error collector. Checked commands return std::expected and leave error handling to the caller. Admission means the operation was accepted; the requested data may still be preparing. Use these commands on the owning UI thread, for example from a button or key handler. runApp owns the background service and terminal cleanup.

The first version is read-only. It does not provide text selection, clipboard export, editing, search or automatic semantic rebasing over arbitrary external rewrites.

Compressed gzip documents

Enable PORTALS_ENABLE_GZIP=ON when building Portals and link the optional portals::gzip target. Include <portals/ui_gzip.hpp> to use ui::viewer(ui::gzipFile("archive.sql.gz")). The ordinary core build has no gzip runtime dependency. The adapter is bundled for offline builds; an installed consumer needs no separate zlib installation.

find_package(Portals CONFIG REQUIRED COMPONENTS gzip)
target_link_libraries(my_viewer PRIVATE portals::gzip)

Build portals_document_gzip_example with PORTALS_BUILD_EXAMPLES=ON and run it from its executable directory. The build places identical SQL data in plain and gzip form beside the program. F2 selects the original file, F3 selects the compressed archive, and each retained descriptor remembers its reading position. Home and End navigate within the selected logical document. F10 closes the app.

Complete source

// Copyright (c) 2026 ttldtor.
// SPDX-License-Identifier: BSL-1.0
#include <portals/ui.hpp>
#include <portals/ui_gzip.hpp>
#include <portals/ui_style.hpp>
int main() {
using namespace portals;
ui::Ref<Label> selected;
const auto archive = ui::gzipFile("archive.sql.gz");
const auto original = ui::documentFile("archive.sql");
// clang-format off
return ui::scene(ui::vbox(
ui::label("Archive desk | F2: original | F3: gzip | Home/End: first/last page | F10: quit"),
ui::label(selected, "gzip: archive.sql.gz"),
ui::viewer(reader, archive).language("mysql").lineNumbers().flex(1)
.framed("rounded", "Orders")))
| ui::theme(nordTheme())
| ui::onKey("F2", [reader, selected, original] {
reader.model(original);
selected.text() = "Plain: archive.sql";
})
| ui::onKey("F3", [reader, selected, archive] {
reader.model(archive);
selected.text() = "gzip: archive.sql.gz";
})
| ui::onKey("F10 | Ctrl+C", ui::quit)
| ui::runApp();
// clang-format on
}
Read plain and gzip SQL, restore each reading position and reach the final complete page.

The factory owns the path and creates a cold descriptor. Opening, checking the gzip header, decompression and seeking happen on the existing background executor. Gzip selection is explicit: the adapter checks the content and does not infer its format from a filename extension. ui::gzip(provider) adapts an existing seekable byte provider; files are one supported source family.

The view displays decompressed bytes. Until every gzip member and the physical end have been checked, the logical size is unknown; the footer can therefore show progress unknown. The archive's 32-bit ISIZE field is not used as a total size. Concatenated gzip members form one logical document. CRC failures, truncation and trailing garbage produce a source error instead of a clean EOF. An integrity error replaces the visible body with a recoverable error message. Previously prepared data remain retained for recovery; that prefix is not proof that the whole archive passed validation.

The adapter keeps a bounded number of in-memory decompressor checkpoints, including their dictionary and bit state. Backward seeks can replay from an earlier checkpoint or the source origin after eviction. A cold End may decompress the complete archive cumulatively. End first asks the provider to discover the logical extent without laying out the intervening text, then prepares a bounded suffix for the last full page. Discovery validates the complete gzip stream but discards its output, retaining only bounded buffers and restart checkpoints. It can still take substantial time and occupy a worker. Cancellation is checked between bounded input/output quanta; an underlying provider's blocking I/O is subject to that provider's own cancellation contract. DocumentViewConfig.workBytes is not a limit on hidden compressed replay work.

GzipDocumentOptions exposes the input/output capacities, checkpoint spacing and count, replay-buffer size, inflater allocation cap and header-byte cap. Decompressor allocations and retained checkpoints use the same SourceBudget root as the view. There is no temporary-file or persistent disk cache. Reuse one gzip wrapper across views; do not concurrently access its underlying provider through separate wrappers or other owners. Changes to the compressed source invalidate the frozen revision and are reported as REVISION_CHANGED.

Default tuning through GzipDocumentOptions:

Setting Default Purpose
compressedBlockBytes 64 KiB Input quantum; valid range 1–64 KiB.
inflateOutputBytes 32 KiB Maximum output per inflate call before a cancellation check.
checkpointStrideBytes 4 MiB Logical spacing between optional restart snapshots.
maxCheckpoints 8 Resident snapshot count; 0 disables them, maximum 64.
replayBytes 64 KiB Logical-byte replay ring; 0 disables it.
maxInflateBytes 512 KiB Combined live inflater allocation cap, including copied states.
maxHeaderBytes 1 MiB Compressed-byte cap for each gzip member header.

The count and byte limits apply together, so fewer snapshots can be retained. Under memory pressure, idle inflater state and checkpoints can be reclaimed; a later cache miss replays from an available starting point.

Encodings and resource settings

The default UTF-8 hint applies after an explicit encoding or a recognized BOM. Supported decoders are UTF-8, UTF-16LE/BE, UTF-32LE/BE, Windows-1251 and Windows-1252. Select one with .encoding(DocumentEncoding::UTF16LE). .wrap(false) keeps a horizontal cell window; .lineNumbers() enables the gutter. Neither setting changes the original byte anchor.

Replacement decoding is the default. Low-level DocumentViewConfig::decoder also supports strict decoding; a strict failure reports a typed preparation error. A local seek or fast EOF checks the selected decoded region, including the origin needed to determine its encoding; it does not certify an omitted prefix. Terminal control characters are rendered as visible escapes. Ordinary multi-scalar grapheme clusters, including those crossing page boundaries, are preserved. Local restart uses up to 4 KiB of grapheme precontext, in addition to independent decoder lookbehind. An oversized cluster or unprovable bounded grapheme context (for example, a regional-indicator run longer than 4 KiB) is shown as a visible dotted-circle continuation and sets fragmentedCluster. For a leading regional-indicator run, parity remains unproven until a non-regional-indicator resets it, including after a cached near seek. This bounded local projection does not limit logical line length.

The native resource type is DocumentView. In the CONFIGURATION grammar its viewer-specific properties are file (a literal UTF-8 path), lineNumbers, wrap, encoding and language, plus syntax, positive maxAutoHighlightBytes and tailWorkTurns (1–255), followed by fastScroll, fastKeyModifier and fastWheelModifier. A positive fastScroll enables the absolute fast step; modifier names CTRL, ALT and SHIFT are case-insensitive. Existing keyStep and wheelStep together express the scrollStep shorthand, and pageOverlap sets page overlap. The ordinary size, frame and scrollbar properties use the same semantics as their C++ modifiers. They are not accepted as viewer properties on unrelated controls.

Complete resource program

// Copyright (c) 2026 ttldtor.
// SPDX-License-Identifier: BSL-1.0
#include <portals/ui.hpp>
int main() {
using namespace portals;
auto scene = ui::scene(R"scene(
scene {
DocumentView#reader {
file="README.md" lineNumbers=true wrap=true fastScroll=8
frame { enabled=true pattern=ROUNDED title="Document" }
}
}
)scene", {.format = ui::SceneResourceFormat::CONFIGURATION});
return scene
| ui::onKey("F10 | Ctrl+C", ui::quit)
| ui::runApp();
}

Styling reference

The type selector is DocumentView. Text, fill and footer use the normal, :focused, or :disabled appearance. Built-in themes retain the document surface while focused chrome carries the accent; an explicit DocumentView:focused rule can override the text surface. foreground, background, bold, italic and underline use the ordinary style cascade.

Frame patterns, title decoration, arrows, tracks and individual thumb parts use the complete frame and scrollbar styling reference. .framed("rounded", "Document") supplies a title; the one-argument .framed("rounded") selects a pattern, as for other controls.

DocumentView registers three base paint parts: body for document text, gutter for line numbers, and position for the footer. The gutter is visible when .lineNumbers() is enabled. Their five PSS properties are role-<part>-foreground, role-<part>-background, role-<part>-bold, role-<part>-italic, and role-<part>-underline; see the style property reference for values and cascade rules. These parts use the existing theme/application/user cascade. The example installs nordTheme() before its role layer, so omitted backgrounds inherit its dark surface. For each presentation state, omitted role leaves inherit the resolved DocumentView paint. Changing role paint updates presentation without reloading the document source.

Part Foreground Background Bold Italic Underline
body role-body-foreground role-body-background role-body-bold role-body-italic role-body-underline
gutter role-gutter-foreground role-gutter-background role-gutter-bold role-gutter-italic role-gutter-underline
position role-position-foreground role-position-background role-position-bold role-position-italic role-position-underline
hex-zero role-hex-zero-foreground role-hex-zero-background role-hex-zero-bold role-hex-zero-italic role-hex-zero-underline
hex-printable role-hex-printable-foreground role-hex-printable-background role-hex-printable-bold role-hex-printable-italic role-hex-printable-underline
hex-control role-hex-control-foreground role-hex-control-background role-hex-control-bold role-hex-control-italic role-hex-control-underline
hex-high-byte role-hex-high-byte-foreground role-hex-high-byte-background role-hex-high-byte-bold role-hex-high-byte-italic role-hex-high-byte-underline

HEX adds hex-zero for zero bytes, hex-printable for graphic ASCII and space, hex-control for other ASCII controls, and hex-high-byte for bytes at or above 0x80. Offsets use gutter; separators and padding use body. HEX roles are registered only for that representation and use the same PSS/theme cascade.

Run this sample from the Portals source directory so README.md is available. Press F2 to show or hide the line-number gutter while reading. The source and reading anchor are preserved, including wheel input already accepted during loading. Setting the existing value again does not start another load or redraw.

Complete application example

// Copyright (c) 2026 ttldtor.
// SPDX-License-Identifier: BSL-1.0
#include <portals/ui.hpp>
#include <portals/ui_style.hpp>
int main() {
using namespace portals;
// clang-format off
return ui::scene(
ui::viewer(file, "README.md").fastScroll()
.framed("rounded", "Document | F2 Numbers | F10 Quit"))
| ui::theme(nordTheme())
| ui::style(R"pss(
DocumentView {
role-body-foreground: #dce1e8;
role-gutter-foreground: #7d8797;
role-position-foreground: #62b4d7;
role-position-bold: true;
}
)pss")
| ui::onKey("F2", [file] { file.toggleLineNumbers(); })
| ui::onKey("F10 | Ctrl+C", ui::quit)
| ui::runApp();
// clang-format on
}
Light document text, gray line numbers and a blue position footer.
Toggle line numbers, scroll one row per wheel step, and reach the visible end.

Resource limits

Limits bound retained capacity and work, rather than document size. The default source root reserves at most 8 MiB; applications can share and configure a SourceBudget. DocumentViewConfig defaults to 16,384 actual viewport cells, 64 KiB of prepared payload, and 256 KiB of admitted source bytes per preparation quantum. Source pages default to 64 KiB. A viewport exceeding its configured preparation cap reports PAGE_TOO_LARGE; it is not silently truncated.

DocumentViewConfig.tailWorkTurns defaults to 32 and bounds the number of quanta in one managed seekable text-tail job. Set it to 1 for the previous single-quantum scheduling granularity; zero is invalid. workBytes bounds each quantum, so a job can admit up to workBytes * tailWorkTurns source bytes. Batching also checks an 8 ms soft slice between quanta, including initial inspection and staging time. A provider operation can exceed this slice; it is not an I/O or response-time guarantee. Cancellation and revision checks still run at each source page. Other navigation, non-seekable sources, HEX and exact-color recovery keep their ordinary preparation path. This changes scheduling, not the retained-memory cap.

For file-backed text-tail preparation, the worker opens one bounded read session per job and reuses its native handle across pages. Each page still checks handle metadata, the captured file generation and extent, and cancellation. Before returning either a continuation or a completed window, it validates the current path again and closes the session on the worker. A detected replacement, append, truncation or observed edit rejects that job. This does not provide an atomic snapshot of a file that another process is modifying.

DocumentReadBatch exposes the same opt-in mechanism for source adapters. Its pages are provisional until seal() succeeds; callers must seal before publishing any derived data. A successful seal is terminal. Create, read, seal and destroy the batch on the same worker; it retains its source and 4 KiB of source credits, plus the existing per-operation envelope and bounded pages. Providers opt in with ByteDocumentCapabilities.readSessions and openReadSession(); ordinary source reads keep their existing validation. If a session reports an unknown extent, End releases it before using the provider's ordinary extent discovery and reads. A known zero extent remains valid. Memory and gzip adapters do not inherit the raw file session capability. No whole-file buffer is introduced.

Pinned pages, immutable scanner snapshots, prepared output and cancelled work retain their credits until their actual owners finish. Provider-owned domain storage is outside the SDK's retained-page ledger. Process memory, source credits, cold-seek latency and terminal presentation time are different measurements; none is a file-size guarantee.

The view retains up to 16 in-session source bookmarks. Slots are reused cyclically for additional sources; a source without a retained bookmark opens at byte zero. These bookmarks are not persisted across application runs.

Search a large document and export bytes

The path/CLI viewer example also includes this search bar: open your own file and use F6 or Shift+F6 to navigate matches. Its existing F3 hexadecimal shortcut stays available. The smaller application below bundles a reproducible input.

Build portals_document_search_example and run it from its executable directory; the build places archive.sql beside it. The search bar can appear before the viewer in the scene. Edit its query or use Previous/Next, F3 and Shift+F3. F4 shows the same selected bytes in hexadecimal mode; F5 returns to text.

Complete source

// Copyright (c) 2026 ttldtor.
// SPDX-License-Identifier: BSL-1.0
#include <portals/ui.hpp>
#include <portals/ui_document_export.hpp>
#include <portals/ui_document_search.hpp>
#include <portals/ui_style.hpp>
int main() {
using namespace portals;
// clang-format off
return ui::scene(ui::vbox(
ui::label("Orders | F3: next | Shift+F3: previous | F4: hex | F5: text | F10: quit"),
ui::findBar(search, reader, "INSERT"),
ui::viewer(reader, ui::documentFile("archive.sql")).language("mysql").lineNumbers().flex(1)
.framed("rounded", "Orders"),
ui::hbox(LinearOptions{.gap = 1}, ui::button(save, "Export copy"), ui::label(status, "Ready"))))
| ui::theme(nordTheme())
| ui::onClick(save, [reader, status] {
ui::exportFile(reader, "orders-copy.sql", [status](const auto &result) {
status.text() = result.complete ? "Export complete" : "Export failed";
});
})
| ui::onKey("F3", [search] { search.next(); })
| ui::onKey("Shift+F3", [search] { search.previous(); })
| ui::onKey("F4", [reader] { reader.mode(DocumentViewMode::HEX); })
| ui::onKey("F5", [reader] { reader.mode(DocumentViewMode::TEXT); })
| ui::onKey("F10 | Ctrl+C", ui::quit)
| ui::runApp();
// clang-format on
}
Owning linear container options.
Definition layout.hpp:193
Literal search, Next/Previous, the same selected bytes in HEX, and an exported copy.

ui::findBar(search, reader, "INSERT") searches the reader's current logical source on workers. It keeps one selected match and bounded query/decoder storage, without loading the document or retaining every hit. Matching is case-sensitive, allows overlaps, and requires complete source graphemes. There is no Unicode normalization. The query is UTF-8; returned source ranges use original encoded byte offsets. FindMatch::sourceByteOffset() and sourceByteLength() distinguish those offsets from begin() and end() within the bounded UTF-8 result context. storedCount() describes retained results, not the total number of source hits.

While a search is pending, another Next/Previous request is rejected with WOULD_BLOCK; query editing and ordinary document navigation remain available.

Next continues the streaming scan. Previous may rescan the required prefix while retaining only the last eligible match; it can therefore take longer on a distant position. Both directions wrap. The UI remains available and query changes cancel obsolete work. A source or encoding replacement clears old results and retains the query and reading position. Edit the query or choose a navigation button to search the replacement. Manual navigation while a search is pending prevents its late result from moving the reading position.

The selected range uses the optional match role in text and hex projections:

DocumentView {
role-match-foreground: #202630;
role-match-background: #ebcb8b;
role-match-bold: true;
}

Themes supply contrasting match colors, including disabled state. The role uses the existing foreground/background/bold/italic/underline properties. Unused search extensions add no role payload to every control's computed style.

ui::exportFile(reader, output, completed) admits a background export of the source currently attached to the reader. ui::startExport returns the checked admission result. An existing output is never overwritten, including the source file itself. The completion runs on UI and receives DocumentExportResult with actual accepted bytes and any source/sink error. Runtime failures also enter the scene's error reporting. Only one export per viewer is admitted at a time. Changing its model does not redirect an admitted export; removing the viewer or closing its scene requests cancellation. A partial output remains after an error or cancellation. Completion does not promise durable storage or rollback.

For worker integrations, copyDocumentBytes(source, range, maxBytes) returns an owning raw-byte copy; the default ceiling is 64 KiB. It rejects oversized ranges before payload reads, and requires an explicit end when the extent is unknown. exportDocument writes fixed-size portions to DocumentExportSink. Both share the source's budget. They preserve the original text encoding; gzip sources produce decompressed bytes. Neither operation writes to the OS clipboard. A custom sink defines its own storage and blocking/cancellation latency.

Measured viewing profile

See the 2/8 GiB qualification for measured memory, first-text and navigation costs with one or four views, and the boundaries of AUTO/EXACT results. These fixed-workload observations are not universal latency guarantees.