Properly take in input and control characters

This commit is contained in:
Timothy Warren 2019-08-23 13:34:00 -04:00
parent 84e0cd89a8
commit f08f5f3cae
2 changed files with 62 additions and 23 deletions

View File

@ -5,32 +5,44 @@ use nix::sys::termios::Termios;
use nix::unistd::read;
use std::io;
use std::io::{BufReader, Error, Stdin};
use std::io::prelude::*;
use std::io::{BufReader, Error, Stdin};
use std::str::Chars;
use term_parser::{Action, ActionIter};
/// Main structure for the editor
pub struct Editor {
/// Reference to terminal settings before setting up raw mode
original_termios: Termios,
}
// init
impl Editor {
pub fn new() -> Self {
Editor {
original_termios: get_termios(STDIN_FILENO)
}
}
}
fn read_key(&mut self) -> char {
// Terminal
impl Editor {
fn read_key(&mut self) -> Option<Vec<char>> {
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 chars = in_str.chars();
chars.next().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)
}
fn read_term_code(&mut self) -> ActionIter<BufReader<Stdin>> {
@ -38,10 +50,7 @@ impl Editor {
let buffer = BufReader::new(stdin);
let term_code_iter = ActionIter::new(buffer);
term_code_iter
}
pub fn process_keypress(&mut self) -> Option<()> {
/*
for term_code in self.read_term_code() {
let term_code = match term_code {
Ok(code) => code,
@ -49,23 +58,49 @@ impl Editor {
};
print!("{:?}\r\n", term_code);
}
*/
/* let char = self.read_key();
term_code_iter
}
}
if char == 'q' {
disable_raw_mode(&self.original_termios)?;
// Input
impl Editor {
pub fn process_keypress(&mut self) -> Option<()> {
let chars= self.read_key();
// Break out of the input loop
return None;
// No input, just continue
if chars.is_none() {
return Some(())
}
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);
}
// Echo characters
if is_cntrl(char) {
print!("{}\r\n", char as u8);
} else {
print!("{} ('{}')\r\n", char as u8, char);
} */
print!("{:?}\r\n", chars);
// Handle escape sequences
}
Some(())
}
}
}
const fn CTRL_KEY(c: char) -> char {
let key = c as u8;
(key & 0x1f) as char
}

View File

@ -2,9 +2,11 @@ mod editor;
mod helpers;
use crate::editor::Editor;
use crate::helpers::{STDIN_FILENO, enable_raw_mode};
use crate::helpers::*;
fn main() {
let original_termios = get_termios(STDIN_FILENO);
enable_raw_mode().unwrap();
let mut editor = Editor::new();
@ -12,4 +14,6 @@ fn main() {
while editor.process_keypress().is_some() {
// loop
}
disable_raw_mode(&original_termios).unwrap();
}