platform.rs

  1#![allow(unused)]
  2
  3use crate::{
  4    Action, AnyWindowHandle, BackgroundExecutor, Bounds, ClipboardItem, CursorStyle, DisplayId,
  5    ForegroundExecutor, Keymap, LinuxDispatcher, LinuxDisplay, LinuxTextSystem, LinuxWindow,
  6    LinuxWindowState, Menu, PathPromptOptions, Platform, PlatformDisplay, PlatformInput,
  7    PlatformTextSystem, PlatformWindow, Point, Result, SemanticVersion, Size, Task, WindowOptions,
  8};
  9
 10use async_task::Runnable;
 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
 35#[derive(Default)]
 36struct Callbacks {
 37    open_urls: Option<Box<dyn FnMut(Vec<String>)>>,
 38    become_active: Option<Box<dyn FnMut()>>,
 39    resign_active: Option<Box<dyn FnMut()>>,
 40    quit: Option<Box<dyn FnMut()>>,
 41    reopen: Option<Box<dyn FnMut()>>,
 42    event: Option<Box<dyn FnMut(PlatformInput) -> bool>>,
 43    app_menu_action: Option<Box<dyn FnMut(&dyn Action)>>,
 44    will_open_app_menu: Option<Box<dyn FnMut()>>,
 45    validate_app_menu_command: Option<Box<dyn FnMut(&dyn Action) -> bool>>,
 46}
 47
 48pub(crate) struct LinuxPlatform {
 49    xcb_connection: Arc<xcb::Connection>,
 50    x_root_index: i32,
 51    atoms: XcbAtoms,
 52    background_executor: BackgroundExecutor,
 53    foreground_executor: ForegroundExecutor,
 54    main_receiver: flume::Receiver<Runnable>,
 55    text_system: Arc<LinuxTextSystem>,
 56    callbacks: Mutex<Callbacks>,
 57    state: Mutex<LinuxPlatformState>,
 58}
 59
 60pub(crate) struct LinuxPlatformState {
 61    quit_requested: bool,
 62    windows: HashMap<x::Window, Arc<LinuxWindowState>>,
 63}
 64
 65impl Default for LinuxPlatform {
 66    fn default() -> Self {
 67        Self::new()
 68    }
 69}
 70
 71impl LinuxPlatform {
 72    pub(crate) fn new() -> Self {
 73        let (xcb_connection, x_root_index) = xcb::Connection::connect(None).unwrap();
 74        let atoms = XcbAtoms::intern_all(&xcb_connection).unwrap();
 75
 76        let xcb_connection = Arc::new(xcb_connection);
 77        let (main_sender, main_receiver) = flume::unbounded::<Runnable>();
 78        let dispatcher = Arc::new(LinuxDispatcher::new(
 79            main_sender,
 80            &xcb_connection,
 81            x_root_index,
 82        ));
 83
 84        Self {
 85            xcb_connection,
 86            x_root_index,
 87            atoms,
 88            background_executor: BackgroundExecutor::new(dispatcher.clone()),
 89            foreground_executor: ForegroundExecutor::new(dispatcher.clone()),
 90            main_receiver,
 91            text_system: Arc::new(LinuxTextSystem::new()),
 92            callbacks: Mutex::new(Callbacks::default()),
 93            state: Mutex::new(LinuxPlatformState {
 94                quit_requested: false,
 95                windows: HashMap::default(),
 96            }),
 97        }
 98    }
 99}
