Struct minifb::Window

source ·
pub struct Window(_);
Expand description

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.

Implementations§

source§

impl Window

source

pub fn new( name: &str, width: usize, height: usize, opts: WindowOptions ) -> Result<Window>

Opens up a new window

Examples

Open up a window with default settings

let mut window = match Window::new("Test", 640, 400, WindowOptions::default()) {
   Ok(win) => win,
   Err(err) => {
       println!("Unable to create window {}", err);
       return;
   }
};

Open up a window that is resizeable

let mut window = Window::new("Test", 640, 400,
    WindowOptions {
       resize: true,
       ..WindowOptions::default()
 })
 .expect("Unable to open Window");
source

pub fn set_title(&mut self, title: &str)

Allows you to set a new title of the window after creation

Examples
let mut window = Window::new("Test", 640, 400, WindowOptions::default()).unwrap();

window.set_title("My New Title!");
source

pub fn set_icon(&mut self, icon: Icon)

Sets the icon of the window after creation.

The file path has to be relative to the current working directory.

Windows: Has to be a .ico file. To also set the icon of the .exe file, see the rc.exe tool

Linux:

  • X11: Needs a u64 buffer with ARGB data
  • Wayland: not implemented (use a .desktop file)

MacOS:

RedoxOS: not implemented

Examples
let mut window = Window::new("Test", 640, 400, WindowOptions::default()).unwrap();

#[cfg(target_os = "windows")]
window.set_icon(Icon::from_str("src/icon.ico").unwrap());
source

pub fn get_window_handle(&self) -> *mut c_void

Returns the native handle for a window which is an opaque pointer/handle which dependens on the current operating system:

Windows HWND
MacOS   NSWindow
X11     XWindow
source

pub fn update_with_buffer( &mut self, buffer: &[u32], width: usize, height: usize ) -> Result<()>

Updates the window with a 32-bit pixel buffer. The encoding for each pixel is 0RGB: The upper 8-bits are ignored, the next 8-bits are for the red channel, the next 8-bits afterwards for the green channel, and the lower 8-bits for the blue channel.

Notice that the buffer needs to be at least the size of the created window. Also only one of update_with_buffer or update should be called for updating a single window.

Examples
fn from_u8_rgb(r: u8, g: u8, b: u8) -> u32 {
    let (r, g, b) = (r as u32, g as u32, b as u32);
    (r << 16) | (g << 8) | b
}
let window_width = 600;
let window_height = 400;
let buffer_width = 600;
let buffer_height = 400;

let azure_blue = from_u8_rgb(0, 127, 255);

let mut buffer: Vec<u32> = vec![azure_blue; buffer_width * buffer_height];

let mut window = Window::new("Test", window_width, window_height, WindowOptions::default()).unwrap();

window.update_with_buffer(&buffer, buffer_width, buffer_height).unwrap();
source

pub fn update(&mut self)

Updates the window (this is required to call in order to get keyboard/mouse input, etc)

Notice that when using this function then update_with_buffer should not be called for the same window. Only one of the functions should be used.

Examples
let mut buffer: Vec<u32> = vec![0; 640 * 400];

let mut window = Window::new("Test", 640, 400, WindowOptions::default()).unwrap();

window.update();
source

pub fn is_open(&self) -> bool

Checks if the window is still open. A window can be closed by the user (by for example pressing the close button on the window) It’s up to the user to make sure that this is being checked and take action depending on the state.

Examples
while window.is_open() {
    // Update window
}
source

pub fn set_position(&mut self, x: isize, y: isize)

Sets the position of the window. This is useful if you have more than one window and want to align them up on the screen

Examples
// Moves the window to pixel position 20, 20 on the screen
window.set_position(20, 20);
source

pub fn get_position(&self) -> (isize, isize)

Gets the position of the window. This is useful if you want to store the position of the window across sessions

Examples
// Retrieves the current window position
let (x,y) = window.get_position();
source

pub fn topmost(&self, topmost: bool)

Makes the window the topmost window and makes it stay always on top. This is useful if you want the window to float above all over windows

Examples
// Makes the window always on top
window.topmost(true);
source

pub fn set_background_color(&mut self, red: usize, green: usize, blue: usize)

Sets the background color that is used with update_with_buffer. In some cases there will be a blank area around the buffer depending on the ScaleMode that has been set. This color will be used in the in that area. The function takes 3 parameters in (red, green, blue) and each value is in the range of 0-255 where 255 is the brightest value

Examples
// Set background color to bright red
window.set_background_color(255, 0, 0);
source

pub fn set_cursor_visibility(&mut self, visibility: bool)

Changes whether or not the cursor image should be shown or if the cursor image should be invisible inside the window When creating a new window the default is ‘false’

source

pub fn limit_update_rate(&mut self, time: Option<Duration>)

Limits the update rate of polling for new events in order to reduce CPU usage. The problem of having a tight loop that does something like this

loop {
   window.update();
}

Is that lots of CPU time will be spent calling system functions to check for new events in a tight loop making the CPU time go up. Using limit_update_rate minifb will check how much time has passed since the last time and if it’s less than the selected time it will sleep for the remainder of it. This means that if more time has spent than the set time (external code taking longer) minifb will not do any waiting at all so there is no loss in CPU performance with this feature. By default it’s set to 4 milliseconds. Setting this value to None and no waiting will be done

Examples
// Make sure that at least 4 ms has passed since the last event poll
window.limit_update_rate(Some(std::time::Duration::from_millis(4)));
source

pub fn get_size(&self) -> (usize, usize)

