dear-implot 0.12.0

High-level Rust bindings to ImPlot with dear-imgui-rs integration
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
use crate::{AxisFlags, PlotCond, XAxis, YAxis, sys};
use dear_imgui_rs::{
    Context as ImGuiContext, Ui, with_scratch_txt, with_scratch_txt_slice, with_scratch_txt_two,
};
use dear_imgui_sys as imgui_sys;
use std::os::raw::c_char;
use std::{cell::RefCell, rc::Rc};

/// ImPlot context that manages the plotting state
///
/// This context is separate from the Dear ImGui context but works alongside it.
/// You need both contexts to create plots.
pub struct PlotContext {
    raw: *mut sys::ImPlotContext,
    imgui_ctx_raw: *mut imgui_sys::ImGuiContext,
    imgui_alive: Option<dear_imgui_rs::ContextAliveToken>,
}

impl PlotContext {
    /// Try to create a new ImPlot context
    ///
    /// This should be called after creating the Dear ImGui context.
    /// The ImPlot context will use the same Dear ImGui context internally.
    pub fn try_create(imgui_ctx: &ImGuiContext) -> dear_imgui_rs::ImGuiResult<Self> {
        let imgui_ctx_raw = imgui_ctx.as_raw();
        let imgui_alive = Some(imgui_ctx.alive_token());
        assert_eq!(
            unsafe { imgui_sys::igGetCurrentContext() },
            imgui_ctx_raw,
            "dear-implot: PlotContext must be created with the currently-active ImGui context"
        );

        // Bind ImPlot to the ImGui context before creating.
        // On some toolchains/platforms, not setting this can lead to crashes
        // if ImPlot initialization queries ImGui state during CreateContext.
        unsafe { sys::ImPlot_SetImGuiContext(imgui_ctx_raw) };

        let raw = unsafe { sys::ImPlot_CreateContext() };
        if raw.is_null() {
            return Err(dear_imgui_rs::ImGuiError::context_creation(
                "ImPlot_CreateContext returned null",
            ));
        }

        // Ensure the newly created context is current (defensive, CreateContext should do this).
        unsafe { sys::ImPlot_SetCurrentContext(raw) };

        Ok(Self {
            raw,
            imgui_ctx_raw,
            imgui_alive,
        })
    }

    /// Create a new ImPlot context (panics on error)
    pub fn create(imgui_ctx: &ImGuiContext) -> Self {
        Self::try_create(imgui_ctx).expect("Failed to create ImPlot context")
    }

    /// Get the current ImPlot context
    ///
    /// Returns None if no context is current
    pub fn current() -> Option<Self> {
        let raw = unsafe { sys::ImPlot_GetCurrentContext() };
        if raw.is_null() {
            None
        } else {
            Some(Self {
                raw,
                imgui_ctx_raw: unsafe { imgui_sys::igGetCurrentContext() },
                imgui_alive: None,
            })
        }
    }

    /// Set this context as the current ImPlot context
    pub fn set_as_current(&self) {
        if let Some(alive) = &self.imgui_alive {
            assert!(
                alive.is_alive(),
                "dear-implot: ImGui context has been dropped"
            );
            unsafe { sys::ImPlot_SetImGuiContext(self.imgui_ctx_raw) };
        }
        unsafe {
            sys::ImPlot_SetCurrentContext(self.raw);
        }
    }

    /// Get a PlotUi for creating plots
    ///
    /// This borrows both the ImPlot context and the Dear ImGui Ui,
    /// ensuring that plots can only be created when both are available.
    pub fn get_plot_ui<'ui>(&'ui self, ui: &'ui Ui) -> PlotUi<'ui> {
        if let Some(alive) = &self.imgui_alive {
            assert!(
                alive.is_alive(),
                "dear-implot: ImGui context has been dropped"
            );
            assert_eq!(
                unsafe { imgui_sys::igGetCurrentContext() },
                self.imgui_ctx_raw,
                "dear-implot: PlotUi must be used with the currently-active ImGui context"
            );
        }
        self.set_as_current();
        PlotUi { context: self, ui }
    }

    /// Get the raw ImPlot context pointer
    ///
    /// # Safety
    ///
    /// The caller must ensure the pointer is used safely and not stored
    /// beyond the lifetime of this context.
    pub unsafe fn raw(&self) -> *mut sys::ImPlotContext {
        self.raw
    }
}

