dear-app 0.14.0

Convenient Dear ImGui application runner for dear-imgui-rs (Winit + WGPU, docking, themes, add-ons)
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
//! dear-app: minimal Dear ImGui app runner for dear-imgui-rs
//!
//! Goals
//! - Hide boilerplate (Winit + WGPU + platform + renderer)
//! - Provide a simple per-frame closure API similar to `immapp::Run`
//! - Optionally initialize add-ons (ImPlot, ImNodes) and expose them to the UI callback
//!
//! Quickstart
//! ```no_run
//! use dear_app::{run_simple};
//! use dear_imgui_rs::*;
//!
//! fn main() {
//!     run_simple(|ui| {
//!         ui.window("Hello")
//!             .size([300.0, 120.0], Condition::FirstUseEver)
//!             .build(|| ui.text("Hello from dear-app!"));
//!     }).unwrap();
//! }
//! ```
use dear_imgui_rs as imgui;
use dear_imgui_rs::{ConfigFlags, DockFlags, Id, TextureId, WindowFlags};
use dear_imgui_wgpu as imgui_wgpu;
use dear_imgui_winit as imgui_winit;
use pollster::block_on;
use std::marker::PhantomData;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::{Duration, Instant};
use thiserror::Error;
use tracing::{error, info};
use winit::application::ApplicationHandler;
use winit::dpi::LogicalSize;
use winit::event::WindowEvent;
use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
use winit::window::{Window, WindowId};

/// Re-exported for convenience when configuring `WgpuConfig`.
pub use wgpu;

#[cfg(feature = "imnodes")]
use dear_imnodes as imnodes;
#[cfg(feature = "implot")]
use dear_implot as implot;
#[cfg(feature = "implot3d")]
use dear_implot3d as implot3d;

