libplasmoid-updater 0.2.0

Library for updating KDE Plasma 6 components from the KDE Store. Meant for use in topgrade.
Documentation
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
// SPDX-License-Identifier: GPL-3.0-or-later

use std::collections::HashMap;
use std::sync::LazyLock;

/// Default embedded widgets-id mapping file provided by Apdatifier.
///
/// This file maps component directory names to KDE Store content IDs
/// and is used as a fallback when other resolution methods fail.
const DEFAULT_WIDGETS_ID: &str = include_str!("../widgets-id");

static DEFAULT_WIDGETS_TABLE: LazyLock<HashMap<String, u64>> =
    LazyLock::new(|| Config::parse_widgets_id(DEFAULT_WIDGETS_ID));

/// Controls plasmashell restart behavior after updates.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum RestartBehavior {
    /// Never restart plasmashell (default).
    #[default]
    Never,
    /// Always restart plasmashell after successful updates that require it.
    Always,
    /// Prompt the user interactively. Falls back to [`Never`](Self::Never) if
    /// stdin is not a terminal.
    Prompt,
}

/// Configuration for libplasmoid-updater operations.
///
/// This struct contains all configuration options used by the library.
/// Library consumers (like topgrade or other automation tools) can construct
/// this directly without needing config file parsing.
///
/// # Examples
///
/// ## Basic Configuration
///
/// ```rust
/// use libplasmoid_updater::Config;
///
/// let config = Config::new();
/// ```
///
/// ## With Custom Settings
///
/// ```rust
/// use libplasmoid_updater::{Config, RestartBehavior};
/// use std::collections::HashMap;
///
/// let mut widgets_table = HashMap::new();
/// widgets_table.insert("com.example.widget".to_string(), 123456);
///
/// let config = Config::new()
///     .with_excluded_packages(vec!["problematic-widget".to_string()])
///     .with_widgets_id_table(widgets_table)
///     .with_restart(RestartBehavior::Always);
/// ```
#[derive(Debug, Clone, Default)]
pub struct Config {
    /// If `true`, operate on system-wide components (in `/usr/share`).
    /// If `false` (default), operate on user components (in `~/.local/share`).
    /// System operations require root privileges.
    pub system: bool,

    /// Packages to exclude from updates.
    ///
    /// Can match either directory names (e.g., "org.kde.plasma.systemmonitor")
    /// or display names (e.g., "System Monitor"). Components in this list
    /// will be skipped during update operations.
    pub excluded_packages: Vec<String>,

    /// Widget ID fallback table mapping directory names to KDE Store content IDs.
    ///
    /// This table is used as a fallback when content ID resolution via KNewStuff
    /// registry or exact name matching fails. The library uses a three-tier
    /// resolution strategy:
    ///
    /// 1. KNewStuff registry lookup (most reliable)
    /// 2. Exact name match from KDE Store API
    /// 3. Fallback to this widgets_id_table
    ///
    /// # Format
    ///
    /// - Key: Component directory name (e.g., "org.kde.plasma.systemmonitor")
    /// - Value: KDE Store content ID (numeric)
    ///
    /// The CLI application loads this from a `widgets-id` file, but library
    /// consumers can provide it programmatically or leave it empty.
    pub widgets_id_table: HashMap<String, u64>,

    /// Controls plasmashell restart behavior after successful updates.
    pub restart: RestartBehavior,

    /// When `true`, skip interactive prompts and apply all non-excluded updates
    /// automatically. Has no effect without the `cli` feature.
    pub auto_confirm: bool,

    /// Maximum number of parallel installation threads.
    ///
    /// `None` (default) uses the number of logical CPU threads available.
    /// `Some(n)` pins the pool to exactly `n` threads.
    pub threads: Option<usize>,

    /// When `true`, skip KDE Plasma environment detection and proceed regardless.
    pub skip_plasma_detection: bool,

    /// When `true` (default), inhibit system idle/sleep/shutdown during installs.
    ///
    /// Uses a 3-tier fallback: logind DBus → `systemd-inhibit` subprocess → no-op.
    /// Set to `false` if the caller handles its own power management inhibition.
    pub inhibit_idle: bool,
}