impl Drop for PlotContext {
    fn drop(&mut self) {
        if !self.raw.is_null() {
            if let Some(alive) = &self.imgui_alive {
                if !alive.is_alive() {
                    // Avoid calling into ImGui allocators after the context has been dropped.
                    // Best-effort: leak the ImPlot context instead of risking UB.
                    return;
                }
                unsafe { sys::ImPlot_SetImGuiContext(self.imgui_ctx_raw) };
            }
            unsafe {
                if sys::ImPlot_GetCurrentContext() == self.raw {
                    sys::ImPlot_SetCurrentContext(std::ptr::null_mut());
                }
                sys::ImPlot_DestroyContext(self.raw);
            }
        }
    }
}

// ImPlot context is tied to Dear ImGui and not thread-safe to send/share.

/// A temporary reference for building plots
///
/// This struct ensures that plots can only be created when both ImGui and ImPlot
/// contexts are available and properly set up.
pub struct PlotUi<'ui> {
    #[allow(dead_code)]
    context: &'ui PlotContext,
    #[allow(dead_code)]
    ui: &'ui Ui,
}

impl<'ui> PlotUi<'ui> {
    /// Begin a new plot with the given title
    ///
    /// Returns a PlotToken if the plot was successfully started.
    /// The plot will be automatically ended when the token is dropped.
    pub fn begin_plot(&self, title: &str) -> Option<PlotToken<'_>> {
        let size = sys::ImVec2_c { x: -1.0, y: 0.0 };
        if title.contains('\0') {
            return None;
        }
        let started = with_scratch_txt(title, |ptr| unsafe { sys::ImPlot_BeginPlot(ptr, size, 0) });

