dear-implot 0.13.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
//! Advanced plotting features for complex visualizations
//!
//! This module provides high-level functionality for creating complex plots
//! with multiple subplots, legends, and advanced layout management.

use crate::context::PlotScopeGuard;
use crate::{AxisFlags, YAxis, plots::PlotError, sys};
use std::ffi::CString;
use std::marker::PhantomData;

fn validate_size(caller: &str, size: [f32; 2]) -> Result<(), PlotError> {
    if size[0].is_finite() && size[1].is_finite() {
        Ok(())
    } else {
        Err(PlotError::InvalidData(format!(
            "{caller} size must be finite"
        )))
    }
}

fn validate_positive_count(caller: &str, name: &str, value: i32) -> Result<(), PlotError> {
    if value > 0 {
        Ok(())
    } else {
        Err(PlotError::InvalidData(format!(
            "{caller} {name} must be positive"
        )))
    }
}

fn validate_ratios(caller: &str, name: &str, ratios: &[f32]) -> Result<(), PlotError> {
    if ratios.iter().all(|value| value.is_finite() && *value > 0.0) {
        Ok(())
    } else {
        Err(PlotError::InvalidData(format!(
            "{caller} {name} must contain only positive finite values"
        )))
    }
}

fn validate_range(caller: &str, min: f64, max: f64) -> Result<(), PlotError> {
    if min.is_finite() && max.is_finite() && min != max {
        Ok(())
    } else {
        Err(PlotError::InvalidData(format!(
            "{caller} range values must be finite and distinct"
        )))
    }
}

/// Multi-plot layout manager for creating subplot grids
pub struct SubplotGrid<'a> {
    title: &'a str,
    rows: i32,
    cols: i32,
    size: Option<[f32; 2]>,
    flags: SubplotFlags,
    row_ratios: Option<Vec<f32>>,
    col_ratios: Option<Vec<f32>>,
}

bitflags::bitflags! {
    /// Flags for subplot configuration
    pub struct SubplotFlags: u32 {
        const NONE = 0;
        const NO_TITLE = 1 << 0;
        const NO_RESIZE = 1 << 1;
        const NO_ALIGN = 1 << 2;
        const SHARE_ITEMS = 1 << 3;
        const LINK_ROWS = 1 << 4;
        const LINK_COLS = 1 << 5;
        const LINK_ALL_X = 1 << 6;
        const LINK_ALL_Y = 1 << 7;
        const COLUMN_MAJOR = 1 << 8;
    }
}

impl<'a> SubplotGrid<'a> {
    /// Create a new subplot grid
    pub fn new(title: &'a str, rows: i32, cols: i32) -> Self {
        Self {
            title,
            rows,
            cols,
            size: None,
            flags: SubplotFlags::NONE,
            row_ratios: None,
            col_ratios: None,
        }
    }

    /// Set the size of the subplot grid
    pub fn with_size(mut self, size: [f32; 2]) -> Self {
        self.size = Some(size);
        self
    }

    /// Set subplot flags
    pub fn with_flags(mut self, flags: SubplotFlags) -> Self {
        self.flags = flags;
        self
    }

    /// Set row height ratios
    pub fn with_row_ratios(mut self, ratios: &[f32]) -> Self {
        self.row_ratios = if ratios.is_empty() {
            None
        } else {
            Some(ratios.to_vec())
        };
        self
    }

    /// Set column width ratios
    pub fn with_col_ratios(mut self, ratios: &[f32]) -> Self {
        self.col_ratios = if ratios.is_empty() {
            None
        } else {
            Some(ratios.to_vec())
        };
        self
    }

    /// Begin the subplot grid and return a token
    pub fn begin(self) -> Result<SubplotToken<'a>, PlotError> {
        validate_positive_count("SubplotGrid::begin()", "rows", self.rows)?;
        validate_positive_count("SubplotGrid::begin()", "cols", self.cols)?;
        let title_cstr =
            CString::new(self.title).map_err(|e| PlotError::StringConversion(e.to_string()))?;

        let size = self.size.unwrap_or([-1.0, -1.0]);
        validate_size("SubplotGrid::begin()", size)?;
        let size_vec = sys::ImVec2_c {
            x: size[0],
            y: size[1],
        };

