platform.rs

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