dear-imgui-rs 0.12.0

High-level Rust bindings to Dear ImGui v1.92.7 with docking, WGPU/GL backends, and extensions (ImPlot/ImPlot3D, ImNodes, ImGuizmo, file browser, reflection-based UI)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
#![allow(
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss,
    clippy::as_conversions,
    // We intentionally keep explicit casts for FFI clarity; avoid auto-fix churn.
    clippy::unnecessary_cast
)]
//! Drag and Drop functionality for Dear ImGui
//!
//! This module provides a complete drag and drop system that allows users to transfer
//! data between UI elements. The system consists of drag sources and drop targets,
//! with type-safe payload management.
//!
//! # Basic Usage
//!
//! ```no_run
//! # use dear_imgui_rs::*;
//! # let mut ctx = Context::create();
//! # let ui = ctx.frame();
//! // Create a drag source
//! ui.button("Drag me!");
//! if let Some(source) = ui.drag_drop_source_config("MY_DATA").begin() {
//!     ui.text("Dragging...");
//!     source.end();
//! }
//!
//! // Create a drop target
//! ui.button("Drop here!");
//! if let Some(target) = ui.drag_drop_target() {
//!     if target.accept_payload_empty("MY_DATA", DragDropFlags::empty()).is_some() {
//!         println!("Data dropped!");
//!     }
//!     target.pop();
//! }
//! ```

use crate::{Ui, sys};

/// Condition for updating a drag and drop payload.
///
/// Dear ImGui only accepts `Always` and `Once` for `SetDragDropPayload`.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[repr(i32)]
#[allow(clippy::unnecessary_cast)]
pub enum DragDropPayloadCond {
    /// Update the payload every frame while dragging.
    Always = sys::ImGuiCond_Always as i32,
    /// Update the payload once when the drag starts.
    Once = sys::ImGuiCond_Once as i32,
}
use std::{any, ffi};

bitflags::bitflags! {
    /// Flags for drag and drop operations
    #[repr(transparent)]
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    pub struct DragDropFlags: u32 {
        /// No flags
        const NONE = 0;

        // Source flags
        /// Disable preview tooltip during drag
        const SOURCE_NO_PREVIEW_TOOLTIP = sys::ImGuiDragDropFlags_SourceNoPreviewTooltip as u32;
        /// Don't disable hover during drag
        const SOURCE_NO_DISABLE_HOVER = sys::ImGuiDragDropFlags_SourceNoDisableHover as u32;
        /// Don't open tree nodes/headers when hovering during drag
        const SOURCE_NO_HOLD_TO_OPEN_OTHERS = sys::ImGuiDragDropFlags_SourceNoHoldToOpenOthers as u32;
        /// Allow items without unique ID to be drag sources
        const SOURCE_ALLOW_NULL_ID = sys::ImGuiDragDropFlags_SourceAllowNullID as u32;
        /// External drag source (from outside ImGui)
        const SOURCE_EXTERN = sys::ImGuiDragDropFlags_SourceExtern as u32;
        /// Automatically expire payload if source stops being submitted
        const PAYLOAD_AUTO_EXPIRE = sys::ImGuiDragDropFlags_PayloadAutoExpire as u32;

        // Target flags
        /// Accept payload before mouse button is released
        const ACCEPT_BEFORE_DELIVERY = sys::ImGuiDragDropFlags_AcceptBeforeDelivery as u32;
        /// Don't draw default highlight rectangle when hovering
        const ACCEPT_NO_DRAW_DEFAULT_RECT = sys::ImGuiDragDropFlags_AcceptNoDrawDefaultRect as u32;
        /// Don't show preview tooltip from source
        const ACCEPT_NO_PREVIEW_TOOLTIP = sys::ImGuiDragDropFlags_AcceptNoPreviewTooltip as u32;
        /// Render accepting target as hovered (e.g. allow Button() as drop target)
        const ACCEPT_DRAW_AS_HOVERED = sys::ImGuiDragDropFlags_AcceptDrawAsHovered as u32;
        /// Convenience flag for peeking (ACCEPT_BEFORE_DELIVERY | ACCEPT_NO_DRAW_DEFAULT_RECT)
        const ACCEPT_PEEK_ONLY = sys::ImGuiDragDropFlags_AcceptPeekOnly as u32;
    }
}

