Crate dear_imgui_rs

Crate dear_imgui_rs 

Source
Expand description

§Dear ImGui - Rust Bindings with Docking Support

High-level Rust bindings for Dear ImGui, the immediate mode GUI library. This crate provides safe, idiomatic Rust bindings with full support for docking and multi-viewport features.

§Features

  • Safe, idiomatic Rust API
  • Full docking and multi-viewport support
  • Builder pattern for widgets
  • Memory-safe string handling
  • Integration with modern Rust graphics ecosystems

§Quick Start

use dear_imgui_rs::*;

let mut ctx = Context::create();
let ui = ctx.frame();

ui.window("Hello World")
    .size([300.0, 100.0], Condition::FirstUseEver)
    .build(|| {
        ui.text("Hello, world!");
        ui.text("This is Dear ImGui with docking support!");
    });

§Math Interop (mint/glam)

Many drawing and coordinate-taking APIs accept impl Into<sys::ImVec2> so you can pass:

  • [f32; 2] or (f32, f32)
  • dear_imgui_sys::ImVec2
  • mint::Vector2<f32> (via dear-imgui-sys conversions)
  • With optional integrations, glam::Vec2 via your own Into<ImVec2>

Example:

let dl = ui.get_window_draw_list();
dl.add_line([0.0, 0.0], [100.0, 100.0], [1.0, 1.0, 1.0, 1.0]).build();
// Also works with mint::Vector2<f32>
let a = mint::Vector2 { x: 10.0, y: 20.0 };
let b = mint::Vector2 { x: 30.0, y: 40.0 };
dl.add_rect(a, b, [1.0, 0.0, 0.0, 1.0]).build();

§Textures (ImGui 1.92+)

You can pass either a legacy TextureId or an ImGui-managed TextureData (preferred):

// 1) Legacy handle
let tex_id = texture::TextureId::new(0x1234);
ui.image(tex_id, [64.0, 64.0]);

// 2) Managed texture (created/updated/destroyed via DrawData::textures())
let mut tex = texture::TextureData::new();
tex.create(texture::TextureFormat::RGBA32, 256, 256);
// fill pixels / request updates ...
ui.image(&mut *tex, [256.0, 256.0]);

Lifetime note: when using &TextureData, ensure it remains alive through rendering of the frame.

§Texture Management Guide

  • Concepts:
    • TextureId: legacy plain handle (e.g., GL texture name, Vk descriptor).
    • TextureData: managed CPU-side description with status flags and pixel buffer.
    • TextureRef: a small wrapper used by widgets/drawlist, constructed from either of the above.
  • Basic flow:
    1. Create TextureData and call create(format, w, h) to allocate pixels.
    2. Fill/modify pixels; call set_status(WantCreate) for initial upload, or WantUpdates with UpdateRect for sub-updates. TextureData::set_data() is a convenience which copies data and marks an update.
    3. Use the texture in UI via ui.image(&mut tex, size) or drawlist APIs.
    4. In your renderer, during render(), iterate DrawData::textures() and honor the requests (Create/Update/Destroy), then set status back to OK/Destroyed.
  • Alternatives: when you already have a GPU handle, pass TextureId directly.

§Renderer Integration (Modern Textures)

When integrating a renderer backend (WGPU, OpenGL, etc.) with ImGui 1.92+:

  • Set BackendFlags::RENDERER_HAS_TEXTURES on the ImGui Io before building the font atlas.
  • Each frame, iterate DrawData::textures() and honor all requests:
    • WantCreate: create a GPU texture, upload pixels, assign a non-zero TexID back to ImGui, then set status to OK.
    • WantUpdates: upload pending UpdateRects, then set status to OK.
    • WantDestroy: delete/free the GPU texture and set status to Destroyed.
  • When binding textures for draw commands, do not rely only on DrawCmdParams.texture_id. With the modern system it may be 0. Resolve the effective id at bind time using ImDrawCmd_GetTexID(raw_cmd) along with your renderer state.
  • Optional: some backends perform a font-atlas fallback upload on initialization. This affects only the font texture for the first frame; user textures go through the modern ImTextureData path.

Pseudocode outline:

// 1) Configure context
io.backend_flags |= BackendFlags::RENDERER_HAS_TEXTURES;

// 2) Per-frame: handle texture requests
for tex in draw_data.textures() {
    match tex.status() {
        WantCreate => { create_gpu_tex(tex); tex.set_tex_id(id); tex.set_ok(); }
        WantUpdates => { upload_rects(tex); tex.set_ok(); }
        WantDestroy => { destroy_gpu_tex(tex); tex.set_destroyed(); }
        _ => {}
    }
}

