Skip to main content

strata_platform/
window_manager.rs

1//! Multi-window desktop manager with parent-child modality, focus arbitration, and event multiplexing.
2
3use crate::events::PlatformEvent;
4use crate::window::{LivePlatformWindow, PlatformWindow, WindowConfig};
5use std::collections::HashMap;
6
7/// Unique 64-bit identifier for an active platform window.
8#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
9pub struct WindowId(pub u64);
10
11impl WindowId {
12    pub const MAIN: Self = Self(1);
13}
14
15/// Internal tracking entry for a managed window.
16struct ManagedWindowEntry {
17    #[allow(dead_code)]
18    id: WindowId,
19    window: Box<dyn PlatformWindow>,
20    is_modal: bool,
21    parent_id: Option<WindowId>,
22    children: Vec<WindowId>,
23}
24
25/// Multi-window desktop manager coordinating multiple concurrent windows.
26pub struct WindowManager {
27    windows: HashMap<u64, ManagedWindowEntry>,
28    active_window: Option<WindowId>,
29    next_id: u64,
30}
31
32impl Default for WindowManager {
33    fn default() -> Self {
34        Self::new()
35    }
36}
37
38impl WindowManager {
39    /// Creates a new empty window manager.
40    pub fn new() -> Self {
41        Self {
42            windows: HashMap::new(),
43            active_window: None,
44            next_id: 1,
45        }
46    }
47
48    /// Spawns a new independent top-level window with the specified configuration.
49    pub fn create_window(&mut self, config: WindowConfig) -> WindowId {
50        let win = Box::new(LivePlatformWindow::new(config));
51        self.register_window(win)
52    }
53
54    /// Registers an existing platform window instance into the manager.
55    pub fn register_window(&mut self, window: Box<dyn PlatformWindow>) -> WindowId {
56        let id = WindowId(self.next_id);
57        self.next_id += 1;
58
59        let entry = ManagedWindowEntry {
60            id,
61            window,
62            is_modal: false,
63            parent_id: None,
64            children: Vec::new(),
65        };
66
67        self.windows.insert(id.0, entry);
68
69        if self.active_window.is_none() {
70            self.active_window = Some(id);
71        }
72
73        id
74    }
75
76    /// Spawns a modal child dialog window attached to a specified parent window.
77    pub fn create_modal(
78        &mut self,
79        parent: WindowId,
80        config: WindowConfig,
81    ) -> Result<WindowId, String> {
82        let win = Box::new(LivePlatformWindow::new(config));
83        self.register_modal(parent, win)
84    }
85
86    /// Registers a modal platform window attached to a parent window.
87    pub fn register_modal(
88        &mut self,
89        parent: WindowId,
90        window: Box<dyn PlatformWindow>,
91    ) -> Result<WindowId, String> {
92        if !self.windows.contains_key(&parent.0) {
93            return Err(format!("Parent window {:?} does not exist", parent));
94        }
95
96        let id = WindowId(self.next_id);
97        self.next_id += 1;
98
99        let entry = ManagedWindowEntry {
100            id,
101            window,
102            is_modal: true,
103            parent_id: Some(parent),
104            children: Vec::new(),
105        };
106
107        self.windows.insert(id.0, entry);
108
109        if let Some(parent_entry) = self.windows.get_mut(&parent.0) {
110            parent_entry.children.push(id);
111        }
112
113        // Focus the modal window
114        self.active_window = Some(id);
115
116        Ok(id)
117    }
118
119    /// Closes a managed window, unblocking any parents and dismissing descendants.
120    pub fn close_window(&mut self, id: WindowId) -> Result<(), String> {
121        let entry = self
122            .windows
123            .remove(&id.0)
124            .ok_or_else(|| format!("Window {:?} not found", id))?;
125
126        // Remove from parent's children list
127        if let Some(parent_id) = entry.parent_id {
128            if let Some(parent) = self.windows.get_mut(&parent_id.0) {
129                parent.children.retain(|&c| c != id);
130            }
131        }
132
133        // Recursively close all children
134        for child_id in entry.children {
135            let _ = self.close_window(child_id);
136        }
137
138        // If this was active window, transfer focus to parent or any remaining window
139        if self.active_window == Some(id) {
140            self.active_window = entry
141                .parent_id
142                .filter(|p| self.windows.contains_key(&p.0))
143                .or_else(|| self.windows.keys().next().map(|&k| WindowId(k)));
144        }
145
146        Ok(())
147    }
148
149    /// Returns a reference to the window with the given ID.
150    pub fn get_window(&self, id: WindowId) -> Option<&dyn PlatformWindow> {
151        self.windows.get(&id.0).map(|e| e.window.as_ref())
152    }
153
154    /// Returns a mutable reference to the window with the given ID.
155    pub fn get_window_mut(&mut self, id: WindowId) -> Option<&mut (dyn PlatformWindow + 'static)> {
156        self.windows.get_mut(&id.0).map(|e| e.window.as_mut())
157    }
158
159    /// Returns the active window ID currently possessing focus.
160    pub fn active_window(&self) -> Option<WindowId> {
161        self.active_window
162    }
163
164    /// Sets the active focused window ID.
165    pub fn set_active_window(&mut self, id: WindowId) -> Result<(), String> {
166        if !self.windows.contains_key(&id.0) {
167            return Err(format!("Window {:?} not found", id));
168        }
169
170        // Check if modal blocked
171        if self.is_modal_blocked(id) {
172            return Err(format!(
173                "Window {:?} cannot receive focus while blocked by a modal dialog",
174                id
175            ));
176        }
177
178        // Update focus flags
179        for (wid, entry) in self.windows.iter_mut() {
180            entry.window.set_focused(*wid == id.0);
181        }
182
183        self.active_window = Some(id);
184        Ok(())
185    }
186
187    /// Checks if a window is blocked from interaction by an active modal child.
188    pub fn is_modal_blocked(&self, id: WindowId) -> bool {
189        if let Some(entry) = self.windows.get(&id.0) {
190            entry.children.iter().any(|&child_id| {
191                self.windows
192                    .get(&child_id.0)
193                    .is_some_and(|child| child.is_modal)
194            })
195        } else {
196            false
197        }
198    }
199
200    /// Total number of open windows.
201    pub fn window_count(&self) -> usize {
202        self.windows.len()
203    }
204
205    /// Dispatches an event to all open non-blocked windows (e.g. system theme changes).
206    pub fn broadcast_event(&mut self, event: PlatformEvent) {
207        for entry in self.windows.values_mut() {
208            entry.window.push_event(event.clone());
209        }
210    }
211
212    /// Polls all window event queues and collects pending events labeled by WindowId.
213    pub fn poll_all_events(&mut self) -> Vec<(WindowId, PlatformEvent)> {
214        let mut all_events = Vec::new();
215        for (&id, entry) in self.windows.iter_mut() {
216            let events = entry.window.poll_events();
217            for ev in events {
218                all_events.push((WindowId(id), ev));
219            }
220        }
221        all_events
222    }
223}