nwg-notifications 0.4.1

D-Bus notification daemon + notification center for Hyprland and Sway. Claims org.freedesktop.Notifications, shows popup toasts, and ships a slide-out history panel with Do-Not-Disturb controls and optional waybar integration. Replaces mako; runs standalone.
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
//! D-Bus server for the notification daemon. Claims
//! `org.freedesktop.Notifications` (the freedesktop-spec interface)
//! and `org.nwg.Notifications` (the project-private interface used
//! by `nwg-shell-config` and `nwg-panel` for live config + count
//! IPC). Runs directly on the glib main loop via
//! `gio::bus_own_name`; no async bridge.

use crate::config::NotificationConfig;
use crate::notification::{Notification, Urgency, clean_markup, parse_actions};
use crate::state::NotificationState;
use gtk4::gio;
use gtk4::glib;
use std::cell::RefCell;
use std::rc::Rc;
use std::time::SystemTime;

/// D-Bus introspection XML for org.freedesktop.Notifications.
const INTROSPECT_XML: &str = r#"
<node>
  <interface name="org.freedesktop.Notifications">
    <method name="Notify">
      <arg name="app_name" type="s" direction="in"/>
      <arg name="replaces_id" type="u" direction="in"/>
      <arg name="app_icon" type="s" direction="in"/>
      <arg name="summary" type="s" direction="in"/>
      <arg name="body" type="s" direction="in"/>
      <arg name="actions" type="as" direction="in"/>
      <arg name="hints" type="a{sv}" direction="in"/>
      <arg name="expire_timeout" type="i" direction="in"/>
      <arg name="id" type="u" direction="out"/>
    </method>
    <method name="CloseNotification">
      <arg name="id" type="u" direction="in"/>
    </method>
    <method name="GetCapabilities">
      <arg name="capabilities" type="as" direction="out"/>
    </method>
    <method name="GetServerInformation">
      <arg name="name" type="s" direction="out"/>
      <arg name="vendor" type="s" direction="out"/>
      <arg name="version" type="s" direction="out"/>
      <arg name="spec_version" type="s" direction="out"/>
    </method>
    <signal name="NotificationClosed">
      <arg name="id" type="u"/>
      <arg name="reason" type="u"/>
    </signal>
    <signal name="ActionInvoked">
      <arg name="id" type="u"/>
      <arg name="action_key" type="s"/>
    </signal>
  </interface>
</node>
"#;

/// D-Bus introspection XML for the nwg-specific count IPC interface.
const NWG_COUNT_INTROSPECT_XML: &str = r#"
<node>
  <interface name="org.nwg.Notifications">
    <method name="GetCount">
      <arg name="count" type="u" direction="out"/>
    </method>
    <signal name="CountChanged">
      <arg name="count" type="u"/>
    </signal>
    <method name="SetPopupPosition">
      <arg name="position" type="s" direction="in"/>
    </method>
    <method name="SetPopupWidth">
      <arg name="width" type="u" direction="in"/>
    </method>
    <method name="SetPanelWidth">
      <arg name="width" type="u" direction="in"/>
    </method>
    <method name="SetPopupTimeout">
      <arg name="timeout_ms" type="u" direction="in"/>
    </method>
    <method name="SetMaxPopups">
      <arg name="max" type="u" direction="in"/>
    </method>
    <method name="SetMaxHistory">
      <arg name="max" type="u" direction="in"/>
    </method>
  </interface>
</node>
"#;

/// D-Bus name for the nwg-specific count IPC interface.
pub(crate) const NWG_COUNT_BUS_NAME: &str = "org.nwg.Notifications";
/// D-Bus object path for the nwg-specific count IPC interface.
pub(crate) const NWG_COUNT_OBJECT_PATH: &str = "/org/nwg/Notifications";

/// Callback invoked when a new notification arrives via D-Bus.
/// Implement this to show popups, update waybar, etc.
pub(crate) type OnNotify = Rc<dyn Fn(&Notification)>;

/// Callback invoked when a notification is closed via D-Bus.
pub(crate) type OnClose = Rc<dyn Fn(u32)>;

