Guide API
Skip to main content

View

Trait View 

Source
pub trait View {
Show 39 methods // Required methods fn state(&self) -> &ViewState; fn state_mut(&mut self) -> &mut ViewState; fn draw(&mut self, ctx: &mut DrawCtx<'_>); // Provided methods fn handle_event(&mut self, _ev: &mut Event, _ctx: &mut Context<'_>) { ... } fn set_state( &mut self, flag: StateFlag, enable: bool, ctx: &mut Context<'_>, ) { ... } fn valid(&mut self, _cmd: Command, _ctx: &mut Context<'_>) -> bool { ... } fn set_modal_answer(&mut self, _cmd: Command) { ... } fn value(&self) -> Option<FieldValue> { ... } fn set_value(&mut self, _v: FieldValue) { ... } fn set_modal_data(&mut self, _data: FieldValue) { ... } fn set_value_ctx(&mut self, v: FieldValue, ctx: &mut Context<'_>) { ... } fn awaken(&mut self) { ... } fn size_limits(&self, owner_size: Point) -> (Point, Point) { ... } fn calc_bounds(&mut self, owner_size: Point, delta: Point) -> Rect { ... } fn change_bounds(&mut self, bounds: Rect) { ... } fn on_bounds_changed(&mut self, _ctx: &mut Context<'_>) { ... } fn cursor_request(&self) -> Option<Point> { ... } fn caret_size(&self) -> u8 { ... } fn find_mut(&mut self, id: ViewId) -> Option<&mut dyn View> { ... } fn remove_descendant(&mut self, id: ViewId, ctx: &mut Context<'_>) -> bool { ... } fn focus_descendant(&mut self, id: ViewId, ctx: &mut Context<'_>) -> bool { ... } fn has_focusable_leaf(&self) -> bool { ... } fn focus_to_edge(&mut self, backward: bool, ctx: &mut Context<'_>) -> bool { ... } fn reset_current(&mut self, _ctx: &mut Context<'_>) { ... } fn settle_currency(&mut self, _ctx: &mut Context<'_>) { ... } fn set_visible_descendant( &mut self, id: ViewId, visible: bool, ctx: &mut Context<'_>, ) -> bool { ... } fn number(&self) -> Option<i16> { ... } fn grabs_focus_on_click(&self) -> bool { ... } fn select_window_num(&mut self, num: i16, ctx: &mut Context<'_>) -> bool { ... } fn tile(&mut self, _r: Rect) { ... } fn cascade(&mut self, _r: Rect) { ... } fn apply_scroll_sync( &mut self, _h: Option<i32>, _v: Option<i32>, _ctx: &mut Context<'_>, ) { ... } fn update_menu_commands(&mut self, _disabled_cmds: &CommandSet) { ... } fn set_menu_current(&mut self, _current: Option<usize>) { ... } fn get_help_ctx(&self) -> HelpCtx { ... } fn as_any_mut(&mut self) -> Option<&mut dyn Any> { ... } fn descendant_global_bounds(&self, _id: ViewId, _acc: Point) -> Option<Rect> { ... } fn set_indicator_value(&mut self, _location: Point, _modified: bool) { ... } fn apply_page_sync(&mut self, _idx: usize, _ctx: &mut Context<'_>) { ... }
}
Expand description

The behavior every view implements. Widgets supply state / state_mut / draw; the rest default.

A widget embeds a ViewState (its bounds, state flags, options, owner id, …) and implements View (draw, handle an event, report its value, …). The packed framework flag words become the State/Options/GrowMode/DragMode structs-of-bools, and the state-mutating verbs become plain field flips or small helpers.

§What lives on View vs. elsewhere

View and ViewState are the abstract base. Several operations have no home on a bare view because the data they need lives in the tree or the event loop:

  • Up-tree / owner operations live on Group — focusing, selecting, sibling navigation, and the coordinate transforms. Because a view has no up-pointer, the group drives these top-down. The auto-select on a selecting mouse-down likewise lives in the group’s routing; the base View::handle_event is a no-op.

  • Already provided elsewhere: timers → Context::set_timer / kill_timer; colors → views call ctx.style(Role::…) directly, so the trait has no color methods; the clip rect → DrawCtx::clip.

  • Modality and data transfer: a modal loop runs through Program::exec_view and Context::end_modal; window drag/resize is a capture handler; getting/setting a view’s contents is the typed View::value / View::set_value protocol.

  • Subsumed by the single event loop: the blocking event-pump and put-back helpers, cursor placement, and teardown collapse into the one loop plus Drop and the group’s child removal.

  • Command-enable policy. The program-global command set lives on Program as its complement — a disabled set (denylist): every command, including app-minted ones, is enabled unless explicitly disabled. Views write through Context::enable_command/disable_command and read through the Context::command_enabled per-pump snapshot (docs/design/command-enablement.md).

  • Dropped entirely: the occlusion/damage family (per-view back buffers and the exposed-region cache) is replaced by DrawCtx writes + whole-tree redraw + diff; serialization is gone; the error attribute becomes Role::Error.

