Skip to main content

artifactize_core/
viewer.rs

1//! The desktop hosts a viewer; this library decides what its bridge can read.
2
3mod review;
4
5pub use review::{Address, ReviewScope, review_checkout, review_scope};
6
7use std::{
8    fs::File,
9    path::{Path, PathBuf},
10};
11
12use artifactize_tools::scope::{self, InputPath};
13use serde::Serialize;
14
15use crate::{
16    config::{
17        self, Artifact, ArtifactKind, PluginName, RepoConfig,
18        plugins::{BuiltinViewer, ViewerEntry},
19    },
20    graph_structure, platform, repository,
21    types::{ArtifactName, RequestId, ReviewerId},
22};
23
24/// Relative file reads and directory listings use the selected Artifact's own scope, not the
25/// workspace or the rest of the review's scope. A viewer cannot choose its own scope.
26#[derive(Debug, Clone)]
27pub struct Session {
28    root: PathBuf,
29    checkout: repository::Identity,
30    artifact: Artifact,
31    /// The viewer tool that opened it, and the plugin whose page it shows.
32    tool: config::ToolFqn,
33    plugin: PluginName,
34    title: String,
35    entry: ViewerEntry,
36}
37
38/// The ownership boundaries that can change while the Artifact's target remains the same.
39#[derive(Debug, Clone, Default, PartialEq, Eq)]
40pub struct Scope {
41    nested: std::collections::BTreeMap<config::ChildPrefix, ArtifactName>,
42    covering_part: Option<ArtifactName>,
43}
44
45#[derive(Debug, Clone)]
46pub struct Review {
47    pub id: RequestId,
48    pub reviewer: ReviewerId,
49}
50
51#[derive(Debug, Serialize)]
52#[serde(rename_all = "camelCase")]
53pub struct Context<'a> {
54    pub artifact: &'a ArtifactName,
55    #[serde(rename = "type")]
56    pub type_name: &'a PluginName,
57    pub title: &'a str,
58    pub target: &'a config::Target,
59    pub target_kind: ArtifactKind,
60    pub review: Option<&'a RequestId>,
61}
62
63#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
64#[serde(rename_all = "lowercase")]
65pub enum EntryKind {
66    File,
67    Directory,
68}
69
70#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
71pub struct FileEntry {
72    pub name: String,
73    pub path: InputPath,
74    pub kind: EntryKind,
75}
76
77impl Session {
78    pub fn open(
79        repo: &Path,
80        artifact: &ArtifactName,
81        tool: &config::ToolFqn,
82    ) -> Result<Self, String> {
83        let config = config::read_workspace_config(repo).map_err(|error| error.to_string())?;
84        Self::from_config(&config, artifact, tool)
85    }
86
87    pub(crate) fn from_config(
88        config: &RepoConfig,
89        artifact: &ArtifactName,
90        tool: &config::ToolFqn,
91    ) -> Result<Self, String> {
92        let artifact = config
93            .artifacts
94            .get(artifact)
95            .ok_or_else(|| format!("Unknown Artifact {artifact}."))?;
96        let Some(config::HumanTool::Viewer(viewer)) = artifact.views.human_tools.get(tool) else {
97            return Err(format!(
98                "Artifact {} has no viewer tool {tool}.",
99                artifact.name
100            ));
101        };
102        let plugin = config
103            .plugins
104            .get(&viewer.plugin)
105            .ok_or_else(|| format!("Plugin {} is not installed.", viewer.plugin))?;
106        let entry = plugin
107            .viewer
108            .clone()
109            .ok_or_else(|| format!("Plugin {} has no viewer.", viewer.plugin))?;
110        crate::scope::validate_file_target(&config.root, artifact)
111            .map_err(|error| error.to_string())?;
112        Ok(Self {
113            root: config.root.clone(),
114            checkout: repository::identify(&config.root),
115            artifact: artifact.clone(),
116            tool: tool.clone(),
117            plugin: plugin.info.name.clone(),
118            title: plugin.info.title.clone(),
119            entry,
120        })
121    }
122
123    /// The viewer tool that opened it.
124    pub fn tool(&self) -> &config::ToolFqn {
125        &self.tool
126    }
127
128    pub fn scope(&self) -> Scope {
129        Scope {
130            nested: self.artifact.nested.clone(),
131            covering_part: self.artifact.covering_part.clone(),
132        }
133    }
134
135    pub fn workspace(&self) -> &Path {
136        &self.root
137    }
138
139    pub fn checkout(&self) -> &repository::Identity {
140        &self.checkout
141    }
142
143    /// The same path may later hold different branch contents and must not be reused.
144    pub fn check_checkout(&self) -> Result<(), String> {
145        check_checkout(&self.root, &self.checkout)
146    }
147
148    /// An already-open viewer's scope cannot authorize access after a declaration changes.
149    pub fn check_scope(&self) -> Result<(), String> {
150        self.check_checkout()?;
151        let config =
152            config::read_workspace_config(&self.root).map_err(|error| error.to_string())?;
153        if config
154            .artifacts
155            .get(&self.artifact.name)
156            .is_some_and(|current| {
157                current.path == self.artifact.path
158                    && matches!(
159                        current.views.human_tools.get(&self.tool),
160                        Some(config::HumanTool::Viewer(viewer)) if viewer.plugin == self.plugin
161                    )
162                    && current.nested == self.artifact.nested
163                    && current.covering_part == self.artifact.covering_part
164            })
165        {
166            Ok(())
167        } else {
168            Err("This Artifact's viewer scope has changed. Reopen the viewer.".into())
169        }
170    }
171
172    pub fn entry(&self) -> &ViewerEntry {
173        &self.entry
174    }
175
176    pub fn context<'a>(&'a self, review: Option<&'a Review>) -> Context<'a> {
177        Context {
178            artifact: &self.artifact.name,
179            type_name: &self.plugin,
180            title: &self.title,
181            target: &self.artifact.path,
182            target_kind: self.artifact.kind(),
183            review: review.map(|review| &review.id),
184        }
185    }
186
187    /// Append a Point to the host-selected review; the store rechecks its claim atomically.
188    pub async fn pointing(
189        &self,
190        state: &Path,
191        review: &Review,
192        text: &str,
193    ) -> Result<crate::review::Draft, String> {
194        let session = self.clone();
195        crate::task::blocking(move || session.check_scope()).await??;
196        let context = self.context(None);
197        let source = format!("{} ยท {}", context.artifact, context.title);
198        crate::review::append_point(state, &review.id, &review.reviewer, text, &source).await
199    }
200
201    pub fn read_text(&self, path: &InputPath) -> Result<String, String> {
202        self.check_scope()?;
203        let path = self
204            .artifact
205            .file_name()
206            .filter(|_| path.as_str().is_empty())
207            .unwrap_or(path.as_str());
208        config::plugins::read_document(self.open_file(path)?)
209    }
210
211    /// Read one directory at a time. Never list non-owned siblings of a file Artifact or
212    /// directories outside an aspect's selection.
213    pub fn files(&self, path: &InputPath) -> Result<Vec<FileEntry>, String> {
214        self.check_scope()?;
215        let path = path.as_str();
216        if path.is_empty()
217            && let Some(name) = self.artifact.file_name()
218        {
219            self.open_file(name)?;
220            return Ok(vec![FileEntry {
221                name: name.into(),
222                path: name
223                    .parse()
224                    .map_err(|error: scope::ScopeError| error.to_string())?,
225                kind: EntryKind::File,
226            }]);
227        }
228        let directory = self.open_file(path)?;
229        let mut entries = Vec::new();
230        for entry in platform::read_dir(&directory).map_err(|error| error.to_string())? {
231            let entry = entry.map_err(|error| error.to_string())?;
232            let name = entry.file_name();
233            let Some(name) = platform::os_text(&name) else {
234                continue;
235            };
236            let child = if path.is_empty() {
237                name.to_owned()
238            } else {
239                format!("{path}/{name}")
240            };
241            let Ok(child_path) = child.parse::<InputPath>() else {
242                continue;
243            };
244            let kind = match entry.file_type().map_err(|error| error.to_string())? {
245                platform::FileKind::File => EntryKind::File,
246                platform::FileKind::Directory => EntryKind::Directory,
247                _ => continue,
248            };
249            if self.open_file(child_path.as_str()).is_ok() {
250                entries.push(FileEntry {
251                    name: name.into(),
252                    path: child_path,
253                    kind,
254                });
255            }
256        }
257        entries.sort_by(|left, right| left.path.cmp(&right.path));
258        Ok(entries)
259    }
260
261    pub fn declarations(&self) -> Result<graph_structure::Structure, String> {
262        self.check_scope()?;
263        if !matches!(
264            self.entry,
265            ViewerEntry::Builtin {
266                viewer: BuiltinViewer::Artifactize
267            }
268        ) {
269            return Err("Only an Artifactize Viewer can read the declared graph.".into());
270        }
271        graph_structure::read_scoped(&self.root, &self.artifact)
272    }
273
274    fn open_file(&self, path: &str) -> Result<File, String> {
275        if self.artifact.covering_part.is_some() {
276            return Err("This Artifact's files belong to a folder part.".into());
277        }
278        scope::open_input(&self.root, &self.artifact.tool_scope(), path)
279            .map_err(|error| error.to_string())
280    }
281}
282
283fn check_checkout(worktree: &Path, checkout: &repository::Identity) -> Result<(), String> {
284    if worktree.is_dir() && repository::identify(worktree) == *checkout {
285        Ok(())
286    } else {
287        Err("This Artifact Viewer's checkout changed. Reopen the viewer.".into())
288    }
289}