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

320 lines
9.1 KiB
Rust

4 years ago
//! A View representing a Gopher text entry.
//! Responds to user input by producing an Action which is then handed
//! to the main UI to perform.
use crate::{
config::SharedConfig as Config,
4 years ago
encoding::Encoding,
terminal,
ui::{self, Action, Key, View, MAX_COLS, SCROLL_LINES},
};
4 years ago
use std::{borrow::Cow, fmt, str};
5 years ago
4 years ago
/// The Text View holds the raw Gopher response as well as information
/// about which lines should currently be displayed on screen.
5 years ago
pub struct Text {
/// Ref to our global config
config: Config,
/// Gopher URL
5 years ago
url: String,
/// Gopher response
4 years ago
raw_response: Vec<u8>,
/// Current scroll offset, in rows
scroll: usize,
/// Number of lines
lines: usize,
/// Size of longest line
longest: usize,
/// Current screen size, cols and rows
size: (usize, usize),
/// Was this page retrieved view TLS?
pub tls: bool,
/// Retrieved via Tor?
pub tor: bool,
/// UI mode. Interactive (Run), Printing, Raw mode...
mode: ui::Mode,
4 years ago
/// Text Encoding of Response
encoding: Encoding,
/// Currently in wide mode?
pub wide: bool,
5 years ago
}
5 years ago
impl fmt::Display for Text {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.url())
}
}
5 years ago
impl View for Text {
fn is_tls(&self) -> bool {
self.tls
}
4 years ago
fn is_tor(&self) -> bool {
self.tor
}
fn url(&self) -> &str {
self.url.as_ref()
5 years ago
}
fn raw(&self) -> &str {
4 years ago
str::from_utf8(&self.raw_response).unwrap_or_default()
5 years ago
}
5 years ago
fn term_size(&mut self, cols: usize, rows: usize) {
self.size = (cols, rows);
}
fn set_wide(&mut self, wide: bool) {
self.wide = wide;
}
fn wide(&mut self) -> bool {
self.wide
}
fn encoding(&self) -> Encoding {
self.encoding
}
5 years ago
fn respond(&mut self, c: Key) -> Action {
match c {
4 years ago
Key::Home => {
5 years ago
self.scroll = 0;
Action::Redraw
}
4 years ago
Key::End => {
4 years ago
self.scroll = self.final_scroll();
Action::Redraw
5 years ago
}
4 years ago
Key::Ctrl('e') => self.toggle_encoding(),
4 years ago
Key::Down | Key::Ctrl('n') | Key::Char('n') | Key::Ctrl('j') | Key::Char('j') => {
4 years ago
if self.scroll < self.final_scroll() {
self.scroll += 1;
Action::Redraw
} else {
Action::None
}
}
4 years ago
Key::Up | Key::Ctrl('p') | Key::Char('p') | Key::Ctrl('k') | 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(' ') => {
4 years ago
self.scroll += SCROLL_LINES;
if self.scroll > self.final_scroll() {
self.scroll = self.final_scroll();
}
4 years ago
Action::Redraw
}
_ => Action::Keypress(c),
}
5 years ago
}
fn render(&mut 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 {
" ".repeat((cols - longest) / 2)
} else {
String::from("")
};
let limit = if self.mode == ui::Mode::Run {
rows - 1
} else {
self.lines
};
4 years ago
let response = self.encoded_response();
let iter = response
.split_terminator('\n')
5 years ago
.skip(self.scroll)
.take(limit);
for line in iter {
4 years ago
// Check for Gopher's weird "end of response" line.
if line == ".\r" || line == "." {
continue;
}
5 years ago
if !self.wide {
out.push_str(&indent);
}
let line = line.trim_end_matches('\r').replace('\t', " ");
out.push_str(&line);
// clear rest of line
out.push_str(&format!("{}", terminal::ClearUntilNewline));
out.push_str("\r\n");
5 years ago
}
// clear remainder of screen
out.push_str(&format!("{}", terminal::ClearAfterCursor));
5 years ago
out
5 years ago
}
}
5 years ago
impl Text {
/// Create a Text View from a raw Gopher response and a few options.
pub fn from(url: &str, response: Vec<u8>, config: Config, tls: bool) -> Text {
let mut lines = 0;
let mut longest = 0;
4 years ago
let mut line_len = 0;
4 years ago
for &b in &response {
line_len += 1;
if b == b'\n' {
if line_len > longest {
longest = line_len;
}
line_len = 0;
lines += 1;
}
}
let mode = config.read().unwrap().mode;
let tor = config.read().unwrap().tor;
let encoding = config.read().unwrap().encoding;
let wide = config.read().unwrap().wide;
5 years ago
Text {
config,
url: url.into(),
raw_response: response,
scroll: 0,
5 years ago
lines,
longest,
size: (0, 0),
mode,
tls,
tor,
encoding,
wide,
}
5 years ago
}
5 years ago
4 years ago
/// Toggle between our two encodings.
fn toggle_encoding(&mut self) -> Action {
if matches!(self.encoding, Encoding::UTF8) {
self.encoding = Encoding::CP437;
} else {
self.encoding = Encoding::UTF8;
}
self.config.write().unwrap().encoding = self.encoding;
4 years ago
Action::Redraw
}
/// Interpret `self.raw_response` according to `self.encoding`.
fn encoded_response(&self) -> Cow<str> {
if matches!(self.encoding, Encoding::CP437) {
let mut converted = String::with_capacity(self.raw_response.len());
for b in &self.raw_response {
converted.push_str(cp437::convert_byte(&b));
}
Cow::from(converted)
} else {
String::from_utf8_lossy(&self.raw_response)
}
}
4 years ago
/// Final `self.scroll` value.
fn final_scroll(&self) -> usize {
4 years ago
let padding = (self.size.1 as f64 * 0.9) as usize;
5 years ago
if self.lines > padding {
self.lines - padding
} else {
0
}
}
5 years ago
}
4 years ago
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_cp437() {
let body = include_bytes!("../tests/CP437.txt");
let mut text = Text::from("", body.to_vec(), Config::default(), false);
4 years ago
text.mode = ui::Mode::Print;
let res = text.render();
assert!(!res.contains("╟"));
assert!(!res.contains("≈"));
assert!(!res.contains("Ω"));
assert!(!res.contains("Θ"));
text.toggle_encoding();
let res = text.render();
assert!(res.contains("╟"));
assert!(res.contains("≈"));
assert!(res.contains("Ω"));
assert!(res.contains("Θ"));
}
4 years ago
#[test]
fn test_wrapping() {
let text = "regular line
really really really really really really really really really really long line
super duper extra scooper hoopa loopa double doopa maxi paxi giga baxi very very long line
Qua nova re oblata omnis administratio belliconsistit militesque aversi a proelio ad studium audiendi et cognoscendi feruntur ubi hostes ad legatosexercitumque pervenerunt universi se ad pedes proiciunt orant ut adventus Caesaris expectetur captamsuam urbem videre...
really really really really really really really really really kinda-but-not-really long line
another regular line
";
let lines = wrap_lines(text, 70);
assert_eq!("regular line", lines[0]);
assert_eq!(
"really really really really really really really really really really",
lines[1].trim()
);
assert_eq!("long line", lines[2].trim());
assert_eq!("very very long line", lines[4].trim());
assert_eq!(
"Qua nova re oblata omnis administratio belliconsistit militesque",
lines[5].trim()
);
assert_eq!(
"aversi a proelio ad studium audiendi et cognoscendi feruntur ubi",
lines[6].trim()
);
assert_eq!(
"hostes ad legatosexercitumque pervenerunt universi se ad pedes",
lines[7].trim()
);
assert_eq!(
"really really really really really really really really really kinda-",
lines[10].trim()
);
assert_eq!("but-not-really long line", lines[11].trim());
assert_eq!(13, lines.len());
}
4 years ago
}