/// Registers the notification D-Bus server on the session bus.
///
/// Runs entirely on the glib main loop — no threads or async needed.
/// Acquires both `org.freedesktop.Notifications` (the standard notification
/// daemon interface) and `org.nwg.Notifications` (the nwg-specific count IPC).
pub(crate) fn register_server(
    state: &Rc<RefCell<NotificationState>>,
    config: &Rc<RefCell<NotificationConfig>>,
    on_state_change: Rc<dyn Fn()>,
    on_notify: OnNotify,
    on_close: OnClose,
) {
    let state_fdo = Rc::clone(state);
    let on_notify_fdo = Rc::clone(&on_notify);
    let on_close_fdo = Rc::clone(&on_close);

    gio::bus_own_name(
        gio::BusType::Session,
        "org.freedesktop.Notifications",
        gio::BusNameOwnerFlags::REPLACE,
        move |connection, _name| {
            log::info!("Acquired D-Bus name: org.freedesktop.Notifications");
            state_fdo.borrow_mut().dbus_connection = Some(connection.clone());
            register_object(&connection, &state_fdo, &on_notify_fdo, &on_close_fdo);
        },
        |_connection, _name| {
            log::debug!("D-Bus name acquired callback");
        },
        |_connection, _name| {
            log::error!(
                "Lost D-Bus name org.freedesktop.Notifications — is another daemon running?"
            );
        },
    );

    let state_nwg = Rc::clone(state);
    let config_nwg = Rc::clone(config);
    let on_change_nwg = Rc::clone(&on_state_change);
    gio::bus_own_name(
        gio::BusType::Session,
        NWG_COUNT_BUS_NAME,
        gio::BusNameOwnerFlags::REPLACE,
        move |connection, _name| {
            log::info!("Acquired D-Bus name: {NWG_COUNT_BUS_NAME}");
            register_nwg_count_object(&connection, &state_nwg, &config_nwg, &on_change_nwg);
        },
        |_connection, _name| {
            log::debug!("nwg-count D-Bus name acquired callback");
        },
        |_connection, _name| {
            log::error!("Lost D-Bus name {NWG_COUNT_BUS_NAME} — another daemon?");
        },
    );
}

/// Registers the daemon's `org.freedesktop.Notifications` D-Bus
/// object on the given connection. Wires `handle_method` as the
/// method-call dispatcher.
///
/// # Panics
///
/// Panics on three unreachable-in-practice failure modes, all of
/// which represent a build-time misconfiguration rather than a
/// runtime condition:
/// - `INTROSPECT_XML` fails to parse — the XML is a `const &str`
///   in this file, so a parse failure means we shipped malformed
///   XML and CI should have caught it.
/// - The `org.freedesktop.Notifications` interface name doesn't
///   resolve in the parsed `DBusNodeInfo` — same `const`-source
///   provenance as above.
/// - `register_object` fails to build — the object path is a
///   string literal and the interface info just came from the
///   parsed `const`, so any failure here would be a bug in `gio`'s
///   builder.
fn register_object(
    connection: &gio::DBusConnection,
    state: &Rc<RefCell<NotificationState>>,
    on_notify: &OnNotify,
    on_close: &OnClose,
) {
    let node_info = gio::DBusNodeInfo::for_xml(INTROSPECT_XML)
        .expect("Failed to parse notification introspection XML");

    let interface_info = node_info
        .lookup_interface("org.freedesktop.Notifications")
        .expect("Interface not found in XML");

    let state = Rc::clone(state);
    let on_notify = Rc::clone(on_notify);
    let on_close = Rc::clone(on_close);

    connection
        .register_object("/org/freedesktop/Notifications", &interface_info)
        .method_call(
            move |_conn, _sender, _path, _iface, method, params, invocation| {
                handle_method(method, params, invocation, &state, &on_notify, &on_close);
            },
        )
        .build()
        .expect("Failed to register D-Bus object");
}

fn handle_method(
    method: &str,
    params: glib::Variant,
    invocation: gio::DBusMethodInvocation,
    state: &Rc<RefCell<NotificationState>>,
    on_notify: &OnNotify,
    on_close: &OnClose,
) {
    match method {
        "Notify" => handle_notify(&params, invocation, state, on_notify),
        "CloseNotification" => handle_close(&params, invocation, state, on_close),
        "GetCapabilities" => handle_capabilities(invocation),
        "GetServerInformation" => handle_server_info(invocation),
        // Daemon-side unknown-method dispatch is `warn`, not `error`:
        // the freedesktop `Notify` D-Bus surface is open enough that a
        // misbehaving client (or a forward-compat probe) calling a
        // method we don't implement is something to log but not page on.
        // The mirror site on the *client* side — `--update` against a
        // stale daemon in `main.rs`'s `is_unknown_method_error` branch —
        // is `error` because there it's an actionable failure for the
        // human running the CLI ("restart the daemon"). Same wire-level
        // condition, different side, different severity. The sibling
        // arm in `handle_nwg_count_method` shares this policy.
        _ => {
            log::warn!("Unknown D-Bus method: {method}");
            invocation.return_dbus_error(
                "org.freedesktop.DBus.Error.UnknownMethod",
                &format!("Unknown method: {method}"),
            );
        }
    }
}

