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
498
499
500
//! This module defines screen related utilities.

mod buffer;

use crate::{
    color::{self, Color, Color2},
    coord,
    coord::{Coord, Vec2},
    error::Error,
    screen::buffer::ScreenBuffer,
    stdio,
    stdio::{restore_screen, save_screen, LockedStdout, Stdout},
    string::{TermGrapheme, TermString},
    style::Style,
    terminal::Shared,
    tile::{self, Tile},
};
use std::{
    fmt::Write,
    sync::atomic::{AtomicBool, Ordering::*},
    time::Duration,
};
use tokio::{
    io,
    sync::{Mutex, MutexGuard, Notify},
    task,
    time,
};

/// Shared memory between terminal handle copies.
#[derive(Debug)]
pub(crate) struct ScreenData {
    /// Minimum screen size.
    min_size: Vec2,
    /// Frame interval time.
    frame_time: Duration,
    /// Whether the terminal handle has been cleaned up (using
    /// terminal.cleanup).
    cleanedup: AtomicBool,
    /// A lock to the standard output.
    stdout: Stdout,
    /// Buffer responsible for rendering the screen.
    buffer: Mutex<ScreenBuffer>,
    /// Notification handle of the screen.
    notifier: Notify,
}

impl ScreenData {
    /// Creates screen data from the given settings. If given actual size is
    /// less than given minimum allowed size, the actual size is replaced by the
    /// minimum size.
    pub fn new(size: Vec2, min_size: Vec2, frame_time: Duration) -> Self {
        let corrected_size = if size.x >= min_size.x && size.y >= min_size.y {
            size
        } else {
            min_size
        };
        Self {
            min_size,
            frame_time,
            cleanedup: AtomicBool::new(false),
            stdout: Stdout::new(),
            buffer: Mutex::new(ScreenBuffer::blank(corrected_size)),
            notifier: Notify::new(),
        }
    }

    /// Notifies all parties subscribed to the screen updates.
    pub fn notify(&self) {
        self.notifier.notify_waiters()
    }

    /// Subscribes to changes in the screen data such as disconnection.
    async fn subscribe(&self) {
        self.notifier.notified().await
    }

    /// Locks the screen data into an actual screen handle.
    pub async fn lock<'this>(&'this self) -> Screen<'this> {
        Screen::new(self).await
    }

    /// Initialization of the terminal, such as cleaning the screen.
    pub async fn setup(&self) -> Result<(), Error> {
        let mut buf = String::new();
        save_screen(&mut buf)?;
        write!(
            buf,
            "{}{}{}{}",
            crossterm::style::SetBackgroundColor(
                crossterm::style::Color::Black
            ),
            crossterm::style::SetForegroundColor(
                crossterm::style::Color::White
            ),
            crossterm::cursor::Hide,
            crossterm::terminal::Clear(crossterm::terminal::ClearType::All),
        )?;
        self.stdout.write_and_flush(buf.as_bytes()).await?;
        Ok(())
    }

    /// Asynchronous cleanup. It is preferred to call this before dropping.
    pub async fn cleanup(&self) -> Result<(), Error> {
        task::block_in_place(|| crossterm::terminal::disable_raw_mode())?;
        let mut buf = String::new();
        write!(buf, "{}", crossterm::cursor::Show)?;
        restore_screen(&mut buf)?;
        self.stdout.write_and_flush(buf.as_bytes()).await?;
        self.cleanedup.store(true, Release);
        Ok(())
    }
}

impl Drop for ScreenData {
    fn drop(&mut self) {
        if !self.cleanedup.load(Relaxed) {
            let _ = crossterm::terminal::disable_raw_mode();
            let mut buf = String::new();
            write!(buf, "{}", crossterm::cursor::Show)
                .ok()
                .and_then(|_| stdio::restore_screen(&mut buf).ok())
                .map(|_| println!("{}", buf));
        }
    }
}

/// Panics given that a point in the screen is out of bounds. This is here so
/// that the compiler can make other functions smaller.
#[cold]
#[inline(never)]
fn out_of_bounds(point: Vec2, size: Vec2) -> ! {
    panic!(
        "Point x: {}, y: {} out of screen size x: {}, y: {}",
        point.x, point.y, size.x, size.y
    )
}

/// A locked screen terminal with exclusive access to it. With this struct, a
/// locked screen handle, one can execute many operations without locking and
/// unlocking.
#[derive(Debug)]
pub struct Screen<'terminal> {
    /// Reference to the original screen.
    data: &'terminal ScreenData,
    /// Locked guard to the buffer.
    buffer: MutexGuard<'terminal, ScreenBuffer>,
}