        // The C API takes `float*` for ratios. Keep owned copies alive in the token to avoid
        // casting away constness and to stay sound even if the backend ever writes to them.
        let mut row_ratios = self.row_ratios;
        let mut col_ratios = self.col_ratios;
        if let Some(row_ratios) = &row_ratios {
            let rows = usize::try_from(self.rows).map_err(|_| {
                PlotError::InvalidData("SubplotGrid::begin() rows out of range".to_string())
            })?;
            if row_ratios.len() != rows {
                return Err(PlotError::InvalidData(format!(
                    "SubplotGrid::begin() row_ratios length must equal rows ({rows})"
                )));
            }
            validate_ratios("SubplotGrid::begin()", "row_ratios", row_ratios)?;
        }
        if let Some(col_ratios) = &col_ratios {
            let cols = usize::try_from(self.cols).map_err(|_| {
                PlotError::InvalidData("SubplotGrid::begin() cols out of range".to_string())
            })?;
            if col_ratios.len() != cols {
                return Err(PlotError::InvalidData(format!(
                    "SubplotGrid::begin() col_ratios length must equal cols ({cols})"
                )));
            }
            validate_ratios("SubplotGrid::begin()", "col_ratios", col_ratios)?;
        }
        let row_ratios_ptr = row_ratios
            .as_mut()
            .map(|r| r.as_mut_ptr())
            .unwrap_or(std::ptr::null_mut());
        let col_ratios_ptr = col_ratios
            .as_mut()
            .map(|c| c.as_mut_ptr())
            .unwrap_or(std::ptr::null_mut());

        let success = unsafe {
            sys::ImPlot_BeginSubplots(
                title_cstr.as_ptr(),
                self.rows,
                self.cols,
                size_vec,
                self.flags.bits() as i32,
                row_ratios_ptr,
                col_ratios_ptr,
            )
        };

        if success {
            Ok(SubplotToken {
                _title: title_cstr,
                _row_ratios: row_ratios,
                _col_ratios: col_ratios,
                _phantom: PhantomData,
            })
        } else {
            Err(PlotError::PlotCreationFailed(
                "Failed to begin subplots".to_string(),
            ))
        }
    }
}

/// Token representing an active subplot grid
pub struct SubplotToken<'a> {
    _title: CString,
    _row_ratios: Option<Vec<f32>>,
    _col_ratios: Option<Vec<f32>>,
    _phantom: PhantomData<&'a ()>,
}

impl<'a> SubplotToken<'a> {
    /// End the subplot grid
    pub fn end(self) {
        // The actual ending happens in Drop.
    }
}

impl<'a> Drop for SubplotToken<'a> {
    fn drop(&mut self) {
        unsafe {
            sys::ImPlot_EndSubplots();
        }
    }
}

/// Multi-axis plot support
pub struct MultiAxisPlot<'a> {
    title: &'a str,
    size: Option<[f32; 2]>,
    y_axes: Vec<YAxisConfig<'a>>,
}

/// Configuration for a Y-axis
pub struct YAxisConfig<'a> {
    pub label: Option<&'a str>,
    pub flags: AxisFlags,
    pub range: Option<(f64, f64)>,
}

impl<'a> MultiAxisPlot<'a> {
    /// Create a new multi-axis plot
    pub fn new(title: &'a str) -> Self {
        Self {
            title,
            size: None,
            y_axes: Vec::new(),
        }
    }

    /// Set the plot size
    pub fn with_size(mut self, size: [f32; 2]) -> Self {
        self.size = Some(size);
        self
    }

    /// Add a Y-axis
    pub fn add_y_axis(mut self, config: YAxisConfig<'a>) -> Self {
        self.y_axes.push(config);
        self
    }

    /// Begin the multi-axis plot
    pub fn begin(self) -> Result<MultiAxisToken<'a>, PlotError> {
        let title_cstr =
            CString::new(self.title).map_err(|e| PlotError::StringConversion(e.to_string()))?;

        for axis in &self.y_axes {
            if let Some(label) = axis.label
                && label.contains('\0')
            {
                return Err(PlotError::StringConversion(
                    "Axis label contained an interior NUL byte".to_string(),
                ));
            }
            if let Some((min, max)) = axis.range {
                validate_range("MultiAxisPlot::begin()", min, max)?;
            }
        }
        if self.y_axes.len() > 3 {
            return Err(PlotError::InvalidData(
                "MultiAxisPlot::begin() supports at most 3 Y axes".to_string(),
            ));
        }

        let size = self.size.unwrap_or([-1.0, -1.0]);
        validate_size("MultiAxisPlot::begin()", size)?;
        let size_vec = sys::ImVec2_c {
            x: size[0],
            y: size[1],
        };

        let success = unsafe { sys::ImPlot_BeginPlot(title_cstr.as_ptr(), size_vec, 0) };

