Skip to main content

artifactize_core/monitor/
session.rs

1//! Selected-session jobs. Geometry/input are pure; the driver alone starts bounded reader jobs.
2//! A UI sizes the window in text columns and rows, whether a terminal or the desktop app.
3use crate::agent::session::{
4    document::{Anchor, Position, Scroll},
5    live::{Reader, Source, Window},
6};
7pub use crate::agent::session::{
8    document::{Mode, Move},
9    live::{Resolution, resolve},
10    transcript::BlockId,
11};
12
13/// Identity of one selected-session reader, distinct from its layout revision.
14#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
15pub struct ReaderId(u64);
16
17impl ReaderId {
18    /// Retire the current reader identity when a selection creates its replacement.
19    pub fn next(self) -> Self {
20        Self(
21            self.0
22                .checked_add(1)
23                .expect("session reader identity exhausted"),
24        )
25    }
26}
27
28impl From<u64> for ReaderId {
29    fn from(value: u64) -> Self {
30        Self(value)
31    }
32}
33
34pub struct Live {
35    pub serial: ReaderId,
36    pub source: Source,
37    pub reader: Option<Reader>,
38    pub scroll: Scroll,
39    pub window: Window,
40    width: usize,
41    height: usize,
42    anchor: Anchor,
43    position: Position,
44    revision: u64,
45    rendered_width: usize,
46    dirty: bool,
47    expanded: std::collections::BTreeSet<BlockId>,
48}
49
50pub struct Job {
51    pub serial: ReaderId,
52    pub revision: u64,
53    pub width: usize,
54    pub height: usize,
55    pub position: Position,
56    pub reader: Reader,
57    pub expanded: std::collections::BTreeSet<BlockId>,
58}
59impl Live {
60    pub fn new(serial: ReaderId, source: Source) -> Self {
61        Self {
62            serial,
63            source: source.clone(),
64            reader: Some(Reader::new(source)),
65            scroll: Scroll::default(),
66            window: Window::default(),
67            width: 0,
68            height: 0,
69            anchor: Anchor::default(),
70            position: Position::Bottom,
71            revision: 0,
72            rendered_width: 0,
73            dirty: true,
74            expanded: std::collections::BTreeSet::new(),
75        }
76    }
77    pub fn geometry(&mut self, width: usize, height: usize) {
78        if self.width != width || self.height != height {
79            self.width = width;
80            self.height = height;
81            // Preserve pending Row/Top intent. The reader converts an old-layout row to
82            // its logical anchor before changing width; committed positions already anchor.
83            self.revision += 1;
84            self.dirty = true;
85        }
86    }
87    pub fn invalidate(&mut self) {
88        self.dirty = true;
89    }
90
91    /// Point this reader at a freshly resolved `source`. Of the same session it keeps its
92    /// position, follow state and expanded groups and reads again (`true`); another session
93    /// is not this reader's (`false`, nothing changed).
94    pub fn refresh(&mut self, source: &Source) -> bool {
95        if self.source.reference != source.reference {
96            return false;
97        }
98        self.source = source.clone();
99        if let Some(reader) = &mut self.reader {
100            reader.source = source.clone();
101        }
102        self.invalidate();
103        true
104    }
105    pub fn toggle(&mut self, id: BlockId) {
106        if !self.expanded.remove(&id) {
107            self.expanded.insert(id);
108        }
109        self.revision += 1;
110        self.dirty = true;
111    }
112    pub fn toggle_visible(&mut self) {
113        if let Some((_, id)) = self.window.groups.first().copied() {
114            self.toggle(id);
115        }
116    }
117    pub fn movement(&mut self, movement: Move) {
118        let before = self.scroll.top;
119        self.scroll.apply(movement);
120        let delta = self.scroll.top as isize - before as isize;
121        self.position = match movement {
122            Move::Bottom => Position::Bottom,
123            Move::Top => Position::Anchor(Anchor::default()),
124            Move::Up(_) | Move::Down(_) if self.scroll.mode == Mode::Following => Position::Bottom,
125            Move::Up(_) | Move::Down(_) => match self.position {
126                Position::Anchor(anchor) => Position::Relative {
127                    anchor,
128                    rows: delta,
129                    width: self.rendered_width.max(1),
130                },
131                Position::Relative {
132                    anchor,
133                    rows,
134                    width,
135                } => Position::Relative {
136                    anchor,
137                    rows: rows.saturating_add(delta),
138                    width,
139                },
140                _ => Position::Relative {
141                    anchor: self.anchor,
142                    rows: self.scroll.top as isize - self.window.top as isize,
143                    width: self.rendered_width.max(1),
144                },
145            },
146        };
147        self.revision += 1;
148        self.dirty = true;
149    }
150    pub fn job(&mut self) -> Option<Job> {
151        if !self.dirty || self.width == 0 || self.height == 0 {
152            return None;
153        }
154        let reader = self.reader.take()?;
155        self.dirty = false;
156        Some(Job {
157            serial: self.serial,
158            revision: self.revision,
159            width: self.width,
160            height: self.height,
161            position: self.position,
162            reader,
163            expanded: self.expanded.clone(),
164        })
165    }
166    pub fn finish(&mut self, job: Job, window: Window) {
167        let mut reader = job.reader;
168        reader.source = self.source.clone();
169        self.reader = Some(reader);
170        // A replacement creates a different document even if its visible result is stale.
171        if window.reset {
172            self.scroll = Scroll::default();
173            self.position = Position::Bottom;
174            self.dirty = true;
175        }
176        if self.revision != job.revision {
177            self.dirty = true;
178            return;
179        }
180        if window.loading() && window.rows.is_empty() {
181            // Keep the old visible text during bounded relayout, with an honest loading label.
182            self.window.status = crate::agent::session::live::WindowStatus::Loading;
183            self.position = window.position;
184        } else {
185            self.scroll
186                .update(window.total, self.height, Some(window.top));
187            self.anchor = window.anchor;
188            self.rendered_width = job.width;
189            if let Some(reader) = &mut self.reader {
190                reader.commit(job.width);
191            }
192            self.position = match self.scroll.mode {
193                Mode::Following => Position::Bottom,
194                Mode::Paused => Position::Anchor(self.anchor),
195            };
196            self.window = window;
197        }
198        self.dirty |= self.window.loading();
199    }
200    pub fn indicator(&self) -> String {
201        let position = if self.scroll.total == 0 {
202            "0/0".into()
203        } else {
204            format!("{}/{}", self.scroll.top + 1, self.scroll.total)
205        };
206        format!(
207            "{position} {} {}{}",
208            if self.scroll.at_bottom() {
209                "bottom"
210            } else {
211                "history"
212            },
213            if self.scroll.mode == Mode::Following {
214                "following"
215            } else {
216                "paused"
217            },
218            if self.window.loading() {
219                " · indexing…"
220            } else {
221                ""
222            }
223        )
224    }
225}
226
227#[cfg(any(test, feature = "test-support"))]
228mod tests;