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    scatter::{ScatterPlot, SimpleScatterPlot},
120    shaded::{ShadedBetweenPlot, ShadedPlot, SimpleShadedPlot},
121    stems::{SimpleStemPlot, StemPlot},
122};
123
124// Constants
125const IMPLOT_AUTO: i32 = -1;
126
127/// Choice of Y axis for multi-axis plots
128#[derive(Clone, Copy, Debug, PartialEq, Eq)]
129#[repr(u32)]
130pub enum YAxisChoice {
131    First = 0,
132    Second = 1,
133    Third = 2,
134}
135
136/// Convert an Option<YAxisChoice> into an i32. Picks IMPLOT_AUTO for None.
137fn y_axis_choice_option_to_i32(y_axis_choice: Option<YAxisChoice>) -> i32 {
138    match y_axis_choice {
139        Some(choice) => choice as i32,
140        None => IMPLOT_AUTO,
141    }
142}
143
144/// X axis selector matching ImPlot's ImAxis values
145#[derive(Clone, Copy, Debug, PartialEq, Eq)]
146#[repr(i32)]
147pub enum XAxis {
148    X1 = 0,
149    X2 = 1,
150    X3 = 2,
151}
152
153/// Y axis selector matching ImPlot's ImAxis values
154#[derive(Clone, Copy, Debug, PartialEq, Eq)]
155#[repr(i32)]
156pub enum YAxis {
157    Y1 = 3,
158    Y2 = 4,
159    Y3 = 5,
160}
161
162impl YAxis {
163    /// Convert a Y axis (Y1..Y3) to the 0-based index used by ImPlotPlot_YAxis_Nil
164    pub(crate) fn to_index(self) -> i32 {
165        (self as i32) - 3
166    }
167}
168
169/// Ui extension for obtaining a PlotUi from an ImPlot PlotContext
170pub trait ImPlotExt {
171    fn implot<'ui>(&'ui self, ctx: &'ui PlotContext) -> PlotUi<'ui>;
172}
173
174impl ImPlotExt for Ui {
175    fn implot<'ui>(&'ui self, ctx: &'ui PlotContext) -> PlotUi<'ui> {
176        ctx.get_plot_ui(self)
177    }
178}
179
180/// Markers for plot points
181#[repr(i32)]
182#[derive(Copy, Clone, Debug, PartialEq, Eq)]
183pub enum Marker {
184    None = sys::ImPlotMarker_None as i32,
185    Circle = sys::ImPlotMarker_Circle as i32,
186    Square = sys::ImPlotMarker_Square as i32,
187    Diamond = sys::ImPlotMarker_Diamond as i32,
188    Up = sys::ImPlotMarker_Up as i32,
189    Down = sys::ImPlotMarker_Down as i32,
190    Left = sys::ImPlotMarker_Left as i32,
191    Right = sys::ImPlotMarker_Right as i32,
192    Cross = sys::ImPlotMarker_Cross as i32,
193    Plus = sys::ImPlotMarker_Plus as i32,
194    Asterisk = sys::ImPlotMarker_Asterisk as i32,
195}
196
197/// Colorable plot elements
198#[repr(u32)]
199#[derive(Copy, Clone, Debug, PartialEq, Eq)]
200pub enum PlotColorElement {
201    FrameBg = sys::ImPlotCol_FrameBg as u32,
202    PlotBg = sys::ImPlotCol_PlotBg as u32,
203    PlotBorder = sys::ImPlotCol_PlotBorder as u32,
204    LegendBg = sys::ImPlotCol_LegendBg as u32,
205    LegendBorder = sys::ImPlotCol_LegendBorder as u32,
206    LegendText = sys::ImPlotCol_LegendText as u32,
207    TitleText = sys::ImPlotCol_TitleText as u32,
208    InlayText = sys::ImPlotCol_InlayText as u32,
209    AxisText = sys::ImPlotCol_AxisText as u32,
210    AxisGrid = sys::ImPlotCol_AxisGrid as u32,
211    AxisTick = sys::ImPlotCol_AxisTick as u32,
212    AxisBg = sys::ImPlotCol_AxisBg as u32,
213    AxisBgHovered = sys::ImPlotCol_AxisBgHovered as u32,
214    AxisBgActive = sys::ImPlotCol_AxisBgActive as u32,
215    Selection = sys::ImPlotCol_Selection as u32,
216    Crosshairs = sys::ImPlotCol_Crosshairs as u32,
217}
218
219/// Built-in colormaps
220#[repr(u32)]
221#[derive(Copy, Clone, Debug, PartialEq, Eq)]
222pub enum Colormap {
223    Deep = sys::ImPlotColormap_Deep as u32,
224    Dark = sys::ImPlotColormap_Dark as u32,
225    Pastel = sys::ImPlotColormap_Pastel as u32,
226    Paired = sys::ImPlotColormap_Paired as u32,
227    Viridis = sys::ImPlotColormap_Viridis as u32,
228    Plasma = sys::ImPlotColormap_Plasma as u32,
229    Hot = sys::ImPlotColormap_Hot as u32,
230    Cool = sys::ImPlotColormap_Cool as u32,
231    Pink = sys::ImPlotColormap_Pink as u32,
232    Jet = sys::ImPlotColormap_Jet as u32,
233}
234
235/// Plot location for legends, labels, etc.
236#[repr(u32)]
237#[derive(Copy, Clone, Debug, PartialEq, Eq)]
238pub enum PlotLocation {
239    Center = sys::ImPlotLocation_Center as u32,
240    North = sys::ImPlotLocation_North as u32,
241    South = sys::ImPlotLocation_South as u32,
242    West = sys::ImPlotLocation_West as u32,
243    East = sys::ImPlotLocation_East as u32,
244    NorthWest = sys::ImPlotLocation_NorthWest as u32,
245    NorthEast = sys::ImPlotLocation_NorthEast as u32,
246    SouthWest = sys::ImPlotLocation_SouthWest as u32,
247    SouthEast = sys::ImPlotLocation_SouthEast as u32,
248}
249
250/// Plot orientation
251#[repr(u32)]
252#[derive(Copy, Clone, Debug, PartialEq, Eq)]
253pub enum PlotOrientation {
254    Horizontal = 0,
255    Vertical = 1,
256}
257
258/// Binning methods for histograms
259#[repr(i32)]
260#[derive(Copy, Clone, Debug, PartialEq, Eq)]
261pub enum BinMethod {
262    Sqrt = -1,
263    Sturges = -2,
264    Rice = -3,
265    Scott = -4,
266}
267
268bitflags::bitflags! {
269    /// Flags for ANY `PlotX` function. Used by setting `ImPlotSpec::Flags`.
270    ///
271    /// These flags can be composed with the plot-type-specific flags (e.g. `LineFlags`).
272    #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
273    pub struct ItemFlags: u32 {
274        const NONE = sys::ImPlotItemFlags_None as u32;
275        const NO_LEGEND = sys::ImPlotItemFlags_NoLegend as u32;
276        const NO_FIT = sys::ImPlotItemFlags_NoFit as u32;
277    }
278}
279
280// Plot flags for different plot types
281bitflags::bitflags! {
282    /// Flags for heatmap plots
283    pub struct HeatmapFlags: u32 {
284        const NONE = sys::ImPlotHeatmapFlags_None as u32;
285        const COL_MAJOR = sys::ImPlotHeatmapFlags_ColMajor as u32;
286    }
287}
288
289bitflags::bitflags! {
290    /// Flags for histogram plots
291    pub struct HistogramFlags: u32 {
292        const NONE = sys::ImPlotHistogramFlags_None as u32;
293        const HORIZONTAL = sys::ImPlotHistogramFlags_Horizontal as u32;
294        const CUMULATIVE = sys::ImPlotHistogramFlags_Cumulative as u32;
295        const DENSITY = sys::ImPlotHistogramFlags_Density as u32;
296        const NO_OUTLIERS = sys::ImPlotHistogramFlags_NoOutliers as u32;
297        const COL_MAJOR = sys::ImPlotHistogramFlags_ColMajor as u32;
298    }
299}
300
301bitflags::bitflags! {
302    /// Flags for pie chart plots
303    pub struct PieChartFlags: u32 {
304        const NONE = sys::ImPlotPieChartFlags_None as u32;
305        const NORMALIZE = sys::ImPlotPieChartFlags_Normalize as u32;
306        const IGNORE_HIDDEN = sys::ImPlotPieChartFlags_IgnoreHidden as u32;
307        const EXPLODING = sys::ImPlotPieChartFlags_Exploding as u32;
308    }
309}
310
311bitflags::bitflags! {
312    /// Flags for line plots
313    pub struct LineFlags: u32 {
314        const NONE = sys::ImPlotLineFlags_None as u32;
315        const SEGMENTS = sys::ImPlotLineFlags_Segments as u32;
316        const LOOP = sys::ImPlotLineFlags_Loop as u32;
317        const SKIP_NAN = sys::ImPlotLineFlags_SkipNaN as u32;
318        const NO_CLIP = sys::ImPlotLineFlags_NoClip as u32;
319        const SHADED = sys::ImPlotLineFlags_Shaded as u32;
320    }
321}
322
323bitflags::bitflags! {
324    /// Flags for scatter plots
325    pub struct ScatterFlags: u32 {
326        const NONE = sys::ImPlotScatterFlags_None as u32;
327        const NO_CLIP = sys::ImPlotScatterFlags_NoClip as u32;
328    }
329}
330
331bitflags::bitflags! {
332    /// Flags for bar plots
333    pub struct BarsFlags: u32 {
334        const NONE = sys::ImPlotBarsFlags_None as u32;
335        const HORIZONTAL = sys::ImPlotBarsFlags_Horizontal as u32;
336    }
337}
338
339bitflags::bitflags! {
340    /// Flags for shaded plots
341    pub struct ShadedFlags: u32 {
342        const NONE = sys::ImPlotShadedFlags_None as u32;
343    }
344}
345
346bitflags::bitflags! {
347    /// Flags for stem plots
348    pub struct StemsFlags: u32 {
349        const NONE = sys::ImPlotStemsFlags_None as u32;
350        const HORIZONTAL = sys::ImPlotStemsFlags_Horizontal as u32;
351    }
352}
353
354bitflags::bitflags! {
355    /// Flags for error bar plots
356    pub struct ErrorBarsFlags: u32 {
357        const NONE = sys::ImPlotErrorBarsFlags_None as u32;
358        const HORIZONTAL = sys::ImPlotErrorBarsFlags_Horizontal as u32;
359    }
360}
361
362bitflags::bitflags! {
363    /// Flags for stairs plots
364    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
365    pub struct StairsFlags: u32 {
366        const NONE = sys::ImPlotStairsFlags_None as u32;
367        const PRE_STEP = sys::ImPlotStairsFlags_PreStep as u32;
368        const SHADED = sys::ImPlotStairsFlags_Shaded as u32;
369    }
370}
371
372bitflags::bitflags! {
373    /// Flags for bar groups plots
374    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
375    pub struct BarGroupsFlags: u32 {
376        const NONE = sys::ImPlotBarGroupsFlags_None as u32;
377        const HORIZONTAL = sys::ImPlotBarGroupsFlags_Horizontal as u32;
378        const STACKED = sys::ImPlotBarGroupsFlags_Stacked as u32;
379    }
380}
381
382bitflags::bitflags! {
383    /// Flags for digital plots
384    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
385    pub struct DigitalFlags: u32 {
386        const NONE = sys::ImPlotDigitalFlags_None as u32;
387    }
388}
389
390bitflags::bitflags! {
391    /// Flags for text plots
392    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
393    pub struct TextFlags: u32 {
394        const NONE = sys::ImPlotTextFlags_None as u32;
395        const VERTICAL = sys::ImPlotTextFlags_Vertical as u32;
396    }
397}
398
399bitflags::bitflags! {
400    /// Flags for dummy plots
401    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
402    pub struct DummyFlags: u32 {
403        const NONE = sys::ImPlotDummyFlags_None as u32;
404    }
405}
406
407bitflags::bitflags! {
408    /// Flags for drag tools (points/lines)
409    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
410    pub struct DragToolFlags: u32 {
411        const NONE = sys::ImPlotDragToolFlags_None as u32;
412        const NO_CURSORS = sys::ImPlotDragToolFlags_NoCursors as u32;
413        const NO_FIT = sys::ImPlotDragToolFlags_NoFit as u32;
414        const NO_INPUTS = sys::ImPlotDragToolFlags_NoInputs as u32;
415        const DELAYED = sys::ImPlotDragToolFlags_Delayed as u32;
416    }
417}
418
419bitflags::bitflags! {
420    /// Flags for infinite lines plots
421    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
422    pub struct InfLinesFlags: u32 {
423        const NONE = sys::ImPlotInfLinesFlags_None as u32;
424        const HORIZONTAL = sys::ImPlotInfLinesFlags_Horizontal as u32;
425    }
426}
427
428bitflags::bitflags! {
429    /// Flags for image plots
430    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
431    pub struct ImageFlags: u32 {
432        const NONE = sys::ImPlotImageFlags_None as u32;
433    }
434}
435
436bitflags::bitflags! {
437    /// Axis flags matching ImPlotAxisFlags_ (see cimplot.h)
438    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
439    pub struct AxisFlags: u32 {
440        const NONE           = sys::ImPlotAxisFlags_None as u32;
441        const NO_LABEL       = sys::ImPlotAxisFlags_NoLabel as u32;
442        const NO_GRID_LINES  = sys::ImPlotAxisFlags_NoGridLines as u32;
443        const NO_TICK_MARKS  = sys::ImPlotAxisFlags_NoTickMarks as u32;
444        const NO_TICK_LABELS = sys::ImPlotAxisFlags_NoTickLabels as u32;
445        const NO_INITIAL_FIT = sys::ImPlotAxisFlags_NoInitialFit as u32;
446        const NO_MENUS       = sys::ImPlotAxisFlags_NoMenus as u32;
447        const NO_SIDE_SWITCH = sys::ImPlotAxisFlags_NoSideSwitch as u32;
448        const NO_HIGHLIGHT   = sys::ImPlotAxisFlags_NoHighlight as u32;
449        const OPPOSITE       = sys::ImPlotAxisFlags_Opposite as u32;
450        const FOREGROUND     = sys::ImPlotAxisFlags_Foreground as u32;
451        const INVERT         = sys::ImPlotAxisFlags_Invert as u32;
452        const AUTO_FIT       = sys::ImPlotAxisFlags_AutoFit as u32;
453        const RANGE_FIT      = sys::ImPlotAxisFlags_RangeFit as u32;
454        const PAN_STRETCH    = sys::ImPlotAxisFlags_PanStretch as u32;
455        const LOCK_MIN       = sys::ImPlotAxisFlags_LockMin as u32;
456        const LOCK_MAX       = sys::ImPlotAxisFlags_LockMax as u32;
457    }
458}
459
460/// Plot condition (setup/next) matching ImPlotCond (ImGuiCond)
461#[derive(Clone, Copy, Debug, PartialEq, Eq)]
462#[repr(i32)]
463pub enum PlotCond {
464    None = 0,
465    Always = 1,
466    Once = 2,
467}
468
469// Re-export all plot types for convenience
470pub use plots::*;
471
472// Re-export advanced features (explicit to avoid AxisFlags name clash)
473pub use advanced::{
474    LegendFlags, LegendLocation, LegendManager, LegendToken, MultiAxisPlot, MultiAxisToken,
475    SubplotFlags, SubplotGrid, SubplotToken, YAxisConfig,
476};