Skip to main content

crabshell_services/
desktop_entries.rs

1//! The installed applications, from their desktop entries: what a
2//! launcher lists, and where a window's app id finds its icon.
3
4mod parse;
5#[cfg(test)]
6mod tests;
7
8use std::cell::RefCell;
9use std::collections::{HashMap, HashSet};
10use std::ffi::OsStr;
11use std::fs::File;
12use std::io::Read;
13use std::os::unix::fs::MetadataExt;
14use std::path::{Path, PathBuf};
15use std::process::Command;
16use std::rc::{Rc, Weak};
17use std::sync::Once;
18use std::time::{Duration, Instant};
19
20use calloop::timer::TimeoutAction;
21use crabshell_reactive::{ReadSignal, Signal, untrack};
22use crabshell_ui::Cx;
23use inotify::{EventMask, WatchMask};
24use zbus::OwnedObjectPath;
25use zbus::names::WellKnownName;
26
27use crate::dbus::{CALL_TIMEOUT, set_changed};
28use crate::watch::{self, Change, Watch};
29use crate::{Shared, activation, spawn};
30
31/// What a link's own watch hears: its last name going, as a link renamed
32/// over it takes it, and the link itself removed or moved.
33const LINK: WatchMask = WatchMask::DONT_FOLLOW
34  .union(WatchMask::ATTRIB)
35  .union(WatchMask::DELETE_SELF)
36  .union(WatchMask::MOVE_SELF);
37/// The interface a D-Bus activatable application is started through.
38const APPLICATION: &str = "org.freedesktop.Application";
39/// How long the files stay still after a change before the list is read
40/// again, so a package manager that writes many reads it once.
41const SETTLE: Duration = Duration::from_millis(100);
42/// The largest desktop file read.
43const MAX_FILE: u64 = 64 * 1024;
44/// The most desktop files read. The rest are left out.
45const MAX_ENTRIES: usize = 10_000;
46
47/// An installed application, from its desktop entry.
48#[derive(Clone, Debug, PartialEq)]
49pub struct DesktopEntry {
50  /// Its desktop file ID: the file's path under `applications/`, with
51  /// `/` as `-` and without `.desktop`, such as `org.gnome.Nautilus`.
52  pub id: String,
53  /// Its name, in the user's language when the file has it.
54  pub name: String,
55  /// What kind of program it is, such as `Web Browser`, or `""`.
56  pub generic_name: String,
57  /// A line about it, for a tooltip, or `""`.
58  pub comment: String,
59  /// Its icon, a name in the icon theme or a file's path as the entry
60  /// writes it, or `""`.
61  pub icon: String,
62  /// What it runs, as its `Exec` key writes it, field codes such as `%U`
63  /// and quotes included. `""` for one only D-Bus starts.
64  pub exec: String,
65  /// Whether it is started over D-Bus, from `DBusActivatable`, with
66  /// `exec` only for when that fails.
67  pub dbus_activatable: bool,
68  /// Whether it runs in a terminal.
69  pub terminal: bool,
70  /// Its categories, such as `Network` and `WebBrowser`.
71  pub categories: Vec<String>,
72  /// More words a search may match, in the user's language when the
73  /// file has them.
74  pub keywords: Vec<String>,
75  /// Whether a launcher leaves it out: for `NoDisplay`, or because
76  /// `OnlyShowIn` or `NotShowIn` leave out this desktop. A window's icon
77  /// may still come from it.
78  pub no_display: bool,
79  /// The window class its windows have, if the entry says, or `""`.
80  pub startup_wm_class: String,
81  /// The directory it runs in, if not the shell's.
82  pub working_dir: Option<PathBuf>,
83  /// What else it can do, such as open a private window, in the
84  /// entry's order.
85  pub actions: Vec<DesktopAction>,
86  /// The desktop file it was read from.
87  pub path: PathBuf,
88}
89
90/// Something more an application can do, as a launcher's menu offers it.
91#[derive(Clone, Debug, PartialEq)]
92pub struct DesktopAction {
93  /// Its name in the desktop file, such as `new-window`.
94  pub id: String,
95  /// What a menu shows, in the user's language when the file has it.
96  pub name: String,
97  /// Its icon, as [`DesktopEntry::icon`], or `""`.
98  pub icon: String,
99  /// What it runs, as [`DesktopEntry::exec`].
100  pub exec: String,
101}
102
103/// Where the desktop entries are, and what picks among them. Tests point
104/// it at their own directories.
105#[derive(Default)]
106pub(crate) struct Sources {
107  /// Each `applications` directory, the user's first.
108  pub(crate) dirs: Vec<PathBuf>,
109  /// The desktops `XDG_CURRENT_DESKTOP` names, such as `sway`.
110  pub(crate) desktops: Vec<String>,
111  /// The locale for messages, from `LC_ALL`, `LC_MESSAGES` or `LANG`.
112  pub(crate) locale: String,
113  /// `PATH`'s directories, where `TryExec` and `xdg-terminal-exec` are
114  /// looked for.
115  pub(crate) path: Vec<PathBuf>,
116}
117
118impl Sources {
119  /// The user's: the XDG data directories, `XDG_CURRENT_DESKTOP`, the
120  /// locale and `PATH`.
121  pub(crate) fn system() -> Sources {
122    let var = |name| std::env::var_os(name).filter(|value| !value.is_empty());
123    // The XDG spec ignores relative paths.
124    let home = var("XDG_DATA_HOME")
125      .map(PathBuf::from)
126      .filter(|dir| dir.is_absolute())
127      .or_else(|| var("HOME").map(|home| PathBuf::from(home).join(".local/share")));
128    let data_dirs = var("XDG_DATA_DIRS").unwrap_or_else(|| "/usr/local/share:/usr/share".into());
129    let dirs = home.into_iter().chain(std::env::split_paths(&data_dirs));
130    let desktops = std::env::var("XDG_CURRENT_DESKTOP").unwrap_or_default();
131    let locale = ["LC_ALL", "LC_MESSAGES", "LANG"]
132      .into_iter()
133      .find_map(|name| std::env::var(name).ok().filter(|value| !value.is_empty()));
134    Sources {
135      dirs: dirs
136        .filter(|dir| dir.is_absolute())
137        .map(|dir| dir.join("applications"))
138        .collect(),
139      desktops: desktops
140        .split(':')
141        .filter(|desktop| !desktop.is_empty())
142        .map(str::to_owned)
143        .collect(),
144      locale: locale.unwrap_or_default(),
145      path: var("PATH").map_or_else(Vec::new, |path| std::env::split_paths(&path).collect()),
146    }
147  }
148}
149
150/// The installed applications, from `cx.desktop_entries()`. Cloning it
151/// is cheap.
152#[derive(Clone)]
153pub struct DesktopEntries {
154  service: Option<Rc<Service>>,
155  applications: ReadSignal<Vec<DesktopEntry>>,
156}
157
158impl DesktopEntries {
159  /// Every application, sorted by name ignoring case, then by ID. Empty
160  /// until the loop's next turn after the first `cx.desktop_entries()`.
161  pub fn applications(&self) -> ReadSignal<Vec<DesktopEntry>> {
162    self.applications
163  }
164
165  /// The application a window's app id names, as a task bar finds the
166  /// window's icon: the one with that ID, else one whose ID differs only
167  /// in case, else one whose `StartupWMClass` matches ignoring case,
168  /// else one whose ID ends in that part after a dot, as
169  /// `org.gnome.Nautilus` does for `nautilus`. It reads the list as
170  /// `get` does, so a binding that calls it runs again when the list
171  /// changes.
172  pub fn lookup(&self, app_id: &str) -> Option<DesktopEntry> {
173    let found = self
174      .applications
175      .try_with(|apps| lookup(apps, app_id).cloned());
176    found.flatten()
177  }
178
179  /// Starts the application with ID `id`, on its own: in a process
180  /// group of its own, with no input or output, and in its `working_dir`
181  /// if it has one. A terminal app runs through `xdg-terminal-exec`. One
182  /// that is [`dbus_activatable`](DesktopEntry::dbus_activatable) is
183  /// called with `org.freedesktop.Application.Activate` on the session
184  /// bus, which starts it if it isn't running, and runs its `Exec` if
185  /// that fails. What can't start is logged: an unknown ID, a malformed
186  /// `Exec`, a terminal app without `xdg-terminal-exec` on `PATH`, and a
187  /// D-Bus app that didn't start with no `Exec` to fall back on.
188  ///
189  /// When the compositor hands out activation tokens, the shell asks for
190  /// one first, with the app's ID and the last click or key press on its
191  /// windows, and starts the app once it comes, or after 100 ms without
192  /// one. The token goes in `XDG_ACTIVATION_TOKEN` and
193  /// `DESKTOP_STARTUP_ID` for `Exec`, and in the platform data's
194  /// `activation-token` and `desktop-startup-id` over D-Bus, so the
195  /// compositor may focus the app's window.
196  pub fn launch(&self, id: &str) {
197    self.launch_with(id, None);
198  }
199
200  /// Starts one of an application's actions, named by its
201  /// [`DesktopAction::id`], as [`launch`](Self::launch) does, a D-Bus
202  /// app's with `ActivateAction`.
203  pub fn launch_action(&self, id: &str, action: &str) {
204    self.launch_with(id, Some(action));
205  }
206
207  fn launch_with(&self, id: &str, action: Option<&str>) {
208    let Some(service) = &self.service else {
209      return;
210    };
211    let find = |apps: &Vec<DesktopEntry>| apps.iter().find(|app| app.id == id).cloned();
212    match untrack(|| self.applications.try_with(find)).flatten() {
213      Some(app) => launch(service, &app, action),
214      None => tracing::warn!(id, "no application has this ID, so nothing starts"),
215    }
216  }
217}
218
219fn lookup<'a>(apps: &'a [DesktopEntry], app_id: &str) -> Option<&'a DesktopEntry> {
220  if app_id.is_empty() {
221    return None;
222  }
223  let last_part = |app: &&DesktopEntry| {
224    let part = app.id.rsplit('.').next();
225    part.is_some_and(|part| part.eq_ignore_ascii_case(app_id))
226  };
227  apps
228    .iter()
229    .find(|app| app.id == app_id)
230    .or_else(|| apps.iter().find(|app| app.id.eq_ignore_ascii_case(app_id)))
231    .or_else(|| {
232      apps
233        .iter()
234        .find(|app| app.startup_wm_class.eq_ignore_ascii_case(app_id))
235    })
236    .or_else(|| apps.iter().find(last_part))
237}
238
239/// Starts `app`, or its `action`, apart from the shell: over D-Bus if
240/// it says so, falling back to its `Exec`.
241fn launch(service: &Rc<Service>, app: &DesktopEntry, action: Option<&str>) {
242  let id = app.id.as_str();
243  let exec = match action {
244    None => &app.exec,
245    Some(action) => match app.actions.iter().find(|found| found.id == action) {
246      Some(found) => &found.exec,
247      None => {
248        return tracing::warn!(
249          id,
250          action,
251          "the application has no such action, so nothing starts"
252        );
253      }
254    },
255  };
256  let (shared, then) = (&service.shared, Rc::clone(service));
257  let (app, exec, action) = (app.clone(), exec.clone(), action.map(str::to_owned));
258  activation::with_token(shared, Some(id), move |token| {
259    start(&then, app, exec, action, token);
260  });
261}
262
263/// Starts `app` with `exec`, or with its `action` over D-Bus, given the
264/// activation token `token` if one came.
265fn start(
266  service: &Rc<Service>,
267  app: DesktopEntry,
268  exec: String,
269  action: Option<String>,
270  token: Option<String>,
271) {
272  let id = app.id.as_str();
273  if !app.dbus_activatable {
274    return run(service, &app, &exec, token.as_deref());
275  }
276  let Some(path) = object_path(id) else {
277    tracing::warn!(
278      id,
279      "the application's ID isn't a D-Bus name, so it can't start over D-Bus"
280    );
281    return run(service, &app, &exec, token.as_deref());
282  };
283  let Some(address) = service.shared.config.session_bus.clone() else {
284    tracing::warn!(id, "no session bus to start the application over D-Bus");
285    return run(service, &app, &exec, token.as_deref());
286  };
287  let service = Rc::clone(service);
288  let shared = Rc::clone(&service.shared);
289  shared.spawn(async move {
290    let token = token.as_deref();
291    let activated = activate(
292      &service.shared,
293      address,
294      &app.id,
295      path,
296      action.as_deref(),
297      token,
298    );
299    match activated.await {
300      Ok(()) => {}
301      Err((error, true)) => {
302        tracing::warn!(id = app.id, %error, "couldn't start the application over D-Bus");
303        run(&service, &app, &exec, token);
304      }
305      // It may have started all the same, and a second would open twice.
306      Err((error, false)) => tracing::warn!(
307        id = app.id,
308        %error,
309        "the application didn't answer its start over D-Bus; not running its Exec"
310      ),
311    }
312  });
313}
314
315/// The object path of the application with ID `id`, as the Desktop
316/// Entry Specification derives it, or `None` when `id` isn't a D-Bus
317/// well-known name.
318fn object_path(id: &str) -> Option<OwnedObjectPath> {
319  WellKnownName::try_from(id).ok()?;
320  let path = format!("/{}", id.replace('.', "/").replace('-', "_"));
321  OwnedObjectPath::try_from(path).ok()
322}
323
324/// Calls `Activate`, or `ActivateAction` for `action`, on the
325/// application `id` at `path` on the session bus, which starts it first
326/// if it isn't running, with the activation `token` in its platform
327/// data. An error comes with whether the call surely never reached the
328/// app: no bus, or a refusal from the bus or from an app without that
329/// object or method.
330async fn activate(
331  shared: &Shared,
332  address: zbus::Address,
333  id: &str,
334  path: OwnedObjectPath,
335  action: Option<&str>,
336  token: Option<&str>,
337) -> Result<(), (zbus::Error, bool)> {
338  let built = zbus::connection::Builder::address(address).build().await;
339  let connection = built.map_err(|error| (error, true))?;
340  let mut platform_data = HashMap::<&str, zbus::Variant<'_>>::new();
341  if let Some(token) = token {
342    platform_data.insert("activation-token", token.into());
343    platform_data.insert("desktop-startup-id", token.into());
344  }
345  let (destination, interface) = (Some(id), Some(APPLICATION));
346  let reply = match action {
347    None => {
348      let body = (platform_data,);
349      let call = connection.call_method(destination, &path, interface, "Activate", &body);
350      shared.timeout(CALL_TIMEOUT, call).await
351    }
352    Some(action) => {
353      let body = (action, Vec::<zbus::Variant<'_>>::new(), platform_data);
354      let call = connection.call_method(destination, &path, interface, "ActivateAction", &body);
355      shared.timeout(CALL_TIMEOUT, call).await
356    }
357  };
358  reply.map(drop).map_err(|error| {
359    let refused = refused(&error);
360    (error, refused)
361  })
362}
363
364/// Whether `error` says the call reached no app: no one owns the name,
365/// and the bus can't start one, or the app has no such object or method.
366fn refused(error: &zbus::Error) -> bool {
367  const REFUSALS: [&str; 4] = [
368    "org.freedesktop.DBus.Error.ServiceUnknown",
369    "org.freedesktop.DBus.Error.NameHasNoOwner",
370    "org.freedesktop.DBus.Error.UnknownObject",
371    "org.freedesktop.DBus.Error.UnknownMethod",
372  ];
373  match error {
374    zbus::Error::MethodError(name, _, _) => REFUSALS.contains(&name.as_str()),
375    zbus::Error::FDO(error) => matches!(
376      **error,
377      zbus::fdo::Error::ServiceUnknown(_)
378        | zbus::fdo::Error::NameHasNoOwner(_)
379        | zbus::fdo::Error::UnknownObject(_)
380        | zbus::fdo::Error::UnknownMethod(_)
381    ),
382    _ => false,
383  }
384}
385
386/// Runs `exec`, `app`'s or one of its actions', apart from the shell,
387/// with the activation `token` if one came.
388fn run(service: &Service, app: &DesktopEntry, exec: &str, token: Option<&str>) {
389  let (id, shared) = (app.id.as_str(), &service.shared);
390  if exec.is_empty() {
391    return tracing::warn!(
392      id,
393      "the application has no Exec to fall back on, so nothing starts"
394    );
395  }
396  let argv = match parse::command_line(exec, app) {
397    Ok(argv) => argv,
398    Err(why) => return tracing::warn!(id, exec, why, "a malformed Exec, so nothing starts"),
399  };
400  if let Err(why) = parse::split_exec(exec)
401    && service.split_logged.borrow_mut().insert(id.to_owned())
402  {
403    tracing::info!(
404      id,
405      exec,
406      why,
407      "an Exec the spec refuses, split as a shell would"
408    );
409  }
410  let mut command = if app.terminal {
411    let path = &shared.config.desktop_entries.path;
412    let Some(terminal) = parse::find("xdg-terminal-exec", path) else {
413      return tracing::warn!(
414        id,
415        "a terminal application, and xdg-terminal-exec isn't on PATH, so nothing starts"
416      );
417    };
418    let mut command = Command::new(terminal);
419    command.args(&argv);
420    command
421  } else {
422    let mut command = Command::new(&argv[0]);
423    command.args(&argv[1..]);
424    command
425  };
426  if let Some(dir) = &app.working_dir {
427    command.current_dir(dir);
428  }
429  if let Some(token) = token {
430    activation::set_env(&mut command, token);
431  }
432  // A failure is logged there.
433  let _ = spawn::spawn(shared, &mut command);
434}
435
436/// `cx.desktop_entries()`.
437pub(crate) fn desktop_entries(cx: &Cx) -> DesktopEntries {
438  let Some(service) = cx.service::<Service>() else {
439    static LOGGED: Once = Once::new();
440    LOGGED.call_once(|| {
441      tracing::warn!("cx.desktop_entries() needs the services the shell provides; it stays empty");
442    });
443    return DesktopEntries {
444      service: None,
445      applications: cx.signal(Vec::new()).read_only(),
446    };
447  };
448  service.start()
449}
450
451/// The desktop entries of one shell, read from the first ask.
452pub(crate) struct Service {
453  shared: Rc<Shared>,
454  state: RefCell<Option<State>>,
455  /// The IDs whose `Exec` was split as a shell would, each logged once.
456  split_logged: RefCell<HashSet<String>>,
457}
458
459struct State {
460  applications: Signal<Vec<DesktopEntry>>,
461  /// A watch on each directory read, and on the parent of each
462  /// `applications` directory that isn't there yet.
463  watches: Vec<Watch>,
464  /// Whether a read waits on a timer.
465  waiting: bool,
466  /// The last change heard while a read waits.
467  changed_at: Option<Instant>,
468  /// The caps logged so far, as each is logged once.
469  logged: Logged,
470}
471
472#[derive(Clone, Copy, Default)]
473struct Logged {
474  big: bool,
475  long: bool,
476  many: bool,
477}
478
479impl Service {
480  pub(crate) fn new(shared: Rc<Shared>) -> Service {
481    Service {
482      shared,
483      state: RefCell::new(None),
484      split_logged: RefCell::default(),
485    }
486  }
487
488  fn start(self: &Rc<Self>) -> DesktopEntries {
489    let started = self.state.borrow().as_ref().map(|state| state.applications);
490    let applications = started.unwrap_or_else(|| {
491      let applications = self.shared.root.signal(Vec::new());
492      *self.state.borrow_mut() = Some(State {
493        applications,
494        watches: Vec::new(),
495        waiting: false,
496        changed_at: None,
497        logged: Logged::default(),
498      });
499      self.read_later();
500      applications
501    });
502    DesktopEntries {
503      service: Some(Rc::clone(self)),
504      applications: applications.read_only(),
505    }
506  }
507
508  /// Something changed in a watched directory.
509  fn changed(self: &Rc<Self>) {
510    let waiting = {
511      let mut state = self.state.borrow_mut();
512      let Some(state) = state.as_mut() else {
513        return;
514      };
515      state.changed_at = Some(Instant::now());
516      state.waiting
517    };
518    if !waiting {
519      self.read_later();
520    }
521  }
522
523  /// Reads the list on the loop's next turn, or [`SETTLE`] after the
524  /// last change, on one timer that moves while changes come.
525  fn read_later(self: &Rc<Self>) {
526    let Some(event_loop) = self.shared.event_loop() else {
527      return;
528    };
529    let settled = |state: &State| state.changed_at.map(|at| at + SETTLE);
530    let at = {
531      let mut state = self.state.borrow_mut();
532      let Some(state) = state.as_mut() else {
533        return;
534      };
535      state.waiting = true;
536      settled(state).unwrap_or_else(Instant::now)
537    };
538    let service = Rc::clone(self);
539    let tick = Box::new(move || {
540      let at = service.state.borrow().as_ref().and_then(settled);
541      match at {
542        Some(at) if at > Instant::now() => TimeoutAction::ToInstant(at),
543        _ => {
544          service.read();
545          TimeoutAction::Drop
546        }
547      }
548    });
549    if event_loop.insert_timer(at, tick).is_none()
550      && let Some(state) = self.state.borrow_mut().as_mut()
551    {
552      state.waiting = false;
553    }
554  }
555
556  /// Reads every directory and shows what it holds.
557  fn read(self: &Rc<Self>) {
558    let (applications, logged) = {
559      let mut state = self.state.borrow_mut();
560      let Some(state) = state.as_mut() else {
561        return;
562      };
563      state.waiting = false;
564      state.changed_at = None;
565      (state.applications, state.logged)
566    };
567    // Gone with the shell.
568    if applications.try_with(|_| ()).is_none() {
569      return;
570    }
571    let sources = &self.shared.config.desktop_entries;
572    let mut scan = Scan {
573      service: Rc::downgrade(self),
574      shared: &self.shared,
575      sources,
576      locales: parse::locales(&sources.locale),
577      watches: Vec::new(),
578      visited: HashSet::new(),
579      seen: HashSet::new(),
580      entries: Vec::new(),
581      logged,
582    };
583    for root in &sources.dirs {
584      scan.root(root);
585    }
586    let Scan {
587      mut entries,
588      watches,
589      logged,
590      ..
591    } = scan;
592    entries.sort_by_cached_key(|app| (app.name.to_lowercase(), app.id.clone()));
593    let old = {
594      let mut state = self.state.borrow_mut();
595      let Some(state) = state.as_mut() else {
596        return;
597      };
598      state.logged = logged;
599      std::mem::replace(&mut state.watches, watches)
600    };
601    // After the new ones, so a directory still there keeps its kernel
602    // watch.
603    drop(old);
604    set_changed(applications, entries);
605  }
606}
607
608/// One read of every directory.
609struct Scan<'a> {
610  service: Weak<Service>,
611  shared: &'a Rc<Shared>,
612  sources: &'a Sources,
613  locales: Vec<String>,
614  watches: Vec<Watch>,
615  /// Each directory read, by device and inode, so one listed twice or
616  /// reached again through a link is read once.
617  visited: HashSet<(u64, u64)>,
618  /// Each ID found so far, since the first file with an ID decides it.
619  seen: HashSet<String>,
620  entries: Vec<DesktopEntry>,
621  logged: Logged,
622}
623
624impl Scan<'_> {
625  fn root(&mut self, root: &Path) {
626    self.links(root);
627    if root.is_dir() {
628      return self.dir(root, root);
629    }
630    // Watched for the directory to appear.
631    if let (Some(parent), Some(name)) = (
632      root.parent().filter(|parent| parent.is_dir()),
633      root.file_name(),
634    ) {
635      let name = name.to_owned();
636      self.watch(parent, watch::DIRECTORY, move |change| {
637        change.name.as_ref().is_none_or(|changed| *changed == name)
638      });
639    }
640  }
641
642  /// Watches each link on the way to `root`, and on the way to what each
643  /// names, so a link swapped for another, as a NixOS profile is, reads
644  /// the list again. The link itself is watched, not the directory that
645  /// holds it, which may be `$HOME`: renamed over, the old link loses its
646  /// last name, and the read watches the new one.
647  fn links(&mut self, root: &Path) {
648    let mut paths = vec![root.to_owned()];
649    // As many as the kernel follows before it calls it a loop.
650    let mut links = 0;
651    while let Some(path) = paths.pop() {
652      let mut prefix = PathBuf::new();
653      let mut components = path.components();
654      while let Some(component) = components.next() {
655        prefix.push(component);
656        let Ok(target) = std::fs::read_link(&prefix) else {
657          continue;
658        };
659        links += 1;
660        let (Some(dir), true) = (prefix.parent(), links <= 40) else {
661          return;
662        };
663        // shortcut: a directory swapped in for the link since `read_link`
664        // would get this mask in place of its own; nothing gives it back.
665        self.watch(&prefix, LINK, |_| true);
666        paths.push(dir.join(target).join(components.as_path()));
667        break;
668      }
669    }
670  }
671
672  /// Reads the list again on each change `mask` names at `path` that
673  /// `counts`.
674  fn watch(&mut self, path: &Path, mask: WatchMask, counts: impl Fn(&Change) -> bool + 'static) {
675    let service = self.service.clone();
676    let on_change = move |change: &Change| {
677      if let Some(service) = service.upgrade().filter(|_| counts(change)) {
678        service.changed();
679      }
680    };
681    match watch::watch(self.shared, path, mask, on_change) {
682      Ok(watch) => self.watches.push(watch),
683      Err(error) => {
684        tracing::warn!(%error, path = %path.display(), "can't watch a directory of applications or a link on the way")
685      }
686    }
687  }
688
689  fn dir(&mut self, root: &Path, dir: &Path) {
690    let Ok(meta) = dir.metadata() else {
691      return;
692    };
693    if !self.visited.insert((meta.dev(), meta.ino())) {
694      return;
695    }
696    // Before the read, so a change during it is heard.
697    self.watch(dir, watch::DIRECTORY, |change| {
698      let name = change.name.as_ref().map(Path::new);
699      let entry = name.is_some_and(|name| name.extension() == Some(OsStr::new("desktop")));
700      // A link made or removed carries no ISDIR, and may lead to a
701      // directory: anything but a written file or a cache counts.
702      let linked = !change.mask.contains(EventMask::CLOSE_WRITE)
703        && name.is_some_and(|name| name.extension() != Some(OsStr::new("cache")));
704      name.is_none() || entry || linked || change.mask.contains(EventMask::ISDIR)
705    });
706    let Ok(read) = std::fs::read_dir(dir) else {
707      return;
708    };
709    let mut paths: Vec<PathBuf> = read.flatten().map(|entry| entry.path()).collect();
710    // So the same file wins each time when two make one ID.
711    paths.sort();
712    for path in paths {
713      // Followed through links, as packages often link their entries in.
714      match path.metadata() {
715        Ok(meta) if meta.is_dir() => self.dir(root, &path),
716        // A regular file only: opening a FIFO would wait for a writer.
717        Ok(meta) if meta.is_file() && path.extension() == Some(OsStr::new("desktop")) => {
718          self.file(root, &path);
719        }
720        _ => {}
721      }
722    }
723  }
724
725  fn file(&mut self, root: &Path, path: &Path) {
726    // A path that isn't UTF-8 has no ID.
727    let Some(id) = id(root, path) else {
728      return;
729    };
730    if self.seen.contains(&id) {
731      return;
732    }
733    let shown = path.display();
734    if self.seen.len() == MAX_ENTRIES {
735      if !std::mem::replace(&mut self.logged.many, true) {
736        tracing::warn!(path = %shown, "over {MAX_ENTRIES} desktop entries; the rest are left out");
737      }
738      return;
739    }
740    self.seen.insert(id.clone());
741    let mut bytes = Vec::new();
742    let read = File::open(path).and_then(|file| file.take(MAX_FILE + 1).read_to_end(&mut bytes));
743    if let Err(error) = read {
744      return tracing::info!(%error, path = %shown, "can't read a desktop entry");
745    }
746    if bytes.len() as u64 > MAX_FILE {
747      if !std::mem::replace(&mut self.logged.big, true) {
748        tracing::warn!(path = %shown, "a desktop entry over 64 KiB is left out");
749      }
750      return;
751    }
752    let Ok(text) = String::from_utf8(bytes) else {
753      return tracing::info!(path = %shown, "a desktop entry that isn't UTF-8 is left out");
754    };
755    let (groups, long) = parse::groups(&text);
756    if long && !std::mem::replace(&mut self.logged.long, true) {
757      tracing::warn!(path = %shown, "a line over 4 KiB in a desktop entry is left out");
758    }
759    let entry = parse::entry(id, path.to_owned(), &groups, self.sources, &self.locales);
760    self.entries.extend(entry);
761  }
762}
763
764/// The desktop file ID of `path` under `root`: `kde4/konsole.desktop`
765/// is `kde4-konsole`.
766fn id(root: &Path, path: &Path) -> Option<String> {
767  let relative = path.strip_prefix(root).ok()?.to_str()?;
768  Some(relative.strip_suffix(".desktop")?.replace('/', "-"))
769}