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