Cross platfrom window and framebuffer crate for Rust

Overview

Build Status Crates.io Documentation

minifb is a cross platform library written in Rust and that makes it easy to setup a window and to (optional) display a 32-bit pixel buffer. It also makes it easy to get input from keyboard and mouse. Notice that minifb is primary designed for prototyping and may not include all the features found in full window handling libraries. An example is the best way to show how it works:

Changelog

Usage

# Cargo.toml
[dependencies]
minifb = "0.23"

Example

extern crate minifb;

use minifb::{Key, Window, WindowOptions};

const WIDTH: usize = 640;
const HEIGHT: usize = 360;

fn main() {
    let mut buffer: Vec<u32> = vec![0; WIDTH * HEIGHT];

    let mut window = Window::new(
        "Test - ESC to exit",
        WIDTH,
        HEIGHT,
        WindowOptions::default(),
    )
    .unwrap_or_else(|e| {
        panic!("{}", e);
    });

    // Limit to max ~60 fps update rate
    window.limit_update_rate(Some(std::time::Duration::from_micros(16600)));

    while window.is_open() && !window.is_key_down(Key::Escape) {
        for i in buffer.iter_mut() {
            *i = 0; // write something more funny here!
        }

        // We unwrap here as we want this code to exit if it fails. Real applications may want to handle this in a different way
        window
            .update_with_buffer(&buffer, WIDTH, HEIGHT)
            .unwrap();
    }
}

Status

Currently macOS, Linux and Windows (64-bit and 32-bit) are the current supported platforms. X11 (Linux/FreeBSD/etc) support has been tested on Ubuntu (x64). Linux Wayland support is also available. Bug report(s) for other OSes/CPUs are welcome! Notice: That after 0.13 Redox hasn't been updated and some work is required to get that working again. PR are welcome.

Build instructions

On Linux you may need to install these dependencies first:

sudo apt install libxkbcommon-dev libwayland-cursor0 libwayland-dev
cargo build
cargo run --example noise

This will run the noise example

License

Licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Comments
  • [WIP] Wayland support

    [WIP] Wayland support

    Implemented:

    • [x] new()

    • [x] set_title()

    • [x] set_background_color() saves only the color - does currently nothing

    • [x] is_open()

    • [x] get_size()

    • [x] get_keys()

    • [x] get_keys_pressed()

    • [x] get_mouse_pos()

    • [x] get_mouse_down()

    • [x] get_unscaled_mouse_pos()

    • [x] get_scroll_wheel()

    • [x] is_key_down()

    • [x] set_position()

    • [x] set_rate()

    • [x] set_key_repeat_rate()

    • [x] set_key_repeat_delay()

    • [x] is_key_pressed()

    • [x] is_key_released()

    • [x] update_rate()

    • [x] is_active() - keyboard or mouse or both?

    • [x] update()

    • [x] update_with_buffer_stride()

    • [x] set_cursor_style()

    • [x] set_input_callback()

    • [x] all menu functions

    BUGS:

    • keyboard input doesn't work anymore when switching between Wayland and X11 session(Sway specific/wlroots(see: https://github.com/swaywm/sway/issues/3244))
    opened by nifker 72
  • Segfault on arm using nightly rust 1.6

    Segfault on arm using nightly rust 1.6

    Continuing from https://github.com/emoon/minifb/issues/2, here's the backtrace after the s.as_ptr() as *const _ hack:

    Starting program: /tmp/rust64-master/target/debug/rust64
    Program received signal SIGSEGV, Segmentation fault.
    0x7f57cc4c in mfb_update (buffer=0xb6458000) at src/native/x11/X11MiniFB.c:128
    128             s_ximage->data = (char*)buffer;
    (gdb) bt
    #0  0x7f57cc4c in mfb_update (buffer=0xb6458000) at src/native/x11/X11MiniFB.c:128
    #1  0x7f57c6f8 in minifb::update (buffer=...)
        at /home/odroid/.cargo/git/checkouts/rust_minifb-65b6a7c68ef60bd2/master/src/lib.rs:53
    #2  0x7f55ff88 in rust64::c64::C64::render (self=0xbeffec78) at src/c64/mod.rs:89
    #3  0x7f55cb38 in rust64::main () at src/main.rs:68
    #4  0x7f586874 in sys_common::unwind::try::try_fn::h3067093340196622558 ()
    #5  0x7f583c80 in __rust_try ()
    #6  0x7f5863e0 in rt::lang_start::h6fedeacd81917c3471x ()
    #7  0x7f560034 in main () at src/c64/mod.rs:90
    
    opened by MagaTailor 33
  • WASM support

    WASM support

    Would it fit the project to add a WebAssembly target?

    • Creating a simple HTML5 canvas object and then copying the buffer of pixels every frame to JavaScript and sending the events back. Or it could be done using ImageData.
    • Scaling could be implemented like this.
    • A example for keyboard input is shown here.
    • The menus could be a problem but that could be fixed with custom buttons in JavaScript.

    I would love to help with developing/testing this if it fits your vision of the project!

    opened by tversteeg 27
  • Resize issue

    Resize issue

    If I resize the window the frame buffer is not drawn correctly. After resize the pixels are shifted. If I draw the buffer to an png it looks correct. I've read in the documentation there is an issue with resize and u32 buffers.

    What could I do to fix this behavior?

    opened by FloVanGH 26
  • On Windows, buffers larger than the window cause weird artifacts and look horrible

    On Windows, buffers larger than the window cause weird artifacts and look horrible

    At least on Windows, displaying a buffer larger than the size of the window causes weird artifacts.

    My ray tracer is a good example of this, and is how the bug was discovered.

    At 1x resolution:

    image

    At 2x resolution:

    image

    My friends with real Windows machines originally reported this bug to me, then I confirmed that it also happens in Wine, so I think the problem is minifb.

    opened by LoganDark 20
  • crash when resizing window

    crash when resizing window

    crate version: 0.13.0

    Sometimes when I resize, the application crashes, reporting that the buffer size does not match the window size. I tried to test various starting sizes and also various magnitudes, directions, and speeds of resizing and perhaps the speed of resizing matters but I can’t be sure.

    This is reproducible in Linux, macOS and Windows using the menu example:

    thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: UpdateFailed("Update failed because input buffer is too small. Required size for 1088 x 998 window (2x scale) is 1085824 bytes but the size of the input buffer has the size 921600 bytes")', src\libcore\result.rs:1084:5
    note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace.
    error: process didn't exit successfully: `target\release\examples\menu.exe` (exit code: 101)
    

    Interestingly, I also tried this on Linux in a VM and while I can reproduce the crash with a VM having a display size of 1280x1024, I cannot reproduce this when resizing the window within the confines of a display of 1024x768.

    opened by ghost 16
  • Scaling not working on XWayland.

    Scaling not working on XWayland.

    Hi. Currently on an X11 system but I'll try to get more details for you later.

    The minifb::Scale option appears to have no effect on Wayland. I also seem to remember seeing an info message saying that only minifb::Scale::X8 and lower is supported. The window starts extremely small.

    I believe the system I had the issue on was running Fedora 27, which uses XWayland.

    opened by cedws 15
  • Reduce dependencies

    Reduce dependencies

    Currently when building for Linux one get a dependency list like this

      Compiling libc v0.2.74
       Compiling cfg-if v0.1.10
       Compiling proc-macro2 v1.0.19
       Compiling unicode-xid v0.2.1
       Compiling memchr v2.3.3
       Compiling pkg-config v0.3.18
       Compiling bitflags v1.2.1
       Compiling version_check v0.9.2
       Compiling lazy_static v1.4.0
       Compiling glob v0.3.0
       Compiling log v0.4.13
       Compiling xml-rs v0.8.3
       Compiling unicode-width v0.1.8
       Compiling regex-syntax v0.6.22
       Compiling cfg-if v1.0.0
       Compiling termcolor v1.1.2
       Compiling humantime v2.1.0
       Compiling bindgen v0.56.0
       Compiling strsim v0.8.0
       Compiling nix v0.17.0
       Compiling getrandom v0.1.14
       Compiling ansi_term v0.11.0
       Compiling vec_map v0.8.2
       Compiling rustc-hash v1.1.0
       Compiling peeking_take_while v0.1.2
       Compiling void v1.0.2
       Compiling lazycell v1.3.0
       Compiling shlex v0.1.1
       Compiling smallvec v1.4.2
       Compiling once_cell v1.4.0
       Compiling ppv-lite86 v0.2.8
       Compiling maybe-uninit v2.0.0
       Compiling byteorder v1.3.4
       Compiling downcast-rs v1.2.0
       Compiling cc v1.0.58
       Compiling crc32fast v1.2.0
       Compiling adler32 v1.2.0
       Compiling remove_dir_all v0.5.3
       Compiling libloading v0.6.7
       Compiling textwrap v0.11.0
       Compiling thread_local v1.1.0
       Compiling miniz_oxide v0.3.7
       Compiling nom v5.1.2
       Compiling clang-sys v1.0.3
       Compiling wayland-sys v0.27.0
       Compiling x11-dl v2.18.5
       Compiling aho-corasick v0.7.15
       Compiling deflate v0.8.6
       Compiling quote v1.0.7
       Compiling minifb v0.19.2 (/home/emoon/code/projects/rust_minifb)
       Compiling wayland-scanner v0.27.0
       Compiling png v0.16.7
       Compiling atty v0.2.14
       Compiling which v3.1.1
       Compiling raw-window-handle v0.3.3
       Compiling clap v2.33.3
       Compiling rand_core v0.5.1
       Compiling wayland-client v0.27.0
       Compiling wayland-protocols v0.27.0
       Compiling rand_chacha v0.2.2
       Compiling regex v1.4.3
       Compiling cexpr v0.4.0
       Compiling xcursor v0.3.2
       Compiling rand v0.7.3
       Compiling tempfile v3.1.0
       Compiling env_logger v0.8.2
       Compiling wayland-commons v0.27.0
       Compiling wayland-cursor v0.27.0
       Compiling xkbcommon-sys v0.7.5
       Compiling xkb v0.2.1
    

    Which is WAY too much stuff being dragged in... like clang-sys This needs to be fixed

    opened by emoon 13
  • Is it possible to get data out of the InputCallback?

    Is it possible to get data out of the InputCallback?

    Is there an example explaining how to get data from an InputCallback-implementing struct into the main() function? I want to create a mutable buffer containing all of the key presses from the user which is accessible from the main() function.

    opened by shraiwi 13
  • is_key_down misses key down + lag after letting key go

    is_key_down misses key down + lag after letting key go

    Thanks a lot for this library, it's a joy to use!

    Running the below example and holding down the space key for a longer time (3 seconds+) will result in odd behavior. The space! and nothing! prints will "alternate", even though the space key is pressed all the time. Furthermore after letting the space key go, it takes a while till space! is not printed anymore. The key down detection lags behind.

    I couldn't find anything wrong with my code but maybe I am missing something?

    I am on Ubuntu 20.04, using X11 and rustc 1.59 with minifb 0.20.0.

    use minifb::{Key, Window, WindowOptions};
    
    fn main() {
        let mut window = Window::new("Test", 500, 500, WindowOptions::default()).unwrap();
    
        window.limit_update_rate(Some(std::time::Duration::from_millis(16)));
        while window.is_open() {
            if window.is_key_down(Key::Space) {
                println!("space!");
            } else {
                println!("nothing!");
            }
    
            window.update();
        }
    }
    
    

    Alternating behavior:

    space!
    space!
    space!
    space!
    space!
    space!
    space!
    space!
    space!
    space!
    space!
    space!
    space!
    space!
    nothing!
    nothing!
    space!
    space!
    nothing!
    nothing!
    space!
    space!
    nothing!
    nothing!
    space!
    nothing!
    nothing!
    space!
    space!
    nothing!
    nothing!
    space!
    space!
    nothing!
    nothing!
    
    x11 
    opened by TJB-99 12
  • compile error on ARM 32 / 64bit

    compile error on ARM 32 / 64bit

    I try to use minifb on ARM (pi zero 32bit raspberrypiOS arm-linux-gnueabihf / allwinner a64 64bit armbian stable-aarch64-linux-gnu). I tried both current rust stable as well as nightly. Compiling the same git revision with the same toolchain version on 64bit AMD 64 works fine.

    The error is

    error[E0308]: mismatched types --> src/os/posix/x11.rs:424:52 | 424 | (d.lib.XInternAtom)(d.display, "_MOTIF_WM_HINTS\0" as *const _ as *const i8, 0); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected u8, found i8 | = note: expected raw pointer *const u8 found raw pointer *const i8

    I'm actually not sure if this is a rust bug or minifb bug. As both, i8 and u8 have a platform independent size it should not matter, should it?

    opened by derpeter 12
  • Extended documentation / examples

    Extended documentation / examples

    Love the crate, busy using it for some visualization work for strange attractors. Just want to see if @emoon is open to me adding to the documentation / examples or if there's a particular style they want for them?

    I see there are some example scripts, but was thinking about adding references to them so they're more discoverable and adding some more in-line examples to the docs.

    If this would be appreciated then I'll get started on it.

    opened by beyarkay 3
  • Option to embed icon file in windows should be available

    Option to embed icon file in windows should be available

    Currently, icon file is loaded from the path. If the icon file is renamed or moved, it is gone. The option to embed icon (like that of Linux) should be available.

    help wanted windows 
    opened by arnabanimesh 1
  • Server side decorations under Gnome Wayland

    Server side decorations under Gnome Wayland

    Similar to this issue #224, I am experiencing the same thing. Now in that issue it says it is Gnome's fault and upon reading up on that, that does seem to be the case. But will there ever be a way to use this library under Gnome Wayland?

    Right now, this makes this library not really usable on say Manjaro Linux with Gnome. I get the warning: Failed to create server-side surface decoration: Missing and a borderless window with an invisible cursor that only updates when the cursor is moved.

    help wanted 
    opened by xkevio 5
  • RUSTSEC-2021-0119

    RUSTSEC-2021-0119

    It seems as if you guys use an older version of wayland-rs that itself uses an older version of nix

    I have looked into it and have tried to upgrade the version of wayland-rs used in this crate but some types went missing and this requires a bit more work than I expected, Would you guys accept to merge an alpha version of a crate (v0.30.0-alpha3) ?

    opened by InfRandomness 2
  • Support for pixel formats with an alpha channel

    Support for pixel formats with an alpha channel

    Hello,

    I am wondering if supporting pixel formats other than 0RGB would be out of the scope of this library. I am currently using this library to prototype something that requires support for an alpha channel, and having this available in the windowing library would be very useful.

    I see discussion about this in https://github.com/emoon/rust_minifb/issues/101, but would like to clarify thoughts here. Would you be open to a PR implementing this for POSIX?

    I think the ideal API would be to have the format specifiable in minifb::WindowOptions, but that would be a breaking change. Do you have other thoughts for how/where this should be implemented?

    opened by connorskees 2
