Guide API
Skip to main content

tvision_rs/widgets/
indicator.rs

1//! `Indicator`, the editor row:col display (documented on the type).
2
3use crate::theme::Role;
4use crate::view::{DrawCtx, GrowMode, Point, Rect, View, ViewState};
5
6// ---------------------------------------------------------------------------
7// Indicator
8// ---------------------------------------------------------------------------
9
10/// A 1-row strip that displays an editor's current cursor position (row:col).
11/// It is owned by the editor and updated through [`Indicator::set_value`].
12///
13/// # Color
14///
15/// [`Role::IndicatorNormal`] when not dragging, [`Role::IndicatorDragging`]
16/// while the editor window is being dragged.
17///
18/// # Glyphs
19///
20/// Glyphs come from `ctx.glyphs()`:
21/// - `indicator_frame_normal` (`═`) — fill char when **not** dragging.
22/// - `indicator_frame_dragging` (`─`) — fill char **while** dragging.
23/// - `indicator_modified` (`☼`) — the "buffer modified" marker.
24///
25/// # Colon alignment
26///
27/// The position string is placed so the `:` lands at column 8. The string is
28/// `" {row}:{col} "`, so the colon sits at byte index `1 + digits(row)` and
29/// drawing starts at `7 - digits(row)`. That only goes negative once the row
30/// number has 8 or more digits (row ≥ 10,000,000) — unreachable in a real
31/// editor, but handled gracefully: [`DrawCtx::put_str`] skips the off-screen
32/// prefix without panicking.
33///
34/// There is no event handling; the indicator is display-only. The dragging
35/// state is read live from the view state each frame.
36///
37/// The owner pushes updates via [`set_value`](Self::set_value); the next
38/// whole-tree redraw reads the updated fields.
39///
40/// # Turbo Vision heritage
41///
42/// Ports `TIndicator` (`tindictr.cpp`). The hardcoded frame characters become
43/// [`Glyphs`](crate::theme::Glyphs) fields and the palette becomes [`Role`]s
44/// (deviation D7).
45pub struct Indicator {
46    /// View state (geometry, flags, etc.) — the composition target.
47    pub state: ViewState,
48    /// Current cursor position displayed as `row:col`.
49    ///
50    /// `y` is the zero-based row; `x` is the zero-based column. Both are
51    /// displayed one-based (so `(0, 0)` renders as `"1:1"`). Read this
52    /// field to inspect the editor's last-reported position; write it only
53    /// through [`set_value`](Self::set_value), which the pump calls when it
54    /// applies a `Deferred::IndicatorSetValue` queued by the editor.
55    ///
56    /// Initialized to `(0, 0)` on construction.
57    pub location: Point,
58    /// Whether the editor buffer has unsaved changes.
59    ///
60    /// When `true` the indicator renders a `☼` marker at column 0. Updated
61    /// alongside [`location`](Self::location) through
62    /// [`set_value`](Self::set_value); do not write directly.
63    ///
64    /// Initialized to `false` on construction.
65    pub modified: bool,
66}
67
68impl Indicator {
69    /// Create a display-only indicator sized to `bounds`.
70    ///
71    /// Embed the returned `Indicator` in an editor group, then let the pump
72    /// keep it current: whenever the editor's cursor moves it queues a
73    /// `Deferred::IndicatorSetValue`; the pump resolves that into a call to
74    /// [`set_value`](Self::set_value) and the next whole-tree redraw picks up
75    /// the new values.
76    ///
77    /// The indicator starts at position `(0, 0)` and unmodified. Its
78    /// `grow_mode` is set to `lo_y | hi_y` so that it follows the bottom edge
79    /// of the enclosing window when the window is resized. It is never
80    /// selectable — the indicator is display-only and cannot receive focus.
81    ///
82    /// # Turbo Vision heritage
83    ///
84    /// Mirrors `TIndicator::TIndicator(bounds)`: sets
85    /// `growMode = gfGrowLoY | gfGrowHiY` and does not set `ofSelectable`.
86    pub fn new(bounds: Rect) -> Self {
87        let mut state = ViewState::new(bounds);
88        state.grow_mode = GrowMode {
89            lo_y: true,
90            hi_y: true,
91            ..Default::default()
92        };
93        Indicator {
94            state,
95            location: Point::new(0, 0),
96            modified: false,
97        }
98    }
99
100    /// Update the cursor position and modified flag displayed by the indicator.
101    ///
102    /// Do not call this directly from application code. The intended call path
103    /// is: editor queues `Deferred::IndicatorSetValue` → pump resolves the
104    /// deferred by downcasting via `as_any_mut` to `&mut Indicator` and
105    /// calling this method. The next whole-tree redraw then picks up the new
106    /// values without any explicit `drawView` call.
107    ///
108    /// This differs from the C++ `TIndicator::setValue`, which calls `drawView`
109    /// immediately and skips the update entirely when neither value changes. The
110    /// Rust port omits the no-op guard (the unconditional whole-tree redraw
111    /// makes it unnecessary) and defers the redraw to the pump cycle.
112    ///
113    /// # Turbo Vision heritage
114    ///
115    /// Ports `TIndicator::setValue(loc, mod)` (`tindictr.cpp`), minus the
116    /// early-return guard for unchanged values.
117    pub fn set_value(&mut self, location: Point, modified: bool) {
118        self.location = location;
119        self.modified = modified;
120    }
121}
122
123impl View for Indicator {
124    fn state(&self) -> &ViewState {
125        &self.state
126    }
127
128    fn state_mut(&mut self) -> &mut ViewState {
129        &mut self.state
130    }
131
132    /// Delivers an editor→indicator status push: stores the new cursor `location`
133    /// and `modified` flag. Called by the pump when applying a
134    /// [`Deferred::IndicatorSetValue`](crate::view::Deferred::IndicatorSetValue)
135    /// from an editor's `doUpdate`. Virtual dispatch via the `View` trait — no
136    /// downcast needed.
137    fn set_indicator_value(&mut self, location: Point, modified: bool) {
138        self.set_value(location, modified);
139    }
140
141    /// Concrete-reach hatch retained for test inspection (reading `location` from
142    /// an integration test requires the concrete type). No longer used by the
143    /// `IndicatorSetValue` pump arm, which now calls
144    /// [`set_indicator_value`](View::set_indicator_value) via virtual dispatch.
145    fn as_any_mut(&mut self) -> Option<&mut dyn core::any::Any> {
146        Some(self)
147    }
148
149    /// Paint the one-row position display.
150    ///
151    /// Draw order:
152    /// 1. Fill row 0 with the frame char (`═` or `─`) in the current role.
153    /// 2. If `modified`, overwrite column 0 with `☼` in the same role.
154    /// 3. Draw the position string so that the `:` lands at column 8.
155    fn draw(&mut self, ctx: &mut DrawCtx) {
156        let glyphs = *ctx.glyphs();
157        let dragging = self.state.state.dragging;
158
159        // Faithful inversion: C++ draws `dragFrame` (═) when NOT dragging,
160        // and `normalFrame` (─) while dragging. Our glyph names follow the
161        // C++ semantics verbatim despite the inverted field names.
162        let (frame_ch, color) = if !dragging {
163            (
164                glyphs.indicator_frame_normal,
165                ctx.style(Role::IndicatorNormal),
166            )
167        } else {
168            (
169                glyphs.indicator_frame_dragging,
170                ctx.style(Role::IndicatorDragging),
171            )
172        };
173
174        // Step 1: fill the entire row with the frame character.
175        ctx.fill(Rect::new(0, 0, self.state.size.x, 1), frame_ch, color);
176
177        // Step 2: modified marker at column 0 (C++ `b.putChar(0, 15)`; char 15 = ☼).
178        if self.modified {
179            ctx.put_char(0, 0, glyphs.indicator_modified, color);
180        }
181
182        // Step 3: position string — " row:col " with ':' at column 8.
183        //
184        // C++: `os << ' ' << (location.y+1) << ':' << (location.x+1) << ' '`
185        // i.e. y (row) before x (col), one-based, space-padded on both sides.
186        let s = format!(" {}:{} ", self.location.y + 1, self.location.x + 1);
187        // The colon's byte offset equals its column index (ASCII prefix only).
188        let colon_col = s.find(':').expect("format string always contains ':'") as i32;
189        let start_col = 8 - colon_col;
190        // start_col can be negative for very large row numbers; put_str handles
191        // that via its text_indent path (skips off-screen prefix without panic).
192        ctx.put_str(start_col, 0, &s, color);
193    }
194}
195
196// ---------------------------------------------------------------------------
197// Tests
198// ---------------------------------------------------------------------------
199
200#[cfg(test)]
201mod tests {
202    use super::*;
203    use crate::backend::{HeadlessBackend, Renderer};
204    use crate::screen::Buffer;
205    use crate::theme::Theme;
206    use crate::view::Point;
207
208    // -----------------------------------------------------------------------
209    // set_value
210    // -----------------------------------------------------------------------
211
212    #[test]
213    fn set_value_updates_location_and_modified() {
214        let mut ind = Indicator::new(Rect::new(0, 0, 20, 1));
215        assert_eq!(ind.location, Point::new(0, 0));
216        assert!(!ind.modified);
217
218        ind.set_value(Point::new(4, 2), true);
219        assert_eq!(ind.location, Point::new(4, 2));
220        assert!(ind.modified);
221
222        ind.set_value(Point::new(10, 99), false);
223        assert_eq!(ind.location, Point::new(10, 99));
224        assert!(!ind.modified);
225    }
226
227    #[test]
228    fn set_value_overwrites_previous() {
229        let mut ind = Indicator::new(Rect::new(0, 0, 20, 1));
230        ind.set_value(Point::new(1, 1), true);
231        ind.set_value(Point::new(7, 3), false);
232        assert_eq!(ind.location, Point::new(7, 3));
233        assert!(!ind.modified);
234    }
235
236    // -----------------------------------------------------------------------
237    // grow_mode
238    // -----------------------------------------------------------------------
239
240    #[test]
241    fn grow_mode_is_lo_y_and_hi_y() {
242        let ind = Indicator::new(Rect::new(0, 0, 20, 1));
243        assert!(ind.state.grow_mode.lo_y, "gfGrowLoY must be set");
244        assert!(ind.state.grow_mode.hi_y, "gfGrowHiY must be set");
245        assert!(!ind.state.grow_mode.lo_x);
246        assert!(!ind.state.grow_mode.hi_x);
247    }
248
249    // -----------------------------------------------------------------------
250    // Snapshot tests
251    // -----------------------------------------------------------------------
252
253    /// Normal state: location (x=4, y=2) → displays " 3:5 " with ':' at col 8.
254    /// Frame = ═ (indicator_frame_normal), role = IndicatorNormal.
255    #[test]
256    fn snapshot_normal() {
257        let theme = Theme::classic_blue();
258        let mut ind = Indicator::new(Rect::new(0, 0, 16, 1));
259        ind.set_value(Point::new(4, 2), false);
260
261        let (backend, screen) = HeadlessBackend::new(16, 1);
262        let mut r = Renderer::new(Box::new(backend));
263        r.render(|buf: &mut Buffer| {
264            let bounds = ind.state.get_bounds();
265            let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
266            ind.draw(&mut dc);
267        });
268        insta::assert_snapshot!(screen.snapshot());
269    }
270
271    /// Modified marker: same position but `modified = true` → ☼ at col 0.
272    #[test]
273    fn snapshot_modified() {
274        let theme = Theme::classic_blue();
275        let mut ind = Indicator::new(Rect::new(0, 0, 16, 1));
276        ind.set_value(Point::new(4, 2), true);
277
278        let (backend, screen) = HeadlessBackend::new(16, 1);
279        let mut r = Renderer::new(Box::new(backend));
280        r.render(|buf: &mut Buffer| {
281            let bounds = ind.state.get_bounds();
282            let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
283            ind.draw(&mut dc);
284        });
285        insta::assert_snapshot!(screen.snapshot());
286    }
287
288    /// Dragging state: `sfDragging` set → ─ frame + IndicatorDragging role.
289    #[test]
290    fn snapshot_dragging() {
291        let theme = Theme::classic_blue();
292        let mut ind = Indicator::new(Rect::new(0, 0, 16, 1));
293        ind.set_value(Point::new(4, 2), false);
294        // Set dragging directly — no ctx needed (no side effects to propagate).
295        ind.state.state.dragging = true;
296
297        let (backend, screen) = HeadlessBackend::new(16, 1);
298        let mut r = Renderer::new(Box::new(backend));
299        r.render(|buf: &mut Buffer| {
300            let bounds = ind.state.get_bounds();
301            let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
302            ind.draw(&mut dc);
303        });
304        insta::assert_snapshot!(screen.snapshot());
305    }
306
307    /// Colon alignment check: location (x=0, y=0) → " 1:1 "
308    /// colon is at byte 2, so start_col = 8 - 2 = 6; ':' rendered at col 8.
309    #[test]
310    fn snapshot_colon_at_column_8_small_numbers() {
311        let theme = Theme::classic_blue();
312        let mut ind = Indicator::new(Rect::new(0, 0, 16, 1));
313        ind.set_value(Point::new(0, 0), false);
314
315        let (backend, screen) = HeadlessBackend::new(16, 1);
316        let mut r = Renderer::new(Box::new(backend));
317        r.render(|buf: &mut Buffer| {
318            let bounds = ind.state.get_bounds();
319            let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
320            ind.draw(&mut dc);
321        });
322        insta::assert_snapshot!(screen.snapshot());
323    }
324
325    /// Large row number: location (x=0, y=9999) → " 10000:1 "
326    /// colon at byte 6, start_col = 7 - 5 digits = 2; ':' at col 8. No panic.
327    #[test]
328    fn snapshot_large_row_number() {
329        let theme = Theme::classic_blue();
330        let mut ind = Indicator::new(Rect::new(0, 0, 16, 1));
331        ind.set_value(Point::new(0, 9999), false);
332
333        let (backend, screen) = HeadlessBackend::new(16, 1);
334        let mut r = Renderer::new(Box::new(backend));
335        r.render(|buf: &mut Buffer| {
336            let bounds = ind.state.get_bounds();
337            let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
338            ind.draw(&mut dc);
339        });
340        insta::assert_snapshot!(screen.snapshot());
341    }
342
343    /// Genuinely-negative `start_col`: an 8-digit displayed row (y=9_999_999 →
344    /// " 10000000:1 ", colon at byte 9, `start_col = 8 - 9 = -1`). Exercises
345    /// `DrawCtx::put_str`'s off-screen-prefix skip — must not panic, and the
346    /// leading space of the string is clipped off the left.
347    #[test]
348    fn negative_start_col_does_not_panic() {
349        let theme = Theme::classic_blue();
350        let mut ind = Indicator::new(Rect::new(0, 0, 16, 1));
351        ind.set_value(Point::new(0, 9_999_999), false);
352
353        let (backend, screen) = HeadlessBackend::new(16, 1);
354        let mut r = Renderer::new(Box::new(backend));
355        r.render(|buf: &mut Buffer| {
356            let bounds = ind.state.get_bounds();
357            let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
358            ind.draw(&mut dc);
359        });
360        // start_col = -1: the leading ' ' is clipped, so "10000000:1 " begins at
361        // col 0 and the colon lands at col 7 (was 8 before the left-clip).
362        let snap = screen.snapshot();
363        assert!(
364            snap.contains("10000000:1"),
365            "row string rendered, left-clipped"
366        );
367    }
368}