summaryrefslogtreecommitdiffstats
path: root/src/shell/history/mod.rs
blob: 91149c12138fc7db915e6ea23cb05f7a26d34559 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
use crate::shell::prelude::*;

mod entry;
pub use entry::{Entry, ExitInfo};
mod pty;

pub struct History {
    size: (u16, u16),
    entries: Vec<Entry>,
    scroll_pos: usize,
}

impl History {
    pub fn new() -> Self {
        Self {
            size: (24, 80),
            entries: vec![],
            scroll_pos: 0,
        }
    }

    pub fn render(
        &self,
        out: &mut impl textmode::Textmode,
        repl_lines: usize,
        focus: Option<usize>,
        scrolling: bool,
        offset: time::UtcOffset,
    ) {
        let mut cursor = None;
        for (idx, used_lines, mut vt) in
            self.visible(repl_lines, focus, scrolling).rev()
        {
            let focused = focus.map_or(false, |focus| idx == focus);
            out.move_to(
                (usize::from(self.size.0) - used_lines).try_into().unwrap(),
                0,
            );
            self.entries[idx].render(
                out,
                self.entry_count(),
                &mut *vt,
                focused,
                scrolling,
                offset,
            );
            if focused && !scrolling {
                cursor = Some((
                    out.screen().cursor_position(),
                    out.screen().hide_cursor(),
                ));
            }
        }
        if let Some((pos, hide)) = cursor {
            out.move_to(pos.0, pos.1);
            out.hide_cursor(hide);
        }
    }

    pub fn entry(&self, idx: usize) -> &Entry {
        &self.entries[idx]
    }

    pub fn entry_mut(&mut self, idx: usize) -> &mut Entry {
        &mut self.entries[idx]
    }

    pub fn resize(&mut self, size: (u16, u16)) {
        self.size = size;
        for entry in &self.entries {
            entry.resize(size);
        }
    }

    pub fn run(
        &mut self,
        cmdline: String,
        env: Env,
        event_w: crate::shell::event::Writer,
    ) {
        self.entries
            .push(Entry::new(cmdline, env, self.size, event_w).unwrap());
    }

    pub fn entry_count(&self) -> usize {
        self.entries.len()
    }

    pub fn make_focus_visible(
        &mut self,
        repl_lines: usize,
        focus: Option<usize>,
        scrolling: bool,
    ) {
        if self.entries.is_empty() || focus.is_none() {
            return;
        }
        let focus = focus.unwrap();

        let mut done = false;
        while focus
            < self
                .visible(repl_lines, Some(focus), scrolling)
                .map(|(idx, ..)| idx)
                .next()
                .unwrap()
        {
            self.scroll_pos += 1;
            done = true;
        }
        if done {
            return;
        }

        while focus
            > self
                .visible(repl_lines, Some(focus), scrolling)
                .map(|(idx, ..)| idx)
                .last()
                .unwrap()
        {
            self.scroll_pos -= 1;
        }
    }

    pub async fn save(&self) {
        // TODO: we'll probably want some amount of flock or something here
        let mut fh = tokio::fs::OpenOptions::new()
            .append(true)
            .open(crate::dirs::history_file())
            .await
            .unwrap();
        for entry in &self.entries {
            fh.write_all(
                format!(
                    ": {}:0;{}\n",
                    entry.start_time().unix_timestamp(),
                    entry.cmd()
                )
                .as_bytes(),
            )
            .await
            .unwrap();
        }
    }

    fn visible(
        &self,
        repl_lines: usize,
        focus: Option<usize>,
        scrolling: bool,
    ) -> VisibleEntries {
        let mut iter = VisibleEntries::new();
        let mut used_lines = repl_lines;
        for (idx, entry) in
            self.entries.iter().enumerate().rev().skip(self.scroll_pos)
        {
            let focused = focus.map_or(false, |focus| idx == focus);
            used_lines +=
                entry.lines(self.entry_count(), focused && !scrolling);
            if used_lines > usize::from(self.size.0) {
                break;
            }
            iter.add(idx, used_lines, entry.lock_vt());
        }
        iter
    }
}

struct VisibleEntries<'a> {
    entries: std::collections::VecDeque<(
        usize,
        usize,
        std::sync::MutexGuard<'a, pty::Vt>,
    )>,
}

impl<'a> VisibleEntries<'a> {
    fn new() -> Self {
        Self {
            entries: std::collections::VecDeque::new(),
        }
    }

    fn add(
        &mut self,
        idx: usize,
        offset: usize,
        vt: std::sync::MutexGuard<'a, pty::Vt>,
    ) {
        // push_front because we are adding them in reverse order
        self.entries.push_front((idx, offset, vt));
    }
}

impl<'a> std::iter::Iterator for VisibleEntries<'a> {
    type Item = (usize, usize, std::sync::MutexGuard<'a, pty::Vt>);

    fn next(&mut self) -> Option<Self::Item> {
        self.entries.pop_front()
    }
}

impl<'a> std::iter::DoubleEndedIterator for VisibleEntries<'a> {
    fn next_back(&mut self) -> Option<Self::Item> {
        self.entries.pop_back()
    }
}