prismsdk-linux 0.1.0

Prism backend for Linux desktops (GTK 4 native widgets).
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
//! Linux system surfaces and device APIs, through freedesktop standards:
//!
//! | | |
//! |---|---|
//! | location | GeoClue2 (system D-Bus: `CreateClient`, `LocationUpdated`) |
//! | photos | the desktop's file chooser (`GtkFileChooserNative`, portal-aware) |
//! | clipboard | the display's clipboard |
//! | links | the default app for the URI |
//! | notifications | `GNotification` (freedesktop notifications or the portal), with buttons |
//! | alerts | a modal window |
//! | context menus, menu bar | `GMenu` models with app actions (`app.m<id>`) |
//! | background tasks | run while the app is open |
//! | secrets, fingerprint, sign-in | Secret Service, fprintd, loopback redirect (`security.rs`) |
//!
//! Motion, camera, haptics and the share sheet have no desktop standard:
//! capabilities say so and calls fail with "unavailable".

use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;

use gtk::prelude::*;
use gtk::{gio, glib};
use prism_core::menu::{ActionRole, AlertSpec, MenuItemSpec, MenuSpec};
use prism_core::surfaces::PlatformRequest;
use prism_core::{
    Accuracy, Capabilities, DeviceCall, DeviceError, DeviceEvent, DeviceValue, Permission,
    PermissionState, PickedFile, PlatformServices, UiEvent,
};

use crate::imp;
use crate::security::SecretOp;

/// Prefix of secrets that need a fingerprint first (kept in the keyring).
const GATED: &str = "\u{1}prism-gated\u{1}";

const GEOCLUE: &str = "org.freedesktop.GeoClue2";

pub(crate) struct LinuxServices {
    pub app: gtk::Application,
    pub window: gtk::ApplicationWindow,
    caps: Capabilities,
    /// GeoClue clients of running location streams (call id → client path).
    location_streams: Rc<RefCell<HashMap<u64, String>>>,
    /// Delayed notifications not sent yet.
    pending: HashMap<String, glib::SourceId>,
    /// Background tasks: id → (next run, interval).
    pub background: Vec<(String, std::time::Instant, std::time::Duration)>,
    /// Sign-ins waiting for their loopback redirect.
    loopback: crate::security::Loopback,
    /// The app's data directory (push keys).
    data_dir: std::path::PathBuf,
}

fn reply(id: u64, result: Result<DeviceValue, DeviceError>) {
    glib::idle_add_local_once(move || imp::device_reply(id, result));
}

fn event(id: u64, e: DeviceEvent) {
    glib::idle_add_local_once(move || imp::device_event(id, e));
}

/// Shows `path` selected in the desktop's file manager (#210), through
/// `org.freedesktop.FileManager1.ShowItems` (Files, Dolphin, Nemo, Thunar…);
/// without one, opens its folder.
fn reveal(path: &std::path::Path) {
    let uri = gio::File::for_path(path).uri().to_string();
    let folder = path
        .parent()
        .map(|p| gio::File::for_path(p).uri().to_string());
    let open_folder = move || {
        if let Some(folder) = &folder {
            let _ = gio::AppInfo::launch_default_for_uri(folder, None::<&gio::AppLaunchContext>);
        }
    };
    let Ok(bus) = gio::bus_get_sync(gio::BusType::Session, None::<&gio::Cancellable>) else {
        return open_folder();
    };
    bus.call(
        Some("org.freedesktop.FileManager1"),
        "/org/freedesktop/FileManager1",
        "org.freedesktop.FileManager1",
        "ShowItems",
        Some(&(vec![uri], "").to_variant()),
        None,
        gio::DBusCallFlags::NONE,
        5000,
        None::<&gio::Cancellable>,
        move |r| {
            if r.is_err() {
                open_folder();
            }
        },
    );
}

fn system_bus() -> Option<gio::DBusConnection> {
    gio::bus_get_sync(gio::BusType::System, None::<&gio::Cancellable>).ok()
}

impl LinuxServices {
    pub fn new(
        app: gtk::Application,
        window: gtk::ApplicationWindow,
        data_dir: std::path::PathBuf,
    ) -> Self {
        // GNotification needs the session bus; location needs GeoClue on the
        // system bus.
        let session = gio::bus_get_sync(gio::BusType::Session, None::<&gio::Cancellable>).is_ok();
        let geoclue = system_bus().is_some_and(|bus| {
            bus.call_sync(
                Some("org.freedesktop.DBus"),
                "/org/freedesktop/DBus",
                "org.freedesktop.DBus",
                "ListActivatableNames",
                None,
                Some(glib::VariantTy::new("(as)").expect("type")),
                gio::DBusCallFlags::NONE,
                -1,
                None::<&gio::Cancellable>,
            )
            .ok()
            .and_then(|v| v.child_value(0).get::<Vec<String>>())
            .is_some_and(|names| names.iter().any(|n| n == GEOCLUE))
        });
        let (secrets, biometry) = crate::security::capabilities();
        LinuxServices {
            caps: Capabilities {
                car: false,
                notifications: session,
                app_menu: true,
                tray: session,
                location: geoclue,
                photos: true,
                clipboard: true,
                secure_storage: secrets,
                biometry,
                // fprintd only: no desktop standard checks a password for an app.
                device_auth: biometry.is_biometric(),
                web_auth: true,
                // UnifiedPush over D-Bus, when a distributor runs (push.rs).
                push: crate::push::distributor().map(|_| prism_core::PushService::UnifiedPush),
                // GtkDropTarget (#111).
                drop_files: true,
                drag_and_drop: true,
                ..Default::default()
            },
            data_dir,
            app,
            window,
            location_streams: Rc::new(RefCell::new(HashMap::new())),
            pending: HashMap::new(),
            background: Vec::new(),
            loopback: Default::default(),
        }
    }

