Skip to main content

mouser_mode_api/
ui.rs

1//! The UI model shared by Mouser and mode plugins: plain data a mode lays
2//! out and the host draws.
3
4/// A rectangle in window pixels.
5#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize, Default)]
6pub struct Rect {
7    pub x: i32,
8    pub y: i32,
9    pub w: i32,
10    pub h: i32,
11}
12
13impl Rect {
14    pub fn contains(&self, px: i32, py: i32) -> bool {
15        px >= self.x && px < self.x + self.w && py >= self.y && py < self.y + self.h
16    }
17}
18
19/// Pixel geometry of the window, so a view can lay out in real cells.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
21pub struct Viewport {
22    pub width: i32,
23    pub height: i32,
24    pub cell_w: i32,
25    pub cell_h: i32,
26}
27
28/// How the host draws one panel item.
29#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
30pub enum PanelStyle {
31    Title,
32    Label,
33    Hint,
34    Error,
35    /// Selectable list row.
36    Row {
37        selected: bool,
38    },
39    Button {
40        primary: bool,
41    },
42    /// Text input; `valid` false draws it in the error colour.
43    Field {
44        focused: bool,
45        valid: bool,
46    },
47    /// Colour sample.
48    Swatch(u32),
49    /// Framed tile (commander grid / carousel item).
50    Tile {
51        selected: bool,
52    },
53    /// Background of a dropdown drawn over the panel.
54    Popup,
55    /// A veil over the rect (`0` clear … `255` opaque black) for motion such as
56    /// the fullscreen viewer backdrop.
57    Dim(u8),
58    /// Name tag drawn on top of everything, previews included (commander
59    /// carousel): a slightly transparent rounded box with a soft shadow.
60    FloatLabel,
61    /// Folder icon filling the rect (commander carousel).
62    FolderIcon,
63    /// Type badge (`mouser_core::commander::Badge` index) on a grid tile or
64    /// carousel item, drawn on top like [`PanelStyle::FloatLabel`].
65    Badge(u8),
66    /// Seek / volume bar: `done` and the hover mark (`u16::MAX`: none) in 1/1000.
67    Progress {
68        done: u16,
69        hover: u16,
70    },
71    /// Scroll position: a slim track with a thumb from `start` for `len`
72    /// (1/1000 of the content). Vertical when taller than wide.
73    Scrollbar {
74        start: u16,
75        len: u16,
76    },
77    /// Dropdown row; bit `i` of `highlight` marks char `i` as matched.
78    Option {
79        selected: bool,
80        highlight: u64,
81    },
82    /// Font picker row: `text` is the family name and is drawn in that face.
83    FontOption {
84        selected: bool,
85        highlight: u64,
86    },
87    /// Mini terminal sample for live theme edits (side preview).
88    ThemePreview {
89        fg: u32,
90        bg: u32,
91        cursor: u32,
92        accent: u32,
93    },
94    /// A markdown text run (`mouser_core::markdown` span flags; `heading`
95    /// level, 0 for body text).
96    Md {
97        flags: u8,
98        heading: u8,
99    },
100    /// Markdown code block background, rounded at the block's `top` and `bottom`.
101    MdCode {
102        top: bool,
103        bottom: bool,
104    },
105    /// A highlighted run in a Markdown code block: its token class
106    /// (`mouser_core::highlight`), coloured from the theme's palette.
107    MdToken(u8),
108    /// Markdown block quote bar.
109    MdQuote,
110    /// Markdown thematic break.
111    MdRule,
112    /// A rounded outline box (the chat's frames, like grokbot-tui's): the
113    /// item's text is a title set into the top edge; `focused` draws it in the
114    /// accent. Nothing is filled, so items drawn after it show inside.
115    Frame {
116        focused: bool,
117    },
118    /// A rounded message bubble behind the rows drawn after it; `mine`
119    /// tints it with the accent (your messages).
120    Bubble {
121        mine: bool,
122    },
123}
124
125/// What clicking a panel item a mode drew does. Mouser's own windows use a
126/// wider action set (`mouser_render::ui::UiAction`); a mode only ever gets
127/// its own actions back, as `ui.action` events.
128#[derive(Debug, Clone, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
129pub enum Action {
130    #[default]
131    None,
132    /// The mode's own action id and an argument (e.g. an item index).
133    Mode { action: String, arg: i32 },
134}
135
136/// One drawn item: a rectangle, its text, how it looks and what a click does.
137#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
138pub struct PanelItem<A = Action> {
139    pub rect: Rect,
140    pub text: String,
141    pub style: PanelStyle,
142    pub action: A,
143}
144
145/// A dock or floating window: a frame and its items, drawn in order.
146#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
147pub struct Panel<A = Action> {
148    pub rect: Rect,
149    pub items: Vec<PanelItem<A>>,
150}
151
152impl<A> Panel<A> {
153    /// The same panel with each item's action converted (a plugin's
154    /// [`Action`]s into the host's action type).
155    pub fn map<B>(self, mut f: impl FnMut(A) -> B) -> Panel<B> {
156        Panel {
157            rect: self.rect,
158            items: self.items.into_iter().map(|i| PanelItem { rect: i.rect, text: i.text, style: i.style, action: f(i.action) }).collect(),
159        }
160    }
161}
162
163/// The dock height the user chose (dragging the dock's bottom edge, the
164/// host's taller / shorter keys, or its fullscreen toggle). Mouser sends it as
165/// `dock` in the `view.resized` payload (and again whenever it changes);
166/// a mode lays its dock out with [`DockSize::height`]. Older modes ignore it
167/// and keep their own height.
168#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
169pub struct DockSize {
170    /// Share of the terminal area in 1/1000 (`None`: the mode's default).
171    #[serde(default)]
172    pub permille: Option<u16>,
173    /// The dock fills the whole terminal area (the shell is hidden until it
174    /// is toggled off; the terminal keeps its size).
175    #[serde(default)]
176    pub full: bool,
177}
178
179/// Height of the host chrome at the bottom of a mode dock (the ⤢ fullscreen
180/// button and the focus hint). Keep footers and the input line above this
181/// strip so they are not covered.
182pub fn dock_chrome_height(cell_h: i32) -> i32 {
183    cell_h + 10
184}
185
186impl DockSize {
187    /// The dock height for `area`: the whole area when full, else the chosen
188    /// share, else `default_h`; at least four rows and leaving two for the shell.
189    pub fn height(&self, area: Rect, cell_h: i32, default_h: i32) -> i32 {
190        let min = (cell_h * 4).min(area.h.max(0));
191        if self.full {
192            return area.h.max(min);
193        }
194        let max = (area.h - cell_h * 2).max(min);
195        match self.permille {
196            Some(p) => ((area.h as i64 * p as i64 / 1000) as i32).clamp(min, max),
197            None => default_h,
198        }
199    }
200
201    /// From a `view.resized` payload (`dock`, absent from older hosts).
202    pub fn from_payload(v: &serde_json::Value) -> Self {
203        serde_json::from_value(v["dock"].clone()).unwrap_or_default()
204    }
205}
206
207/// One entry of a context menu ([`crate::protocol::Out::Menu`]): an action
208/// from the mode's own action registry, so the menu and the key bindings
209/// never drift apart. Picking it is the same `ui.action` (`id`, `arg`) its
210/// key or button sends.
211#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
212pub struct MenuEntry {
213    pub id: String,
214    pub arg: i32,
215    pub label: String,
216    /// The action's current key as typed (`s`, `enter`); empty: none.
217    pub key: String,
218    pub enabled: bool,
219}
220
221#[cfg(test)]
222mod dock_tests {
223    use super::*;
224
225    #[test]
226    fn dock_size_heights() {
227        let a = Rect { x: 0, y: 0, w: 800, h: 600 };
228        assert_eq!(DockSize::default().height(a, 20, 300), 300);
229        assert_eq!(DockSize { permille: Some(750), full: false }.height(a, 20, 300), 450);
230        assert_eq!(DockSize { permille: Some(1000), full: false }.height(a, 20, 300), 560, "two rows stay the shell's");
231        assert_eq!(DockSize { permille: Some(10), full: false }.height(a, 20, 300), 80, "at least four rows");
232        assert_eq!(DockSize { permille: None, full: true }.height(a, 20, 300), 600);
233        let p = serde_json::json!({"dock": {"permille": 500, "full": false}});
234        assert_eq!(DockSize::from_payload(&p).permille, Some(500));
235        assert_eq!(DockSize::from_payload(&serde_json::json!({})), DockSize::default(), "an older host");
236        assert_eq!(dock_chrome_height(18), 28);
237    }
238}