1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
//! Provides a glfw-based backend platform for imgui-rs. This crate is modeled
//! after the winit version.
//!
//! # Usage
//!
//! 1. Initialize a `GlfwPlatform`
//! 2. Attach it to a glfw `Window`
//! 3. Optionally, enable platform clipboard integration
//! 4. Pass events to the platform (every frame)
//! 5. Call frame preparation (every frame)
//! 6. Call render preperation (every frame)
//!
//! # Example
//!
//! ```no_run
//! use std::time::Instant;
//!
//! fn main() {
//!     let mut glfw = glfw::init(glfw::FAIL_ON_ERRORS).expect("GLFW failed to init");
//!     glfw.window_hint(glfw::WindowHint::ClientApi(glfw::ClientApiHint::NoApi));
//!
//!     let (width, height) = (1600, 900);
//!
//!     let (mut window, event_receiver) = glfw
//!         .create_window(width, height, "Hello, ImGui", glfw::WindowMode::Windowed)
//!         .expect("failed to create window");
//!
//!     window.set_all_polling(true);
//!
//!     let surface = wgpu::Surface::create(&window);
//!
//!     let adapter = wgpu::Adapter::request(&wgpu::RequestAdapterOptions {
//!         power_preference: wgpu::PowerPreference::HighPerformance,
//!         backends: wgpu::BackendBit::PRIMARY,
//!     })
//!     .unwrap();
//!
//!     let (device, mut queue) = adapter.request_device(&wgpu::DeviceDescriptor {
//!         extensions: wgpu::Extensions {
//!             anisotropic_filtering: false,
//!         },
//!         limits: wgpu::Limits::default(),
//!     });
//!
//!     let mut swap_chain_desc = wgpu::SwapChainDescriptor {
//!         usage: wgpu::TextureUsage::OUTPUT_ATTACHMENT,
//!         format: wgpu::TextureFormat::Bgra8Unorm,
//!         width,
//!         height,
//!         present_mode: wgpu::PresentMode::NoVsync,
//!     };
//!
//!     let mut swap_chain = device.create_swap_chain(&surface, &swap_chain_desc);
//!
//!     let mut imgui = imgui::Context::create();
//!     imgui.set_ini_filename(None);
//!
//!     let mut glfw_platform = imgui_glfw_support::GlfwPlatform::init(&mut imgui);
//!
//!     glfw_platform.attach_window(
//!         imgui.io_mut(),
//!         &window,
//!         imgui_glfw_support::HiDpiMode::Default,
//!     );
//!
//!     // Adding platform clipboard integration is unsafe because the caller must ensure that
//!     // the window outlives the imgui context and that all imgui functions that may access
//!     // the clipboard are called from the main thread.
//!     unsafe {
//!         glfw_platform.set_clipboard_backend(&mut imgui, &window);
//!     }
//!
//!     let clear_color = wgpu::Color {
//!         r: 0.1,
//!         g: 0.2,
//!         b: 0.3,
//!         a: 1.0,
//!     };
//!
//!     let mut imgui_renderer = imgui_wgpu::Renderer::new(
//!         &mut imgui,
//!         &device,
//!         &mut queue,
//!         swap_chain_desc.format,
//!         Some(clear_color),
//!     );
//!
//!     let mut last_cursor = None;
//!     let mut last_frame_time = Instant::now();
//!
//!     while !window.should_close() {
//!         glfw.wait_events_timeout(0.1);
//!
//!         let mut recreate_swap_chain = false;
//!         for (_timestamp, event) in event_receiver.try_iter() {
//!             glfw_platform.handle_event(imgui.io_mut(), &window, &event);
//!             match event {
//!                 glfw::WindowEvent::Size(width, height) => {
//!                     swap_chain_desc.width = width as _;
//!                     swap_chain_desc.height = height as _;
//!                     recreate_swap_chain = true;
//!                 }
//!                 _ => {}
//!             }
//!         }
//!         if recreate_swap_chain {
//!             swap_chain = device.create_swap_chain(&surface, &swap_chain_desc);
//!         }
//!
//!         let frame = swap_chain.get_next_texture();
//!         last_frame_time = imgui.io_mut().update_delta_time(last_frame_time);
//!
//!         glfw_platform
//!             .prepare_frame(imgui.io_mut(), &mut window)
//!             .expect("prepare_frame failed");
//!
//!         let ui = imgui.frame();
//!         ui.show_demo_window(&mut true);
//!
//!         let cursor = ui.mouse_cursor();
//!         if last_cursor != cursor {
//!             last_cursor = cursor;
//!             glfw_platform.prepare_render(&ui, &mut window);
//!         }
//!
//!         let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor::default());
//!         imgui_renderer
//!             .render(ui.render(), &device, &mut encoder, &frame.view)
//!             .expect("render failed");
//!         queue.submit(&[encoder.finish()]);
//!     }
//! }
//!
//! ```

