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
// Style and theming for plots

use crate::sys;
use dear_imgui_rs::{with_scratch_txt, with_scratch_txt_two};
use std::borrow::Cow;
use std::os::raw::c_char;

/// Style variables that can be modified
#[repr(i32)]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum StyleVar {
    PlotDefaultSize = sys::ImPlotStyleVar_PlotDefaultSize as i32,
    PlotMinSize = sys::ImPlotStyleVar_PlotMinSize as i32,
    PlotBorderSize = sys::ImPlotStyleVar_PlotBorderSize as i32,
    MinorAlpha = sys::ImPlotStyleVar_MinorAlpha as i32,
    MajorTickLen = sys::ImPlotStyleVar_MajorTickLen as i32,
    MinorTickLen = sys::ImPlotStyleVar_MinorTickLen as i32,
    MajorTickSize = sys::ImPlotStyleVar_MajorTickSize as i32,
    MinorTickSize = sys::ImPlotStyleVar_MinorTickSize as i32,
    MajorGridSize = sys::ImPlotStyleVar_MajorGridSize as i32,
    MinorGridSize = sys::ImPlotStyleVar_MinorGridSize as i32,
    PlotPadding = sys::ImPlotStyleVar_PlotPadding as i32,
    LabelPadding = sys::ImPlotStyleVar_LabelPadding as i32,
    LegendPadding = sys::ImPlotStyleVar_LegendPadding as i32,
    LegendInnerPadding = sys::ImPlotStyleVar_LegendInnerPadding as i32,
    LegendSpacing = sys::ImPlotStyleVar_LegendSpacing as i32,
    MousePosPadding = sys::ImPlotStyleVar_MousePosPadding as i32,
    AnnotationPadding = sys::ImPlotStyleVar_AnnotationPadding as i32,
    FitPadding = sys::ImPlotStyleVar_FitPadding as i32,
    DigitalPadding = sys::ImPlotStyleVar_DigitalPadding as i32,
    DigitalSpacing = sys::ImPlotStyleVar_DigitalSpacing as i32,
}

/// Token for managing style variable changes
pub struct StyleVarToken {
    was_popped: bool,
}

impl StyleVarToken {
    /// Pop this style variable from the stack
    pub fn pop(mut self) {
        if self.was_popped {
            panic!("Attempted to pop a style var token twice.");
        }
        self.was_popped = true;
        unsafe {
            sys::ImPlot_PopStyleVar(1);
        }
    }
}

impl Drop for StyleVarToken {
    fn drop(&mut self) {
        if !self.was_popped {
            unsafe {
                sys::ImPlot_PopStyleVar(1);
            }
        }
    }
}

/// Token for managing style color changes
pub struct StyleColorToken {
    was_popped: bool,
}

impl StyleColorToken {
    /// Pop this style color from the stack
    pub fn pop(mut self) {
        if self.was_popped {
            panic!("Attempted to pop a style color token twice.");
        }
        self.was_popped = true;
        unsafe {
            sys::ImPlot_PopStyleColor(1);
        }
    }
}

impl Drop for StyleColorToken {
    fn drop(&mut self) {
        if !self.was_popped {
            unsafe {
                sys::ImPlot_PopStyleColor(1);
            }
        }
    }
}

/// One-shot array-backed item style overrides for the next plot submission.
///
/// This mirrors the new per-item array fields added to `ImPlotSpec` without storing
/// borrowed pointers beyond the closure passed to [`with_next_plot_item_array_style`].
#[derive(Debug, Clone, Default, PartialEq)]
pub struct PlotItemArrayStyle<'a> {
    line_colors: Option<Cow<'a, [u32]>>,
    fill_colors: Option<Cow<'a, [u32]>>,
    marker_sizes: Option<Cow<'a, [f32]>>,
    marker_line_colors: Option<Cow<'a, [u32]>>,
    marker_fill_colors: Option<Cow<'a, [u32]>>,
}

impl<'a> PlotItemArrayStyle<'a> {
    /// Create an empty array-style override.
    pub fn new() -> Self {
        Self::default()
    }

    /// Override per-index line colors using Dear ImGui packed colors (`ImU32` / ABGR).
    pub fn with_line_colors(mut self, colors: &'a [u32]) -> Self {
        self.line_colors = Some(Cow::Borrowed(colors));
        self
    }

    /// Override per-index fill colors using Dear ImGui packed colors (`ImU32` / ABGR).
    pub fn with_fill_colors(mut self, colors: &'a [u32]) -> Self {
        self.fill_colors = Some(Cow::Borrowed(colors));
        self
    }

    /// Override per-index marker sizes in pixels.
    pub fn with_marker_sizes(mut self, sizes: &'a [f32]) -> Self {
        self.marker_sizes = Some(Cow::Borrowed(sizes));
        self
    }

    /// Override per-index marker outline colors using Dear ImGui packed colors (`ImU32` / ABGR).
    pub fn with_marker_line_colors(mut self, colors: &'a [u32]) -> Self {
        self.marker_line_colors = Some(Cow::Borrowed(colors));
        self
    }

