Skip to main content

indigo_core/
window.rs

1use crate::{
2    buffer::{Buffer, BufferKey},
3    selection::{Selection, SelectionEdit, SelectionMove, SelectionState},
4};
5use indigo_text::rope::{LINE_TYPE, RopeExt as _};
6use indigo_wrap::{WMut, WRef, Wrap, WrapMut, WrapRef};
7use std::cmp::min;
8
9slotmap::new_key_type! {
10    #[must_use]
11    pub struct WindowKey;
12}
13
14#[derive(Clone)]
15pub struct WindowState {
16    pub buffer: BufferKey,
17    pub selection: SelectionState,
18    pub height: u16,
19    pub prev_vertical_scroll: usize,
20    // TODO(horizontal_scroll)
21}
22
23impl WindowState {
24    #[must_use]
25    pub fn new(buffer_key: BufferKey) -> Self {
26        Self {
27            buffer: buffer_key,
28            selection: SelectionState::default(),
29            height: 0,
30            prev_vertical_scroll: 0,
31        }
32    }
33}
34
35#[must_use]
36pub struct WindowView<'a, W: Wrap> {
37    state: W::Wrap<'a, WindowState>,
38    buffer: W::Wrap<'a, Buffer>,
39}
40
41pub type Window<'a> = WindowView<'a, WRef>;
42
43pub type WindowMut<'a> = WindowView<'a, WMut>;
44
45#[expect(clippy::elidable_lifetime_names)]
46impl<'a, W: Wrap> WindowView<'a, W> {
47    //
48}
49
50impl<'a, W: WrapRef> WindowView<'a, W> {
51    pub fn new(buffer: W::WrapRef<'a, Buffer>, state: W::WrapRef<'a, WindowState>) -> Self {
52        Self { state, buffer }
53    }
54
55    #[must_use]
56    pub fn height(&self) -> u16 {
57        self.state.height
58    }
59
60    #[must_use]
61    pub fn vertical_scroll(&self) -> usize {
62        let last_line = self.buffer.text.rope().len_lines_unix().saturating_sub(1);
63        min(self.state.prev_vertical_scroll, last_line)
64    }
65
66    // TODO(horizontal_scroll)
67
68    #[must_use]
69    pub fn buffer(&self) -> &Buffer {
70        &self.buffer
71    }
72
73    pub fn selection(&self) -> Selection<'_> {
74        Selection::new(&self.buffer.text, &self.state.selection)
75            .expect("Window text and selection state are always kept valid")
76    }
77
78    pub fn assert_invariants(&self) -> anyhow::Result<()> {
79        let _ = Selection::new(&self.buffer.text, &self.state.selection)?;
80        Ok(())
81    }
82}
83
84impl<W: WrapMut> WindowView<'_, W> {
85    pub fn set_height(&mut self, height: u16) {
86        self.state.height = height;
87    }
88
89    pub fn scroll_to_line(&mut self, line: usize) {
90        let last_line = self.buffer.text.rope().len_lines_unix().saturating_sub(1);
91        self.state.prev_vertical_scroll = min(line, last_line);
92    }
93
94    // TODO: There's a bug where the cursor can move one line above the viewport without this
95    // function scrolling it into view. Try moving up line-by-line in a long file like `Cargo.lock`
96    // and watch it pop in and out from the top of the viewport. Moving down works correctly: the
97    // cursor never disappears below the bottom of the viewport.
98    pub fn scroll_to_selection(&mut self) {
99        let state = &self.state.selection;
100        let head_byte_index = state.ranges[state.primary_range].head.byte_index;
101        let line = self
102            .buffer
103            .text
104            .rope()
105            .byte_to_line_idx(head_byte_index, LINE_TYPE);
106        let top = self.vertical_scroll();
107        let bottom = top + usize::from(self.state.height).saturating_sub(1);
108        if line < top {
109            self.state.prev_vertical_scroll = line;
110        } else if line > bottom {
111            self.state.prev_vertical_scroll = top + (line - bottom);
112        }
113    }
114
115    pub fn scroll_center_selection(&mut self) {
116        let state = &self.state.selection;
117        let head_byte_index = state.ranges[state.primary_range].head.byte_index;
118        let line = self
119            .buffer
120            .text
121            .rope()
122            .byte_to_line_idx(head_byte_index, LINE_TYPE);
123        let half_height = usize::from(self.state.height) / 2;
124        self.state.prev_vertical_scroll = line.saturating_sub(half_height);
125    }
126
127    pub fn scroll_up(&mut self) {
128        let line = self.vertical_scroll().saturating_sub(3);
129        self.scroll_to_line(line);
130    }
131
132    pub fn scroll_down(&mut self) {
133        let line = self.vertical_scroll() + 3;
134        self.scroll_to_line(line);
135    }
136
137    pub fn scroll_lines_up(&mut self, count: usize) {
138        let line = self.vertical_scroll().saturating_sub(count);
139        self.scroll_to_line(line);
140    }
141
142    pub fn scroll_lines_down(&mut self, count: usize) {
143        let line = self.vertical_scroll().saturating_add(count);
144        self.scroll_to_line(line);
145    }
146
147    // TODO(horizontal_scroll)
148
149    pub fn scroll_half_page_up(&mut self) {
150        let line = self
151            .vertical_scroll()
152            .saturating_sub(usize::from(self.height()) / 2);
153        self.scroll_to_line(line);
154    }
155
156    pub fn scroll_half_page_down(&mut self) {
157        let line = self.vertical_scroll() + usize::from(self.height()) / 2;
158        self.scroll_to_line(line);
159    }
160
161    pub fn scroll_full_page_up(&mut self) {
162        let line = self
163            .vertical_scroll()
164            .saturating_sub(usize::from(self.height()));
165        self.scroll_to_line(line);
166    }
167
168    pub fn scroll_full_page_down(&mut self) {
169        let line = self.vertical_scroll() + usize::from(self.height());
170        self.scroll_to_line(line);
171    }
172
173    #[must_use]
174    pub fn buffer_mut(&mut self) -> &mut Buffer {
175        &mut self.buffer
176    }
177
178    pub fn selection_move(&mut self) -> SelectionMove<'_> {
179        SelectionMove::new(&self.buffer.text, &mut self.state.selection)
180            .expect("Window text and selection state are always kept valid")
181            .on_drop(|selection| {
182                if cfg!(debug_assertions) {
183                    selection.assert_invariants().unwrap();
184                }
185            })
186    }
187
188    pub fn selection_edit(&mut self) -> SelectionEdit<'_> {
189        SelectionEdit::new(&mut self.buffer.text, &mut self.state.selection)
190            .expect("Window text and selection state are always kept valid")
191            .on_drop(|selection| {
192                if cfg!(debug_assertions) {
193                    selection.assert_invariants().unwrap();
194                }
195            })
196    }
197
198    #[tracing::instrument(skip_all)]
199    pub fn undo(&mut self) -> anyhow::Result<bool> {
200        let version = self.buffer.text.version();
201        if self.buffer.text.undo()? {
202            if let Some(opss) = self.buffer.text.ops_since(version) {
203                for ops in opss {
204                    self.state.selection.transform(ops, &self.buffer.text);
205                }
206                self.state.selection.merge_overlapping();
207            }
208            Ok(true)
209        } else {
210            Ok(false)
211        }
212    }
213
214    #[tracing::instrument(skip_all)]
215    pub fn redo(&mut self) -> anyhow::Result<bool> {
216        let version = self.buffer.text.version();
217        if self.buffer.text.redo()? {
218            if let Some(opss) = self.buffer.text.ops_since(version) {
219                for ops in opss {
220                    self.state.selection.transform(ops, &self.buffer.text);
221                }
222                self.state.selection.merge_overlapping();
223            }
224            Ok(true)
225        } else {
226            Ok(false)
227        }
228    }
229}