crabshell-services 0.1.0

Crabshell's services, so far the clock, Sway workspaces, audio and the tray
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
//! The system tray: every app's StatusNotifierItem on the session bus.
//!
//! An app's tray icon is an item, an object on the session bus with the
//! `org.kde.StatusNotifierItem` interface. A watcher, the owner of
//! `org.kde.StatusNotifierWatcher`, keeps the list of items, and hosts
//! such as this bar show them. The shell queues for the watcher's name,
//! so it runs the watcher while nobody else does, and otherwise reads the
//! list from the one that runs.
//!
//! Everything runs on the services' executor, on the main thread. One
//! stream reads every message the bus sends this connection, so a quiet
//! bus leaves the shell asleep.

mod menu;
mod watcher;
mod widget;

#[cfg(test)]
mod tests;

use std::cell::RefCell;
use std::future::poll_fn;
use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::rc::Rc;
use std::sync::Once;

use crabshell_reactive::{ReadSignal, Signal};
use crabshell_ui::{Cx, IconPixels, IconSource};
use zbus::export::futures_core::Stream;
use zbus::fdo::{RequestNameFlags, RequestNameReply};
use zbus::message::Type as Kind;
use zbus::names::BusName;
use zbus::{Connection, DeserializeDict, DynamicType, Message, MessageStream, ObjectPath, Type};

use crate::Shared;
use menu::{DBUSMENU, OpenMenu};
pub use menu::{MenuEntry, MenuToggle, TrayMenu};
pub use widget::Tray;

const WATCHER: &str = "org.kde.StatusNotifierWatcher";
const WATCHER_PATH: &str = "/StatusNotifierWatcher";
const ITEM: &str = "org.kde.StatusNotifierItem";
const ITEM_PATH: &str = "/StatusNotifierItem";
const BUS: &str = "org.freedesktop.DBus";
const BUS_PATH: &str = "/org/freedesktop/DBus";
const PROPERTIES: &str = "org.freedesktop.DBus.Properties";

/// The largest pixmap side kept, the same as the renderer's cap.
const MAX_PIXMAP_SIDE: i32 = 512;

/// The most pixmap bytes kept per item: one 512 px pixmap, or a usual
/// set of sizes from 16 to 256 px.
const MAX_PIXMAP_BYTES: usize = 512 * 512 * 4;

/// How long a call to an app or another watcher may take, libdbus's
/// default.
const CALL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(25);

/// Whether a tray item wants to be seen.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TrayStatus {
  /// Nothing to report now, so a bar may hide it.
  Passive,
  /// The usual state.
  #[default]
  Active,
  /// It asks for the user's attention, and shows its attention icon if
  /// it has one.
  NeedsAttention,
}

/// One app's tray icon, as its StatusNotifierItem describes it.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct TrayItem {
  /// Unique while the item is registered: its bus name and object path,
  /// such as `:1.42/StatusNotifierItem`. The key to give
  /// `children_keyed`, and what [`TrayHost::activate`] and the rest take.
  pub id: String,
  /// The app's name for itself, such as `nm-applet`. Two copies of one
  /// app share it.
  pub app_id: String,
  /// A name for the item, such as `Network`.
  pub title: String,
  /// Whether it wants to be seen.
  pub status: TrayStatus,
  /// A freedesktop icon name, or empty.
  pub icon_name: String,
  /// The icon as raw pixels, in each size the app sent, for an item with
  /// no icon name. Each side is at most 512 px.
  pub icon_pixmaps: Vec<IconPixels>,
  /// The icon name to show while it needs attention, or empty.
  pub attention_icon_name: String,
  /// A directory where the app keeps its own icon files, or empty.
  pub icon_theme_path: String,
  /// The tooltip's title, or empty.
  pub tooltip: String,
  /// Whether the item offers only its menu, so a left click opens the
  /// menu instead of calling [`TrayHost::activate`].
  pub item_is_menu: bool,
  /// Where its menu is on the bus, or empty for none. Open it with
  /// [`TrayHost::open_menu`].
  pub menu: String,
}

