1use std::sync::{Arc, Mutex, MutexGuard, RwLock, RwLockReadGuard, RwLockWriteGuard};
2
3use crate::JobId;
4
5type Repainter = Arc<dyn Fn() + Send + Sync>;
8
9#[derive(Debug, Clone, Copy)]
11pub enum PromptSegment {
12 Left,
14
15 Right,
17
18 Indicator,
20
21 ViInsert,
23
24 ViNormal,
26
27 Multiline,
29}
30
31#[derive(Debug, Default, Clone)]
33pub struct PromptContents {
34 pub left: Option<Arc<str>>,
35 pub right: Option<Arc<str>>,
36 pub indicator: Option<Arc<str>>,
37 pub vi_insert: Option<Arc<str>>,
38 pub vi_normal: Option<Arc<str>>,
39 pub multiline: Option<Arc<str>>,
40 pub render_right_on_last_line: bool,
41}
42
43impl PromptContents {
44 pub fn apply_segment_override(&mut self, segment: PromptSegment, content: impl Into<Arc<str>>) {
46 let content = content.into();
47 match segment {
48 PromptSegment::Left => self.left = Some(content),
49 PromptSegment::Right => self.right = Some(content),
50 PromptSegment::Indicator => self.indicator = Some(content),
51 PromptSegment::ViInsert => self.vi_insert = Some(content),
52 PromptSegment::ViNormal => self.vi_normal = Some(content),
53 PromptSegment::Multiline => self.multiline = Some(content),
54 }
55 }
56
57 pub fn overridden_by(&self, overrides: &PromptContents) -> PromptContents {
65 PromptContents {
66 left: overrides.left.clone().or_else(|| self.left.clone()),
67 right: overrides.right.clone().or_else(|| self.right.clone()),
68 indicator: overrides
69 .indicator
70 .clone()
71 .or_else(|| self.indicator.clone()),
72 vi_insert: overrides
73 .vi_insert
74 .clone()
75 .or_else(|| self.vi_insert.clone()),
76 vi_normal: overrides
77 .vi_normal
78 .clone()
79 .or_else(|| self.vi_normal.clone()),
80 multiline: overrides
81 .multiline
82 .clone()
83 .or_else(|| self.multiline.clone()),
84 render_right_on_last_line: self.render_right_on_last_line,
85 }
86 }
87}
88
89#[derive(Debug, Default)]
91struct PromptData {
92 contents: PromptContents,
93
94 pending: Option<PendingPushes>,
98}
99
100#[derive(Debug)]
102struct PendingPushes {
103 first_job: JobId,
107
108 pushed: PromptContents,
109}
110
111impl PendingPushes {
112 fn accepts(&self, root_job: JobId) -> bool {
114 root_job == JobId::ZERO || root_job >= self.first_job
115 }
116}
117
118#[derive(derive_more::Debug, Default)]
120pub struct PromptState {
121 data: RwLock<PromptData>,
124
125 #[debug(skip)]
128 repainter: Mutex<Option<Repainter>>,
129}
130
131impl PromptState {
132 pub fn new() -> Self {
133 Self::default()
134 }
135
136 fn acquire_read_lock(&self) -> RwLockReadGuard<'_, PromptData> {
137 self.data
138 .read()
139 .unwrap_or_else(|poisoned_error| poisoned_error.into_inner())
140 }
141
142 fn acquire_write_lock(&self) -> RwLockWriteGuard<'_, PromptData> {
143 self.data
144 .write()
145 .unwrap_or_else(|poisoned_error| poisoned_error.into_inner())
146 }
147
148 fn acquire_repainter_lock(&self) -> MutexGuard<'_, Option<Repainter>> {
149 self.repainter
150 .lock()
151 .unwrap_or_else(|poisoned_error| poisoned_error.into_inner())
152 }
153
154 pub fn with_contents<ReturnType>(
156 &self,
157 action: impl FnOnce(&PromptContents) -> ReturnType,
158 ) -> ReturnType {
159 action(&self.acquire_read_lock().contents)
160 }
161
162 pub fn contents(&self) -> PromptContents {
164 self.with_contents(PromptContents::clone)
165 }
166
167 pub fn begin_update(&self, first_job: JobId) {
178 self.acquire_write_lock().pending = Some(PendingPushes {
179 first_job,
180 pushed: PromptContents::default(),
181 });
182 }
183
184 pub fn set_contents(&self, new_contents: PromptContents) {
187 let mut data = self.acquire_write_lock();
188 data.contents = match data.pending.take() {
189 Some(pending) => new_contents.overridden_by(&pending.pushed),
190 None => new_contents,
191 };
192 }
193
194 pub fn apply(&self, pushed: PromptContents, root_job: JobId) {
202 let mut data = self.acquire_write_lock();
203 data.contents = data.contents.overridden_by(&pushed);
204 if let Some(pending) = &mut data.pending
205 && pending.accepts(root_job)
206 {
207 pending.pushed = pending.pushed.overridden_by(&pushed);
208 }
209 drop(data);
211 self.request_repaint();
212 }
213
214 pub fn set(&self, segment: PromptSegment, content: impl Into<Arc<str>>, root_job: JobId) {
217 let mut pushed = PromptContents::default();
218 pushed.apply_segment_override(segment, content);
219 self.apply(pushed, root_job);
220 }
221
222 pub fn set_repainter(&self, new_repainter: Option<Repainter>) {
224 *self.acquire_repainter_lock() = new_repainter;
225 }
226
227 fn request_repaint(&self) {
229 let local_repainter = self.acquire_repainter_lock().clone();
232
233 if let Some(repainter) = local_repainter {
234 repainter();
235 }
236 }
237}
238
239#[cfg(test)]
240mod tests {
241 use super::*;
242 use std::sync::atomic::{AtomicUsize, Ordering};
243
244 const JOB: JobId = JobId::new(1);
246
247 fn setup_state_with_counter() -> (Arc<PromptState>, Arc<AtomicUsize>) {
249 let state = Arc::new(PromptState::new());
250 let repainter_count = Arc::new(AtomicUsize::new(0));
251 let counter_reference = Arc::clone(&repainter_count);
252
253 state.set_repainter(Some(Arc::new(move || {
254 counter_reference.fetch_add(1, Ordering::Relaxed);
255 })));
256
257 (state, repainter_count)
258 }
259
260 #[test]
261 fn set_writes_only_the_targeted_segment() {
262 let state = PromptState::new();
263 state.set(PromptSegment::Left, "LeftSegment", JOB);
264
265 let contents = state.contents();
266 assert_eq!(contents.left.as_deref(), Some("LeftSegment"));
267 assert_eq!(contents.right, None);
268 }
269
270 #[test]
271 fn indicator_vi_insert_vi_normal_and_multiline_are_independent() {
272 let state = PromptState::new();
273 let mut pushed = PromptContents::default();
274 pushed.apply_segment_override(PromptSegment::Indicator, "Indicator");
275 pushed.apply_segment_override(PromptSegment::ViInsert, "ViInsert");
276 pushed.apply_segment_override(PromptSegment::ViNormal, "ViNormal");
277 pushed.apply_segment_override(PromptSegment::Multiline, "Multiline");
278 state.apply(pushed, JOB);
279
280 let contents = state.contents();
281 assert_eq!(contents.indicator.as_deref(), Some("Indicator"));
282 assert_eq!(contents.vi_insert.as_deref(), Some("ViInsert"));
283 assert_eq!(contents.vi_normal.as_deref(), Some("ViNormal"));
284 assert_eq!(contents.multiline.as_deref(), Some("Multiline"));
285 }
286
287 #[test]
288 fn each_set_triggers_exactly_one_repaint() {
289 let (state, repainter_count) = setup_state_with_counter();
290 state.set(PromptSegment::Left, "Alpha", JOB);
291 state.set(PromptSegment::Right, "Beta", JOB);
292
293 assert_eq!(repainter_count.load(Ordering::Relaxed), 2);
294 }
295
296 #[test]
297 fn apply_batches_multiple_segments_into_one_repaint() {
298 let (state, repainter_count) = setup_state_with_counter();
299 let mut pushed = PromptContents::default();
300 pushed.apply_segment_override(PromptSegment::Left, "Alpha");
301 pushed.apply_segment_override(PromptSegment::Right, "Beta");
302 pushed.apply_segment_override(PromptSegment::Indicator, "Gamma");
303 state.apply(pushed, JOB);
304
305 let contents = state.contents();
306 assert_eq!(contents.left.as_deref(), Some("Alpha"));
307 assert_eq!(contents.right.as_deref(), Some("Beta"));
308 assert_eq!(contents.indicator.as_deref(), Some("Gamma"));
309 assert_eq!(repainter_count.load(Ordering::Relaxed), 1);
311 }
312
313 #[test]
314 fn set_contents_overwrites_a_pushed_override() {
315 let state = PromptState::new();
316 state.set(PromptSegment::Left, "Pushed", JOB);
317
318 state.set_contents(PromptContents {
319 left: Some("Baseline".into()),
320 ..Default::default()
321 });
322
323 assert_eq!(state.contents().left.as_deref(), Some("Baseline"));
324 }
325
326 #[test]
327 fn push_during_update_survives_set_contents() {
328 let state = PromptState::new();
329 state.begin_update(JOB);
330 state.set(PromptSegment::Right, "Pushed", JOB);
331
332 state.set_contents(PromptContents {
333 left: Some("BaselineLeft".into()),
334 right: Some("BaselineRight".into()),
335 ..Default::default()
336 });
337
338 let contents = state.contents();
339 assert_eq!(contents.left.as_deref(), Some("BaselineLeft"));
340 assert_eq!(contents.right.as_deref(), Some("Pushed"));
341 }
342
343 #[test]
344 fn begin_update_drops_pushes_from_the_previous_prompt() {
345 let state = PromptState::new();
346 state.begin_update(JOB);
348 state.set(PromptSegment::Left, "Previous", JOB);
349 state.begin_update(JOB);
350 state.set(PromptSegment::Right, "Current", JOB);
351
352 state.set_contents(PromptContents {
353 left: Some("BaselineLeft".into()),
354 right: Some("BaselineRight".into()),
355 ..Default::default()
356 });
357
358 let contents = state.contents();
359 assert_eq!(contents.left.as_deref(), Some("BaselineLeft"));
360 assert_eq!(contents.right.as_deref(), Some("Current"));
361 }
362
363 #[test]
364 fn set_contents_ends_the_update() {
365 let state = PromptState::new();
366 state.begin_update(JOB);
367 state.set_contents(PromptContents::default());
368 state.set(PromptSegment::Left, "AfterUpdate", JOB);
369
370 state.set_contents(PromptContents {
371 left: Some("NextBaseline".into()),
372 ..Default::default()
373 });
374
375 assert_eq!(state.contents().left.as_deref(), Some("NextBaseline"));
376 }
377
378 #[test]
379 fn push_from_an_older_job_is_shown_but_not_kept() {
380 let state = PromptState::new();
381 state.begin_update(JobId::new(2));
382 state.set(PromptSegment::Left, "Stale", JobId::new(1));
383 assert_eq!(state.contents().left.as_deref(), Some("Stale"));
384
385 state.set_contents(PromptContents {
386 left: Some("Baseline".into()),
387 ..Default::default()
388 });
389
390 assert_eq!(state.contents().left.as_deref(), Some("Baseline"));
391 }
392
393 #[test]
394 fn push_from_the_main_thread_during_update_survives_set_contents() {
395 let state = PromptState::new();
396 state.begin_update(JobId::new(2));
397 state.set(PromptSegment::Left, "FromHook", JobId::ZERO);
398
399 state.set_contents(PromptContents {
400 left: Some("Baseline".into()),
401 ..Default::default()
402 });
403
404 assert_eq!(state.contents().left.as_deref(), Some("FromHook"));
405 }
406
407 #[test]
408 fn detaching_repainter_stops_repaints() {
409 let (state, repainter_count) = setup_state_with_counter();
410 state.set_repainter(None);
411 state.set(PromptSegment::Left, "Delta", JOB);
412
413 assert_eq!(repainter_count.load(Ordering::Relaxed), 0);
414 }
415}