rustfmt pass

This commit is contained in:
Daniel Collin 2019-11-27 08:03:33 +01:00
parent 38fa50a4ef
commit 8de9567541
18 changed files with 1356 additions and 1187 deletions

View file

@ -1,7 +1,7 @@
extern crate minifb; extern crate minifb;
use minifb::{InputCallback, Window, Key, Scale, WindowOptions, Menu}; use minifb::MENU_KEY_CTRL;
use minifb::{MENU_KEY_CTRL}; use minifb::{InputCallback, Key, Menu, Scale, Window, WindowOptions};
const WIDTH: usize = 640; const WIDTH: usize = 640;
const HEIGHT: usize = 360; const HEIGHT: usize = 360;
@ -24,14 +24,16 @@ impl InputCallback for KeyCharCallback {
fn main() { fn main() {
let mut buffer: Vec<u32> = vec![0; WIDTH * HEIGHT]; let mut buffer: Vec<u32> = vec![0; WIDTH * HEIGHT];
let mut window = Window::new("Menu Test - Press ESC to exit", let mut window = Window::new(
"Menu Test - Press ESC to exit",
WIDTH, WIDTH,
HEIGHT, HEIGHT,
WindowOptions { WindowOptions {
resize: true, resize: true,
scale: Scale::X2, scale: Scale::X2,
..WindowOptions::default() ..WindowOptions::default()
}) },
)
.expect("Unable to Open Window"); .expect("Unable to Open Window");
window.set_input_callback(Box::new(KeyCharCallback {})); window.set_input_callback(Box::new(KeyCharCallback {}));
@ -39,16 +41,28 @@ fn main() {
let mut menu = Menu::new("Test").unwrap(); let mut menu = Menu::new("Test").unwrap();
let mut sub = Menu::new("Select Color").unwrap(); let mut sub = Menu::new("Select Color").unwrap();
sub.add_item("Color 0", COLOR_0_ID).shortcut(Key::F1, 0).build(); sub.add_item("Color 0", COLOR_0_ID)
sub.add_item("Color 1", COLOR_1_ID).shortcut(Key::F2, 0).build(); .shortcut(Key::F1, 0)
sub.add_item("Color 2", COLOR_2_ID).shortcut(Key::F7, 0).build(); .build();
sub.add_item("Color 1", COLOR_1_ID)
.shortcut(Key::F2, 0)
.build();
sub.add_item("Color 2", COLOR_2_ID)
.shortcut(Key::F7, 0)
.build();
menu.add_item("Menu Test", MENU_TEST_ID).shortcut(Key::W, MENU_KEY_CTRL).build(); menu.add_item("Menu Test", MENU_TEST_ID)
.shortcut(Key::W, MENU_KEY_CTRL)
.build();
menu.add_separator(); menu.add_separator();
menu.add_item("Other Menu", OTHER_MENU_ID).shortcut(Key::W, MENU_KEY_CTRL).build(); menu.add_item("Other Menu", OTHER_MENU_ID)
menu.add_item("Remove Menu", CLOSE_MENU_ID).shortcut(Key::R, 0).build(); .shortcut(Key::W, MENU_KEY_CTRL)
.build();
menu.add_item("Remove Menu", CLOSE_MENU_ID)
.shortcut(Key::R, 0)
.build();
menu.add_sub_menu("Sub Test", &sub); menu.add_sub_menu("Sub Test", &sub);

View file

@ -1,6 +1,6 @@
extern crate minifb; extern crate minifb;
use minifb::{MouseButton, MouseMode, Window, Key, Scale, WindowOptions}; use minifb::{Key, MouseButton, MouseMode, Scale, Window, WindowOptions};
const WIDTH: usize = 640; const WIDTH: usize = 640;
const HEIGHT: usize = 360; const HEIGHT: usize = 360;
@ -8,12 +8,16 @@ const HEIGHT: usize = 360;
fn main() { fn main() {
let mut buffer: Vec<u32> = vec![0; WIDTH * HEIGHT]; let mut buffer: Vec<u32> = vec![0; WIDTH * HEIGHT];
let mut window = match Window::new("Mouse Draw - Press ESC to exit", WIDTH, HEIGHT, let mut window = match Window::new(
"Mouse Draw - Press ESC to exit",
WIDTH,
HEIGHT,
WindowOptions { WindowOptions {
resize: true, resize: true,
scale: Scale::X2, scale: Scale::X2,
..WindowOptions::default() ..WindowOptions::default()
}) { },
) {
Ok(win) => win, Ok(win) => win,
Err(err) => { Err(err) => {
println!("Unable to create window {}", err); println!("Unable to create window {}", err);
@ -27,7 +31,6 @@ fn main() {
{ {
let (new_width, new_height) = window.get_size(); let (new_width, new_height) = window.get_size();
if new_width != width || new_height != height { if new_width != width || new_height != height {
// copy valid bits of old buffer to new buffer // copy valid bits of old buffer to new buffer
let mut new_buffer = vec![0; new_width * new_height / 2 / 2]; let mut new_buffer = vec![0; new_width * new_height / 2 / 2];
for y in 0..(height / 2).min(new_height / 2) { for y in 0..(height / 2).min(new_height / 2) {
@ -38,13 +41,15 @@ fn main() {
buffer = new_buffer; buffer = new_buffer;
width = new_width; width = new_width;
height = new_height; height = new_height;
} }
} }
window.get_mouse_pos(MouseMode::Discard).map(|(x, y)| { window.get_mouse_pos(MouseMode::Discard).map(|(x, y)| {
let screen_pos = ((y as usize) * width / 2) + x as usize; let screen_pos = ((y as usize) * width / 2) + x as usize;
println!("{:?}", window.get_unscaled_mouse_pos(MouseMode::Discard).unwrap()); println!(
"{:?}",
window.get_unscaled_mouse_pos(MouseMode::Discard).unwrap()
);
if window.get_mouse_down(MouseButton::Left) { if window.get_mouse_down(MouseButton::Left) {
buffer[screen_pos] = 0x00ffffff; buffer[screen_pos] = 0x00ffffff;

View file

@ -1,26 +1,39 @@
extern crate minifb; extern crate minifb;
use minifb::{WindowOptions, Window, Scale, Key}; use minifb::{Key, Scale, Window, WindowOptions};
fn main() { fn main() {
let width = 640; let width = 640;
let height = 320; let height = 320;
let mut buffer = vec![0u32; width * height]; let mut buffer = vec![0u32; width * height];
let mut double = Window::new("Larger", width, height, WindowOptions { let mut double = Window::new(
"Larger",
width,
height,
WindowOptions {
scale: Scale::X2, scale: Scale::X2,
..WindowOptions::default() ..WindowOptions::default()
}).unwrap(); },
)
.unwrap();
let mut orig = Window::new("Smaller", width, height, WindowOptions { let mut orig = Window::new(
"Smaller",
width,
height,
WindowOptions {
..WindowOptions::default() ..WindowOptions::default()
}).unwrap(); },
)
.unwrap();
let mut pos = 13; let mut pos = 13;
while orig.is_open() && double.is_open() while orig.is_open()
&& double.is_open()
&& !orig.is_key_down(Key::Escape) && !orig.is_key_down(Key::Escape)
&& !double.is_key_down(Key::Escape) { && !double.is_key_down(Key::Escape)
{
orig.update_with_buffer(&buffer).unwrap(); orig.update_with_buffer(&buffer).unwrap();
double.update_with_buffer(&buffer).unwrap(); double.update_with_buffer(&buffer).unwrap();
pos += 7; pos += 7;

View file

@ -1,6 +1,6 @@
extern crate minifb; extern crate minifb;
use minifb::{Window, Key, Scale, WindowOptions}; use minifb::{Key, Scale, Window, WindowOptions};
const WIDTH: usize = 640; const WIDTH: usize = 640;
const HEIGHT: usize = 360; const HEIGHT: usize = 360;
@ -10,13 +10,16 @@ fn main() {
let mut carry; let mut carry;
let mut seed = 0xbeefu32; let mut seed = 0xbeefu32;
let mut window = match Window::new(
let mut window = match Window::new("Noise Test - Press ESC to exit", WIDTH, HEIGHT, "Noise Test - Press ESC to exit",
WIDTH,
HEIGHT,
WindowOptions { WindowOptions {
resize: true, resize: true,
scale: Scale::X2, scale: Scale::X2,
..WindowOptions::default() ..WindowOptions::default()
}) { },
) {
Ok(win) => win, Ok(win) => win,
Err(err) => { Err(err) => {
println!("Unable to create window {}", err); println!("Unable to create window {}", err);

View file

@ -1,6 +1,6 @@
extern crate minifb; extern crate minifb;
use minifb::{CursorStyle, Window, Key, Scale, WindowOptions, MouseMode}; use minifb::{CursorStyle, Key, MouseMode, Scale, Window, WindowOptions};
const WIDTH: usize = 640; const WIDTH: usize = 640;
const HEIGHT: usize = 360; const HEIGHT: usize = 360;
@ -21,8 +21,7 @@ impl Rect {
let xe = self.x + self.width; let xe = self.x + self.width;
let ye = self.y + self.height; let ye = self.y + self.height;
if (y >= self.y) && (y <= ye) && if (y >= self.y) && (y <= ye) && (x >= self.x) && (x <= xe) {
(x >= self.x) && (x <= xe) {
true true
} else { } else {
false false
@ -41,23 +40,81 @@ fn fill_rect(dest: &mut [u32], rect: &Rect) {
fn main() { fn main() {
let mut buffer: Vec<u32> = vec![0; WIDTH * HEIGHT]; let mut buffer: Vec<u32> = vec![0; WIDTH * HEIGHT];
let mut window = Window::new("I haz no title :(", let mut window = Window::new(
"I haz no title :(",
WIDTH, WIDTH,
HEIGHT, HEIGHT,
WindowOptions { WindowOptions {
scale: Scale::X2, scale: Scale::X2,
..WindowOptions::default() ..WindowOptions::default()
}) },
)
.expect("Unable to Open Window"); .expect("Unable to Open Window");
let rects = [ let rects = [
Rect { x: 0, y: 0, width: 160, height: 180, color: 0x00b27474, cursor_style: CursorStyle::Arrow }, Rect {
Rect { x: 160, y: 0, width: 160, height: 180, color: 0x00b28050, cursor_style: CursorStyle::Ibeam }, x: 0,
Rect { x: 320, y: 0, width: 160, height: 180, color: 0x00a9b250, cursor_style: CursorStyle::Crosshair }, y: 0,
Rect { x: 480, y: 0, width: 160, height: 180, color: 0x0060b250, cursor_style: CursorStyle::ClosedHand }, width: 160,
Rect { x: 0, y: 180, width: 160, height: 180, color: 0x004fb292, cursor_style: CursorStyle::OpenHand }, height: 180,
Rect { x: 160, y: 180, width: 160, height: 180, color: 0x004f71b2, cursor_style: CursorStyle::ResizeLeftRight }, color: 0x00b27474,
Rect { x: 320, y: 180, width: 160, height: 180, color: 0x008850b2, cursor_style: CursorStyle::ResizeUpDown }, cursor_style: CursorStyle::Arrow,
Rect { x: 480, y: 180, width: 160, height: 180, color: 0x00b25091, cursor_style: CursorStyle::ResizeAll } },
Rect {
x: 160,
y: 0,
width: 160,
height: 180,
color: 0x00b28050,
cursor_style: CursorStyle::Ibeam,
},
Rect {
x: 320,
y: 0,
width: 160,
height: 180,
color: 0x00a9b250,
cursor_style: CursorStyle::Crosshair,
},
Rect {
x: 480,
y: 0,
width: 160,
height: 180,
color: 0x0060b250,
cursor_style: CursorStyle::ClosedHand,
},
Rect {
x: 0,
y: 180,
width: 160,
height: 180,
color: 0x004fb292,
cursor_style: CursorStyle::OpenHand,
},
Rect {
x: 160,
y: 180,
width: 160,
height: 180,
color: 0x004f71b2,
cursor_style: CursorStyle::ResizeLeftRight,
},
Rect {
x: 320,
y: 180,
width: 160,
height: 180,
color: 0x008850b2,
cursor_style: CursorStyle::ResizeUpDown,
},
Rect {
x: 480,
y: 180,
width: 160,
height: 180,
color: 0x00b25091,
cursor_style: CursorStyle::ResizeAll,
},
]; ];
window.set_title("Different cursor on each color region"); window.set_title("Different cursor on each color region");
@ -76,4 +133,3 @@ fn main() {
window.update_with_buffer(&buffer).unwrap(); window.update_with_buffer(&buffer).unwrap();
} }
} }

View file

@ -1,7 +1,12 @@
use error::Error; use error::Error;
use Result; use Result;
pub fn check_buffer_size(window_width: usize, window_height: usize, scale: usize, buffer: &[u32]) -> Result<()> { pub fn check_buffer_size(
window_width: usize,
window_height: usize,
scale: usize,
buffer: &[u32],
) -> Result<()> {
let buffer_size = buffer.len() * 4; // len is the number of entries so * 4 as we want bytes let buffer_size = buffer.len() * 4; // len is the number of entries so * 4 as we want bytes
let required_buffer_size = (window_width / scale) * (window_height / scale) * 4; // * 4 for 32-bit buffer let required_buffer_size = (window_width / scale) * (window_height / scale) * 4; // * 4 for 32-bit buffer

View file

@ -38,18 +38,10 @@ impl StdError for Error {
impl fmt::Display for Error { impl fmt::Display for Error {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match *self { match *self {
Error::MenusNotSupported => { Error::MenusNotSupported => write!(fmt, "{}", self.description()),
write!(fmt, "{}", self.description()) Error::MenuExists(ref e) => write!(fmt, "{} {:?}", self.description(), e),
}, Error::WindowCreate(ref e) => write!(fmt, "{} {:?}", self.description(), e),
Error::MenuExists(ref e) => { Error::UpdateFailed(ref e) => write!(fmt, "{} {:?}", self.description(), e),
write!(fmt, "{} {:?}", self.description(), e)
},
Error::WindowCreate(ref e) => {
write!(fmt, "{} {:?}", self.description(), e)
}
Error::UpdateFailed(ref e) => {
write!(fmt, "{} {:?}", self.description(), e)
}
} }
} }
} }

View file

@ -125,4 +125,3 @@ pub enum Key {
Count = 107, Count = 107,
} }

View file

@ -1,7 +1,7 @@
extern crate time; extern crate time;
use std::mem; use std::mem;
use {Key, KeyRepeat, InputCallback}; use {InputCallback, Key, KeyRepeat};
pub struct KeyHandler { pub struct KeyHandler {
pub key_callback: Option<Box<dyn InputCallback>>, pub key_callback: Option<Box<dyn InputCallback>>,
@ -118,7 +118,9 @@ impl KeyHandler {
if repeat == KeyRepeat::Yes && t > self.key_repeat_delay { if repeat == KeyRepeat::Yes && t > self.key_repeat_delay {
let delay = self.key_repeat_delay; let delay = self.key_repeat_delay;
let rate = self.key_repeat_rate; let rate = self.key_repeat_rate;
if (((t - delay) % rate) > rate * 0.5) != (((t - delay - self.delta_time) % rate) > rate * 0.5) { if (((t - delay) % rate) > rate * 0.5)
!= (((t - delay - self.delta_time) % rate) > rate * 0.5)
{
return true; return true;
} }
} }

View file

@ -50,7 +50,6 @@ pub enum MouseButton {
Right, Right,
} }
/// The diffrent modes that can be used to decide how mouse coordinates should be handled /// The diffrent modes that can be used to decide how mouse coordinates should be handled
#[derive(PartialEq, Clone, Copy, Debug)] #[derive(PartialEq, Clone, Copy, Debug)]
pub enum MouseMode { pub enum MouseMode {
@ -94,11 +93,11 @@ pub use self::error::Error;
pub type Result<T> = std::result::Result<T, Error>; pub type Result<T> = std::result::Result<T, Error>;
mod key; mod key;
pub use key::Key as Key; pub use key::Key;
mod os;
mod mouse_handler;
mod buffer_helper; mod buffer_helper;
mod key_handler; mod key_handler;
mod mouse_handler;
mod os;
mod window_flags; mod window_flags;
//mod menu; //mod menu;
//pub use menu::Menu as Menu; //pub use menu::Menu as Menu;
@ -108,19 +107,20 @@ mod window_flags;
//pub use menu::MENU_KEY_CTRL; //pub use menu::MENU_KEY_CTRL;
//pub use menu::MENU_KEY_ALT; //pub use menu::MENU_KEY_ALT;
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
use self::os::macos as imp; use self::os::macos as imp;
#[cfg(target_os = "windows")] #[cfg(target_os = "redox")]
use self::os::windows as imp; use self::os::redox as imp;
#[cfg(any(target_os="linux", #[cfg(any(
target_os = "linux",
target_os = "freebsd", target_os = "freebsd",
target_os = "dragonfly", target_os = "dragonfly",
target_os = "netbsd", target_os = "netbsd",
target_os="openbsd"))] target_os = "openbsd"
))]
use self::os::unix as imp; use self::os::unix as imp;
#[cfg(target_os = "redox")] #[cfg(target_os = "windows")]
use self::os::redox as imp; use self::os::windows as imp;
/// ///
/// Window is used to open up a window. It's possible to optionally display a 32-bit buffer when /// Window is used to open up a window. It's possible to optionally display a 32-bit buffer when
/// the widow is set as non-resizable. /// the widow is set as non-resizable.
@ -129,9 +129,7 @@ pub struct Window(imp::Window);
impl fmt::Debug for Window { impl fmt::Debug for Window {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_tuple("Window") f.debug_tuple("Window").field(&format_args!("..")).finish()
.field(&format_args!(".."))
.finish()
} }
} }
@ -590,18 +588,19 @@ impl Window {
/// Get Unix menu. Will only return menus on Unix class OSes /// Get Unix menu. Will only return menus on Unix class OSes
/// otherwise ```None``` /// otherwise ```None```
/// ///
#[cfg(any(target_os="macos", #[cfg(any(target_os = "macos", target_os = "windows"))]
target_os="windows"))]
pub fn get_unix_menus(&self) -> Option<&Vec<UnixMenu>> { pub fn get_unix_menus(&self) -> Option<&Vec<UnixMenu>> {
None None
} }
#[cfg(any(target_os="linux", #[cfg(any(
target_os = "linux",
target_os = "freebsd", target_os = "freebsd",
target_os = "dragonfly", target_os = "dragonfly",
target_os = "netbsd", target_os = "netbsd",
target_os = "openbsd", target_os = "openbsd",
target_os="redox"))] target_os = "redox"
))]
pub fn get_unix_menus(&self) -> Option<&Vec<UnixMenu>> { pub fn get_unix_menus(&self) -> Option<&Vec<UnixMenu>> {
self.0.get_unix_menus() self.0.get_unix_menus()
} }
@ -615,7 +614,6 @@ impl Window {
} }
} }
/// Command key on Mac OS /// Command key on Mac OS
pub const MENU_KEY_COMMAND: usize = 1; pub const MENU_KEY_COMMAND: usize = 1;
/// Windows key on Windows /// Windows key on Windows
@ -675,7 +673,6 @@ pub struct MenuItemHandle(pub u64);
#[doc(hidden)] #[doc(hidden)]
pub struct MenuHandle(pub u64); pub struct MenuHandle(pub u64);
/// ///
/// Menu holds info for menus /// Menu holds info for menus
/// ///
@ -683,9 +680,7 @@ pub struct Menu(imp::Menu);
impl fmt::Debug for Menu { impl fmt::Debug for Menu {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_tuple("Menu") f.debug_tuple("Menu").field(&format_args!("..")).finish()
.field(&format_args!(".."))
.finish()
} }
} }
@ -709,7 +704,10 @@ impl Menu {
/// Adds a menu separator /// Adds a menu separator
pub fn add_separator(&mut self) { pub fn add_separator(&mut self) {
self.add_menu_item(&MenuItem { id: MENU_ID_SEPARATOR, ..MenuItem::default() }); self.add_menu_item(&MenuItem {
id: MENU_ID_SEPARATOR,
..MenuItem::default()
});
} }
#[inline] #[inline]

View file

@ -4,7 +4,14 @@ fn clamp(v: f32, lb: f32, ub: f32) -> f32 {
f32::min(f32::max(v, lb), ub) f32::min(f32::max(v, lb), ub)
} }
pub fn get_pos(mode: MouseMode, mx: f32, my: f32, scale: f32, width: f32, height: f32) -> Option<(f32, f32)> { pub fn get_pos(
mode: MouseMode,
mx: f32,
my: f32,
scale: f32,
width: f32,
height: f32,
) -> Option<(f32, f32)> {
let s = 1.0 / scale as f32; let s = 1.0 / scale as f32;
let x = mx * s; let x = mx * s;
let y = my * s; let y = my * s;
@ -13,17 +20,16 @@ pub fn get_pos(mode: MouseMode, mx: f32, my: f32, scale: f32, width: f32, height
match mode { match mode {
MouseMode::Pass => Some((x, y)), MouseMode::Pass => Some((x, y)),
MouseMode::Clamp => { MouseMode::Clamp => Some((
Some((clamp(x, 0.0, window_width - 1.0), clamp(x, 0.0, window_width - 1.0),
clamp(y, 0.0, window_height - 1.0))) clamp(y, 0.0, window_height - 1.0),
}, )),
MouseMode::Discard => { MouseMode::Discard => {
if x < 0.0 || y < 0.0 || x >= window_width || y >= window_height { if x < 0.0 || y < 0.0 || x >= window_width || y >= window_height {
None None
} else { } else {
Some((x, y)) Some((x, y))
} }
},
} }
} }
}

View file

@ -1,22 +1,22 @@
#![cfg(target_os = "macos")] #![cfg(target_os = "macos")]
use {MouseButton, MouseMode, Scale, Key, KeyRepeat, WindowOptions};
use key_handler::KeyHandler;
use error::Error; use error::Error;
use key_handler::KeyHandler;
use Result; use Result;
use {Key, KeyRepeat, MouseButton, MouseMode, Scale, WindowOptions};
// use MenuItem; // use MenuItem;
use InputCallback;
use mouse_handler;
use buffer_helper; use buffer_helper;
use mouse_handler;
use window_flags; use window_flags;
use {CursorStyle, MenuItem, MenuItemHandle, MenuHandle}; use InputCallback;
use {CursorStyle, MenuHandle, MenuItem, MenuItemHandle};
// use menu::Menu; // use menu::Menu;
use std::os::raw::{c_void, c_char, c_uchar};
use std::ffi::CString; use std::ffi::CString;
use std::ptr;
use std::mem; use std::mem;
use std::os::raw; use std::os::raw;
use std::os::raw::{c_char, c_uchar, c_void};
use std::ptr;
// Table taken from GLFW and slightly modified // Table taken from GLFW and slightly modified
@ -154,21 +154,24 @@ static KEY_MAPPINGS: [Key; 128] = [
#[link(name = "Cocoa", kind = "framework")] #[link(name = "Cocoa", kind = "framework")]
#[link(name = "Carbon", kind = "framework")] #[link(name = "Carbon", kind = "framework")]
extern "C" { extern "C" {
fn mfb_open(name: *const c_char, fn mfb_open(
name: *const c_char,
width: u32, width: u32,
height: u32, height: u32,
flags: u32, flags: u32,
scale: i32) scale: i32,
-> *mut c_void; ) -> *mut c_void;
fn mfb_set_title(window: *mut c_void, title: *const c_char); fn mfb_set_title(window: *mut c_void, title: *const c_char);
fn mfb_close(window: *mut c_void); fn mfb_close(window: *mut c_void);
fn mfb_update(window: *mut c_void); fn mfb_update(window: *mut c_void);
fn mfb_update_with_buffer(window: *mut c_void, buffer: *const c_uchar); fn mfb_update_with_buffer(window: *mut c_void, buffer: *const c_uchar);
fn mfb_set_position(window: *mut c_void, x: i32, y: i32); fn mfb_set_position(window: *mut c_void, x: i32, y: i32);
fn mfb_set_key_callback(window: *mut c_void, fn mfb_set_key_callback(
window: *mut c_void,
target: *mut c_void, target: *mut c_void,
cb: unsafe extern "C" fn(*mut c_void, i32, i32), cb: unsafe extern "C" fn(*mut c_void, i32, i32),
cb: unsafe extern "C" fn(*mut c_void, u32)); cb: unsafe extern "C" fn(*mut c_void, u32),
);
fn mfb_set_mouse_data(window_handle: *mut c_void, shared_data: *mut SharedData); fn mfb_set_mouse_data(window_handle: *mut c_void, shared_data: *mut SharedData);
fn mfb_set_cursor_style(window: *mut c_void, cursor: u32); fn mfb_set_cursor_style(window: *mut c_void, cursor: u32);
fn mfb_should_close(window: *mut c_void) -> i32; fn mfb_should_close(window: *mut c_void) -> i32;
@ -181,13 +184,14 @@ extern "C" {
fn mfb_create_menu(name: *const c_char) -> *mut c_void; fn mfb_create_menu(name: *const c_char) -> *mut c_void;
fn mfb_remove_menu_at(window: *mut c_void, index: i32); fn mfb_remove_menu_at(window: *mut c_void, index: i32);
fn mfb_add_menu_item(menu_item: *mut c_void, fn mfb_add_menu_item(
menu_item: *mut c_void,
menu_id: i32, menu_id: i32,
name: *const c_char, name: *const c_char,
enabled: bool, enabled: bool,
key: u32, key: u32,
modifier: u32) modifier: u32,
-> u64; ) -> u64;
fn mfb_remove_menu_item(menu: *mut c_void, item_handle: u64); fn mfb_remove_menu_item(menu: *mut c_void, item_handle: u64);
} }
@ -220,7 +224,9 @@ unsafe extern "C" fn key_callback(window: *mut c_void, key: i32, state: i32) {
if key > 128 { if key > 128 {
(*win).key_handler.set_key_state(Key::Unknown, s); (*win).key_handler.set_key_state(Key::Unknown, s);
} else { } else {
(*win).key_handler.set_key_state(KEY_MAPPINGS[key as usize], s); (*win)
.key_handler
.set_key_state(KEY_MAPPINGS[key as usize], s);
} }
} }
@ -249,11 +255,13 @@ impl Window {
unsafe { unsafe {
let scale_factor = Self::get_scale_factor(width, height, opts.scale) as usize; let scale_factor = Self::get_scale_factor(width, height, opts.scale) as usize;
let handle = mfb_open(n.as_ptr(), let handle = mfb_open(
n.as_ptr(),
width as u32, width as u32,
height as u32, height as u32,
window_flags::get_flags(opts), window_flags::get_flags(opts),
scale_factor as i32); scale_factor as i32,
);
if handle == ptr::null_mut() { if handle == ptr::null_mut() {
return Err(Error::WindowCreate("Unable to open Window".to_owned())); return Err(Error::WindowCreate("Unable to open Window".to_owned()));
@ -295,10 +303,12 @@ impl Window {
pub fn update_with_buffer(&mut self, buffer: &[u32]) -> Result<()> { pub fn update_with_buffer(&mut self, buffer: &[u32]) -> Result<()> {
self.key_handler.update(); self.key_handler.update();
let check_res = buffer_helper::check_buffer_size(self.shared_data.width as usize, let check_res = buffer_helper::check_buffer_size(
self.shared_data.width as usize,
self.shared_data.height as usize, self.shared_data.height as usize,
self.scale_factor as usize, self.scale_factor as usize,
buffer); buffer,
);
if check_res.is_err() { if check_res.is_err() {
return check_res; return check_res;
} }
@ -306,10 +316,12 @@ impl Window {
unsafe { unsafe {
mfb_update_with_buffer(self.window_handle, buffer.as_ptr() as *const u8); mfb_update_with_buffer(self.window_handle, buffer.as_ptr() as *const u8);
Self::set_mouse_data(self); Self::set_mouse_data(self);
mfb_set_key_callback(self.window_handle, mfb_set_key_callback(
self.window_handle,
mem::transmute(self), mem::transmute(self),
key_callback, key_callback,
char_callback); char_callback,
);
} }
Ok(()) Ok(())
@ -321,10 +333,12 @@ impl Window {
unsafe { unsafe {
mfb_update(self.window_handle); mfb_update(self.window_handle);
Self::set_mouse_data(self); Self::set_mouse_data(self);
mfb_set_key_callback(self.window_handle, mfb_set_key_callback(
self.window_handle,
mem::transmute(self), mem::transmute(self),
key_callback, key_callback,
char_callback); char_callback,
);
} }
} }
@ -334,8 +348,10 @@ impl Window {
} }
pub fn get_size(&self) -> (usize, usize) { pub fn get_size(&self) -> (usize, usize) {
(self.shared_data.width as usize, (
self.shared_data.height as usize) self.shared_data.width as usize,
self.shared_data.height as usize,
)
} }
pub fn get_scroll_wheel(&self) -> Option<(f32, f32)> { pub fn get_scroll_wheel(&self) -> Option<(f32, f32)> {
@ -362,12 +378,14 @@ impl Window {
let w = self.shared_data.width as f32; let w = self.shared_data.width as f32;
let h = self.shared_data.height as f32; let h = self.shared_data.height as f32;
mouse_handler::get_pos(mode, mouse_handler::get_pos(
mode,
self.shared_data.mouse_x, self.shared_data.mouse_x,
self.shared_data.mouse_y, self.shared_data.mouse_y,
s, s,
w, w,
h) h,
)
} }
pub fn get_unscaled_mouse_pos(&self, mode: MouseMode) -> Option<(f32, f32)> { pub fn get_unscaled_mouse_pos(&self, mode: MouseMode) -> Option<(f32, f32)> {
@ -375,12 +393,14 @@ impl Window {
let w = self.shared_data.width as f32; let w = self.shared_data.width as f32;
let h = self.shared_data.height as f32; let h = self.shared_data.height as f32;
mouse_handler::get_pos(mode, mouse_handler::get_pos(
mode,
self.shared_data.mouse_x, self.shared_data.mouse_x,
self.shared_data.mouse_y, self.shared_data.mouse_y,
s, s,
w, w,
h) h,
)
} }
#[inline] #[inline]
@ -513,7 +533,9 @@ impl Menu {
pub fn new(name: &str) -> Result<Menu> { pub fn new(name: &str) -> Result<Menu> {
unsafe { unsafe {
let menu_name = CString::new(name).unwrap(); let menu_name = CString::new(name).unwrap();
Ok(Menu { menu_handle: mfb_create_menu(menu_name.as_ptr()) }) Ok(Menu {
menu_handle: mfb_create_menu(menu_name.as_ptr()),
})
} }
} }
@ -640,12 +662,14 @@ impl Menu {
let item_name = CString::new(item.label.as_str()).unwrap(); let item_name = CString::new(item.label.as_str()).unwrap();
let conv_key = Self::map_key_to_menu_key(item.key); let conv_key = Self::map_key_to_menu_key(item.key);
MenuItemHandle(mfb_add_menu_item(self.menu_handle, MenuItemHandle(mfb_add_menu_item(
self.menu_handle,
item.id as i32, item.id as i32,
item_name.as_ptr(), item_name.as_ptr(),
item.enabled, item.enabled,
conv_key, conv_key,
item.modifier as u32)) item.modifier as u32,
))
} }
} }
@ -663,4 +687,3 @@ impl Drop for Window {
} }
} }
} }

View file

@ -1,12 +1,14 @@
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
pub mod macos; pub mod macos;
#[cfg(target_os = "windows")] #[cfg(target_os = "redox")]
pub mod windows; pub mod redox;
#[cfg(any(target_os="linux", #[cfg(any(
target_os = "linux",
target_os = "freebsd", target_os = "freebsd",
target_os = "dragonfly", target_os = "dragonfly",
target_os = "netbsd", target_os = "netbsd",
target_os="openbsd"))] target_os = "openbsd"
))]
pub mod unix; pub mod unix;
#[cfg(target_os = "redox")] #[cfg(target_os = "windows")]
pub mod redox; pub mod windows;

View file

@ -3,16 +3,16 @@
extern crate orbclient; extern crate orbclient;
use os::redox::orbclient::Renderer; use os::redox::orbclient::Renderer;
use error::Error;
use Result;
use mouse_handler;
use buffer_helper; use buffer_helper;
use error::Error;
use key_handler::KeyHandler; use key_handler::KeyHandler;
use mouse_handler;
use InputCallback; use InputCallback;
use Result;
use {CursorStyle, MouseButton, MouseMode}; use {CursorStyle, MouseButton, MouseMode};
use {Key, KeyRepeat}; use {Key, KeyRepeat};
use {MenuHandle, MenuItem, MenuItemHandle, UnixMenu, UnixMenuItem};
use {Scale, WindowOptions}; use {Scale, WindowOptions};
use {MenuItem, MenuItemHandle, MenuHandle, UnixMenu, UnixMenuItem};
use std::cmp; use std::cmp;
use std::os::raw; use std::os::raw;
@ -47,14 +47,15 @@ impl Window {
.map_err(|_| Error::WindowCreate("Unable to get display size".to_owned()))?; .map_err(|_| Error::WindowCreate("Unable to get display size".to_owned()))?;
let mut scale = 32; let mut scale = 32;
while scale > 1 { while scale > 1 {
if width * scale < display_size.0 as usize && if width * scale < display_size.0 as usize
height * scale < display_size.1 as usize { && height * scale < display_size.1 as usize
{
break; break;
} }
scale -= 1; scale -= 1;
} }
scale scale
}, }
}; };
let window_width = width as u32 * window_scale as u32; let window_width = width as u32 * window_scale as u32;
@ -68,15 +69,10 @@ impl Window {
window_flags.push(orbclient::WindowFlag::Borderless); window_flags.push(orbclient::WindowFlag::Borderless);
} }
let window_opt = orbclient::Window::new_flags(-1, let window_opt =
-1, orbclient::Window::new_flags(-1, -1, window_width, window_height, name, &window_flags);
window_width,
window_height,
name,
&window_flags);
match window_opt { match window_opt {
Some(window) => { Some(window) => Ok(Window {
Ok(Window {
mouse_pos: None, mouse_pos: None,
mouse_scroll: None, mouse_scroll: None,
mouse_state: (false, false, false), mouse_state: (false, false, false),
@ -89,8 +85,7 @@ impl Window {
key_handler: KeyHandler::new(), key_handler: KeyHandler::new(),
menu_counter: MenuHandle(0), menu_counter: MenuHandle(0),
menus: Vec::new(), menus: Vec::new(),
}) }),
},
None => Err(Error::WindowCreate("Unable to open Window".to_owned())), None => Err(Error::WindowCreate("Unable to open Window".to_owned())),
} }
} }
@ -107,7 +102,12 @@ impl Window {
self.process_events(); self.process_events();
self.key_handler.update(); self.key_handler.update();
let check_res = buffer_helper::check_buffer_size(self.buffer_width, self.buffer_height, self.window_scale, buffer); let check_res = buffer_helper::check_buffer_size(
self.buffer_width,
self.buffer_height,
self.window_scale,
buffer,
);
if check_res.is_err() { if check_res.is_err() {
return check_res; return check_res;
} }
@ -150,12 +150,14 @@ impl Window {
pub fn get_mouse_pos(&self, mode: MouseMode) -> Option<(f32, f32)> { pub fn get_mouse_pos(&self, mode: MouseMode) -> Option<(f32, f32)> {
if let Some((mouse_x, mouse_y)) = self.mouse_pos { if let Some((mouse_x, mouse_y)) = self.mouse_pos {
mouse_handler::get_pos(mode, mouse_handler::get_pos(
mode,
mouse_x as f32, mouse_x as f32,
mouse_y as f32, mouse_y as f32,
self.window_scale as f32, self.window_scale as f32,
self.buffer_width as f32 * self.window_scale as f32, self.buffer_width as f32 * self.window_scale as f32,
self.buffer_height as f32 * self.window_scale as f32) self.buffer_height as f32 * self.window_scale as f32,
)
} else { } else {
None None
} }
@ -163,12 +165,14 @@ impl Window {
pub fn get_unscaled_mouse_pos(&self, mode: MouseMode) -> Option<(f32, f32)> { pub fn get_unscaled_mouse_pos(&self, mode: MouseMode) -> Option<(f32, f32)> {
if let Some((mouse_x, mouse_y)) = self.mouse_pos { if let Some((mouse_x, mouse_y)) = self.mouse_pos {
mouse_handler::get_pos(mode, mouse_handler::get_pos(
mode,
mouse_x as f32, mouse_x as f32,
mouse_y as f32, mouse_y as f32,
1.0 as f32, 1.0 as f32,
self.buffer_width as f32 * self.window_scale as f32, self.buffer_width as f32 * self.window_scale as f32,
self.buffer_height as f32 * self.window_scale as f32) self.buffer_height as f32 * self.window_scale as f32,
)
} else { } else {
None None
} }
@ -228,26 +232,26 @@ impl Window {
if let Some(key) = key_opt { if let Some(key) = key_opt {
self.key_handler.set_key_state(key, key_event.pressed); self.key_handler.set_key_state(key, key_event.pressed);
} }
}, }
orbclient::EventOption::Mouse(mouse_event) => { orbclient::EventOption::Mouse(mouse_event) => {
self.mouse_pos = Some((mouse_event.x, mouse_event.y)); self.mouse_pos = Some((mouse_event.x, mouse_event.y));
}, }
orbclient::EventOption::Button(button_event) => { orbclient::EventOption::Button(button_event) => {
self.mouse_state = (button_event.left, button_event.middle, button_event.right); self.mouse_state = (button_event.left, button_event.middle, button_event.right);
}, }
orbclient::EventOption::Quit(_) => { orbclient::EventOption::Quit(_) => {
self.is_open = false; self.is_open = false;
}, }
orbclient::EventOption::Focus(focus_event) => { orbclient::EventOption::Focus(focus_event) => {
self.is_active = focus_event.focused; self.is_active = focus_event.focused;
if !self.is_active { if !self.is_active {
self.mouse_pos = None; self.mouse_pos = None;
} }
}, }
orbclient::EventOption::Scroll(scroll_event) => { orbclient::EventOption::Scroll(scroll_event) => {
self.mouse_pos = Some((scroll_event.x, scroll_event.y)); self.mouse_pos = Some((scroll_event.x, scroll_event.y));
}, }
_ => { }, _ => {}
} }
} }
} }
@ -335,16 +339,20 @@ impl Window {
_ => { _ => {
println!("Unknown Orbital scancode 0x{:2x}", scancode); println!("Unknown Orbital scancode 0x{:2x}", scancode);
None None
}, }
} }
} }
/// Renders the given pixel data into the Orbital window /// Renders the given pixel data into the Orbital window
fn render_buffer(&mut self, buffer: &[u32]) { fn render_buffer(&mut self, buffer: &[u32]) {
let render_width = cmp::min(self.buffer_width * self.window_scale, let render_width = cmp::min(
self.window.width() as usize); self.buffer_width * self.window_scale,
let render_height = cmp::min(self.buffer_height * self.window_scale, self.window.width() as usize,
self.window.height() as usize); );
let render_height = cmp::min(
self.buffer_height * self.window_scale,
self.window.height() as usize,
);
let window_width = self.window.width() as usize; let window_width = self.window.width() as usize;
let window_buffer = self.window.data_mut(); let window_buffer = self.window.data_mut();
@ -400,7 +408,7 @@ impl Menu {
item_counter: MenuItemHandle(0), item_counter: MenuItemHandle(0),
name: name.to_owned(), name: name.to_owned(),
items: Vec::new(), items: Vec::new(),
} },
}) })
} }
@ -438,6 +446,8 @@ impl Menu {
} }
pub fn remove_item(&mut self, handle: &MenuItemHandle) { pub fn remove_item(&mut self, handle: &MenuItemHandle) {
self.internal.items.retain(|ref item| item.handle.0 != handle.0); self.internal
.items
.retain(|ref item| item.handle.0 != handle.0);
} }
} }

