Skip to content

windows: improve/fix raw mode #815

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 22 additions & 14 deletions src/terminal/sys/windows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,36 +4,44 @@ use std::fmt::{self, Write};
use std::io::{self};

use crossterm_winapi::{Console, ConsoleMode, Coord, Handle, ScreenBuffer, Size};
use winapi::{
shared::minwindef::DWORD,
um::wincon::{SetConsoleTitleW, ENABLE_ECHO_INPUT, ENABLE_LINE_INPUT, ENABLE_PROCESSED_INPUT},
use winapi::shared::minwindef::DWORD;
use winapi::um::wincon::{
SetConsoleTitleW, ENABLE_ECHO_INPUT, ENABLE_EXTENDED_FLAGS, ENABLE_INSERT_MODE,
ENABLE_LINE_INPUT, ENABLE_MOUSE_INPUT, ENABLE_PROCESSED_INPUT, ENABLE_QUICK_EDIT_MODE,
ENABLE_VIRTUAL_TERMINAL_INPUT, ENABLE_WINDOW_INPUT,
};

use crate::{
cursor,
terminal::{ClearType, WindowSize},
};
use crate::cursor;
use crate::terminal::{ClearType, WindowSize};

/// bits which must be set in raw mode
const RAW_MODE_MASK: DWORD = ENABLE_EXTENDED_FLAGS
| ENABLE_INSERT_MODE
| ENABLE_QUICK_EDIT_MODE
| ENABLE_VIRTUAL_TERMINAL_INPUT;

/// bits which can't be set in raw mode
const NOT_RAW_MODE_MASK: DWORD = ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT | ENABLE_PROCESSED_INPUT;
const NOT_RAW_MODE_MASK: DWORD = ENABLE_LINE_INPUT
| ENABLE_ECHO_INPUT
| ENABLE_MOUSE_INPUT
| ENABLE_WINDOW_INPUT
| ENABLE_PROCESSED_INPUT;

pub(crate) fn is_raw_mode_enabled() -> std::io::Result<bool> {
let console_mode = ConsoleMode::from(Handle::current_in_handle()?);

let dw_mode = console_mode.mode()?;

Ok(
// check none of the "not raw" bits is set
dw_mode & NOT_RAW_MODE_MASK == 0,
)
// check none of the "not raw" and all of the "raw" bits are set
Ok(dw_mode & NOT_RAW_MODE_MASK == 0 && dw_mode & RAW_MODE_MASK == RAW_MODE_MASK)
}

pub(crate) fn enable_raw_mode() -> std::io::Result<()> {
let console_mode = ConsoleMode::from(Handle::current_in_handle()?);

let dw_mode = console_mode.mode()?;

let new_mode = dw_mode & !NOT_RAW_MODE_MASK;
let new_mode = dw_mode & !NOT_RAW_MODE_MASK | RAW_MODE_MASK;

console_mode.set_mode(new_mode)?;

Expand All @@ -45,7 +53,7 @@ pub(crate) fn disable_raw_mode() -> std::io::Result<()> {

let dw_mode = console_mode.mode()?;

let new_mode = dw_mode | NOT_RAW_MODE_MASK;
let new_mode = dw_mode & !RAW_MODE_MASK | NOT_RAW_MODE_MASK;

console_mode.set_mode(new_mode)?;

Expand Down