    // --- Device ------------------------------------------------------------------------

    fn device(&mut self, id: u64, call: DeviceCall) {
        match call {
            // GeoClue authorizes when a client starts (its agent asks the
            // user): asking means starting one.
            DeviceCall::RequestPermission(Permission::Location | Permission::LocationAlways)
                if self.caps.location =>
            {
                let desktop_id = self.desktop_id();
                glib::MainContext::default().spawn_local(async move {
                    let state = match geoclue::start_client(&desktop_id, 4).await {
                        Ok((bus, path)) => {
                            geoclue::stop(&bus, &path).await;
                            PermissionState::Granted
                        }
                        Err("denied") => PermissionState::Denied,
                        Err(_) => PermissionState::Unavailable,
                    };
                    reply(id, Ok(DeviceValue::Permission(state)));
                });
            }
            DeviceCall::PermissionStatus(p) | DeviceCall::RequestPermission(p) => {
                let state = match p {
                    Permission::Location | Permission::LocationAlways if self.caps.location => {
                        // GeoClue's agent asks the user when a client starts.
                        PermissionState::NotDetermined
                    }
                    Permission::Notifications if self.caps.notifications => {
                        PermissionState::Granted
                    }
                    // The file chooser needs no permission.
                    Permission::Photos => PermissionState::Granted,
                    _ => PermissionState::Unavailable,
                };
                reply(id, Ok(DeviceValue::Permission(state)));
            }
            DeviceCall::CurrentLocation(a) => self.locate(id, a, false),
            DeviceCall::WatchLocation(a) => self.locate(id, a, true),
            DeviceCall::StopWatch => {
                if let Some(path) = self.location_streams.borrow_mut().remove(&id)
                    && let Some(bus) = system_bus()
                {
                    glib::MainContext::default()
                        .spawn_local(async move { geoclue::stop(&bus, &path).await });
                }
            }
            DeviceCall::PickImages(o) => {
                if o.camera {
                    return reply(id, Err(DeviceError::from_message("unavailable")));
                }
                self.pick_images(id, o.limit);
            }
            DeviceCall::PickFiles(o) => self.pick_files(id, o),
            DeviceCall::PickFolder(o) => self.pick_folder(id, o),
            DeviceCall::SaveFile(f) => self.save_file(id, f),
            DeviceCall::RevealPath(p) => reveal(&p),
            DeviceCall::ReadClipboard => {
                let clipboard = self.window.clipboard();
                clipboard.read_text_async(None::<&gio::Cancellable>, move |r| {
                    let text = r.ok().flatten().map(|t| t.to_string());
                    reply(id, Ok(DeviceValue::Text(text)));
                });
            }
            DeviceCall::CopyText(t) => {
                self.window.clipboard().set_text(&t);
                reply(id, Ok(DeviceValue::Done));
            }
            // #246: every type the clipboard offers, images as PNG.
            DeviceCall::ReadClipboardItem => {
                let clipboard = self.window.clipboard();
                glib::MainContext::default().spawn_local(async move {
                    let item = read_clipboard_item(&clipboard).await;
                    reply(id, Ok(DeviceValue::Clipboard(item)));
                });
            }
            DeviceCall::WriteClipboard(item) => {
                write_clipboard_item(&self.window.clipboard(), &item);
                reply(id, Ok(DeviceValue::Done));
            }
            // No tabs here: the default handler opens it either way.
            DeviceCall::OpenUrl(url) | DeviceCall::OpenUrlIn(url, _) => {
                let ok = gio::AppInfo::launch_default_for_uri(&url, None::<&gio::AppLaunchContext>);
                reply(
                    id,
                    ok.map(|_| DeviceValue::Done)
                        .map_err(|e| DeviceError::from_message(&e.to_string())),
                );
            }
            DeviceCall::WatchMotion(_) => event(
                id,
                DeviceEvent::Error(DeviceError::from_message("unavailable")),
            ),
            // No platform passkeys on the Linux desktop (#94).
            DeviceCall::Haptic(_)
            | DeviceCall::Share(_)
            | DeviceCall::SignInWithApple(_)
            | DeviceCall::WebAuthn(_) => reply(id, Err(DeviceError::from_message("unavailable"))),
            DeviceCall::SecureGet { key, prompt, .. } => {
                self.secret(id, key, SecretOp::Get, prompt)
            }
            DeviceCall::SecureSet {
                key,
                value,
                options,
            } => {
                // The keyring has no per-item owner check: only
                // `confirm_owner` secrets, gated with fprintd (S22).
                // `biometric` stays `Unavailable` by decision: no Linux
                // store ties a secret to the user's presence. The Secret
                // Service unlocks whole collections for every program of
                // the user, the kernel keyring checks no presence, the TPM
                // is closed to users on most distributions (and its PIN
                // would be typed into the app), and fprintd or polkit only
                // answer the app yes or no, bound to nothing.
                let gated = match options.app_gate(self.caps.device_auth) {
                    Ok(gated) => gated,
                    Err(e) => return reply(id, Err(e)),
                };
                let label = self
                    .window
                    .title()
                    .map(|t| t.to_string())
                    .unwrap_or_default();
                let value = format!("{}{value}", if gated { GATED } else { "" });
                self.secret(id, key, SecretOp::Set { label, value }, None)
            }
            DeviceCall::SecureDelete { key, .. } => self.secret(id, key, SecretOp::Delete, None),
            DeviceCall::BiometryStatus => {
                crate::security::biometry(move |r| imp::device_reply(id, r))
            }
            DeviceCall::Authenticate(r) => {
                crate::security::authenticate(&self.window, r.reason, move |r| {
                    imp::device_reply(id, r)
                })
            }
            DeviceCall::AuthRedirect(_) => reply(id, self.loopback.redirect()),
            DeviceCall::WebAuth(r) => self
                .loopback
                .start(&r.url, &r.redirect, move |r| imp::device_reply(id, r)),
            // No cookies here (secure storage keeps secrets), no live session.
            DeviceCall::SetCookie(_) => reply(id, Err(DeviceError::Unavailable)),
            DeviceCall::Reconnect => {}
            // No browser id natively: nothing to renew.
            DeviceCall::RenewBrowserId => reply(id, Ok(DeviceValue::Done)),
        }
    }

