platform.rs

  1#![allow(unused)]
  2
  3use crate::{
  4    Action, AnyWindowHandle, BackgroundExecutor, ClipboardItem, CursorStyle, DisplayId,
  5    ForegroundExecutor, Keymap, LinuxDispatcher, LinuxDisplay, LinuxTextSystem, LinuxWindow,
  6    LinuxWindowState, LinuxWindowStatePtr, Menu, PathPromptOptions, Platform, PlatformDisplay,
  7    PlatformInput, PlatformTextSystem, PlatformWindow, Result, SemanticVersion, Task,
  8    WindowOptions,
  9};
 10
 11use collections::{HashMap, HashSet};
 12use futures::channel::oneshot;
 13use parking_lot::Mutex;
 14
 15use std::{
 16    path::{Path, PathBuf},
 17    rc::Rc,
 18    sync::Arc,
 19    time::Duration,
 20};
 21use time::UtcOffset;
 22use xcb::{x, Xid as _};
 23
 24xcb::atoms_struct! {
 25    #[derive(Debug)]
 26    pub(crate) struct XcbAtoms {
 27        pub wm_protocols    => b"WM_PROTOCOLS",
 28        pub wm_del_window   => b"WM_DELETE_WINDOW",
 29        wm_state        => b"_NET_WM_STATE",
 30        wm_state_maxv   => b"_NET_WM_STATE_MAXIMIZED_VERT",
 31        wm_state_maxh   => b"_NET_WM_STATE_MAXIMIZED_HORZ",
 32    }
 33}
 34
 35pub(crate) struct LinuxPlatform(Mutex<LinuxPlatformState>);
 36
 37pub(crate) struct LinuxPlatformState {
 38    xcb_connection: xcb::Connection,
 39    x_root_index: i32,
 40    atoms: XcbAtoms,
 41    background_executor: BackgroundExecutor,
 42    foreground_executor: ForegroundExecutor,
 43    windows: HashMap<x::Window, LinuxWindowStatePtr>,
 44    text_system: Arc<LinuxTextSystem>,
 45}
 46
 47impl Default for LinuxPlatform {
 48    fn default() -> Self {
 49        Self::new()
 50    }
 51}
 52
 53impl LinuxPlatform {
 54    pub(crate) fn new() -> Self {
 55        let (xcb_connection, x_root_index) = xcb::Connection::connect(None).unwrap();
 56        let atoms = XcbAtoms::intern_all(&xcb_connection).unwrap();
 57
 58        let dispatcher = Arc::new(LinuxDispatcher::new());
 59
 60        Self(Mutex::new(LinuxPlatformState {
 61            xcb_connection,
 62            x_root_index,
 63            atoms,
 64            background_executor: BackgroundExecutor::new(dispatcher.clone()),
 65            foreground_executor: ForegroundExecutor::new(dispatcher),
 66            windows: HashMap::default(),
 67            text_system: Arc::new(LinuxTextSystem::new()),
 68        }))
 69    }
 70}
 71
 72impl Platform for LinuxPlatform {
 73    fn background_executor(&self) -> BackgroundExecutor {
 74        self.0.lock().background_executor.clone()
 75    }
 76
 77    fn foreground_executor(&self) -> crate::ForegroundExecutor {
 78        self.0.lock().foreground_executor.clone()
 79    }
 80
 81    fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
 82        self.0.lock().text_system.clone()
 83    }
 84
 85    fn run(&self, on_finish_launching: Box<dyn FnOnce()>) {
 86        on_finish_launching();
 87
 88        while !self.0.lock().windows.is_empty() {
 89            let event = self.0.lock().xcb_connection.wait_for_event().unwrap();
 90            let mut repaint_x_window = None;
 91            match event {
 92                xcb::Event::X(x::Event::ClientMessage(ev)) => {
 93                    if let x::ClientMessageData::Data32([atom, ..]) = ev.data() {
 94                        let mut this = self.0.lock();
 95                        if atom == this.atoms.wm_del_window.resource_id() {
 96                            // window "x" button clicked by user, we gracefully exit
 97                            {
 98                                let mut window = this.windows[&ev.window()].lock();
 99                                window.destroy();
100                            }
101                            this.xcb_connection.send_request(&x::UnmapWindow {
102                                window: ev.window(),
103                            });
104                            this.xcb_connection.send_request(&x::DestroyWindow {
105                                window: ev.window(),
106                            });
107                            this.windows.remove(&ev.window());
108                            break;
109                        }
110                    }
111                }
112                xcb::Event::X(x::Event::Expose(ev)) => {
113                    repaint_x_window = Some(ev.window());
114                }
115                xcb::Event::X(x::Event::ResizeRequest(ev)) => {
116                    let this = self.0.lock();
117                    let mut window = this.windows[&ev.window()].lock();
118                    window.resize(ev.width(), ev.height());
119                }
120                _ => {}
121            }
122
123            if let Some(x_window) = repaint_x_window {
124                let this = self.0.lock();
125                let mut window = this.windows[&x_window].lock();
126                window.request_frame();
127                this.xcb_connection.flush();
128            }
129        }
130    }
131
132    fn quit(&self) {}
133
134    fn restart(&self) {}
135
136    fn activate(&self, ignoring_other_apps: bool) {}
137
138    fn hide(&self) {}
139
140    fn hide_other_apps(&self) {}
141
142    fn unhide_other_apps(&self) {}
143
144    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
145        let this = self.0.lock();
146        let setup = this.xcb_connection.get_setup();
147        setup
148            .roots()
149            .enumerate()
150            .map(|(root_id, _)| {
151                Rc::new(LinuxDisplay::new(&this.xcb_connection, root_id as i32))
152                    as Rc<dyn PlatformDisplay>
153            })
154            .collect()
155    }
156
157    fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
158        let this = self.0.lock();
159        Some(Rc::new(LinuxDisplay::new(
160            &this.xcb_connection,
161            id.0 as i32,
162        )))
163    }
164
165    fn active_window(&self) -> Option<AnyWindowHandle> {
166        None
167    }
168
169    fn open_window(
170        &self,
171        handle: AnyWindowHandle,
172        options: WindowOptions,
173    ) -> Box<dyn PlatformWindow> {
174        let mut this = self.0.lock();
175        let x_window = this.xcb_connection.generate_id();
176
177        let window_ptr = LinuxWindowState::new_ptr(
178            options,
179            handle,
180            &this.xcb_connection,
181            this.x_root_index,
182            x_window,
183            &this.atoms,
184        );
185        this.windows.insert(x_window, window_ptr.clone());
186        Box::new(LinuxWindow(window_ptr))
187    }
188
189    fn set_display_link_output_callback(
190        &self,
191        display_id: DisplayId,
192        callback: Box<dyn FnMut() + Send>,
193    ) {
194        unimplemented!()
195    }
196
197    fn start_display_link(&self, display_id: DisplayId) {}
198
199    fn stop_display_link(&self, display_id: DisplayId) {}
200
201    fn open_url(&self, url: &str) {}
202
203    fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {}
204
205    fn prompt_for_paths(
206        &self,
207        options: PathPromptOptions,
208    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
209        unimplemented!()
210    }
211
212    fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
213        unimplemented!()
214    }
215
216    fn reveal_path(&self, path: &Path) {}
217
218    fn on_become_active(&self, callback: Box<dyn FnMut()>) {}
219
220    fn on_resign_active(&self, callback: Box<dyn FnMut()>) {}
221
222    fn on_quit(&self, callback: Box<dyn FnMut()>) {}
223
224    fn on_reopen(&self, callback: Box<dyn FnMut()>) {}
225
226    fn on_event(&self, callback: Box<dyn FnMut(PlatformInput) -> bool>) {}
227
228    fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {}
229
230    fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {}
231
232    fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {}
233
234    fn os_name(&self) -> &'static str {
235        "Linux"
236    }
237
238    fn double_click_interval(&self) -> Duration {
239        Duration::default()
240    }
241
242    fn os_version(&self) -> Result<SemanticVersion> {
243        Ok(SemanticVersion {
244            major: 1,
245            minor: 0,
246            patch: 0,
247        })
248    }
249
250    fn app_version(&self) -> Result<SemanticVersion> {
251        Ok(SemanticVersion {
252            major: 1,
253            minor: 0,
254            patch: 0,
255        })
256    }
257
258    fn app_path(&self) -> Result<PathBuf> {
259        unimplemented!()
260    }
261
262    fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap) {}
263
264    fn local_timezone(&self) -> UtcOffset {
265        UtcOffset::UTC
266    }
267
268    fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
269        unimplemented!()
270    }
271
272    fn set_cursor_style(&self, style: CursorStyle) {}
273
274    fn should_auto_hide_scrollbars(&self) -> bool {
275        false
276    }
277
278    fn write_to_clipboard(&self, item: ClipboardItem) {}
279
280    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
281        None
282    }
283
284    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
285        unimplemented!()
286    }
287
288    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
289        unimplemented!()
290    }
291
292    fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
293        unimplemented!()
294    }
295}
296
297#[cfg(test)]
298mod tests {
299    use crate::ClipboardItem;
300
301    use super::*;
302
303    fn build_platform() -> LinuxPlatform {
304        let platform = LinuxPlatform::new();
305        platform
306    }
307}