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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
//! [egui](https://github.com/emilk/egui) bindings for [miniquad](https://github.com/not-fl3/miniquad).
//!
//! ## Usage
//! Create an instance of [`EguiMq`] and call its event-handler from
//! your `miniquad::EventHandler` implementation.
//!
//! In your `miniquad::EventHandler::draw` method do this:
//!
//! ```
//! use miniquad as mq;
//!
//! struct MyMiniquadApp {
//!     egui_mq: egui_miniquad::EguiMq,
//! }
//!
//! impl MyMiniquadApp {
//!     fn new(ctx: &mut mq::Context) -> Self {
//!         Self {
//!             egui_mq: egui_miniquad::EguiMq::new(ctx),
//!         }
//!     }
//!
//!     fn ui(&mut self) {
//!         egui::Window::new("Egui Window").show(self.egui_mq.egui_ctx(), |ui| {
//!             ui.heading("Hello World!");
//!         });
//!     }
//! }
//!
//! impl mq::EventHandler for MyMiniquadApp {
//!     fn update(&mut self, _: &mut mq::Context) {}
//!
//!     fn draw(&mut self, ctx: &mut mq::Context) {
//!         ctx.clear(Some((1., 1., 1., 1.)), None, None);
//!         ctx.begin_default_pass(mq::PassAction::clear_color(0.0, 0.0, 0.0, 1.0));
//!         ctx.end_render_pass();
//!
//!         self.egui_mq.begin_frame(ctx);
//!         self.ui();
//!         self.egui_mq.end_frame(ctx);
//!
//!         // Draw things behind egui here
//!
//!         self.egui_mq.draw(ctx);
//!
//!         // Draw things in front of egui here
//!
//!         ctx.commit_frame();
//!     }
//!
//!     fn mouse_motion_event(&mut self, ctx: &mut mq::Context, x: f32, y: f32) {
//!         self.egui_mq.mouse_motion_event(ctx, x, y);
//!     }
//!
//!     fn mouse_wheel_event(&mut self, ctx: &mut mq::Context, dx: f32, dy: f32) {
//!         self.egui_mq.mouse_wheel_event(ctx, dx, dy);
//!     }
//!
//!     fn mouse_button_down_event(
//!         &mut self,
//!         ctx: &mut mq::Context,
//!         mb: mq::MouseButton,
//!         x: f32,
//!         y: f32,
//!     ) {
//!         self.egui_mq.mouse_button_down_event(ctx, mb, x, y);
//!     }
//!
//!     fn mouse_button_up_event(
//!         &mut self,
//!         ctx: &mut mq::Context,
//!         mb: mq::MouseButton,
//!         x: f32,
//!         y: f32,
//!     ) {
//!         self.egui_mq.mouse_button_up_event(ctx, mb, x, y);
//!     }
//!
//!     fn char_event(
//!         &mut self,
//!         _ctx: &mut mq::Context,
//!         character: char,
//!         _keymods: mq::KeyMods,
//!         _repeat: bool,
//!     ) {
//!         self.egui_mq.char_event(character);
//!     }
//!
//!     fn key_down_event(
//!         &mut self,
//!         ctx: &mut mq::Context,
//!         keycode: mq::KeyCode,
//!         keymods: mq::KeyMods,
//!         _repeat: bool,
//!     ) {
//!         self.egui_mq.key_down_event(ctx, keycode, keymods);
//!     }
//!
//!     fn key_up_event(&mut self, _ctx: &mut mq::Context, keycode: mq::KeyCode, keymods: mq::KeyMods) {
//!         self.egui_mq.key_up_event(keycode, keymods);
//!     }
//! }
//! ```

mod input;
mod painter;

// ----------------------------------------------------------------------------

use egui::CursorIcon;
use miniquad as mq;

#[cfg(target_os = "macos")] // https://github.com/not-fl3/miniquad/issues/172
use copypasta::ClipboardProvider;

/// egui bindings for miniquad.
///
///
pub struct EguiMq {
    egui_ctx: egui::CtxRef,
    egui_input: egui::RawInput,
    painter: painter::Painter,
    #[cfg(target_os = "macos")]
    clipboard: Option<copypasta::ClipboardContext>,
    shapes: Option<Vec<egui::epaint::ClippedShape>>,
}

impl EguiMq {
    pub fn new(mq_ctx: &mut mq::Context) -> Self {
        Self {
            egui_ctx: egui::CtxRef::default(),
            painter: painter::Painter::new(mq_ctx),
            egui_input: Default::default(),
            #[cfg(target_os = "macos")]
            clipboard: init_clipboard(),
            shapes: None,
        }
    }

    /// Use this to open egui windows, panels etc.
    /// Can only be used between [`Self::begin_frame`] and [`Self::end_frame`].
    pub fn egui_ctx(&self) -> &egui::CtxRef {
        &self.egui_ctx
    }

