Skip to main content

indigo_core/
client.rs

1use crate::{
2    buffer::{Buffer, BufferKey},
3    fs::Fs,
4    mode::{Keymaps, Mode, insert, normal, prompt, view},
5    path,
6    session::Session,
7    window::{Window, WindowKey, WindowMut, WindowState},
8};
9use camino::{Utf8Path, Utf8PathBuf};
10use indigo_key::{Key, Keys};
11use indigo_wrap::{WMut, WRef, Wrap, WrapMut, WrapRef};
12use slotmap::SlotMap;
13use std::{
14    borrow::Cow,
15    num::NonZeroUsize,
16    ops::{Deref, DerefMut},
17    process::ExitCode,
18    sync::Arc,
19};
20use thiserror::Error;
21
22#[derive(Debug, Error)]
23pub enum Error {
24    #[error("Focused window {key:?} does not exist")]
25    FocusedWindowMissing { key: WindowKey },
26
27    #[error("Window {window_key:?} refers to buffer {buffer_key:?}, which does not exist")]
28    WindowBufferMissing {
29        window_key: WindowKey,
30        buffer_key: BufferKey,
31    },
32
33    #[error("Error from window {key:?}")]
34    Window {
35        key: WindowKey,
36        #[source]
37        source: anyhow::Error,
38    },
39
40    #[error("Error from prompt")]
41    Prompt(#[source] anyhow::Error),
42}
43
44#[derive(Clone)]
45pub struct ClientState {
46    windows: SlotMap<WindowKey, WindowState>,
47    focused_window: WindowKey,
48    pub mode: Mode,
49    pub keymaps: Keymaps,
50    pub count: Option<NonZeroUsize>,
51    pub pending_keys: Vec<Key>,
52    message: Option<Result<Cow<'static, str>, Cow<'static, str>>>,
53    pub suspend: bool,
54    pub exit_code: Option<ExitCode>,
55}
56
57impl ClientState {
58    #[must_use]
59    pub(crate) fn new(buffer_key: BufferKey) -> Self {
60        let window = WindowState::new(buffer_key);
61        let mut windows = SlotMap::default();
62        let window_key = windows.insert(window);
63
64        Self {
65            windows,
66            focused_window: window_key,
67            mode: Mode::default(),
68            keymaps: Keymaps::default(),
69            count: None,
70            pending_keys: Vec::new(),
71            message: None,
72            suspend: false,
73            exit_code: None,
74        }
75    }
76
77    #[must_use]
78    pub fn message(&self) -> Option<Result<&str, &str>> {
79        match &self.message {
80            Some(Ok(message)) => Some(Ok(message)),
81            Some(Err(message)) => Some(Err(message)),
82            None => None,
83        }
84    }
85
86    pub fn set_message(&mut self, message: impl Into<Cow<'static, str>>) {
87        self.message = Some(Ok(message.into()));
88    }
89
90    pub fn set_error(&mut self, message: impl Into<Cow<'static, str>>) {
91        self.message = Some(Err(message.into()));
92    }
93
94    pub fn clear_message(&mut self) {
95        self.message = None;
96    }
97
98    /// Doesn't actually terminate the process, just records the desired exit code.
99    pub fn exit(&mut self, exit_code: u8) {
100        self.exit_code = Some(ExitCode::from(exit_code));
101    }
102}
103
104#[must_use]
105pub struct ClientView<'a, W: Wrap> {
106    state: W::Wrap<'a, ClientState>,
107    session: W::Wrap<'a, Session>,
108    fs: &'a Arc<dyn Fs + Send + Sync>,
109    home: &'a Utf8Path,
110}
111
112pub type Client<'a> = ClientView<'a, WRef>;
113
114pub type ClientMut<'a> = ClientView<'a, WMut>;
115
116impl<W: WrapRef> Deref for ClientView<'_, W> {
117    type Target = ClientState;
118
119    fn deref(&self) -> &Self::Target {
120        &self.state
121    }
122}
123
124impl<W: WrapMut> DerefMut for ClientView<'_, W> {
125    fn deref_mut(&mut self) -> &mut Self::Target {
126        &mut self.state
127    }
128}
129
130impl<'a, W: WrapRef> ClientView<'a, W> {
131    pub fn new(
132        fs: &'a Arc<dyn Fs + Send + Sync>,
133        home: &'a Utf8Path,
134        session: W::WrapRef<'a, Session>,
135        state: W::WrapRef<'a, ClientState>,
136    ) -> Self {
137        Self {
138            state,
139            session,
140            fs,
141            home,
142        }
143    }
144
145    #[must_use]
146    pub fn session(&self) -> &Session {
147        &self.session
148    }
149
150    #[must_use]
151    pub fn fs(&self) -> &'a Arc<dyn Fs + Send + Sync> {
152        self.fs
153    }
154
155    #[must_use]
156    pub fn home(&self) -> &Utf8Path {
157        self.home
158    }
159
160    #[must_use]
161    pub fn absolute_path(&self, path: &Utf8Path) -> Utf8PathBuf {
162        path::absolute_path(self.home, self.session.pwd(), path)
163    }
164
165    #[must_use]
166    pub fn display_path(&self, path: &Utf8Path) -> String {
167        path::display_path(self.home, self.session.pwd(), path)
168    }
169
170    #[must_use]
171    pub fn focused_buffer(&self) -> &Buffer {
172        let window = self
173            .state
174            .windows
175            .get(self.state.focused_window)
176            .expect("Window state is always kept valid");
177        self.session
178            .get_buffer(window.buffer)
179            .expect("Window state is always kept valid")
180    }
181
182    #[must_use]
183    pub fn get_window(&self, window_key: WindowKey) -> Option<Window<'_>> {
184        let window = self.state.windows.get(window_key)?;
185        let buffer = self
186            .session
187            .get_buffer(window.buffer)
188            .expect("Window state is always kept valid");
189        Some(Window::new(buffer, window))
190    }
191
192    pub fn focused_window(&self) -> Window<'_> {
193        let window = self
194            .state
195            .windows
196            .get(self.state.focused_window)
197            .expect("Window state is always kept valid");
198        let buffer = self
199            .session
200            .get_buffer(window.buffer)
201            .expect("Window state is always kept valid");
202        Window::new(buffer, window)
203    }
204
205    // TODO: Add windows iterator
206
207    pub fn assert_invariants(&self) -> anyhow::Result<()> {
208        let home = self.home;
209        anyhow::ensure!(
210            home.is_absolute(),
211            "Home directory is not absolute: `{home}`"
212        );
213        self.session.assert_invariants()?;
214        if !self.state.windows.contains_key(self.state.focused_window) {
215            anyhow::bail!(Error::FocusedWindowMissing {
216                key: self.state.focused_window,
217            });
218        }
219        for (window_key, window) in &self.state.windows {
220            let Some(buffer) = self.session.get_buffer(window.buffer) else {
221                anyhow::bail!(Error::WindowBufferMissing {
222                    window_key,
223                    buffer_key: window.buffer,
224                });
225            };
226            Window::new(buffer, window)
227                .assert_invariants()
228                .map_err(|source| Error::Window {
229                    key: window_key,
230                    source,
231                })?;
232        }
233        if let Mode::Prompt(state) = &self.state.mode {
234            state.assert_invariants().map_err(Error::Prompt)?;
235        }
236        Ok(())
237    }
238}
239
240impl<W: WrapMut> ClientView<'_, W> {
241    #[must_use]
242    pub fn session_mut(&mut self) -> &mut Session {
243        &mut self.session
244    }
245
246    #[must_use]
247    pub fn focused_buffer_mut(&mut self) -> &mut Buffer {
248        let window = self
249            .state
250            .windows
251            .get(self.state.focused_window)
252            .expect("Window state is always kept valid");
253        self.session
254            .get_buffer_mut(window.buffer)
255            .expect("Window state is always kept valid")
256    }
257
258    // TODO: Figure out a safer/better way to add and remove windows
259    pub(crate) fn insert_window(&mut self, window: WindowState) -> WindowKey {
260        assert!(
261            self.session.get_buffer(window.buffer).is_some(),
262            "Window has invalid buffer key"
263        );
264        self.state.windows.insert(window)
265    }
266
267    pub fn focus_window(&mut self, window_key: WindowKey) -> bool {
268        if self.state.windows.contains_key(window_key) {
269            self.state.focused_window = window_key;
270            true
271        } else {
272            false
273        }
274    }
275
276    #[must_use]
277    pub fn get_window_mut(&mut self, window_key: WindowKey) -> Option<WindowMut<'_>> {
278        let window = self.state.windows.get_mut(window_key)?;
279        let buffer = self
280            .session
281            .get_buffer_mut(window.buffer)
282            .expect("Window state is always kept valid");
283        Some(WindowMut::new(buffer, window))
284    }
285
286    pub fn focused_window_mut(&mut self) -> WindowMut<'_> {
287        let focused_window = self.state.focused_window;
288        let window = self
289            .state
290            .windows
291            .get_mut(focused_window)
292            .expect("Window state is always kept valid");
293        let buffer = self
294            .session
295            .get_buffer_mut(window.buffer)
296            .expect("Window state is always kept valid");
297        WindowMut::new(buffer, window)
298    }
299}
300
301impl ClientMut<'_> {
302    pub fn handle_event(&mut self, mut event: Event) -> anyhow::Result<bool> {
303        #[expect(irrefutable_let_patterns)]
304        if let Event::Key(KeyEvent { key, .. }) = &mut event {
305            key.normalize();
306            self.state.pending_keys.push(*key);
307        }
308
309        let keys = Keys(self.state.pending_keys.clone());
310
311        let handled = match event {
312            Event::Key(_) => match self.state.mode {
313                Mode::Normal => normal::handle_keys(self),
314                Mode::Insert => insert::handle_keys(self),
315                Mode::Prompt(_) => prompt::handle_keys(self),
316                Mode::View(_) => view::handle_keys(self),
317            },
318        };
319
320        if !handled {
321            self.set_error(format!("{keys} is not mapped"));
322        }
323
324        if cfg!(debug_assertions) {
325            self.assert_invariants()?;
326        }
327
328        Ok(handled)
329    }
330}
331
332#[derive(Debug)]
333pub enum Event {
334    Key(KeyEvent),
335}
336
337#[derive(Debug, PartialEq)]
338pub struct KeyEvent {
339    pub key: Key,
340    pub kind: KeyEventKind,
341}
342
343#[derive(Debug, PartialEq)]
344pub enum KeyEventKind {
345    Press,
346    Repeat,
347    Release,
348}