use glfw::{
    Action, Cursor, CursorMode, Key as GlfwKey, Modifiers, MouseButton, StandardCursor, Window,
    WindowEvent,
};
use imgui::{BackendFlags, ConfigFlags, Context, ImString, Io, Key, Ui};

pub struct GlfwPlatform {
    hidpi_mode: ActiveHiDpiMode,
    hidpi_factor: f64,
}

#[derive(Copy, Clone, Debug, PartialEq)]
enum ActiveHiDpiMode {
    Default,
    Rounded,
    Locked,
}

#[derive(Copy, Clone, Debug, PartialEq)]
pub enum HiDpiMode {
    /// The DPI factor from glfw is used directly without adjustment
    Default,
    /// The DPI factor from glfw is rounded to an integer value.
    ///
    /// This prevents the user interface from becoming blurry with non-integer scaling.
    Rounded,
    /// The DPI factor from glfw is ignored, and the included value is used instead.
    ///
    /// This is useful if you want to force some DPI factor (e.g. 1.0) and not care about the value
    /// coming from glfw.
    Locked(f64),
}

struct Clipboard {
    window_ptr: *mut glfw::ffi::GLFWwindow,
}

impl imgui::ClipboardBackend for Clipboard {
    fn set(&mut self, s: &imgui::ImStr) {
        unsafe {
            glfw::ffi::glfwSetClipboardString(self.window_ptr, s.as_ptr());
        }
    }
    fn get(&mut self) -> std::option::Option<imgui::ImString> {
        unsafe {
            let s = glfw::ffi::glfwGetClipboardString(self.window_ptr);
            let s = std::ffi::CStr::from_ptr(s);
            let bytes = s.to_bytes();
            if !bytes.is_empty() {
                let v = String::from_utf8_lossy(bytes);
                Some(imgui::ImString::new(v))
            } else {
                None
            }
        }
    }
}

impl HiDpiMode {
    fn apply(&self, hidpi_factor: f64) -> (ActiveHiDpiMode, f64) {
        match *self {
            HiDpiMode::Default => (ActiveHiDpiMode::Default, hidpi_factor),
            HiDpiMode::Rounded => (ActiveHiDpiMode::Rounded, hidpi_factor.round()),
            HiDpiMode::Locked(value) => (ActiveHiDpiMode::Locked, value),
        }
    }
}

impl GlfwPlatform {
    /// Initializes a glfw platform instance and configures imgui.
    ///
    /// * backend flgs are updated
    /// * keys are configured
    /// * platform name is set
    pub fn init(imgui: &mut Context) -> GlfwPlatform {
        let io = imgui.io_mut();
        io.backend_flags.insert(BackendFlags::HAS_MOUSE_CURSORS);
        io.backend_flags.insert(BackendFlags::HAS_SET_MOUSE_POS);
        io.backend_flags.insert(BackendFlags::HAS_MOUSE_CURSORS);
        io.backend_flags.insert(BackendFlags::HAS_SET_MOUSE_POS);
        io[Key::Tab] = GlfwKey::Tab as _;
        io[Key::LeftArrow] = GlfwKey::Left as _;
        io[Key::RightArrow] = GlfwKey::Right as _;
        io[Key::UpArrow] = GlfwKey::Up as _;
        io[Key::DownArrow] = GlfwKey::Down as _;
        io[Key::PageUp] = GlfwKey::PageUp as _;
        io[Key::PageDown] = GlfwKey::PageDown as _;
        io[Key::Home] = GlfwKey::Home as _;
        io[Key::End] = GlfwKey::End as _;
        io[Key::Insert] = GlfwKey::Insert as _;
        io[Key::Delete] = GlfwKey::Delete as _;
        io[Key::Backspace] = GlfwKey::Backspace as _;
        io[Key::Space] = GlfwKey::Space as _;
        io[Key::Enter] = GlfwKey::Enter as _;
        io[Key::Escape] = GlfwKey::Escape as _;
        io[Key::KeyPadEnter] = GlfwKey::KpEnter as _;
        io[Key::A] = GlfwKey::A as _;
        io[Key::C] = GlfwKey::C as _;
        io[Key::V] = GlfwKey::V as _;
        io[Key::X] = GlfwKey::X as _;
        io[Key::Y] = GlfwKey::Y as _;
        io[Key::Z] = GlfwKey::Z as _;
        imgui.set_platform_name(Some(ImString::from(format!(
            "imgui-glfw-support {}",
            env!("CARGO_PKG_VERSION")
        ))));
        GlfwPlatform {
            hidpi_mode: ActiveHiDpiMode::Default,
            hidpi_factor: 1.0,
        }
    }

    /// Adds platform clipboard integration for the provided window. The caller **must** ensure that
    /// the `Window` outlives the imgui `Context` **and** that any imgui functions that may access
    /// the clipboard are called from the **main thread** (the thread that's executing the event polling).
    pub unsafe fn set_clipboard_backend(&self, imgui: &mut Context, window: &Window) {
        use glfw::Context;
        let window_ptr = window.window_ptr();
        imgui.set_clipboard_backend(Box::new(Clipboard { window_ptr }));
    }