    /// Override per-index marker fill colors using Dear ImGui packed colors (`ImU32` / ABGR).
    pub fn with_marker_fill_colors(mut self, colors: &'a [u32]) -> Self {
        self.marker_fill_colors = Some(Cow::Borrowed(colors));
        self
    }

    fn apply_to_spec(&self, spec: &mut sys::ImPlotSpec_c) {
        spec.LineColors = self
            .line_colors
            .as_ref()
            .map_or(std::ptr::null_mut(), |colors| colors.as_ptr() as *mut _);
        spec.FillColors = self
            .fill_colors
            .as_ref()
            .map_or(std::ptr::null_mut(), |colors| colors.as_ptr() as *mut _);
        spec.MarkerSizes = self
            .marker_sizes
            .as_ref()
            .map_or(std::ptr::null_mut(), |sizes| sizes.as_ptr() as *mut _);
        spec.MarkerLineColors = self
            .marker_line_colors
            .as_ref()
            .map_or(std::ptr::null_mut(), |colors| colors.as_ptr() as *mut _);
        spec.MarkerFillColors = self
            .marker_fill_colors
            .as_ref()
            .map_or(std::ptr::null_mut(), |colors| colors.as_ptr() as *mut _);
    }
}

/// Apply array-backed item styling to the next plot submission executed inside `f`.
///
/// This is intentionally closure-scoped so borrowed slices stay valid for the entire
/// duration of the next plot call and cannot leak into later frames accidentally.
pub fn with_next_plot_item_array_style<'a, R>(
    style: PlotItemArrayStyle<'a>,
    f: impl FnOnce() -> R,
) -> R {
    let previous = crate::plots::take_next_plot_spec();
    let mut spec = previous.unwrap_or_else(crate::plots::default_plot_spec);
    style.apply_to_spec(&mut spec);
    crate::plots::set_next_plot_spec(Some(spec));

    let out = f();

    if crate::plots::take_next_plot_spec().is_some() {
        crate::plots::set_next_plot_spec(previous);
    }

    out
}

/// Push a float style variable to the stack
pub fn push_style_var_f32(var: StyleVar, value: f32) -> StyleVarToken {
    unsafe {
        sys::ImPlot_PushStyleVar_Float(var as sys::ImPlotStyleVar, value);
    }
    StyleVarToken { was_popped: false }
}

/// Push an integer style variable to the stack (converted to float)
pub fn push_style_var_i32(var: StyleVar, value: i32) -> StyleVarToken {
    unsafe {
        sys::ImPlot_PushStyleVar_Int(var as sys::ImPlotStyleVar, value);
    }
    StyleVarToken { was_popped: false }
}

/// Push a Vec2 style variable to the stack
pub fn push_style_var_vec2(var: StyleVar, value: [f32; 2]) -> StyleVarToken {
    unsafe {
        sys::ImPlot_PushStyleVar_Vec2(
            var as sys::ImPlotStyleVar,
            sys::ImVec2_c {
                x: value[0],
                y: value[1],
            },
        );
    }
    StyleVarToken { was_popped: false }
}

/// Push a style color to the stack
pub fn push_style_color(element: crate::PlotColorElement, color: [f32; 4]) -> StyleColorToken {
    unsafe {
        // Convert color to ImU32 format (RGBA)
        let r = (color[0] * 255.0) as u32;
        let g = (color[1] * 255.0) as u32;
        let b = (color[2] * 255.0) as u32;
        let a = (color[3] * 255.0) as u32;
        let color_u32 = (a << 24) | (b << 16) | (g << 8) | r;

        sys::ImPlot_PushStyleColor_U32(element as sys::ImPlotCol, color_u32);
    }
    StyleColorToken { was_popped: false }
}

/// Push a colormap to the stack
pub fn push_colormap(preset: crate::Colormap) {
    unsafe {
        sys::ImPlot_PushColormap_PlotColormap(preset as sys::ImPlotColormap);
    }
}

/// Pop a colormap from the stack
pub fn pop_colormap(count: i32) {
    unsafe {
        sys::ImPlot_PopColormap(count);
    }
}

/// Add a custom colormap from a vector of colors
pub fn add_colormap(name: &str, colors: &[sys::ImVec4], qualitative: bool) -> sys::ImPlotColormap {
    assert!(!name.contains('\0'), "colormap name contained NUL");
    let count = i32::try_from(colors.len()).expect("colormap contained too many colors");
    with_scratch_txt(name, |ptr| unsafe {
        sys::ImPlot_AddColormap_Vec4Ptr(ptr, colors.as_ptr(), count, qualitative)
            as sys::ImPlotColormap
    })
}

// Style editor / selectors and input-map helpers

/// Show the ImPlot style editor window
pub fn show_style_editor() {
    unsafe { sys::ImPlot_ShowStyleEditor(std::ptr::null_mut()) }
}