100
101impl Platform for LinuxPlatform {
102    fn background_executor(&self) -> BackgroundExecutor {
103        self.background_executor.clone()
104    }
105
106    fn foreground_executor(&self) -> ForegroundExecutor {
107        self.foreground_executor.clone()
108    }
109
110    fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
111        self.text_system.clone()
112    }
113
114    fn run(&self, on_finish_launching: Box<dyn FnOnce()>) {
115        on_finish_launching();
116        //Note: here and below, don't keep the lock() open when calling
117        // into window functions as they may invoke callbacks that need
118        // to immediately access the platform (self).
119        while !self.state.lock().quit_requested {
120            let event = self.xcb_connection.wait_for_event().unwrap();
121            match event {
122                xcb::Event::X(x::Event::ClientMessage(ev)) => {
123                    if let x::ClientMessageData::Data32([atom, ..]) = ev.data() {
124                        if atom == self.atoms.wm_del_window.resource_id() {
125                            // window "x" button clicked by user, we gracefully exit
126                            let window = self.state.lock().windows.remove(&ev.window()).unwrap();
127                            window.destroy();
128                            if self.state.lock().windows.is_empty() {
129                                if let Some(ref mut fun) = self.callbacks.lock().quit {
130                                    fun();
131                                }
132                            }
133                        }
134                    }
135                }
136                xcb::Event::X(x::Event::Expose(ev)) => {
137                    let window = {
138                        let state = self.state.lock();
139                        Arc::clone(&state.windows[&ev.window()])
140                    };
141                    window.expose();
142                }
143                xcb::Event::X(x::Event::ConfigureNotify(ev)) => {
144                    let bounds = Bounds {
145                        origin: Point {
146                            x: ev.x().into(),
147                            y: ev.y().into(),
148                        },
149                        size: Size {
150                            width: ev.width().into(),
151                            height: ev.height().into(),
152                        },
153                    };
154                    let window = {
155                        let state = self.state.lock();
156                        Arc::clone(&state.windows[&ev.window()])
157                    };
158                    window.configure(bounds)
159                }
160                _ => {}
161            }
162
163            if let Ok(runnable) = self.main_receiver.try_recv() {
164                runnable.run();
165            }
166        }
167    }
168
169    fn quit(&self) {
170        self.state.lock().quit_requested = true;
171    }
172
173    //todo!(linux)
174    fn restart(&self) {}
175
176    //todo!(linux)
177    fn activate(&self, ignoring_other_apps: bool) {}
178
179    //todo!(linux)
180    fn hide(&self) {}
181
182    //todo!(linux)
183    fn hide_other_apps(&self) {}
184
185    //todo!(linux)
186    fn unhide_other_apps(&self) {}
187
188    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
189        let setup = self.xcb_connection.get_setup();
190        setup
191            .roots()
192            .enumerate()
193            .map(|(root_id, _)| {
194                Rc::new(LinuxDisplay::new(&self.xcb_connection, root_id as i32))
195                    as Rc<dyn PlatformDisplay>
196            })
197            .collect()
198    }
199
200    fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
201        Some(Rc::new(LinuxDisplay::new(
202            &self.xcb_connection,
203            id.0 as i32,
204        )))
205    }
206
207    //todo!(linux)
208    fn active_window(&self) -> Option<AnyWindowHandle> {
209        None
210    }
211
212    fn open_window(
213        &self,
214        handle: AnyWindowHandle,
215        options: WindowOptions,
216    ) -> Box<dyn PlatformWindow> {
217        let x_window = self.xcb_connection.generate_id();
218
219        let window_ptr = Arc::new(LinuxWindowState::new(
220            options,
221            &self.xcb_connection,
222            self.x_root_index,
223            x_window,
224            &self.atoms,
225        ));
226
227        self.state
228            .lock()
229            .windows
230            .insert(x_window, Arc::clone(&window_ptr));
231        Box::new(LinuxWindow(window_ptr))
232    }
233
234    fn set_display_link_output_callback(
235        &self,
236        display_id: DisplayId,
237        callback: Box<dyn FnMut() + Send>,
238    ) {
239        log::warn!("unimplemented: set_display_link_output_callback");
240    }
241
242    fn start_display_link(&self, display_id: DisplayId) {
243        unimplemented!()
244    }
245
246    fn stop_display_link(&self, display_id: DisplayId) {
247        unimplemented!()
248    }
249
250    fn open_url(&self, url: &str) {
251        unimplemented!()
252    }
253
254    fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
255        self.callbacks.lock().open_urls = Some(callback);
256    }
257
258    fn prompt_for_paths(
259        &self,
260        options: PathPromptOptions,
261    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
262        unimplemented!()
263    }
264
265    fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
266        unimplemented!()
267    }
268
269    fn reveal_path(&self, path: &Path) {
270        unimplemented!()
271    }
272
273    fn on_become_active(&self, callback: Box<dyn FnMut()>) {
274        self.callbacks.lock().become_active = Some(callback);
275    }
276
277    fn on_resign_active(&self, callback: Box<dyn FnMut()>) {
278        self.callbacks.lock().resign_active = Some(callback);
279    }
280
281    fn on_quit(&self, callback: Box<dyn FnMut()>) {
282        self.callbacks.lock().quit = Some(callback);
283    }
284
285    fn on_reopen(&self, callback: Box<dyn FnMut()>) {
286        self.callbacks.lock().reopen = Some(callback);
287    }
288
289    fn on_event(&self, callback: Box<dyn FnMut(PlatformInput) -> bool>) {
290        self.callbacks.lock().event = Some(callback);
291    }
292
293    fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
294        self.callbacks.lock().app_menu_action = Some(callback);
295    }
296
297    fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
298        self.callbacks.lock().will_open_app_menu = Some(callback);
299    }
300
301    fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
302        self.callbacks.lock().validate_app_menu_command = Some(callback);
303    }
304
305    fn os_name(&self) -> &'static str {
306        "Linux"
307    }
308
309    fn double_click_interval(&self) -> Duration {
310        Duration::default()
311    }
312
313    fn os_version(&self) -> Result<SemanticVersion> {
314        Ok(SemanticVersion {
315            major: 1,
316            minor: 0,
317            patch: 0,
318        })
319    }
320
321    fn app_version(&self) -> Result<SemanticVersion> {
322        Ok(SemanticVersion {
323            major: 1,
324            minor: 0,
325            patch: 0,
326        })
327    }
328
329    fn app_path(&self) -> Result<PathBuf> {
330        unimplemented!()
331    }
332
333    //todo!(linux)
334    fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap) {}
335
336    fn local_timezone(&self) -> UtcOffset {
337        UtcOffset::UTC
338    }
339
340    fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
341        unimplemented!()
342    }
343
344    //todo!(linux)
345    fn set_cursor_style(&self, style: CursorStyle) {}
346
347    //todo!(linux)
348    fn should_auto_hide_scrollbars(&self) -> bool {
349        unimplemented!()
350    }
351
352    //todo!(linux)
353    fn write_to_clipboard(&self, item: ClipboardItem) {}
354
355    //todo!(linux)
356    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
357        None
358    }
359
360    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
361        unimplemented!()
362    }
363
364    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
365        unimplemented!()
366    }
367
368    fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
369        unimplemented!()
370    }
371
372    fn window_appearance(&self) -> crate::WindowAppearance {
373        unimplemented!()
374    }
375}
376
377#[cfg(test)]
378mod tests {
379    use crate::ClipboardItem;
380
381    use super::*;
382
383    fn build_platform() -> LinuxPlatform {
384        let platform = LinuxPlatform::new();
385        platform
386    }
387}