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    fn restart(&self) {}
174
175    fn activate(&self, ignoring_other_apps: bool) {}
176
177    fn hide(&self) {}
178
179    fn hide_other_apps(&self) {}
180
181    fn unhide_other_apps(&self) {}
182
183    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
184        let setup = self.xcb_connection.get_setup();
185        setup
186            .roots()
187            .enumerate()
188            .map(|(root_id, _)| {
189                Rc::new(LinuxDisplay::new(&self.xcb_connection, root_id as i32))
190                    as Rc<dyn PlatformDisplay>
191            })
192            .collect()
193    }
194
195    fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
196        Some(Rc::new(LinuxDisplay::new(
197            &self.xcb_connection,
198            id.0 as i32,
199        )))
200    }
201
202    fn active_window(&self) -> Option<AnyWindowHandle> {
203        None
204    }
205
206    fn open_window(
207        &self,
208        handle: AnyWindowHandle,
209        options: WindowOptions,
210    ) -> Box<dyn PlatformWindow> {
211        let x_window = self.xcb_connection.generate_id();
212
213        let window_ptr = Arc::new(LinuxWindowState::new(
214            options,
215            &self.xcb_connection,
216            self.x_root_index,
217            x_window,
218            &self.atoms,
219        ));
220
221        self.state
222            .lock()
223            .windows
224            .insert(x_window, Arc::clone(&window_ptr));
225        Box::new(LinuxWindow(window_ptr))
226    }
227
228    fn set_display_link_output_callback(
229        &self,
230        display_id: DisplayId,
231        callback: Box<dyn FnMut() + Send>,
232    ) {
233        log::warn!("unimplemented: set_display_link_output_callback");
234    }
235
236    fn start_display_link(&self, display_id: DisplayId) {
237        unimplemented!()
238    }
239
240    fn stop_display_link(&self, display_id: DisplayId) {
241        unimplemented!()
242    }
243
244    fn open_url(&self, url: &str) {
245        unimplemented!()
246    }
247
248    fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
249        self.callbacks.lock().open_urls = Some(callback);
250    }
251
252    fn prompt_for_paths(
253        &self,
254        options: PathPromptOptions,
255    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
256        unimplemented!()
257    }
258
259    fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
260        unimplemented!()
261    }
262
263    fn reveal_path(&self, path: &Path) {
264        unimplemented!()
265    }
266
267    fn on_become_active(&self, callback: Box<dyn FnMut()>) {
268        self.callbacks.lock().become_active = Some(callback);
269    }
270
271    fn on_resign_active(&self, callback: Box<dyn FnMut()>) {
272        self.callbacks.lock().resign_active = Some(callback);
273    }
274
275    fn on_quit(&self, callback: Box<dyn FnMut()>) {
276        self.callbacks.lock().quit = Some(callback);
277    }
278
279    fn on_reopen(&self, callback: Box<dyn FnMut()>) {
280        self.callbacks.lock().reopen = Some(callback);
281    }
282
283    fn on_event(&self, callback: Box<dyn FnMut(PlatformInput) -> bool>) {
284        self.callbacks.lock().event = Some(callback);
285    }
286
287    fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
288        self.callbacks.lock().app_menu_action = Some(callback);
289    }
290
291    fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
292        self.callbacks.lock().will_open_app_menu = Some(callback);
293    }
294
295    fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
296        self.callbacks.lock().validate_app_menu_command = Some(callback);
297    }
298
299    fn os_name(&self) -> &'static str {
300        "Linux"
301    }
302
303    fn double_click_interval(&self) -> Duration {
304        Duration::default()
305    }
306
307    fn os_version(&self) -> Result<SemanticVersion> {
308        Ok(SemanticVersion {
309            major: 1,
310            minor: 0,
311            patch: 0,
312        })
313    }
314
315    fn app_version(&self) -> Result<SemanticVersion> {
316        Ok(SemanticVersion {
317            major: 1,
318            minor: 0,
319            patch: 0,
320        })
321    }
322
323    fn app_path(&self) -> Result<PathBuf> {
324        unimplemented!()
325    }
326
327    fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap) {}
328
329    fn local_timezone(&self) -> UtcOffset {
330        UtcOffset::UTC
331    }
332
333    fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
334        unimplemented!()
335    }
336
337    fn set_cursor_style(&self, style: CursorStyle) {}
338
339    fn should_auto_hide_scrollbars(&self) -> bool {
340        false
341    }
342
343    fn write_to_clipboard(&self, item: ClipboardItem) {}
344
345    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
346        None
347    }
348
349    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
350        unimplemented!()
351    }
352
353    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
354        unimplemented!()
355    }
356
357    fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
358        unimplemented!()
359    }
360}
361
362#[cfg(test)]
363mod tests {
364    use crate::ClipboardItem;
365
366    use super::*;
367
368    fn build_platform() -> LinuxPlatform {
369        let platform = LinuxPlatform::new();
370        platform
371    }
372}