        if started {
            Some(PlotToken::new())
        } else {
            None
        }
    }

    /// Begin a plot with custom size
    pub fn begin_plot_with_size(&self, title: &str, size: [f32; 2]) -> Option<PlotToken<'_>> {
        let plot_size = sys::ImVec2_c {
            x: size[0],
            y: size[1],
        };
        if title.contains('\0') {
            return None;
        }
        let started = with_scratch_txt(title, |ptr| unsafe {
            sys::ImPlot_BeginPlot(ptr, plot_size, 0)
        });

        if started {
            Some(PlotToken::new())
        } else {
            None
        }
    }

    /// Plot a line with the given label and data
    ///
    /// This is a convenience method that can be called within a plot.
    pub fn plot_line(&self, label: &str, x_data: &[f64], y_data: &[f64]) {
        if x_data.len() != y_data.len() {
            return; // Data length mismatch
        }
        let count = match i32::try_from(x_data.len()) {
            Ok(v) => v,
            Err(_) => return,
        };

        let label = if label.contains('\0') { "" } else { label };
        with_scratch_txt(label, |ptr| unsafe {
            let spec = crate::plots::plot_spec_from(0, 0, std::mem::size_of::<f64>() as i32);
            sys::ImPlot_PlotLine_doublePtrdoublePtr(
                ptr,
                x_data.as_ptr(),
                y_data.as_ptr(),
                count,
                spec,
            );
        })
    }

    /// Plot a scatter plot with the given label and data
    pub fn plot_scatter(&self, label: &str, x_data: &[f64], y_data: &[f64]) {
        if x_data.len() != y_data.len() {
            return; // Data length mismatch
        }
        let count = match i32::try_from(x_data.len()) {
            Ok(v) => v,
            Err(_) => return,
        };

        let label = if label.contains('\0') { "" } else { label };
        with_scratch_txt(label, |ptr| unsafe {
            let spec = crate::plots::plot_spec_from(0, 0, std::mem::size_of::<f64>() as i32);
            sys::ImPlot_PlotScatter_doublePtrdoublePtr(
                ptr,
                x_data.as_ptr(),
                y_data.as_ptr(),
                count,
                spec,
            );
        })
    }

    /// Plot a polygon with the given label and vertex data.
    pub fn plot_polygon(&self, label: &str, x_data: &[f64], y_data: &[f64]) {
        if x_data.len() != y_data.len() {
            return;
        }
        let count = match i32::try_from(x_data.len()) {
            Ok(v) => v,
            Err(_) => return,
        };

        let label = if label.contains('\0') { "" } else { label };
        with_scratch_txt(label, |ptr| unsafe {
            let spec = crate::plots::plot_spec_from(0, 0, std::mem::size_of::<f64>() as i32);
            sys::ImPlot_PlotPolygon_doublePtr(ptr, x_data.as_ptr(), y_data.as_ptr(), count, spec);
        })
    }

    /// Check if the plot area is hovered
    pub fn is_plot_hovered(&self) -> bool {
        unsafe { sys::ImPlot_IsPlotHovered() }
    }

    /// Get the mouse position in plot coordinates
    pub fn get_plot_mouse_pos(&self, y_axis: Option<crate::YAxisChoice>) -> sys::ImPlotPoint {
        let y_axis_i32 = crate::y_axis_choice_option_to_i32(y_axis);
        let y_axis = match y_axis_i32 {
            0 => 3,
            1 => 4,
            2 => 5,
            _ => 3,
        };
        unsafe { sys::ImPlot_GetPlotMousePos(0, y_axis) }
    }

    /// Get the mouse position in plot coordinates for specific axes
    pub fn get_plot_mouse_pos_axes(&self, x_axis: XAxis, y_axis: YAxis) -> sys::ImPlotPoint {
        unsafe { sys::ImPlot_GetPlotMousePos(x_axis as i32, y_axis as i32) }
    }

    /// Set current axes for subsequent plot submissions
    pub fn set_axes(&self, x_axis: XAxis, y_axis: YAxis) {
        unsafe { sys::ImPlot_SetAxes(x_axis as i32, y_axis as i32) }
    }

    /// Setup a specific X axis
    pub fn setup_x_axis(&self, axis: XAxis, label: Option<&str>, flags: AxisFlags) {
        let label = label.filter(|s| !s.contains('\0'));
        match label {
            Some(label) => with_scratch_txt(label, |ptr| unsafe {
                sys::ImPlot_SetupAxis(
                    axis as sys::ImAxis,
                    ptr,
                    flags.bits() as sys::ImPlotAxisFlags,
                )
            }),
            None => unsafe {
                sys::ImPlot_SetupAxis(
                    axis as sys::ImAxis,
                    std::ptr::null(),
                    flags.bits() as sys::ImPlotAxisFlags,
                )
            },
        }
    }

    /// Setup a specific Y axis
    pub fn setup_y_axis(&self, axis: YAxis, label: Option<&str>, flags: AxisFlags) {
        let label = label.filter(|s| !s.contains('\0'));
        match label {
            Some(label) => with_scratch_txt(label, |ptr| unsafe {
                sys::ImPlot_SetupAxis(
                    axis as sys::ImAxis,
                    ptr,
                    flags.bits() as sys::ImPlotAxisFlags,
                )
            }),
            None => unsafe {
                sys::ImPlot_SetupAxis(
                    axis as sys::ImAxis,
                    std::ptr::null(),
                    flags.bits() as sys::ImPlotAxisFlags,
                )
            },
        }
    }

    /// Setup axis limits for a specific X axis
    pub fn setup_x_axis_limits(&self, axis: XAxis, min: f64, max: f64, cond: PlotCond) {
        unsafe {
            sys::ImPlot_SetupAxisLimits(axis as sys::ImAxis, min, max, cond as sys::ImPlotCond)
        }
    }

    /// Setup axis limits for a specific Y axis
    pub fn setup_y_axis_limits(&self, axis: YAxis, min: f64, max: f64, cond: PlotCond) {
        unsafe {
            sys::ImPlot_SetupAxisLimits(axis as sys::ImAxis, min, max, cond as sys::ImPlotCond)
        }
    }

    /// Link an axis to external min/max values (live binding)
    pub fn setup_axis_links(
        &self,
        axis: i32,
        link_min: Option<&mut f64>,
        link_max: Option<&mut f64>,
    ) {
        let pmin = link_min.map_or(std::ptr::null_mut(), |r| r as *mut f64);
        let pmax = link_max.map_or(std::ptr::null_mut(), |r| r as *mut f64);
        unsafe { sys::ImPlot_SetupAxisLinks(axis, pmin, pmax) }
    }

    /// Setup both axes labels/flags at once
    pub fn setup_axes(
        &self,
        x_label: Option<&str>,
        y_label: Option<&str>,
        x_flags: AxisFlags,
        y_flags: AxisFlags,
    ) {
        let x_label = x_label.filter(|s| !s.contains('\0'));
        let y_label = y_label.filter(|s| !s.contains('\0'));

        match (x_label, y_label) {
            (Some(x_label), Some(y_label)) => {
                with_scratch_txt_two(x_label, y_label, |xp, yp| unsafe {
                    sys::ImPlot_SetupAxes(
                        xp,
                        yp,
                        x_flags.bits() as sys::ImPlotAxisFlags,
                        y_flags.bits() as sys::ImPlotAxisFlags,
                    )
                })
            }
            (Some(x_label), None) => with_scratch_txt(x_label, |xp| unsafe {
                sys::ImPlot_SetupAxes(
                    xp,
                    std::ptr::null(),
                    x_flags.bits() as sys::ImPlotAxisFlags,
                    y_flags.bits() as sys::ImPlotAxisFlags,
                )
            }),
            (None, Some(y_label)) => with_scratch_txt(y_label, |yp| unsafe {
                sys::ImPlot_SetupAxes(
                    std::ptr::null(),
                    yp,
                    x_flags.bits() as sys::ImPlotAxisFlags,
                    y_flags.bits() as sys::ImPlotAxisFlags,
                )
            }),
            (None, None) => unsafe {
                sys::ImPlot_SetupAxes(
                    std::ptr::null(),
                    std::ptr::null(),
                    x_flags.bits() as sys::ImPlotAxisFlags,
                    y_flags.bits() as sys::ImPlotAxisFlags,
                )
            },
        }
    }

    /// Setup axes limits (both) at once
    pub fn setup_axes_limits(
        &self,
        x_min: f64,
        x_max: f64,
        y_min: f64,
        y_max: f64,
        cond: PlotCond,
    ) {
        unsafe { sys::ImPlot_SetupAxesLimits(x_min, x_max, y_min, y_max, cond as sys::ImPlotCond) }
    }

    /// Call after axis setup to finalize configuration
    pub fn setup_finish(&self) {
        unsafe { sys::ImPlot_SetupFinish() }
    }

    /// Set next frame limits for a specific axis
    pub fn set_next_x_axis_limits(&self, axis: XAxis, min: f64, max: f64, cond: PlotCond) {
        unsafe {
            sys::ImPlot_SetNextAxisLimits(axis as sys::ImAxis, min, max, cond as sys::ImPlotCond)
        }
    }

    /// Set next frame limits for a specific axis
    pub fn set_next_y_axis_limits(&self, axis: YAxis, min: f64, max: f64, cond: PlotCond) {
        unsafe {
            sys::ImPlot_SetNextAxisLimits(axis as sys::ImAxis, min, max, cond as sys::ImPlotCond)
        }
    }

    /// Link an axis to external min/max for next frame
    pub fn set_next_axis_links(
        &self,
        axis: i32,
        link_min: Option<&mut f64>,
        link_max: Option<&mut f64>,
    ) {
        let pmin = link_min.map_or(std::ptr::null_mut(), |r| r as *mut f64);
        let pmax = link_max.map_or(std::ptr::null_mut(), |r| r as *mut f64);
        unsafe { sys::ImPlot_SetNextAxisLinks(axis, pmin, pmax) }
    }

    /// Set next frame limits for both axes
    pub fn set_next_axes_limits(
        &self,
        x_min: f64,
        x_max: f64,
        y_min: f64,
        y_max: f64,
        cond: PlotCond,
    ) {
        unsafe {
            sys::ImPlot_SetNextAxesLimits(x_min, x_max, y_min, y_max, cond as sys::ImPlotCond)
        }
    }

    /// Fit next frame both axes
    pub fn set_next_axes_to_fit(&self) {
        unsafe { sys::ImPlot_SetNextAxesToFit() }
    }

    /// Fit next frame a specific axis (raw)
    pub fn set_next_axis_to_fit(&self, axis: i32) {
        unsafe { sys::ImPlot_SetNextAxisToFit(axis as sys::ImAxis) }
    }

    /// Fit next frame a specific X axis
    pub fn set_next_x_axis_to_fit(&self, axis: XAxis) {
        unsafe { sys::ImPlot_SetNextAxisToFit(axis as sys::ImAxis) }
    }

    /// Fit next frame a specific Y axis
    pub fn set_next_y_axis_to_fit(&self, axis: YAxis) {
        unsafe { sys::ImPlot_SetNextAxisToFit(axis as sys::ImAxis) }
    }

    /// Setup ticks with explicit positions and optional labels for an X axis.
    ///
    /// If `labels` is provided, it must have the same length as `values`.
    pub fn setup_x_axis_ticks_positions(
        &self,
        axis: XAxis,
        values: &[f64],
        labels: Option<&[&str]>,
        keep_default: bool,
    ) {
        let count = match i32::try_from(values.len()) {
            Ok(v) => v,
            Err(_) => return,
        };
        if let Some(labels) = labels {
            if labels.len() != values.len() {
                return;
            }
            let cleaned: Vec<&str> = labels
                .iter()
                .map(|&s| if s.contains('\0') { "" } else { s })
                .collect();
            with_scratch_txt_slice(&cleaned, |ptrs| unsafe {
                sys::ImPlot_SetupAxisTicks_doublePtr(
                    axis as sys::ImAxis,
                    values.as_ptr(),
                    count,
                    ptrs.as_ptr() as *const *const c_char,
                    keep_default,
                )
            })
        } else {
            unsafe {
                sys::ImPlot_SetupAxisTicks_doublePtr(
                    axis as sys::ImAxis,
                    values.as_ptr(),
                    count,
                    std::ptr::null(),
                    keep_default,
                )
            }
        }
    }

    /// Setup ticks with explicit positions and optional labels for a Y axis.
    ///
    /// If `labels` is provided, it must have the same length as `values`.
    pub fn setup_y_axis_ticks_positions(
        &self,
        axis: YAxis,
        values: &[f64],
        labels: Option<&[&str]>,
        keep_default: bool,
    ) {
        let count = match i32::try_from(values.len()) {
            Ok(v) => v,
            Err(_) => return,
        };
        if let Some(labels) = labels {
            if labels.len() != values.len() {
                return;
            }
            let cleaned: Vec<&str> = labels
                .iter()
                .map(|&s| if s.contains('\0') { "" } else { s })
                .collect();
            with_scratch_txt_slice(&cleaned, |ptrs| unsafe {
                sys::ImPlot_SetupAxisTicks_doublePtr(
                    axis as sys::ImAxis,
                    values.as_ptr(),
                    count,
                    ptrs.as_ptr() as *const *const c_char,
                    keep_default,
                )
            })
        } else {
            unsafe {
                sys::ImPlot_SetupAxisTicks_doublePtr(
                    axis as sys::ImAxis,
                    values.as_ptr(),
                    count,
                    std::ptr::null(),
                    keep_default,
                )
            }
        }
    }

    /// Setup ticks on a range with tick count and optional labels for an X axis.
    ///
    /// If `labels` is provided, it must have length `n_ticks`.
    pub fn setup_x_axis_ticks_range(
        &self,
        axis: XAxis,
        v_min: f64,
        v_max: f64,
        n_ticks: i32,
        labels: Option<&[&str]>,
        keep_default: bool,
    ) {
        if n_ticks <= 0 {
            return;
        }
        if let Some(labels) = labels {
            let Ok(ticks_usize) = usize::try_from(n_ticks) else {
                return;
            };
            if labels.len() != ticks_usize {
                return;
            }
            let cleaned: Vec<&str> = labels
                .iter()
                .map(|&s| if s.contains('\0') { "" } else { s })
                .collect();
            with_scratch_txt_slice(&cleaned, |ptrs| unsafe {
                sys::ImPlot_SetupAxisTicks_double(
                    axis as sys::ImAxis,
                    v_min,
                    v_max,
                    n_ticks,
                    ptrs.as_ptr() as *const *const c_char,
                    keep_default,
                )
            })
        } else {
            unsafe {
                sys::ImPlot_SetupAxisTicks_double(
                    axis as sys::ImAxis,
                    v_min,
                    v_max,
                    n_ticks,
                    std::ptr::null(),
                    keep_default,
                )
            }
        }
    }

    /// Setup ticks on a range with tick count and optional labels for a Y axis.
    ///
    /// If `labels` is provided, it must have length `n_ticks`.
    pub fn setup_y_axis_ticks_range(
        &self,
        axis: YAxis,
        v_min: f64,
        v_max: f64,
        n_ticks: i32,
        labels: Option<&[&str]>,
        keep_default: bool,
    ) {
        if n_ticks <= 0 {
            return;
        }
        if let Some(labels) = labels {
            let Ok(ticks_usize) = usize::try_from(n_ticks) else {
                return;
            };
            if labels.len() != ticks_usize {
                return;
            }
            let cleaned: Vec<&str> = labels
                .iter()
                .map(|&s| if s.contains('\0') { "" } else { s })
                .collect();
            with_scratch_txt_slice(&cleaned, |ptrs| unsafe {
                sys::ImPlot_SetupAxisTicks_double(
                    axis as sys::ImAxis,
                    v_min,
                    v_max,
                    n_ticks,
                    ptrs.as_ptr() as *const *const c_char,
                    keep_default,
                )
            })
        } else {
            unsafe {
                sys::ImPlot_SetupAxisTicks_double(
                    axis as sys::ImAxis,
                    v_min,
                    v_max,
                    n_ticks,
                    std::ptr::null(),
                    keep_default,
                )
            }
        }
    }

    /// Setup tick label format string for a specific X axis
    pub fn setup_x_axis_format(&self, axis: XAxis, fmt: &str) {
        if fmt.contains('\0') {
            return;
        }
        with_scratch_txt(fmt, |ptr| unsafe {
            sys::ImPlot_SetupAxisFormat_Str(axis as sys::ImAxis, ptr)
        })
    }

    /// Setup tick label format string for a specific Y axis
    pub fn setup_y_axis_format(&self, axis: YAxis, fmt: &str) {
        if fmt.contains('\0') {
            return;
        }
        with_scratch_txt(fmt, |ptr| unsafe {
            sys::ImPlot_SetupAxisFormat_Str(axis as sys::ImAxis, ptr)
        })
    }

    /// Setup scale for a specific X axis (pass sys::ImPlotScale variant)
    pub fn setup_x_axis_scale(&self, axis: XAxis, scale: sys::ImPlotScale) {
        unsafe { sys::ImPlot_SetupAxisScale_PlotScale(axis as sys::ImAxis, scale) }
    }

    /// Setup scale for a specific Y axis (pass sys::ImPlotScale variant)
    pub fn setup_y_axis_scale(&self, axis: YAxis, scale: sys::ImPlotScale) {
        unsafe { sys::ImPlot_SetupAxisScale_PlotScale(axis as sys::ImAxis, scale) }
    }

    /// Setup axis limits constraints
    pub fn setup_axis_limits_constraints(&self, axis: i32, v_min: f64, v_max: f64) {
        unsafe { sys::ImPlot_SetupAxisLimitsConstraints(axis as sys::ImAxis, v_min, v_max) }
    }

    /// Setup axis zoom constraints
    pub fn setup_axis_zoom_constraints(&self, axis: i32, z_min: f64, z_max: f64) {
        unsafe { sys::ImPlot_SetupAxisZoomConstraints(axis as sys::ImAxis, z_min, z_max) }
    }

    // -------- Formatter (closure) --------
    /// Setup tick label formatter using a Rust closure.
    ///
    /// The closure is kept alive until the current plot ends.
    pub fn setup_x_axis_format_closure<F>(&self, axis: XAxis, f: F) -> AxisFormatterToken
    where
        F: Fn(f64) -> String + Send + Sync + 'static,
    {
        AxisFormatterToken::new(axis as sys::ImAxis, f)
    }

    /// Setup tick label formatter using a Rust closure.
    ///
    /// The closure is kept alive until the current plot ends.
    pub fn setup_y_axis_format_closure<F>(&self, axis: YAxis, f: F) -> AxisFormatterToken
    where
        F: Fn(f64) -> String + Send + Sync + 'static,
    {
        AxisFormatterToken::new(axis as sys::ImAxis, f)
    }

    // -------- Transform (closure) --------
    /// Setup custom axis transform using Rust closures (forward/inverse).
    ///
    /// The closures are kept alive until the current plot ends.
    pub fn setup_x_axis_transform_closure<FW, INV>(
        &self,
        axis: XAxis,
        forward: FW,
        inverse: INV,
    ) -> AxisTransformToken
    where
        FW: Fn(f64) -> f64 + Send + Sync + 'static,
        INV: Fn(f64) -> f64 + Send + Sync + 'static,
    {
        AxisTransformToken::new(axis as sys::ImAxis, forward, inverse)
    }

    /// Setup custom axis transform for Y axis using closures
    pub fn setup_y_axis_transform_closure<FW, INV>(
        &self,
        axis: YAxis,
        forward: FW,
        inverse: INV,
    ) -> AxisTransformToken
    where
        FW: Fn(f64) -> f64 + Send + Sync + 'static,
        INV: Fn(f64) -> f64 + Send + Sync + 'static,
    {
        AxisTransformToken::new(axis as sys::ImAxis, forward, inverse)
    }
}

