Guide API
Skip to main content

tvision_rs/app/
application.rs

1//! `Application`, the thin wrapper over `Program` (documented on the type).
2
3use crate::app::Program;
4use crate::backend::Backend;
5use crate::command::Command;
6use crate::theme::Theme;
7use crate::timer::Clock;
8use crate::view::{Rect, View, ViewId};
9
10/// A thin embed-and-delegate wrapper over [`Program`].
11///
12/// `Application` adds the application-level window commands on top of [`Program`]:
13/// the tile and cascade commands lay the desktop's windows out (into
14/// [`get_tile_rect`]'s rectangle), and the shell command suspends the terminal.
15/// Subsystem init and teardown are handled by the
16/// [`Backend`](crate::backend::Backend) +
17/// [`Renderer`](crate::backend::Renderer) construction path. History needs no
18/// explicit setup: the store is a `thread_local!` `Vec` that auto-initializes and
19/// auto-drops (see `history.rs`). The type is thin: one [`get_tile_rect`] helper
20/// plus forwarding delegations to the embedded program.
21///
22/// `Application` provides [`Application::get_tile_rect`] (the rectangle tile and
23/// cascade lay windows into) and forwards all other behavior verbatim to the
24/// embedded [`Program`].
25///
26/// Build with [`Application::new`]; drive with [`Application::run`] or step with
27/// [`Application::pump_once`].
28///
29/// # Turbo Vision heritage
30///
31/// Ports `TApplication` (`tapplica.cpp`); its constructor is the factory mixin
32/// that wires up the status line, menu bar, and desktop. The `TApplication :
33/// TProgram` inheritance becomes embed-and-delegate composition (deviation D2):
34/// the type holds a [`Program`] and forwards to it. History
35/// needs no explicit setup — the store is a `thread_local!` `Vec` that
36/// auto-initializes and auto-drops (see `history.rs`).
37///
38/// [`get_tile_rect`]: Application::get_tile_rect
39pub struct Application {
40    /// The embedded program. `Application` forwards every public operation
41    /// through this field — see the forwarding methods below.
42    program: Program,
43}
44
45impl Application {
46    /// Construct the application and its three subviews.
47    ///
48    /// `create_desktop`, `create_status_line`, and `create_menu_bar` are
49    /// factory closures, each receiving the full terminal `Rect`; they own their
50    /// own inset (shrink the rect by one row for a menu bar, one row for a status
51    /// line, etc.) and return `None` to omit that subview entirely. Pass
52    /// [`Desktop::new`](crate::desktop::Desktop::new) wrapped in `Some(Box::new(...))`
53    /// for a standard desktop; substitute custom types as needed.
54    ///
55    /// Hardware/mouse/screen subsystem init is handled by the `backend` construction
56    /// path (e.g. [`CrosstermBackend::new`](crate::backend::CrosstermBackend::new));
57    /// history needs no explicit setup — the store is a `thread_local!` `Vec` that
58    /// auto-initializes and auto-drops.
59    ///
60    /// After construction, drive the loop with [`Application::run`] (production) or
61    /// step with [`Application::pump_once`] (tests).
62    ///
63    /// # Turbo Vision heritage
64    /// Ports `TApplication::TApplication` (`tapplica.cpp`). The subsystem-init
65    /// sequence (`TMemoryManager`, `TSystemError`, `TEventQueue`, `TScreen`) is
66    /// folded into the backend construction path; the virtual factory overrides
67    /// (`initDeskTop`, `initStatusLine`, `initMenuBar`) become the three factory
68    /// closures, with `Application` embedding and delegating to its `Program`.
69    pub fn new(
70        backend: Box<dyn Backend>,
71        clock: Box<dyn Clock>,
72        theme: Theme,
73        create_desktop: impl FnOnce(Rect) -> Option<Box<dyn View>>,
74        create_status_line: impl FnOnce(Rect) -> Option<Box<dyn View>>,
75        create_menu_bar: impl FnOnce(Rect) -> Option<Box<dyn View>>,
76    ) -> Self {
77        Application {
78            program: Program::new(
79                backend,
80                clock,
81                theme,
82                create_desktop,
83                create_status_line,
84                create_menu_bar,
85            ),
86        }
87    }
88
89    // -- Delegations to Program (one-line forwards) --------------------------
90
91    /// Run the event loop — delegates to [`Program::run`].
92    pub fn run(&mut self) -> Command {
93        self.program.run()
94    }
95
96    /// One iteration of the event loop — delegates to [`Program::pump_once`].
97    pub fn pump_once(&mut self) {
98        self.program.pump_once();
99    }
100
101    /// Run `view` as a modal dialog — delegates to [`Program::exec_view`].
102    pub fn exec_view(&mut self, view: Box<dyn View>) -> Command {
103        self.program.exec_view(view)
104    }
105
106    /// The desktop child's id — delegates to [`Program::desktop`].
107    pub fn desktop(&self) -> Option<ViewId> {
108        self.program.desktop()
109    }
110
111    /// Request the modal loop end — delegates to [`Program::end_modal`].
112    pub fn end_modal(&mut self, cmd: Command) {
113        self.program.end_modal(cmd);
114    }
115
116    /// The current modal end state — delegates to [`Program::end_state`].
117    pub fn end_state(&self) -> Option<Command> {
118        self.program.end_state()
119    }
120
121    /// Enable a command — delegates to [`Program::enable_command`].
122    pub fn enable_command(&mut self, cmd: Command) {
123        self.program.enable_command(cmd);
124    }
125
126    /// Disable a command — delegates to [`Program::disable_command`].
127    pub fn disable_command(&mut self, cmd: Command) {
128        self.program.disable_command(cmd);
129    }
130
131    /// Whether a command is currently enabled — delegates to
132    /// [`Program::command_enabled`].
133    pub fn command_enabled(&self, cmd: Command) -> bool {
134        self.program.command_enabled(cmd)
135    }
136
137    // -- Escape hatches ------------------------------------------------------
138
139    /// Shared borrow of the embedded [`Program`].
140    pub fn program(&self) -> &Program {
141        &self.program
142    }
143
144    /// Exclusive borrow of the embedded [`Program`].
145    pub fn program_mut(&mut self) -> &mut Program {
146        &mut self.program
147    }
148
149    /// Register a closure that produces the shell-suspend message printed before
150    /// the terminal is yielded to the shell (`Command::DOS_SHELL`).
151    /// See [`Program::set_shell_msg_hook`] for the full contract and an example.
152    pub fn set_shell_msg_hook(&mut self, hook: Box<dyn Fn() -> String>) {
153        self.program.set_shell_msg_hook(hook);
154    }
155
156    // -- tile/cascade layout rectangle ---------------------------------------
157
158    /// The rectangle that the tile and cascade window commands lay windows into:
159    /// the desktop child's local-origin extent `(0, 0, w, h)`, so it stays
160    /// correct when the desktop is inset below a menu bar or above a status line.
161    /// Returns `None` if no desktop was created.
162    ///
163    /// The `TILE` and `CASCADE` command handlers call this internally. You can
164    /// call it directly if you need the desktop layout rectangle for your own
165    /// window-positioning logic (e.g. centering a newly opened window within the
166    /// desktop area). To restrict tiling to a sub-region, size the desktop
167    /// accordingly rather than adjusting this value.
168    ///
169    /// Requires `&mut self` because the underlying `Group::find_mut` requires `&mut`.
170    ///
171    /// # Turbo Vision heritage
172    /// Ports `TApplication::getTileRect` (`tapplica.cpp`); virtual in C++ so
173    /// subclasses could exclude reserved rows. Here the desktop rect is the
174    /// canonical answer; adjust by sizing the desktop in the factory closure.
175    pub fn get_tile_rect(&mut self) -> Option<Rect> {
176        self.program.get_tile_rect()
177    }
178}
179
180// ---------------------------------------------------------------------------
181// Tests
182// ---------------------------------------------------------------------------
183
184#[cfg(test)]
185mod tests {
186    use super::*;
187    use crate::backend::HeadlessBackend;
188    use crate::desktop::Desktop;
189    use crate::event::Event;
190    use crate::timer::ManualClock;
191    use std::rc::Rc;
192
193    /// Build an `Application` with a real `Desktop` and stubbed status-line/menu-bar,
194    /// over a headless backend. Mirrors the `program_with_desktop` harness in
195    /// `program.rs`.
196    fn application_with_desktop(w: u16, h: u16) -> Application {
197        let (backend, _handle) = HeadlessBackend::new(w, h);
198        let theme = Theme::classic_blue();
199        let clock = Rc::new(ManualClock::new(0));
200        Application::new(
201            Box::new(backend),
202            Box::new(clock),
203            theme,
204            |r| {
205                Some(Box::new(Desktop::new(r, |r2| {
206                    Some(Desktop::init_background(r2))
207                })))
208            },
209            |_r| None, // status line stubbed
210            |_r| None, // menu bar stubbed
211        )
212    }
213
214    /// `get_tile_rect` returns the **desktop child's** extent in desktop-local coords
215    /// (`(0,0,dw,dh)`), NOT the screen extent. The desktop is created with an inset
216    /// rect (`(0,0,80,20)`) inside an 80×25 backend, so any code that returned the
217    /// screen rect would produce `(0,0,80,25)` and fail this assertion.
218    #[test]
219    fn get_tile_rect_returns_desktop_extent() {
220        // Backend is 80×25; desktop is inset to 80×20 (a menu/status bar shrinks
221        // it further — this exercises that property).
222        let (backend, _handle) = HeadlessBackend::new(80, 25);
223        let theme = Theme::classic_blue();
224        let clock = Rc::new(ManualClock::new(0));
225        let mut app = Application::new(
226            Box::new(backend),
227            Box::new(clock),
228            theme,
229            |_r| {
230                // Ignore the full-screen `r`; create the desktop with an inset rect
231                // so the test can distinguish desktop-extent from screen-extent.
232                Some(Box::new(Desktop::new(Rect::new(0, 0, 80, 20), |r2| {
233                    Some(Desktop::init_background(r2))
234                })))
235            },
236            |_r| None,
237            |_r| None,
238        );
239        let rect = app.get_tile_rect();
240        assert_eq!(
241            rect,
242            Some(Rect::new(0, 0, 80, 20)),
243            "get_tile_rect must return the desktop's local-origin extent, not the screen rect"
244        );
245    }
246
247    /// `get_tile_rect` returns `None` when no desktop was created.
248    #[test]
249    fn get_tile_rect_none_without_desktop() {
250        let (backend, _handle) = HeadlessBackend::new(40, 12);
251        let theme = Theme::classic_blue();
252        let clock = Rc::new(ManualClock::new(0));
253        let mut app = Application::new(
254            Box::new(backend),
255            Box::new(clock),
256            theme,
257            |_r| None, // no desktop
258            |_r| None,
259            |_r| None,
260        );
261        assert_eq!(app.get_tile_rect(), None);
262    }
263
264    /// Delegation smoke test: `enable_command` + `command_enabled` round-trips
265    /// through `Application`, and `desktop()` returns `Some` when a desktop exists.
266    #[test]
267    fn enable_command_and_desktop_delegation() {
268        let mut app = application_with_desktop(80, 25);
269        assert!(
270            app.desktop().is_some(),
271            "desktop() must return Some after construction with a desktop factory"
272        );
273        // CLOSE starts disabled (per Program's initial_disabled_commands seed);
274        // enable it and verify the forwarding path.
275        assert!(
276            !app.command_enabled(Command::CLOSE),
277            "cmClose starts disabled"
278        );
279        app.enable_command(Command::CLOSE);
280        assert!(
281            app.command_enabled(Command::CLOSE),
282            "enable_command forwarded: cmClose is now enabled"
283        );
284        app.disable_command(Command::CLOSE);
285        assert!(
286            !app.command_enabled(Command::CLOSE),
287            "disable_command forwarded: cmClose disabled again"
288        );
289    }
290
291    /// `Event::Command(Command::DOS_SHELL)` is consumed cleanly — no crash,
292    /// `end_state` stays `None`. HeadlessBackend::suspend/resume are no-ops;
293    /// `raise(SIGTSTP)` is `#[cfg(all(unix, not(test)))]`-gated (no suspension).
294    #[test]
295    fn dos_shell_consumed_cleanly() {
296        let (backend, handle) = HeadlessBackend::new(80, 25);
297        let theme = Theme::classic_blue();
298        let clock = Rc::new(ManualClock::new(0));
299        let mut app = Application::new(
300            Box::new(backend),
301            Box::new(clock),
302            theme,
303            |r| {
304                Some(Box::new(Desktop::new(r, |r2| {
305                    Some(Desktop::init_background(r2))
306                })))
307            },
308            |_r| None,
309            |_r| None,
310        );
311        handle.push_event(Event::Command(Command::DOS_SHELL));
312        app.pump_once();
313        assert_eq!(app.end_state(), None, "DOS_SHELL must not set end_state");
314    }
315}