appimg 0.4.1

Install, update and remove AppImages as proper desktop applications
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
//! State of the terminal interface and what the keys do to it.

use std::path::PathBuf;

use anyhow::Result;
use appimg_core::list::InstalledApp;
use appimg_core::update::UpdateSource;
use appimg_core::{install, list, metadata, remove, update, Error, Paths};
use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyModifiers};

use super::browser::Browser;
use super::form::{Field, InstallForm};

#[cfg(test)]
#[path = "../../tests/marker/mod.rs"]
mod marker;

/// Work that takes long enough to deserve a redraw before it starts, or that
/// needs the terminal back, so the event loop runs it, not the key handler.
pub enum Action {
    Install(Box<InstallForm>),
    Inspect(PathBuf),
    UpdateOne(String),
    UpdateAll,
    Remove(String),
    Edit(String),
}

pub enum Mode {
    List,
    Search,
    Details,
    Help,
    Browse(Box<Browser>),
    Form(Box<InstallForm>),
    Preview(Box<InstallForm>),
    Confirm { question: String, action: Box<Action> },
}

pub struct App {
    pub paths: Paths,
    pub apps: Vec<InstalledApp>,
    pub visible: Vec<usize>,
    pub selected: usize,
    pub filter: String,
    pub mode: Mode,
    pub status: Option<String>,
    pub quit: bool,
    pending: Option<Action>,
}

impl App {
    pub fn new(paths: Paths) -> Result<Self> {
        let mut app = Self {
            paths,
            apps: Vec::new(),
            visible: Vec::new(),
            selected: 0,
            filter: String::new(),
            mode: Mode::List,
            status: None,
            quit: false,
            pending: None,
        };
        app.reload()?;
        Ok(app)
    }

    pub fn reload(&mut self) -> Result<()> {
        self.apps = list::list(&self.paths)?;
        self.apply_filter();
        Ok(())
    }

    pub fn apply_filter(&mut self) {
        let needle = self.filter.trim().to_lowercase();
        self.visible = self
            .apps
            .iter()
            .enumerate()
            .filter(|(_, app)| {
                needle.is_empty()
                    || app.name.to_lowercase().contains(&needle)
                    || app.slug.contains(&needle)
                    || app.categories.iter().any(|c| c.to_lowercase().contains(&needle))
            })
            .map(|(index, _)| index)
            .collect();
        self.selected = self.selected.min(self.visible.len().saturating_sub(1));
    }

    pub fn selected_app(&self) -> Option<&InstalledApp> {
        self.visible.get(self.selected).and_then(|index| self.apps.get(*index))
    }

    pub fn take_pending(&mut self) -> Option<Action> {
        self.pending.take()
    }

    fn schedule(&mut self, action: Action, status: &str) {
        self.status = Some(status.to_string());
        self.pending = Some(action);
    }

    fn move_by(&mut self, delta: isize) {
        if self.visible.is_empty() {
            return;
        }
        let last = self.visible.len() - 1;
        self.selected = match delta {
            delta if delta < 0 => self.selected.saturating_sub(delta.unsigned_abs()),
            delta => (self.selected + delta as usize).min(last),
        };
    }

    pub fn on_key(&mut self, key: KeyEvent) {
        if key.kind != KeyEventKind::Press {
            return;
        }
        if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('c') {
            self.quit = true;
            return;
        }
        self.status = None;

        match &mut self.mode {
            Mode::List => self.on_list_key(key),
            Mode::Search => self.on_search_key(key),
            Mode::Details | Mode::Help => {
                self.mode = Mode::List;
            }
            Mode::Browse(_) => self.on_browse_key(key),
            Mode::Form(_) => self.on_form_key(key),
            Mode::Preview(_) => self.on_preview_key(key),
            Mode::Confirm { .. } => self.on_confirm_key(key),
        }
    }