// Plot-scope callback storage -------------------------------------------------
//
// ImPlot's axis formatter/transform APIs take function pointers + `user_data`
// pointers, and may call them at any point until the current plot ends.
//
// Returning a standalone token that owns the closure is unsound: safe Rust code
// could drop the token early, leaving ImPlot with a dangling `user_data` pointer.
//
// To keep the safe API sound without forcing users to manually retain tokens,
// we store callback holders in thread-local, plot-scoped storage that is
// created when a plot begins and destroyed when the plot ends.

#[derive(Default)]
struct PlotScopeStorage {
    formatters: Vec<Box<FormatterHolder>>,
    transforms: Vec<Box<TransformHolder>>,
}

thread_local! {
    static PLOT_SCOPE_STACK: RefCell<Vec<PlotScopeStorage>> = const { RefCell::new(Vec::new()) };
}

fn with_plot_scope_storage<T>(f: impl FnOnce(&mut PlotScopeStorage) -> T) -> Option<T> {
    PLOT_SCOPE_STACK.with(|stack| {
        let mut stack = stack.borrow_mut();
        stack.last_mut().map(f)
    })
}

pub(crate) struct PlotScopeGuard {
    _not_send_or_sync: std::marker::PhantomData<Rc<()>>,
}

impl PlotScopeGuard {
    pub(crate) fn new() -> Self {
        PLOT_SCOPE_STACK.with(|stack| stack.borrow_mut().push(PlotScopeStorage::default()));
        Self {
            _not_send_or_sync: std::marker::PhantomData,
        }
    }
}

