Skip to main content

comb/widgets/
window.rs

1//! A floating, draggable / resizable window with a title-bar grab handle.
2
3use crate::core::buffer::Buffer;
4use crate::core::geom::Rect;
5use crate::core::style::Style;
6use crate::core::text::{Line, Span};
7use crate::draw::border::Border;
8use crate::term::event::{MouseButton, MouseKind};
9use crate::widgets::Palette;
10
11#[derive(Clone, Copy, PartialEq, Eq, Debug)]
12pub enum ResizeEdge {
13    Bottom,
14    Right,
15    BottomRight,
16}
17
18#[derive(Clone, Copy, PartialEq, Eq, Debug)]
19enum DragKind {
20    Move { grab_x: u16, grab_y: u16 },
21    Resize(ResizeEdge),
22}
23
24/// Floating chrome: title bar to move, edges to resize, clamped to a workspace.
25#[derive(Clone, Debug)]
26pub struct Window {
27    pub title: String,
28    pub x: u16,
29    pub y: u16,
30    pub width: u16,
31    pub height: u16,
32    pub min_w: u16,
33    pub min_h: u16,
34    pub border: Border,
35    /// Panel fill behind content. Windows must be opaque so a window on top
36    /// fully covers whatever is underneath (no bleed-through).
37    pub fill: Style,
38    drag: Option<DragKind>,
39}
40
41impl Window {
42    pub fn new(title: impl Into<String>, x: u16, y: u16, width: u16, height: u16) -> Self {
43        Window {
44            title: title.into(),
45            x,
46            y,
47            width,
48            height,
49            min_w: 16,
50            min_h: 5,
51            border: Border::Rounded,
52            fill: Style::new().bg(crate::core::style::Color::rgb(0x1c, 0x1c, 0x1c)),
53            drag: None,
54        }
55    }
56
57    pub fn area(&self) -> Rect {
58        Rect::new(self.x, self.y, self.width, self.height)
59    }
60
61    pub fn inner(&self) -> Rect {
62        self.area().inner(1, 1)
63    }
64
65    pub fn is_dragging(&self) -> bool {
66        self.drag.is_some()
67    }
68
69    pub fn end_drag(&mut self) {
70        self.drag = None;
71    }
72
73    /// Clamp geometry into `workspace` (usually the usable screen area).
74    pub fn clamp_to(&mut self, workspace: Rect) {
75        if workspace.is_empty() {
76            return;
77        }
78        self.width = self
79            .width
80            .clamp(self.min_w, workspace.width.max(self.min_w));
81        self.height = self
82            .height
83            .clamp(self.min_h, workspace.height.max(self.min_h));
84        let max_x = workspace.right().saturating_sub(self.width);
85        let max_y = workspace.bottom().saturating_sub(self.height);
86        self.x = self.x.clamp(workspace.x, max_x.max(workspace.x));
87        self.y = self.y.clamp(workspace.y, max_y.max(workspace.y));
88    }
89
90    /// Draw opaque fill + border + title. Content is left to the caller (`inner()`).
91    /// Always paints `fill` first so stacking windows never leak lower layers.
92    pub fn render_chrome(&self, buf: &mut Buffer, pal: &Palette, focused: bool) {
93        let area = self.area();
94        if area.is_empty() {
95            return;
96        }
97        let fill = if self.fill.bg.is_some() {
98            self.fill
99        } else {
100            pal.panel
101        };
102        buf.paint(area, fill);
103        let border = if focused { pal.accent } else { pal.border };
104        let title_st = if focused {
105            pal.accent.bold().patch(fill)
106        } else {
107            pal.normal.patch(fill)
108        };
109        let title = Line::from(Span::styled(self.title.clone(), title_st));
110        // Border cells keep the window fill so edges stay opaque when stacked.
111        buf.border_title(area, self.border, border.patch(fill), &title);
112        // Subtle resize grip on the bottom-right corner.
113        if area.width >= 3 && area.height >= 2 {
114            let grip = Style::new()
115                .fg(crate::core::style::Color::rgb(0x70, 0x70, 0x70))
116                .patch(fill);
117            buf.set(area.right() - 1, area.bottom() - 1, '╯', grip);
118        }
119    }
120
121    /// Handle move / resize. Returns `true` if the event was consumed.
122    /// `workspace` clamps the window while dragging.
123    pub fn handle_mouse(&mut self, kind: MouseKind, col: u16, row: u16, workspace: Rect) -> bool {
124        let area = self.area();
125        match kind {
126            MouseKind::Up => {
127                let was = self.drag.is_some();
128                self.drag = None;
129                was
130            }
131            MouseKind::Drag | MouseKind::Moved if self.drag.is_some() => {
132                match self.drag {
133                    Some(DragKind::Move { grab_x, grab_y }) => {
134                        let nx = col.saturating_sub(grab_x);
135                        let ny = row.saturating_sub(grab_y);
136                        self.x = nx;
137                        self.y = ny;
138                        self.clamp_to(workspace);
139                    }
140                    Some(DragKind::Resize(edge)) => {
141                        match edge {
142                            ResizeEdge::Bottom | ResizeEdge::BottomRight => {
143                                self.height =
144                                    row.saturating_sub(self.y).saturating_add(1).max(self.min_h);
145                            }
146                            ResizeEdge::Right => {}
147                        }
148                        match edge {
149                            ResizeEdge::Right | ResizeEdge::BottomRight => {
150                                self.width =
151                                    col.saturating_sub(self.x).saturating_add(1).max(self.min_w);
152                            }
153                            ResizeEdge::Bottom => {}
154                        }
155                        self.clamp_to(workspace);
156                    }
157                    None => {}
158                }
159                true
160            }
161            MouseKind::Down(MouseButton::Left) => {
162                if !area.contains(col, row) {
163                    return false;
164                }
165                let on_title = row == area.y;
166                let on_bottom = row + 1 == area.bottom();
167                let on_right = col + 1 == area.right();
168                if on_title {
169                    self.drag = Some(DragKind::Move {
170                        grab_x: col.saturating_sub(self.x),
171                        grab_y: row.saturating_sub(self.y),
172                    });
173                    return true;
174                }
175                if on_bottom && on_right {
176                    self.drag = Some(DragKind::Resize(ResizeEdge::BottomRight));
177                    return true;
178                }
179                if on_bottom {
180                    self.drag = Some(DragKind::Resize(ResizeEdge::Bottom));
181                    return true;
182                }
183                if on_right {
184                    self.drag = Some(DragKind::Resize(ResizeEdge::Right));
185                    return true;
186                }
187                // Content click — still "handled" for focus/z-order by the caller
188                // when they see contains(); return false so content widgets run.
189                false
190            }
191            _ => false,
192        }
193    }
194
195    pub fn contains(&self, col: u16, row: u16) -> bool {
196        self.area().contains(col, row)
197    }
198}
199
200#[cfg(test)]
201mod tests {
202    use super::*;
203
204    #[test]
205    fn title_drag_moves_window() {
206        let mut w = Window::new("t", 4, 4, 20, 8);
207        let ws = Rect::new(0, 0, 80, 40);
208        assert!(w.handle_mouse(MouseKind::Down(MouseButton::Left), 6, 4, ws));
209        assert!(w.is_dragging());
210        w.handle_mouse(MouseKind::Drag, 16, 10, ws);
211        assert_eq!((w.x, w.y), (14, 10));
212    }
213
214    #[test]
215    fn resize_bottom_right_grows() {
216        let mut w = Window::new("t", 2, 2, 20, 8);
217        let ws = Rect::new(0, 0, 80, 40);
218        let br_x = w.area().right() - 1;
219        let br_y = w.area().bottom() - 1;
220        assert!(w.handle_mouse(MouseKind::Down(MouseButton::Left), br_x, br_y, ws));
221        w.handle_mouse(MouseKind::Drag, 40, 20, ws);
222        assert!(w.width >= 30);
223        assert!(w.height >= 15);
224    }
225}