impl TrayItem {
  /// What to draw at `size` physical pixels, the icon's logical size
  /// times the output's scale. That is the attention icon while the item
  /// needs attention and has one, otherwise its icon name, as a file in
  /// `icon_theme_path` if one is there. An app with an `icon_theme_path`
  /// that lacks the file keeps its icons apart from the theme, so its
  /// pixmaps, if it sent any, come before the name. With no name, it is
  /// the pixmap closest to `size`. `None` when there is nothing to draw.
  pub fn icon(&self, size: u32) -> Option<IconSource> {
    let name = match self.status {
      TrayStatus::NeedsAttention if !self.attention_icon_name.is_empty() => {
        &self.attention_icon_name
      }
      _ => &self.icon_name,
    };
    if let Some(file) = app_icon_file(Path::new(&self.icon_theme_path), name) {
      return Some(IconSource::File(file));
    }
    let closest = self
      .icon_pixmaps
      .iter()
      .min_by_key(|pixels| pixels.width.max(pixels.height).abs_diff(size));
    match closest {
      Some(pixels) if name.is_empty() || !self.icon_theme_path.is_empty() => {
        Some(IconSource::Pixels(pixels.clone()))
      }
      _ => (!name.is_empty()).then(|| IconSource::Name(name.clone())),
    }
  }
}

/// `<dir>/<name>.png` or `.svg`, where Electron apps put their icon.
/// `None` for a relative `dir`, a name that could leave it, or no file.
fn app_icon_file(dir: &Path, name: &str) -> Option<PathBuf> {
  let safe = !matches!(name, "" | "." | "..") && !name.contains(['/', '\0']);
  if !dir.is_absolute() || !safe {
    return None;
  }
  ["png", "svg"]
    .into_iter()
    .map(|extension| dir.join(format!("{name}.{extension}")))
    .find(|path| path.is_file())
}

/// The tray, from `cx.tray()`. A clone is cheap and shares the one
/// connection.
#[derive(Clone)]
pub struct TrayHost {
  /// `None` when the shell provided no services.
  service: Option<Rc<Service>>,
  items: ReadSignal<Vec<TrayItem>>,
  menu: ReadSignal<Option<TrayMenu>>,
}

impl TrayHost {
  /// Every item, in the order they registered. Empty while there is no
  /// session bus. An item shows once its properties are read.
  pub fn items(&self) -> ReadSignal<Vec<TrayItem>> {
    self.items
  }

  /// Tells item `id` it was clicked, as a left click does. A Wayland
  /// client can't know where on screen that was, so the item is told
  /// `(0, 0)`. A refusal or an unknown `id` is logged.
  pub fn activate(&self, id: &str) {
    self.call(id, ITEM, "Activate", (0, 0));
  }

  /// Tells item `id` it was middle-clicked, as for [`activate`](Self::activate).
  pub fn secondary_activate(&self, id: &str) {
    self.call(id, ITEM, "SecondaryActivate", (0, 0));
  }

  /// Tells item `id` the wheel turned `steps`, positive for up, as a
  /// button's `on_scroll` gives them.
  pub fn scroll(&self, id: &str, steps: i32) {
    self.call(id, ITEM, "Scroll", (steps, "vertical"));
  }

  /// The tray menu that is open, if any. One is open at a time: opening
  /// another closes it. It is `None` from [`open_menu`](Self::open_menu)
  /// until the app's layout arrives, and follows the app's changes while
  /// it stays open.
  pub fn menu(&self) -> ReadSignal<Option<TrayMenu>> {
    self.menu
  }

  /// Opens item `id`'s menu: tells the app, as a right click does, then
  /// reads the layout into [`menu`](Self::menu). An item with no menu, or
  /// an unknown `id`, is logged.
  pub fn open_menu(&self, id: &str) {
    if let Some(service) = &self.service {
      service.open_menu(id);
    }
  }

