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.foreground_executor()
231            .spawn(async move {
232                let title = if options.multiple {
233                    if !options.files {
234                        "Open folders"
235                    } else {
236                        "Open files"
237                    }
238                } else {
239                    if !options.files {
240                        "Open folder"
241                    } else {
242                        "Open file"
243                    }
244                };
245
246                let result = OpenFileRequest::default()
247                    .modal(true)
248                    .title(title)
249                    .accept_label("Select")
250                    .multiple(options.multiple)
251                    .directory(options.directories)
252                    .send()
253                    .await
254                    .ok()
255                    .and_then(|request| request.response().ok())
256                    .and_then(|response| {
257                        response
258                            .uris()
259                            .iter()
260                            .map(|uri| uri.to_file_path().ok())
261                            .collect()
262                    });
263
264                done_tx.send(result);
265            })
266            .detach();
267        done_rx
268    }
269
270    fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
271        let (done_tx, done_rx) = oneshot::channel();
272        let directory = directory.to_owned();
273        self.foreground_executor()
274            .spawn(async move {
275                let result = SaveFileRequest::default()
276                    .modal(true)
277                    .title("Select new path")
278                    .accept_label("Accept")
279                    .send()
280                    .await
281                    .ok()
282                    .and_then(|request| request.response().ok())
283                    .and_then(|response| {
284                        response
285                            .uris()
286                            .first()
287                            .and_then(|uri| uri.to_file_path().ok())
288                    });
289
290                done_tx.send(result);
291            })
292            .detach();
293        done_rx
294    }
295
296    fn reveal_path(&self, path: &Path) {
297        if path.is_dir() {
298            open::that(path);
299            return;
300        }
301        // If `path` is a file, the system may try to open it in a text editor
302        let dir = path.parent().unwrap_or(Path::new(""));
303        open::that(dir);
304    }
305
306    fn on_become_active(&self, callback: Box<dyn FnMut()>) {
307        self.inner.callbacks.lock().become_active = Some(callback);
308    }
309
310    fn on_resign_active(&self, callback: Box<dyn FnMut()>) {
311        self.inner.callbacks.lock().resign_active = Some(callback);
312    }
313
314    fn on_quit(&self, callback: Box<dyn FnMut()>) {
315        self.inner.callbacks.lock().quit = Some(callback);
316    }
317
318    fn on_reopen(&self, callback: Box<dyn FnMut()>) {
319        self.inner.callbacks.lock().reopen = Some(callback);
320    }
321
322    fn on_event(&self, callback: Box<dyn FnMut(PlatformInput) -> bool>) {
323        self.inner.callbacks.lock().event = Some(callback);
324    }
325
326    fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
327        self.inner.callbacks.lock().app_menu_action = Some(callback);
328    }
329
330    fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
331        self.inner.callbacks.lock().will_open_app_menu = Some(callback);
332    }
333
334    fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
335        self.inner.callbacks.lock().validate_app_menu_command = Some(callback);
336    }
337
338    fn os_name(&self) -> &'static str {
339        "Linux"
340    }
341
342    fn double_click_interval(&self) -> Duration {
343        Duration::default()
344    }
345
346    fn os_version(&self) -> Result<SemanticVersion> {
347        Ok(SemanticVersion {
348            major: 1,
349            minor: 0,
350            patch: 0,
351        })
352    }
353
354    fn app_version(&self) -> Result<SemanticVersion> {
355        Ok(SemanticVersion {
356            major: 1,
357            minor: 0,
358            patch: 0,
359        })
360    }
361
362    fn app_path(&self) -> Result<PathBuf> {
363        unimplemented!()
364    }
365
366    //todo!(linux)
367    fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap) {}
368
369    fn local_timezone(&self) -> UtcOffset {
370        UtcOffset::UTC
371    }
372
373    fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
374        unimplemented!()
375    }
376
377    //todo!(linux)
378    fn set_cursor_style(&self, style: CursorStyle) {}
379
380    //todo!(linux)
381    fn should_auto_hide_scrollbars(&self) -> bool {
382        false
383    }
384
385    //todo!(linux)
386    fn write_to_clipboard(&self, item: ClipboardItem) {}
387
388    //todo!(linux)
389    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
390        None
391    }
392
393    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
394        unimplemented!()
395    }
396
397    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
398        unimplemented!()
399    }
400
401    fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
402        unimplemented!()
403    }
404
405    fn window_appearance(&self) -> crate::WindowAppearance {
406        crate::WindowAppearance::Light
407    }
408}
409
410#[cfg(test)]
411mod tests {
412    use super::*;
413
414    fn build_platform() -> LinuxPlatform {
415        let platform = LinuxPlatform::new();
416        platform
417    }
418}