impl Drop for PlotScopeGuard {
    fn drop(&mut self) {
        PLOT_SCOPE_STACK.with(|stack| {
            let popped = stack.borrow_mut().pop();
            debug_assert!(popped.is_some(), "dear-implot: plot scope stack underflow");
        });
    }
}

// =================== Formatter bridge ===================

struct FormatterHolder {
    func: Box<dyn Fn(f64) -> String + Send + Sync + 'static>,
}

#[must_use]
pub struct AxisFormatterToken {
    _private: (),
}

impl AxisFormatterToken {
    fn new<F>(axis: sys::ImAxis, f: F) -> Self
    where
        F: Fn(f64) -> String + Send + Sync + 'static,
    {
        let configured = with_plot_scope_storage(|storage| {
            let holder = Box::new(FormatterHolder { func: Box::new(f) });
            let user = &*holder as *const FormatterHolder as *mut std::os::raw::c_void;
            storage.formatters.push(holder);
            unsafe {
                sys::ImPlot_SetupAxisFormat_PlotFormatter(
                    axis as sys::ImAxis,
                    Some(formatter_thunk),
                    user,
                )
            }
        })
        .is_some();

        debug_assert!(
            configured,
            "dear-implot: axis formatter closure must be set within an active plot"
        );

        Self { _private: () }
    }
}

