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;
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 HEIGHT: usize = 360;
@ -24,14 +24,16 @@ impl InputCallback for KeyCharCallback {
fn main() {
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,
HEIGHT,
WindowOptions {
resize: true,
scale: Scale::X2,
..WindowOptions::default()
})
},
)
.expect("Unable to Open Window");
window.set_input_callback(Box::new(KeyCharCallback {}));
@ -39,16 +41,28 @@ fn main() {
let mut menu = Menu::new("Test").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 1", COLOR_1_ID).shortcut(Key::F2, 0).build();
sub.add_item("Color 2", COLOR_2_ID).shortcut(Key::F7, 0).build();
sub.add_item("Color 0", COLOR_0_ID)
.shortcut(Key::F1, 0)
.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_item("Other Menu", OTHER_MENU_ID).shortcut(Key::W, MENU_KEY_CTRL).build();
menu.add_item("Remove Menu", CLOSE_MENU_ID).shortcut(Key::R, 0).build();
menu.add_item("Other Menu", OTHER_MENU_ID)
.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);

View file

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

View file

@ -1,26 +1,39 @@
extern crate minifb;
use minifb::{WindowOptions, Window, Scale, Key};
use minifb::{Key, Scale, Window, WindowOptions};
fn main() {
let width = 640;
let height = 320;
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,
..WindowOptions::default()
}).unwrap();
},
)
.unwrap();
let mut orig = Window::new("Smaller", width, height, WindowOptions {
let mut orig = Window::new(
"Smaller",
width,
height,
WindowOptions {
..WindowOptions::default()
}).unwrap();
},
)
.unwrap();
let mut pos = 13;
while orig.is_open() && double.is_open()
while orig.is_open()
&& double.is_open()
&& !orig.is_key_down(Key::Escape)
&& !double.is_key_down(Key::Escape) {
&& !double.is_key_down(Key::Escape)
{
orig.update_with_buffer(&buffer).unwrap();
double.update_with_buffer(&buffer).unwrap();
pos += 7;

View file

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

View file

@ -1,6 +1,6 @@
extern crate minifb;
use minifb::{CursorStyle, Window, Key, Scale, WindowOptions, MouseMode};
use minifb::{CursorStyle, Key, MouseMode, Scale, Window, WindowOptions};
const WIDTH: usize = 640;
const HEIGHT: usize = 360;
@ -21,8 +21,7 @@ impl Rect {
let xe = self.x + self.width;
let ye = self.y + self.height;
if (y >= self.y) && (y <= ye) &&
(x >= self.x) && (x <= xe) {
if (y >= self.y) && (y <= ye) && (x >= self.x) && (x <= xe) {
true
} else {
false
@ -41,23 +40,81 @@ fn fill_rect(dest: &mut [u32], rect: &Rect) {
fn main() {
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,
HEIGHT,
WindowOptions {
scale: Scale::X2,
..WindowOptions::default()
})
},
)
.expect("Unable to Open Window");
let rects = [
Rect { x: 0, y: 0, width: 160, height: 180, color: 0x00b27474, cursor_style: CursorStyle::Arrow },
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 }
Rect {
x: 0,
y: 0,
width: 160,
height: 180,
color: 0x00b27474,
cursor_style: CursorStyle::Arrow,
},
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");
@ -76,4 +133,3 @@ fn main() {
window.update_with_buffer(&buffer).unwrap();
}
}

View file

@ -1,7 +1,12 @@
use error::Error;
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 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 {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::MenusNotSupported => {
write!(fmt, "{}", self.description())
},
Error::MenuExists(ref e) => {
write!(fmt, "{} {:?}", self.description(), e)
},
Error::WindowCreate(ref e) => {
write!(fmt, "{} {:?}", self.description(), e)
}
Error::UpdateFailed(ref e) => {
write!(fmt, "{} {:?}", self.description(), e)
}
Error::MenusNotSupported => write!(fmt, "{}", self.description()),
Error::MenuExists(ref 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,
}

View file

@ -1,7 +1,7 @@
extern crate time;
use std::mem;
use {Key, KeyRepeat, InputCallback};
use {InputCallback, Key, KeyRepeat};
pub struct KeyHandler {
pub key_callback: Option<Box<dyn InputCallback>>,
@ -118,7 +118,9 @@ impl KeyHandler {
if repeat == KeyRepeat::Yes && t > self.key_repeat_delay {
let delay = self.key_repeat_delay;
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;
}
}

View file

@ -50,7 +50,6 @@ pub enum MouseButton {
Right,
}
/// The diffrent modes that can be used to decide how mouse coordinates should be handled
#[derive(PartialEq, Clone, Copy, Debug)]
pub enum MouseMode {
@ -94,11 +93,11 @@ pub use self::error::Error;
pub type Result<T> = std::result::Result<T, Error>;
mod key;
pub use key::Key as Key;
mod os;
mod mouse_handler;
pub use key::Key;
mod buffer_helper;
mod key_handler;
mod mouse_handler;
mod os;
mod window_flags;
//mod 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_ALT;
#[cfg(target_os = "macos")]
use self::os::macos as imp;
#[cfg(target_os = "windows")]
use self::os::windows as imp;
#[cfg(any(target_os="linux",
target_os="freebsd",
target_os="dragonfly",
target_os="netbsd",
target_os="openbsd"))]
use self::os::unix as imp;
#[cfg(target_os = "redox")]
use self::os::redox as imp;
#[cfg(any(
target_os = "linux",
target_os = "freebsd",
target_os = "dragonfly",
target_os = "netbsd",
target_os = "openbsd"
))]
use self::os::unix as imp;
#[cfg(target_os = "windows")]
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
/// the widow is set as non-resizable.
@ -129,9 +129,7 @@ pub struct Window(imp::Window);
impl fmt::Debug for Window {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_tuple("Window")
.field(&format_args!(".."))
.finish()
f.debug_tuple("Window").field(&format_args!("..")).finish()
}
}
@ -590,18 +588,19 @@ impl Window {
/// Get Unix menu. Will only return menus on Unix class OSes
/// otherwise ```None```
///
#[cfg(any(target_os="macos",
target_os="windows"))]
#[cfg(any(target_os = "macos", target_os = "windows"))]
pub fn get_unix_menus(&self) -> Option<&Vec<UnixMenu>> {
None
}
#[cfg(any(target_os="linux",
target_os="freebsd",
target_os="dragonfly",
target_os="netbsd",
target_os="openbsd",
target_os="redox"))]
#[cfg(any(
target_os = "linux",
target_os = "freebsd",
target_os = "dragonfly",
target_os = "netbsd",
target_os = "openbsd",
target_os = "redox"
))]
pub fn get_unix_menus(&self) -> Option<&Vec<UnixMenu>> {
self.0.get_unix_menus()
}
@ -615,7 +614,6 @@ impl Window {
}
}
/// Command key on Mac OS
pub const MENU_KEY_COMMAND: usize = 1;
/// Windows key on Windows
@ -627,7 +625,7 @@ pub const MENU_KEY_CTRL: usize = 8;
/// Alt key
pub const MENU_KEY_ALT: usize = 16;
const MENU_ID_SEPARATOR:usize = 0xffffffff;
const MENU_ID_SEPARATOR: usize = 0xffffffff;
///
/// Used on Unix (Linux, FreeBSD, etc) as menus aren't supported in a native where there.
@ -675,7 +673,6 @@ pub struct MenuItemHandle(pub u64);
#[doc(hidden)]
pub struct MenuHandle(pub u64);
///
/// Menu holds info for menus
///
@ -683,9 +680,7 @@ pub struct Menu(imp::Menu);
impl fmt::Debug for Menu {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_tuple("Menu")
.field(&format_args!(".."))
.finish()
f.debug_tuple("Menu").field(&format_args!("..")).finish()
}
}
@ -709,7 +704,10 @@ impl Menu {
/// Adds a menu separator
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]
@ -808,7 +806,7 @@ impl<'a> MenuItem<'a> {
MenuItem {
key: key,
modifier: modifier,
.. self
..self
}
}
#[inline]
@ -826,7 +824,7 @@ impl<'a> MenuItem<'a> {
pub fn separator(self) -> Self {
MenuItem {
id: MENU_ID_SEPARATOR,
.. self
..self
}
}
#[inline]
@ -843,7 +841,7 @@ impl<'a> MenuItem<'a> {
pub fn enabled(self, enabled: bool) -> Self {
MenuItem {
enabled: enabled,
.. self
..self
}
}
#[inline]

View file

@ -4,7 +4,14 @@ fn clamp(v: f32, lb: f32, ub: f32) -> f32 {
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 x = mx * 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 {
MouseMode::Pass => Some((x, y)),
MouseMode::Clamp => {
Some((clamp(x, 0.0, window_width - 1.0),
clamp(y, 0.0, window_height - 1.0)))
},
MouseMode::Clamp => Some((
clamp(x, 0.0, window_width - 1.0),
clamp(y, 0.0, window_height - 1.0),
)),
MouseMode::Discard => {
if x < 0.0 || y < 0.0 || x >= window_width || y >= window_height {
None
} else {
Some((x, y))
}
},
}
}
}

View file

@ -1,22 +1,22 @@
#![cfg(target_os = "macos")]
use {MouseButton, MouseMode, Scale, Key, KeyRepeat, WindowOptions};
use key_handler::KeyHandler;
use error::Error;
use key_handler::KeyHandler;
use Result;
use {Key, KeyRepeat, MouseButton, MouseMode, Scale, WindowOptions};
// use MenuItem;
use InputCallback;
use mouse_handler;
use buffer_helper;
use mouse_handler;
use window_flags;
use {CursorStyle, MenuItem, MenuItemHandle, MenuHandle};
use InputCallback;
use {CursorStyle, MenuHandle, MenuItem, MenuItemHandle};
// use menu::Menu;
use std::os::raw::{c_void, c_char, c_uchar};
use std::ffi::CString;
use std::ptr;
use std::mem;
use std::os::raw;
use std::os::raw::{c_char, c_uchar, c_void};
use std::ptr;
// Table taken from GLFW and slightly modified
@ -154,21 +154,24 @@ static KEY_MAPPINGS: [Key; 128] = [
#[link(name = "Cocoa", kind = "framework")]
#[link(name = "Carbon", kind = "framework")]
extern "C" {
fn mfb_open(name: *const c_char,
fn mfb_open(
name: *const c_char,
width: u32,
height: u32,
flags: u32,
scale: i32)
-> *mut c_void;
scale: i32,
) -> *mut c_void;
fn mfb_set_title(window: *mut c_void, title: *const c_char);
fn mfb_close(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_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,
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_cursor_style(window: *mut c_void, cursor: u32);
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_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,
name: *const c_char,
enabled: bool,
key: u32,
modifier: u32)
-> u64;
modifier: u32,
) -> 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 {
(*win).key_handler.set_key_state(Key::Unknown, s);
} 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 {
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,
height as u32,
window_flags::get_flags(opts),
scale_factor as i32);
scale_factor as i32,
);
if handle == ptr::null_mut() {
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<()> {
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.scale_factor as usize,
buffer);
buffer,
);
if check_res.is_err() {
return check_res;
}
@ -306,10 +316,12 @@ impl Window {
unsafe {
mfb_update_with_buffer(self.window_handle, buffer.as_ptr() as *const u8);
Self::set_mouse_data(self);
mfb_set_key_callback(self.window_handle,
mfb_set_key_callback(
self.window_handle,
mem::transmute(self),
key_callback,
char_callback);
char_callback,
);
}
Ok(())
@ -321,10 +333,12 @@ impl Window {
unsafe {
mfb_update(self.window_handle);
Self::set_mouse_data(self);
mfb_set_key_callback(self.window_handle,
mfb_set_key_callback(
self.window_handle,
mem::transmute(self),
key_callback,
char_callback);
char_callback,
);
}
}
@ -334,8 +348,10 @@ impl Window {
}
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)> {
@ -362,12 +378,14 @@ impl Window {
let w = self.shared_data.width 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_y,
s,
w,
h)
h,
)
}
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 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_y,
s,
w,
h)
h,
)
}
#[inline]
@ -513,7 +533,9 @@ impl Menu {
pub fn new(name: &str) -> Result<Menu> {
unsafe {
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 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_name.as_ptr(),
item.enabled,
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")]
pub mod macos;
#[cfg(target_os = "windows")]
pub mod windows;
#[cfg(any(target_os="linux",
target_os="freebsd",
target_os="dragonfly",
target_os="netbsd",
target_os="openbsd"))]
pub mod unix;
#[cfg(target_os = "redox")]
pub mod redox;
#[cfg(any(
target_os = "linux",
target_os = "freebsd",
target_os = "dragonfly",
target_os = "netbsd",
target_os = "openbsd"
))]
pub mod unix;
#[cfg(target_os = "windows")]
pub mod windows;