/// Registers the daemon's `org.nwg.Notifications` D-Bus object on
/// the given connection. Backs `GetCount`, the six `Set*` live-config
/// setters, and the `CountChanged` signal source.
///
/// # Panics
///
/// Panics on three unreachable-in-practice failure modes, all of
/// which represent a build-time misconfiguration rather than a
/// runtime condition:
/// - `NWG_COUNT_INTROSPECT_XML` fails to parse — the XML is a
///   `const &str` in this file, so a parse failure means we
///   shipped malformed XML and CI should have caught it.
/// - The `org.nwg.Notifications` interface name doesn't resolve
///   in the parsed `DBusNodeInfo` — same `const`-source
///   provenance as above.
/// - `register_object` fails to build — the object path is a
///   string literal and the interface info just came from the
///   parsed `const`.
fn register_nwg_count_object(
    connection: &gio::DBusConnection,
    state: &Rc<RefCell<NotificationState>>,
    config: &Rc<RefCell<NotificationConfig>>,
    on_state_change: &Rc<dyn Fn()>,
) {
    let node_info = gio::DBusNodeInfo::for_xml(NWG_COUNT_INTROSPECT_XML)
        .expect("Failed to parse nwg-count introspection XML");

    let interface_info = node_info
        .lookup_interface(NWG_COUNT_BUS_NAME)
        .expect("nwg-count interface not found in XML");

    let state = Rc::clone(state);
    let config = Rc::clone(config);
    let on_state_change = Rc::clone(on_state_change);

    connection
        .register_object(NWG_COUNT_OBJECT_PATH, &interface_info)
        .method_call(
            move |_conn, _sender, _path, _iface, method, params, invocation| {
                handle_nwg_count_method(
                    method,
                    &params,
                    invocation,
                    &state,
                    &config,
                    &on_state_change,
                );
            },
        )
        .build()
        .expect("Failed to register nwg-count D-Bus object");
}

fn handle_nwg_count_method(
    method: &str,
    params: &glib::Variant,
    invocation: gio::DBusMethodInvocation,
    state: &Rc<RefCell<NotificationState>>,
    config: &Rc<RefCell<NotificationConfig>>,
    on_state_change: &Rc<dyn Fn()>,
) {
    match method {
        "GetCount" => {
            let count = unread_count_to_u32(state.borrow().unread_count());
            let result = glib::Variant::from((count,));
            invocation.return_value(Some(&result));
        }
        "SetPopupPosition" => {
            handle_set_popup_position(params, invocation, state, config, on_state_change)
        }
        "SetPopupWidth" => handle_set_u32(
            params,
            invocation,
            state,
            config,
            on_state_change,
            "SetPopupWidth",
            "popup_width",
            |raw, cfg| {
                let v = i32::try_from(raw)
                    .map_err(|_| format!("popup-width {raw} exceeds i32::MAX"))?;
                if !(crate::ui::constants::POPUP_WIDTH_MIN..=crate::ui::constants::POPUP_WIDTH_MAX)
                    .contains(&v)
                {
                    return Err(format!(
                        "popup-width {v} is not in {min}..={max}",
                        min = crate::ui::constants::POPUP_WIDTH_MIN,
                        max = crate::ui::constants::POPUP_WIDTH_MAX,
                    ));
                }
                cfg.popup_width = v;
                Ok(())
            },
        ),
        "SetPanelWidth" => handle_set_u32(
            params,
            invocation,
            state,
            config,
            on_state_change,
            "SetPanelWidth",
            "panel_width",
            |raw, cfg| {
                let v = i32::try_from(raw)
                    .map_err(|_| format!("panel-width {raw} exceeds i32::MAX"))?;
                if !(crate::ui::constants::PANEL_WIDTH_MIN..=crate::ui::constants::PANEL_WIDTH_MAX)
                    .contains(&v)
                {
                    return Err(format!(
                        "panel-width {v} is not in {min}..={max}",
                        min = crate::ui::constants::PANEL_WIDTH_MIN,
                        max = crate::ui::constants::PANEL_WIDTH_MAX,
                    ));
                }
                cfg.panel_width = v;
                Ok(())
            },
        ),
        "SetPopupTimeout" => handle_set_u32(
            params,
            invocation,
            state,
            config,
            on_state_change,
            "SetPopupTimeout",
            "popup_timeout",
            |raw, cfg| {
                // 0 is a valid value (means "never auto-dismiss").
                cfg.popup_timeout = u64::from(raw);
                Ok(())
            },
        ),
        "SetMaxPopups" => handle_set_u32(
            params,
            invocation,
            state,
            config,
            on_state_change,
            "SetMaxPopups",
            "max_popups",
            |raw, cfg| {
                if raw == 0 {
                    return Err("max-popups must be >= 1".to_string());
                }
                cfg.max_popups =
                    usize::try_from(raw).expect("u32 fits in usize on every supported target");
                Ok(())
            },
        ),
        "SetMaxHistory" => handle_set_u32(
            params,
            invocation,
            state,
            config,
            on_state_change,
            "SetMaxHistory",
            "max_history",
            |raw, cfg| {
                if raw == 0 {
                    return Err("max-history must be >= 1".to_string());
                }
                cfg.max_history =
                    usize::try_from(raw).expect("u32 fits in usize on every supported target");
                Ok(())
            },
        ),
        _ => {
            log::warn!("Unknown nwg-count D-Bus method: {method}");
            invocation.return_dbus_error(
                "org.freedesktop.DBus.Error.UnknownMethod",
                &format!("Unknown method: {method}"),
            );
        }
    }
}

fn return_invalid_args(invocation: gio::DBusMethodInvocation, msg: &str) {
    invocation.return_dbus_error("org.freedesktop.DBus.Error.InvalidArgs", msg);
}