Owner
Daniel Collin
Demoscener in TBL. Does Rust at home and work at Unity Technologies.
Daniel Collin
skyWM is an extensible tiling window manager written in Rust. skyWM has a clear and distinct focus adhering to the KISS and Unix philosophy.

Please note: skyWM is currently in heavy development and is not usable as of yet. Documentation and versions will change quickly. skyWM skyWM is an ex

MrBeeBenson 74 Dec 28, 2022
A library that creates a terminal-like window with feature-packed drawing of text and easy input handling. MIRROR.

BearLibTerminal provides a pseudoterminal window with a grid of character cells and a simple yet powerful API for flexible textual output and uncompli

Tommy Ettinger 43 Oct 31, 2022
A fully modular window manager, extremely extensibile and easily approachable.

AquariWM is a fully modular window manager, allowing extreme extensibility while remaining easily approachable. Installation AquariWM is currently in

AquariWM Window Manager 8 Nov 14, 2022
A collection of tools for i3 that assist in window, workspace and output operations.

i3-valet A collection of tools for i3 that assist in window, workspace and output operations. i3-valet can be run directly from the command line or as

Erich Heine 15 Jan 8, 2023
A minimal window context for Rust on Windows.

winctx A minimal window context for Rust on Windows. I read msdn so you don't have to. This crate provides a minimalistic method for setting up and ru

