1mod 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
31const LINK: WatchMask = WatchMask::DONT_FOLLOW
34 .union(WatchMask::ATTRIB)
35 .union(WatchMask::DELETE_SELF)
36 .union(WatchMask::MOVE_SELF);
37const APPLICATION: &str = "org.freedesktop.Application";
39const SETTLE: Duration = Duration::from_millis(100);
42const MAX_FILE: u64 = 64 * 1024;
44const MAX_ENTRIES: usize = 10_000;
46
47#[derive(Clone, Debug, PartialEq)]
49pub struct DesktopEntry {
50 pub id: String,
53 pub name: String,
55 pub generic_name: String,
57 pub comment: String,
59 pub icon: String,
62 pub exec: String,
65 pub dbus_activatable: bool,
68 pub terminal: bool,
70 pub categories: Vec<String>,
72 pub keywords: Vec<String>,
75 pub no_display: bool,
79 pub startup_wm_class: String,
81 pub working_dir: Option<PathBuf>,
83 pub actions: Vec<DesktopAction>,
86 pub path: PathBuf,
88}
89
90#[derive(Clone, Debug, PartialEq)]
92pub struct DesktopAction {
93 pub id: String,
95 pub name: String,
97 pub icon: String,
99 pub exec: String,
101}
102
103#[derive(Default)]
106pub(crate) struct Sources {
107 pub(crate) dirs: Vec<PathBuf>,
109 pub(crate) desktops: Vec<String>,
111 pub(crate) locale: String,
113 pub(crate) path: Vec<PathBuf>,
116}
117
118impl Sources {
119 pub(crate) fn system() -> Sources {
122 let var = |name| std::env::var_os(name).filter(|value| !value.is_empty());
123 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#[derive(Clone)]
153pub struct DesktopEntries {
154 service: Option<Rc<Service>>,
155 applications: ReadSignal<Vec<DesktopEntry>>,
156}
157
158impl DesktopEntries {
159 pub fn applications(&self) -> ReadSignal<Vec<DesktopEntry>> {
162 self.applications
163 }
164
165 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 pub fn launch(&self, id: &str) {
197 self.launch_with(id, None);
198 }
199
200 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
239fn 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
263fn 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 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
315fn 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
324async 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
364fn 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
386fn 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 let _ = spawn::spawn(shared, &mut command);
434}
435
436pub(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
451pub(crate) struct Service {
453 shared: Rc<Shared>,
454 state: RefCell<Option<State>>,
455 split_logged: RefCell<HashSet<String>>,
457}
458
459struct State {
460 applications: Signal<Vec<DesktopEntry>>,
461 watches: Vec<Watch>,
464 waiting: bool,
466 changed_at: Option<Instant>,
468 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 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 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 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 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 drop(old);
604 set_changed(applications, entries);
605 }
606}
607
608struct Scan<'a> {
610 service: Weak<Service>,
611 shared: &'a Rc<Shared>,
612 sources: &'a Sources,
613 locales: Vec<String>,
614 watches: Vec<Watch>,
615 visited: HashSet<(u64, u64)>,
618 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 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 fn links(&mut self, root: &Path) {
648 let mut paths = vec![root.to_owned()];
649 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 self.watch(&prefix, LINK, |_| true);
666 paths.push(dir.join(target).join(components.as_path()));
667 break;
668 }
669 }
670 }
671
672 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 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 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 paths.sort();
712 for path in paths {
713 match path.metadata() {
715 Ok(meta) if meta.is_dir() => self.dir(root, &path),
716 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 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
764fn 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}