impl Ui {
    /// Creates a new drag drop source configuration
    ///
    /// # Arguments
    /// * `name` - Identifier for this drag source (must match target name)
    ///
    /// # Example
    /// ```no_run
    /// # use dear_imgui_rs::*;
    /// # let mut ctx = Context::create();
    /// # let ui = ctx.frame();
    /// ui.button("Drag me!");
    /// if let Some(source) = ui.drag_drop_source_config("MY_DATA")
    ///     .flags(DragDropFlags::SOURCE_NO_PREVIEW_TOOLTIP)
    ///     .begin() {
    ///     ui.text("Custom drag tooltip");
    ///     source.end();
    /// }
    /// ```
    pub fn drag_drop_source_config<T: AsRef<str>>(&self, name: T) -> DragDropSource<'_, T> {
        DragDropSource {
            name,
            flags: DragDropFlags::NONE,
            cond: DragDropPayloadCond::Always,
            ui: self,
        }
    }

    /// Creates a drag drop target for the last item
    ///
    /// Returns `Some(DragDropTarget)` if the last item can accept drops,
    /// `None` otherwise.
    ///
    /// # Example
    /// ```no_run
    /// # use dear_imgui_rs::*;
    /// # let mut ctx = Context::create();
    /// # let ui = ctx.frame();
    /// ui.button("Drop target");
    /// if let Some(target) = ui.drag_drop_target() {
    ///     if target.accept_payload_empty("MY_DATA", DragDropFlags::NONE).is_some() {
    ///         println!("Received drop!");
    ///     }
    ///     target.pop();
    /// }
    /// ```
    #[doc(alias = "BeginDragDropTarget")]
    pub fn drag_drop_target(&self) -> Option<DragDropTarget<'_>> {
        let should_begin = unsafe { sys::igBeginDragDropTarget() };
        if should_begin {
            Some(DragDropTarget(self))
        } else {
            None
        }
    }

    /// Returns the current drag and drop payload, if any.
    ///
    /// This is a convenience wrapper over `ImGui::GetDragDropPayload`.
    ///
    /// The returned payload is owned and managed by Dear ImGui and may become invalid
    /// after the drag operation completes. Do not cache it beyond the current frame.
    #[doc(alias = "GetDragDropPayload")]
    pub fn drag_drop_payload(&self) -> Option<DragDropPayload> {
        unsafe {
            let ptr = sys::igGetDragDropPayload();
            if ptr.is_null() {
                return None;
            }
            let inner = *ptr;
            let size = if inner.DataSize <= 0 || inner.Data.is_null() {
                0
            } else {
                inner.DataSize as usize
            };
            Some(DragDropPayload {
                data: inner.Data,
                size,
                preview: inner.Preview,
                delivery: inner.Delivery,
            })
        }
    }
}

/// Builder for creating drag drop sources
///
/// This struct is created by [`Ui::drag_drop_source_config`] and provides
/// a fluent interface for configuring drag sources.
#[derive(Debug)]
pub struct DragDropSource<'ui, T> {
    name: T,
    flags: DragDropFlags,
    cond: DragDropPayloadCond,
    ui: &'ui Ui,
}

impl<'ui, T: AsRef<str>> DragDropSource<'ui, T> {
    /// Set flags for this drag source
    ///
    /// # Arguments
    /// * `flags` - Combination of source-related `DragDropFlags`
    #[inline]
    pub fn flags(mut self, flags: DragDropFlags) -> Self {
        self.flags = flags;
        self
    }

    /// Set condition for when to update the payload
    ///
    /// # Arguments
    /// * `cond` - When to update the payload data
    #[inline]
    pub fn condition(mut self, cond: DragDropPayloadCond) -> Self {
        self.cond = cond;
        self
    }

    /// Begin drag source with empty payload
    ///
    /// This is the safest option for simple drag and drop operations.
    /// Use shared state or other mechanisms to transfer actual data.
    ///
    /// Returns a tooltip token if dragging started, `None` otherwise.
    #[inline]
    pub fn begin(self) -> Option<DragDropSourceTooltip<'ui>> {
        self.begin_payload(())
    }

    /// Begin drag source with typed payload
    ///
    /// The payload data will be copied and managed by ImGui.
    /// The data must be `Copy + 'static` for safety.
    ///
    /// # Arguments
    /// * `payload` - Data to transfer (must be Copy + 'static)
    ///
    /// Returns a tooltip token if dragging started, `None` otherwise.
    #[inline]
    pub fn begin_payload<P: Copy + 'static>(
        self,
        payload: P,
    ) -> Option<DragDropSourceTooltip<'ui>> {
        unsafe {
            let payload = make_typed_payload(payload);
            self.begin_payload_unchecked(
                &payload as *const _ as *const ffi::c_void,
                std::mem::size_of::<TypedPayload<P>>(),
            )
        }
    }

    /// Begin drag source with raw payload data (unsafe)
    ///
    /// # Safety
    /// The caller must ensure:
    /// - `ptr` points to valid data of `size` bytes
    /// - The data remains valid for the duration of the drag operation
    /// - The data layout matches what targets expect
    ///
    /// # Arguments
    /// * `ptr` - Pointer to payload data
    /// * `size` - Size of payload data in bytes
    pub unsafe fn begin_payload_unchecked(
        &self,
        ptr: *const ffi::c_void,
        size: usize,
    ) -> Option<DragDropSourceTooltip<'ui>> {
        unsafe {
            let should_begin = sys::igBeginDragDropSource(self.flags.bits() as i32);

            if should_begin {
                sys::igSetDragDropPayload(
                    self.ui.scratch_txt(&self.name),
                    ptr,
                    size,
                    self.cond as i32,
                );

                Some(DragDropSourceTooltip::new(self.ui))
            } else {
                None
            }
        }
    }
}

