pijul_org / pijul

Fixing two bugs in line, one with and the other one with creating a new terminal row by inserting in the middle

By blabla on February 27, 2019
This patch is not signed.
6wsJKnYUiDkkp3ihTumDVgUdLzvBjV5U6mkiSYiK39D1hetcF66435Ky4oy3LKSEwt3PL2UphNEpASjwxpGWKCwe
This patch is in the following branches:
latest
master
testing




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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298


299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
        let delta_y = (self.cursor + self.posy0 - 1) / w;
            write!(o, "\x1b[{};{}H", self.posy, 1)?;
                    write!(o, "\x1b[{};{}H", self.posy, 1)?;
                write!(o, "\x1b[{};{}H", self.posy+1, 1)?;
use libc;
use std;
use std::io::{Read, Write};
use utf8parse;

fn size() -> (usize, usize) {
    unsafe {
        let mut size: libc::winsize = std::mem::zeroed();

        // Albeit it may look useless in the general case, the use of `into()`
        // here is justified for portability reason.  It looks like there is a
        // type mismatch in the `libc` API for FreeBSD, which prevents `line`
        // from compiling.
        if libc::ioctl(1, libc::TIOCGWINSZ.into(), &mut size) == 0 {
            (size.ws_col as usize, size.ws_row as usize)
        } else {
            (0, 0)
        }
    }
}

pub struct Terminal {
    attr: libc::termios,
    posx: usize,
    posy: usize,
    posx0: usize,
    posy0: usize,
    cursor: usize,
    n_chars: usize,
    buf: String,
}

impl Terminal {
    pub fn new() -> Option<Terminal> {
        unsafe {
            if libc::isatty(0) != 0 {
                let mut attr = std::mem::zeroed();
                libc::tcgetattr(0, &mut attr);

                // attr type implements copy and therefore does not need to be
                // cloned
                let attr_orig = attr;

                attr.c_iflag &=
                    !(libc::BRKINT | libc::ICRNL | libc::INPCK | libc::ISTRIP | libc::IXON);
                attr.c_oflag &= !libc::OPOST;
                attr.c_lflag &= !(libc::ECHO | libc::ICANON | libc::IEXTEN | libc::ISIG);
                libc::tcsetattr(0, libc::TCSAFLUSH, &attr);
                Some(Terminal {
                    attr: attr_orig,
                    posx: 0,
                    posy: 0,
                    posx0: 0,
                    posy0: 0,
                    cursor: 0,
                    n_chars: 0,
                    buf: String::new(),
                })
            } else {
                None
            }
        }
    }
}

impl Drop for Terminal {
    fn drop(&mut self) {
        unsafe {
            libc::tcsetattr(0, libc::TCSAFLUSH, &self.attr);
        }
    }
}

fn next_char(s: &str, i: usize) -> usize {
    let s = s.as_bytes();
    if s[i] <= 0x7f {
        i + 1
    } else if s[i] >> 5 == 0b110 {
        i + 2
    } else if s[i] >> 4 == 0b1110 {
        i + 3
    } else {
        i + 4
    }
}

fn prev_char(s: &str, mut i: usize) -> usize {
    let s = s.as_bytes();
    i -= 1;
    while s[i] & 0b1100_0000 == 0b1000_0000 {
        i -= 1
    }
    i
}

impl Terminal {
    fn move_left(&mut self) -> Result<(), std::io::Error> {
        let mut o = std::io::stdout();
        if self.cursor > 0 {
            self.cursor = prev_char(&self.buf, self.cursor);
            if self.posx > 1 {
                self.posx -= 1;
            } else {
                let (w, _) = size();
                self.posx = w;
                self.posy -= 1;
            }
            write!(o, "\x1b[{};{}H", self.posy, self.posx)?;
        }
        o.flush()?;
        Ok(())
    }

    fn word_left(&mut self) -> Result<(), std::io::Error> {
        if self.cursor > 0 {
            let bytes = self.buf.as_bytes();
            let mut is_first = true;
            while self.cursor > 0 {
                self.cursor -= 1;
                if self.posx > 1 {
                    self.posx -= 1;
                } else {
                    let (w, _) = size();
                    self.posx = w;
                    self.posy -= 1;
                }
                if bytes[self.cursor] == b' ' {
                    if !is_first {
                        break;
                    }
                } else {
                    is_first = false
                }
            }
        }
        if self.buf.as_bytes()[self.cursor] == b' ' {
            self.move_right()?
        } else {
            let mut o = std::io::stdout();
            write!(o, "\x1b[{};{}H", self.posy, self.posx)?;
            o.flush()?;
        }
        Ok(())
    }

    fn home(&mut self) -> Result<(), std::io::Error> {
        let mut o = std::io::stdout();
        let (w, _) = size();
        let delta_y = (self.cursor + self.posx0 - 1) / w;
        self.posy -= delta_y;
        self.posx = self.posx0;
        self.posy = self.posy0;
        self.cursor = 0;
        write!(o, "\x1b[{};{}H", self.posy, self.posx)?;
        o.flush()?;
        Ok(())
    }

    fn end(&mut self) -> Result<(), std::io::Error> {
        let mut o = std::io::stdout();
        let remaining_chars = self.buf.split_at(self.cursor).1.chars().count();
        let (w, _) = size();
        self.cursor = self.buf.len();
        self.posy += (self.posx + remaining_chars) / w;
        self.posx = 1 + ((self.posx - 1 + remaining_chars) % w);
        write!(o, "\x1b[{};{}H", self.posy, self.posx)?;
        o.flush()?;
        Ok(())
    }

