Skip to content
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

Migrating to windows-sys #26

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
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
9 changes: 8 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,14 @@ readme = "README.md"
edition = "2018"

[target.'cfg(windows)'.dependencies]
winapi = { version = "0.3.8", features = ["winbase", "consoleapi", "processenv", "handleapi", "synchapi", "impl-default"] }
windows-sys = { version = "0.42.0", features = [
"Win32_Foundation",
"Win32_Security",
"Win32_System_Threading",
"Win32_System_Console",
"Win32_Storage_FileSystem",
"Win32_System_SystemServices",
] }

[package.metadata.docs.rs]
default-target = "x86_64-pc-windows-msvc"
24 changes: 12 additions & 12 deletions src/console.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,13 @@ use std::iter;
use std::slice;
use std::str;

use winapi::ctypes::c_void;
use winapi::shared::minwindef::DWORD;
use winapi::shared::ntdef::NULL;
use winapi::um::consoleapi::{GetNumberOfConsoleInputEvents, ReadConsoleInputW, WriteConsoleW};
use winapi::um::wincon::{
use std::ffi::c_void;
use windows_sys::Win32::System::Console::{
FillConsoleOutputAttribute, FillConsoleOutputCharacterA, GetLargestConsoleWindowSize,
SetConsoleTextAttribute, SetConsoleWindowInfo, COORD, INPUT_RECORD, SMALL_RECT,
GetNumberOfConsoleInputEvents, ReadConsoleInputW, SetConsoleTextAttribute,
SetConsoleWindowInfo, WriteConsoleW, COORD, INPUT_RECORD, SMALL_RECT,
};
const NULL: *mut c_void = 0 as *mut c_void;

use super::{result, Coord, Handle, HandleType, InputRecord, WindowPositions};

Expand Down Expand Up @@ -75,7 +74,7 @@ impl Console {
// fill the cells in console with blanks
FillConsoleOutputCharacterA(
*self.handle,
filling_char as i8,
filling_char as u8,
cells_to_write,
COORD::from(start_location),
&mut chars_written,
Expand Down Expand Up @@ -157,7 +156,7 @@ impl Console {
/// This wraps
/// [`ReadConsoleInputW`](https://docs.microsoft.com/en-us/windows/console/readconsoleinput).
pub fn read_single_input_event(&self) -> Result<InputRecord> {
let mut record: INPUT_RECORD = INPUT_RECORD::default();
let mut record: INPUT_RECORD = unsafe { ::std::mem::zeroed() };

{
// Convert an INPUT_RECORD to an &mut [INPUT_RECORD] of length 1
Expand All @@ -184,9 +183,10 @@ impl Console {
return Ok(vec![]);
}

let mut buf: Vec<INPUT_RECORD> = iter::repeat_with(INPUT_RECORD::default)
.take(buf_len as usize)
.collect();
let mut buf: Vec<INPUT_RECORD> =
iter::repeat_with(|| unsafe { ::std::mem::zeroed::<INPUT_RECORD>() })
.take(buf_len as usize)
.collect();

let num_read = self.read_input(buf.as_mut_slice())?;

Expand All @@ -202,7 +202,7 @@ impl Console {
/// This wraps
/// [`GetNumberOfConsoleInputEvents`](https://docs.microsoft.com/en-us/windows/console/getnumberofconsoleinputevents).
pub fn number_of_console_input_events(&self) -> Result<u32> {
let mut buf_len: DWORD = 0;
let mut buf_len = 0;
result(unsafe { GetNumberOfConsoleInputEvents(*self.handle, &mut buf_len) })?;
Ok(buf_len)
}
Expand Down
2 changes: 1 addition & 1 deletion src/console_mode.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::io::Result;

use winapi::um::consoleapi::{GetConsoleMode, SetConsoleMode};
use windows_sys::Win32::System::Console::{GetConsoleMode, SetConsoleMode};

use super::{result, Handle, HandleType};

Expand Down
2 changes: 1 addition & 1 deletion src/csbi.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::fmt;
use std::mem::zeroed;

use winapi::um::wincon::CONSOLE_SCREEN_BUFFER_INFO;
use windows_sys::Win32::System::Console::CONSOLE_SCREEN_BUFFER_INFO;

use super::{Coord, Size, WindowPositions};

Expand Down
34 changes: 14 additions & 20 deletions src/handle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,17 @@

use std::io::Result;
use std::ops::Deref;
use std::ptr::null_mut;
use std::ptr::{null, null_mut};
use std::sync::Arc;

use winapi::shared::minwindef::DWORD;
use winapi::um::{
fileapi::{CreateFileW, OPEN_EXISTING},
handleapi::{CloseHandle, INVALID_HANDLE_VALUE},
processenv::GetStdHandle,
winbase::{STD_INPUT_HANDLE, STD_OUTPUT_HANDLE},
winnt::{FILE_SHARE_READ, FILE_SHARE_WRITE, GENERIC_READ, GENERIC_WRITE, HANDLE},
use windows_sys::Win32::Foundation::{CloseHandle, HANDLE, INVALID_HANDLE_VALUE};
use windows_sys::Win32::Storage::FileSystem::{
CreateFileW, FILE_SHARE_READ, FILE_SHARE_WRITE, OPEN_EXISTING,
};
use windows_sys::Win32::System::Console::{
GetStdHandle, STD_HANDLE, STD_INPUT_HANDLE, STD_OUTPUT_HANDLE,
};
use windows_sys::Win32::System::SystemServices::{GENERIC_READ, GENERIC_WRITE};

use super::handle_result;

Expand Down Expand Up @@ -114,18 +114,15 @@ impl Handle {
/// This wraps
/// [`CreateFileW`](https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilew).
pub fn current_out_handle() -> Result<Handle> {
let utf16: Vec<u16> = "CONOUT$\0".encode_utf16().collect();
let utf16_ptr: *const u16 = utf16.as_ptr();

let handle = handle_result(unsafe {
CreateFileW(
utf16_ptr,
::windows_sys::w!("CONOUT$"),
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
null_mut(),
null(),
OPEN_EXISTING,
0,
null_mut(),
0,
)
})?;

Expand All @@ -141,18 +138,15 @@ impl Handle {
/// This wraps
/// [`CreateFileW`](https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilew).
pub fn current_in_handle() -> Result<Handle> {
let utf16: Vec<u16> = "CONIN$\0".encode_utf16().collect();
let utf16_ptr: *const u16 = utf16.as_ptr();

let handle = handle_result(unsafe {
CreateFileW(
utf16_ptr,
::windows_sys::w!("CONIN$"),
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
null_mut(),
OPEN_EXISTING,
0,
null_mut(),
0,
)
})?;

Expand Down Expand Up @@ -181,7 +175,7 @@ impl Handle {
Self::std_handle(STD_INPUT_HANDLE)
}

fn std_handle(which_std: DWORD) -> Result<Handle> {
fn std_handle(which_std: STD_HANDLE) -> Result<Handle> {
let handle = handle_result(unsafe { GetStdHandle(which_std) })?;

Ok(Handle {
Expand Down
8 changes: 3 additions & 5 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,8 @@

use std::io;

use winapi::shared::minwindef::BOOL;
use winapi::um::handleapi::INVALID_HANDLE_VALUE;
use winapi::um::wincontypes::COORD;
use winapi::um::winnt::HANDLE;
use windows_sys::Win32::Foundation::{BOOL, HANDLE, INVALID_HANDLE_VALUE};
use windows_sys::Win32::System::Console::COORD;

pub use self::{
console::Console,
Expand Down Expand Up @@ -63,7 +61,7 @@ pub fn handle_result(return_value: HANDLE) -> io::Result<HANDLE> {
/// Get the result of a call to WinAPI that returns a handle or `NULL`.
#[inline]
pub fn nonnull_handle_result(return_value: HANDLE) -> io::Result<HANDLE> {
if return_value.is_null() {
if return_value == 0 {
Err(io::Error::last_os_error())
} else {
Ok(return_value)
Expand Down
24 changes: 10 additions & 14 deletions src/screen_buffer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,14 @@
use std::io::Result;
use std::mem::size_of;

use winapi::{
shared::minwindef::TRUE,
shared::ntdef::NULL,
um::{
minwinbase::SECURITY_ATTRIBUTES,
wincon::{
CreateConsoleScreenBuffer, GetConsoleScreenBufferInfo, SetConsoleActiveScreenBuffer,
SetConsoleScreenBufferSize, CONSOLE_TEXTMODE_BUFFER, COORD,
},
winnt::{FILE_SHARE_READ, FILE_SHARE_WRITE, GENERIC_READ, GENERIC_WRITE},
},
use windows_sys::Win32::Security::SECURITY_ATTRIBUTES;
use windows_sys::Win32::Storage::FileSystem::{FILE_SHARE_READ, FILE_SHARE_WRITE};
use windows_sys::Win32::System::Console::{
CreateConsoleScreenBuffer, GetConsoleScreenBufferInfo, SetConsoleActiveScreenBuffer,
SetConsoleScreenBufferSize, CONSOLE_TEXTMODE_BUFFER, COORD,
};
use windows_sys::Win32::System::SystemServices::{GENERIC_READ, GENERIC_WRITE};
pub const TRUE: ::windows_sys::Win32::Foundation::BOOL = 1;

use super::{handle_result, result, Handle, HandleType, ScreenBufferInfo};

Expand Down Expand Up @@ -44,7 +40,7 @@ impl ScreenBuffer {
pub fn create() -> Result<ScreenBuffer> {
let security_attr: SECURITY_ATTRIBUTES = SECURITY_ATTRIBUTES {
nLength: size_of::<SECURITY_ATTRIBUTES>() as u32,
lpSecurityDescriptor: NULL,
lpSecurityDescriptor: ::std::ptr::null_mut(),
bInheritHandle: TRUE,
};

Expand All @@ -55,8 +51,8 @@ impl ScreenBuffer {
FILE_SHARE_READ | FILE_SHARE_WRITE, // shared
&security_attr, // default security attributes
CONSOLE_TEXTMODE_BUFFER, // must be TEXTMODE
NULL,
)
::std::ptr::null_mut(),
) as _
})?;
Ok(ScreenBuffer {
handle: unsafe { Handle::from_raw(new_screen_buffer) },
Expand Down
7 changes: 3 additions & 4 deletions src/semaphore.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::{io, ptr};

use winapi::um::synchapi::{CreateSemaphoreW, ReleaseSemaphore};
use windows_sys::Win32::System::Threading::{CreateSemaphoreW, ReleaseSemaphore};

use crate::{nonnull_handle_result, result, Handle};

Expand All @@ -14,9 +14,8 @@ impl Semaphore {
/// This wraps
/// [`CreateSemaphoreW`](https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-createsemaphorew).
pub fn new() -> io::Result<Self> {
let handle = nonnull_handle_result(unsafe {
CreateSemaphoreW(ptr::null_mut(), 0, 1, ptr::null_mut())
})?;
let handle =
nonnull_handle_result(unsafe { CreateSemaphoreW(ptr::null(), 0, 1, ptr::null()) })?;

let handle = unsafe { Handle::from_raw(handle) };
Ok(Self(handle))
Expand Down
2 changes: 1 addition & 1 deletion src/structs/coord.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
//! For example, in WinAPI we have `COORD` which looks and feels inconvenient.
//! This module provides also some trait implementations who will make parsing and working with `COORD` easier.

use winapi::um::wincon::COORD;
use windows_sys::Win32::System::Console::COORD;

/// This is type represents the position of something on a certain 'x' and 'y'.
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, PartialOrd)]
Expand Down
25 changes: 12 additions & 13 deletions src/structs/input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,7 @@
//! - `InputEventType`
//! - `INPUT_RECORD`

use winapi::shared::minwindef::DWORD;
use winapi::um::wincon::{
use windows_sys::Win32::System::Console::{
FOCUS_EVENT, FOCUS_EVENT_RECORD, FROM_LEFT_1ST_BUTTON_PRESSED, FROM_LEFT_2ND_BUTTON_PRESSED,
FROM_LEFT_3RD_BUTTON_PRESSED, FROM_LEFT_4TH_BUTTON_PRESSED, INPUT_RECORD, KEY_EVENT,
KEY_EVENT_RECORD, MENU_EVENT, MENU_EVENT_RECORD, MOUSE_EVENT, MOUSE_EVENT_RECORD,
Expand Down Expand Up @@ -55,7 +54,7 @@ impl KeyEventRecord {
repeat_count: record.wRepeatCount,
virtual_key_code: record.wVirtualKeyCode,
virtual_scan_code: record.wVirtualScanCode,
u_char: unsafe { *record.uChar.UnicodeChar() },
u_char: unsafe { record.uChar.UnicodeChar },
control_key_state: ControlKeyState(record.dwControlKeyState),
}
}
Expand Down Expand Up @@ -121,9 +120,9 @@ pub struct ButtonState {
state: i32,
}

impl From<DWORD> for ButtonState {
impl From<u32> for ButtonState {
#[inline]
fn from(event: DWORD) -> Self {
fn from(event: u32) -> Self {
let state = event as i32;
ButtonState { state }
}
Expand Down Expand Up @@ -218,8 +217,8 @@ pub enum EventFlags {
}

// TODO: Replace with TryFrom.
impl From<DWORD> for EventFlags {
fn from(event: DWORD) -> Self {
impl From<u32> for EventFlags {
fn from(event: u32) -> Self {
match event {
0x0000 => EventFlags::PressOrRelease,
0x0002 => EventFlags::DoubleClick,
Expand Down Expand Up @@ -303,14 +302,14 @@ pub enum InputRecord {
impl From<INPUT_RECORD> for InputRecord {
#[inline]
fn from(record: INPUT_RECORD) -> Self {
match record.EventType {
match record.EventType as u32 {
KEY_EVENT => InputRecord::KeyEvent(KeyEventRecord::from_winapi(unsafe {
record.Event.KeyEvent()
&record.Event.KeyEvent
})),
MOUSE_EVENT => InputRecord::MouseEvent(unsafe { *record.Event.MouseEvent() }.into()),
MOUSE_EVENT => InputRecord::MouseEvent(unsafe { record.Event.MouseEvent }.into()),
WINDOW_BUFFER_SIZE_EVENT => InputRecord::WindowBufferSizeEvent({
let mut buffer =
unsafe { WindowBufferSizeRecord::from(*record.Event.WindowBufferSizeEvent()) };
unsafe { WindowBufferSizeRecord::from(record.Event.WindowBufferSizeEvent) };
let window = ScreenBuffer::current().unwrap().info().unwrap();
let screen_size = window.terminal_size();

Expand All @@ -319,8 +318,8 @@ impl From<INPUT_RECORD> for InputRecord {

buffer
}),
FOCUS_EVENT => InputRecord::FocusEvent(unsafe { *record.Event.FocusEvent() }.into()),
MENU_EVENT => InputRecord::MenuEvent(unsafe { *record.Event.MenuEvent() }.into()),
FOCUS_EVENT => InputRecord::FocusEvent(unsafe { record.Event.FocusEvent }.into()),
MENU_EVENT => InputRecord::MenuEvent(unsafe { record.Event.MenuEvent }.into()),
code => panic!("Unexpected INPUT_RECORD EventType: {}", code),
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/structs/size.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
//! For example, in WinAPI we have `COORD` to represent screen/buffer size but this is a little inconvenient.
//! This module provides some trait implementations who will make parsing and working with `COORD` easier.

use winapi::um::wincon::COORD;
use windows_sys::Win32::System::Console::COORD;

/// This is type represents the size of something in width and height.
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
Expand Down
2 changes: 1 addition & 1 deletion src/structs/window_coords.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
//! For example, in WinAPI we have `SMALL_RECT` to represent a window size but this is a little inconvenient.
//! This module provides some trait implementations who will make parsing and working with `SMALL_RECT` easier.

use winapi::um::wincon::{CONSOLE_SCREEN_BUFFER_INFO, SMALL_RECT};
use windows_sys::Win32::System::Console::{CONSOLE_SCREEN_BUFFER_INFO, SMALL_RECT};

/// This is a wrapper for the locations of a rectangle.
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
Expand Down