John-John Tedro 19 Dec 25, 2023
My Window Manager

mwm My window manager that is a work in progress. Currently hacky Installation Clone this repo then: cargo build --release Put the binary in your pat

Monroe Clinton 5 Dec 14, 2022
Use raw-window-handle 0.5 with crates that depend on 0.4.

OldHasRawWindowHandleWrapper Wrap any type that implements HasRawWindowHandle and HasRawDisplayHandle from raw-window-handle 0.5 in OldHasRawWindowHan

null 1 Nov 25, 2022
An i3/Sway utility to switch focus to your last focused window. Alt+Tab in i3

i3-back An i3/Sway utility to switch focus to your last focused window. Allows for behavior similar to Alt+Tab on other desktop environments. Features

Charles C 17 Mar 13, 2023
[PoC] An all-in-one preview window for the furries

previuwu An all-in-one preview window for the furries. Uses egui to render the preview window. STATUS: Proof of Concept ( ⚠️ heavy work in progress).

Arijit Basu 9 Feb 10, 2023
Customize window border colors :3

cute-borders Makes focused and unfocused window borders have a different border color, configurable per program. Windows 11 only. Preview Installing D

Elaina 6 Aug 16, 2023
A monitor (service) for your monitor (display). Intercepts window behaviour when monitor configuration changes.