#[derive(Debug, Error)]
#[non_exhaustive]
pub enum DearAppError {
    #[error("event loop error: {0}")]
    EventLoop(#[from] winit::error::EventLoopError),
    #[error("AppBuilder::run requires an on_frame callback")]
    MissingFrameCallback,
    #[error("window creation failed: {0}")]
    WindowCreation(#[source] winit::error::OsError),
    #[error("WGPU surface creation failed: {0}")]
    SurfaceCreation(#[source] wgpu::CreateSurfaceError),
    #[error("no suitable WGPU adapter found: {0}")]
    AdapterUnavailable(#[source] wgpu::RequestAdapterError),
    #[error("WGPU device request failed: {0}")]
    DeviceRequest(#[source] wgpu::RequestDeviceError),
    #[error("WGPU renderer initialization failed: {0}")]
    RendererInit(#[source] imgui_wgpu::RendererError),
    #[error("WGPU renderer frame preparation failed: {0}")]
    FramePrepare(#[source] imgui_wgpu::RendererError),
    #[error("WGPU renderer draw failed: {0}")]
    Render(#[source] imgui_wgpu::RendererError),
    #[error("WGPU surface lost")]
    SurfaceLost,
    #[error("WGPU surface outdated")]
    SurfaceOutdated,
    #[error("WGPU surface timeout")]
    SurfaceTimeout,
    #[error("WGPU surface validation failed while acquiring the next frame")]
    SurfaceValidation,
    #[error("Generic error: {0}")]
    Generic(String),
}

/// Add-ons to be initialized and provided to the UI callback
#[derive(Default, Clone, Copy)]
pub struct AddOnsConfig {
    pub with_implot: bool,
    pub with_imnodes: bool,
    pub with_implot3d: bool,
}

impl AddOnsConfig {
    /// Enable add-ons that are compiled into this crate via features.
    /// This does not fail if a given add-on is not enabled at compile time;
    /// missing ones are simply ignored during initialization.
    pub fn auto() -> Self {
        Self {
            with_implot: cfg!(feature = "implot"),
            with_imnodes: cfg!(feature = "imnodes"),
            with_implot3d: cfg!(feature = "implot3d"),
        }
    }
}

/// Mutable view to add-ons for per-frame rendering
pub struct AddOns<'a> {
    #[cfg(feature = "implot")]
    pub implot: Option<&'a implot::PlotContext>,
    #[cfg(not(feature = "implot"))]
    pub implot: Option<()>,

    #[cfg(feature = "imnodes")]
    pub imnodes: Option<&'a imnodes::Context>,
    #[cfg(not(feature = "imnodes"))]
    pub imnodes: Option<()>,

    #[cfg(feature = "implot3d")]
    pub implot3d: Option<&'a implot3d::Plot3DContext>,
    #[cfg(not(feature = "implot3d"))]
    pub implot3d: Option<()>,
    pub docking: DockingApi<'a>,
    pub gpu: GpuApi<'a>,
    _marker: PhantomData<&'a ()>,
}

/// Basic runner configuration
pub struct RunnerConfig {
    pub window_title: String,
    pub window_size: (f64, f64),
    pub present_mode: wgpu::PresentMode,
    pub clear_color: [f32; 4],
    /// WGPU instance/adapter/device configuration.
    pub wgpu: WgpuConfig,
    pub docking: DockingConfig,
    pub ini_filename: Option<PathBuf>,
    pub restore_previous_geometry: bool,
    pub redraw: RedrawMode,
    /// Optional override for `Io::config_flags` in addition to docking flag.
    /// If `Some`, it will be merged with docking flag; if `None`, only docking is applied.
    pub io_config_flags: Option<ConfigFlags>,
    /// Optional built-in theme to apply at startup (before on_style callback)
    pub theme: Option<Theme>,
}

impl Default for RunnerConfig {
    fn default() -> Self {
        Self {
            window_title: format!("Dear ImGui App - {}", env!("CARGO_PKG_VERSION")),
            window_size: (1280.0, 720.0),
            present_mode: wgpu::PresentMode::Fifo,
            clear_color: [0.1, 0.2, 0.3, 1.0],
            wgpu: WgpuConfig::default(),
            docking: DockingConfig::default(),
            ini_filename: None,
            restore_previous_geometry: true,
            redraw: RedrawMode::Poll,
            io_config_flags: None,
            theme: None,
        }
    }
}

/// WGPU configuration for adapter/device creation.
///
/// This is intentionally a small, stable subset of WGPU knobs that tend to matter for apps
/// (adapter selection and required features/limits).
pub struct WgpuConfig {
    /// Which backends to enable for the WGPU instance.
    pub backends: wgpu::Backends,
    /// Adapter power preference.
    pub power_preference: wgpu::PowerPreference,
    /// Whether to allow selecting a fallback (software) adapter.
    pub force_fallback_adapter: bool,
    /// Optional device debug label.
    pub device_label: Option<String>,
    /// Features required from the device.
    pub required_features: wgpu::Features,
    /// Limits required from the device.
    pub required_limits: wgpu::Limits,
    /// Memory allocation hints for the device.
    pub memory_hints: wgpu::MemoryHints,
}

/// Small set of curated WGPU presets for common application needs.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Default)]
pub enum WgpuPreset {
    /// Uses `WgpuConfig::default()`.
    #[default]
    Default,
    /// Prefer the fastest adapter (often discrete GPU).
    HighPerformance,
    /// Prefer the lowest power adapter (often integrated GPU).
    LowPower,
    /// Let WGPU decide (power preference is not considered).
    Balanced,
    /// Prefer broad compatibility by requesting downlevel-friendly limits.
    DownlevelCompatible,
    /// Force selecting a fallback (software) adapter if available.
    SoftwareFallback,
}

impl Default for WgpuConfig {
    fn default() -> Self {
        Self {
            backends: wgpu::Backends::PRIMARY,
            power_preference: wgpu::PowerPreference::HighPerformance,
            force_fallback_adapter: false,
            device_label: None,
            required_features: wgpu::Features::empty(),
            required_limits: wgpu::Limits::default(),
            memory_hints: wgpu::MemoryHints::default(),
        }
    }
}

impl WgpuConfig {
    /// Build a `WgpuConfig` from a curated preset.
    #[must_use]
    pub fn from_preset(preset: WgpuPreset) -> Self {
        match preset {
            WgpuPreset::Default => Self::default(),
            WgpuPreset::HighPerformance => Self {
                power_preference: wgpu::PowerPreference::HighPerformance,
                memory_hints: wgpu::MemoryHints::Performance,
                ..Self::default()
            },
            WgpuPreset::LowPower => Self {
                power_preference: wgpu::PowerPreference::LowPower,
                memory_hints: wgpu::MemoryHints::MemoryUsage,
                ..Self::default()
            },
            WgpuPreset::Balanced => Self {
                power_preference: wgpu::PowerPreference::None,
                ..Self::default()
            },
            WgpuPreset::DownlevelCompatible => Self {
                power_preference: wgpu::PowerPreference::None,
                required_limits: wgpu::Limits::downlevel_defaults(),
                ..Self::default()
            },
            WgpuPreset::SoftwareFallback => Self {
                power_preference: wgpu::PowerPreference::None,
                force_fallback_adapter: true,
                required_limits: wgpu::Limits::downlevel_defaults(),
                ..Self::default()
            },
        }
    }
}

/// Docking configuration
pub struct DockingConfig {
    /// Enable ImGui docking (sets `ConfigFlags::DOCKING_ENABLE`)
    pub enable: bool,
    /// Automatically create a fullscreen host window + dockspace over main viewport
    pub auto_dockspace: bool,
    /// Flags used for the created dockspace
    pub dockspace_flags: DockFlags,
    /// Host window flags (for the fullscreen dockspace host)
    pub host_window_flags: WindowFlags,
    /// Optional host window name (useful to persist ini settings)
    pub host_window_name: &'static str,
}

impl Default for DockingConfig {
    fn default() -> Self {
        Self {
            enable: true,
            auto_dockspace: true,
            dockspace_flags: DockFlags::PASSTHRU_CENTRAL_NODE,
            host_window_flags: WindowFlags::NO_TITLE_BAR
                | WindowFlags::NO_RESIZE
                | WindowFlags::NO_MOVE
                | WindowFlags::NO_COLLAPSE
                | WindowFlags::NO_BRING_TO_FRONT_ON_FOCUS
                | WindowFlags::NO_NAV_FOCUS,
            host_window_name: "DockSpaceHost",
        }
    }
}

/// Redraw behavior for the event loop
#[derive(Clone, Copy, Debug)]
pub enum RedrawMode {
    /// Always redraw (ControlFlow::Poll)
    Poll,
    /// On-demand redraw (ControlFlow::Wait)
    Wait,
    /// Redraw at most `fps` per second using WaitUntil
    WaitUntil { fps: f32 },
}

/// Simple built-in themes for convenience
#[derive(Clone, Copy, Debug)]
pub enum Theme {
    Dark,
    Light,
    Classic,
}

fn apply_theme(ctx: &mut imgui::Context, theme: Theme) {
    let preset = match theme {
        Theme::Dark => imgui::ThemePreset::Dark,
        Theme::Light => imgui::ThemePreset::Light,
        Theme::Classic => imgui::ThemePreset::Classic,
    };
    let mut t = imgui::Theme::default();
    t.preset = preset;
    t.apply_to_context(ctx);
}

/// Runner lifecycle callbacks (all optional)
pub struct RunnerCallbacks {
    pub on_setup: Option<Box<dyn FnMut(&mut imgui::Context)>>,
    pub on_style: Option<Box<dyn FnMut(&mut imgui::Context)>>,
    pub on_fonts: Option<Box<dyn FnMut(&mut imgui::Context)>>,
    pub on_post_init: Option<Box<dyn FnMut(&mut imgui::Context)>>,
    pub on_gpu_init: Option<
        Box<dyn FnMut(&Arc<Window>, &wgpu::Device, &wgpu::Queue, &wgpu::SurfaceConfiguration)>,
    >,
    pub on_event:
        Option<Box<dyn FnMut(&winit::event::Event<()>, &Arc<Window>, &mut imgui::Context)>>,
    pub on_exit: Option<Box<dyn FnMut(&mut imgui::Context)>>,
}

impl Default for RunnerCallbacks {
    fn default() -> Self {
        Self {
            on_setup: None,
            on_style: None,
            on_fonts: None,
            on_post_init: None,
            on_gpu_init: None,
            on_event: None,
            on_exit: None,
        }
    }
}

/// App builder for ergonomic configuration
pub struct AppBuilder {
    cfg: RunnerConfig,
    addons: AddOnsConfig,
    cbs: RunnerCallbacks,
    on_frame: Option<Box<dyn FnMut(&imgui::Ui, &mut AddOns) + 'static>>,
}

impl AppBuilder {
    pub fn new() -> Self {
        Self {
            cfg: RunnerConfig::default(),
            addons: AddOnsConfig::default(),
            cbs: RunnerCallbacks::default(),
            on_frame: None,
        }
    }
    pub fn with_config(mut self, cfg: RunnerConfig) -> Self {
        self.cfg = cfg;
        self
    }
    pub fn with_addons(mut self, addons: AddOnsConfig) -> Self {
        self.addons = addons;
        self
    }
    pub fn with_theme(mut self, theme: Theme) -> Self {
        self.cfg.theme = Some(theme);
        self
    }
    pub fn on_setup<F: FnMut(&mut imgui::Context) + 'static>(mut self, f: F) -> Self {
        self.cbs.on_setup = Some(Box::new(f));
        self
    }
    pub fn on_style<F: FnMut(&mut imgui::Context) + 'static>(mut self, f: F) -> Self {
        self.cbs.on_style = Some(Box::new(f));
        self
    }
    pub fn on_fonts<F: FnMut(&mut imgui::Context) + 'static>(mut self, f: F) -> Self {
        self.cbs.on_fonts = Some(Box::new(f));
        self
    }
    pub fn on_post_init<F: FnMut(&mut imgui::Context) + 'static>(mut self, f: F) -> Self {
        self.cbs.on_post_init = Some(Box::new(f));
        self
    }
    pub fn on_gpu_init<
        F: FnMut(&Arc<Window>, &wgpu::Device, &wgpu::Queue, &wgpu::SurfaceConfiguration) + 'static,
    >(
        mut self,
        f: F,
    ) -> Self {
        self.cbs.on_gpu_init = Some(Box::new(f));
        self
    }
    pub fn on_event<
        F: FnMut(&winit::event::Event<()>, &Arc<Window>, &mut imgui::Context) + 'static,
    >(
        mut self,
        f: F,
    ) -> Self {
        self.cbs.on_event = Some(Box::new(f));
        self
    }
    pub fn on_frame<F: FnMut(&imgui::Ui, &mut AddOns) + 'static>(mut self, f: F) -> Self {
        self.on_frame = Some(Box::new(f));
        self
    }
    pub fn on_exit<F: FnMut(&mut imgui::Context) + 'static>(mut self, f: F) -> Self {
        self.cbs.on_exit = Some(Box::new(f));
        self
    }
    pub fn run(mut self) -> Result<(), DearAppError> {
        let frame_fn = self
            .on_frame
            .take()
            .ok_or(DearAppError::MissingFrameCallback)?;
        run_with_callbacks(self.cfg, self.addons, self.cbs, frame_fn)
    }
}

/// Simple helper to run an app with a per-frame UI callback.
///
/// - Initializes Winit + WGPU + Dear ImGui
/// - Optionally initializes add-ons (ImPlot, ImNodes)
/// - Calls `gui` every frame with `Ui` and available add-ons
pub fn run_simple<F>(mut gui: F) -> Result<(), DearAppError>
where
    F: FnMut(&imgui::Ui) + 'static,
{
    run(
        RunnerConfig::default(),
        AddOnsConfig::default(),
        move |ui, _addons| gui(ui),
    )
}

/// Run an app with configuration and add-ons.
///
/// The `gui` callback is called every frame with access to ImGui `Ui` and the initialized add-ons.
pub fn run<F>(runner: RunnerConfig, addons_cfg: AddOnsConfig, gui: F) -> Result<(), DearAppError>
where
    F: FnMut(&imgui::Ui, &mut AddOns) + 'static,
{
    run_with_callbacks(runner, addons_cfg, RunnerCallbacks::default(), gui)
}

/// Run with explicit lifecycle callbacks (used by the builder-style API)
pub fn run_with_callbacks<F>(
    runner: RunnerConfig,
    addons_cfg: AddOnsConfig,
    cbs: RunnerCallbacks,
    gui: F,
) -> Result<(), DearAppError>
where
    F: FnMut(&imgui::Ui, &mut AddOns) + 'static,
{
    let event_loop = EventLoop::new()?;
    match runner.redraw {
        RedrawMode::Poll => event_loop.set_control_flow(ControlFlow::Poll),
        RedrawMode::Wait => event_loop.set_control_flow(ControlFlow::Wait),
        RedrawMode::WaitUntil { fps } => {
            let frame = Duration::from_secs_f32(1.0f32 / fps.max(1.0));
            event_loop.set_control_flow(ControlFlow::WaitUntil(Instant::now() + frame));
        }
    }

    let mut app = App::new(runner, addons_cfg, cbs, gui);
    info!("Starting Dear App event loop");
    event_loop.run_app(&mut app)?;
    Ok(())
}

struct ImguiState {
    context: imgui::Context,
    platform: imgui_winit::WinitPlatform,
    renderer: imgui_wgpu::WgpuRenderer,
}

// Runtime docking flags controller
pub struct DockingController {
    flags: DockFlags,
}

pub struct DockingApi<'a> {
    ctrl: &'a mut DockingController,
}