/// Generic handler for any `u32`-valued live-config setter on
/// `org.nwg.Notifications`. Decodes the first param as `u32`, hands
/// it to the `apply` closure (which validates and writes into
/// `NotificationConfig`), and bridges the result back to the D-Bus
/// invocation: `Ok(())` marks the override, persists the config,
/// returns success and fires `on_state_change`;
/// `Err(msg)` returns `org.freedesktop.DBus.Error.InvalidArgs` with
/// the supplied message.
///
/// `method_name` is used only for the wrong-type error message
/// (e.g. `"SetMaxPopups expects a uint32 argument"`); pass the bare
/// D-Bus method name without quoting.
///
/// `field_name` is the snake_case config field name recorded in
/// `dbus_overrides` so the hot-reload watcher knows to skip it.
#[allow(clippy::too_many_arguments)]
fn handle_set_u32(
    params: &glib::Variant,
    invocation: gio::DBusMethodInvocation,
    state: &Rc<RefCell<NotificationState>>,
    config: &Rc<RefCell<NotificationConfig>>,
    on_state_change: &Rc<dyn Fn()>,
    method_name: &str,
    field_name: &'static str,
    apply: impl FnOnce(u32, &mut NotificationConfig) -> Result<(), String>,
) {
    let raw: u32 = match params.child_value(0).get() {
        Some(v) => v,
        None => {
            return_invalid_args(
                invocation,
                &format!("{method_name} expects a uint32 argument"),
            );
            return;
        }
    };
    let result = {
        let mut cfg = config.borrow_mut();
        apply(raw, &mut cfg)
    };
    match result {
        Ok(()) => {
            state.borrow_mut().mark_dbus_override(field_name);
            persist_config(field_name, &config.borrow());
            invocation.return_value(None);
            on_state_change();
        }
        Err(msg) => return_invalid_args(invocation, &msg),
    }
}

fn handle_set_popup_position(
    params: &glib::Variant,
    invocation: gio::DBusMethodInvocation,
    state: &Rc<RefCell<NotificationState>>,
    config: &Rc<RefCell<NotificationConfig>>,
    on_state_change: &Rc<dyn Fn()>,
) {
    let raw: String = match params.child_value(0).get() {
        Some(s) => s,
        None => {
            return_invalid_args(invocation, "SetPopupPosition expects a string argument");
            return;
        }
    };
    use clap::ValueEnum;
    match crate::config::PopupPosition::from_str(&raw, true) {
        Ok(pos) => {
            config.borrow_mut().popup_position = pos;
            state.borrow_mut().mark_dbus_override("popup_position");
            persist_config("popup_position", &config.borrow());
            invocation.return_value(None);
            on_state_change();
        }
        Err(_) => {
            return_invalid_args(
                invocation,
                &format!(
                    "Invalid popup-position '{raw}'. Expected one of: top-right, top-center, top-left, bottom-right, bottom-center, bottom-left."
                ),
            );
        }
    }
}

fn handle_notify(
    params: &glib::Variant,
    invocation: gio::DBusMethodInvocation,
    state: &Rc<RefCell<NotificationState>>,
    on_notify: &OnNotify,
) {
    // Parse the Notify parameters: (susssasa{sv}i)
    let app_name: String = params.child_value(0).get().unwrap_or_default();
    let replaces_id: u32 = params.child_value(1).get().unwrap_or(0);
    let app_icon: String = params.child_value(2).get().unwrap_or_default();
    let summary: String = params.child_value(3).get().unwrap_or_default();
    let body: String = params.child_value(4).get().unwrap_or_default();
    let timeout: i32 = params.child_value(7).get().unwrap_or(-1);

    // Parse actions array
    let actions_variant = params.child_value(5);
    let actions: Vec<String> = (0..actions_variant.n_children())
        .filter_map(|i| actions_variant.child_value(i).get::<String>())
        .collect();

    // Parse hints dict for urgency and desktop-entry
    let hints_variant = params.child_value(6);
    let urgency = extract_urgency(&hints_variant);
    let desktop_entry = extract_hint::<String>(&hints_variant, "desktop-entry");

    let notif = Notification {
        id: 0, // assigned by state.add/replace
        app_name,
        app_icon,
        summary: clean_markup(&summary),
        body: clean_markup(&body),
        actions: parse_actions(&actions),
        urgency,
        timeout_ms: timeout,
        timestamp: SystemTime::now(),
        read: false,
        desktop_entry,
    };

    log::debug!(
        "Notify: app={}, summary={}, urgency={:?}",
        notif.app_name,
        notif.summary,
        notif.urgency
    );

    let id = state.borrow_mut().replace(replaces_id, notif.clone());

    // Update the notification with the assigned ID for the callback
    let mut notif_with_id = notif;
    notif_with_id.id = id;
    on_notify(&notif_with_id);

    // Return the assigned ID
    let result = glib::Variant::from((id,));
    invocation.return_value(Some(&result));
}

fn handle_close(
    params: &glib::Variant,
    invocation: gio::DBusMethodInvocation,
    state: &Rc<RefCell<NotificationState>>,
    on_close: &OnClose,
) {
    let id: u32 = params.child_value(0).get().unwrap_or(0);
    state.borrow_mut().remove(id);
    on_close(id);
    invocation.return_value(None);
}