View file

@ -61,7 +61,6 @@
* *
*/ */
//************************************************************************ //************************************************************************
//**** KeySym to Unicode mapping table **** //**** KeySym to Unicode mapping table ****
//************************************************************************ //************************************************************************
@ -830,7 +829,6 @@ const keysymtab: [CodePair ; LENGTH] = [
(0x13bd, 0x0153), (0x13bd, 0x0153),
(0x13be, 0x0178), (0x13be, 0x0178),
(0x20ac, 0x20ac), (0x20ac, 0x20ac),
// Numeric keypad with numlock on // Numeric keypad with numlock on
(0xff80 /*XKB_KEY_KP_Space*/, ' ' as u32), (0xff80 /*XKB_KEY_KP_Space*/, ' ' as u32),
(0xffaa /*XKB_KEY_KP_Multiply*/, '*' as u32), (0xffaa /*XKB_KEY_KP_Multiply*/, '*' as u32),
@ -852,7 +850,6 @@ const keysymtab: [CodePair ; LENGTH] = [
(0xffbd /*XKB_KEY_KP_Equal*/, '=' as u32), (0xffbd /*XKB_KEY_KP_Equal*/, '=' as u32),
]; ];
fn binary_search(value: u32, min: isize, max: isize) -> Option<u32> { fn binary_search(value: u32, min: isize, max: isize) -> Option<u32> {
if max >= min { if max >= min {
let mid = (min + max) / 2; let mid = (min + max) / 2;
@ -871,12 +868,9 @@ fn binary_search(value: u32, min: isize, max: isize) -> Option<u32> {
} }
} }
pub fn keysym_to_unicode(keysym: u32) -> Option<u32> { pub fn keysym_to_unicode(keysym: u32) -> Option<u32> {
// First check for Latin-1 characters (1:1 mapping) // First check for Latin-1 characters (1:1 mapping)
if (keysym >= 0x0020 && keysym <= 0x007e) || if (keysym >= 0x0020 && keysym <= 0x007e) || (keysym >= 0x00a0 && keysym <= 0x00ff) {
(keysym >= 0x00a0 && keysym <= 0x00ff)
{
return Some(keysym); return Some(keysym);
} }
@ -889,7 +883,6 @@ pub fn keysym_to_unicode(keysym: u32) -> Option<u32> {
binary_search(keysym, 0, (LENGTH - 1) as isize) binary_search(keysym, 0, (LENGTH - 1) as isize)
} }
#[allow(dead_code)] #[allow(dead_code)]
pub fn test_it() { pub fn test_it() {
assert_eq!(keysym_to_unicode('1' as u32), Some('1' as u32)); assert_eq!(keysym_to_unicode('1' as u32), Some('1' as u32));
@ -909,4 +902,3 @@ pub fn test_it() {
assert_eq!(keysym_to_unicode(p.0), Some(p.1)); assert_eq!(keysym_to_unicode(p.0), Some(p.1));
} }
} }

View file

@ -178,9 +178,7 @@ impl DisplayInfo {
fn load_cursor(&mut self, name: &'static str) -> xlib::Cursor { fn load_cursor(&mut self, name: &'static str) -> xlib::Cursor {
let name = CString::new(name).expect("static data"); let name = CString::new(name).expect("static data");
unsafe { unsafe { (self.cursor_lib.XcursorLibraryLoadCursor)(self.display, name.as_ptr()) }
(self.cursor_lib.XcursorLibraryLoadCursor)(self.display, name.as_ptr())
}
} }
fn init_atoms(&mut self) { fn init_atoms(&mut self) {
@ -259,7 +257,8 @@ impl Window {
let mut d = DisplayInfo::new()?; let mut d = DisplayInfo::new()?;
let scale = Self::get_scale_factor(width, height, d.screen_width, d.screen_height, opts.scale); let scale =
Self::get_scale_factor(width, height, d.screen_width, d.screen_height, opts.scale);
let width = width * scale; let width = width * scale;
let height = height * scale; let height = height * scale;
@ -274,8 +273,16 @@ impl Window {
attributes.backing_store = xlib::NotUseful; attributes.backing_store = xlib::NotUseful;
let x = if d.screen_width > width { (d.screen_width - width) / 2 } else { 0 }; let x = if d.screen_width > width {
let y = if d.screen_height > height { (d.screen_height - height) / 2 } else { 0 }; (d.screen_width - width) / 2
} else {
0
};
let y = if d.screen_height > height {
(d.screen_height - height) / 2
} else {
0
};
let handle = (d.lib.XCreateWindow)( let handle = (d.lib.XCreateWindow)(
d.display, d.display,
@ -363,7 +370,12 @@ impl Window {
} }
} }
unsafe fn alloc_image(d: &DisplayInfo, width: usize, height: usize, draw_buffer: &mut Vec<u32>) -> Option<*mut xlib::XImage> { unsafe fn alloc_image(
d: &DisplayInfo,
width: usize,
height: usize,
draw_buffer: &mut Vec<u32>,
) -> Option<*mut xlib::XImage> {
let bytes_per_line = (width as i32) * 4; let bytes_per_line = (width as i32) * 4;
draw_buffer.resize(width * height, 0); draw_buffer.resize(width * height, 0);
@ -550,7 +562,13 @@ impl Window {
true true
} }
fn get_scale_factor(width: usize, height: usize, screen_width: usize, screen_height: usize, scale: Scale) -> usize { fn get_scale_factor(
width: usize,
height: usize,
screen_width: usize,
screen_height: usize,
scale: Scale,
) -> usize {
match scale { match scale {
Scale::X1 => 1, Scale::X1 => 1,
Scale::X2 => 2, Scale::X2 => 2,
@ -743,7 +761,9 @@ impl Window {
&self.d, &self.d,
cast::usize(self.width), cast::usize(self.width),
cast::usize(self.height), cast::usize(self.height),
&mut self.draw_buffer).expect("todo"); &mut self.draw_buffer,
)
.expect("todo");
} }
_ => {} _ => {}
@ -997,13 +1017,7 @@ macro_rules! gen_scale_x(
) )
); );
gen_scale_x!( gen_scale_x!(scale_2x, 2, scale_4x, 4, scale_8x, 8, scale_16x, 16, scale_32x, 32,);
scale_2x, 2,
scale_4x, 4,
scale_8x, 8,
scale_16x, 16,
scale_32x, 32,
);
impl Drop for Window { impl Drop for Window {
fn drop(&mut self) { fn drop(&mut self) {

View file

@ -1,33 +1,33 @@
#![cfg(target_os = "windows")] #![cfg(target_os = "windows")]
extern crate winapi;
extern crate time; extern crate time;
extern crate winapi;
const INVALID_ACCEL: usize = 0xffffffff; const INVALID_ACCEL: usize = 0xffffffff;
use {Scale, Key, KeyRepeat, MouseButton, MouseMode, WindowOptions, InputCallback};
use key_handler::KeyHandler;
use error::Error; use error::Error;
use key_handler::KeyHandler;
use Result; use Result;
use {CursorStyle, MenuItem, MenuItemHandle, MenuHandle}; use {CursorStyle, MenuHandle, MenuItem, MenuItemHandle};
use {MENU_KEY_WIN, MENU_KEY_SHIFT, MENU_KEY_CTRL, MENU_KEY_ALT}; use {InputCallback, Key, KeyRepeat, MouseButton, MouseMode, Scale, WindowOptions};
use {MENU_KEY_ALT, MENU_KEY_CTRL, MENU_KEY_SHIFT, MENU_KEY_WIN};
use std::ptr; use buffer_helper;
use std::os::windows::ffi::OsStrExt; use mouse_handler;
use std::ffi::OsStr; use std::ffi::OsStr;
use std::mem; use std::mem;
use std::os::raw; use std::os::raw;
use mouse_handler; use std::os::windows::ffi::OsStrExt;
use buffer_helper; use std::ptr;
use self::winapi::shared::basetsd; use self::winapi::shared::basetsd;
use self::winapi::um::winuser;
use self::winapi::shared::minwindef; use self::winapi::shared::minwindef;
use self::winapi::shared::windef;
use self::winapi::um::wingdi;
use self::winapi::shared::ntdef; use self::winapi::shared::ntdef;
use self::winapi::um::libloaderapi; use self::winapi::shared::windef;
use self::winapi::um::errhandlingapi; use self::winapi::um::errhandlingapi;
use self::winapi::um::libloaderapi;
use self::winapi::um::wingdi;
use self::winapi::um::winuser;
// Wrap this so we can have a proper numbef of bmiColors to write in // Wrap this so we can have a proper numbef of bmiColors to write in
#[repr(C)] #[repr(C)]
@ -167,11 +167,12 @@ unsafe fn get_window_long(window: windef::HWND) -> ntdef::LONG {
winuser::GetWindowLongW(window, winuser::GWLP_USERDATA) winuser::GetWindowLongW(window, winuser::GWLP_USERDATA)
} }
unsafe extern "system" fn wnd_proc(window: windef::HWND, unsafe extern "system" fn wnd_proc(
window: windef::HWND,
msg: minwindef::UINT, msg: minwindef::UINT,
wparam: minwindef::WPARAM, wparam: minwindef::WPARAM,
lparam: minwindef::LPARAM) lparam: minwindef::LPARAM,
-> minwindef::LRESULT { ) -> minwindef::LRESULT {
// This make sure we actually don't do anything before the user data has been setup for the // This make sure we actually don't do anything before the user data has been setup for the
// window // window
@ -212,29 +213,17 @@ unsafe extern "system" fn wnd_proc(window: windef::HWND,
char_down(wnd, wparam as u32); char_down(wnd, wparam as u32);
} }
winuser::WM_LBUTTONDOWN => { winuser::WM_LBUTTONDOWN => wnd.mouse.state[0] = true,
wnd.mouse.state[0] = true
}
winuser::WM_LBUTTONUP => { winuser::WM_LBUTTONUP => wnd.mouse.state[0] = false,
wnd.mouse.state[0] = false
}
winuser::WM_MBUTTONDOWN => { winuser::WM_MBUTTONDOWN => wnd.mouse.state[1] = true,
wnd.mouse.state[1] = true
}
winuser::WM_MBUTTONUP => { winuser::WM_MBUTTONUP => wnd.mouse.state[1] = false,
wnd.mouse.state[1] = false
}
winuser::WM_RBUTTONDOWN => { winuser::WM_RBUTTONDOWN => wnd.mouse.state[2] = true,
wnd.mouse.state[2] = true
}
winuser::WM_RBUTTONUP => { winuser::WM_RBUTTONUP => wnd.mouse.state[2] = false,
wnd.mouse.state[2] = false
}
winuser::WM_CLOSE => { winuser::WM_CLOSE => {
wnd.is_open = false; wnd.is_open = false;
@ -259,7 +248,6 @@ unsafe extern "system" fn wnd_proc(window: windef::HWND,
} }
winuser::WM_PAINT => { winuser::WM_PAINT => {
// if we have nothing to draw here we return the default function // if we have nothing to draw here we return the default function
if wnd.buffer.len() == 0 { if wnd.buffer.len() == 0 {
return winuser::DefWindowProcW(window, msg, wparam, lparam); return winuser::DefWindowProcW(window, msg, wparam, lparam);
@ -277,7 +265,8 @@ unsafe extern "system" fn wnd_proc(window: windef::HWND,
bitmap_info.bmi_colors[1].rgbGreen = 0xff; bitmap_info.bmi_colors[1].rgbGreen = 0xff;
bitmap_info.bmi_colors[2].rgbBlue = 0xff; bitmap_info.bmi_colors[2].rgbBlue = 0xff;
wingdi::StretchDIBits(wnd.dc.unwrap(), wingdi::StretchDIBits(
wnd.dc.unwrap(),
0, 0,
0, 0,
wnd.width * wnd.scale_factor, wnd.width * wnd.scale_factor,
@ -289,7 +278,8 @@ unsafe extern "system" fn wnd_proc(window: windef::HWND,
mem::transmute(wnd.buffer.as_ptr()), mem::transmute(wnd.buffer.as_ptr()),
mem::transmute(&bitmap_info), mem::transmute(&bitmap_info),
wingdi::DIB_RGB_COLORS, wingdi::DIB_RGB_COLORS,
wingdi::SRCCOPY); wingdi::SRCCOPY,
);
winuser::ValidateRect(window, ptr::null_mut()); winuser::ValidateRect(window, ptr::null_mut());
@ -307,7 +297,10 @@ pub enum MinifbError {
} }
fn to_wstring(str: &str) -> Vec<u16> { fn to_wstring(str: &str) -> Vec<u16> {
let v: Vec<u16> = OsStr::new(str).encode_wide().chain(Some(0).into_iter()).collect(); let v: Vec<u16> = OsStr::new(str)
.encode_wide()
.chain(Some(0).into_iter())
.collect();
v v
} }
@ -353,7 +346,13 @@ pub struct Window {
// } // }
impl Window { impl Window {
fn open_window(name: &str, width: usize, height: usize, opts: WindowOptions, scale_factor: i32) -> Option<windef::HWND> { fn open_window(
name: &str,
width: usize,
height: usize,
opts: WindowOptions,
scale_factor: i32,
) -> Option<windef::HWND> {
unsafe { unsafe {
let class_name = to_wstring("minifb_window"); let class_name = to_wstring("minifb_window");
let class = winuser::WNDCLASSW { let class = winuser::WNDCLASSW {
@ -372,7 +371,10 @@ impl Window {
if winuser::RegisterClassW(&class) == 0 { if winuser::RegisterClassW(&class) == 0 {
// ignore the "Class already exists" error for multiple windows // ignore the "Class already exists" error for multiple windows
if errhandlingapi::GetLastError() as u32 != 1410 { if errhandlingapi::GetLastError() as u32 != 1410 {
println!("Unable to register class, error {}", errhandlingapi::GetLastError() as u32); println!(
"Unable to register class, error {}",
errhandlingapi::GetLastError() as u32
);
return None; return None;
} }
} }
@ -387,9 +389,11 @@ impl Window {
bottom: new_height as ntdef::LONG, bottom: new_height as ntdef::LONG,
}; };
winuser::AdjustWindowRect(&mut rect, winuser::AdjustWindowRect(
&mut rect,
winuser::WS_POPUP | winuser::WS_SYSMENU | winuser::WS_CAPTION, winuser::WS_POPUP | winuser::WS_SYSMENU | winuser::WS_CAPTION,
0); 0,
);
rect.right -= rect.left; rect.right -= rect.left;
rect.bottom -= rect.top; rect.bottom -= rect.top;
@ -404,7 +408,6 @@ impl Window {
if opts.resize { if opts.resize {
flags |= winuser::WS_THICKFRAME as u32 | winuser::WS_MAXIMIZEBOX as u32; flags |= winuser::WS_THICKFRAME as u32 | winuser::WS_MAXIMIZEBOX as u32;
} else { } else {
flags &= !winuser::WS_MAXIMIZEBOX; flags &= !winuser::WS_MAXIMIZEBOX;
flags &= !winuser::WS_THICKFRAME; flags &= !winuser::WS_THICKFRAME;
@ -414,7 +417,8 @@ impl Window {
flags &= !winuser::WS_THICKFRAME; flags &= !winuser::WS_THICKFRAME;
} }
let handle = winuser::CreateWindowExW(0, let handle = winuser::CreateWindowExW(
0,
class_name.as_ptr(), class_name.as_ptr(),
window_name.as_ptr(), window_name.as_ptr(),
flags, flags,
@ -425,9 +429,13 @@ impl Window {
ptr::null_mut(), ptr::null_mut(),
ptr::null_mut(), ptr::null_mut(),
ptr::null_mut(), ptr::null_mut(),
ptr::null_mut()); ptr::null_mut(),
);
if handle.is_null() { if handle.is_null() {
println!("Unable to create window, error {}", errhandlingapi::GetLastError() as u32); println!(
"Unable to create window, error {}",
errhandlingapi::GetLastError() as u32
);
return None; return None;
} }
@ -437,11 +445,7 @@ impl Window {
} }
} }
pub fn new(name: &str, pub fn new(name: &str, width: usize, height: usize, opts: WindowOptions) -> Result<Window> {
width: usize,
height: usize,
opts: WindowOptions)
-> Result<Window> {
unsafe { unsafe {
let scale_factor = Self::get_scale_factor(width, height, opts.scale); let scale_factor = Self::get_scale_factor(width, height, opts.scale);
@ -497,8 +501,15 @@ impl Window {
#[inline] #[inline]
pub fn set_position(&mut self, x: isize, y: isize) { pub fn set_position(&mut self, x: isize, y: isize) {
unsafe { unsafe {
winuser::SetWindowPos(self.window.unwrap(), ptr::null_mut(), x as i32, y as i32, winuser::SetWindowPos(
0, 0, winuser::SWP_SHOWWINDOW | winuser::SWP_NOSIZE); self.window.unwrap(),
ptr::null_mut(),
x as i32,
y as i32,
0,
0,
winuser::SWP_SHOWWINDOW | winuser::SWP_NOSIZE,
);
} }
} }
@ -596,7 +607,7 @@ impl Window {
#[inline] #[inline]
pub fn is_open(&self) -> bool { pub fn is_open(&self) -> bool {
return self.is_open return self.is_open;
} }
fn generic_update(&mut self, window: windef::HWND) { fn generic_update(&mut self, window: windef::HWND) {
@ -625,7 +636,12 @@ impl Window {
winuser::TranslateMessage(&mut msg); winuser::TranslateMessage(&mut msg);
winuser::DispatchMessageW(&mut msg); winuser::DispatchMessageW(&mut msg);
} else { } else {
if winuser::TranslateAcceleratorW(msg.hwnd, mem::transmute(self.accel_table), &mut msg) == 0 { if winuser::TranslateAcceleratorW(
msg.hwnd,
mem::transmute(self.accel_table),
&mut msg,
) == 0
{
winuser::TranslateMessage(&mut msg); winuser::TranslateMessage(&mut msg);
winuser::DispatchMessageW(&mut msg); winuser::DispatchMessageW(&mut msg);
} }
@ -639,10 +655,12 @@ impl Window {
Self::generic_update(self, window); Self::generic_update(self, window);
let check_res = buffer_helper::check_buffer_size(self.width as usize, let check_res = buffer_helper::check_buffer_size(
self.width as usize,
self.height as usize, self.height as usize,
self.scale_factor as usize, self.scale_factor as usize,
buffer); buffer,
);
if check_res.is_err() { if check_res.is_err() {
return check_res; return check_res;
} }
@ -712,12 +730,14 @@ impl Window {
let menu_height = winuser::GetSystemMetrics(winuser::SM_CYMENU); let menu_height = winuser::GetSystemMetrics(winuser::SM_CYMENU);
winuser::GetWindowRect(handle, &mut rect); winuser::GetWindowRect(handle, &mut rect);
winuser::MoveWindow(handle, winuser::MoveWindow(
handle,
rect.left, rect.left,
rect.top, rect.top,
rect.right - rect.left, rect.right - rect.left,
(rect.bottom - rect.top) + menu_height, (rect.bottom - rect.top) + menu_height,
1); 1,
);
} }
unsafe fn set_accel_table(&mut self) { unsafe fn set_accel_table(&mut self) {
@ -734,13 +754,14 @@ impl Window {
winuser::DestroyAcceleratorTable(self.accel_table); winuser::DestroyAcceleratorTable(self.accel_table);
} }
self.accel_table = winuser::CreateAcceleratorTableW(temp_accel_table.as_mut_ptr(), self.accel_table = winuser::CreateAcceleratorTableW(
temp_accel_table.len() as i32); temp_accel_table.as_mut_ptr(),
temp_accel_table.len() as i32,
);
println!("accel {:?}", self.accel_table); println!("accel {:?}", self.accel_table);
} }
pub fn add_menu(&mut self, menu: &Menu) -> MenuHandle { pub fn add_menu(&mut self, menu: &Menu) -> MenuHandle {
unsafe { unsafe {
let window = self.window.unwrap(); let window = self.window.unwrap();
@ -752,10 +773,12 @@ impl Window {
Self::adjust_window_size_for_menu(window); Self::adjust_window_size_for_menu(window);
} }
winuser::AppendMenuW(main_menu, winuser::AppendMenuW(
main_menu,
0x10, 0x10,
menu.menu_handle as basetsd::UINT_PTR, menu.menu_handle as basetsd::UINT_PTR,
menu.name.as_ptr()); menu.name.as_ptr(),
);
self.menus.push(menu.clone()); self.menus.push(menu.clone());
// TODO: Setup accel table // TODO: Setup accel table
@ -932,15 +955,17 @@ impl Menu {
pub fn add_sub_menu(&mut self, name: &str, menu: &Menu) { pub fn add_sub_menu(&mut self, name: &str, menu: &Menu) {
unsafe { unsafe {
let menu_name = to_wstring(name); let menu_name = to_wstring(name);
winuser::AppendMenuW(self.menu_handle, winuser::AppendMenuW(
self.menu_handle,
0x10, 0x10,
menu.menu_handle as basetsd::UINT_PTR, menu.menu_handle as basetsd::UINT_PTR,
menu_name.as_ptr()); menu_name.as_ptr(),
self.accel_table.extend_from_slice(menu.accel_table.as_slice()); );
self.accel_table
.extend_from_slice(menu.accel_table.as_slice());
} }
} }
fn format_name(menu_item: &MenuItem, key_name: &'static str) -> String { fn format_name(menu_item: &MenuItem, key_name: &'static str) -> String {
let mut name = menu_item.label.clone(); let mut name = menu_item.label.clone();
@ -1004,7 +1029,8 @@ impl Menu {
let accel = winuser::ACCEL { let accel = winuser::ACCEL {
fVirt: virt as minwindef::BYTE, fVirt: virt as minwindef::BYTE,
cmd: menu_item.id as minwindef::WORD, cmd: menu_item.id as minwindef::WORD,
key: vk_accel.0 as minwindef::WORD }; key: vk_accel.0 as minwindef::WORD,
};
self.accel_table.push(accel); self.accel_table.push(accel);
} }
@ -1016,12 +1042,22 @@ impl Menu {
match vk_accel.0 { match vk_accel.0 {
0 => { 0 => {
let item_name = to_wstring(&menu_item.label); let item_name = to_wstring(&menu_item.label);
winuser::AppendMenuW(self.menu_handle, 0x10, menu_item.id as basetsd::UINT_PTR, item_name.as_ptr()); winuser::AppendMenuW(
}, self.menu_handle,
0x10,
menu_item.id as basetsd::UINT_PTR,
item_name.as_ptr(),
);
}
_ => { _ => {
let menu_name = Self::format_name(menu_item, vk_accel.1); let menu_name = Self::format_name(menu_item, vk_accel.1);
let w_name = to_wstring(&menu_name); let w_name = to_wstring(&menu_name);
winuser::AppendMenuW(self.menu_handle, 0x10, menu_item.id as basetsd::UINT_PTR, w_name.as_ptr()); winuser::AppendMenuW(
self.menu_handle,
0x10,
menu_item.id as basetsd::UINT_PTR,
w_name.as_ptr(),
);
self.add_accel(vk_accel.0, menu_item); self.add_accel(vk_accel.0, menu_item);
} }
} }
@ -1039,7 +1075,6 @@ impl Menu {
} }
} }
impl Drop for Window { impl Drop for Window {
fn drop(&mut self) { fn drop(&mut self) {
unsafe { unsafe {