Guide API
Skip to main content

Context

Struct Context 

Source
pub struct Context<'a> { /* private fields */ }
Expand description

The event/update context handle_event and capture handlers reach for.

Downward draw and event/update contexts.

There are no up-pointers from a view to its parent: instead a parent passes a context down carrying everything a child would otherwise reach upward for. There are two:

  • DrawCtx — the clipped, themed writer a view paints through during draw(). It works in view-local coordinates; the ctx translates them to absolute screen coordinates and clips. Its write ops are built on top of the Buffer and the text primitives — never re-deriving wide-char logic.
  • Context — the event/update context handlers and handle_event reach for. It exposes the ctx.* call surface (post / broadcast / timer scheduling / deferred capture push). It is built over loop-owned state as distinct &mut fields so the event loop can take disjoint-field borrows; the fields are deliberately not hidden behind one getter.

Built over loop-owned state as distinct &mut fields (not hidden behind a single getter) so the event loop can borrow them disjointly. The live event loop owns the backing VecDeque / TimerQueue / pending-capture Vec and constructs a fresh Context per dispatch.

A synchronous return-valued query to a view by id, or a direct message to one, are tree-owner primitives (Group/Program over find_mut), not Context methods — a Context deliberately holds no tree to route through. tvision-rs has no consumer for a synchronous return-valued query (the close-the-form veto is realized differently), so these are intentionally absent here.

§Turbo Vision heritage

The downward-passed successor to the data a view reads through its owner pointer — the owner’s size and dispatch phase, event put-back, command enable/disable, and broadcasts — gathered into one context handed down the tree instead of reached for upward (deviation D3). Broadcasts carry a ViewId subject rather than a raw pointer (deviation D4).

Implementations§

Source§

impl<'a> Context<'a>

Source

