Guide API
Skip to main content

tvision_rs/dialog/colorpick/
mod.rs

1//! The truecolor `ColorPicker` (documented on the type).
2
3pub(crate) mod drag;
4mod info;
5pub mod model;
6mod page;
7pub(crate) mod plane;
8pub(crate) mod presets;
9pub(crate) mod rgb;
10pub(crate) mod xterm256;
11
12use std::cell::RefCell;
13use std::rc::Rc;
14
15use crate::color::Color;
16use crate::data::FieldValue;
17use crate::event::{Event, Key, hot_key};
18use crate::view::{Context, DrawCtx, Group, Point, Rect, View, ViewId};
19use model::ColorModel;
20
21/// The picker's surfaces and info column share one model.
22pub(crate) type SharedModel = Rc<RefCell<model::ColorModel>>;
23
24/// A picker surface — draws + handles events against the shared [`ColorModel`].
25pub(crate) trait Surface {
26    fn draw(&self, ctx: &mut DrawCtx, body: Rect, m: &ColorModel);
27    fn handle_event(&mut self, ev: &mut Event, body: Rect, m: &mut ColorModel, ctx: &mut Context);
28    fn drag_region_at(&self, _p: Point, _body: Rect) -> Option<drag::ColorDragRegion> {
29        None
30    }
31    fn apply_drag(
32        &mut self,
33        _region: drag::ColorDragRegion,
34        _p: Point,
35        _body: Rect,
36        _m: &mut ColorModel,
37    ) {
38    }
39}
40
41// -- Tab enum -----------------------------------------------------------------
42
43/// The active surface tab.
44#[derive(Clone, Copy, Debug, PartialEq, Eq)]
45pub enum Tab {
46    Presets,
47    Rgb,
48    Plane,
49    Xterm256,
50}
51
52impl Tab {
53    const ORDER: [Tab; 4] = [Tab::Presets, Tab::Rgb, Tab::Plane, Tab::Xterm256];
54
55    /// Label for the tab bar, with `~X~` marking the (unique) hotkey letter.
56    fn label(self) -> &'static str {
57        match self {
58            Tab::Presets => "~P~resets",
59            Tab::Rgb => "~R~GB",
60            Tab::Plane => "~H~ue/Sat",
61            Tab::Xterm256 => "~X~term",
62        }
63    }
64
65    /// The four labels in tab order (Presets, Rgb, Plane, Xterm256).
66    fn labels() -> [&'static str; 4] {
67        [
68            Tab::Presets.label(),
69            Tab::Rgb.label(),
70            Tab::Plane.label(),
71            Tab::Xterm256.label(),
72        ]
73    }
74
75    fn idx(self) -> usize {
76        // ORDER is exhaustive over all Tab variants, so position() always succeeds.
77        Self::ORDER.iter().position(|&t| t == self).unwrap()
78    }
79}
80
81// -- ColorPicker container ----------------------------------------------------
82
83/// The reusable, embeddable truecolor color-picker view. A `Group` wrapping a
84/// `TabBar` + `PageStack` (four surface pages) + an `InfoColumn`, all sharing one
85/// `ColorModel`. Does NOT own OK/Cancel (dialog chrome).
86///
87/// Truecolor color picker, a tvision-rs extension that replaces `TColorDialog`.
88///
89/// [`ColorPicker`] is a [`Group`](crate::view::Group) container assembled from a
90/// [`TabBar`](crate::widgets::TabBar) (tab strip), a
91/// [`PageStack`](crate::widgets::PageStack) of four surface pages, and an
92/// always-visible `InfoColumn`. The four surfaces and the info column share one
93/// `ColorModel` through a `SharedModel`. Produces any
94/// [`Color`](crate::color::Color) variant.
95///
96/// # Turbo Vision heritage
97///
98/// **tvision-rs extension**: no Turbo Vision counterpart. It takes the place of the
99/// `TColorDialog` cluster (`colorsel.h`), which edited the application's
100/// `TPalette`, each entry a foreground/background attribute built from the BIOS
101/// colors. tvision-rs replaces that
102/// palette with a role-based [`Theme`](crate::theme::Theme).
103pub struct ColorPicker {
104    group: Group,
105    tab_bar_id: ViewId,
106    page_stack_id: ViewId,
107    model: SharedModel,
108    /// A tab preselected via [`select_tab`](Self::select_tab) before the modal
109    /// loop, applied (page-switch sync queued) on the first event.
110    pending_tab: Option<usize>,
111}
112
113/// Info-column width. Sized to fit the widest readout (`Rgb(255,255,255)` is 16
114/// chars) plus a 1-cell left margin and a little slack → 18. With the real picker
115/// sizes (color_dialog 56 wide, gallery/tvdemo 58–60 wide) this leaves the
116/// surface body ≈ 38–42 cols, matching the old fixed `body=38` layout.
117const INFO_COL_W: i32 = 18;
118
119impl ColorPicker {
120    /// Build a `ColorPicker` occupying `bounds`, seeded with `initial` as the
121    /// starting color.
122    ///
123    /// The picker is a [`Group`](crate::view::Group) containing a `TabBar`,
124    /// a `PageStack` of four surface pages (Presets, RGB, Plane, Xterm-256),
125    /// and an always-visible `InfoColumn`. All surfaces share one `ColorModel`.
126    ///
127    /// `bounds` sets the picker's absolute position within its owner (non-zero
128    /// origin is supported — embed it inside a dialog with an inset, e.g.
129    /// `Rect::new(2, 2, 58, 20)`). The picker handles OK/Cancel buttons
130    /// externally; embed it inside a [`Dialog`](crate::dialog::Dialog) and add
131    /// buttons separately, or use the convenience wrapper
132    /// [`Program::color_dialog`](crate::Program::color_dialog).
133    ///
134    /// # Turbo Vision heritage
135    /// No Turbo Vision counterpart. Supersedes `TColorDialog::Init` (guide
136    /// p. 407–408), which built a fixed 62×19 dialog editing the application's
137    /// `TPalette` attributes. This constructor builds only the picker body; the caller owns
138    /// the dialog chrome.
139    pub fn new(bounds: Rect, initial: Color) -> Self {
140        let w = bounds.b.x - bounds.a.x;
141        let h = bounds.b.y - bounds.a.y;
142        let body_w = (w - INFO_COL_W).max(1);
143
144        let model: SharedModel = Rc::new(RefCell::new(ColorModel::new(initial)));
145
146        // The group carries the picker's real `bounds` (not a (0,0)-based extent):
147        // its origin is what the parent's `ctx.sub(child_bounds)` offsets by, so a
148        // non-zero placement (e.g. a dialog inserting the picker at (2,2)) lands
149        // correctly instead of overdrawing the parent's frame. Children below stay
150        // in (0,0)-based local coordinates.
151        let mut group = Group::new(bounds);
152        // Embeddable selectable child with first-click activation (port of the
153        // old ctor's `Options { selectable: true, first_click: true, .. }`).
154        {
155            let opts = &mut group.state_mut().options;
156            opts.selectable = true;
157            opts.first_click = true;
158        }
159
160        // Tab strip (row 0, body-width).
161        let labels = Tab::labels();
162        let tab_bar = crate::widgets::TabBar::new(Rect::new(0, 0, body_w, 1), &labels);
163        let tab_bar_id = group.insert(Box::new(tab_bar));
164
165        // Page stack (rows 1..h), one page per surface.
166        let mut page_stack = crate::widgets::PageStack::new(Rect::new(0, 1, body_w, h));
167        let ext = Rect::new(0, 0, body_w, (h - 1).max(1));
168        page_stack.insert_page(Box::new(page::SurfacePage::new(
169            ext,
170            presets::PresetsSurface::new(&model.borrow()),
171            model.clone(),
172        )));
173        page_stack.insert_page(Box::new(page::SurfacePage::new(
174            ext,
175            rgb::RgbSurface::new(),
176            model.clone(),
177        )));
178        page_stack.insert_page(Box::new(page::SurfacePage::new(
179            ext,
180            plane::PlaneSurface::new(),
181            model.clone(),
182        )));
183        page_stack.insert_page(Box::new(page::SurfacePage::new(
184            ext,
185            xterm256::Xterm256Surface::new(&model.borrow()),
186            model.clone(),
187        )));
188        page_stack.bind_tab_bar(tab_bar_id);
189        let page_stack_id = group.insert(Box::new(page_stack));
190
191        // Info column (right of the body, full height).
192        let info =
193            info::InfoColumn::new(Rect::new(w - INFO_COL_W, 0, w, h), model.clone(), initial);
194        group.insert(Box::new(info));
195
196        ColorPicker {
197            group,
198            tab_bar_id,
199            page_stack_id,
200            model,
201            pending_tab: None,
202        }
203    }
204
205    /// The current selection — the contract `color_dialog` reads.
206    pub fn color(&self) -> Color {
207        self.model.borrow().color
208    }
209
210    /// Open the picker on a specific [`Tab`]. By default the picker starts on the
211    /// preset palette; call this to preselect another surface (e.g. the visual
212    /// hue/saturation [`Tab::Plane`]) when embedding the picker yourself. Called
213    /// BEFORE the modal loop (no `Context`): the TabBar value is set now so the
214    /// strip shows the right active tab immediately, and the page switch is
215    /// stashed to apply on the first event (the broker needs a `Context`).
216    pub fn select_tab(&mut self, tab: Tab) {
217        let idx = tab.idx();
218        self.pending_tab = Some(idx);
219        self.set_tab_bar_value(idx);
220    }
221
222    /// Set the embedded `TabBar`'s value (no ctx — see `TabBar::set_value`).
223    fn set_tab_bar_value(&mut self, idx: usize) {
224        if let Some(tb) = self
225            .group
226            .child_mut(self.tab_bar_id)
227            .and_then(|v| v.as_any_mut())
228            .and_then(|a| a.downcast_mut::<crate::widgets::TabBar>())
229        {
230            View::set_value(tb, FieldValue::Int(idx as i32));
231        }
232    }
233
234    /// Read the embedded `TabBar`'s selected index.
235    fn tab_bar_selected(&mut self) -> usize {
236        self.group
237            .child_mut(self.tab_bar_id)
238            .and_then(|v| v.as_any_mut())
239            .and_then(|a| a.downcast_mut::<crate::widgets::TabBar>())
240            .map(|tb| tb.selected())
241            .unwrap_or(0)
242    }
243
244    /// Drive a tab change exactly as a strip click would: set the TabBar value and
245    /// queue the PageStack sync (the broker switches the visible page).
246    fn switch_to_tab(&mut self, idx: usize, ctx: &mut Context) {
247        self.set_tab_bar_value(idx);
248        ctx.request_sync_page_stack(self.page_stack_id, self.tab_bar_id);
249    }
250}
251
252#[crate::delegate(to = group, skip(as_any_mut, handle_event, value, set_value))]
253impl View for ColorPicker {
254    fn as_any_mut(&mut self) -> Option<&mut dyn core::any::Any> {
255        Some(self)
256    }
257
258    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
259        // On the first event after a pre-modal `select_tab`, apply the stashed
260        // page switch (set_value alone moved the strip; the broker moves the page).
261        if let Some(idx) = self.pending_tab.take() {
262            self.switch_to_tab(idx, ctx);
263        }
264
265        if let Event::KeyDown(ke) = *ev {
266            // Ctrl+Left/Right cycle the tab.
267            if ke.modifiers.ctrl && matches!(ke.key, Key::Left | Key::Right) {
268                let n = Tab::ORDER.len();
269                let cur = self.tab_bar_selected();
270                let next = if matches!(ke.key, Key::Right) {
271                    (cur + 1) % n
272                } else {
273                    (cur + n - 1) % n
274                };
275                self.switch_to_tab(next, ctx);
276                ev.clear();
277                return;
278            }
279            // Alt+hotkey jumps to a tab (P/R/H/X).
280            if ke.modifiers.alt
281                && let Key::Char(c) = ke.key
282            {
283                let up = c.to_ascii_uppercase();
284                for t in Tab::ORDER {
285                    if hot_key(t.label()) == Some(up) {
286                        self.switch_to_tab(t.idx(), ctx);
287                        ev.clear();
288                        return;
289                    }
290                }
291            }
292            // Plain Tab / Shift+Tab belong to the dialog — leave uncleared.
293            if ke.key == Key::Tab {
294                return;
295            }
296        }
297
298        // Everything else routes into the group: a strip click broadcasts
299        // TAB_BAR_CHANGED → the PageStack broker switches the page; plain keys
300        // route to the focused page; the info column ignores them.
301        self.group.handle_event(ev, ctx);
302    }
303}
304
305// -- Tests --------------------------------------------------------------------
306
307#[cfg(test)]
308mod view_tests {
309    use super::*;
310    use crate::color::Color;
311    use crate::event::{Key, KeyEvent, KeyModifiers};
312    use crate::timer::TimerQueue;
313    use crate::view::Deferred;
314    use std::collections::VecDeque;
315
316    fn ctrl(k: Key) -> Event {
317        Event::KeyDown(KeyEvent::new(
318            k,
319            KeyModifiers {
320                ctrl: true,
321                ..Default::default()
322            },
323        ))
324    }
325
326    fn plain(k: Key) -> Event {
327        Event::KeyDown(KeyEvent::new(k, KeyModifiers::default()))
328    }
329
330    #[test]
331    fn color_returns_seed() {
332        let p = ColorPicker::new(Rect::new(0, 0, 56, 18), Color::Rgb(30, 144, 255));
333        assert_eq!(p.color(), Color::Rgb(30, 144, 255));
334    }
335
336    #[test]
337    fn ctrl_right_cycles_tab_and_queues_sync() {
338        let mut p = ColorPicker::new(Rect::new(0, 0, 56, 18), Color::Default);
339        assert_eq!(p.tab_bar_selected(), 0);
340
341        let mut out = VecDeque::new();
342        let mut timers = TimerQueue::new();
343        let mut deferred: Vec<Deferred> = Vec::new();
344        {
345            let mut ctx = Context::new(&mut out, &mut timers, 0, &mut deferred);
346            let mut ev = ctrl(Key::Right);
347            p.handle_event(&mut ev, &mut ctx);
348            assert!(ev.is_nothing());
349        }
350        assert_eq!(p.tab_bar_selected(), 1, "Ctrl+Right advances the TabBar");
351        assert!(
352            deferred
353                .iter()
354                .any(|d| matches!(d, Deferred::PageStackSync { .. })),
355            "a PageStackSync is queued so the page switches too"
356        );
357    }
358
359    #[test]
360    fn plain_tab_is_left_unhandled() {
361        let mut p = ColorPicker::new(Rect::new(0, 0, 56, 18), Color::Default);
362        let mut out = VecDeque::new();
363        let mut timers = TimerQueue::new();
364        let mut deferred: Vec<Deferred> = Vec::new();
365        let mut ctx = Context::new(&mut out, &mut timers, 0, &mut deferred);
366        let mut ev = plain(Key::Tab);
367        p.handle_event(&mut ev, &mut ctx);
368        assert!(!ev.is_nothing(), "plain Tab must pass to the dialog");
369    }
370
371    #[test]
372    fn switching_tab_does_not_change_color() {
373        let mut p = ColorPicker::new(Rect::new(0, 0, 56, 18), Color::Rgb(10, 20, 30));
374        let mut out = VecDeque::new();
375        let mut timers = TimerQueue::new();
376        let mut deferred: Vec<Deferred> = Vec::new();
377        let mut ctx = Context::new(&mut out, &mut timers, 0, &mut deferred);
378        let mut ev = ctrl(Key::Right);
379        p.handle_event(&mut ev, &mut ctx);
380        assert_eq!(p.color(), Color::Rgb(10, 20, 30));
381    }
382
383    #[test]
384    fn select_tab_sets_strip_immediately() {
385        let mut p = ColorPicker::new(Rect::new(0, 0, 56, 18), Color::Default);
386        p.select_tab(Tab::Plane);
387        assert_eq!(
388            p.tab_bar_selected(),
389            Tab::Plane.idx(),
390            "select_tab moves the strip before any event"
391        );
392        assert_eq!(p.pending_tab, Some(Tab::Plane.idx()));
393    }
394
395    #[test]
396    fn picker_group_keeps_its_placement_origin() {
397        // Regression: the picker's Group must carry the real `bounds` (origin 2,2),
398        // not a (0,0)-based extent — otherwise the parent's `ctx.sub(child_bounds)`
399        // applies no offset and the picker overdraws the dialog frame (tab bar on
400        // the title row, left edge on the left border).
401        let p = ColorPicker::new(Rect::new(2, 2, 60, 19), Color::Default);
402        let b = View::state(&p).get_bounds();
403        assert_eq!((b.a.x, b.a.y), (2, 2), "picker keeps its placement origin");
404        assert_eq!(
405            (b.b.x - b.a.x, b.b.y - b.a.y),
406            (58, 17),
407            "picker keeps its size"
408        );
409    }
410}
411
412#[cfg(test)]
413mod snap_tests {
414    use super::*;
415    use crate::backend::{HeadlessBackend, Renderer};
416    use crate::color::Color;
417    use crate::screen::Buffer;
418    use crate::theme::Theme;
419    use crate::view::DrawCtx;
420
421    /// Render the whole picker Group at a realistic 56×18 (the color_dialog size).
422    /// A 40×12 canvas would shrink the body to 40−18=22 cols — too narrow for the
423    /// preset list to read — so we use the real picker size here.
424    fn render_picker(initial: Color, tab: Tab) -> String {
425        let theme = Theme::classic_blue();
426        let (backend, screen) = HeadlessBackend::new(56, 18);
427        let mut r = Renderer::new(Box::new(backend));
428        let mut p = ColorPicker::new(Rect::new(0, 0, 56, 18), initial);
429        p.select_tab(tab);
430        r.render(|buf: &mut Buffer| {
431            let bounds = Rect::new(0, 0, 56, 18);
432            let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
433            p.draw(&mut dc);
434        });
435        screen.snapshot()
436    }
437
438    #[test]
439    fn snapshot_picker_presets() {
440        insta::assert_snapshot!(render_picker(Color::Bios(4), Tab::Presets));
441    }
442
443    /// Extract the `text:` rows (the `|...|` lines) from a snapshot string.
444    fn text_rows(snap: &str) -> Vec<String> {
445        let mut rows = Vec::new();
446        let mut in_text = false;
447        for line in snap.lines() {
448            match line {
449                "text:" => in_text = true,
450                "attr:" | "legend:" => in_text = false,
451                _ if in_text && line.starts_with('|') && line.ends_with('|') => {
452                    rows.push(line[1..line.len() - 1].to_string());
453                }
454                _ => {}
455            }
456        }
457        rows
458    }
459
460    #[test]
461    fn picker_nested_at_offset_renders_below_and_right_of_origin() {
462        // Regression for the (0,0)-origin bug: place the picker at (2,2) inside a
463        // parent Group and render the parent. The tab bar must land on row 2 / col 2,
464        // never on the parent's (0,0) corner.
465        let theme = Theme::classic_blue();
466        let (backend, screen) = HeadlessBackend::new(60, 20);
467        let mut r = Renderer::new(Box::new(backend));
468        let mut parent = crate::view::Group::new(Rect::new(0, 0, 60, 20));
469        let mut picker = ColorPicker::new(Rect::new(2, 2, 60, 19), Color::Default);
470        picker.select_tab(Tab::Presets);
471        parent.insert(Box::new(picker));
472        r.render(|buf: &mut Buffer| {
473            let bounds = Rect::new(0, 0, 60, 20);
474            let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
475            parent.draw(&mut dc);
476        });
477        let rows = text_rows(&screen.snapshot());
478        assert!(
479            !rows[0].contains("Presets") && !rows[1].contains("Presets"),
480            "tab bar must not overdraw the parent's top rows; row0={:?} row1={:?}",
481            rows[0],
482            rows[1]
483        );
484        // Row 2 (the picker's origin) carries the tab strip, offset by 2 columns:
485        // 2 leading blanks, then the active corner-cap `┌Presets┐`.
486        assert!(
487            rows[2].starts_with("  ┌Presets┐"),
488            "tab strip starts 2 cols in with the active corner-cap; row2={:?}",
489            rows[2]
490        );
491    }
492}