impl Drop for AxisFormatterToken {
    fn drop(&mut self) {
        // The actual callback lifetime is managed by PlotScopeGuard.
    }
}

unsafe extern "C" fn formatter_thunk(
    value: f64,
    buff: *mut std::os::raw::c_char,
    size: std::os::raw::c_int,
    user_data: *mut std::os::raw::c_void,
) -> std::os::raw::c_int {
    if user_data.is_null() || buff.is_null() || size <= 0 {
        return 0;
    }
    // Safety: ImPlot passes back the same pointer we provided in `AxisFormatterToken::new`.
    let holder = unsafe { &*(user_data as *const FormatterHolder) };
    let s = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| (holder.func)(value))) {
        Ok(v) => v,
        Err(_) => {
            eprintln!("dear-implot: panic in axis formatter callback");
            std::process::abort();
        }
    };
    let bytes = s.as_bytes();
    let max = (size - 1).max(0) as usize;
    let n = bytes.len().min(max);

    // Safety: `buff` is assumed to point to a valid buffer of at least `size`
    // bytes, with space for a terminating null. This matches ImPlot's
    // formatter contract.
    unsafe {
        std::ptr::copy_nonoverlapping(bytes.as_ptr(), buff as *mut u8, n);
        *buff.add(n) = 0;
    }
    n as std::os::raw::c_int
}

