dear_imgui/lib.rs
1//! # Dear ImGui - Rust Bindings with Docking Support
2//!
3//! High-level Rust bindings for Dear ImGui, the immediate mode GUI library.
4//! This crate provides safe, idiomatic Rust bindings with full support for
5//! docking and multi-viewport features.
6//!
7//! ## Features
8//!
9//! - Safe, idiomatic Rust API
10//! - Full docking and multi-viewport support
11//! - Builder pattern for widgets
12//! - Memory-safe string handling
13//! - Integration with modern Rust graphics ecosystems
14//!
15//! ## Quick Start
16//!
17//! ```no_run
18//! use dear_imgui::*;
19//!
20//! let mut ctx = Context::create();
21//! let ui = ctx.frame();
22//!
23//! ui.window("Hello World")
24//! .size([300.0, 100.0], Condition::FirstUseEver)
25//! .build(|| {
26//! ui.text("Hello, world!");
27//! ui.text("This is Dear ImGui with docking support!");
28//! });
29//! ```
30//!
31//! ## Math Interop (mint/glam)
32//!
33//! Many drawing and coordinate-taking APIs accept `impl Into<sys::ImVec2>` so you can pass:
34//! - `[f32; 2]` or `(f32, f32)`
35//! - `dear_imgui_sys::ImVec2`
36//! - `mint::Vector2<f32>` (via `dear-imgui-sys` conversions)
37//! - With optional integrations, `glam::Vec2` via your own `Into<ImVec2>`
38//!
39//! Example:
40//! ```no_run
41//! # use dear_imgui::*;
42//! # fn demo(ui: &Ui) {
43//! let dl = ui.get_window_draw_list();
44//! dl.add_line([0.0, 0.0], [100.0, 100.0], [1.0, 1.0, 1.0, 1.0]).build();
45//! // Also works with mint::Vector2<f32>
46//! let a = mint::Vector2 { x: 10.0, y: 20.0 };
47//! let b = mint::Vector2 { x: 30.0, y: 40.0 };
48//! dl.add_rect(a, b, [1.0, 0.0, 0.0, 1.0]).build();
49//! # }
50//! ```
51//!
52//! ## Textures (ImGui 1.92+)
53//!
54//! You can pass either a legacy `TextureId` or an ImGui-managed `TextureData` (preferred):
55//!
56//! ```no_run
57//! # use dear_imgui::*;
58//! # fn demo(ui: &Ui) {
59//! // 1) Legacy handle
60//! let tex_id = texture::TextureId::new(0x1234);
61//! ui.image(tex_id, [64.0, 64.0]);
62//!
63//! // 2) Managed texture (created/updated/destroyed via DrawData::textures())
64//! let mut tex = texture::TextureData::new();
65//! tex.create(texture::TextureFormat::RGBA32, 256, 256);
66//! // fill pixels / request updates ...
67//! ui.image(&mut tex, [256.0, 256.0]);
68//! # }
69//! ```
70//!
71//! Lifetime note: when using `&TextureData`, ensure it remains alive through rendering of the frame.
72//!
73//! ### Texture Management Guide
74//!
75//! - Concepts:
76//! - `TextureId`: legacy plain handle (e.g., GL texture name, Vk descriptor).
77//! - `TextureData`: managed CPU-side description with status flags and pixel buffer.
78//! - `TextureRef`: a small wrapper used by widgets/drawlist, constructed from either of the above.
79//! - Basic flow:
80//! 1. Create `TextureData` and call `create(format, w, h)` to allocate pixels.
81//! 2. Fill/modify pixels; call `set_status(WantCreate)` for initial upload, or `WantUpdates` with
82//! `UpdateRect` for sub-updates. `TextureData::set_data()` is a convenience which copies data and
83//! marks an update.
84//! 3. Use the texture in UI via `ui.image(&mut tex, size)` or drawlist APIs.
85//! 4. In your renderer, during `render()`, iterate `DrawData::textures()` and honor the requests
86//! (Create/Update/Destroy), then set status back to `OK`/`Destroyed`.
87//! - Alternatives: when you already have a GPU handle, pass `TextureId` directly.
88//!
89//! ## Renderer Integration (Modern Textures)
90//!
91//! When integrating a renderer backend (WGPU, OpenGL, etc.) with ImGui 1.92+:
92//! - Set `BackendFlags::RENDERER_HAS_TEXTURES` on the ImGui `Io` before building the font atlas.
93//! - Each frame, iterate `DrawData::textures()` and honor all requests:
94//! - `WantCreate`: create a GPU texture, upload pixels, assign a non-zero TexID back to ImGui, then set status to `OK`.
95//! - `WantUpdates`: upload pending `UpdateRect`s, then set status to `OK`.
96//! - `WantDestroy`: delete/free the GPU texture and set status to `Destroyed`.
97//! - When binding textures for draw commands, do not rely only on `DrawCmdParams.texture_id`.
98//! With the modern system it may be `0`. Resolve the effective id at bind time using
99//! `ImDrawCmd_GetTexID(raw_cmd)` along with your renderer state.
100//! - Optional: some backends perform a font-atlas fallback upload on initialization.
101//! This affects only the font texture for the first frame; user textures go through
102//! the modern `ImTextureData` path.
103//!
104//! Pseudocode outline:
105//! ```ignore
106//! // 1) Configure context
107//! io.backend_flags |= BackendFlags::RENDERER_HAS_TEXTURES;
108//!
109//! // 2) Per-frame: handle texture requests
110//! for tex in draw_data.textures() {
111//! match tex.status() {
112//! WantCreate => { create_gpu_tex(tex); tex.set_tex_id(id); tex.set_ok(); }
113//! WantUpdates => { upload_rects(tex); tex.set_ok(); }
114//! WantDestroy => { destroy_gpu_tex(tex); tex.set_destroyed(); }
115//! _ => {}
116//! }
117//! }
118//!
119//! // 3) Rendering: resolve texture at bind-time
120//! for cmd in draw_list.commands() {
121//! match cmd {
122//! Elements { cmd_params, raw_cmd, .. } => {
123//! let effective = unsafe { sys::ImDrawCmd_GetTexID(raw_cmd) };
124//! bind_texture(effective);
125//! draw(cmd_params);
126//! }
127//! _ => { /* ... */ }
128//! }
129//! }
130//! ```
131//!
132//! ## Colors (ImU32 ABGR)
133//!
134//! Dear ImGui uses a packed 32-bit color in ABGR order for low-level APIs (aka `ImU32`).
135//! When you need a packed color (e.g. `TableSetBgColor`), use `colors::Color::to_imgui_u32()`:
136//!
137//! ```no_run
138//! # use dear_imgui::*;
139//! # fn demo(ui: &Ui) {
140//! // Pack RGBA floats to ImGui ABGR (ImU32)
141//! let abgr = colors::Color::rgb(1.0, 0.0, 0.0).to_imgui_u32();
142//! ui.table_set_bg_color_u32(widget::TableBgTarget::CellBg, abgr, -1);
143//! # }
144//! ```
145//!
146//! For draw-list helpers you can continue to pass `[f32;4]` or use `draw::ImColor32` which
147//! represents the same ABGR packed value in a convenient wrapper.
148//!
149//! ## Text Input (String vs ImString)
150//!
151//! This crate offers two ways to edit text:
152//! - String-backed builders: `ui.input_text(label, &mut String)` and
153//! `ui.input_text_multiline(label, &mut String, size)`.
154//! - Internally stage a growable UTF‑8 buffer for the call and copy the
155//! edited bytes back into your `String` afterwards.
156//! - For very large fields, use `.capacity_hint(bytes)` on the builder to
157//! reduce reallocations, e.g.:
158//! ```no_run
159//! # use dear_imgui::*;
160//! # fn demo(ui: &Ui, big: &mut String) {
161//! ui.input_text("Big", big)
162//! .capacity_hint(64 * 1024)
163//! .build();
164//! # }
165//! ```
166//! - ImString-backed builders: `ui.input_text_imstr(label, &mut ImString)` and
167//! `ui.input_text_multiline_imstr(label, &mut ImString, size)`.
168//! - Zero‑copy: pass your `ImString` buffer directly to ImGui.
169//! - Uses ImGui's `CallbackResize` under the hood to grow the same buffer the
170//! widget edits — no copy before/after the call.
171//!
172//! Choose String for convenience (especially for small/medium inputs). Prefer
173//! ImString when you want to avoid copies for large or frequently edited text.
174
175//! ## Low-level Draw APIs
176//!
177//! Draw list wrappers expose both high-level primitives and some low-level building blocks:
178//!
179//! - Concave polygons (ImGui 1.92+):
180//! - `DrawListMut::add_concave_poly_filled(&[P], color)` fills an arbitrary concave polygon.
181//! - `DrawListMut::path_fill_concave(color)` fills the current path using the concave tessellator.
182//! - Note: requires Dear ImGui 1.92 or newer in `dear-imgui-sys`.
183//!
184//! - Channels splitting:
185//! - `DrawListMut::channels_split(count, |channels| { ... })` splits draw into multiple channels
186//! and automatically merges on scope exit. Call `channels.set_current(i)` to select a channel.
187//!
188//! - Clipping helpers:
189//! - `push_clip_rect`, `push_clip_rect_full_screen`, `pop_clip_rect`, `with_clip_rect`,
190//! `clip_rect_min`, `clip_rect_max`.
191//!
192//! - Unsafe prim API (for custom geometry):
193//! - `prim_reserve`, `prim_unreserve`, `prim_rect`, `prim_rect_uv`, `prim_quad_uv`,
194//! `prim_write_vtx`, `prim_write_idx`, `prim_vtx`.
195//! - Safety: these mirror ImGui's low-level geometry functions. Callers must respect vertex/index
196//! counts, write exactly the reserved amounts, and ensure valid topology. Prefer high-level
197//! helpers unless you need exact control.
198//!
199//! - Callbacks during draw:
200//! - Safe builder: `DrawListMut::add_callback_safe(|| { ... }).build()` registers an `FnOnce()`
201//! that runs when the draw list is rendered. Resources captured by the closure are freed when
202//! the callback runs. If the draw list is never rendered, the callback will not run and its
203//! resources won't be reclaimed.
204//! - Raw: `unsafe DrawListMut::add_callback` allows passing a C callback and raw userdata; see
205//! method docs for safety requirements.
206
207#![deny(rust_2018_idioms)]
208#![cfg_attr(test, allow(clippy::float_cmp))]
209#![allow(
210 clippy::cast_possible_truncation,
211 clippy::cast_sign_loss,
212 clippy::as_conversions
213)]
214
215// Re-export the sys crate for advanced users
216pub extern crate dear_imgui_sys as sys;
217
218/// Condition for setting window/widget properties
219#[derive(Debug, Copy, Clone, PartialEq, Eq)]
220#[repr(i32)]
221pub enum Condition {
222 /// Never apply the setting
223 Never = -1,
224 /// Set the variable always
225 Always = sys::ImGuiCond_Always as i32,
226 /// Set the variable once per runtime session (only the first call will succeed)
227 Once = sys::ImGuiCond_Once as i32,
228 /// Set the variable if the object/window has no persistently saved data (no entry in .ini file)
229 FirstUseEver = sys::ImGuiCond_FirstUseEver as i32,
230 /// Set the variable if the object/window is appearing after being hidden/inactive (or the first time)
231 Appearing = sys::ImGuiCond_Appearing as i32,
232}
233
234// use std::cell;
235// use std::os::raw::c_char;
236
237// Core modules
238pub use self::clipboard::{ClipboardBackend, DummyClipboardBackend};
239pub use self::context::*;
240// Note: draw types are now in render module
241pub use self::fonts::*;
242pub use self::input::*;
243pub use self::io::*;
244pub use self::platform_io::*;
245pub use self::string::*;
246pub use self::style::*;
247pub use self::ui::*;
248// Re-export utility flags/types for convenience
249pub use self::utils::HoveredFlags;
250
251// Utility modules
252pub use self::list_clipper::*;
253// pub use self::math::*;
254
255// Widget modules
256pub use self::widget::*;
257pub use self::window::*;
258
259// Stack management
260pub use self::stacks::*;
261
262// Layout and cursor control
263pub use self::layout::*;
264
265// Drag and drop system
266pub use self::drag_drop::*;
267
268// Text filtering system
269pub use self::text_filter::*;
270
271// Column layout system (included in layout module)
272pub use self::columns::*;
273
274// Internal modules
275mod clipboard;
276mod colors;
277mod context;
278mod dock_builder;
279mod dock_space;
280mod draw;
281mod error;
282mod fonts;
283pub mod input;
284pub mod internal;
285mod io;
286mod list_clipper;
287pub mod platform_io;
288pub mod render;
289mod string;
290mod style;
291pub mod texture;
292mod ui;
293mod utils;
294#[cfg(feature = "multi-viewport")]
295pub mod viewport_backend;
296// mod math;
297mod widget;
298mod window;
299
300// Token system for resource management
301#[macro_use]
302mod tokens;
303
304// Stack management
305mod stacks;
306
307// Layout and cursor control
308mod layout;
309
310// Drag and drop system
311mod drag_drop;
312
313// Text filtering system
314mod text_filter;
315
316// Column layout system
317mod columns;
318
319// Logging utilities
320pub mod logging;
321
322// Re-export public API
323pub use colors::*;
324pub use dock_builder::*;
325pub use dock_space::*;
326// Export DrawListMut for extensions
327pub use draw::DrawListMut;
328pub use error::*;
329// Note: draw types are now in render module, no need to export draw::*
330pub use render::*;
331pub use texture::*;
332
333// Version information
334pub const VERSION: &str = env!("CARGO_PKG_VERSION");
335
336/// Check if docking features are available
337pub const HAS_DOCKING: bool = sys::HAS_DOCKING;
338
339/// Check if FreeType font rasterizer support is compiled in
340pub const HAS_FREETYPE: bool = sys::HAS_FREETYPE;
341
342/// Check if WASM support is compiled in (sys layer)
343pub const HAS_WASM: bool = sys::HAS_WASM;
344
345/// Returns the underlying Dear ImGui library version
346#[doc(alias = "GetVersion")]
347pub fn dear_imgui_version() -> &'static str {
348 unsafe {
349 let version_ptr = sys::igGetVersion();
350
351 let bytes = std::ffi::CStr::from_ptr(version_ptr).to_bytes();
352 std::str::from_utf8_unchecked(bytes)
353 }
354}