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,
185    Circle = sys::ImPlotMarker_Circle,
186    Square = sys::ImPlotMarker_Square,
187    Diamond = sys::ImPlotMarker_Diamond,
188    Up = sys::ImPlotMarker_Up,
189    Down = sys::ImPlotMarker_Down,
190    Left = sys::ImPlotMarker_Left,
191    Right = sys::ImPlotMarker_Right,
192    Cross = sys::ImPlotMarker_Cross,
193    Plus = sys::ImPlotMarker_Plus,
194    Asterisk = sys::ImPlotMarker_Asterisk,
195}
196
197/// Colorable plot elements
198#[repr(u32)]
199#[derive(Copy, Clone, Debug, PartialEq, Eq)]
200pub enum PlotColorElement {
201    Line = sys::ImPlotCol_Line as u32,
202    Fill = sys::ImPlotCol_Fill as u32,
203    MarkerOutline = sys::ImPlotCol_MarkerOutline as u32,
204    MarkerFill = sys::ImPlotCol_MarkerFill as u32,
205    ErrorBar = sys::ImPlotCol_ErrorBar as u32,
206    FrameBg = sys::ImPlotCol_FrameBg as u32,
207    PlotBg = sys::ImPlotCol_PlotBg as u32,
208    PlotBorder = sys::ImPlotCol_PlotBorder as u32,
209    LegendBg = sys::ImPlotCol_LegendBg as u32,
210    LegendBorder = sys::ImPlotCol_LegendBorder as u32,
211    LegendText = sys::ImPlotCol_LegendText as u32,
212    TitleText = sys::ImPlotCol_TitleText as u32,
213    InlayText = sys::ImPlotCol_InlayText as u32,
214    AxisText = sys::ImPlotCol_AxisText as u32,
215    AxisGrid = sys::ImPlotCol_AxisGrid as u32,
216    AxisTick = sys::ImPlotCol_AxisTick as u32,
217    AxisBg = sys::ImPlotCol_AxisBg as u32,
218    AxisBgHovered = sys::ImPlotCol_AxisBgHovered as u32,
219    AxisBgActive = sys::ImPlotCol_AxisBgActive as u32,
220    Selection = sys::ImPlotCol_Selection as u32,
221    Crosshairs = sys::ImPlotCol_Crosshairs as u32,
222}
223
224/// Built-in colormaps
225#[repr(u32)]
226#[derive(Copy, Clone, Debug, PartialEq, Eq)]
227pub enum Colormap {
228    Deep = sys::ImPlotColormap_Deep as u32,
229    Dark = sys::ImPlotColormap_Dark as u32,
230    Pastel = sys::ImPlotColormap_Pastel as u32,
231    Paired = sys::ImPlotColormap_Paired as u32,
232    Viridis = sys::ImPlotColormap_Viridis as u32,
233    Plasma = sys::ImPlotColormap_Plasma as u32,
234    Hot = sys::ImPlotColormap_Hot as u32,
235    Cool = sys::ImPlotColormap_Cool as u32,
236    Pink = sys::ImPlotColormap_Pink as u32,
237    Jet = sys::ImPlotColormap_Jet as u32,
238}
239
240/// Plot location for legends, labels, etc.
241#[repr(u32)]
242#[derive(Copy, Clone, Debug, PartialEq, Eq)]
243pub enum PlotLocation {
244    Center = sys::ImPlotLocation_Center as u32,
245    North = sys::ImPlotLocation_North as u32,
246    South = sys::ImPlotLocation_South as u32,
247    West = sys::ImPlotLocation_West as u32,
248    East = sys::ImPlotLocation_East as u32,
249    NorthWest = sys::ImPlotLocation_NorthWest as u32,
250    NorthEast = sys::ImPlotLocation_NorthEast as u32,
251    SouthWest = sys::ImPlotLocation_SouthWest as u32,
252    SouthEast = sys::ImPlotLocation_SouthEast as u32,
253}
254
255/// Plot orientation
256#[repr(u32)]
257#[derive(Copy, Clone, Debug, PartialEq, Eq)]
258pub enum PlotOrientation {
259    Horizontal = 0,
260    Vertical = 1,
261}
262
263/// Binning methods for histograms
264#[repr(i32)]
265#[derive(Copy, Clone, Debug, PartialEq, Eq)]
266pub enum BinMethod {
267    Sqrt = -1,
268    Sturges = -2,
269    Rice = -3,
270    Scott = -4,
271}
272
273// Plot flags for different plot types
274bitflags::bitflags! {
275    /// Flags for heatmap plots
276    pub struct HeatmapFlags: u32 {
277        const NONE = sys::ImPlotHeatmapFlags_None as u32;
278        const COL_MAJOR = sys::ImPlotHeatmapFlags_ColMajor as u32;
279    }
280}
281
282bitflags::bitflags! {
283    /// Flags for histogram plots
284    pub struct HistogramFlags: u32 {
285        const NONE = sys::ImPlotHistogramFlags_None as u32;
286        const HORIZONTAL = sys::ImPlotHistogramFlags_Horizontal as u32;
287        const CUMULATIVE = sys::ImPlotHistogramFlags_Cumulative as u32;
288        const DENSITY = sys::ImPlotHistogramFlags_Density as u32;
289        const NO_OUTLIERS = sys::ImPlotHistogramFlags_NoOutliers as u32;
290        const COL_MAJOR = sys::ImPlotHistogramFlags_ColMajor as u32;
291    }
292}
293
294bitflags::bitflags! {
295    /// Flags for pie chart plots
296    pub struct PieChartFlags: u32 {
297        const NONE = sys::ImPlotPieChartFlags_None as u32;
298        const NORMALIZE = sys::ImPlotPieChartFlags_Normalize as u32;
299        const IGNORE_HIDDEN = sys::ImPlotPieChartFlags_IgnoreHidden as u32;
300        const EXPLODING = sys::ImPlotPieChartFlags_Exploding as u32;
301    }
302}
303
304bitflags::bitflags! {
305    /// Flags for line plots
306    pub struct LineFlags: u32 {
307        const NONE = sys::ImPlotLineFlags_None as u32;
308        const SEGMENTS = sys::ImPlotLineFlags_Segments as u32;
309        const LOOP = sys::ImPlotLineFlags_Loop as u32;
310        const SKIP_NAN = sys::ImPlotLineFlags_SkipNaN as u32;
311        const NO_CLIP = sys::ImPlotLineFlags_NoClip as u32;
312        const SHADED = sys::ImPlotLineFlags_Shaded as u32;
313    }
314}
315
316bitflags::bitflags! {
317    /// Flags for scatter plots
318    pub struct ScatterFlags: u32 {
319        const NONE = sys::ImPlotScatterFlags_None as u32;
320        const NO_CLIP = sys::ImPlotScatterFlags_NoClip as u32;
321    }
322}
323
324bitflags::bitflags! {
325    /// Flags for bar plots
326    pub struct BarsFlags: u32 {
327        const NONE = sys::ImPlotBarsFlags_None as u32;
328        const HORIZONTAL = sys::ImPlotBarsFlags_Horizontal as u32;
329    }
330}
331
332bitflags::bitflags! {
333    /// Flags for shaded plots
334    pub struct ShadedFlags: u32 {
335        const NONE = sys::ImPlotShadedFlags_None as u32;
336    }
337}
338
339bitflags::bitflags! {
340    /// Flags for stem plots
341    pub struct StemsFlags: u32 {
342        const NONE = sys::ImPlotStemsFlags_None as u32;
343        const HORIZONTAL = sys::ImPlotStemsFlags_Horizontal as u32;
344    }
345}
346
347bitflags::bitflags! {
348    /// Flags for error bar plots
349    pub struct ErrorBarsFlags: u32 {
350        const NONE = sys::ImPlotErrorBarsFlags_None as u32;
351        const HORIZONTAL = sys::ImPlotErrorBarsFlags_Horizontal as u32;
352    }
353}
354
355bitflags::bitflags! {
356    /// Flags for stairs plots
357    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
358    pub struct StairsFlags: u32 {
359        const NONE = sys::ImPlotStairsFlags_None as u32;
360        const PRE_STEP = sys::ImPlotStairsFlags_PreStep as u32;
361        const SHADED = sys::ImPlotStairsFlags_Shaded as u32;
362    }
363}
364
365bitflags::bitflags! {
366    /// Flags for bar groups plots
367    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
368    pub struct BarGroupsFlags: u32 {
369        const NONE = sys::ImPlotBarGroupsFlags_None as u32;
370        const HORIZONTAL = sys::ImPlotBarGroupsFlags_Horizontal as u32;
371        const STACKED = sys::ImPlotBarGroupsFlags_Stacked as u32;
372    }
373}
374
375bitflags::bitflags! {
376    /// Flags for digital plots
377    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
378    pub struct DigitalFlags: u32 {
379        const NONE = sys::ImPlotDigitalFlags_None as u32;
380    }
381}
382
383bitflags::bitflags! {
384    /// Flags for text plots
385    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
386    pub struct TextFlags: u32 {
387        const NONE = sys::ImPlotTextFlags_None as u32;
388        const VERTICAL = sys::ImPlotTextFlags_Vertical as u32;
389    }
390}
391
392bitflags::bitflags! {
393    /// Flags for dummy plots
394    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
395    pub struct DummyFlags: u32 {
396        const NONE = sys::ImPlotDummyFlags_None as u32;
397    }
398}
399
400bitflags::bitflags! {
401    /// Flags for drag tools (points/lines)
402    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
403    pub struct DragToolFlags: u32 {
404        const NONE = sys::ImPlotDragToolFlags_None as u32;
405        const NO_CURSORS = sys::ImPlotDragToolFlags_NoCursors as u32;
406        const NO_FIT = sys::ImPlotDragToolFlags_NoFit as u32;
407        const NO_INPUTS = sys::ImPlotDragToolFlags_NoInputs as u32;
408        const DELAYED = sys::ImPlotDragToolFlags_Delayed as u32;
409    }
410}
411
412bitflags::bitflags! {
413    /// Flags for infinite lines plots
414    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
415    pub struct InfLinesFlags: u32 {
416        const NONE = sys::ImPlotInfLinesFlags_None as u32;
417        const HORIZONTAL = sys::ImPlotInfLinesFlags_Horizontal as u32;
418    }
419}
420
421bitflags::bitflags! {
422    /// Flags for image plots
423    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
424    pub struct ImageFlags: u32 {
425        const NONE = sys::ImPlotImageFlags_None as u32;
426    }
427}
428
429bitflags::bitflags! {
430    /// Axis flags matching ImPlotAxisFlags_ (see cimplot.h)
431    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
432    pub struct AxisFlags: u32 {
433        const NONE           = sys::ImPlotAxisFlags_None as u32;
434        const NO_LABEL       = sys::ImPlotAxisFlags_NoLabel as u32;
435        const NO_GRID_LINES  = sys::ImPlotAxisFlags_NoGridLines as u32;
436        const NO_TICK_MARKS  = sys::ImPlotAxisFlags_NoTickMarks as u32;
437        const NO_TICK_LABELS = sys::ImPlotAxisFlags_NoTickLabels as u32;
438        const NO_INITIAL_FIT = sys::ImPlotAxisFlags_NoInitialFit as u32;
439        const NO_MENUS       = sys::ImPlotAxisFlags_NoMenus as u32;
440        const NO_SIDE_SWITCH = sys::ImPlotAxisFlags_NoSideSwitch as u32;
441        const NO_HIGHLIGHT   = sys::ImPlotAxisFlags_NoHighlight as u32;
442        const OPPOSITE       = sys::ImPlotAxisFlags_Opposite as u32;
443        const FOREGROUND     = sys::ImPlotAxisFlags_Foreground as u32;
444        const INVERT         = sys::ImPlotAxisFlags_Invert as u32;
445        const AUTO_FIT       = sys::ImPlotAxisFlags_AutoFit as u32;
446        const RANGE_FIT      = sys::ImPlotAxisFlags_RangeFit as u32;
447        const PAN_STRETCH    = sys::ImPlotAxisFlags_PanStretch as u32;
448        const LOCK_MIN       = sys::ImPlotAxisFlags_LockMin as u32;
449        const LOCK_MAX       = sys::ImPlotAxisFlags_LockMax as u32;
450    }
451}
452
453/// Plot condition (setup/next) matching ImPlotCond (ImGuiCond)
454#[derive(Clone, Copy, Debug, PartialEq, Eq)]
455#[repr(i32)]
456pub enum PlotCond {
457    None = 0,
458    Always = 1,
459    Once = 2,
460}
461
462// Re-export all plot types for convenience
463pub use plots::*;
464
465// Re-export advanced features (explicit to avoid AxisFlags name clash)
466pub use advanced::{
467    LegendFlags, LegendLocation, LegendManager, LegendToken, MultiAxisPlot, MultiAxisToken,
468    SubplotFlags, SubplotGrid, SubplotToken, YAxisConfig,
469};