Skip to main content

rightkit_document_workspace/
documents.rs

1//! Document types and the backend seam. The host supplies format classification and the actual
2//! document reads and writes (encoding detection, atomic writes) through [`DocumentBackend`].
3
4use serde::Serialize;
5
6#[derive(Debug, Serialize)]
7pub struct RawDocument {
8    pub path: String,
9    pub content: String,
10    pub last_view: Option<String>,
11    /// Per-format view metadata (JSON string) restored from the database by `read_document`.
12    pub view_meta: Option<String>,
13    /// True only when even the detected encoding could not decode the bytes cleanly (genuinely
14    /// garbled input): replacement characters were substituted.
15    pub lossy: bool,
16    /// The encoding the content was decoded from. Saving re-encodes to this encoding.
17    pub encoding: String,
18    /// Modified time (ms since epoch) at read time. 0 if the platform does not report it.
19    pub mtime_ms: i64,
20    /// Byte size at read time. With `mtime_ms` this is the cheap on-disk fingerprint.
21    pub size: i64,
22    /// SHA-256 of text bytes at read time. Save uses it to reject stale in-place writes.
23    pub source_sha256: Option<String>,
24    /// Opaque token for binary viewer URLs; the renderer never receives the path in that URL.
25    pub stream_token: Option<String>,
26}
27
28/// Cheap on-disk fingerprint (mtime ms + size) used to detect that a file changed while its tab
29/// was inactive. Reads only metadata, never the file body.
30#[derive(Debug, Serialize)]
31pub struct FileFingerprint {
32    pub mtime_ms: i64,
33    pub size: i64,
34}
35
36#[derive(Debug, Serialize)]
37pub struct WriteDocumentResult {
38    pub encoding: String,
39    pub source_sha256: String,
40}
41
42/// Document format classification and file IO as the host implements them. Errors are plain
43/// strings; the workspace classifies them into [`crate::WorkspaceError`] variants.
44pub trait DocumentBackend {
45    /// The format id of a path (`"image"`, `"pdf"`, `"md"`, ..., or `"unknown"`).
46    fn format_of(&self, path: &str) -> &'static str;
47    /// Read and decode a document.
48    fn read(&self, path: &str) -> Result<RawDocument, String>;
49    /// Encode and atomically write text, rejecting stale in-place saves.
50    fn write(
51        &self,
52        path: &str,
53        content: &str,
54        encoding: &str,
55        expected_source_sha256: Option<&str>,
56    ) -> Result<WriteDocumentResult, String>;
57    /// Write base64 content as raw bytes.
58    fn write_bytes(&self, path: &str, content_base64: &str) -> Result<(), String>;
59    /// Write raw bytes.
60    fn write_raw_bytes(&self, path: &str, bytes: &[u8]) -> Result<(), String>;
61    /// Copy a document to a new location.
62    fn copy_document(&self, source: &str, target: &str) -> Result<(), String>;
63    /// Metadata-only fingerprint.
64    fn fingerprint(&self, path: &str) -> Result<FileFingerprint, String>;
65}