    /// Call this at the start of each `draw` call.
    pub fn begin_frame(&mut self, mq_ctx: &mut mq::Context) {
        input::on_frame_start(&mut self.egui_input, mq_ctx);
        self.egui_ctx.begin_frame(self.egui_input.take());
    }

    /// Call this at the end of each `draw` call.
    /// This will draw the `egui` interface.
    pub fn end_frame(&mut self, mq_ctx: &mut mq::Context) {
        let (output, shapes) = self.egui_ctx.end_frame();
        if self.shapes.is_some() {
            eprintln!(
                "Egui contents not drawed. You need to call `draw` after calling `end_frame`"
            );
        }
        self.shapes = Some(shapes);

        let egui::Output {
            cursor_icon,
            open_url,
            copied_text,
            needs_repaint: _, // miniquad always runs at full framerate
            events: _,        // no screen reader
            text_cursor: _,   // no IME
        } = output;

        if let Some(url) = open_url {
            quad_url::link_open(&url.url, url.new_tab);
        }

        if cursor_icon == egui::CursorIcon::None {
            mq_ctx.show_mouse(false);
        } else {
            mq_ctx.show_mouse(true);

            let mq_cursor_icon = to_mq_cursor_icon(cursor_icon);
            let mq_cursor_icon = mq_cursor_icon.unwrap_or(mq::CursorIcon::Default);
            mq_ctx.set_mouse_cursor(mq_cursor_icon);
        }

        if !copied_text.is_empty() {
            self.set_clipboard(mq_ctx, copied_text);
        }
    }

    /// Call this when you need to draw egui.
    /// Must be called after `end_frame`.
    pub fn draw(&mut self, mq_ctx: &mut mq::Context) {
        if let Some(shapes) = self.shapes.take() {
            let paint_jobs = self.egui_ctx.tessellate(shapes);
            self.painter
                .paint(mq_ctx, paint_jobs, &self.egui_ctx.texture());
        } else {
            eprintln!("Failed to draw egui. You need to call `end_frame` before calling `draw`");
        }
    }

    /// Call from your [`miniquad::EventHandler`].
    pub fn mouse_motion_event(&mut self, ctx: &mut mq::Context, x: f32, y: f32) {
        let pos = egui::pos2(x as f32 / ctx.dpi_scale(), y as f32 / ctx.dpi_scale());
        self.egui_input.events.push(egui::Event::PointerMoved(pos))
    }

    /// Call from your [`miniquad::EventHandler`].
    pub fn mouse_wheel_event(&mut self, ctx: &mut mq::Context, dx: f32, dy: f32) {
        self.egui_input.scroll_delta += egui::vec2(dx, dy) * ctx.dpi_scale(); // not quite right speed on Mac for some reason
    }

    /// Call from your [`miniquad::EventHandler`].
    pub fn mouse_button_down_event(
        &mut self,
        ctx: &mut mq::Context,
        mb: mq::MouseButton,
        x: f32,
        y: f32,
    ) {
        let pos = egui::pos2(x as f32 / ctx.dpi_scale(), y as f32 / ctx.dpi_scale());
        let button = to_egui_button(mb);
        self.egui_input.events.push(egui::Event::PointerButton {
            pos,
            button,
            pressed: true,
            modifiers: self.egui_input.modifiers,
        })
    }

    /// Call from your [`miniquad::EventHandler`].
    pub fn mouse_button_up_event(
        &mut self,
        ctx: &mut mq::Context,
        mb: mq::MouseButton,
        x: f32,
        y: f32,
    ) {
        let pos = egui::pos2(x as f32 / ctx.dpi_scale(), y as f32 / ctx.dpi_scale());
        let button = to_egui_button(mb);

        self.egui_input.events.push(egui::Event::PointerButton {
            pos,
            button,
            pressed: false,
            modifiers: self.egui_input.modifiers,
        })
    }

    /// Call from your [`miniquad::EventHandler`].
    pub fn char_event(&mut self, chr: char) {
        if input::is_printable_char(chr)
            && !self.egui_input.modifiers.ctrl
            && !self.egui_input.modifiers.mac_cmd
        {
            self.egui_input
                .events
                .push(egui::Event::Text(chr.to_string()));
        }
    }

    /// Call from your [`miniquad::EventHandler`].
    pub fn key_down_event(
        &mut self,
        mq_ctx: &mut mq::Context,
        keycode: mq::KeyCode,
        keymods: mq::KeyMods,
    ) {
        let modifiers = input::egui_modifiers_from_mq_modifiers(keymods);
        self.egui_input.modifiers = modifiers;

        if modifiers.command && keycode == mq::KeyCode::X {
            self.egui_input.events.push(egui::Event::Cut);
        } else if modifiers.command && keycode == mq::KeyCode::C {
            self.egui_input.events.push(egui::Event::Copy);
        } else if modifiers.command && keycode == mq::KeyCode::V {
            if let Some(text) = self.get_clipboard(mq_ctx) {
                self.egui_input.events.push(egui::Event::Text(text));
            }
        } else if let Some(key) = input::egui_key_from_mq_key(keycode) {
            self.egui_input.events.push(egui::Event::Key {
                key,
                pressed: true,
                modifiers,
            })
        }
    }