fn handle_capabilities(invocation: gio::DBusMethodInvocation) {
    let caps = vec!["body", "body-markup", "actions", "icon-static"];
    let variant = glib::Variant::from((caps,));
    invocation.return_value(Some(&variant));
}

/// Returns the (name, vendor, version, spec_version) tuple reported by the
/// `org.freedesktop.Notifications.GetServerInformation` D-Bus method.
/// Vendor is the daemon's own name (single-vendor project convention);
/// version comes from `Cargo.toml` at compile time so it stays in sync
/// with releases automatically; spec_version tracks the freedesktop
/// notification specification level we implement.
fn server_info_tuple() -> (&'static str, &'static str, &'static str, &'static str) {
    (
        "nwg-notifications",
        "nwg-notifications",
        env!("CARGO_PKG_VERSION"),
        "1.2",
    )
}

fn handle_server_info(invocation: gio::DBusMethodInvocation) {
    let info = server_info_tuple();
    let variant = glib::Variant::from(info);
    invocation.return_value(Some(&variant));
}

/// Emits the ActionInvoked D-Bus signal to the sending app.
pub(crate) fn emit_action_invoked(connection: &gio::DBusConnection, id: u32, action_key: &str) {
    let params = glib::Variant::from((id, action_key));
    if let Err(e) = connection.emit_signal(
        None::<&str>,
        "/org/freedesktop/Notifications",
        "org.freedesktop.Notifications",
        "ActionInvoked",
        Some(&params),
    ) {
        log::warn!("Failed to emit ActionInvoked: {e}");
    }
}

/// Converts a usize unread count to the u32 expected by the
/// `org.nwg.Notifications` wire format. usize on 64-bit hosts is u64, so
/// in theory a count could exceed u32::MAX; in practice `max_history`
/// caps that long before the protocol cares. Logs and clamps to
/// `u32::MAX` if it ever does happen rather than silently truncating.
pub(crate) fn unread_count_to_u32(unread: usize) -> u32 {
    u32::try_from(unread).unwrap_or_else(|_| {
        log::error!("Unread count {unread} exceeds u32::MAX; clamping for D-Bus payload");
        u32::MAX
    })
}

/// Timeout for the `--count` CLI's D-Bus call, in milliseconds.
/// Local D-Bus calls to the running daemon are sub-millisecond when healthy;
/// 2s is generous enough to absorb transient bus contention while keeping
/// the CLI responsive when something is genuinely broken.
const QUERY_COUNT_TIMEOUT_MS: i32 = 2_000;

/// Timeout for the six `--update` D-Bus pushes. Wider than
/// `QUERY_COUNT_TIMEOUT_MS` because the setter path drops `NO_AUTO_START`
/// (a write should auto-spawn the daemon if none is running). On a cold
/// boot the auto-activation chain — D-Bus exec, GTK4 init, layer-shell
/// and name registration, then method dispatch — can take a few hundred
/// ms; 5s gives plenty of headroom while still failing fast on something
/// genuinely broken.
const SETTER_TIMEOUT_MS: i32 = 5_000;

/// Queries the running daemon's `GetCount()` method over the session bus
/// and returns the unread count. Uses `NO_AUTO_START` so it never spawns
/// a daemon — if no daemon is running, this returns an error.
///
/// Used by the `--count` CLI subcommand.
///
/// # Errors
///
/// Returns the underlying `glib::Error` when:
/// - The session bus isn't reachable (no D-Bus, no `DBUS_SESSION_BUS_ADDRESS`).
/// - No daemon owns the `org.nwg.Notifications` name (`NO_AUTO_START` semantics).
/// - The call exceeds `QUERY_COUNT_TIMEOUT_MS`.
/// - The reply payload doesn't unpack to the expected `(u32,)` tuple.
pub(crate) fn query_count_via_dbus() -> Result<u32, glib::Error> {
    let connection = gio::bus_get_sync(gio::BusType::Session, gio::Cancellable::NONE)?;
    let result = connection.call_sync(
        Some(NWG_COUNT_BUS_NAME),
        NWG_COUNT_OBJECT_PATH,
        NWG_COUNT_BUS_NAME,
        "GetCount",
        None,
        None,
        gio::DBusCallFlags::NO_AUTO_START,
        QUERY_COUNT_TIMEOUT_MS,
        gio::Cancellable::NONE,
    )?;
    result.child_value(0).get::<u32>().ok_or_else(|| {
        glib::Error::new(
            gio::IOErrorEnum::InvalidData,
            "GetCount returned unexpected payload type",
        )
    })
}

