Skip to main content

egui_baseview/
window.rs

1use std::cell::{Cell, RefCell};
2use std::sync::Arc;
3use std::sync::atomic::{AtomicBool, Ordering};
4use std::time::Instant;
5
6use baseview::dpi::{LogicalPosition, LogicalSize, Size};
7use baseview::{
8    Event, EventStatus, HandlerError, ParentWindowHandle, Window, WindowContext, WindowHandler,
9    WindowSettings, WindowSize,
10};
11use copypasta::ClipboardProvider;
12use egui::{FullOutput, Pos2, Rect, Rgba, ViewportCommand, pos2, vec2};
13use keyboard_types::Modifiers;
14use raw_window_handle::HasWindowHandle;
15
16use crate::App;
17use crate::{GraphicsConfig, renderer::Renderer};
18
19#[cfg(all(feature = "log", not(feature = "tracing")))]
20use log::{error, warn};
21#[cfg(feature = "tracing")]
22use tracing::{error, warn};
23
24/// A realtime-safe handle to request a update & repaint for an egui app.
25///
26/// This can be used, for example, to notify the GUI that the value of a decibel
27/// meter has changed.
28#[derive(Debug, Clone)]
29pub struct RepaintNotifier {
30    repaint: Arc<AtomicBool>,
31}
32
33impl RepaintNotifier {
34    pub fn new() -> Self {
35        Self {
36            repaint: Arc::new(AtomicBool::new(true)),
37        }
38    }
39
40    pub fn request_repaint(&self) {
41        self.repaint.store(true, Ordering::Relaxed);
42    }
43
44    pub fn request_repaint_with(&self, repaint: bool) {
45        if repaint {
46            self.repaint.store(true, Ordering::Relaxed);
47        }
48    }
49
50    fn repaint_requested(&self) -> bool {
51        self.repaint.swap(false, Ordering::Relaxed)
52    }
53}
54
55impl Default for RepaintNotifier {
56    fn default() -> Self {
57        Self::new()
58    }
59}
60
61/// Settings used when creating a new window
62#[derive(Debug, Clone)]
63pub struct EguiWindowSettings {
64    /// The window title.
65    pub title: String,
66
67    /// The size of the window, either in physical or logical coordinates.
68    pub size: Size,
69
70    /// The minimum window size. Set to `None` for no minimum size.
71    pub min_size: Option<Size>,
72    /// The maximum window size. Set to `None` for no maximum size.
73    pub max_size: Option<Size>,
74
75    /// Whether the window can be resized.
76    pub resizable: bool,
77
78    /// The amount of zoom (scaling) to apply. This is applied on top of the
79    /// system's native scaling factor.
80    ///
81    /// The zoom factor can also be changed later with
82    /// [`Context::set_zoom_factor()`](egui::Context::set_zoom_factor).
83    pub zoom_factor: f32,
84
85    /// The graphics configuration
86    pub graphics: GraphicsConfig,
87
88    /// If the window is to be embedded in a parent window, the handle to that window.
89    ///
90    /// If `None`, the window will be standalone.
91    pub parent: Option<ParentWindowHandle>,
92
93    /// If the window expects to have a parent when first displayed.
94    ///
95    /// Setting this will delay the actual creation of the window until the parent is set (unless
96    /// the window is shown first).
97    ///
98    /// If the `parent` field is already set, this does nothing and is ignored.
99    pub wait_for_parent: bool,
100
101    /// A fallback scale factor, if Baseview couldn't get one from the platform.
102    ///
103    /// If the platform does already provide an accurate scaling factor, this doesn't do anything.
104    ///
105    /// If the given fallback scale factor is actually useful and different from the current one
106    /// (1.0 by default), this will resize and redraw the window accordingly.
107    ///
108    /// # Platform compatibility notes.
109    ///
110    /// On Win32, this value is used if running on early versions of Windows 10 (or earlier).
111    ///
112    /// On X11, this value is used if no `Xft.dpi`setting is set.
113    ///
114    /// On macOS, this function is always a no-op.
115    pub fallback_scale_factor: Option<f64>,
116
117    /// A realtime-safe handle to request an update & repaint for an egui app.
118    ///
119    /// This can be used, for example, to notify the GUI that the value of a decibel
120    /// meter has changed.
121    pub repaint_notifier: Option<RepaintNotifier>,
122}
123
124impl EguiWindowSettings {
125    #[inline]
126    pub fn new() -> Self {
127        Self::default()
128    }
129
130    /// The window title.
131    #[inline]
132    pub fn with_title(mut self, title: impl Into<String>) -> Self {
133        self.title = title.into();
134        self
135    }
136
137    /// The size of the window, either in physical or logical coordinates.
138    #[inline]
139    pub fn with_size(mut self, size: impl Into<Size>) -> Self {
140        self.size = size.into();
141        self
142    }
143
144    /// Sets whether the window can be resized.
145    ///
146    /// Defaults to `true`.
147    #[inline]
148    pub fn with_resizable(mut self, resizable: bool) -> Self {
149        self.resizable = resizable;
150        self
151    }
152
153    /// The minimum window size. Set to `None` for no minimum size.
154    ///
155    /// Defaults to `None`.
156    #[inline]
157    pub fn with_min_size<S: Into<Size>>(mut self, min_size: Option<S>) -> Self {
158        self.min_size = min_size.map(|s| s.into());
159        self
160    }
161
162    /// The maximum window size. Set to `None` for no maximum size.
163    ///
164    /// Defaults to `None`.
165    #[inline]
166    pub fn with_max_size<S: Into<Size>>(mut self, max_size: Option<S>) -> Self {
167        self.max_size = max_size.map(|s| s.into());
168        self
169    }
170
171    /// The amount of zoom (scaling) to apply. This is applied on top of the
172    /// system's native scaling factor.
173    ///
174    /// This is ignored if [`size`](EguiWindowSettings::size) is in physical units.
175    ///
176    /// The zoom factor can also be changed later with
177    /// [`Context::set_zoom_factor()`](egui::Context::set_zoom_factor).
178    #[inline]
179    pub fn with_zoom_factor(mut self, zoom_factor: f32) -> Self {
180        self.zoom_factor = zoom_factor;
181        self
182    }
183
184    /// If the window is to be embedded in a parent window, the handle to that window.
185    ///
186    /// If `None`, the window will be standalone.
187    #[inline]
188    pub fn with_parent<'a, P: HasWindowHandle + 'a>(
189        mut self,
190        parent: impl Into<Option<&'a P>>,
191    ) -> Self {
192        self.parent = parent.into().map(ParentWindowHandle::from_window);
193        self
194    }
195
196    /// Sets [`wait_for_parent`](Self::wait_for_parent) to the given value.
197    pub fn with_wait_for_parent(mut self, wait_for_parent: bool) -> Self {
198        self.wait_for_parent = wait_for_parent;
199        self
200    }
201
202    /// Sets [`wait_for_parent`](Self::wait_for_parent) to `true`.
203    #[inline]
204    pub fn wait_for_parent(mut self) -> Self {
205        self.wait_for_parent = true;
206        self
207    }
208
209    /// Sets [`fallback_scale_factor`](Self::fallback_scale_factor) to the given value.
210    #[inline]
211    pub fn with_fallback_scale_factor(mut self, scale_factor: impl Into<Option<f64>>) -> Self {
212        self.fallback_scale_factor = scale_factor.into();
213        self
214    }
215
216    /// The graphics configuration
217    #[inline]
218    pub fn with_graphics_config(mut self, config: GraphicsConfig) -> Self {
219        self.graphics = config;
220        self
221    }
222
223    /// A clone of the realtime-safe handle to request a update & repaint for an egui app.
224    ///
225    /// This can be used, for example, to notify the GUI that the value of a decibel
226    /// meter has changed.
227    #[inline]
228    pub fn with_repaint_notifier(mut self, repaint_notifier: RepaintNotifier) -> Self {
229        self.repaint_notifier = Some(repaint_notifier);
230        self
231    }
232}
233
234impl Default for EguiWindowSettings {
235    fn default() -> Self {
236        Self {
237            title: String::new(),
238            size: Size::Logical(LogicalSize {
239                width: 300.0,
240                height: 200.0,
241            }),
242            min_size: None,
243            max_size: None,
244            resizable: true,
245            zoom_factor: 1.0,
246            graphics: GraphicsConfig::default(),
247            parent: None,
248            wait_for_parent: false,
249            fallback_scale_factor: None,
250            repaint_notifier: None,
251        }
252    }
253}
254
255/// Represents the surroundings of your app.
256pub struct Frame {
257    renderer: Renderer,
258    window: WindowContext,
259    clear_color: Rgba,
260    key_capture: KeyCapture,
261}
262
263impl Frame {
264    fn new(renderer: Renderer, window: WindowContext) -> Self {
265        Self {
266            renderer,
267            window,
268            clear_color: Rgba::BLACK,
269            key_capture: Default::default(),
270        }
271    }
272
273    /// Set the clear color of the renderer.
274    pub fn set_clear_color(&mut self, clear_color: Rgba) {
275        self.clear_color = clear_color;
276    }
277
278    /// Set how to handle capturing key events from the host.
279    pub fn set_key_capture(&mut self, key_capture: KeyCapture) {
280        self.key_capture = key_capture;
281    }
282
283    /// Access the internal baseview window.
284    pub fn baseview_window(&self) -> &WindowContext {
285        &self.window
286    }
287
288    /// A reference to the underlying
289    /// [glow](https://docs.rs/glow/0.17.0/x86_64-unknown-linux-gnu/glow/index.html)
290    /// (OpenGL) context.
291    ///
292    /// This can be used, for instance, to:
293    ///
294    /// * Render things to offscreen buffers.
295    /// * Read the pixel buffer from the previous frame (glow::Context::read_pixels).
296    /// * Render things behind the egui windows.
297    ///
298    /// Note that all egui painting is deferred to after the call to App::ui
299    /// (egui only collects egui::Shapes and then egui-baseview paints them all in
300    /// one go later on).
301    #[cfg(feature = "opengl")]
302    pub fn gl(&self) -> &std::sync::Arc<egui_glow::glow::Context> {
303        &self.renderer.glow_context
304    }
305}
306
307/// Describes how to handle capturing key events from the host.
308#[derive(Default, Debug, Clone, PartialEq)]
309pub enum KeyCapture {
310    #[default]
311    /// All keys will be captured from the host.
312    CaptureAll,
313    /// No keys will be captured from the host.
314    IgnoreAll,
315    /// Only the given keys will be captured from the host.
316    CaptureKeys(Vec<keyboard_types::Key>),
317    /// All keys except the given ones will be captured from the host.
318    IgnoreKeys(Vec<keyboard_types::Key>),
319}
320
321struct EguiWindowInner<A: App> {
322    user_app: A,
323    egui_ctx: egui::Context,
324    clipboard_ctx: Option<copypasta::ClipboardContext>,
325    frame: Frame,
326}
327
328/// Handles an egui-baseview application
329pub struct EguiWindow<A: App> {
330    inner: RefCell<EguiWindowInner<A>>,
331    egui_input: RefCell<egui::RawInput>,
332    viewport_id: egui::ViewportId,
333    start_time: Instant,
334    system_scale_factor: Cell<f64>,
335    zoom_factor: Cell<f32>,
336    pointer_logical_pos: Cell<Option<egui::Pos2>>,
337    current_cursor_icon: Cell<baseview::MouseCursor>,
338    repaint_notifier: Option<RepaintNotifier>,
339    modifiers: Cell<egui::Modifiers>,
340
341    // Re-use the allocations from the previous output.
342    full_output: RefCell<FullOutput>,
343
344    pub window: WindowContext,
345}
346
347impl<A: App> EguiWindow<A> {
348    fn new(
349        window: WindowContext,
350        title: String,
351        graphics_config: GraphicsConfig,
352        mut user_app: A,
353        zoom_factor: f32,
354        repaint_notifier: Option<RepaintNotifier>,
355    ) -> Result<EguiWindow<A>, HandlerError> {
356        let renderer = Renderer::new(window.clone(), graphics_config)?;
357        let egui_ctx = egui::Context::default();
358
359        egui_ctx.set_zoom_factor(zoom_factor);
360
361        {
362            let waker = window.waker();
363            egui_ctx.set_request_repaint_callback(move |request_repaint_info| {
364                waker.request_redraw_after(request_repaint_info.delay)
365            });
366        }
367
368        let size = window.size();
369
370        let system_scale_factor = size.scale_factor;
371        let total_scale_factor = system_scale_factor * zoom_factor as f64;
372
373        let logical_size: LogicalSize<f64> = size.physical.to_logical(total_scale_factor);
374
375        let screen_rect = Rect::from_min_size(
376            Pos2::new(0f32, 0f32),
377            vec2(logical_size.width as f32, logical_size.height as f32),
378        );
379
380        let viewport_info = egui::ViewportInfo {
381            parent: None,
382            title: Some(title),
383            native_pixels_per_point: Some(system_scale_factor as f32),
384            focused: Some(true),
385            inner_rect: Some(screen_rect),
386            ..Default::default()
387        };
388        let viewport_id = egui::ViewportId::default();
389
390        let mut egui_input = egui::RawInput {
391            max_texture_side: Some(renderer.max_texture_side()),
392            screen_rect: Some(screen_rect),
393            ..Default::default()
394        };
395        let _ = egui_input.viewports.insert(viewport_id, viewport_info);
396
397        let mut frame = Frame::new(renderer, window.clone());
398
399        user_app.build(egui_ctx.clone(), &mut frame)?;
400
401        let clipboard_ctx = match copypasta::ClipboardContext::new() {
402            Ok(clipboard_ctx) => Some(clipboard_ctx),
403            Err(e) => {
404                #[cfg(any(feature = "tracing", feature = "log"))]
405                error!("Failed to initialize clipboard: {}", e);
406
407                #[cfg(not(any(feature = "tracing", feature = "log")))]
408                let _ = e;
409
410                None
411            }
412        };
413
414        let start_time = Instant::now();
415
416        Ok(Self {
417            inner: RefCell::new(EguiWindowInner {
418                user_app,
419                egui_ctx,
420                clipboard_ctx,
421                frame,
422            }),
423            viewport_id,
424            start_time,
425            egui_input: egui_input.into(),
426            pointer_logical_pos: None.into(),
427            current_cursor_icon: baseview::MouseCursor::Default.into(),
428            system_scale_factor: system_scale_factor.into(),
429            zoom_factor: zoom_factor.into(),
430            window,
431            repaint_notifier,
432            modifiers: Cell::new(egui::Modifiers::default()),
433            full_output: RefCell::new(FullOutput::default()),
434        })
435    }
436
437    /// Open a new window.
438    ///
439    /// * `settings` - The settings of the window.
440    /// * `app` - The application to run.
441    pub fn create(settings: EguiWindowSettings, app: A) -> Result<Window, baseview::Error> {
442        Self::create_with_host(settings, app, None)
443    }
444
445    /// Open a new window.
446    ///
447    /// * `settings` - The settings of the window.
448    /// * `app` - The application to run.
449    /// * `host` - The baseview ['Host'](baseview::host::Host) callbacks.
450    pub fn create_with_host(
451        settings: EguiWindowSettings,
452        app: A,
453        host: Option<baseview::host::Host>,
454    ) -> Result<Window, baseview::Error> {
455        let size = match settings.size {
456            Size::Logical(size) => Size::Logical(LogicalSize {
457                width: size.width as f64 * settings.zoom_factor as f64,
458                height: size.height as f64 * settings.zoom_factor as f64,
459            }),
460            Size::Physical(size) => Size::Physical(size),
461        };
462
463        let mut options = WindowSettings::new()
464            .with_title(settings.title.clone())
465            .with_size(size)
466            .with_min_size::<Size>(settings.min_size)
467            .with_max_size::<Size>(settings.max_size)
468            .with_resizable(settings.resizable)
469            .with_wait_for_parent(settings.wait_for_parent)
470            .with_fallback_scale_factor(settings.fallback_scale_factor);
471
472        options.parent = settings.parent;
473
474        #[cfg(feature = "opengl")]
475        let options = { options.with_gl_config(Some(settings.graphics.gl_config.clone())) };
476
477        Window::create_with_host(
478            options,
479            move |window| {
480                EguiWindow::new(
481                    window,
482                    settings.title,
483                    settings.graphics,
484                    app,
485                    settings.zoom_factor,
486                    settings.repaint_notifier,
487                )
488            },
489            host,
490        )
491    }
492}
493
494/// Update the pressed key modifiers when a mouse event has sent a new set of modifiers.
495fn update_modifiers(
496    old_modifiers: &Cell<egui::Modifiers>,
497    new_modifiers: &Modifiers,
498    egui_input: &mut egui::RawInput,
499) {
500    let (new_mac_cmd, new_command) = if cfg!(target_os = "macos") {
501        let m = new_modifiers.meta();
502        (m, m)
503    } else {
504        (false, new_modifiers.ctrl())
505    };
506
507    let new_modifiers = egui::Modifiers {
508        alt: new_modifiers.alt(),
509        ctrl: new_modifiers.ctrl(),
510        shift: new_modifiers.shift(),
511        mac_cmd: new_mac_cmd,
512        command: new_command,
513    };
514
515    if old_modifiers.get() != new_modifiers {
516        old_modifiers.set(new_modifiers);
517        egui_input
518            .events
519            .push(egui::Event::ModifiersChanged(new_modifiers));
520    }
521}
522
523impl<A: App> WindowHandler for EguiWindow<A> {
524    fn poll(&self) {
525        if let Some(repaint_notifier) = &self.repaint_notifier
526            && repaint_notifier.repaint_requested()
527        {
528            self.window.request_redraw();
529        }
530    }
531
532    fn draw(&self) -> Result<(), HandlerError> {
533        let (egui_input, logical_size) = {
534            let mut egui_input = self.egui_input.borrow_mut();
535            egui_input.time = Some(self.start_time.elapsed().as_secs_f64());
536
537            let zoom_factor = self.zoom_factor.get();
538
539            let size = self.window.size();
540            let logical_size: LogicalSize<f32> = size
541                .physical
542                .to_logical(size.scale_factor * zoom_factor as f64);
543
544            let screen_rect = Rect::from_min_size(
545                Pos2::new(0f32, 0f32),
546                vec2(logical_size.width, logical_size.height),
547            );
548
549            egui_input.screen_rect = Some(screen_rect);
550            (egui_input.take(), logical_size)
551        };
552
553        // Re-use the allocations from the previous output.
554        let mut full_output = self.full_output.borrow_mut();
555
556        *full_output = {
557            let mut inner = self.inner.borrow_mut();
558            let EguiWindowInner {
559                user_app,
560                egui_ctx,
561                clipboard_ctx: _,
562                frame,
563            } = &mut *inner;
564
565            egui_ctx.run_ui(egui_input, |ui| user_app.ui(ui, frame))
566        };
567
568        let Some(viewport_output) = full_output.viewport_output.get(&self.viewport_id) else {
569            // The main window was closed by egui.
570            self.window.request_close();
571            return Ok(());
572        };
573
574        let mut new_size = None;
575        let new_zoom = { self.inner.borrow().egui_ctx.zoom_factor() };
576
577        if self.zoom_factor.get() != new_zoom {
578            self.zoom_factor.set(new_zoom);
579
580            let mut inner = self.inner.borrow_mut();
581
582            inner.egui_ctx.set_zoom_factor(new_zoom);
583            inner.user_app.zoom_factor_changed(new_zoom);
584
585            new_size = Some(Size::Logical(LogicalSize::new(
586                (logical_size.width * new_zoom) as f64,
587                (logical_size.height * new_zoom) as f64,
588            )));
589        }
590
591        for command in viewport_output.commands.iter() {
592            match command {
593                ViewportCommand::Close => {
594                    self.window.request_close();
595                }
596                ViewportCommand::InnerSize(size) => {
597                    new_size = Some(Size::Logical(LogicalSize::new(
598                        (size.x * new_zoom) as f64,
599                        (size.y * new_zoom) as f64,
600                    )));
601                }
602                ViewportCommand::Focus => {
603                    self.window.focus()?;
604                }
605                _ => {}
606            }
607        }
608
609        if let Some(new_size) = new_size {
610            if let Err(e) = self.window.resize(new_size) {
611                error!("Failed to resize window: {}", e);
612            }
613        }
614
615        {
616            let mut inner = self.inner.borrow_mut();
617            let EguiWindowInner {
618                user_app: _,
619                egui_ctx,
620                clipboard_ctx,
621                frame,
622            } = &mut *inner;
623
624            let size = self.window.size();
625            frame.renderer.render(
626                &self.window,
627                frame.clear_color,
628                size.physical,
629                size.scale_factor as f32 * egui_ctx.zoom_factor(),
630                egui_ctx,
631                &mut full_output,
632            );
633
634            for command in full_output.platform_output.commands.drain(..) {
635                match command {
636                    egui::OutputCommand::CopyText(text) => {
637                        if let Some(clipboard_ctx) = clipboard_ctx.as_mut()
638                            && let Err(err) = clipboard_ctx.set_contents(text)
639                        {
640                            #[cfg(any(feature = "tracing", feature = "log"))]
641                            error!("Copy/Cut error: {}", err);
642
643                            #[cfg(not(any(feature = "tracing", feature = "log")))]
644                            let _ = err;
645                        }
646                    }
647                    egui::OutputCommand::CopyImage(_) => {
648                        #[cfg(any(feature = "tracing", feature = "log"))]
649                        warn!("Copying images is not supported in egui_baseview.");
650                    }
651                    egui::OutputCommand::OpenUrl(open_url) => {
652                        if let Err(err) = open::that_detached(&open_url.url) {
653                            #[cfg(any(feature = "tracing", feature = "log"))]
654                            error!("Open error: {}", err);
655
656                            #[cfg(not(any(feature = "tracing", feature = "log")))]
657                            let _ = err;
658                        }
659                    }
660                }
661            }
662        }
663
664        let cursor_icon =
665            crate::translate::translate_cursor_icon(full_output.platform_output.cursor_icon);
666        if self.current_cursor_icon.get() != cursor_icon {
667            self.current_cursor_icon.set(cursor_icon);
668
669            self.window.set_mouse_cursor(cursor_icon)?;
670        }
671
672        // A temporary workaround for keyboard input not working sometimes.
673        // See https://codeberg.org/RustAudio/egui-baseview/issues/20
674        #[cfg(feature = "keyboard_focus_workaround")]
675        {
676            if !full_output.platform_output.events.is_empty()
677                || full_output.platform_output.ime.is_some()
678            {
679                self.window.focus();
680            }
681        }
682
683        Ok(())
684    }
685
686    fn resized(&self, new_size: WindowSize) -> Result<(), HandlerError> {
687        let zoom_factor = self.inner.borrow().egui_ctx.zoom_factor();
688
689        let total_scale_factor = new_size.scale_factor * zoom_factor as f64;
690        let logical_size: LogicalSize<f64> = new_size.physical.to_logical(total_scale_factor);
691
692        let screen_rect = Rect::from_min_size(
693            Pos2::new(0f32, 0f32),
694            vec2(logical_size.width as f32, logical_size.height as f32),
695        );
696
697        let mut egui_input = self.egui_input.borrow_mut();
698
699        egui_input.screen_rect = Some(screen_rect);
700
701        let viewport_info = egui_input.viewports.get_mut(&self.viewport_id).unwrap();
702        viewport_info.native_pixels_per_point = Some(new_size.scale_factor as f32);
703        viewport_info.inner_rect = Some(screen_rect);
704
705        self.system_scale_factor.set(new_size.scale_factor);
706
707        let mut inner = self.inner.borrow_mut();
708
709        inner.user_app.resized(WindowSize {
710            physical: new_size.physical,
711            logical: logical_size,
712            scale_factor: total_scale_factor,
713        });
714
715        Ok(())
716    }
717
718    fn on_event(&self, event: Event) -> EventStatus {
719        let mut return_status = EventStatus::Captured;
720
721        // Parent/embedded windows do not always gain keyboard focus
722        // Automatically on click. Request focus explicitly before forwarding the event.
723        //
724        // TODO: Check if this is still necessary.
725        if matches!(
726            event,
727            baseview::Event::Mouse(baseview::MouseEvent::ButtonPressed { .. })
728        ) && !self.window.has_focus()
729        {
730            self.window.focus().unwrap();
731        }
732
733        let mut egui_input = self.egui_input.borrow_mut();
734
735        let mut do_repaint = true;
736
737        match &event {
738            baseview::Event::Mouse(event) => match event {
739                baseview::MouseEvent::CursorMoved {
740                    position,
741                    modifiers,
742                } => {
743                    update_modifiers(&self.modifiers, modifiers, &mut egui_input);
744
745                    let logical_pos: LogicalPosition<f32> = position.to_logical(
746                        self.system_scale_factor.get()
747                            * self.inner.borrow().egui_ctx.zoom_factor() as f64,
748                    );
749                    let pos = pos2(logical_pos.x, logical_pos.y);
750
751                    self.pointer_logical_pos.set(Some(pos));
752                    egui_input.events.push(egui::Event::PointerMoved(pos));
753                }
754                baseview::MouseEvent::ButtonPressed { button, modifiers } => {
755                    update_modifiers(&self.modifiers, modifiers, &mut egui_input);
756
757                    if let Some(pos) = self.pointer_logical_pos.get()
758                        && let Some(button) = crate::translate::translate_mouse_button(*button)
759                    {
760                        egui_input.events.push(egui::Event::PointerButton {
761                            pos,
762                            button,
763                            pressed: true,
764                            modifiers: self.modifiers.get(),
765                        });
766                    }
767                }
768                baseview::MouseEvent::ButtonReleased { button, modifiers } => {
769                    update_modifiers(&self.modifiers, modifiers, &mut egui_input);
770
771                    if let Some(pos) = self.pointer_logical_pos.get()
772                        && let Some(button) = crate::translate::translate_mouse_button(*button)
773                    {
774                        egui_input.events.push(egui::Event::PointerButton {
775                            pos,
776                            button,
777                            pressed: false,
778                            modifiers: self.modifiers.get(),
779                        });
780                    }
781                }
782                baseview::MouseEvent::WheelScrolled {
783                    delta: scroll_delta,
784                    modifiers,
785                } => {
786                    update_modifiers(&self.modifiers, modifiers, &mut egui_input);
787
788                    #[allow(unused_mut)]
789                    let (unit, mut delta) = match scroll_delta {
790                        baseview::ScrollDelta::Lines { x, y } => {
791                            (egui::MouseWheelUnit::Line, egui::vec2(*x, *y))
792                        }
793
794                        baseview::ScrollDelta::Pixels { x, y } => (
795                            egui::MouseWheelUnit::Point,
796                            egui::vec2(*x, *y) * self.window.scale_factor() as f32,
797                        ),
798                    };
799
800                    if cfg!(target_os = "macos") {
801                        // This is still buggy in winit despite
802                        // https://github.com/rust-windowing/winit/issues/1695 being closed
803                        //
804                        // TODO: See if this is an issue in baseview as well.
805                        delta.x *= -1.0;
806                    }
807
808                    egui_input.events.push(egui::Event::MouseWheel {
809                        unit,
810                        delta,
811                        modifiers: self.modifiers.get(),
812                        phase: egui::TouchPhase::Move,
813                    });
814                }
815                baseview::MouseEvent::CursorLeft => {
816                    self.pointer_logical_pos.set(None);
817                    egui_input.events.push(egui::Event::PointerGone);
818                }
819                _ => do_repaint = false,
820            },
821            baseview::Event::Keyboard(event) => {
822                update_modifiers(&self.modifiers, &event.modifiers, &mut egui_input);
823
824                let pressed = event.state == keyboard_types::KeyState::Down;
825
826                let modifiers = self.modifiers.get();
827
828                if let Some(key) = crate::translate::translate_virtual_key(&event.key) {
829                    egui_input.events.push(egui::Event::Key {
830                        key,
831                        physical_key: None,
832                        pressed,
833                        repeat: event.repeat,
834                        modifiers,
835                    });
836                }
837
838                if pressed {
839                    // VirtualKeyCode::Paste etc in winit are broken/untrustworthy,
840                    // so we detect these things manually:
841                    //
842                    // TODO: See if this is an issue in baseview as well.
843                    if is_cut_command(modifiers, event.code) {
844                        egui_input.events.push(egui::Event::Cut);
845                    } else if is_copy_command(modifiers, event.code) {
846                        egui_input.events.push(egui::Event::Copy);
847                    } else if is_paste_command(modifiers, event.code) {
848                        if let Some(clipboard_ctx) = self.inner.borrow_mut().clipboard_ctx.as_mut()
849                        {
850                            match clipboard_ctx.get_contents() {
851                                Ok(contents) => egui_input.events.push(egui::Event::Text(contents)),
852                                Err(err) => {
853                                    #[cfg(any(feature = "tracing", feature = "log"))]
854                                    error!("Paste error: {}", err);
855
856                                    #[cfg(not(any(feature = "tracing", feature = "log")))]
857                                    let _ = err;
858                                }
859                            }
860                        }
861                    } else if let keyboard_types::Key::Character(written) = &event.key
862                        && !modifiers.ctrl
863                        && !modifiers.command
864                    {
865                        egui_input.events.push(egui::Event::Text(written.clone()));
866                    }
867                }
868
869                match &self.inner.borrow().frame.key_capture {
870                    KeyCapture::CaptureAll => {}
871                    KeyCapture::IgnoreAll => return_status = EventStatus::Ignored,
872                    KeyCapture::CaptureKeys(keys) => {
873                        if !keys.contains(&event.key) {
874                            return_status = EventStatus::Ignored
875                        }
876                    }
877                    KeyCapture::IgnoreKeys(keys) => {
878                        if keys.contains(&event.key) {
879                            return_status = EventStatus::Ignored
880                        }
881                    }
882                }
883            }
884            baseview::Event::Window(event) => match event {
885                baseview::WindowEvent::Focused => {
886                    egui_input.events.push(egui::Event::WindowFocused(true));
887                    egui_input
888                        .viewports
889                        .get_mut(&self.viewport_id)
890                        .unwrap()
891                        .focused = Some(true);
892                }
893                baseview::WindowEvent::Unfocused => {
894                    egui_input.events.push(egui::Event::WindowFocused(false));
895                    egui_input
896                        .viewports
897                        .get_mut(&self.viewport_id)
898                        .unwrap()
899                        .focused = Some(false);
900                }
901                baseview::WindowEvent::WillClose => {}
902                _ => {}
903            },
904            _ => do_repaint = false,
905        }
906
907        if do_repaint {
908            self.window.request_redraw();
909        }
910
911        // For keyboard events, also check if egui actually wants keyboard input
912        // This allows DAW shortcuts (spacebar, etc.) to pass through when no text field is focused
913        match &event {
914            baseview::Event::Keyboard(_) => {
915                let egui_ctx = &self.inner.borrow().egui_ctx;
916                if return_status == EventStatus::Captured && !egui_ctx.egui_wants_keyboard_input() {
917                    EventStatus::Ignored
918                } else {
919                    return_status
920                }
921            }
922            baseview::Event::Mouse(_) => {
923                let egui_ctx = &self.inner.borrow().egui_ctx;
924                if egui_ctx.egui_is_using_pointer() || egui_ctx.egui_wants_pointer_input() {
925                    EventStatus::Captured
926                } else {
927                    EventStatus::Ignored
928                }
929            }
930            baseview::Event::Window(_) => EventStatus::Captured,
931            _ => EventStatus::Ignored,
932        }
933    }
934}
935
936fn is_cut_command(modifiers: egui::Modifiers, keycode: keyboard_types::Code) -> bool {
937    (modifiers.command && keycode == keyboard_types::Code::KeyX)
938        || (cfg!(target_os = "windows")
939            && modifiers.shift
940            && keycode == keyboard_types::Code::Delete)
941}
942
943fn is_copy_command(modifiers: egui::Modifiers, keycode: keyboard_types::Code) -> bool {
944    (modifiers.command && keycode == keyboard_types::Code::KeyC)
945        || (cfg!(target_os = "windows")
946            && modifiers.ctrl
947            && keycode == keyboard_types::Code::Insert)
948}
949
950fn is_paste_command(modifiers: egui::Modifiers, keycode: keyboard_types::Code) -> bool {
951    (modifiers.command && keycode == keyboard_types::Code::KeyV)
952        || (cfg!(target_os = "windows")
953            && modifiers.shift
954            && keycode == keyboard_types::Code::Insert)
955}