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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
// Copyright 2021 System76 <info@system76.com>
// SPDX-License-Identifier: MPL-2.0

use std::{
    borrow::Cow,
    collections::BTreeMap,
    fs::File,
    io::{self, BufRead},
    path::{Path, PathBuf},
};

use crate::DesktopEntry;
use crate::{Groups, LocaleMap};
use thiserror::Error;

#[derive(Debug, Error)]
pub enum DecodeError {
    #[error("path does not contain a valid app ID")]
    AppID,
    #[error(transparent)]
    Io(#[from] std::io::Error),
}

impl<'a> DesktopEntry<'a> {
    pub fn from_str<L>(
        path: &'a Path,
        input: &'a str,
        locales: &[L],
    ) -> Result<DesktopEntry<'a>, DecodeError>
    where
        L: AsRef<str>,
    {
        let appid = get_app_id(path)?;

        let mut groups = Groups::new();
        let mut active_group = Cow::Borrowed("");
        let mut ubuntu_gettext_domain = None;

        let locales = add_generic_locales(locales);

        for line in input.lines() {
            process_line(
                line,
                &mut groups,
                &mut active_group,
                &mut ubuntu_gettext_domain,
                &locales,
                Cow::Borrowed,
            )
        }

        Ok(DesktopEntry {
            appid: Cow::Borrowed(appid),
            groups,
            path: Cow::Borrowed(path),
            ubuntu_gettext_domain,
        })
    }

    pub fn from_paths<'i, 'l: 'i, L>(
        paths: impl Iterator<Item = PathBuf> + 'i,
        locales: &'l [L],
    ) -> impl Iterator<Item = Result<DesktopEntry<'static>, DecodeError>> + 'i
    where
        L: AsRef<str>,
    {
        let mut buf = String::new();
        let locales = add_generic_locales(locales);

        paths.map(move |path| decode_from_path_with_buf(path, &locales, &mut buf))
    }

    /// Return an owned [`DesktopEntry`]
    pub fn from_path<L>(path: PathBuf, locales: &[L]) -> Result<DesktopEntry<'static>, DecodeError>
    where
        L: AsRef<str>,
    {
        let mut buf = String::new();
        let locales = add_generic_locales(locales);
        decode_from_path_with_buf(path, &locales, &mut buf)
    }
}

fn get_app_id<P: AsRef<Path> + ?Sized>(path: &P) -> Result<&str, DecodeError> {
    let appid = path
        .as_ref()
        .file_stem()
        .ok_or(DecodeError::AppID)?
        .to_str()
        .ok_or(DecodeError::AppID)?;
    Ok(appid)
}

#[inline]
fn process_line<'buf, 'local_ref, 'res: 'local_ref + 'buf, F, L>(
    line: &'buf str,
    groups: &'local_ref mut Groups<'res>,
    active_group: &'local_ref mut Cow<'res, str>,
    ubuntu_gettext_domain: &'local_ref mut Option<Cow<'res, str>>,
    locales_filter: &[L],
    convert_to_cow: F,
) where
    F: Fn(&'buf str) -> Cow<'res, str>,
    L: AsRef<str>,
{
    let line = line.trim();
    if line.is_empty() || line.starts_with('#') {
        return;
    }

    let line_bytes = line.as_bytes();

    if line_bytes[0] == b'[' {
        if let Some(end) = memchr::memrchr(b']', &line_bytes[1..]) {
            *active_group = convert_to_cow(&line[1..end + 1]);
        }
    } else if let Some(delimiter) = memchr::memchr(b'=', line_bytes) {
        let key = &line[..delimiter];
        let value = &line[delimiter + 1..];

        // if locale
        if key.as_bytes()[key.len() - 1] == b']' {
            if let Some(start) = memchr::memchr(b'[', key.as_bytes()) {
                let key_name = &key[..start];
                let locale = &key[start + 1..key.len() - 1];

                if !locales_filter.iter().any(|l| l.as_ref() == locale) {
                    return;
                }

                groups
                    .entry(active_group.clone())
                    .or_default()
                    .entry(convert_to_cow(key_name))
                    .or_insert_with(|| (Cow::Borrowed(""), LocaleMap::new()))
                    .1
                    .insert(convert_to_cow(locale), convert_to_cow(value));

                return;
            }
        }

        if key == "X-Ubuntu-Gettext-Domain" {
            *ubuntu_gettext_domain = Some(convert_to_cow(value));
            return;
        }

        groups
            .entry(active_group.clone())
            .or_default()
            .entry(convert_to_cow(key))
            .or_insert_with(|| (Cow::Borrowed(""), BTreeMap::new()))
            .0 = convert_to_cow(value);
    }
}

#[inline]
fn decode_from_path_with_buf<L>(
    path: PathBuf,
    locales: &[L],
    buf: &mut String,
) -> Result<DesktopEntry<'static>, DecodeError>
where
    L: AsRef<str>,
{
    let file = File::open(&path)?;

    let appid = get_app_id(&path)?;

    let mut groups = Groups::new();
    let mut active_group = Cow::Borrowed("");
    let mut ubuntu_gettext_domain = None;

    let mut reader = io::BufReader::new(file);

    while reader.read_line(buf)? != 0 {
        process_line(
            buf,
            &mut groups,
            &mut active_group,
            &mut ubuntu_gettext_domain,
            locales,
            |s| Cow::Owned(s.to_owned()),
        );
        buf.clear();
    }

    Ok(DesktopEntry {
        appid: Cow::Owned(appid.to_owned()),
        groups,
        path: Cow::Owned(path),
        ubuntu_gettext_domain,
    })
}

/// Ex: if a locale equal fr_FR, add fr
fn add_generic_locales<L: AsRef<str>>(locales: &[L]) -> Vec<&str> {
    let mut v = Vec::with_capacity(locales.len() + 1);

    for l in locales {
        let l = l.as_ref();

        v.push(l);

        if let Some(start) = memchr::memchr(b'_', l.as_bytes()) {
            v.push(l.split_at(start).0)
        }
    }

    v
}