    /// Attaches the platform instance to a glfw window.
    ///
    /// * framebuffer sacle (i.e. DPI factor) is set
    /// * display size is set
    pub fn attach_window(&mut self, io: &mut Io, window: &Window, hidpi_mode: HiDpiMode) {
        let (scale_factor_x, _scale_factor_y) = window.get_content_scale();
        let (hidpi_mode, hidpi_factor) = hidpi_mode.apply(scale_factor_x as _);
        self.hidpi_mode = hidpi_mode;
        self.hidpi_factor = hidpi_factor;
        io.display_framebuffer_scale = [hidpi_factor as f32, hidpi_factor as f32];
        let (width, height) = window.get_size();
        io.display_size = [width as f32, height as f32];
    }

    /// Handles a glfw window event
    ///
    /// * keyboard state is updated
    /// * mouse state is updated
    pub fn handle_event(&self, io: &mut Io, _window: &Window, event: &WindowEvent) {
        match *event {
            WindowEvent::Key(key, _scancode, action, modifiers) => {
                if action == Action::Release {
                    io.keys_down[key as usize] = false;
                } else {
                    io.keys_down[key as usize] = true;
                }
                io.key_shift = modifiers.contains(Modifiers::Shift);
                io.key_ctrl = modifiers.contains(Modifiers::Control);
                io.key_alt = modifiers.contains(Modifiers::Alt);
                io.key_super = modifiers.contains(Modifiers::Super);
            }
            WindowEvent::Size(width, height) => {
                io.display_size = [width as _, height as _];
            }
            WindowEvent::Char(ch) => {
                // Exclude the backspace key
                if ch != '\u{7f}' {
                    io.add_input_character(ch);
                }
            }
            WindowEvent::CursorPos(x, y) => {
                io.mouse_pos = [x as _, y as _];
            }
            WindowEvent::Scroll(x, y) => {
                io.mouse_wheel_h = x as _;
                io.mouse_wheel = y as _;
            }
            WindowEvent::MouseButton(button, action, _modifiers) => {
                let pressed = action == Action::Press;
                match button {
                    MouseButton::Button1 => io.mouse_down[0] = pressed,
                    MouseButton::Button2 => io.mouse_down[1] = pressed,
                    MouseButton::Button3 => io.mouse_down[2] = pressed,
                    _ => (),
                }
            }
            _ => {}
        }
    }

    /// Prepare the window for the next frame.
    ///
    /// Call before calling the imgui-rs `Context::frame` function.
    ///
    /// * mouse cursor is repositioned if requested by imgui
    pub fn prepare_frame(&self, io: &mut Io, window: &mut Window) -> Result<(), String> {
        if io.want_set_mouse_pos {
            let [x, y] = io.mouse_pos;
            window.set_cursor_pos(x as _, y as _);
            Ok(())
        } else {
            Ok(())
        }
    }

    /// Prepare the window for rendering.
    ///
    /// Call before calling the imgui backend renderer function (e.g. `imgui_wgpu::Renderer::render`).
    ///
    /// * the mouse cursor is changed or hidden if requested by imgui
    pub fn prepare_render(&self, ui: &Ui, window: &mut Window) {
        let io = ui.io();
        if !io
            .config_flags
            .contains(ConfigFlags::NO_MOUSE_CURSOR_CHANGE)
        {
            match ui.mouse_cursor() {
                Some(mouse_cursor) if !io.mouse_draw_cursor => {
                    window.set_cursor_mode(CursorMode::Normal);
                    window.set_cursor(Some(match mouse_cursor {
                        // TODO: GLFW has more cursor options on master, but they aren't released yet
                        imgui::MouseCursor::Arrow => Cursor::standard(StandardCursor::Arrow),
                        imgui::MouseCursor::ResizeAll => Cursor::standard(StandardCursor::Arrow),
                        imgui::MouseCursor::ResizeNS => Cursor::standard(StandardCursor::VResize),
                        imgui::MouseCursor::ResizeEW => Cursor::standard(StandardCursor::HResize),
                        imgui::MouseCursor::ResizeNESW => Cursor::standard(StandardCursor::Arrow),
                        imgui::MouseCursor::ResizeNWSE => Cursor::standard(StandardCursor::Arrow),
                        imgui::MouseCursor::Hand => Cursor::standard(StandardCursor::Hand),
                        imgui::MouseCursor::NotAllowed => {
                            Cursor::standard(StandardCursor::Crosshair)
                        }
                        imgui::MouseCursor::TextInput => Cursor::standard(StandardCursor::IBeam),
                    }));
                }
                _ => window.set_cursor_mode(CursorMode::Hidden),
            }
        }
    }
}