  /// Tells the open menu's app that its submenu `entry` opens, as a
  /// nested popup does. An app that fills submenus only then sends the
  /// entries, and [`menu`](Self::menu) shows them.
  pub fn open_submenu(&self, entry: i32) {
    if let Some(service) = &self.service {
      service.open_submenu(entry);
    }
  }

  /// Closes the open menu and stops following it.
  pub fn close_menu(&self) {
    if let Some(service) = &self.service {
      service.close_menu();
    }
  }

  /// Tells item `id` its menu entry `entry` was clicked. A refusal or an
  /// unknown `id` is logged.
  pub fn menu_event(&self, id: &str, entry: i32) {
    let event = (entry, "clicked", zbus::Variant::from(0), 0u32);
    self.call(id, DBUSMENU, "Event", event);
  }

  /// Calls `method` on item `id`, or on its menu for [`DBUSMENU`],
  /// without waiting for the answer.
  fn call<B>(&self, id: &str, interface: &'static str, method: &'static str, body: B)
  where
    B: serde::Serialize + DynamicType + 'static,
  {
    let target = self.service.as_ref().and_then(|service| {
      let connection = service.state.borrow().as_ref()?.connection.clone()?;
      let at = service.with_entry(id, |entry| {
        let path = match interface {
          ITEM => entry.path.clone(),
          _ => entry.shown.as_ref()?.menu.clone(),
        };
        Some((entry.bus.clone(), path)).filter(|(_, path)| !path.is_empty())
      });
      let (bus, path) = at.flatten()?;
      Some((service, connection, bus, path))
    });
    let Some((service, connection, bus, path)) = target else {
      return tracing::warn!(id, method, "no such tray item");
    };
    let id = id.to_owned();
    let shared = Rc::clone(&service.shared);
    service.shared.spawn(async move {
      let call = connection.call_method(
        Some(bus.as_str()),
        path.as_str(),
        Some(interface),
        method,
        &body,
      );
      if let Err(error) = shared.timeout(CALL_TIMEOUT, call).await {
        tracing::info!(id, method, %error, "the tray item refused");
      }
    });
  }
}

/// `cx.tray()`.
pub(crate) fn tray(cx: &Cx) -> TrayHost {
  let Some(service) = cx.service::<Service>() else {
    static LOGGED: Once = Once::new();
    LOGGED.call_once(|| {
      tracing::warn!("cx.tray() needs the services the shell provides; the tray stays empty");
    });
    return TrayHost {
      service: None,
      items: cx.signal(Vec::new()).read_only(),
      menu: cx.signal(None).read_only(),
    };
  };
  let (items, menu) = service.start();
  TrayHost {
    service: Some(service),
    items,
    menu,
  }
}

/// The tray of one shell, started on first use.
pub(crate) struct Service {
  shared: Rc<Shared>,
  state: RefCell<Option<State>>,
}

struct State {
  items: Signal<Vec<TrayItem>>,
  /// The session bus, once connected.
  connection: Option<Connection>,
  /// Every registered item, in the order they came, read or not.
  entries: Vec<Entry>,
  /// Whether this shell owns the watcher's name.
  watcher: bool,
  /// The open menu's layout, `None` while none is shown.
  menu: Signal<Option<TrayMenu>>,
  /// The open menu, from `open_menu` until `close_menu`.
  open: Option<OpenMenu>,
  /// Counts menu openings and reads, so a task or reply left from an
  /// earlier one never overwrites a newer one.
  menu_count: u64,
}

struct Entry {
  id: String,
  bus: String,
  path: String,
  /// The unique name behind `bus`, which the item's signals come from.
  /// `None` until the bus says.
  owner: Option<String>,
  /// Counts reads, so a slow reply never overwrites a newer one.
  reads: u64,
  /// The item as last read. `None` until a read works.
  shown: Option<TrayItem>,
}