    fn on_list_key(&mut self, key: KeyEvent) {
        match key.code {
            KeyCode::Char('q') | KeyCode::Esc => self.quit = true,
            KeyCode::Char('j') | KeyCode::Down => self.move_by(1),
            KeyCode::Char('k') | KeyCode::Up => self.move_by(-1),
            KeyCode::Char('g') | KeyCode::Home => self.selected = 0,
            KeyCode::Char('G') | KeyCode::End => {
                self.selected = self.visible.len().saturating_sub(1)
            }
            KeyCode::PageDown => self.move_by(10),
            KeyCode::PageUp => self.move_by(-10),
            KeyCode::Char('?') => self.mode = Mode::Help,
            KeyCode::Char('/') => {
                self.filter.clear();
                self.apply_filter();
                self.mode = Mode::Search;
            }
            KeyCode::Enter => {
                if self.selected_app().is_some() {
                    self.mode = Mode::Details;
                }
            }
            KeyCode::Char('r') => match self.reload() {
                Ok(()) => self.status = Some("Reloaded.".to_string()),
                Err(error) => self.status = Some(format!("{error:#}")),
            },
            KeyCode::Char('i') => self.mode = Mode::Browse(Box::new(Browser::new())),
            KeyCode::Char('u') => {
                if let Some(app) = self.selected_app() {
                    let (slug, name) = (app.slug.clone(), app.name.clone());
                    self.schedule(Action::UpdateOne(slug), &format!("Updating {name}..."));
                }
            }
            KeyCode::Char('U') => {
                if !self.apps.is_empty() {
                    self.schedule(Action::UpdateAll, "Updating everything...");
                }
            }
            KeyCode::Char('e') => {
                if let Some(app) = self.selected_app() {
                    let slug = app.slug.clone();
                    self.schedule(Action::Edit(slug), "Opening the editor...");
                }
            }
            KeyCode::Char('d') => {
                if let Some(app) = self.selected_app() {
                    let files = remove::plan(&self.paths, &app.slug)
                        .map(|plan| plan.files().len())
                        .unwrap_or(0);
                    self.mode = Mode::Confirm {
                        question: format!("Remove {} and its {files} files?", app.name),
                        action: Box::new(Action::Remove(app.slug.clone())),
                    };
                }
            }
            _ => {}
        }
    }

    fn on_search_key(&mut self, key: KeyEvent) {
        match key.code {
            KeyCode::Esc => {
                self.filter.clear();
                self.apply_filter();
                self.mode = Mode::List;
            }
            KeyCode::Enter => self.mode = Mode::List,
            KeyCode::Backspace => {
                self.filter.pop();
                self.apply_filter();
            }
            KeyCode::Char(character) => {
                self.filter.push(character);
                self.apply_filter();
            }
            _ => {}
        }
    }

    fn on_browse_key(&mut self, key: KeyEvent) {
        let Mode::Browse(browser) = &mut self.mode else {
            return;
        };
        match key.code {
            KeyCode::Esc | KeyCode::Char('q') => self.mode = Mode::List,
            KeyCode::Char('j') | KeyCode::Down => browser.move_by(1),
            KeyCode::Char('k') | KeyCode::Up => browser.move_by(-1),
            KeyCode::Char('g') | KeyCode::Home => browser.go_to(0),
            KeyCode::Char('G') | KeyCode::End => browser.go_to(usize::MAX),
            KeyCode::PageDown => browser.move_by(10),
            KeyCode::PageUp => browser.move_by(-10),
            KeyCode::Char('h') | KeyCode::Left => {
                if let Some(parent) = browser.directory.parent().map(std::path::Path::to_path_buf) {
                    browser.directory = parent;
                    browser.reload();
                }
            }
            KeyCode::Enter | KeyCode::Char('l') | KeyCode::Right => {
                if let Some(path) = browser.activate() {
                    self.schedule(Action::Inspect(path), "Reading the AppImage...");
                }
            }
            _ => {}
        }
    }