/// Generic D-Bus client helper used by all six `--update` push wrappers.
/// Unlike `query_count_via_dbus`, this path *allows* auto-activation:
/// `--update` is a write operation, so if no daemon is running the right
/// thing is to spawn one via the `org.nwg.Notifications.service` file,
/// queue the method call, and let it land on the freshly-spawned daemon.
/// The fresh daemon loads `config.json`, accepts the `Set*`, and writes
/// the field back — the *persisted-config* outcome matches an update
/// against an already-running daemon. (Session-only state like active
/// popup queues or accumulated `dbus_overrides` doesn't carry over from
/// a non-existent prior daemon — but `--update` only cares about
/// persistence.) `SETTER_TIMEOUT_MS` (5s) absorbs the cold-spawn
/// latency.
fn call_setter_sync(method: &str, payload: glib::Variant) -> Result<(), glib::Error> {
    let connection = gio::bus_get_sync(gio::BusType::Session, gio::Cancellable::NONE)?;
    connection.call_sync(
        Some(NWG_COUNT_BUS_NAME),
        NWG_COUNT_OBJECT_PATH,
        NWG_COUNT_BUS_NAME,
        method,
        Some(&payload),
        None,
        gio::DBusCallFlags::NONE,
        SETTER_TIMEOUT_MS,
        gio::Cancellable::NONE,
    )?;
    Ok(())
}

/// Pushes a `--popup-position` change to the running daemon via
/// `org.nwg.Notifications.SetPopupPosition`. Used by
/// `nwg-notifications --update --popup-position <value>`.
///
/// # Errors
///
/// Returns the underlying `glib::Error` when:
/// - The session bus isn't reachable.
/// - The daemon isn't running and D-Bus auto-activation can't recover
///   (the `org.nwg.Notifications.service` file is missing, or its
///   `Exec=` path doesn't resolve — see `make install-dbus`).
/// - The daemon rejects the value with
///   `org.freedesktop.DBus.Error.InvalidArgs` (for example, an
///   unrecognised position string).
/// - The daemon's running version doesn't expose `SetPopupPosition`
///   yet — surfaced as `org.freedesktop.DBus.Error.UnknownMethod`,
///   which the CLI's `--update` path translates into the
///   "restart-after-upgrade" hint.
pub(crate) fn push_popup_position(value: &str) -> Result<(), glib::Error> {
    call_setter_sync("SetPopupPosition", glib::Variant::from((value,)))
}

/// Pushes a `--popup-width <px>` change to the running daemon via
/// `org.nwg.Notifications.SetPopupWidth`. Used by
/// `nwg-notifications --update --popup-width <px>`.
///
/// # Errors
///
/// Returns the underlying `glib::Error` when:
/// - The session bus isn't reachable.
/// - The daemon isn't running and D-Bus auto-activation can't recover
///   (the `org.nwg.Notifications.service` file is missing, or its
///   `Exec=` path doesn't resolve — see `make install-dbus`).
/// - The daemon rejects the value with
///   `org.freedesktop.DBus.Error.InvalidArgs` (for example, a value
///   outside the 100..=2000 range).
/// - The daemon's running version doesn't expose `SetPopupWidth`
///   yet — surfaced as `org.freedesktop.DBus.Error.UnknownMethod`.
pub(crate) fn push_popup_width(value: u32) -> Result<(), glib::Error> {
    call_setter_sync("SetPopupWidth", glib::Variant::from((value,)))
}

/// Pushes a `--panel-width <px>` change to the running daemon via
/// `org.nwg.Notifications.SetPanelWidth`. Used by
/// `nwg-notifications --update --panel-width <px>`.
///
/// # Errors
///
/// Returns the underlying `glib::Error` when:
/// - The session bus isn't reachable.
/// - The daemon isn't running and D-Bus auto-activation can't recover
///   (the `org.nwg.Notifications.service` file is missing, or its
///   `Exec=` path doesn't resolve — see `make install-dbus`).
/// - The daemon rejects the value with
///   `org.freedesktop.DBus.Error.InvalidArgs` (for example, a value
///   outside the 200..=2000 range).
/// - The daemon's running version doesn't expose `SetPanelWidth`
///   yet — surfaced as `org.freedesktop.DBus.Error.UnknownMethod`.
pub(crate) fn push_panel_width(value: u32) -> Result<(), glib::Error> {
    call_setter_sync("SetPanelWidth", glib::Variant::from((value,)))
}

/// Pushes a `--popup-timeout <secs>` change to the running daemon via
/// `org.nwg.Notifications.SetPopupTimeout`. Used by
/// `nwg-notifications --update --popup-timeout <secs>`.
///
/// # Errors
///
/// Returns the underlying `glib::Error` when:
/// - The session bus isn't reachable.
/// - The daemon isn't running and D-Bus auto-activation can't recover
///   (the `org.nwg.Notifications.service` file is missing, or its
///   `Exec=` path doesn't resolve — see `make install-dbus`).
/// - The daemon rejects the payload type with
///   `org.freedesktop.DBus.Error.InvalidArgs` (only fires on a
///   non-`u32` payload — `handle_set_popup_timeout` does not enforce
///   a value range, so any `u32` is accepted).
/// - The daemon's running version doesn't expose `SetPopupTimeout`
///   yet — surfaced as `org.freedesktop.DBus.Error.UnknownMethod`.
pub(crate) fn push_popup_timeout(value: u32) -> Result<(), glib::Error> {
    call_setter_sync("SetPopupTimeout", glib::Variant::from((value,)))
}