View file

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

File diff suppressed because it is too large Load diff

View file

@ -178,9 +178,7 @@ impl DisplayInfo {
fn load_cursor(&mut self, name: &'static str) -> xlib::Cursor {
let name = CString::new(name).expect("static data");
unsafe {
(self.cursor_lib.XcursorLibraryLoadCursor)(self.display, name.as_ptr())
}
unsafe { (self.cursor_lib.XcursorLibraryLoadCursor)(self.display, name.as_ptr()) }
}
fn init_atoms(&mut self) {
@ -259,7 +257,8 @@ impl Window {
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 height = height * scale;
@ -274,8 +273,16 @@ impl Window {
attributes.backing_store = xlib::NotUseful;
let x = if d.screen_width > width { (d.screen_width - width) / 2 } else { 0 };
let y = if d.screen_height > height { (d.screen_height - height) / 2 } else { 0 };
let x = if d.screen_width > width {
(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)(
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;
draw_buffer.resize(width * height, 0);
@ -550,7 +562,13 @@ impl Window {
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 {
Scale::X1 => 1,
Scale::X2 => 2,
@ -743,7 +761,9 @@ impl Window {
&self.d,
cast::usize(self.width),
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!(
scale_2x, 2,
scale_4x, 4,
scale_8x, 8,
scale_16x, 16,
scale_32x, 32,
);
gen_scale_x!(scale_2x, 2, scale_4x, 4, scale_8x, 8, scale_16x, 16, scale_32x, 32,);
impl Drop for Window {
fn drop(&mut self) {

View file

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