1#![allow(unused)]
2
3use std::any::{type_name, Any};
4use std::cell::{self, RefCell};
5use std::env;
6use std::ffi::OsString;
7use std::fs::File;
8use std::io::Read;
9use std::ops::{Deref, DerefMut};
10use std::os::fd::{AsRawFd, FromRawFd};
11use std::panic::Location;
12use std::rc::Weak;
13use std::{
14 path::{Path, PathBuf},
15 process::Command,
16 rc::Rc,
17 sync::Arc,
18 time::Duration,
19};
20
21use anyhow::anyhow;
22use ashpd::desktop::file_chooser::{OpenFileRequest, SaveFileRequest};
23use async_task::Runnable;
24use calloop::channel::Channel;
25use calloop::{EventLoop, LoopHandle, LoopSignal};
26use filedescriptor::FileDescriptor;
27use flume::{Receiver, Sender};
28use futures::channel::oneshot;
29use mio::Waker;
30use parking_lot::Mutex;
31use time::UtcOffset;
32use util::ResultExt;
33use wayland_client::Connection;
34use wayland_protocols::wp::cursor_shape::v1::client::wp_cursor_shape_device_v1::Shape;
35use xkbcommon::xkb::{self, Keycode, Keysym, State};
36
37use crate::platform::linux::wayland::WaylandClient;
38use crate::{
39 px, Action, AnyWindowHandle, BackgroundExecutor, ClipboardItem, CosmicTextSystem, CursorStyle,
40 DisplayId, ForegroundExecutor, Keymap, Keystroke, LinuxDispatcher, Menu, MenuItem, Modifiers,
41 OwnedMenu, PathPromptOptions, Pixels, Platform, PlatformDisplay, PlatformInputHandler,
42 PlatformTextSystem, PlatformWindow, Point, PromptLevel, Result, SemanticVersion, SharedString,
43 Size, Task, WindowAppearance, WindowOptions, WindowParams,
44};
45
46use super::x11::X11Client;
47
48pub(crate) const SCROLL_LINES: f64 = 3.0;
49
50// Values match the defaults on GTK.
51// Taken from https://github.com/GNOME/gtk/blob/main/gtk/gtksettings.c#L320
52pub(crate) const DOUBLE_CLICK_INTERVAL: Duration = Duration::from_millis(400);
53pub(crate) const DOUBLE_CLICK_DISTANCE: Pixels = px(5.0);
54pub(crate) const KEYRING_LABEL: &str = "zed-github-account";
55
56pub trait LinuxClient {
57 fn compositor_name(&self) -> &'static str;
58 fn with_common<R>(&self, f: impl FnOnce(&mut LinuxCommon) -> R) -> R;
59 fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>>;
60 fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>>;
61 fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>>;
62
63 fn open_window(
64 &self,
65 handle: AnyWindowHandle,
66 options: WindowParams,
67 ) -> anyhow::Result<Box<dyn PlatformWindow>>;
68 fn set_cursor_style(&self, style: CursorStyle);
69 fn open_uri(&self, uri: &str);
70 fn write_to_primary(&self, item: ClipboardItem);
71 fn write_to_clipboard(&self, item: ClipboardItem);
72 fn read_from_primary(&self) -> Option<ClipboardItem>;
73 fn read_from_clipboard(&self) -> Option<ClipboardItem>;
74 fn active_window(&self) -> Option<AnyWindowHandle>;
75 fn run(&self);
76}
77
78#[derive(Default)]
79pub(crate) struct PlatformHandlers {
80 pub(crate) open_urls: Option<Box<dyn FnMut(Vec<String>)>>,
81 pub(crate) quit: Option<Box<dyn FnMut()>>,
82 pub(crate) reopen: Option<Box<dyn FnMut()>>,
83 pub(crate) app_menu_action: Option<Box<dyn FnMut(&dyn Action)>>,
84 pub(crate) will_open_app_menu: Option<Box<dyn FnMut()>>,
85 pub(crate) validate_app_menu_command: Option<Box<dyn FnMut(&dyn Action) -> bool>>,
86}
87
88pub trait QuitSignal {
89 fn quit(&mut self);
90}
91
92impl QuitSignal for LoopSignal {
93 fn quit(&mut self) {
94 self.stop();
95 }
96}
97
98pub(crate) struct LinuxCommon {
99 pub(crate) background_executor: BackgroundExecutor,
100 pub(crate) foreground_executor: ForegroundExecutor,
101 pub(crate) text_system: Arc<CosmicTextSystem>,
102 pub(crate) appearance: WindowAppearance,
103 pub(crate) auto_hide_scrollbars: bool,
104 pub(crate) callbacks: PlatformHandlers,
105 pub(crate) quit_signal: Box<dyn QuitSignal>,
106 pub(crate) menus: Vec<OwnedMenu>,
107}
108
109impl LinuxCommon {
110 pub fn new(
111 quit_signal: Box<dyn QuitSignal>,
112 main_waker: Option<Arc<Waker>>,
113 ) -> (Self, Channel<Runnable>) {
114 let (main_sender, main_receiver) = calloop::channel::channel::<Runnable>();
115 let text_system = Arc::new(CosmicTextSystem::new());
116 let callbacks = PlatformHandlers::default();
117
118 let dispatcher = Arc::new(LinuxDispatcher::new(main_sender.clone(), main_waker));
119
120 let background_executor = BackgroundExecutor::new(dispatcher.clone());
121
122 let common = LinuxCommon {
123 background_executor,
124 foreground_executor: ForegroundExecutor::new(dispatcher.clone()),
125 text_system,
126 appearance: WindowAppearance::Light,
127 auto_hide_scrollbars: false,
128 callbacks,
129 quit_signal,
130 menus: Vec::new(),
131 };
132
133 (common, main_receiver)
134 }
135}
136
137impl<P: LinuxClient + 'static> Platform for P {
138 fn background_executor(&self) -> BackgroundExecutor {
139 self.with_common(|common| common.background_executor.clone())
140 }
141
142 fn foreground_executor(&self) -> ForegroundExecutor {
143 self.with_common(|common| common.foreground_executor.clone())
144 }
145
146 fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
147 self.with_common(|common| common.text_system.clone())
148 }
149
150 fn run(&self, on_finish_launching: Box<dyn FnOnce()>) {
151 on_finish_launching();
152
153 LinuxClient::run(self);
154
155 self.with_common(|common| {
156 if let Some(mut fun) = common.callbacks.quit.take() {
157 fun();
158 }
159 });
160 }
161
162 fn quit(&self) {
163 self.with_common(|common| common.quit_signal.quit());
164 }
165
166 fn compositor_name(&self) -> &'static str {
167 self.compositor_name()
168 }
169
170 fn restart(&self, binary_path: Option<PathBuf>) {
171 use std::os::unix::process::CommandExt as _;
172
173 // get the process id of the current process
174 let app_pid = std::process::id().to_string();
175 // get the path to the executable
176 let app_path = if let Some(path) = binary_path {
177 path
178 } else {
179 match self.app_path() {
180 Ok(path) => path,
181 Err(err) => {
182 log::error!("Failed to get app path: {:?}", err);
183 return;
184 }
185 }
186 };
187
188 log::info!("Restarting process, using app path: {:?}", app_path);
189
190 // Script to wait for the current process to exit and then restart the app.
191 // We also wait for possibly open TCP sockets by the process to be closed,
192 // since on Linux it's not guaranteed that a process' resources have been
193 // cleaned up when `kill -0` returns.
194 let script = format!(
195 r#"
196 while kill -O {pid} 2>/dev/null; do
197 sleep 0.1
198 done
199
200 while lsof -nP -iTCP -a -p {pid} 2>/dev/null; do
201 sleep 0.1
202 done
203
204 {app_path}
205 "#,
206 pid = app_pid,
207 app_path = app_path.display()
208 );
209
210 // execute the script using /bin/bash
211 let restart_process = Command::new("/bin/bash")
212 .arg("-c")
213 .arg(script)
214 .process_group(0)
215 .spawn();
216
217 match restart_process {
218 Ok(_) => self.quit(),
219 Err(e) => log::error!("failed to spawn restart script: {:?}", e),
220 }
221 }
222
223 fn activate(&self, ignoring_other_apps: bool) {
224 log::info!("activate is not implemented on Linux, ignoring the call")
225 }
226
227 fn hide(&self) {
228 log::info!("hide is not implemented on Linux, ignoring the call")
229 }
230
231 fn hide_other_apps(&self) {
232 log::info!("hide_other_apps is not implemented on Linux, ignoring the call")
233 }
234
235 fn unhide_other_apps(&self) {
236 log::info!("unhide_other_apps is not implemented on Linux, ignoring the call")
237 }
238
239 fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
240 self.primary_display()
241 }
242
243 fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
244 self.displays()
245 }
246
247 fn active_window(&self) -> Option<AnyWindowHandle> {
248 self.active_window()
249 }
250
251 fn open_window(
252 &self,
253 handle: AnyWindowHandle,
254 options: WindowParams,
255 ) -> anyhow::Result<Box<dyn PlatformWindow>> {
256 self.open_window(handle, options)
257 }
258
259 fn open_url(&self, url: &str) {
260 self.open_uri(url);
261 }
262
263 fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
264 self.with_common(|common| common.callbacks.open_urls = Some(callback));
265 }
266
267 fn prompt_for_paths(
268 &self,
269 options: PathPromptOptions,
270 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
271 let (done_tx, done_rx) = oneshot::channel();
272 self.foreground_executor()
273 .spawn(async move {
274 let title = if options.multiple {
275 if !options.files {
276 "Open folders"
277 } else {
278 "Open files"
279 }
280 } else {
281 if !options.files {
282 "Open folder"
283 } else {
284 "Open file"
285 }
286 };
287
288 let result = OpenFileRequest::default()
289 .modal(true)
290 .title(title)
291 .accept_label("Select")
292 .multiple(options.multiple)
293 .directory(options.directories)
294 .send()
295 .await
296 .ok()
297 .and_then(|request| request.response().ok())
298 .and_then(|response| {
299 response
300 .uris()
301 .iter()
302 .map(|uri| uri.to_file_path().ok())
303 .collect()
304 });
305
306 done_tx.send(result);
307 })
308 .detach();
309 done_rx
310 }
311
312 fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
313 let (done_tx, done_rx) = oneshot::channel();
314 let directory = directory.to_owned();
315 self.foreground_executor()
316 .spawn(async move {
317 let request = SaveFileRequest::default()
318 .modal(true)
319 .title("Select new path")
320 .accept_label("Accept")
321 .current_folder(directory);
322
323 let result = if let Ok(request) = request {
324 request
325 .send()
326 .await
327 .ok()
328 .and_then(|request| request.response().ok())
329 .and_then(|response| {
330 response
331 .uris()
332 .first()
333 .and_then(|uri| uri.to_file_path().ok())
334 })
335 } else {
336 None
337 };
338
339 done_tx.send(result);
340 })
341 .detach();
342
343 done_rx
344 }
345
346 fn reveal_path(&self, path: &Path) {
347 if path.is_dir() {
348 open::that_detached(path);
349 return;
350 }
351 // If `path` is a file, the system may try to open it in a text editor
352 let dir = path.parent().unwrap_or(Path::new(""));
353 open::that_detached(dir);
354 }
355
356 fn on_quit(&self, callback: Box<dyn FnMut()>) {
357 self.with_common(|common| {
358 common.callbacks.quit = Some(callback);
359 });
360 }
361
362 fn on_reopen(&self, callback: Box<dyn FnMut()>) {
363 self.with_common(|common| {
364 common.callbacks.reopen = Some(callback);
365 });
366 }
367
368 fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
369 self.with_common(|common| {
370 common.callbacks.app_menu_action = Some(callback);
371 });
372 }
373
374 fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
375 self.with_common(|common| {
376 common.callbacks.will_open_app_menu = Some(callback);
377 });
378 }
379
380 fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
381 self.with_common(|common| {
382 common.callbacks.validate_app_menu_command = Some(callback);
383 });
384 }
385
386 fn app_path(&self) -> Result<PathBuf> {
387 // get the path of the executable of the current process
388 let exe_path = std::env::current_exe()?;
389 Ok(exe_path)
390 }
391
392 fn set_menus(&self, menus: Vec<Menu>, _keymap: &Keymap) {
393 self.with_common(|common| {
394 common.menus = menus.into_iter().map(|menu| menu.owned()).collect();
395 })
396 }
397
398 fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
399 self.with_common(|common| Some(common.menus.clone()))
400 }
401
402 fn set_dock_menu(&self, menu: Vec<MenuItem>, keymap: &Keymap) {}
403
404 fn local_timezone(&self) -> UtcOffset {
405 UtcOffset::UTC
406 }
407
408 fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
409 Err(anyhow::Error::msg(
410 "Platform<LinuxPlatform>::path_for_auxiliary_executable is not implemented yet",
411 ))
412 }
413
414 fn set_cursor_style(&self, style: CursorStyle) {
415 self.set_cursor_style(style)
416 }
417
418 fn should_auto_hide_scrollbars(&self) -> bool {
419 self.with_common(|common| common.auto_hide_scrollbars)
420 }
421
422 fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
423 let url = url.to_string();
424 let username = username.to_string();
425 let password = password.to_vec();
426 self.background_executor().spawn(async move {
427 let keyring = oo7::Keyring::new().await?;
428 keyring.unlock().await?;
429 keyring
430 .create_item(
431 KEYRING_LABEL,
432 &vec![("url", &url), ("username", &username)],
433 password,
434 true,
435 )
436 .await?;
437 Ok(())
438 })
439 }
440
441 fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
442 let url = url.to_string();
443 self.background_executor().spawn(async move {
444 let keyring = oo7::Keyring::new().await?;
445 keyring.unlock().await?;
446
447 let items = keyring.search_items(&vec![("url", &url)]).await?;
448
449 for item in items.into_iter() {
450 if item.label().await.is_ok_and(|label| label == KEYRING_LABEL) {
451 let attributes = item.attributes().await?;
452 let username = attributes
453 .get("username")
454 .ok_or_else(|| anyhow!("Cannot find username in stored credentials"))?;
455 let secret = item.secret().await?;
456
457 // we lose the zeroizing capabilities at this boundary,
458 // a current limitation GPUI's credentials api
459 return Ok(Some((username.to_string(), secret.to_vec())));
460 } else {
461 continue;
462 }
463 }
464 Ok(None)
465 })
466 }
467
468 fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
469 let url = url.to_string();
470 self.background_executor().spawn(async move {
471 let keyring = oo7::Keyring::new().await?;
472 keyring.unlock().await?;
473
474 let items = keyring.search_items(&vec![("url", &url)]).await?;
475
476 for item in items.into_iter() {
477 if item.label().await.is_ok_and(|label| label == KEYRING_LABEL) {
478 item.delete().await?;
479 return Ok(());
480 }
481 }
482
483 Ok(())
484 })
485 }
486
487 fn window_appearance(&self) -> WindowAppearance {
488 self.with_common(|common| common.appearance)
489 }
490
491 fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> {
492 Task::ready(Err(anyhow!("register_url_scheme unimplemented")))
493 }
494
495 fn write_to_primary(&self, item: ClipboardItem) {
496 self.write_to_primary(item)
497 }
498
499 fn write_to_clipboard(&self, item: ClipboardItem) {
500 self.write_to_clipboard(item)
501 }
502
503 fn read_from_primary(&self) -> Option<ClipboardItem> {
504 self.read_from_primary()
505 }
506
507 fn read_from_clipboard(&self) -> Option<ClipboardItem> {
508 self.read_from_clipboard()
509 }
510
511 fn add_recent_document(&self, _path: &Path) {}
512}
513
514pub(super) fn open_uri_internal(uri: &str, activation_token: Option<&str>) {
515 let mut last_err = None;
516 for mut command in open::commands(uri) {
517 if let Some(token) = activation_token {
518 command.env("XDG_ACTIVATION_TOKEN", token);
519 }
520 match command.spawn() {
521 Ok(_) => return,
522 Err(err) => last_err = Some(err),
523 }
524 }
525 log::error!("failed to open uri: {uri:?}, last error: {last_err:?}");
526}
527
528pub(super) fn is_within_click_distance(a: Point<Pixels>, b: Point<Pixels>) -> bool {
529 let diff = a - b;
530 diff.x.abs() <= DOUBLE_CLICK_DISTANCE && diff.y.abs() <= DOUBLE_CLICK_DISTANCE
531}
532
533pub(super) fn get_xkb_compose_state(cx: &xkb::Context) -> Option<xkb::compose::State> {
534 let mut locales = Vec::default();
535 if let Some(locale) = std::env::var_os("LC_CTYPE") {
536 locales.push(locale);
537 }
538 locales.push(OsString::from("C"));
539 let mut state: Option<xkb::compose::State> = None;
540 for locale in locales {
541 if let Ok(table) =
542 xkb::compose::Table::new_from_locale(&cx, &locale, xkb::compose::COMPILE_NO_FLAGS)
543 {
544 state = Some(xkb::compose::State::new(
545 &table,
546 xkb::compose::STATE_NO_FLAGS,
547 ));
548 break;
549 }
550 }
551 state
552}
553
554pub(super) unsafe fn read_fd(mut fd: FileDescriptor) -> Result<String> {
555 let mut file = File::from_raw_fd(fd.as_raw_fd());
556
557 let mut buffer = String::new();
558 file.read_to_string(&mut buffer)?;
559
560 // Normalize the text to unix line endings, otherwise
561 // copying from eg: firefox inserts a lot of blank
562 // lines, and that is super annoying.
563 let result = buffer.replace("\r\n", "\n");
564 Ok(result)
565}
566
567impl CursorStyle {
568 pub(super) fn to_shape(&self) -> Shape {
569 match self {
570 CursorStyle::Arrow => Shape::Default,
571 CursorStyle::IBeam => Shape::Text,
572 CursorStyle::Crosshair => Shape::Crosshair,
573 CursorStyle::ClosedHand => Shape::Grabbing,
574 CursorStyle::OpenHand => Shape::Grab,
575 CursorStyle::PointingHand => Shape::Pointer,
576 CursorStyle::ResizeLeft => Shape::WResize,
577 CursorStyle::ResizeRight => Shape::EResize,
578 CursorStyle::ResizeLeftRight => Shape::EwResize,
579 CursorStyle::ResizeUp => Shape::NResize,
580 CursorStyle::ResizeDown => Shape::SResize,
581 CursorStyle::ResizeUpDown => Shape::NsResize,
582 CursorStyle::ResizeUpLeftDownRight => Shape::NwseResize,
583 CursorStyle::ResizeUpRightDownLeft => Shape::NeswResize,
584 CursorStyle::ResizeColumn => Shape::ColResize,
585 CursorStyle::ResizeRow => Shape::RowResize,
586 CursorStyle::IBeamCursorForVerticalLayout => Shape::VerticalText,
587 CursorStyle::OperationNotAllowed => Shape::NotAllowed,
588 CursorStyle::DragLink => Shape::Alias,
589 CursorStyle::DragCopy => Shape::Copy,
590 CursorStyle::ContextualMenu => Shape::ContextMenu,
591 }
592 }
593
594 pub(super) fn to_icon_name(&self) -> String {
595 // Based on cursor names from https://gitlab.gnome.org/GNOME/adwaita-icon-theme (GNOME)
596 // and https://github.com/KDE/breeze (KDE). Both of them seem to be also derived from
597 // Web CSS cursor names: https://developer.mozilla.org/en-US/docs/Web/CSS/cursor#values
598 match self {
599 CursorStyle::Arrow => "arrow",
600 CursorStyle::IBeam => "text",
601 CursorStyle::Crosshair => "crosshair",
602 CursorStyle::ClosedHand => "grabbing",
603 CursorStyle::OpenHand => "grab",
604 CursorStyle::PointingHand => "pointer",
605 CursorStyle::ResizeLeft => "w-resize",
606 CursorStyle::ResizeRight => "e-resize",
607 CursorStyle::ResizeLeftRight => "ew-resize",
608 CursorStyle::ResizeUp => "n-resize",
609 CursorStyle::ResizeDown => "s-resize",
610 CursorStyle::ResizeUpDown => "ns-resize",
611 CursorStyle::ResizeUpLeftDownRight => "nwse-resize",
612 CursorStyle::ResizeUpRightDownLeft => "nesw-resize",
613 CursorStyle::ResizeColumn => "col-resize",
614 CursorStyle::ResizeRow => "row-resize",
615 CursorStyle::IBeamCursorForVerticalLayout => "vertical-text",
616 CursorStyle::OperationNotAllowed => "not-allowed",
617 CursorStyle::DragLink => "alias",
618 CursorStyle::DragCopy => "copy",
619 CursorStyle::ContextualMenu => "context-menu",
620 }
621 .to_string()
622 }
623}
624
625impl Keystroke {
626 pub(super) fn from_xkb(state: &State, modifiers: Modifiers, keycode: Keycode) -> Self {
627 let mut modifiers = modifiers;
628
629 let key_utf32 = state.key_get_utf32(keycode);
630 let key_utf8 = state.key_get_utf8(keycode);
631 let key_sym = state.key_get_one_sym(keycode);
632
633 let key = match key_sym {
634 Keysym::Return => "enter".to_owned(),
635 Keysym::Prior => "pageup".to_owned(),
636 Keysym::Next => "pagedown".to_owned(),
637 Keysym::ISO_Left_Tab => "tab".to_owned(),
638
639 Keysym::comma => ",".to_owned(),
640 Keysym::period => ".".to_owned(),
641 Keysym::less => "<".to_owned(),
642 Keysym::greater => ">".to_owned(),
643 Keysym::slash => "/".to_owned(),
644 Keysym::question => "?".to_owned(),
645
646 Keysym::semicolon => ";".to_owned(),
647 Keysym::colon => ":".to_owned(),
648 Keysym::apostrophe => "'".to_owned(),
649 Keysym::quotedbl => "\"".to_owned(),
650
651 Keysym::bracketleft => "[".to_owned(),
652 Keysym::braceleft => "{".to_owned(),
653 Keysym::bracketright => "]".to_owned(),
654 Keysym::braceright => "}".to_owned(),
655 Keysym::backslash => "\\".to_owned(),
656 Keysym::bar => "|".to_owned(),
657
658 Keysym::grave => "`".to_owned(),
659 Keysym::asciitilde => "~".to_owned(),
660 Keysym::exclam => "!".to_owned(),
661 Keysym::at => "@".to_owned(),
662 Keysym::numbersign => "#".to_owned(),
663 Keysym::dollar => "$".to_owned(),
664 Keysym::percent => "%".to_owned(),
665 Keysym::asciicircum => "^".to_owned(),
666 Keysym::ampersand => "&".to_owned(),
667 Keysym::asterisk => "*".to_owned(),
668 Keysym::parenleft => "(".to_owned(),
669 Keysym::parenright => ")".to_owned(),
670 Keysym::minus => "-".to_owned(),
671 Keysym::underscore => "_".to_owned(),
672 Keysym::equal => "=".to_owned(),
673 Keysym::plus => "+".to_owned(),
674
675 _ => xkb::keysym_get_name(key_sym).to_lowercase(),
676 };
677
678 if modifiers.shift {
679 // we only include the shift for upper-case letters by convention,
680 // so don't include for numbers and symbols, but do include for
681 // tab/enter, etc.
682 if key.chars().count() == 1 && key_utf8 == key {
683 modifiers.shift = false;
684 }
685 }
686
687 // Ignore control characters (and DEL) for the purposes of ime_key
688 let ime_key =
689 (key_utf32 >= 32 && key_utf32 != 127 && !key_utf8.is_empty()).then_some(key_utf8);
690
691 Keystroke {
692 modifiers,
693 key,
694 ime_key,
695 }
696 }
697
698 /**
699 * Returns which symbol the dead key represents
700 * https://developer.mozilla.org/en-US/docs/Web/API/UI_Events/Keyboard_event_key_values#dead_keycodes_for_linux
701 */
702 pub fn underlying_dead_key(keysym: Keysym) -> Option<String> {
703 match keysym {
704 Keysym::dead_grave => Some("`".to_owned()),
705 Keysym::dead_acute => Some("´".to_owned()),
706 Keysym::dead_circumflex => Some("^".to_owned()),
707 Keysym::dead_tilde => Some("~".to_owned()),
708 Keysym::dead_perispomeni => Some("͂".to_owned()),
709 Keysym::dead_macron => Some("¯".to_owned()),
710 Keysym::dead_breve => Some("˘".to_owned()),
711 Keysym::dead_abovedot => Some("˙".to_owned()),
712 Keysym::dead_diaeresis => Some("¨".to_owned()),
713 Keysym::dead_abovering => Some("˚".to_owned()),
714 Keysym::dead_doubleacute => Some("˝".to_owned()),
715 Keysym::dead_caron => Some("ˇ".to_owned()),
716 Keysym::dead_cedilla => Some("¸".to_owned()),
717 Keysym::dead_ogonek => Some("˛".to_owned()),
718 Keysym::dead_iota => Some("ͅ".to_owned()),
719 Keysym::dead_voiced_sound => Some("゙".to_owned()),
720 Keysym::dead_semivoiced_sound => Some("゚".to_owned()),
721 Keysym::dead_belowdot => Some("̣̣".to_owned()),
722 Keysym::dead_hook => Some("̡".to_owned()),
723 Keysym::dead_horn => Some("̛".to_owned()),
724 Keysym::dead_stroke => Some("̶̶".to_owned()),
725 Keysym::dead_abovecomma => Some("̓̓".to_owned()),
726 Keysym::dead_psili => Some("᾿".to_owned()),
727 Keysym::dead_abovereversedcomma => Some("ʽ".to_owned()),
728 Keysym::dead_dasia => Some("῾".to_owned()),
729 Keysym::dead_doublegrave => Some("̏".to_owned()),
730 Keysym::dead_belowring => Some("˳".to_owned()),
731 Keysym::dead_belowmacron => Some("̱".to_owned()),
732 Keysym::dead_belowcircumflex => Some("ꞈ".to_owned()),
733 Keysym::dead_belowtilde => Some("̰".to_owned()),
734 Keysym::dead_belowbreve => Some("̮".to_owned()),
735 Keysym::dead_belowdiaeresis => Some("̤".to_owned()),
736 Keysym::dead_invertedbreve => Some("̯".to_owned()),
737 Keysym::dead_belowcomma => Some("̦".to_owned()),
738 Keysym::dead_currency => None,
739 Keysym::dead_lowline => None,
740 Keysym::dead_aboveverticalline => None,
741 Keysym::dead_belowverticalline => None,
742 Keysym::dead_longsolidusoverlay => None,
743 Keysym::dead_a => None,
744 Keysym::dead_A => None,
745 Keysym::dead_e => None,
746 Keysym::dead_E => None,
747 Keysym::dead_i => None,
748 Keysym::dead_I => None,
749 Keysym::dead_o => None,
750 Keysym::dead_O => None,
751 Keysym::dead_u => None,
752 Keysym::dead_U => None,
753 Keysym::dead_small_schwa => Some("ə".to_owned()),
754 Keysym::dead_capital_schwa => Some("Ə".to_owned()),
755 Keysym::dead_greek => None,
756 _ => None,
757 }
758 }
759}
760
761impl Modifiers {
762 pub(super) fn from_xkb(keymap_state: &State) -> Self {
763 let shift = keymap_state.mod_name_is_active(xkb::MOD_NAME_SHIFT, xkb::STATE_MODS_EFFECTIVE);
764 let alt = keymap_state.mod_name_is_active(xkb::MOD_NAME_ALT, xkb::STATE_MODS_EFFECTIVE);
765 let control =
766 keymap_state.mod_name_is_active(xkb::MOD_NAME_CTRL, xkb::STATE_MODS_EFFECTIVE);
767 let platform =
768 keymap_state.mod_name_is_active(xkb::MOD_NAME_LOGO, xkb::STATE_MODS_EFFECTIVE);
769 Modifiers {
770 shift,
771 alt,
772 control,
773 platform,
774 function: false,
775 }
776 }
777}
778
779#[cfg(test)]
780mod tests {
781 use super::*;
782 use crate::{px, Point};
783
784 #[test]
785 fn test_is_within_click_distance() {
786 let zero = Point::new(px(0.0), px(0.0));
787 assert_eq!(
788 is_within_click_distance(zero, Point::new(px(5.0), px(5.0))),
789 true
790 );
791 assert_eq!(
792 is_within_click_distance(zero, Point::new(px(-4.9), px(5.0))),
793 true
794 );
795 assert_eq!(
796 is_within_click_distance(Point::new(px(3.0), px(2.0)), Point::new(px(-2.0), px(-2.0))),
797 true
798 );
799 assert_eq!(
800 is_within_click_distance(zero, Point::new(px(5.0), px(5.1))),
801 false
802 );
803 }
804}