impl Service {
  pub(crate) fn new(shared: Rc<Shared>) -> Service {
    Service {
      shared,
      state: RefCell::new(None),
    }
  }

  /// The list and the open menu, joining the bus if this is the first ask.
  fn start(self: &Rc<Self>) -> (ReadSignal<Vec<TrayItem>>, ReadSignal<Option<TrayMenu>>) {
    if let Some(state) = &*self.state.borrow() {
      return (state.items.read_only(), state.menu.read_only());
    }
    let items = self.shared.root.signal(Vec::new());
    let menu = self.shared.root.signal(None);
    *self.state.borrow_mut() = Some(State {
      items,
      connection: None,
      entries: Vec::new(),
      watcher: false,
      menu,
      open: None,
      menu_count: 0,
    });
    match self.shared.config.session_bus.clone() {
      Some(address) => self.shared.spawn(run(Rc::clone(self), address)),
      None => tracing::info!("no session bus, so the tray is empty"),
    }
    (items.read_only(), menu.read_only())
  }

  /// Whether the list is still there: its owner, the root, isn't disposed.
  fn alive(&self) -> bool {
    let state = self.state.borrow();
    let alive = state
      .as_ref()
      .and_then(|state| state.items.try_with(|_| ()));
    alive.is_some()
  }

  fn is_watcher(&self) -> bool {
    self
      .state
      .borrow()
      .as_ref()
      .is_some_and(|state| state.watcher)
  }

  /// Every registered item's id, read or not, as the watcher lists them.
  fn ids(&self) -> Vec<String> {
    let state = self.state.borrow();
    let entries = state.as_ref().map(|state| state.entries.as_slice());
    entries
      .unwrap_or_default()
      .iter()
      .map(|entry| entry.id.clone())
      .collect()
  }

  fn with_entry<R>(&self, id: &str, f: impl FnOnce(&mut Entry) -> R) -> Option<R> {
    let mut state = self.state.borrow_mut();
    let entry = state
      .as_mut()?
      .entries
      .iter_mut()
      .find(|entry| entry.id == id)?;
    Some(f(entry))
  }

  /// Subscribes to what items and the watcher say, then queues for the
  /// watcher's name and registers as a host.
  async fn join(self: &Rc<Self>, connection: &Connection) -> zbus::Result<()> {
    bus_call(
      connection,
      "AddMatch",
      &format!("type='signal',interface='{ITEM}'"),
    )
    .await?;
    // From the watcher's owner only, so no other app can spoof it.
    let rule = format!("type='signal',sender='{WATCHER}',interface='{WATCHER}'");
    bus_call(connection, "AddMatch", &rule).await?;
    let host = format!("org.kde.StatusNotifierHost-{}", std::process::id());
    connection.request_name(host.as_str()).await?;
    // Queued rather than refused, so the bus hands the name over when
    // another watcher leaves. NameAcquired says so, in `on_signal`.
    let reply = connection
      .request_name_with_flags(WATCHER, RequestNameFlags::empty())
      .await?;
    if reply == RequestNameReply::InQueue {
      // Apart from the message loop, so a frozen watcher can't stall it.
      let (service, connection) = (Rc::clone(self), connection.clone());
      self.shared.spawn(async move {
        if let Err(error) = service.use_watcher(&connection, &host).await {
          tracing::warn!(%error, "the running tray watcher didn't answer");
        }
      });
    }
    Ok(())
  }

  /// Registers with the watcher another program runs, and takes its list.
  async fn use_watcher(self: &Rc<Self>, connection: &Connection, host: &str) -> zbus::Result<()> {
    tracing::info!("another program runs the tray watcher; using it");
    let register = "RegisterStatusNotifierHost";
    let path = WATCHER_PATH;
    let call = connection.call_method(Some(WATCHER), path, Some(WATCHER), register, &host);
    self.shared.timeout(CALL_TIMEOUT, call).await?;
    let get = (WATCHER, "RegisteredStatusNotifierItems");
    let call = connection.call_method(Some(WATCHER), path, Some(PROPERTIES), "Get", &get);
    let reply = self.shared.timeout(CALL_TIMEOUT, call).await?;
    let list: Vec<String> = reply
      .body()
      .deserialize::<zbus::Variant<'_>>()?
      .downcast()?;
    for service in list {
      self.add_registered(connection, &service);
    }
    Ok(())
  }