    fn on_form_key(&mut self, key: KeyEvent) {
        let Mode::Form(form) = &mut self.mode else {
            return;
        };
        match key.code {
            KeyCode::Esc => self.mode = Mode::List,
            KeyCode::Tab | KeyCode::Down => form.field = form.field.next(),
            KeyCode::BackTab | KeyCode::Up => form.field = form.field.previous(),
            KeyCode::Enter => {
                let mut form = match std::mem::replace(&mut self.mode, Mode::List) {
                    Mode::Form(form) => form,
                    _ => return,
                };
                match form.finish() {
                    Ok(()) => self.mode = Mode::Preview(form),
                    Err(problem) => {
                        self.status = Some(problem);
                        self.mode = Mode::Form(form);
                    }
                }
            }
            KeyCode::Char(' ') if form.field == Field::Categories => form.toggle_category(),
            KeyCode::Char(' ') if form.field == Field::Terminal => {
                form.request.terminal = !form.request.terminal
            }
            KeyCode::Left if form.field == Field::Categories => form.move_category(-1),
            KeyCode::Right if form.field == Field::Categories => form.move_category(1),
            KeyCode::Backspace => {
                if let Some(text) = form.text_mut() {
                    text.pop();
                }
            }
            KeyCode::Char(character) => {
                if let Some(text) = form.text_mut() {
                    text.push(character);
                }
            }
            _ => {}
        }
    }

    fn on_preview_key(&mut self, key: KeyEvent) {
        match key.code {
            KeyCode::Esc | KeyCode::Char('e') => {
                if let Mode::Preview(form) = std::mem::replace(&mut self.mode, Mode::List) {
                    self.mode = Mode::Form(form);
                }
            }
            KeyCode::Enter | KeyCode::Char('y') => {
                if let Mode::Preview(form) = std::mem::replace(&mut self.mode, Mode::List) {
                    let name = form.request.name.clone();
                    self.schedule(Action::Install(form), &format!("Installing {name}..."));
                }
            }
            KeyCode::Char('q') => self.quit = true,
            _ => {}
        }
    }

    fn on_confirm_key(&mut self, key: KeyEvent) {
        match key.code {
            KeyCode::Char('y') | KeyCode::Enter => {
                if let Mode::Confirm { action, .. } = std::mem::replace(&mut self.mode, Mode::List)
                {
                    self.schedule(*action, "Working...");
                }
            }
            _ => self.mode = Mode::List,
        }
    }

    /// Runs everything that does not need the terminal back.
    pub fn run_action(&mut self, action: Action) -> Result<()> {
        match action {
            Action::Inspect(path) => self.inspect(path),
            Action::Install(form) => self.install(*form),
            Action::UpdateOne(slug) => self.update_one(&slug),
            Action::UpdateAll => self.update_all(),
            Action::Remove(slug) => self.remove(&slug),
            // The event loop owns the terminal, so it runs the editor itself.
            Action::Edit(_) => Ok(()),
        }
    }

    fn inspect(&mut self, path: PathBuf) -> Result<()> {
        // The same checks a download gets, before the metadata is read.
        install::check_file(&path)?;
        // Nothing is confirmed while the form is filled in, so the AppImage
        // is never run for it: without unsquashfs nothing is read, and the
        // install goes by what the form says once it is confirmed.
        let info = metadata::inspect(
            &path,
            appimg_core::current_locale().as_deref(),
            metadata::Reading::WithoutRunning,
        )?;
        // Not reading it is not fatal here, the form asks for name and icon
        // anyway, but the reason belongs on screen.
        let problem = info.extract_root().is_none().then(|| {
            if info.extract_problems.is_empty() {
                "Metadata not read, name and icon are guesses.".to_string()
            } else {
                format!(
                    "Metadata not read, name and icon are guesses: {}",
                    info.extract_problems.join("; ")
                )
            }
        });
        let origin = path.to_string_lossy().into_owned();
        self.mode = Mode::Form(Box::new(InstallForm::new(&path, &origin, info)));
        self.status = problem;
        Ok(())
    }

    fn install(&mut self, mut form: InstallForm) -> Result<()> {
        let plan = install::plan(&self.paths, &form.request)?;
        form.request.overwrite = plan.already_installed;
        let outcome = install::install(&self.paths, &form.request)?;
        self.reload()?;
        self.select_slug(&outcome.slug);

        let what = if outcome.replaced { "Replaced" } else { "Installed" };
        let mut message = format!("{what} {} ({} icons).", outcome.slug, outcome.icons.len());
        if let Some(warning) = outcome.validation_warnings.first() {
            message.push_str(&format!(" desktop-file-validate: {warning}"));
        }
        self.status = Some(message);
        Ok(())
    }

