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