  /// Acts on one message from the bus.
  async fn on_message(self: &Rc<Self>, connection: &Connection, message: &Message) {
    match message.header().message_type() {
      Kind::MethodCall => watcher::answer(self, connection, message).await,
      Kind::Signal => self.on_signal(connection, message),
      _ => {}
    }
  }

  fn on_signal(self: &Rc<Self>, connection: &Connection, message: &Message) {
    let header = message.header();
    let (Some(interface), Some(member)) = (header.interface(), header.member()) else {
      return;
    };
    let from_bus = header.sender().is_some_and(|sender| sender.as_str() == BUS);
    // The bus sends this connection a broadcast signal only when a match
    // rule picks it, but any app can address one to it directly.
    let broadcast = header.destination().is_none();
    let body = message.body();
    match (interface.as_str(), member.as_str()) {
      (BUS, "NameAcquired") if from_bus && body.deserialize::<&str>().ok() == Some(WATCHER) => {
        self.become_watcher(connection);
      }
      (BUS, "NameOwnerChanged") if from_bus => {
        if let Ok((name, _, owner)) = body.deserialize::<(&str, &str, &str)>() {
          self.owner_changed(connection, name, owner);
        }
      }
      // Ours echo back while this shell is the watcher.
      (WATCHER, "StatusNotifierItemRegistered") if broadcast && !self.is_watcher() => {
        if let Ok(service) = body.deserialize::<&str>() {
          self.add_registered(connection, service);
        }
      }
      (WATCHER, "StatusNotifierItemUnregistered") if broadcast && !self.is_watcher() => {
        if let Ok(id) = body.deserialize::<&str>() {
          self.remove(connection, id);
        }
      }
      (DBUSMENU, "LayoutUpdated" | "ItemsPropertiesUpdated") => {
        if let (Some(sender), Some(path)) = (header.sender(), header.path()) {
          self.menu_changed(connection, sender.as_str(), path.as_str());
        }
      }
      // NewIcon, NewTitle, NewStatus and the rest: read it all again.
      (ITEM, member) if member.starts_with("New") => {
        let (sender, path) = (header.sender(), header.path());
        let (Some(sender), Some(path)) = (sender, path) else {
          return;
        };
        let state = self.state.borrow();
        let entries = state.as_ref().map(|state| state.entries.as_slice());
        let ids: Vec<String> = entries
          .unwrap_or_default()
          .iter()
          .filter(|entry| entry.owner.as_deref() == Some(sender.as_str()))
          .filter(|entry| entry.path == path.as_str())
          .map(|entry| entry.id.clone())
          .collect();
        drop(state);
        for id in ids {
          self.read(connection, id);
        }
      }
      _ => {}
    }
  }

  /// This shell owns the watcher's name now, from the start or after
  /// another watcher left. The items already known stay.
  fn become_watcher(&self, connection: &Connection) {
    tracing::info!("running the tray watcher");
    if let Some(state) = self.state.borrow_mut().as_mut() {
      state.watcher = true;
    }
    self.emit(connection, "StatusNotifierHostRegistered", None);
  }

  /// Adds the item a watcher's list or signal names. A bad name is logged.
  fn add_registered(self: &Rc<Self>, connection: &Connection, service: &str) {
    match parse_service(service, None) {
      Some((bus, path)) => self.add(connection, bus, path),
      None => tracing::warn!(service, "the tray watcher named a bad item; skipped"),
    }
  }