/// Token representing an active drag source tooltip
///
/// While this token exists, you can add UI elements that will be shown
/// as a tooltip during the drag operation.
#[derive(Debug)]
pub struct DragDropSourceTooltip<'ui> {
    _ui: &'ui Ui,
}

impl<'ui> DragDropSourceTooltip<'ui> {
    fn new(ui: &'ui Ui) -> Self {
        Self { _ui: ui }
    }

    /// End the drag source tooltip manually
    ///
    /// This is called automatically when the token is dropped.
    pub fn end(self) {
        // Drop will handle cleanup
    }
}

impl Drop for DragDropSourceTooltip<'_> {
    fn drop(&mut self) {
        unsafe {
            sys::igEndDragDropSource();
        }
    }
}

/// Drag drop target for accepting payloads
///
/// This struct is created by [`Ui::drag_drop_target`] and provides
/// methods for accepting different types of payloads.
#[derive(Debug)]
pub struct DragDropTarget<'ui>(&'ui Ui);

impl<'ui> DragDropTarget<'ui> {
    /// Accept an empty payload
    ///
    /// This is the safest option for drag and drop operations.
    /// Use this when you only need to know that a drop occurred,
    /// not transfer actual data.
    ///
    /// # Arguments
    /// * `name` - Payload type name (must match source name)
    /// * `flags` - Accept flags
    ///
    /// Returns payload info if accepted, `None` otherwise.
    pub fn accept_payload_empty(
        &self,
        name: impl AsRef<str>,
        flags: DragDropFlags,
    ) -> Option<DragDropPayloadEmpty> {
        self.accept_payload(name, flags)?
            .ok()
            .map(|payload_pod: DragDropPayloadPod<()>| DragDropPayloadEmpty {
                preview: payload_pod.preview,
                delivery: payload_pod.delivery,
            })
    }

    /// Accept a typed payload
    ///
    /// Attempts to accept a payload with the specified type.
    /// Returns `Ok(payload)` if the type matches, `Err(PayloadIsWrongType)` if not.
    ///
    /// # Arguments
    /// * `name` - Payload type name (must match source name)
    /// * `flags` - Accept flags
    ///
    /// Returns `Some(Result<payload, error>)` if payload exists, `None` otherwise.
    pub fn accept_payload<T: 'static + Copy, Name: AsRef<str>>(
        &self,
        name: Name,
        flags: DragDropFlags,
    ) -> Option<Result<DragDropPayloadPod<T>, PayloadIsWrongType>> {
        let output = unsafe { self.accept_payload_unchecked(name, flags) };

        output.map(|payload| {
            if payload.data.is_null() || payload.size < std::mem::size_of::<TypedPayload<T>>() {
                return Err(PayloadIsWrongType);
            }

            // Dear ImGui stores payload data in an unaligned byte buffer, so always read unaligned.
            let typed_payload: TypedPayload<T> =
                unsafe { std::ptr::read_unaligned(payload.data as *const TypedPayload<T>) };

            if typed_payload.type_id == any::TypeId::of::<T>() {
                Ok(DragDropPayloadPod {
                    data: typed_payload.data,
                    preview: payload.preview,
                    delivery: payload.delivery,
                })
            } else {
                Err(PayloadIsWrongType)
            }
        })
    }

    /// Accept raw payload data (unsafe)
    ///
    /// # Safety
    /// The returned pointer and size are managed by ImGui and may become
    /// invalid at any time. The caller must not access the data after
    /// the drag operation completes.
    ///
    /// # Arguments
    /// * `name` - Payload type name
    /// * `flags` - Accept flags
    pub unsafe fn accept_payload_unchecked(
        &self,
        name: impl AsRef<str>,
        flags: DragDropFlags,
    ) -> Option<DragDropPayload> {
        let inner =
            unsafe { sys::igAcceptDragDropPayload(self.0.scratch_txt(name), flags.bits() as i32) };

        if inner.is_null() {
            None
        } else {
            let inner = unsafe { *inner };
            let size = if inner.DataSize <= 0 || inner.Data.is_null() {
                0
            } else {
                inner.DataSize as usize
            };
            Some(DragDropPayload {
                data: inner.Data,
                size,
                preview: inner.Preview,
                delivery: inner.Delivery,
            })
        }
    }

    /// End the drag drop target
    ///
    /// This is called automatically when the token is dropped.
    pub fn pop(self) {
        // Drop will handle cleanup
    }
}