    /// A Secret Service operation; biometric items are verified with
    /// fprintd before their value is returned.
    fn secret(&mut self, id: u64, key: String, op: SecretOp, prompt: Option<String>) {
        if !self.caps.secure_storage {
            return reply(id, Err(DeviceError::Unavailable));
        }
        let window = self.window.clone();
        let get = matches!(op, SecretOp::Get);
        crate::security::secret(self.desktop_id(), key, op, move |r| match r {
            Ok(DeviceValue::Text(Some(v))) if get && v.starts_with(GATED) => {
                let value = v[GATED.len()..].to_string();
                let reason = prompt
                    .or_else(|| window.title().map(|t| t.to_string()))
                    .unwrap_or_default();
                crate::security::authenticate(&window, reason, move |r| {
                    imp::device_reply(id, r.map(|_| DeviceValue::Text(Some(value))))
                });
            }
            r => imp::device_reply(id, r),
        });
    }

    fn desktop_id(&self) -> String {
        self.app
            .application_id()
            .map(|s| s.to_string())
            .unwrap_or_default()
    }

    /// GeoClue2: a client per call; `stream` keeps it running. Everything
    /// is asynchronous: GeoClue may take seconds to answer.
    fn locate(&mut self, id: u64, accuracy: Accuracy, stream: bool) {
        let fail = move |m: &str| {
            if stream {
                event(id, DeviceEvent::Error(DeviceError::from_message(m)));
            } else {
                reply(id, Err(DeviceError::from_message(m)));
            }
        };
        if !self.caps.location {
            return fail("unavailable");
        }
        // GClueAccuracyLevel (gclue-enums.h): CITY 4, STREET 6, EXACT 8.
        let level: u32 = match accuracy {
            Accuracy::Coarse => 4,
            Accuracy::Balanced => 6,
            Accuracy::Best => 8,
        };
        let desktop_id = self.desktop_id();
        let streams = self.location_streams.clone();
        glib::MainContext::default().spawn_local(async move {
            let (bus, path) = match geoclue::create_client(&desktop_id, level).await {
                Ok(c) => c,
                Err(e) => return fail(e),
            };
            geoclue::on_location(&bus, &path, move |bus, client, location| {
                if stream {
                    event(id, DeviceEvent::Location(location));
                    true
                } else {
                    reply(id, Ok(DeviceValue::Location(location)));
                    let (bus, client) = (bus.clone(), client.to_string());
                    glib::MainContext::default()
                        .spawn_local(async move { geoclue::stop(&bus, &client).await });
                    false
                }
            });
            if stream {
                streams.borrow_mut().insert(id, path.clone());
            }
            if let Err(e) = geoclue::start(&bus, &path).await {
                streams.borrow_mut().remove(&id);
                fail(e);
            }
        });
    }

    /// The desktop's file chooser, images only.
    fn pick_images(&mut self, id: u64, limit: u32) {
        let chooser = gtk::FileChooserNative::new(
            None,
            Some(&self.window),
            gtk::FileChooserAction::Open,
            None,
            None,
        );
        chooser.set_select_multiple(limit != 1);
        let filter = gtk::FileFilter::new();
        filter.add_mime_type("image/*");
        chooser.add_filter(&filter);
        let keep = chooser.clone();
        chooser.connect_response(move |c, response| {
            let _ = &keep;
            if response != gtk::ResponseType::Accept {
                return reply(id, Err(DeviceError::from_message("cancelled")));
            }
            let files = c.files();
            let mut picked = Vec::new();
            for i in 0..files.n_items() {
                if limit > 0 && picked.len() as u32 >= limit {
                    break;
                }
                let Some(file) = files.item(i).and_downcast::<gio::File>() else {
                    continue;
                };
                if let Some(p) = copy_picked(&file) {
                    picked.push(p);
                }
            }
            reply(id, Ok(DeviceValue::Files(picked)));
        });
        chooser.show();
    }

