summaryrefslogtreecommitdiff
path: root/src/devices/file/directory_listing.rs
blob: 0709fc36492c4fd74d77606ead7c59157aeb3fd6 (plain) (blame)
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
use super::*;

use std::ffi::OsString;
use std::os::unix::ffi::{OsStrExt, OsStringExt};
use std::path::{Component, Path, PathBuf};


pub struct DirectoryListing {
    children: Vec<DirectoryChild>,
    length: u32,
    selected: Option<u32>,
    name_buffer: CircularPathBuffer,
}

impl DirectoryListing {
    pub fn from_path(path: &Path, base: &Path) -> Result<Self, ()> {
        macro_rules! continue_on_err {
            ($result:expr) => { match $result { Ok(v) => v, Err(_) => continue} };
        }

        let mut children = Vec::new();
        if let Ok(iter_dir) = std::fs::read_dir(path) {
            for (i, entry_result) in iter_dir.enumerate() {
                if i == u16::MAX as usize {
                    eprintln!("Warning, {path:?} contains more than 65536 entries.")
                };
                let entry = continue_on_err!(entry_result);
                let path = continue_on_err!(remove_base(&entry.path(), &base));
                let byte_path = path.as_os_str().as_bytes();
                if byte_path.len() > 255 {
                    continue;
                };
                if filename_dot_prefixed(&path) {
                    continue;
                }
                let metadata = continue_on_err!(std::fs::metadata(&entry.path()));
                children.push( DirectoryChild {
                    byte_path: Vec::from(byte_path),
                    entry_type: if metadata.is_file() {
                        EntryType::File
                    } else if metadata.is_dir() {
                        EntryType::Directory
                    } else {
                        continue;
                    },
                } )
            }
            children.sort_unstable();
            let length = u32::try_from(children.len()).unwrap_or(u32::MAX);
            let selected = None;
            let name_buffer = CircularPathBuffer::new();
            Ok(Self { children, length, selected, name_buffer } )
        } else {
            Err(())
        }
    }

    pub fn get(&self, index: u32) -> Option<&DirectoryChild> {
        self.children.get(index as usize)
    }

    pub fn length(&self) -> u32 {
        self.length
    }

    pub fn selected(&self) -> u32 {
        self.selected.unwrap_or(0)
    }

    pub fn set_selected(&mut self, index: u32) {
        if let Some(info) = self.get(index) {
            self.name_buffer.populate(&info.byte_path.clone());
            self.selected = Some(index);
        } else {
            self.name_buffer.clear();
            self.selected = None;
        }
    }

    pub fn child_name(&mut self) -> &mut CircularPathBuffer {
        &mut self.name_buffer
    }

    pub fn child_type(&self) -> Option<EntryType> {
        self.selected.and_then(|s| self.get(s).and_then(|i| Some(i.entry_type)))
    }

    pub fn child_path(&self) -> Option<PathBuf> {
        self.selected.and_then(|s| self.get(s).and_then(|i| {
            let os_string: OsString = OsStringExt::from_vec(i.byte_path.clone());
            Some(os_string.into())
        }))
    }
}

pub fn remove_base(absolute_path: &Path, base_path: &Path) -> Result<PathBuf, ()> {
    if let Ok(relative) = absolute_path.strip_prefix(base_path) {
        let mut baseless_path = PathBuf::from("/");
        for component in relative.components() {
            match component {
                Component::Normal(s) => baseless_path.push(s),
                Component::ParentDir => return Err(()),
                Component::CurDir => continue,
                Component::RootDir => continue,
                Component::Prefix(_) => continue,
            }
        }
        return Ok(baseless_path);
    }
    return Err(());
}

// Returns true if a dot character directly follows the right-most
// forward-slash character in the path.
fn filename_dot_prefixed(path: &Path) -> bool {
    let bytes = path.as_os_str().as_bytes();
    // Find position of final forward-slash byte.
    let mut final_slash = None;
    for (i, byte) in bytes.iter().enumerate() {
        if *byte == b'/' { final_slash = Some(i) }
    }
    if let Some(i) = final_slash {
        if let Some(b'.') = bytes.get(i+1) {
            return true;
        }
    }
    return false;
}