    /// Call from your [`miniquad::EventHandler`].
    pub fn key_up_event(&mut self, keycode: mq::KeyCode, keymods: mq::KeyMods) {
        let modifiers = input::egui_modifiers_from_mq_modifiers(keymods);
        self.egui_input.modifiers = modifiers;
        if let Some(key) = input::egui_key_from_mq_key(keycode) {
            self.egui_input.events.push(egui::Event::Key {
                key,
                pressed: false,
                modifiers,
            })
        }
    }

    #[cfg(not(target_os = "macos"))]
    fn set_clipboard(&mut self, mq_ctx: &mut mq::Context, text: String) {
        mq::clipboard::set(mq_ctx, text.as_str());
    }

    #[cfg(not(target_os = "macos"))]
    fn get_clipboard(&mut self, mq_ctx: &mut mq::Context) -> Option<String> {
        mq::clipboard::get(mq_ctx)
    }

    #[cfg(target_os = "macos")]
    fn set_clipboard(&mut self, _mq_ctx: &mut mq::Context, text: String) {
        if let Some(clipboard) = &mut self.clipboard {
            if let Err(err) = clipboard.set_contents(text) {
                eprintln!("Copy/Cut error: {}", err);
            }
        }
    }

    #[cfg(target_os = "macos")]
    fn get_clipboard(&mut self, _mq_ctx: &mut mq::Context) -> Option<String> {
        if let Some(clipboard) = &mut self.clipboard {
            match clipboard.get_contents() {
                Ok(contents) => Some(contents),
                Err(err) => {
                    eprintln!("Paste error: {}", err);
                    None
                }
            }
        } else {
            None
        }
    }
}

#[cfg(target_os = "macos")]
fn init_clipboard() -> Option<copypasta::ClipboardContext> {
    match copypasta::ClipboardContext::new() {
        Ok(clipboard) => Some(clipboard),
        Err(err) => {
            eprintln!("Failed to initialize clipboard: {}", err);
            None
        }
    }
}

fn to_egui_button(mb: mq::MouseButton) -> egui::PointerButton {
    match mb {
        mq::MouseButton::Left => egui::PointerButton::Primary,
        mq::MouseButton::Right => egui::PointerButton::Secondary,
        mq::MouseButton::Middle => egui::PointerButton::Middle,
        mq::MouseButton::Unknown => egui::PointerButton::Primary,
    }
}

fn to_mq_cursor_icon(cursor_icon: egui::CursorIcon) -> Option<mq::CursorIcon> {
    match cursor_icon {
        // Handled outside this function
        CursorIcon::None => None,

        egui::CursorIcon::Default => Some(mq::CursorIcon::Default),
        egui::CursorIcon::PointingHand => Some(mq::CursorIcon::Pointer),
        egui::CursorIcon::Text => Some(mq::CursorIcon::Text),
        egui::CursorIcon::ResizeHorizontal => Some(mq::CursorIcon::EWResize),
        egui::CursorIcon::ResizeVertical => Some(mq::CursorIcon::NSResize),
        egui::CursorIcon::ResizeNeSw => Some(mq::CursorIcon::NESWResize),
        egui::CursorIcon::ResizeNwSe => Some(mq::CursorIcon::NWSEResize),
        egui::CursorIcon::Help => Some(mq::CursorIcon::Help),
        egui::CursorIcon::Wait => Some(mq::CursorIcon::Wait),
        egui::CursorIcon::Crosshair => Some(mq::CursorIcon::Crosshair),
        egui::CursorIcon::Move => Some(mq::CursorIcon::Move),
        egui::CursorIcon::NotAllowed => Some(mq::CursorIcon::NotAllowed),

        // Similar enough
        egui::CursorIcon::AllScroll => Some(mq::CursorIcon::Move),
        egui::CursorIcon::Progress => Some(mq::CursorIcon::Wait),

        // Not implemented, see https://github.com/not-fl3/miniquad/pull/173 and https://github.com/not-fl3/miniquad/issues/171
        egui::CursorIcon::Grab | egui::CursorIcon::Grabbing => None,

        // Also not implemented:
        egui::CursorIcon::Alias
        | egui::CursorIcon::Cell
        | egui::CursorIcon::ContextMenu
        | egui::CursorIcon::Copy
        | egui::CursorIcon::NoDrop
        | egui::CursorIcon::VerticalText
        | egui::CursorIcon::ZoomIn
        | egui::CursorIcon::ZoomOut => None,
    }
}