impl<'a> DockingApi<'a> {
    pub fn flags(&self) -> DockFlags {
        DockFlags::from_bits_retain(self.ctrl.flags.bits())
    }
    pub fn set_flags(&mut self, flags: DockFlags) {
        self.ctrl.flags = flags;
    }
}

// Minimal textures API to allow explicit texture updates from UI code
/// GPU access API for real-time scenarios (game view, image browser, atlas editor)
pub struct GpuApi<'a> {
    device: &'a wgpu::Device,
    queue: &'a wgpu::Queue,
    renderer: &'a mut imgui_wgpu::WgpuRenderer,
}

impl<'a> GpuApi<'a> {
    /// Access the WGPU device
    pub fn device(&self) -> &wgpu::Device {
        self.device
    }
    /// Access the default WGPU queue
    pub fn queue(&self) -> &wgpu::Queue {
        self.queue
    }
    /// Register an external texture + view and obtain an ImGui texture id.
    pub fn register_texture(
        &mut self,
        texture: &wgpu::Texture,
        view: &wgpu::TextureView,
    ) -> TextureId {
        self.renderer.register_external_texture(texture, view)
    }
    /// Update the view for an existing registered texture
    pub fn update_texture_view(&mut self, tex_id: TextureId, view: &wgpu::TextureView) -> bool {
        self.renderer.update_external_texture_view(tex_id, view)
    }
    /// Unregister a previously registered texture
    pub fn unregister_texture(&mut self, tex_id: TextureId) {
        self.renderer.unregister_texture(tex_id)
    }
    /// Optional: directly drive managed TextureData create/update without waiting for draw pass
    pub fn update_texture_data(
        &mut self,
        texture_data: &mut dear_imgui_rs::TextureData,
    ) -> Result<(), String> {
        let res = self
            .renderer
            .update_texture(texture_data)
            .map_err(|e| format!("update_texture failed: {e}"))?;
        // Important: apply result so TexID/Status are written back
        res.apply_to(texture_data);
        Ok(())
    }
}