// =================== Transform bridge ===================

struct TransformHolder {
    forward: Box<dyn Fn(f64) -> f64 + Send + Sync + 'static>,
    inverse: Box<dyn Fn(f64) -> f64 + Send + Sync + 'static>,
}

#[must_use]
pub struct AxisTransformToken {
    _private: (),
}

impl AxisTransformToken {
    fn new<FW, INV>(axis: sys::ImAxis, forward: FW, inverse: INV) -> Self
    where
        FW: Fn(f64) -> f64 + Send + Sync + 'static,
        INV: Fn(f64) -> f64 + Send + Sync + 'static,
    {
        let configured = with_plot_scope_storage(|storage| {
            let holder = Box::new(TransformHolder {
                forward: Box::new(forward),
                inverse: Box::new(inverse),
            });
            let user = &*holder as *const TransformHolder as *mut std::os::raw::c_void;
            storage.transforms.push(holder);
            unsafe {
                sys::ImPlot_SetupAxisScale_PlotTransform(
                    axis as sys::ImAxis,
                    Some(transform_forward_thunk),
                    Some(transform_inverse_thunk),
                    user,
                )
            }
        })
        .is_some();

        debug_assert!(
            configured,
            "dear-implot: axis transform closure must be set within an active plot"
        );

        Self { _private: () }
    }
}