    /// The desktop's file chooser (portal-aware `GtkFileChooserNative`:
    /// `GtkFileDialog` needs GTK 4.10), filtered by MIME types and
    /// extensions.
    fn pick_files(&mut self, id: u64, o: prism_core::PickFiles) {
        let chooser = gtk::FileChooserNative::new(
            None,
            Some(&self.window),
            gtk::FileChooserAction::Open,
            None,
            None,
        );
        chooser.set_select_multiple(o.multiple);
        if !o.types.is_empty() {
            let filter = gtk::FileFilter::new();
            for t in &o.types {
                match t.trim().strip_prefix('.') {
                    Some(ext) => filter.add_suffix(ext),
                    None => filter.add_mime_type(t.trim()),
                }
            }
            chooser.add_filter(&filter);
        }
        let keep = chooser.clone();
        chooser.connect_response(move |c, response| {
            let _ = &keep;
            if response != gtk::ResponseType::Accept {
                return reply(id, Err(DeviceError::from_message("cancelled")));
            }
            let files = c.files();
            let mut picked = Vec::new();
            for i in 0..files.n_items() {
                if !o.multiple && !picked.is_empty() {
                    break;
                }
                let Some(file) = files.item(i).and_downcast::<gio::File>() else {
                    continue;
                };
                if let Some(p) = copy_picked(&file) {
                    picked.push(p);
                }
            }
            reply(id, Ok(DeviceValue::Files(picked)));
        });
        chooser.show();
    }

    /// GTK's folder chooser (#225), then the folder's files read in place,
    /// off the main thread.
    fn pick_folder(&mut self, id: u64, o: prism_core::PickFolder) {
        let chooser = gtk::FileChooserNative::new(
            o.title.as_deref(),
            Some(&self.window),
            gtk::FileChooserAction::SelectFolder,
            o.title.as_deref(),
            None,
        );
        let keep = chooser.clone();
        chooser.connect_response(move |c, response| {
            let _ = &keep;
            if response != gtk::ResponseType::Accept {
                return reply(id, Err(DeviceError::from_message("cancelled")));
            }
            let Some(root) = c.file().and_then(|f| f.path()) else {
                return reply(id, Err(DeviceError::Failed("not a local folder".into())));
            };
            glib::MainContext::default().spawn_local(async move {
                match gio::spawn_blocking(move || folder_files(&root)).await {
                    Ok(files) => reply(id, Ok(DeviceValue::Files(files))),
                    Err(_) => reply(
                        id,
                        Err(DeviceError::Failed("could not read the folder".into())),
                    ),
                }
            });
        });
        chooser.show();
    }

    /// A save dialog (#210): the user picks the name and folder (GTK asks
    /// before replacing a file), then the file is written off the main
    /// thread.
    fn save_file(&mut self, id: u64, f: prism_core::SaveFile) {
        let chooser = gtk::FileChooserNative::new(
            None,
            Some(&self.window),
            gtk::FileChooserAction::Save,
            None,
            None,
        );
        chooser.set_current_name(&f.file_name());
        let keep = chooser.clone();
        let file = RefCell::new(Some(f));
        chooser.connect_response(move |c, response| {
            let _ = &keep;
            let Some(f) = file.borrow_mut().take() else {
                return;
            };
            if response != gtk::ResponseType::Accept {
                return reply(id, Err(DeviceError::from_message("cancelled")));
            }
            let Some(path) = c.file().and_then(|file| file.path()) else {
                return reply(id, Err(DeviceError::Failed("not a local file".into())));
            };
            glib::MainContext::default().spawn_local(async move {
                let dest = path.clone();
                let mime = f.mime_type();
                let written = gio::spawn_blocking(move || f.write_to(&dest)).await;
                reply(
                    id,
                    match written {
                        Ok(Ok(size)) => Ok(DeviceValue::Files(vec![PickedFile {
                            name: path
                                .file_name()
                                .map(|n| n.to_string_lossy().into_owned())
                                .unwrap_or_default(),
                            path: path.to_string_lossy().into_owned(),
                            mime,
                            size,
                        }])),
                        Ok(Err(e)) => Err(DeviceError::Failed(e.to_string())),
                        Err(_) => Err(DeviceError::Failed("could not save the file".into())),
                    },
                );
            });
        });
        chooser.show();
    }

    // --- Notifications ------------------------------------------------------------------