    fn update_one(&mut self, slug: &str) -> Result<()> {
        let app = list::find(&self.paths, slug)?;
        let message = match update::update(&self.paths, &app, None) {
            Ok(outcome) => {
                if outcome.backup_path.is_some()
                    && metadata::extract(&outcome.appimage_path).is_none()
                {
                    update::rollback(&self.paths, slug)?;
                    format!("{}: the new version does not run, rolled back.", app.name)
                } else {
                    update::confirm(&self.paths, slug)?;
                    format!(
                        "Updated {} to {}.",
                        app.name,
                        outcome.to_version.as_deref().unwrap_or("the latest version")
                    )
                }
            }
            // It names the application and says what to do already.
            Err(error @ Error::NoUpdateSource(_)) => error.to_string(),
            Err(error) => format!("{}: {error}", app.name),
        };

        self.reload()?;
        self.select_slug(slug);
        self.status = Some(message);
        Ok(())
    }

    fn update_all(&mut self) -> Result<()> {
        let apps = list::list(&self.paths)?;
        let mut updated = 0;
        let mut failed = 0;
        let mut manual = 0;

        for app in &apps {
            // Nothing to update from is not a failure.
            if update::source_for(app) == UpdateSource::Manual {
                manual += 1;
                continue;
            }
            match update::check(app) {
                Ok(status) if !status.available && status.note.is_none() => continue,
                Ok(_) | Err(_) => {}
            }
            match update::update(&self.paths, app, None) {
                Ok(_) => {
                    let _ = update::confirm(&self.paths, &app.slug);
                    updated += 1;
                }
                Err(_) => failed += 1,
            }
        }

        self.reload()?;
        self.status = Some(match (updated, failed) {
            (0, 0) if manual > 0 => "Everything with an update source is up to date.".to_string(),
            (0, 0) => "Everything is up to date.".to_string(),
            (updated, 0) => format!("Updated {updated} applications."),
            (updated, failed) => format!("Updated {updated}, {failed} failed."),
        });
        Ok(())
    }

    fn remove(&mut self, slug: &str) -> Result<()> {
        let plan = remove::remove(&self.paths, slug)?;
        self.reload()?;
        self.status = Some(format!("Removed {slug} ({} files).", plan.files().len()));
        Ok(())
    }

    pub fn select_slug(&mut self, slug: &str) {
        if let Some(position) = self.visible.iter().position(|index| self.apps[*index].slug == slug)
        {
            self.selected = position;
        }
    }
}

#[cfg(test)]
mod tests {
    use std::fs;
    use std::os::unix::fs::PermissionsExt;

    use super::*;

    /// The install form is filled in before anything is confirmed, so
    /// reading the metadata for it never runs the AppImage, nor makes it
    /// executable. Whether `unsquashfs` is on `PATH` or not, it cannot read
    /// the marker without the stand-in the CLI tests have, so nothing is
    /// read, and the status line says so and why.
    #[test]
    fn prefilling_the_install_form_runs_nothing() {
        let dir = tempfile::Builder::new().prefix("appimg-test-").tempdir().unwrap();
        let root = dir.path();
        let data_home = root.join("data");
        let paths = Paths {
            appimage_dir: data_home.join("appimages"),
            applications_dir: data_home.join("applications"),
            icons_root: data_home.join("icons/hicolor"),
            config_home: root.join("config"),
            state_home: root.join("state"),
            data_home,
        };
        paths.ensure_dirs().unwrap();
        let file = root.join("Marker.AppImage");
        let mark = root.join("it-ran");
        marker::write(&file, &mark, &root.join("payload"), 0o644);

        let mut app = App::new(paths).unwrap();
        app.run_action(Action::Inspect(file.clone())).unwrap();

        assert!(!mark.exists(), "filling in the form ran the AppImage");
        assert_eq!(fs::metadata(&file).unwrap().permissions().mode() & 0o7777, 0o644);
        let Mode::Form(form) = &app.mode else {
            panic!("no install form");
        };
        assert_eq!(form.request.name, "Marker");
        let status = app.status.clone().unwrap_or_default();
        assert!(status.starts_with("Metadata not read, name and icon are guesses: "), "{status}");
        assert!(status.contains("the AppImage was not run to read it instead"), "{status}");
    }
}