-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathglow_integration.rs
1474 lines (1268 loc) · 53.2 KB
/
glow_integration.rs
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Note that this file contains code very similar to [`wgpu_integration`].
//! When making changes to one you often also want to apply it to the other.
//!
//! This is also very complex code, and not very pretty.
//! There is a bunch of improvements we could do,
//! like removing a bunch of `unwraps`.
#![allow(clippy::arc_with_non_send_sync)] // glow::Context was accidentally non-Sync in glow 0.13, but that will be fixed in future releases of glow: https://github.com/grovesNL/glow/commit/c4a5f7151b9b4bbb380faa06ec27415235d1bf7e
use std::{cell::RefCell, rc::Rc, sync::Arc, time::Instant};
use glutin::{
config::GlConfig,
context::NotCurrentGlContext,
display::GetGlDisplay,
prelude::{GlDisplay, PossiblyCurrentGlContext},
surface::GlSurface,
};
use winit::{
event_loop::{EventLoop, EventLoopProxy, EventLoopWindowTarget},
window::{Window, WindowId},
};
use egui::{
epaint::ahash::HashMap, DeferredViewportUiCallback, ImmediateViewport, NumExt as _,
ViewportBuilder, ViewportClass, ViewportId, ViewportIdMap, ViewportIdPair, ViewportIdSet,
ViewportInfo, ViewportOutput,
};
#[cfg(feature = "accesskit")]
use egui_winit::accesskit_winit;
use crate::{
native::{epi_integration::EpiIntegration, winit_integration::create_egui_context},
App, AppCreator, CreationContext, NativeOptions, Result, Storage,
};
use super::{
winit_integration::{EventResult, UserEvent, WinitApp},
*,
};
// Note: that the current Glutin API design tightly couples the GL context with
// the Window which means it's not practically possible to just destroy the
// window and re-create a new window while continuing to use the same GL context.
//
// For now this means it's not possible to support Android as well as we can with
// wgpu because we're basically forced to destroy and recreate _everything_ when
// the application suspends and resumes.
//
// There is work in progress to improve the Glutin API so it has a separate Surface
// API that would allow us to just destroy a Window/Surface when suspending, see:
// https://github.com/rust-windowing/glutin/pull/1435
// ----------------------------------------------------------------------------
// Types:
pub struct GlowWinitApp {
repaint_proxy: Arc<egui::mutex::Mutex<EventLoopProxy<UserEvent>>>,
app_name: String,
native_options: NativeOptions,
running: Option<GlowWinitRunning>,
// Note that since this `AppCreator` is FnOnce we are currently unable to support
// re-initializing the `GlowWinitRunning` state on Android if the application
// suspends and resumes.
app_creator: Option<AppCreator>,
}
/// State that is initialized when the application is first starts running via
/// a Resumed event. On Android this ensures that any graphics state is only
/// initialized once the application has an associated `SurfaceView`.
struct GlowWinitRunning {
integration: EpiIntegration,
app: Box<dyn App>,
// These needs to be shared with the immediate viewport renderer, hence the Rc/Arc/RefCells:
glutin: Rc<RefCell<GlutinWindowContext>>,
// NOTE: one painter shared by all viewports.
painter: Rc<RefCell<egui_glow::Painter>>,
}
/// This struct will contain both persistent and temporary glutin state.
///
/// Platform Quirks:
/// * Microsoft Windows: requires that we create a window before opengl context.
/// * Android: window and surface should be destroyed when we receive a suspend event. recreate on resume event.
///
/// winit guarantees that we will get a Resumed event on startup on all platforms.
/// * Before Resumed event: `gl_config`, `gl_context` can be created at any time. on windows, a window must be created to get `gl_context`.
/// * Resumed: `gl_surface` will be created here. `window` will be re-created here for android.
/// * Suspended: on android, we drop window + surface. on other platforms, we don't get Suspended event.
///
/// The setup is divided between the `new` fn and `on_resume` fn. we can just assume that `on_resume` is a continuation of
/// `new` fn on all platforms. only on android, do we get multiple resumed events because app can be suspended.
struct GlutinWindowContext {
egui_ctx: egui::Context,
swap_interval: glutin::surface::SwapInterval,
gl_config: glutin::config::Config,
max_texture_side: Option<usize>,
current_gl_context: Option<glutin::context::PossiblyCurrentContext>,
not_current_gl_context: Option<glutin::context::NotCurrentContext>,
viewports: ViewportIdMap<Viewport>,
viewport_from_window: HashMap<WindowId, ViewportId>,
window_from_viewport: ViewportIdMap<WindowId>,
focused_viewport: Option<ViewportId>,
}
struct Viewport {
ids: ViewportIdPair,
class: ViewportClass,
builder: ViewportBuilder,
info: ViewportInfo,
screenshot_requested: bool,
/// The user-callback that shows the ui.
/// None for immediate viewports.
viewport_ui_cb: Option<Arc<DeferredViewportUiCallback>>,
// These three live and die together.
// TODO(emilk): clump them together into one struct!
gl_surface: Option<glutin::surface::Surface<glutin::surface::WindowSurface>>,
window: Option<Arc<Window>>,
egui_winit: Option<egui_winit::State>,
}
// ----------------------------------------------------------------------------
impl GlowWinitApp {
pub fn new(
event_loop: &EventLoop<UserEvent>,
app_name: &str,
native_options: NativeOptions,
app_creator: AppCreator,
) -> Self {
crate::profile_function!();
Self {
repaint_proxy: Arc::new(egui::mutex::Mutex::new(event_loop.create_proxy())),
app_name: app_name.to_owned(),
native_options,
running: None,
app_creator: Some(app_creator),
}
}
#[allow(unsafe_code)]
fn create_glutin_windowed_context(
egui_ctx: &egui::Context,
event_loop: &EventLoopWindowTarget<UserEvent>,
storage: Option<&dyn Storage>,
native_options: &mut NativeOptions,
) -> Result<(GlutinWindowContext, egui_glow::Painter)> {
crate::profile_function!();
let window_settings = epi_integration::load_window_settings(storage);
let winit_window_builder = epi_integration::viewport_builder(
egui_ctx.zoom_factor(),
event_loop,
native_options,
window_settings,
)
.with_visible(false); // Start hidden until we render the first frame to fix white flash on startup (https://github.com/emilk/egui/pull/3631)
let mut glutin_window_context = unsafe {
GlutinWindowContext::new(egui_ctx, winit_window_builder, native_options, event_loop)?
};
// Creates the window - must come before we create our glow context
glutin_window_context.initialize_window(ViewportId::ROOT, event_loop)?;
{
let viewport = &glutin_window_context.viewports[&ViewportId::ROOT];
let window = viewport.window.as_ref().unwrap(); // Can't fail - we just called `initialize_all_viewports`
epi_integration::apply_window_settings(window, window_settings);
}
let gl = unsafe {
crate::profile_scope!("glow::Context::from_loader_function");
Arc::new(glow::Context::from_loader_function(|s| {
let s = std::ffi::CString::new(s)
.expect("failed to construct C string from string for gl proc address");
glutin_window_context.get_proc_address(&s)
}))
};
let painter = egui_glow::Painter::new(gl, "", native_options.shader_version)?;
Ok((glutin_window_context, painter))
}
fn init_run_state(
&mut self,
event_loop: &EventLoopWindowTarget<UserEvent>,
) -> Result<&mut GlowWinitRunning> {
crate::profile_function!();
let storage = epi_integration::create_storage(
self.native_options
.viewport
.app_id
.as_ref()
.unwrap_or(&self.app_name),
);
let egui_ctx = create_egui_context(storage.as_deref());
let (mut glutin, painter) = Self::create_glutin_windowed_context(
&egui_ctx,
event_loop,
storage.as_deref(),
&mut self.native_options,
)?;
let gl = painter.gl().clone();
let max_texture_side = painter.max_texture_side();
glutin.max_texture_side = Some(max_texture_side);
for viewport in glutin.viewports.values_mut() {
if let Some(egui_winit) = viewport.egui_winit.as_mut() {
egui_winit.set_max_texture_side(max_texture_side);
}
}
let system_theme =
winit_integration::system_theme(&glutin.window(ViewportId::ROOT), &self.native_options);
let integration = EpiIntegration::new(
egui_ctx,
&glutin.window(ViewportId::ROOT),
system_theme,
&self.app_name,
&self.native_options,
storage,
Some(gl.clone()),
#[cfg(feature = "wgpu")]
None,
);
{
let event_loop_proxy = self.repaint_proxy.clone();
integration
.egui_ctx
.set_request_repaint_callback(move |info| {
log::trace!("request_repaint_callback: {info:?}");
let when = Instant::now() + info.delay;
let frame_nr = info.current_frame_nr;
event_loop_proxy
.lock()
.send_event(UserEvent::RequestRepaint {
viewport_id: info.viewport_id,
when,
frame_nr,
})
.ok();
});
}
#[cfg(feature = "accesskit")]
{
let event_loop_proxy = self.repaint_proxy.lock().clone();
let viewport = glutin.viewports.get_mut(&ViewportId::ROOT).unwrap();
if let Viewport {
window: Some(window),
egui_winit: Some(egui_winit),
..
} = viewport
{
integration.init_accesskit(egui_winit, window, event_loop_proxy);
}
}
let theme = system_theme.unwrap_or(self.native_options.default_theme);
integration.egui_ctx.set_visuals(theme.egui_visuals());
if self
.native_options
.viewport
.mouse_passthrough
.unwrap_or(false)
{
if let Err(err) = glutin.window(ViewportId::ROOT).set_cursor_hittest(false) {
log::warn!("set_cursor_hittest(false) failed: {err}");
}
}
let app_creator = std::mem::take(&mut self.app_creator)
.expect("Single-use AppCreator has unexpectedly already been taken");
let app = {
// Use latest raw_window_handle for eframe compatibility
use raw_window_handle::{HasDisplayHandle as _, HasWindowHandle as _};
let window = glutin.window(ViewportId::ROOT);
let cc = CreationContext {
egui_ctx: integration.egui_ctx.clone(),
integration_info: integration.frame.info().clone(),
storage: integration.frame.storage(),
gl: Some(gl),
#[cfg(feature = "wgpu")]
wgpu_render_state: None,
raw_display_handle: window.display_handle().map(|h| h.as_raw()),
raw_window_handle: window.window_handle().map(|h| h.as_raw()),
};
crate::profile_scope!("app_creator");
app_creator(&cc)
};
let glutin = Rc::new(RefCell::new(glutin));
let painter = Rc::new(RefCell::new(painter));
{
// Create weak pointers so that we don't keep
// state alive for too long.
let glutin = Rc::downgrade(&glutin);
let painter = Rc::downgrade(&painter);
let beginning = integration.beginning;
let event_loop: *const EventLoopWindowTarget<UserEvent> = event_loop;
egui::Context::set_immediate_viewport_renderer(move |egui_ctx, immediate_viewport| {
if let (Some(glutin), Some(painter)) = (glutin.upgrade(), painter.upgrade()) {
// SAFETY: the event loop lives longer than
// the Rc:s we just upgraded above.
#[allow(unsafe_code)]
let event_loop = unsafe { event_loop.as_ref().unwrap() };
render_immediate_viewport(
event_loop,
egui_ctx,
&glutin,
&painter,
beginning,
immediate_viewport,
);
} else {
log::warn!("render_sync_callback called after window closed");
}
});
}
Ok(self.running.insert(GlowWinitRunning {
glutin,
painter,
integration,
app,
}))
}
}
impl WinitApp for GlowWinitApp {
fn frame_nr(&self, viewport_id: ViewportId) -> u64 {
self.running
.as_ref()
.map_or(0, |r| r.integration.egui_ctx.frame_nr_for(viewport_id))
}
fn is_focused(&self, window_id: WindowId) -> bool {
if let Some(running) = &self.running {
let glutin = running.glutin.borrow();
if let Some(window_id) = glutin.viewport_from_window.get(&window_id) {
return glutin.focused_viewport == Some(*window_id);
}
}
false
}
fn integration(&self) -> Option<&EpiIntegration> {
self.running.as_ref().map(|r| &r.integration)
}
fn window(&self, window_id: WindowId) -> Option<Arc<Window>> {
let running = self.running.as_ref()?;
let glutin = running.glutin.borrow();
let viewport_id = *glutin.viewport_from_window.get(&window_id)?;
if let Some(viewport) = glutin.viewports.get(&viewport_id) {
viewport.window.clone()
} else {
None
}
}
fn window_id_from_viewport_id(&self, id: ViewportId) -> Option<WindowId> {
self.running
.as_ref()
.and_then(|r| r.glutin.borrow().window_from_viewport.get(&id).copied())
}
fn save_and_destroy(&mut self) {
if let Some(mut running) = self.running.take() {
crate::profile_function!();
running.integration.save(
running.app.as_mut(),
Some(&running.glutin.borrow().window(ViewportId::ROOT)),
);
running.app.on_exit(Some(running.painter.borrow().gl()));
running.painter.borrow_mut().destroy();
}
}
fn run_ui_and_paint(
&mut self,
event_loop: &EventLoopWindowTarget<UserEvent>,
window_id: WindowId,
) -> EventResult {
if let Some(running) = &mut self.running {
running.run_ui_and_paint(event_loop, window_id)
} else {
EventResult::Wait
}
}
fn on_event(
&mut self,
event_loop: &EventLoopWindowTarget<UserEvent>,
event: &winit::event::Event<UserEvent>,
) -> Result<EventResult> {
crate::profile_function!(winit_integration::short_event_description(event));
Ok(match event {
winit::event::Event::Resumed => {
log::debug!("Event::Resumed");
let running = if let Some(running) = &mut self.running {
// Not the first resume event. Create all outstanding windows.
running
.glutin
.borrow_mut()
.initialize_all_windows(event_loop);
running
} else {
// First resume event. Created our root window etc.
self.init_run_state(event_loop)?
};
let window_id = running.glutin.borrow().window_from_viewport[&ViewportId::ROOT];
EventResult::RepaintNow(window_id)
}
winit::event::Event::Suspended => {
if let Some(running) = &mut self.running {
running.glutin.borrow_mut().on_suspend()?;
}
EventResult::Wait
}
winit::event::Event::WindowEvent { event, window_id } => {
if let Some(running) = &mut self.running {
running.on_window_event(*window_id, event)
} else {
EventResult::Wait
}
}
#[cfg(feature = "accesskit")]
winit::event::Event::UserEvent(UserEvent::AccessKitActionRequest(
accesskit_winit::ActionRequestEvent { request, window_id },
)) => {
if let Some(running) = &self.running {
let mut glutin = running.glutin.borrow_mut();
if let Some(viewport_id) = glutin.viewport_from_window.get(window_id).copied() {
if let Some(viewport) = glutin.viewports.get_mut(&viewport_id) {
if let Some(egui_winit) = &mut viewport.egui_winit {
crate::profile_scope!("on_accesskit_action_request");
egui_winit.on_accesskit_action_request(request.clone());
}
}
}
// As a form of user input, accessibility actions should
// lead to a repaint.
EventResult::RepaintNext(*window_id)
} else {
EventResult::Wait
}
}
_ => EventResult::Wait,
})
}
}
impl GlowWinitRunning {
fn run_ui_and_paint(
&mut self,
event_loop: &EventLoopWindowTarget<UserEvent>,
window_id: WindowId,
) -> EventResult {
crate::profile_function!();
let Some(viewport_id) = self
.glutin
.borrow()
.viewport_from_window
.get(&window_id)
.copied()
else {
return EventResult::Wait;
};
#[cfg(feature = "puffin")]
puffin::GlobalProfiler::lock().new_frame();
{
let glutin = self.glutin.borrow();
let viewport = &glutin.viewports[&viewport_id];
let is_immediate = viewport.viewport_ui_cb.is_none();
if is_immediate && viewport_id != ViewportId::ROOT {
// This will only happen if this is an immediate viewport.
// That means that the viewport cannot be rendered by itself and needs his parent to be rendered.
if let Some(parent_viewport) = glutin.viewports.get(&viewport.ids.parent) {
if let Some(window) = parent_viewport.window.as_ref() {
return EventResult::RepaintNext(window.id());
}
}
return EventResult::Wait;
}
}
let (raw_input, viewport_ui_cb) = {
let mut glutin = self.glutin.borrow_mut();
let egui_ctx = glutin.egui_ctx.clone();
let viewport = glutin.viewports.get_mut(&viewport_id).unwrap();
let window = viewport.window.as_ref().unwrap();
egui_winit::update_viewport_info(&mut viewport.info, &egui_ctx, window);
let egui_winit = viewport.egui_winit.as_mut().unwrap();
let mut raw_input = egui_winit.take_egui_input(window);
let viewport_ui_cb = viewport.viewport_ui_cb.clone();
self.integration.pre_update();
raw_input.time = Some(self.integration.beginning.elapsed().as_secs_f64());
raw_input.viewports = glutin
.viewports
.iter()
.map(|(id, viewport)| (*id, viewport.info.clone()))
.collect();
(raw_input, viewport_ui_cb)
};
let clear_color = self
.app
.clear_color(&self.integration.egui_ctx.style().visuals);
let has_many_viewports = self.glutin.borrow().viewports.len() > 1;
let clear_before_update = !has_many_viewports; // HACK: for some reason, an early clear doesn't "take" on Mac with multiple viewports.
if clear_before_update {
// clear before we call update, so users can paint between clear-color and egui windows:
let mut glutin = self.glutin.borrow_mut();
let GlutinWindowContext {
viewports,
current_gl_context,
..
} = &mut *glutin;
let viewport = &viewports[&viewport_id];
let window = viewport.window.as_ref().unwrap();
let gl_surface = viewport.gl_surface.as_ref().unwrap();
let screen_size_in_pixels: [u32; 2] = window.inner_size().into();
change_gl_context(current_gl_context, gl_surface);
self.painter
.borrow()
.clear(screen_size_in_pixels, clear_color);
}
// ------------------------------------------------------------
// The update function, which could call immediate viewports,
// so make sure we don't hold any locks here required by the immediate viewports rendeer.
let full_output =
self.integration
.update(self.app.as_mut(), viewport_ui_cb.as_deref(), raw_input);
// ------------------------------------------------------------
let Self {
integration,
app,
glutin,
painter,
..
} = self;
let mut glutin = glutin.borrow_mut();
let mut painter = painter.borrow_mut();
let egui::FullOutput {
platform_output,
textures_delta,
shapes,
pixels_per_point,
viewport_output,
} = full_output;
let GlutinWindowContext {
viewports,
current_gl_context,
..
} = &mut *glutin;
let viewport = viewports.get_mut(&viewport_id).unwrap();
viewport.info.events.clear(); // they should have been processed
let window = viewport.window.as_ref().unwrap();
let gl_surface = viewport.gl_surface.as_ref().unwrap();
let egui_winit = viewport.egui_winit.as_mut().unwrap();
integration.post_update();
egui_winit.handle_platform_output(window, platform_output);
let clipped_primitives = integration.egui_ctx.tessellate(shapes, pixels_per_point);
// We may need to switch contexts again, because of immediate viewports:
change_gl_context(current_gl_context, gl_surface);
let screen_size_in_pixels: [u32; 2] = window.inner_size().into();
if !clear_before_update {
painter.clear(screen_size_in_pixels, clear_color);
}
painter.paint_and_update_textures(
screen_size_in_pixels,
pixels_per_point,
&clipped_primitives,
&textures_delta,
);
{
let screenshot_requested = std::mem::take(&mut viewport.screenshot_requested);
if screenshot_requested {
let screenshot = painter.read_screen_rgba(screen_size_in_pixels);
egui_winit
.egui_input_mut()
.events
.push(egui::Event::Screenshot {
viewport_id,
image: screenshot.into(),
});
}
integration.post_rendering(window);
}
{
crate::profile_scope!("swap_buffers");
if let Err(err) = gl_surface.swap_buffers(
current_gl_context
.as_ref()
.expect("failed to get current context to swap buffers"),
) {
log::error!("swap_buffers failed: {err}");
}
}
// give it time to settle:
#[cfg(feature = "__screenshot")]
if integration.egui_ctx.frame_nr() == 2 {
if let Ok(path) = std::env::var("EFRAME_SCREENSHOT_TO") {
save_screeshot_and_exit(&path, &painter, screen_size_in_pixels);
}
}
integration.maybe_autosave(app.as_mut(), Some(window));
if window.is_minimized() == Some(true) {
// On Mac, a minimized Window uses up all CPU:
// https://github.com/emilk/egui/issues/325
crate::profile_scope!("minimized_sleep");
std::thread::sleep(std::time::Duration::from_millis(10));
}
glutin.handle_viewport_output(event_loop, &integration.egui_ctx, viewport_output);
if integration.should_close() {
EventResult::Exit
} else {
EventResult::Wait
}
}
fn on_window_event(
&mut self,
window_id: WindowId,
event: &winit::event::WindowEvent,
) -> EventResult {
crate::profile_function!(egui_winit::short_window_event_description(event));
let mut glutin = self.glutin.borrow_mut();
let viewport_id = glutin.viewport_from_window.get(&window_id).copied();
// On Windows, if a window is resized by the user, it should repaint synchronously, inside the
// event handler.
//
// If this is not done, the compositor will assume that the window does not want to redraw,
// and continue ahead.
//
// In eframe's case, that causes the window to rapidly flicker, as it struggles to deliver
// new frames to the compositor in time.
//
// The flickering is technically glutin or glow's fault, but we should be responding properly
// to resizes anyway, as doing so avoids dropping frames.
//
// See: https://github.com/emilk/egui/issues/903
let mut repaint_asap = false;
match event {
winit::event::WindowEvent::Focused(new_focused) => {
glutin.focused_viewport = new_focused.then(|| viewport_id).flatten();
}
winit::event::WindowEvent::Resized(physical_size) => {
// Resize with 0 width and height is used by winit to signal a minimize event on Windows.
// See: https://github.com/rust-windowing/winit/issues/208
// This solves an issue where the app would panic when minimizing on Windows.
if 0 < physical_size.width && 0 < physical_size.height {
if let Some(viewport_id) = viewport_id {
repaint_asap = true;
glutin.resize(viewport_id, *physical_size);
}
}
}
winit::event::WindowEvent::CloseRequested => {
if viewport_id == Some(ViewportId::ROOT) && self.integration.should_close() {
log::debug!(
"Received WindowEvent::CloseRequested for main viewport - shutting down."
);
return EventResult::Exit;
}
log::debug!("Received WindowEvent::CloseRequested for viewport {viewport_id:?}");
if let Some(viewport_id) = viewport_id {
if let Some(viewport) = glutin.viewports.get_mut(&viewport_id) {
// Tell viewport it should close:
viewport.info.events.push(egui::ViewportEvent::Close);
// We may need to repaint both us and our parent to close the window,
// and perhaps twice (once to notice the close-event, once again to enforce it).
// `request_repaint_of` does a double-repaint though:
self.integration.egui_ctx.request_repaint_of(viewport_id);
self.integration
.egui_ctx
.request_repaint_of(viewport.ids.parent);
}
}
}
_ => {}
}
if self.integration.should_close() {
return EventResult::Exit;
}
let mut event_response = egui_winit::EventResponse {
consumed: false,
repaint: false,
};
if let Some(viewport_id) = viewport_id {
if let Some(viewport) = glutin.viewports.get_mut(&viewport_id) {
if let (Some(window), Some(egui_winit)) =
(&viewport.window, &mut viewport.egui_winit)
{
event_response = self.integration.on_window_event(window, egui_winit, event);
}
} else {
log::trace!("Ignoring event: no viewport for {viewport_id:?}");
}
} else {
log::trace!("Ignoring event: no viewport_id");
}
if event_response.repaint {
if repaint_asap {
EventResult::RepaintNow(window_id)
} else {
EventResult::RepaintNext(window_id)
}
} else {
EventResult::Wait
}
}
}
fn change_gl_context(
current_gl_context: &mut Option<glutin::context::PossiblyCurrentContext>,
gl_surface: &glutin::surface::Surface<glutin::surface::WindowSurface>,
) {
crate::profile_function!();
let not_current = {
crate::profile_scope!("make_not_current");
current_gl_context
.take()
.unwrap()
.make_not_current()
.unwrap()
};
crate::profile_scope!("make_current");
*current_gl_context = Some(not_current.make_current(gl_surface).unwrap());
}
impl GlutinWindowContext {
#[allow(unsafe_code)]
unsafe fn new(
egui_ctx: &egui::Context,
viewport_builder: ViewportBuilder,
native_options: &NativeOptions,
event_loop: &EventLoopWindowTarget<UserEvent>,
) -> Result<Self> {
crate::profile_function!();
// There is a lot of complexity with opengl creation,
// so prefer extensive logging to get all the help we can to debug issues.
use glutin::prelude::*;
// convert native options to glutin options
let hardware_acceleration = match native_options.hardware_acceleration {
crate::HardwareAcceleration::Required => Some(true),
crate::HardwareAcceleration::Preferred => None,
crate::HardwareAcceleration::Off => Some(false),
};
let swap_interval = if native_options.vsync {
glutin::surface::SwapInterval::Wait(std::num::NonZeroU32::new(1).unwrap())
} else {
glutin::surface::SwapInterval::DontWait
};
/* opengl setup flow goes like this:
1. we create a configuration for opengl "Display" / "Config" creation
2. choose between special extensions like glx or egl or wgl and use them to create config/display
3. opengl context configuration
4. opengl context creation
*/
// start building config for gl display
let config_template_builder = glutin::config::ConfigTemplateBuilder::new()
.prefer_hardware_accelerated(hardware_acceleration)
.with_depth_size(native_options.depth_buffer)
.with_stencil_size(native_options.stencil_buffer)
.with_transparency(native_options.viewport.transparent.unwrap_or(false));
// we don't know if multi sampling option is set. so, check if its more than 0.
let config_template_builder = if native_options.multisampling > 0 {
config_template_builder.with_multisampling(
native_options
.multisampling
.try_into()
.expect("failed to fit multisamples option of native_options into u8"),
)
} else {
config_template_builder
};
log::debug!("trying to create glutin Display with config: {config_template_builder:?}");
// Create GL display. This may probably create a window too on most platforms. Definitely on `MS windows`. Never on Android.
let display_builder = glutin_winit::DisplayBuilder::new()
// we might want to expose this option to users in the future. maybe using an env var or using native_options.
.with_preference(glutin_winit::ApiPreference::FallbackEgl) // https://github.com/emilk/egui/issues/2520#issuecomment-1367841150
.with_window_builder(Some(egui_winit::create_winit_window_builder(
egui_ctx,
event_loop,
viewport_builder.clone(),
)));
let (window, gl_config) = {
crate::profile_scope!("DisplayBuilder::build");
display_builder
.build(
event_loop,
config_template_builder.clone(),
|mut config_iterator| {
let config = config_iterator.next().expect(
"failed to find a matching configuration for creating glutin config",
);
log::debug!(
"using the first config from config picker closure. config: {config:?}"
);
config
},
)
.map_err(|e| crate::Error::NoGlutinConfigs(config_template_builder.build(), e))?
};
if let Some(window) = &window {
egui_winit::apply_viewport_builder_to_window(egui_ctx, window, &viewport_builder);
}
let gl_display = gl_config.display();
log::debug!(
"successfully created GL Display with version: {} and supported features: {:?}",
gl_display.version_string(),
gl_display.supported_features()
);
let glutin_raw_window_handle = window.as_ref().map(|w| {
use rwh_05::HasRawWindowHandle as _; // glutin stuck on old version of raw-window-handle
w.raw_window_handle()
});
log::debug!("creating gl context using raw window handle: {glutin_raw_window_handle:?}");
// create gl context. if core context cannot be created, try gl es context as fallback.
let context_attributes =
glutin::context::ContextAttributesBuilder::new().build(glutin_raw_window_handle);
let fallback_context_attributes = glutin::context::ContextAttributesBuilder::new()
.with_context_api(glutin::context::ContextApi::Gles(None))
.build(glutin_raw_window_handle);
let gl_context_result = unsafe {
crate::profile_scope!("create_context");
gl_config
.display()
.create_context(&gl_config, &context_attributes)
};
let gl_context = match gl_context_result {
Ok(it) => it,
Err(err) => {
log::warn!("Failed to create context using default context attributes {context_attributes:?} due to error: {err}");
log::debug!(
"Retrying with fallback context attributes: {fallback_context_attributes:?}"
);
unsafe {
gl_config
.display()
.create_context(&gl_config, &fallback_context_attributes)?
}
}
};
let not_current_gl_context = Some(gl_context);
let mut viewport_from_window = HashMap::default();
let mut window_from_viewport = ViewportIdMap::default();
let mut info = ViewportInfo::default();
if let Some(window) = &window {
viewport_from_window.insert(window.id(), ViewportId::ROOT);
window_from_viewport.insert(ViewportId::ROOT, window.id());
info.minimized = window.is_minimized();
info.maximized = Some(window.is_maximized());
}
let mut viewports = ViewportIdMap::default();
viewports.insert(
ViewportId::ROOT,
Viewport {
ids: ViewportIdPair::ROOT,
class: ViewportClass::Root,
builder: viewport_builder,
info,
screenshot_requested: false,
viewport_ui_cb: None,
gl_surface: None,
window: window.map(Arc::new),
egui_winit: None,
},
);
// the fun part with opengl gl is that we never know whether there is an error. the context creation might have failed, but
// it could keep working until we try to make surface current or swap buffers or something else. future glutin improvements might
// help us start from scratch again if we fail context creation and go back to preferEgl or try with different config etc..
// https://github.com/emilk/egui/pull/2541#issuecomment-1370767582
let mut slf = Self {
egui_ctx: egui_ctx.clone(),
swap_interval,
gl_config,
current_gl_context: None,
not_current_gl_context,
viewports,
viewport_from_window,
max_texture_side: None,
window_from_viewport,
focused_viewport: Some(ViewportId::ROOT),
};
slf.initialize_window(ViewportId::ROOT, event_loop)?;
Ok(slf)
}
/// Create a surface, window, and winit integration for all viewports lacking any of that.
///
/// Errors will be logged.
fn initialize_all_windows(&mut self, event_loop: &EventLoopWindowTarget<UserEvent>) {
crate::profile_function!();
let viewports: Vec<ViewportId> = self.viewports.keys().copied().collect();
for viewport_id in viewports {
if let Err(err) = self.initialize_window(viewport_id, event_loop) {
log::error!("Failed to initialize a window for viewport {viewport_id:?}: {err}");
}
}