    fn notify(&mut self, n: prism_core::surfaces::Notification) {
        if let Some(timer) = self.pending.remove(&n.id) {
            timer.remove();
        }
        let notification = gio::Notification::new(&n.title);
        let body = [n.subtitle.clone(), Some(n.body.clone())]
            .into_iter()
            .flatten()
            .filter(|s| !s.is_empty())
            .collect::<Vec<_>>()
            .join("\n");
        if !body.is_empty() {
            notification.set_body(Some(&body));
        }
        let target = |action: &str, link: Option<&String>| {
            (n.id.as_str(), action, link.map_or("", String::as_str)).to_variant()
        };
        notification.set_default_action_and_target_value(
            "app.prism-notification",
            Some(&target("", n.link.as_ref())),
        );
        for a in &n.actions {
            // GNotification has no text field: replies send no text.
            notification.add_button_with_target_value(
                &a.title,
                "app.prism-notification",
                Some(&target(&a.id, a.link.as_ref())),
            );
        }
        let app = self.app.clone();
        let id = n.id.clone();
        match n.delay {
            Some(delay) if !delay.is_zero() => {
                let pending_id = id.clone();
                let timer = glib::timeout_add_local_once(delay, move || {
                    app.send_notification(Some(&pending_id), &notification)
                });
                self.pending.insert(id, timer);
            }
            _ => app.send_notification(Some(&id), &notification),
        }
    }
}

// --- Clipboard types (#246) ----------------------------------------------------------

/// The clipboard's MIME types (X11 atoms such as `UTF8_STRING` left out):
/// the text through GDK's text reader, one image as PNG through its
/// texture, the others as their bytes.
async fn read_clipboard_item(clipboard: &gtk::gdk::Clipboard) -> prism_core::ClipboardItem {
    let mut item = prism_core::ClipboardItem::new();
    let formats = clipboard.formats();
    let mimes: Vec<String> = formats.mime_types().iter().map(|m| m.to_string()).collect();
    let base = |m: &str| {
        m.split(';')
            .next()
            .unwrap_or("")
            .trim()
            .to_ascii_lowercase()
    };
    if mimes.iter().any(|m| base(m) == "text/plain")
        && let Ok(Some(text)) = clipboard.read_text_future().await
    {
        item = item.text(text.as_str());
    }
    if (formats.contains_type(gtk::gdk::Texture::static_type())
        || mimes.iter().any(|m| m.starts_with("image/")))
        && let Ok(Some(texture)) = clipboard.read_texture_future().await
    {
        item = item.image(texture.save_to_png_bytes().to_vec(), "image/png");
    }
    let mut seen = Vec::new();
    for mime in &mimes {
        let ty = base(mime);
        if !ty.contains('/') || ty == "text/plain" || ty.starts_with("image/") || seen.contains(&ty)
        {
            continue;
        }
        seen.push(ty.clone());
        let Ok((stream, _)) = clipboard
            .read_future(&[mime.as_str()], glib::Priority::DEFAULT)
            .await
        else {
            continue;
        };
        let out = gio::MemoryOutputStream::new_resizable();
        let flags =
            gio::OutputStreamSpliceFlags::CLOSE_SOURCE | gio::OutputStreamSpliceFlags::CLOSE_TARGET;
        if out
            .splice_future(&stream, flags, glib::Priority::DEFAULT)
            .await
            .is_ok()
        {
            item = item.custom(ty, out.steal_as_bytes().to_vec());
        }
    }
    item
}

/// Every type of `item` on the clipboard: text through GDK's text value
/// (so X11 and Wayland clients get it in their encodings), an image also
/// as a texture (other apps then paste it in the format they ask for).
fn write_clipboard_item(clipboard: &gtk::gdk::Clipboard, item: &prism_core::ClipboardItem) {
    use gtk::gdk::ContentProvider;
    let mut providers = Vec::new();
    for (ty, data) in item.entries() {
        if ty == prism_core::ClipboardItem::TEXT {
            providers.push(ContentProvider::for_value(
                &String::from_utf8_lossy(data).to_value(),
            ));
        } else {
            providers.push(ContentProvider::for_bytes(ty, &glib::Bytes::from(data)));
        }
    }
    if let Some(image) = item.as_image()
        && let Ok(texture) = gtk::gdk::Texture::from_bytes(&glib::Bytes::from_owned(image.bytes))
    {
        providers.push(ContentProvider::for_value(&texture.to_value()));
    }
    let _ = clipboard.set_content(Some(&ContentProvider::new_union(&providers)));
}

// --- Menus --------------------------------------------------------------------------

/// A `GMenu` for a Prism menu; items activate app actions `app.m<id>`.
pub(crate) fn menu_model(app: &gtk::Application, spec: &MenuSpec) -> gio::Menu {
    let menu = gio::Menu::new();
    let mut section = gio::Menu::new();
    for item in &spec.items {
        match item {
            MenuItemSpec::Action {
                id,
                title,
                shortcut,
                shortcut_hint,
                role,
                checked,
                enabled,
                ..
            } => {
                let name = format!("m{id}");
                action(app, &name, *id, *enabled);
                let label = match (checked, role) {
                    (Some(true), _) => format!("✓ {title}"),
                    _ => title.clone(),
                };
                let entry = gio::MenuItem::new(Some(&label), Some(&format!("app.{name}")));
                match shortcut {
                    // A hint (#247): shown by the menu, not an accelerator,
                    // so the key stays the focused widget's.
                    Some(keys) if *shortcut_hint => {
                        entry.set_attribute_value("accel", Some(&accelerator(keys).to_variant()));
                    }
                    Some(keys) => {
                        app.set_accels_for_action(&format!("app.{name}"), &[&accelerator(keys)]);
                    }
                    None => {}
                }
                section.append_item(&entry);
            }
            MenuItemSpec::Separator => {
                menu.append_section(None, &section);
                section = gio::Menu::new();
            }
            // System actions (#161) are AppKit's: GTK fields have their own.
            MenuItemSpec::System { .. } => {}
            MenuItemSpec::Submenu {
                title, menu: sub, ..
            } => {
                let model = menu_model(app, sub);
                section.append_submenu(Some(title), &model);
            }
        }
    }
    menu.append_section(None, &section);
    menu
}

