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

140 lines
3.8 KiB
Rust

5 years ago
use ui::{Action, Key, View, MAX_COLS, SCROLL_LINES};
5 years ago
5 years ago
pub struct Text {
5 years ago
url: String,
5 years ago
raw_response: String,
scroll: usize, // offset
lines: usize, // # of lines
longest: usize, // longest line
size: (usize, usize), // cols, rows
5 years ago
}
5 years ago
impl View for Text {
5 years ago
fn url(&self) -> String {
self.url.to_string()
}
5 years ago
fn raw(&self) -> String {
self.raw_response.to_string()
}
5 years ago
fn term_size(&mut self, cols: usize, rows: usize) {
self.size = (cols, rows);
}
5 years ago
fn respond(&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') => {
if self.lines >= SCROLL_LINES {
self.scroll = self.lines - SCROLL_LINES;
Action::Redraw
} else {
Action::None
}
5 years ago
}
5 years ago
Key::Down | Key::Ctrl('n') | Key::Char('j') => {
if self.lines > SCROLL_LINES && self.scroll < (self.lines - SCROLL_LINES) {
self.scroll += 1;
Action::Redraw
} else {
Action::None
}
}
5 years ago
Key::Up | Key::Ctrl('p') | Key::Char('k') => {
if self.scroll > 0 {
self.scroll -= 1;
Action::Redraw
} else {
Action::None
}
}
Key::PageUp | Key::Char('-') => {
if self.scroll > 0 {
if self.scroll >= SCROLL_LINES {
self.scroll -= SCROLL_LINES;
} else {
self.scroll = 0;
}
Action::Redraw
} else {
Action::None
}
}
Key::PageDown | Key::Char(' ') => {
let lines = self.lines - 1;
if lines > SCROLL_LINES {
if self.scroll < lines - SCROLL_LINES {
self.scroll += SCROLL_LINES;
if self.scroll >= lines {
self.scroll = lines;
}
}
Action::Redraw
} else {
Action::None
}
}
_ => Action::Keypress(c),
}
5 years ago
}
fn render(&self) -> String {
let (cols, rows) = self.size;
5 years ago
let mut out = String::new();
5 years ago
let longest = if self.longest > MAX_COLS {
MAX_COLS
} else {
self.longest
};
let indent = if cols >= longest && cols - longest <= 6 {
String::from("")
} else if cols >= longest {
5 years ago
let left = (cols - longest) / 2;
" ".repeat(left)
} else {
String::from("")
};
let iter = self
5 years ago
.raw_response
.split_terminator('\n')
5 years ago
.skip(self.scroll)
.take(rows - 1);
for line in iter {
if line == ".\r" {
continue;
}
out.push_str(&indent);
5 years ago
out.push_str(line);
out.push('\n');
}
out
5 years ago
}
}
5 years ago
impl Text {
pub fn from(url: String, response: String) -> Text {
let mut lines = 0;
let mut longest = 0;
for line in response.split_terminator('\n') {
lines += 1;
if line.len() > longest {
longest = line.len();
}
}
5 years ago
Text {
url,
5 years ago
raw_response: response,
scroll: 0,
5 years ago
lines,
longest,
size: (0, 0),
}
5 years ago
}
}