impl<'terminal> Screen<'terminal> {
    /// Creates a locked screen from a reference to the unlocked screen handle,
    /// and a locked guard to the buffer.
    pub(crate) async fn new<'param>(
        data: &'param ScreenData,
    ) -> Screen<'terminal>
    where
        'param: 'terminal,
    {
        Self { data, buffer: data.buffer.lock().await }
    }

    /// Returns the current size of the screen.
    pub fn size(&self) -> Vec2 {
        self.buffer.size()
    }

    /// Returns whether the stored size is the actual size and the actual size
    /// is valid.
    pub fn valid_size(&self) -> bool {
        self.buffer.valid
    }

    /// Returns the minimum size required for the screen.
    pub fn min_size(&self) -> Vec2 {
        self.data.min_size
    }

    /// Applies an update function to a [`Tile`]. An update function gets access
    /// to a mutable reference of a [`Tile`], updates it, and then the screen
    /// handles any changes made to it. A regular [`Tile`] can be used as an
    /// updater, in which the case a simple replacement is made. This operation
    /// is buffered.
    pub fn set<T>(&mut self, point: Vec2, updater: T)
    where
        T: tile::Updater,
    {
        let index = self
            .buffer
            .make_index(point)
            .unwrap_or_else(|| out_of_bounds(point, self.buffer.size()));
        updater.update(&mut self.buffer.curr[index]);
        if self.buffer.old[index] != self.buffer.curr[index] {
            self.buffer.changed.insert(point);
        } else {
            self.buffer.changed.remove(&point);
        }
    }

    /// Gets the attributes of a given [`Tile`], regardless of being flushed to
    /// the screen yet or not.
    pub fn get(&self, point: Vec2) -> &Tile {
        let index = self
            .buffer
            .make_index(point)
            .unwrap_or_else(|| out_of_bounds(point, self.buffer.size()));
        &self.buffer.curr[index]
    }

    /// Sets every [`Tile`] into a whitespace grapheme with the given color.
    pub fn clear(&mut self, background: Color) {
        let size = self.buffer.size();
        let tile = Tile {
            colors: Color2 { background, ..Color2::default() },
            grapheme: TermGrapheme::space(),
        };

        for y in 0 .. size.y {
            for x in 0 .. size.x {
                self.set(Vec2 { x, y }, tile.clone());
            }
        }
    }

    /// Prints a grapheme-encoded text (a [`TermString`]) using some style
    /// options like ratio to the screen, color, margin and others. See
    /// [`Style`].
    pub fn styled_text<C>(
        &mut self,
        tstring: &TermString,
        style: Style<C>,
    ) -> Coord
    where
        C: color::Updater,
    {
        let mut len = tstring.count_graphemes();
        let mut slice = tstring.index(..);
        let screen_size = self.buffer.size();
        let size = style.make_size(screen_size);

        let mut cursor = Vec2 { x: 0, y: style.top_margin };
        let mut is_inside = cursor.y - style.top_margin < size.y;

        while len > 0 && is_inside {
            is_inside = cursor.y - style.top_margin + 1 < size.y;
            let width = coord::to_index(size.x);
            let pos = self.find_break_pos(width, len, size, &slice, is_inside);

            cursor.x = size.x - coord::from_index(pos);
            cursor.x = cursor.x + style.left_margin - style.right_margin;
            cursor.x = cursor.x * style.align_numer / style.align_denom;

            slice = slice.index(.. pos);

            self.write_styled_slice(&slice, &style, &mut cursor);

            if pos != len && !is_inside {
                self.set(cursor, |tile: &mut Tile| {
                    let grapheme = TermGrapheme::new_lossy("…");
                    let colors = style.colors.update(tile.colors);
                    *tile = Tile { grapheme, colors };
                });
            }

            cursor.y += 1;
            len -= pos;
        }
        cursor.y
    }

    /// Finds the position where a line should break in a styled text.
    fn find_break_pos(
        &self,
        width: usize,
        total_graphemes: usize,
        term_size: Vec2,
        slice: &TermString,
        is_inside: bool,
    ) -> usize {
        if width <= slice.len() {
            let mut pos = slice
                .index(.. coord::to_index(term_size.x))
                .iter()
                .rev()
                .position(|grapheme| grapheme == TermGrapheme::space())
                .map_or(width, |rev| total_graphemes - rev);
            if !is_inside {
                pos -= 1;
            }
            pos
        } else {
            total_graphemes
        }
    }

    /// Writes a slice using the given style. It should fit in one line.
    fn write_styled_slice<C>(
        &mut self,
        slice: &TermString,
        style: &Style<C>,
        cursor: &mut Vec2,
    ) where
        C: color::Updater,
    {
        for grapheme in slice {
            self.set(*cursor, |tile: &mut Tile| {
                tile.grapheme = grapheme;
                tile.colors = style.colors.update(tile.colors);
            });
            cursor.x += 1;
        }
    }

    /// Checks if the new size is valid. If valid, then it resizes the screen,
    /// and sets the `guard` to `None`. Otherwise, stdout is locked, and the
    /// locked stdout is put into `guard`.
    pub(crate) async fn check_resize(
        &mut self,
        new_size: Vec2,
        guard: &mut Option<LockedStdout<'terminal>>,
    ) -> io::Result<()> {
        let min_size = self.data.min_size;
        if new_size.x < min_size.x || new_size.y < min_size.y {
            if guard.is_none() {
                self.buffer.valid = false;
                let mut stdout = self.data.stdout.lock().await;
                self.ask_resize(&mut stdout, min_size).await?;
                *guard = Some(stdout);
            }
        } else {
            let mut stdout = match guard.take() {
                Some(stdout) => stdout,
                None => self.data.stdout.lock().await,
            };
            self.buffer.valid = true;
            self.resize(new_size, &mut stdout).await?;
        }

        Ok(())
    }

    /// Asks the user to resize the screen (manually).
    async fn ask_resize(
        &mut self,
        stdout: &mut LockedStdout<'terminal>,
        min_size: Vec2,
    ) -> io::Result<()> {
        let buf = format!(
            "{}{}RESIZE {}x{}",
            crossterm::terminal::Clear(crossterm::terminal::ClearType::All),
            crossterm::cursor::MoveTo(0, 0),
            min_size.x,
            min_size.y,
        );

        stdout.write_and_flush(buf.as_bytes()).await?;

        Ok(())
    }

    /// Triggers the resize of the screen.
    async fn resize(
        &mut self,
        new_size: Vec2,
        stdout: &mut LockedStdout<'terminal>,
    ) -> io::Result<()> {
        let buf = format!(
            "{}{}{}",
            crossterm::style::SetForegroundColor(
                crossterm::style::Color::White
            ),
            crossterm::style::SetBackgroundColor(
                crossterm::style::Color::Black
            ),
            crossterm::terminal::Clear(crossterm::terminal::ClearType::All)
        );
        stdout.write_and_flush(buf.as_bytes()).await?;
        self.buffer.resize(new_size);

        Ok(())
    }

    /// Renders the buffer into the screen using the referred terminal.
    pub(crate) async fn render(
        &mut self,
        buf: &mut String,
    ) -> Result<(), Error> {
        let screen_size = self.buffer.size();
        buf.clear();

        let mut colors = Color2::default();
        let mut cursor = Vec2 { x: 0, y: 0 };
        self.render_init_term(buf, colors, cursor)?;

        for &coord in self.buffer.changed.iter() {
            self.render_tile(
                buf,
                &mut colors,
                &mut cursor,
                screen_size,
                coord,
            )?;
        }

        if let Some(mut stdout) = self.data.stdout.try_lock() {
            stdout.write_and_flush(buf.as_bytes()).await?;
        }

        self.buffer.next_tick();

        Ok(())
    }

    /// Initializes terminal state into the buffer before rendering.
    fn render_init_term(
        &self,
        buf: &mut String,
        colors: Color2,
        cursor: Vec2,
    ) -> Result<(), Error> {
        write!(
            buf,
            "{}{}{}",
            crossterm::style::SetForegroundColor(
                colors.foreground.to_crossterm()
            ),
            crossterm::style::SetBackgroundColor(
                colors.background.to_crossterm()
            ),
            crossterm::cursor::MoveTo(
                coord::to_crossterm(cursor.x),
                coord::to_crossterm(cursor.y)
            ),
        )?;

        Ok(())
    }

    /// Renders a single tile in the given coordinate.
    fn render_tile(
        &self,
        buf: &mut String,
        colors: &mut Color2,
        cursor: &mut Vec2,
        screen_size: Vec2,
        coord: Vec2,
    ) -> Result<(), Error> {
        if *cursor != coord {
            write!(
                buf,
                "{}",
                crossterm::cursor::MoveTo(
                    coord::to_crossterm(coord.x),
                    coord::to_crossterm(coord.y)
                )
            )?;
        }
        *cursor = coord;

        let tile = self.get(*cursor);
        if colors.background != tile.colors.background {
            let color = tile.colors.background.to_crossterm();
            write!(buf, "{}", crossterm::style::SetBackgroundColor(color))?;
        }
        if colors.foreground != tile.colors.foreground {
            let color = tile.colors.foreground.to_crossterm();
            write!(buf, "{}", crossterm::style::SetForegroundColor(color))?;
        }
        *colors = tile.colors;

        write!(buf, "{}", tile.grapheme)?;

        if cursor.x <= screen_size.x {
            cursor.x += 1;
        }

        Ok(())
    }
}

/// The renderer loop. Should be called only when setting up a terminal handler.
/// Exits on error or when notified that it should exit.
pub(crate) async fn renderer(shared: &Shared) -> Result<(), Error> {
    let mut interval = time::interval(shared.screen().frame_time);
    let mut buf = String::new();

    loop {
        {
            let _guard = shared.service_guard().await?;
            let mut screen = shared.screen().lock().await;
            screen.render(&mut buf).await?;
        }

        tokio::select! {
            _ = interval.tick() => (),
            _ = shared.screen().subscribe() => break,
        };
    }

    Ok(())
}