/// Pushes a `--max-popups <N>` change to the running daemon via
/// `org.nwg.Notifications.SetMaxPopups`. Used by
/// `nwg-notifications --update --max-popups <N>`.
///
/// # Errors
///
/// Returns the underlying `glib::Error` when:
/// - The session bus isn't reachable.
/// - The daemon isn't running and D-Bus auto-activation can't recover
///   (the `org.nwg.Notifications.service` file is missing, or its
///   `Exec=` path doesn't resolve — see `make install-dbus`).
/// - The daemon rejects the value with
///   `org.freedesktop.DBus.Error.InvalidArgs`. `handle_set_max_popups`
///   only rejects two cases: a non-`u32` payload, and the literal
///   value `0` ("max-popups must be >= 1"). No upper bound is enforced
///   daemon-side.
/// - The daemon's running version doesn't expose `SetMaxPopups`
///   yet — surfaced as `org.freedesktop.DBus.Error.UnknownMethod`.
pub(crate) fn push_max_popups(value: u32) -> Result<(), glib::Error> {
    call_setter_sync("SetMaxPopups", glib::Variant::from((value,)))
}

/// Pushes a `--max-history <N>` change to the running daemon via
/// `org.nwg.Notifications.SetMaxHistory`. Used by
/// `nwg-notifications --update --max-history <N>`.
///
/// # Errors
///
/// Returns the underlying `glib::Error` when:
/// - The session bus isn't reachable.
/// - The daemon isn't running and D-Bus auto-activation can't recover
///   (the `org.nwg.Notifications.service` file is missing, or its
///   `Exec=` path doesn't resolve — see `make install-dbus`).
/// - The daemon rejects the value with
///   `org.freedesktop.DBus.Error.InvalidArgs`. `handle_set_max_history`
///   only rejects two cases: a non-`u32` payload, and the literal
///   value `0` ("max-history must be >= 1"). No upper bound is enforced
///   daemon-side.
/// - The daemon's running version doesn't expose `SetMaxHistory`
///   yet — surfaced as `org.freedesktop.DBus.Error.UnknownMethod`.
pub(crate) fn push_max_history(value: u32) -> Result<(), glib::Error> {
    call_setter_sync("SetMaxHistory", glib::Variant::from((value,)))
}

/// Returns true if the given `glib::Error` is the standard D-Bus
/// `org.freedesktop.DBus.Error.UnknownMethod` error class. Used by the
/// `--update` CLI to give an actionable message when the running daemon
/// is from a release older than the CLI and doesn't recognise a method
/// the CLI is trying to call (#25).
pub(crate) fn is_unknown_method_error(err: &glib::Error) -> bool {
    err.matches(gio::DBusError::UnknownMethod)
}

/// Emits CountChanged on the org.nwg.Notifications interface.
///
/// Best-effort: a failure here doesn't affect anything else; we log and move on.
pub(crate) fn emit_count_changed(connection: &gio::DBusConnection, count: u32) {
    let params = glib::Variant::from((count,));
    if let Err(e) = connection.emit_signal(
        None::<&str>,
        NWG_COUNT_OBJECT_PATH,
        NWG_COUNT_BUS_NAME,
        "CountChanged",
        Some(&params),
    ) {
        log::warn!("Failed to emit CountChanged: {e}");
    }
}

/// Looks up `key_name` inside an `a{sv}` hints dict and returns the
/// inner value if present and of the expected type. Generic over the
/// expected value type — both `extract_urgency` and the inline
/// `desktop-entry` extractor in `handle_notify` use it.
///
/// The dict structure is the freedesktop notification spec's
/// `hints` parameter to `Notify`: an array of dict-entries where
/// each entry is `(s, v)` (string key, variant value). The variant
/// value wraps the actual typed payload one level deeper.
fn extract_hint<T>(hints: &glib::Variant, key_name: &str) -> Option<T>
where
    T: glib::variant::FromVariant,
{
    for i in 0..hints.n_children() {
        let entry = hints.child_value(i);
        let key: Option<String> = entry.child_value(0).get();
        if key.as_deref() == Some(key_name) {
            return entry.child_value(1).child_value(0).get::<T>();
        }
    }
    None
}

fn extract_urgency(hints: &glib::Variant) -> Urgency {
    extract_hint::<u8>(hints, "urgency")
        .map(Urgency::from)
        .unwrap_or(Urgency::Normal)
}

