Skip to main content

nu_protocol/engine/
prompt_state.rs

1use std::sync::{Arc, Mutex, MutexGuard, RwLock, RwLockReadGuard, RwLockWriteGuard};
2
3use crate::JobId;
4
5/// Wakes the active interactive line editor and asks it to repaint the prompt in
6/// place, without disturbing the line currently being edited.
7type Repainter = Arc<dyn Fn() + Send + Sync>;
8
9/// Which prompt segment an asynchronous [`PromptState::set`] targets.
10#[derive(Debug, Clone, Copy)]
11pub enum PromptSegment {
12    /// The main (left) prompt, `$env.PROMPT_COMMAND`.
13    Left,
14
15    /// The right prompt, `$env.PROMPT_COMMAND_RIGHT`.
16    Right,
17
18    /// The prompt indicator for the default/emacs edit mode, `$env.PROMPT_INDICATOR`.
19    Indicator,
20
21    /// The vi insert-mode indicator, `$env.PROMPT_INDICATOR_VI_INSERT`.
22    ViInsert,
23
24    /// The vi normal-mode indicator, `$env.PROMPT_INDICATOR_VI_NORMAL`.
25    ViNormal,
26
27    /// The multiline continuation indicator, `$env.PROMPT_MULTILINE_INDICATOR`.
28    Multiline,
29}
30
31/// The full set of rendered prompt strings, as the line editor draws them.
32#[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    /// Applies an overriding string to a specific segment.
45    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    /// Layer `overrides` on top of `self`, preferring the override where set
58    /// and falling back to `self` otherwise. `render_right_on_last_line` always
59    /// comes from `self`, so a push never changes it.
60    ///
61    /// This lays pushes over the live contents and over the new baseline, and
62    /// renders the transient prompt from the *live* baseline (so late pushes
63    /// still show up) with `TRANSIENT_PROMPT_*` values layered on top.
64    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/// The rendered prompt, plus the pushes kept while the REPL rebuilds it.
90#[derive(Debug, Default)]
91struct PromptData {
92    contents: PromptContents,
93
94    /// The pushes kept since [`PromptState::begin_update`]. `None` outside the window between
95    /// that call and [`PromptState::set_contents`], which layers them over the new baseline.
96    /// Without it, a job that finishes before the REPL rebuilds the prompt would lose its push.
97    pending: Option<PendingPushes>,
98}
99
100/// The segments pushed for the prompt the REPL is rebuilding.
101#[derive(Debug)]
102struct PendingPushes {
103    /// The id of the first job the main thread started for this prompt. A job whose root is
104    /// lower is left over from an earlier prompt, so its result may be out of date (computed for
105    /// another directory, say).
106    first_job: JobId,
107
108    pushed: PromptContents,
109}
110
111impl PendingPushes {
112    /// Whether a push belongs to the prompt being rebuilt (see [`PromptState::begin_update`]).
113    fn accepts(&self, root_job: JobId) -> bool {
114        root_job == JobId::ZERO || root_job >= self.first_job
115    }
116}
117
118/// Shared, thread-safe home for the interactive prompt's rendered content.
119#[derive(derive_more::Debug, Default)]
120pub struct PromptState {
121    /// Upgraded to RwLock: Enables infinite concurrent reads, locking only for mutations.
122    /// The pending pushes share the lock so a push can't slip between them and the contents.
123    data: RwLock<PromptData>,
124
125    /// Kept in its own lock: it is installed/cleared by the REPL and read by
126    /// [`PromptState::apply`], never together with `data`.
127    #[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    /// Run an action with shared, read-only access to the current contents.
155    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    /// A snapshot of the current contents.
163    pub fn contents(&self) -> PromptContents {
164        self.with_contents(PromptContents::clone)
165    }
166
167    /// Start rebuilding the prompt. Until [`Self::set_contents`], a push is also kept aside, so the
168    /// new baseline doesn't overwrite it, when it comes from the main thread or from a job whose
169    /// `CurrentJob::root` is at least `first_job`: a job the main thread started after this call,
170    /// or a job one of those spawned. A push from an older job still shows until the new baseline
171    /// replaces it.
172    ///
173    /// The REPL calls this before the hooks that run ahead of each prompt, and passes the id the
174    /// next spawned job will get. Until `set_contents`, everything the main thread runs prepares
175    /// this prompt: the `env_change` and `pre_prompt` hooks, `color_config` and `ENV_CONVERSIONS`
176    /// closures, and the prompt closures themselves.
177    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    /// Replace all prompt content (the baseline), then lay over it the pushes kept since
185    /// [`Self::begin_update`].
186    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    /// Replace the segments set in `pushed` under a single write lock, then request one in-place
195    /// repaint. Callers touching several segments at once should use this as to not flash-update.
196    ///
197    /// `root_job` is the pushing thread's `CurrentJob::root` (`JobId::ZERO` on the main thread);
198    /// it decides whether the push outlives the next [`Self::set_contents`] (see
199    /// [`Self::begin_update`]). Segments left `None` keep their current value, and
200    /// `render_right_on_last_line` is ignored.
201    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        // Release the lock before repainting: the line editor reads the prompt to redraw it.
210        drop(data);
211        self.request_repaint();
212    }
213
214    /// Push an override for a single segment and request an in-place repaint. `root_job` is as
215    /// in [`Self::apply`].
216    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    /// Install or remove the line editor's repainter mechanism.
223    pub fn set_repainter(&self, new_repainter: Option<Repainter>) {
224        *self.acquire_repainter_lock() = new_repainter;
225    }
226
227    /// Fire the installed repainter, explicitly dropping the lock before executing.
228    fn request_repaint(&self) {
229        // Cloning the Option<Arc> locally ensures the MutexGuard drops immediately
230        // at the end of this statement, keeping lock contention to a minimum.
231        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    /// A background job id, for tests where the exact id doesn't matter.
245    const JOB: JobId = JobId::new(1);
246
247    /// A `PromptState` wired to a repainter that counts how often it fires.
248    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        // Three segments, but a single repaint.
310        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        // A window the REPL never finished, as when a hook panics before `set_contents`.
347        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}