§Turbo Vision heritage

Ports TView (tview.cpp/views.h), the root of the view hierarchy. Inheritance becomes a trait plus a composed ViewState (deviation D2); the packed sf*/of*/gf*/dm* flag words become structs-of-bools (deviation D5); owner/sibling pointers become tree edges plus ViewId handles (deviation D3), and methods that reached up an owner pointer instead take the downward Context (deviation D3).

Required Methods§

Source

fn state(&self) -> &ViewState

Borrow the embedded ViewState (the view’s data members).

Source

fn state_mut(&mut self) -> &mut ViewState

Mutably borrow the embedded ViewState.

Source

fn draw(&mut self, ctx: &mut DrawCtx<'_>)

Paint the view through ctx. Must be overridden.

There is no sensible default paint (a bare view has no palette to fill with and is never instantiated), so draw is required rather than defaulted.

Provided Methods§

Source

fn handle_event(&mut self, _ev: &mut Event, _ctx: &mut Context<'_>)

Handle an event. The base is a no-op (the event passes through).

The one piece of shared base behavior — auto-selecting a view on a selecting mouse-down — lives on Group, because it drives focus from the parent down.

Source

fn set_state(&mut self, flag: StateFlag, enable: bool, ctx: &mut Context<'_>)

Flip a propagating state flag and run its side effects. The base flips the flag and, for StateFlag::Focused, emits the focus broadcast (RECEIVED_FOCUS/RELEASED_FOCUS) via ctx.

The broadcast carries the view whose focus changed as its source (self.state().id()); it goes to the loop’s event queue rather than to a specific receiver. A Group overrides this to also propagate to its children. The flags handled directly on ViewState (visibility, cursor, shadow) are not driven through this hook.

Source

fn valid(&mut self, _cmd: Command, _ctx: &mut Context<'_>) -> bool

Whether the view is in a valid state for cmd (e.g. a modal end / focus release). Base is always true.

Carries &mut Context (the async-modal-from-a-view seam): a control’s validation may need to pop a modal message box (a validator error, the FileEditor modified-save prompt) and observe the answer. A downward-borrowed &mut View cannot run a nested modal inline, so it requests one via Context::request_message_box and re-validates once the answer is routed back (see docs/design/async-modal-from-view.md).

Source

fn set_modal_answer(&mut self, _cmd: Command)

Stash the user’s choice from an async modal message box this view requested via Context::request_message_box (the answer_to/RouteModalAnswer round-trip). Default: no-op. Overridden by views that drive a Yes/No/Cancel prompt out of valid (e.g. FileEditor caches it for the re-validate).

Source

fn value(&self) -> Option<FieldValue>

This control’s current value as a FieldValue, or None for a view that carries no transferable data.

The dialog gather walk calls this on every child in insertion order and collects the results into a Vec<Option<FieldValue>>. Override in a data-bearing control (e.g. InputLine returns FieldValue::Text, ScrollBar returns FieldValue::Int). The base returns None — a bare view carries nothing. Controls that don’t participate (buttons, labels) simply leave the base in place.

A Dialog answers with its whole gathered record (Dialog::gather_list, an ordered FieldValue::List); that is what a Context::request_exec_view modal hands back via set_modal_data. (Window and Group still return None.)

Source

fn set_value(&mut self, _v: FieldValue)

Load a typed FieldValue into this control.

The dialog scatter walk calls this on every child in insertion order, distributing an edited record. Override in a data-bearing control; the base ignores the call. A control should silently ignore a FieldValue variant it does not understand (e.g. an InputLine ignores FieldValue::Int) so that record schemas with mixed control types work without downcasting.

Source

fn set_modal_data(&mut self, _data: FieldValue)

Deliver a finished modal’s typed result record to the view that launched it. Defaulted no-op; a launcher view overrides it to load the record. Two producers call it:

The method does not say which modal the record came from, so an override that matches on record shape alone can misread a record from a different form with the same shape. A type that embeds or delegates to a view with such an override (e.g. Editor) and launches its own forms via request_exec_view must override set_modal_data itself, handle its own records, and forward only the ones meant for the inner view.

Distinct from set_value: set_value carries a view’s own field/document data (e.g. the editor’s text), whereas set_modal_data carries a separate modal-result record addressed to the launcher by id — the two channels must not collide. Driven from apply_modal_completion (the cluster-D modal-result path); the pump resolves the launcher with group.find_mut(id) and calls this method by virtual dispatch, never a downcast.

§Turbo Vision heritage

The return-less successor to delivering a dialog’s gathered record back to the requester (getData read at the modal’s close, handed to the owner).

Source

fn set_value_ctx(&mut self, v: FieldValue, ctx: &mut Context<'_>)

Scatter a typed FieldValue into this control with a Context. Default: calls set_value (the context-free setter). Override when scatter needs deferred publishing (e.g. ListBox republishes its vertical scrollbar via focus_item).

Source

fn awaken(&mut self)

Post-construction initialization hook. Called once after the view has been inserted into its group and the group’s layout is complete — the earliest point at which a view may safely resolve sibling ids or run initialization that requires a fully-wired tree. Override when a widget needs to do work that cannot happen during construction (e.g. reading a linked control’s current value). Base is a no-op.

Source

fn size_limits(&self, owner_size: Point) -> (Point, Point)

The (min, max) size this view may take inside an owner of owner_size.

Returns (Point::new(0,0), owner_size) by default, or (0, (i32::MAX, i32::MAX)) when GrowMode::fixed is set (the view does not track the owner’s size). Override to impose a minimum size: Window returns a 16×6 minimum so the frame stays readable. The result is consumed by View::calc_bounds and the free function locate; callers generally should not call this directly — use calc_bounds instead, which keeps the two in sync.

Source

fn calc_bounds(&mut self, owner_size: Point, delta: Point) -> Rect

The new bounds after the owner resized to owner_size (delta = new - old). Computes the size limits via the overridable size_limits hook — so a widget override (e.g. a window’s minimum) participates — then delegates the grow math to ViewState::calc_bounds (the single source). Returns the bounds; it does not apply them (change_bounds does).

Source

fn change_bounds(&mut self, bounds: Rect)

Apply bounds to this view and propagate as needed.

The base implementation sets the bounds fields via ViewState::set_bounds with no redraw (whole-tree redraw is automatic). Groups and windows override to call calc_bounds/change_bounds on each child so they track the resize. When you need to resize a view from outside the tree (e.g. a capture handler), prefer Context::request_bounds (deferred) over calling this directly — the tree is &mut-borrowed during dispatch.

Source

fn on_bounds_changed(&mut self, _ctx: &mut Context<'_>)

Called by the pump after change_bounds is applied via Deferred::ChangeBounds — provides a Context for re-publishing state that depends on the new bounds (e.g. scrollbar params). Default implementation is a no-op.

Scrollers re-apply their scroll limit after a resize, and list viewers re-publish their step params; both do so by overriding this hook in their respective concrete types. A Group whose size changed forwards the call to every child, so the hook reaches views at any depth. Every resize path (deferred bounds change, zoom, terminal resize) ends with this call on the view it re-bounded.

Source

fn cursor_request(&self) -> Option<Point>

The view-local hardware-cursor position this view wants shown, or None to hide it. Base: Some(cursor) iff the view is focused with a visible cursor, else None.

This is the top-down realization of the focused-chain cursor walk: the live event loop asks the root for the absolute cursor each pass. Group overrides this to descend into its current child, accumulating the child’s origin at each level.

Source

fn caret_size(&self) -> u8

The caret size this view wants while its cursor is shown, as a percentage of the character cell (1..=100). Base: CARET_INSERT (a block) when the cursor_ins state is set, else CARET_NORMAL (the normal caret). The event loop reads it along the same focused chain as cursor_request; Group overrides it to descend into its current child.

§Turbo Vision heritage

Ports TVCursor::decideCaretSize (tvcursor.cpp): 100 when sfCursorIns is set, else TScreen::cursorLines & 0x0F.

Source

fn find_mut(&mut self, id: ViewId) -> Option<&mut dyn View>

Resolve id to a descendant of this view (never self — the parent identifies a view by id). A leaf has no descendants, so the base returns None; a Group overrides to search its children and recurse; a Group-embedding view delegates to its inner group. This is the “tree-walk via Context” — the uniform way the event loop / a capture handler acts on a view it holds only by id (move a window’s bounds, flip the dragging flag, …).

Source

fn remove_descendant(&mut self, id: ViewId, ctx: &mut Context<'_>) -> bool

Remove the descendant named by id from whichever group owns it. Returns true if it was found+removed. Distinct from find_mut because removal happens in the owner’s child Vec (a view cannot remove itself — it doesn’t know its owner) and must run the owning group’s reset_current. Base: false (a leaf owns nothing).

Source

fn focus_descendant(&mut self, id: ViewId, ctx: &mut Context<'_>) -> bool

Focus (select) the descendant named by id within whichever group owns it — the tree-op behind a label focusing its linked control. Returns true if id was found in this subtree (selectable or not — finding it stops the walk). Distinct from find_mut because focusing happens in the owning group (a view cannot select itself within itself): the owning Group calls focus_child after applying the selectable gate. Base: false (a leaf owns nothing).

Scope: this focuses the link within its owning group, not the full ancestor chain. That is correct for the label/link sibling case (label and link share a group already on the focused path); a cross-group link would need an up-chain walk, which has no consumer.

Source

fn has_focusable_leaf(&self) -> bool

Whether this view’s subtree contains a focusable leaf (visible, enabled, selectable). Base: whether THIS view is itself a focusable leaf; Group overrides to recurse into children; wrapper views delegate. Used by the hierarchical Tab traversal to skip selectable-but-empty subtrees.

Source

fn focus_to_edge(&mut self, backward: bool, ctx: &mut Context<'_>) -> bool

Focus the first (Tab, backward = false) or last (Shift-Tab, backward = true) focusable leaf in this view’s subtree, establishing the full focus path down to it. Returns true if a focusable leaf was focused.

Base: a leaf reports whether IT is focusable — its owning group has already made it current, so there is nothing further to descend into. Group overrides to pick its edge child and recurse; wrapper views delegate. Used by the hierarchical Tab traversal to ENTER a group at its edge.

Source

fn reset_current(&mut self, _ctx: &mut Context<'_>)

Establish this view’s INTERNAL currency — for a group-bearing view, set its current child to the first visible+selectable child. The insert-time currency cascade cannot run inside the context-less Group::insert, so exec_view calls this on a freshly-inserted modal BEFORE focusing it, so the modal’s first selectable child is current on open (otherwise the modal is keyboard-dead until a nav event — see the seam note in exec_view). Base: no-op (a leaf has no internal currency); Group overrides; Window/Dialog delegate.

Source

fn settle_currency(&mut self, _ctx: &mut Context<'_>)

Run any pending insert-time reset-current cascades in this subtree.

When a visible, selectable view is inserted, the owning group must re-pick its current child. The context-less Group::insert cannot run that at insert time; instead the insert marks the group currency_dirty and the pump / Program::new settles it here, BEFORE the next event pick.

Post-order (children first): a child group’s currency exists before its owner’s focus cascade descends into it. Runs the INHERENT Group::reset_current (not the virtual one) — embedders that key one-time init off reset_current (a file dialog’s initial directory read) get it from exec_view’s kept virtual call instead, never from the settle pass. Base: no-op (a leaf has no children); Group overrides; embedders forward via #[delegate] (the specs.rs forwarder).

Source

fn set_visible_descendant( &mut self, id: ViewId, visible: bool, ctx: &mut Context<'_>, ) -> bool

Tree-op: set the visible flag of the descendant named by id from its OWNING group, running the owning group’s currency tail. Toggling visibility on a selectable view re-picks the owner’s current child, in both directions (show and hide). Returns true if id was found in this subtree.

Symmetric with remove_descendant / focus_descendant: the flag write and the reset_current happen in the owning group (a view cannot re-current its owner — it doesn’t know it). Backs Deferred::SetVisible (a scroller showing/hiding its scrollbar). Base: false (a leaf owns nothing).

Source

fn number(&self) -> Option<i16>

The window number for Alt-N selection. Base views are unnumbered (None); Window overrides to return its number when > 0 (0 means unnumbered → None).

Source

fn grabs_focus_on_click(&self) -> bool

Whether a mouse-down inside this view should auto-select (focus) it — the per-view opt-out for the group’s mouse-down auto-select (see Group::route_event). Default true (the common case); a Button overrides to return its grab-focus flag. A view returning false is not focused by a click but still receives the click (so it can act, e.g. press, without becoming the current view).

Source

fn select_window_num(&mut self, num: i16, ctx: &mut Context<'_>) -> bool

Tree-op: ask this subtree to select the window numbered num. Returns whether one matched. Consistent with the find_mut / remove_descendant tree-op family: the live loop holds a subtree only by id (here, the desktop) and asks it to act. Default: no-op (false). Desktop overrides.

Source

fn tile(&mut self, _r: Rect)

Tree-op: lay this subtree’s tileable windows out in a grid (the tile command). Base: no-op (only Desktop lays out windows). r is the desktop-local layout rect. Mirrors select_window_num: the live loop drives the desktop by id through &mut dyn View.

Source

fn cascade(&mut self, _r: Rect)

Tree-op: lay this subtree’s tileable windows out cascaded (the cascade command). Base: no-op; Desktop overrides.

Source

fn apply_scroll_sync( &mut self, _h: Option<i32>, _v: Option<i32>, _ctx: &mut Context<'_>, )

The shared scrollbar read-sync broker hook. Defaulted no-op; scroll-aware widgets override it to apply a freshly-read scrollbar delta to themselves. The pump passes the horizontal/vertical scrollbar values (None if that bar is absent or unresolved), each read via View::value. Overridden by the list viewers (delegate to list_viewer::apply_scroll), Scroller, the outline viewer, and the editor — every sibling-scrollbar read sync routes through this one method instead of a pump downcast.

Each widget interprets None per its own semantics (a read-only scroller treats a missing bar as delta 0; the editor preserves None to skip that axis). Driven by Deferred::ScrollSync.

Source

fn update_menu_commands(&mut self, _disabled_cmds: &CommandSet)

The menu command-graying broker hook. Defaulted no-op; menu views override to re-gray their menu tree against the program’s live disabled-command set (denylist — the argument is the set of commands currently disabled; an item grays iff its command is in it). The free fn menu::menu_view::update_menu_commands implements the re-gray walk.

A menu view (a child) cannot borrow the program’s CommandSet inline — the pump owns it, and storing a &CommandSet on Context would alias the apply-loop’s mutation of the disabled set. So the view requests Deferred::UpdateMenu by its own id, and the pump calls back here at apply time with the live set in hand. (A plain read needs no broker — Context::command_enabled answers from an owned per-pump snapshot.) No “changed” return is needed — under whole-tree redraw the next pump repaints unconditionally.

Source

fn set_menu_current(&mut self, _current: Option<usize>)

The menu-highlight write-back hook. Defaulted no-op; menu views (MenuBar / MenuBox) override to set their MenuViewState::current — the write-only display cache their draw reads to pick the selected colour.

While a menu session is active the MenuSession capture handler owns the interaction; the boxes are never focused and run no event logic. When the session changes a level’s highlight it requests Deferred::SetMenuCurrent by the box/bar id, and the pump calls back here at apply time. A trait method (not a downcast) keeps the broker uniform across the two concrete menu views, exactly like update_menu_commands.

Source

fn get_help_ctx(&self) -> HelpCtx

The effective help context for status-line switching. Returns HelpCtx::DRAGGING while the view is being dragged, otherwise the view’s own ViewState::help_ctx.

The status-line widget calls this on the currently focused view each pump to decide which help topic to display. Leaf views need not override — the default delegates to ViewState::get_help_ctx and the #[delegate] macro forwards it automatically through wrapper types. Override only when the type aggregates children’s contexts (like Group, which descends into its current child).

Source

fn as_any_mut(&mut self) -> Option<&mut dyn Any>

Downcast hook for the rare parent→child push that needs the concrete type (e.g. a window pushing its zoomed flag to its frame). Base returns None; only views that must be reached concretely override it. (Any requires 'static, which every view is.)

Source

fn descendant_global_bounds(&self, _id: ViewId, _acc: Point) -> Option<Rect>

Resolve descendant id to its absolute bounds, given acc = this view’s own absolute origin. Base returns None (a leaf owns no descendants); a Group overrides to walk its children accumulating origins, and a Group-embedding view delegates to its inner group. The THistory open path needs its linked input line’s bounds in the root/absolute frame, because exec_view root-inserts the modal and the modal frame hit-tests in absolute coords (the documented ROOT-INSERT + (0,0) caveat). Mirrors find_mut’s recursion but returns geometry, not a borrow.

Source

fn set_indicator_value(&mut self, _location: Point, _modified: bool)

The editor→indicator status-push broker hook. Defaulted no-op; the editor’s status Indicator overrides it to store the new cursor location + modified flag. Driven by Deferred::IndicatorSetValue: the editor (a leaf) cannot reach its indicator sibling inline, so it requests this and the pump calls the method by id — virtual dispatch, not a downcast.

Source

fn apply_page_sync(&mut self, _idx: usize, _ctx: &mut Context<'_>)

The tab-bar→page-stack switch broker hook. Defaulted no-op; PageStack overrides it to make page idx active. Driven by Deferred::PageStackSync: the pump reads the bound tab bar’s value and calls this method by id — virtual dispatch, not a downcast.

Dyn Compatibility§

This trait is dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§