/// Show the ImPlot style selector combo; returns true if selection changed
pub fn show_style_selector(label: &str) -> bool {
    let label = if label.contains('\0') { "" } else { label };
    with_scratch_txt(label, |ptr| unsafe { sys::ImPlot_ShowStyleSelector(ptr) })
}

/// Show the ImPlot colormap selector combo; returns true if selection changed
pub fn show_colormap_selector(label: &str) -> bool {
    let label = if label.contains('\0') { "" } else { label };
    with_scratch_txt(label, |ptr| unsafe {
        sys::ImPlot_ShowColormapSelector(ptr)
    })
}

/// Show the ImPlot input-map selector combo; returns true if selection changed
pub fn show_input_map_selector(label: &str) -> bool {
    let label = if label.contains('\0') { "" } else { label };
    with_scratch_txt(label, |ptr| unsafe {
        sys::ImPlot_ShowInputMapSelector(ptr)
    })
}

/// Map input to defaults
pub fn map_input_default() {
    unsafe { sys::ImPlot_MapInputDefault(sys::ImPlot_GetInputMap()) }
}

/// Map input to reversed scheme
pub fn map_input_reverse() {
    unsafe { sys::ImPlot_MapInputReverse(sys::ImPlot_GetInputMap()) }
}

// Colormap widgets

/// Draw a colormap scale widget
pub fn colormap_scale(
    label: &str,
    scale_min: f64,
    scale_max: f64,
    height: f32,
    cmap: Option<sys::ImPlotColormap>,
) {
    let label = if label.contains('\0') { "" } else { label };
    let size = sys::ImVec2_c { x: 0.0, y: height };
    let fmt_ptr: *const c_char = std::ptr::null();
    let flags: i32 = 0; // ImPlotColormapScaleFlags_None
    with_scratch_txt(label, |ptr| unsafe {
        sys::ImPlot_ColormapScale(
            ptr,
            scale_min,
            scale_max,
            size,
            fmt_ptr,
            flags,
            cmap.unwrap_or(0),
        )
    })
}

/// Draw a colormap slider; returns true if selection changed
pub fn colormap_slider(
    label: &str,
    t: &mut f32,
    out_color: &mut sys::ImVec4,
    format: Option<&str>,
    cmap: sys::ImPlotColormap,
) -> bool {
    let label = if label.contains('\0') { "" } else { label };
    let format = format.filter(|s| !s.contains('\0'));

    match format {
        Some(fmt) => with_scratch_txt_two(label, fmt, |label_ptr, fmt_ptr| unsafe {
            sys::ImPlot_ColormapSlider(
                label_ptr,
                t as *mut f32,
                out_color as *mut sys::ImVec4,
                fmt_ptr,
                cmap,
            )
        }),
        None => with_scratch_txt(label, |label_ptr| unsafe {
            sys::ImPlot_ColormapSlider(
                label_ptr,
                t as *mut f32,
                out_color as *mut sys::ImVec4,
                std::ptr::null(),
                cmap,
            )
        }),
    }
}

/// Draw a colormap picker button; returns true if clicked
pub fn colormap_button(label: &str, size: [f32; 2], cmap: sys::ImPlotColormap) -> bool {
    let label = if label.contains('\0') { "" } else { label };
    let sz = sys::ImVec2_c {
        x: size[0],
        y: size[1],
    };
    with_scratch_txt(label, |ptr| unsafe {
        sys::ImPlot_ColormapButton(ptr, sz, cmap)
    })
}

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

    #[test]
    fn next_plot_item_array_style_is_consumed_by_next_spec() {
        let line_colors = [0x01020304u32, 0x05060708];
        let fill_colors = [0x11121314u32];
        let marker_sizes = [2.0f32, 4.0, 8.0];

        with_next_plot_item_array_style(
            PlotItemArrayStyle::new()
                .with_line_colors(&line_colors)
                .with_fill_colors(&fill_colors)
                .with_marker_sizes(&marker_sizes),
            || {
                let spec = crate::plots::plot_spec_from(7, 3, 16);
                assert_eq!(spec.Flags, 7);
                assert_eq!(spec.Offset, 3);
                assert_eq!(spec.Stride, 16);
                assert_eq!(spec.LineColors, line_colors.as_ptr() as *mut _);
                assert_eq!(spec.FillColors, fill_colors.as_ptr() as *mut _);
                assert_eq!(spec.MarkerSizes, marker_sizes.as_ptr() as *mut _);
            },
        );

        let spec = crate::plots::plot_spec_from(0, 0, crate::IMPLOT_AUTO);
        assert!(spec.LineColors.is_null());
        assert!(spec.FillColors.is_null());
        assert!(spec.MarkerSizes.is_null());
    }

    #[test]
    fn next_plot_item_array_style_is_restored_if_unused() {
        let line_colors = [0xAABBCCDDu32];

        with_next_plot_item_array_style(
            PlotItemArrayStyle::new().with_line_colors(&line_colors),
            || {},
        );

        let spec = crate::plots::plot_spec_from(0, 0, crate::IMPLOT_AUTO);
        assert!(spec.LineColors.is_null());
    }
}