You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
phetch/src/text.rs

106 lines
2.8 KiB
Rust

5 years ago
use ui::{Action, Key, View};
pub struct TextView {
url: String,
raw: String,
scroll: isize, // offset
lines: isize, // # of lines
longest: usize, // longest line
5 years ago
}
5 years ago
const SCROLL_LINES: isize = 15;
5 years ago
impl View for TextView {
5 years ago
fn url(&self) -> String {
self.url.to_string()
}
5 years ago
fn process_input(&mut self, c: Key) -> Action {
match c {
5 years ago
Key::Char('t') | Key::Char('g') => {
self.scroll = 0;
Action::Redraw
}
Key::Char('b') | Key::Char('G') => {
5 years ago
self.scroll = self.lines - SCROLL_LINES;
5 years ago
Action::Redraw
}
Key::Down => {
5 years ago
if self.scroll < self.lines - 1 {
self.scroll += 1;
Action::Redraw
} else {
Action::None
}
}
Key::Up => {
if self.scroll > 0 {
self.scroll -= 1;
Action::Redraw
} else {
Action::None
}
}
Key::PageUp | Key::Char('-') => {
if self.scroll > 0 {
5 years ago
self.scroll -= SCROLL_LINES;
if self.scroll < 0 {
self.scroll = 0;
}
Action::Redraw
} else {
Action::None
}
}
Key::PageDown | Key::Char(' ') => {
5 years ago
if self.scroll < self.lines - 1 - SCROLL_LINES {
self.scroll += SCROLL_LINES;
5 years ago
if self.scroll >= self.lines {
self.scroll = self.lines - 1;
}
Action::Redraw
} else {
Action::None
}
}
_ => Action::Unknown,
}
5 years ago
}
5 years ago
fn render(&self, _cols: u16, rows: u16) -> String {
5 years ago
let mut out = String::new();
for (i, line) in self.raw.split_terminator('\n').enumerate() {
5 years ago
if i as isize > (self.scroll + rows as isize) - 2 {
5 years ago
break;
}
5 years ago
if i < self.scroll as usize {
continue;
}
5 years ago
out.push_str(line);
out.push('\n');
}
out
5 years ago
}
}
impl TextView {
pub fn from(url: String, response: String) -> TextView {
let mut lines = 0;
let mut longest = 0;
for line in response.split_terminator('\n') {
lines += 1;
if line.len() > longest {
longest = line.len();
}
}
TextView {
url,
raw: response,
scroll: 0,
5 years ago
lines,
longest,
}
5 years ago
}
}