1#[cfg(not(windows))]
2pub use cosmic_launch::gpu;
3#[cfg(not(windows))]
4pub use freedesktop_desktop_entry as fde;
5#[cfg(not(windows))]
6pub use mime::Mime;
7use std::path::{Path, PathBuf};
8#[cfg(not(windows))]
9use std::{borrow::Cow, collections::HashSet};
10
11pub trait IconSourceExt {
12 fn as_cosmic_icon(&self) -> crate::widget::icon::Handle;
13}
14
15#[cfg(not(windows))]
16impl IconSourceExt for fde::IconSource {
17 fn as_cosmic_icon(&self) -> crate::widget::icon::Handle {
18 match self {
19 fde::IconSource::Name(name) => crate::widget::icon::from_name(name.as_str())
20 .prefer_svg(true)
21 .size(128)
22 .fallback(Some(crate::widget::icon::IconFallback::Names(vec![
23 "application-default".into(),
24 "application-x-executable".into(),
25 ])))
26 .handle(),
27 fde::IconSource::Path(path) => crate::widget::icon::from_path(path.clone()),
28 }
29 }
30}
31
32#[cfg(not(windows))]
33#[derive(Debug, Clone, PartialEq)]
34pub struct DesktopAction {
35 pub name: String,
36 pub exec: String,
37}
38
39#[cfg(not(windows))]
40#[derive(Debug, Clone, PartialEq, Default)]
41pub struct DesktopEntryData {
42 pub id: String,
43 pub name: String,
44 pub wm_class: Option<String>,
45 pub exec: Option<String>,
46 pub icon: fde::IconSource,
47 pub path: Option<PathBuf>,
48 pub categories: Vec<String>,
49 pub desktop_actions: Vec<DesktopAction>,
50 pub mime_types: Vec<Mime>,
51 pub prefers_dgpu: bool,
52 pub working_directory: Option<String>,
53 pub terminal: bool,
54}
55
56#[cfg(not(windows))]
57impl cosmic_launch::Executable for DesktopEntryData {
58 fn name(&self) -> Cow<'_, str> {
59 Cow::Borrowed(&self.name)
60 }
61
62 fn appid(&self) -> Option<&str> {
63 Some(&self.id)
64 }
65
66 fn exec(&self, action: Option<&str>) -> &str {
67 action.map_or_else(
68 || self.exec.as_deref().unwrap_or_default(),
69 |action| {
70 self.desktop_actions
71 .iter()
72 .find(|a| a.name == action)
73 .map(|action| action.exec.as_str())
74 .unwrap_or_default()
75 },
76 )
77 }
78
79 fn path(&self) -> Option<&str> {
80 self.path.as_ref().and_then(|path| path.to_str())
81 }
82
83 fn working_directory(&self) -> Option<&str> {
84 self.working_directory.as_deref()
85 }
86
87 fn is_terminal(&self) -> bool {
88 self.terminal
89 }
90}
91
92#[cfg(not(windows))]
93#[derive(Debug, Clone)]
94pub struct DesktopEntryCache {
95 locales: Vec<String>,
96 entries: Vec<fde::DesktopEntry>,
97}
98
99#[cfg(not(windows))]
100impl DesktopEntryCache {
101 pub fn new(locales: Vec<String>) -> Self {
102 Self {
103 locales,
104 entries: Vec::new(),
105 }
106 }
107
108 pub fn from_entries(locales: Vec<String>, entries: Vec<fde::DesktopEntry>) -> Self {
109 Self { locales, entries }
110 }
111
112 pub fn ensure_loaded(&mut self) {
113 if self.entries.is_empty() {
114 self.refresh();
115 }
116 }
117
118 pub fn refresh(&mut self) {
119 self.entries = desktop_entries_with_precedence(
120 fde::Iter::new(fde::default_paths())
121 .filter_map(|p| fde::DesktopEntry::from_path(p, Some(&self.locales)).ok()),
122 )
123 .filter(|entry| !entry.hidden())
124 .collect();
125 }
126
127 pub fn insert(&mut self, entry: fde::DesktopEntry) {
128 if self
129 .entries
130 .iter()
131 .any(|existing| existing.id() == entry.id())
132 {
133 return;
134 }
135
136 self.entries.push(entry);
137 }
138
139 pub fn locales(&self) -> &[String] {
140 &self.locales
141 }
142
143 pub fn entries(&self) -> &[fde::DesktopEntry] {
144 &self.entries
145 }
146
147 pub fn entries_mut(&mut self) -> &mut [fde::DesktopEntry] {
148 &mut self.entries
149 }
150}
151
152#[cfg(not(windows))]
153impl Default for DesktopEntryCache {
154 fn default() -> Self {
155 Self::new(Vec::new())
156 }
157}
158
159#[cfg(not(windows))]
160#[derive(Debug, Clone)]
161pub struct DesktopLookupContext<'a> {
162 pub app_id: Cow<'a, str>,
163 pub identifier: Option<Cow<'a, str>>,
164 pub title: Option<Cow<'a, str>>,
165}
166
167#[cfg(not(windows))]
168impl<'a> DesktopLookupContext<'a> {
169 pub fn new(app_id: impl Into<Cow<'a, str>>) -> Self {
170 Self {
171 app_id: app_id.into(),
172 identifier: None,
173 title: None,
174 }
175 }
176
177 pub fn with_identifier(mut self, identifier: impl Into<Cow<'a, str>>) -> Self {
178 self.identifier = Some(identifier.into());
179 self
180 }
181
182 pub fn with_title(mut self, title: impl Into<Cow<'a, str>>) -> Self {
183 self.title = Some(title.into());
184 self
185 }
186}
187
188#[cfg(not(windows))]
189#[derive(Debug, Clone)]
190pub struct DesktopResolveOptions {
191 pub include_no_display: bool,
192 pub xdg_current_desktop: Option<String>,
193}
194
195#[cfg(not(windows))]
196impl Default for DesktopResolveOptions {
197 fn default() -> Self {
198 Self {
199 include_no_display: false,
200 xdg_current_desktop: std::env::var("XDG_CURRENT_DESKTOP").ok(),
201 }
202 }
203}
204
205#[cfg(not(windows))]
206pub fn resolve_desktop_entry(
213 cache: &mut DesktopEntryCache,
214 context: &DesktopLookupContext<'_>,
215 options: &DesktopResolveOptions,
216) -> fde::DesktopEntry {
217 let app_id = fde::unicase::Ascii::new(context.app_id.as_ref());
218 let resolve = |cache: &mut DesktopEntryCache| {
219 if let Some(entry) = fde::find_app_by_id(cache.entries(), app_id) {
220 return Some(entry.clone());
221 }
222
223 let candidate_ids = candidate_desktop_ids(context);
224
225 if let Some(entry) = try_match_cached(cache.entries(), &candidate_ids) {
226 return Some(entry);
227 }
228
229 if let Some(entry) = load_entry_via_app_ids(
230 cache,
231 &candidate_ids,
232 options.include_no_display,
233 options.xdg_current_desktop.as_deref(),
234 ) {
235 cache.insert(entry.clone());
236 return Some(entry);
237 }
238
239 if let Some(entry) = match_startup_wm_class(cache.entries(), context) {
240 return Some(entry);
241 }
242
243 if let Some(entry) = match_crx_id(cache.entries(), context) {
245 return Some(entry);
246 }
247
248 if let Some(entry) = match_exec_basename(cache.entries(), &candidate_ids) {
249 return Some(entry);
250 }
251
252 if let Some(entry) = proton_or_wine_fallback(cache, context) {
253 cache.insert(entry.clone());
254 return Some(entry);
255 }
256
257 None
258 };
259
260 if let Some(entry) = resolve(cache) {
261 return entry.clone();
262 }
263
264 cache.refresh();
265 resolve(cache).unwrap_or_else(|| {
266 let fallback = fallback_entry(context);
267 cache.insert(fallback.clone());
268 fallback
269 })
270}
271
272#[cfg(not(windows))]
273fn try_match_cached(
274 entries: &[fde::DesktopEntry],
275 candidate_ids: &[String],
276) -> Option<fde::DesktopEntry> {
277 candidate_ids.iter().find_map(|candidate| {
278 fde::find_app_by_id(entries, fde::unicase::Ascii::new(candidate.as_str())).cloned()
279 })
280}
281
282#[cfg(not(windows))]
283fn load_entry_via_app_ids(
284 cache: &DesktopEntryCache,
285 candidate_ids: &[String],
286 include_no_display: bool,
287 xdg_current_desktop: Option<&str>,
288) -> Option<fde::DesktopEntry> {
289 if candidate_ids.is_empty() {
290 return None;
291 }
292
293 let candidate_refs: Vec<&str> = candidate_ids.iter().map(String::as_str).collect();
294 let locales = cache.locales().to_vec();
295 let iter_locales = locales.clone();
296
297 let desktop_iter = fde::Iter::new(fde::default_paths())
298 .filter_map(move |path| fde::DesktopEntry::from_path(path, Some(&iter_locales)).ok());
299
300 let app_iter = load_applications_for_app_ids(
301 desktop_iter,
302 &locales,
303 candidate_refs,
304 false,
305 include_no_display,
306 xdg_current_desktop,
307 );
308
309 let locales_for_load = cache.locales().to_vec();
310 for app in app_iter {
311 if let Some(path) = app.path
312 && let Ok(entry) = fde::DesktopEntry::from_path(path, Some(&locales_for_load))
313 {
314 return Some(entry);
315 }
316 }
317
318 None
319}
320
321#[cfg(not(windows))]
322fn match_startup_wm_class(
323 entries: &[fde::DesktopEntry],
324 context: &DesktopLookupContext<'_>,
325) -> Option<fde::DesktopEntry> {
326 let mut candidates = Vec::new();
327 candidates.push(context.app_id.as_ref());
328 if let Some(identifier) = context.identifier.as_deref() {
329 candidates.push(identifier);
330 }
331 if let Some(title) = context.title.as_deref() {
332 candidates.push(title);
333 }
334
335 for entry in entries {
336 let Some(wm_class) = entry.startup_wm_class() else {
337 continue;
338 };
339
340 if candidates
341 .iter()
342 .any(|candidate| candidate.eq_ignore_ascii_case(wm_class))
343 {
344 return Some(entry.clone());
345 }
346 }
347
348 None
349}
350
351#[cfg(not(windows))]
352fn is_crx_id(candidate: &str) -> bool {
353 is_crx_bytes(candidate.as_bytes())
354}
355
356#[cfg(not(windows))]
357fn is_crx_bytes(bytes: &[u8]) -> bool {
358 bytes.len() == 32 && bytes.iter().all(|b| matches!(b, b'a'..=b'p'))
359}
360
361#[cfg(not(windows))]
362pub fn extract_crx_id(value: &str) -> Option<String> {
363 if let Some(rest) = value.strip_prefix("chrome-")
364 && let Some(first) = rest.split(&['-', '_'][..]).next()
365 && is_crx_id(first)
366 {
367 return Some(first.to_string());
368 }
369
370 if let Some(rest) = value.strip_prefix("crx_") {
371 let token = rest
372 .split(|c: char| !c.is_ascii_lowercase())
373 .next()
374 .unwrap_or(rest);
375 if is_crx_id(token) {
376 return Some(token.to_string());
377 }
378 }
379 if is_crx_id(value) {
380 return Some(value.to_string());
381 }
382
383 for window in value.as_bytes().windows(32) {
384 if is_crx_bytes(window) {
385 let slice = std::str::from_utf8(window).expect("ASCII window");
387 return Some(slice.to_string());
388 }
389 }
390
391 None
392}
393
394#[cfg(not(windows))]
395fn match_crx_id(
396 entries: &[fde::DesktopEntry],
397 context: &DesktopLookupContext<'_>,
398) -> Option<fde::DesktopEntry> {
399 let crx = extract_crx_id(context.app_id.as_ref())
400 .or_else(|| context.identifier.as_deref().and_then(extract_crx_id))?;
401
402 for entry in entries {
403 if let Some(exec) = entry.exec()
404 && exec.contains(&format!("--app-id={}", crx))
405 {
406 return Some(entry.clone());
407 }
408 if let Some(wm) = entry.startup_wm_class()
409 && wm.eq_ignore_ascii_case(&format!("crx_{}", crx))
410 {
411 return Some(entry.clone());
412 }
413 if let Some(icon) = entry.icon()
414 && icon.contains(&crx)
415 {
416 return Some(entry.clone());
417 }
418 }
419
420 None
421}
422
423#[cfg(not(windows))]
424fn match_exec_basename(
425 entries: &[fde::DesktopEntry],
426 candidate_ids: &[String],
427) -> Option<fde::DesktopEntry> {
428 fn normalize_candidate(candidate: &str) -> String {
429 candidate
430 .trim_matches(|c: char| c == '"' || c == '\'')
431 .to_ascii_lowercase()
432 }
433
434 let mut normalized: Vec<String> = candidate_ids
435 .iter()
436 .map(|c| normalize_candidate(c))
437 .collect();
438 normalized.retain(|c| !c.is_empty());
439
440 for entry in entries {
441 let Some(exec) = entry.exec() else {
442 continue;
443 };
444
445 let command = exec
446 .split_whitespace()
447 .next()
448 .map(|token| token.trim_matches(|c: char| c == '"' || c == '\''))
449 .filter(|token| !token.is_empty());
450
451 let Some(command) = command else {
452 continue;
453 };
454
455 let command = Path::new(command);
456 let basename = command
457 .file_stem()
458 .or_else(|| command.file_name())
459 .and_then(|s| s.to_str());
460
461 let Some(basename) = basename else {
462 continue;
463 };
464
465 let basename_lower = basename.to_ascii_lowercase();
466 if normalized
467 .iter()
468 .any(|candidate| candidate == &basename_lower)
469 {
470 return Some(entry.clone());
471 }
472 }
473
474 None
475}
476
477#[cfg(not(windows))]
478fn fallback_entry(context: &DesktopLookupContext<'_>) -> fde::DesktopEntry {
479 let mut entry = fde::DesktopEntry {
480 appid: context.app_id.to_string(),
481 groups: Default::default(),
482 path: Default::default(),
483 ubuntu_gettext_domain: None,
484 };
485
486 let name = context
487 .title
488 .as_ref()
489 .map_or_else(|| context.app_id.to_string(), |title| title.to_string());
490 entry.add_desktop_entry("Name".to_string(), name);
491 entry
492}
493
494#[cfg(not(windows))]
495fn proton_or_wine_fallback(
501 cache: &DesktopEntryCache,
502 context: &DesktopLookupContext<'_>,
503) -> Option<fde::DesktopEntry> {
504 let app_id = context.app_id.as_ref();
505 let is_proton_game = app_id == "steam_app_default";
506 let is_wine_entry = std::path::Path::new(app_id)
507 .extension()
508 .is_some_and(|ext| ext.eq_ignore_ascii_case("exe"));
509
510 if !is_proton_game && !is_wine_entry {
511 return None;
512 }
513
514 let title = context.title.as_deref()?;
515
516 for entry in cache.entries() {
517 let localized_name_matches = entry
518 .name(cache.locales())
519 .is_some_and(|name| name == title);
520
521 if !localized_name_matches {
522 continue;
523 }
524
525 if is_proton_game && !entry.categories().unwrap_or_default().contains(&"Game") {
526 continue;
527 }
528
529 return Some(entry.clone());
530 }
531
532 None
533}
534
535#[cfg(not(windows))]
536fn candidate_desktop_ids(context: &DesktopLookupContext<'_>) -> Vec<String> {
537 fn push_candidate(seen: &mut HashSet<String>, ordered: &mut Vec<String>, candidate: &str) {
538 let trimmed = candidate.trim();
539 if trimmed.is_empty() {
540 return;
541 }
542
543 let key = trimmed.to_ascii_lowercase();
544 if seen.insert(key) {
545 ordered.push(trimmed.to_string());
546 }
547 }
548
549 fn add_variants(
550 seen: &mut HashSet<String>,
551 ordered: &mut Vec<String>,
552 value: Option<&str>,
553 suffixes: &[&str],
554 ) {
555 let Some(value) = value else {
556 return;
557 };
558
559 let stripped_quotes = value.trim_matches(|c: char| c == '"' || c == '\'');
560 let trimmed = stripped_quotes.trim();
561 if trimmed.is_empty() {
562 return;
563 }
564
565 push_candidate(seen, ordered, trimmed);
566 if stripped_quotes != trimmed {
567 push_candidate(seen, ordered, stripped_quotes.trim());
568 }
569
570 for suffix in suffixes {
571 if let Some(cut) = trimmed.strip_suffix(suffix) {
572 push_candidate(seen, ordered, cut);
573 }
574 }
575
576 if trimmed.contains('.')
577 && let Some(last) = trimmed.rsplit('.').next()
578 && last.len() >= 2
579 {
580 push_candidate(seen, ordered, last);
581 }
582
583 if trimmed.contains('-') {
584 push_candidate(seen, ordered, &trimmed.replace('-', "_"));
585 }
586 if trimmed.contains('_') {
587 push_candidate(seen, ordered, &trimmed.replace('_', "-"));
588 }
589
590 for token in
591 trimmed.split(|c: char| matches!(c, '.' | '-' | '_' | '@') || c.is_whitespace())
592 {
593 if token.len() >= 2 && token != trimmed {
594 push_candidate(seen, ordered, token);
595 }
596 }
597 }
598
599 const SUFFIXES: &[&str] = &[".desktop", ".Desktop", ".DESKTOP"];
600
601 let mut ordered = Vec::new();
602 let mut seen = HashSet::new();
603
604 add_variants(
605 &mut seen,
606 &mut ordered,
607 Some(context.app_id.as_ref()),
608 SUFFIXES,
609 );
610 add_variants(
611 &mut seen,
612 &mut ordered,
613 context.identifier.as_deref(),
614 SUFFIXES,
615 );
616 add_variants(&mut seen, &mut ordered, context.title.as_deref(), &[]);
617
618 if let Some(app_id) = Some(context.app_id.as_ref()) {
624 if let Some(rest) = app_id.strip_prefix("chrome-")
625 && rest.ends_with("-Default")
626 {
627 let crx = rest.trim_end_matches("-Default");
628 let variants = [
629 format!("org.chromium.Chromium.flextop.chrome-{}-Default", crx),
630 format!("org.chromium.Chromium.chrome-{}-Default", crx),
631 ];
632 for v in variants {
633 push_candidate(&mut seen, &mut ordered, &v);
634 }
635 }
636 if let Some(rest) = app_id.strip_prefix("crx_") {
637 let crx = rest;
639 let variants = [
640 format!("org.chromium.Chromium.flextop.chrome-{}-Default", crx),
641 format!("org.chromium.Chromium.chrome-{}-Default", crx),
642 ];
643 for v in variants {
644 push_candidate(&mut seen, &mut ordered, &v);
645 }
646 }
647 }
648
649 ordered
650}
651
652#[cfg(not(windows))]
653fn desktop_entries_with_precedence<'a>(
654 entries: impl Iterator<Item = fde::DesktopEntry> + 'a,
655) -> impl Iterator<Item = fde::DesktopEntry> + 'a {
656 let mut seen = HashSet::new();
657
658 entries.filter(move |entry| seen.insert(entry.id().to_owned()))
659}
660
661#[cfg(not(windows))]
662pub fn load_applications<'a>(
663 locales: &'a [String],
664 include_no_display: bool,
665 only_show_in: Option<&'a str>,
666) -> impl Iterator<Item = DesktopEntryData> + 'a {
667 desktop_entries_with_precedence(
668 fde::Iter::new(fde::default_paths())
669 .filter_map(move |p| fde::DesktopEntry::from_path(p, Some(locales)).ok()),
670 )
671 .filter(move |de| {
672 !de.hidden()
673 && (include_no_display || !de.no_display())
674 && only_show_in.zip(de.only_show_in()).is_none_or(
675 |(xdg_current_desktop, only_show_in)| only_show_in.contains(&xdg_current_desktop),
676 )
677 && only_show_in.zip(de.not_show_in()).is_none_or(
678 |(xdg_current_desktop, not_show_in)| !not_show_in.contains(&xdg_current_desktop),
679 )
680 })
681 .map(move |de| DesktopEntryData::from_desktop_entry(locales, de))
682}
683
684#[cfg(not(windows))]
686#[auto_enums::auto_enum(Iterator)]
687pub fn load_applications_for_app_ids<'a>(
688 iter: impl Iterator<Item = fde::DesktopEntry> + 'a,
689 locales: &'a [String],
690 app_ids: Vec<&'a str>,
691 fill_missing_ones: bool,
692 include_no_display: bool,
693 only_show_in: Option<&'a str>,
694) -> impl Iterator<Item = DesktopEntryData> + 'a {
695 let app_ids = std::rc::Rc::new(std::cell::RefCell::new(app_ids));
696 let app_ids_ = app_ids.clone();
697
698 let applications = desktop_entries_with_precedence(iter)
699 .filter(move |de| {
700 let position = {
704 let requested = app_ids.borrow();
705
706 requested
707 .iter()
708 .position(|id| de.matches_id(fde::unicase::Ascii::new(*id)))
709 .or_else(|| {
710 requested
711 .iter()
712 .position(|id| de.matches_name(fde::unicase::Ascii::new(*id)))
713 })
714 };
715
716 let Some(position) = position else {
717 return false;
718 };
719
720 app_ids.borrow_mut().remove(position);
721
722 if de.hidden() {
723 return false;
724 }
725
726 if !include_no_display && de.no_display() {
727 return false;
728 }
729
730 if only_show_in.zip(de.only_show_in()).is_some_and(
731 |(xdg_current_desktop, only_show_in)| !only_show_in.contains(&xdg_current_desktop),
732 ) {
733 return false;
734 }
735
736 if only_show_in.zip(de.not_show_in()).is_some_and(
737 |(xdg_current_desktop, not_show_in)| not_show_in.contains(&xdg_current_desktop),
738 ) {
739 return false;
740 }
741
742 true
743 })
744 .map(move |de| DesktopEntryData::from_desktop_entry(locales, de));
745
746 if fill_missing_ones {
747 applications.chain(
748 std::iter::once_with(move || {
749 std::mem::take(&mut *app_ids_.borrow_mut())
750 .into_iter()
751 .map(|app_id| DesktopEntryData {
752 id: app_id.to_string(),
753 name: app_id.to_string(),
754 icon: fde::IconSource::default(),
755 ..Default::default()
756 })
757 })
758 .flatten(),
759 )
760 } else {
761 applications
762 }
763}
764
765#[cfg(not(windows))]
766pub fn load_desktop_file(locales: &[String], path: PathBuf) -> Option<DesktopEntryData> {
767 fde::DesktopEntry::from_path(path, Some(locales))
768 .ok()
769 .map(|de| DesktopEntryData::from_desktop_entry(locales, de))
770}
771
772#[cfg(not(windows))]
773impl DesktopEntryData {
774 pub fn from_desktop_entry(locales: &[String], de: fde::DesktopEntry) -> DesktopEntryData {
775 let name = de
776 .name(locales)
777 .unwrap_or(Cow::Borrowed(&de.appid))
778 .to_string();
779
780 let icon = fde::IconSource::from_unknown(de.icon().unwrap_or(&de.appid));
782
783 DesktopEntryData {
784 id: de.appid.to_string(),
785 wm_class: de.startup_wm_class().map(ToString::to_string),
786 exec: de.exec().map(ToString::to_string),
787 working_directory: de.path().map(ToString::to_string),
788 name,
789 icon,
790 categories: de
791 .categories()
792 .unwrap_or_default()
793 .into_iter()
794 .map(std::string::ToString::to_string)
795 .collect(),
796 desktop_actions: de
797 .actions()
798 .map(|actions| {
799 actions
800 .into_iter()
801 .filter_map(|action| {
802 let name = de.action_entry_localized(action, "Name", locales);
803 let exec = de.action_entry(action, "Exec");
804 if let (Some(name), Some(exec)) = (name, exec) {
805 Some(DesktopAction {
806 name: name.to_string(),
807 exec: exec.to_string(),
808 })
809 } else {
810 None
811 }
812 })
813 .collect::<Vec<_>>()
814 })
815 .unwrap_or_default(),
816 mime_types: de
817 .mime_type()
818 .map(|mime_types| {
819 mime_types
820 .into_iter()
821 .filter_map(|mime_type| mime_type.parse::<Mime>().ok())
822 .collect::<Vec<_>>()
823 })
824 .unwrap_or_default(),
825 prefers_dgpu: de.prefers_non_default_gpu(),
826 terminal: de.terminal(),
827 path: Some(de.path),
828 }
829 }
830}
831
832#[cfg(all(test, not(windows)))]
833mod tests {
834 use super::*;
835 use std::path::Path;
836 use std::{env, fs};
837 use tempfile::tempdir;
838
839 struct EnvVarGuard {
840 key: &'static str,
841 original: Option<String>,
842 }
843
844 impl EnvVarGuard {
845 fn set(key: &'static str, value: &Path) -> Self {
846 let original = env::var(key).ok();
847 unsafe { std::env::set_var(key, value) };
850 Self { key, original }
851 }
852 }
853
854 impl Drop for EnvVarGuard {
855 fn drop(&mut self) {
856 if let Some(ref original) = self.original {
857 unsafe { std::env::set_var(self.key, original) };
858 } else {
859 unsafe { std::env::remove_var(self.key) };
860 }
861 }
862 }
863
864 fn load_entry(file_name: &str, contents: &str, locales: &[String]) -> fde::DesktopEntry {
865 let temp = tempdir().expect("tempdir");
866 let path = temp.path().join(file_name);
867 fs::write(&path, contents).expect("write desktop file");
868 let entry = fde::DesktopEntry::from_path(path, Some(locales)).expect("load desktop file");
869 temp.close().expect("close tempdir");
871 entry
872 }
873
874 #[test]
875 fn desktop_entry_precedence_prefers_first_entry() {
876 let locales = vec!["en_US.UTF-8".to_string()];
877
878 let user_entry = load_entry(
879 "com.example.App.desktop",
880 "[Desktop Entry]\n\
881 Type=Application\n\
882 Name=User Application\n\
883 Exec=user-application\n",
884 &locales,
885 );
886
887 let system_entry = load_entry(
888 "com.example.App.desktop",
889 "[Desktop Entry]\n\
890 Type=Application\n\
891 Name=System Application\n\
892 Exec=system-application\n",
893 &locales,
894 );
895
896 let entries = desktop_entries_with_precedence(vec![user_entry, system_entry].into_iter())
897 .collect::<Vec<_>>();
898
899 assert_eq!(entries.len(), 1);
900 assert_eq!(entries[0].exec(), Some("user-application"));
901 }
902
903 #[test]
904 fn hidden_override_masks_system_entry_without_fallback() {
905 let locales = vec!["en_US.UTF-8".to_string()];
906
907 let user_entry = load_entry(
908 "com.example.App.desktop",
909 "[Desktop Entry]\n\
910 Type=Application\n\
911 Name=Example Application\n\
912 Hidden=true\n",
913 &locales,
914 );
915
916 let system_entry = load_entry(
917 "com.example.App.desktop",
918 "[Desktop Entry]\n\
919 Type=Application\n\
920 Name=Example Application\n\
921 Exec=system-application\n",
922 &locales,
923 );
924
925 let applications = load_applications_for_app_ids(
926 vec![user_entry, system_entry].into_iter(),
927 &locales,
928 vec!["com.example.App"],
929 true,
930 false,
931 Some("COSMIC"),
932 )
933 .collect::<Vec<_>>();
934
935 assert!(applications.is_empty());
936 }
937
938 #[test]
939 fn no_display_override_masks_system_entry() {
940 let locales = vec!["en_US.UTF-8".to_string()];
941
942 let user_entry = load_entry(
943 "com.example.App.desktop",
944 "[Desktop Entry]\n\
945 Type=Application\n\
946 Name=User Application\n\
947 Exec=user-application\n\
948 NoDisplay=true\n",
949 &locales,
950 );
951
952 let system_entry = load_entry(
953 "com.example.App.desktop",
954 "[Desktop Entry]\n\
955 Type=Application\n\
956 Name=System Application\n\
957 Exec=system-application\n",
958 &locales,
959 );
960
961 let hidden_from_menu = load_applications_for_app_ids(
962 vec![user_entry.clone(), system_entry.clone()].into_iter(),
963 &locales,
964 vec!["com.example.App"],
965 true,
966 false,
967 Some("COSMIC"),
968 )
969 .collect::<Vec<_>>();
970
971 assert!(hidden_from_menu.is_empty());
972
973 let included_when_requested = load_applications_for_app_ids(
974 vec![user_entry, system_entry].into_iter(),
975 &locales,
976 vec!["com.example.App"],
977 true,
978 true,
979 Some("COSMIC"),
980 )
981 .collect::<Vec<_>>();
982
983 assert_eq!(included_when_requested.len(), 1);
984 assert_eq!(
985 included_when_requested[0].exec.as_deref(),
986 Some("user-application")
987 );
988 }
989
990 #[test]
991 fn not_show_in_override_masks_system_entry_for_cosmic() {
992 let locales = vec!["en_US.UTF-8".to_string()];
993
994 let user_entry = load_entry(
995 "com.example.App.desktop",
996 "[Desktop Entry]\n\
997 Type=Application\n\
998 Name=User Application\n\
999 Exec=user-application\n\
1000 NotShowIn=COSMIC;\n",
1001 &locales,
1002 );
1003
1004 let system_entry = load_entry(
1005 "com.example.App.desktop",
1006 "[Desktop Entry]\n\
1007 Type=Application\n\
1008 Name=System Application\n\
1009 Exec=system-application\n",
1010 &locales,
1011 );
1012
1013 let hidden_in_cosmic = load_applications_for_app_ids(
1014 vec![user_entry.clone(), system_entry.clone()].into_iter(),
1015 &locales,
1016 vec!["com.example.App"],
1017 true,
1018 false,
1019 Some("COSMIC"),
1020 )
1021 .collect::<Vec<_>>();
1022
1023 assert!(hidden_in_cosmic.is_empty());
1024
1025 let visible_in_gnome = load_applications_for_app_ids(
1026 vec![user_entry, system_entry].into_iter(),
1027 &locales,
1028 vec!["com.example.App"],
1029 true,
1030 false,
1031 Some("GNOME"),
1032 )
1033 .collect::<Vec<_>>();
1034
1035 assert_eq!(visible_in_gnome.len(), 1);
1036 assert_eq!(
1037 visible_in_gnome[0].exec.as_deref(),
1038 Some("user-application")
1039 );
1040 }
1041
1042 #[test]
1043 fn candidate_generation_covers_common_variants() {
1044 let ctx = DesktopLookupContext::new("com.example.App.desktop")
1045 .with_identifier("com-example-App")
1046 .with_title("Example App");
1047 let candidates = candidate_desktop_ids(&ctx);
1048
1049 assert_eq!(candidates.first().unwrap(), "com.example.App.desktop");
1050 for test in [
1051 "com.example.App",
1052 "com-example-App",
1053 "com_example_App",
1054 "Example App",
1055 "Example",
1056 "App",
1057 ] {
1058 assert!(candidates.iter().any(|c| c.eq_ignore_ascii_case(test)),);
1059 }
1060 }
1061
1062 #[test]
1063 fn startup_wm_class_matching_detects_flatpak_chrome_apps() {
1064 let temp = tempdir().expect("tempdir");
1065 let apps_dir = temp.path().join("applications");
1066 fs::create_dir_all(&apps_dir).expect("create applications dir");
1067
1068 let desktop_contents = "\
1069[Desktop Entry]
1070Version=1.0
1071Type=Application
1072Name=Proton Mail
1073Exec=chromium --app-id=jnpecgipniidlgicjocehkhajgdnjekh
1074Icon=chrome-jnpecgipniidlgicjocehkhajgdnjekh-Default
1075StartupWMClass=crx_jnpecgipniidlgicjocehkhajgdnjekh
1076";
1077 let desktop_path = apps_dir.join(
1078 "org.chromium.Chromium.flextop.chrome-jnpecgipniidlgicjocehkhajgdnjekh-Default.desktop",
1079 );
1080 fs::write(desktop_path, desktop_contents).expect("write desktop file");
1081
1082 let _guard = EnvVarGuard::set("XDG_DATA_HOME", temp.path());
1083
1084 let locales = vec!["en_US.UTF-8".to_string()];
1085 let mut cache = DesktopEntryCache::new(locales.clone());
1086 cache.refresh();
1087
1088 let ctx = DesktopLookupContext::new("crx_jnpecgipniidlgicjocehkhajgdnjekh");
1089 let resolved = resolve_desktop_entry(&mut cache, &ctx, &DesktopResolveOptions::default());
1090
1091 assert_eq!(
1092 resolved.id(),
1093 "org.chromium.Chromium.flextop.chrome-jnpecgipniidlgicjocehkhajgdnjekh-Default"
1094 );
1095 }
1096
1097 #[test]
1098 fn exec_basename_matching_handles_vmware() {
1099 let temp = tempdir().expect("tempdir");
1100 let apps_dir = temp.path().join("applications");
1101 fs::create_dir_all(&apps_dir).expect("create applications dir");
1102
1103 let desktop_contents = r#"[Desktop Entry]
1104Version=1.0
1105Type=Application
1106Name=VMware Workstation
1107Exec=/usr/bin/vmware %U
1108Icon=vmware-workstation
1109"#;
1110 let desktop_path = apps_dir.join("vmware-workstation.desktop");
1111 fs::write(desktop_path, desktop_contents).expect("write desktop file");
1112
1113 let _guard = EnvVarGuard::set("XDG_DATA_HOME", temp.path());
1114
1115 let locales = vec!["en_US.UTF-8".to_string()];
1116 let mut cache = DesktopEntryCache::new(locales.clone());
1117 cache.refresh();
1118
1119 let ctx = DesktopLookupContext::new("vmware").with_title("Library — VMware Workstation");
1120
1121 let resolved = resolve_desktop_entry(&mut cache, &ctx, &DesktopResolveOptions::default());
1122
1123 assert_eq!(resolved.id(), "vmware-workstation");
1124 }
1125
1126 #[test]
1127 fn proton_fallback_prefers_game_entries() {
1128 let locales = vec!["en_US.UTF-8".to_string()];
1129 let entry = load_entry(
1130 "proton.desktop",
1131 "[Desktop Entry]\nType=Application\nName=Proton Game\nCategories=Game;Utility;\nExec=proton-game\n",
1132 &locales,
1133 );
1134 let cache = DesktopEntryCache::from_entries(locales.clone(), vec![entry]);
1135 let ctx = DesktopLookupContext::new("steam_app_default").with_title("Proton Game");
1136
1137 let resolved = proton_or_wine_fallback(&cache, &ctx).expect("expected proton match");
1138 let name = resolved
1139 .name(&locales)
1140 .expect("name available")
1141 .into_owned();
1142
1143 assert_eq!(name, "Proton Game");
1144 }
1145
1146 #[test]
1147 fn proton_fallback_skips_non_games() {
1148 let locales = vec!["en_US.UTF-8".to_string()];
1149 let entry = load_entry(
1150 "tool.desktop",
1151 "[Desktop Entry]\nType=Application\nName=Proton Tool\nCategories=Utility;\nExec=proton-tool\n",
1152 &locales,
1153 );
1154 let cache = DesktopEntryCache::from_entries(locales, vec![entry]);
1155 let ctx = DesktopLookupContext::new("steam_app_default").with_title("Proton Tool");
1156
1157 assert!(proton_or_wine_fallback(&cache, &ctx).is_none());
1158 }
1159
1160 #[test]
1161 fn wine_fallback_matches_executable_titles() {
1162 let locales = vec!["en_US.UTF-8".to_string()];
1163 let entry = load_entry(
1164 "wine.desktop",
1165 "[Desktop Entry]\nType=Application\nName=Wine Game\nExec=wine-game\n",
1166 &locales,
1167 );
1168 let cache = DesktopEntryCache::from_entries(locales.clone(), vec![entry]);
1169 let ctx = DesktopLookupContext::new("WINEGAME.EXE").with_title("Wine Game");
1170
1171 let resolved = proton_or_wine_fallback(&cache, &ctx).expect("expected wine match");
1172 let name = resolved
1173 .name(&locales)
1174 .expect("name available")
1175 .into_owned();
1176 assert_eq!(name, "Wine Game");
1177 }
1178
1179 #[test]
1180 fn fallback_entry_uses_title_when_available() {
1181 let ctx = DesktopLookupContext::new("unknown-app").with_title("Unknown App");
1182 let entry = fallback_entry(&ctx);
1183
1184 assert_eq!(entry.id(), "unknown-app");
1185 assert_eq!(
1186 entry.name(&["en_US".to_string()]),
1187 Some(Cow::Owned("Unknown App".to_string()))
1188 );
1189 }
1190
1191 #[test]
1192 fn desktop_entry_data_prefers_localized_name() {
1193 let locales = vec!["fr".to_string(), "en_US".to_string()];
1194 let entry = load_entry(
1195 "localized.desktop",
1196 "[Desktop Entry]\nType=Application\nName=Default\nName[fr]=Localisé\nExec=localized\n",
1197 &locales,
1198 );
1199 let data = DesktopEntryData::from_desktop_entry(&locales, entry);
1200
1201 assert_eq!(data.name, "Localisé");
1202 }
1203
1204 #[test]
1205 fn crx_id_extraction_variants() {
1206 let id = "cadlkienfkclaiaibeoongdcgmdikeeg"; assert_eq!(
1208 super::extract_crx_id(&format!("chrome-{}-Default", id)),
1209 Some(id.to_string())
1210 );
1211 assert_eq!(
1212 super::extract_crx_id(&format!("crx_{}", id)),
1213 Some(id.to_string())
1214 );
1215 assert_eq!(super::extract_crx_id(id), Some(id.to_string()));
1216 let embedded = format!("org.chromium.Chromium.flextop.chrome-{}-Default", id);
1218 assert_eq!(super::extract_crx_id(&embedded), Some(id.to_string()));
1219 }
1220
1221 #[test]
1222 fn crx_matcher_by_exec_and_wmclass() {
1223 let locales = vec!["en_US.UTF-8".to_string()];
1224 let id = "cadlkienfkclaiaibeoongdcgmdikeeg";
1225 let mut cache = DesktopEntryCache::new(locales.clone());
1226 cache.insert(fde::DesktopEntry::from_str(
1227 "org.chromium.Chromium.flextop.chrome-cadlkienfkclaiaibeoongdcgmdikeeg-Default.desktop",
1228 &format!(
1229 r#"[Desktop Entry]
1230Type=Application
1231Name=Example
1232Exec=chromium --app-id={id} --profile-directory=Default
1233StartupWMClass=crx_{id}
1234Icon=chrome-{id}-Default
1235"#
1236 ),
1237 Some(&locales),
1238 )
1239 .unwrap());
1240
1241 let short_id = format!("chrome-{}-Default", id);
1242 let ctx = DesktopLookupContext::new(short_id);
1243 let resolved = resolve_desktop_entry(&mut cache, &ctx, &DesktopResolveOptions::default());
1244 assert!(resolved.exec().is_some());
1245 assert!(resolved.icon().is_some());
1246 let expected = format!("crx_{}", id);
1247 assert_eq!(resolved.startup_wm_class(), Some(expected.as_str()));
1248 }
1249
1250 #[test]
1251 fn crx_extraction_handles_utf8_prefixes() {
1252 let id = "cadlkienfkclaiaibeoongdcgmdikeeg";
1253 let prefixed = format!("å{}", id);
1254 assert_eq!(super::extract_crx_id(&prefixed), Some(id.to_string()));
1255 }
1256
1257 #[test]
1258 fn crx_extraction_ignores_non_ascii_sequences() {
1259 let id = "cadlkienfkclaiaibeoongdcgmdikeeg";
1260 let embedded = format!("{id}æøå");
1261
1262 assert_eq!(super::extract_crx_id(&embedded), Some(id.to_string()));
1263 assert_eq!(super::extract_crx_id("æøå"), None);
1264 }
1265}