struct AppWindow {
    // Kept alive to ensure the surface outlives its instance on all backends.
    #[allow(dead_code)]
    instance: wgpu::Instance,
    device: wgpu::Device,
    queue: wgpu::Queue,
    window: Arc<Window>,
    surface_desc: wgpu::SurfaceConfiguration,
    surface: wgpu::Surface<'static>,
    imgui: ImguiState,

    // add-ons
    #[cfg(feature = "implot")]
    implot_ctx: Option<implot::PlotContext>,
    #[cfg(feature = "imnodes")]
    imnodes_ctx: Option<imnodes::Context>,
    #[cfg(feature = "implot3d")]
    implot3d_ctx: Option<implot3d::Plot3DContext>,

    // config for rendering
    clear_color: wgpu::Color,
    docking_ctrl: DockingController,
}

impl AppWindow {
    fn new(
        event_loop: &ActiveEventLoop,
        cfg: &RunnerConfig,
        addons: &AddOnsConfig,
        cbs: &mut RunnerCallbacks,
    ) -> Result<Self, DearAppError> {
        let _ = addons;

        // WGPU instance and window
        let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
            backends: cfg.wgpu.backends,
            ..wgpu::InstanceDescriptor::new_without_display_handle()
        });

        let window = {
            let size = LogicalSize::new(cfg.window_size.0, cfg.window_size.1);
            Arc::new(
                event_loop
                    .create_window(
                        Window::default_attributes()
                            .with_title(cfg.window_title.clone())
                            .with_inner_size(size),
                    )
                    .map_err(DearAppError::WindowCreation)?,
            )
        };

        let surface = instance
            .create_surface(window.clone())
            .map_err(DearAppError::SurfaceCreation)?;

        let adapter = block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
            power_preference: cfg.wgpu.power_preference,
            compatible_surface: Some(&surface),
            force_fallback_adapter: cfg.wgpu.force_fallback_adapter,
        }))
        .map_err(DearAppError::AdapterUnavailable)?;

        let device_desc = wgpu::DeviceDescriptor {
            label: cfg.wgpu.device_label.as_deref(),
            required_features: cfg.wgpu.required_features,
            required_limits: cfg.wgpu.required_limits.clone(),
            memory_hints: cfg.wgpu.memory_hints.clone(),
            ..Default::default()
        };
        let (device, queue) =
            block_on(adapter.request_device(&device_desc)).map_err(DearAppError::DeviceRequest)?;

        // Surface config
        let physical_size = window.inner_size();
        let caps = surface.get_capabilities(&adapter);
        let preferred_srgb = [
            wgpu::TextureFormat::Bgra8UnormSrgb,
            wgpu::TextureFormat::Rgba8UnormSrgb,
        ];
        let format = preferred_srgb
            .iter()
            .cloned()
            .find(|f| caps.formats.contains(f))
            .unwrap_or(caps.formats[0]);

        let surface_desc = wgpu::SurfaceConfiguration {
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
            format,
            width: physical_size.width,
            height: physical_size.height,
            present_mode: cfg.present_mode,
            alpha_mode: wgpu::CompositeAlphaMode::Auto,
            view_formats: vec![],
            desired_maximum_frame_latency: 2,
        };

        surface.configure(&device, &surface_desc);

        if let Some(cb) = cbs.on_gpu_init.as_mut() {
            cb(&window, &device, &queue, &surface_desc);
        }

        // ImGui setup
        let mut context = imgui::Context::create();
        // ini setup before fonts
        if !cfg.restore_previous_geometry {
            let _ = context.set_ini_filename(None::<String>);
        } else if let Some(p) = &cfg.ini_filename {
            let _ = context.set_ini_filename(Some(p.clone()));
        } else {
            let _ = context.set_ini_filename(None::<String>);
        }

        // lifecycle: on_setup/style/fonts before renderer init
        if let Some(cb) = cbs.on_setup.as_mut() {
            cb(&mut context);
        }
        // Apply optional theme from config before user style tweak
        if let Some(theme) = cfg.theme {
            apply_theme(&mut context, theme);
        }
        if let Some(cb) = cbs.on_style.as_mut() {
            cb(&mut context);
        }
        if let Some(cb) = cbs.on_fonts.as_mut() {
            cb(&mut context);
        }

        let mut platform = imgui_winit::WinitPlatform::new(&mut context);
        platform.attach_window(&window, imgui_winit::HiDpiMode::Default, &mut context);

        let init_info =
            imgui_wgpu::WgpuInitInfo::new(device.clone(), queue.clone(), surface_desc.format);
        let mut renderer = imgui_wgpu::WgpuRenderer::new(init_info, &mut context)
            .map_err(DearAppError::RendererInit)?;
        renderer.set_gamma_mode(imgui_wgpu::GammaMode::Auto);

        // Configure IO flags & docking (never enable multi-viewport here)
        {
            let io = context.io_mut();
            let mut flags = io.config_flags();
            if cfg.docking.enable {
                flags.insert(ConfigFlags::DOCKING_ENABLE);
            }
            if let Some(extra) = &cfg.io_config_flags {
                let merged = flags.bits() | extra.bits();
                flags = ConfigFlags::from_bits_retain(merged);
            }
            io.set_config_flags(flags);
        }

        #[cfg(feature = "implot")]
        let implot_ctx = if addons.with_implot {
            Some(implot::PlotContext::create(&context))
        } else {
            None
        };

        #[cfg(feature = "imnodes")]
        let imnodes_ctx = if addons.with_imnodes {
            Some(imnodes::Context::create(&context))
        } else {
            None
        };

        #[cfg(feature = "implot3d")]
        let implot3d_ctx = if addons.with_implot3d {
            Some(implot3d::Plot3DContext::create(&context))
        } else {
            None
        };

        let imgui = ImguiState {
            context,
            platform,
            renderer,
        };

        Ok(Self {
            instance,
            device,
            queue,
            window,
            surface_desc,
            surface,
            imgui,
            #[cfg(feature = "implot")]
            implot_ctx,
            #[cfg(feature = "imnodes")]
            imnodes_ctx,
            #[cfg(feature = "implot3d")]
            implot3d_ctx,
            clear_color: wgpu::Color {
                r: cfg.clear_color[0] as f64,
                g: cfg.clear_color[1] as f64,
                b: cfg.clear_color[2] as f64,
                a: cfg.clear_color[3] as f64,
            },
            docking_ctrl: DockingController {
                flags: DockFlags::from_bits_retain(cfg.docking.dockspace_flags.bits()),
            },
        })
    }

    fn resize(&mut self, new_size: winit::dpi::PhysicalSize<u32>) {
        if new_size.width > 0 && new_size.height > 0 {
            self.surface_desc.width = new_size.width;
            self.surface_desc.height = new_size.height;
            self.surface.configure(&self.device, &self.surface_desc);
        }
    }

    fn render<F>(&mut self, gui: &mut F, docking: &DockingConfig) -> Result<(), DearAppError>
    where
        F: FnMut(&imgui::Ui, &mut AddOns),
    {
        self.imgui
            .platform
            .prepare_frame(&self.window, &mut self.imgui.context);
        let ui = self.imgui.context.frame();

        // Optional fullscreen dockspace
        if docking.enable && docking.auto_dockspace {
            let viewport = ui.main_viewport();
            // Host window always covering the main viewport
            ui.set_next_window_viewport(viewport.id());
            let pos = viewport.pos();
            let size = viewport.size();
            // NO_BACKGROUND if passthru central node
            let current_flags = DockFlags::from_bits_retain(self.docking_ctrl.flags.bits());
            let mut win_flags = docking.host_window_flags;
            if current_flags.contains(DockFlags::PASSTHRU_CENTRAL_NODE) {
                win_flags |= WindowFlags::NO_BACKGROUND;
            }
            ui.window(docking.host_window_name)
                .flags(win_flags)
                .position([pos[0], pos[1]], imgui::Condition::Always)
                .size([size[0], size[1]], imgui::Condition::Always)
                .build(|| {
                    let ds_flags = DockFlags::from_bits_retain(current_flags.bits());
                    let _ = ui.dockspace_over_main_viewport_with_flags(Id::from(0u32), ds_flags);
                });
        }

        // Build add-ons view
        let mut addons = AddOns {
            #[cfg(feature = "implot")]
            implot: self.implot_ctx.as_ref(),
            #[cfg(not(feature = "implot"))]
            implot: None,
            #[cfg(feature = "imnodes")]
            imnodes: self.imnodes_ctx.as_ref(),
            #[cfg(not(feature = "imnodes"))]
            imnodes: None,
            #[cfg(feature = "implot3d")]
            implot3d: self.implot3d_ctx.as_ref(),
            #[cfg(not(feature = "implot3d"))]
            implot3d: None,
            docking: DockingApi {
                ctrl: &mut self.docking_ctrl,
            },
            gpu: GpuApi {
                device: &self.device,
                queue: &self.queue,
                renderer: &mut self.imgui.renderer,
            },
            _marker: PhantomData,
        };

        // Call user GUI
        gui(&ui, &mut addons);

        // Keep OS cursor/IME state in sync with Dear ImGui's per-frame intent.
        self.imgui
            .platform
            .prepare_render_with_ui(&ui, &self.window);

        let draw_data = self.imgui.context.render();

        // Acquire the swapchain image as late as possible to reduce time holding it.
        let (frame, reconfigure_after_present) = match self.surface.get_current_texture() {
            wgpu::CurrentSurfaceTexture::Success(frame) => (frame, false),
            wgpu::CurrentSurfaceTexture::Suboptimal(frame) => (frame, true),
            wgpu::CurrentSurfaceTexture::Lost | wgpu::CurrentSurfaceTexture::Outdated => {
                self.surface.configure(&self.device, &self.surface_desc);
                return Ok(());
            }
            wgpu::CurrentSurfaceTexture::Timeout | wgpu::CurrentSurfaceTexture::Occluded => {
                return Ok(());
            }
            wgpu::CurrentSurfaceTexture::Validation => {
                return Err(DearAppError::SurfaceValidation);
            }
        };

        let view = frame
            .texture
            .create_view(&wgpu::TextureViewDescriptor::default());
        let mut encoder = self
            .device
            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
                label: Some("Render Encoder"),
            });

        {
            let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                label: Some("Render Pass"),
                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                    view: &view,
                    resolve_target: None,
                    ops: wgpu::Operations {
                        load: wgpu::LoadOp::Clear(self.clear_color),
                        store: wgpu::StoreOp::Store,
                    },
                    depth_slice: None,
                })],
                depth_stencil_attachment: None,
                timestamp_writes: None,
                occlusion_query_set: None,
                multiview_mask: None,
            });

            self.imgui
                .renderer
                .new_frame()
                .map_err(DearAppError::FramePrepare)?;
            self.imgui
                .renderer
                .render_draw_data(draw_data, &mut rpass)
                .map_err(DearAppError::Render)?;
        }

        self.queue.submit(Some(encoder.finish()));
        frame.present();
        if reconfigure_after_present {
            self.surface.configure(&self.device, &self.surface_desc);
        }
        Ok(())
    }
}