pub fn new( out_events: &'a mut VecDeque<Event>, timers: &'a mut TimerQueue, now_ms: u64, deferred: &'a mut Vec<Deferred>, ) -> Self

Build an event/update context over the loop-owned state.

Source

pub fn set_disabled_commands(&mut self, snapshot: CommandSet)

Refresh the disabled-command snapshot backing command_enabled. Called by the pump once per pump_once pass with a clone of the program’s live disabled set; a default-constructed Context (tests, ctor plumbing) keeps the empty set (= everything enabled, matching the denylist default).

Source

pub fn command_enabled(&self, cmd: Command) -> bool

Whether cmd is currently enabled (view-side, denylist: enabled iff not in the disabled set) — answered from the per-pump snapshot (see the field doc): a ctx.enable_command / ctx.disable_command requested during this dispatch is deferred and becomes visible here on the next pump. Lets a widget self-gray (e.g. a button checking its own command) without the aliasing problem a live &CommandSet accessor would have.

Source

pub fn clipboard_editor_id(&self) -> Option<ViewId>

The registered internal-clipboard editor ID (from the pump snapshot). None = no internal clipboard wired → use the OS clipboard.

Source

pub fn clipboard_has_selection(&self) -> bool

Whether the clipboard editor has a non-empty selection (from the pump snapshot). Drives the paste-enabled logic in update_commands: paste is enabled when there is no internal clipboard editor, or the registered one has a selection.

Source

pub fn set_clipboard_snapshot( &mut self, editor_id: Option<ViewId>, has_selection: bool, )

Refresh the clipboard snapshot. Called by the pump once per pump_once pass with the live clipboard_editor_id + clipboard_has_selection; default-constructed contexts (tests, ctor plumbing) keep None/false (= OS clipboard, paste always enabled).

Source

pub fn register_clipboard_editor( &mut self, editor_id: ViewId, window_id: ViewId, )

Register editor_id as the process-wide internal clipboard editor — deferred (Deferred::RegisterClipboardEditor). The pump stores the ID, marks the editor is_clipboard = true, and sets the EditWindow’s title to “Clipboard”.

Source

pub fn clipboard_editor_receive(&mut self, clipboard_id: ViewId, data: Vec<u8>)

Copy data into the clipboard editor — deferred (Deferred::ClipboardEditorReceive). The pump finds the clipboard editor and calls insert_from(&data) (which selects the inserted text, since this is the clipboard editor).

Source

pub fn clipboard_editor_paste(&mut self, dest_id: ViewId, clipboard_id: ViewId)

Paste from the clipboard editor into dest_id — deferred (Deferred::ClipboardEditorPaste). The pump reads the clipboard editor’s selection bytes, then calls insert_from(&data) on the dest editor.

Source

pub fn post(&mut self, cmd: Command)

Post a targeted command (Event::Command) into the loop’s queue.

Source

pub fn broadcast(&mut self, command: Command, source: Option<ViewId>)

Broadcast a command (Event::Broadcast) into the loop’s queue. source names the view the broadcast is about (the resolvable subject), or None if it concerns no particular view.

§Note: signalling view refreshes from external data

broadcast is the view-side half of the external-data pattern: after draining new data into shared state, call ctx.broadcast(REFRESH_CMD, None) to notify all views. See Program::set_on_idle for the full pattern, and Context::set_timer for the view-owned periodic-drain variant.

Source

pub fn set_timer( &mut self, timeout: Duration, period: Option<Duration>, ) -> TimerId

Arm a timer, returning its handle. now_ms is supplied from this context’s dispatch snapshot (the clock is not stored in the queue).

§Note: view-owned periodic drain for external data

set_timer is the building block for driving the UI from an external or async data source entirely within a view. The pattern:

  • Embed a zero-area child view (a “pump view”) in your window’s group. It is never drawn or hit-tested, but Event::Timer is delivered to every child unconditionally — even zero-area ones — on each tick.
  • In the pump view’s first handle_event, arm a recurring timer: ctx.set_timer(Duration::from_millis(50), Some(Duration::from_millis(50))).
  • On each Event::Timer(_), drain the external source (e.g. try_recv), update shared Rc<RefCell<AppState>>, drop the borrow, then call ctx.broadcast(REFRESH_CMD, None).
  • Other views match that broadcast in their handle_event and repaint from the shared state.

For program-level drains where &mut Program is available, prefer Program::set_on_idle instead.

Source

pub fn kill_timer(&mut self, id: TimerId)

Cancel a pending timer.

Source

pub fn push_capture(&mut self, handler: Box<dyn CaptureHandler>)

Push a capture handler — deferred (Deferred::PushCapture). The loop applies the queue after the current dispatch, so the pushed handler sees the next event, never the current one.

There is intentionally no pop_capture: a handler pops itself by returning CaptureFlow::ConsumedPop.

Source

pub fn enable_command(&mut self, cmd: Command)

Request cmd be enabled in the program’s command set — deferred (Deferred::EnableCommand). Lets a view enable a command without an up-pointer to the program.

The change is applied by the loop after the current dispatch; a subsequent command_enabled call in the same handler still returns the old value. Call this from View::handle_event (e.g. to enable a Save command once data is present) or from update_commands on a focus change. To disable, use disable_command. The underlying model is a denylist: a command is enabled iff it is not in the disabled set.

Source

pub fn disable_command(&mut self, cmd: Command)

Request cmd be disabled in the program’s command set — deferred (Deferred::DisableCommand). The mirror of enable_command: the change is applied after the current dispatch, and the denylist model means disabling an already-disabled command is harmless. Call this to gray out menu items or buttons that are not applicable in the current context (e.g. Paste when the clipboard is empty). Re-enable with enable_command.

Source

pub fn request_bounds(&mut self, id: ViewId, bounds: Rect)

Request the view named by id be moved/resized to bounds — deferred (Deferred::ChangeBounds). The loop resolves id via find_mut and calls change_bounds. A capture handler (the drag) holds only a ViewId, so it cannot mutate the tree inline.

Source

pub fn request_set_state(&mut self, id: ViewId, flag: StateFlag, enable: bool)

Request a propagating state flag be flipped on the view named by id — deferred (Deferred::SetState; see request_bounds). The loop resolves id via find_mut and calls set_state (e.g. clearing the dragging flag at drag end).

Source

pub fn request_close(&mut self, id: ViewId)

Request the view named by id be removed from whichever group owns it — deferred (Deferred::Close; see request_bounds). The loop resolves it via remove_descendant (the close command).

Source

pub fn request_focus(&mut self, id: ViewId)

Request the view named by id be focused (selected) within its owning group — deferred (Deferred::FocusById; see request_close). The loop resolves it via View::focus_descendant (a label focusing its linked control). The selectable gate is applied during that group walk, so the caller (the label) need not — and cannot, holding only the id — check it.

Source

pub fn set_fullscreen(&mut self, window: ViewId, mode: Fullscreen)

Request a fullscreen-mode change for window. The pump applies the cross-tree layout (menu bar, desktop, window re-fit). See Deferred::SetFullscreen.

Source

pub fn make_button_default(&mut self, button: ViewId, enable: bool)

Request the button be made (or un-made) the dialog’s default — deferred (Deferred::MakeButtonDefault). The pump resolves button, downcasts to Button, and calls make_default. A leaf view (the change-directory dialog’s directory list, on a focus change) holds only &mut Context and cannot poke its sibling button inline; it requests the change here.

Source

pub fn end_modal(&mut self, cmd: Command)

Signal that the current modal loop should end, returning cmd as its result — deferred (Deferred::EndModal).

Call this from inside a View::handle_event override (or any code that holds &mut Context) to close the modal dialog started by Program::exec_view and return cmd to its caller. Common commands are Command::OK (user confirmed) and Command::CANCEL (user dismissed).

The call is deferred: it pushes a Deferred::EndModal onto the queue; the pump applies it by setting Program::end_state after the current dispatch unwinds. This is safe from deep inside the view tree where no up-pointer to Program exists.

View-side, deferred. A View holds only &mut Context, never &mut Program. The top-level path (when you already hold &mut Program) is the immediate Program::end_modal. Rule of thumb: view → ctx.end_modal; owner / top-level → Program::end_modal.

See also: ending a modal in the tvision-rs guide.

Source

pub fn request_scroll_sync( &mut self, target: ViewId, h: Option<ViewId>, v: Option<ViewId>, )

Request the unified sibling-scrollbar read-sync (Deferred::ScrollSync): the pump reads h/v bar values and calls View::apply_scroll_sync on target. Used by the scroller, list viewers, outline viewer, and editor.

Source

pub fn request_scroll_bar_params( &mut self, id: ViewId, value: Option<i32>, min: Option<i32>, max: Option<i32>, page_step: Option<i32>, arrow_step: Option<i32>, )

Request the scrollbar id have its parameters set — deferred (Deferred::ScrollBarSetParams). Each None field is preserved from the bar’s live value at apply time. The scroller (a leaf) cannot mutate its sibling bar inline.

Source

pub fn request_set_visible(&mut self, id: ViewId, visible: bool)

Request the view id be shown/hidden — deferred (Deferred::SetVisible). A scroller showing/hiding a sibling scrollbar (which the scroller, a leaf, cannot reach inline).

Source

pub fn splitter_divider(&mut self, splitter: ViewId, op: DividerOp)

Broker a DividerOp to a splitter by id — deferred (Deferred::SplitterDivider). Used by the window resize capture, which cannot touch the splitter inline (holds only &mut Context).

Source

pub fn request_sync_page_stack(&mut self, page_stack: ViewId, tab_bar: ViewId)

Queue a PageStack sync (see Deferred::PageStackSync). Called by PageStack::handle_event on a TAB_BAR_CHANGED broadcast from its bound bar.

Source

pub fn request_resolve_focused_file( &mut self, subscriber: ViewId, source: ViewId, )

Request the focused directory entry of the file list source be resolved and written into subscriber (the file input line) — deferred (Deferred::ResolveFocusedFile). The resolve-by-source broker for the payload-carrying file-focused broadcast: the consumer (a leaf) holds only &mut Context and cannot read its FileList sibling, so the pump brokers the read + write.

Source

pub fn request_update_menu(&mut self, id: ViewId)

Request the menu view id regray its menu tree against the program’s live command set — deferred (Deferred::UpdateMenu). The menu view (a child) cannot read the command set itself; the pump brokers it and calls back through View::update_menu_commands. A menu view requests this by its own id when the command set changes.

Source

pub fn request_open_menu_box(&mut self, id: ViewId, menu: Menu, bounds: Rect)

Request a MenuBox be opened over bounds presenting menu, stamped with the pre-minted id — deferred (Deferred::OpenMenuBox). The MenuSession mints id itself (so it knows the box id with no callback) and the pump builds + inserts the box (no focus move). The submenu-open arm of the flattened menu interaction.

Source

pub fn request_set_menu_current(&mut self, id: ViewId, current: Option<usize>)

Request the menu view id set its highlight cache to current — deferred (Deferred::SetMenuCurrent). The pump calls back through View::set_menu_current. The session owns the authoritative highlight and pushes it to the view for draw.

Source

pub fn request_open_history( &mut self, link: ViewId, history_id: u8, require_focus: bool, )

Request a view-triggered history modal be opened over the link link — deferred (Deferred::OpenHistory). The history drop-down icon (a leaf) holds only the link’s id and cannot call exec_view (top-level only), so it requests the open; the pump reads the link, records history, builds the history window, and stashes it into Program::pending_modal for the outer driver to exec_view at top level. require_focus gates the keyboard trigger on the link being focused.

Source

pub fn request_record_history(&mut self, link: ViewId, history_id: u8)

Request the link’s current text be recorded into history — deferred (Deferred::RecordHistory). The pump resolves the link, reads its current text, and history_adds it to the channel.

Source

pub fn request_message_box( &mut self, text: String, kind: MessageBoxKind, buttons: MessageBoxButtons, answer_to: Option<ViewId>, then_command: Option<Command>, )

Request a modal message box be opened from inside a downward-borrowed &mut View — deferred (Deferred::OpenMessageBox; the async-modal-from-a-view seam, docs/design/async-modal-from-view.md). Validation (a validator error, the FileEditor modified-save prompt) holds only &mut Context and cannot run a nested modal inline, so it requests one; the pump builds + drives it.

answer_to = Some(id) routes the chosen button Command back to that view via View::set_modal_answer, and then_command = Some(cmd) re-posts a focused command afterwards so the original action re-validates with the cached answer. Both None for an informational (OK-only) box.

Source

pub fn request_exec_view( &mut self, view: Box<dyn View>, requester: ViewId, then_command: Option<Command>, )

Request a generic view-launched modal (ExecView): run view as a modal, then hand its result back to requester and re-inject then_command. The view-launched counterpart of Program::exec_view_with (which a view cannot call — a view holds only &mut Context, never &mut Program). Queues Deferred::OpenModal.

When the modal closes with command c, the pump, while the modal is still in the tree:

  1. if c != Command::CANCEL and the modal’s View::value is Some(record), calls requester.set_modal_data(record) — for a Dialog (or a type delegating value to one) the record is its gather_list;
  2. calls requester.set_modal_answer(c);
  3. re-posts then_command, where the requester acts with a full ctx.

This is C++ if (execView(d) != cmCancel) d->getData(&rec); split across the two hooks. A requester removed while the modal ran receives nothing (both deliveries resolve by id and drop silently). then_command is None for a fire-and-forget modal (e.g. a read-only info dialog).

ⓘ
// In the launcher's handle_event:
let mut d = Dialog::new(Rect::new(0, 0, 40, 8), Some("Rename".into()));
d.insert_child(Box::new(InputLine::new(Rect::new(2, 2, 36, 3), 64, None, LimitMode::MaxBytes)));
// ... plus OK / Cancel buttons (`d.button_row(…)`).
let me = self.state().id().expect("launcher is in the tree");
ctx.request_exec_view(Box::new(d), me, Some(CM_RENAME_DONE));

// In the launcher's View impl:
fn set_modal_data(&mut self, data: FieldValue) {
    if let FieldValue::List(v) = data
        && let Some(FieldValue::Text(name)) = v.into_iter().next()
    {
        self.pending_name = Some(name);
    }
}
// ... and on CM_RENAME_DONE: take `pending_name` and act on it.
Source

pub fn start_mouse_track( &mut self, view: ViewId, origin: Point, mask: TrackMask, )

Start mouse hold-tracking for view — the widget-facing entry into a modal mouse hold. Wraps push_capture with a MouseTrackCapture: from the next pump on (the deferred-push latency — so the widget runs its press handling once before the first forwarded event), every masked MouseMove/MouseAuto/MouseWheel event — and the terminating MouseUp — is localized against origin and delivered straight back to view’s handle_event via Deferred::MouseTrack; everything else is swallowed (the hold is modal). The widget’s own MouseMove/MouseAuto arms run while held; its MouseUp arm runs once at release.

origin is the absolute screen position of view-local (0, 0), cached by the widget’s last draw (the Button::abs_origin pattern).

The widget’s MouseUp arm must be guarded by a tracking flag set at MouseDown time: MouseUp is not gated by Group::wants, so a stray, untracked up delivered via normal routing would otherwise reach the release arm. See step 5 of docs/design/mouse-track.md.

§Turbo Vision heritage

Replaces entering the blocking hold loop do { … } while (mouseEvent(event, mask)) (tview.cpp:636-643) — whose body-once-before-the-first-wait shape is why the capture is pushed deferred.

Source

pub fn request_save_as_dialog(&mut self, editor_id: ViewId)

Request the pump to open a FileDialog for editor_id to pick a save-as filename — deferred (Deferred::OpenSaveAsDialog). Called from the file editor’s save / save-as path when the buffer is untitled. The pump builds + stashes the dialog; the SaveAsPick completion sets the picked name on the editor and re-injects the save command.

Source

pub fn open_color_dialog_for_role( &mut self, editor_id: ViewId, role: Role, fg: bool, current: Color, )

Queue Deferred::OpenColorDialogForRole for the theme editor’s per-role color picker — deferred. Called from ThemeEditorBody::handle_event. The pump builds a “Select Color” dialog seeded with current and stashes it into pending_modal with a ThemeColorPick completion; on OK the completion updates the ThemeEditorBody’s working theme for role/fg.

Source

pub fn open_find_dialog(&mut self, editor_id: ViewId)

Request the Find dialog be opened for editor_id — deferred (Deferred::OpenFindDialog).

Source

pub fn open_replace_dialog(&mut self, editor_id: ViewId)

Request the Replace dialog be opened for editor_id — deferred (Deferred::OpenReplaceDialog).

Source

pub fn set_indicator_value( &mut self, indicator: ViewId, location: Point, modified: bool, )

Request the editor’s indicator display location/modified — deferred (Deferred::IndicatorSetValue). The editor (a leaf) cannot mutate its sibling indicator inline.

Source

pub fn set_clipboard(&mut self, text: String)

Request text be copied to the system clipboard — deferred (Deferred::SetClipboard). The pump writes it to the backend clipboard.

Source

pub fn editor_paste(&mut self, id: ViewId)

Request the editor id paste the system-clipboard text — deferred (Deferred::EditorPaste). The pump reads the clipboard and inserts.

Source

pub fn request_input_line_paste(&mut self, id: ViewId)

Request the input line id paste the system-clipboard text — deferred (Deferred::InputLinePaste). The pump reads the clipboard and calls InputLine::paste_text.

Source

pub fn set_primary(&mut self, text: String)

Publish text as the PRIMARY selection — deferred (Deferred::SetPrimary). Call this when a mouse selection completes; keyboard selection deliberately does not publish (it would re-take X selection ownership on every arrow key).

Source

pub fn request_input_line_paste_primary(&mut self, id: ViewId)

Request the input line id paste the PRIMARY selection — deferred (Deferred::InputLinePastePrimary). The X11 middle-click gesture.

Source

pub fn request_editor_paste_primary(&mut self, id: ViewId)

Request the editor id paste the PRIMARY selection — deferred (Deferred::EditorPastePrimary).

Source

pub fn put_event(&mut self, ev: Event)

Re-queue a raw event into the loop’s event queue.

Unlike post (which queues only Event::Command), this accepts any Event — useful for re-delivering a mouse or key event on the next pump. The event lands in out_events, which the loop drains before polling the backend, so it is processed on the very next pump cycle. Typical use: the menu session re-posts the triggering outside click so the view that recovers focus sees it; a capture handler forwards a deferred key press. Prefer post or broadcast for simple command notifications.

Source

pub fn now_ms(&self) -> u64

The clock value sampled for this dispatch pass.

Source

pub fn owner_size(&self) -> Point

The owner’s size for the view currently being routed to — the downward realization of reading the owner’s size/extent. See the owner_size field docs: it is transient routing state set/restored by each Group::handle_event around delivery, valid only during group-routed dispatch. Defaults to (0, 0).

Source

pub fn set_owner_size(&mut self, size: Point)

Set the owner size for the routed view — called by Group::handle_event before delivering to children (set to the group’s own size) and to restore it on exit.

Source

pub fn phase(&self) -> Phase

The focused-dispatch phase for the view currently being routed to — the downward realization of reading the owner’s dispatch phase (no up-pointer, so the phase rides the Context; see the phase field docs). Defaults to Phase::Focused outside a focused-events walk.

Auto Trait Implementations§

§

impl<'a> !RefUnwindSafe for Context<'a>

§

impl<'a> !Send for Context<'a>

§

impl<'a> !Sync for Context<'a>

§

impl<'a> !UnwindSafe for Context<'a>

§

impl<'a> Freeze for Context<'a>

§

impl<'a> Unpin for Context<'a>

§

impl<'a> UnsafeUnpin for Context<'a>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> Downcast for T
where T: Any,

§

fn into_any(self: Box<T>) -> Box<dyn Any>

Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.
§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
§

fn as_any(&self) -> &(dyn Any + 'static)

Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.