impl Config {
    /// Creates a new configuration with default values.
    ///
    /// Default values:
    /// - `system`: false (user components)
    /// - `excluded_packages`: empty
    /// - `widgets_id_table`: loaded from embedded widgets-id file
    /// - `restart`: [`RestartBehavior::Never`]
    ///
    /// The embedded widgets-id table provides fallback content ID mappings
    /// for components that cannot be resolved via KNewStuff registry or
    /// exact name matching.
    pub fn new() -> Self {
        Self {
            widgets_id_table: DEFAULT_WIDGETS_TABLE.clone(),
            inhibit_idle: true,
            ..Default::default()
        }
    }

    /// Sets whether to operate on system-wide components.
    ///
    /// When true, the library scans and updates components in `/usr/share`
    /// instead of `~/.local/share`. System operations require root privileges.
    ///
    /// # Example
    ///
    /// ```rust
    /// use libplasmoid_updater::Config;
    ///
    /// let config = Config::new().with_system(true);
    /// ```
    pub fn with_system(mut self, system: bool) -> Self {
        self.system = system;
        self
    }

    /// Sets the widgets ID fallback table.
    ///
    /// This table maps component directory names to KDE Store content IDs
    /// and is used as a fallback when other resolution methods fail.
    ///
    /// # Arguments
    ///
    /// * `table` - HashMap mapping directory names to content IDs
    ///
    /// # Example
    ///
    /// ```rust
    /// use libplasmoid_updater::Config;
    /// use std::collections::HashMap;
    ///
    /// let mut table = HashMap::new();
    /// table.insert("org.kde.plasma.systemmonitor".to_string(), 998890);
    ///
    /// let config = Config::new().with_widgets_id_table(table);
    /// ```
    pub fn with_widgets_id_table(mut self, table: HashMap<String, u64>) -> Self {
        self.widgets_id_table = table;
        self
    }

    /// Sets the list of Plasmoids to exclude from updates.
    ///
    /// Components in this list will be skipped during updates.
    /// The list can contain either directory names or display names.
    ///
    /// # Arguments
    ///
    /// * `packages` - Vector of package names to exclude
    ///
    /// # Example
    ///
    /// ```rust
    /// use libplasmoid_updater::Config;
    ///
    /// let config = Config::new()
    ///     .with_excluded_packages(vec![
    ///         "org.kde.plasma.systemmonitor".to_string(),
    ///         "Problematic Widget".to_string(),
    ///     ]);
    /// ```
    pub fn with_excluded_packages(mut self, packages: Vec<String>) -> Self {
        self.excluded_packages = packages;
        self
    }

    /// Sets the plasmashell restart behavior after updates.
    ///
    /// # Example
    ///
    /// ```rust
    /// use libplasmoid_updater::{Config, RestartBehavior};
    ///
    /// let config = Config::new().with_restart(RestartBehavior::Always);
    /// ```
    pub fn with_restart(mut self, restart: RestartBehavior) -> Self {
        self.restart = restart;
        self
    }

    /// Parses a widgets-id table from a string.
    ///
    /// The format is one entry per line: `content_id directory_name`
    /// Lines starting with `#` are comments.
    pub fn parse_widgets_id(content: &str) -> HashMap<String, u64> {
        let mut table = HashMap::with_capacity(content.lines().count());
        for line in content.lines() {
            if let Some((id, name)) = parse_widgets_id_line(line) {
                table.insert(name, id);
            }
        }
        table
    }

    /// Sets whether to skip interactive prompts and apply all non-excluded
    /// updates automatically.
    ///
    /// Has no effect without the `cli` feature enabled.
    ///
    /// # Example
    ///
    /// ```rust
    /// use libplasmoid_updater::Config;
    ///
    /// let config = Config::new().with_auto_confirm(true);
    /// ```
    pub fn with_auto_confirm(mut self, auto_confirm: bool) -> Self {
        self.auto_confirm = auto_confirm;
        self
    }

    /// Sets the maximum number of parallel installation threads.
    ///
    /// By default (`None`), the library uses the number of logical CPUs.
    /// Setting this to a specific value pins the thread pool to exactly
    /// that many threads.
    ///
    /// # Example
    ///
    /// ```rust
    /// use libplasmoid_updater::Config;
    ///
    /// let config = Config::new().with_threads(4);
    /// ```
    pub fn with_threads(mut self, threads: usize) -> Self {
        self.threads = Some(threads);
        self
    }