fn action(app: &gtk::Application, name: &str, id: u64, enabled: bool) {
    if let Some(existing) = app.lookup_action(name).and_downcast::<gio::SimpleAction>() {
        existing.set_enabled(enabled);
        return;
    }
    let action = gio::SimpleAction::new(name, None);
    action.set_enabled(enabled);
    action.connect_activate(move |_, _| imp::dispatch(UiEvent::MenuSelect(id)));
    app.add_action(&action);
}

impl LinuxServices {
    fn alert(&self, spec: AlertSpec) {
        let dialog = gtk::Window::builder()
            .transient_for(&self.window)
            .modal(true)
            .resizable(false)
            .default_width(360)
            .build();
        let body = gtk::Box::new(gtk::Orientation::Vertical, 12);
        body.set_margin_top(20);
        body.set_margin_bottom(20);
        body.set_margin_start(20);
        body.set_margin_end(20);
        let title = gtk::Label::new(Some(&spec.title));
        title.add_css_class("title-3");
        title.set_wrap(true);
        body.append(&title);
        if let Some(m) = &spec.message {
            let message = gtk::Label::new(Some(m));
            message.set_wrap(true);
            body.append(&message);
        }
        let buttons = gtk::Box::new(gtk::Orientation::Horizontal, 8);
        buttons.set_halign(gtk::Align::End);
        for (index, (label, role)) in spec.actions.iter().enumerate() {
            let b = gtk::Button::with_label(label);
            match role {
                ActionRole::Destructive => b.add_css_class("destructive-action"),
                ActionRole::Cancel => {}
                _ => b.add_css_class("suggested-action"),
            }
            let (dialog, id) = (dialog.clone(), spec.id);
            b.connect_clicked(move |_| {
                dialog.close();
                imp::dispatch(UiEvent::AlertAction(id, index));
            });
            buttons.append(&b);
        }
        body.append(&buttons);
        dialog.set_child(Some(&body));
        dialog.present();
    }

    /// Background tasks due now (removed until they reschedule).
    pub fn due_background(&mut self) -> Vec<String> {
        let now = std::time::Instant::now();
        let (due, later): (Vec<_>, Vec<_>) =
            self.background.drain(..).partition(|(_, at, _)| *at <= now);
        self.background = later;
        due.into_iter().map(|(id, _, _)| id).collect()
    }
}

impl PlatformServices for LinuxServices {
    fn capabilities(&self) -> Capabilities {
        self.caps
    }

    fn handle(&mut self, request: PlatformRequest) {
        match request {
            PlatformRequest::Device { id, call } => self.device(id, call),
            PlatformRequest::Notify(n) => {
                if self.caps.notifications {
                    self.notify(n)
                }
            }
            PlatformRequest::CancelNotification(id) => {
                if let Some(timer) = self.pending.remove(&id) {
                    timer.remove();
                }
                self.app.withdraw_notification(&id);
            }
            PlatformRequest::RequestNotificationPermission => {}
            // No standard app badge on the Linux desktop (#239).
            PlatformRequest::SetBadge(_) => {}
            PlatformRequest::RegisterPush => crate::push::register(
                self.data_dir.clone(),
                |r| {
                    glib::idle_add_local_once(move || imp::push_registered(r));
                },
                |m| {
                    glib::idle_add_local_once(move || imp::push_received(m));
                },
            ),
            PlatformRequest::UnregisterPush => crate::push::unregister(&self.data_dir),
            // No Live Activities on Linux desktops.
            PlatformRequest::WatchActivityPushToStart => {}
            PlatformRequest::ShowAlert(spec) => self.alert(spec),
            // The app's whole bar (#161): GTK has no menus of its own.
            PlatformRequest::SetAppMenu(menus) | PlatformRequest::SetMenuBar(menus) => {
                let bar = gio::Menu::new();
                for m in &menus {
                    let model = menu_model(&self.app, m);
                    bar.append_submenu(Some(&m.title), &model);
                }
                self.app.set_menubar(Some(&bar));
                self.window.set_show_menubar(true);
            }
            PlatformRequest::ScheduleBackgroundTask(task) => {
                let every = imp::background_interval(task.every);
                self.background.retain(|(id, _, _)| *id != task.id);
                self.background
                    .push((task.id, std::time::Instant::now() + every, every));
            }
            PlatformRequest::SetTray(spec) => crate::tray::set(self, spec),
            PlatformRequest::RemoveTray(id) => crate::tray::remove(&id),
            // No car screens on Linux.
            PlatformRequest::SetCar(_) => {}
            // Fonts are registered by the backend, which draws texts again
            // (imp.rs, `load_font`); stylesheets are a web thing.
            PlatformRequest::LoadFont(_)
            | PlatformRequest::AddStylesheet(_)
            | PlatformRequest::RemoveStylesheet(_)
            // The window's title and its close question are the backend's
            // (imp.rs), which has the window.
            | PlatformRequest::SetTitle(_)
            | PlatformRequest::SetUnsavedChanges(_) => {}
            // No widgets or Live Activities on Linux desktops.
            PlatformRequest::ReloadWidgets(_)
            | PlatformRequest::StartActivity { .. }
            | PlatformRequest::UpdateActivity { .. }
            | PlatformRequest::EndActivity { .. } => {}
        }
    }
}

