platform.rs

  1#![allow(unused)]
  2
  3use std::env;
  4use std::{
  5    path::{Path, PathBuf},
  6    rc::Rc,
  7    sync::Arc,
  8    time::Duration,
  9};
 10
 11use ashpd::desktop::file_chooser::{OpenFileRequest, SaveFileRequest};
 12use async_task::Runnable;
 13use flume::{Receiver, Sender};
 14use futures::channel::oneshot;
 15use parking_lot::Mutex;
 16use time::UtcOffset;
 17use wayland_client::Connection;
 18
 19use crate::platform::linux::client::Client;
 20use crate::platform::linux::client_dispatcher::ClientDispatcher;
 21use crate::platform::linux::wayland::{WaylandClient, WaylandClientDispatcher};
 22use crate::platform::{X11Client, X11ClientDispatcher, XcbAtoms};
 23use crate::{
 24    Action, AnyWindowHandle, BackgroundExecutor, ClipboardItem, CursorStyle, DisplayId,
 25    ForegroundExecutor, Keymap, LinuxDispatcher, LinuxTextSystem, Menu, PathPromptOptions,
 26    Platform, PlatformDisplay, PlatformInput, PlatformTextSystem, PlatformWindow, Result,
 27    SemanticVersion, Task, WindowOptions,
 28};
 29
 30#[derive(Default)]
 31pub(crate) struct Callbacks {
 32    open_urls: Option<Box<dyn FnMut(Vec<String>)>>,
 33    become_active: Option<Box<dyn FnMut()>>,
 34    resign_active: Option<Box<dyn FnMut()>>,
 35    pub(crate) quit: Option<Box<dyn FnMut()>>,
 36    reopen: Option<Box<dyn FnMut()>>,
 37    event: Option<Box<dyn FnMut(PlatformInput) -> bool>>,
 38    app_menu_action: Option<Box<dyn FnMut(&dyn Action)>>,
 39    will_open_app_menu: Option<Box<dyn FnMut()>>,
 40    validate_app_menu_command: Option<Box<dyn FnMut(&dyn Action) -> bool>>,
 41}
 42
 43pub(crate) struct LinuxPlatformInner {
 44    pub(crate) background_executor: BackgroundExecutor,
 45    pub(crate) foreground_executor: ForegroundExecutor,
 46    pub(crate) main_receiver: flume::Receiver<Runnable>,
 47    pub(crate) text_system: Arc<LinuxTextSystem>,
 48    pub(crate) callbacks: Mutex<Callbacks>,
 49    pub(crate) state: Mutex<LinuxPlatformState>,
 50}
 51
 52pub(crate) struct LinuxPlatform {
 53    client: Rc<dyn Client>,
 54    inner: Rc<LinuxPlatformInner>,
 55}
 56
 57pub(crate) struct LinuxPlatformState {
 58    pub(crate) quit_requested: bool,
 59}
 60
 61impl Default for LinuxPlatform {
 62    fn default() -> Self {
 63        Self::new()
 64    }
 65}
 66
 67impl LinuxPlatform {
 68    pub(crate) fn new() -> Self {
 69        let wayland_display = env::var_os("WAYLAND_DISPLAY");
 70        let use_wayland = wayland_display.is_some() && !wayland_display.unwrap().is_empty();
 71
 72        let (main_sender, main_receiver) = flume::unbounded::<Runnable>();
 73        let text_system = Arc::new(LinuxTextSystem::new());
 74        let callbacks = Mutex::new(Callbacks::default());
 75        let state = Mutex::new(LinuxPlatformState {
 76            quit_requested: false,
 77        });
 78
 79        if use_wayland {
 80            Self::new_wayland(main_sender, main_receiver, text_system, callbacks, state)
 81        } else {
 82            Self::new_x11(main_sender, main_receiver, text_system, callbacks, state)
 83        }
 84    }
 85
 86    fn new_wayland(
 87        main_sender: Sender<Runnable>,
 88        main_receiver: Receiver<Runnable>,
 89        text_system: Arc<LinuxTextSystem>,
 90        callbacks: Mutex<Callbacks>,
 91        state: Mutex<LinuxPlatformState>,
 92    ) -> Self {
 93        let conn = Arc::new(Connection::connect_to_env().unwrap());
 94        let client_dispatcher: Arc<dyn ClientDispatcher + Send + Sync> =
 95            Arc::new(WaylandClientDispatcher::new(&conn));
 96        let dispatcher = Arc::new(LinuxDispatcher::new(main_sender, &client_dispatcher));
 97        let inner = Rc::new(LinuxPlatformInner {
 98            background_executor: BackgroundExecutor::new(dispatcher.clone()),
 99            foreground_executor: ForegroundExecutor::new(dispatcher.clone()),
100            main_receiver,
101            text_system,
102            callbacks,
103            state,
104        });
105        let client = Rc::new(WaylandClient::new(Rc::clone(&inner), Arc::clone(&conn)));
106        Self {
107            client,
108            inner: Rc::clone(&inner),
109        }
110    }
111
112    fn new_x11(
113        main_sender: Sender<Runnable>,
114        main_receiver: Receiver<Runnable>,
115        text_system: Arc<LinuxTextSystem>,
116        callbacks: Mutex<Callbacks>,
117        state: Mutex<LinuxPlatformState>,
118    ) -> Self {
119        let (xcb_connection, x_root_index) = xcb::Connection::connect_with_extensions(
120            None,
121            &[xcb::Extension::Present, xcb::Extension::Xkb],
122            &[],
123        )
124        .unwrap();
125
126        let xkb_ver = xcb_connection
127            .wait_for_reply(xcb_connection.send_request(&xcb::xkb::UseExtension {
128                wanted_major: xcb::xkb::MAJOR_VERSION as u16,
129                wanted_minor: xcb::xkb::MINOR_VERSION as u16,
130            }))
131            .unwrap();
132        assert!(xkb_ver.supported());
133
134        let atoms = XcbAtoms::intern_all(&xcb_connection).unwrap();
135        let xcb_connection = Arc::new(xcb_connection);
136        let client_dispatcher: Arc<dyn ClientDispatcher + Send + Sync> =
137            Arc::new(X11ClientDispatcher::new(&xcb_connection, x_root_index));
138        let dispatcher = Arc::new(LinuxDispatcher::new(main_sender, &client_dispatcher));
139        let inner = Rc::new(LinuxPlatformInner {
140            background_executor: BackgroundExecutor::new(dispatcher.clone()),
141            foreground_executor: ForegroundExecutor::new(dispatcher.clone()),
142            main_receiver,
143            text_system,
144            callbacks,
145            state,
146        });
147        let client = Rc::new(X11Client::new(
148            Rc::clone(&inner),
149            xcb_connection,
150            x_root_index,
151            atoms,
152        ));
153        Self {
154            client,
155            inner: Rc::clone(&inner),
156        }
157    }
158}
159
160impl Platform for LinuxPlatform {
161    fn background_executor(&self) -> BackgroundExecutor {
162        self.inner.background_executor.clone()
163    }
164
165    fn foreground_executor(&self) -> ForegroundExecutor {
166        self.inner.foreground_executor.clone()
167    }
168
169    fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
170        self.inner.text_system.clone()
171    }
172
173    fn run(&self, on_finish_launching: Box<dyn FnOnce()>) {
174        self.client.run(on_finish_launching)
175    }
176
177    fn quit(&self) {
178        self.inner.state.lock().quit_requested = true;
179    }
180
181    //todo!(linux)
182    fn restart(&self) {}
183
184    //todo!(linux)
185    fn activate(&self, ignoring_other_apps: bool) {}
186
187    //todo!(linux)
188    fn hide(&self) {}
189
190    //todo!(linux)
191    fn hide_other_apps(&self) {}
192
193    //todo!(linux)
194    fn unhide_other_apps(&self) {}
195
196    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
197        self.client.displays()
198    }
199
200    fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
201        self.client.display(id)
202    }
203
204    //todo!(linux)
205    fn active_window(&self) -> Option<AnyWindowHandle> {
206        None
207    }
208
209    fn open_window(
210        &self,
211        handle: AnyWindowHandle,
212        options: WindowOptions,
213    ) -> Box<dyn PlatformWindow> {
214        self.client.open_window(handle, options)
215    }
216
217    fn open_url(&self, url: &str) {
218        open::that(url);
219    }
220
221    fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
222        self.inner.callbacks.lock().open_urls = Some(callback);
223    }
224
225    fn prompt_for_paths(
226        &self,
227        options: PathPromptOptions,
228    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
229        let (done_tx, done_rx) = oneshot::channel();
230        self.inner
231            .foreground_executor
232            .spawn(async move {
233                let title = if options.multiple {
234                    if !options.files {
235                        "Open folders"
236                    } else {
237                        "Open files"
238                    }
239                } else {
240                    if !options.files {
241                        "Open folder"
242                    } else {
243                        "Open file"
244                    }
245                };
246
247                let result = OpenFileRequest::default()
248                    .modal(true)
249                    .title(title)
250                    .accept_label("Select")
251                    .multiple(options.multiple)
252                    .directory(options.directories)
253                    .send()
254                    .await
255                    .ok()
256                    .and_then(|request| request.response().ok())
257                    .and_then(|response| {
258                        response
259                            .uris()
260                            .iter()
261                            .map(|uri| uri.to_file_path().ok())
262                            .collect()
263                    });
264
265                done_tx.send(result);
266            })
267            .detach();
268        done_rx
269    }
270
271    fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
272        let (done_tx, done_rx) = oneshot::channel();
273        let directory = directory.to_owned();
274        self.inner
275            .foreground_executor
276            .spawn(async move {
277                let result = SaveFileRequest::default()
278                    .modal(true)
279                    .title("Select new path")
280                    .accept_label("Accept")
281                    .send()
282                    .await
283                    .ok()
284                    .and_then(|request| request.response().ok())
285                    .and_then(|response| {
286                        response
287                            .uris()
288                            .first()
289                            .and_then(|uri| uri.to_file_path().ok())
290                    });
291
292                done_tx.send(result);
293            })
294            .detach();
295        done_rx
296    }
297
298    fn reveal_path(&self, path: &Path) {
299        if path.is_dir() {
300            open::that(path);
301            return;
302        }
303        // If `path` is a file, the system may try to open it in a text editor
304        let dir = path.parent().unwrap_or(Path::new(""));
305        open::that(dir);
306    }
307
308    fn on_become_active(&self, callback: Box<dyn FnMut()>) {
309        self.inner.callbacks.lock().become_active = Some(callback);
310    }
311
312    fn on_resign_active(&self, callback: Box<dyn FnMut()>) {
313        self.inner.callbacks.lock().resign_active = Some(callback);
314    }
315
316    fn on_quit(&self, callback: Box<dyn FnMut()>) {
317        self.inner.callbacks.lock().quit = Some(callback);
318    }
319
320    fn on_reopen(&self, callback: Box<dyn FnMut()>) {
321        self.inner.callbacks.lock().reopen = Some(callback);
322    }
323
324    fn on_event(&self, callback: Box<dyn FnMut(PlatformInput) -> bool>) {
325        self.inner.callbacks.lock().event = Some(callback);
326    }
327
328    fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
329        self.inner.callbacks.lock().app_menu_action = Some(callback);
330    }
331
332    fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
333        self.inner.callbacks.lock().will_open_app_menu = Some(callback);
334    }
335
336    fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
337        self.inner.callbacks.lock().validate_app_menu_command = Some(callback);
338    }
339
340    fn os_name(&self) -> &'static str {
341        "Linux"
342    }
343
344    fn double_click_interval(&self) -> Duration {
345        Duration::default()
346    }
347
348    fn os_version(&self) -> Result<SemanticVersion> {
349        Ok(SemanticVersion {
350            major: 1,
351            minor: 0,
352            patch: 0,
353        })
354    }
355
356    fn app_version(&self) -> Result<SemanticVersion> {
357        Ok(SemanticVersion {
358            major: 1,
359            minor: 0,
360            patch: 0,
361        })
362    }
363
364    fn app_path(&self) -> Result<PathBuf> {
365        unimplemented!()
366    }
367
368    //todo!(linux)
369    fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap) {}
370
371    fn local_timezone(&self) -> UtcOffset {
372        UtcOffset::UTC
373    }
374
375    fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
376        unimplemented!()
377    }
378
379    //todo!(linux)
380    fn set_cursor_style(&self, style: CursorStyle) {}
381
382    //todo!(linux)
383    fn should_auto_hide_scrollbars(&self) -> bool {
384        false
385    }
386
387    //todo!(linux)
388    fn write_to_clipboard(&self, item: ClipboardItem) {}
389
390    //todo!(linux)
391    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
392        None
393    }
394
395    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
396        unimplemented!()
397    }
398
399    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
400        unimplemented!()
401    }
402
403    fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
404        unimplemented!()
405    }
406
407    fn window_appearance(&self) -> crate::WindowAppearance {
408        crate::WindowAppearance::Light
409    }
410}
411
412#[cfg(test)]
413mod tests {
414    use super::*;
415
416    fn build_platform() -> LinuxPlatform {
417        let platform = LinuxPlatform::new();
418        platform
419    }
420}