impl Drop for DragDropTarget<'_> {
    fn drop(&mut self) {
        unsafe {
            sys::igEndDragDropTarget();
        }
    }
}

// Payload types and utilities

/// Wrapper for typed payloads with runtime type checking.
///
/// Important: payload memory is copied and stored by Dear ImGui in an unaligned byte buffer.
/// Never take `&TypedPayload<T>` from the raw pointer returned by `AcceptDragDropPayload()`.
/// Always copy out using `ptr::read_unaligned`.
#[repr(C)]
#[derive(Copy, Clone)]
struct TypedPayload<T: Copy> {
    type_id: any::TypeId,
    data: T,
}

fn make_typed_payload<T: Copy + 'static>(data: T) -> TypedPayload<T> {
    // Ensure we do not pass uninitialized padding bytes across the C++ boundary.
    let mut out = std::mem::MaybeUninit::<TypedPayload<T>>::zeroed();
    unsafe {
        let ptr = out.as_mut_ptr();
        std::ptr::addr_of_mut!((*ptr).type_id).write(any::TypeId::of::<T>());
        std::ptr::addr_of_mut!((*ptr).data).write(data);
        out.assume_init()
    }
}

/// Empty payload (no data, just notification)
#[derive(Debug, Clone, Copy)]
pub struct DragDropPayloadEmpty {
    /// True when hovering over target
    pub preview: bool,
    /// True when payload should be delivered
    pub delivery: bool,
}

/// Typed payload with data
#[derive(Debug, Clone, Copy)]
pub struct DragDropPayloadPod<T> {
    /// The payload data
    pub data: T,
    /// True when hovering over target
    pub preview: bool,
    /// True when payload should be delivered
    pub delivery: bool,
}

/// Raw payload data
#[derive(Debug)]
pub struct DragDropPayload {
    /// Pointer to payload data (managed by ImGui)
    pub data: *const ffi::c_void,
    /// Size of payload data in bytes
    pub size: usize,
    /// True when hovering over target
    pub preview: bool,
    /// True when payload should be delivered
    pub delivery: bool,
}

/// Error type for payload type mismatches
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PayloadIsWrongType;

impl std::fmt::Display for PayloadIsWrongType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "drag drop payload has wrong type")
    }
}

impl std::error::Error for PayloadIsWrongType {}

#[cfg(test)]
mod tests {
    use super::*;

    fn payload_bytes<T: Copy + 'static>(value: T) -> Vec<u8> {
        let payload = make_typed_payload(value);
        let size = std::mem::size_of::<TypedPayload<T>>();
        let mut out = vec![0u8; size];
        unsafe {
            std::ptr::copy_nonoverlapping(
                std::ptr::from_ref(&payload).cast::<u8>(),
                out.as_mut_ptr(),
                size,
            );
        }
        out
    }

    #[test]
    fn typed_payload_bytes_are_deterministic() {
        // If we accidentally leak uninitialized padding bytes, these can become nondeterministic.
        assert_eq!(payload_bytes(7u8), payload_bytes(7u8));
        assert_eq!(payload_bytes(0x1122_3344u32), payload_bytes(0x1122_3344u32));
    }

    #[test]
    fn typed_payload_can_be_read_unaligned() {
        let bytes = payload_bytes(7u8);
        let mut buf = vec![0u8; 1 + bytes.len()];
        buf[1..].copy_from_slice(&bytes);
        let ptr = unsafe { buf.as_ptr().add(1) } as *const TypedPayload<u8>;
        let decoded = unsafe { std::ptr::read_unaligned(ptr) };
        assert_eq!(decoded.type_id, any::TypeId::of::<u8>());
        assert_eq!(decoded.data, 7u8);
    }
}