tvision_rs/command.rs
1//! Commands and command sets.
2//!
3//! A [`Command`] is the identity of an action — the thing a menu item, button,
4//! or key binding emits and a view interprets. Each command is an opaque
5//! newtype around a **namespaced static string** (`"tv.ok"`), so application-
6//! and view-defined commands are collision-safe by construction. A
7//! [`CommandSet`] is a set of commands the framework enables or disables in
8//! bulk.
9//!
10//! The associated constants below are **only the framework's shared
11//! vocabulary** — commands the core (program/view/window/dialog/menu/
12//! status-line/desktop) generates or interprets generically, all under the
13//! `tv.` namespace. **View-specific commands live with their view module**
14//! (e.g. the editor's `char_left`, the file dialog's `file_open`); external
15//! views and apps mint their own the same way, via [`Command::custom`] with
16//! their own dotted prefix.
17//!
18//! **Guide:** [Commands & events](../../../apps/commands.html).
19//!
20//! # Turbo Vision heritage
21//!
22//! Ports the `cm*` command family and `TCommandSet` (`views.h`, `tcmdset.cpp`).
23//! Commands were originally hand-assigned `int`s; here a command's identity is a
24//! namespaced `&'static str` instead, so the command space is open and extensions
25//! cannot collide (deviation D1). The integers existed only for serialization
26//! (dropped) and to index a 256-bit set (now a [`HashSet`]), so commands no longer
27//! carry a number.
28
29use std::collections::HashSet;
30use std::ops::{AddAssign, BitAndAssign, BitOrAssign, SubAssign};
31
32/// The identity of an action — what a menu item, button, or key binding emits
33/// and a view interprets. A command's identity is a **namespaced static
34/// string** rather than a number, so downstream code can mint
35/// application-specific commands collision-safely.
36///
37/// The field is private: a `Command` is an opaque token. The associated
38/// constants below are the framework's standard vocabulary, and external
39/// apps/views use [`Command::custom`] to define their own, namespacing under their
40/// own dotted prefix:
41///
42/// ```
43/// const REFRESH: tvision_rs::Command = tvision_rs::Command::custom("myapp.refresh");
44/// ```
45///
46/// Equality and hashing compare the string *contents*, so two `Command`s with
47/// equal-content names are equal regardless of where the literals live.
48///
49/// [`Default`] is [`Command::VALID`] (the zero command).
50///
51/// # Turbo Vision heritage
52///
53/// Ports the `cm*` command family (`views.h`), which were plain `int`s; here a
54/// command's identity is a namespaced `&'static str` (deviation D1).
55#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
56pub struct Command(&'static str);
57
58impl Default for Command {
59 fn default() -> Self {
60 Command::VALID
61 }
62}
63
64impl Command {
65 /// Mint an application- or view-specific command from a namespaced name.
66 ///
67 /// The escape hatch external code uses to define its own commands; pick a
68 /// dotted prefix unique to your app/view (`"myapp.refresh"`) so it cannot
69 /// collide with the framework's `tv.*` vocabulary or another extension's.
70 pub const fn custom(name: &'static str) -> Command {
71 Command(name)
72 }
73
74 /// The command's namespaced name (e.g. `"tv.ok"`).
75 pub const fn name(self) -> &'static str {
76 self.0
77 }
78
79 // --- Core commands ---
80 /// The no-op / always-valid command; also the zero/default command.
81 ///
82 /// Used as the response to [`View::valid`](crate::view::View::valid) meaning
83 /// "this view is always willing to proceed". Also the [`Default`] value for
84 /// `Command`.
85 pub const VALID: Command = Command("tv.valid");
86 /// Quit the application — emit from a menu item or key binding (e.g. Alt-X).
87 ///
88 /// Handled by [`Program`](crate::Program), which closes all windows and exits
89 /// the event loop. Place in your status-line or File menu to give users a
90 /// standard exit path.
91 pub const QUIT: Command = Command("tv.quit");
92 /// Report a runtime error — a beep / no-op fallback for unhandled commands.
93 ///
94 /// `Program` sends this to the focused view when a command cannot be routed;
95 /// the default handler produces an audible bell. Views should not normally
96 /// emit this directly.
97 pub const ERROR: Command = Command("tv.error");
98 /// Open the menu bar — emit from a key binding (conventionally F10).
99 ///
100 /// Handled by the `MenuBar`; the status-line default key set binds F10 to this
101 /// command so users can enter the menu with the keyboard.
102 pub const MENU: Command = Command("tv.menu");
103 /// Close the active window — handled by the active [`Window`](crate::Window).
104 ///
105 /// Emitted by the window's close button (frame close icon) or from a menu item
106 /// (e.g. Alt-F3 in the default window menu). The window calls
107 /// [`View::valid`](crate::view::View::valid) before closing.
108 pub const CLOSE: Command = Command("tv.close");
109 /// Maximize / restore the active window — handled by the active [`Window`](crate::Window).
110 ///
111 /// Emitted by the window's zoom button (frame zoom icon) or a key binding.
112 /// Toggles between the zoomed (full-desktop) rect and the saved un-zoom rect.
113 pub const ZOOM: Command = Command("tv.zoom");
114 /// Cycle the active window through frameless-fullscreen modes
115 /// (`Off → Desktop → Screen → Off`). Handled by the [`Window`](crate::Window); no default key
116 /// binding (apps bind their own). See [`Window::set_fullscreen`](crate::window::Window::set_fullscreen).
117 pub const FULLSCREEN: Command = Command("tv.fullscreen");
118 /// Enter window resize/move mode — handled by the active [`Window`](crate::Window).
119 ///
120 /// Emitted by the frame drag handle or a key binding. Starts the interactive
121 /// drag loop where arrow keys reposition or resize the window.
122 pub const RESIZE: Command = Command("tv.resize");
123 /// Focus the next window on the desktop — handled by [`Program`](crate::Program).
124 ///
125 /// Cycles the desktop's current window forward. Bind to a key (e.g. F6) in
126 /// the window menu to give keyboard access to window cycling.
127 pub const NEXT: Command = Command("tv.next");
128 /// Send the active window to the back (focus the previous one).
129 ///
130 /// Handled by [`Program`](crate::Program); cycles the desktop's current window
131 /// backward. Bind to Shift-F6 or the window menu as a companion to `NEXT`.
132 pub const PREV: Command = Command("tv.prev");
133 /// Open context help — handled by [`Program`](crate::Program).
134 ///
135 /// Dispatched when the user presses F1 or the frame help icon. `Program`
136 /// routes it to the registered help viewer if any.
137 pub const HELP: Command = Command("tv.help");
138
139 // --- Standard dialog result commands ---
140 /// Confirm / accept a dialog — the modal result returned when the user presses
141 /// the OK / default button or Enter.
142 ///
143 /// `Program::exec_view` returns this command when a dialog's modal loop ends on
144 /// confirmation. Check the return value to distinguish OK from CANCEL after a
145 /// `Dialog::run` / `MessageBox` call.
146 pub const OK: Command = Command("tv.ok");
147 /// Cancel / dismiss a dialog without accepting — always enabled (cannot be
148 /// disabled via [`CommandSet`]).
149 ///
150 /// The Escape key generates this in a dialog. The framework guarantees
151 /// `CANCEL` is always in the enabled command set so users can always dismiss.
152 pub const CANCEL: Command = Command("tv.cancel");
153 /// Answer "yes" in a yes/no confirmation dialog.
154 ///
155 /// Emitted by the Yes button in a `MessageBox::confirm` style dialog; check the
156 /// modal result against this to detect a "yes" answer.
157 pub const YES: Command = Command("tv.yes");
158 /// Answer "no" in a yes/no confirmation dialog.
159 ///
160 /// Emitted by the No button in a `MessageBox::confirm` style dialog. The dialog
161 /// loop ends and this is the return value when the user picks No.
162 pub const NO: Command = Command("tv.no");
163 /// Activate the dialog's default button — broadcast on Enter inside a dialog
164 /// to the default button (the one whose `ButtonFlags.default` is true).
165 pub const DEFAULT: Command = Command("tv.default");
166
167 // --- Standard editing / clipboard commands ---
168 /// Cut the selection to the clipboard (Shift-Del / Ctrl-X).
169 ///
170 /// Handled by `Editor` / `Memo`; disable via [`CommandSet`] when nothing is
171 /// selected. Place in a standard Edit menu.
172 pub const CUT: Command = Command("tv.cut");
173 /// Copy the selection to the clipboard (Ctrl-Ins / Ctrl-C).
174 ///
175 /// Handled by `Editor` / `Memo`; disable via [`CommandSet`] when nothing is
176 /// selected. Place in a standard Edit menu.
177 pub const COPY: Command = Command("tv.copy");
178 /// Paste from the clipboard (Shift-Ins / Ctrl-V).
179 ///
180 /// Handled by `Editor` / `Memo`. Place in a standard Edit menu.
181 pub const PASTE: Command = Command("tv.paste");
182 /// Undo the last edit (Alt-Backspace / Ctrl-Z).
183 ///
184 /// Handled by `Editor` / `Memo`; disable via [`CommandSet`] when the undo
185 /// buffer is empty. Place in a standard Edit menu.
186 pub const UNDO: Command = Command("tv.undo");
187 /// Clear (delete) the selection without copying to the clipboard (Ctrl-Del).
188 ///
189 /// Handled by `Editor` / `Memo`; disable via [`CommandSet`] when nothing is
190 /// selected.
191 pub const CLEAR: Command = Command("tv.clear");
192
193 // --- Window management ---
194 /// Tile the open windows into a grid — handled by [`Desktop`](crate::Desktop).
195 ///
196 /// Bind to a Window menu item (e.g. "Tile"); the desktop repositions and
197 /// resizes all tileable windows (`Options::tileable = true`) to fill the
198 /// desktop area without overlap.
199 pub const TILE: Command = Command("tv.tile");
200 /// Cascade the open windows in an offset stack — handled by [`Desktop`](crate::Desktop).
201 ///
202 /// Bind to a Window menu item (e.g. "Cascade"); each tileable window is
203 /// placed at a staggered offset so title bars are visible.
204 pub const CASCADE: Command = Command("tv.cascade");
205
206 // --- Application menu commands ---
207 /// Create a new document — emit from a File menu "New" item.
208 ///
209 /// The framework does not handle this; your application handles it by
210 /// opening a new editor window.
211 pub const NEW: Command = Command("tv.new");
212 /// Open a document — emit from a File menu "Open" item.
213 ///
214 /// The framework does not handle this automatically; your application handles
215 /// it by running a file-open dialog and opening the chosen file.
216 pub const OPEN: Command = Command("tv.open");
217 /// Save the current document — emit from a File menu "Save" item.
218 ///
219 /// Your application handles this; disable via [`CommandSet`] when no document
220 /// is open or the editor is unmodified.
221 pub const SAVE: Command = Command("tv.save");
222 /// Save the current document under a new name — emit from "Save As".
223 ///
224 /// Your application handles this by running a file-save dialog.
225 pub const SAVE_AS: Command = Command("tv.save_as");
226 /// Save all open documents — emit from "Save All".
227 ///
228 /// Your application handles this; disable when no modified documents are open.
229 pub const SAVE_ALL: Command = Command("tv.save_all");
230 /// Change the working directory — opens the change-directory dialog.
231 ///
232 /// Handled by the standard `ChDirDialog` when your application routes it.
233 pub const CH_DIR: Command = Command("tv.ch_dir");
234 /// Drop to a shell prompt (inherited from the DOS era; keep for compatibility).
235 ///
236 /// In the original Turbo Vision this suspended the application to a DOS
237 /// shell; in a modern port you may repurpose it or leave it disabled.
238 pub const DOS_SHELL: Command = Command("tv.dos_shell");
239 /// Close all open windows — emit from a Window menu "Close All" item.
240 ///
241 /// [`Desktop`](crate::Desktop) / `Program` close every window whose
242 /// `valid(CLOSE)` returns true.
243 pub const CLOSE_ALL: Command = Command("tv.close_all");
244
245 // --- Broadcast / message commands ---
246 /// A view received focus — broadcast by `Group` whenever it calls
247 /// `set_current`; carries the newly-focused view's `ViewId` as `source`.
248 ///
249 /// Listen for this in a parent or sibling to react to focus changes (e.g. to
250 /// update a status bar or enable/disable commands).
251 pub const RECEIVED_FOCUS: Command = Command("tv.received_focus");
252 /// A view is about to release focus — broadcast before `set_current` removes
253 /// focus; carries the old view's `ViewId` as `source`.
254 ///
255 /// Can be vetoed via [`View::valid`](crate::view::View::valid): if the focused
256 /// view's `valid(RELEASED_FOCUS)` returns false, the focus change is blocked.
257 pub const RELEASED_FOCUS: Command = Command("tv.released_focus");
258 /// The set of enabled commands changed — broadcast by `Program` after any
259 /// [`CommandSet`] update.
260 ///
261 /// Menu bars, status lines, and buttons listen for this to re-query which
262 /// commands are enabled and redraw accordingly.
263 pub const COMMAND_SET_CHANGED: Command = Command("tv.command_set_changed");
264 /// A scroll bar's value changed — broadcast by [`ScrollBar`](crate::ScrollBar)
265 /// whenever the thumb moves; `source` is the scroll bar's `ViewId`.
266 ///
267 /// A scroller or list viewer receives this broadcast and scrolls its content
268 /// to match. The cross-view broker in the pump resolves `source` to the
269 /// scroll bar and reads its value.
270 pub const SCROLL_BAR_CHANGED: Command = Command("tv.scroll_bar_changed");
271 /// A scroll bar arrow or page region was clicked — broadcast by
272 /// [`ScrollBar`](crate::ScrollBar) to trigger a single scroll step.
273 pub const SCROLL_BAR_CLICKED: Command = Command("tv.scroll_bar_clicked");
274 /// Broadcast by a [`TabBar`](crate::widgets::TabBar) when its selected tab
275 /// changes; carries the bar's own [`ViewId`](crate::view::ViewId) as the
276 /// broadcast `source` so a sibling [`PageStack`](crate::widgets::PageStack)
277 /// can tell which bar fired (the D3/D4 pattern, mirroring SCROLL_BAR_CHANGED).
278 pub const TAB_BAR_CHANGED: Command = Command("tv.tab_bar_changed");
279 /// Select the desktop window whose number matches the Alt-*N* keypress.
280 ///
281 /// Emitted by `Program` when the user presses Alt-1 through Alt-9; the
282 /// desktop walks its children and focuses the window whose
283 /// [`View::number`](crate::view::View::number) matches.
284 pub const SELECT_WINDOW_NUM: Command = Command("tv.select_window_num");
285 /// A list item was activated (broadcast) — emitted by `ListViewer` on
286 /// Enter or double-click; `source` is the list viewer's `ViewId`.
287 ///
288 /// Listen for this broadcast in a parent view to react to item selection
289 /// (e.g. open a document, populate a detail pane).
290 pub const LIST_ITEM_SELECTED: Command = Command("tv.list_item_selected");
291 /// The find query changed (incremental find-and-highlight); `source` is the
292 /// list viewer's `ViewId`. Mirrors [`SCROLL_BAR_CHANGED`](Self::SCROLL_BAR_CHANGED)'s notify-by-
293 /// broadcast — a parent filters on `source` to drive an external search
294 /// (e.g. submit an async query and re-feed results).
295 pub const LIST_FIND_CHANGED: Command = Command("tv.list_find_changed");
296 /// A [`Table`](crate::widgets::Table)'s sort order changed through the user
297 /// (a header click or [`TABLE_SORT_NEXT`](Self::TABLE_SORT_NEXT) /
298 /// [`TABLE_SORT_FLIP`](Self::TABLE_SORT_FLIP)); `source` is the table's
299 /// `ViewId`. Read the new order with `Table::sort_spec`.
300 pub const TABLE_SORT_CHANGED: Command = Command("tv.table_sort_changed");
301 /// A multi-select [`Table`](crate::widgets::Table)'s set of marked rows
302 /// changed through the user (Space or a double-click toggled a row);
303 /// `source` is the table's `ViewId`. Read the set with
304 /// `Table::selected_keys`.
305 pub const TABLE_SELECTION_CHANGED: Command = Command("tv.table_selection_changed");
306 /// Sort a focused [`Table`](crate::widgets::Table) by the next visible
307 /// column, ascending (wrapping; with no sort yet, the first visible
308 /// column). The table binds no key to it: an app maps a key to this
309 /// command (status line or keymap) if it wants keyboard sorting.
310 pub const TABLE_SORT_NEXT: Command = Command("tv.table_sort_next");
311 /// Flip the sort direction of a focused [`Table`](crate::widgets::Table)
312 /// on its current sort column (with no sort yet: sort the first visible
313 /// column ascending). Unbound by default, like
314 /// [`TABLE_SORT_NEXT`](Self::TABLE_SORT_NEXT).
315 pub const TABLE_SORT_FLIP: Command = Command("tv.table_sort_flip");
316 /// A [`Table`](crate::widgets::Table) cell editor committed a new text
317 /// that the model accepted; `source` is the table's `ViewId`. Read the
318 /// value from `Table::model` (or the app's own copy of the data). An
319 /// edit committed by the command that closes a modal dialog arrives
320 /// after the dialog is gone (see `Table::valid`).
321 pub const TABLE_CELL_EDITED: Command = Command("tv.table_cell_edited");
322 /// Open a focused [`Table`](crate::widgets::Table)'s column popup at its
323 /// header: every column with a check mark, choosing one shows or hides it
324 /// (the same popup a right-click on the header opens). Unbound by
325 /// default, like [`TABLE_SORT_NEXT`](Self::TABLE_SORT_NEXT).
326 pub const TABLE_COLUMNS: Command = Command("tv.table_columns");
327 /// A [`Table`](crate::widgets::Table)'s column layout changed through the
328 /// user (a column resized, moved, shown or hidden); `source` is the
329 /// table's `ViewId`. Read the layout with `Table::column_layout` to
330 /// persist it.
331 pub const TABLE_COLUMNS_CHANGED: Command = Command("tv.table_columns_changed");
332 /// Record the current input-line value into its history list — handled by
333 /// `InputLine` when it loses focus.
334 ///
335 /// `Program` broadcasts this before routing focus away from an input line so
336 /// the line's history list is updated even if the user did not press Enter.
337 pub const RECORD_HISTORY: Command = Command("tv.record_history");
338 /// Broadcast by a `RevealEye` when its reveal intent changes, so the owning
339 /// `MaskedInput` re-syncs its field's reveal state (source = the eye's id).
340 pub const REVEAL_CHANGED: Command = Command("tv.reveal_changed");
341
342 // --- Editor search/replace commands ---
343 /// Open the find dialog — handled by `Editor`; bind to Ctrl-Q/F or Ctrl-F.
344 pub const FIND: Command = Command("tv.find");
345 /// Open the find-and-replace dialog — handled by `Editor`; bind to Ctrl-Q/A
346 /// or Ctrl-H.
347 pub const REPLACE: Command = Command("tv.replace");
348 /// Repeat the last search from the current cursor position — handled by
349 /// `Editor`; bind to Ctrl-L.
350 pub const SEARCH_AGAIN: Command = Command("tv.search_again");
351
352 // --- Editor movement / edit commands (handled by `Editor` / `Memo`) ---
353 /// Move the cursor one character left (Left arrow / Ctrl-S in WordStar mode).
354 pub const CHAR_LEFT: Command = Command("tv.char_left");
355 /// Move the cursor one character right (Right arrow / Ctrl-D in WordStar mode).
356 pub const CHAR_RIGHT: Command = Command("tv.char_right");
357 /// Move the cursor one word left (Ctrl-Left / Ctrl-A in WordStar mode).
358 pub const WORD_LEFT: Command = Command("tv.word_left");
359 /// Move the cursor one word right (Ctrl-Right / Ctrl-F in WordStar mode).
360 pub const WORD_RIGHT: Command = Command("tv.word_right");
361 /// Move the cursor to the start of the line (Home / Ctrl-Q-S).
362 pub const LINE_START: Command = Command("tv.line_start");
363 /// Move the cursor to the end of the line (End / Ctrl-Q-D).
364 pub const LINE_END: Command = Command("tv.line_end");
365 /// Move the cursor up one line (Up arrow / Ctrl-E in WordStar mode).
366 pub const LINE_UP: Command = Command("tv.line_up");
367 /// Move the cursor down one line (Down arrow / Ctrl-X in WordStar mode).
368 pub const LINE_DOWN: Command = Command("tv.line_down");
369 /// Scroll up one page (PgUp / Ctrl-R in WordStar mode).
370 pub const PAGE_UP: Command = Command("tv.page_up");
371 /// Scroll down one page (PgDn / Ctrl-C in WordStar mode).
372 pub const PAGE_DOWN: Command = Command("tv.page_down");
373 /// Move the cursor to the start of the document (Ctrl-Home / Ctrl-Q-R).
374 pub const TEXT_START: Command = Command("tv.text_start");
375 /// Move the cursor to the end of the document (Ctrl-End / Ctrl-Q-C).
376 pub const TEXT_END: Command = Command("tv.text_end");
377 /// Insert a line break at the cursor position (Enter).
378 pub const NEW_LINE: Command = Command("tv.new_line");
379 /// Delete the character before the cursor (Backspace / Ctrl-H).
380 pub const BACK_SPACE: Command = Command("tv.back_space");
381 /// Delete the character at the cursor position (Delete / Ctrl-G).
382 pub const DEL_CHAR: Command = Command("tv.del_char");
383 /// Delete the word at (to the right of) the cursor (Ctrl-T in WordStar mode).
384 pub const DEL_WORD: Command = Command("tv.del_word");
385 /// Delete from the cursor to the start of the line (Ctrl-Q-Backspace).
386 pub const DEL_START: Command = Command("tv.del_start");
387 /// Delete from the cursor to the end of the line (Ctrl-Q-Y).
388 pub const DEL_END: Command = Command("tv.del_end");
389 /// Delete the current line (Ctrl-Y).
390 pub const DEL_LINE: Command = Command("tv.del_line");
391 /// Toggle insert / overwrite mode (Ins key).
392 pub const INS_MODE: Command = Command("tv.ins_mode");
393 /// Begin a keyboard selection (Ctrl-K-B).
394 pub const START_SELECT: Command = Command("tv.start_select");
395 /// Collapse / hide the current selection without deleting it (Ctrl-K-H).
396 pub const HIDE_SELECT: Command = Command("tv.hide_select");
397 /// Toggle auto-indent mode (Ctrl-O-I).
398 pub const INDENT_MODE: Command = Command("tv.indent_mode");
399 /// Update the editor window's title bar — emitted by `Editor` after a save
400 /// or filename change so the frame rerenders the new title.
401 pub const UPDATE_TITLE: Command = Command("tv.update_title");
402 /// Select the entire document contents (Ctrl-A / Ctrl-K-K after Ctrl-K-B).
403 pub const SELECT_ALL: Command = Command("tv.select_all");
404 /// Delete the word to the left of the cursor (Ctrl-Backspace).
405 pub const DEL_WORD_LEFT: Command = Command("tv.del_word_left");
406 /// Change the text encoding of the current editor document.
407 pub const ENCODING: Command = Command("tv.encoding");
408
409 // --- File-dialog commands ---
410 /// The file dialog's Open button.
411 pub const FILE_OPEN: Command = Command("tv.file_open");
412 /// The file dialog's Replace button.
413 pub const FILE_REPLACE: Command = Command("tv.file_replace");
414 /// The file dialog's Clear button.
415 pub const FILE_CLEAR: Command = Command("tv.file_clear");
416 /// Re-read the file dialog's directory listing.
417 pub const FILE_INIT: Command = Command("tv.file_init");
418 /// Confirm a directory change in the change-directory dialog.
419 pub const CHANGE_DIR: Command = Command("tv.change_dir");
420 /// Revert the change-directory dialog to the current directory.
421 pub const REVERT: Command = Command("tv.revert");
422 /// A file in the file list gained focus (broadcast on every focus change; the
423 /// focused file record is carried via the broadcast's resolvable `source`).
424 pub const FILE_FOCUSED: Command = Command("tv.file_focused");
425 /// A file in the file list was double-clicked (broadcast). Payload-less in
426 /// tvision-rs: the file dialog just turns it into [`OK`](Command::OK).
427 pub const FILE_DOUBLE_CLICKED: Command = Command("tv.file_double_clicked");
428
429 /// An outline-viewer item was selected — broadcast by
430 /// [`Outline`](crate::widgets::Outline) when the user presses Enter or
431 /// double-clicks a node.
432 ///
433 /// `source` is the `Outline`'s `ViewId`. Listen for this broadcast in a parent
434 /// or sibling to react to node activation (e.g. open the selected item). The
435 /// selected node is the one at `OutlineViewerState::foc`; resolve the outline's
436 /// `ViewId` to read it.
437 ///
438 /// # Turbo Vision heritage
439 /// Ports `cmOutlineItemSelected` (`outline.h`).
440 pub const OUTLINE_ITEM_SELECTED: Command = Command("tv.outline_item_selected");
441
442 // --- Theme editor commands ---
443 /// Open the foreground color picker for the selected theme role (tvision-rs-native).
444 pub const THEME_EDIT_FG: Command = Command("tv.theme_edit_fg");
445 /// Open the background color picker for the selected theme role (tvision-rs-native).
446 pub const THEME_EDIT_BG: Command = Command("tv.theme_edit_bg");
447}
448
449/// A set of commands the framework enables or disables in bulk.
450///
451/// The command space is **open/unbounded** (commands are namespaced strings,
452/// not `0..=255`), so there is no trackable-range guard and no `all()`
453/// constructor — "all commands" is not enumerable. The set itself is
454/// polarity-neutral; the framework's **enabled-by-default policy** lives in
455/// [`Program`](crate::Program), which keeps its current set as the complement —
456/// a **disabled set** (a denylist). The `enable_cmd`/`disable_cmd` methods mean
457/// insert/remove regardless of which polarity a particular owner stores; the
458/// polarity-neutral [`insert`](Self::insert) / [`remove`](Self::remove) aliases
459/// are preferred at sites where the set's meaning is not "enabled commands" (e.g.
460/// the disabled set).
461///
462/// # Turbo Vision heritage
463///
464/// Ports `TCommandSet` (`views.h`, `tcmdset.cpp`); the 256-bit array becomes a
465/// [`HashSet<Command>`] (deviation D1).
466#[derive(Clone, PartialEq, Eq, Debug, Default)]
467pub struct CommandSet {
468 cmds: HashSet<Command>,
469}
470
471impl CommandSet {
472 /// Build an empty command set.
473 ///
474 /// The returned set contains no commands. Populate it incrementally with
475 /// [`enable_cmd`](Self::enable_cmd) / [`insert`](Self::insert) or the `+=`
476 /// operator, or use it as the start of a denylist by calling
477 /// [`disable_cmd`](Self::disable_cmd) / [`insert`](Self::insert) for each
478 /// command that should be blocked.
479 pub fn new() -> Self {
480 CommandSet::default()
481 }
482
483 /// Test whether `cmd` is a member of this set.
484 ///
485 /// Returns `true` when the command was previously added and not yet
486 /// removed. On a **disabled set** (denylist) the result means the command
487 /// is blocked; on an **enabled set** it means the command is active — the
488 /// interpretation depends on the set's role, not this method.
489 ///
490 /// Use [`contains`](Self::contains) at new call sites as the idiomatic
491 /// Rust name; use `has` when mirroring the C++ `TCommandSet::has` call.
492 pub fn has(&self, cmd: Command) -> bool {
493 self.cmds.contains(&cmd)
494 }
495
496 /// Idiomatic alias for [`has`](Self::has) — follows Rust collection
497 /// convention (`HashSet::contains`). Prefer this name at new call sites.
498 pub fn contains(&self, cmd: Command) -> bool {
499 self.has(cmd)
500 }
501
502 /// Add `cmd` to this set (semantic name: enable the command).
503 ///
504 /// When `self` is an **enabled set**, this marks the command as enabled
505 /// and it will pass the framework's enabled-command check. When `self` is
506 /// a **disabled set** (denylist — the pattern [`Program`](crate::Program)
507 /// uses internally), prefer the polarity-neutral
508 /// [`insert`](Self::insert) alias to avoid misleading code.
509 ///
510 /// The `+=` operator (`AddAssign<Command>`) is equivalent.
511 pub fn enable_cmd(&mut self, cmd: Command) {
512 self.cmds.insert(cmd);
513 }
514
515 /// Remove `cmd` from this set (semantic name: disable the command).
516 ///
517 /// When `self` is an **enabled set**, this marks the command as disabled
518 /// so it will be greyed out in menus and rejected by status-line items.
519 /// When `self` is a **disabled set** (denylist), prefer the
520 /// polarity-neutral [`remove`](Self::remove) alias instead.
521 ///
522 /// The `-=` operator (`SubAssign<Command>`) is equivalent.
523 pub fn disable_cmd(&mut self, cmd: Command) {
524 self.cmds.remove(&cmd);
525 }
526
527 /// Polarity-neutral alias for [`enable_cmd`](Self::enable_cmd): add `cmd`
528 /// to the set.
529 ///
530 /// Prefer `insert` over `enable_cmd` when the set's meaning is not "which
531 /// commands are currently enabled" — for example, when building a denylist
532 /// of blocked commands, `disabled.insert(cmd)` is clearer than
533 /// `disabled.enable_cmd(cmd)`.
534 pub fn insert(&mut self, cmd: Command) {
535 self.enable_cmd(cmd);
536 }
537
538 /// Polarity-neutral alias for [`disable_cmd`](Self::disable_cmd): remove
539 /// `cmd` from the set.
540 ///
541 /// Prefer `remove` over `disable_cmd` at denylist sites — see
542 /// [`insert`](Self::insert) for the naming rationale.
543 pub fn remove(&mut self, cmd: Command) {
544 self.disable_cmd(cmd);
545 }
546
547 /// Add every command in `other` to this set (set union).
548 ///
549 /// After this call, `self` contains every command it previously held plus
550 /// every command in `other`. Use to merge two enabled sets, or to
551 /// re-enable a batch of commands at a denylist site (remove them from the
552 /// blocked list by calling `disabled.disable_set(&to_restore)`).
553 ///
554 /// The `+=` / `|=` operators (`AddAssign<&CommandSet>` /
555 /// `BitOrAssign<&CommandSet>`) are equivalent.
556 pub fn enable_set(&mut self, other: &CommandSet) {
557 self.cmds.extend(other.cmds.iter().copied());
558 }
559
560 /// Remove every command in `other` from this set (set difference).
561 ///
562 /// After this call, `self` no longer contains any command that appears in
563 /// `other`. Use to suppress a batch of commands in an enabled set, or to
564 /// block a batch of commands by adding them to a denylist.
565 ///
566 /// The `-=` operator (`SubAssign<&CommandSet>`) is equivalent.
567 pub fn disable_set(&mut self, other: &CommandSet) {
568 for cmd in &other.cmds {
569 self.cmds.remove(cmd);
570 }
571 }
572
573 /// Whether no commands are enabled.
574 pub fn is_empty(&self) -> bool {
575 self.cmds.is_empty()
576 }
577}
578
579// --- Operator overloads ---
580
581/// `set += cmd` — add a single command (equivalent to [`enable_cmd`](CommandSet::enable_cmd) /
582/// [`insert`](CommandSet::insert)). Use this operator when building a set incrementally:
583/// `let mut s = CommandSet::new(); s += Command::CUT; s += Command::COPY;`
584impl AddAssign<Command> for CommandSet {
585 fn add_assign(&mut self, cmd: Command) {
586 self.enable_cmd(cmd);
587 }
588}
589
590/// `set -= cmd` — remove a single command (equivalent to [`disable_cmd`](CommandSet::disable_cmd) /
591/// [`remove`](CommandSet::remove)). Use to revoke a single command from an enabled set or to
592/// unblock a single command from a denylist.
593impl SubAssign<Command> for CommandSet {
594 fn sub_assign(&mut self, cmd: Command) {
595 self.disable_cmd(cmd);
596 }
597}
598
599/// `set += other` — add every command in `other` (set union, equivalent to
600/// [`enable_set`](CommandSet::enable_set)). Idiomatic C++ Pascal set `+` operator.
601impl AddAssign<&CommandSet> for CommandSet {
602 fn add_assign(&mut self, other: &CommandSet) {
603 self.enable_set(other);
604 }
605}
606
607/// `set -= other` — remove every command in `other` (set difference, equivalent to
608/// [`disable_set`](CommandSet::disable_set)). Idiomatic C++ Pascal set `-` operator.
609impl SubAssign<&CommandSet> for CommandSet {
610 fn sub_assign(&mut self, other: &CommandSet) {
611 self.disable_set(other);
612 }
613}
614
615/// `set |= other` — set union (alias for `+= other`); same as
616/// [`enable_set`](CommandSet::enable_set). The `|=` spelling emphasizes
617/// the Boolean-OR semantics over the Pascal-add semantics.
618impl BitOrAssign<&CommandSet> for CommandSet {
619 fn bitor_assign(&mut self, other: &CommandSet) {
620 self.enable_set(other);
621 }
622}
623
624/// `set &= other` — set intersection: retains only commands present in **both**
625/// `self` and `other`. Equivalent to the Pascal `*` operator on sets. Use when
626/// you need the overlap of two command sets — for example, to find which commands
627/// are enabled in all active views simultaneously.
628impl BitAndAssign<&CommandSet> for CommandSet {
629 fn bitand_assign(&mut self, other: &CommandSet) {
630 self.cmds.retain(|cmd| other.cmds.contains(cmd));
631 }
632}
633
634#[cfg(test)]
635mod tests {
636 use super::*;
637
638 #[test]
639 fn custom_round_trips_and_namespaces() {
640 let c = Command::custom("myapp.refresh");
641 assert_eq!(c.name(), "myapp.refresh");
642
643 // Two commands with equal-content names compare equal, regardless of
644 // where the literals live.
645 let a = Command::custom("myapp.refresh");
646 let b = Command::custom(&"myapp.refresh".to_string().leak()[..]);
647 assert_eq!(a, b);
648
649 // Different namespaces (or names) differ.
650 assert_ne!(Command::custom("a.refresh"), Command::custom("b.refresh"));
651 assert_ne!(
652 Command::custom("myapp.refresh"),
653 Command::custom("myapp.reload")
654 );
655 }
656
657 #[test]
658 fn framework_constants_are_namespaced() {
659 assert_eq!(Command::VALID.name(), "tv.valid");
660 assert_eq!(Command::OK.name(), "tv.ok");
661 assert_eq!(Command::SAVE_AS.name(), "tv.save_as");
662 assert_eq!(
663 Command::COMMAND_SET_CHANGED.name(),
664 "tv.command_set_changed"
665 );
666 }
667
668 #[test]
669 fn default_command_is_valid() {
670 assert_eq!(Command::default(), Command::VALID);
671 }
672
673 #[test]
674 fn new_set_is_empty() {
675 let cs = CommandSet::new();
676 assert!(cs.is_empty());
677 assert!(!cs.has(Command::OK));
678 }
679
680 #[test]
681 fn enable_disable_has() {
682 let mut cs = CommandSet::new();
683 cs.enable_cmd(Command::OK);
684 assert!(cs.has(Command::OK));
685 assert!(cs.contains(Command::OK));
686 cs.disable_cmd(Command::OK);
687 assert!(!cs.has(Command::OK));
688 }
689
690 #[test]
691 fn insert_remove_alias_enable_disable_cmd() {
692 // The polarity-neutral aliases are behaviorally identical to the
693 // faithful port names (insert == enable_cmd, remove == disable_cmd).
694 let mut via_alias = CommandSet::new();
695 let mut via_port = CommandSet::new();
696
697 via_alias.insert(Command::OK);
698 via_port.enable_cmd(Command::OK);
699 via_alias.insert(Command::ZOOM);
700 via_port.enable_cmd(Command::ZOOM);
701 assert_eq!(via_alias, via_port);
702 assert!(via_alias.has(Command::OK) && via_alias.has(Command::ZOOM));
703
704 via_alias.remove(Command::OK);
705 via_port.disable_cmd(Command::OK);
706 assert_eq!(via_alias, via_port);
707 assert!(!via_alias.has(Command::OK));
708 assert!(via_alias.has(Command::ZOOM));
709
710 // Idempotent like the underlying HashSet ops.
711 via_alias.remove(Command::OK);
712 via_port.disable_cmd(Command::OK);
713 assert_eq!(via_alias, via_port);
714 }
715
716 #[test]
717 fn custom_commands_are_tracked() {
718 // The command space is open: a custom command can be enabled and is
719 // reported by `has`, with no 0..=255 boundary behaviour.
720 let mut cs = CommandSet::new();
721 let refresh = Command::custom("x.y");
722 cs.enable_cmd(refresh);
723 assert!(cs.has(refresh));
724 cs.disable_cmd(refresh);
725 assert!(!cs.has(refresh));
726 assert!(cs.is_empty());
727 }
728
729 #[test]
730 fn add_sub_assign_command() {
731 let mut cs = CommandSet::new();
732 cs += Command::CUT;
733 cs += Command::COPY;
734 assert!(cs.has(Command::CUT));
735 assert!(cs.has(Command::COPY));
736 cs -= Command::CUT;
737 assert!(!cs.has(Command::CUT));
738 assert!(cs.has(Command::COPY));
739 }
740
741 #[test]
742 fn union_via_enable_set_and_add_assign() {
743 let mut a = CommandSet::new();
744 a.enable_cmd(Command::OK);
745 let mut b = CommandSet::new();
746 b.enable_cmd(Command::CANCEL);
747 b.enable_cmd(Command::YES);
748
749 let mut viamethod = a.clone();
750 viamethod.enable_set(&b);
751 assert!(viamethod.has(Command::OK));
752 assert!(viamethod.has(Command::CANCEL));
753 assert!(viamethod.has(Command::YES));
754
755 let mut viaop = a.clone();
756 viaop += &b;
757 assert_eq!(viaop, viamethod);
758
759 let mut viabitor = a;
760 viabitor |= &b;
761 assert_eq!(viabitor, viamethod);
762 }
763
764 #[test]
765 fn disable_set_and_sub_assign() {
766 let mut a = CommandSet::new();
767 a.enable_cmd(Command::OK);
768 a.enable_cmd(Command::ZOOM);
769 a.enable_cmd(Command::CLOSE);
770 let mut remove = CommandSet::new();
771 remove.enable_cmd(Command::ZOOM);
772 remove.enable_cmd(Command::CLOSE);
773
774 let mut viamethod = a.clone();
775 viamethod.disable_set(&remove);
776 assert!(!viamethod.has(Command::ZOOM));
777 assert!(!viamethod.has(Command::CLOSE));
778 assert!(viamethod.has(Command::OK));
779
780 a -= &remove;
781 assert_eq!(a, viamethod);
782 }
783
784 #[test]
785 fn intersection_via_bitand_assign() {
786 let mut a = CommandSet::new();
787 a.enable_cmd(Command::OK);
788 a.enable_cmd(Command::CANCEL);
789 a.enable_cmd(Command::YES);
790
791 let mut b = CommandSet::new();
792 b.enable_cmd(Command::CANCEL);
793 b.enable_cmd(Command::YES);
794 b.enable_cmd(Command::NO);
795
796 a &= &b;
797 assert!(!a.has(Command::OK));
798 assert!(a.has(Command::CANCEL));
799 assert!(a.has(Command::YES));
800 assert!(!a.has(Command::NO)); // only in b, not in original a
801 }
802
803 #[test]
804 fn equality_and_is_empty() {
805 let mut a = CommandSet::new();
806 let mut b = CommandSet::new();
807 assert_eq!(a, b);
808 assert!(a.is_empty());
809
810 a.enable_cmd(Command::OK);
811 assert_ne!(a, b);
812 assert!(!a.is_empty());
813
814 b.enable_cmd(Command::OK);
815 assert_eq!(a, b);
816 }
817}