Returns the current size of the window

Examples
let size = window.get_size();
println!("width {} height {}", size.0, size.1);
source

pub fn get_mouse_pos(&self, mode: MouseMode) -> Option<(f32, f32)>

Get the current position of the mouse relative to the current window The coordinate system is as 0, 0 as the upper left corner

Examples
window.get_mouse_pos(MouseMode::Clamp).map(|mouse| {
    println!("x {} y {}", mouse.0, mouse.1);
});
source

pub fn get_unscaled_mouse_pos(&self, mode: MouseMode) -> Option<(f32, f32)>

Get the current position of the mouse relative to the current window The coordinate system is as 0, 0 as the upper left corner and ignores any scaling set to the window.

Examples
window.get_unscaled_mouse_pos(MouseMode::Clamp).map(|mouse| {
    println!("x {} y {}", mouse.0, mouse.1);
});
source

pub fn get_mouse_down(&self, button: MouseButton) -> bool

Check if a mouse button is down or not

Examples
let left_down = window.get_mouse_down(MouseButton::Left);
println!("is left down? {}", left_down)
source

pub fn get_scroll_wheel(&self) -> Option<(f32, f32)>

Get the current movement of the scroll wheel. Scroll wheel can mean different thing depending on the device attach. For example on Mac with trackpad “scroll wheel” means two finger swiping up/down (y axis) and to the sides (x-axis) When using a mouse this assumes the scroll wheel which often is only y direction.

Examples
window.get_scroll_wheel().map(|scroll| {
    println!("scrolling - x {} y {}", scroll.0, scroll.1);
});
source

pub fn set_cursor_style(&mut self, cursor: CursorStyle)

Set a different cursor style. This can be used if you have resizing elements or something like that

Examples
window.set_cursor_style(CursorStyle::ResizeLeftRight);
source

pub fn get_keys(&self) -> Vec<Key>

Get the current keys that are down.

Examples
window.get_keys().iter().for_each(|key|
        match key {
            Key::W => println!("holding w"),
            Key::T => println!("holding t"),
            _ => (),
        }
    );
source

pub fn get_keys_pressed(&self, repeat: KeyRepeat) -> Vec<Key>

Get the current pressed keys. Repeat can be used to control if keys should be repeated if down or not.

Examples
window.get_keys_pressed(KeyRepeat::No).iter().for_each(|key|
        match key {
            Key::W => println!("pressed w"),
            Key::T => println!("pressed t"),
            _ => (),
        }
    );
source

pub fn get_keys_released(&self) -> Vec<Key>

Get the current released keys.

Examples
window.get_keys_released().iter().for_each(|key|
        match key {
            Key::W => println!("released w"),
            Key::T => println!("released t"),
            _ => (),
        }
    );
source

pub fn is_key_down(&self, key: Key) -> bool

Check if a single key is down.

Examples
if window.is_key_down(Key::A) {
    println!("Key A is down");
}
source

pub fn is_key_pressed(&self, key: Key, repeat: KeyRepeat) -> bool

Check if a single key is pressed. KeyRepeat will control if the key should be repeated or not while being pressed.

Examples
if window.is_key_pressed(Key::A, KeyRepeat::No) {
    println!("Key A is down");
}
source

pub fn is_key_released(&self, key: Key) -> bool

Check if a single key was released since last call to update.

source

pub fn set_key_repeat_delay(&mut self, delay: f32)

Sets the delay for when a key is being held before it starts being repeated the default value is 0.25 sec

Examples
window.set_key_repeat_delay(0.5) // 0.5 sec before repeat starts
source

pub fn set_key_repeat_rate(&mut self, rate: f32)

Sets the rate in between when the keys has passed the initial repeat_delay. The default value is 0.05 sec

Examples
window.set_key_repeat_rate(0.01) // 0.01 sec between keys
source

pub fn is_active(&mut self) -> bool

Returns if this windows is the current active one

source

pub fn set_input_callback(&mut self, callback: Box<dyn InputCallback>)

Set input callback to recive callback on char input

source

pub fn add_menu(&mut self, menu: &Menu) -> MenuHandle

This allows adding menus to your windows. As menus behaves a bit diffrently depending on Operating system here is how it works.

Windows:
  Each window has their own menu and shortcuts are active depending on active window.
Mac:
  As Mac uses one menu for the whole program the menu will change depending
  on which window you have active.
Linux/BSD/etc:
  Menus aren't supported as they depend on each WindowManager and is outside of the
  scope for this library to support. Use [get_posix_menus] to get a structure
source

pub fn remove_menu(&mut self, handle: MenuHandle)

Remove a menu that has been added with [#add_menu]

source

pub fn get_posix_menus(&self) -> Option<&Vec<UnixMenu>>

source

pub fn get_unix_menus(&self) -> Option<&Vec<UnixMenu>>

👎Deprecated since 0.17.0: get_unix_menus will be removed in 1.0.0, use get_posix_menus instead
source

pub fn is_menu_pressed(&mut self) -> Option<usize>

Check if a menu item has been pressed

Trait Implementations§

source§

impl Debug for Window

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl HasRawWindowHandle for Window

Auto Trait Implementations§

§

impl !RefUnwindSafe for Window

§

impl !Send for Window

§

impl !Sync for Window

§

impl Unpin for Window

§

impl !UnwindSafe for Window

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

const: unstable · source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

const: unstable · source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

const: unstable · source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for Twhere U: From<T>,

const: unstable · source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
const: unstable · source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
const: unstable · source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.