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