// 3) Rendering: resolve texture at bind-time
for cmd in draw_list.commands() {
    match cmd {
        Elements { cmd_params, raw_cmd, .. } => {
            let effective = unsafe { sys::ImDrawCmd_GetTexID(raw_cmd) };
            bind_texture(effective);
            draw(cmd_params);
        }
        _ => { /* ... */ }
    }
}

§Colors (ImU32 ABGR)

Dear ImGui uses a packed 32-bit color in ABGR order for low-level APIs (aka ImU32). When you need a packed color (e.g. TableSetBgColor), use colors::Color::to_imgui_u32():

// Pack RGBA floats to ImGui ABGR (ImU32)
let abgr = Color::rgb(1.0, 0.0, 0.0).to_imgui_u32();
ui.table_set_bg_color_u32(TableBgTarget::CellBg, abgr, -1);

For draw-list helpers you can continue to pass [f32;4] or use draw::ImColor32 which represents the same ABGR packed value in a convenient wrapper.

§Text Input (String vs ImString)

This crate offers two ways to edit text:

  • String-backed builders: ui.input_text(label, &mut String) and ui.input_text_multiline(label, &mut String, size).
    • Internally stage a growable UTF‑8 buffer for the call and copy the edited bytes back into your String afterwards.
    • For very large fields, use .capacity_hint(bytes) on the builder to reduce reallocations, e.g.:
      ui.input_text("Big", big)
          .capacity_hint(64 * 1024)
          .build();
  • ImString-backed builders: ui.input_text_imstr(label, &mut ImString) and ui.input_text_multiline_imstr(label, &mut ImString, size).
    • Zero‑copy: pass your ImString buffer directly to ImGui.
    • Uses ImGui’s CallbackResize under the hood to grow the same buffer the widget edits — no copy before/after the call.

Choose String for convenience (especially for small/medium inputs). Prefer ImString when you want to avoid copies for large or frequently edited text.

§Low-level Draw APIs

Draw list wrappers expose both high-level primitives and some low-level building blocks:

  • Concave polygons (ImGui 1.92+):

    • DrawListMut::add_concave_poly_filled(&[P], color) fills an arbitrary concave polygon.
    • DrawListMut::path_fill_concave(color) fills the current path using the concave tessellator.
    • Note: requires Dear ImGui 1.92 or newer in dear-imgui-sys.
  • Channels splitting:

    • DrawListMut::channels_split(count, |channels| { ... }) splits draw into multiple channels and automatically merges on scope exit. Call channels.set_current(i) to select a channel.
  • Clipping helpers:

    • push_clip_rect, push_clip_rect_full_screen, pop_clip_rect, with_clip_rect, clip_rect_min, clip_rect_max.
  • Unsafe prim API (for custom geometry):

    • prim_reserve, prim_unreserve, prim_rect, prim_rect_uv, prim_quad_uv, prim_write_vtx, prim_write_idx, prim_vtx.
    • Safety: these mirror ImGui’s low-level geometry functions. Callers must respect vertex/index counts, write exactly the reserved amounts, and ensure valid topology. Prefer high-level helpers unless you need exact control.
  • Callbacks during draw:

    • Safe builder: DrawListMut::add_callback_safe(|| { ... }).build() registers an FnOnce() that runs when the draw list is rendered. Resources captured by the closure are freed when the callback runs. If the draw list is never rendered, the callback will not run and its resources won’t be reclaimed.
    • Raw: unsafe DrawListMut::add_callback allows passing a C callback and raw userdata; see method docs for safety requirements.

Re-exports§

pub extern crate dear_imgui_sys as sys;

Re-exports§

pub use crate::Direction as ArrowDirection;
pub use self::input::*;
pub use self::platform_io::*;
pub use render::*;
pub use texture::*;

Modules§

atlas
Font atlas management for Dear ImGui v1.92+
button
Buttons
color
Color widgets
combo
Combo boxes
drag
Drag slider widgets for numeric input
font
Font runtime data and operations
glyph
Font glyph data structures
glyph_rangesDeprecated
Deprecated glyph ranges helpers.
image
Image widgets
input
Input types (mouse, keyboard, cursors)
internal
Internal low-level types
list_box
List boxes
logging
Logging utilities for Dear ImGui
menu
Menus and menu bars
misc
Miscellaneous widgets
platform_io
Platform IO functionality for Dear ImGui
plot
Basic plots
popup
Popups and modals
progress
Progress bars
render
Rendering system for Dear ImGui
selectable
Selectable items
slider
Sliders
tab
Tabs
table
Tables
text
Text helpers
texture
Texture management for Dear ImGui
tooltip
Tooltips
tree
Trees and collapsing headers

Macros§