impl Drop for AxisTransformToken {
    fn drop(&mut self) {
        // The actual callback lifetime is managed by PlotScopeGuard.
    }
}

unsafe extern "C" fn transform_forward_thunk(
    value: f64,
    user_data: *mut std::os::raw::c_void,
) -> f64 {
    if user_data.is_null() {
        return value;
    }
    let holder = unsafe { &*(user_data as *const TransformHolder) };
    match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| (holder.forward)(value))) {
        Ok(v) => v,
        Err(_) => {
            eprintln!("dear-implot: panic in axis transform (forward) callback");
            std::process::abort();
        }
    }
}

unsafe extern "C" fn transform_inverse_thunk(
    value: f64,
    user_data: *mut std::os::raw::c_void,
) -> f64 {
    if user_data.is_null() {
        return value;
    }
    let holder = unsafe { &*(user_data as *const TransformHolder) };
    match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| (holder.inverse)(value))) {
        Ok(v) => v,
        Err(_) => {
            eprintln!("dear-implot: panic in axis transform (inverse) callback");
            std::process::abort();
        }
    }
}

/// Token that represents an active plot
///
/// The plot will be automatically ended when this token is dropped.
pub struct PlotToken<'ui> {
    _scope: PlotScopeGuard,
    _lifetime: std::marker::PhantomData<&'ui ()>,
}

impl<'ui> PlotToken<'ui> {
    /// Create a new PlotToken (internal use only)
    pub(crate) fn new() -> Self {
        Self {
            _scope: PlotScopeGuard::new(),
            _lifetime: std::marker::PhantomData,
        }
    }

    /// Manually end the plot
    ///
    /// This is called automatically when the token is dropped,
    /// but you can call it manually if needed.
    pub fn end(self) {
        // The actual ending happens in Drop
    }
}

impl<'ui> Drop for PlotToken<'ui> {
    fn drop(&mut self) {
        unsafe {
            sys::ImPlot_EndPlot();
        }
    }
}