/// `cmd+shift+n` → `<Control><Shift>n` (Command maps to Control on Linux).
fn accelerator(keys: &str) -> String {
    let mut out = String::new();
    let mut key = String::new();
    for part in keys.split('+') {
        match part.trim().to_ascii_lowercase().as_str() {
            "cmd" | "command" | "ctrl" | "control" | "meta" => out += "<Control>",
            "shift" => out += "<Shift>",
            "alt" | "option" | "opt" => out += "<Alt>",
            "super" => out += "<Super>",
            other => key = other.to_string(),
        }
    }
    // Single characters by their GDK key name (`,` → `comma`).
    let mut chars = key.chars();
    if let (Some(c), None) = (chars.next(), chars.next()) {
        use gtk::glib::translate::FromGlib;
        // SAFETY: plain conversion of a code point to a key value.
        let keyval =
            unsafe { gtk::gdk::Key::from_glib(gtk::gdk::ffi::gdk_unicode_to_keyval(c as u32)) };
        if let Some(name) = keyval.name() {
            key = name.to_string();
        }
    }
    out + &key
}

/// GeoClue2 over the system bus (org.freedesktop.GeoClue2.*.xml).
mod geoclue {
    use std::cell::RefCell;
    use std::rc::Rc;

    use gtk::prelude::*;
    use gtk::{gio, glib};
    use prism_core::Location;

    use super::GEOCLUE;

    /// GeoClue may wait on its agent or location sources.
    const TIMEOUT_MS: i32 = 10_000;

    type Handler = Rc<dyn Fn(&gio::DBusConnection, &str, Location) -> bool>;

    async fn call(
        bus: &gio::DBusConnection,
        path: &str,
        interface: &str,
        method: &str,
        args: Option<glib::Variant>,
        reply: Option<&str>,
    ) -> Result<glib::Variant, glib::Error> {
        bus.call_future(
            Some(GEOCLUE),
            path,
            interface,
            method,
            args.as_ref(),
            reply.map(|r| glib::VariantTy::new(r).expect("type")),
            gio::DBusCallFlags::NONE,
            TIMEOUT_MS,
        )
        .await
    }

    fn error(e: glib::Error) -> &'static str {
        eprintln!("prism-linux: GeoClue: {e}");
        if e.to_string().contains("AccessDenied") {
            "denied"
        } else {
            "unavailable"
        }
    }

    /// A client for this app at `level` (GClueAccuracyLevel), not started.
    pub async fn create_client(
        desktop_id: &str,
        level: u32,
    ) -> Result<(gio::DBusConnection, String), &'static str> {
        let bus = gio::bus_get_future(gio::BusType::System)
            .await
            .map_err(|_| "unavailable")?;
        let created = call(
            &bus,
            "/org/freedesktop/GeoClue2/Manager",
            "org.freedesktop.GeoClue2.Manager",
            "CreateClient",
            None,
            Some("(o)"),
        )
        .await
        .map_err(error)?;
        let path = created
            .child_value(0)
            .str()
            .map(str::to_string)
            .ok_or("unavailable")?;
        for (name, value) in [
            ("DesktopId", desktop_id.to_variant()),
            ("RequestedAccuracyLevel", level.to_variant()),
        ] {
            call(
                &bus,
                &path,
                "org.freedesktop.DBus.Properties",
                "Set",
                Some(("org.freedesktop.GeoClue2.Client", name, value).to_variant()),
                None,
            )
            .await
            .map_err(error)?;
        }
        Ok((bus, path))
    }

    /// Creates and starts a client (GeoClue asks its agent).
    pub async fn start_client(
        desktop_id: &str,
        level: u32,
    ) -> Result<(gio::DBusConnection, String), &'static str> {
        let (bus, path) = create_client(desktop_id, level).await?;
        start(&bus, &path).await?;
        Ok((bus, path))
    }

    pub async fn start(bus: &gio::DBusConnection, path: &str) -> Result<(), &'static str> {
        call(
            bus,
            path,
            "org.freedesktop.GeoClue2.Client",
            "Start",
            None,
            None,
        )
        .await
        .map(|_| ())
        .map_err(error)
    }

    pub async fn stop(bus: &gio::DBusConnection, path: &str) {
        let _ = call(
            bus,
            path,
            "org.freedesktop.GeoClue2.Client",
            "Stop",
            None,
            None,
        )
        .await;
    }

    /// Calls `f` with each new location until it returns `false`.
    // `signal_subscribe` is the GLib 2.74 API (the image's GLib).
    #[allow(deprecated)]
    pub fn on_location(
        bus: &gio::DBusConnection,
        path: &str,
        f: impl Fn(&gio::DBusConnection, &str, Location) -> bool + 'static,
    ) {
        let f: Handler = Rc::new(f);
        let subscription: Rc<RefCell<Option<gio::SignalSubscriptionId>>> =
            Rc::new(RefCell::new(None));
        let sub = subscription.clone();
        let client = path.to_string();
        let handle = bus.signal_subscribe(
            Some(GEOCLUE),
            Some("org.freedesktop.GeoClue2.Client"),
            Some("LocationUpdated"),
            Some(path),
            None,
            gio::DBusSignalFlags::NONE,
            move |bus, _, _, _, _, params| {
                let Some(location_path) = params.child_value(1).str().map(str::to_string) else {
                    return;
                };
                let (bus, client, sub, f) = (bus.clone(), client.clone(), sub.clone(), f.clone());
                glib::MainContext::default().spawn_local(async move {
                    let Some(location) = read_location(&bus, &location_path).await else {
                        return;
                    };
                    if !f(&bus, &client, location)
                        && let Some(id) = sub.borrow_mut().take()
                    {
                        bus.signal_unsubscribe(id);
                    }
                });
            },
        );
        *subscription.borrow_mut() = Some(handle);
    }

    /// The properties of a `Location` object (unknown values per
    /// org.freedesktop.GeoClue2.Location.xml: altitude = -DBL_MAX, speed and
    /// heading = -1).
    pub async fn read_location(bus: &gio::DBusConnection, path: &str) -> Option<Location> {
        let all = call(
            bus,
            path,
            "org.freedesktop.DBus.Properties",
            "GetAll",
            Some(("org.freedesktop.GeoClue2.Location",).to_variant()),
            None,
        )
        .await
        .ok()?;
        let props = all.child_value(0);
        let dict = glib::VariantDict::new(Some(&props));
        let num = |k: &str| dict.lookup::<f64>(k).ok().flatten();
        let timestamp = dict
            .lookup_value("Timestamp", None)
            .and_then(|v| v.get::<(u64, u64)>())
            .map_or(0., |(s, us)| s as f64 + us as f64 / 1e6);
        Some(Location {
            latitude: num("Latitude")?,
            longitude: num("Longitude")?,
            altitude: num("Altitude").filter(|a| *a > f64::MIN),
            accuracy: num("Accuracy").unwrap_or(0.),
            speed: num("Speed").filter(|s| *s >= 0.),
            heading: num("Heading").filter(|h| *h >= 0.),
            timestamp,
        })
    }
}