    /// Sets whether to skip KDE Plasma environment detection.
    ///
    /// When `true`, the library proceeds without checking for the KNewStuff3
    /// registry directory. Useful for CI, testing, or non-standard KDE setups.
    ///
    /// # Example
    ///
    /// ```rust
    /// use libplasmoid_updater::Config;
    ///
    /// let config = Config::new().with_skip_plasma_detection(true);
    /// ```
    pub fn with_skip_plasma_detection(mut self, skip: bool) -> Self {
        self.skip_plasma_detection = skip;
        self
    }

    /// Sets whether to inhibit system idle/sleep/shutdown during installs.
    ///
    /// Defaults to `true`. Set to `false` if the calling application handles
    /// its own power management inhibition (e.g., a GUI app using DBus directly).
    ///
    /// # Example
    ///
    /// ```rust
    /// use libplasmoid_updater::Config;
    ///
    /// let config = Config::new().with_inhibit_idle(false);
    /// assert!(!config.inhibit_idle);
    /// ```
    pub fn with_inhibit_idle(mut self, inhibit: bool) -> Self {
        self.inhibit_idle = inhibit;
        self
    }
}

pub(crate) fn parse_widgets_id_line(line: &str) -> Option<(u64, String)> {
    let line = line.trim();
    if line.is_empty() || line.starts_with('#') {
        return None;
    }

    let mut parts = line.splitn(2, ' ');
    let id = parts.next()?.parse::<u64>().ok()?;
    let name = parts.next()?.trim();
    if name.is_empty() {
        return None;
    }
    Some((id, name.to_string()))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_widgets_id_line_valid() {
        let line = "998890 com.bxabi.bumblebee-indicator";
        let result = parse_widgets_id_line(line);
        assert_eq!(
            result,
            Some((998890, "com.bxabi.bumblebee-indicator".to_string()))
        );
    }

    #[test]
    fn test_parse_widgets_id_line_comment() {
        let line = "#2182964 adhe.menu.11 #Ignored, not a unique ID";
        let result = parse_widgets_id_line(line);
        assert_eq!(result, None);
    }

    #[test]
    fn test_parse_widgets_id_line_empty() {
        let line = "";
        let result = parse_widgets_id_line(line);
        assert_eq!(result, None);
    }

    #[test]
    fn test_parse_widgets_id_table() {
        let content = "998890 com.bxabi.bumblebee-indicator\n\
                       998913 org.kde.plasma.awesomewidget\n\
                       # Comment line\n\
                       1155946 com.dschopf.plasma.qalculate\n";
        let table = Config::parse_widgets_id(content);
        assert_eq!(table.len(), 3);
        assert_eq!(table.get("com.bxabi.bumblebee-indicator"), Some(&998890));
        assert_eq!(table.get("org.kde.plasma.awesomewidget"), Some(&998913));
        assert_eq!(table.get("com.dschopf.plasma.qalculate"), Some(&1155946));
    }

    #[test]
    fn test_default_widgets_id_table_loads() {
        let config = Config::new();
        // Verify the embedded file is loaded and contains expected entries
        assert!(
            !config.widgets_id_table.is_empty(),
            "Default widgets_id_table should not be empty"
        );
        // Check for a few known entries from the widgets-id file
        assert_eq!(
            config.widgets_id_table.get("com.bxabi.bumblebee-indicator"),
            Some(&998890)
        );
        assert_eq!(
            config.widgets_id_table.get("org.kde.plasma.awesomewidget"),
            Some(&998913)
        );
    }

    #[test]
    fn test_config_with_custom_widgets_id_table() {
        let mut custom_table = HashMap::new();
        custom_table.insert("custom.widget".to_string(), 123456);

        let config = Config::new().with_widgets_id_table(custom_table.clone());

        // Should use custom table, not default
        assert_eq!(config.widgets_id_table, custom_table);
        assert_eq!(config.widgets_id_table.get("custom.widget"), Some(&123456));
        // Default entry should not be present
        assert_eq!(
            config.widgets_id_table.get("com.bxabi.bumblebee-indicator"),
            None
        );
    }

    #[test]
    fn default_widgets_table_is_cached() {
        // Creating multiple configs should all have the same table
        let config1 = Config::new();
        let config2 = Config::new();
        assert_eq!(config1.widgets_id_table, config2.widgets_id_table);
        assert!(!config1.widgets_id_table.is_empty());
    }

    #[test]
    fn cached_table_matches_fresh_parse() {
        let cached = &*DEFAULT_WIDGETS_TABLE;
        let fresh = Config::parse_widgets_id(DEFAULT_WIDGETS_ID);
        assert_eq!(cached, &fresh);
    }
}