Skip to main content

rightkit_document_workspace/
document_io.rs

1//! Document read/write/copy, sibling-image listing and file watching, with the grant checks the
2//! commands apply. Every function is synchronous; the host runs them off its IPC thread.
3
4use crate::documents::{DocumentBackend, FileFingerprint, RawDocument, WriteDocumentResult};
5use crate::error::{broker_error, WorkspaceError};
6use crate::grants::{authorize_existing_for_read, PathGrants};
7use crate::store::Db;
8use crate::watch::WorkspaceWatcher;
9
10/// Read a granted document, attach a stream token for binary formats and restore the stored view
11/// state.
12pub fn read_document(
13    db: &Db,
14    grants: &dyn PathGrants,
15    docs: &dyn DocumentBackend,
16    path: &str,
17) -> Result<RawDocument, WorkspaceError> {
18    let path = authorize_existing_for_read(path, grants)?;
19    let format = docs.format_of(&path);
20    let mut doc = docs.read(&path).map_err(|e| match format {
21        "unknown" => WorkspaceError::UnsupportedFormat(e),
22        _ if e.contains("too large") => WorkspaceError::DocumentTooLarge(e),
23        _ => WorkspaceError::Io(e),
24    })?;
25    if matches!(format, "pdf" | "docx" | "image") {
26        doc.stream_token = Some(grants.grant_stream_token(&path)?);
27    }
28    let st = db.view_state(&path)?;
29    doc.last_view = st.last_view;
30    doc.view_meta = st.view_meta;
31    Ok(doc)
32}
33
34pub fn write_document(
35    grants: &dyn PathGrants,
36    docs: &dyn DocumentBackend,
37    path: &str,
38    content: &str,
39    encoding: Option<String>,
40    expected_source_sha256: Option<&str>,
41) -> Result<WriteDocumentResult, WorkspaceError> {
42    let path = grants.require_write_target(path).map_err(broker_error)?;
43    let encoding = encoding.unwrap_or_else(|| "UTF-8".to_string());
44    let result = docs.write(&path, content, &encoding, expected_source_sha256);
45    if result.is_ok() {
46        let _ = grants.record_write_target(std::path::Path::new(&path));
47    }
48    result.map_err(|e| {
49        if e.starts_with("write conflict:") {
50            WorkspaceError::WriteConflict(e)
51        } else if e.to_ascii_lowercase().contains("encod") {
52            WorkspaceError::Encoding(e)
53        } else {
54            WorkspaceError::Io(e)
55        }
56    })
57}
58
59/// Decoded write request payload: the document bytes (raw) or base64 text (legacy).
60#[derive(Debug, PartialEq)]
61pub enum WritePayload {
62    Raw(Vec<u8>),
63    Base64(String),
64}
65
66/// Decode the hex-encoded UTF-8 target path a raw-body save carries in a request header. Hex keeps
67/// the header ASCII-safe for any filesystem path.
68pub fn decode_hex_path(hex: &str) -> Result<String, String> {
69    rightkit_fs::digest::unhex(hex)
70        .filter(|bytes| !bytes.is_empty())
71        .and_then(|bytes| String::from_utf8(bytes).ok())
72        .ok_or_else(|| "invalid write path header".to_string())
73}
74
75pub fn write_document_payload(
76    grants: &dyn PathGrants,
77    docs: &dyn DocumentBackend,
78    path: &str,
79    payload: WritePayload,
80) -> Result<(), WorkspaceError> {
81    let path = grants.require_write_target(path).map_err(broker_error)?;
82    let result = match payload {
83        WritePayload::Raw(bytes) => docs.write_raw_bytes(&path, &bytes),
84        WritePayload::Base64(b64) => docs.write_bytes(&path, &b64),
85    };
86    if result.is_ok() {
87        let _ = grants.record_write_target(std::path::Path::new(&path));
88    }
89    result.map_err(WorkspaceError::Io)
90}
91
92pub fn copy_document(
93    grants: &dyn PathGrants,
94    docs: &dyn DocumentBackend,
95    source_path: &str,
96    target_path: &str,
97) -> Result<(), WorkspaceError> {
98    let source = authorize_existing_for_read(source_path, grants).map_err(broker_error)?;
99    let target = grants
100        .require_write_target(target_path)
101        .map_err(broker_error)?;
102    docs.copy_document(&source, &target)
103        .map_err(WorkspaceError::Io)?;
104    grants
105        .record_write_target(std::path::Path::new(&target))
106        .map_err(broker_error)?;
107    Ok(())
108}
109
110pub fn revoke_path(grants: &dyn PathGrants, path: &str) -> Result<(), WorkspaceError> {
111    grants.revoke_path(path).map_err(broker_error)
112}
113
114/// List sibling image files in the same directory as an already-opened image, naturally sorted
115/// (so `img2` precedes `img10`), and grant each so the viewer can page through the folder in
116/// place. The input must already be authorized, which scopes this to a folder the user chose, and
117/// the filter is image-only so this never authorizes arbitrary file types. The returned list
118/// includes the current image.
119pub fn list_sibling_images(
120    grants: &dyn PathGrants,
121    docs: &dyn DocumentBackend,
122    path: &str,
123) -> Result<Vec<String>, WorkspaceError> {
124    let current = authorize_existing_for_read(path, grants).map_err(broker_error)?;
125    let dir = std::path::Path::new(&current)
126        .parent()
127        .ok_or_else(|| WorkspaceError::FileNotFound("image has no parent directory".into()))?
128        .to_path_buf();
129    // Canonical containment root: a sibling is only granted if its REAL path stays inside this
130    // folder. read_dir + canonicalize follow symlinks, so without this a symlink in the folder
131    // pointing at an image elsewhere on disk would get a grant.
132    let dir_canon = std::fs::canonicalize(&dir)?;
133    let mut images: Vec<std::path::PathBuf> = std::fs::read_dir(&dir)?
134        .filter_map(|entry| entry.ok().map(|e| e.path()))
135        .filter(|p| p.is_file() && docs.format_of(&p.to_string_lossy()) == "image")
136        .filter_map(|p| std::fs::canonicalize(&p).ok()) // resolve symlinks to their real target
137        .filter(|c| c.starts_with(&dir_canon)) // drop anything whose real path escapes the folder
138        .collect();
139    images.sort_by(|a, b| natural_cmp(&file_name_lossy(a), &file_name_lossy(b)));
140    images.dedup(); // a symlink + its target both resolve here: grant the file once
141    Ok(grants.grant_existing_files(&images))
142}
143
144fn file_name_lossy(p: &std::path::Path) -> String {
145    p.file_name()
146        .map(|n| n.to_string_lossy().into_owned())
147        .unwrap_or_default()
148}
149
150/// Case-insensitive natural ordering: letter runs compare lexically (lowercased), digit runs compare
151/// by numeric value so `2` sorts before `10`. Ties on value fall back to raw length then bytes for a
152/// stable, deterministic order (e.g. `img02` vs `img2`). Shared with `explorer` for its tree sort.
153pub fn natural_cmp(a: &str, b: &str) -> std::cmp::Ordering {
154    use std::cmp::Ordering;
155    let mut ai = a.chars().peekable();
156    let mut bi = b.chars().peekable();
157    loop {
158        match (ai.peek().copied(), bi.peek().copied()) {
159            (None, None) => return Ordering::Equal,
160            (None, Some(_)) => return Ordering::Less,
161            (Some(_), None) => return Ordering::Greater,
162            (Some(ac), Some(bc)) => {
163                if ac.is_ascii_digit() && bc.is_ascii_digit() {
164                    let an = take_digits(&mut ai);
165                    let bn = take_digits(&mut bi);
166                    let at = an.trim_start_matches('0');
167                    let bt = bn.trim_start_matches('0');
168                    let ord = at
169                        .len()
170                        .cmp(&bt.len())
171                        .then_with(|| at.cmp(bt))
172                        .then_with(|| an.len().cmp(&bn.len()));
173                    if ord != Ordering::Equal {
174                        return ord;
175                    }
176                } else {
177                    let ord = ac.to_ascii_lowercase().cmp(&bc.to_ascii_lowercase());
178                    if ord != Ordering::Equal {
179                        return ord;
180                    }
181                    ai.next();
182                    bi.next();
183                }
184            }
185        }
186    }
187}
188
189fn take_digits(it: &mut std::iter::Peekable<std::str::Chars>) -> String {
190    let mut s = String::new();
191    while let Some(&c) = it.peek() {
192        if !c.is_ascii_digit() {
193            break;
194        }
195        s.push(c);
196        it.next();
197    }
198    s
199}
200
201pub fn file_fingerprint(
202    grants: &dyn PathGrants,
203    docs: &dyn DocumentBackend,
204    path: &str,
205) -> Result<FileFingerprint, WorkspaceError> {
206    let path = grants.require_existing_file(path).map_err(broker_error)?;
207    docs.fingerprint(&path).map_err(WorkspaceError::Io)
208}
209
210pub fn watch_file(
211    grants: &dyn PathGrants,
212    watcher: &dyn WorkspaceWatcher,
213    path: &str,
214) -> Result<(), WorkspaceError> {
215    let path = grants.require_existing_file(path).map_err(broker_error)?;
216    watcher.watch_files(&[path]).map_err(WorkspaceError::Watch)
217}
218
219pub fn watch_files(
220    grants: &dyn PathGrants,
221    watcher: &dyn WorkspaceWatcher,
222    paths: &[String],
223) -> Result<(), WorkspaceError> {
224    // Authorize each path independently; skip any no longer granted/existing rather than failing
225    // the whole arm (a navigated sub-page may have been deleted or had its grant revoked).
226    let authorized: Vec<String> = paths
227        .iter()
228        .filter_map(|p| grants.require_existing_file(p).ok())
229        .collect();
230    if authorized.is_empty() {
231        // Nothing left to watch (last tab closed, or every grant revoked): drop the previous
232        // watcher instead of leaving it armed on files no open tab owns anymore.
233        watcher.clear_files();
234        return Ok(());
235    }
236    watcher
237        .watch_files(&authorized)
238        .map_err(WorkspaceError::Watch)
239}
240
241#[cfg(test)]
242mod tests {
243    use super::*;
244    use std::cmp::Ordering;
245
246    #[test]
247    fn natural_order_compares_digit_runs_numerically() {
248        assert_eq!(natural_cmp("img2", "img10"), Ordering::Less);
249        assert_eq!(natural_cmp("IMG2", "img2"), Ordering::Equal);
250        assert_eq!(natural_cmp("a", "a1"), Ordering::Less);
251    }
252
253    #[test]
254    fn hex_path_header_round_trips() {
255        assert_eq!(decode_hex_path("612f62").unwrap(), "a/b");
256        assert!(decode_hex_path("").is_err());
257        assert!(decode_hex_path("zz").is_err());
258    }
259}