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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
|
#![forbid(unsafe_code)]
use crate::types::*;
use smol::prelude::*;
use smol::fs::File;
use smol::lock::RwLock;
use std::path::PathBuf;
use std::process::ExitCode;
use std::ops::Range;
mod encoding;
mod terminal;
mod types;
struct Ivy {
terminal: RwLock<Terminal>,
buffer: RwLock<Buffer>,
window: RwLock<Window>,
argument_files: Vec<PathBuf>,
}
struct Buffer {
path: Option<PathBuf>,
contents: RwLock<Vec<u8>>,
lines: RwLock<Vec<usize>>,
has_end_newline: RwLock<bool>,
}
struct Window {
/* The traditional order of writing "row, column" is the opposite of the
* traditional order of writing "x, y"; be mindful. An alternate approach
* would use "x" and "y" for all the names, which might arguably reduce
* confusion, but personally we find the ordering concern to be
* aesthetically pleasing, a quiet reminder of how much humans care about
* everything.
*/
cursor_row: RwLock<usize>,
cursor_column: RwLock<usize>,
/* The neutral column is the one that vertical movement will attempt to
* land in, if it exists in the target row.
*/
cursor_neutral_column: RwLock<usize>,
scroll_top: RwLock<usize>,
}
fn main() -> ExitCode {
smol::block_on(async {
if let Err(e) = Ivy::new().await.run().await {
println!("{:?}", e);
ExitCode::FAILURE
} else {
ExitCode::SUCCESS
}
})
}
impl Ivy {
async fn new() -> Self {
Ivy {
terminal: RwLock::new(Terminal::new().await),
buffer: RwLock::new(Buffer::new().await),
window: RwLock::new(Window::new().await),
argument_files: Vec::new(),
}
}
async fn run(mut self) -> Result<()> {
/* The awkward structure here is because it's important that cleanup still
* happen even if something fails in the middle.
*/
let mut error = None;
error = error.or(self.init().await.err());
error = error.or(self.interact().await.err());
error = error.or(self.zap().await.err());
if let Some(error) = error {
Err(error)
} else {
Ok(())
}
}
async fn init(&mut self) -> Result<()> {
self.init_arguments().await?;
self.init_editor().await?;
self.terminal.write().await.init_termios().await?;
self.terminal.write().await.init_full_screen().await?;
Ok(())
}
async fn zap(&mut self) -> Result<()> {
let mut error = None;
error = error.or(
self.terminal.write().await.zap_full_screen().await.err());
error = error.or(
self.terminal.write().await.zap_termios().await.err());
if let Some(error) = error {
Err(error)
} else {
Ok(())
}
}
async fn init_arguments(&mut self) -> Result<()> {
self.argument_files.clear();
let mut args = std::env::args();
let _ = args.next();
for argument in args {
self.argument_files.push(argument.into());
}
Ok(())
}
async fn init_editor(&mut self) -> Result<()> {
if !self.argument_files.is_empty() {
let path = self.argument_files.remove(0);
let new_buffer = Buffer::from_file(path).await?;
*self.buffer.write().await = new_buffer;
}
Ok(())
}
async fn draw(&mut self) -> Result<()> {
let mut terminal = self.terminal.write().await;
let buffer = self.buffer.read().await;
let height = *terminal.height.read().await;
let window = self.window.read().await;
let scroll_top = *window.scroll_top.read().await;
let mut screen_y = 0;
for i in 0 .. height - 1 {
if let Some(span) = buffer.line_span(i + scroll_top).await {
if i > 0 {
terminal.stdout.write_all("\n".as_bytes()).await?;
}
terminal.stdout.write_all(&buffer.contents.read().await[span]).await?;
screen_y += 1;
} else {
break;
}
}
for _ in screen_y .. height - 1 {
terminal.stdout.write_all("\n~".as_bytes()).await?;
}
terminal.do_cursor_position(0, height).await?;
terminal.stdout.write_all(" status goes here".as_bytes()).await?;
let window = self.window.read().await;
terminal.do_cursor_position(*window.cursor_column.read().await,
*window.cursor_row.read().await
- *window.scroll_top.read().await).await?;
terminal.stdout.flush().await?;
Ok(())
}
async fn interact(&mut self) -> Result<()> {
self.draw().await?;
loop {
let c = self.terminal.write().await.read_char().await?;
match c {
'h' => {
self.handle_movement(async |ivy: &mut Ivy| {
let window = ivy.window.write().await;
let mut column = window.cursor_column.write().await;
if *column > 0 {
*column -= 1;
/* The neutral column only changes if the horizontal part of
* the movement actually moves. Tentatively, it doesn't look
* like POSIX has an opinion on this, but it matches Vim.
*/
*window.cursor_neutral_column.write().await = *column;
}
Ok(())
}).await?;
},
'j' => {
self.handle_movement(async |ivy: &mut Ivy| {
let buffer = ivy.buffer.read().await;
let window = ivy.window.write().await;
let mut row = window.cursor_row.write().await;
if *row + 1 < buffer.lines.read().await.len() {
*row += 1;
};
Ok(())
}).await?;
},
'k' => {
self.handle_movement(async |ivy: &mut Ivy| {
let window = ivy.window.write().await;
let mut row = window.cursor_row.write().await;
if *row > 0 {
*row -= 1;
}
Ok(())
}).await?;
},
'l' => {
self.handle_movement(async |ivy: &mut Ivy| {
let buffer = ivy.buffer.read().await;
let window = ivy.window.write().await;
let row = *window.cursor_row.read().await;
if let Some(span) = buffer.line_span(row).await {
let width = span.end - span.start;
let mut column = window.cursor_column.write().await;
if *column + 1 < width {
*column += 1;
/* The neutral column only changes if the horizontal part of
* the movement actually moves. Tentatively, it doesn't look
* like POSIX has an opinion on this, but it matches Vim.
*/
*window.cursor_neutral_column.write().await = *column;
}
}
Ok(())
}).await?;
},
'0' => {
self.handle_movement(async |ivy: &mut Ivy| {
let window = ivy.window.write().await;
let mut column = window.cursor_column.write().await;
*column = 0;
/* For this one, the neutral column changes regardless of
* whether the column does.
*/
*window.cursor_neutral_column.write().await = *column;
Ok(())
}).await?;
},
'$' => {
self.handle_movement(async |ivy: &mut Ivy| {
let buffer = ivy.buffer.read().await;
let window = ivy.window.write().await;
let row = *window.cursor_row.read().await;
if let Some(span) = buffer.line_span(row).await {
let width = span.end - span.start;
let mut column = window.cursor_column.write().await;
if width > 0 {
*column = width - 1;
} else {
*column = 0;
}
/* For this one, the neutral column changes regardless of
* whether the column does.
*/
*window.cursor_neutral_column.write().await = *column;
}
Ok(())
}).await?;
},
_ => {
return Ok(());
},
}
}
}
/* A movement is an arbitrarily complicated action that will not change the
* contents of the buffer, but may change other things, including the cursor
* position.
*/
async fn handle_movement(&mut self,
movement: impl AsyncFn(&mut Ivy) -> Result<()>)
-> Result<()>
{
let (old_row, old_column) = {
let window = self.window.read().await;
(*window.cursor_row.read().await,
*window.cursor_column.read().await)
};
movement(self).await?;
/* We clamp the column to the line width unconditionally, regardless of
* what kind of movement we did. This is always correct, because no
* intended behavior ever places the cursor beyond the end of the line.
* It does require taking a couple of locks that we might always need, but
* there's no strong reason to avoid that.
*/
self.clamp_cursor_column().await?;
self.scroll_to_cursor().await?;
{
let window = self.window.read().await;
let row = *window.cursor_row.read().await;
let column = *window.cursor_column.read().await;
if old_row != row || old_column != column {
let mut terminal = self.terminal.write().await;
let scroll_top = *window.scroll_top.read().await;
terminal.do_cursor_position(column, row - scroll_top).await?;
terminal.stdout.flush().await?;
}
}
Ok(())
}
async fn clamp_cursor_column(&mut self) -> Result<()> {
let window = self.window.write().await;
let row = window.cursor_row.read().await;
let mut column = window.cursor_column.write().await;
let buffer = self.buffer.read().await;
if let Some(span) = buffer.line_span(*row).await {
let width = span.end - span.start;
let neutral_column = *window.cursor_neutral_column.read().await;
if neutral_column < width {
*column = neutral_column;
} else if width > 0 {
*column = width - 1;
} else {
*column = 0;
}
}
Ok(())
}
async fn scroll_to_cursor(&mut self) -> Result<()> {
let old_scroll_top = *self.window.read().await.scroll_top.read().await;
{
let terminal = self.terminal.read().await;
let window = self.window.write().await;
let mut scroll_top = window.scroll_top.write().await;
let row = *window.cursor_row.read().await;
let height = *terminal.height.read().await;
let last_visible = *scroll_top + height - 2;
if row < *scroll_top {
*scroll_top -= *scroll_top - row;
} else if row > last_visible {
*scroll_top += row - last_visible;
}
}
let new_scroll_top = *self.window.read().await.scroll_top.read().await;
let height = *self.terminal.read().await.height.read().await - 1;
if new_scroll_top != old_scroll_top {
let difference = new_scroll_top as isize - old_scroll_top as isize;
if (difference.abs() as usize) < height {
self.terminal.write().await.scroll(difference).await?;
} else {
self.terminal.write().await.clear().await?;
self.draw().await?;
}
}
Ok(())
}
}
impl Buffer {
pub async fn new() -> Self {
Buffer {
path: None,
contents: RwLock::new("\n".to_string().into_bytes()),
lines: RwLock::new(vec![0]),
has_end_newline: RwLock::new(true),
}
}
pub async fn from_file(path: PathBuf) -> Result<Self> {
let mut file = File::open(&path).await?;
let mut contents = Vec::new();
let _ = file.read_to_end(&mut contents).await?;
let mut result = Buffer {
path: Some(path),
contents: RwLock::new(contents),
lines: RwLock::new(vec![0]),
has_end_newline: RwLock::new(true),
};
result.count_lines().await;
Ok(result)
}
pub async fn count_lines(&mut self) {
let contents = self.contents.read().await;
*self.lines.write().await = vec![0];
if contents.len() == 0 {
*self.has_end_newline.write().await = false;
} else {
let mut offset = 0;
while offset < contents.len() {
let c = contents[offset];
offset += 1;
if c == b'\n' {
if offset < contents.len() {
self.lines.write().await.push(offset);
} else {
*self.has_end_newline.write().await = true;
}
} else if offset == contents.len() {
*self.has_end_newline.write().await = false;
}
}
}
}
pub async fn line_span(&self, index: usize) -> Option<Range<usize>> {
let lines = self.lines.read().await;
if index < lines.len() {
let start = lines[index];
if index + 1 < lines.len() {
let end = lines[index + 1] - 1;
Some(start .. end)
} else {
let end = if *self.has_end_newline.read().await {
self.contents.read().await.len() - 1
} else {
self.contents.read().await.len()
};
Some(start .. end)
}
} else {
None
}
}
}
impl Window {
pub async fn new() -> Self {
Window {
cursor_row: RwLock::new(0),
cursor_column: RwLock::new(0),
cursor_neutral_column: RwLock::new(0),
scroll_top: RwLock::new(0),
}
}
}
|