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    /// 从主窗口 Dock 工作区拖出形成的独立原生 OS 窗口(支持共享 `Signal` 状态并随时拖回吸附合并)。
29    DockTearOff = 4,
30}
31
32/// Dock 工作区停靠目标方位(用于拖回吸附合并)。
33#[repr(u8)]
34#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
35pub enum DockZone {
36    Left = 0,
37    Right = 1,
38    Bottom = 2,
39    Center = 3,
40}
41
42/// 已从主窗拖出的 Dock 面板记录。
43#[derive(Clone, PartialEq, Eq, Debug)]
44pub struct DetachedDockPanel {
45    pub window_id: MultiWindowId,
46    pub parent_id: MultiWindowId,
47    pub panel_key: String,
48    pub title: String,
49    pub origin_zone: DockZone,
50}
51
52/// 客户端自绘无边框标题栏(Client-Side Decorations / CSD)配置。
53#[derive(Copy, Clone, PartialEq, Eq, Debug)]
54pub struct CsdConfig {
55    /// 是否关闭 OS 原生标题栏并启用 CSD 自定义标题栏。
56    pub enabled: bool,
57    /// 自定义标题栏高度(逻辑像素,默认 `36`)。
58    pub titlebar_height: i16,
59    /// 窗口四边可拖拽缩放的边缘热区宽度(逻辑像素,默认 `6`)。
60    pub resize_border_px: i16,
61    /// 显式排除拖拽的右上角窗口按钮区域宽度(最小化/最大化/关闭按钮,默认 `138`)。
62    pub controls_inset_right: i16,
63    /// 双击标题栏空白处是否切换最大化。
64    pub double_click_maximize: bool,
65}
66
67impl Default for CsdConfig {
68    fn default() -> Self {
69        Self {
70            enabled: false,
71            titlebar_height: 36,
72            resize_border_px: 6,
73            controls_inset_right: 138,
74            double_click_maximize: true,
75        }
76    }
77}
78
79/// 无边框 CSD 命中测试区域(直接对应 Windows `WM_NCHITTEST` / Wayland `xdg_toplevel::move/resize`)。
80#[derive(Copy, Clone, PartialEq, Eq, Debug)]
81pub enum CsdHitZone {
82    Client,
83    Caption,
84    ResizeLeft,
85    ResizeRight,
86    ResizeTop,
87    ResizeBottom,
88    ResizeTopLeft,
89    ResizeTopRight,
90    ResizeBottomLeft,
91    ResizeBottomRight,
92}
93
94impl CsdConfig {
95    /// 根据窗口逻辑尺寸 `(win_w, win_h)` 与局部指针坐标 `(x, y)` 判定 CSD 命中区域。
96    pub fn hit_test(&self, x: i16, y: i16, win_w: i16, win_h: i16) -> CsdHitZone {
97        if !self.enabled {
98            return CsdHitZone::Client;
99        }
100        let b = self.resize_border_px.max(0);
101        let left = x < b;
102        let right = x >= win_w.saturating_sub(b);
103        let top = y < b;
104        let bottom = y >= win_h.saturating_sub(b);
105
106        match (left, right, top, bottom) {
107            (true, _, true, _) => CsdHitZone::ResizeTopLeft,
108            (_, true, true, _) => CsdHitZone::ResizeTopRight,
109            (true, _, _, true) => CsdHitZone::ResizeBottomLeft,
110            (_, true, _, true) => CsdHitZone::ResizeBottomRight,
111            (true, _, _, _) => CsdHitZone::ResizeLeft,
112            (_, true, _, _) => CsdHitZone::ResizeRight,
113            (_, _, true, _) => CsdHitZone::ResizeTop,
114            (_, _, _, true) => CsdHitZone::ResizeBottom,
115            _ => {
116                if y < self.titlebar_height
117                    && x < win_w.saturating_sub(self.controls_inset_right)
118                {
119                    CsdHitZone::Caption
120                } else {
121                    CsdHitZone::Client
122                }
123            }
124        }
125    }
126}
127
128/// 多窗口创建描述。
129#[derive(Clone, Debug)]
130pub struct MultiWindowSpec {
131    pub title: String,
132    pub width: i16,
133    pub height: i16,
134    pub role: WindowRole,
135    pub parent: Option<MultiWindowId>,
136    pub transparent: bool,
137    pub always_on_top: bool,
138    pub csd: CsdConfig,
139}
140
141impl MultiWindowSpec {
142    pub fn primary(title: impl Into<String>, width: i16, height: i16) -> Self {
143        Self {
144            title: title.into(),
145            width,
146            height,
147            role: WindowRole::Primary,
148            parent: None,
149            transparent: false,
150            always_on_top: false,
151            csd: CsdConfig::default(),
152        }
153    }
154
155    pub fn popover(parent: MultiWindowId, width: i16, height: i16) -> Self {
156        Self {
157            title: String::new(),
158            width,
159            height,
160            role: WindowRole::Popover,
161            parent: Some(parent),
162            transparent: true,
163            always_on_top: true,
164            csd: CsdConfig::default(),
165        }
166    }
167
168    pub fn with_csd(mut self, csd: CsdConfig) -> Self {
169        self.csd = csd;
170        self
171    }
172}
173
174/// 单个受托管窗口的运行时会话(独立 `VeloxEngine` + 增量 `AccessKitBridge` + CSD 配置)。
175pub struct WindowSession {
176    pub id: MultiWindowId,
177    pub spec: MultiWindowSpec,
178    pub engine: VeloxEngine,
179    pub a11y: AccessKitBridge,
180    pub focused: bool,
181    pub maximized: bool,
182}
183
184/// 跨平台多窗口会话管理器(支持主窗 + 任意副窗 + 越界浮层 Popover + Dock 拖出独立窗 + 统一广播事件与独立脏区步进)。
185pub struct MultiWindowManager {
186    next_id: u32,
187    windows: HashMap<MultiWindowId, WindowSession>,
188    order: Vec<MultiWindowId>,
189    detached_docks: Vec<DetachedDockPanel>,
190}
191
192impl Default for MultiWindowManager {
193    fn default() -> Self {
194        Self::new()
195    }
196}
197
198impl MultiWindowManager {
199    pub fn new() -> Self {
200        Self {
201            next_id: 1,
202            windows: HashMap::new(),
203            order: Vec::new(),
204            detached_docks: Vec::new(),
205        }
206    }
207
208    /// 打开并挂载一个新窗口(可为主窗、副窗或越界 Popover 浮层)。
209    pub fn open_window<V: View>(&mut self, spec: MultiWindowSpec, root_view: V) -> MultiWindowId {
210        let id = MultiWindowId(self.next_id);
211        self.next_id = self.next_id.wrapping_add(1).max(1);
212        let mut engine = VeloxEngine::new(spec.width.max(1), spec.height.max(1));
213        let _ = engine.mount_root(root_view);
214        let session = WindowSession {
215            id,
216            spec,
217            engine,
218            a11y: AccessKitBridge::new(),
219            focused: self.windows.is_empty(),
220            maximized: false,
221        };
222        self.windows.insert(id, session);
223        self.order.push(id);
224        id
225    }
226
227    /// 关闭指定窗口(同时自动级联关闭挂接在该父窗口下的所有 `Popover` / `Tooltip` 子浮层)。
228    pub fn close_window(&mut self, id: MultiWindowId) -> bool {
229        if self.windows.remove(&id).is_none() {
230            return false;
231        }
232        self.order.retain(|&w| w != id);
233        let orphans: Vec<MultiWindowId> = self
234            .windows
235            .values()
236            .filter(|w| w.spec.parent == Some(id))
237            .map(|w| w.id)
238            .collect();
239        for child in orphans {
240            self.close_window(child);
241        }
242        true
243    }
244
245    #[inline]
246    pub fn window_count(&self) -> usize {
247        self.windows.len()
248    }
249
250    #[inline]
251    pub fn window(&self, id: MultiWindowId) -> Option<&WindowSession> {
252        self.windows.get(&id)
253    }
254
255    #[inline]
256    pub fn window_mut(&mut self, id: MultiWindowId) -> Option<&mut WindowSession> {
257        self.windows.get_mut(&id)
258    }
259
260    /// 向指定窗口派发输入事件。
261    pub fn dispatch_event(&mut self, id: MultiWindowId, event: InputEvent) -> bool {
262        self.windows
263            .get_mut(&id)
264            .is_some_and(|w| w.engine.dispatch_event(event))
265    }
266
267    /// 向全部窗口广播系统级事件(如 `InputEvent::SystemThemeChanged`)。
268    pub fn broadcast_event(&mut self, event: InputEvent) -> usize {
269        let mut changed = 0usize;
270        for &id in &self.order {
271            if let Some(w) = self.windows.get_mut(&id) {
272                if w.engine.dispatch_event(event) {
273                    changed += 1;
274                }
275            }
276        }
277        changed
278    }
279
280    /// 步进所有活跃窗口一帧,返回产出脏区的 `(WindowId, dirty_count, Option<AccessKitTreeUpdate>)` 列表。
281    pub fn step_all(
282        &mut self,
283        dt_ms: u16,
284    ) -> Vec<(MultiWindowId, usize, Option<AccessKitTreeUpdate>)> {
285        let mut reports = Vec::with_capacity(self.order.len());
286        for &id in &self.order {
287            if let Some(w) = self.windows.get_mut(&id) {
288                let dirty_n = w.engine.step_frame_dt(dt_ms).len();
289                let a11y_update = if dirty_n > 0 {
290                    w.a11y.sync_engine(&w.engine)
291                } else {
292                    None
293                };
294                reports.push((id, dirty_n, a11y_update));
295            }
296        }
297        reports
298    }
299
300    /// 判定指定窗口坐标处的无边框 CSD 命中区域(供拖动标题栏/边缘缩放)。
301    pub fn hit_test_csd(&self, id: MultiWindowId, x: i16, y: i16) -> CsdHitZone {
302        let Some(w) = self.windows.get(&id) else {
303            return CsdHitZone::Client;
304        };
305        let vp: Region = w.engine.viewport_region();
306        w.spec.csd.hit_test(x, y, vp.w, vp.h)
307    }
308
309    /// 将主窗口中的某个 Dock 面板拖出(Tear-Off)为独立原生 OS 窗口,并共享同一响应式 `Signal` 图。
310    pub fn tear_off_dock_panel<V: View>(
311        &mut self,
312        parent: MultiWindowId,
313        panel_key: impl Into<String>,
314        title: impl Into<String>,
315        origin_zone: DockZone,
316        width: i16,
317        height: i16,
318        view: V,
319    ) -> MultiWindowId {
320        let title_str = title.into();
321        let key_str = panel_key.into();
322        let spec = MultiWindowSpec {
323            title: title_str.clone(),
324            width,
325            height,
326            role: WindowRole::DockTearOff,
327            parent: Some(parent),
328            transparent: false,
329            always_on_top: false,
330            csd: CsdConfig {
331                enabled: true,
332                ..CsdConfig::default()
333            },
334        };
335        let win_id = self.open_window(spec, view);
336        self.detached_docks.push(DetachedDockPanel {
337            window_id: win_id,
338            parent_id: parent,
339            panel_key: key_str,
340            title: title_str,
341            origin_zone,
342        });
343        win_id
344    }
345
346    /// 将独立拖出窗口重新吸附合并回主窗口指定 [`DockZone`],关闭该子窗并返回 `(panel_key, target_zone)`。
347    pub fn redock_panel(
348        &mut self,
349        win_id: MultiWindowId,
350        target_zone: DockZone,
351    ) -> Option<(String, DockZone)> {
352        let pos = self
353            .detached_docks
354            .iter()
355            .position(|d| d.window_id == win_id)?;
356        let entry = self.detached_docks.remove(pos);
357        let _ = self.close_window(win_id);
358        Some((entry.panel_key, target_zone))
359    }
360
361    /// 返回当前所有处于独立窗口状态的 Dock 拖出面板列表。
362    #[inline]
363    pub fn detached_dock_panels(&self) -> &[DetachedDockPanel] {
364        &self.detached_docks
365    }
366}