Skip to main content

tenui_core/
dnd.rs

1//! Native spatial drag-and-drop URI parsing and path sanitization.
2
3use std::path::PathBuf;
4
5/// Sanitizes dropped payloads, decoding RFC 8089 file URIs, percent-encoded bytes,
6/// and shell-escaped file paths into valid OS PathBuf representations.
7pub struct PathSanitizer;
8
9impl PathSanitizer {
10    /// Parses a raw drag-and-drop payload string (which may contain multiple lines
11    /// and file:// URI schemes) into sanitized PathBuf instances.
12    pub fn parse_drop_payload(payload: &str) -> Vec<PathBuf> {
13        let mut paths = Vec::new();
14
15        for line in payload.lines() {
16            let trimmed = line.trim();
17            if trimmed.is_empty() {
18                continue;
19            }
20
21            let path_str = Self::strip_file_uri(trimmed);
22
23            // Decode into raw bytes and preserve them: filenames are arbitrary bytes on
24            // unix, so a percent-encoded non-UTF-8 path must survive round-trip rather
25            // than being dropped back to its still-encoded form.
26            let decoded = Self::percent_decode_bytes(path_str);
27            let cleaned = Self::unescape_shell_bytes(decoded);
28            if !cleaned.is_empty() {
29                paths.push(Self::bytes_to_pathbuf(cleaned));
30            }
31        }
32
33        paths
34    }
35
36    /// Heuristic classifier: does `payload` look like a file drag-and-drop rather than
37    /// ordinary pasted text? Returns true when it uses the `file://` scheme, or when every
38    /// non-empty line is shaped like a filesystem path (`/…`, `~/…`, `./…`, `../…`, or a
39    /// Windows drive path like `C:\…`).
40    ///
41    /// This is **purely syntactic** — it never touches the filesystem, so it stays
42    /// deterministic and testable. A terminal delivers both a real drop and a normal paste
43    /// as `Event::Paste`, so use this to decide whether to route a payload through
44    /// [`parse_drop_payload`](Self::parse_drop_payload); because a path-shaped line of prose
45    /// can still slip through, callers wanting certainty should confirm the parsed paths
46    /// exist before acting on them.
47    pub fn looks_like_drop(payload: &str) -> bool {
48        let mut saw_line = false;
49        for line in payload.lines() {
50            let t = line.trim();
51            if t.is_empty() {
52                continue;
53            }
54            saw_line = true;
55            let is_uri = t.starts_with("file://");
56            let is_path = t.starts_with('/')
57                || t.starts_with("~/")
58                || t.starts_with("./")
59                || t.starts_with("../")
60                || Self::looks_like_windows_path(t);
61            if !(is_uri || is_path) {
62                return false;
63            }
64        }
65        saw_line
66    }
67
68    /// `C:\…` or `C:/…` — a drive letter, a colon, then a separator.
69    fn looks_like_windows_path(s: &str) -> bool {
70        let b = s.as_bytes();
71        b.len() >= 3 && b[0].is_ascii_alphabetic() && b[1] == b':' && (b[2] == b'/' || b[2] == b'\\')
72    }
73
74    /// Strips a leading `file://` scheme and any `localhost`/empty authority per RFC 8089,
75    /// yielding the bare path. `file:///a` -> `/a`, `file://localhost/a` -> `/a`,
76    /// `file://host/a` -> `host/a` (kept, as a remote authority is not a local path).
77    fn strip_file_uri(input: &str) -> &str {
78        let Some(rest) = input.strip_prefix("file://") else {
79            return input;
80        };
81        let path = match rest.find('/') {
82            Some(0) => rest, // file:///path — empty authority
83            Some(slash) => {
84                if rest[..slash].eq_ignore_ascii_case("localhost") {
85                    &rest[slash..]
86                } else {
87                    rest
88                }
89            }
90            None => rest,
91        };
92        #[cfg(windows)]
93        let path = path.strip_prefix('/').unwrap_or(path); // file:///C:/x -> C:/x
94        path
95    }
96
97    /// Decodes percent-encoded byte sequences (e.g. `%20` -> `' '`, `%2F` -> `'/'`)
98    /// using standard library without external dependencies.
99    ///
100    /// Lossy in the presence of non-UTF-8 bytes; prefer [`percent_decode_bytes`] on
101    /// unix where filenames may not be valid UTF-8.
102    ///
103    /// [`percent_decode_bytes`]: Self::percent_decode_bytes
104    pub fn percent_decode(input: &str) -> String {
105        String::from_utf8(Self::percent_decode_bytes(input)).unwrap_or_else(|_| input.to_string())
106    }
107
108    /// Byte-exact percent decoder. Preserves arbitrary (non-UTF-8) path bytes.
109    pub fn percent_decode_bytes(input: &str) -> Vec<u8> {
110        let bytes = input.as_bytes();
111        let mut out = Vec::with_capacity(bytes.len());
112        let mut i = 0;
113
114        while i < bytes.len() {
115            if bytes[i] == b'%'
116                && i + 2 < bytes.len()
117                && let (Some(h1), Some(h2)) = ((bytes[i + 1] as char).to_digit(16), (bytes[i + 2] as char).to_digit(16))
118            {
119                out.push(((h1 << 4) | h2) as u8);
120                i += 3;
121                continue;
122            }
123            out.push(bytes[i]);
124            i += 1;
125        }
126
127        out
128    }
129
130    /// Strips shell escape characters from file paths (e.g. `\ ` -> `' '`, `\\` -> `'\'`).
131    pub fn unescape_shell_path(input: &str) -> String {
132        input.replace("\\ ", " ").replace("\\\\", "\\")
133    }
134
135    /// Byte-level shell unescape: `\ ` -> ` `, `\\` -> `\`. Single left-to-right pass so
136    /// escapes don't interact (unlike chained `replace`, where the second could re-scan
137    /// output of the first).
138    fn unescape_shell_bytes(input: Vec<u8>) -> Vec<u8> {
139        let mut out = Vec::with_capacity(input.len());
140        let mut i = 0;
141        while i < input.len() {
142            if input[i] == b'\\' && i + 1 < input.len() {
143                match input[i + 1] {
144                    b' ' => {
145                        out.push(b' ');
146                        i += 2;
147                        continue;
148                    }
149                    b'\\' => {
150                        out.push(b'\\');
151                        i += 2;
152                        continue;
153                    }
154                    _ => {}
155                }
156            }
157            out.push(input[i]);
158            i += 1;
159        }
160        out
161    }
162
163    #[cfg(unix)]
164    fn bytes_to_pathbuf(bytes: Vec<u8>) -> PathBuf {
165        use std::os::unix::ffi::OsStringExt;
166        PathBuf::from(std::ffi::OsString::from_vec(bytes))
167    }
168
169    #[cfg(not(unix))]
170    fn bytes_to_pathbuf(bytes: Vec<u8>) -> PathBuf {
171        PathBuf::from(String::from_utf8_lossy(&bytes).into_owned())
172    }
173}
174
175#[cfg(test)]
176mod tests {
177    use super::*;
178
179    #[test]
180    fn test_file_uri_host_stripping() {
181        assert_eq!(
182            PathSanitizer::parse_drop_payload("file:///home/demon/a.txt"),
183            vec![PathBuf::from("/home/demon/a.txt")]
184        );
185        // Named/localhost authority must not leak into the path.
186        assert_eq!(
187            PathSanitizer::parse_drop_payload("file://localhost/home/demon/a.txt"),
188            vec![PathBuf::from("/home/demon/a.txt")]
189        );
190        // Plain (non-URI) path is passed through.
191        assert_eq!(
192            PathSanitizer::parse_drop_payload("/tmp/plain path"),
193            vec![PathBuf::from("/tmp/plain path")]
194        );
195    }
196
197    #[test]
198    fn test_percent_and_shell_decode() {
199        assert_eq!(
200            PathSanitizer::parse_drop_payload("file:///home/a%20b/c%2Fd"),
201            vec![PathBuf::from("/home/a b/c/d")]
202        );
203        assert_eq!(
204            PathSanitizer::parse_drop_payload("/home/a\\ b"),
205            vec![PathBuf::from("/home/a b")]
206        );
207    }
208
209    #[test]
210    fn test_looks_like_drop_classifies_payloads() {
211        // Drops: file:// URIs and path-shaped lines.
212        assert!(PathSanitizer::looks_like_drop("file:///home/demon/a.txt"));
213        assert!(PathSanitizer::looks_like_drop("/tmp/a.txt\n/tmp/b.txt"));
214        assert!(PathSanitizer::looks_like_drop("~/notes.md"));
215        assert!(PathSanitizer::looks_like_drop("./rel/path"));
216        assert!(PathSanitizer::looks_like_drop("C:\\Users\\me\\f.txt"));
217
218        // Not drops: ordinary pasted prose/code, or a mix where one line isn't path-shaped.
219        assert!(!PathSanitizer::looks_like_drop("hello world"));
220        assert!(!PathSanitizer::looks_like_drop("fn main() { println!(\"hi\"); }"));
221        assert!(!PathSanitizer::looks_like_drop("/tmp/ok.txt\nbut this line is prose"));
222        assert!(!PathSanitizer::looks_like_drop("")); // empty is not a drop
223        assert!(!PathSanitizer::looks_like_drop("   \n  ")); // whitespace-only is not a drop
224    }
225
226    #[cfg(unix)]
227    #[test]
228    fn test_non_utf8_path_preserved() {
229        use std::os::unix::ffi::OsStrExt;
230        // %FF is not valid UTF-8; the byte must survive into the PathBuf.
231        let paths = PathSanitizer::parse_drop_payload("file:///tmp/%FFname");
232        assert_eq!(paths.len(), 1);
233        assert!(paths[0].as_os_str().as_bytes().contains(&0xFF));
234    }
235}