aboutsummaryrefslogtreecommitdiff
path: root/.config/awesome/quarrel/native/src/lenses/application.rs
blob: cc12e8249bb5d80585e010ea0fd049d31ba16826 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
use std::{
    any::type_name,
    fs::read_dir,
    path::PathBuf,
    sync::{
        Arc,
        OnceLock,
        RwLock,
        atomic::{
            AtomicBool,
            Ordering,
        },
    },
};

use freedesktop_entry_parser as fd;
use mlua::prelude::*;
use notify::RecommendedWatcher;
use rayon::prelude::*;
use url::Url;

use crate::lenses::{
    Cache,
    Entries,
    Entry,
    Lense,
};

static APPS_DIR: &'static str = "/usr/share/applications";
static WATCHER: OnceLock<RecommendedWatcher> = OnceLock::new();

#[derive(Default)]
pub struct Application {
    cache: RwLock<Cache>,
    should_interrupt: AtomicBool,
}

impl Lense for Application {
    const NAME: &str = "Application";
    const PREFIX: Option<&'static str> = None;

    fn init() -> Arc<Self> {
        let this = Arc::new(Application::default());
        let watcher_this = this.clone();
        WATCHER
            .set(
                notify::recommended_watcher(move |event| {
                    match event {
                        Ok(_) => {
                            // We don't care what specifically changed, just that *it did*
                            watcher_this.set_cache(Cache::Stale);
                        }
                        Err(err) => {
                            eprintln!("Watch error: {:?}", err)
                        }
                    }
                })
                .expect("Failed to instantiate a watcher"),
            )
            .expect("Failed to set a watcher");
        this
    }

    #[inline]
    fn set_cache(&self, cache: Cache) {
        if let Err(err) = self.cache.write().map(|mut place| *place = cache) {
            eprintln!(
                "Failed to write cache value for {}: {:?}",
                type_name::<Self>(),
                err
            )
        }
    }

    #[inline]
    fn get_cache(&self) -> Cache {
        match self.cache.read() {
            Ok(ok) => ok.clone(),
            Err(err) => {
                eprintln!(
                    "Failed to read cache value for {}: {:?}",
                    type_name::<Self>(),
                    err
                );
                Cache::Stale
            }
        }
    }

    #[inline]
    fn set_interrupt(&self, interrupt: bool) {
        // self.should_interrupt.store(interrupt, Ordering::Relaxed)
    }

    #[inline]
    fn get_interrupt(&self) -> bool {
        false
        // self.should_interrupt.load(Ordering::Relaxed)
    }

    fn entries(&self, _: &Lua, _: &str) -> Result<Entries, anyhow::Error> {
        let entries = read_dir(APPS_DIR)?
            .map(|result| result.map(|e| e.path()))
            .collect::<Result<Vec<_>, std::io::Error>>()?;

        let parsed_entries: Entries = entries
            .into_par_iter()
            .filter(|path| path.extension().is_some_and(|ext| ext == "desktop"))
            .filter_map(|path| parse_entry(path).ok().flatten())
            .collect::<Vec<Entry>>()
            .into();

        Ok(parsed_entries)
    }
}

fn parse_entry(path: PathBuf) -> Result<Option<Entry>, ()> {
    let Ok(entry) = fd::parse_entry(&path) else {
        return Err(());
    };

    let section = entry.section("Desktop Entry");
    let name = section.attr("Name").ok_or(())?.to_string();

    if section.attr("Type").ok_or(())? != "Application" {
        return Err(());
    }

    if section.attr("OnlyShowIn").is_some()
        || section.attr("Hidden").is_some()
        || section.attr("NoDisplay").is_some()
    {
        return Err(());
    }

    let exec = section.attr("Exec").ok_or(())?.to_string();
    let mut new_exec = exec.clone();
    for (index, _) in exec.match_indices('%') {
        match exec.chars().nth(index + 1).unwrap().to_ascii_lowercase() {
            'i' => {
                if let Some(icon) = section.attr("Icon") {
                    new_exec.replace_range(index..index + 2, &format!("--icon {icon}"));
                }
            }
            'c' => new_exec.replace_range(index..index + 2, &name),
            'k' => new_exec.replace_range(index..index + 2, Url::from_file_path(&path)?.as_str()),

            'f' | 'u' | 'v' | 'm' | 'd' | 'n' => new_exec.replace_range(index..index + 2, ""),
            _ => continue,
        }
    }

    Ok(Some(Entry {
        message: name,
        exec: Some((
            new_exec,
            section
                .attr("Terminal")
                .unwrap_or("false")
                .parse()
                .map_err(drop)?,
        )),
    }))
}