  /// Starts showing the item at `bus` and `path`, unless it is already
  /// there: the bus is asked who owns `bus`, then the item is read.
  fn add(self: &Rc<Self>, connection: &Connection, bus: String, path: String) {
    let id = format!("{bus}{path}");
    let mut state = self.state.borrow_mut();
    let Some(state) = state.as_mut() else {
      return;
    };
    if state.entries.iter().any(|entry| entry.id == id) {
      return;
    }
    state.entries.push(Entry {
      id: id.clone(),
      bus: bus.clone(),
      path,
      owner: None,
      reads: 0,
      shown: None,
    });
    if state.watcher {
      self.emit(connection, "StatusNotifierItemRegistered", Some(id.clone()));
    }
    let service = Rc::clone(self);
    let connection = connection.clone();
    self.shared.spawn(async move {
      // Before asking for the owner, so a leave in between is still seen.
      if let Err(error) = bus_call(&connection, "AddMatch", &owner_rule(&bus)).await {
        tracing::warn!(id, %error, "can't watch a tray item's name");
      }
      let ask = connection.call_method(Some(BUS), BUS_PATH, Some(BUS), "GetNameOwner", &bus);
      let owner = ask
        .await
        .and_then(|reply| reply.body().deserialize::<String>());
      match owner {
        Ok(owner) => {
          service.with_entry(&id, |entry| entry.owner = Some(owner));
          service.read(&connection, id);
        }
        Err(error) => {
          tracing::info!(id, %error, "a tray item left before it was read");
          service.remove(&connection, &id);
        }
      }
    });
  }

  /// Reads item `id`'s properties again and shows them. A failed read is
  /// logged, and the item keeps what it showed.
  fn read(self: &Rc<Self>, connection: &Connection, id: String) {
    let read = self.with_entry(&id, |entry| {
      entry.reads += 1;
      (entry.bus.clone(), entry.path.clone(), entry.reads)
    });
    let Some((bus, path, read)) = read else {
      return;
    };
    let service = Rc::clone(self);
    let connection = connection.clone();
    self.shared.spawn(async move {
      let get_all = connection.call_method(
        Some(bus.as_str()),
        path.as_str(),
        Some(PROPERTIES),
        "GetAll",
        &ITEM,
      );
      let properties = service
        .shared
        .timeout(CALL_TIMEOUT, get_all)
        .await
        .and_then(|reply| reply.body().deserialize::<Properties>());
      let item = match properties {
        Ok(properties) => properties.into_item(id.clone()),
        Err(error) => return tracing::warn!(id, %error, "can't read a tray item"),
      };
      let newest = service.with_entry(&id, |entry| {
        if entry.reads == read {
          entry.shown = Some(item);
        }
      });
      if newest.is_some() {
        service.publish();
      }
    });
  }

  /// A name an item is at got a new owner, or none when it left the bus.
  fn owner_changed(self: &Rc<Self>, connection: &Connection, name: &str, owner: &str) {
    let ids: Vec<String> = {
      let state = self.state.borrow();
      let entries = state.as_ref().map(|state| state.entries.as_slice());
      let at_name = entries
        .unwrap_or_default()
        .iter()
        .filter(|entry| entry.bus == name);
      at_name.map(|entry| entry.id.clone()).collect()
    };
    for id in ids {
      if owner.is_empty() {
        self.remove(connection, &id);
      } else {
        // Its menu's signals now come from the new owner.
        self.close_menu_of(&id);
        self.with_entry(&id, |entry| entry.owner = Some(owner.to_owned()));
        self.read(connection, id);
      }
    }
  }

  /// Stops showing item `id`. One that isn't there is ignored.
  fn remove(&self, connection: &Connection, id: &str) {
    let removed = {
      let mut state = self.state.borrow_mut();
      let Some(state) = state.as_mut() else {
        return;
      };
      let at = state.entries.iter().position(|entry| entry.id == id);
      at.map(|at| (state.entries.remove(at), state.watcher))
    };
    let Some((entry, watcher)) = removed else {
      return;
    };
    self.close_menu_of(id);
    let rule = owner_rule(&entry.bus);
    let bus = connection.clone();
    self.shared.spawn(async move {
      if let Err(error) = bus_call(&bus, "RemoveMatch", &rule).await {
        tracing::debug!(%error, "a tray item's name match was already gone");
      }
    });
    if watcher {
      self.emit(connection, "StatusNotifierItemUnregistered", Some(entry.id));
    }
    self.publish();
  }