/// Atomically writes the just-changed field to the JSON file by
/// loading the current on-disk values, overlaying only `field_name`
/// from the runtime config, and saving the result. This avoids
/// leaking CLI-only session overrides (e.g., `--persist`, `--dnd`)
/// into the file: those fields belong in the JSON schema, but a
/// user passing `--dnd` for one diagnostic run shouldn't have that
/// state baked into config.json forever just because they later
/// pushed an unrelated `SetMaxPopups`.
///
/// On a malformed on-disk file we log + skip the write rather than
/// clobber the user's mid-edit content. On `NotFound` we start from
/// `NotificationConfig::default()` (first-run write where Set* is
/// the very first persistence event). Logs (warn-level) on save
/// failure but doesn't propagate the error — the in-memory
/// mutation already succeeded, so persistence is best-effort.
fn persist_config(field_name: &str, runtime: &crate::config::NotificationConfig) {
    let path = crate::paths::config_path();
    let mut to_save = match crate::config_file::load(&path) {
        Ok(c) => c,
        Err(crate::config_file::ConfigFileError::NotFound) => {
            crate::config::NotificationConfig::default()
        }
        Err(e) => {
            log::warn!(
                "Cannot persist Set* update because config at {} is unreadable: {e}",
                path.display()
            );
            return;
        }
    };
    match field_name {
        "popup_position" => to_save.popup_position = runtime.popup_position,
        "popup_timeout" => to_save.popup_timeout = runtime.popup_timeout,
        "popup_width" => to_save.popup_width = runtime.popup_width,
        "panel_width" => to_save.panel_width = runtime.panel_width,
        "max_popups" => to_save.max_popups = runtime.max_popups,
        "max_history" => to_save.max_history = runtime.max_history,
        _ => {
            log::warn!("persist_config called with unknown field: {field_name}; refusing to write");
            return;
        }
    }
    if let Err(e) = crate::config_file::save(&path, &to_save) {
        log::warn!("Failed to persist Set* update to {}: {e}", path.display());
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn unread_count_to_u32_passes_through_small_values() {
        assert_eq!(unread_count_to_u32(0), 0);
        assert_eq!(unread_count_to_u32(1), 1);
        assert_eq!(unread_count_to_u32(42), 42);
    }

    #[test]
    fn unread_count_to_u32_passes_through_u32_max() {
        // u32::MAX as usize is always representable on every supported target.
        assert_eq!(unread_count_to_u32(u32::MAX as usize), u32::MAX);
    }

    /// Overflow only exists on targets where `usize > u32` (i.e. 64-bit).
    /// On 32-bit hosts `usize` *is* `u32`, so `try_from` can't fail and this
    /// test would be tautological.
    #[cfg(target_pointer_width = "64")]
    #[test]
    fn unread_count_to_u32_clamps_on_overflow() {
        assert_eq!(unread_count_to_u32(u32::MAX as usize + 1), u32::MAX);
        assert_eq!(unread_count_to_u32(usize::MAX), u32::MAX);
    }

    #[test]
    fn is_unknown_method_error_recognises_dbus_unknown_method() {
        let err = glib::Error::new(gio::DBusError::UnknownMethod, "method missing");
        assert!(is_unknown_method_error(&err));
    }

    #[test]
    fn is_unknown_method_error_rejects_other_dbus_errors() {
        let err = glib::Error::new(gio::DBusError::NoMemory, "out of memory");
        assert!(!is_unknown_method_error(&err));
    }

    #[test]
    fn server_info_tuple_uses_cargo_pkg_version() {
        let (name, vendor, version, spec) = server_info_tuple();
        assert_eq!(name, "nwg-notifications");
        assert_eq!(vendor, "nwg-notifications");
        assert_eq!(version, env!("CARGO_PKG_VERSION"));
        assert_eq!(spec, "1.2");
    }

    /// Helper for tests: builds a synthetic `a{sv}` hints variant
    /// with the supplied entries, mirroring what the freedesktop
    /// `Notify` method receives in real life.
    fn build_hints_variant(entries: &[(&str, glib::Variant)]) -> glib::Variant {
        let dict = glib::VariantDict::new(None);
        for (key, value) in entries {
            dict.insert_value(key, value);
        }
        dict.end()
    }

    #[test]
    fn extract_hint_returns_none_for_missing_key() {
        let hints = build_hints_variant(&[]);
        assert_eq!(extract_hint::<u8>(&hints, "urgency"), None);
        assert_eq!(extract_hint::<String>(&hints, "desktop-entry"), None);
    }

    #[test]
    fn extract_hint_returns_none_for_wrong_value_type() {
        // "urgency" present but its value is a string instead of u8.
        let hints = build_hints_variant(&[("urgency", glib::Variant::from("high"))]);
        assert_eq!(extract_hint::<u8>(&hints, "urgency"), None);
    }

    #[test]
    fn extract_urgency_recognises_low_normal_critical() {
        let low = build_hints_variant(&[("urgency", glib::Variant::from(0u8))]);
        let normal = build_hints_variant(&[("urgency", glib::Variant::from(1u8))]);
        let critical = build_hints_variant(&[("urgency", glib::Variant::from(2u8))]);
        assert_eq!(extract_urgency(&low), Urgency::Low);
        assert_eq!(extract_urgency(&normal), Urgency::Normal);
        assert_eq!(extract_urgency(&critical), Urgency::Critical);
        // Missing urgency falls back to Normal per spec.
        let empty = build_hints_variant(&[]);
        assert_eq!(extract_urgency(&empty), Urgency::Normal);
    }

    #[test]
    fn extract_hint_string_returns_well_formed_desktop_entry() {
        let hints = build_hints_variant(&[("desktop-entry", glib::Variant::from("firefox"))]);
        assert_eq!(
            extract_hint::<String>(&hints, "desktop-entry"),
            Some("firefox".to_string())
        );
    }
}