├── .github ├── dependabot.yml └── workflows │ └── ci.yml ├── .gitignore ├── CHANGELOG.md ├── Cargo.toml ├── LICENSE ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── Web.toml ├── build.rs ├── examples ├── char_callback.rs ├── drop.rs ├── fractal.rs ├── icon.rs ├── image.rs ├── menu.rs ├── mouse.rs ├── multi.rs ├── noise.rs ├── resources │ ├── icon256.ico │ ├── planet.png │ └── uv.png ├── text.rs ├── title_cursor.rs ├── topmost.rs ├── transparent.rs └── wasm.rs └── src ├── error.rs ├── icon.rs ├── key.rs ├── key_handler.rs ├── lib.rs ├── native ├── macosx │ ├── MacMiniFB.m │ ├── OSXWindow.h │ ├── OSXWindow.m │ ├── OSXWindowFrameView.h │ ├── OSXWindowFrameView.m │ └── shared_data.h └── posix │ └── scalar.c ├── os ├── macos │ └── mod.rs ├── mod.rs ├── posix │ ├── common.rs │ ├── mod.rs │ ├── wayland.rs │ ├── x11.rs │ ├── xkb_ffi.rs │ └── xkb_keysyms.rs ├── redox │ └── mod.rs ├── wasm │ ├── keycodes.rs │ └── mod.rs └── windows │ └── mod.rs └── rate.rs /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: cargo 4 | directory: "/" 5 | schedule: 6 | interval: daily 7 | time: "04:00" 8 | open-pull-requests-limit: 10 9 | ignore: 10 | - dependency-name: wayland-client 11 | versions: 12 | - 0.28.0 13 | - dependency-name: wayland-protocols 14 | versions: 15 | - 0.28.0 16 | - dependency-name: wayland-cursor 17 | versions: 18 | - 0.28.0 19 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | on: [push, pull_request] 2 | 3 | name: CI 4 | 5 | jobs: 6 | fmt: 7 | runs-on: ubuntu-latest 8 | # Steps represent a sequence of tasks that will be executed as part of the job. 9 | steps: 10 | - name: Checkout Repository 11 | uses: actions/checkout@v3 12 | 13 | - name: Setup Rust 14 | uses: actions-rs/toolchain@v1 15 | with: 16 | toolchain: stable 17 | profile: minimal 18 | components: rustfmt 19 | override: true 20 | 21 | - name: Check Format 22 | run: cargo fmt -- --check 23 | 24 | build_and_test: 25 | name: Test 26 | strategy: 27 | matrix: 28 | os: [ubuntu-latest, windows-latest, macOS-latest] 29 | runs-on: ${{ matrix.os }} 30 | steps: 31 | - if: matrix.os == 'ubuntu-latest' 32 | run: sudo apt install libwayland-cursor0 libxkbcommon-dev libwayland-dev 33 | - uses: actions/checkout@v2 34 | - name: Build 35 | run: cargo build --verbose 36 | - name: Run tests 37 | run: cargo test --verbose 38 | - name: Install wasm target 39 | run: rustup target add wasm32-unknown-unknown 40 | - name: Check wasm build 41 | run: cargo check --target wasm32-unknown-unknown --no-default-features 42 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | Cargo.lock 3 | *.idea 4 | *.iml 5 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | This project follows semantic versioning. 4 | 5 | ### v0.28 (2025-01-20) 6 | 7 | - [fixed] raw window handle and related fixes to get wgpu working. (Thanks Wumpf!) 8 | - [fixed] Various example fixes. 9 | - [fixed] Various WASM improvements. (Thanks augustkline!) 10 | - [fixed] Various changelog and doc fixes. (Thanks Chubercik!) 11 | 12 | ### v0.27 (2024-05-20) 13 | 14 | - [fixed] Temporary fix for struct layout issue on Windows. 15 | 16 | ### v0.26 (2024-05-11) 17 | 18 | - [fixed] Lots of formatting & style fixes (Thanks Stefano Incardone!) 19 | - [fixed] raw-window-handle 0.6 (Thanks Stefano Incardone!) 20 | - [fixed] Lots of various fixes and cleanups (Thanks Stefano Incardone!) 21 | - [fixed] repr(C) on Window Struct (Thanks gillet-hernadez!) 22 | - [fixed] Switch Linux scalar code from C++ to C (Thanks Speykious!) 23 | - [API BREAKAGE] `limit_update_rate` has been removed. Use `set_target_fps` instead. 24 | 25 | ### v0.25 (2023-08-02) 26 | 27 | - [fixed] Fix changing window title (Thanks royaltm!) 28 | 29 | ### v0.24 (2023-02-18) 30 | 31 | - [fixed] Windows: Unable to use F10 key 32 | - [fixed] set byposition flag when removing menus (Thanks piksel!) 33 | - [fixed] fixed compilation for x11 32-bit mode (Thanks HBehrens!) 34 | - [fixed] X11 window names not supporting UTF-8 (Thanks edarogh!) 35 | - [fixed] `get_window_position` for multiscreen setup on macOS (Thanks AnderasOM!) 36 | - [fixed] Using minifb on multiple threads under x11 works and doesn't crash (Thanks to konnorandrews for suggestion!) 37 | - [Added] ARM and AARCH64 Windows Support (Thanks smb123w64gb!) 38 | 39 | ### v0.23 (2022-04-19) 40 | 41 | - [fixed] wayland: Fix key character callback & Reduce wayland dependencies (Thanks vmedea!) 42 | - [fixed] Use coercion on types failing compilation on 64 bit raspbian bullseye (Thanks wtfuzz!) 43 | - [added] WASM support. Thanks dc740 and tversteeg! See https://github.com/dc740/minifb-async-examples for example. 44 | 45 | ### v0.22 (2022-03-27) 46 | 47 | - [fixed] Updated docs to make it a bit more clear that only one of `update_with_buffer` or `update` should be used for updating a window. 48 | 49 | ### v0.21 (2022-03-27) 50 | 51 | - [fixed] Holding down a key on x11 would no repeat correctly 52 | - [fixed] Windows dependency cleanups (Thanks Arnab Animesh Das!) 53 | - [fixed] Fixed mouse button being "stuck" when moved out side of window, released and then moved by in on Windows (Thanks Arnab Animesh Das for bug report!) 54 | - [fixed] Memory-map the keymap FD on Wayland to fix EOF error (Thanks Greg Depoire--Ferrer!) 55 | - [added] getter for window position (Thanks Andreas Neukoetter!) 56 | - [fixed] Fix clippy lints under windows (Thanks Kevin K!) 57 | - [added] Add `set_icon()` method to set a window icon at runtime (Thanks Kevin K!) 58 | - [added] inputcallback: add a callback for key events and key_handler: add a callback for key events (Thanks xobs and vemoo!) 59 | - [fixed] macOS: Fix segmentation fault when resizing window. (Thanks KaDiWa!) 60 | - [fixed] Various x11 and wayland fixes, version updates (Thanks vemoo!) 61 | 62 | ### v0.20 (2021-11-28) 63 | 64 | - [API BREAKAGE] Changing return types of get_keys from Option> to Vec (Thanks Zij-IT!) 65 | - [fixed] get_scroll_wheel() would get "stuck" on macOS. (Thanks NikoUY for bug report!) 66 | 67 | ### v0.19.3 (2021-03-23) 68 | 69 | - [fixed] Fixed typos in description (Thanks hiqua!) 70 | - [fixed] update wayland to 0.28 and small cleanup (Thanks xMAC94x!) 71 | - [fixed] Bump xkbcommon-sys to 0.7.5 72 | - [fixed] wayland missing cursor (Thanks dc740!) 73 | - [fixed] windows: use c_void from winapi (Thanks xobs!) 74 | 75 | ### v0.19.2 (2021-01-18) 76 | 77 | TODO 78 | 79 | ### v0.19 (2020-09-22) 80 | 81 | - [fixed] Removed dummy logging 82 | 83 | ### v0.19 (2020-09-16) 84 | 85 | - [added] Added char_callback example on how to capture data. 86 | - [added] Support for topmost on Windows (Thanks phillvancejr!) 87 | - [fixed] ARM (Raspberry Pi) now builds and runs. (Thanks derpeter!) 88 | - [changed] Removed a bunch of dependencies not needed anymore (Thanks RazrFalcon!) 89 | 90 | ### v0.18 (2020-08-14) 91 | 92 | - [fixed] get_released_keys wasn't working under Wayland. 93 | 94 | ### v0.17 (2020-07-09) 95 | 96 | - [changed] unix renamed to posix. (Thanks LoganDark) 97 | - [changed] bunch of Linux/x11 fixes by Luna Siena. Such as Transparency support, Borderless, Cursor Visibility. Thanks! 98 | - [changed] use `std::ptr::null_mut()` to Windows `PeekMessageW` it fix alt-tab stall on Window 7. Thanks lynnux for the report! 99 | - [added] Implemented std::error::Error for minifb::Error. (Thanks Christofer Nolander!) 100 | 101 | ### v0.16 (2020-04-05) 102 | 103 | - [added] Wayland support. (Big thanks to Luna Siena add this support with assistance by Cole Helbling!) 104 | - [added] Added `get_released_keys` (Thanks to Alex Melville!) 105 | - [added] Added Topmost/Always on Top functionality to macOS (Thanks phillvancejr!) 106 | - [fixed] Removed left over logging on macOS (Thanks phillvancejr!) 107 | 108 | ### v0.15.3 (2020-01-21) 109 | 110 | - [Added] On macOS NSView (MTKView) is supplied with raw_window_handle now 111 | 112 | ### v0.15.2 (2020-01-21) 113 | 114 | - [fixed] Fixed forever block on macOS when using `update` and not `update_with_buffer` 115 | 116 | ### v0.15.1 (2019-12-27) 117 | 118 | - [fixed] Fixed access to raw_window_handle() 119 | 120 | ### v0.15 (2019-12-16) 121 | 122 | - [API BREAKAGE] - `update_with_buffer` now always take width and height parameters. 123 | - [added] scale_mode in WindowOptions now allow for aspect correct scaling, center of non-scaled buffers and more. 124 | - [added] Added `limit_update_rate(..)` in order to reduce CPU usage and not hammer the native system calls. 125 | - [changed] x11 now uses C for it's scaling in software mode in order to always have opts on even in debug build. 126 | - [changed] Several fixes with rescaling on all platforms 127 | - [changed] on x11 some window mangers will resize a non-resizable windows and minifb handles this now correctly. 128 | - [fixed] Cursor was behaving bad on Windows. This has now been fixed 129 | - [known issues] There are some flickering and various issues when resizing on most platforms. PRs/ideas welcome for this. 130 | 131 | ### v0.14 (2019-12-03) 132 | 133 | - [changed] Deprecated update_with_buffer on favor of update_with_buffer_size. The idea is that a size in of the buffer will be more robust and allow for aspect scaling as well. 134 | - [changed] Improved macOS resizing support. 135 | - [changed] Better modifier handling on macOS. 136 | - [changed] Moved CI over to Github Actions 137 | - [changed] Formatted all code with rustfmt 138 | - [changed] Documentation improvments (Thanks Gary Guo & Arif Roktim!) 139 | - [fixed] 'attempt to subtract with overflow' bug (Thanks Venceslas!) 140 | - [fixed] Window close handling & missing Alt keys for X11 (Thanks Gary Guo!) 141 | - [added] Juila example added (Thanks mishazawa!) 142 | - [added] Add support for raspberry pi (Thanks Florian Blasius!) 143 | - [added] Added support for raw-window-handle trait 144 | 145 | ### v0.13 (2019-08-30) 146 | 147 | - [changed] unix: replaced scale functions with macro and added missing invocations (Thanks Johannes Stölp!) 148 | 149 | ### v0.12 (2019-07-21) 150 | 151 | - [changed] Linux/Unix backend rewritten in Rust (thanks Chris West!) 152 | - [changed] WinAPI updated to 0.3 (Thanks Richard Hozák!) 153 | - [changed] Bump orbclient to 0.3.20 on Redox, remove alpha handling hacks (Thanks Nagy Tibor!) 154 | 155 | ### v0.11.2 (2018-12-19) 156 | 157 | - [added] Window.is_key_released 158 | 159 | ### v0.11.1 (2018-11-13) 160 | 161 | - [fixed] Fixed bad window size in menu example 162 | 163 | ### v0.11 (2018-10-23) 164 | 165 | - [changed] macOS now uses Metal for rendering the buffer. 166 | 167 | ### v0.10.7 (2018-08-10) 168 | 169 | Thanks to Lukas Kalbertodt for these changes! 170 | 171 | - [added] Debug impls for public types 172 | - [fixed] Removed several `doc(hidden)` 173 | 174 | ### v0.10.6 (2018-05-18) 175 | 176 | - [added] Scale x16 and x32 added for Unix 177 | 178 | ### v0.10.5 (2018-05-05) 179 | 180 | - [added] Scale x8 added for Unix 181 | - [fixed] Auto scaling now works correct if scale up is >= screen size 182 | 183 | ### v0.10.4 (2018-01-08) 184 | 185 | - [fixed] Bumped kernel32 to 0.2.2 due to compile errors on Windows. Thanks to Thomas Versteeg for this fix. 186 | 187 | ### v0.10.1 (2017-08-15) 188 | 189 | - [fixed] Typo in the Redox implementation was fixed after changes in 0.10.0 190 | 191 | ### v0.10.0 (2017-08-11) 192 | 193 | - [changed] ```update_with_buffer``` Now make sures that input buffer will be large enough. As of this it now returns ```Result<>``` to indicate the status of the call. 194 | 195 | ### v0.9.2 (2017-07-31) 196 | 197 | - [fixed] Bumped x11-dll to 2.14 as it was causing issues on nightly. 198 | 199 | ### v0.9.1 (2017-04-02) 200 | 201 | - [fixed] Correct link to docs in Cargo.toml 202 | 203 | ### v0.9.0 (2016-08-02) 204 | 205 | - [added] ```get_unscaled_mouse_pos``` Can be used the get actual mouse pos on a scaled window 206 | 207 | ### v0.8.4 (2016-07-31) 208 | 209 | - [fixed] Mac: Fixed crash on large window sizes 210 | 211 | ### v0.8.3 (2016-07-29) 212 | 213 | - [fixed] Mac: "Plonk sound" when pressing keys 214 | - [fixed] Mac: incorrect size for ``get_size()`` 215 | 216 | ### v0.8.2 (2016-07-07) 217 | 218 | - [fixed] Fixed so keypad keys works on Linux 219 | 220 | ### v0.8.1 (2016-07-07) 221 | 222 | - [fixed] Character callback wouldn't get called on Mac and Linux 223 | - [fixed] Resize cursors on Windows was swapped 224 | 225 | ### v0.8.0 (2016-06-24) 226 | 227 | - [added] ```window.set_title``` Can now change title after creation 228 | - [added] ```window.set_cursor_style``` Can now change the style of the cursor with a number of (OS supported types) 229 | - [added] Added cursor_title example code to show the newly added features 230 | 231 | ### v0.7.1 (2016-05-27) 232 | 233 | - [fixed] Character callback wouldn't get called on Mac. 234 | 235 | ### v0.7.0 (2016-05-12) 236 | 237 | - [changed] - Fully rewrote the Menu API. See the documentation/menu example for the changes. 238 | - [added] - Added ```Window::get_unix_menus``` to get data access to menus on Linux/x11 239 | 240 | ### v0.6.0 (2016-05-01) 241 | 242 | - [added] added ```get_size()``` to retrive the size of the window. 243 | 244 | ### v0.5.2 (2016-04-29) 245 | 246 | - [fixed] On Mac shortcuts using F1-F12 wasn't working correctly. 247 | 248 | ### v0.5.1 (2016-04-25) 249 | 250 | - [fixed] ```get_window_handle``` would return an invalid value on Unix. Now fixed. 251 | 252 | ### v0.5.0 (2016-03-04) 253 | 254 | - [changed] - Proper Errors which uses ```std::Error``` as base. ```Window::new``` uses this but the API itself hasn't changed. 255 | - [added] - Menu support on Mac and Windows. See the Menu API functions [here](http://prodbg.com/minifb/minifb/struct.Window.html#method.add_menu) 256 | - [known issue] - ```remove_menu``` doesn't work on Windows [issue](https://github.com/emoon/rust_minifb/issues/16) 257 | - [known issue] - On Mac when running an application from terminal on has to switch to another application and back to get menu focus. [issue](https://github.com/emoon/rust_minifb/issues/17) 258 | 259 | ### v0.4.0 (2016-01-31) 260 | 261 | This release breaks some of the API by changing names and parameters to some functions. 262 | 263 | - [changed] ```Window::new(...)``` now takes WindowOptions struct to configure the creation of the Window. [doc](http://prodbg.com/minifb/minifb/struct.Window.html#method.new) 264 | - [changed] ```window.update()``` Doesn't take a buffer anymore. See ```window.update_with_buffer``` [doc](http://prodbg.com/minifb/minifb/struct.Window.html#method.update) 265 | - [added] ```window.update_with_buffer()``` Old update version that takes buffer as input parameter [doc](http://prodbg.com/minifb/minifb/struct.Window.html#method.update_with_buffer) 266 | - [added] ```window.get_window_handle()``` Returns the native handle (os dependant) [doc](http://prodbg.com/minifb/minifb/struct.Window.html#method.get_window_handle) 267 | 268 | ### v0.3.1 (2016-01-29) 269 | 270 | - [fixed] ```get_mouse_pos(Clamp)``` clamps to ```[(0, 0) - (width - 1, height - 1)]``` instead of ```(width, height)``` 271 | 272 | ### v0.3.0 (2016-01-29) 273 | 274 | This release adds support for mouse input. See the documentation and the examples for usage 275 | 276 | - [added] [get_mouse_pos](http://prodbg.com/minifb/minifb/struct.Window.html#method.get_mouse_pos) 277 | - [added] [get_mouse_down](http://prodbg.com/minifb/minifb/struct.Window.html#method.get_mouse_down) 278 | - [added] [get_scroll_wheel](http://prodbg.com/minifb/minifb/struct.Window.html#method.get_scroll_wheel) 279 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "minifb" 3 | version = "0.28.0" 4 | license = "MIT OR Apache-2.0" 5 | authors = ["Daniel Collin "] 6 | description = "Cross-platform window setup with optional bitmap rendering" 7 | keywords = ["windowing", "window", "framebuffer"] 8 | categories = ["rendering"] 9 | repository = "https://github.com/emoon/rust_minifb" 10 | documentation = "https://docs.rs/minifb/0.15/minifb" 11 | build = "build.rs" 12 | edition = "2018" 13 | readme = "README.md" 14 | 15 | exclude = ["examples/resources/"] 16 | 17 | [[example]] 18 | name = "wasm" 19 | crate-type = ["cdylib"] 20 | 21 | [badges] 22 | maintenance = { status = "actively-developed" } 23 | 24 | [dev-dependencies] 25 | png = "0.17" 26 | console_error_panic_hook = "0.1.7" 27 | web-sys = { version = "0.3.56", features = [ 28 | "Blob", 29 | "CanvasRenderingContext2d", 30 | "CssStyleDeclaration", 31 | "Document", 32 | "Element", 33 | "Gamepad", 34 | "GamepadButton", 35 | "GamepadEvent", 36 | "Headers", 37 | "HtmlCanvasElement", 38 | "HtmlImageElement", 39 | "ImageData", 40 | "Navigator", 41 | "Node", 42 | "Request", 43 | "RequestInit", 44 | "RequestMode", 45 | "Response", 46 | "Url", 47 | "Window", 48 | "console", 49 | 'KeyboardEvent', 50 | 'MouseEvent', 51 | ] } 52 | wasm-bindgen = { version = "0.2.79", features = ["serde-serialize"] } 53 | 54 | [build-dependencies] 55 | cc = "1.0" 56 | 57 | [dependencies] 58 | raw-window-handle = "0.6" 59 | 60 | [target.'cfg(windows)'.dependencies.winapi] 61 | version = "0.3.9" 62 | features = ["winuser", "wingdi", "libloaderapi", "errhandlingapi", "fileapi"] 63 | 64 | [features] 65 | default = ["wayland", "x11", "dlopen"] 66 | dlopen = ["wayland-client/dlopen"] 67 | x11 = ["x11-dl", "libc"] 68 | wayland = [ 69 | "dlib", 70 | "lazy_static", 71 | "libc", 72 | "tempfile", 73 | "wayland-client", 74 | "wayland-cursor", 75 | "wayland-protocols", 76 | ] 77 | 78 | [target.'cfg(not(any(target_os = "macos", target_os = "redox", windows, target_arch="wasm32")))'.dependencies] 79 | wayland-client = { version = "0.29", optional = true } 80 | wayland-protocols = { version = "0.29", features = [ 81 | "client", 82 | "unstable_protocols", 83 | ], optional = true } 84 | wayland-cursor = { version = "0.29", optional = true } 85 | tempfile = { version = "3.3", optional = true } 86 | x11-dl = { version = "2.19.1", optional = true } 87 | libc = { version = "0.2.107", optional = true } 88 | dlib = { version = "0.5", optional = true } 89 | lazy_static = { version = "1.0", optional = true } 90 | 91 | 92 | [target.x86_64-unknown-redox.dependencies] 93 | orbclient = "0.3.20" 94 | 95 | [target.'cfg(target_arch = "wasm32")'.dependencies] 96 | instant = { version = "0.1.12", features = ["wasm-bindgen", "inaccurate"] } 97 | js-sys = "0.3.56" 98 | wasm-bindgen-futures = "0.4.29" 99 | serde = { version = "1.0.136", features = ["derive"] } 100 | serde_derive = "1.0.123" 101 | futures = "0.3.12" 102 | console_error_panic_hook = "0.1.7" 103 | # The `web-sys` crate allows you to interact with the various browser APIs, 104 | # like the DOM. 105 | web-sys = { version = "0.3.56", features = [ 106 | "Blob", 107 | "CanvasRenderingContext2d", 108 | "CssStyleDeclaration", 109 | "Document", 110 | "Element", 111 | "Gamepad", 112 | "GamepadButton", 113 | "GamepadEvent", 114 | "Headers", 115 | "HtmlCanvasElement", 116 | "HtmlImageElement", 117 | "ImageData", 118 | "Navigator", 119 | "Node", 120 | "Request", 121 | "RequestInit", 122 | "RequestMode", 123 | "Response", 124 | "Url", 125 | "Window", 126 | "console", 127 | 'KeyboardEvent', 128 | 'MouseEvent', 129 | ] } 130 | # The `wasm-bindgen` crate provides the bare minimum functionality needed 131 | # to interact with JavaScript. 132 | wasm-bindgen = { version = "0.2.79", features = ["serde-serialize"] } 133 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2014 Daniel Collin 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2016 Daniel Collin 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://github.com/emoon/rust_minifb/workflows/CI/badge.svg)](https://github.com/emoon/rust_minifb/actions?workflow=CI) 2 | [![Crates.io](https://img.shields.io/crates/v/minifb.svg)](https://crates.io/crates/minifb) 3 | [![Documentation](https://docs.rs/minifb/badge.svg)](https://docs.rs/minifb) 4 | 5 | minifb is a cross platform library written in [Rust](https://www.rust-lang.org) 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. 6 | An example is the best way to show how it works: 7 | 8 | [Changelog](https://github.com/emoon/rust_minifb/blob/master/CHANGELOG.md) 9 | 10 | Usage 11 | ----- 12 | 13 | ```toml 14 | # Cargo.toml 15 | [dependencies] 16 | minifb = "0.28" 17 | ``` 18 | 19 | Example 20 | ------- 21 | 22 | ```rust 23 | use minifb::{Key, Window, WindowOptions}; 24 | 25 | const WIDTH: usize = 640; 26 | const HEIGHT: usize = 360; 27 | 28 | fn main() { 29 | let mut buffer: Vec = vec![0; WIDTH * HEIGHT]; 30 | 31 | let mut window = Window::new( 32 | "Test - ESC to exit", 33 | WIDTH, 34 | HEIGHT, 35 | WindowOptions::default(), 36 | ) 37 | .unwrap_or_else(|e| { 38 | panic!("{}", e); 39 | }); 40 | 41 | // Limit to max ~60 fps update rate 42 | window.set_target_fps(60); 43 | 44 | while window.is_open() && !window.is_key_down(Key::Escape) { 45 | for i in buffer.iter_mut() { 46 | *i = 0; // write something more funny here! 47 | } 48 | 49 | // We unwrap here as we want this code to exit if it fails. Real applications may want to handle this in a different way 50 | window 51 | .update_with_buffer(&buffer, WIDTH, HEIGHT) 52 | .unwrap(); 53 | } 54 | } 55 | ``` 56 | 57 | Status 58 | ------ 59 | 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! 60 | Notice: That after 0.13 Redox hasn't been updated and some work is required to get that working again. PR are welcome. 61 | 62 | Build instructions 63 | ------------------ 64 | 65 | On Linux you may need to install these dependencies first: 66 | 67 | ``` 68 | sudo apt install libxkbcommon-dev libwayland-cursor0 libwayland-dev 69 | ``` 70 | 71 | ``` 72 | cargo build 73 | cargo run --example noise 74 | ``` 75 | 76 | This will run the [noise example](https://github.com/emoon/rust_minifb/blob/master/examples/noise.rs) 77 | 78 | ## License 79 | 80 | Licensed under either of 81 | 82 | * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 83 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 84 | 85 | at your option. 86 | 87 | ### Contribution 88 | 89 | 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. 90 | -------------------------------------------------------------------------------- /Web.toml: -------------------------------------------------------------------------------- 1 | # The default value of `--target` used when building this crate 2 | # in cases where it's not specified on the command line. 3 | default-target = "wasm32-unknown-unknown" 4 | 5 | [cargo-web] 6 | # Asserts the minimum required version of `cargo-web` necessary 7 | # to compile this crate; supported since 0.6.0. 8 | minimum-version = "0.6.0" 9 | -------------------------------------------------------------------------------- /build.rs: -------------------------------------------------------------------------------- 1 | use std::env; 2 | extern crate cc; 3 | 4 | //cargo build --target=wasm32-unknown-unknown --verbose --no-default-features --features web 5 | 6 | fn main() { 7 | /* 8 | println!("Environment configuration:"); 9 | for (key, value) in env::vars() { 10 | if key.starts_with("CARGO_CFG_") { 11 | println!("{}: {:?}", key, value); 12 | } 13 | } 14 | println!("OS: {:?}", env::var("OS").unwrap_or("".to_string())); 15 | println!("FAMILY: {:?}", env::var("FAMILY").unwrap_or("".to_string())); 16 | println!("ARCH: {:?}", env::var("ARCH").unwrap_or("".to_string())); 17 | println!("TARGET: {:?}", env::var("TARGET").unwrap_or("".to_string())); 18 | */ 19 | // target_arch is not working? OS FAMILY and ARCH variables were empty too 20 | // I think the cross-compilation is broken. We could take these from the environment, 21 | // since the build script seems to have a different target_arch than the destination. 22 | let target = env::var("TARGET").expect("cargo should have set $TARGET"); 23 | if target != "wasm32-unknown-unknown" 24 | && !target.contains("-macos") 25 | && !target.contains("-windows") 26 | && !target.contains("-redox") 27 | && !target.starts_with("wasm32-") // this is ignored. Why? 28 | && cfg!(not(any(feature = "wayland", feature = "x11"))) 29 | { 30 | panic!("At least one of the x11 or wayland features must be enabled"); 31 | } 32 | 33 | if target.contains("darwin") { 34 | cc::Build::new() 35 | .flag("-mmacosx-version-min=10.10") 36 | .file("src/native/macosx/MacMiniFB.m") 37 | .file("src/native/macosx/OSXWindow.m") 38 | .file("src/native/macosx/OSXWindowFrameView.m") 39 | .compile("libminifb_native.a"); 40 | println!("cargo:rustc-link-lib=framework=Metal"); 41 | println!("cargo:rustc-link-lib=framework=MetalKit"); 42 | } else if !target.contains("windows") && !target.contains("wasm32") { 43 | // build scalar on non-windows and non-mac 44 | cc::Build::new() 45 | .file("src/native/posix/scalar.c") 46 | .opt_level(3) // always build with opts for scaler so it's fast in debug also 47 | .compile("libscalar.a") 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /examples/char_callback.rs: -------------------------------------------------------------------------------- 1 | use minifb::{InputCallback, Key, Window, WindowOptions}; 2 | use std::{cell::RefCell, rc::Rc}; 3 | 4 | const WIDTH: usize = 1280; 5 | const HEIGHT: usize = 720; 6 | 7 | type KeyVec = Rc>>; 8 | 9 | struct Input { 10 | keys: KeyVec, 11 | } 12 | 13 | impl InputCallback for Input { 14 | /// Will be called every time a character key is pressed 15 | fn add_char(&mut self, uni_char: u32) { 16 | self.keys.borrow_mut().push(uni_char); 17 | } 18 | } 19 | 20 | fn main() { 21 | let mut buffer = vec![0u32; WIDTH * HEIGHT]; 22 | 23 | let mut window = Window::new( 24 | "char_callback example - press ESC to exit", 25 | WIDTH, 26 | HEIGHT, 27 | WindowOptions::default(), 28 | ) 29 | .expect("Unable to create the window"); 30 | 31 | window.set_target_fps(60); 32 | 33 | let keys = KeyVec::new(RefCell::new(Vec::new())); 34 | window.set_input_callback(Box::new(Input { keys: keys.clone() })); 35 | 36 | // produces a wave pattern where the screen goes from red to blue, and vice-versa 37 | let mut wave: u8 = 0; 38 | let mut wave_direction: i8 = 1; 39 | while window.is_open() && !window.is_key_down(Key::Escape) { 40 | let red: u32 = (wave as u32) << 16; 41 | let green: u32 = 64 << 8; 42 | let blue: u32 = (255 - wave) as u32; 43 | let bg_color = red | green | blue; 44 | 45 | for pixel in buffer.iter_mut() { 46 | *pixel = bg_color; 47 | } 48 | 49 | // We unwrap here as we want this code to exit if it fails. Real applications may want to handle this in a different way 50 | window.update_with_buffer(&buffer, WIDTH, HEIGHT).unwrap(); 51 | 52 | let mut keys = keys.borrow_mut(); 53 | 54 | for t in keys.iter() { 55 | println!("Code point: {}, Character: {:?}", *t, char::from_u32(*t)); 56 | } 57 | 58 | keys.clear(); 59 | 60 | // switch color wave directions 61 | match wave.checked_add_signed(wave_direction) { 62 | Some(new_wave) => wave = new_wave, 63 | None => { 64 | wave_direction = -wave_direction; 65 | if wave_direction > 0 { 66 | wave += 1; 67 | } else { 68 | wave -= 1; 69 | } 70 | } 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /examples/drop.rs: -------------------------------------------------------------------------------- 1 | use minifb::{Window, WindowOptions}; 2 | use std::{ 3 | thread, 4 | time::{Duration, Instant}, 5 | }; 6 | 7 | const WIDTH: usize = 1280; 8 | const HEIGHT: usize = 720; 9 | 10 | fn main() { 11 | println!("Creating and showing a Window"); 12 | 13 | let mut window = Window::new( 14 | "Drop example - Window will close after 5 seconds", 15 | WIDTH, 16 | HEIGHT, 17 | WindowOptions::default(), 18 | ) 19 | .expect("Unable to create the window"); 20 | 21 | window.set_target_fps(60); 22 | 23 | let now = Instant::now(); 24 | while window.is_open() && now.elapsed().as_secs() < 5 { 25 | window.update(); 26 | } 27 | 28 | drop(window); 29 | println!("Dropped"); 30 | 31 | thread::sleep(Duration::from_secs(2)); 32 | println!("Exiting"); 33 | } 34 | -------------------------------------------------------------------------------- /examples/fractal.rs: -------------------------------------------------------------------------------- 1 | use minifb::{Key, Scale, ScaleMode, Window, WindowOptions}; 2 | 3 | const WIDTH: usize = 100; 4 | const HEIGHT: usize = 100; 5 | const FRACTAL_DEPTH: u32 = 64; 6 | const GENERATION_INFINITY: f64 = 16.; 7 | 8 | fn main() { 9 | let mut buffer = vec![0u32; WIDTH * HEIGHT]; 10 | 11 | let mut window = Window::new( 12 | "Fractal example - press ESC to exit", 13 | WIDTH, 14 | HEIGHT, 15 | WindowOptions { 16 | resize: true, 17 | scale: Scale::X4, 18 | scale_mode: ScaleMode::AspectRatioStretch, 19 | ..WindowOptions::default() 20 | }, 21 | ) 22 | .expect("Unable to create the window"); 23 | 24 | window.set_target_fps(60); 25 | 26 | let range = 2.0; 27 | let x_min = 0. - range; 28 | let y_min = 0. - range; 29 | 30 | let x_max = 0. + range; 31 | let y_max = 0. + range; 32 | 33 | let mut angle: f64 = 0.0; 34 | 35 | window.set_background_color(0, 0, 20); 36 | 37 | while window.is_open() && !window.is_key_down(Key::Escape) { 38 | for (i, pixel) in buffer.iter_mut().enumerate() { 39 | let mut real = map((i % WIDTH) as f64, 0., WIDTH as f64, x_min, x_max); 40 | let mut imag = map((i / HEIGHT) as f64, 0., HEIGHT as f64, y_min, y_max); 41 | 42 | let mut depth = 0; 43 | while depth < FRACTAL_DEPTH { 44 | let re = real.powf(2.) - imag.powf(2.); 45 | let im = 2. * real * imag; 46 | 47 | real = re + angle.cos(); 48 | imag = im + angle.sin(); 49 | 50 | if (real + imag).abs() > GENERATION_INFINITY { 51 | break; // Leave when achieve infinity 52 | } 53 | depth += 1; 54 | } 55 | 56 | *pixel = if depth == FRACTAL_DEPTH { 57 | 0x00 58 | } else { 59 | depth * 32 % 255 60 | }; 61 | } 62 | 63 | angle += 0.1; 64 | 65 | // We unwrap here as we want this code to exit if it fails 66 | window.update_with_buffer(&buffer, WIDTH, HEIGHT).unwrap(); 67 | } 68 | } 69 | 70 | fn map(val: f64, start1: f64, stop1: f64, start2: f64, stop2: f64) -> f64 { 71 | start2 + (stop2 - start2) * ((val - start1) / (stop1 - start1)) 72 | } 73 | -------------------------------------------------------------------------------- /examples/icon.rs: -------------------------------------------------------------------------------- 1 | #[cfg(target_os = "linux")] 2 | use std::convert::TryFrom; 3 | #[cfg(target_os = "windows")] 4 | use std::str::FromStr; 5 | 6 | use minifb::{Icon, Key, Window, WindowOptions}; 7 | 8 | const WIDTH: usize = 1280; 9 | const HEIGHT: usize = 720; 10 | 11 | fn main() { 12 | let mut window = Window::new( 13 | "Window icon example - press ESC to exit", 14 | WIDTH, 15 | HEIGHT, 16 | WindowOptions { 17 | resize: true, 18 | ..WindowOptions::default() 19 | }, 20 | ) 21 | .expect("Unable to create the window"); 22 | 23 | window.set_target_fps(60); 24 | 25 | #[cfg(target_os = "windows")] 26 | window.set_icon(Icon::from_str("examples/resources/icon256.ico").unwrap()); 27 | 28 | #[cfg(target_os = "linux")] 29 | { 30 | let test: [u64; 1284] = [ 31 | 16, 16, 4294901760, 4294901760, 4294901760, 4294901760, 4294901760, 4294901760, 32 | 4294901760, 4294901760, 338034905, 3657433343, 0, 184483840, 234881279, 3053453567, 33 | 3221225727, 1879048447, 0, 0, 0, 0, 0, 0, 0, 1224737023, 3305111807, 3875537151, 0, 0, 34 | 2063597823, 1291845887, 0, 67109119, 4294901760, 4294901760, 4294901760, 4294901760, 35 | 4294901760, 4294901760, 4294901760, 4294901760, 50266112, 3422552319, 0, 0, 3070230783, 36 | 2063597823, 2986344703, 771752191, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3422552319, 0, 0, 37 | 3372220671, 1509949695, 704643327, 3355443455, 4294901760, 4294901760, 4294901760, 38 | 4294901760, 4294901760, 4294901760, 4294901760, 4294901760, 0, 3422552319, 0, 39 | 134152192, 3187671295, 251658495, 0, 3439329535, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3422552319, 40 | 0, 0, 2332033279, 1342177535, 167772415, 3338666239, 4294901760, 4294901760, 41 | 4294901760, 4294901760, 4294901760, 4294901760, 4294901760, 4294901760, 0, 3422552319, 42 | 0, 0, 436207871, 3322085628, 3456106751, 1375731967, 4278255360, 4026597120, 43 | 3758161664, 3489726208, 3204513536, 2952855296, 2684419840, 2399207168, 2130771712, 44 | 1845559040, 1593900800, 1308688128, 1040252672, 755040000, 486604544, 234946304, 45 | 4278255360, 4043374336, 3774938880, 3506503424, 3221290752, 2952855296, 2667642624, 46 | 2399207168, 2130771712, 1862336256, 1627453957, 1359017481, 1073805064, 788591627, 47 | 503379721, 218169088, 4278255360, 4043374336, 3758161664, 3506503424, 3221290752, 48 | 2952855296, 2684419840, 2415984384, 2130771712, 1862336256, 1577123584, 1308688128, 49 | 1040252672, 755040000, 486604544, 218169088, 4278190335, 4026532095, 3758096639, 50 | 3489661183, 3221225727, 2952790271, 2667577599, 2415919359, 2130706687, 1862271231, 51 | 1593835775, 1325400319, 1056964863, 771752191, 520093951, 234881279, 4278190335, 52 | 4026532095, 3758096639, 3489661183, 3221225727, 2952790271, 2667577599, 2415919359, 53 | 2130706687, 1862271231, 1593835775, 1325400319, 1056964863, 771752191, 503316735, 54 | 234881279, 4278190335, 4026532095, 3758096639, 3489661183, 3221225727, 2952790271, 55 | 2684354815, 2399142143, 2130706687, 1862271231, 1593835775, 1325400319, 1040187647, 56 | 771752191, 520093951, 234881279, 4294901760, 4043243520, 3774808064, 3506372608, 57 | 3221159936, 2952724480, 2684289024, 2399076352, 2147418112, 1862205440, 1593769984, 58 | 1308557312, 1040121856, 771686400, 503250944, 234815488, 4294901760, 4060020736, 59 | 3758030848, 3506372608, 3221159936, 2952724480, 2684289024, 2415853568, 2130640896, 60 | 1862205440, 1593769984, 1308557312, 1040121856, 771686400, 503250944, 234815488, 61 | 4294901760, 4043243520, 3774808064, 3489595392, 3237937152, 2952724480, 2684289024, 62 | 2415853568, 2147418112, 1862205440, 1593769984, 1325334528, 1056899072, 788463616, 63 | 503250944, 234815488, 32, 32, 4294901760, 4294901760, 4294901760, 4294901760, 64 | 4294901760, 4294901760, 4294901760, 4294901760, 4294901760, 4294901760, 4294901760, 65 | 4294901760, 4294901760, 4294901760, 4294901760, 4294901760, 0, 0, 0, 0, 0, 0, 0, 0, 0, 66 | 268369920, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 67 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4294901760, 4294901760, 4294901760, 4294901760, 68 | 4294901760, 4294901760, 4294901760, 4294901760, 4294901760, 4294901760, 4294901760, 69 | 4294901760, 4294901760, 4294901760, 4294901760, 4294901760, 1509949695, 3120562431, 70 | 4009754879, 4194304255, 3690987775, 2130706687, 83886335, 0, 50331903, 1694499071, 71 | 3170894079, 3992977663, 4211081471, 3657433343, 1879048447, 16777471, 0, 0, 0, 0, 0, 0, 72 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3087007999, 2281701631, 1191182591, 1040187647, 73 | 2030043391, 4127195391, 2566914303, 0, 16777471, 3254780159, 2181038335, 1191182591, 74 | 973078783, 2030043391, 4177527039, 2130706687, 4294901760, 4294901760, 4294901760, 75 | 4294901760, 4294901760, 4294901760, 4294901760, 4294901760, 4294901760, 4294901760, 76 | 4294901760, 4294901760, 4294901760, 4294901760, 4294901760, 4294901760, 0, 0, 0, 0, 0, 77 | 2214592767, 4093640959, 0, 0, 0, 0, 0, 0, 0, 2298478847, 3909091583, 0, 0, 0, 0, 0, 0, 78 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2214592767, 3607101695, 0, 0, 0, 0, 0, 0, 79 | 0, 1946157311, 4093640959, 4294901760, 4294901760, 4294901760, 4294901760, 4294901760, 80 | 4294901760, 4294901760, 4294901760, 4294901760, 4294901760, 4294901760, 4294901760, 81 | 4294901760, 4294901760, 4294901760, 4294901760, 0, 0, 536871167, 1191182591, 82 | 2281701631, 3019899135, 637534463, 0, 0, 0, 100597760, 251592704, 33488896, 0, 83 | 3321889023, 2919235839, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 84 | 2550137087, 4278190335, 4278190335, 3405775103, 570425599, 0, 0, 0, 0, 0, 0, 85 | 2046820607, 4043309311, 620757247, 4294901760, 4294901760, 4294901760, 4294901760, 86 | 4294901760, 4294901760, 4294901760, 4294901760, 4294901760, 4294901760, 4294901760, 87 | 4294901760, 4294901760, 4294901760, 4294901760, 4294901760, 33488896, 0, 0, 218104063, 88 | 1291845887, 3841982719, 3388997887, 0, 0, 0, 0, 0, 1996488959, 4093640959, 1073742079, 89 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1761607935, 90 | 4278190335, 150995199, 0, 0, 67109119, 2550137087, 3909091583, 889192703, 0, 0, 91 | 4294901760, 4294901760, 4294901760, 4294901760, 4294901760, 4294901760, 4294901760, 92 | 4294901760, 4294901760, 4294901760, 4294901760, 4294901760, 4294901760, 4294901760, 93 | 4294901760, 4294901760, 0, 0, 0, 0, 0, 2181038335, 3925868799, 0, 0, 218104063, 94 | 3070230783, 3623878911, 570425599, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95 | 0, 805306623, 3288334591, 1795162367, 1040187647, 1023410431, 2231369983, 4211081471, 96 | 1694499071, 0, 369099007, 3456106751, 3825205503, 1174405375, 872415487, 872415487, 97 | 872415487, 872415487, 4294901760, 4294901760, 4294901760, 4294901760, 4294901760, 98 | 4294901760, 4294901760, 4294901760, 4294901760, 4294901760, 4294901760, 4294901760, 99 | 4294901760, 4294901760, 4294901760, 4293984270, 2046951677, 3422552319, 4110418175, 100 | 4177527039, 3405775103, 1409286399, 0, 0, 1409286399, 4278190335, 4278190335, 101 | 4278190335, 4278190335, 4278190335, 4278190335, 4278190335, 0, 0, 0, 0, 0, 0, 0, 0, 0, 102 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4294901760, 103 | 4294901760, 4294901760, 4294901760, 4294901760, 4294901760, 4294901760, 4294901760, 104 | 4294901760, 4294901760, 4294901760, 4294901760, 4294901760, 4294901760, 4294901760, 105 | 4294901760, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 106 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 107 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 108 | 4278255360, 4144037632, 4009819904, 3875602176, 3741384448, 3607166720, 3472948992, 109 | 3338731264, 3204513536, 3053518592, 2936078080, 2801860352, 2650865408, 2516647680, 110 | 2382429952, 2264989440, 2113994496, 1996553984, 1862336256, 1728118528, 1577123584, 111 | 1459683072, 1325465344, 1191247616, 1040252672, 922812160, 771817216, 637599488, 112 | 503381760, 385941248, 234946304, 100728576, 4278255360, 4144037632, 4009819904, 113 | 3875602176, 3724607232, 3607166720, 3472948992, 3338731264, 3204513536, 3070295808, 114 | 2936078080, 2801860352, 2667642624, 2516647680, 2399207168, 2264989440, 2130771712, 115 | 1996553984, 1845559040, 1728118528, 1593900800, 1459683072, 1308688128, 1191247616, 116 | 1057029888, 922812160, 788594432, 637599488, 503381760, 369164032, 234946304, 117 | 117505792, 4278255360, 4144037632, 4009819904, 3875602176, 3741384448, 3607166720, 118 | 3472948992, 3338731264, 3204513536, 3053518592, 2919300864, 2801860352, 2650865408, 119 | 2533424896, 2399207168, 2264989440, 2113994496, 1996553984, 1862336256, 1728118528, 120 | 1593900800, 1459683072, 1325465344, 1191247616, 1040252672, 906034944, 771817216, 121 | 654376704, 503381760, 369164032, 234946304, 117505792, 4278255360, 4144037632, 122 | 4009819904, 3858824960, 3741384448, 3607166720, 3472948992, 3338731264, 3204513536, 123 | 3070295808, 2936078080, 2801860352, 2667642624, 2533424896, 2382429952, 2264989440, 124 | 2130771712, 1979776768, 1862336256, 1728118528, 1577123584, 1442905856, 1325465344, 125 | 1191247616, 1040252672, 922812160, 771817216, 637599488, 503381760, 369164032, 126 | 234946304, 100728576, 4278255360, 4144037632, 4009819904, 3875602176, 3741384448, 127 | 3607166720, 3472948992, 3338731264, 3204513536, 3070295808, 2919300864, 2801860352, 128 | 2667642624, 2533424896, 2399207168, 2264989440, 2113994496, 1996553984, 1862336256, 129 | 1728118528, 1593900800, 1442905856, 1342241795, 1174470400, 1057029888, 906034944, 130 | 788594432, 654376704, 503381760, 385941248, 251723520, 100728576, 4278190335, 131 | 4160749823, 4026532095, 3892314367, 3741319423, 3623878911, 3472883967, 3338666239, 132 | 3221225727, 3070230783, 2952790271, 2818572543, 2667577599, 2533359871, 2399142143, 133 | 2264924415, 2147483903, 1996488959, 1862271231, 1728053503, 1593835775, 1459618047, 134 | 1325400319, 1191182591, 1056964863, 922747135, 788529407, 654311679, 520093951, 135 | 385876223, 251658495, 117440767, 4278190335, 4160749823, 4026532095, 3892314367, 136 | 3741319423, 3623878911, 3489661183, 3355443455, 3221225727, 3087007999, 2936013055, 137 | 2801795327, 2667577599, 2533359871, 2399142143, 2281701631, 2130706687, 1996488959, 138 | 1862271231, 1728053503, 1593835775, 1459618047, 1325400319, 1191182591, 1056964863, 139 | 922747135, 788529407, 654311679, 520093951, 385876223, 234881279, 100663551, 140 | 4278190335, 4160749823, 4026532095, 3892314367, 3758096639, 3623878911, 3489661183, 141 | 3355443455, 3221225727, 3087007999, 2936013055, 2801795327, 2667577599, 2550137087, 142 | 2415919359, 2264924415, 2130706687, 1996488959, 1862271231, 1728053503, 1593835775, 143 | 1459618047, 1325400319, 1191182591, 1056964863, 922747135, 788529407, 654311679, 144 | 503316735, 369099007, 251658495, 100663551, 4278190335, 4160749823, 4026532095, 145 | 3892314367, 3758096639, 3623878911, 3489661183, 3355443455, 3204448511, 3087007999, 146 | 2936013055, 2818572543, 2667577599, 2533359871, 2399142143, 2264924415, 2130706687, 147 | 1996488959, 1879048447, 1728053503, 1593835775, 1459618047, 1325400319, 1191182591, 148 | 1056964863, 922747135, 788529407, 654311679, 520093951, 385876223, 251658495, 149 | 117440767, 4278190335, 4160749823, 4026532095, 3892314367, 3758096639, 3623878911, 150 | 3489661183, 3355443455, 3221225727, 3087007999, 2952790271, 2818572543, 2667577599, 151 | 2533359871, 2399142143, 2264924415, 2147483903, 2013266175, 1862271231, 1744830719, 152 | 1610612991, 1476395263, 1342177535, 1191182591, 1056964863, 922747135, 788529407, 153 | 654311679, 520093951, 385876223, 251658495, 100663551, 4294901760, 4160684032, 154 | 4026466304, 3909025792, 3774808064, 3623813120, 3489595392, 3355377664, 3237937152, 155 | 3103719424, 2952724480, 2818506752, 2684289024, 2550071296, 2415853568, 2281635840, 156 | 2147418112, 2013200384, 1878982656, 1744764928, 1593769984, 1476329472, 1325334528, 157 | 1207894016, 1056899072, 939458560, 788463616, 654245888, 520028160, 385810432, 158 | 251592704, 117374976, 4294901760, 4177461248, 4043243520, 3909025792, 3774808064, 159 | 3640590336, 3506372608, 3355377664, 3221159936, 3086942208, 2952724480, 2818506752, 160 | 2701066240, 2550071296, 2415853568, 2281635840, 2147418112, 2013200384, 1878982656, 161 | 1727987712, 1610547200, 1476329472, 1325334528, 1191116800, 1073676288, 922681344, 162 | 788463616, 654245888, 520028160, 385810432, 251592704, 100597760, 4294901760, 163 | 4177461248, 4043243520, 3909025792, 3774808064, 3640590336, 3489595392, 3372154880, 164 | 3237937152, 3103719424, 2952724480, 2818506752, 2700935170, 2550071296, 2415853568, 165 | 2281635840, 2147418112, 2013200384, 1878982656, 1744764928, 1610547200, 1459552256, 166 | 1342111744, 1191116800, 1056899072, 922681344, 788463616, 671023104, 520028160, 167 | 385810432, 251592704, 100597760, 4294901760, 4177461248, 4043243520, 3909025792, 168 | 3774808064, 3640590336, 3489595392, 3372154880, 3237937152, 3086942208, 2969501696, 169 | 2818506752, 2684289024, 2550071296, 2432630784, 2281635840, 2147418112, 2013200384, 170 | 1862205440, 1744764928, 1610547200, 1476329472, 1342111744, 1191116800, 1056899072, 171 | 922681344, 788463616, 654245888, 520028160, 385810432, 251592704, 117374976, 172 | 4294901760, 4177461248, 4043243520, 3909025792, 3774808064, 3623813120, 3506372608, 173 | 3372154880, 3237937152, 3103719424, 2952724480, 2835283968, 2684289024, 2550071296, 174 | 2432630784, 2281635840, 2147418112, 2046492676, 1862205440, 1744764928, 1610547200, 175 | 1476329472, 1342111744, 1207894016, 1056899072, 939458560, 788463616, 654245888, 176 | 536281096, 385810432, 251592704, 134152192, 177 | ]; 178 | 179 | // NOTE(@StefanoIncardone): this does not work on wayland 180 | window.set_icon(Icon::try_from(test.as_slice()).unwrap()); 181 | } 182 | 183 | while window.is_open() && !window.is_key_down(Key::Escape) { 184 | window.update(); 185 | } 186 | } 187 | -------------------------------------------------------------------------------- /examples/image.rs: -------------------------------------------------------------------------------- 1 | use minifb::{Key, Window, WindowOptions}; 2 | use png::{Decoder, Transformations}; 3 | use std::fs::File; 4 | 5 | fn main() { 6 | let mut decoder = Decoder::new(File::open("examples/resources/planet.png").unwrap()); 7 | 8 | // Reading the image in RGBA format. 9 | decoder.set_transformations(Transformations::ALPHA); 10 | let mut reader = decoder.read_info().unwrap(); 11 | 12 | let mut buffer = vec![0u32; reader.output_buffer_size() / 4]; 13 | 14 | // View of pixels as individual subpixels (avoids allocating a second pixel buffer). 15 | let mut u8_buffer = unsafe { 16 | std::slice::from_raw_parts_mut( 17 | buffer.as_mut_ptr() as *mut u8, 18 | buffer.len() * std::mem::size_of::(), 19 | ) 20 | }; 21 | 22 | // Read the next frame. Currently this function should only be called once. 23 | reader.next_frame(&mut u8_buffer).unwrap(); 24 | 25 | // convert RGBA buffer read by the reader to an ARGB buffer as expected by minifb. 26 | for (rgba, argb) in u8_buffer.chunks_mut(4).zip(buffer.iter_mut()) { 27 | // extracting the subpixels 28 | let r = rgba[0] as u32; 29 | let g = rgba[1] as u32; 30 | let b = rgba[2] as u32; 31 | let a = rgba[3] as u32; 32 | 33 | // merging the subpixels in ARGB format. 34 | *argb = a << 24 | r << 16 | g << 8 | b; 35 | } 36 | 37 | let width = reader.info().width as usize; 38 | let height = reader.info().height as usize; 39 | 40 | let mut window = Window::new( 41 | "Image background example - Press ESC to exit", 42 | width, 43 | height, 44 | WindowOptions::default(), 45 | ) 46 | .expect("Unable to create the window"); 47 | 48 | window.set_target_fps(60); 49 | 50 | while window.is_open() && !window.is_key_down(Key::Escape) { 51 | window.update_with_buffer(&buffer, width, height).unwrap(); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /examples/menu.rs: -------------------------------------------------------------------------------- 1 | use minifb::{Key, Menu, Scale, Window, WindowOptions, MENU_KEY_CTRL}; 2 | 3 | const WIDTH: usize = 1280 / 2; 4 | const HEIGHT: usize = 720 / 2; 5 | 6 | const MENU_TEST_ID: usize = 1; 7 | const OTHER_MENU_ID: usize = 2; 8 | const COLOR_0_ID: usize = 3; 9 | const COLOR_1_ID: usize = 4; 10 | const COLOR_2_ID: usize = 5; 11 | const CLOSE_MENU_ID: usize = 6; 12 | 13 | fn main() { 14 | let mut buffer = vec![0u32; WIDTH * HEIGHT]; 15 | 16 | let mut window = Window::new( 17 | "Menu example - press ESC to exit", 18 | WIDTH, 19 | HEIGHT, 20 | WindowOptions { 21 | resize: true, 22 | scale: Scale::X2, 23 | ..WindowOptions::default() 24 | }, 25 | ) 26 | .expect("Unable to open the window"); 27 | 28 | window.set_target_fps(60); 29 | 30 | let mut menu = Menu::new("Test").unwrap(); 31 | let mut sub = Menu::new("Select Color").unwrap(); 32 | 33 | sub.add_item("Color 0", COLOR_0_ID) 34 | .shortcut(Key::F1, 0) 35 | .build(); 36 | sub.add_item("Color 1", COLOR_1_ID) 37 | .shortcut(Key::F2, 0) 38 | .build(); 39 | sub.add_item("Color 2", COLOR_2_ID) 40 | .shortcut(Key::F7, 0) 41 | .build(); 42 | menu.add_item("Menu Test", MENU_TEST_ID) 43 | .shortcut(Key::W, MENU_KEY_CTRL) 44 | .build(); 45 | 46 | menu.add_separator(); 47 | 48 | menu.add_item("Other Menu", OTHER_MENU_ID) 49 | .shortcut(Key::W, MENU_KEY_CTRL) 50 | .build(); 51 | menu.add_item("Remove Menu", CLOSE_MENU_ID) 52 | .shortcut(Key::R, 0) 53 | .build(); 54 | 55 | menu.add_sub_menu("Sub Test", &sub); 56 | 57 | let menu_handle = window.add_menu(&menu); 58 | 59 | if let Some(menus) = window.get_posix_menus() { 60 | println!("Menus {:?}", menus); 61 | } 62 | 63 | let mut color_mul = 1; 64 | 65 | while window.is_open() && !window.is_key_down(Key::Escape) { 66 | for y in 0..HEIGHT { 67 | for x in 0..WIDTH { 68 | buffer[(y * WIDTH) + x] = (((x ^ y) & 0xff) * color_mul) as u32; 69 | } 70 | } 71 | 72 | if let Some(menu_id) = window.is_menu_pressed() { 73 | match menu_id { 74 | COLOR_0_ID => { 75 | color_mul = 0xfe0000; 76 | } 77 | COLOR_1_ID => { 78 | color_mul = 0xff00; 79 | } 80 | COLOR_2_ID => { 81 | color_mul = 1; 82 | } 83 | CLOSE_MENU_ID => { 84 | println!("Removed menu id {:?}", menu_handle); 85 | window.remove_menu(menu_handle); 86 | } 87 | _ => (), 88 | } 89 | 90 | println!("Menu id {} pressed", menu_id); 91 | } 92 | 93 | window.update_with_buffer(&buffer, WIDTH, HEIGHT).unwrap(); 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /examples/mouse.rs: -------------------------------------------------------------------------------- 1 | use minifb::{Key, MouseButton, MouseMode, Scale, Window, WindowOptions}; 2 | 3 | // Divided by 2 to account for the scale of the window 4 | const WIDTH: usize = 1280 / 2; 5 | const HEIGHT: usize = 720 / 2; 6 | 7 | fn main() { 8 | let mut buffer = vec![0u32; WIDTH * HEIGHT]; 9 | 10 | let mut window = Window::new( 11 | "Mouse drawing example - press ESC to exit", 12 | WIDTH, 13 | HEIGHT, 14 | WindowOptions { 15 | scale: Scale::X2, 16 | ..WindowOptions::default() 17 | }, 18 | ) 19 | .expect("Unable to create the window"); 20 | 21 | window.set_target_fps(60); 22 | 23 | let (mut width, mut height) = (WIDTH, HEIGHT); 24 | 25 | while window.is_open() && !window.is_key_down(Key::Escape) { 26 | let (new_width, new_height) = window.get_size(); 27 | if new_width != width || new_height != height { 28 | // Divide by / 2 here as we use 2x scaling for the buffer 29 | let mut new_buffer = vec![0; (new_width / 2) * (new_height / 2)]; 30 | 31 | // copy valid bits of old buffer to new buffer 32 | for y in 0..(height / 2).min(new_height / 2) { 33 | for x in 0..(width / 2).min(new_width / 2) { 34 | new_buffer[y * (new_width / 2) + x] = buffer[y * (width / 2) + x]; 35 | } 36 | } 37 | 38 | buffer = new_buffer; 39 | width = new_width; 40 | height = new_height; 41 | } 42 | 43 | if let Some((x, y)) = window.get_mouse_pos(MouseMode::Discard) { 44 | let screen_pos = ((y as usize) * (width / 2)) + x as usize; 45 | 46 | if window.get_mouse_down(MouseButton::Left) { 47 | buffer[screen_pos] = 0x00ffffff; // white 48 | } 49 | 50 | if window.get_mouse_down(MouseButton::Right) { 51 | buffer[screen_pos] = 0x00000000; // black 52 | } 53 | } 54 | 55 | if let Some((scroll_x, scroll_y)) = window.get_scroll_wheel() { 56 | println!("Scrolling {} - {}", scroll_x, scroll_y); 57 | } 58 | 59 | // We unwrap here as we want this code to exit if it fails 60 | window 61 | .update_with_buffer(&buffer, width / 2, height / 2) 62 | .unwrap(); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /examples/multi.rs: -------------------------------------------------------------------------------- 1 | use minifb::{Key, Scale, Window, WindowOptions}; 2 | 3 | // Size of the main window 4 | const WIDTH: usize = 1280 / 2; 5 | const HEIGHT: usize = 720 / 2; 6 | 7 | fn main() { 8 | let mut buffer = vec![0u32; WIDTH * HEIGHT]; 9 | 10 | let mut larger_window = Window::new( 11 | "Larger - press ESC to exit", 12 | WIDTH, 13 | HEIGHT, 14 | WindowOptions { 15 | scale: Scale::X2, 16 | ..WindowOptions::default() 17 | }, 18 | ) 19 | .expect("Unable to create the larger window"); 20 | 21 | larger_window.set_target_fps(60); 22 | 23 | // Creating the smaller window after the larger one to make it appear on top 24 | let mut smaller_window = Window::new( 25 | "Smaller - press ESC to exit", 26 | WIDTH, 27 | HEIGHT, 28 | WindowOptions { 29 | scale: Scale::X1, // Which is also the default 30 | ..WindowOptions::default() 31 | }, 32 | ) 33 | .expect("Unable to create the smaller window"); 34 | 35 | smaller_window.set_target_fps(60); 36 | 37 | // Randomly drawing dots 38 | let mut dot_position = 13; 39 | 40 | while smaller_window.is_open() 41 | && larger_window.is_open() 42 | && !smaller_window.is_key_down(Key::Escape) 43 | && !larger_window.is_key_down(Key::Escape) 44 | { 45 | smaller_window 46 | .update_with_buffer(&buffer, WIDTH, HEIGHT) 47 | .unwrap(); 48 | larger_window 49 | .update_with_buffer(&buffer, WIDTH, HEIGHT) 50 | .unwrap(); 51 | 52 | dot_position += 7; 53 | dot_position *= 13; 54 | dot_position %= buffer.len(); 55 | 56 | buffer[dot_position] = 0x00_ff_ff_ff; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /examples/noise.rs: -------------------------------------------------------------------------------- 1 | use minifb::{Key, ScaleMode, Window, WindowOptions}; 2 | 3 | const WIDTH: usize = 1280; 4 | const HEIGHT: usize = 720; 5 | 6 | fn main() { 7 | let mut noise; 8 | let mut carry; 9 | let mut seed = 0xbeefu32; 10 | 11 | let mut buffer = vec![0u32; WIDTH * HEIGHT]; 12 | 13 | let mut window = Window::new( 14 | "Noise Test - Press ESC to exit", 15 | WIDTH, 16 | HEIGHT, 17 | WindowOptions { 18 | resize: true, 19 | scale_mode: ScaleMode::UpperLeft, 20 | ..WindowOptions::default() 21 | }, 22 | ) 23 | .expect("Unable to create the window"); 24 | 25 | window.set_target_fps(60); 26 | 27 | let mut size = (0, 0); 28 | 29 | while window.is_open() && !window.is_key_down(Key::Escape) { 30 | let new_size = window.get_size(); 31 | if new_size != size { 32 | size = new_size; 33 | buffer.resize(size.0 * size.1, 0); 34 | } 35 | 36 | for pixel in buffer.iter_mut() { 37 | noise = seed; 38 | noise >>= 3; 39 | noise ^= seed; 40 | carry = noise & 1; 41 | noise >>= 1; 42 | seed >>= 1; 43 | seed |= carry << 30; 44 | noise &= 0xFF; 45 | 46 | *pixel = (noise << 16) | (noise << 8) | noise; 47 | } 48 | 49 | window 50 | .update_with_buffer(&buffer, new_size.0, new_size.1) 51 | .unwrap(); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /examples/resources/icon256.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/emoon/rust_minifb/fa3001b840fa9a255200350fe593be72581975bb/examples/resources/icon256.ico -------------------------------------------------------------------------------- /examples/resources/planet.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/emoon/rust_minifb/fa3001b840fa9a255200350fe593be72581975bb/examples/resources/planet.png -------------------------------------------------------------------------------- /examples/resources/uv.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/emoon/rust_minifb/fa3001b840fa9a255200350fe593be72581975bb/examples/resources/uv.png -------------------------------------------------------------------------------- /examples/text.rs: -------------------------------------------------------------------------------- 1 | use minifb::{Key, Window, WindowOptions}; 2 | 3 | const WIDTH: usize = 1280; 4 | const HEIGHT: usize = 720; 5 | 6 | fn main() { 7 | let mut buffer = vec![0u32; WIDTH * HEIGHT]; 8 | 9 | let mut window = Window::new( 10 | "Plasma + Text Example", 11 | WIDTH, 12 | HEIGHT, 13 | WindowOptions { 14 | resize: false, 15 | ..WindowOptions::default() 16 | }, 17 | ) 18 | .expect("Unable to create the window"); 19 | 20 | window.set_target_fps(60); 21 | 22 | let mut size = (0, 0); 23 | let mut time = 0.0f32; 24 | 25 | let press_esc_text = Text::new(WIDTH, HEIGHT, 2); 26 | 27 | while window.is_open() && !window.is_key_down(Key::Escape) { 28 | let new_size = window.get_size(); 29 | if new_size != size { 30 | size = new_size; 31 | buffer.resize(size.0 * size.1, 0); 32 | } 33 | 34 | let y_step = 1.0 / HEIGHT as f32; 35 | let x_step = 1.0 / WIDTH as f32; 36 | 37 | let mut y = 0.0; 38 | for yi in 0..HEIGHT { 39 | let row = &mut buffer[yi * WIDTH..(yi + 1) * WIDTH]; 40 | 41 | // So this code is really slow, but good enough as an example :) 42 | let mut x = 0.0; 43 | for xi in 0..WIDTH { 44 | let k = 0.1 + (y + (0.148 - time).sin()).cos() + 2.4 * time; 45 | let w = 0.9 + (x + (0.628 + time).cos()).cos() - 0.7 * time; 46 | let d = (x * x + y * y).sqrt(); 47 | 48 | let s = 7.0 * (d + w).cos() * (k + w).sin(); 49 | 50 | let r = ((s + 0.2).cos() * 255.0) as u32; 51 | let g = ((s + 0.5).cos() * 255.0) as u32; 52 | let b = ((s + 0.7).cos() * 255.0) as u32; 53 | row[xi] = (r << 16) | (g << 8) | b; 54 | 55 | x += x_step; 56 | } 57 | 58 | y += y_step; 59 | } 60 | 61 | // Show some basic text at the bottom of the screen 62 | press_esc_text.draw(&mut buffer, (20, HEIGHT - 20), "Press ESC to exit"); 63 | 64 | window 65 | .update_with_buffer(&buffer, new_size.0, new_size.1) 66 | .unwrap(); 67 | 68 | // This should really be calculated from the time it takes to render 69 | time += 1.0 / 60.0; 70 | } 71 | } 72 | 73 | pub struct Text { 74 | texture: Vec, 75 | width: usize, 76 | // height: usize, 77 | scale: usize, 78 | } 79 | 80 | #[inline(always)] 81 | fn color_from_bit(bit: u8) -> u32 { 82 | if bit == 0 { 83 | 0x00000000 84 | } else { 85 | 0xFFFFFFFF 86 | } 87 | } 88 | 89 | impl Text { 90 | pub fn new(width: usize, _height: usize, scale: usize) -> Self { 91 | // Unpack texture for easier drawing 92 | let mut texture = Vec::with_capacity(128 * 128); 93 | 94 | for t in MICROKNIGHT_FONT { 95 | texture.push(color_from_bit((t >> 7) & 1)); 96 | texture.push(color_from_bit((t >> 6) & 1)); 97 | texture.push(color_from_bit((t >> 5) & 1)); 98 | texture.push(color_from_bit((t >> 4) & 1)); 99 | texture.push(color_from_bit((t >> 3) & 1)); 100 | texture.push(color_from_bit((t >> 2) & 1)); 101 | texture.push(color_from_bit((t >> 1) & 1)); 102 | texture.push(color_from_bit(t & 1)); 103 | } 104 | 105 | Self { 106 | texture, 107 | width, 108 | // height, 109 | scale, 110 | } 111 | } 112 | 113 | pub fn draw(&self, screen: &mut [u32], (mut x, y): (usize, usize), text: &str) { 114 | for c in text.chars() { 115 | let mut index = c as usize - ' ' as usize; 116 | if index > MICROKNIGHT_LAYOUT.len() as usize { 117 | index = 0; 118 | } 119 | 120 | let (layout_x, layout_y) = MICROKNIGHT_LAYOUT[index]; 121 | let texture_offset = layout_x as usize + (layout_y as usize * 128); 122 | 123 | for fy in 0..8 * self.scale { 124 | let ty = fy / self.scale; 125 | for fx in 0..8 * self.scale { 126 | let tx = fx / self.scale; 127 | let pixel = texture_offset + (ty * 128) + tx; 128 | if pixel != 0 { 129 | screen[((y + fy) * self.width) + fx + x] = self.texture[pixel]; 130 | } 131 | } 132 | } 133 | 134 | x += 8 * self.scale; 135 | } 136 | } 137 | } 138 | 139 | // Microknight font (128x128 packed with 1 bit per pixel) 140 | #[rustfmt::skip] 141 | static MICROKNIGHT_FONT: [u8; ((128 * 128) / u8::BITS) as usize] = [ 142 | 0x00, 0x0c, 0x1b, 0x0d, 0x81, 0x03, 0x01, 0xc0, 0x30, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 143 | 0x00, 0x0c, 0x1b, 0x0d, 0x87, 0xc4, 0xb3, 0x60, 0x30, 0x30, 0x0c, 0x1b, 0x03, 0x00, 0x00, 0x00, 144 | 0x00, 0x0c, 0x09, 0x1f, 0xcd, 0x03, 0xe1, 0xc0, 0x10, 0x60, 0x06, 0x0e, 0x03, 0x00, 0x00, 0x00, 145 | 0x00, 0x0c, 0x00, 0x0d, 0x87, 0xc0, 0xc3, 0xd8, 0x20, 0x60, 0x06, 0x3f, 0x8f, 0xc0, 0x03, 0xe0, 146 | 0x00, 0x0c, 0x00, 0x1f, 0xc1, 0x61, 0x83, 0x70, 0x00, 0x60, 0x06, 0x0e, 0x03, 0x01, 0x80, 0x00, 147 | 0x00, 0x00, 0x00, 0x0d, 0x81, 0x63, 0x63, 0x60, 0x00, 0x30, 0x0c, 0x1b, 0x03, 0x01, 0x80, 0x00, 148 | 0x00, 0x0c, 0x00, 0x0d, 0x87, 0xc6, 0x91, 0xf0, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x80, 0x00, 149 | 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x60, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 150 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 151 | 0x00, 0x00, 0x00, 0x03, 0x07, 0xc1, 0xe0, 0x61, 0xf0, 0x70, 0x7f, 0x1e, 0x0f, 0x00, 0x00, 0x00, 152 | 0x00, 0x03, 0x1e, 0x03, 0x00, 0x60, 0x30, 0x61, 0x80, 0xc0, 0x03, 0x33, 0x19, 0x81, 0x80, 0xc0, 153 | 0x00, 0x06, 0x33, 0x07, 0x03, 0xc0, 0xe0, 0xc1, 0xf8, 0xfc, 0x06, 0x1f, 0x18, 0xc1, 0x80, 0xc0, 154 | 0x00, 0x0c, 0x37, 0x83, 0x06, 0x00, 0x31, 0xb0, 0x0c, 0xc6, 0x0c, 0x31, 0x98, 0xc0, 0x00, 0x00, 155 | 0x00, 0x18, 0x3d, 0x83, 0x0c, 0x02, 0x33, 0x30, 0x8c, 0xc6, 0x0c, 0x31, 0x8f, 0xc0, 0x00, 0x00, 156 | 0x18, 0x30, 0x39, 0x83, 0x0c, 0x06, 0x33, 0xf9, 0x98, 0xcc, 0x0c, 0x33, 0x00, 0xc1, 0x80, 0xc0, 157 | 0x18, 0x60, 0x1f, 0x0f, 0xcf, 0xe3, 0xe0, 0x30, 0xf0, 0x78, 0x0c, 0x1e, 0x03, 0x81, 0x80, 0x40, 158 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 159 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 160 | 0x00, 0x00, 0x00, 0x0f, 0x83, 0x83, 0xc3, 0xe0, 0xf0, 0xf8, 0x7f, 0x3f, 0x87, 0x0c, 0x63, 0xf0, 161 | 0x18, 0x00, 0x0c, 0x18, 0xc6, 0xc6, 0x63, 0x31, 0x98, 0xcc, 0x60, 0x30, 0x0c, 0x0c, 0x60, 0xc0, 162 | 0x30, 0x3e, 0x06, 0x00, 0xcd, 0xe6, 0x33, 0xf1, 0x80, 0xc6, 0x7e, 0x3f, 0x18, 0x0c, 0x60, 0xc0, 163 | 0x60, 0x00, 0x03, 0x07, 0x8f, 0x67, 0xf3, 0x19, 0x80, 0xc6, 0x60, 0x30, 0x19, 0xcf, 0xe0, 0xc0, 164 | 0x30, 0x3e, 0x06, 0x06, 0x0d, 0xe6, 0x33, 0x19, 0x80, 0xc6, 0x60, 0x30, 0x18, 0xcc, 0x60, 0xc0, 165 | 0x18, 0x00, 0x0c, 0x00, 0x0c, 0x06, 0x33, 0x31, 0x8c, 0xc6, 0x60, 0x30, 0x18, 0xcc, 0x60, 0xc0, 166 | 0x00, 0x00, 0x00, 0x06, 0x06, 0x66, 0x33, 0xe0, 0xf8, 0xfc, 0x7f, 0x30, 0x0f, 0xcc, 0x63, 0xf0, 167 | 0x00, 0x00, 0x00, 0x00, 0x03, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 168 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 169 | 0x0e, 0x63, 0x30, 0x18, 0xcc, 0x63, 0xc3, 0xe0, 0xf0, 0xf8, 0x3c, 0x1f, 0x98, 0xcc, 0x66, 0x30, 170 | 0x06, 0x66, 0x30, 0x1d, 0xce, 0x66, 0x63, 0x31, 0x98, 0xcc, 0x60, 0x06, 0x18, 0xcc, 0x66, 0x30, 171 | 0x06, 0x6c, 0x30, 0x1f, 0xcf, 0x66, 0x33, 0x19, 0x8c, 0xc6, 0x3e, 0x06, 0x18, 0xcc, 0x66, 0x30, 172 | 0x06, 0x78, 0x30, 0x1a, 0xcd, 0xe6, 0x33, 0x19, 0x8c, 0xc6, 0x03, 0x06, 0x18, 0xc6, 0xc6, 0xb0, 173 | 0xc6, 0x6c, 0x30, 0x18, 0xcc, 0xe6, 0x33, 0xf1, 0x8c, 0xfc, 0x23, 0x06, 0x18, 0xc6, 0xc7, 0xf0, 174 | 0xc6, 0x66, 0x30, 0x18, 0xcc, 0x66, 0x33, 0x01, 0xac, 0xd8, 0x63, 0x06, 0x18, 0xc3, 0x87, 0x70, 175 | 0x7c, 0x63, 0x3f, 0x98, 0xcc, 0x63, 0xe3, 0x00, 0xf8, 0xcc, 0x3e, 0x06, 0x0f, 0x83, 0x86, 0x30, 176 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 177 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 178 | 0xc6, 0x63, 0x3f, 0x87, 0x00, 0x01, 0xc0, 0x40, 0x00, 0x18, 0x00, 0x30, 0x00, 0x00, 0x60, 0x00, 179 | 0x6c, 0x63, 0x03, 0x06, 0x0c, 0x00, 0xc0, 0xe0, 0x00, 0x18, 0x1e, 0x3e, 0x0f, 0x03, 0xe3, 0xc0, 180 | 0x38, 0x63, 0x06, 0x06, 0x06, 0x00, 0xc1, 0xb0, 0x00, 0x10, 0x03, 0x33, 0x19, 0x86, 0x66, 0x60, 181 | 0x38, 0x3e, 0x0c, 0x06, 0x03, 0x00, 0xc0, 0x00, 0x00, 0x08, 0x3f, 0x31, 0x98, 0x0c, 0x67, 0xe0, 182 | 0x6c, 0x06, 0x18, 0x06, 0x01, 0x80, 0xc0, 0x00, 0x00, 0x00, 0x63, 0x31, 0x98, 0x0c, 0x66, 0x00, 183 | 0xc6, 0x06, 0x30, 0x06, 0x00, 0xc0, 0xc0, 0x00, 0x00, 0x00, 0x63, 0x31, 0x98, 0xcc, 0x66, 0x30, 184 | 0xc6, 0x06, 0x3f, 0x87, 0x00, 0x61, 0xc0, 0x00, 0x00, 0x00, 0x3f, 0x3f, 0x0f, 0x87, 0xe3, 0xe0, 185 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 186 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 187 | 0x38, 0x00, 0x30, 0x03, 0x00, 0xc6, 0x00, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 188 | 0x6c, 0x3f, 0x3e, 0x00, 0x00, 0x06, 0x60, 0x61, 0x88, 0xf8, 0x3c, 0x3e, 0x07, 0xcf, 0xc3, 0xc0, 189 | 0x60, 0x63, 0x33, 0x07, 0x01, 0xc6, 0xc0, 0x61, 0xdc, 0xcc, 0x66, 0x33, 0x0c, 0xcc, 0x66, 0x00, 190 | 0x78, 0x63, 0x31, 0x83, 0x00, 0xc7, 0x80, 0x61, 0xfc, 0xc6, 0x63, 0x31, 0x98, 0xcc, 0x03, 0xe0, 191 | 0x60, 0x63, 0x31, 0x83, 0x00, 0xc6, 0xc0, 0x61, 0xac, 0xc6, 0x63, 0x31, 0x98, 0xcc, 0x00, 0x30, 192 | 0x60, 0x3f, 0x31, 0x83, 0x00, 0xc6, 0x60, 0x61, 0x8c, 0xc6, 0x63, 0x31, 0x98, 0xcc, 0x06, 0x30, 193 | 0x60, 0x03, 0x31, 0x8f, 0xc4, 0xc6, 0x31, 0xf9, 0x8c, 0xc6, 0x3e, 0x3f, 0x0f, 0xcc, 0x03, 0xe0, 194 | 0x60, 0x3e, 0x00, 0x00, 0x03, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x00, 0xc0, 0x00, 0x00, 195 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 196 | 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x18, 0x1c, 0x87, 0x00, 0x00, 0xc0, 197 | 0x7c, 0x63, 0x31, 0x98, 0xcc, 0x66, 0x33, 0xf8, 0x30, 0x18, 0x0c, 0x27, 0x0e, 0x00, 0x00, 0x00, 198 | 0x30, 0x63, 0x31, 0x9a, 0xc6, 0xc6, 0x30, 0x30, 0x30, 0x18, 0x0c, 0x00, 0x1c, 0x00, 0x00, 0xc0, 199 | 0x30, 0x63, 0x1b, 0x1f, 0xc3, 0x86, 0x30, 0x60, 0x60, 0x18, 0x06, 0x00, 0x18, 0x20, 0x00, 0xc0, 200 | 0x30, 0x63, 0x1b, 0x0f, 0x83, 0x86, 0x30, 0xc0, 0x30, 0x18, 0x0c, 0x00, 0x10, 0x60, 0x00, 0xc0, 201 | 0x32, 0x63, 0x0e, 0x0d, 0x86, 0xc3, 0xf1, 0x80, 0x30, 0x18, 0x0c, 0x00, 0x00, 0xe0, 0x00, 0xc0, 202 | 0x1c, 0x3f, 0x0e, 0x08, 0x8c, 0x60, 0x33, 0xf8, 0x18, 0x18, 0x18, 0x00, 0x01, 0xc0, 0x00, 0xc0, 203 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xe0, 0x00, 0x00, 0x18, 0x00, 0x00, 0x03, 0x80, 0x00, 0x00, 204 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 205 | 0x30, 0x1c, 0x00, 0x18, 0xc1, 0x83, 0xc1, 0xb0, 0x78, 0x00, 0x00, 0x1f, 0x00, 0x03, 0xc3, 0xe0, 206 | 0x78, 0x36, 0x31, 0x98, 0xc1, 0x86, 0x00, 0x00, 0x84, 0x7e, 0x1b, 0x03, 0x00, 0x04, 0x20, 0x00, 207 | 0xcc, 0x30, 0x1f, 0x18, 0xc1, 0x83, 0xe0, 0x01, 0x32, 0xc6, 0x36, 0x00, 0x00, 0x0b, 0x90, 0x00, 208 | 0xc0, 0x7c, 0x31, 0x8f, 0x80, 0x06, 0x30, 0x01, 0x42, 0xc6, 0x6c, 0x00, 0x0f, 0x8a, 0x50, 0x00, 209 | 0xc0, 0x30, 0x31, 0x81, 0x81, 0x86, 0x30, 0x01, 0x42, 0x7e, 0x36, 0x00, 0x00, 0x0b, 0x90, 0x00, 210 | 0xc6, 0x30, 0x1f, 0x07, 0xc1, 0x83, 0xe0, 0x01, 0x32, 0x00, 0x1b, 0x00, 0x00, 0x0a, 0x50, 0x00, 211 | 0x7c, 0x7f, 0x31, 0x81, 0x81, 0x80, 0x30, 0x00, 0x84, 0x7c, 0x00, 0x00, 0x00, 0x04, 0x20, 0x00, 212 | 0x30, 0x00, 0x00, 0x00, 0x00, 0x01, 0xe0, 0x00, 0x78, 0x00, 0x00, 0x00, 0x00, 0x03, 0xc0, 0x00, 213 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 214 | 0x38, 0x00, 0x1c, 0x0e, 0x01, 0x80, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x06, 0x03, 0x00, 215 | 0x6c, 0x08, 0x06, 0x03, 0x03, 0x06, 0x31, 0xf8, 0x00, 0x00, 0x38, 0x1f, 0x1b, 0x0e, 0x67, 0x30, 216 | 0x6c, 0x3e, 0x0c, 0x06, 0x06, 0x06, 0x33, 0xd0, 0x30, 0x00, 0x18, 0x31, 0x8d, 0x86, 0xc3, 0x60, 217 | 0x38, 0x08, 0x18, 0x03, 0x00, 0x06, 0x31, 0xd0, 0x30, 0x00, 0x18, 0x31, 0x86, 0xc7, 0xa3, 0xc0, 218 | 0x00, 0x00, 0x1e, 0x0e, 0x00, 0x06, 0x30, 0x50, 0x00, 0x00, 0x3c, 0x1f, 0x0d, 0x83, 0x61, 0xf0, 219 | 0x00, 0x3e, 0x00, 0x00, 0x00, 0x06, 0x30, 0x50, 0x00, 0x00, 0x00, 0x00, 0x1b, 0x06, 0xf3, 0x18, 220 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0xe0, 0x50, 0x00, 0x18, 0x00, 0x1f, 0x00, 0x0c, 0xf6, 0x70, 221 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x00, 0x30, 0xf8, 222 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 223 | 0xe0, 0x18, 0x0c, 0x03, 0x03, 0x03, 0x91, 0xb0, 0xf0, 0x3f, 0x3c, 0x0c, 0x03, 0x01, 0x83, 0x60, 224 | 0x36, 0x00, 0x02, 0x04, 0x0c, 0xc4, 0xe0, 0x01, 0x98, 0x6c, 0x66, 0x02, 0x04, 0x06, 0x60, 0x00, 225 | 0x6c, 0x18, 0x1e, 0x0f, 0x07, 0x83, 0xc1, 0xe0, 0xf0, 0xcf, 0x60, 0x3f, 0x9f, 0xcf, 0xe7, 0xf0, 226 | 0x3a, 0x1e, 0x33, 0x19, 0x8c, 0xc6, 0x63, 0x31, 0x98, 0xfc, 0x60, 0x30, 0x18, 0x0c, 0x06, 0x00, 227 | 0xf6, 0x03, 0x3f, 0x9f, 0xcf, 0xe7, 0xf3, 0xf9, 0xfc, 0xcc, 0x60, 0x3f, 0x1f, 0x8f, 0xc7, 0xe0, 228 | 0x6f, 0x63, 0x31, 0x98, 0xcc, 0x66, 0x33, 0x19, 0x8c, 0xcc, 0x63, 0x30, 0x18, 0x0c, 0x06, 0x00, 229 | 0xcf, 0x3e, 0x31, 0x98, 0xcc, 0x66, 0x33, 0x19, 0x8c, 0xcf, 0x3e, 0x3f, 0x9f, 0xcf, 0xe7, 0xf0, 230 | 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 231 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 232 | 0x30, 0x0c, 0x06, 0x0d, 0x8f, 0x83, 0x90, 0xc0, 0x30, 0x30, 0x39, 0x1b, 0x00, 0x07, 0x81, 0x80, 233 | 0x08, 0x10, 0x19, 0x80, 0x0c, 0xc4, 0xe0, 0x20, 0x40, 0xcc, 0x4e, 0x00, 0x0f, 0x8c, 0xc0, 0x40, 234 | 0x7e, 0x3f, 0x1f, 0x8f, 0xcc, 0x67, 0x31, 0xe0, 0xf0, 0x78, 0x3c, 0x1e, 0x1a, 0xcd, 0xe6, 0x30, 235 | 0x18, 0x0c, 0x06, 0x03, 0x0e, 0x67, 0xb3, 0x31, 0x98, 0xcc, 0x66, 0x33, 0x1f, 0xef, 0x66, 0x30, 236 | 0x18, 0x0c, 0x06, 0x03, 0x0c, 0x66, 0xf3, 0x19, 0x8c, 0xc6, 0x63, 0x31, 0x9b, 0x6e, 0x66, 0x30, 237 | 0x18, 0x0c, 0x06, 0x03, 0x0c, 0x66, 0x73, 0x19, 0x8c, 0xc6, 0x63, 0x31, 0x98, 0xec, 0x66, 0x30, 238 | 0x7e, 0x3f, 0x1f, 0x8f, 0xcf, 0xc6, 0x31, 0xf0, 0xf8, 0x7c, 0x3e, 0x1f, 0x0f, 0xc7, 0xc3, 0xe0, 239 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 240 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 241 | 0x18, 0x0c, 0x1b, 0x03, 0x0c, 0x00, 0x00, 0xc0, 0x30, 0x18, 0x39, 0x1b, 0x07, 0x80, 0x00, 0x00, 242 | 0x20, 0x33, 0x00, 0x04, 0x0f, 0x83, 0xc0, 0x20, 0x40, 0x66, 0x4e, 0x00, 0x0c, 0xc7, 0xe3, 0xc0, 243 | 0xc6, 0x63, 0x31, 0x98, 0xcc, 0xc6, 0x60, 0xf0, 0x78, 0x3c, 0x1e, 0x0f, 0x07, 0x81, 0xb6, 0x60, 244 | 0xc6, 0x63, 0x31, 0x98, 0xcc, 0x66, 0xe0, 0x18, 0x0c, 0x06, 0x03, 0x01, 0x80, 0xc7, 0xf6, 0x00, 245 | 0xc6, 0x63, 0x31, 0x8f, 0x8f, 0xc6, 0x31, 0xf8, 0xfc, 0x7e, 0x3f, 0x1f, 0x8f, 0xcd, 0x86, 0x00, 246 | 0xc6, 0x63, 0x31, 0x81, 0x8c, 0x06, 0x33, 0x19, 0x8c, 0xc6, 0x63, 0x31, 0x98, 0xcd, 0x86, 0x30, 247 | 0x7c, 0x3e, 0x1f, 0x01, 0x8c, 0x06, 0xe1, 0xf8, 0xfc, 0x7e, 0x3f, 0x1f, 0x8f, 0xc7, 0xf3, 0xe0, 248 | 0x00, 0x00, 0x00, 0x00, 0x0c, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x80, 249 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 250 | 0x30, 0x0c, 0x0c, 0x0d, 0x83, 0x00, 0xc0, 0x60, 0xd8, 0x0c, 0x39, 0x0c, 0x03, 0x01, 0x83, 0x90, 251 | 0x08, 0x10, 0x33, 0x00, 0x00, 0x81, 0x01, 0x98, 0x00, 0x16, 0x4e, 0x02, 0x04, 0x06, 0x64, 0xe0, 252 | 0x78, 0x3c, 0x1e, 0x0f, 0x03, 0x81, 0xc0, 0xe0, 0x70, 0x3e, 0x7c, 0x1e, 0x0f, 0x07, 0x83, 0xc0, 253 | 0xfc, 0x7e, 0x3f, 0x1f, 0x81, 0x80, 0xc0, 0x60, 0x30, 0x66, 0x66, 0x33, 0x19, 0x8c, 0xc6, 0x60, 254 | 0xc0, 0x60, 0x30, 0x18, 0x01, 0x80, 0xc0, 0x60, 0x30, 0xc6, 0x63, 0x31, 0x98, 0xcc, 0x66, 0x30, 255 | 0xc6, 0x63, 0x31, 0x98, 0xc1, 0x80, 0xc0, 0x60, 0x30, 0xc6, 0x63, 0x31, 0x98, 0xcc, 0x66, 0x30, 256 | 0x7c, 0x3e, 0x1f, 0x0f, 0x87, 0xe3, 0xf1, 0xf8, 0xfc, 0x7e, 0x63, 0x1f, 0x0f, 0x87, 0xc3, 0xe0, 257 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 258 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 259 | 0x6c, 0x00, 0x00, 0x06, 0x01, 0x80, 0xc1, 0xb0, 0x30, 0xc0, 0x36, 0x00, 0x00, 0x00, 0x00, 0x00, 260 | 0x00, 0x0c, 0x1e, 0x01, 0x02, 0x03, 0x30, 0x00, 0x40, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 261 | 0x78, 0x00, 0x33, 0x18, 0xcc, 0x66, 0x33, 0x19, 0x8c, 0xf8, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 262 | 0xcc, 0x3f, 0x37, 0x98, 0xcc, 0x66, 0x33, 0x19, 0x8c, 0xcc, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 263 | 0xc6, 0x00, 0x3d, 0x98, 0xcc, 0x66, 0x33, 0x19, 0x8c, 0xc6, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 264 | 0xc6, 0x0c, 0x39, 0x98, 0xcc, 0x66, 0x33, 0x18, 0xfc, 0xfc, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 265 | 0x7c, 0x00, 0x1f, 0x0f, 0xc7, 0xe3, 0xf1, 0xf8, 0x0c, 0xc0, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 266 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xc0, 0x3e, 0x00, 0x00, 0x00, 0x00, 0x00, 267 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 268 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 269 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 270 | ]; 271 | 272 | // Font layout (generated from Angelcode Bitmap Font generator) 273 | #[rustfmt::skip] 274 | static MICROKNIGHT_LAYOUT: [(u8, u8); 224] = [ 275 | (0, 0), (9, 0), (18, 0), (27, 0), (36, 0), (45, 0), (54, 0), (63, 0), (72, 0), (81, 0), (90, 0), (99, 0), (108, 0), 276 | (117, 0), (0, 9), (9, 9), (18, 9), (27, 9), (36, 9), (45, 9), (54, 9), (63, 9), (72, 9), (81, 9), (90, 9), (99, 9), 277 | (108, 9), (117, 9), (0, 18), (9, 18), (18, 18), (27, 18), (36, 18), (45, 18), (54, 18), (63, 18), (72, 18), (81, 18), 278 | (90, 18), (99, 18), (108, 18), (117, 18), (0, 27), (9, 27), (18, 27), (27, 27), (36, 27), (45, 27), (54, 27), (63, 27), 279 | (72, 27), (81, 27), (90, 27), (99, 27), (108, 27), (117, 27), (0, 36), (9, 36), (18, 36), (27, 36), (36, 36), (45, 36), 280 | (54, 36), (63, 36), (72, 36), (81, 36), (90, 36), (99, 36), (108, 36), (117, 36), (0, 45), (9, 45), (18, 45), (27, 45), 281 | (36, 45), (45, 45), (54, 45), (63, 45), (72, 45), (81, 45), (90, 45), (99, 45), (108, 45), (117, 45), (0, 54), (9, 54), 282 | (18, 54), (27, 54), (36, 54), (45, 54), (54, 54), (63, 54), (72, 54), (81, 54), (90, 54), (99, 54), (0, 0), (0, 0), 283 | (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), 284 | (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), 285 | (108, 54), (117, 54), (0, 63), (9, 63), (18, 63), (27, 63), (36, 63), (45, 63), (54, 63), (63, 63), (72, 63), (81, 63), 286 | (90, 63), (99, 63), (108, 63), (117, 63), (0, 72), (9, 72), (18, 72), (27, 72), (36, 72), (45, 72), (54, 72), (63, 72), 287 | (72, 72), (81, 72), (90, 72), (99, 72), (108, 72), (117, 72), (0, 81), (9, 81), (18, 81), (27, 81), (36, 81), (45, 81), 288 | (54, 81), (63, 81), (72, 81), (81, 81), (90, 81), (99, 81), (108, 81), (117, 81), (0, 90), (9, 90), (18, 90), (27, 90), 289 | (36, 90), (45, 90), (54, 90), (63, 90), (72, 90), (81, 90), (90, 90), (99, 90), (108, 90), (117, 90), (0, 99), (9, 99), 290 | (18, 99), (27, 99), (36, 99), (45, 99), (54, 99), (63, 99), (72, 99), (81, 99), (90, 99), (99, 99), (108, 99), (117, 99), 291 | (0, 108), (9, 108), (18, 108), (27, 108), (36, 108), (45, 108), (54, 108), (63, 108), (72, 108), (81, 108), (90, 108), 292 | (99, 108), (108, 108), (117, 108), (0, 117), (9, 117), (18, 117), (27, 117), (36, 117), (45, 117), (54, 117), (63, 117), 293 | (72, 117), (81, 117), 294 | ]; 295 | -------------------------------------------------------------------------------- /examples/title_cursor.rs: -------------------------------------------------------------------------------- 1 | use minifb::{CursorStyle, Key, MouseMode, Window, WindowOptions}; 2 | 3 | const WIDTH: usize = 1280; 4 | const HEIGHT: usize = 720; 5 | 6 | struct Rect { 7 | top_left_x: usize, 8 | top_left_y: usize, 9 | width: usize, 10 | height: usize, 11 | color: u32, 12 | cursor_style: CursorStyle, 13 | } 14 | 15 | impl Rect { 16 | const WIDTH: usize = WIDTH / 4; // Four rectangles per row 17 | const HEIGHT: usize = HEIGHT / 2; // Two rectangles per column 18 | 19 | pub fn is_inside(&self, top_left_x: usize, top_left_y: usize) -> bool { 20 | let bottom_right_x = self.top_left_x + self.width; 21 | let bottom_right_y = self.top_left_y + self.height; 22 | 23 | (top_left_y >= self.top_left_y) 24 | && (top_left_y <= bottom_right_y) 25 | && (top_left_x >= self.top_left_x) 26 | && (top_left_x <= bottom_right_x) 27 | } 28 | } 29 | 30 | fn fill_rect(dest: &mut [u32], rect: &Rect) { 31 | for y in 0..rect.height { 32 | for x in 0..rect.width { 33 | dest[((rect.top_left_y + y) * WIDTH) + rect.top_left_x + x] = rect.color; 34 | } 35 | } 36 | } 37 | 38 | fn main() { 39 | let mut buffer = vec![0u32; WIDTH * HEIGHT]; 40 | 41 | let mut window = Window::new("I haz no title :(", WIDTH, HEIGHT, WindowOptions::default()) 42 | .expect("Unable to open the window"); 43 | 44 | window.set_target_fps(60); 45 | 46 | let rects = [ 47 | // Top row 48 | Rect { 49 | top_left_x: 0, 50 | top_left_y: 0, 51 | width: Rect::WIDTH, 52 | height: Rect::HEIGHT, 53 | color: 0x00b27474, 54 | cursor_style: CursorStyle::Arrow, 55 | }, 56 | Rect { 57 | top_left_x: Rect::WIDTH, 58 | top_left_y: 0, 59 | width: Rect::WIDTH, 60 | height: Rect::HEIGHT, 61 | color: 0x00b28050, 62 | cursor_style: CursorStyle::Ibeam, 63 | }, 64 | Rect { 65 | top_left_x: Rect::WIDTH * 2, 66 | top_left_y: 0, 67 | width: Rect::WIDTH, 68 | height: Rect::HEIGHT, 69 | color: 0x00a9b250, 70 | cursor_style: CursorStyle::Crosshair, 71 | }, 72 | Rect { 73 | top_left_x: Rect::WIDTH * 3, 74 | top_left_y: 0, 75 | width: Rect::WIDTH, 76 | height: Rect::HEIGHT, 77 | color: 0x0060b250, 78 | cursor_style: CursorStyle::ClosedHand, 79 | }, 80 | // Bottom row 81 | Rect { 82 | top_left_x: 0, 83 | top_left_y: Rect::HEIGHT, 84 | width: Rect::WIDTH, 85 | height: Rect::HEIGHT, 86 | color: 0x004fb292, 87 | cursor_style: CursorStyle::OpenHand, 88 | }, 89 | Rect { 90 | top_left_x: Rect::WIDTH, 91 | top_left_y: Rect::HEIGHT, 92 | width: Rect::WIDTH, 93 | height: Rect::HEIGHT, 94 | color: 0x004f71b2, 95 | cursor_style: CursorStyle::ResizeLeftRight, 96 | }, 97 | Rect { 98 | top_left_x: Rect::WIDTH * 2, 99 | top_left_y: Rect::HEIGHT, 100 | width: Rect::WIDTH, 101 | height: Rect::HEIGHT, 102 | color: 0x008850b2, 103 | cursor_style: CursorStyle::ResizeUpDown, 104 | }, 105 | Rect { 106 | top_left_x: Rect::WIDTH * 3, 107 | top_left_y: Rect::HEIGHT, 108 | width: Rect::WIDTH, 109 | height: Rect::HEIGHT, 110 | color: 0x00b25091, 111 | cursor_style: CursorStyle::ResizeAll, 112 | }, 113 | ]; 114 | 115 | while window.is_open() && !window.is_key_down(Key::Escape) { 116 | let (mx, my) = window.get_mouse_pos(MouseMode::Clamp).unwrap(); 117 | 118 | for rect in &rects { 119 | fill_rect(&mut buffer, rect); 120 | if rect.is_inside(mx as usize, my as usize) { 121 | window.set_cursor_style(rect.cursor_style); 122 | window.set_title(&format!( 123 | "Cursor of hovered rectangle: {:?}", 124 | rect.cursor_style 125 | )); 126 | } 127 | } 128 | 129 | window.update_with_buffer(&buffer, WIDTH, HEIGHT).unwrap(); 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /examples/topmost.rs: -------------------------------------------------------------------------------- 1 | use minifb::{Key, ScaleMode, Window, WindowOptions}; 2 | 3 | const WIDTH: usize = 1280; 4 | const HEIGHT: usize = 720; 5 | 6 | fn main() { 7 | let buffer = vec![0x00_FF_FF_00u32; WIDTH * HEIGHT]; 8 | 9 | let mut window = Window::new( 10 | "Topmost example - press ESC to exit", 11 | WIDTH, 12 | HEIGHT, 13 | WindowOptions { 14 | resize: true, 15 | scale_mode: ScaleMode::Center, 16 | topmost: true, 17 | ..WindowOptions::default() 18 | }, 19 | ) 20 | .expect("Unable to open the window"); 21 | 22 | window.set_target_fps(60); 23 | 24 | while window.is_open() && !window.is_key_down(Key::Escape) { 25 | window.update_with_buffer(&buffer, WIDTH, HEIGHT).unwrap(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /examples/transparent.rs: -------------------------------------------------------------------------------- 1 | use minifb::{Key, ScaleMode, Window, WindowOptions}; 2 | 3 | const WIDTH: usize = 1280; 4 | const HEIGHT: usize = 720; 5 | 6 | fn main() { 7 | let mut buffer = vec![0u32; WIDTH * HEIGHT]; 8 | 9 | let mut window = Window::new( 10 | "Transparent window example - press ESC to exit", 11 | WIDTH, 12 | HEIGHT, 13 | WindowOptions { 14 | transparency: true, 15 | ..WindowOptions::default() 16 | }, 17 | ) 18 | .expect("Unable to create the window"); 19 | 20 | window.set_target_fps(60); 21 | 22 | // produces a wave pattern where the screen goes from red to blue, and vice-versa 23 | let mut wave: u8 = 0; 24 | let mut wave_direction: i8 = 1; 25 | while window.is_open() && !window.is_key_down(Key::Escape) { 26 | let red: u32 = (wave as u32) << 16; 27 | let green: u32 = 64 << 8; 28 | let blue: u32 = (255 - wave) as u32; 29 | let bg_color = red | green | blue; 30 | 31 | for pixel in buffer.iter_mut() { 32 | *pixel = bg_color; 33 | } 34 | 35 | // We unwrap here as we want this code to exit if it fails. Real applications may want to handle this in a different way 36 | window.update_with_buffer(&buffer, WIDTH, HEIGHT).unwrap(); 37 | 38 | // switch color wave directions 39 | match wave.checked_add_signed(wave_direction) { 40 | Some(new_wave) => wave = new_wave, 41 | None => { 42 | wave_direction = -wave_direction; 43 | if wave_direction > 0 { 44 | wave += 1; 45 | } else { 46 | wave -= 1; 47 | } 48 | } 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /examples/wasm.rs: -------------------------------------------------------------------------------- 1 | // This example produces a wasm module that you can add to a web project, check out 2 | // https://github.com/dc740/minifb-async-examples to see how to integrate it 3 | 4 | use minifb::{Window, WindowOptions}; 5 | use std::{cell::RefCell, panic, rc::Rc}; 6 | use wasm_bindgen::prelude::*; 7 | 8 | const WIDTH: usize = 1280; 9 | const HEIGHT: usize = 720; 10 | 11 | fn window() -> web_sys::Window { 12 | web_sys::window().expect("no global `window` exists") 13 | } 14 | 15 | fn request_animation_frame(f: &Closure) { 16 | window() 17 | .request_animation_frame(f.as_ref().unchecked_ref()) 18 | .expect("should register `requestAnimationFrame` OK"); 19 | } 20 | 21 | #[wasm_bindgen(start)] 22 | fn main() { 23 | panic::set_hook(Box::new(console_error_panic_hook::hook)); 24 | 25 | // The id of a DOM element to render the window into 26 | let container = "minifb-container"; 27 | 28 | let mut window = Window::new(container, WIDTH, HEIGHT, WindowOptions::default()) 29 | .expect("Unable to create the window"); 30 | 31 | let mut buffer = vec![0; WIDTH * HEIGHT]; 32 | 33 | // A reference counted pointer to the closure that will update window 34 | let f = Rc::new(RefCell::new(None)); 35 | let g = f.clone(); 36 | // we update the window here just to reference the buffer 37 | // internally. Next calls to .update() will use the same buffer 38 | window.update_with_buffer(&buffer, WIDTH, HEIGHT).unwrap(); 39 | 40 | // create the closure for updating and rendering the window 41 | *g.borrow_mut() = Some(Closure::wrap(Box::new(move || { 42 | for pixel in buffer.iter_mut() { 43 | *pixel = pixel.wrapping_add(1); 44 | } 45 | 46 | // as the buffer is referenced from inside the ImageData, and 47 | // we push that to the canvas, so we could call update() and 48 | // avoid all this. I don't think it's possible to get artifacts 49 | // on the web side, but I definitely see them on the desktop app 50 | let _ = window.update_with_buffer(&buffer, WIDTH, HEIGHT); 51 | 52 | // schedule this closure for running again at next frame 53 | request_animation_frame(f.borrow().as_ref().unwrap()); 54 | }) as Box)); 55 | 56 | // start the animation loop 57 | request_animation_frame(g.borrow().as_ref().unwrap()); 58 | } 59 | -------------------------------------------------------------------------------- /src/error.rs: -------------------------------------------------------------------------------- 1 | use std::fmt; 2 | 3 | /// Errors that can be returned from various operations 4 | pub enum Error { 5 | /// Returned if menu Menu function isn't supported 6 | MenusNotSupported, 7 | /// Menu already exists 8 | MenuExists(String), 9 | /// Failed to create window 10 | WindowCreate(String), 11 | /// Unable to Update 12 | UpdateFailed(String), 13 | } 14 | 15 | impl fmt::Display for Error { 16 | fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { 17 | match self { 18 | Error::MenusNotSupported => write!(formatter, "Menus not supported"), 19 | Error::MenuExists(_) => write!(formatter, "Menu already exists"), 20 | Error::WindowCreate(_) => write!(formatter, "Failed to create window"), 21 | Error::UpdateFailed(_) => write!(formatter, "Failed to Update"), 22 | } 23 | } 24 | } 25 | 26 | impl fmt::Debug for Error { 27 | fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { 28 | match self { 29 | Error::MenusNotSupported => write!(fmt, "{}", self), 30 | Error::MenuExists(ref e) => write!(fmt, "{}, {:?}", self, e), 31 | Error::WindowCreate(ref e) => write!(fmt, "{}, {:?}", self, e), 32 | Error::UpdateFailed(ref e) => write!(fmt, "{}, {:?}", self, e), 33 | } 34 | } 35 | } 36 | 37 | impl std::error::Error for Error {} 38 | 39 | #[cfg(target_arch = "wasm32")] 40 | impl From for Error { 41 | fn from(js_value: wasm_bindgen::JsValue) -> Self { 42 | Error::UpdateFailed( 43 | js_value 44 | .as_string() 45 | .unwrap_or("Non string error.".to_string()), 46 | ) 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/icon.rs: -------------------------------------------------------------------------------- 1 | #[cfg(target_os = "linux")] 2 | use std::convert::TryFrom; 3 | #[cfg(target_os = "windows")] 4 | use std::{ffi::OsStr, os::windows::prelude::OsStrExt, str::FromStr}; 5 | 6 | /// Represents a window icon 7 | /// 8 | /// Different under Windows, Linux and MacOS 9 | /// 10 | /// **Windows**: Icon can be created from a relative path string 11 | /// 12 | /// **Linux / X11:** Icon can be created from an ARGB buffer 13 | #[derive(Clone, Copy, Debug)] 14 | pub enum Icon { 15 | Path(*const u16), 16 | Buffer(*const u64, u32), 17 | } 18 | 19 | #[cfg(target_os = "windows")] 20 | impl FromStr for Icon { 21 | type Err = &'static str; 22 | 23 | fn from_str(s: &str) -> Result { 24 | if s.is_empty() { 25 | return Err("Path to icon cannot be empty!"); 26 | } 27 | 28 | let path = OsStr::new(s) 29 | .encode_wide() 30 | //.chain(Some(0).into_iter()) 31 | .chain(Some(0)) 32 | .collect::>(); 33 | 34 | Ok(Icon::Path(path.as_ptr())) 35 | } 36 | } 37 | 38 | #[cfg(target_os = "linux")] 39 | impl TryFrom<&[u64]> for Icon { 40 | type Error = &'static str; 41 | 42 | fn try_from(value: &[u64]) -> Result { 43 | if value.is_empty() { 44 | return Err("ARGB buffer cannot be empty!"); 45 | } 46 | 47 | Ok(Icon::Buffer(value.as_ptr(), value.len() as u32)) 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/key.rs: -------------------------------------------------------------------------------- 1 | /// Key is used by the get key functions to check if some keys on the keyboard has been pressed 2 | #[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Clone, Copy)] 3 | pub enum Key { 4 | Key0 = 0, 5 | Key1 = 1, 6 | Key2 = 2, 7 | Key3 = 3, 8 | Key4 = 4, 9 | Key5 = 5, 10 | Key6 = 6, 11 | Key7 = 7, 12 | Key8 = 8, 13 | Key9 = 9, 14 | 15 | A = 10, 16 | B = 11, 17 | C = 12, 18 | D = 13, 19 | E = 14, 20 | F = 15, 21 | G = 16, 22 | H = 17, 23 | I = 18, 24 | J = 19, 25 | K = 20, 26 | L = 21, 27 | M = 22, 28 | N = 23, 29 | O = 24, 30 | P = 25, 31 | Q = 26, 32 | R = 27, 33 | S = 28, 34 | T = 29, 35 | U = 30, 36 | V = 31, 37 | W = 32, 38 | X = 33, 39 | Y = 34, 40 | Z = 35, 41 | 42 | F1, 43 | F2, 44 | F3, 45 | F4, 46 | F5, 47 | F6, 48 | F7, 49 | F8, 50 | F9, 51 | F10, 52 | F11, 53 | F12, 54 | F13, 55 | F14, 56 | F15, 57 | 58 | Down, 59 | Left, 60 | Right, 61 | Up, 62 | Apostrophe, 63 | Backquote, 64 | 65 | Backslash, 66 | Comma, 67 | Equal, 68 | LeftBracket, 69 | Minus, 70 | Period, 71 | RightBracket, 72 | Semicolon, 73 | 74 | Slash, 75 | Backspace, 76 | Delete, 77 | End, 78 | Enter, 79 | 80 | Escape, 81 | 82 | Home, 83 | Insert, 84 | Menu, 85 | 86 | PageDown, 87 | PageUp, 88 | 89 | Pause, 90 | Space, 91 | Tab, 92 | NumLock, 93 | CapsLock, 94 | ScrollLock, 95 | LeftShift, 96 | RightShift, 97 | LeftCtrl, 98 | RightCtrl, 99 | 100 | NumPad0, 101 | NumPad1, 102 | NumPad2, 103 | NumPad3, 104 | NumPad4, 105 | NumPad5, 106 | NumPad6, 107 | NumPad7, 108 | NumPad8, 109 | NumPad9, 110 | NumPadDot, 111 | NumPadSlash, 112 | NumPadAsterisk, 113 | NumPadMinus, 114 | NumPadPlus, 115 | NumPadEnter, 116 | 117 | LeftAlt, 118 | RightAlt, 119 | 120 | LeftSuper, 121 | RightSuper, 122 | 123 | /// Used when an Unknown key has been pressed 124 | Unknown, 125 | 126 | Count = 107, 127 | } 128 | -------------------------------------------------------------------------------- /src/key_handler.rs: -------------------------------------------------------------------------------- 1 | #[cfg(target_arch = "wasm32")] 2 | extern crate instant; 3 | 4 | #[cfg(target_arch = "wasm32")] 5 | use instant::{Duration, Instant}; 6 | #[cfg(not(target_arch = "wasm32"))] 7 | use std::time::{Duration, Instant}; 8 | 9 | use crate::{InputCallback, Key, KeyRepeat}; 10 | 11 | pub struct KeyHandler { 12 | pub key_callback: Option>, 13 | prev_time: Instant, 14 | delta_time: Duration, 15 | keys: [bool; 512], 16 | keys_prev: [bool; 512], 17 | keys_down_duration: [f32; 512], 18 | key_repeat_delay: f32, 19 | key_repeat_rate: f32, 20 | } 21 | 22 | impl KeyHandler { 23 | pub fn new() -> KeyHandler { 24 | KeyHandler { 25 | key_callback: None, 26 | keys: [false; 512], 27 | keys_prev: [false; 512], 28 | keys_down_duration: [-1.0; 512], 29 | prev_time: Instant::now(), 30 | delta_time: Duration::from_secs(0), 31 | key_repeat_delay: 0.250, 32 | key_repeat_rate: 0.050, 33 | } 34 | } 35 | 36 | #[inline] 37 | pub fn set_key_state(&mut self, key: Key, state: bool) { 38 | self.keys[key as usize] = state; 39 | if let Some(cb) = &mut self.key_callback { 40 | cb.set_key_state(key, state); 41 | } 42 | } 43 | 44 | pub fn get_keys(&self) -> Vec { 45 | let mut keys: Vec = Vec::new(); 46 | 47 | for (idx, is_down) in self.keys.iter().enumerate() { 48 | if *is_down { 49 | unsafe { 50 | keys.push(std::mem::transmute::(idx as u8)); 51 | } 52 | } 53 | } 54 | 55 | keys 56 | } 57 | 58 | pub fn update(&mut self) { 59 | self.delta_time = self.prev_time.elapsed(); 60 | self.prev_time = Instant::now(); 61 | let delta_time = self.delta_time.as_secs_f32(); 62 | 63 | for idx in 0..self.keys.len() { 64 | if self.keys[idx] { 65 | if self.keys_down_duration[idx] < 0.0 { 66 | self.keys_down_duration[idx] = 0.0; 67 | } else { 68 | self.keys_down_duration[idx] += delta_time; 69 | } 70 | } else { 71 | self.keys_down_duration[idx] = -1.0; 72 | } 73 | self.keys_prev[idx] = self.keys[idx]; 74 | } 75 | } 76 | 77 | #[inline] 78 | pub fn set_input_callback(&mut self, callback: Box) { 79 | self.key_callback = Some(callback); 80 | } 81 | 82 | pub fn get_keys_pressed(&self, repeat: KeyRepeat) -> Vec { 83 | let mut keys: Vec = Vec::new(); 84 | 85 | for (idx, is_down) in self.keys.iter().enumerate() { 86 | if *is_down && self.is_key_index_pressed(idx, repeat) { 87 | unsafe { 88 | keys.push(std::mem::transmute::(idx as u8)); 89 | } 90 | } 91 | } 92 | 93 | keys 94 | } 95 | 96 | pub fn get_keys_released(&self) -> Vec { 97 | let mut keys: Vec = Vec::new(); 98 | 99 | for (idx, is_down) in self.keys.iter().enumerate() { 100 | if !(*is_down) && self.is_key_index_released(idx) { 101 | unsafe { 102 | keys.push(std::mem::transmute::(idx as u8)); 103 | } 104 | } 105 | } 106 | 107 | keys 108 | } 109 | 110 | #[inline] 111 | pub fn is_key_down(&self, key: Key) -> bool { 112 | self.keys[key as usize] 113 | } 114 | 115 | #[inline] 116 | pub fn set_key_repeat_delay(&mut self, delay: f32) { 117 | self.key_repeat_delay = delay; 118 | } 119 | 120 | #[inline] 121 | pub fn set_key_repeat_rate(&mut self, rate: f32) { 122 | self.key_repeat_rate = rate; 123 | } 124 | 125 | fn is_key_index_pressed(&self, index: usize, repeat: KeyRepeat) -> bool { 126 | let t = self.keys_down_duration[index]; 127 | 128 | if t == 0.0 { 129 | return true; 130 | } 131 | 132 | if repeat == KeyRepeat::Yes && t > self.key_repeat_delay { 133 | let delta_time = self.delta_time.as_secs_f32(); 134 | let delay = self.key_repeat_delay; 135 | let rate = self.key_repeat_rate; 136 | if (((t - delay) % rate) > rate * 0.5) 137 | != (((t - delay - delta_time) % rate) > rate * 0.5) 138 | { 139 | return true; 140 | } 141 | } 142 | 143 | false 144 | } 145 | 146 | #[inline] 147 | pub fn is_key_pressed(&self, key: Key, repeat: KeyRepeat) -> bool { 148 | self.is_key_index_pressed(key as usize, repeat) 149 | } 150 | 151 | #[inline] 152 | pub fn is_key_released(&self, key: Key) -> bool { 153 | self.is_key_index_released(key as usize) 154 | } 155 | 156 | #[inline] 157 | fn is_key_index_released(&self, idx: usize) -> bool { 158 | self.keys_prev[idx] && !self.keys[idx] 159 | } 160 | } 161 | -------------------------------------------------------------------------------- /src/native/macosx/OSXWindow.h: -------------------------------------------------------------------------------- 1 | #import 2 | #include "shared_data.h" 3 | 4 | #define MAX_MENUS 512 5 | 6 | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 7 | 8 | typedef struct Menu { 9 | const char* name; 10 | NSMenu* menu; 11 | NSMenuItem* menu_item; 12 | } Menu; 13 | 14 | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 15 | 16 | typedef struct MenuData { 17 | Menu menus[MAX_MENUS]; 18 | int menu_count; 19 | } MenuData; 20 | 21 | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 22 | 23 | typedef struct MenuDesc { 24 | char name[512]; 25 | struct MenuDesc* sub_menu; 26 | int menu_id; 27 | int key; 28 | int special_key; 29 | int modifier; 30 | int modifier_mac; 31 | int enabled; 32 | } MenuDesc; 33 | 34 | void build_submenu(NSMenu* menu, MenuDesc* desc); 35 | 36 | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 37 | 38 | @interface OSXWindow : NSWindow { 39 | NSView* childContentView; 40 | @public void (*key_callback)(void* user_data, int key, int state); 41 | @public void (*char_callback)(void* user_data, unsigned int key); 42 | @public float width; 43 | @public float height; 44 | @public int scale; 45 | @public DrawParameters* draw_parameters; 46 | @public void* rust_data; 47 | @public SharedData* shared_data; 48 | @public bool should_close; 49 | @public bool is_active; 50 | @public int active_menu_id; 51 | @public int prev_cursor; 52 | @public MenuData* menu_data; 53 | @public void* frame_view; 54 | } 55 | @end 56 | -------------------------------------------------------------------------------- /src/native/macosx/OSXWindow.m: -------------------------------------------------------------------------------- 1 | #import "OSXWindow.h" 2 | #import "OSXWindowFrameView.h" 3 | 4 | @implementation OSXWindow 5 | 6 | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 7 | 8 | - (void)dealloc { 9 | [[NSNotificationCenter defaultCenter] 10 | removeObserver:self]; 11 | [super dealloc]; 12 | } 13 | 14 | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 15 | 16 | - (void)setContentSize:(NSSize)newSize { 17 | NSSize sizeDelta = newSize; 18 | NSSize childBoundsSize = [childContentView bounds].size; 19 | sizeDelta.width -= childBoundsSize.width; 20 | sizeDelta.height -= childBoundsSize.height; 21 | 22 | OSXWindowFrameView *frameView = [super contentView]; 23 | NSSize newFrameSize = [frameView bounds].size; 24 | newFrameSize.width += sizeDelta.width; 25 | newFrameSize.height += sizeDelta.height; 26 | 27 | [super setContentSize:newFrameSize]; 28 | } 29 | 30 | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 31 | 32 | -(void)flagsChanged:(NSEvent *)event { 33 | const uint32_t flags = [event modifierFlags]; 34 | 35 | // Ctrl checking - First check device dependent flags, otherwise fallback to none-device dependent 36 | 37 | if ((flags & NX_DEVICELCTLKEYMASK) || (flags & NX_DEVICERCTLKEYMASK)) { 38 | key_callback(rust_data, 0x3b, (flags & NX_DEVICELCTLKEYMASK) ? 1 : 0); // Left Ctrl 39 | key_callback(rust_data, 0x3e, (flags & NX_DEVICERCTLKEYMASK) ? 1 : 0); // Right Ctrl 40 | } else if (flags & NX_CONTROLMASK) { 41 | key_callback(rust_data, 0x3b, 1); // Left Ctrl 42 | key_callback(rust_data, 0x3e, 1); // Right Ctrl 43 | } else { 44 | key_callback(rust_data, 0x3b, 0); // Left Ctrl 45 | key_callback(rust_data, 0x3e, 0); // Right Ctrl 46 | } 47 | 48 | // Shift checking - First check device dependent flags, otherwise fallback to none-device dependent 49 | 50 | if ((flags & NX_DEVICELSHIFTKEYMASK) || (flags & NX_DEVICERSHIFTKEYMASK)) { 51 | key_callback(rust_data, 0x38, (flags & NX_DEVICELSHIFTKEYMASK) ? 1 : 0); // Left Shift 52 | key_callback(rust_data, 0x3c, (flags & NX_DEVICERSHIFTKEYMASK) ? 1 : 0); // Right Shift 53 | } else if (flags & NX_SHIFTMASK) { 54 | key_callback(rust_data, 0x38, 1); // Left Shift 55 | key_callback(rust_data, 0x3c, 1); // Right Shift 56 | } else { 57 | key_callback(rust_data, 0x38, 0); // Left Shift 58 | key_callback(rust_data, 0x3c, 0); // Right Shift 59 | } 60 | 61 | // Alt checking - First check device dependent flags, otherwise fallback to none-device dependent 62 | 63 | if ((flags & NX_DEVICELALTKEYMASK) || (flags & NX_DEVICERALTKEYMASK)) { 64 | key_callback(rust_data, 0x3a, (flags & NX_DEVICELALTKEYMASK) ? 1 : 0); // Left Alt 65 | key_callback(rust_data, 0x3d, (flags & NX_DEVICERALTKEYMASK) ? 1 : 0); // Right Alt 66 | } else if (flags & NX_ALTERNATEMASK) { 67 | key_callback(rust_data, 0x3a, 1); // Left Alt 68 | key_callback(rust_data, 0x3d, 1); // Right Alt 69 | } else { 70 | key_callback(rust_data, 0x3a, 0); // Left Alt 71 | key_callback(rust_data, 0x3d, 0); // Right Alt 72 | } 73 | 74 | // Cmd checking - First check device dependent flags, otherwise fallback to none-device dependent 75 | 76 | if ((flags & NX_DEVICELCMDKEYMASK) || (flags & NX_DEVICERCMDKEYMASK)) { 77 | key_callback(rust_data, 0x37, (flags & NX_DEVICELCMDKEYMASK) ? 1 : 0); // Left Cmd 78 | key_callback(rust_data, 0x36, (flags & NX_DEVICERCMDKEYMASK) ? 1 : 0); // Right Cmd 79 | } else if (flags & NX_COMMANDMASK) { 80 | key_callback(rust_data, 0x37, 1); // Left Cmd 81 | key_callback(rust_data, 0x36, 1); // Right Cmd 82 | } else { 83 | key_callback(rust_data, 0x37, 0); // Left Cmd 84 | key_callback(rust_data, 0x36, 0); // Right Cmd 85 | } 86 | 87 | [super flagsChanged:event]; 88 | } 89 | 90 | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 91 | 92 | - (void)keyDown:(NSEvent *)event { 93 | if (key_callback) { 94 | key_callback(rust_data, [event keyCode], 1); 95 | } 96 | 97 | if (char_callback) { 98 | NSString* characters = [event characters]; 99 | NSUInteger i, length = [characters length]; 100 | 101 | for (i = 0; i < length; i++) { 102 | char_callback(rust_data, [characters characterAtIndex:i]); 103 | } 104 | } 105 | } 106 | 107 | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 108 | 109 | - (void)keyUp:(NSEvent *)event { 110 | if (key_callback) { 111 | key_callback(rust_data, [event keyCode], 0); 112 | } 113 | } 114 | 115 | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 116 | 117 | - (void)mainWindowChanged:(NSNotification *)note { 118 | void* window = [note object]; 119 | 120 | if (window == self) { 121 | self->is_active = true; 122 | } else { 123 | self->is_active = false; 124 | } 125 | } 126 | 127 | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 128 | 129 | - (void)windowWillClose:(NSNotification *)notification { 130 | (void)notification; 131 | should_close = true; 132 | } 133 | 134 | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 135 | 136 | - (BOOL)windowShouldClose:(id)sender { 137 | (void)sender; 138 | should_close = true; 139 | return TRUE; 140 | } 141 | 142 | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 143 | 144 | - (void)setContentView:(NSView *)aView { 145 | if ([childContentView isEqualTo:aView]) { 146 | return; 147 | } 148 | 149 | NSRect bounds = [self frame]; 150 | bounds.origin = NSZeroPoint; 151 | 152 | OSXWindowFrameView* frameView = [super contentView]; 153 | if (!frameView) { 154 | [[NSNotificationCenter defaultCenter] 155 | addObserver:self 156 | selector:@selector(mainWindowChanged:) 157 | name:NSWindowDidBecomeMainNotification 158 | object:self]; 159 | 160 | [[NSNotificationCenter defaultCenter] 161 | addObserver:self 162 | selector:@selector(mainWindowChanged:) 163 | name:NSWindowDidResignMainNotification 164 | object:self]; 165 | 166 | frameView = [[[OSXWindowFrameView alloc] initWithFrame:bounds] autorelease]; 167 | 168 | [super setContentView:frameView]; 169 | } 170 | 171 | frame_view = frameView; 172 | 173 | if (childContentView) { 174 | [childContentView removeFromSuperview]; 175 | } 176 | 177 | //printf("osxwindow: setContentFrameView %p\n", frameView); 178 | //printf("osxwindow: setting controller %p\n", view_controller); 179 | //frameView->m_view_controller = view_controller; 180 | 181 | //NSRect t = [self contentRectForFrameRect:bounds]; 182 | 183 | childContentView = aView; 184 | [childContentView setFrame:[self contentRectForFrameRect:bounds]]; 185 | [childContentView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; 186 | [frameView addSubview:childContentView]; 187 | } 188 | 189 | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 190 | 191 | - (NSView *)contentView { 192 | return childContentView; 193 | } 194 | 195 | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 196 | 197 | - (BOOL)canBecomeKeyWindow { 198 | return YES; 199 | } 200 | 201 | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 202 | 203 | - (BOOL)canBecomeMainWindow { 204 | return YES; 205 | } 206 | 207 | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 208 | 209 | - (NSRect)contentRectForFrameRect:(NSRect)windowFrame { 210 | windowFrame.origin = NSZeroPoint; 211 | return NSInsetRect(windowFrame, 0, 0); 212 | } 213 | 214 | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 215 | 216 | - (void)updateSize { 217 | } 218 | 219 | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 220 | 221 | - (void)onMenuPress:(id)sender { 222 | int menu_id = (int)((NSButton*)sender).tag; 223 | self->active_menu_id = menu_id; 224 | } 225 | 226 | @end 227 | -------------------------------------------------------------------------------- /src/native/macosx/OSXWindowFrameView.h: -------------------------------------------------------------------------------- 1 | #import 2 | #import 3 | #include "shared_data.h" 4 | 5 | // Number of textures in flight (tripple buffered) 6 | #define MaxBuffersInFlight 3 7 | 8 | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 9 | 10 | typedef struct DrawState { 11 | int texture_width; 12 | int texture_height; 13 | id vertex_buffer; 14 | id texture; 15 | } DrawState; 16 | 17 | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 18 | 19 | typedef struct Vertex { 20 | float x,y; 21 | float u,v; 22 | } Vertex; 23 | 24 | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 25 | 26 | typedef struct DelayedTextureDelete { 27 | id texture; 28 | int frame_count; 29 | } DelayedTextureDelete; 30 | 31 | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 32 | 33 | @interface WindowViewController : NSViewController { 34 | @public DrawState m_draw_state[MaxBuffersInFlight]; 35 | @public DelayedTextureDelete m_delayed_delete_textures[MaxBuffersInFlight]; 36 | @public int m_current_buffer; 37 | @public DrawParameters* m_draw_parameters; 38 | @public float m_width; 39 | @public float m_height; 40 | // Used for syncing with CPU/GPU 41 | @public dispatch_semaphore_t m_semaphore; 42 | } 43 | @end 44 | 45 | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 46 | 47 | @interface OSXWindowFrameView : NSView { 48 | @public WindowViewController* m_view_controller; 49 | //@public int scale; 50 | //@public int width; 51 | //@public int height; 52 | //@public void* draw_buffer; 53 | @private NSTrackingArea* trackingArea; 54 | } 55 | @end 56 | -------------------------------------------------------------------------------- /src/native/macosx/OSXWindowFrameView.m: -------------------------------------------------------------------------------- 1 | #import "OSXWindowFrameView.h" 2 | #import "OSXWindow.h" 3 | #import 4 | 5 | id g_metal_device; 6 | id g_command_queue; 7 | id g_library; 8 | id g_pipeline_state; 9 | 10 | enum ScaleMode { 11 | ScaleMode_Stretch, 12 | ScaleMode_AspectRatioStretch, 13 | ScaleMode_Center, 14 | ScaleMode_UpperLeft, 15 | }; 16 | 17 | typedef struct Box { 18 | int x, y, width, height; 19 | } Box; 20 | 21 | static void gen_normalized(Vertex* output, const Box* box, float x, float y, float u, float v) { 22 | // data gets normalized in the shader 23 | float pos_x = box->x / x; 24 | float pos_y = box->y / y; 25 | float width = box->width / x; 26 | float height = box->height / y; 27 | 28 | output[0].x = pos_x; 29 | output[0].y = pos_y; 30 | output[0].u = u; 31 | output[0].v = 0.0f; 32 | 33 | output[1].x = width; 34 | output[1].y = pos_y; 35 | output[1].u = u; 36 | output[1].v = v; 37 | 38 | output[2].x = width; 39 | output[2].y = height; 40 | output[2].u = 0.0f; 41 | output[2].v = v; 42 | 43 | output[3].x = pos_x; 44 | output[3].y = pos_y; 45 | output[3].u = u; 46 | output[3].v = 0.0f; 47 | 48 | output[4].x = width; 49 | output[4].y = height; 50 | output[4].u = 0.0f; 51 | output[4].v = v; 52 | 53 | output[5].x = pos_x; 54 | output[5].y = height; 55 | output[5].u = 0.0f; 56 | output[5].v = 0.0f; 57 | } 58 | 59 | static void calculate_scaling( 60 | Vertex* output, 61 | int buf_width, int buf_height, 62 | int texture_width, int texture_height, 63 | float window_width, float window_height, 64 | int scale_mode 65 | ) { 66 | float x_ratio = (float)window_width; 67 | float y_ratio = (float)window_height; 68 | float v_ratio = (float)buf_width / (float)texture_width; 69 | float u_ratio = (float)buf_height / (float)texture_height; 70 | 71 | switch (scale_mode) { 72 | case ScaleMode_Stretch: { 73 | Box box = { 0, 0, window_width, window_height }; 74 | gen_normalized(output, &box, x_ratio, y_ratio, u_ratio, v_ratio); 75 | break; 76 | } 77 | 78 | case ScaleMode_AspectRatioStretch: { 79 | float buffer_aspect = (float)buf_width / (float)buf_height; 80 | float win_aspect = (float)window_width / (float)(window_height); 81 | 82 | if (buffer_aspect > win_aspect) { 83 | int new_height = (int)(window_width / buffer_aspect); 84 | int offset = (new_height - window_height) / -2; 85 | 86 | Box box = { 0, offset, window_width, offset + new_height }; 87 | gen_normalized(output, &box, x_ratio, y_ratio, u_ratio, v_ratio); 88 | } else { 89 | int new_width = (int)(window_height * buffer_aspect); 90 | int offset = (new_width - window_width) / -2; 91 | 92 | Box box = { offset, 0, offset + new_width, window_height }; 93 | gen_normalized(output, &box, x_ratio, y_ratio, u_ratio, v_ratio); 94 | } 95 | 96 | break; 97 | } 98 | 99 | case ScaleMode_Center: { 100 | int pos_x; 101 | int pos_y; 102 | 103 | if (buf_height > window_height) { 104 | pos_y = -(buf_height - window_height) / 2; 105 | } else { 106 | pos_y = (window_height - buf_height) / 2; 107 | } 108 | 109 | if (buf_width > window_width) { 110 | pos_x = -(buf_width - window_width) / 2; 111 | } else { 112 | pos_x = (window_width - buf_width) / 2; 113 | } 114 | 115 | int height = buf_height + pos_y; 116 | int width = buf_width + pos_x; 117 | 118 | Box box = { pos_x, pos_y, width, height }; 119 | gen_normalized(output, &box, x_ratio, y_ratio, u_ratio, v_ratio); 120 | 121 | break; 122 | } 123 | 124 | case ScaleMode_UpperLeft: { 125 | int pos_y; 126 | 127 | if (buf_height > window_height) { 128 | pos_y = -(buf_height - window_height); 129 | } else { 130 | pos_y = (window_height - buf_height); 131 | } 132 | 133 | Box box = { 0, pos_y, buf_width, buf_height + pos_y }; 134 | gen_normalized(output, &box, x_ratio, y_ratio, u_ratio, v_ratio); 135 | 136 | break; 137 | } 138 | 139 | default: { 140 | break; 141 | } 142 | } 143 | } 144 | 145 | 146 | @implementation WindowViewController 147 | - (void)mtkView:(nonnull MTKView *)view drawableSizeWillChange:(CGSize)size { 148 | (void)size; 149 | (void)view; 150 | 151 | NSSize new_size = [view bounds].size; 152 | m_width = new_size.width; 153 | m_height = new_size.height; 154 | } 155 | 156 | uint32_t upper_power_of_two(uint32_t v) { 157 | v--; 158 | v |= v >> 1; 159 | v |= v >> 2; 160 | v |= v >> 4; 161 | v |= v >> 8; 162 | v |= v >> 16; 163 | v++; 164 | return v; 165 | } 166 | 167 | - (void)drawInMTKView:(nonnull MTKView *)view { 168 | const int buffer_width = m_draw_parameters->buffer_width; 169 | const int buffer_height = m_draw_parameters->buffer_height; 170 | 171 | if (!m_draw_parameters->buffer) { 172 | return; 173 | } 174 | 175 | // Wait to ensure only MaxBuffersInFlight number of frames are getting proccessed 176 | // by any stage in the Metal pipeline (App, Metal, Drivers, GPU, etc) 177 | dispatch_semaphore_wait(m_semaphore, DISPATCH_TIME_FOREVER); 178 | 179 | // Iterate through our Metal buffers, and cycle back to the first when we've written to MaxBuffersInFlight 180 | m_current_buffer = (m_current_buffer + 1) % MaxBuffersInFlight; 181 | 182 | for (int i = 0; i < MaxBuffersInFlight; ++i) { 183 | DelayedTextureDelete* del_texture = &m_delayed_delete_textures[i]; 184 | int frame_count = del_texture->frame_count - 1; 185 | 186 | if (frame_count == 0) { 187 | //printf("freeing texture\n"); 188 | [del_texture->texture setPurgeableState:MTLPurgeableStateEmpty]; 189 | [del_texture->texture release]; 190 | del_texture->frame_count = -1; 191 | } else if (frame_count > 0) { 192 | del_texture->frame_count = frame_count; 193 | } 194 | } 195 | 196 | DrawState* draw_state = &m_draw_state[m_current_buffer]; 197 | 198 | // make sure the current buffer fits in the texture, otherwise allocate a new one 199 | 200 | if (buffer_width > draw_state->texture_width || buffer_height > draw_state->texture_height) { 201 | 202 | //printf("buffer size %d %d\n", buffer_width, buffer_height); 203 | //printf("old texture size %d %d\n", draw_state->texture_width, draw_state->texture_height); 204 | 205 | int new_width = upper_power_of_two(buffer_width); 206 | int new_height = upper_power_of_two(buffer_height); 207 | 208 | //printf("allocating new texture at size %d %d\n", new_width, new_height); 209 | 210 | MTLTextureDescriptor* texture_desc = [[MTLTextureDescriptor alloc] init]; 211 | 212 | // Indicate that each pixel has a blue, green, red, and alpha channel, where each channel is 213 | // an 8-bit unsigned normalized value (i.e. 0 maps to 0.0 and 255 maps to 1.0) 214 | texture_desc.pixelFormat = MTLPixelFormatBGRA8Unorm; 215 | 216 | // Set the pixel dimensions of the texture 217 | texture_desc.width = new_width; 218 | texture_desc.height = new_height; 219 | 220 | // Allocate the now texture 221 | 222 | id texture = [view.device newTextureWithDescriptor:texture_desc]; 223 | 224 | if (texture == 0) { 225 | printf("Failed to create texture of size %d - %d. Please report this issue. Skipping rendering\n", 226 | new_width, new_height); 227 | return; 228 | } 229 | 230 | bool found_del_slot = false; 231 | 232 | // Put the old texture up for deleting and fail if there are no free slots around. 233 | 234 | for (int i = 0; i < MaxBuffersInFlight; ++i) { 235 | if (m_delayed_delete_textures[i].frame_count == -1) { 236 | m_delayed_delete_textures[i].texture = draw_state->texture; 237 | m_delayed_delete_textures[i].frame_count = MaxBuffersInFlight; 238 | found_del_slot = true; 239 | break; 240 | } 241 | } 242 | 243 | if (!found_del_slot) { 244 | printf("Unable to delete texture!\n"); 245 | } 246 | 247 | draw_state->texture = texture; 248 | draw_state->texture_width = new_width; 249 | draw_state->texture_height = new_height; 250 | } 251 | 252 | // Calculate the number of bytes per row of our image. 253 | NSUInteger bytesPerRow = 4 * m_draw_parameters->buffer_stride; 254 | MTLRegion region = { 255 | { 0, 0, 0 }, 256 | { m_draw_parameters->buffer_width, m_draw_parameters->buffer_height, 1 } 257 | }; 258 | 259 | //printf("updating texture with %p\n", m_draw_parameters->buffer); 260 | 261 | // Copy the bytes from our data object into the texture 262 | [draw_state->texture replaceRegion:region 263 | mipmapLevel:0 withBytes:m_draw_parameters->buffer bytesPerRow:bytesPerRow]; 264 | 265 | // Update the vertex buffer 266 | calculate_scaling( 267 | draw_state->vertex_buffer.contents, 268 | m_draw_parameters->buffer_width, m_draw_parameters->buffer_height, 269 | draw_state->texture_width, draw_state->texture_height, 270 | m_width, m_height, 271 | m_draw_parameters->scale_mode); 272 | 273 | // Create a new command buffer for each render pass to the current drawable 274 | id commandBuffer = [g_command_queue commandBuffer]; 275 | commandBuffer.label = @"minifb_command_buffer"; 276 | 277 | // Add completion hander which signals _inFlightSemaphore when Metal and the GPU has fully 278 | // finished processing the commands we're encoding this frame. This indicates when the 279 | // dynamic buffers filled with our vertices, that we're writing to this frame, will no longer 280 | // be needed by Metal and the GPU, meaning we can overwrite the buffer contents without 281 | // corrupting the rendering. 282 | __block dispatch_semaphore_t block_sema = m_semaphore; 283 | [commandBuffer addCompletedHandler:^(id buffer) 284 | { 285 | (void)buffer; 286 | dispatch_semaphore_signal(block_sema); 287 | }]; 288 | 289 | MTLRenderPassDescriptor* renderPassDescriptor = view.currentRenderPassDescriptor; 290 | 291 | if (renderPassDescriptor != nil) { 292 | float red = ((m_draw_parameters->bg_color >> 16) & 0xff) * 1.0f / 255.0f; 293 | float green = ((m_draw_parameters->bg_color >> 8) & 0xff) * 1.0f / 255.0f; 294 | float blue = ((m_draw_parameters->bg_color >> 0) & 0xff) * 1.0f / 255.0f; 295 | 296 | renderPassDescriptor.colorAttachments[0].clearColor = MTLClearColorMake(red, green, blue, 1.0); 297 | 298 | // Create a render command encoder so we can render into something 299 | id renderEncoder = 300 | [commandBuffer renderCommandEncoderWithDescriptor:renderPassDescriptor]; 301 | renderEncoder.label = @"minifb_command_encoder"; 302 | 303 | // Set render command encoder state 304 | [renderEncoder setRenderPipelineState:g_pipeline_state]; 305 | 306 | [renderEncoder setFragmentTexture:draw_state->texture atIndex:0]; 307 | [renderEncoder setVertexBuffer:draw_state->vertex_buffer offset:0 atIndex:0]; 308 | 309 | // Draw the vertices of our quads 310 | [renderEncoder drawPrimitives:MTLPrimitiveTypeTriangle 311 | vertexStart:0 312 | vertexCount:6]; 313 | 314 | // We're done encoding commands 315 | [renderEncoder endEncoding]; 316 | 317 | // Schedule a present once the framebuffer is complete using the current drawable 318 | [commandBuffer presentDrawable:view.currentDrawable]; 319 | } 320 | 321 | // Finalize rendering here & push the command buffer to the GPU 322 | [commandBuffer commit]; 323 | } 324 | @end 325 | 326 | @implementation OSXWindowFrameView 327 | 328 | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 329 | 330 | - (void)updateTrackingAreas { 331 | if(trackingArea != nil) { 332 | [self removeTrackingArea:trackingArea]; 333 | [trackingArea release]; 334 | } 335 | 336 | int opts = (NSTrackingMouseEnteredAndExited | NSTrackingActiveAlways); 337 | trackingArea = [ [NSTrackingArea alloc] initWithRect:[self bounds] 338 | options:opts 339 | owner:self 340 | userInfo:nil]; 341 | [self addTrackingArea:trackingArea]; 342 | } 343 | 344 | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 345 | 346 | - (void)mouseDown:(NSEvent*)event { 347 | (void)event; 348 | OSXWindow* window = (OSXWindow*)[self window]; 349 | window->shared_data->mouse_state[0] = 1; 350 | } 351 | 352 | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 353 | 354 | - (void)mouseUp:(NSEvent*)event { 355 | (void)event; 356 | OSXWindow* window = (OSXWindow*)[self window]; 357 | window->shared_data->mouse_state[0] = 0; 358 | } 359 | 360 | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 361 | 362 | - (void)rightMouseDown:(NSEvent*)event { 363 | (void)event; 364 | OSXWindow* window = (OSXWindow*)[self window]; 365 | window->shared_data->mouse_state[2] = 1; 366 | } 367 | 368 | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 369 | 370 | - (void)rightMouseUp:(NSEvent*)event { 371 | (void)event; 372 | OSXWindow* window = (OSXWindow*)[self window]; 373 | window->shared_data->mouse_state[2] = 0; 374 | } 375 | 376 | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 377 | 378 | - (void)scrollWheel:(NSEvent *)event { 379 | OSXWindow* window = (OSXWindow*)[self window]; 380 | window->shared_data->scroll_x = [event deltaX]; 381 | window->shared_data->scroll_y = [event deltaY]; 382 | } 383 | 384 | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 385 | 386 | - (BOOL)canBecomeKeyView { 387 | return YES; 388 | } 389 | 390 | - (NSView *)nextValidKeyView { 391 | return self; 392 | } 393 | 394 | - (NSView *)previousValidKeyView { 395 | return self; 396 | } 397 | 398 | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 399 | 400 | - (BOOL)acceptsFirstResponder { 401 | return YES; 402 | } 403 | 404 | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 405 | 406 | - (void)viewDidMoveToWindow { 407 | [[NSNotificationCenter defaultCenter] addObserver:self 408 | selector:@selector(windowResized:) name:NSWindowDidResizeNotification 409 | object:[self window]]; 410 | } 411 | 412 | - (void)viewDidEndLiveResize { 413 | //NSRect originalFrame = [win frame]; 414 | //NSRect contentRect = [NSWindow contentRectForFrameRect: originalFrame styleMask: NSWindowStyleMaskTitled]; 415 | NSSize size = [self bounds].size; 416 | //NSSize size = [[self contentView] frame].size; 417 | OSXWindow* window = (OSXWindow*)[self window]; 418 | 419 | int width = (int)size.width; 420 | int height = (int)size.height; 421 | 422 | //m_view_controller->m_width = (int)width; 423 | //m_view_controller->m_height = (int)height; 424 | 425 | // if windows is resized we need to create new textures so we do that here and put the old textures in a 426 | // "to delete" queue and set a frame counter of 3 frames before the gets released 427 | 428 | if (window->shared_data) { 429 | window->shared_data->width = width; 430 | window->shared_data->height = height; 431 | } 432 | } 433 | 434 | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 435 | 436 | - (void)dealloc { 437 | [[NSNotificationCenter defaultCenter] removeObserver:self]; 438 | [super dealloc]; 439 | } 440 | 441 | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 442 | 443 | - (void)windowResized:(NSNotification *)notification { 444 | (void)notification; 445 | } 446 | 447 | @end 448 | -------------------------------------------------------------------------------- /src/native/macosx/shared_data.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | typedef struct SharedData { 4 | unsigned int bg_color; 5 | unsigned int scale_mode; 6 | unsigned int width; 7 | unsigned int height; 8 | float mouse_x; 9 | float mouse_y; 10 | float scroll_x; 11 | float scroll_y; 12 | unsigned char mouse_state[8]; 13 | } SharedData; 14 | 15 | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 16 | 17 | typedef struct DrawParameters { 18 | void* buffer; 19 | unsigned int bg_color; 20 | int buffer_width; 21 | int buffer_height; 22 | int buffer_stride; 23 | int scale_mode; 24 | } DrawParameters; 25 | -------------------------------------------------------------------------------- /src/native/posix/scalar.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void image_resize_linear( 4 | uint32_t* dst, 5 | const uint32_t dst_width, 6 | const uint32_t dst_height, 7 | const uint32_t* src, 8 | const uint32_t src_width, 9 | const uint32_t src_height, 10 | const uint32_t src_stride 11 | ) { 12 | const float x_ratio = (float)(src_width) / (float)(dst_width); 13 | const float y_ratio = (float)(src_height) / (float)(dst_height); 14 | const int step_x = x_ratio * 1024.0f; 15 | const int step_y = y_ratio * 1024.0f; 16 | int fixed_y = 0; 17 | 18 | for (uint32_t i = 0; i < dst_height; i++) { 19 | const int y = (fixed_y >> 10) * src_stride; 20 | int fixed_x = 0; 21 | for (uint32_t j = 0; j < dst_width; j++) { 22 | int x = fixed_x >> 10; 23 | int index = (y + x); 24 | *dst++ = src[index]; 25 | fixed_x += step_x; 26 | } 27 | fixed_y += step_y; 28 | } 29 | } 30 | 31 | static void image_resize_linear_stride( 32 | uint32_t* dst, 33 | const uint32_t dst_width, 34 | const uint32_t dst_height, 35 | const uint32_t* src, 36 | const uint32_t src_width, 37 | const uint32_t src_height, 38 | const uint32_t src_stride, 39 | const uint32_t stride 40 | ) { 41 | const float x_ratio = (float)(src_width) / (float)(dst_width); 42 | const float y_ratio = (float)(src_height) / (float)(dst_height); 43 | const int step_x = x_ratio * 1024.0f; 44 | const int step_y = y_ratio * 1024.0f; 45 | const int stride_step = stride - dst_width; 46 | int fixed_y = 0; 47 | 48 | for (uint32_t i = 0; i < dst_height; i++) { 49 | const int y = (fixed_y >> 10) * src_stride; 50 | int fixed_x = 0; 51 | for (uint32_t j = 0; j < dst_width; j++) { 52 | const int x = fixed_x >> 10; 53 | const int index = (y + x); 54 | *dst++ = src[index]; 55 | fixed_x += step_x; 56 | } 57 | dst += stride_step; 58 | fixed_y += step_y; 59 | } 60 | } 61 | 62 | void image_resize_linear_aspect_fill( 63 | uint32_t* dst, 64 | const uint32_t dst_width, 65 | const uint32_t dst_height, 66 | const uint32_t* src, 67 | const uint32_t src_width, 68 | const uint32_t src_height, 69 | const uint32_t src_stride, 70 | const uint32_t bg_clear 71 | ) { 72 | // TODO: Optimize by only clearing the areas the image blit doesn't fill 73 | for (uint32_t i = 0; i < dst_width * dst_height; ++i) { 74 | dst[i] = bg_clear; 75 | } 76 | 77 | const float buffer_aspect = (float)(src_width) / (float)(src_height); 78 | const float win_aspect = (float)(dst_width) / (float)(dst_height); 79 | 80 | if (buffer_aspect > win_aspect) { 81 | const uint32_t new_height = (uint32_t)(dst_width / buffer_aspect); 82 | const int offset = (new_height - dst_height) / -2; 83 | image_resize_linear( 84 | dst + (offset * dst_width), 85 | dst_width, new_height, 86 | src, src_width, src_height, src_stride 87 | ); 88 | } else { 89 | const uint32_t new_width = (uint32_t)(dst_height * buffer_aspect); 90 | const int offset = (new_width - dst_width) / -2; 91 | image_resize_linear_stride( 92 | dst + offset, 93 | new_width, dst_height, 94 | src, src_width, src_height, src_stride, 95 | dst_width 96 | ); 97 | } 98 | } 99 | 100 | void image_center( 101 | uint32_t* dst, 102 | const uint32_t dst_width, 103 | const uint32_t dst_height, 104 | const uint32_t* src, 105 | const uint32_t src_width, 106 | const uint32_t src_height, 107 | const uint32_t src_stride, 108 | const uint32_t bg_clear 109 | ) { 110 | // TODO: Optimize by only clearing the areas the image blit doesn't fill 111 | for (uint32_t i = 0; i < dst_width * dst_height; ++i) { 112 | dst[i] = bg_clear; 113 | } 114 | 115 | if (src_height > dst_height) { 116 | const int y_offset = (src_height - dst_height) / 2; 117 | uint32_t new_height = src_height - y_offset; 118 | src += y_offset * src_stride; 119 | 120 | if (new_height > dst_height) 121 | new_height = dst_height; 122 | 123 | if (src_width > dst_width) { 124 | const int x_offset = (src_width - dst_width) / 2; 125 | src += x_offset; 126 | 127 | for (uint32_t y = 0; y < dst_height; ++y) { 128 | for (uint32_t x = 0; x < dst_width; ++x) { 129 | *dst++ = *src++; 130 | } 131 | src += (src_stride - dst_width); 132 | } 133 | } else { 134 | const int x_offset = (dst_width - src_width) / 2; 135 | 136 | for (uint32_t y = 0; y < new_height; ++y) { 137 | dst += x_offset; 138 | 139 | for (uint32_t x = 0; x < src_width; ++x) { 140 | *dst++ = *src++; 141 | } 142 | dst += (dst_width - (src_width + x_offset)); 143 | src += src_stride - src_width; 144 | } 145 | } 146 | } else { 147 | const int y_offset = (dst_height - src_height) / 2; 148 | dst += y_offset * dst_width; 149 | 150 | if (src_width > dst_width) { 151 | const int x_offset = (src_width - dst_width) / 2; 152 | src += x_offset; 153 | 154 | for (uint32_t y = 0; y < src_height; ++y) { 155 | for (uint32_t x = 0; x < dst_width; ++x) { 156 | *dst++ = *src++; 157 | } 158 | src += (src_stride - dst_width); 159 | } 160 | } else { 161 | const int x_offset = (dst_width - src_width) / 2; 162 | dst += x_offset; 163 | 164 | for (uint32_t y = 0; y < src_height; ++y) { 165 | for (uint32_t x = 0; x < src_width; ++x) { 166 | *dst++ = *src++; 167 | } 168 | dst += (dst_width - src_width); 169 | src += src_stride - src_width; 170 | } 171 | } 172 | } 173 | } 174 | 175 | void image_upper_left( 176 | uint32_t* dst, 177 | const uint32_t dst_width, 178 | const uint32_t dst_height, 179 | const uint32_t* src, 180 | const uint32_t src_width, 181 | const uint32_t src_height, 182 | const uint32_t src_stride, 183 | const uint32_t bg_clear 184 | ) { 185 | // TODO: Optimize by only clearing the areas the image blit doesn't fill 186 | for (uint32_t i = 0; i < dst_width * dst_height; ++i) { 187 | dst[i] = bg_clear; 188 | } 189 | 190 | if (src_height > dst_height) { 191 | const int y_offset = (src_height - dst_height) / 2; 192 | const uint32_t new_height = src_height - y_offset; 193 | 194 | if (src_width > dst_width) { 195 | for (uint32_t y = 0; y < dst_height; ++y) { 196 | for (uint32_t x = 0; x < dst_width; ++x) { 197 | *dst++ = *src++; 198 | } 199 | src += (src_stride - dst_width); 200 | } 201 | } else { 202 | for (uint32_t y = 0; y < new_height; ++y) { 203 | for (uint32_t x = 0; x < src_width; ++x) { 204 | *dst++ = *src++; 205 | } 206 | dst += (dst_width - src_width); 207 | src += src_stride - src_width; 208 | } 209 | } 210 | } else { 211 | if (src_width > dst_width) { 212 | for (uint32_t y = 0; y < src_height; ++y) { 213 | for (uint32_t x = 0; x < dst_width; ++x) { 214 | *dst++ = *src++; 215 | } 216 | src += (src_stride - dst_width); 217 | } 218 | } else { 219 | for (uint32_t y = 0; y < src_height; ++y) { 220 | for (uint32_t x = 0; x < src_width; ++x) { 221 | *dst++ = *src++; 222 | } 223 | dst += (dst_width - src_width); 224 | src += src_stride - src_width; 225 | } 226 | } 227 | } 228 | } 229 | -------------------------------------------------------------------------------- /src/os/mod.rs: -------------------------------------------------------------------------------- 1 | #[cfg(target_os = "macos")] 2 | pub mod macos; 3 | #[cfg(any( 4 | target_os = "linux", 5 | target_os = "freebsd", 6 | target_os = "dragonfly", 7 | target_os = "netbsd", 8 | target_os = "openbsd" 9 | ))] 10 | pub mod posix; 11 | #[cfg(target_os = "redox")] 12 | pub mod redox; 13 | #[cfg(target_arch = "wasm32")] 14 | pub mod wasm; 15 | #[cfg(target_os = "windows")] 16 | pub mod windows; 17 | -------------------------------------------------------------------------------- /src/os/posix/common.rs: -------------------------------------------------------------------------------- 1 | use crate::{Key, MenuHandle, MenuItem, MenuItemHandle, Result, UnixMenu, UnixMenuItem}; 2 | 3 | pub struct Menu { 4 | pub internal: UnixMenu, 5 | } 6 | 7 | impl Menu { 8 | pub fn new(name: &str) -> Result { 9 | Ok(Menu { 10 | internal: UnixMenu { 11 | handle: MenuHandle(0), 12 | item_counter: MenuItemHandle(0), 13 | name: name.to_owned(), 14 | items: Vec::new(), 15 | }, 16 | }) 17 | } 18 | 19 | #[inline] 20 | pub fn add_sub_menu(&mut self, name: &str, sub_menu: &Menu) { 21 | let handle = self.next_item_handle(); 22 | self.internal.items.push(UnixMenuItem { 23 | label: name.to_owned(), 24 | handle, 25 | sub_menu: Some(Box::new(sub_menu.internal.clone())), 26 | id: 0, 27 | enabled: true, 28 | key: Key::Unknown, 29 | modifier: 0, 30 | }); 31 | } 32 | 33 | #[inline] 34 | fn next_item_handle(&mut self) -> MenuItemHandle { 35 | let handle = self.internal.item_counter; 36 | self.internal.item_counter.0 += 1; 37 | handle 38 | } 39 | 40 | #[inline] 41 | pub fn add_menu_item(&mut self, item: &MenuItem) -> MenuItemHandle { 42 | let item_handle = self.next_item_handle(); 43 | self.internal.items.push(UnixMenuItem { 44 | sub_menu: None, 45 | handle: self.internal.item_counter, 46 | id: item.id, 47 | label: item.label.clone(), 48 | enabled: item.enabled, 49 | key: item.key, 50 | modifier: item.modifier, 51 | }); 52 | item_handle 53 | } 54 | 55 | #[inline] 56 | pub fn remove_item(&mut self, handle: &MenuItemHandle) { 57 | self.internal.items.retain(|item| item.handle.0 != handle.0); 58 | } 59 | } 60 | 61 | // These functions are implemented in C in order to always have 62 | // optimizations on (`-O3`), allowing debug builds to run fast as well. 63 | extern "C" { 64 | pub(crate) fn image_upper_left( 65 | dst: *mut u32, 66 | dst_width: u32, 67 | dst_height: u32, 68 | src: *const u32, 69 | src_width: u32, 70 | src_height: u32, 71 | src_stride: u32, 72 | bg_color: u32, 73 | ); 74 | 75 | pub(crate) fn image_center( 76 | dst: *mut u32, 77 | dst_width: u32, 78 | dst_height: u32, 79 | src: *const u32, 80 | src_width: u32, 81 | src_height: u32, 82 | src_stride: u32, 83 | bg_color: u32, 84 | ); 85 | 86 | pub(crate) fn image_resize_linear_aspect_fill( 87 | dst: *mut u32, 88 | dst_width: u32, 89 | dst_height: u32, 90 | src: *const u32, 91 | src_width: u32, 92 | src_height: u32, 93 | src_stride: u32, 94 | bg_color: u32, 95 | ); 96 | 97 | pub(crate) fn image_resize_linear( 98 | dst: *mut u32, 99 | dst_width: u32, 100 | dst_height: u32, 101 | src: *const u32, 102 | src_width: u32, 103 | src_height: u32, 104 | src_stride: u32, 105 | ); 106 | } 107 | -------------------------------------------------------------------------------- /src/os/posix/mod.rs: -------------------------------------------------------------------------------- 1 | #![cfg(any( 2 | target_os = "linux", 3 | target_os = "freebsd", 4 | target_os = "dragonfly", 5 | target_os = "netbsd", 6 | target_os = "openbsd" 7 | ))] 8 | // turn off a gazillion warnings about X keysym names 9 | #![allow(non_upper_case_globals)] 10 | 11 | mod common; 12 | 13 | #[cfg(feature = "wayland")] 14 | mod wayland; 15 | #[cfg(feature = "x11")] 16 | mod x11; 17 | #[cfg(feature = "wayland")] 18 | mod xkb_ffi; 19 | #[cfg(feature = "wayland")] 20 | mod xkb_keysyms; 21 | 22 | use crate::{ 23 | icon::Icon, CursorStyle, InputCallback, Key, KeyRepeat, MenuHandle, MouseButton, MouseMode, 24 | Result, UnixMenu, WindowOptions, 25 | }; 26 | pub use common::Menu; 27 | use raw_window_handle::{ 28 | DisplayHandle, HandleError, HasDisplayHandle, HasWindowHandle, WindowHandle, 29 | }; 30 | use std::{ffi::c_void, time::Duration}; 31 | 32 | // Differentiate between Wayland and X11 at run-time 33 | #[allow(clippy::large_enum_variant)] 34 | pub enum Window { 35 | #[cfg(feature = "x11")] 36 | X11(x11::Window), 37 | #[cfg(feature = "wayland")] 38 | Wayland(wayland::Window), 39 | } 40 | 41 | impl Window { 42 | #[cfg(all(feature = "x11", feature = "wayland"))] 43 | pub fn new(name: &str, width: usize, height: usize, opts: WindowOptions) -> Result { 44 | // Try to create Wayland display first 45 | let wl_window = wayland::Window::new(name, width, height, opts); 46 | match wl_window { 47 | Ok(w) => Ok(Window::Wayland(w)), 48 | Err(_) => { 49 | // Create X11 Window when Wayland fails 50 | let window = Window::X11(x11::Window::new(name, width, height, opts)?); 51 | Ok(window) 52 | } 53 | } 54 | } 55 | 56 | #[cfg(all(feature = "wayland", not(feature = "x11")))] 57 | pub fn new(name: &str, width: usize, height: usize, opts: WindowOptions) -> Result { 58 | let wl_window = wayland::Window::new(name, width, height, opts)?; 59 | Ok(Window::Wayland(wl_window)) 60 | } 61 | 62 | #[cfg(all(feature = "x11", not(feature = "wayland")))] 63 | pub fn new(name: &str, width: usize, height: usize, opts: WindowOptions) -> Result { 64 | let window = Window::X11(x11::Window::new(name, width, height, opts)?); 65 | Ok(window) 66 | } 67 | 68 | pub fn set_title(&mut self, title: &str) { 69 | match self { 70 | #[cfg(feature = "x11")] 71 | Window::X11(w) => w.set_title(title), 72 | #[cfg(feature = "wayland")] 73 | Window::Wayland(w) => w.set_title(title), 74 | } 75 | } 76 | 77 | pub fn set_icon(&mut self, icon: Icon) { 78 | match self { 79 | #[cfg(feature = "x11")] 80 | Window::X11(w) => w.set_icon(icon), 81 | #[cfg(feature = "wayland")] 82 | Window::Wayland(_w) => { 83 | unimplemented!("Cannot set icons at runtime on Wayland, create a .desktop file!") 84 | } 85 | } 86 | } 87 | 88 | pub fn update_with_buffer_stride( 89 | &mut self, 90 | buffer: &[u32], 91 | buf_width: usize, 92 | buf_height: usize, 93 | buf_stride: usize, 94 | ) -> Result<()> { 95 | match self { 96 | #[cfg(feature = "x11")] 97 | Window::X11(w) => { 98 | w.update_with_buffer_stride(buffer, buf_width, buf_height, buf_stride) 99 | } 100 | #[cfg(feature = "wayland")] 101 | Window::Wayland(w) => { 102 | w.update_with_buffer_stride(buffer, buf_width, buf_height, buf_stride) 103 | } 104 | } 105 | } 106 | 107 | pub fn update(&mut self) { 108 | match self { 109 | #[cfg(feature = "x11")] 110 | Window::X11(w) => w.update(), 111 | #[cfg(feature = "wayland")] 112 | Window::Wayland(w) => w.update(), 113 | } 114 | } 115 | 116 | pub fn get_window_handle(&self) -> *mut c_void { 117 | match self { 118 | #[cfg(feature = "x11")] 119 | Window::X11(w) => w.get_window_handle(), 120 | #[cfg(feature = "wayland")] 121 | Window::Wayland(w) => w.get_window_handle(), 122 | } 123 | } 124 | 125 | pub fn set_background_color(&mut self, bg_color: u32) { 126 | match self { 127 | #[cfg(feature = "x11")] 128 | Window::X11(w) => w.set_background_color(bg_color), 129 | #[cfg(feature = "wayland")] 130 | Window::Wayland(w) => w.set_background_color(bg_color), 131 | } 132 | } 133 | 134 | pub fn set_cursor_visibility(&mut self, visibility: bool) { 135 | match self { 136 | #[cfg(feature = "x11")] 137 | Window::X11(w) => w.set_cursor_visibility(visibility), 138 | #[cfg(feature = "wayland")] 139 | Window::Wayland(w) => w.set_cursor_visibility(visibility), 140 | } 141 | } 142 | 143 | pub fn set_position(&mut self, x: isize, y: isize) { 144 | match self { 145 | #[cfg(feature = "x11")] 146 | Window::X11(w) => w.set_position(x, y), 147 | #[cfg(feature = "wayland")] 148 | Window::Wayland(w) => w.set_position(x, y), 149 | } 150 | } 151 | 152 | pub fn get_position(&self) -> (isize, isize) { 153 | match self { 154 | #[cfg(feature = "x11")] 155 | Window::X11(w) => w.get_position(), 156 | #[cfg(feature = "wayland")] 157 | Window::Wayland(w) => w.get_position(), 158 | } 159 | } 160 | 161 | pub fn topmost(&self, _topmost: bool) { 162 | // We will just do nothing until it is implemented so that nothing breaks 163 | } 164 | 165 | pub fn get_size(&self) -> (usize, usize) { 166 | match self { 167 | #[cfg(feature = "x11")] 168 | Window::X11(w) => w.get_size(), 169 | #[cfg(feature = "wayland")] 170 | Window::Wayland(w) => w.get_size(), 171 | } 172 | } 173 | 174 | pub fn get_mouse_pos(&self, mode: MouseMode) -> Option<(f32, f32)> { 175 | match self { 176 | #[cfg(feature = "x11")] 177 | Window::X11(w) => w.get_mouse_pos(mode), 178 | #[cfg(feature = "wayland")] 179 | Window::Wayland(w) => w.get_mouse_pos(mode), 180 | } 181 | } 182 | 183 | pub fn get_unscaled_mouse_pos(&self, mode: MouseMode) -> Option<(f32, f32)> { 184 | match self { 185 | #[cfg(feature = "x11")] 186 | Window::X11(w) => w.get_unscaled_mouse_pos(mode), 187 | #[cfg(feature = "wayland")] 188 | Window::Wayland(w) => w.get_unscaled_mouse_pos(mode), 189 | } 190 | } 191 | 192 | pub fn get_mouse_down(&self, button: MouseButton) -> bool { 193 | match self { 194 | #[cfg(feature = "x11")] 195 | Window::X11(w) => w.get_mouse_down(button), 196 | #[cfg(feature = "wayland")] 197 | Window::Wayland(w) => w.get_mouse_down(button), 198 | } 199 | } 200 | 201 | pub fn get_scroll_wheel(&self) -> Option<(f32, f32)> { 202 | match self { 203 | #[cfg(feature = "x11")] 204 | Window::X11(w) => w.get_scroll_wheel(), 205 | #[cfg(feature = "wayland")] 206 | Window::Wayland(w) => w.get_scroll_wheel(), 207 | } 208 | } 209 | 210 | pub fn set_cursor_style(&mut self, cursor: CursorStyle) { 211 | match self { 212 | #[cfg(feature = "x11")] 213 | Window::X11(w) => w.set_cursor_style(cursor), 214 | #[cfg(feature = "wayland")] 215 | Window::Wayland(w) => w.set_cursor_style(cursor), 216 | } 217 | } 218 | 219 | pub fn set_rate(&mut self, rate: Option) { 220 | match self { 221 | #[cfg(feature = "x11")] 222 | Window::X11(w) => w.set_rate(rate), 223 | #[cfg(feature = "wayland")] 224 | Window::Wayland(w) => w.set_rate(rate), 225 | } 226 | } 227 | 228 | pub fn update_rate(&mut self) { 229 | match self { 230 | #[cfg(feature = "x11")] 231 | Window::X11(w) => w.update_rate(), 232 | #[cfg(feature = "wayland")] 233 | Window::Wayland(w) => w.update_rate(), 234 | } 235 | } 236 | 237 | pub fn get_keys(&self) -> Vec { 238 | match self { 239 | #[cfg(feature = "x11")] 240 | Window::X11(w) => w.get_keys(), 241 | #[cfg(feature = "wayland")] 242 | Window::Wayland(w) => w.get_keys(), 243 | } 244 | } 245 | 246 | pub fn get_keys_pressed(&self, repeat: KeyRepeat) -> Vec { 247 | match self { 248 | #[cfg(feature = "x11")] 249 | Window::X11(w) => w.get_keys_pressed(repeat), 250 | #[cfg(feature = "wayland")] 251 | Window::Wayland(w) => w.get_keys_pressed(repeat), 252 | } 253 | } 254 | 255 | pub fn get_keys_released(&self) -> Vec { 256 | match self { 257 | #[cfg(feature = "x11")] 258 | Window::X11(w) => w.get_keys_released(), 259 | #[cfg(feature = "wayland")] 260 | Window::Wayland(w) => w.get_keys_released(), 261 | } 262 | } 263 | 264 | pub fn is_key_down(&self, key: Key) -> bool { 265 | match self { 266 | #[cfg(feature = "x11")] 267 | Window::X11(w) => w.is_key_down(key), 268 | #[cfg(feature = "wayland")] 269 | Window::Wayland(w) => w.is_key_down(key), 270 | } 271 | } 272 | 273 | pub fn set_key_repeat_delay(&mut self, delay: f32) { 274 | match self { 275 | #[cfg(feature = "x11")] 276 | Window::X11(w) => w.set_key_repeat_delay(delay), 277 | #[cfg(feature = "wayland")] 278 | Window::Wayland(w) => w.set_key_repeat_delay(delay), 279 | } 280 | } 281 | 282 | pub fn set_key_repeat_rate(&mut self, rate: f32) { 283 | match self { 284 | #[cfg(feature = "x11")] 285 | Window::X11(w) => w.set_key_repeat_rate(rate), 286 | #[cfg(feature = "wayland")] 287 | Window::Wayland(w) => w.set_key_repeat_rate(rate), 288 | } 289 | } 290 | 291 | pub fn is_key_pressed(&self, key: Key, repeat: KeyRepeat) -> bool { 292 | match self { 293 | #[cfg(feature = "x11")] 294 | Window::X11(w) => w.is_key_pressed(key, repeat), 295 | #[cfg(feature = "wayland")] 296 | Window::Wayland(w) => w.is_key_pressed(key, repeat), 297 | } 298 | } 299 | 300 | pub fn is_key_released(&self, key: Key) -> bool { 301 | match self { 302 | #[cfg(feature = "x11")] 303 | Window::X11(w) => w.is_key_released(key), 304 | #[cfg(feature = "wayland")] 305 | Window::Wayland(w) => w.is_key_released(key), 306 | } 307 | } 308 | 309 | pub fn set_input_callback(&mut self, callback: Box) { 310 | match self { 311 | #[cfg(feature = "x11")] 312 | Window::X11(w) => w.set_input_callback(callback), 313 | #[cfg(feature = "wayland")] 314 | Window::Wayland(w) => w.set_input_callback(callback), 315 | } 316 | } 317 | 318 | pub fn is_open(&self) -> bool { 319 | match self { 320 | #[cfg(feature = "x11")] 321 | Window::X11(w) => w.is_open(), 322 | #[cfg(feature = "wayland")] 323 | Window::Wayland(w) => w.is_open(), 324 | } 325 | } 326 | 327 | pub fn is_active(&self) -> bool { 328 | match self { 329 | #[cfg(feature = "x11")] 330 | Window::X11(w) => w.is_active(), 331 | #[cfg(feature = "wayland")] 332 | Window::Wayland(w) => w.is_active(), 333 | } 334 | } 335 | 336 | pub fn add_menu(&mut self, menu: &Menu) -> MenuHandle { 337 | match self { 338 | #[cfg(feature = "x11")] 339 | Window::X11(w) => w.add_menu(menu), 340 | #[cfg(feature = "wayland")] 341 | Window::Wayland(w) => w.add_menu(menu), 342 | } 343 | } 344 | 345 | pub fn get_posix_menus(&self) -> Option<&Vec> { 346 | match self { 347 | #[cfg(feature = "x11")] 348 | Window::X11(w) => w.get_posix_menus(), 349 | #[cfg(feature = "wayland")] 350 | Window::Wayland(w) => w.get_posix_menus(), 351 | } 352 | } 353 | 354 | pub fn remove_menu(&mut self, handle: MenuHandle) { 355 | match self { 356 | #[cfg(feature = "x11")] 357 | Window::X11(w) => w.remove_menu(handle), 358 | #[cfg(feature = "wayland")] 359 | Window::Wayland(w) => w.remove_menu(handle), 360 | } 361 | } 362 | 363 | pub fn is_menu_pressed(&mut self) -> Option { 364 | match self { 365 | #[cfg(feature = "x11")] 366 | Window::X11(w) => w.is_menu_pressed(), 367 | #[cfg(feature = "wayland")] 368 | Window::Wayland(w) => w.is_menu_pressed(), 369 | } 370 | } 371 | } 372 | 373 | impl HasWindowHandle for Window { 374 | fn window_handle(&self) -> std::result::Result { 375 | match self { 376 | #[cfg(feature = "x11")] 377 | Window::X11(w) => w.window_handle(), 378 | #[cfg(feature = "wayland")] 379 | Window::Wayland(w) => w.window_handle(), 380 | } 381 | } 382 | } 383 | 384 | impl HasDisplayHandle for Window { 385 | fn display_handle(&self) -> std::result::Result { 386 | match self { 387 | #[cfg(feature = "x11")] 388 | Window::X11(w) => w.display_handle(), 389 | #[cfg(feature = "wayland")] 390 | Window::Wayland(w) => w.display_handle(), 391 | } 392 | } 393 | } 394 | -------------------------------------------------------------------------------- /src/os/posix/xkb_ffi.rs: -------------------------------------------------------------------------------- 1 | #![allow(non_camel_case_types, clippy::identity_op)] 2 | 3 | /** Minimal xkb_common ffi wrapper, based on sctk's. */ 4 | use std::ffi::c_char; 5 | 6 | #[repr(C)] 7 | pub struct xkb_context { 8 | _private: [u8; 0], 9 | } 10 | #[repr(C)] 11 | pub struct xkb_keymap { 12 | _private: [u8; 0], 13 | } 14 | #[repr(C)] 15 | pub struct xkb_state { 16 | _private: [u8; 0], 17 | } 18 | 19 | pub type xkb_keycode_t = u32; 20 | pub type xkb_keysym_t = u32; 21 | pub type xkb_layout_index_t = u32; 22 | pub type xkb_mod_mask_t = u32; 23 | 24 | #[repr(C)] 25 | #[derive(Copy, Clone, Debug, PartialEq)] 26 | pub enum xkb_context_flags { 27 | /** Do not apply any context flags. */ 28 | XKB_CONTEXT_NO_FLAGS = 0, 29 | } 30 | 31 | #[repr(C)] 32 | #[derive(Copy, Clone, Debug, PartialEq)] 33 | pub enum xkb_keymap_compile_flags { 34 | /** Do not apply any flags. */ 35 | XKB_KEYMAP_COMPILE_NO_FLAGS = 0, 36 | } 37 | 38 | #[repr(C)] 39 | #[derive(Copy, Clone, Debug, PartialEq)] 40 | pub enum xkb_keymap_format { 41 | /** The current/classic XKB text format, as generated by xkbcomp -xkb. */ 42 | XKB_KEYMAP_FORMAT_TEXT_V1 = 1, 43 | } 44 | 45 | pub type xkb_state_component = u32; 46 | 47 | external_library!(XkbCommon, "xkbcommon", 48 | functions: 49 | fn xkb_keysym_to_utf32(xkb_keysym_t) -> u32, 50 | fn xkb_context_new(xkb_context_flags) -> *mut xkb_context, 51 | fn xkb_context_unref(*mut xkb_context) -> (), 52 | fn xkb_keymap_new_from_string(*mut xkb_context, 53 | *const c_char, 54 | xkb_keymap_format, 55 | xkb_keymap_compile_flags 56 | ) -> *mut xkb_keymap, 57 | fn xkb_keymap_unref(*mut xkb_keymap) -> (), 58 | fn xkb_state_key_get_one_sym(*mut xkb_state, xkb_keycode_t) -> xkb_keysym_t, 59 | fn xkb_state_new(*mut xkb_keymap) -> *mut xkb_state, 60 | fn xkb_state_unref(*mut xkb_state) -> (), 61 | fn xkb_state_update_mask(*mut xkb_state, 62 | xkb_mod_mask_t, 63 | xkb_mod_mask_t, 64 | xkb_mod_mask_t, 65 | xkb_layout_index_t, 66 | xkb_layout_index_t, 67 | xkb_layout_index_t 68 | ) -> xkb_state_component, 69 | ); 70 | 71 | #[cfg(feature = "dlopen")] 72 | lazy_static::lazy_static!( 73 | pub static ref XKBCOMMON_OPTION: Option = unsafe { 74 | XkbCommon::open("libxkbcommon.so.0") 75 | .or_else(|_| XkbCommon::open("libxkbcommon.so")) 76 | .ok() 77 | }; 78 | pub static ref XKBCOMMON_HANDLE: &'static XkbCommon = { 79 | XKBCOMMON_OPTION.as_ref().expect("Library libxkbcommon.so could not be loaded.") 80 | }; 81 | ); 82 | -------------------------------------------------------------------------------- /src/os/posix/xkb_keysyms.rs: -------------------------------------------------------------------------------- 1 | #![allow(missing_docs, non_upper_case_globals, unused_parens, clippy::all)] 2 | 3 | /** The subset of XKB_* key symbols that are used in minifb. */ 4 | pub const XKB_KEY_0: u32 = 0x0030; 5 | pub const XKB_KEY_1: u32 = 0x0031; 6 | pub const XKB_KEY_2: u32 = 0x0032; 7 | pub const XKB_KEY_3: u32 = 0x0033; 8 | pub const XKB_KEY_4: u32 = 0x0034; 9 | pub const XKB_KEY_5: u32 = 0x0035; 10 | pub const XKB_KEY_6: u32 = 0x0036; 11 | pub const XKB_KEY_7: u32 = 0x0037; 12 | pub const XKB_KEY_8: u32 = 0x0038; 13 | pub const XKB_KEY_9: u32 = 0x0039; 14 | pub const XKB_KEY_a: u32 = 0x0061; 15 | pub const XKB_KEY_b: u32 = 0x0062; 16 | pub const XKB_KEY_c: u32 = 0x0063; 17 | pub const XKB_KEY_d: u32 = 0x0064; 18 | pub const XKB_KEY_e: u32 = 0x0065; 19 | pub const XKB_KEY_f: u32 = 0x0066; 20 | pub const XKB_KEY_g: u32 = 0x0067; 21 | pub const XKB_KEY_h: u32 = 0x0068; 22 | pub const XKB_KEY_i: u32 = 0x0069; 23 | pub const XKB_KEY_j: u32 = 0x006a; 24 | pub const XKB_KEY_k: u32 = 0x006b; 25 | pub const XKB_KEY_l: u32 = 0x006c; 26 | pub const XKB_KEY_m: u32 = 0x006d; 27 | pub const XKB_KEY_n: u32 = 0x006e; 28 | pub const XKB_KEY_o: u32 = 0x006f; 29 | pub const XKB_KEY_p: u32 = 0x0070; 30 | pub const XKB_KEY_q: u32 = 0x0071; 31 | pub const XKB_KEY_r: u32 = 0x0072; 32 | pub const XKB_KEY_s: u32 = 0x0073; 33 | pub const XKB_KEY_t: u32 = 0x0074; 34 | pub const XKB_KEY_u: u32 = 0x0075; 35 | pub const XKB_KEY_v: u32 = 0x0076; 36 | pub const XKB_KEY_w: u32 = 0x0077; 37 | pub const XKB_KEY_x: u32 = 0x0078; 38 | pub const XKB_KEY_y: u32 = 0x0079; 39 | pub const XKB_KEY_z: u32 = 0x007a; 40 | pub const XKB_KEY_apostrophe: u32 = 0x0027; 41 | pub const XKB_KEY_grave: u32 = 0x0060; 42 | pub const XKB_KEY_backslash: u32 = 0x005c; 43 | pub const XKB_KEY_comma: u32 = 0x002c; 44 | pub const XKB_KEY_equal: u32 = 0x003d; 45 | pub const XKB_KEY_bracketleft: u32 = 0x005b; 46 | pub const XKB_KEY_bracketright: u32 = 0x005d; 47 | pub const XKB_KEY_minus: u32 = 0x002d; 48 | pub const XKB_KEY_period: u32 = 0x002e; 49 | pub const XKB_KEY_semicolon: u32 = 0x003b; 50 | pub const XKB_KEY_slash: u32 = 0x002f; 51 | pub const XKB_KEY_space: u32 = 0x0020; 52 | pub const XKB_KEY_F1: u32 = 0xffbe; 53 | pub const XKB_KEY_F2: u32 = 0xffbf; 54 | pub const XKB_KEY_F3: u32 = 0xffc0; 55 | pub const XKB_KEY_F4: u32 = 0xffc1; 56 | pub const XKB_KEY_F5: u32 = 0xffc2; 57 | pub const XKB_KEY_F6: u32 = 0xffc3; 58 | pub const XKB_KEY_F7: u32 = 0xffc4; 59 | pub const XKB_KEY_F8: u32 = 0xffc5; 60 | pub const XKB_KEY_F9: u32 = 0xffc6; 61 | pub const XKB_KEY_F10: u32 = 0xffc7; 62 | pub const XKB_KEY_F11: u32 = 0xffc8; 63 | pub const XKB_KEY_F12: u32 = 0xffc9; 64 | pub const XKB_KEY_Down: u32 = 0xff54; 65 | pub const XKB_KEY_Left: u32 = 0xff51; 66 | pub const XKB_KEY_Right: u32 = 0xff53; 67 | pub const XKB_KEY_Up: u32 = 0xff52; 68 | pub const XKB_KEY_Escape: u32 = 0xff1b; 69 | pub const XKB_KEY_BackSpace: u32 = 0xff08; 70 | pub const XKB_KEY_Delete: u32 = 0xffff; 71 | pub const XKB_KEY_End: u32 = 0xff57; 72 | pub const XKB_KEY_Return: u32 = 0xff0d; 73 | pub const XKB_KEY_Home: u32 = 0xff50; 74 | pub const XKB_KEY_Insert: u32 = 0xff63; 75 | pub const XKB_KEY_Menu: u32 = 0xff67; 76 | pub const XKB_KEY_Page_Down: u32 = 0xff56; 77 | pub const XKB_KEY_Page_Up: u32 = 0xff55; 78 | pub const XKB_KEY_Pause: u32 = 0xff13; 79 | pub const XKB_KEY_Tab: u32 = 0xff09; 80 | pub const XKB_KEY_Num_Lock: u32 = 0xff7f; 81 | pub const XKB_KEY_Caps_Lock: u32 = 0xffe5; 82 | pub const XKB_KEY_Scroll_Lock: u32 = 0xff14; 83 | pub const XKB_KEY_Shift_L: u32 = 0xffe1; 84 | pub const XKB_KEY_Shift_R: u32 = 0xffe2; 85 | pub const XKB_KEY_Alt_L: u32 = 0xffe9; 86 | pub const XKB_KEY_Alt_R: u32 = 0xffea; 87 | pub const XKB_KEY_Control_L: u32 = 0xffe3; 88 | pub const XKB_KEY_Control_R: u32 = 0xffe4; 89 | pub const XKB_KEY_Super_L: u32 = 0xffeb; 90 | pub const XKB_KEY_Super_R: u32 = 0xffec; 91 | pub const XKB_KEY_KP_Insert: u32 = 0xff9e; 92 | pub const XKB_KEY_KP_End: u32 = 0xff9c; 93 | pub const XKB_KEY_KP_Down: u32 = 0xff99; 94 | pub const XKB_KEY_KP_Next: u32 = 0xff9b; 95 | pub const XKB_KEY_KP_Left: u32 = 0xff96; 96 | pub const XKB_KEY_KP_Begin: u32 = 0xff9d; 97 | pub const XKB_KEY_KP_Right: u32 = 0xff98; 98 | pub const XKB_KEY_KP_Home: u32 = 0xff95; 99 | pub const XKB_KEY_KP_Up: u32 = 0xff97; 100 | pub const XKB_KEY_KP_Prior: u32 = 0xff9a; 101 | pub const XKB_KEY_KP_Decimal: u32 = 0xffae; 102 | pub const XKB_KEY_KP_Divide: u32 = 0xffaf; 103 | pub const XKB_KEY_KP_Multiply: u32 = 0xffaa; 104 | pub const XKB_KEY_KP_Subtract: u32 = 0xffad; 105 | pub const XKB_KEY_KP_Add: u32 = 0xffab; 106 | pub const XKB_KEY_KP_Enter: u32 = 0xff8d; 107 | -------------------------------------------------------------------------------- /src/os/redox/mod.rs: -------------------------------------------------------------------------------- 1 | #![cfg(target_os = "redox")] 2 | 3 | use crate::{ 4 | check_buffer_size, error::Error, icon::Icon, key_handler::KeyHandler, 5 | os::redox::orbclient::Renderer, CursorStyle, InputCallback, Key, KeyRepeat, MenuHandle, 6 | MenuItem, MenuItemHandle, MouseButton, MouseMode, Result, Scale, UnixMenu, UnixMenuItem, 7 | WindowOptions, 8 | }; 9 | use orbclient::Renderer; 10 | use raw_window_handle::{ 11 | DisplayHandle, HandleError, HasDisplayHandle, HasWindowHandle, OrbitalDisplayHandle, 12 | OrbitalWindowHandle, RawDisplayHandle, RawWindowHandle, WindowHandle, 13 | }; 14 | use std::{cmp, std::ffi::c_void}; 15 | 16 | pub struct Window { 17 | is_open: bool, 18 | is_active: bool, 19 | mouse_pos: Option<(i32, i32)>, 20 | mouse_scroll: Option<(i32, i32)>, 21 | /// The state of the left, middle and right mouse buttons 22 | mouse_state: (bool, bool, bool), 23 | buffer_width: usize, 24 | buffer_height: usize, 25 | window: orbclient::Window, 26 | window_scale: usize, 27 | key_handler: KeyHandler, 28 | menu_counter: MenuHandle, 29 | menus: Vec, 30 | } 31 | 32 | impl Window { 33 | pub fn new(name: &str, width: usize, height: usize, opts: WindowOptions) -> Result { 34 | let window_scale = match opts.scale { 35 | Scale::X1 => 1, 36 | Scale::X2 => 2, 37 | Scale::X4 => 4, 38 | Scale::X8 => 8, 39 | Scale::X16 => 16, 40 | Scale::X32 => 32, 41 | Scale::FitScreen => { 42 | let display_size = orbclient::get_display_size() 43 | .map_err(|_| Error::WindowCreate("Unable to get display size".to_owned()))?; 44 | let mut scale = 32; 45 | while scale > 1 { 46 | if width * scale < display_size.0 as usize 47 | && height * scale < display_size.1 as usize 48 | { 49 | break; 50 | } 51 | scale -= 1; 52 | } 53 | scale 54 | } 55 | }; 56 | 57 | let window_width = width as u32 * window_scale as u32; 58 | let window_height = height as u32 * window_scale as u32; 59 | 60 | let mut window_flags = vec![orbclient::WindowFlag::Async]; 61 | if opts.resize && !opts.none { 62 | window_flags.push(orbclient::WindowFlag::Resizable); 63 | } 64 | if !opts.title { 65 | window_flags.push(orbclient::WindowFlag::Borderless); 66 | } 67 | if opts.transparency { 68 | window_flags.push(orbclient::WindowFlag::Transparent); 69 | } 70 | 71 | let window_opt = 72 | orbclient::Window::new_flags(-1, -1, window_width, window_height, name, &window_flags); 73 | match window_opt { 74 | Some(window) => Ok(Window { 75 | mouse_pos: None, 76 | mouse_scroll: None, 77 | mouse_state: (false, false, false), 78 | is_open: true, 79 | is_active: true, 80 | buffer_width: width, 81 | buffer_height: height, 82 | window, 83 | window_scale, 84 | key_handler: KeyHandler::new(), 85 | menu_counter: MenuHandle(0), 86 | menus: Vec::new(), 87 | }), 88 | None => Err(Error::WindowCreate("Unable to open Window".to_owned())), 89 | } 90 | } 91 | 92 | #[inline] 93 | pub fn set_title(&mut self, title: &str) { 94 | self.window.set_title(title) 95 | } 96 | 97 | #[inline] 98 | pub fn set_icon(&mut self, _icon: Icon) { 99 | unimplemented!("Currenty not implemented on RedoxOS") 100 | } 101 | 102 | #[inline] 103 | pub fn get_window_handle(&self) -> *mut c_void { 104 | std::ptr::null_mut() 105 | } 106 | 107 | pub fn update_with_buffer(&mut self, buffer: &[u32]) -> Result<()> { 108 | self.process_events(); 109 | self.key_handler.update(); 110 | 111 | check_buffer_size( 112 | buffer, 113 | self.buffer_width, 114 | self.buffer_height, 115 | self.window_scale, 116 | )?; 117 | 118 | self.render_buffer(buffer); 119 | self.window.sync(); 120 | 121 | Ok(()) 122 | } 123 | 124 | #[inline] 125 | pub fn update(&mut self) { 126 | self.process_events(); 127 | self.key_handler.update(); 128 | self.window.sync(); 129 | } 130 | 131 | #[inline] 132 | pub fn set_position(&mut self, x: isize, y: isize) { 133 | self.window.set_pos(x as i32, y as i32) 134 | } 135 | 136 | #[inline] 137 | pub fn get_size(&self) -> (usize, usize) { 138 | (self.window.width() as usize, self.window.height() as usize) 139 | } 140 | 141 | #[inline] 142 | pub fn get_scroll_wheel(&self) -> Option<(f32, f32)> { 143 | if let Some((scroll_x, scroll_y)) = self.mouse_scroll { 144 | Some((scroll_x as f32, scroll_y as f32)) 145 | } else { 146 | None 147 | } 148 | } 149 | 150 | #[inline] 151 | pub fn get_mouse_down(&self, button: MouseButton) -> bool { 152 | match button { 153 | MouseButton::Left => self.mouse_state.0, 154 | MouseButton::Middle => self.mouse_state.1, 155 | MouseButton::Right => self.mouse_state.2, 156 | } 157 | } 158 | 159 | #[inline] 160 | pub fn get_mouse_pos(&self, mode: MouseMode) -> Option<(f32, f32)> { 161 | if let Some((mouse_x, mouse_y)) = self.mouse_pos { 162 | mode.get_pos( 163 | mouse_x as f32, 164 | mouse_y as f32, 165 | self.window_scale as f32, 166 | self.buffer_width as f32 * self.window_scale as f32, 167 | self.buffer_height as f32 * self.window_scale as f32, 168 | ) 169 | } else { 170 | None 171 | } 172 | } 173 | 174 | #[inline] 175 | pub fn get_unscaled_mouse_pos(&self, mode: MouseMode) -> Option<(f32, f32)> { 176 | if let Some((mouse_x, mouse_y)) = self.mouse_pos { 177 | mode.get_pos( 178 | mouse_x as f32, 179 | mouse_y as f32, 180 | 1.0 as f32, 181 | self.buffer_width as f32 * self.window_scale as f32, 182 | self.buffer_height as f32 * self.window_scale as f32, 183 | ) 184 | } else { 185 | None 186 | } 187 | } 188 | 189 | #[inline] 190 | pub fn set_cursor_style(&mut self, _cursor: CursorStyle) { 191 | // Orbital doesn't support cursor styles yet 192 | } 193 | 194 | #[inline] 195 | pub fn set_cursor_visibility(&mut self, visibility: bool) { 196 | self.window.set_mouse_cursor(visibility); 197 | } 198 | 199 | #[inline] 200 | pub fn get_keys(&self) -> Vec { 201 | self.key_handler.get_keys() 202 | } 203 | 204 | #[inline] 205 | pub fn get_keys_pressed(&self, repeat: KeyRepeat) -> Vec { 206 | self.key_handler.get_keys_pressed(repeat) 207 | } 208 | 209 | #[inline] 210 | pub fn get_keys_released(&self) -> Vec { 211 | self.key_handler.get_keys_released() 212 | } 213 | 214 | #[inline] 215 | pub fn is_key_down(&self, key: Key) -> bool { 216 | self.key_handler.is_key_down(key) 217 | } 218 | 219 | #[inline] 220 | pub fn set_key_repeat_delay(&mut self, delay: f32) { 221 | self.key_handler.set_key_repeat_delay(delay) 222 | } 223 | 224 | #[inline] 225 | pub fn set_key_repeat_rate(&mut self, rate: f32) { 226 | self.key_handler.set_key_repeat_rate(rate) 227 | } 228 | 229 | #[inline] 230 | pub fn is_key_pressed(&self, key: Key, repeat: KeyRepeat) -> bool { 231 | self.key_handler.is_key_pressed(key, repeat) 232 | } 233 | 234 | #[inline] 235 | pub fn is_key_released(&self, key: Key) -> bool { 236 | self.key_handler.is_key_released(key) 237 | } 238 | 239 | #[inline] 240 | pub fn set_input_callback(&mut self, callback: Box) { 241 | self.key_handler.set_input_callback(callback) 242 | } 243 | 244 | #[inline] 245 | pub fn is_open(&self) -> bool { 246 | self.is_open 247 | } 248 | 249 | #[inline] 250 | pub fn is_active(&self) -> bool { 251 | self.is_active 252 | } 253 | 254 | fn process_events(&mut self) { 255 | self.mouse_scroll = None; 256 | 257 | for event in self.window.events() { 258 | match event.to_option() { 259 | orbclient::EventOption::Key(key_event) => { 260 | let key_opt = self.map_key_to_minifb(key_event.scancode); 261 | if let Some(key) = key_opt { 262 | self.key_handler.set_key_state(key, key_event.pressed); 263 | } 264 | } 265 | orbclient::EventOption::Mouse(mouse_event) => { 266 | self.mouse_pos = Some((mouse_event.x, mouse_event.y)); 267 | } 268 | orbclient::EventOption::Button(button_event) => { 269 | self.mouse_state = (button_event.left, button_event.middle, button_event.right); 270 | } 271 | orbclient::EventOption::Quit(_) => { 272 | self.is_open = false; 273 | } 274 | orbclient::EventOption::Focus(focus_event) => { 275 | self.is_active = focus_event.focused; 276 | if !self.is_active { 277 | self.mouse_pos = None; 278 | } 279 | } 280 | orbclient::EventOption::Scroll(scroll_event) => { 281 | self.mouse_pos = Some((scroll_event.x, scroll_event.y)); 282 | } 283 | _ => {} 284 | } 285 | } 286 | } 287 | 288 | /// Maps Orbital scancodes to MiniFB Key enums 289 | fn map_key_to_minifb(&self, scancode: u8) -> Option { 290 | match scancode { 291 | orbclient::K_0 => Some(Key::Key0), 292 | orbclient::K_1 => Some(Key::Key1), 293 | orbclient::K_2 => Some(Key::Key2), 294 | orbclient::K_3 => Some(Key::Key3), 295 | orbclient::K_4 => Some(Key::Key4), 296 | orbclient::K_5 => Some(Key::Key5), 297 | orbclient::K_6 => Some(Key::Key6), 298 | orbclient::K_7 => Some(Key::Key7), 299 | orbclient::K_8 => Some(Key::Key8), 300 | orbclient::K_9 => Some(Key::Key9), 301 | orbclient::K_A => Some(Key::A), 302 | orbclient::K_B => Some(Key::B), 303 | orbclient::K_C => Some(Key::C), 304 | orbclient::K_D => Some(Key::D), 305 | orbclient::K_E => Some(Key::E), 306 | orbclient::K_F => Some(Key::F), 307 | orbclient::K_G => Some(Key::G), 308 | orbclient::K_H => Some(Key::H), 309 | orbclient::K_I => Some(Key::I), 310 | orbclient::K_J => Some(Key::J), 311 | orbclient::K_K => Some(Key::K), 312 | orbclient::K_L => Some(Key::L), 313 | orbclient::K_M => Some(Key::M), 314 | orbclient::K_N => Some(Key::N), 315 | orbclient::K_O => Some(Key::O), 316 | orbclient::K_P => Some(Key::P), 317 | orbclient::K_Q => Some(Key::Q), 318 | orbclient::K_R => Some(Key::R), 319 | orbclient::K_S => Some(Key::S), 320 | orbclient::K_T => Some(Key::T), 321 | orbclient::K_U => Some(Key::U), 322 | orbclient::K_V => Some(Key::V), 323 | orbclient::K_W => Some(Key::W), 324 | orbclient::K_X => Some(Key::X), 325 | orbclient::K_Y => Some(Key::Y), 326 | orbclient::K_Z => Some(Key::Z), 327 | orbclient::K_F1 => Some(Key::F1), 328 | orbclient::K_F2 => Some(Key::F2), 329 | orbclient::K_F3 => Some(Key::F3), 330 | orbclient::K_F4 => Some(Key::F4), 331 | orbclient::K_F5 => Some(Key::F5), 332 | orbclient::K_F6 => Some(Key::F6), 333 | orbclient::K_F7 => Some(Key::F7), 334 | orbclient::K_F8 => Some(Key::F8), 335 | orbclient::K_F9 => Some(Key::F9), 336 | orbclient::K_F10 => Some(Key::F10), 337 | orbclient::K_F11 => Some(Key::F11), 338 | orbclient::K_F12 => Some(Key::F12), 339 | orbclient::K_DOWN => Some(Key::Down), 340 | orbclient::K_LEFT => Some(Key::Left), 341 | orbclient::K_RIGHT => Some(Key::Right), 342 | orbclient::K_UP => Some(Key::Up), 343 | orbclient::K_TICK => Some(Key::Apostrophe), 344 | orbclient::K_BACKSLASH => Some(Key::Backslash), 345 | orbclient::K_COMMA => Some(Key::Comma), 346 | orbclient::K_EQUALS => Some(Key::Equal), 347 | orbclient::K_BRACE_OPEN => Some(Key::LeftBracket), 348 | orbclient::K_MINUS => Some(Key::Minus), 349 | orbclient::K_PERIOD => Some(Key::Period), 350 | orbclient::K_BRACE_CLOSE => Some(Key::RightBracket), 351 | orbclient::K_SEMICOLON => Some(Key::Semicolon), 352 | orbclient::K_SLASH => Some(Key::Slash), 353 | orbclient::K_BKSP => Some(Key::Backspace), 354 | orbclient::K_DEL => Some(Key::Delete), 355 | orbclient::K_END => Some(Key::End), 356 | orbclient::K_ENTER => Some(Key::Enter), 357 | orbclient::K_ESC => Some(Key::Escape), 358 | orbclient::K_HOME => Some(Key::Home), 359 | orbclient::K_PGDN => Some(Key::PageDown), 360 | orbclient::K_PGUP => Some(Key::PageUp), 361 | orbclient::K_SPACE => Some(Key::Space), 362 | orbclient::K_TAB => Some(Key::Tab), 363 | orbclient::K_CAPS => Some(Key::CapsLock), 364 | orbclient::K_LEFT_SHIFT => Some(Key::LeftShift), 365 | orbclient::K_RIGHT_SHIFT => Some(Key::RightShift), 366 | orbclient::K_CTRL => Some(Key::LeftCtrl), 367 | orbclient::K_ALT => Some(Key::LeftAlt), 368 | _ => { 369 | println!("Unknown Orbital scancode 0x{:2x}", scancode); 370 | None 371 | } 372 | } 373 | } 374 | 375 | /// Renders the given pixel data into the Orbital window 376 | fn render_buffer(&mut self, buffer: &[u32]) { 377 | let render_width = cmp::min( 378 | self.buffer_width * self.window_scale, 379 | self.window.width() as usize, 380 | ); 381 | let render_height = cmp::min( 382 | self.buffer_height * self.window_scale, 383 | self.window.height() as usize, 384 | ); 385 | 386 | let window_width = self.window.width() as usize; 387 | let window_buffer = self.window.data_mut(); 388 | 389 | for y in 0..render_height { 390 | for x in 0..render_width { 391 | let buffer_x = x / self.window_scale; 392 | let buffer_y = y / self.window_scale; 393 | 394 | window_buffer[y * window_width + x] = orbclient::Color { 395 | data: buffer[buffer_y * self.buffer_width + buffer_x], 396 | }; 397 | } 398 | } 399 | } 400 | 401 | #[inline] 402 | fn next_menu_handle(&mut self) -> MenuHandle { 403 | let handle = self.menu_counter; 404 | self.menu_counter.0 += 1; 405 | handle 406 | } 407 | 408 | #[inline] 409 | pub fn add_menu(&mut self, menu: &Menu) -> MenuHandle { 410 | let handle = self.next_menu_handle(); 411 | let mut menu = menu.internal.clone(); 412 | menu.handle = handle; 413 | self.menus.push(menu); 414 | handle 415 | } 416 | 417 | #[inline] 418 | pub fn get_posix_menus(&self) -> Option<&Vec> { 419 | Some(&self.menus) 420 | } 421 | 422 | #[inline] 423 | pub fn remove_menu(&mut self, handle: MenuHandle) { 424 | self.menus.retain(|ref menu| menu.handle != handle); 425 | } 426 | 427 | #[inline] 428 | pub fn is_menu_pressed(&mut self) -> Option { 429 | None 430 | } 431 | } 432 | 433 | impl HasWindowHandle for Window { 434 | fn window_handle(&self) -> std::result::Result { 435 | let raw_window = &self.window as *const orbclient::Window as *const c_void; 436 | let handle = OrbitalWindowHandle::new(raw_window); 437 | let raw_handle = RawWindowHandle::Orbital(handle); 438 | unsafe { Ok(WindowHandle::borrow_raw(raw_handle)) } 439 | } 440 | } 441 | 442 | impl HasDisplayHandle for Window { 443 | fn display_handle(&self) -> std::result::Result { 444 | let handle = OrbitalDisplayHandle::new(); 445 | let raw_handle = RawDisplayHandle::Orbital(handle); 446 | unsafe { Ok(DisplayHandle::borrow_raw(raw_handle)) } 447 | } 448 | } 449 | 450 | pub struct Menu { 451 | pub internal: UnixMenu, 452 | } 453 | 454 | impl Menu { 455 | pub fn new(name: &str) -> Result { 456 | Ok(Menu { 457 | internal: UnixMenu { 458 | handle: MenuHandle(0), 459 | item_counter: MenuItemHandle(0), 460 | name: name.to_owned(), 461 | items: Vec::new(), 462 | }, 463 | }) 464 | } 465 | 466 | #[inline] 467 | pub fn add_sub_menu(&mut self, name: &str, sub_menu: &Menu) { 468 | let handle = self.next_item_handle(); 469 | self.internal.items.push(UnixMenuItem { 470 | label: name.to_owned(), 471 | handle, 472 | sub_menu: Some(Box::new(sub_menu.internal.clone())), 473 | id: 0, 474 | enabled: true, 475 | key: Key::Unknown, 476 | modifier: 0, 477 | }); 478 | } 479 | 480 | #[inline] 481 | fn next_item_handle(&mut self) -> MenuItemHandle { 482 | let handle = self.internal.item_counter; 483 | self.internal.item_counter.0 += 1; 484 | handle 485 | } 486 | 487 | #[inline] 488 | pub fn add_menu_item(&mut self, item: &MenuItem) -> MenuItemHandle { 489 | let item_handle = self.next_item_handle(); 490 | self.internal.items.push(UnixMenuItem { 491 | sub_menu: None, 492 | handle: self.internal.item_counter, 493 | id: item.id, 494 | label: item.label.clone(), 495 | enabled: item.enabled, 496 | key: item.key, 497 | modifier: item.modifier, 498 | }); 499 | item_handle 500 | } 501 | 502 | #[inline] 503 | pub fn remove_item(&mut self, handle: &MenuItemHandle) { 504 | self.internal 505 | .items 506 | .retain(|ref item| item.handle.0 != handle.0); 507 | } 508 | } 509 | -------------------------------------------------------------------------------- /src/os/wasm/keycodes.rs: -------------------------------------------------------------------------------- 1 | use crate::key::Key; 2 | 3 | pub const BACKSPACE: &'static str = "Backspace"; 4 | pub const TAB: &'static str = "Tab"; 5 | pub const ENTER: &'static str = "Enter"; 6 | pub const SHIFT_LEFT: &'static str = "ShiftLeft"; 7 | pub const SHIFT_RIGHT: &'static str = "ShiftRight"; 8 | pub const CONTROL_LEFT: &'static str = "ControlLeft"; 9 | pub const CONTROL_RIGHT: &'static str = "ControlRight"; 10 | pub const ALT_LEFT: &'static str = "AltLeft"; 11 | pub const ALT_RIGHT: &'static str = "AltRight"; 12 | pub const PAUSE: &'static str = "Pause"; 13 | pub const CAPS_LOCK: &'static str = "CapsLock"; 14 | pub const ESCAPE: &'static str = "Escape"; 15 | pub const SPACE: &'static str = "Space"; 16 | pub const PAGE_UP: &'static str = "PageUp"; 17 | pub const PAGE_DOWN: &'static str = "PageDown"; 18 | pub const END: &'static str = "End"; 19 | pub const HOME: &'static str = "Home"; 20 | pub const ARROW_LEFT: &'static str = "ArrowLeft"; 21 | pub const ARROW_UP: &'static str = "ArrowUp"; 22 | pub const ARROW_RIGHT: &'static str = "ArrowRight"; 23 | pub const ARROW_DOWN: &'static str = "ArrowDown"; 24 | //pub const PRINT_SCREEN: &'static str = "PrintScreen"; 25 | pub const INSERT: &'static str = "Insert"; 26 | pub const DELETE: &'static str = "Delete"; 27 | pub const DIGIT_0: &'static str = "Digit0"; 28 | pub const DIGIT_1: &'static str = "Digit1"; 29 | pub const DIGIT_2: &'static str = "Digit2"; 30 | pub const DIGIT_3: &'static str = "Digit3"; 31 | pub const DIGIT_4: &'static str = "Digit4"; 32 | pub const DIGIT_5: &'static str = "Digit5"; 33 | pub const DIGIT_6: &'static str = "Digit6"; 34 | pub const DIGIT_7: &'static str = "Digit7"; 35 | pub const DIGIT_8: &'static str = "Digit8"; 36 | pub const DIGIT_9: &'static str = "Digit9"; 37 | pub const KEY_A: &'static str = "KeyA"; 38 | pub const KEY_B: &'static str = "KeyB"; 39 | pub const KEY_C: &'static str = "KeyC"; 40 | pub const KEY_D: &'static str = "KeyD"; 41 | pub const KEY_E: &'static str = "KeyE"; 42 | pub const KEY_F: &'static str = "KeyF"; 43 | pub const KEY_G: &'static str = "KeyG"; 44 | pub const KEY_H: &'static str = "KeyH"; 45 | pub const KEY_I: &'static str = "KeyI"; 46 | pub const KEY_J: &'static str = "KeyJ"; 47 | pub const KEY_K: &'static str = "KeyK"; 48 | pub const KEY_L: &'static str = "KeyL"; 49 | pub const KEY_M: &'static str = "KeyM"; 50 | pub const KEY_N: &'static str = "KeyN"; 51 | pub const KEY_O: &'static str = "KeyO"; 52 | pub const KEY_P: &'static str = "KeyP"; 53 | pub const KEY_Q: &'static str = "KeyQ"; 54 | pub const KEY_R: &'static str = "KeyR"; 55 | pub const KEY_S: &'static str = "KeyS"; 56 | pub const KEY_T: &'static str = "KeyT"; 57 | pub const KEY_U: &'static str = "KeyU"; 58 | pub const KEY_V: &'static str = "KeyV"; 59 | pub const KEY_W: &'static str = "KeyW"; 60 | pub const KEY_X: &'static str = "KeyX"; 61 | pub const KEY_Y: &'static str = "KeyY"; 62 | pub const KEY_Z: &'static str = "KeyZ"; 63 | //pub const META_LEFT: &'static str = "MetaLeft"; 64 | //pub const META_RIGHT: &'static str = "MetaRight"; 65 | //pub const CONTEXT_MENU: &'static str = "ContextMenu"; 66 | pub const NUMPAD_0: &'static str = "Numpad0"; 67 | pub const NUMPAD_1: &'static str = "Numpad1"; 68 | pub const NUMPAD_2: &'static str = "Numpad2"; 69 | pub const NUMPAD_3: &'static str = "Numpad3"; 70 | pub const NUMPAD_4: &'static str = "Numpad4"; 71 | pub const NUMPAD_5: &'static str = "Numpad5"; 72 | pub const NUMPAD_6: &'static str = "Numpad6"; 73 | pub const NUMPAD_7: &'static str = "Numpad7"; 74 | pub const NUMPAD_8: &'static str = "Numpad8"; 75 | pub const NUMPAD_9: &'static str = "Numpad9"; 76 | pub const NUMPAD_MULTIPLY: &'static str = "NumpadMultiply"; 77 | pub const NUMPAD_ADD: &'static str = "NumpadAdd"; 78 | pub const NUMPAD_SUBTRACT: &'static str = "NumpadSubtract"; 79 | pub const NUMPAD_DECIMAL: &'static str = "NumpadDecimal"; 80 | pub const NUMPAD_DIVIDE: &'static str = "NumpadDivide"; 81 | pub const F1: &'static str = "F1"; 82 | pub const F2: &'static str = "F2"; 83 | pub const F3: &'static str = "F3"; 84 | pub const F4: &'static str = "F4"; 85 | pub const F5: &'static str = "F5"; 86 | pub const F6: &'static str = "F6"; 87 | pub const F7: &'static str = "F7"; 88 | pub const F8: &'static str = "F8"; 89 | pub const F9: &'static str = "F9"; 90 | pub const F10: &'static str = "F10"; 91 | pub const F11: &'static str = "F11"; 92 | pub const F12: &'static str = "F12"; 93 | pub const NUM_LOCK: &'static str = "NumLock"; 94 | pub const SCROLL_LOCK: &'static str = "ScrollLock"; 95 | //pub const VOLUME_MUTE: &'static str = "VolumeMute"; 96 | //pub const VOLUME_DOWN: &'static str = "VolumeDown"; 97 | //pub const VOLUME_UP: &'static str = "VolumeUp"; 98 | //pub const MEDIA_SELECT: &'static str = "MediaSelect"; 99 | //pub const LAUNCH_APP1: &'static str = "LaunchApp1"; 100 | //pub const LAUNCH_APP2: &'static str = "LaunchApp2"; 101 | pub const SEMICOLON: &'static str = "Semicolon"; 102 | pub const EQUAL: &'static str = "Equal"; 103 | pub const COMMA: &'static str = "Comma"; 104 | pub const MINUS: &'static str = "Minus"; 105 | pub const PERIOD: &'static str = "Period"; 106 | pub const SLASH: &'static str = "Slash"; 107 | pub const BACKQUOTE: &'static str = "Backquote"; 108 | pub const BRACKET_LEFT: &'static str = "BracketLeft"; 109 | pub const BACKSLASH: &'static str = "Backslash"; 110 | pub const BRACKET_RIGHT: &'static str = "BracketRight"; 111 | pub const QUOTE: &'static str = "Quote"; 112 | 113 | pub fn event_to_key(event: &web_sys::KeyboardEvent) -> Key { 114 | match event.code().as_str() { 115 | BACKSPACE => Key::Backspace, 116 | TAB => Key::Tab, 117 | ENTER => Key::Enter, 118 | SHIFT_LEFT => Key::LeftShift, 119 | SHIFT_RIGHT => Key::RightShift, 120 | CONTROL_LEFT => Key::LeftCtrl, 121 | CONTROL_RIGHT => Key::RightCtrl, 122 | ALT_LEFT => Key::LeftAlt, 123 | ALT_RIGHT => Key::RightAlt, 124 | PAUSE => Key::Pause, 125 | CAPS_LOCK => Key::CapsLock, 126 | ESCAPE => Key::Escape, 127 | SPACE => Key::Space, 128 | PAGE_UP => Key::PageUp, 129 | PAGE_DOWN => Key::PageDown, 130 | END => Key::End, 131 | HOME => Key::Home, 132 | ARROW_LEFT => Key::Left, 133 | ARROW_UP => Key::Up, 134 | ARROW_RIGHT => Key::Right, 135 | ARROW_DOWN => Key::Down, 136 | INSERT => Key::Insert, 137 | DELETE => Key::Delete, 138 | DIGIT_0 => Key::Key0, 139 | DIGIT_1 => Key::Key1, 140 | DIGIT_2 => Key::Key2, 141 | DIGIT_3 => Key::Key3, 142 | DIGIT_4 => Key::Key4, 143 | DIGIT_5 => Key::Key5, 144 | DIGIT_6 => Key::Key6, 145 | DIGIT_7 => Key::Key7, 146 | DIGIT_8 => Key::Key8, 147 | DIGIT_9 => Key::Key9, 148 | KEY_A => Key::A, 149 | KEY_B => Key::B, 150 | KEY_C => Key::C, 151 | KEY_D => Key::D, 152 | KEY_E => Key::E, 153 | KEY_F => Key::F, 154 | KEY_G => Key::G, 155 | KEY_H => Key::H, 156 | KEY_I => Key::I, 157 | KEY_J => Key::J, 158 | KEY_K => Key::K, 159 | KEY_L => Key::L, 160 | KEY_M => Key::M, 161 | KEY_N => Key::N, 162 | KEY_O => Key::O, 163 | KEY_P => Key::P, 164 | KEY_Q => Key::Q, 165 | KEY_R => Key::R, 166 | KEY_S => Key::S, 167 | KEY_T => Key::T, 168 | KEY_U => Key::U, 169 | KEY_V => Key::V, 170 | KEY_W => Key::W, 171 | KEY_X => Key::X, 172 | KEY_Y => Key::Y, 173 | KEY_Z => Key::Z, 174 | NUMPAD_0 => Key::NumPad0, 175 | NUMPAD_1 => Key::NumPad1, 176 | NUMPAD_2 => Key::NumPad2, 177 | NUMPAD_3 => Key::NumPad3, 178 | NUMPAD_4 => Key::NumPad4, 179 | NUMPAD_5 => Key::NumPad5, 180 | NUMPAD_6 => Key::NumPad6, 181 | NUMPAD_7 => Key::NumPad7, 182 | NUMPAD_8 => Key::NumPad8, 183 | NUMPAD_9 => Key::NumPad9, 184 | NUMPAD_MULTIPLY => Key::NumPadAsterisk, 185 | NUMPAD_ADD => Key::NumPadPlus, 186 | NUMPAD_SUBTRACT => Key::NumPadMinus, 187 | NUMPAD_DECIMAL => Key::NumPadDot, 188 | NUMPAD_DIVIDE => Key::NumPadSlash, 189 | F1 => Key::F1, 190 | F2 => Key::F2, 191 | F3 => Key::F3, 192 | F4 => Key::F4, 193 | F5 => Key::F5, 194 | F6 => Key::F6, 195 | F7 => Key::F7, 196 | F8 => Key::F8, 197 | F9 => Key::F9, 198 | F10 => Key::F10, 199 | F11 => Key::F11, 200 | F12 => Key::F12, 201 | NUM_LOCK => Key::NumLock, 202 | SCROLL_LOCK => Key::ScrollLock, 203 | SEMICOLON => Key::Semicolon, 204 | EQUAL => Key::Equal, 205 | COMMA => Key::Comma, 206 | MINUS => Key::Minus, 207 | PERIOD => Key::Period, 208 | SLASH => Key::Slash, 209 | BACKQUOTE => Key::Backquote, 210 | BRACKET_LEFT => Key::LeftBracket, 211 | BACKSLASH => Key::Backslash, 212 | BRACKET_RIGHT => Key::RightBracket, 213 | QUOTE => Key::Apostrophe, 214 | _ => { 215 | /* 216 | PRINT_SCREEN=> Key::PrintScreen, 217 | META_LEFT=> Key::MetaLeft, 218 | META_RIGHT=> Key::MetaRight, 219 | CONTEXT_MENU=> Key::ContextMenu, 220 | VOLUME_MUTE=> Key::VolumeMute, 221 | VOLUME_DOWN=> Key::VolumeDown, 222 | VOLUME_UP=> Key::VolumeUp, 223 | MEDIA_SELECT=> Key::MediaSelect, 224 | LAUNCH_APP1=> Key::LaunchApp1, 225 | LAUNCH_APP2=> Key::LaunchApp2, 226 | */ 227 | // ignore other keys 228 | Key::Unknown 229 | } 230 | } 231 | } 232 | -------------------------------------------------------------------------------- /src/os/wasm/mod.rs: -------------------------------------------------------------------------------- 1 | // NOTE(stefano): add missing implementations of methods where possible 2 | #![cfg(target_arch = "wasm32")] 3 | 4 | mod keycodes; 5 | 6 | use crate::{ 7 | check_buffer_size, key_handler::KeyHandler, CursorStyle, Icon, InputCallback, Key, KeyRepeat, 8 | MenuHandle, MenuItem, MenuItemHandle, MouseButton, MouseMode, Result, Scale, UnixMenu, 9 | UnixMenuItem, WindowOptions, 10 | }; 11 | use keycodes::event_to_key; 12 | use raw_window_handle::{ 13 | DisplayHandle, HandleError, HasDisplayHandle, HasWindowHandle, RawDisplayHandle, 14 | RawWindowHandle, WebDisplayHandle, WebWindowHandle, WindowHandle, 15 | }; 16 | use std::{ 17 | cell::{Cell, RefCell}, 18 | ffi::c_void, 19 | rc::Rc, 20 | time::Duration, 21 | }; 22 | use wasm_bindgen::{prelude::*, Clamped, JsCast}; 23 | use web_sys::{window, CanvasRenderingContext2d, HtmlCanvasElement, HtmlElement, ImageData}; 24 | 25 | #[inline(always)] 26 | #[allow(dead_code)] // Only used on 32-bit builds currently 27 | pub fn u32_as_u8<'a>(src: &'a [u32]) -> &'a [u8] { 28 | unsafe { 29 | std::slice::from_raw_parts( 30 | src.as_ptr() as *mut u8, 31 | src.len() * std::mem::size_of::(), 32 | ) 33 | } 34 | } 35 | 36 | struct MouseState { 37 | pos: Cell>, 38 | //scroll: Cell>, 39 | left_button: Cell, 40 | right_button: Cell, 41 | middle_button: Cell, 42 | } 43 | 44 | struct Context2D { 45 | context: CanvasRenderingContext2d, 46 | img_data: ImageData, 47 | } 48 | 49 | // IDEA(stefano): possibly have this contain a "document" field, so not to recompute it every time 50 | pub struct Window { 51 | width: u32, 52 | height: u32, 53 | bg_color: u32, 54 | window_scale: usize, 55 | canvas: HtmlCanvasElement, 56 | // 2D context is created lazily since its creation precludes creation of webgl & webgpu contexts. 57 | context2d: Option, 58 | mouse_state: Rc, 59 | key_handler: Rc>, 60 | menu_counter: MenuHandle, 61 | menus: Vec, 62 | raw_handle_id: u32, 63 | } 64 | 65 | impl Window { 66 | /// Create a new window 67 | /// * `container` - The id of a DOM element to use as a container 68 | pub fn new( 69 | container: &str, 70 | width: usize, 71 | height: usize, 72 | opts: WindowOptions, 73 | ) -> Result { 74 | let window_scale = match opts.scale { 75 | Scale::X1 => 1, 76 | Scale::X2 => 2, 77 | Scale::X4 => 4, 78 | Scale::X8 => 8, 79 | Scale::X16 => 16, 80 | Scale::X32 => 32, 81 | Scale::FitScreen => 1, //TODO: Resize the canvas and implement this 82 | }; 83 | let document = window().unwrap().document().unwrap(); 84 | 85 | // Create a canvas element and place it in the window as a child of the container 86 | let canvas = document 87 | .create_element("canvas") 88 | .unwrap() 89 | .dyn_into::() 90 | .unwrap(); 91 | 92 | // Raw handle requires to inject an id into the canvas' data attributes. 93 | // TODO assign a different ID to each window 94 | let raw_handle_id = 0; 95 | canvas 96 | .set_attribute("data-raw-handle", &raw_handle_id.to_string()) 97 | .unwrap(); 98 | 99 | let container = document 100 | .get_element_by_id(container) 101 | .unwrap() 102 | .dyn_into::() 103 | .unwrap(); 104 | 105 | container.append_child(&canvas).unwrap(); 106 | 107 | canvas.set_width(width as u32); 108 | canvas.set_height(height as u32); 109 | // set this to get the keyboard events 110 | canvas.set_tab_index(0); 111 | 112 | // Create an image buffer 113 | let key_handler = Rc::new(RefCell::new(KeyHandler::new())); 114 | let mouse_struct = MouseState { 115 | pos: Cell::new(None), 116 | //scroll: Cell::new(None), 117 | left_button: Cell::new(false), 118 | right_button: Cell::new(false), 119 | middle_button: Cell::new(false), 120 | }; 121 | let mouse_state = Rc::new(mouse_struct); 122 | { 123 | let key_handler = key_handler.clone(); 124 | let closure = Closure::wrap(Box::new(move |event: web_sys::KeyboardEvent| { 125 | event.prevent_default(); 126 | let key = event_to_key(&event); 127 | key_handler.borrow_mut().set_key_state(key, true); 128 | }) as Box); 129 | canvas.add_event_listener_with_callback("keydown", closure.as_ref().unchecked_ref())?; 130 | closure.forget(); // FYI, the closure now lives forevah... evah... evah... 131 | } 132 | { 133 | let key_handler = key_handler.clone(); 134 | let closure = Closure::wrap(Box::new(move |event: web_sys::KeyboardEvent| { 135 | event.prevent_default(); 136 | let key = event_to_key(&event); 137 | key_handler.borrow_mut().set_key_state(key, false); 138 | }) as Box); 139 | canvas.add_event_listener_with_callback("keyup", closure.as_ref().unchecked_ref())?; 140 | closure.forget(); // FYI, the closure now lives forevah... evah... evah... 141 | } 142 | { 143 | let mouse_state = mouse_state.clone(); 144 | let closure = Closure::wrap(Box::new(move |event: web_sys::MouseEvent| { 145 | mouse_state 146 | .pos 147 | .set(Some((event.offset_x() as i32, event.offset_y() as i32))); 148 | match event.button() { 149 | 0 => mouse_state.left_button.set(true), 150 | 1 => mouse_state.middle_button.set(true), 151 | 2 => mouse_state.right_button.set(true), 152 | _ => (), 153 | } 154 | }) as Box); 155 | canvas 156 | .add_event_listener_with_callback("mousedown", closure.as_ref().unchecked_ref())?; 157 | closure.forget(); 158 | } 159 | { 160 | let mouse_state = mouse_state.clone(); 161 | let closure = Closure::wrap(Box::new(move |event: web_sys::MouseEvent| { 162 | mouse_state 163 | .pos 164 | .set(Some((event.offset_x() as i32, event.offset_y() as i32))); 165 | }) as Box); 166 | canvas 167 | .add_event_listener_with_callback("mousemove", closure.as_ref().unchecked_ref())?; 168 | closure.forget(); 169 | } 170 | { 171 | let mouse_state = mouse_state.clone(); 172 | let closure = Closure::wrap(Box::new(move |event: web_sys::MouseEvent| { 173 | mouse_state 174 | .pos 175 | .set(Some((event.offset_x() as i32, event.offset_y() as i32))); 176 | match event.button() { 177 | 0 => mouse_state.left_button.set(false), 178 | 1 => mouse_state.middle_button.set(false), 179 | 2 => mouse_state.right_button.set(false), 180 | _ => (), 181 | } 182 | }) as Box); 183 | canvas.add_event_listener_with_callback("mouseup", closure.as_ref().unchecked_ref())?; 184 | closure.forget(); 185 | } 186 | 187 | Ok(Window { 188 | width: width as u32, 189 | height: height as u32, 190 | bg_color: 0, 191 | window_scale, 192 | canvas, 193 | context2d: None, 194 | key_handler, 195 | mouse_state, 196 | menu_counter: MenuHandle(0), 197 | menus: Vec::new(), 198 | raw_handle_id, 199 | }) 200 | } 201 | 202 | fn create_2d_context(&self) -> CanvasRenderingContext2d { 203 | let context: CanvasRenderingContext2d = self 204 | .canvas 205 | .get_context("2d") 206 | .unwrap() 207 | .unwrap() 208 | .dyn_into::() 209 | .unwrap(); 210 | context.set_image_smoothing_enabled(false); 211 | context 212 | } 213 | 214 | #[inline] 215 | pub fn set_title(&mut self, title: &str) { 216 | let document = window().unwrap().document().unwrap(); 217 | document.set_title(title); 218 | } 219 | 220 | #[inline] 221 | pub fn set_rate(&mut self, _rate: Option) {} 222 | 223 | #[inline] 224 | pub fn update_rate(&mut self) {} 225 | 226 | #[inline] 227 | pub fn get_window_handle(&self) -> *mut c_void { 228 | std::ptr::null_mut() 229 | } 230 | 231 | #[inline] 232 | pub fn topmost(&self, _topmost: bool) { 233 | // TODO? 234 | } 235 | 236 | #[inline] 237 | pub fn set_background_color(&mut self, bg_color: u32) { 238 | self.bg_color = bg_color; 239 | } 240 | 241 | #[inline] 242 | pub fn set_cursor_visibility(&mut self, visibility: bool) { 243 | self.canvas 244 | .style() 245 | .set_property( 246 | "cursor", 247 | match visibility { 248 | true => "auto", 249 | false => "none", 250 | }, 251 | ) 252 | .unwrap_or(()); 253 | } 254 | 255 | pub fn update_with_buffer_stride( 256 | &mut self, 257 | buffer: &[u32], 258 | buf_width: usize, 259 | buf_height: usize, 260 | buf_stride: usize, 261 | ) -> Result<()> { 262 | check_buffer_size(buffer, buf_width, buf_height, buf_stride)?; 263 | // scaling not implemented. It's faster to just update the buffer 264 | //unsafe { self.scale_buffer(buffer, buf_width, buf_height, buf_stride) }; 265 | self.update_with_buffer(&buffer).unwrap(); 266 | 267 | Ok(()) 268 | } 269 | 270 | pub fn update_with_buffer(&mut self, buffer: &[u32]) -> Result<()> { 271 | check_buffer_size( 272 | buffer, 273 | self.width as usize, 274 | self.height as usize, 275 | self.window_scale, 276 | )?; 277 | let mut data = u32_as_u8(buffer); 278 | 279 | let image_data = ImageData::new_with_u8_clamped_array_and_sh( 280 | Clamped(&mut data), 281 | self.width, 282 | self.height, 283 | ) 284 | .unwrap(); 285 | 286 | if let Some(context2d) = &mut self.context2d { 287 | context2d.img_data = image_data; 288 | } else { 289 | self.context2d = Some(Context2D { 290 | context: self.create_2d_context(), 291 | img_data: image_data, 292 | }); 293 | } 294 | 295 | self.update(); 296 | 297 | Ok(()) 298 | } 299 | 300 | #[inline] 301 | pub fn update(&mut self) { 302 | self.key_handler.borrow_mut().update(); 303 | 304 | if let Some(context2d) = &self.context2d { 305 | context2d 306 | .context 307 | .put_image_data(&context2d.img_data, 0.0, 0.0) 308 | .unwrap(); 309 | } 310 | } 311 | 312 | #[inline] 313 | pub fn set_icon(&mut self, _icon: Icon) {} 314 | 315 | #[inline] 316 | pub fn set_position(&mut self, _x: isize, _y: isize) {} 317 | 318 | #[inline] 319 | pub fn get_position(&self) -> (isize, isize) { 320 | (0isize, 0isize) 321 | } 322 | 323 | #[inline] 324 | pub fn get_size(&self) -> (usize, usize) { 325 | (self.width as usize, self.height as usize) 326 | } 327 | 328 | #[inline] 329 | pub fn get_mouse_pos(&self, mode: MouseMode) -> Option<(f32, f32)> { 330 | if let Some((mouse_x, mouse_y)) = self.mouse_state.pos.get() { 331 | mode.get_pos( 332 | mouse_x as f32, 333 | mouse_y as f32, 334 | self.window_scale as f32, 335 | self.width as f32 * self.window_scale as f32, 336 | self.height as f32 * self.window_scale as f32, 337 | ) 338 | } else { 339 | None 340 | } 341 | } 342 | 343 | #[inline] 344 | pub fn get_unscaled_mouse_pos(&self, mode: MouseMode) -> Option<(f32, f32)> { 345 | if let Some((mouse_x, mouse_y)) = self.mouse_state.pos.get() { 346 | mode.get_pos( 347 | mouse_x as f32, 348 | mouse_y as f32, 349 | 1.0 as f32, 350 | self.width as f32 * self.window_scale as f32, 351 | self.height as f32 * self.window_scale as f32, 352 | ) 353 | } else { 354 | None 355 | } 356 | } 357 | 358 | #[inline] 359 | pub fn get_mouse_down(&self, button: MouseButton) -> bool { 360 | match button { 361 | MouseButton::Left => self.mouse_state.left_button.get(), 362 | MouseButton::Middle => self.mouse_state.middle_button.get(), 363 | MouseButton::Right => self.mouse_state.right_button.get(), 364 | } 365 | } 366 | 367 | #[inline] 368 | pub fn get_scroll_wheel(&self) -> Option<(f32, f32)> { 369 | None 370 | } 371 | 372 | #[inline] 373 | pub fn set_cursor_style(&mut self, _cursor: CursorStyle) {} 374 | 375 | #[inline] 376 | pub fn get_keys(&self) -> Vec { 377 | self.key_handler.borrow().get_keys() 378 | } 379 | 380 | #[inline] 381 | pub fn get_keys_pressed(&self, repeat: KeyRepeat) -> Vec { 382 | self.key_handler.borrow().get_keys_pressed(repeat) 383 | } 384 | 385 | #[inline] 386 | pub fn is_key_down(&self, key: Key) -> bool { 387 | self.key_handler.borrow().is_key_down(key) 388 | } 389 | 390 | #[inline] 391 | pub fn set_key_repeat_delay(&mut self, delay: f32) { 392 | self.key_handler.borrow_mut().set_key_repeat_delay(delay) 393 | } 394 | 395 | #[inline] 396 | pub fn set_key_repeat_rate(&mut self, rate: f32) { 397 | self.key_handler.borrow_mut().set_key_repeat_rate(rate) 398 | } 399 | 400 | #[inline] 401 | pub fn is_key_pressed(&self, key: Key, repeat: KeyRepeat) -> bool { 402 | self.key_handler.borrow().is_key_pressed(key, repeat) 403 | } 404 | 405 | #[inline] 406 | pub fn is_key_released(&self, key: Key) -> bool { 407 | self.key_handler.borrow().is_key_released(key) 408 | } 409 | 410 | #[inline] 411 | pub fn set_input_callback(&mut self, callback: Box) { 412 | self.key_handler.borrow_mut().set_input_callback(callback) 413 | } 414 | 415 | #[inline] 416 | pub fn is_open(&self) -> bool { 417 | true 418 | } 419 | 420 | #[inline] 421 | pub fn get_keys_released(&self) -> Vec { 422 | self.key_handler.borrow().get_keys_released() 423 | } 424 | 425 | #[inline] 426 | pub fn is_active(&self) -> bool { 427 | window() 428 | .and_then(|window| window.document()) 429 | .and_then(|document| document.active_element()) 430 | .map_or(false, |element| element == **self.canvas) 431 | } 432 | 433 | #[inline] 434 | fn next_menu_handle(&mut self) -> MenuHandle { 435 | let handle = self.menu_counter; 436 | self.menu_counter.0 += 1; 437 | handle 438 | } 439 | 440 | #[inline] 441 | pub fn add_menu(&mut self, menu: &Menu) -> MenuHandle { 442 | let handle = self.next_menu_handle(); 443 | let mut menu = menu.internal.clone(); 444 | menu.handle = handle; 445 | self.menus.push(menu); 446 | handle 447 | } 448 | 449 | #[inline] 450 | pub fn remove_menu(&mut self, handle: MenuHandle) { 451 | self.menus.retain(|ref menu| menu.handle != handle); 452 | } 453 | 454 | #[inline] 455 | pub fn is_menu_pressed(&mut self) -> Option { 456 | None 457 | } 458 | } 459 | 460 | pub struct Menu { 461 | pub internal: UnixMenu, 462 | } 463 | 464 | impl Menu { 465 | pub fn new(name: &str) -> Result { 466 | Ok(Menu { 467 | internal: UnixMenu { 468 | handle: MenuHandle(0), 469 | item_counter: MenuItemHandle(0), 470 | name: name.to_owned(), 471 | items: Vec::new(), 472 | }, 473 | }) 474 | } 475 | 476 | #[inline] 477 | pub fn add_sub_menu(&mut self, _name: &str, _sub_menu: &Menu) {} 478 | 479 | #[inline] 480 | fn next_item_handle(&mut self) -> MenuItemHandle { 481 | let handle = self.internal.item_counter; 482 | self.internal.item_counter.0 += 1; 483 | handle 484 | } 485 | 486 | #[inline] 487 | pub fn add_menu_item(&mut self, item: &MenuItem) -> MenuItemHandle { 488 | let item_handle = self.next_item_handle(); 489 | self.internal.items.push(UnixMenuItem { 490 | sub_menu: None, 491 | handle: self.internal.item_counter, 492 | id: item.id, 493 | label: item.label.clone(), 494 | enabled: item.enabled, 495 | key: item.key, 496 | modifier: item.modifier, 497 | }); 498 | item_handle 499 | } 500 | 501 | #[inline] 502 | pub fn remove_item(&mut self, _handle: &MenuItemHandle) {} 503 | } 504 | 505 | impl HasWindowHandle for Window { 506 | fn window_handle(&self) -> std::result::Result { 507 | let handle = WebWindowHandle::new(self.raw_handle_id); 508 | let raw_handle = RawWindowHandle::Web(handle); 509 | unsafe { Ok(WindowHandle::borrow_raw(raw_handle)) } 510 | } 511 | } 512 | 513 | impl HasDisplayHandle for Window { 514 | fn display_handle(&self) -> std::result::Result { 515 | let handle = WebDisplayHandle::new(); 516 | let raw_handle = RawDisplayHandle::Web(handle); 517 | unsafe { Ok(DisplayHandle::borrow_raw(raw_handle)) } 518 | } 519 | } 520 | -------------------------------------------------------------------------------- /src/rate.rs: -------------------------------------------------------------------------------- 1 | #[cfg(target_arch = "wasm32")] 2 | extern crate instant; 3 | #[cfg(target_arch = "wasm32")] 4 | use instant::{Duration, Instant}; 5 | #[cfg(not(target_arch = "wasm32"))] 6 | use std::time::{Duration, Instant}; 7 | 8 | #[cfg_attr(target_arch = "wasm32", allow(unused))] 9 | pub struct UpdateRate { 10 | target_rate: Option, 11 | prev_time: Instant, 12 | } 13 | 14 | #[cfg_attr(target_arch = "wasm32", allow(unused))] 15 | impl UpdateRate { 16 | pub fn new() -> UpdateRate { 17 | UpdateRate { 18 | // Default limit to 4 ms 19 | target_rate: Some(Duration::from_millis(4)), 20 | prev_time: Instant::now(), 21 | } 22 | } 23 | 24 | #[inline] 25 | pub fn set_rate(&mut self, rate: Option) { 26 | self.target_rate = rate 27 | } 28 | 29 | pub fn update(&mut self) { 30 | if let Some(target_rate) = self.target_rate { 31 | let delta = self.prev_time.elapsed(); 32 | 33 | if delta < target_rate { 34 | let sleep_time = target_rate - delta; 35 | //eprintln!("sleeping {} ms", sleep_time.as_secs_f64() * 1000.); 36 | std::thread::sleep(sleep_time); 37 | } 38 | 39 | self.prev_time = Instant::now(); 40 | } 41 | } 42 | } 43 | --------------------------------------------------------------------------------