  /// Sets the list from the items read so far, if it changed.
  fn publish(&self) {
    let state = self.state.borrow();
    let Some(state) = state.as_ref() else {
      return;
    };
    let list: Vec<TrayItem> = state
      .entries
      .iter()
      .filter_map(|entry| entry.shown.clone())
      .collect();
    if state.items.try_with(|old| *old != list) == Some(true) {
      state.items.set(list);
    }
  }

  /// Empties the list, once the bus is gone.
  fn clear(&self) {
    self.close_menu();
    if let Some(state) = self.state.borrow_mut().as_mut() {
      state.entries.clear();
      state.connection = None;
    }
    self.publish();
  }

  /// Sends one of the watcher's signals, with an item's id or nothing.
  fn emit(&self, connection: &Connection, signal: &'static str, id: Option<String>) {
    let connection = connection.clone();
    self.shared.spawn(async move {
      let sent = match id {
        Some(id) => {
          let emit = connection.emit_signal(None::<&str>, WATCHER_PATH, WATCHER, signal, &id);
          emit.await
        }
        None => {
          let emit = connection.emit_signal(None::<&str>, WATCHER_PATH, WATCHER, signal, &());
          emit.await
        }
      };
      if let Err(error) = sent {
        tracing::warn!(signal, %error, "the tray watcher couldn't send a signal");
      }
    });
  }
}

/// Joins the session bus at `address` and acts on what arrives, until the
/// bus closes or the list is disposed.
async fn run(service: Rc<Service>, address: zbus::Address) {
  // A call to an app that hangs fails after this, instead of keeping its
  // future forever. There is no timer while no call is out.
  let builder = zbus::connection::Builder::address(address);
  let connection = match builder.build().await {
    Ok(connection) => connection,
    Err(error) => {
      return tracing::info!(%error, "can't reach the session bus, so the tray is empty");
    }
  };
  // Made before anything is asked, so no reply or signal is missed.
  let mut messages = MessageStream::from(&connection);
  if let Some(state) = service.state.borrow_mut().as_mut() {
    state.connection = Some(connection.clone());
  }
  if let Err(error) = service.join(&connection).await {
    return tracing::warn!(%error, "couldn't join the tray on the session bus");
  }
  loop {
    let next = poll_fn(|cx| Pin::new(&mut messages).poll_next(cx)).await;
    if !service.alive() {
      return service.clear();
    }
    match next {
      Some(Ok(message)) => service.on_message(&connection, &message).await,
      Some(Err(error)) => tracing::warn!(%error, "a bad message on the session bus"),
      None => break,
    }
  }
  tracing::warn!("the session bus closed, so the tray is empty");
  service.clear();
}

/// Calls the bus itself, such as `AddMatch` with a match rule.
async fn bus_call(connection: &Connection, method: &str, rule: &str) -> zbus::Result<()> {
  let call = connection.call_method(Some(BUS), BUS_PATH, Some(BUS), method, &rule);
  call.await.map(drop)
}

/// The match rule that says when `bus` gets a new owner or none. `bus`
/// is a checked bus name, so it holds no quote.
fn owner_rule(bus: &str) -> String {
  format!("type='signal',sender='{BUS}',interface='{BUS}',member='NameOwnerChanged',arg0='{bus}'")
}