    fn move_right(&mut self) -> Result<(), std::io::Error> {
        let mut o = std::io::stdout();
        if self.cursor < self.buf.len() {
            self.cursor = next_char(&self.buf, self.cursor);

            let (w, h) = size();
            if self.posx < w {
                self.posx += 1;
            } else {
                if self.posy >= h {
                    write!(o, "\x1b[1S")?;
                }
                self.posx = 1;
                self.posy += 1;
            }
            write!(o, "\x1b[{};{}H", self.posy, self.posx)?;
        }
        o.flush()?;
        Ok(())
    }

    fn word_right(&mut self) -> Result<(), std::io::Error> {
        let mut o = std::io::stdout();
        if self.cursor < self.buf.len() {
            let bytes = self.buf.as_bytes();
            let (w, h) = size();
            let mut is_first = true;
            while self.cursor < self.buf.len() {
                self.cursor += 1;
                if self.posx < w {
                    self.posx += 1;
                } else {
                    if self.posy >= h {
                        write!(o, "\x1b[1S")?;
                    }
                    self.posx = 1;
                    self.posy += 1;
                }
                if self.cursor >= self.buf.len() || bytes[self.cursor] == b' ' {
                    if !is_first {
                        break;
                    }
                } else {
                    is_first = false
                }
            }
        }
        if self.cursor < self.buf.len() && self.buf.as_bytes()[self.cursor] == b' ' {
            self.move_right()?
        } else {
            let mut o = std::io::stdout();
            write!(o, "\x1b[{};{}H", self.posy, self.posx)?;
            o.flush()?;
        }
        Ok(())
    }

    fn backspace(&mut self) -> Result<(), std::io::Error> {
        let mut o = std::io::stdout();
        if self.cursor >= 1 {
            self.cursor = prev_char(&self.buf, self.cursor);
            self.buf.remove(self.cursor);
            self.n_chars -= 1;
            if self.posx > 1 {
                self.posx -= 1;
                write!(o, "\x1b[{};{}H", self.posy, self.posx)?;
            } else {
                let (w, _) = size();
                self.posx = w;
                if self.posy > 1 {
                    write!(o, "\x1b[{};{}H", self.posy - 1, w)?;
                    self.posy -= 1;
                } else {
                    // scroll down by one
                    write!(o, "\x1b[1T")?;
                    write!(o, "\x1b[1;{}H", w)?;
                    self.posy0 = 1;
                    self.posy = 1;
                }
            }
            let (_, end) = self.buf.split_at(self.cursor);
            o.write_all(end.as_bytes())?;
            write!(o, "\x1b[0J")?;
            write!(o, "\x1b[{};{}H", self.posy, self.posx)?;
            o.flush()?;
        }
        Ok(())
    }

    fn delete(&mut self) -> Result<(), std::io::Error> {
        let mut o = std::io::stdout();
        if self.cursor < self.buf.len() {
            self.buf.remove(self.cursor);
            self.n_chars -= 1;
            let (_, end) = self.buf.split_at(self.cursor);
            o.write_all(end.as_bytes())?;
            write!(o, "\x1b[0J")?;
            write!(o, "\x1b[{};{}H", self.posy, self.posx)?;
            o.flush()?;
        }
        Ok(())
    }

    fn erase_to_end(&mut self) -> Result<(), std::io::Error> {
        let mut o = std::io::stdout();
        if self.cursor < self.buf.len() {
            self.buf.truncate(self.cursor);
            write!(o, "\x1b[0J")?;
            write!(o, "\x1b[{};{}H", self.posy, self.posx)?;
            o.flush()?;
        }
        Ok(())
    }

    fn insert(&mut self, c: char) -> Result<(), std::io::Error> {
        let mut o = std::io::stdout();
        self.n_chars += 1;
        self.buf.insert(self.cursor, c);
        let (w, h) = size();

        let (_, end) = self.buf.split_at(self.cursor);
        o.write_all(end.as_bytes())?;

        if self.posx + 1 > w && self.posy + 1 > h && end.len() == 1 {
            // we're discovering a new line, scroll up
            write!(o, "\x1b[1S")?;
            write!(o, "\x1b[{};1H", self.posy)?;
            self.posx = 1;
        } else {
            write!(o, "\x1b[{};{}H", self.posy, self.posx + 1)?;
            self.posx += 1
            // did we scroll down when we wrote `end`?
            let y_end = self.posy + ((self.posx + end.len() - 2) / w);
            if y_end > h {
                if self.posx + 1 > w {
                    write!(o, "\x1b[{};1H", self.posy)?;
                    self.posx = 1;
                } else {
                    write!(o, "\x1b[{};{}H", self.posy - 1, self.posx + 1)?;
                    self.posy -= 1;
                    self.posx += 1;
                }
            } else if self.posx + 1 > w {
                // Ok, we didn't scroll down, but we're at the right
                // edge of the screen, and `end` did not start a new
                // line.
                write!(o, "\x1b[{};1H", self.posy + 1)?;
                self.posx = 1;
                self.posy += 1;
            } else {
                // we're not at the right edge of the screen, and
                // `end` did not start a new line.
                write!(o, "\x1b[{};{}H", self.posy, self.posx + 1)?;
                self.posx += 1;
            }
        }