summaryrefslogtreecommitdiffstats
path: root/src/textview.rs
blob: 73b7741547f0c3cdbfa33a40ab47bea28cba45d7 (plain)
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
use ::rayon::prelude::*;

use std::io::BufRead;

use crate::coordinates::{Coordinates, Position, Size};
use crate::files::File;
use crate::term::sized_string;
use crate::widget::Widget;

#[derive(PartialEq)]
pub struct TextView {
    pub lines: Vec<String>,
    pub buffer: String,
    pub coordinates: Coordinates,
}

impl TextView {
    pub fn new_from_file(file: &File) -> TextView {
        let file = std::fs::File::open(&file.path).unwrap();
        let file = std::io::BufReader::new(file);
        let lines = file.lines().map(|line|
                                     line.unwrap()
                                     .replace("\t", "    ")).collect();

        TextView {
            lines: lines,
            buffer: String::new(),
            coordinates: Coordinates::new(),
        }
    }
    pub fn new_from_file_limit_lines(file: &File, num: usize) -> TextView {
        let file = std::fs::File::open(&file.path).unwrap();
        let file = std::io::BufReader::new(file);
        let lines = file.lines()
                        .take(num)
                        .map(|line|
                             line.unwrap()
                                 .replace("\t", "    ")).collect();

        TextView {
            lines: lines,
            buffer: String::new(),
            coordinates: Coordinates::new(),
        }
    }
}

impl Widget for TextView {
    fn get_coordinates(&self) -> &Coordinates {
        &self.coordinates
    }
    fn set_coordinates(&mut self, coordinates: &Coordinates) {
        self.coordinates = coordinates.clone();
        self.refresh();
    }
    fn render_header(&self) -> String {
        "".to_string()
    }
    fn refresh(&mut self) {
        let (xsize, ysize) = self.get_coordinates().size().size();
        let (xpos, ypos) = self.get_coordinates().position().position();

        self.buffer = self.get_clearlist() +
            &self
            .lines
            .par_iter()
            .take(ysize as usize)
            .enumerate()
            .map(|(i, line)| {
                format!(
                    "{}{}{}",
                    crate::term::goto_xy(xpos, i as u16 + ypos),
                    crate::term::reset(),
                    sized_string(&line, xsize))
            })
            .collect::<String>();
    }

    fn get_drawlist(&self) -> String {
        self.buffer.clone()
    }
}