Mon-Mon A monitor (service) for your monitor (display). Listens for changes to display configuration (e.g. plugging in an additional screen) and allow

dan 5 Sep 29, 2023
Efficient scan conversion of a line segment with clipping to a rectangular window.

✂️ clipline ?? clipline is a Rust crate for efficient scan conversion of a line segment with clipping to a rectangular window. It is an implementation

Nurzhan Sakén 5 Oct 26, 2023
WIP: A program for switching Dygma layouts based on window name or exe name.

Dygma Layer Switcher Config On the first run of dygma-layer-switcher the config.yml will be generated. --- # Toggle logging. logging: false # Port of

Matthew Wilding 5 Nov 11, 2023
Rust-battery - Rust crate providing cross-platform information about the notebook batteries.

battery Rust crate providing cross-platform information about the notebook batteries. Table of contents Overview Supported platforms Install Examples

svartalf 326 Dec 21, 2022
Cross-platform Rust library for coloring and formatting terminal output

Coloring terminal output Documentation term-painter is a cross-platform (i.e. also non-ANSI terminals) Rust library for coloring and formatting termin

Lukas Kalbertodt 75 Jul 28, 2022
Write Cross-platform application with React-like decralative UI framework and scalable ECS architecture all in Rust.

bevy_dioxus Dioxus Plugin for Bevy Write Cross-platform application with React-like decralative UI framework and scalable ECS architecture all in Rust

Junichi Sugiura 269 Dec 29, 2022
Rust-based language and runtime for cross-platform app development

Pax Pax is a cross-platform rendering engine & Rust framework for interactive graphics, animations, and GUIs. Pax extends the Rust programming languag

Pax 75 Dec 19, 2022
A cross-platofrm desktop app to manage your ports made with Dioxus and Rust.

Port Manager A cross-platofrm desktop app to manage your ports made with Dioxus and Rust. This app has been tested only on macOS. Test on other platfo

Muideen 3 Mar 30, 2024
A cross-platform graphical process/system monitor with a customizable interface and a multitude of features

A cross-platform graphical process/system monitor with a customizable interface and a multitude of features. Supports Linux, macOS, and Windows. Inspired by both gtop and gotop.

Clement Tsang 5.8k Jan 8, 2023