/builds/framezero/productivity/src/ui/notes/diagrams.rs
Line | Count | Source |
1 | | //! Background Mermaid rendering for note previews. |
2 | | //! |
3 | | //! Each preview asks for its diagrams on every render. Missing diagrams render on the |
4 | | //! background executor, keyed by source and appearance; until then (and on failure) the |
5 | | //! fenced source stays visible. When a preview stops asking for a diagram that is still |
6 | | //! rendering, that work is cancelled, so fast typing does not queue stale renders. |
7 | | |
8 | | use std::{ |
9 | | collections::{HashMap, HashSet, VecDeque}, |
10 | | sync::{Arc, Mutex}, |
11 | | }; |
12 | | |
13 | | use productivity::{ |
14 | | application::diagrams::{ |
15 | | DiagramAppearance, DiagramCancellation, DiagramError, render_mermaid_svg, |
16 | | }, |
17 | | core::note_preview::{DiagramSlot, PreparedPreview}, |
18 | | }; |
19 | | |
20 | | /// Finished diagrams kept for reuse; older ones are rendered again when needed. |
21 | | const MAX_FINISHED: usize = 64; |
22 | | |
23 | | type Key = (String, DiagramAppearance); |
24 | | |
25 | | enum Entry { |
26 | | Pending { |
27 | | generation: u64, |
28 | | cancellation: DiagramCancellation, |
29 | | }, |
30 | | Ready(Arc<gpui::Image>), |
31 | | Failed(String), |
32 | | } |
33 | | |
34 | | #[derive(Default)] |
35 | | struct State { |
36 | | entries: HashMap<Key, Entry>, |
37 | | finished: VecDeque<Key>, |
38 | | /// The keys each preview asked for in its latest render. |
39 | | requested: HashMap<gpui::SharedString, HashSet<Key>>, |
40 | | generation: u64, |
41 | | } |
42 | | |
43 | | /// Rendered diagrams shared by every note preview. |
44 | | #[derive(Clone, Default)] |
45 | | pub(in crate::ui) struct DiagramCache(Arc<Mutex<State>>); |
46 | | |
47 | | /// The Markdown to show for a preview, the rendered images it references, and the |
48 | | /// diagrams that still need rendering. |
49 | | pub(super) struct DiagramPass { |
50 | | pub(super) markdown: String, |
51 | | pub(super) images: HashMap<usize, Arc<gpui::Image>>, |
52 | | pub(super) start: Vec<(Key, u64, DiagramCancellation)>, |
53 | | } |
54 | | |
55 | | impl DiagramCache { |
56 | | /// Resolves `preview`'s diagrams for the preview called `owner`, cancelling renders the |
57 | | /// owner no longer needs. Returned renders must be started with [`Self::render`]. |
58 | 1.35k | pub(super) fn pass( |
59 | 1.35k | &self, |
60 | 1.35k | owner: impl Into<gpui::SharedString>, |
61 | 1.35k | preview: &PreparedPreview, |
62 | 1.35k | appearance: DiagramAppearance, |
63 | 1.35k | ) -> DiagramPass { |
64 | 1.35k | let Ok(mut state) = self.0.lock() else { |
65 | | return DiagramPass { |
66 | 0 | markdown: preview.markdown_with_diagrams(|_| DiagramSlot::Source), |
67 | 0 | images: HashMap::new(), |
68 | 0 | start: Vec::new(), |
69 | | }; |
70 | | }; |
71 | 1.35k | let mut images = HashMap::new(); |
72 | 1.35k | let mut start = Vec::new(); |
73 | 1.35k | let mut requested = HashSet::new(); |
74 | 1.35k | let markdown = preview.markdown_with_diagrams(|index| {18 |
75 | 18 | let key = (preview.diagrams[index].source.clone(), appearance); |
76 | 18 | requested.insert(key.clone()); |
77 | 18 | match state.entries.get(&key) { |
78 | | Some(Entry::Ready(image)) => { |
79 | 7 | images.insert(index, image.clone()); |
80 | 7 | DiagramSlot::Rendered |
81 | | } |
82 | 5 | Some(Entry::Failed(message)) => DiagramSlot::Failed(message.clone()), |
83 | 1 | Some(Entry::Pending { .. }) => DiagramSlot::Source, |
84 | | None => { |
85 | 5 | state.generation += 1; |
86 | 5 | let generation = state.generation; |
87 | 5 | let cancellation = DiagramCancellation::new(); |
88 | 5 | state.entries.insert( |
89 | 5 | key.clone(), |
90 | 5 | Entry::Pending { |
91 | 5 | generation, |
92 | 5 | cancellation: cancellation.clone(), |
93 | 5 | }, |
94 | 5 | ); |
95 | 5 | start.push((key, generation, cancellation)); |
96 | 5 | DiagramSlot::Source |
97 | | } |
98 | | } |
99 | 18 | }); |
100 | 1.35k | let previous = state |
101 | 1.35k | .requested |
102 | 1.35k | .insert(owner.into(), requested) |
103 | 1.35k | .unwrap_or_default(); |
104 | 1.35k | let still_wanted: HashSet<Key> = state.requested.values().flatten().cloned().collect(); |
105 | 1.35k | for key in previous.difference(&still_wanted) { |
106 | 2 | if let Some(Entry::Pending { cancellation, .. }) = state.entries.get(key) { |
107 | 1 | cancellation.cancel(); |
108 | 1 | state.entries.remove(key); |
109 | 1 | } |
110 | | } |
111 | 1.35k | DiagramPass { |
112 | 1.35k | markdown, |
113 | 1.35k | images, |
114 | 1.35k | start, |
115 | 1.35k | } |
116 | 1.35k | } |
117 | | |
118 | | /// Renders one diagram off the UI thread and records the result, unless the request was |
119 | | /// superseded meanwhile. Returns whether the cache changed. |
120 | 4 | pub(super) async fn render( |
121 | 4 | &self, |
122 | 4 | executor: gpui::BackgroundExecutor, |
123 | 4 | (key, generation, cancellation): (Key, u64, DiagramCancellation), |
124 | 4 | ) -> bool { |
125 | 4 | let (source, appearance) = key.clone(); |
126 | 4 | let result = executor |
127 | 4 | .spawn(async move { render_mermaid_svg(&source, appearance, &cancellation) }) |
128 | 4 | .await; |
129 | 4 | let Ok(mut state) = self.0.lock() else { |
130 | 0 | return false; |
131 | | }; |
132 | 4 | let current = matches!( |
133 | 4 | state.entries.get(&key), |
134 | 3 | Some(Entry::Pending { generation: pending, .. }) if *pending == generation |
135 | | ); |
136 | 4 | if !current { |
137 | 1 | return false; |
138 | 3 | } |
139 | 3 | let entry = match result { |
140 | 2 | Ok(svg) => Entry::Ready(Arc::new(gpui::Image::from_bytes( |
141 | 2 | gpui::ImageFormat::Svg, |
142 | 2 | svg.into_bytes(), |
143 | 2 | ))), |
144 | | Err(DiagramError::Cancelled) => { |
145 | 0 | state.entries.remove(&key); |
146 | 0 | return true; |
147 | | } |
148 | 1 | Err(error) => Entry::Failed(error.to_string()), |
149 | | }; |
150 | 3 | state.entries.insert(key.clone(), entry); |
151 | 3 | state.finished.push_back(key); |
152 | 3 | while state.finished.len() > MAX_FINISHED { |
153 | 0 | if let Some(old) = state.finished.pop_front() { |
154 | 0 | state.entries.remove(&old); |
155 | 0 | } |
156 | | } |
157 | 3 | true |
158 | 4 | } |
159 | | |
160 | | #[cfg(all(test, feature = "ui-tests"))] |
161 | 1 | pub(super) fn ready(&self, source: &str) -> Option<Arc<gpui::Image>> { |
162 | 1 | let state = self.0.lock().ok()?0 ; |
163 | 1 | state |
164 | 1 | .entries |
165 | 1 | .iter() |
166 | 1 | .find_map(|((key, _), entry)| match entry { |
167 | 1 | Entry::Ready(image) if key == source => Some(image.clone()), |
168 | 0 | _ => None, |
169 | 1 | }) |
170 | 1 | } |
171 | | |
172 | | /// Finished diagram images kept in memory and their encoded size in bytes. |
173 | 28 | pub(in crate::ui) fn memory_usage(&self) -> (usize, u64) { |
174 | 28 | self.0.lock().map_or((0, 0), |state| { |
175 | 28 | state |
176 | 28 | .entries |
177 | 28 | .values() |
178 | 0 | .filter_map(|entry| match entry { |
179 | 0 | Entry::Ready(image) => Some(image.bytes.len() as u64), |
180 | 0 | _ => None, |
181 | 0 | }) |
182 | 28 | .fold((0, 0), |(count, bytes), size| (count + 10 , bytes + size0 )) |
183 | 28 | }) |
184 | 28 | } |
185 | | |
186 | | #[cfg(all(test, feature = "ui-tests"))] |
187 | 3 | pub(super) fn pending(&self) -> usize { |
188 | 3 | self.0.lock().map_or(0, |state| { |
189 | 3 | state |
190 | 3 | .entries |
191 | 3 | .values() |
192 | 4 | .filter(|entry| matches!(entry, Entry::Pending { .. })) |
193 | | .count() |
194 | 3 | }) |
195 | 3 | } |
196 | | } |
197 | | |
198 | | #[cfg(all(test, feature = "ui-tests"))] |
199 | | mod tests { |
200 | | use super::*; |
201 | | |
202 | 2 | fn preview(source: &str) -> PreparedPreview { |
203 | 2 | productivity::core::note_preview::prepare_preview_with_images( |
204 | 2 | &format!("```mermaid\n{source}\n```\n"), |
205 | 2 | "note.md", |
206 | 2 | ) |
207 | 2 | .unwrap() |
208 | 2 | } |
209 | | |
210 | | #[gpui::test] |
211 | 1 | async fn superseded_renders_are_cancelled_and_results_cached(cx: &mut gpui::TestAppContext) { |
212 | 1 | let cache = DiagramCache::default(); |
213 | 1 | let first = preview("flowchart TD\n A --> B"); |
214 | 1 | let second = preview("flowchart TD\n A --> C"); |
215 | 1 | let started = cache.pass("editor", &first, DiagramAppearance::Light); |
216 | 1 | assert_eq!(started.start.len(), 1); |
217 | | // Typing replaces the diagram before the first render ran: it is cancelled. |
218 | 1 | let replaced = cache.pass("editor", &second, DiagramAppearance::Light); |
219 | 1 | assert_eq!(cache.pending(), 1); |
220 | 1 | let first_request = started.start.into_iter().next().unwrap(); |
221 | 1 | assert!(!cache.render(cx.executor(), first_request).await); |
222 | 1 | for request in replaced.start { |
223 | 1 | assert!(cache.render(cx.executor(), request).await); |
224 | | } |
225 | 1 | assert_eq!(cache.pending(), 0); |
226 | 1 | let shown = cache.pass("editor", &second, DiagramAppearance::Light); |
227 | 1 | assert!(shown.start.is_empty()); |
228 | 1 | assert!(shown.markdown.contains("productivity-diagram:0")); |
229 | 1 | assert!(shown.images.contains_key(&0)); |
230 | | // Another appearance is a separate render. |
231 | 1 | assert_eq!( |
232 | 1 | cache |
233 | 1 | .pass("editor", &second, DiagramAppearance::Dark) |
234 | 1 | .start |
235 | 1 | .len(), |
236 | 1 | 1 |
237 | | ); |
238 | 1 | } |
239 | | } |