Skip to main content

strop_engine/editor/picker/
preview.rs

1//! Picker preview: bounded worker-prepared ropes; open documents use their live
2//! snapshots. Syntax belongs to the display-analysis actor, not the UI. Reads run as
3//! worker requests — registration precedes launch, every miss is a
4//! typed failure (never an empty success), and a failure never poisons
5//! the path forever.
6
7use std::io::Read;
8use std::path::Path;
9
10use strop_core::worker::{self, CancelReason, Failure, FailureKind, Load, Outcome, Ticket};
11use strop_picker::Payload;
12
13use super::super::Editor;
14use super::{PreviewKey, PreviewResult, PreviewSource};
15
16/// Live delivery already owns a rope. Replay reconstructs the same pure snapshot
17/// from the recorded text; no parser or filesystem access crosses this boundary.
18#[derive(Debug, Clone)]
19pub struct PreparedPreview {
20    pub rope: ropey::Rope,
21}
22impl From<String> for PreparedPreview {
23    fn from(text: String) -> Self {
24        Self {
25            rope: ropey::Rope::from_str(&text),
26        }
27    }
28}
29impl serde::Serialize for PreparedPreview {
30    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
31        serializer.collect_str(&self.rope)
32    }
33}
34impl<'de> serde::Deserialize<'de> for PreparedPreview {
35    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
36        String::deserialize(deserializer).map(Self::from)
37    }
38}
39
40impl Editor {
41    pub fn picker_preview(&mut self) -> Option<(String, Option<usize>, PreviewSource)> {
42        let item = self.picker.as_ref()?.picker.current()?;
43        let (path, focus_line) = match &item.payload {
44            Payload::RemoteDirectory(_)
45            | Payload::RemoteConnect
46            | Payload::Jump { .. }
47            | Payload::CodeAction(_)
48            | Payload::Container(_) => return None,
49            Payload::Buffer(document) => {
50                let name = self
51                    .docs
52                    .get(*document)?
53                    .buf
54                    .path
55                    .as_ref()
56                    .map(|path| path.to_string_lossy().into_owned())
57                    .unwrap_or_else(|| "[scratch]".into());
58                return Some((name, None, PreviewSource::Buffer(*document)));
59            }
60            Payload::File(path) => (path.clone(), None),
61            Payload::Grep { path, line, .. } => (path.clone(), Some(*line)),
62            // A remote hit never previews from the local disk: the
63            // analogous path is another machine's file (0036). The
64            // endpoint-labelled title says where it lives; accepting
65            // opens it remotely.
66            Payload::Remote {
67                endpoint,
68                path,
69                line,
70                ..
71            } => {
72                return Some((
73                    format!("{endpoint}{}", path.display()),
74                    Some(*line),
75                    PreviewSource::Failed("remote hit — accept to open".into()),
76                ));
77            }
78        };
79        let full = self.cwd.join(&path);
80        let title = path.display().to_string();
81        if let Some((document, _)) = self
82            .docs
83            .iter()
84            .find(|(_, document)| document.buf.path.as_ref() == Some(&full))
85        {
86            return Some((title, focus_line, PreviewSource::Buffer(document)));
87        }
88        match self.preview_loads.get(&full) {
89            Some(Load::Failed { failure, .. }) => {
90                return Some((
91                    title,
92                    focus_line,
93                    PreviewSource::Failed(failure.message.clone()),
94                ));
95            }
96            Some(Load::Cancelled { reason, .. }) => {
97                return Some((title, focus_line, PreviewSource::Cancelled(*reason)));
98            }
99            _ => {}
100        }
101        if !self.preview_ready(&full) {
102            return Some((title, focus_line, PreviewSource::Loading));
103        }
104        Some((title, focus_line, PreviewSource::Cached(full)))
105    }
106
107    /// True when the preview is cached. Otherwise registers an owned
108    /// request for this picker instance (cancelling any stale one) and
109    /// launches the bounded read; the next tick picks the result up.
110    fn preview_ready(&mut self, path: &Path) -> bool {
111        if self.previews.contains_key(path) {
112            return true;
113        }
114        let Some(picker) = self.picker.as_ref().map(|glue| glue.id) else {
115            return false;
116        };
117        let key = PreviewKey {
118            picker,
119            path: path.to_path_buf(),
120        };
121        // a request from this instance — running, failed or cancelled —
122        // owns the path: frames never silently retry
123        if self
124            .preview_loads
125            .get(path)
126            .is_some_and(|load| load.covers(&key))
127        {
128            return false;
129        }
130        // a stale Running ticket (older instance) must not block
131        if let Some(Load::Running(old)) = self.preview_loads.get(path).cloned() {
132            if let Some(handle) = self.worker_handles.remove(&old.request) {
133                handle.cancel(CancelReason::Superseded);
134            }
135        }
136        let request = match self.worker_ids.allocate() {
137            Ok(request) => request,
138            Err(error) => {
139                self.message = error.message;
140                return false;
141            }
142        };
143        let ticket = Ticket {
144            request,
145            key: key.clone(),
146        };
147        // registration precedes launch — replay mode stops here and
148        // only injected results populate the cache
149        self.preview_loads
150            .insert(path.to_path_buf(), Load::Running(ticket.clone()));
151        strop_trace::record_with(strop_trace::EventKind::JobStarted, || {
152            serde_json::json!({
153                "service":"preview","request":request.get(),
154                "picker":picker.0.get(),"path":path.to_string_lossy(),
155            })
156        });
157        match self
158            .tape
159            .request("strop-preview", &serde_json::json!({"ticket":ticket}))
160        {
161            Ok(false) => return false,
162            Ok(true) => {}
163            Err(error) => {
164                self.handle_preview(PreviewResult {
165                    ticket,
166                    outcome: Outcome::failed(FailureKind::Protocol, error.to_string()),
167                });
168                return false;
169            }
170        }
171        let launch_path = path.to_path_buf();
172        let tx = self.preview_tx.clone();
173        let handle = worker::spawn(
174            "strop-preview",
175            move |outcome| {
176                let _ = tx.send(PreviewResult { ticket, outcome });
177            },
178            move |_| read_preview(&launch_path),
179        );
180        self.worker_handles.insert(request, handle);
181        false
182    }
183}
184
185/// The bounded preview read: at most 512 KiB, real files only, valid
186/// UTF-8 — every miss is a typed failure, never an empty success. The
187/// read stays capped even if the file grows after metadata.
188pub(crate) fn read_preview(path: &Path) -> Outcome<PreparedPreview> {
189    const LIMIT: u64 = 512 * 1024;
190    let read = || -> Result<String, Failure> {
191        let meta =
192            std::fs::metadata(path).map_err(|e| Failure::new(FailureKind::Io, e.to_string()))?;
193        if !meta.is_file() {
194            return Err(Failure::new(
195                FailureKind::Unavailable,
196                "preview target is not a file",
197            ));
198        }
199        if meta.len() > LIMIT {
200            return Err(Failure::new(FailureKind::Unavailable, "preview too large"));
201        }
202        let file =
203            std::fs::File::open(path).map_err(|e| Failure::new(FailureKind::Io, e.to_string()))?;
204        let mut bytes = Vec::new();
205        file.take(LIMIT + 1)
206            .read_to_end(&mut bytes)
207            .map_err(|e| Failure::new(FailureKind::Io, e.to_string()))?;
208        if bytes.len() as u64 > LIMIT {
209            return Err(Failure::new(FailureKind::Unavailable, "preview too large"));
210        }
211        String::from_utf8(bytes).map_err(|e| Failure::new(FailureKind::Io, e.to_string()))
212    };
213    match read() {
214        Ok(text) => Outcome::Success(text.into()),
215        Err(failure) => Outcome::Failed {
216            failure,
217            partial: None,
218        },
219    }
220}