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::CodeAction(_)
47            | Payload::Container(_) => return None,
48            Payload::Buffer(document) => {
49                let name = self
50                    .docs
51                    .get(*document)?
52                    .buf
53                    .path
54                    .as_ref()
55                    .map(|path| path.to_string_lossy().into_owned())
56                    .unwrap_or_else(|| "[scratch]".into());
57                return Some((name, None, PreviewSource::Buffer(*document)));
58            }
59            Payload::File(path) => (path.clone(), None),
60            Payload::Grep { path, line, .. } => (path.clone(), Some(*line)),
61            // A remote hit never previews from the local disk: the
62            // analogous path is another machine's file (0036). The
63            // endpoint-labelled title says where it lives; accepting
64            // opens it remotely.
65            Payload::Remote {
66                endpoint,
67                path,
68                line,
69                ..
70            } => {
71                return Some((
72                    format!("{endpoint}{}", path.display()),
73                    Some(*line),
74                    PreviewSource::Failed("remote hit — accept to open".into()),
75                ));
76            }
77        };
78        let full = self.cwd.join(&path);
79        let title = path.display().to_string();
80        if let Some((document, _)) = self
81            .docs
82            .iter()
83            .find(|(_, document)| document.buf.path.as_ref() == Some(&full))
84        {
85            return Some((title, focus_line, PreviewSource::Buffer(document)));
86        }
87        match self.preview_loads.get(&full) {
88            Some(Load::Failed { failure, .. }) => {
89                return Some((
90                    title,
91                    focus_line,
92                    PreviewSource::Failed(failure.message.clone()),
93                ));
94            }
95            Some(Load::Cancelled { reason, .. }) => {
96                return Some((title, focus_line, PreviewSource::Cancelled(*reason)));
97            }
98            _ => {}
99        }
100        if !self.preview_ready(&full) {
101            return Some((title, focus_line, PreviewSource::Loading));
102        }
103        Some((title, focus_line, PreviewSource::Cached(full)))
104    }
105
106    /// True when the preview is cached. Otherwise registers an owned
107    /// request for this picker instance (cancelling any stale one) and
108    /// launches the bounded read; the next tick picks the result up.
109    fn preview_ready(&mut self, path: &Path) -> bool {
110        if self.previews.contains_key(path) {
111            return true;
112        }
113        let Some(picker) = self.picker.as_ref().map(|glue| glue.id) else {
114            return false;
115        };
116        let key = PreviewKey {
117            picker,
118            path: path.to_path_buf(),
119        };
120        // a request from this instance — running, failed or cancelled —
121        // owns the path: frames never silently retry
122        if self
123            .preview_loads
124            .get(path)
125            .is_some_and(|load| load.covers(&key))
126        {
127            return false;
128        }
129        // a stale Running ticket (older instance) must not block
130        if let Some(Load::Running(old)) = self.preview_loads.get(path).cloned() {
131            if let Some(handle) = self.worker_handles.remove(&old.request) {
132                handle.cancel(CancelReason::Superseded);
133            }
134        }
135        let request = match self.worker_ids.allocate() {
136            Ok(request) => request,
137            Err(error) => {
138                self.message = error.message;
139                return false;
140            }
141        };
142        let ticket = Ticket {
143            request,
144            key: key.clone(),
145        };
146        // registration precedes launch — replay mode stops here and
147        // only injected results populate the cache
148        self.preview_loads
149            .insert(path.to_path_buf(), Load::Running(ticket.clone()));
150        strop_trace::record_with(strop_trace::EventKind::JobStarted, || {
151            serde_json::json!({
152                "service":"preview","request":request.get(),
153                "picker":picker.0.get(),"path":path.to_string_lossy(),
154            })
155        });
156        match self
157            .tape
158            .request("strop-preview", &serde_json::json!({"ticket":ticket}))
159        {
160            Ok(false) => return false,
161            Ok(true) => {}
162            Err(error) => {
163                self.handle_preview(PreviewResult {
164                    ticket,
165                    outcome: Outcome::failed(FailureKind::Protocol, error.to_string()),
166                });
167                return false;
168            }
169        }
170        let launch_path = path.to_path_buf();
171        let tx = self.preview_tx.clone();
172        let handle = worker::spawn(
173            "strop-preview",
174            move |outcome| {
175                let _ = tx.send(PreviewResult { ticket, outcome });
176            },
177            move |_| read_preview(&launch_path),
178        );
179        self.worker_handles.insert(request, handle);
180        false
181    }
182}
183
184/// The bounded preview read: at most 512 KiB, real files only, valid
185/// UTF-8 — every miss is a typed failure, never an empty success. The
186/// read stays capped even if the file grows after metadata.
187pub(crate) fn read_preview(path: &Path) -> Outcome<PreparedPreview> {
188    const LIMIT: u64 = 512 * 1024;
189    let read = || -> Result<String, Failure> {
190        let meta =
191            std::fs::metadata(path).map_err(|e| Failure::new(FailureKind::Io, e.to_string()))?;
192        if !meta.is_file() {
193            return Err(Failure::new(
194                FailureKind::Unavailable,
195                "preview target is not a file",
196            ));
197        }
198        if meta.len() > LIMIT {
199            return Err(Failure::new(FailureKind::Unavailable, "preview too large"));
200        }
201        let file =
202            std::fs::File::open(path).map_err(|e| Failure::new(FailureKind::Io, e.to_string()))?;
203        let mut bytes = Vec::new();
204        file.take(LIMIT + 1)
205            .read_to_end(&mut bytes)
206            .map_err(|e| Failure::new(FailureKind::Io, e.to_string()))?;
207        if bytes.len() as u64 > LIMIT {
208            return Err(Failure::new(FailureKind::Unavailable, "preview too large"));
209        }
210        String::from_utf8(bytes).map_err(|e| Failure::new(FailureKind::Io, e.to_string()))
211    };
212    match read() {
213        Ok(text) => Outcome::Success(text.into()),
214        Err(failure) => Outcome::Failed {
215            failure,
216            partial: None,
217        },
218    }
219}