create_token
This is a macro used internally by dear-imgui to create StackTokens representing various global state in Dear ImGui.
im_str
Creates an ImString from a string literal at compile time
imgui_debug
Macro for conditional debug logging
imgui_error
Macro for conditional error logging
imgui_info
Macro for conditional info logging
imgui_trace
Macro for conditional tracing
imgui_warn
Macro for conditional warning logging

Structs§

AngleSlider
Builder for an angle slider widget.
BackendFlags
Backend capabilities
Button
Builder for button widget
ButtonFlags
Flags for invisible buttons
ClipRectToken
Tracks a pushed clip rect that will be popped on drop.
Color
RGBA color with 32-bit floating point components
ColorButton
Builder for a color button widget
ColorEdit3
Builder for a 3-component color edit widget
ColorEdit4
Builder for a 4-component color edit widget
ColorEditFlags
Flags for color edit widgets
ColorPicker3
Builder for a 3-component color picker widget
ColorPicker4
Builder for a 4-component color picker widget
ColorStackToken
Tracks a color pushed to the color stack that can be popped by calling .end() or by dropping.
ColumnBuilder
Chainable builder for a single column. Use .done() to return to the table builder.
ComboBox
Builder for a combo box widget
ComboBoxFlags
Flags for combo box widgets
ComboBoxToken
Tracks a combo box that can be ended by calling .end() or by dropping
ConfigFlags
Configuration flags
Context
An imgui context.
DisabledToken
Tracks a disabled scope begun with Ui::begin_disabled and ended on drop.
DockBuilder
DockBuilder API for programmatic dock layout creation
DockFlags
Flags for dock nodes
DockNode
Opaque reference to an ImGui dock node, valid for the duration of the current frame.
DockNodeFlags
Flags for dock nodes
Drag
Builder for a drag slider widget
DragDropFlags
Flags for drag and drop operations
DragDropPayload
Raw payload data
DragDropPayloadEmpty
Empty payload (no data, just notification)
DragDropPayloadPod
Typed payload with data
DragDropSource
Builder for creating drag drop sources
DragDropSourceTooltip
Token representing an active drag source tooltip
DragDropTarget
Drag drop target for accepting payloads
DragRange
Builder for a drag range slider widget
DrawListMut
Object implementing the custom draw API.
DummyClipboardBackend
Non-functioning placeholder clipboard backend
FocusScopeToken
Tracks a pushed focus scope, popped on drop.
Font
A font instance with runtime data
FontAtlas
Font atlas that manages multiple fonts and their texture data
FontAtlasTexture
Handle to a font atlas texture
FontConfig
Font configuration for loading fonts with v1.92+ features
FontId
A font identifier
FontLoader
Font loader interface for custom font backends
FontLoaderFlags
Font loader flags for controlling font loading behavior
FontStackToken
Tracks a font pushed to the font stack that can be popped by calling .end() or by dropping.
Glyph
A single font glyph with its rendering data
GlyphRangesDeprecated
Predefined glyph ranges for common character sets
GlyphRangesBuilderDeprecated
Builder for creating custom glyph ranges
GroupToken
Tracks a layout group that can be ended with end or by dropping.
HoveredFlags
Flags for hovering detection
Id
Strongly-typed wrapper around ImGuiID.
IdStackToken
Tracks an ID pushed to the ID stack that can be popped by calling .pop() or by dropping. See crate::Ui::push_id for more details.
ImString
A UTF-8 encoded, growable, implicitly nul-terminated string.
Image
Builder for an image widget
ImageButton
Builder for an image button widget
InputDouble
Builder for double input widget
InputFloat
Builder for float input widget
InputFloat2
Builder for a 2-component float input widget.
InputFloat3
Builder for a 3-component float input widget.
InputFloat4
Builder for a 4-component float input widget.
InputInt
Builder for integer input widget
InputInt2
Builder for a 2-component int input widget.
InputInt3
Builder for a 3-component int input widget.
InputInt4
Builder for a 4-component int input widget.
InputScalar
Builder for an input scalar widget.
InputScalarN
Builder for an input scalar array widget.
InputText
Builder for a text input widget
InputTextCallback
Callback flags for InputText widgets
InputTextImStr
Builder for a text input backed by ImString (zero-copy)
InputTextMultiline
Builder for multiline text input widget
InputTextMultilineImStr
Builder for multiline text input backed by ImString (zero-copy)
InputTextMultilineWithCb
Multiline InputText with attached callback handler
Io
Settings and inputs/outputs for imgui-rs This is a transparent wrapper around ImGuiIO
ItemWidthStackToken
Tracks a change made with Ui::push_item_width that can be popped by calling ItemWidthStackToken::end or dropping.
ListBox
Builder for a list box widget
ListBoxToken
Tracks a list box that can be ended by calling .end() or by dropping
ListClipper
Used to render only the visible items when displaying a long list of items in a scrollable area.
ListClipperIterator
ListClipperToken
List clipper is a mechanism to efficiently implement scrolling of large lists with random access.
MainMenuBarToken
Tracks a main menu bar that can be ended by calling .end() or by dropping
MenuBarToken
Tracks a menu bar that can be ended by calling .end() or by dropping
MenuToken
Tracks a menu that can be ended by calling .end() or by dropping
ModalPopup
Builder for a modal popup
ModalPopupToken
Tracks a modal popup that can be ended by calling .end() or by dropping
NodeRect
Rectangle in screen space.
OldColumnFlags
Flags for old columns system
PassthroughCallback
This is a ZST which implements InputTextCallbackHandler as a passthrough.
PayloadIsWrongType
Error type for payload type mismatches
PlotHistogram
Builder for a plot histogram widget
PlotLines
Builder for a plot lines widget
PopupFlags
Flags for popup functions
PopupToken
Tracks a popup that can be ended by calling .end() or by dropping
ProgressBar
Builder for a progress bar widget.
Selectable
Builder for a selectable widget.
SelectableFlags
Flags for selectables
SharedFontAtlas
A shared font atlas that can be used across multiple contexts
Slider
Builder for slider widgets
SliderFlags
Flags for slider widgets
Style
User interface style/colors
StyleStackToken
Tracks a style pushed to the style stack that can be popped by calling .end() or by dropping.
SuspendedContext
A suspended Dear ImGui context
TabBar
Builder for a tab bar
TabBarFlags
Flags for tab bar widgets
TabBarToken
Token representing an active tab bar
TabItem
Builder for a tab item
TabItemFlags
Flags for tab item widgets
TabItemToken
Token representing an active tab item
TableBuilder
Builder for ImGui tables with columns + headers + sizing/freeze options.
TableColumnFlags
Flags for table columns
TableColumnSetup
Table column setup information
TableColumnSortSpec
One column sort spec.
TableFlags
Flags for table widgets
TableHeaderData
Safe description of a single angled header cell.
TableRowFlags
Flags for table rows
TableSortSpecs
Table sort specs view.
TableSortSpecsIter
Iterator over TableColumnSortSpec.
TableToken
Tracks a table that can be ended by calling .end() or by dropping
TextCallbackData
This struct provides methods to edit the underlying text buffer that Dear ImGui manipulates. Primarily, it gives remove_chars, insert_chars, and mutable access to what text is selected.
TextFilter
Helper to parse and apply text filters
TextWrapPosStackToken
Tracks a change made with Ui::push_text_wrap_pos that can be popped by calling TextWrapPosStackToken::end or dropping.
TooltipToken
Tracks a tooltip that can be ended by calling .end() or by dropping
TreeNode
Builder for a tree node widget
TreeNodeFlags
Flags for tree node widgets
TreeNodeToken
Tracks a tree node that can be popped by calling .pop() or by dropping
Ui
Represents the Dear ImGui user interface for one frame
UiBuffer
Internal buffer for UI string operations
VerticalSlider
Builder for a vertical slider widget.
Window
Represents a window that can be built
WindowClass
Window class for docking configuration
WindowFlags
Configuration flags for windows
WindowToken
Token representing an active window

