platform.rs

  1#![allow(unused)]
  2
  3use std::any::{type_name, Any};
  4use std::cell::{self, RefCell};
  5use std::env;
  6use std::ops::{Deref, DerefMut};
  7use std::panic::Location;
  8use std::{
  9    path::{Path, PathBuf},
 10    process::Command,
 11    rc::Rc,
 12    sync::Arc,
 13    time::Duration,
 14};
 15
 16use anyhow::anyhow;
 17use ashpd::desktop::file_chooser::{OpenFileRequest, SaveFileRequest};
 18use async_task::Runnable;
 19use calloop::channel::Channel;
 20use calloop::{EventLoop, LoopHandle, LoopSignal};
 21use copypasta::ClipboardProvider;
 22use flume::{Receiver, Sender};
 23use futures::channel::oneshot;
 24use parking_lot::Mutex;
 25use time::UtcOffset;
 26use wayland_client::Connection;
 27use xkbcommon::xkb::{self, Keycode, Keysym, State};
 28
 29use crate::platform::linux::wayland::WaylandClient;
 30use crate::{
 31    px, Action, AnyWindowHandle, BackgroundExecutor, ClipboardItem, CosmicTextSystem, CursorStyle,
 32    DisplayId, ForegroundExecutor, Keymap, Keystroke, LinuxDispatcher, Menu, Modifiers,
 33    PathPromptOptions, Pixels, Platform, PlatformDisplay, PlatformInput, PlatformInputHandler,
 34    PlatformTextSystem, PlatformWindow, Point, PromptLevel, Result, SemanticVersion, Size, Task,
 35    WindowAppearance, WindowOptions, WindowParams,
 36};
 37
 38use super::x11::X11Client;
 39
 40pub(crate) const SCROLL_LINES: f64 = 3.0;
 41
 42// Values match the defaults on GTK.
 43// Taken from https://github.com/GNOME/gtk/blob/main/gtk/gtksettings.c#L320
 44pub(crate) const DOUBLE_CLICK_INTERVAL: Duration = Duration::from_millis(400);
 45pub(crate) const DOUBLE_CLICK_DISTANCE: Pixels = px(5.0);
 46pub(crate) const KEYRING_LABEL: &str = "zed-github-account";
 47
 48pub trait LinuxClient {
 49    fn with_common<R>(&self, f: impl FnOnce(&mut LinuxCommon) -> R) -> R;
 50    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>>;
 51    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>>;
 52    fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>>;
 53    fn open_window(
 54        &self,
 55        handle: AnyWindowHandle,
 56        options: WindowParams,
 57    ) -> Box<dyn PlatformWindow>;
 58    fn set_cursor_style(&self, style: CursorStyle);
 59    fn write_to_clipboard(&self, item: ClipboardItem);
 60    fn read_from_clipboard(&self) -> Option<ClipboardItem>;
 61    fn run(&self);
 62}
 63
 64#[derive(Default)]
 65pub(crate) struct PlatformHandlers {
 66    pub(crate) open_urls: Option<Box<dyn FnMut(Vec<String>)>>,
 67    pub(crate) become_active: Option<Box<dyn FnMut()>>,
 68    pub(crate) resign_active: Option<Box<dyn FnMut()>>,
 69    pub(crate) quit: Option<Box<dyn FnMut()>>,
 70    pub(crate) reopen: Option<Box<dyn FnMut()>>,
 71    pub(crate) event: Option<Box<dyn FnMut(PlatformInput) -> bool>>,
 72    pub(crate) app_menu_action: Option<Box<dyn FnMut(&dyn Action)>>,
 73    pub(crate) will_open_app_menu: Option<Box<dyn FnMut()>>,
 74    pub(crate) validate_app_menu_command: Option<Box<dyn FnMut(&dyn Action) -> bool>>,
 75}
 76
 77pub(crate) struct LinuxCommon {
 78    pub(crate) background_executor: BackgroundExecutor,
 79    pub(crate) foreground_executor: ForegroundExecutor,
 80    pub(crate) text_system: Arc<CosmicTextSystem>,
 81    pub(crate) callbacks: PlatformHandlers,
 82    pub(crate) signal: LoopSignal,
 83}
 84
 85impl LinuxCommon {
 86    pub fn new(signal: LoopSignal) -> (Self, Channel<Runnable>) {
 87        let (main_sender, main_receiver) = calloop::channel::channel::<Runnable>();
 88        let text_system = Arc::new(CosmicTextSystem::new());
 89        let callbacks = PlatformHandlers::default();
 90
 91        let dispatcher = Arc::new(LinuxDispatcher::new(main_sender));
 92
 93        let common = LinuxCommon {
 94            background_executor: BackgroundExecutor::new(dispatcher.clone()),
 95            foreground_executor: ForegroundExecutor::new(dispatcher.clone()),
 96            text_system,
 97            callbacks,
 98            signal,
 99        };
100
101        (common, main_receiver)
102    }
103}
104
105impl<P: LinuxClient + 'static> Platform for P {
106    fn background_executor(&self) -> BackgroundExecutor {
107        self.with_common(|common| common.background_executor.clone())
108    }
109
110    fn foreground_executor(&self) -> ForegroundExecutor {
111        self.with_common(|common| common.foreground_executor.clone())
112    }
113
114    fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
115        self.with_common(|common| common.text_system.clone())
116    }
117
118    fn run(&self, on_finish_launching: Box<dyn FnOnce()>) {
119        on_finish_launching();
120
121        LinuxClient::run(self);
122
123        self.with_common(|common| {
124            if let Some(mut fun) = common.callbacks.quit.take() {
125                fun();
126            }
127        });
128    }
129
130    fn quit(&self) {
131        self.with_common(|common| common.signal.stop());
132    }
133
134    fn restart(&self) {
135        use std::os::unix::process::CommandExt as _;
136
137        // get the process id of the current process
138        let app_pid = std::process::id().to_string();
139        // get the path to the executable
140        let app_path = match self.app_path() {
141            Ok(path) => path,
142            Err(err) => {
143                log::error!("Failed to get app path: {:?}", err);
144                return;
145            }
146        };
147
148        // script to wait for the current process to exit  and then restart the app
149        let script = format!(
150            r#"
151            while kill -O {pid} 2>/dev/null; do
152                sleep 0.1
153            done
154            {app_path}
155            "#,
156            pid = app_pid,
157            app_path = app_path.display()
158        );
159
160        // execute the script using /bin/bash
161        let restart_process = Command::new("/bin/bash")
162            .arg("-c")
163            .arg(script)
164            .process_group(0)
165            .spawn();
166
167        match restart_process {
168            Ok(_) => self.quit(),
169            Err(e) => log::error!("failed to spawn restart script: {:?}", e),
170        }
171    }
172
173    // todo(linux)
174    fn activate(&self, ignoring_other_apps: bool) {}
175
176    // todo(linux)
177    fn hide(&self) {}
178
179    fn hide_other_apps(&self) {
180        log::warn!("hide_other_apps is not implemented on Linux, ignoring the call")
181    }
182
183    // todo(linux)
184    fn unhide_other_apps(&self) {}
185
186    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
187        self.primary_display()
188    }
189
190    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
191        self.displays()
192    }
193
194    fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
195        self.display(id)
196    }
197
198    // todo(linux)
199    fn active_window(&self) -> Option<AnyWindowHandle> {
200        None
201    }
202
203    fn open_window(
204        &self,
205        handle: AnyWindowHandle,
206        options: WindowParams,
207    ) -> Box<dyn PlatformWindow> {
208        self.open_window(handle, options)
209    }
210
211    fn open_url(&self, url: &str) {
212        open::that(url);
213    }
214
215    fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
216        self.with_common(|common| common.callbacks.open_urls = Some(callback));
217    }
218
219    fn prompt_for_paths(
220        &self,
221        options: PathPromptOptions,
222    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
223        let (done_tx, done_rx) = oneshot::channel();
224        self.foreground_executor()
225            .spawn(async move {
226                let title = if options.multiple {
227                    if !options.files {
228                        "Open folders"
229                    } else {
230                        "Open files"
231                    }
232                } else {
233                    if !options.files {
234                        "Open folder"
235                    } else {
236                        "Open file"
237                    }
238                };
239
240                let result = OpenFileRequest::default()
241                    .modal(true)
242                    .title(title)
243                    .accept_label("Select")
244                    .multiple(options.multiple)
245                    .directory(options.directories)
246                    .send()
247                    .await
248                    .ok()
249                    .and_then(|request| request.response().ok())
250                    .and_then(|response| {
251                        response
252                            .uris()
253                            .iter()
254                            .map(|uri| uri.to_file_path().ok())
255                            .collect()
256                    });
257
258                done_tx.send(result);
259            })
260            .detach();
261        done_rx
262    }
263
264    fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
265        let (done_tx, done_rx) = oneshot::channel();
266        let directory = directory.to_owned();
267        self.foreground_executor()
268            .spawn(async move {
269                let result = SaveFileRequest::default()
270                    .modal(true)
271                    .title("Select new path")
272                    .accept_label("Accept")
273                    .send()
274                    .await
275                    .ok()
276                    .and_then(|request| request.response().ok())
277                    .and_then(|response| {
278                        response
279                            .uris()
280                            .first()
281                            .and_then(|uri| uri.to_file_path().ok())
282                    });
283
284                done_tx.send(result);
285            })
286            .detach();
287
288        done_rx
289    }
290
291    fn reveal_path(&self, path: &Path) {
292        if path.is_dir() {
293            open::that(path);
294            return;
295        }
296        // If `path` is a file, the system may try to open it in a text editor
297        let dir = path.parent().unwrap_or(Path::new(""));
298        open::that(dir);
299    }
300
301    fn on_become_active(&self, callback: Box<dyn FnMut()>) {
302        self.with_common(|common| {
303            common.callbacks.become_active = Some(callback);
304        });
305    }
306
307    fn on_resign_active(&self, callback: Box<dyn FnMut()>) {
308        self.with_common(|common| {
309            common.callbacks.resign_active = Some(callback);
310        });
311    }
312
313    fn on_quit(&self, callback: Box<dyn FnMut()>) {
314        self.with_common(|common| {
315            common.callbacks.quit = Some(callback);
316        });
317    }
318
319    fn on_reopen(&self, callback: Box<dyn FnMut()>) {
320        self.with_common(|common| {
321            common.callbacks.reopen = Some(callback);
322        });
323    }
324
325    fn on_event(&self, callback: Box<dyn FnMut(PlatformInput) -> bool>) {
326        self.with_common(|common| {
327            common.callbacks.event = Some(callback);
328        });
329    }
330
331    fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
332        self.with_common(|common| {
333            common.callbacks.app_menu_action = Some(callback);
334        });
335    }
336
337    fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
338        self.with_common(|common| {
339            common.callbacks.will_open_app_menu = Some(callback);
340        });
341    }
342
343    fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
344        self.with_common(|common| {
345            common.callbacks.validate_app_menu_command = Some(callback);
346        });
347    }
348
349    fn os_name(&self) -> &'static str {
350        "Linux"
351    }
352
353    fn os_version(&self) -> Result<SemanticVersion> {
354        Ok(SemanticVersion::new(1, 0, 0))
355    }
356
357    fn app_version(&self) -> Result<SemanticVersion> {
358        Ok(SemanticVersion::new(1, 0, 0))
359    }
360
361    fn app_path(&self) -> Result<PathBuf> {
362        // get the path of the executable of the current process
363        let exe_path = std::env::current_exe()?;
364        Ok(exe_path)
365    }
366
367    // todo(linux)
368    fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap) {}
369
370    fn local_timezone(&self) -> UtcOffset {
371        UtcOffset::UTC
372    }
373
374    //todo(linux)
375    fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
376        Err(anyhow::Error::msg(
377            "Platform<LinuxPlatform>::path_for_auxiliary_executable is not implemented yet",
378        ))
379    }
380
381    fn set_cursor_style(&self, style: CursorStyle) {
382        self.set_cursor_style(style)
383    }
384
385    // todo(linux)
386    fn should_auto_hide_scrollbars(&self) -> bool {
387        false
388    }
389
390    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
391        let url = url.to_string();
392        let username = username.to_string();
393        let password = password.to_vec();
394        self.background_executor().spawn(async move {
395            let keyring = oo7::Keyring::new().await?;
396            keyring.unlock().await?;
397            keyring
398                .create_item(
399                    KEYRING_LABEL,
400                    &vec![("url", &url), ("username", &username)],
401                    password,
402                    true,
403                )
404                .await?;
405            Ok(())
406        })
407    }
408
409    //todo(linux): add trait methods for accessing the primary selection
410    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
411        let url = url.to_string();
412        self.background_executor().spawn(async move {
413            let keyring = oo7::Keyring::new().await?;
414            keyring.unlock().await?;
415
416            let items = keyring.search_items(&vec![("url", &url)]).await?;
417
418            for item in items.into_iter() {
419                if item.label().await.is_ok_and(|label| label == KEYRING_LABEL) {
420                    let attributes = item.attributes().await?;
421                    let username = attributes
422                        .get("username")
423                        .ok_or_else(|| anyhow!("Cannot find username in stored credentials"))?;
424                    let secret = item.secret().await?;
425
426                    // we lose the zeroizing capabilities at this boundary,
427                    // a current limitation GPUI's credentials api
428                    return Ok(Some((username.to_string(), secret.to_vec())));
429                } else {
430                    continue;
431                }
432            }
433            Ok(None)
434        })
435    }
436
437    fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
438        let url = url.to_string();
439        self.background_executor().spawn(async move {
440            let keyring = oo7::Keyring::new().await?;
441            keyring.unlock().await?;
442
443            let items = keyring.search_items(&vec![("url", &url)]).await?;
444
445            for item in items.into_iter() {
446                if item.label().await.is_ok_and(|label| label == KEYRING_LABEL) {
447                    item.delete().await?;
448                    return Ok(());
449                }
450            }
451
452            Ok(())
453        })
454    }
455
456    fn window_appearance(&self) -> crate::WindowAppearance {
457        crate::WindowAppearance::Light
458    }
459
460    fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> {
461        Task::ready(Err(anyhow!("register_url_scheme unimplemented")))
462    }
463
464    fn write_to_clipboard(&self, item: ClipboardItem) {
465        self.write_to_clipboard(item)
466    }
467
468    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
469        self.read_from_clipboard()
470    }
471}
472
473pub(super) fn is_within_click_distance(a: Point<Pixels>, b: Point<Pixels>) -> bool {
474    let diff = a - b;
475    diff.x.abs() <= DOUBLE_CLICK_DISTANCE && diff.y.abs() <= DOUBLE_CLICK_DISTANCE
476}
477
478impl Keystroke {
479    pub(super) fn from_xkb(state: &State, modifiers: Modifiers, keycode: Keycode) -> Self {
480        let mut modifiers = modifiers;
481
482        let key_utf32 = state.key_get_utf32(keycode);
483        let key_utf8 = state.key_get_utf8(keycode);
484        let key_sym = state.key_get_one_sym(keycode);
485
486        // The logic here tries to replicate the logic in `../mac/events.rs`
487        // "Consumed" modifiers are modifiers that have been used to translate a key, for example
488        // pressing "shift" and "1" on US layout produces the key `!` but "consumes" the shift.
489        // Notes:
490        //  - macOS gets the key character directly ("."), xkb gives us the key name ("period")
491        //  - macOS logic removes consumed shift modifier for symbols: "{", not "shift-{"
492        //  - macOS logic keeps consumed shift modifiers for letters: "shift-a", not "a" or "A"
493
494        let mut handle_consumed_modifiers = true;
495        let key = match key_sym {
496            Keysym::Return => "enter".to_owned(),
497            Keysym::Prior => "pageup".to_owned(),
498            Keysym::Next => "pagedown".to_owned(),
499
500            Keysym::comma => ",".to_owned(),
501            Keysym::period => ".".to_owned(),
502            Keysym::less => "<".to_owned(),
503            Keysym::greater => ">".to_owned(),
504            Keysym::slash => "/".to_owned(),
505            Keysym::question => "?".to_owned(),
506
507            Keysym::semicolon => ";".to_owned(),
508            Keysym::colon => ":".to_owned(),
509            Keysym::apostrophe => "'".to_owned(),
510            Keysym::quotedbl => "\"".to_owned(),
511
512            Keysym::bracketleft => "[".to_owned(),
513            Keysym::braceleft => "{".to_owned(),
514            Keysym::bracketright => "]".to_owned(),
515            Keysym::braceright => "}".to_owned(),
516            Keysym::backslash => "\\".to_owned(),
517            Keysym::bar => "|".to_owned(),
518
519            Keysym::grave => "`".to_owned(),
520            Keysym::asciitilde => "~".to_owned(),
521            Keysym::exclam => "!".to_owned(),
522            Keysym::at => "@".to_owned(),
523            Keysym::numbersign => "#".to_owned(),
524            Keysym::dollar => "$".to_owned(),
525            Keysym::percent => "%".to_owned(),
526            Keysym::asciicircum => "^".to_owned(),
527            Keysym::ampersand => "&".to_owned(),
528            Keysym::asterisk => "*".to_owned(),
529            Keysym::parenleft => "(".to_owned(),
530            Keysym::parenright => ")".to_owned(),
531            Keysym::minus => "-".to_owned(),
532            Keysym::underscore => "_".to_owned(),
533            Keysym::equal => "=".to_owned(),
534            Keysym::plus => "+".to_owned(),
535
536            Keysym::ISO_Left_Tab => {
537                handle_consumed_modifiers = false;
538                "tab".to_owned()
539            }
540
541            _ => {
542                handle_consumed_modifiers = false;
543                xkb::keysym_get_name(key_sym).to_lowercase()
544            }
545        };
546
547        // Ignore control characters (and DEL) for the purposes of ime_key,
548        // but if key_utf32 is 0 then assume it isn't one
549        let ime_key = ((key_utf32 == 0 || (key_utf32 >= 32 && key_utf32 != 127))
550            && !key_utf8.is_empty())
551        .then_some(key_utf8);
552
553        if handle_consumed_modifiers {
554            let mod_shift_index = state.get_keymap().mod_get_index(xkb::MOD_NAME_SHIFT);
555            let is_shift_consumed = state.mod_index_is_consumed(keycode, mod_shift_index);
556
557            if modifiers.shift && is_shift_consumed {
558                modifiers.shift = false;
559            }
560        }
561
562        Keystroke {
563            modifiers,
564            key,
565            ime_key,
566        }
567    }
568}
569
570impl Modifiers {
571    pub(super) fn from_xkb(keymap_state: &State) -> Self {
572        let shift = keymap_state.mod_name_is_active(xkb::MOD_NAME_SHIFT, xkb::STATE_MODS_EFFECTIVE);
573        let alt = keymap_state.mod_name_is_active(xkb::MOD_NAME_ALT, xkb::STATE_MODS_EFFECTIVE);
574        let control =
575            keymap_state.mod_name_is_active(xkb::MOD_NAME_CTRL, xkb::STATE_MODS_EFFECTIVE);
576        let platform =
577            keymap_state.mod_name_is_active(xkb::MOD_NAME_LOGO, xkb::STATE_MODS_EFFECTIVE);
578        Modifiers {
579            shift,
580            alt,
581            control,
582            platform,
583            function: false,
584        }
585    }
586}
587
588#[cfg(test)]
589mod tests {
590    use super::*;
591    use crate::{px, Point};
592
593    #[test]
594    fn test_is_within_click_distance() {
595        let zero = Point::new(px(0.0), px(0.0));
596        assert_eq!(
597            is_within_click_distance(zero, Point::new(px(5.0), px(5.0))),
598            true
599        );
600        assert_eq!(
601            is_within_click_distance(zero, Point::new(px(-4.9), px(5.0))),
602            true
603        );
604        assert_eq!(
605            is_within_click_distance(Point::new(px(3.0), px(2.0)), Point::new(px(-2.0), px(-2.0))),
606            true
607        );
608        assert_eq!(
609            is_within_click_distance(zero, Point::new(px(5.0), px(5.1))),
610            false
611        );
612    }
613}