struct App<F>
where
    F: FnMut(&imgui::Ui, &mut AddOns) + 'static,
{
    cfg: RunnerConfig,
    addons_cfg: AddOnsConfig,
    window: Option<AppWindow>,
    gui: F,
    cbs: RunnerCallbacks,
    last_wake: Instant,
}

impl<F> App<F>
where
    F: FnMut(&imgui::Ui, &mut AddOns) + 'static,
{
    fn new(cfg: RunnerConfig, addons_cfg: AddOnsConfig, cbs: RunnerCallbacks, gui: F) -> Self {
        Self {
            cfg,
            addons_cfg,
            window: None,
            gui,
            cbs,
            last_wake: Instant::now(),
        }
    }
}

impl<F> ApplicationHandler for App<F>
where
    F: FnMut(&imgui::Ui, &mut AddOns) + 'static,
{
    fn resumed(&mut self, event_loop: &ActiveEventLoop) {
        if self.window.is_none() {
            match AppWindow::new(event_loop, &self.cfg, &self.addons_cfg, &mut self.cbs) {
                Ok(window) => {
                    self.window = Some(window);
                    info!("Window created successfully");
                    if let Some(cb) = self.cbs.on_post_init.as_mut() {
                        if let Some(w) = self.window.as_mut() {
                            cb(&mut w.imgui.context);
                        }
                    }
                    if let Some(w) = self.window.as_ref() {
                        w.window.request_redraw();
                    }
                }
                Err(e) => {
                    error!("Failed to create window: {e}");
                    event_loop.exit();
                }
            }
        }
    }

    fn window_event(
        &mut self,
        event_loop: &ActiveEventLoop,
        window_id: WindowId,
        event: WindowEvent,
    ) {
        // We may recreate the window/gpu stack on fatal GPU errors, so we avoid
        // holding a mutable borrow of self.window across the whole match.
        match event {
            WindowEvent::RedrawRequested => {
                // Render and, on fatal errors, attempt a full GPU/window rebuild.
                let mut need_recreate = false;
                if let Some(window) = self.window.as_mut() {
                    let full_event: winit::event::Event<()> = winit::event::Event::WindowEvent {
                        window_id,
                        event: event.clone(),
                    };
                    if let Some(cb) = self.cbs.on_event.as_mut() {
                        cb(&full_event, &window.window, &mut window.imgui.context);
                    }
                    window.imgui.platform.handle_event(
                        &mut window.imgui.context,
                        &window.window,
                        &full_event,
                    );

                    if let Err(e) = window.render(&mut self.gui, &self.cfg.docking) {
                        error!("Render error: {e}; attempting to recover by recreating GPU state");
                        need_recreate = true;
                    } else if matches!(self.cfg.redraw, RedrawMode::Poll) {
                        window.window.request_redraw();
                    }
                }

                if need_recreate {
                    // Drop the existing window and try to rebuild the whole stack.
                    let mut old_window = self.window.take();
                    match AppWindow::new(event_loop, &self.cfg, &self.addons_cfg, &mut self.cbs) {
                        Ok(window) => {
                            self.window = Some(window);
                            info!("Successfully recreated window and GPU state after error");
                            if let Some(window) = self.window.as_mut() {
                                if let Some(cb) = self.cbs.on_post_init.as_mut() {
                                    cb(&mut window.imgui.context);
                                }
                                window.window.request_redraw();
                            }
                        }
                        Err(e) => {
                            error!("Failed to recreate window after GPU error: {e}");
                            if let (Some(cb), Some(old)) =
                                (self.cbs.on_exit.as_mut(), old_window.as_mut())
                            {
                                cb(&mut old.imgui.context);
                            }
                            event_loop.exit();
                        }
                    }
                }
            }
            _ => {
                let window = match self.window.as_mut() {
                    Some(window) => window,
                    None => return,
                };

                let full_event: winit::event::Event<()> = winit::event::Event::WindowEvent {
                    window_id,
                    event: event.clone(),
                };
                if let Some(cb) = self.cbs.on_event.as_mut() {
                    cb(&full_event, &window.window, &mut window.imgui.context);
                }
                window.imgui.platform.handle_event(
                    &mut window.imgui.context,
                    &window.window,
                    &full_event,
                );

                match event {
                    WindowEvent::Resized(physical_size) => {
                        window.resize(physical_size);
                        window.window.request_redraw();
                    }
                    WindowEvent::ScaleFactorChanged { .. } => {
                        let new_size = window.window.inner_size();
                        window.resize(new_size);
                        window.window.request_redraw();
                    }
                    WindowEvent::CloseRequested => {
                        if let Some(cb) = self.cbs.on_exit.as_mut() {
                            if let Some(w) = self.window.as_mut() {
                                cb(&mut w.imgui.context);
                            }
                        }
                        event_loop.exit();
                    }
                    _ => {}
                }
            }
        }
    }

    fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
        match self.cfg.redraw {
            RedrawMode::Poll => {
                event_loop.set_control_flow(ControlFlow::Poll);
                if let Some(window) = &self.window {
                    window.window.request_redraw();
                }
            }
            RedrawMode::Wait => {
                event_loop.set_control_flow(ControlFlow::Wait);
            }
            RedrawMode::WaitUntil { fps } => {
                let frame = Duration::from_secs_f32(1.0f32 / fps.max(1.0));
                let now = Instant::now();
                let mut next_wake = self.last_wake + frame;
                if now >= next_wake {
                    self.last_wake = now;
                    next_wake = self.last_wake + frame;
                    if let Some(window) = &self.window {
                        window.window.request_redraw();
                    }
                }
                event_loop.set_control_flow(ControlFlow::WaitUntil(next_wake));
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{AppBuilder, DearAppError};

    #[test]
    fn app_builder_run_requires_frame_callback_without_starting_event_loop() {
        let err = AppBuilder::new()
            .run()
            .expect_err("builder without on_frame should fail before event loop startup");

        assert!(matches!(err, DearAppError::MissingFrameCallback));
        assert_eq!(
            err.to_string(),
            "AppBuilder::run requires an on_frame callback"
        );
    }
}