Skip to main content

dear_implot/
lib.rs

1//! # Dear ImPlot - Rust Bindings with Dear ImGui Compatibility
2//!
3//! High-level Rust bindings for ImPlot, the immediate mode plotting library.
4//! This crate provides safe, idiomatic Rust bindings designed to work seamlessly
5//! with dear-imgui (C++ bindgen) rather than imgui-rs (cimgui).
6//!
7//! ## Features
8//!
9//! - Safe, idiomatic Rust API
10//! - Full compatibility with dear-imgui
11//! - Builder pattern for plots and plot elements
12//! - Memory-safe string handling
13//! - Support for all major plot types
14//!
15//! ## Quick Start
16//!
17//! ```no_run
18//! use dear_imgui_rs::*;
19//! use dear_implot::*;
20//!
21//! let mut ctx = Context::create();
22//! let mut plot_ctx = PlotContext::create(&ctx);
23//!
24//! let ui = ctx.frame();
25//! let plot_ui = plot_ctx.get_plot_ui(&ui);
26//!
27//! if let Some(token) = plot_ui.begin_plot("My Plot") {
28//!     plot_ui.plot_line("Line", &[1.0, 2.0, 3.0, 4.0], &[1.0, 4.0, 2.0, 3.0]);
29//!     token.end();
30//! }
31//! ```
32//!
33//! ## Integration with Dear ImGui
34//!
35//! This crate is designed to work with the `dear-imgui-rs` ecosystem:
36//! - Uses the same context management patterns
37//! - Compatible with dear-imgui's UI tokens and lifetime management
38//! - Shares the same underlying Dear ImGui context
39
40use dear_implot_sys as sys;
41
42// Bindgen output for `dear-implot-sys` can fluctuate between historical
43// out-parameter signatures and the newer return-by-value signatures depending
44// on which generated `OUT_DIR` file rust-analyzer happens to index.
45//
46// Keep the wrapper crate stable by calling a local extern declaration for the
47// specific APIs we expose.
48#[allow(non_snake_case)]
49pub(crate) mod compat_ffi {
50    use super::sys;
51    use std::os::raw::c_char;
52
53    unsafe extern "C" {
54        pub fn ImPlot_GetPlotPos() -> sys::ImVec2;
55        pub fn ImPlot_GetPlotSize() -> sys::ImVec2;
56    }
57
58    // Some targets (notably import-style wasm) cannot call C variadic (`...`) functions.
59    // Declare the `*_Str0` convenience wrappers here to keep the safe layer independent
60    // of bindgen fluctuations / pregenerated bindings.
61    //
62    // On wasm32, these must be provided by the `imgui-sys-v0` provider module.
63    #[cfg(target_arch = "wasm32")]
64    #[link(wasm_import_module = "imgui-sys-v0")]
65    unsafe extern "C" {
66        pub fn ImPlot_Annotation_Str0(
67            x: f64,
68            y: f64,
69            col: sys::ImVec4_c,
70            pix_offset: sys::ImVec2_c,
71            clamp: bool,
72            fmt: *const c_char,
73        );
74        pub fn ImPlot_TagX_Str0(x: f64, col: sys::ImVec4_c, fmt: *const c_char);
75        pub fn ImPlot_TagY_Str0(y: f64, col: sys::ImVec4_c, fmt: *const c_char);
76    }
77
78    #[cfg(not(target_arch = "wasm32"))]
79    unsafe extern "C" {
80        pub fn ImPlot_Annotation_Str0(
81            x: f64,
82            y: f64,
83            col: sys::ImVec4_c,
84            pix_offset: sys::ImVec2_c,
85            clamp: bool,
86            fmt: *const c_char,
87        );
88        pub fn ImPlot_TagX_Str0(x: f64, col: sys::ImVec4_c, fmt: *const c_char);
89        pub fn ImPlot_TagY_Str0(y: f64, col: sys::ImVec4_c, fmt: *const c_char);
90    }
91}
92
93// Re-export essential types
94pub use dear_imgui_rs::{Context, Ui};
95pub use sys::{ImPlotPoint, ImPlotRange, ImPlotRect};
96pub use sys::{ImTextureID, ImVec2, ImVec4};
97
98mod advanced;
99mod context;
100mod style;
101mod utils;
102
103// New modular plot types
104pub mod plots;
105
106pub use context::*;
107pub use style::*;
108pub use utils::*;
109
110// Re-export new modular plot types for convenience
111pub use plots::{
112    Plot, PlotData, PlotError,
113    bar::{BarPlot, PositionalBarPlot},
114    error_bars::{AsymmetricErrorBarsPlot, ErrorBarsPlot, SimpleErrorBarsPlot},
115    heatmap::{HeatmapPlot, HeatmapPlotF32},
116    histogram::{Histogram2DPlot, HistogramPlot},
117    line::{LinePlot, SimpleLinePlot},
118    pie::{PieChartPlot, PieChartPlotF32},
119    polygon::PolygonPlot,
120    scatter::{ScatterPlot, SimpleScatterPlot},
121    shaded::{ShadedBetweenPlot, ShadedPlot, SimpleShadedPlot},
122    stems::{SimpleStemPlot, StemPlot},
123};
124
125// Constants
126const IMPLOT_AUTO: i32 = -1;
127
128/// Choice of Y axis for multi-axis plots
129#[derive(Clone, Copy, Debug, PartialEq, Eq)]
130#[repr(u32)]
131pub enum YAxisChoice {
132    First = 0,
133    Second = 1,
134    Third = 2,
135}
136
137/// Convert an Option<YAxisChoice> into an i32. Picks IMPLOT_AUTO for None.
138fn y_axis_choice_option_to_i32(y_axis_choice: Option<YAxisChoice>) -> i32 {
139    match y_axis_choice {
140        Some(choice) => choice as i32,
141        None => IMPLOT_AUTO,
142    }
143}
144
145/// X axis selector matching ImPlot's ImAxis values
146#[derive(Clone, Copy, Debug, PartialEq, Eq)]
147#[repr(i32)]
148pub enum XAxis {
149    X1 = 0,
150    X2 = 1,
151    X3 = 2,
152}
153
154/// Y axis selector matching ImPlot's ImAxis values
155#[derive(Clone, Copy, Debug, PartialEq, Eq)]
156#[repr(i32)]
157pub enum YAxis {
158    Y1 = 3,
159    Y2 = 4,
160    Y3 = 5,
161}
162
163impl YAxis {
164    /// Convert a Y axis (Y1..Y3) to the 0-based index used by ImPlotPlot_YAxis_Nil
165    pub(crate) fn to_index(self) -> i32 {
166        (self as i32) - 3
167    }
168}
169
170/// Ui extension for obtaining a PlotUi from an ImPlot PlotContext
171pub trait ImPlotExt {
172    fn implot<'ui>(&'ui self, ctx: &'ui PlotContext) -> PlotUi<'ui>;
173}
174
175impl ImPlotExt for Ui {
176    fn implot<'ui>(&'ui self, ctx: &'ui PlotContext) -> PlotUi<'ui> {
177        ctx.get_plot_ui(self)
178    }
179}
180
181/// Markers for plot points
182#[repr(i32)]
183#[derive(Copy, Clone, Debug, PartialEq, Eq)]
184pub enum Marker {
185    Auto = sys::ImPlotMarker_Auto as i32,
186    None = sys::ImPlotMarker_None as i32,
187    Circle = sys::ImPlotMarker_Circle as i32,
188    Square = sys::ImPlotMarker_Square as i32,
189    Diamond = sys::ImPlotMarker_Diamond as i32,
190    Up = sys::ImPlotMarker_Up as i32,
191    Down = sys::ImPlotMarker_Down as i32,
192    Left = sys::ImPlotMarker_Left as i32,
193    Right = sys::ImPlotMarker_Right as i32,
194    Cross = sys::ImPlotMarker_Cross as i32,
195    Plus = sys::ImPlotMarker_Plus as i32,
196    Asterisk = sys::ImPlotMarker_Asterisk as i32,
197}
198
199/// Colorable plot elements
200#[repr(u32)]
201#[derive(Copy, Clone, Debug, PartialEq, Eq)]
202pub enum PlotColorElement {
203    FrameBg = sys::ImPlotCol_FrameBg as u32,
204    PlotBg = sys::ImPlotCol_PlotBg as u32,
205    PlotBorder = sys::ImPlotCol_PlotBorder as u32,
206    LegendBg = sys::ImPlotCol_LegendBg as u32,
207    LegendBorder = sys::ImPlotCol_LegendBorder as u32,
208    LegendText = sys::ImPlotCol_LegendText as u32,
209    TitleText = sys::ImPlotCol_TitleText as u32,
210    InlayText = sys::ImPlotCol_InlayText as u32,
211    AxisText = sys::ImPlotCol_AxisText as u32,
212    AxisGrid = sys::ImPlotCol_AxisGrid as u32,
213    AxisTick = sys::ImPlotCol_AxisTick as u32,
214    AxisBg = sys::ImPlotCol_AxisBg as u32,
215    AxisBgHovered = sys::ImPlotCol_AxisBgHovered as u32,
216    AxisBgActive = sys::ImPlotCol_AxisBgActive as u32,
217    Selection = sys::ImPlotCol_Selection as u32,
218    Crosshairs = sys::ImPlotCol_Crosshairs as u32,
219}
220
221/// Built-in colormaps
222#[repr(u32)]
223#[derive(Copy, Clone, Debug, PartialEq, Eq)]
224pub enum Colormap {
225    Deep = sys::ImPlotColormap_Deep as u32,
226    Dark = sys::ImPlotColormap_Dark as u32,
227    Pastel = sys::ImPlotColormap_Pastel as u32,
228    Paired = sys::ImPlotColormap_Paired as u32,
229    Viridis = sys::ImPlotColormap_Viridis as u32,
230    Plasma = sys::ImPlotColormap_Plasma as u32,
231    Hot = sys::ImPlotColormap_Hot as u32,
232    Cool = sys::ImPlotColormap_Cool as u32,
233    Pink = sys::ImPlotColormap_Pink as u32,
234    Jet = sys::ImPlotColormap_Jet as u32,
235}
236
237/// Plot location for legends, labels, etc.
238#[repr(u32)]
239#[derive(Copy, Clone, Debug, PartialEq, Eq)]
240pub enum PlotLocation {
241    Center = sys::ImPlotLocation_Center as u32,
242    North = sys::ImPlotLocation_North as u32,
243    South = sys::ImPlotLocation_South as u32,
244    West = sys::ImPlotLocation_West as u32,
245    East = sys::ImPlotLocation_East as u32,
246    NorthWest = sys::ImPlotLocation_NorthWest as u32,
247    NorthEast = sys::ImPlotLocation_NorthEast as u32,
248    SouthWest = sys::ImPlotLocation_SouthWest as u32,
249    SouthEast = sys::ImPlotLocation_SouthEast as u32,
250}
251
252/// Plot orientation
253#[repr(u32)]
254#[derive(Copy, Clone, Debug, PartialEq, Eq)]
255pub enum PlotOrientation {
256    Horizontal = 0,
257    Vertical = 1,
258}
259
260/// Binning methods for histograms
261#[repr(i32)]
262#[derive(Copy, Clone, Debug, PartialEq, Eq)]
263pub enum BinMethod {
264    Sqrt = -1,
265    Sturges = -2,
266    Rice = -3,
267    Scott = -4,
268}
269
270bitflags::bitflags! {
271    /// Flags for ANY `PlotX` function. Used by setting `ImPlotSpec::Flags`.
272    ///
273    /// These flags can be composed with the plot-type-specific flags (e.g. `LineFlags`).
274    #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
275    pub struct ItemFlags: u32 {
276        const NONE = sys::ImPlotItemFlags_None as u32;
277        const NO_LEGEND = sys::ImPlotItemFlags_NoLegend as u32;
278        const NO_FIT = sys::ImPlotItemFlags_NoFit as u32;
279    }
280}
281
282// Plot flags for different plot types
283bitflags::bitflags! {
284    /// Flags for heatmap plots
285    pub struct HeatmapFlags: u32 {
286        const NONE = sys::ImPlotHeatmapFlags_None as u32;
287        const COL_MAJOR = sys::ImPlotHeatmapFlags_ColMajor as u32;
288    }
289}
290
291bitflags::bitflags! {
292    /// Flags for histogram plots
293    pub struct HistogramFlags: u32 {
294        const NONE = sys::ImPlotHistogramFlags_None as u32;
295        const HORIZONTAL = sys::ImPlotHistogramFlags_Horizontal as u32;
296        const CUMULATIVE = sys::ImPlotHistogramFlags_Cumulative as u32;
297        const DENSITY = sys::ImPlotHistogramFlags_Density as u32;
298        const NO_OUTLIERS = sys::ImPlotHistogramFlags_NoOutliers as u32;
299        const COL_MAJOR = sys::ImPlotHistogramFlags_ColMajor as u32;
300    }
301}
302
303bitflags::bitflags! {
304    /// Flags for pie chart plots
305    pub struct PieChartFlags: u32 {
306        const NONE = sys::ImPlotPieChartFlags_None as u32;
307        const NORMALIZE = sys::ImPlotPieChartFlags_Normalize as u32;
308        const IGNORE_HIDDEN = sys::ImPlotPieChartFlags_IgnoreHidden as u32;
309        const EXPLODING = sys::ImPlotPieChartFlags_Exploding as u32;
310        const NO_SLICE_BORDER = sys::ImPlotPieChartFlags_NoSliceBorder as u32;
311    }
312}
313
314bitflags::bitflags! {
315    /// Flags for line plots
316    pub struct LineFlags: u32 {
317        const NONE = sys::ImPlotLineFlags_None as u32;
318        const SEGMENTS = sys::ImPlotLineFlags_Segments as u32;
319        const LOOP = sys::ImPlotLineFlags_Loop as u32;
320        const SKIP_NAN = sys::ImPlotLineFlags_SkipNaN as u32;
321        const NO_CLIP = sys::ImPlotLineFlags_NoClip as u32;
322        const SHADED = sys::ImPlotLineFlags_Shaded as u32;
323    }
324}
325
326bitflags::bitflags! {
327    /// Flags for polygon plots
328    pub struct PolygonFlags: u32 {
329        const NONE = sys::ImPlotPolygonFlags_None as u32;
330        const CONCAVE = sys::ImPlotPolygonFlags_Concave as u32;
331    }
332}
333
334bitflags::bitflags! {
335    /// Flags for scatter plots
336    pub struct ScatterFlags: u32 {
337        const NONE = sys::ImPlotScatterFlags_None as u32;
338        const NO_CLIP = sys::ImPlotScatterFlags_NoClip as u32;
339    }
340}
341
342bitflags::bitflags! {
343    /// Flags for bar plots
344    pub struct BarsFlags: u32 {
345        const NONE = sys::ImPlotBarsFlags_None as u32;
346        const HORIZONTAL = sys::ImPlotBarsFlags_Horizontal as u32;
347    }
348}
349
350bitflags::bitflags! {
351    /// Flags for shaded plots
352    pub struct ShadedFlags: u32 {
353        const NONE = sys::ImPlotShadedFlags_None as u32;
354    }
355}
356
357bitflags::bitflags! {
358    /// Flags for stem plots
359    pub struct StemsFlags: u32 {
360        const NONE = sys::ImPlotStemsFlags_None as u32;
361        const HORIZONTAL = sys::ImPlotStemsFlags_Horizontal as u32;
362    }
363}
364
365bitflags::bitflags! {
366    /// Flags for error bar plots
367    pub struct ErrorBarsFlags: u32 {
368        const NONE = sys::ImPlotErrorBarsFlags_None as u32;
369        const HORIZONTAL = sys::ImPlotErrorBarsFlags_Horizontal as u32;
370    }
371}
372
373bitflags::bitflags! {
374    /// Flags for stairs plots
375    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
376    pub struct StairsFlags: u32 {
377        const NONE = sys::ImPlotStairsFlags_None as u32;
378        const PRE_STEP = sys::ImPlotStairsFlags_PreStep as u32;
379        const SHADED = sys::ImPlotStairsFlags_Shaded as u32;
380    }
381}
382
383bitflags::bitflags! {
384    /// Flags for bar groups plots
385    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
386    pub struct BarGroupsFlags: u32 {
387        const NONE = sys::ImPlotBarGroupsFlags_None as u32;
388        const HORIZONTAL = sys::ImPlotBarGroupsFlags_Horizontal as u32;
389        const STACKED = sys::ImPlotBarGroupsFlags_Stacked as u32;
390    }
391}
392
393bitflags::bitflags! {
394    /// Flags for digital plots
395    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
396    pub struct DigitalFlags: u32 {
397        const NONE = sys::ImPlotDigitalFlags_None as u32;
398    }
399}
400
401bitflags::bitflags! {
402    /// Flags for text plots
403    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
404    pub struct TextFlags: u32 {
405        const NONE = sys::ImPlotTextFlags_None as u32;
406        const VERTICAL = sys::ImPlotTextFlags_Vertical as u32;
407    }
408}
409
410bitflags::bitflags! {
411    /// Flags for dummy plots
412    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
413    pub struct DummyFlags: u32 {
414        const NONE = sys::ImPlotDummyFlags_None as u32;
415    }
416}
417
418bitflags::bitflags! {
419    /// Flags for drag tools (points/lines)
420    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
421    pub struct DragToolFlags: u32 {
422        const NONE = sys::ImPlotDragToolFlags_None as u32;
423        const NO_CURSORS = sys::ImPlotDragToolFlags_NoCursors as u32;
424        const NO_FIT = sys::ImPlotDragToolFlags_NoFit as u32;
425        const NO_INPUTS = sys::ImPlotDragToolFlags_NoInputs as u32;
426        const DELAYED = sys::ImPlotDragToolFlags_Delayed as u32;
427    }
428}
429
430bitflags::bitflags! {
431    /// Flags for infinite lines plots
432    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
433    pub struct InfLinesFlags: u32 {
434        const NONE = sys::ImPlotInfLinesFlags_None as u32;
435        const HORIZONTAL = sys::ImPlotInfLinesFlags_Horizontal as u32;
436    }
437}
438
439bitflags::bitflags! {
440    /// Flags for image plots
441    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
442    pub struct ImageFlags: u32 {
443        const NONE = sys::ImPlotImageFlags_None as u32;
444    }
445}
446
447bitflags::bitflags! {
448    /// Axis flags matching ImPlotAxisFlags_ (see cimplot.h)
449    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
450    pub struct AxisFlags: u32 {
451        const NONE           = sys::ImPlotAxisFlags_None as u32;
452        const NO_LABEL       = sys::ImPlotAxisFlags_NoLabel as u32;
453        const NO_GRID_LINES  = sys::ImPlotAxisFlags_NoGridLines as u32;
454        const NO_TICK_MARKS  = sys::ImPlotAxisFlags_NoTickMarks as u32;
455        const NO_TICK_LABELS = sys::ImPlotAxisFlags_NoTickLabels as u32;
456        const NO_INITIAL_FIT = sys::ImPlotAxisFlags_NoInitialFit as u32;
457        const NO_MENUS       = sys::ImPlotAxisFlags_NoMenus as u32;
458        const NO_SIDE_SWITCH = sys::ImPlotAxisFlags_NoSideSwitch as u32;
459        const NO_HIGHLIGHT   = sys::ImPlotAxisFlags_NoHighlight as u32;
460        const OPPOSITE       = sys::ImPlotAxisFlags_Opposite as u32;
461        const FOREGROUND     = sys::ImPlotAxisFlags_Foreground as u32;
462        const INVERT         = sys::ImPlotAxisFlags_Invert as u32;
463        const AUTO_FIT       = sys::ImPlotAxisFlags_AutoFit as u32;
464        const RANGE_FIT      = sys::ImPlotAxisFlags_RangeFit as u32;
465        const PAN_STRETCH    = sys::ImPlotAxisFlags_PanStretch as u32;
466        const LOCK_MIN       = sys::ImPlotAxisFlags_LockMin as u32;
467        const LOCK_MAX       = sys::ImPlotAxisFlags_LockMax as u32;
468    }
469}
470
471/// Plot condition (setup/next) matching ImPlotCond (ImGuiCond)
472#[derive(Clone, Copy, Debug, PartialEq, Eq)]
473#[repr(i32)]
474pub enum PlotCond {
475    None = 0,
476    Always = 1,
477    Once = 2,
478}
479
480// Re-export all plot types for convenience
481pub use plots::*;
482
483// Re-export advanced features (explicit to avoid AxisFlags name clash)
484pub use advanced::{
485    LegendFlags, LegendLocation, LegendManager, LegendToken, MultiAxisPlot, MultiAxisToken,
486    SubplotFlags, SubplotGrid, SubplotToken, YAxisConfig,
487};