summaryrefslogtreecommitdiffstats
path: root/src/app/previewer.rs
blob: 272690b98b60df442240e37647a69d073a8f48be (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
use std::collections::{HashMap, VecDeque};
use std::path::{Path, PathBuf};
use std::sync::mpsc::{self, TryRecvError};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;

use anyhow::{anyhow, Context, Result};

use crate::modes::{FileInfo, Preview, Users};

pub struct Previewer {
    pub tx: mpsc::Sender<Option<PathBuf>>,
    pub handle_receiver: thread::JoinHandle<Result<()>>,
    pub handle_builder: thread::JoinHandle<Result<()>>,
}

impl Previewer {
    pub fn new(preview_cache: Arc<Mutex<PreviewCache>>) -> Self {
        let (tx, rx) = mpsc::channel::<Option<PathBuf>>();
        let queue: Arc<Mutex<VecDeque<PathBuf>>> = Arc::new(Mutex::new(VecDeque::new()));
        let queue2 = queue.clone();

        let handle_receiver = thread::spawn(move || -> Result<()> {
            loop {
                match rx.try_recv() {
                    Ok(Some(path)) => match queue2.lock() {
                        Ok(mut queue) => {
                            queue.push_back(path);
                            drop(queue);
                        }
                        Err(error) => return Err(anyhow!("Error locking queue: {error}")),
                    },
                    Ok(_) | Err(TryRecvError::Disconnected) => {
                        crate::log_info!("terminating previewer");
                        break;
                    }
                    Err(TryRecvError::Empty) => {
                        thread::sleep(Duration::from_millis(33));
                    }
                }
            }
            Ok(())
        });

        let handle_builder = thread::spawn(move || loop {
            match queue.lock() {
                Err(error) => return Err(anyhow!("error locking queue lock: {error}")),
                Ok(mut queue) => {
                    match queue.pop_front() {
                        Some(path) => match preview_cache.lock() {
                            Ok(mut preview_cache) => {
                                preview_cache.update(&path)?;
                                drop(preview_cache);
                            }
                            Err(error) => {
                                return Err(anyhow!("Error locking preview_cache: {error}"))
                            }
                        },
                        None => {
                            thread::sleep(Duration::from_millis(33));
                        }
                    };
                    drop(queue);
                }
            }
        });
        Self {
            tx,
            handle_receiver,
            handle_builder,
        }
    }
}

#[derive(Default)]
pub struct PreviewCache {
    cache: HashMap<PathBuf, Preview>,
    paths: Vec<PathBuf>,
}

impl PreviewCache {
    const SIZE_LIMIT: usize = 100;

    /// Returns an optional reference to the preview.
    pub fn read(&self, path: &Path) -> Option<&Preview> {
        self.cache.get(path)
    }

    /// True iff the cache aleady contains a preview of path.
    ///
    /// # Errors
    ///
    /// May fail if:
    /// - FileInfo fail,
    /// - Preview fail.
    pub fn update(&mut self, path: &Path) -> Result<bool> {
        if self.cache.contains_key(path) {
            crate::log_info!("key {path} already in cache", path = path.display());
            return Ok(false);
        };
        self.add_preview(path)?;
        self.limit_size();
        Ok(true)
    }

    pub fn add_made_preview(&mut self, path: &Path, preview: Preview) {
        self.cache.insert(path.to_path_buf(), preview);
        self.paths.push(path.to_path_buf());
        self.limit_size();
    }

    fn add_preview(&mut self, path: &Path) -> Result<()> {
        self.cache
            .insert(path.to_path_buf(), Self::make_preview(path)?);
        self.paths.push(path.to_path_buf());
        crate::log_info!("added {path} to cache", path = path.display());
        Ok(())
    }

    fn make_preview(path: &Path) -> Result<Preview> {
        Preview::new(&FileInfo::from_path_with_name(
            path,
            &path.file_name().context("")?.to_string_lossy(),
            &Users::default(),
        )?)
    }

    fn limit_size(&mut self) {
        if self.cache.len() > Self::SIZE_LIMIT {
            let path = self.paths.remove(0);
            self.cache.remove(&path);
        }
    }
}