Skip to main content

rightkit_document_workspace/
library.rs

1//! Recent files, pins, per-document view state and the tab session, with the broker rules the
2//! commands apply on top of the [`Db`] store.
3
4use crate::documents::DocumentBackend;
5use crate::error::{broker_error, WorkspaceError};
6use crate::explorer::fs_io_error;
7use crate::grants::PathGrants;
8use crate::store::{Db, FileEntry, PinEntry};
9
10pub fn clamp_recent_limit(limit: Option<i64>) -> i64 {
11    limit.unwrap_or(20).clamp(1, 50)
12}
13
14#[derive(serde::Serialize)]
15pub struct RecentEntry {
16    #[serde(flatten)]
17    entry: FileEntry,
18    // Location metadata only. Opening still requires exchanging the one-shot token.
19    display_path: String,
20}
21
22fn tokenized_entries(entries: Vec<FileEntry>, grants: &dyn PathGrants) -> Vec<RecentEntry> {
23    entries
24        .into_iter()
25        .filter_map(|mut entry| {
26            let token = grants.register_known_stored_path(&entry.path).ok()?;
27            let display_path = entry.path.clone();
28            entry.path = token;
29            Some(RecentEntry {
30                entry,
31                display_path,
32            })
33        })
34        .collect()
35}
36
37pub fn list_recent(
38    db: &Db,
39    grants: &dyn PathGrants,
40    limit: Option<i64>,
41) -> Result<Vec<RecentEntry>, WorkspaceError> {
42    db.list_recent(clamp_recent_limit(limit))
43        .map(|rows| tokenized_entries(rows, grants))
44        .map_err(WorkspaceError::from)
45}
46
47pub fn clear_recent(db: &Db) -> Result<(), WorkspaceError> {
48    db.clear_recent().map_err(WorkspaceError::from)
49}
50
51pub fn purge_user_paths(db: &Db) -> Result<(), WorkspaceError> {
52    db.purge_user_paths().map_err(WorkspaceError::from)
53}
54
55pub fn is_pinned_path(
56    db: &Db,
57    grants: &dyn PathGrants,
58    path: &str,
59) -> Result<bool, WorkspaceError> {
60    let path = grants.require_existing_file(path).map_err(broker_error)?;
61    db.is_pinned(&path).map_err(WorkspaceError::from)
62}
63
64pub fn toggle_pin(
65    db: &Db,
66    grants: &dyn PathGrants,
67    docs: &dyn DocumentBackend,
68    path: &str,
69    display_name: &str,
70) -> Result<bool, WorkspaceError> {
71    let path = grants.require_existing_file(path).map_err(broker_error)?;
72    let format = docs.format_of(&path).to_string();
73    db.toggle_pin(&path, display_name, &format)
74        .map_err(WorkspaceError::from)
75}
76
77/// All pins (files AND directories) in stored pin order. File rows are returned with a live read
78/// grant, so the row is directly openable the way an explorer row is. Directory pins hold no
79/// grant (grants cover file content only). Rows whose target vanished since pinning are skipped.
80pub fn list_pins(db: &Db, grants: &dyn PathGrants) -> Result<Vec<PinEntry>, WorkspaceError> {
81    let rows = db.list_pins()?;
82    let mut out = Vec::with_capacity(rows.len());
83    for entry in rows {
84        if entry.kind == "dir" {
85            if std::path::Path::new(&entry.path).is_dir() {
86                out.push(entry);
87            }
88        } else if let Ok(granted) =
89            grants.grant_existing_file_path(std::path::Path::new(&entry.path))
90        {
91            out.push(PinEntry {
92                path: granted,
93                ..entry
94            });
95        }
96    }
97    Ok(out)
98}
99
100/// Pin or unpin a DIRECTORY (the explorer sidebar's pinned folders). No grant is involved; the
101/// path is canonicalized and must exist and be a directory. Returns the new pinned state.
102pub fn toggle_pin_dir(
103    db: &Db,
104    grants: &dyn PathGrants,
105    app_name: &str,
106    path: &str,
107    display_name: &str,
108) -> Result<bool, WorkspaceError> {
109    let canon = std::fs::canonicalize(path).map_err(|e| fs_io_error(app_name, path, e))?;
110    if !canon.is_dir() {
111        return Err(WorkspaceError::FileNotFound(format!(
112            "not a folder: {path}"
113        )));
114    }
115    let path = grants.path_to_string(&canon);
116    db.toggle_pin_dir(&path, display_name)
117        .map_err(WorkspaceError::from)
118}
119
120pub fn record_recent(
121    db: &Db,
122    grants: &dyn PathGrants,
123    docs: &dyn DocumentBackend,
124    path: &str,
125    display_name: &str,
126) -> Result<(), WorkspaceError> {
127    let path = grants.require_existing_file(path).map_err(broker_error)?;
128    let format = docs.format_of(&path).to_string();
129    db.record_recent(&path, display_name, &format)
130        .map_err(WorkspaceError::from)
131}
132
133pub fn save_view_state(
134    db: &Db,
135    grants: &dyn PathGrants,
136    docs: &dyn DocumentBackend,
137    path: &str,
138    last_view: &str,
139    view_meta: Option<&str>,
140) -> Result<(), WorkspaceError> {
141    let path = grants.require_existing_file(path).map_err(broker_error)?;
142    let format = docs.format_of(&path).to_string();
143    let display_name = std::path::Path::new(&path)
144        .file_name()
145        .and_then(|n| n.to_str())
146        .unwrap_or(&path)
147        .to_string();
148    db.save_view_state(&path, last_view, view_meta, &display_name, &format)
149        .map_err(WorkspaceError::from)
150}
151
152pub fn save_session(
153    db: &Db,
154    grants: &dyn PathGrants,
155    tabs: Vec<(String, bool)>,
156) -> Result<(), WorkspaceError> {
157    // Only persist paths that the broker recognizes (have a live grant). Silently skip others.
158    let valid: Vec<(String, bool)> = tabs
159        .into_iter()
160        .filter(|(path, _)| grants.require_existing_file(path).is_ok())
161        .collect();
162    let refs: Vec<(&str, bool)> = valid.iter().map(|(p, a)| (p.as_str(), *a)).collect();
163    db.save_session(&refs).map_err(WorkspaceError::from)
164}
165
166pub fn load_session(
167    db: &Db,
168    grants: &dyn PathGrants,
169) -> Result<Vec<(String, bool)>, WorkspaceError> {
170    let rows = db.load_session().map_err(WorkspaceError::from)?;
171    // Map real paths to one-shot known tokens. Skip files that no longer exist.
172    let mut result = Vec::new();
173    for (path, active) in rows {
174        if let Ok(token) = grants.register_known_stored_path(&path) {
175            result.push((token, active));
176        }
177    }
178    Ok(result)
179}
180
181pub fn clear_session(db: &Db) -> Result<(), WorkspaceError> {
182    db.clear_session().map_err(WorkspaceError::from)
183}