rs-kilo/src/editor.rs

107 lines
2.2 KiB
Rust
Raw Normal View History

2019-08-22 14:25:18 -04:00
//! Editor functionality
2019-08-22 16:44:47 -04:00
use crate::helpers::*;
2019-08-22 14:25:18 -04:00
2019-08-22 16:44:47 -04:00
use nix::sys::termios::Termios;
use nix::unistd::read;
use std::io;
use std::io::prelude::*;
use std::io::{BufReader, Error, Stdin};
use std::str::Chars;
2019-08-22 16:44:47 -04:00
use term_parser::{Action, ActionIter};
/// Main structure for the editor
pub struct Editor {
2019-08-22 16:44:47 -04:00
}
2019-08-22 14:25:18 -04:00
// init
2019-08-22 14:25:18 -04:00
impl Editor {
pub fn new() -> Self {
Editor {
2019-08-22 16:44:47 -04:00
}
}
}
2019-08-22 16:44:47 -04:00
// Terminal
impl Editor {
fn read_key(&mut self) -> Option<Vec<char>> {
2019-08-22 16:44:47 -04:00
let stdin = io::stdin();
let mut in_str = String::new();
let mut input = BufReader::new(stdin.take(1));
input.read_to_string(&mut in_str).unwrap();
let mut output: Vec<char> = vec![];
for char in in_str.chars() {
output.push(char);
}
if output.len() == 0 {
return None
}
return Some(output)
2019-08-22 16:44:47 -04:00
}
fn read_term_code(&mut self) -> ActionIter<BufReader<Stdin>> {
let stdin = io::stdin();
let buffer = BufReader::new(stdin);
let term_code_iter = ActionIter::new(buffer);
2019-08-22 14:25:18 -04:00
/*
2019-08-22 16:44:47 -04:00
for term_code in self.read_term_code() {
let term_code = match term_code {
Ok(code) => code,
Err(e) => panic!("{:?}\r\n", e),
};
print!("{:?}\r\n", term_code);
}
*/
2019-08-22 16:44:47 -04:00
term_code_iter
}
}
2019-08-22 16:44:47 -04:00
// Input
impl Editor {
pub fn process_keypress(&mut self) -> Option<()> {
let chars= self.read_key();
2019-08-22 16:44:47 -04:00
// No input, just continue
if chars.is_none() {
return Some(())
2019-08-22 14:25:18 -04:00
}
let chars = chars.unwrap();
if chars.len() == 1 {
let char = chars[0];
if char == CTRL_KEY('q') {
// Break out of the input loop
return None;
}
// Echo characters
if char.is_ascii_control() {
print!("{}\r\n", char as u8);
} else {
print!("{} ('{}')\r\n", char as u8, char);
}
2019-08-22 16:44:47 -04:00
} else {
print!("{:?}\r\n", chars);
// Handle escape sequences
}
2019-08-22 16:44:47 -04:00
Some(())
2019-08-22 14:25:18 -04:00
}
}
const fn CTRL_KEY(c: char) -> char {
let key = c as u8;
(key & 0x1f) as char
}