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