/// Copies a picked file under the cache directory, like the other backends.
fn copy_picked(file: &gio::File) -> Option<PickedFile> {
    copy_picked_path(file.path()?)
}

/// Folder `root` and its files (#225): the folder first
/// ([`prism_core::FOLDER_MIME`]), then every regular file under it, read in
/// place and named by its path in it; hidden ones left out.
fn folder_files(root: &std::path::Path) -> Vec<PickedFile> {
    let mut out = vec![PickedFile {
        path: root.to_string_lossy().to_string(),
        name: root
            .file_name()
            .map_or_else(|| "folder".into(), |n| n.to_string_lossy().to_string()),
        mime: prism_core::FOLDER_MIME.into(),
        size: 0,
    }];
    let mut todo = vec![(root.to_path_buf(), String::new())];
    while let Some((dir, prefix)) = todo.pop() {
        let Ok(read) = std::fs::read_dir(&dir) else {
            continue;
        };
        let mut entries: Vec<_> = read.flatten().collect();
        entries.sort_by_key(|e| e.file_name());
        for e in entries {
            let name = e.file_name().to_string_lossy().to_string();
            if name.starts_with('.') {
                continue;
            }
            let rel = if prefix.is_empty() {
                name
            } else {
                format!("{prefix}/{name}")
            };
            let Ok(kind) = e.file_type() else {
                continue;
            };
            if kind.is_dir() {
                todo.push((e.path(), rel));
            } else if kind.is_file() {
                let path = e.path();
                let mime = gio::content_type_guess(Some(&path), None::<&[u8]>).0;
                let mime = gio::content_type_get_mime_type(&mime)
                    .map_or("application/octet-stream".into(), |m| m.to_string());
                out.push(PickedFile {
                    size: e.metadata().map_or(0, |m| m.len()),
                    path: path.to_string_lossy().to_string(),
                    name: rel,
                    mime,
                });
            }
        }
    }
    out
}

/// [`copy_picked`] for a local path (any thread: dropped files are copied
/// off the main loop, #111).
pub(crate) fn copy_picked_path(src: std::path::PathBuf) -> Option<PickedFile> {
    let dir = glib::user_cache_dir().join("prism-picked");
    std::fs::create_dir_all(&dir).ok()?;
    let name = src.file_name()?.to_string_lossy().to_string();
    let ext = src
        .extension()
        .map(|e| e.to_string_lossy().to_string())
        .unwrap_or_default();
    let unique = format!(
        "{}.{ext}",
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map_or(0, |d| d.as_nanos())
    );
    let dest = dir.join(unique);
    let size = std::fs::copy(&src, &dest).ok()?;
    let mime = gio::content_type_guess(Some(&src), None::<&[u8]>).0;
    let mime = gio::content_type_get_mime_type(&mime)
        .map_or("application/octet-stream".into(), |m| m.to_string());
    Some(PickedFile {
        path: dest.to_string_lossy().to_string(),
        name,
        mime,
        size,
    })
}