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/ui.rs

482 lines
14 KiB
Rust

5 years ago
mod action;
5 years ago
mod view;
5 years ago
pub use self::action::Action;
5 years ago
pub use self::view::View;
use std::io;
use std::io::{stdin, stdout, Write};
5 years ago
use std::process;
use std::process::Stdio;
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
5 years ago
use termion::color;
5 years ago
use termion::input::TermRead;
use termion::raw::IntoRawMode;
5 years ago
use termion::terminal_size;
5 years ago
use gopher;
use gopher::io_error;
use gopher::Type;
5 years ago
use help;
5 years ago
use menu::Menu;
use text::Text;
5 years ago
pub type Key = termion::event::Key;
pub type Page = Box<dyn View>;
5 years ago
5 years ago
pub const SCROLL_LINES: usize = 15;
pub const MAX_COLS: usize = 72;
5 years ago
pub struct UI {
views: Vec<Page>, // loaded views
focused: usize, // currently focused view
dirty: bool, // redraw?
running: bool, // main ui loop running?
pub size: (usize, usize), // cols, rows
status: String, // status message, if any
5 years ago
}
impl UI {
pub fn new() -> UI {
let mut size = (0, 0);
5 years ago
if let Ok((cols, rows)) = terminal_size() {
size = (cols as usize, rows as usize);
}
5 years ago
UI {
5 years ago
views: vec![],
5 years ago
focused: 0,
5 years ago
dirty: true,
running: true,
size,
status: String::new(),
5 years ago
}
}
5 years ago
pub fn run(&mut self) {
5 years ago
self.startup();
while self.running {
5 years ago
self.draw();
self.update();
5 years ago
}
self.shutdown();
5 years ago
}
fn set_status(&mut self, status: String) {
self.status = status;
self.dirty = true;
}
fn render_status(&self) -> Option<String> {
if self.status.is_empty() {
None
} else {
Some(format!(
"{}{}{}{}",
termion::cursor::Goto(1, self.rows()),
termion::clear::CurrentLine,
self.status,
color::Fg(color::Reset)
))
}
}
5 years ago
pub fn draw(&mut self) {
if self.dirty {
5 years ago
print!(
"{}{}{}{}{}",
5 years ago
termion::clear::All,
termion::cursor::Goto(1, 1),
termion::cursor::Hide,
self.render(),
5 years ago
self.render_status().unwrap_or_else(|| "".into()),
5 years ago
);
5 years ago
self.dirty = false;
}
5 years ago
}
pub fn update(&mut self) {
let mut stdout = stdout().into_raw_mode().unwrap();
stdout.flush().unwrap();
5 years ago
let action = self.process_page_input();
if let Err(e) = self.process_action(action) {
self.set_status(format!("{}{}", color::Fg(color::LightRed), e));
}
5 years ago
}
pub fn open(&mut self, url: &str) -> io::Result<()> {
self.status.clear();
5 years ago
// no open loops
5 years ago
if let Some(page) = self.views.get(self.focused) {
5 years ago
if page.url() == url {
5 years ago
return Ok(());
}
}
5 years ago
// non-gopher URL
5 years ago
if url.contains("://") && !url.starts_with("gopher://") {
5 years ago
return open_external(url);
}
5 years ago
// binary downloads
let (typ, _, _, _) = gopher::parse_url(url);
if typ.is_download() {
return self.download(url);
}
5 years ago
self.fetch(url).and_then(|page| {
self.add_page(page);
Ok(())
})
5 years ago
}
5 years ago
fn download(&mut self, url: &str) -> io::Result<()> {
let url = url.to_string();
self.spinner("", move || gopher::download_url(&url))
.and_then(|res| res)
.and_then(|res| {
self.set_status(format!("Download complete! {}", res));
Ok(())
})
}
fn fetch(&mut self, url: &str) -> io::Result<Page> {
5 years ago
// on-line help
if url.starts_with("gopher://help/") {
5 years ago
return self.fetch_help(url);
5 years ago
}
// request thread
let thread_url = url.to_string();
let res = self.spinner("", move || gopher::fetch_url(&thread_url))??;
5 years ago
let (typ, _, _, _) = gopher::parse_url(&url);
5 years ago
match typ {
Type::Menu | Type::Search => Ok(Box::new(Menu::from(url.to_string(), res))),
Type::Text | Type::HTML => Ok(Box::new(Text::from(url.to_string(), res))),
_ => Err(io_error(format!("Unsupported Gopher Response: {:?}", typ))),
}
5 years ago
}
5 years ago
// get Menu for on-line help url, ex: gopher://help/1/types
fn fetch_help(&mut self, url: &str) -> io::Result<Page> {
5 years ago
if let Some(source) = help::lookup(
&url.trim_start_matches("gopher://help/")
.trim_start_matches("1/"),
) {
5 years ago
Ok(Box::new(Menu::from(url.to_string(), source.to_string())))
5 years ago
} else {
Err(gopher::io_error(format!("Help file not found: {}", url)))
}
}
// Show a spinner while running a thread. Used to make gopher requests or
// download files.
fn spinner<T: Send + 'static, F: 'static + Send + FnOnce() -> T>(
&mut self,
label: &str,
work: F,
) -> io::Result<T> {
let req = thread::spawn(work);
let (tx, rx) = mpsc::channel();
let label = label.to_string();
thread::spawn(move || loop {
for i in 0..=3 {
if rx.try_recv().is_ok() {
return;
}
print!(
"\r{}{}{}{}{}{}",
termion::cursor::Hide,
color::Fg(color::LightBlack),
label,
".".repeat(i),
termion::clear::AfterCursor,
color::Fg(color::Reset)
);
stdout().flush();
thread::sleep(Duration::from_millis(350));
}
});
let result = req.join();
tx.send(true); // stop spinner
self.dirty = true;
result.map_err(|e| io_error(format!("Spinner error: {:?}", e)))
}
pub fn render(&mut self) -> String {
5 years ago
if let Ok((cols, rows)) = terminal_size() {
5 years ago
self.term_size(cols as usize, rows as usize);
5 years ago
if !self.views.is_empty() && self.focused < self.views.len() {
if let Some(page) = self.views.get_mut(self.focused) {
5 years ago
page.term_size(cols as usize, rows as usize);
return page.render();
}
}
String::from("No content to display.")
} else {
format!(
"Error getting terminal size. Please file a bug: {}",
"https://github.com/dvkt/phetch/issues/new"
)
}
}
fn rows(&self) -> u16 {
self.size.1 as u16
}
5 years ago
fn startup(&mut self) {
self.load_history();
}
fn shutdown(&self) {
self.save_history();
}
5 years ago
fn config_dir_path(&self) -> Option<std::path::PathBuf> {
let homevar = std::env::var("HOME");
if homevar.is_err() {
5 years ago
return None;
}
let dotdir = "~/.config/phetch".replace('~', &homevar.unwrap());
5 years ago
let dotdir = std::path::Path::new(&dotdir);
if dotdir.exists() {
Some(std::path::PathBuf::from(dotdir))
} else {
None
}
}
fn load_history(&mut self) {
// let dotdir = self.config_dir_path();
// if dotdir.is_none() {
// return;
// }
// let history = dotdir.unwrap().join("history");
// if let Ok(file) = std::fs::OpenOptions::new().read(true).open(history) {
// let buffered = BufReader::new(file);
// let mut lines = buffered.lines();
// while let Some(Ok(url)) = lines.next() {}
// }
5 years ago
}
5 years ago
fn save_history(&self) {
let dotdir = self.config_dir_path();
if dotdir.is_none() {
return;
}
let dotdir = dotdir.unwrap();
let mut out = String::new();
5 years ago
for page in &self.views {
5 years ago
let url = page.url();
if url.starts_with("gopher://help/") {
continue;
}
out.push_str(&page.url());
out.push('\n');
}
5 years ago
let history = dotdir.join("history");
5 years ago
if let Ok(mut file) = std::fs::OpenOptions::new()
5 years ago
.append(true)
5 years ago
.create(true)
5 years ago
.open(history)
5 years ago
{
file.write_all(out.as_ref());
}
}
5 years ago
fn term_size(&mut self, cols: usize, rows: usize) {
5 years ago
self.size = (cols, rows);
}
5 years ago
fn add_page(&mut self, page: Page) {
self.dirty = true;
5 years ago
if !self.views.is_empty() && self.focused < self.views.len() - 1 {
self.views.truncate(self.focused + 1);
5 years ago
}
5 years ago
self.views.push(page);
5 years ago
if self.views.len() > 1 {
5 years ago
self.focused += 1;
5 years ago
}
}
fn process_page_input(&mut self) -> Action {
5 years ago
if let Some(page) = self.views.get_mut(self.focused) {
if let Ok(key) = stdin()
.keys()
.nth(0)
5 years ago
.ok_or_else(|| Action::Error("stdin.keys() error".to_string()))
{
if let Ok(key) = key {
5 years ago
return page.respond(key);
}
}
}
Action::None
}
5 years ago
fn process_action(&mut self, action: Action) -> io::Result<()> {
match action {
Action::Keypress(Key::Esc) => self.status.clear(),
Action::Keypress(Key::Ctrl('c')) => {
if self.status.is_empty() {
self.running = false
} else {
self.dirty = true;
self.status.clear();
}
5 years ago
}
Action::Keypress(Key::Ctrl('q')) => self.running = false,
Action::Error(e) => return Err(io_error(e)),
Action::Redraw => self.dirty = true,
Action::Open(url) => self.open(&url)?,
5 years ago
Action::Keypress(Key::Left) | Action::Keypress(Key::Backspace) => {
5 years ago
if self.focused > 0 {
5 years ago
self.dirty = true;
5 years ago
self.focused -= 1;
5 years ago
}
}
5 years ago
Action::Keypress(Key::Right) => {
5 years ago
if self.focused < self.views.len() - 1 {
5 years ago
self.dirty = true;
5 years ago
self.focused += 1;
5 years ago
}
}
5 years ago
Action::Keypress(Key::Ctrl('r')) => {
5 years ago
if let Some(page) = self.views.get(self.focused) {
5 years ago
let url = page.url();
let raw = page.raw();
5 years ago
self.add_page(Box::new(Text::from(url, raw)));
5 years ago
}
}
5 years ago
Action::Keypress(Key::Ctrl('g')) => {
5 years ago
if let Some(url) = prompt("Go to URL: ") {
5 years ago
if !url.contains("://") && !url.starts_with("gopher://") {
self.open(&format!("gopher://{}", url))?;
} else {
self.open(&url)?;
}
}
}
5 years ago
Action::Keypress(Key::Ctrl('h')) => self.open("gopher://help/")?,
5 years ago
Action::Keypress(Key::Ctrl('u')) => {
5 years ago
if let Some(page) = self.views.get(self.focused) {
5 years ago
let url = page.url();
self.set_status(format!("Current URL: {}", url));
5 years ago
}
}
Action::Keypress(Key::Ctrl('y')) => {
5 years ago
if let Some(page) = self.views.get(self.focused) {
5 years ago
let url = page.url();
copy_to_clipboard(&url)?;
self.set_status(format!("Copied {} to clipboard.", url));
5 years ago
}
5 years ago
}
_ => (),
5 years ago
}
Ok(())
5 years ago
}
5 years ago
}
5 years ago
impl Drop for UI {
fn drop(&mut self) {
print!("\x1b[?25h"); // show cursor
}
}
fn copy_to_clipboard(data: &str) -> io::Result<()> {
spawn_os_clipboard()
.and_then(|mut child| {
5 years ago
let child_stdin = child.stdin.as_mut().unwrap();
child_stdin.write_all(data.as_bytes())
})
.map_err(|e| io_error(format!("Clipboard error: {}", e)))
5 years ago
}
5 years ago
fn spawn_os_clipboard() -> io::Result<process::Child> {
5 years ago
if cfg!(target_os = "macos") {
5 years ago
process::Command::new("pbcopy")
.stdin(Stdio::piped())
.spawn()
5 years ago
} else {
5 years ago
process::Command::new("xclip")
5 years ago
.args(&["-sel", "clip"])
.stdin(Stdio::piped())
.spawn()
}
}
5 years ago
// runs the `open` shell command
fn open_external(url: &str) -> io::Result<()> {
process::Command::new("open")
.arg(url)
.output()
.and_then(|_| Ok(()))
}
5 years ago
/// Prompt user for input and return what was entered, if anything.
pub fn prompt(prompt: &str) -> Option<String> {
5 years ago
let (_cols, rows) = terminal_size().unwrap();
5 years ago
print!(
"{}{}{}{}{}",
color::Fg(color::Reset),
termion::cursor::Goto(1, rows),
termion::clear::CurrentLine,
prompt,
termion::cursor::Show,
);
stdout().flush();
let mut input = String::new();
for k in stdin().keys() {
if let Ok(key) = k {
match key {
Key::Char('\n') => {
print!("{}{}", termion::clear::CurrentLine, termion::cursor::Hide);
stdout().flush();
return Some(input);
}
Key::Char(c) => input.push(c),
Key::Esc | Key::Ctrl('c') => {
if input.is_empty() {
print!("{}{}", termion::clear::CurrentLine, termion::cursor::Hide);
stdout().flush();
return None;
} else {
input.clear();
}
}
Key::Backspace | Key::Delete => {
input.pop();
}
_ => {}
}
} else {
break;
}
print!(
"{}{}{}{}",
termion::cursor::Goto(1, rows),
termion::clear::CurrentLine,
prompt,
input,
);
stdout().flush();
}
if !input.is_empty() {
Some(input)
} else {
None
}
}