Enums§

Condition
Condition for setting window/widget properties
Direction
A cardinal direction
FontSource
A source for font data with v1.92+ dynamic font support
HistoryDirection
Direction for history navigation
ImGuiError
Errors that can occur in Dear ImGui operations
SortDirection
Sorting direction for table columns.
SplitDirection
Direction for splitting dock nodes
StyleColor
Style color identifier
StyleVar
A temporary change in user interface style
TableBgTarget
Target for table background colors.
TreeNodeId
Tree node ID that can be constructed from different types

Constants§

HAS_DOCKING
Check if docking features are available
HAS_FREETYPE
Check if FreeType font rasterizer support is compiled in
HAS_WASM
Check if WASM support is compiled in (sys layer)
VERSION

Traits§

ClipboardBackend
Trait for clipboard backends
ImGuiPlatform
Trait for platform backends with unified error handling
ImGuiRenderer
Trait for backend renderers with unified error handling
InputTextCallbackHandler
This trait provides an interface which ImGui will call on InputText callbacks.
IntoImGuiError
Trait for converting backend errors to ImGuiError
SafeStringConversion
Helper trait for safe string conversion

Functions§

dear_imgui_version
Returns the underlying Dear ImGui library version

Type Aliases§

ImGuiResult
Result type for Dear ImGui operations
ImStr
Represents a borrowed string that can be either a Rust string slice or an ImString