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 command: Vec<String>,
78 pub dbus_activatable: bool,
81 pub terminal: bool,
83 pub categories: Vec<String>,
85 pub keywords: Vec<String>,
88 pub no_display: bool,
92 pub startup_wm_class: String,
94 pub working_dir: Option<PathBuf>,
96 pub actions: Vec<DesktopAction>,
99 pub path: PathBuf,
101}
102
103#[derive(Clone, Debug, PartialEq)]
105pub struct DesktopAction {
106 pub id: String,
108 pub name: String,
110 pub icon: String,
112 pub exec: String,
114}
115
116#[derive(Default)]
119pub(crate) struct Sources {
120 pub(crate) dirs: Vec<PathBuf>,
122 pub(crate) desktops: Vec<String>,
124 pub(crate) locale: String,
126 pub(crate) path: Vec<PathBuf>,
129}
130
131impl Sources {
132 pub(crate) fn system() -> Sources {
135 let var = |name| std::env::var_os(name).filter(|value| !value.is_empty());
136 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#[derive(Clone)]
166pub struct DesktopEntries {
167 service: Option<Rc<Service>>,
168 applications: ReadSignal<Vec<DesktopEntry>>,
169}
170
171impl DesktopEntries {
172 pub fn applications(&self) -> ReadSignal<Vec<DesktopEntry>> {
175 self.applications
176 }
177
178 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 pub fn launch(&self, id: &str) {
210 self.launch_with(id, None);
211 }
212
213 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
252fn 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
276fn 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 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
328fn 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
337async 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
377fn 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
399fn 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 let _ = spawn::spawn(shared, &mut command);
447}
448
449pub(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
464pub(crate) struct Service {
466 shared: Rc<Shared>,
467 state: RefCell<Option<State>>,
468 split_logged: RefCell<HashSet<String>>,
470}
471
472struct State {
473 applications: Signal<Vec<DesktopEntry>>,
474 watches: Vec<Watch>,
477 waiting: bool,
479 changed_at: Option<Instant>,
481 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 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 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 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 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 drop(old);
617 set_changed(applications, entries);
618 }
619}
620
621struct Scan<'a> {
623 service: Weak<Service>,
624 shared: &'a Rc<Shared>,
625 sources: &'a Sources,
626 locales: Vec<String>,
627 watches: Vec<Watch>,
628 visited: HashSet<(u64, u64)>,
631 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 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 fn links(&mut self, root: &Path) {
661 let mut paths = vec![root.to_owned()];
662 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 self.watch(&prefix, LINK, |_| true);
679 paths.push(dir.join(target).join(components.as_path()));
680 break;
681 }
682 }
683 }
684
685 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 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 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 paths.sort();
725 for path in paths {
726 match path.metadata() {
728 Ok(meta) if meta.is_dir() => self.dir(root, &path),
729 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 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
777fn 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}