pub struct Editor { /* private fields */ }Expand description
A gap-buffer text editor: a leaf View holding a single Vec<u8> split by
a movable gap, with a cursor, a selection, single-level undo, and a viewport
(delta) onto a content extent (limit). It references two sibling scroll
bars and an indicator on the window frame, runs Find / Replace dialogs, and
cuts/copies/pastes through a shared internal clipboard editor.
§The context-threading split (the central seam)
Redraw work needs a Context, but a View has none at construction, so
requesting a redraw is split from performing it:
- The core editing methods take no
Context— they mutate logical state and only OR bits intoupdate_flags.updateonly records what changed; it never repaints inline. &mut Contextis threaded only intodo_update,unlock,handle_event,set_state, and the public ctx-taking entries (apply_scroll_delta,insert_text).unlockflushes when the lock count hits 0;handle_eventflushes at the end for the arms that ran unlocked.change_boundsis geometry-only plus adeltaclamp plus a view-update request — scroll-bar params republish on the next flush.
This makes the entire gap-buffer + edit core context-free and unit-testable in isolation, where the real oracle (logical buffer state) lives.
§Siblings by ViewId
The editor holds h_scroll_bar/v_scroll_bar/
indicator as Option<ViewId>, never pointers. Every cross-view read/write
is routed through the event loop: read the bar values into delta, publish
range/value, set the indicator value, show/hide. The editor is its own
concrete downcast target (it is not a Scroller).
§Grapheme text
The character-stepping helpers read logical bytes across the gap into a small
buffer, str-decode the contiguous slice, and step whole grapheme clusters
via text::next/text::prev. There is no fixed-size character stack
buffer.
§Mouse hold-tracking
The two mouse-down hold loops (drag-select and pan) become tracked event arms:
the MouseDown arm runs the first loop iteration and arms the capture; the
move/auto/wheel arms are the loop bodies; MouseUp clears. Which loop is in
flight lives in EditorTrack (Select carries the live select mode; Pan
carries the last mouse position). A wheel during a drag-select forwards to both scroll
bars and self-posts a delta-sync, so the new offset lands on the next pump.
Outside a hold, a wheel falls through unconsumed (the editor’s event mask
excludes the wheel).
Search/replace state — the find string, the replacement string, and the
EF_* option flags — is per-editor: each editor independently
remembers its own last search. (C++ Turbo Vision kept these in class-static
globals shared across every editor; per-instance is the intentional
deviation, and is usually what a user wants.)
§Turbo Vision heritage
Ports TEditor (teditor1.cpp, teditor2.cpp, edits.cpp). Up-pointers to
the scroll bars and indicator become ViewId handles brokered by the event
loop (deviation D3); raw byte indices become grapheme-aware stepping (deviation
D13); color lookups become Roles; serialization is dropped.
Implementations§
Source§impl Editor
impl Editor
Sourcepub fn new(
bounds: Rect,
h_scroll_bar: Option<ViewId>,
v_scroll_bar: Option<ViewId>,
indicator: Option<ViewId>,
buf_size: usize,
) -> Self
pub fn new( bounds: Rect, h_scroll_bar: Option<ViewId>, v_scroll_bar: Option<ViewId>, indicator: Option<ViewId>, buf_size: usize, ) -> Self
Build an editor over a buf_size-byte buffer, wired to the given scroll
bars and frame indicator (each optional, by id).
The view grows with its parent on the right/bottom, is selectable, shows a
cursor, and starts with an empty buffer. No redraw is performed here (a
View has no Context at construction); the initial state is
consistent for the first draw, and scroll-bar params publish on the
first flush.
Sourcepub fn buf_len(&self) -> usize
pub fn buf_len(&self) -> usize
Number of logical text bytes currently in the buffer (not counting the gap).
Use this to check whether the editor is empty (buf_len() == 0) or to
drive a progress indicator. For the raw text itself, call text.
Sourcepub fn cur_ptr(&self) -> usize
pub fn cur_ptr(&self) -> usize
Byte offset of the cursor in the logical (gap-elided) text.
Use this to record the cursor position before a programmatic edit, or to verify cursor placement in tests. Offsets are byte-granular; grapheme boundaries are respected by the navigation methods but not enforced here.
Sourcepub fn limit(&self) -> Point
pub fn limit(&self) -> Point
Content extent: x = maximum line length (fixed at 256), y = number of lines.
Use this to size or configure scroll bars programmatically: limit().y is
the total line count, which equals the vertical scroll range. limit().x is
always 256 (the fixed maximum line length used to set horizontal scroll range).
Sourcepub fn delta(&self) -> Point
pub fn delta(&self) -> Point
Viewport top-left: x = first visible column, y = first visible row.
Use this to read the current scroll position, for instance to restore it
after a programmatic buffer reload. The editor updates delta automatically
when the cursor moves off-screen; set it via apply_scroll_delta.
Sourcepub fn cur_pos(&self) -> Point
pub fn cur_pos(&self) -> Point
Cursor position in display coordinates: x = column, y = row (both zero-based).
Use this to read the cursor’s visual position, for example to assert indicator wiring in tests or to display “line N, col M” in a status bar. Updated by every navigation and edit operation.
Sourcepub fn modified(&self) -> bool
pub fn modified(&self) -> bool
Whether the buffer has unsaved changes since the last save or load.
Use this to decide whether to prompt before closing, or to update a dirty
indicator. Set by any edit; cleared by FileEditor’s save path. The
clipboard editor is never marked modified.
Sourcepub fn set_text(&mut self, text: &[u8])
pub fn set_text(&mut self, text: &[u8])
Replace the whole buffer with text (used by Memo::set_value).
All-or-nothing: if text does not fit the buffer and it cannot grow
(plain editor / memo have a fixed buffer; file-editor mode grows instead),
it is a no-op. The replaced text is left unselected.
Sourcepub fn search(&mut self, needle: &str, opts: u16) -> bool
pub fn search(&mut self, needle: &str, opts: u16) -> bool
Find needle from the cursor; on a hit, select it and track the cursor.
This is the low-level search primitive; the interactive Find / Replace
dialogs drive it through do_search_replace.
Context-free: instead of flushing inline, this only records the scroll
target; the actual flush happens on the next handle_event boundary.
Sourcepub fn set_select(
&mut self,
start: usize,
end: usize,
cur_start: bool,
ctx: &mut Context<'_>,
)
pub fn set_select( &mut self, start: usize, end: usize, cur_start: bool, ctx: &mut Context<'_>, )
Set the selection to [start, end) and place the cursor at the start
endpoint when cur_start, else the end endpoint, then publish the
new cursor/selection state.
§Turbo Vision heritage
Ports TEditor::setSelect, which C++ exposes publicly. The ctx
parameter is the tvision-rs deviation already established by
insert_text/apply_scroll_delta:
publishing the cursor and scroll-bar params needs a Context to reach
the pump’s broker. For a context-free call (no flush) use the internal
set_select_core.
Sourcepub fn set_cur_ptr(&mut self, p: usize, select_mode: u8, ctx: &mut Context<'_>)
pub fn set_cur_ptr(&mut self, p: usize, select_mode: u8, ctx: &mut Context<'_>)
Move the cursor to byte offset p, optionally extending the selection
(and snapping to word/line granularity per select_mode), then
publish.
This does not scroll the cursor into view on its own — call
track_cursor afterward if the new position
might be offscreen, exactly as the C++ call sites do.
§Turbo Vision heritage
Ports TEditor::setCurPtr, which C++ exposes publicly. See
set_select for why this takes a ctx. For a
context-free call (no flush) use the internal set_cur_ptr_core.
Sourcepub fn scroll_to(&mut self, x: i32, y: i32, ctx: &mut Context<'_>)
pub fn scroll_to(&mut self, x: i32, y: i32, ctx: &mut Context<'_>)
Set the scroll offset to (x, y), clamped to the content extent, and
publish the new scroll-bar params.
§Turbo Vision heritage
Ports TEditor::scrollTo, which C++ exposes publicly. See
set_select for why this takes a ctx. For a
context-free call (no flush) use the internal scroll_to_core.
Sourcepub fn track_cursor(&mut self, center: bool, ctx: &mut Context<'_>)
pub fn track_cursor(&mut self, center: bool, ctx: &mut Context<'_>)
Scroll so the cursor is visible, centering it when center, and
publish the new scroll-bar params.
§Turbo Vision heritage
Ports TEditor::trackCursor, which C++ exposes publicly. See
set_select for why this takes a ctx. For a
context-free call (no flush) use the internal track_cursor_core.
Sourcepub fn apply_scroll_delta(
&mut self,
dx: Option<i32>,
dy: Option<i32>,
ctx: &mut Context<'_>,
)
pub fn apply_scroll_delta( &mut self, dx: Option<i32>, dy: Option<i32>, ctx: &mut Context<'_>, )
Adopt new scroll offsets read from the scroll bars (applied by the pump).
Public ctx-taking entry: the pump reads each scroll bar’s value, then calls
this with dx/dy (None = no bar). For each present bar, if its value
differs from the current offset, adopt it and flag a full redraw; then
flush.
Sourcepub fn insert_text(
&mut self,
text: &[u8],
select_text: bool,
ctx: &mut Context<'_>,
)
pub fn insert_text( &mut self, text: &[u8], select_text: bool, ctx: &mut Context<'_>, )
Insert text at the cursor, optionally leaving the inserted bytes selected.
Use this to inject text from the outside (clipboard paste, template fill,
programmatic population). select_text = true leaves the new text selected
(useful for a paste that should be immediately replaceable). Flushes after
the insert so scroll-bar params and the indicator are updated on the next pump.
For a context-free insert (no flush) use the internal insert_text_core.
Trait Implementations§
Source§impl View for Editor
impl View for Editor
Source§fn draw(&mut self, ctx: &mut DrawCtx<'_>)
fn draw(&mut self, ctx: &mut DrawCtx<'_>)
Recompute draw_ptr for the current vertical scroll, then render the
viewport rows. draw_ptr/draw_line are display caches, so mutating them
during drawing is intentional.
Source§fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context<'_>)
fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context<'_>)
Handle keyboard editing, command dispatch, single-click mouse positioning, and scroll-bar change notifications.
Source§fn set_state(&mut self, flag: StateFlag, enable: bool, ctx: &mut Context<'_>)
fn set_state(&mut self, flag: StateFlag, enable: bool, ctx: &mut Context<'_>)
Set or clear a view state flag and react to the change.
On Active: shows or hides the paired scroll bars and indicator and
re-grays the editing commands (Cut/Copy/Paste/Undo etc.). On Focused:
broadcasts RECEIVED_FOCUS or RELEASED_FOCUS so other views (such as
the indicator) can update. Override update_commands rather than this
method to customize command gating.
Source§fn change_bounds(&mut self, bounds: Rect)
fn change_bounds(&mut self, bounds: Rect)
Resize and reposition the editor to bounds, clamping the scroll offset so
the current content stays in view.
Called by the parent group when the window is resized. Scroll-bar params are
republished on the next flush rather than inline (the same pattern as
Scroller).
Source§fn valid(&mut self, _cmd: Command, _ctx: &mut Context<'_>) -> bool
fn valid(&mut self, _cmd: Command, _ctx: &mut Context<'_>) -> bool
Returns true when the editor’s buffer allocated successfully; false if
allocation failed (a zero-size fixed buffer).
Called by the framework before a close or dialog-accept to decide whether to
proceed. The base editor only checks the allocation flag; FileEditor
overrides this to run the modified-save Yes/No/Cancel prompt instead.
Source§fn as_any_mut(&mut self) -> Option<&mut dyn Any>
fn as_any_mut(&mut self) -> Option<&mut dyn Any>
Concrete-reach hatch: the pump downcasts to &mut Editor for the
EditorPaste broker, and for the FindPick /
ReplacePick completion to set search state.
Source§fn apply_scroll_sync(
&mut self,
h: Option<i32>,
v: Option<i32>,
ctx: &mut Context<'_>,
)
fn apply_scroll_sync( &mut self, h: Option<i32>, v: Option<i32>, ctx: &mut Context<'_>, )
Read both scroll bars’ values and apply the delta via apply_scroll_delta.
Unlike the scroller/outline, the editor preserves None — a missing
bar skips that axis rather than scrolling to 0. apply_scroll_delta is
the editor’s TEditor::checkScrollBar body; ctx is live so the editor
may queue scrollbar param write-backs for the next pump.
Source§fn set_modal_answer(&mut self, cmd: Command)
fn set_modal_answer(&mut self, cmd: Command)
Cache the user’s answer to the “Replace this occurrence?” prompt, routed
back from the message box. Consumed by do_search_replace on the next
search-again dispatch.
Source§fn set_modal_data(&mut self, data: FieldValue)
fn set_modal_data(&mut self, data: FieldValue)
Load a finished Find/Replace dialog’s search record (the pump packs the
dialog fields, read via View::value, into an ordered
FieldValue::List). A 2-element
[Text(find), Bits(flags)] is the Find shape (leaves replace_str
untouched); a 3-element [Text(find), Text(replace), Bits(flags)] is the
Replace shape. flags is pre-masked by the completion (and already carries
or clears EF_DO_REPLACE); stored as the low 16 bits. Other shapes are
ignored (typed-model drop, like set_value).
Shape collision: the match is on record shape only. A view that
embeds or delegates to Editor and opens its own form via
Context::request_exec_view
would, if that form gathers to [Text, Bits] (an InputLine plus
CheckBoxes) or [Text, Text, Bits], have it overwrite find_str,
replace_str and the editor flags. Such a wrapper overrides
set_modal_data itself and forwards to the editor only the Find/Replace
records.
Source§fn value(&self) -> Option<FieldValue>
fn value(&self) -> Option<FieldValue>
FieldValue, or None for a view
that carries no transferable data. Read moreSource§fn set_value(&mut self, _v: FieldValue)
fn set_value(&mut self, _v: FieldValue)
FieldValue into this control. Read moreSource§fn set_value_ctx(&mut self, v: FieldValue, ctx: &mut Context<'_>)
fn set_value_ctx(&mut self, v: FieldValue, ctx: &mut Context<'_>)
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)
fn awaken(&mut self)
Source§fn calc_bounds(&mut self, owner_size: Point, delta: Point) -> Rect
fn calc_bounds(&mut self, owner_size: Point, delta: Point) -> Rect
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 on_bounds_changed(&mut self, _ctx: &mut Context<'_>)
fn on_bounds_changed(&mut self, _ctx: &mut Context<'_>)
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. Read moreSource§fn cursor_request(&self) -> Option<Point>
fn cursor_request(&self) -> Option<Point>
None to
hide it. Base: Some(cursor) iff the view is focused with a visible cursor,
else None. Read moreSource§fn caret_size(&self) -> u8
fn caret_size(&self) -> u8
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. Read moreSource§fn find_mut(&mut self, id: ViewId) -> Option<&mut dyn View>
fn find_mut(&mut self, id: ViewId) -> Option<&mut dyn View>
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
fn remove_descendant(&mut self, id: ViewId, ctx: &mut Context<'_>) -> bool
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
fn focus_descendant(&mut self, id: ViewId, ctx: &mut Context<'_>) -> bool
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). Read moreSource§fn has_focusable_leaf(&self) -> bool
fn has_focusable_leaf(&self) -> bool
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
fn focus_to_edge(&mut self, backward: bool, ctx: &mut Context<'_>) -> bool
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. Read moreSource§fn reset_current(&mut self, _ctx: &mut Context<'_>)
fn reset_current(&mut self, _ctx: &mut Context<'_>)
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<'_>)
fn settle_currency(&mut self, _ctx: &mut Context<'_>)
Source§fn set_visible_descendant(
&mut self,
id: ViewId,
visible: bool,
ctx: &mut Context<'_>,
) -> bool
fn set_visible_descendant( &mut self, id: ViewId, visible: bool, ctx: &mut Context<'_>, ) -> bool
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. Read moreSource§fn number(&self) -> Option<i16>
fn number(&self) -> Option<i16>
None);
Window overrides to return its number when > 0
(0 means unnumbered → None).Source§fn grabs_focus_on_click(&self) -> bool
fn grabs_focus_on_click(&self) -> bool
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
fn select_window_num(&mut self, num: i16, ctx: &mut Context<'_>) -> bool
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)
fn tile(&mut self, _r: Rect)
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)
fn cascade(&mut self, _r: Rect)
Desktop overrides.menu::menu_view::update_menu_commands
implements the re-gray walk. Read moreMenuBar / MenuBox)
override to set their
MenuViewState::current — the write-only
display cache their draw reads to pick the selected colour. Read moreSource§fn get_help_ctx(&self) -> HelpCtx
fn get_help_ctx(&self) -> HelpCtx
HelpCtx::DRAGGING while the view is being dragged, otherwise the
view’s own ViewState::help_ctx. Read moreSource§fn descendant_global_bounds(&self, _id: ViewId, _acc: Point) -> Option<Rect>
fn descendant_global_bounds(&self, _id: ViewId, _acc: Point) -> Option<Rect>
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)
fn set_indicator_value(&mut self, _location: Point, _modified: bool)
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<'_>)
fn apply_page_sync(&mut self, _idx: usize, _ctx: &mut Context<'_>)
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.Auto Trait Implementations§
impl Freeze for Editor
impl RefUnwindSafe for Editor
impl Send for Editor
impl Sync for Editor
impl Unpin for Editor
impl UnsafeUnpin for Editor
impl UnwindSafe for Editor
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
§impl<T> Downcast for Twhere
T: Any,
impl<T> Downcast for Twhere
T: Any,
§fn into_any(self: Box<T>) -> Box<dyn Any>
fn into_any(self: Box<T>) -> Box<dyn Any>
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>
fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
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)
fn as_any(&self) -> &(dyn Any + 'static)
&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)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
&mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot
generate &mut Any’s vtable from &mut Trait’s.