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