        if success {
            let mut axis_labels: Vec<CString> = Vec::new();

            // Setup Y-axes (Y1..), matching `token.set_y_axis(YAxis::Y*)` convention.
            for (i, axis_config) in self.y_axes.iter().enumerate() {
                let label_ptr = if let Some(label) = axis_config.label {
                    let cstr = CString::new(label)
                        .map_err(|e| PlotError::StringConversion(e.to_string()))?;
                    let ptr = cstr.as_ptr();
                    axis_labels.push(cstr);
                    ptr
                } else {
                    std::ptr::null()
                };

                unsafe {
                    let axis_enum = (i as i32) + 3; // ImAxis_Y1 = 3
                    sys::ImPlot_SetupAxis(axis_enum, label_ptr, axis_config.flags.bits() as i32);

                    if let Some((min, max)) = axis_config.range {
                        sys::ImPlot_SetupAxisLimits(axis_enum, min, max, 0);
                    }
                }
            }

            Ok(MultiAxisToken {
                _title: title_cstr,
                _axis_labels: axis_labels,
                _scope: PlotScopeGuard::new(),
                _phantom: PhantomData,
            })
        } else {
            Err(PlotError::PlotCreationFailed(
                "Failed to begin multi-axis plot".to_string(),
            ))
        }
    }
}

/// Token representing an active multi-axis plot
pub struct MultiAxisToken<'a> {
    _title: CString,
    _axis_labels: Vec<CString>,
    _scope: PlotScopeGuard,
    _phantom: PhantomData<&'a ()>,
}

impl<'a> MultiAxisToken<'a> {
    /// Set the current Y-axis for subsequent plots
    pub fn set_y_axis(&self, axis: YAxis) {
        unsafe {
            sys::ImPlot_SetAxes(
                0, // ImAxis_X1
                axis as i32,
            );
        }
    }

    /// Set the current raw Y-axis for subsequent plots.
    ///
    /// # Safety
    ///
    /// `axis` must be a valid ImPlot Y-axis value for the active plot. Passing an
    /// out-of-range value lets ImPlot index internal axis arrays out of bounds.
    pub unsafe fn set_y_axis_unchecked(&self, axis: sys::ImAxis) {
        unsafe {
            sys::ImPlot_SetAxes(
                0, // ImAxis_X1
                axis,
            );
        }
    }

    /// End the multi-axis plot
    pub fn end(self) {
        // The actual ending happens in Drop.
    }
}

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

/// Legend management utilities
pub struct LegendManager;

impl LegendManager {
    /// Setup legend with custom position and flags
    pub fn setup(location: LegendLocation, flags: LegendFlags) {
        unsafe {
            sys::ImPlot_SetupLegend(location as i32, flags.bits() as i32);
        }
    }

    /// Begin a custom legend
    pub fn begin_custom(label: &str, _size: [f32; 2]) -> Result<LegendToken, PlotError> {
        let label_cstr =
            CString::new(label).map_err(|e| PlotError::StringConversion(e.to_string()))?;

        let success = unsafe {
            sys::ImPlot_BeginLegendPopup(
                label_cstr.as_ptr(),
                1, // mouse button
            )
        };

        if success {
            Ok(LegendToken { _label: label_cstr })
        } else {
            Err(PlotError::PlotCreationFailed(
                "Failed to begin legend".to_string(),
            ))
        }
    }
}

/// Legend location options (ImPlotLocation)
#[repr(i32)]
pub enum LegendLocation {
    Center = sys::ImPlotLocation_Center as i32,
    North = sys::ImPlotLocation_North as i32,
    South = sys::ImPlotLocation_South as i32,
    West = sys::ImPlotLocation_West as i32,
    East = sys::ImPlotLocation_East as i32,
    NorthWest = sys::ImPlotLocation_NorthWest as i32,
    NorthEast = sys::ImPlotLocation_NorthEast as i32,
    SouthWest = sys::ImPlotLocation_SouthWest as i32,
    SouthEast = sys::ImPlotLocation_SouthEast as i32,
}

bitflags::bitflags! {
    /// Flags for legend configuration (ImPlotLegendFlags)
    pub struct LegendFlags: u32 {
        const NONE              = sys::ImPlotLegendFlags_None as u32;
        const NO_BUTTONS        = sys::ImPlotLegendFlags_NoButtons as u32;
        const NO_HIGHLIGHT_ITEM = sys::ImPlotLegendFlags_NoHighlightItem as u32;
        const NO_HIGHLIGHT_AXIS = sys::ImPlotLegendFlags_NoHighlightAxis as u32;
        const NO_MENUS          = sys::ImPlotLegendFlags_NoMenus as u32;
        const OUTSIDE           = sys::ImPlotLegendFlags_Outside as u32;
        const HORIZONTAL        = sys::ImPlotLegendFlags_Horizontal as u32;
        const SORT              = sys::ImPlotLegendFlags_Sort as u32;
        // Note: ImPlotLegendFlags_Reverse is currently not exposed.
    }
}

/// Token representing an active legend
pub struct LegendToken {
    _label: CString,
}

impl LegendToken {
    /// End the legend
    pub fn end(self) {
        // The actual ending happens in Drop.
    }
}

impl Drop for LegendToken {
    fn drop(&mut self) {
        unsafe {
            sys::ImPlot_EndLegendPopup();
        }
    }
}