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                    LinuxWindowState::resize(&this.windows[&ev.window()], ev.width(), ev.height());
118                    repaint_x_window = Some(ev.window());
119                }
120                _ => {}
121            }
122
123            if let Some(x_window) = repaint_x_window {
124                let this = self.0.lock();
125                LinuxWindowState::request_frame(&this.windows[&x_window]);
126                this.xcb_connection.flush();
127            }
128        }
129    }
130
131    fn quit(&self) {}
132
133    fn restart(&self) {}
134
135    fn activate(&self, ignoring_other_apps: bool) {}
136
137    fn hide(&self) {}
138
139    fn hide_other_apps(&self) {}
140
141    fn unhide_other_apps(&self) {}
142
143    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
144        let this = self.0.lock();
145        let setup = this.xcb_connection.get_setup();
146        setup
147            .roots()
148            .enumerate()
149            .map(|(root_id, _)| {
150                Rc::new(LinuxDisplay::new(&this.xcb_connection, root_id as i32))
151                    as Rc<dyn PlatformDisplay>
152            })
153            .collect()
154    }
155
156    fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
157        let this = self.0.lock();
158        Some(Rc::new(LinuxDisplay::new(
159            &this.xcb_connection,
160            id.0 as i32,
161        )))
162    }
163
164    fn active_window(&self) -> Option<AnyWindowHandle> {
165        None
166    }
167
168    fn open_window(
169        &self,
170        handle: AnyWindowHandle,
171        options: WindowOptions,
172    ) -> Box<dyn PlatformWindow> {
173        let mut this = self.0.lock();
174        let x_window = this.xcb_connection.generate_id();
175
176        let window_ptr = LinuxWindowState::new_ptr(
177            options,
178            handle,
179            &this.xcb_connection,
180            this.x_root_index,
181            x_window,
182            &this.atoms,
183        );
184        this.windows.insert(x_window, window_ptr.clone());
185        Box::new(LinuxWindow(window_ptr))
186    }
187
188    fn set_display_link_output_callback(
189        &self,
190        display_id: DisplayId,
191        callback: Box<dyn FnMut() + Send>,
192    ) {
193        unimplemented!()
194    }
195
196    fn start_display_link(&self, display_id: DisplayId) {}
197
198    fn stop_display_link(&self, display_id: DisplayId) {}
199
200    fn open_url(&self, url: &str) {}
201
202    fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {}
203
204    fn prompt_for_paths(
205        &self,
206        options: PathPromptOptions,
207    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
208        unimplemented!()
209    }
210
211    fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
212        unimplemented!()
213    }
214
215    fn reveal_path(&self, path: &Path) {}
216
217    fn on_become_active(&self, callback: Box<dyn FnMut()>) {}
218
219    fn on_resign_active(&self, callback: Box<dyn FnMut()>) {}
220
221    fn on_quit(&self, callback: Box<dyn FnMut()>) {}
222
223    fn on_reopen(&self, callback: Box<dyn FnMut()>) {}
224
225    fn on_event(&self, callback: Box<dyn FnMut(PlatformInput) -> bool>) {}
226
227    fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {}
228
229    fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {}
230
231    fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {}
232
233    fn os_name(&self) -> &'static str {
234        "Linux"
235    }
236
237    fn double_click_interval(&self) -> Duration {
238        Duration::default()
239    }
240
241    fn os_version(&self) -> Result<SemanticVersion> {
242        Ok(SemanticVersion {
243            major: 1,
244            minor: 0,
245            patch: 0,
246        })
247    }
248
249    fn app_version(&self) -> Result<SemanticVersion> {
250        Ok(SemanticVersion {
251            major: 1,
252            minor: 0,
253            patch: 0,
254        })
255    }
256
257    fn app_path(&self) -> Result<PathBuf> {
258        unimplemented!()
259    }
260
261    fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap) {}
262
263    fn local_timezone(&self) -> UtcOffset {
264        UtcOffset::UTC
265    }
266
267    fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
268        unimplemented!()
269    }
270
271    fn set_cursor_style(&self, style: CursorStyle) {}
272
273    fn should_auto_hide_scrollbars(&self) -> bool {
274        false
275    }
276
277    fn write_to_clipboard(&self, item: ClipboardItem) {}
278
279    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
280        None
281    }
282
283    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
284        unimplemented!()
285    }
286
287    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
288        unimplemented!()
289    }
290
291    fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
292        unimplemented!()
293    }
294}
295
296#[cfg(test)]
297mod tests {
298    use crate::ClipboardItem;
299
300    use super::*;
301
302    fn build_platform() -> LinuxPlatform {
303        let platform = LinuxPlatform::new();
304        platform
305    }
306}