Repository navigation
Expand file tree
/
Copy pathlinux_portal.rs
More file actions
1137 lines (1065 loc) · 42.2 KB
/
Copy pathlinux_portal.rs
File metadata and controls
1137 lines (1065 loc) · 42.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! The desktop's portals (`org.freedesktop.portal.*`) over a private bus
//! connection. `PortalBus` registers Hex with the portal and answers
//! requests; `Portal` is the GlobalShortcuts client and
//! `linux_remote_desktop` the RemoteDesktop one.
//!
//! `Portal` binds all of Hex's shortcuts in one session, once, and reports
//! their presses and releases. Desktops keep one shortcut set per app (KDE
//! replaces it with each BindShortcuts call), so Hex never binds a second
//! set or changes this one while running. Desktops also keep the trigger
//! they stored for an id over a later `preferred_trigger` (GNOME, KDE), so
//! `linux_input` names each shortcut by the trigger it asks for. Dropping a bus closes its
//! sessions, and the desktop releases the keys. Each bus runs on its own one-thread tokio runtime, so
//! the portal's signals queue while the caller sleeps.
use std::collections::{HashMap, VecDeque};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{Receiver, RecvTimeoutError, channel};
use std::time::{Duration, Instant};
use color_eyre::eyre::{Result, WrapErr, eyre};
use futures_util::StreamExt;
use zbus::{
Connection, DBusError, MatchRule, MessageStream, OwnedObjectPath, OwnedVariant, Variant,
message,
};
const DESKTOP: &str = "org.freedesktop.portal.Desktop";
const DESKTOP_PATH: &str = "/org/freedesktop/portal/desktop";
const SHORTCUTS: &str = "org.freedesktop.portal.GlobalShortcuts";
const REQUEST: &str = "org.freedesktop.portal.Request";
const SESSION: &str = "org.freedesktop.portal.Session";
/// Hex's Linux app id: the portal names host apps by their desktop entry,
/// `anomaly.hex.desktop`, and Hex's windows report it as their Wayland
/// app_id and X11 WM_CLASS. GNOME's shortcuts provider before 51 rejects ids
/// that are not reverse-DNS (#579), so this matches the macOS bundle
/// identifier.
pub(crate) const APP_ID: &str = "anomaly.hex";
/// The app id and entry name before #579.
const LEGACY_APP_ID: &str = "hex";
const LEGACY_ENTRY: &str = "hex.desktop";
const MANAGED_MARK: &str = "X-Hex-Managed=true";
const CALL_TIMEOUT: Duration = Duration::from_secs(5);
/// A request can wait for the user to approve a desktop dialog.
const RESPONSE_TIMEOUT: Duration = Duration::from_secs(60);
/// How often a pending request checks for cancellation.
const STOP_POLL: Duration = Duration::from_millis(50);
/// Cancel dictation, which the user assigns in the desktop. Not `cancel`:
/// KDE still holds Escape under that id from builds that bound it.
pub(crate) const CANCEL_ID: &str = "cancel-dictation";
/// Cancel dictation's id before #492, when Hex suggested Escape for it.
const LEGACY_CANCEL_ID: &str = "cancel";
/// What Cancel dictation is called in the shortcuts the portal granted.
pub(crate) const CANCEL_DESCRIPTION: &str = "Cancel dictation";
/// KDE's global shortcuts service, which keeps what portal apps bound.
const KGLOBALACCEL: &str = "org.kde.kglobalaccel";
const KGLOBALACCEL_PATH: &str = "/kglobalaccel";
const KGLOBALACCEL_INTERFACE: &str = "org.kde.KGlobalAccel";
/// One shortcut Hex asks the desktop for.
pub(crate) struct Shortcut {
pub(crate) id: String,
pub(crate) description: &'static str,
/// XDG shortcuts format, such as `CTRL+ALT+space`; `None` leaves the
/// shortcut for the user to assign.
pub(crate) trigger: Option<String>,
}
impl Shortcut {
/// Cancel dictation, with no suggested key: a portal shortcut is held
/// for as long as Hex runs, so suggesting Escape would take it from
/// every other application.
pub(crate) fn cancel() -> Self {
Self {
id: CANCEL_ID.into(),
description: CANCEL_DESCRIPTION,
trigger: None,
}
}
}
#[derive(Debug, PartialEq)]
pub(crate) enum Event {
Pressed(String),
Released(String),
/// The user changed Hex's shortcuts in the desktop: the trigger each
/// one now has, by id, or `None` when it has none.
Changed(HashMap<String, Option<String>>),
/// The desktop closed the session.
Closed,
}
pub(crate) type Results = HashMap<String, OwnedVariant>;
/// A portal signal, by the session or request path it names.
enum Signal {
Session(String, Event),
Response(String, u32, Results),
}
fn parse(message: &zbus::Message) -> Option<Signal> {
let header = message.header();
let path = header.path()?.to_string();
let body = message.body();
match (header.interface()?.as_str(), header.member()?.as_str()) {
(SHORTCUTS, member @ ("Activated" | "Deactivated")) => {
let (session, id, _, _): (OwnedObjectPath, String, u64, Results) =
body.deserialize().ok()?;
let event = if member == "Activated" {
Event::Pressed(id)
} else {
Event::Released(id)
};
Some(Signal::Session(session.to_string(), event))
}
(SHORTCUTS, "ShortcutsChanged") => {
let (session, shortcuts): (OwnedObjectPath, Vec<(String, Results)>) =
body.deserialize().ok()?;
Some(Signal::Session(
session.to_string(),
Event::Changed(triggers(shortcuts)),
))
}
(SESSION, "Closed") => Some(Signal::Session(path, Event::Closed)),
(REQUEST, "Response") => {
let (code, results): (u32, Results) = body.deserialize().ok()?;
Some(Signal::Response(path, code, results))
}
_ => None,
}
}
/// Each shortcut's trigger description. An empty one (KDE's for a shortcut
/// it keeps unbound) means no trigger.
fn triggers(shortcuts: Vec<(String, Results)>) -> HashMap<String, Option<String>> {
shortcuts
.into_iter()
.map(|(id, options)| {
let trigger = options
.get("trigger_description")
.and_then(|trigger| <&str>::try_from(trigger).ok())
.map(str::trim)
.filter(|trigger| !trigger.is_empty())
.map(str::to_owned);
(id, trigger)
})
.collect()
}
/// An unknown method or interface: an older portal without that call.
fn unknown(error: &zbus::Error) -> bool {
let name = match error {
zbus::Error::MethodError(name, _, _) => name.to_string(),
zbus::Error::FDO(error) => error.name().to_string(),
_ => return false,
};
name.starts_with("org.freedesktop.DBus.Error.Unknown")
}
/// A private session-bus connection registered with the portal as Hex.
pub(crate) struct PortalBus {
runtime: tokio::runtime::Runtime,
connection: Connection,
signals: Receiver<Signal>,
/// Session signals that arrived while a request waited.
pending: VecDeque<(String, Event)>,
/// This connection's unique name as request paths spell it.
sender: String,
next_token: u32,
/// The portal interface this bus serves and its version.
interface: &'static str,
pub(crate) version: u32,
}
impl PortalBus {
/// `None` when the session has no portal offering `interface`.
pub(crate) fn open(interface: &'static str, stop: &AtomicBool) -> Result<Option<Self>> {
let runtime = tokio::runtime::Builder::new_multi_thread()
.worker_threads(1)
.thread_name("hex-portal")
.enable_all()
.build()
.wrap_err("could not start the portal runtime")?;
let (signals, received) = channel();
let connected = runtime.block_on(async {
let connection = tokio::time::timeout(CALL_TIMEOUT, Connection::session())
.await
.ok()?
.ok()?;
// Subscribed before any request so a fast answer cannot be missed.
let rule = MatchRule::builder()
.msg_type(message::Type::Signal)
.path_namespace(DESKTOP_PATH)
.build()
.ok()?;
let mut stream = MessageStream::for_match_rule(rule, &connection, None)
.await
.ok()?;
tokio::spawn(async move {
while let Some(Ok(message)) = stream.next().await {
if let Some(signal) = parse(&message)
&& signals.send(signal).is_err()
{
break;
}
}
});
Some(connection)
});
let Some(connection) = connected else {
return Ok(None);
};
let Some(sender) = connection
.unique_name()
.map(|name| name.trim_start_matches(':').replace('.', "_"))
else {
return Ok(None);
};
let mut bus = Self {
runtime,
connection,
signals: received,
pending: VecDeque::new(),
sender,
next_token: 0,
interface,
version: 0,
};
match bus.call::<_, OwnedVariant>(
DESKTOP_PATH,
"org.freedesktop.DBus.Properties",
"Get",
&(interface, "version"),
) {
Ok(version) => bus.version = u32::try_from(&version).unwrap_or(1),
Err(error) => {
tracing::info!(%error, interface, "the desktop has no such portal");
return Ok(None);
}
}
let written = ensure_desktop_entry()?;
// Host apps have no sandbox identity; older portals without the
// registry derive one from the systemd unit instead.
if let Err(error) = bus.call::<_, ()>(
DESKTOP_PATH,
"org.freedesktop.host.portal.Registry",
"Register",
&(APP_ID, HashMap::<&str, Variant<'_>>::new()),
) && !unknown(&error)
{
// The portal finds the app id through anomaly.hex.desktop and the caller's
// /proc entry, which setgid wrappers such as newgrp make unreadable.
let fix = match written {
Some(entry) => format!(
"Hex wrote {}; restart xdg-desktop-portal (systemctl --user restart xdg-desktop-portal) so it reads it",
entry.display()
),
None => "run Hex without setuid or setgid wrappers such as newgrp".into(),
};
return Err(eyre!(
"the desktop portal could not identify Hex ({error}); {fix}"
));
}
if stop.load(Ordering::Acquire) {
return Err(eyre!("portal registration canceled"));
}
Ok(Some(bus))
}
pub(crate) fn call<B, R>(
&self,
path: &str,
interface: &str,
method: &str,
body: &B,
) -> zbus::Result<R>
where
B: serde::Serialize + zbus::Type,
R: for<'d> serde::Deserialize<'d> + zbus::Type,
{
self.call_service(DESKTOP, path, interface, method, body)
}
/// Calls a method of another service on this bus.
fn call_service<B, R>(
&self,
destination: &str,
path: &str,
interface: &str,
method: &str,
body: &B,
) -> zbus::Result<R>
where
B: serde::Serialize + zbus::Type,
R: for<'d> serde::Deserialize<'d> + zbus::Type,
{
self.runtime.block_on(async {
let reply = tokio::time::timeout(
CALL_TIMEOUT,
self.connection
.call_method(Some(destination), path, Some(interface), method, body),
)
.await
.map_err(|_| zbus::Error::Failure(format!("{method} timed out")))??;
reply.body().deserialize()
})
}
/// Calls a method of this bus's interface on the portal object.
pub(crate) fn call_portal<B>(&self, method: &str, body: &B) -> Result<()>
where
B: serde::Serialize + zbus::Type,
{
self.call::<_, ()>(DESKTOP_PATH, self.interface, method, body)
.wrap_err_with(|| format!("the {} portal refused {method}", self.interface))
}
pub(crate) fn token(&mut self) -> String {
self.next_token += 1;
format!("hex{}_{}", std::process::id(), self.next_token)
}
/// Calls a portal method that answers through a Request's Response signal.
pub(crate) fn request<B>(
&mut self,
method: &str,
body: impl FnOnce(&str) -> B,
stop: &AtomicBool,
) -> Result<Results>
where
B: serde::Serialize + zbus::Type,
{
let token = self.token();
let path = format!("{DESKTOP_PATH}/request/{}/{token}", self.sender);
let interface = self.interface;
self.call::<_, OwnedObjectPath>(DESKTOP_PATH, interface, method, &body(&token))
.wrap_err_with(|| format!("the {interface} portal refused {method}"))?;
let deadline = Instant::now() + RESPONSE_TIMEOUT;
loop {
match self.signals.recv_timeout(STOP_POLL) {
Ok(Signal::Response(answered, code, results)) if answered == path => {
return match code {
0 => Ok(results),
1 => Err(eyre!("the {interface} request {method} was dismissed")),
_ => Err(eyre!("the {interface} portal could not complete {method}")),
};
}
Ok(Signal::Session(session, event)) => self.pending.push_back((session, event)),
Ok(Signal::Response(..)) | Err(RecvTimeoutError::Timeout) => {}
Err(RecvTimeoutError::Disconnected) => {
return Err(eyre!("the portal connection closed"));
}
}
if stop.load(Ordering::Acquire) {
return Err(eyre!("the {interface} request {method} was canceled"));
}
if Instant::now() >= deadline {
return Err(eyre!("the {interface} portal did not answer {method}"));
}
}
}
pub(crate) fn create_session(&mut self, stop: &AtomicBool) -> Result<OwnedObjectPath> {
let session_token = self.token();
let results = self.request(
"CreateSession",
|token| {
(HashMap::from([
("handle_token", Variant::from(token.to_owned())),
("session_handle_token", Variant::from(session_token.clone())),
]),)
},
stop,
)?;
// Portals send the handle as a string, as the spec says, or as an object path.
results
.get("session_handle")
.and_then(|handle| match <&str>::try_from(handle) {
Ok(handle) => OwnedObjectPath::try_from(handle.to_owned()).ok(),
Err(_) => handle
.try_clone()
.ok()
.and_then(|handle| OwnedObjectPath::try_from(handle).ok()),
})
.ok_or_else(|| eyre!("the {} portal returned no session", self.interface))
}
pub(crate) fn close_session(&self, session: &str) {
if let Err(error) = self.call::<_, ()>(session, SESSION, "Close", &()) {
tracing::warn!(%error, "could not close a portal session");
}
}
/// The session signals that arrived since the last call.
pub(crate) fn events(&mut self) -> Vec<(String, Event)> {
let mut queued = std::mem::take(&mut self.pending);
queued.extend(self.signals.try_iter().filter_map(|signal| match signal {
Signal::Session(session, event) => Some((session, event)),
Signal::Response(..) => None,
}));
queued.into()
}
}
impl Drop for PortalBus {
fn drop(&mut self) {
// The portal closes every session of a vanished connection.
let connection = self.connection.clone();
let _ = self
.runtime
.block_on(async { tokio::time::timeout(CALL_TIMEOUT, connection.close()).await });
}
}
/// Tidies Hex's launcher entry at startup: see [`DesktopEntries::tidy`].
pub(crate) fn tidy_desktop_entries() -> Result<()> {
if let Some(entries) = DesktopEntries::current() {
entries.tidy()?;
}
Ok(())
}
/// The portal identifies a host app by a desktop entry named for its id,
/// `anomaly.hex.desktop`, which installs ship: see [`DesktopEntries::ensure`].
fn ensure_desktop_entry() -> Result<Option<PathBuf>> {
match DesktopEntries::current() {
Some(entries) => {
let executable = std::env::current_exe().wrap_err("could not find Hex's executable")?;
let executable = executable
.to_str()
.ok_or_else(|| eyre!("Hex's executable path is not UTF-8"))?;
entries.ensure(executable)
}
None => Ok(None),
}
}
/// The system data directories from `XDG_DATA_DIRS`, which packages own.
pub(crate) fn system_data_dirs() -> Vec<PathBuf> {
std::env::var("XDG_DATA_DIRS")
.ok()
.filter(|dirs| !dirs.is_empty())
.unwrap_or_else(|| "/usr/local/share:/usr/share".into())
.split(':')
.filter(|dir| !dir.is_empty())
.map(PathBuf::from)
.collect()
}
/// Hex's launcher entry: the user's `applications` directory, which Hex may
/// write, and the system ones from `XDG_DATA_DIRS`, which packages own.
struct DesktopEntries {
applications: PathBuf,
system: Vec<PathBuf>,
}
/// A desktop entry on disk. Hex reads and replaces only regular files.
enum Entry {
Missing,
File(String),
/// A symlink or anything else the user put there.
Other,
}
impl DesktopEntries {
fn current() -> Option<Self> {
let applications = dirs::data_dir()?.join("applications");
let system = system_data_dirs()
.into_iter()
.map(|dir| dir.join("applications"))
.collect();
Some(Self::new(applications, system))
}
/// Leaves the user's own directory out of the system ones, as some
/// profiles list it in `XDG_DATA_DIRS` too.
fn new(applications: PathBuf, system: Vec<PathBuf>) -> Self {
let canonical = |dir: &Path| std::fs::canonicalize(dir).unwrap_or_else(|_| dir.into());
let own = canonical(&applications);
let system = system
.into_iter()
.filter(|dir| canonical(dir) != own)
.collect();
Self {
applications,
system,
}
}
fn entry(&self) -> PathBuf {
self.applications.join(format!("{APP_ID}.desktop"))
}
fn shipped(&self, name: &str) -> bool {
self.system.iter().any(|dir| dir.join(name).exists())
}
/// Moves Hex's own managed `hex.desktop` (the name before #579) to
/// `anomaly.hex.desktop`, keeping its Exec lines, unless the user put an
/// entry of their own there; then removes a hidden fallback that would
/// shadow a package's entry of the same id, or names Hex's icon in an
/// entry Hex wrote with the generic one (#652). Returns the entry it wrote.
fn tidy(&self) -> Result<Option<PathBuf>> {
let entry = self.entry();
let current = read_entry(&entry)?;
let legacy = self.applications.join(LEGACY_ENTRY);
if let Entry::File(old) = read_entry(&legacy)?
&& managed(&old)
{
let replace = match ¤t {
Entry::Missing => true,
Entry::File(current) => managed(current),
Entry::Other => false,
};
if replace {
write_entry(&self.applications, &entry, &moved_entry(&old))
.wrap_err_with(|| format!("could not write {}", entry.display()))?;
}
std::fs::remove_file(&legacy)
.wrap_err_with(|| format!("could not remove {}", legacy.display()))?;
tracing::info!(entry = %entry.display(), "moved Hex's desktop entry to its app id");
return Ok(replace.then_some(entry));
}
if let Entry::File(current) = ¤t
&& managed(current)
&& no_display(current)
&& self.shipped(&format!("{APP_ID}.desktop"))
{
std::fs::remove_file(&entry)
.wrap_err_with(|| format!("could not remove {}", entry.display()))?;
tracing::info!(entry = %entry.display(), "removed Hex's fallback desktop entry");
} else if let Entry::File(current) = ¤t
&& managed(current)
&& with_icon(current) != *current
{
write_entry(&self.applications, &entry, &with_icon(current))
.wrap_err_with(|| format!("could not write {}", entry.display()))?;
tracing::info!(entry = %entry.display(), "named Hex's icon in its desktop entry");
}
Ok(None)
}
/// After [`Self::tidy`], with no entry anywhere, writes a minimal one
/// that runs `executable`, marked managed so an install may replace it,
/// and hidden from launchers when an older package's or the user's own
/// `hex.desktop` already shows Hex. Returns the entry it wrote.
fn ensure(&self, executable: &str) -> Result<Option<PathBuf>> {
if let Some(moved) = self.tidy()? {
return Ok(Some(moved));
}
let entry = self.entry();
if !matches!(read_entry(&entry)?, Entry::Missing)
|| self.shipped(&format!("{APP_ID}.desktop"))
{
return Ok(None);
}
let hidden = self.shipped(LEGACY_ENTRY)
|| !matches!(
read_entry(&self.applications.join(LEGACY_ENTRY))?,
Entry::Missing
);
write_entry(
&self.applications,
&entry,
&desktop_entry(executable, hidden),
)
.wrap_err_with(|| format!("could not write {}", entry.display()))?;
tracing::info!(entry = %entry.display(), "wrote a desktop entry for the portal");
Ok(Some(entry))
}
}
fn read_entry(path: &Path) -> Result<Entry> {
match std::fs::symlink_metadata(path) {
Ok(metadata) if metadata.is_file() => std::fs::read_to_string(path)
.map(Entry::File)
.wrap_err_with(|| format!("could not read {}", path.display())),
Ok(_) => Ok(Entry::Other),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Entry::Missing),
Err(error) => Err(error).wrap_err_with(|| format!("could not read {}", path.display())),
}
}
fn managed(entry: &str) -> bool {
entry.lines().any(|line| line.trim() == MANAGED_MARK)
}
fn no_display(entry: &str) -> bool {
entry.lines().any(|line| line.trim() == "NoDisplay=true")
}
fn write_entry(applications: &Path, entry: &Path, contents: &str) -> Result<()> {
std::fs::create_dir_all(applications)?;
let staged = applications.join(format!(".{APP_ID}.desktop.{}", std::process::id()));
let mut file = std::fs::File::create(&staged)?;
file.write_all(contents.as_bytes())?;
file.sync_all()?;
std::fs::rename(&staged, entry)?;
Ok(())
}
/// `entry` with every `Icon=` naming Hex's icon (`anomaly.hex` in hicolor).
pub(crate) fn with_icon(entry: &str) -> String {
let mut named = String::with_capacity(entry.len());
for line in entry.lines() {
if line.trim_start().starts_with("Icon=") {
named.push_str(&format!("Icon={APP_ID}"));
} else {
named.push_str(line);
}
named.push('\n');
}
named
}
/// An old managed entry under the new name, keeping its Exec lines, naming
/// Hex's windows for X11 launchers, and showing Hex's icon.
fn moved_entry(old: &str) -> String {
let mut entry = String::with_capacity(old.len() + 32);
for line in old
.lines()
.filter(|line| !line.trim_start().starts_with("StartupWMClass="))
{
entry.push_str(line);
entry.push('\n');
if line.trim() == "[Desktop Entry]" {
entry.push_str(&format!("StartupWMClass={APP_ID}\n"));
}
}
with_icon(&entry)
}
/// `NoDisplay`, not `Hidden`: the portal refuses an app whose entry is Hidden.
fn desktop_entry(executable: &str, hidden: bool) -> String {
format!(
"[Desktop Entry]\nType=Application\nName=Hex\nComment=Local voice dictation\nExec={}\nIcon={APP_ID}\nTerminal=false\nCategories=Utility;Accessibility;\nStartupWMClass={APP_ID}\n{}{MANAGED_MARK}\n",
exec_argument(executable),
if hidden { "NoDisplay=true\n" } else { "" }
)
}
/// One quoted Exec argument: quoting escapes, then string escapes, as the
/// Desktop Entry spec reads them, with `%` doubled for field codes.
fn exec_argument(argument: &str) -> String {
let mut quoted = String::from("\"");
for character in argument.chars() {
match character {
'"' | '`' | '$' => {
quoted.push_str("\\\\");
quoted.push(character);
}
'\\' => quoted.push_str("\\\\\\\\"),
'%' => quoted.push_str("%%"),
_ => quoted.push(character),
}
}
quoted.push('"');
quoted
}
/// The GlobalShortcuts client.
pub(crate) struct Portal {
bus: PortalBus,
session: Option<OwnedObjectPath>,
}
impl Portal {
/// `None` when the session has no shortcuts portal.
pub(crate) fn connect(stop: &AtomicBool) -> Result<Option<Self>> {
Ok(PortalBus::open(SHORTCUTS, stop)?.map(|bus| Self { bus, session: None }))
}
/// Whether the desktop can show its dialog for Hex's shortcuts
/// (`ConfigureShortcuts`, version 2).
pub(crate) fn configurable(&self) -> bool {
self.bus.version >= 2
}
/// Opens the desktop's dialog for Hex's shortcuts; changes arrive as
/// `Event::Changed`.
pub(crate) fn configure(&self) -> Result<()> {
let session = self
.session
.as_ref()
.ok_or_else(|| eyre!("no shortcuts are bound"))?;
self.bus.call_portal(
"ConfigureShortcuts",
&(session, "", HashMap::<&str, Variant<'_>>::new()),
)
}
/// Binds Hex's shortcuts and returns the trigger the desktop describes
/// for each one it bound, by id.
pub(crate) fn bind(
&mut self,
shortcuts: &[Shortcut],
stop: &AtomicBool,
) -> Result<HashMap<String, Option<String>>> {
let session = self.bus.create_session(stop)?;
self.session = Some(session.clone());
self.bind_session(session, shortcuts, stop)
}
/// Clears the shortcuts GNOME keeps listed for Hex once its session
/// closes (#575). GNOME Settings stores exactly the set an app binds and
/// asks for approval only for shortcuts it has not stored, so binding none
/// in a fresh session empties the list without a dialog; binding them again
/// asks again. Only on GNOME: KDE would drop keys the person chose for Hex's
/// shortcuts (#482).
pub(crate) fn forget(mut self) -> Result<()> {
if !gnome() {
return Ok(());
}
if let Some(session) = self.session.take() {
self.bus.close_session(session.as_str());
}
let stop = AtomicBool::new(false);
let session = self.bus.create_session(&stop)?;
self.bind_session(session, &[], &stop)?;
tracing::info!("cleared Hex's shortcuts from GNOME Settings");
Ok(())
}
/// Before #579 Hex registered with the portal as `hex`, and before #492
/// its Cancel dictation id `cancel` asked for Escape. KDE keeps every
/// shortcut a portal app bound under that app's id, so an upgraded Hex
/// left `hex`'s set (Cancel dictation on Escape among it) grabbed with
/// nothing able to rebind it, taking Escape from every app (#624).
/// Removes that set, and `cancel` under the current id, from KDE's
/// global shortcuts. Only on KDE, only those entries.
pub(crate) fn forget_legacy_kde_shortcuts(&self) -> Result<()> {
if !desktop_is("KDE") {
return Ok(());
}
let actions: Vec<Vec<String>> = self
.bus
.call_service(
KGLOBALACCEL,
KGLOBALACCEL_PATH,
KGLOBALACCEL_INTERFACE,
"allActionsForComponent",
&(vec![LEGACY_APP_ID],),
)
.wrap_err("could not list Hex's old KDE shortcuts")?;
let mut legacy = actions
.iter()
.filter_map(|action| action.get(1))
.map(|action| (LEGACY_APP_ID, action.as_str()))
.collect::<Vec<_>>();
legacy.push((APP_ID, LEGACY_CANCEL_ID));
for (component, action) in legacy {
let removed: bool = self
.bus
.call_service(
KGLOBALACCEL,
KGLOBALACCEL_PATH,
KGLOBALACCEL_INTERFACE,
"unregister",
&(component, action),
)
.wrap_err_with(|| format!("could not remove Hex's old KDE shortcut {action}"))?;
if removed {
tracing::info!(component, action, "removed an old Hex shortcut from KDE");
}
}
Ok(())
}
/// The presses, releases, and changes that arrived since the last call.
pub(crate) fn events(&mut self) -> Vec<Event> {
let shortcuts = self.session.as_ref().map(|session| session.as_str());
self.bus
.events()
.into_iter()
.filter_map(|(session, event)| (shortcuts == Some(session.as_str())).then_some(event))
.collect()
}
fn bind_session(
&mut self,
session: OwnedObjectPath,
shortcuts: &[Shortcut],
stop: &AtomicBool,
) -> Result<HashMap<String, Option<String>>> {
let requested = shortcuts
.iter()
.map(|shortcut| {
let mut options =
HashMap::from([("description", Variant::from(shortcut.description))]);
if let Some(trigger) = &shortcut.trigger {
options.insert("preferred_trigger", Variant::from(trigger.as_str()));
}
(shortcut.id.as_str(), options)
})
.collect::<Vec<_>>();
let handle = session.into_inner();
let results = self.bus.request(
"BindShortcuts",
|token| {
(
handle,
requested,
"",
HashMap::from([("handle_token", Variant::from(token.to_owned()))]),
)
},
stop,
)?;
let bound = results
.get("shortcuts")
.and_then(|shortcuts| shortcuts.try_clone().ok())
.and_then(|shortcuts| Vec::<(String, Results)>::try_from(shortcuts).ok())
.unwrap_or_default();
Ok(triggers(bound))
}
}
const GNOME_SHORTCUTS: &str = "org.gnome.settings-daemon.global-shortcuts";
/// Before #579 Hex registered with the portal as `hex`. GNOME Settings keeps
/// that set listed beside `anomaly.hex`, and nothing can bind or clear it
/// through the portal again (GNOME 49 and later refuse the id), so Hex removes
/// it from GNOME's own settings once (#575). Only on GNOME, only that entry.
pub(crate) fn forget_legacy_gnome_shortcuts() -> Result<()> {
if !gnome() {
return Ok(());
}
// No gsettings or no GNOME schema: nothing to clear.
let Ok(listed) = gsettings(&["get", GNOME_SHORTCUTS, "applications"]) else {
return Ok(());
};
let applications = string_list(&listed);
if !applications.iter().any(|app| app == LEGACY_APP_ID) {
return Ok(());
}
gsettings(&[
"reset",
&format!(
"{GNOME_SHORTCUTS}.application:/org/gnome/settings-daemon/global-shortcuts/{LEGACY_APP_ID}/"
),
"shortcuts",
])?;
let kept = applications
.iter()
.filter(|app| *app != LEGACY_APP_ID)
.map(String::as_str)
.collect::<Vec<_>>();
gsettings(&[
"set",
GNOME_SHORTCUTS,
"applications",
&string_list_text(&kept),
])?;
tracing::info!("removed Hex's pre-#579 shortcuts from GNOME Settings");
Ok(())
}
fn gsettings(arguments: &[&str]) -> Result<String> {
let output = std::process::Command::new("gsettings")
.args(arguments)
.stdin(std::process::Stdio::null())
.output()
.wrap_err("could not run gsettings")?;
if !output.status.success() {
return Err(eyre!(
"gsettings {} failed: {}",
arguments.join(" "),
String::from_utf8_lossy(&output.stderr).trim()
));
}
Ok(String::from_utf8_lossy(&output.stdout).trim().to_owned())
}
/// A GVariant `as` as gsettings prints it: `['a', 'b']` or `@as []`.
fn string_list(text: &str) -> Vec<String> {
let text = text.trim().trim_start_matches("@as").trim();
text.trim_start_matches('[')
.trim_end_matches(']')
.split(',')
.map(|item| {
item.trim()
.trim_matches(|c| c == '\'' || c == '"')
.to_owned()
})
.filter(|item| !item.is_empty())
.collect()
}
/// App ids never contain quotes or backslashes, so they need no escaping.
fn string_list_text(items: &[&str]) -> String {
if items.is_empty() {
return "@as []".into();
}
let quoted = items
.iter()
.map(|item| format!("'{item}'"))
.collect::<Vec<_>>();
format!("[{}]", quoted.join(", "))
}
fn gnome() -> bool {
desktop_is("GNOME")
}
/// Whether the desktop assigns portal shortcuts their keys in its own
/// configuration and describes no trigger in the portal's answer. Hyprland's
/// portal returns an empty description for every shortcut, bound or not
/// (`bind = …, global, anomaly.hex:…` in its config), so an empty one there
/// is no refusal.
pub(crate) fn desktop_assigns_triggers() -> bool {
desktop_is("Hyprland")
}
fn desktop_is(name: &str) -> bool {
std::env::var("XDG_CURRENT_DESKTOP").is_ok_and(|desktops| {
desktops
.split(':')
.any(|desktop| desktop.eq_ignore_ascii_case(name))
})
}
/// A desktop's trigger description as Settings shows it. GNOME describes a
/// GTK accelerator (`Press <ctrl><alt>F9`); other desktops send readable text.
pub(crate) fn readable_trigger(description: &str) -> String {
let description = description.trim();
let accelerator = description.strip_prefix("Press ").unwrap_or(description);
if accelerator.is_empty() || accelerator.contains([' ', '+']) {
return description.to_string();
}
let mut parts = Vec::new();
let mut rest = accelerator;
while let Some(after) = rest.strip_prefix('<') {
let Some((name, after)) = after.split_once('>') else {
return description.to_string();
};
parts.push(match name.to_ascii_lowercase().as_str() {
"ctrl" | "control" | "primary" => "Ctrl".to_string(),
"alt" | "mod1" => "Alt".to_string(),
"shift" => "Shift".to_string(),
"super" | "logo" | "meta" => "Super".to_string(),
other => other.to_string(),
});
rest = after;
}
parts.push(match rest {
"space" => "Space".to_string(),
key if key.chars().count() == 1 => key.to_uppercase(),
key => key.to_string(),
});
parts.join("+")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_loose_binary_gets_a_quoted_exec_line() {
assert_eq!(
exec_argument("/home/a/Downloads/hex"),
"\"/home/a/Downloads/hex\""
);
assert_eq!(
exec_argument("/tmp/my $dir/100%/a\"b\\c"),
r#""/tmp/my \\$dir/100%%/a\\"b\\\\c""#
);
assert!(desktop_entry("/opt/hex", false).contains("\nExec=\"/opt/hex\"\n"));
assert!(!desktop_entry("/opt/hex", false).contains("NoDisplay"));
assert!(desktop_entry("/opt/hex", true).contains("\nNoDisplay=true\n"));
assert!(desktop_entry("/opt/hex", false).contains("\nStartupWMClass=anomaly.hex\n"));
}
#[test]
fn a_moved_entry_keeps_its_commands_and_names_the_window_class() {
let old = "[Desktop Entry]\nName=Hex\nExec=\"/home/a/.local/bin/hex\"\nStartupWMClass=hex\nX-Hex-Managed=true\n\n[Desktop Action quit]\nExec=\"/home/a/.local/bin/hex\" quit\n";
assert_eq!(
moved_entry(old),
"[Desktop Entry]\nStartupWMClass=anomaly.hex\nName=Hex\nExec=\"/home/a/.local/bin/hex\"\nX-Hex-Managed=true\n\n[Desktop Action quit]\nExec=\"/home/a/.local/bin/hex\" quit\n"
);
}
fn entries(name: &str) -> (PathBuf, DesktopEntries) {
let unique = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos();
let root = std::env::temp_dir().join(format!("hex-desktop-{name}-{unique}"));
let applications = root.join("home/applications");
let system = root.join("system/applications");
std::fs::create_dir_all(&applications).unwrap();
std::fs::create_dir_all(&system).unwrap();
let entries = DesktopEntries::new(applications.clone(), vec![applications, system]);
(root, entries)
}
const OLD: &str =
"[Desktop Entry]\nName=Hex\nExec=\"/home/a/.local/bin/hex\"\nX-Hex-Managed=true\n";
#[test]