/// The bus name and object path a registration names. A path alone is
/// at `sender`, as Ayatana and Electron apps register. A name alone is at
/// `/StatusNotifierItem`. A watcher's list joins the two, as in
/// `:1.42/org/ayatana/NotificationItem/nm`. `None` for anything else.
fn parse_service(service: &str, sender: Option<&str>) -> Option<(String, String)> {
  let (bus, path) = match service.find('/') {
    Some(0) => (sender?, service),
    Some(at) => service.split_at(at),
    None => (service, ITEM_PATH),
  };
  BusName::try_from(bus).ok()?;
  ObjectPath::try_from(path).ok()?;
  Some((bus.to_owned(), path.to_owned()))
}

/// An icon in the spec's `a(iiay)`: width, height and ARGB32 bytes.
type Pixmaps = Vec<(i32, i32, Vec<u8>)>;

/// The properties an item's `GetAll` returns that the tray reads. One of
/// the wrong type fails the whole read.
#[derive(Default, DeserializeDict, Type)]
#[cfg_attr(test, derive(Clone, zbus::SerializeDict))]
#[zbus(signature = "a{sv}", rename_all = "PascalCase")]
struct Properties {
  id: Option<String>,
  title: Option<String>,
  status: Option<String>,
  icon_name: Option<String>,
  icon_pixmap: Option<Pixmaps>,
  attention_icon_name: Option<String>,
  icon_theme_path: Option<String>,
  /// Icon name, icon pixmaps, title and description.
  tool_tip: Option<(String, Pixmaps, String, String)>,
  item_is_menu: Option<bool>,
  menu: Option<zbus::OwnedObjectPath>,
}

impl Properties {
  fn into_item(self, id: String) -> TrayItem {
    let status = match self.status.as_deref() {
      Some("Passive") => TrayStatus::Passive,
      Some("NeedsAttention") => TrayStatus::NeedsAttention,
      Some("Active") | None => TrayStatus::Active,
      Some(other) => {
        tracing::debug!(
          id,
          status = other,
          "a tray item's status is unknown; taken as Active"
        );
        TrayStatus::Active
      }
    };
    TrayItem {
      icon_pixmaps: pixmaps(&id, self.icon_pixmap.unwrap_or_default()),
      app_id: self.id.unwrap_or_default(),
      title: self.title.unwrap_or_default(),
      status,
      icon_name: self.icon_name.unwrap_or_default(),
      attention_icon_name: self.attention_icon_name.unwrap_or_default(),
      icon_theme_path: self.icon_theme_path.unwrap_or_default(),
      tooltip: self
        .tool_tip
        .map(|(_, _, title, _)| title)
        .unwrap_or_default(),
      item_is_menu: self.item_is_menu.unwrap_or_default(),
      // Some apps name this path for "no menu".
      menu: self
        .menu
        .map(|path| path.to_string())
        .filter(|path| path != "/NO_DBUSMENU")
        .unwrap_or_default(),
      id,
    }
  }
}

/// The pixmaps a bar can draw. One that is empty, over 512 px a side, or
/// whose bytes don't match its size is logged and skipped. The smallest
/// are kept first, up to [`MAX_PIXMAP_BYTES`] in all.
fn pixmaps(id: &str, raw: Pixmaps) -> Vec<IconPixels> {
  let side = 1..=MAX_PIXMAP_SIDE;
  let mut kept: Vec<IconPixels> = raw
    .into_iter()
    .filter_map(|(width, height, data)| {
      let fits = side.contains(&width) && side.contains(&height);
      // Both sides are positive and at most 512, so the casts are exact.
      if !fits || data.len() != width as usize * height as usize * 4 {
        let bytes = data.len();
        tracing::debug!(
          id,
          width,
          height,
          bytes,
          "a tray icon pixmap of a bad size; skipped"
        );
        return None;
      }
      let (width, height) = (width as u32, height as u32);
      Some(IconPixels {
        width,
        height,
        data: data.into(),
      })
    })
    .collect();
  kept.sort_by_key(|pixels| pixels.data.len());
  let mut total = 0;
  kept.retain(|pixels| {
    total += pixels.data.len();
    total <= MAX_PIXMAP_BYTES
  });
  kept
}