Skip to main content

velox_engine/platform/winit/
multi_window.rs

1//! 多窗口生命周期管理、越界浮层窗口与无边框自定义标题栏(CSD)命中测试管理器。
2
3use std::collections::HashMap;
4use std::string::String;
5use std::vec::Vec;
6
7use crate::element::View;
8use crate::engine::VeloxEngine;
9use crate::platform::a11y_bridge::{AccessKitBridge, AccessKitTreeUpdate};
10use crate::pod::InputEvent;
11use crate::solver::Region;
12
13/// 强类型多窗口标识符(与宿主 `winit::window::WindowId` 解耦,可独立单元测试)。
14#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
15pub struct MultiWindowId(pub u32);
16
17/// 窗口语义角色。
18#[repr(u8)]
19#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
20pub enum WindowRole {
21    #[default]
22    Primary = 0,
23    Secondary = 1,
24    /// 可越出主窗口边界的原生弹出浮层(右键菜单 / 下拉列表)。
25    Popover = 2,
26    /// 轻量原生悬浮提示窗口。
27    Tooltip = 3,
28}
29
30/// 客户端自绘无边框标题栏(Client-Side Decorations / CSD)配置。
31#[derive(Copy, Clone, PartialEq, Eq, Debug)]
32pub struct CsdConfig {
33    /// 是否关闭 OS 原生标题栏并启用 CSD 自定义标题栏。
34    pub enabled: bool,
35    /// 自定义标题栏高度(逻辑像素,默认 `36`)。
36    pub titlebar_height: i16,
37    /// 窗口四边可拖拽缩放的边缘热区宽度(逻辑像素,默认 `6`)。
38    pub resize_border_px: i16,
39    /// 显式排除拖拽的右上角窗口按钮区域宽度(最小化/最大化/关闭按钮,默认 `138`)。
40    pub controls_inset_right: i16,
41    /// 双击标题栏空白处是否切换最大化。
42    pub double_click_maximize: bool,
43}
44
45impl Default for CsdConfig {
46    fn default() -> Self {
47        Self {
48            enabled: false,
49            titlebar_height: 36,
50            resize_border_px: 6,
51            controls_inset_right: 138,
52            double_click_maximize: true,
53        }
54    }
55}
56
57/// 无边框 CSD 命中测试区域(直接对应 Windows `WM_NCHITTEST` / Wayland `xdg_toplevel::move/resize`)。
58#[derive(Copy, Clone, PartialEq, Eq, Debug)]
59pub enum CsdHitZone {
60    Client,
61    Caption,
62    ResizeLeft,
63    ResizeRight,
64    ResizeTop,
65    ResizeBottom,
66    ResizeTopLeft,
67    ResizeTopRight,
68    ResizeBottomLeft,
69    ResizeBottomRight,
70}
71
72impl CsdConfig {
73    /// 根据窗口逻辑尺寸 `(win_w, win_h)` 与局部指针坐标 `(x, y)` 判定 CSD 命中区域。
74    pub fn hit_test(&self, x: i16, y: i16, win_w: i16, win_h: i16) -> CsdHitZone {
75        if !self.enabled {
76            return CsdHitZone::Client;
77        }
78        let b = self.resize_border_px.max(0);
79        let left = x < b;
80        let right = x >= win_w.saturating_sub(b);
81        let top = y < b;
82        let bottom = y >= win_h.saturating_sub(b);
83
84        match (left, right, top, bottom) {
85            (true, _, true, _) => CsdHitZone::ResizeTopLeft,
86            (_, true, true, _) => CsdHitZone::ResizeTopRight,
87            (true, _, _, true) => CsdHitZone::ResizeBottomLeft,
88            (_, true, _, true) => CsdHitZone::ResizeBottomRight,
89            (true, _, _, _) => CsdHitZone::ResizeLeft,
90            (_, true, _, _) => CsdHitZone::ResizeRight,
91            (_, _, true, _) => CsdHitZone::ResizeTop,
92            (_, _, _, true) => CsdHitZone::ResizeBottom,
93            _ => {
94                if y < self.titlebar_height
95                    && x < win_w.saturating_sub(self.controls_inset_right)
96                {
97                    CsdHitZone::Caption
98                } else {
99                    CsdHitZone::Client
100                }
101            }
102        }
103    }
104}
105
106/// 多窗口创建描述。
107#[derive(Clone, Debug)]
108pub struct MultiWindowSpec {
109    pub title: String,
110    pub width: i16,
111    pub height: i16,
112    pub role: WindowRole,
113    pub parent: Option<MultiWindowId>,
114    pub transparent: bool,
115    pub always_on_top: bool,
116    pub csd: CsdConfig,
117}
118
119impl MultiWindowSpec {
120    pub fn primary(title: impl Into<String>, width: i16, height: i16) -> Self {
121        Self {
122            title: title.into(),
123            width,
124            height,
125            role: WindowRole::Primary,
126            parent: None,
127            transparent: false,
128            always_on_top: false,
129            csd: CsdConfig::default(),
130        }
131    }
132
133    pub fn popover(parent: MultiWindowId, width: i16, height: i16) -> Self {
134        Self {
135            title: String::new(),
136            width,
137            height,
138            role: WindowRole::Popover,
139            parent: Some(parent),
140            transparent: true,
141            always_on_top: true,
142            csd: CsdConfig::default(),
143        }
144    }
145
146    pub fn with_csd(mut self, csd: CsdConfig) -> Self {
147        self.csd = csd;
148        self
149    }
150}
151
152/// 单个受托管窗口的运行时会话(独立 `VeloxEngine` + 增量 `AccessKitBridge` + CSD 配置)。
153pub struct WindowSession {
154    pub id: MultiWindowId,
155    pub spec: MultiWindowSpec,
156    pub engine: VeloxEngine,
157    pub a11y: AccessKitBridge,
158    pub focused: bool,
159    pub maximized: bool,
160}
161
162/// 跨平台多窗口会话管理器(支持主窗 + 任意副窗 + 越界浮层 Popover + 统一广播事件与独立脏区步进)。
163pub struct MultiWindowManager {
164    next_id: u32,
165    windows: HashMap<MultiWindowId, WindowSession>,
166    order: Vec<MultiWindowId>,
167}
168
169impl Default for MultiWindowManager {
170    fn default() -> Self {
171        Self::new()
172    }
173}
174
175impl MultiWindowManager {
176    pub fn new() -> Self {
177        Self {
178            next_id: 1,
179            windows: HashMap::new(),
180            order: Vec::new(),
181        }
182    }
183
184    /// 打开并挂载一个新窗口(可为主窗、副窗或越界 Popover 浮层)。
185    pub fn open_window<V: View>(&mut self, spec: MultiWindowSpec, root_view: V) -> MultiWindowId {
186        let id = MultiWindowId(self.next_id);
187        self.next_id = self.next_id.wrapping_add(1).max(1);
188        let mut engine = VeloxEngine::new(spec.width.max(1), spec.height.max(1));
189        let _ = engine.mount_root(root_view);
190        let session = WindowSession {
191            id,
192            spec,
193            engine,
194            a11y: AccessKitBridge::new(),
195            focused: self.windows.is_empty(),
196            maximized: false,
197        };
198        self.windows.insert(id, session);
199        self.order.push(id);
200        id
201    }
202
203    /// 关闭指定窗口(同时自动级联关闭挂接在该父窗口下的所有 `Popover` / `Tooltip` 子浮层)。
204    pub fn close_window(&mut self, id: MultiWindowId) -> bool {
205        if self.windows.remove(&id).is_none() {
206            return false;
207        }
208        self.order.retain(|&w| w != id);
209        let orphans: Vec<MultiWindowId> = self
210            .windows
211            .values()
212            .filter(|w| w.spec.parent == Some(id))
213            .map(|w| w.id)
214            .collect();
215        for child in orphans {
216            self.close_window(child);
217        }
218        true
219    }
220
221    #[inline]
222    pub fn window_count(&self) -> usize {
223        self.windows.len()
224    }
225
226    #[inline]
227    pub fn window(&self, id: MultiWindowId) -> Option<&WindowSession> {
228        self.windows.get(&id)
229    }
230
231    #[inline]
232    pub fn window_mut(&mut self, id: MultiWindowId) -> Option<&mut WindowSession> {
233        self.windows.get_mut(&id)
234    }
235
236    /// 向指定窗口派发输入事件。
237    pub fn dispatch_event(&mut self, id: MultiWindowId, event: InputEvent) -> bool {
238        self.windows
239            .get_mut(&id)
240            .is_some_and(|w| w.engine.dispatch_event(event))
241    }
242
243    /// 向全部窗口广播系统级事件(如 `InputEvent::SystemThemeChanged`)。
244    pub fn broadcast_event(&mut self, event: InputEvent) -> usize {
245        let mut changed = 0usize;
246        for &id in &self.order {
247            if let Some(w) = self.windows.get_mut(&id) {
248                if w.engine.dispatch_event(event) {
249                    changed += 1;
250                }
251            }
252        }
253        changed
254    }
255
256    /// 步进所有活跃窗口一帧,返回产出脏区的 `(WindowId, dirty_count, Option<AccessKitTreeUpdate>)` 列表。
257    pub fn step_all(
258        &mut self,
259        dt_ms: u16,
260    ) -> Vec<(MultiWindowId, usize, Option<AccessKitTreeUpdate>)> {
261        let mut reports = Vec::with_capacity(self.order.len());
262        for &id in &self.order {
263            if let Some(w) = self.windows.get_mut(&id) {
264                let dirty_n = w.engine.step_frame_dt(dt_ms).len();
265                let a11y_update = if dirty_n > 0 {
266                    w.a11y.sync_engine(&w.engine)
267                } else {
268                    None
269                };
270                reports.push((id, dirty_n, a11y_update));
271            }
272        }
273        reports
274    }
275
276    /// 判定指定窗口坐标处的无边框 CSD 命中区域(供拖动标题栏/边缘缩放)。
277    pub fn hit_test_csd(&self, id: MultiWindowId, x: i16, y: i16) -> CsdHitZone {
278        let Some(w) = self.windows.get(&id) else {
279            return CsdHitZone::Client;
280        };
281        let vp: Region = w.engine.viewport_region();
282        w.spec.csd.hit_test(x, y, vp.w, vp.h)
283    }
284}