dear-imgui-rs 0.13.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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
//! String helpers (ImString and scratch buffers)
//!
//! Utilities for working with strings across the Rust <-> Dear ImGui FFI
//! boundary.
//!
//! - `ImString`: an owned, growable UTF-8 string that maintains a trailing
//!   NUL byte as required by C APIs. Useful for zero-copy text editing via
//!   ImGui callbacks.
//! - `UiBuffer`: an internal scratch buffer used by [`Ui`] methods to stage
//!   temporary C strings for widget labels and hints.
//!
//! Example (zero-copy text input with `ImString`):
//! ```no_run
//! # use dear_imgui_rs::*;
//! # let mut ctx = Context::create();
//! # let ui = ctx.frame();
//! let mut s = ImString::with_capacity(256);
//! if ui.input_text_imstr("Edit", &mut s).build() {
//!     // edited in-place, no extra copies
//! }
//! ```
//!
use std::borrow::Cow;
use std::cell::RefCell;
use std::fmt;
use std::ops::{Deref, Index, RangeFull};
use std::os::raw::c_char;
use std::str;

/// Internal buffer for UI string operations
#[derive(Debug)]
pub struct UiBuffer {
    pub buffer: Vec<u8>,
    pub max_len: usize,
}

impl UiBuffer {
    /// Creates a new buffer with the specified capacity
    pub const fn new(max_len: usize) -> Self {
        Self {
            buffer: Vec::new(),
            max_len,
        }
    }

    /// Internal method to push a single text to our scratch buffer.
    ///
    /// Note: any interior NUL bytes (`'\0'`) will be replaced with `?` to preserve C string semantics.
    pub fn scratch_txt(&mut self, txt: impl AsRef<str>) -> *const std::os::raw::c_char {
        self.refresh_buffer();

        let start_of_substr = self.push(txt);
        unsafe { self.offset(start_of_substr) }
    }

    /// Internal method to push an option text to our scratch buffer.
    pub fn scratch_txt_opt(&mut self, txt: Option<impl AsRef<str>>) -> *const std::os::raw::c_char {
        match txt {
            Some(v) => self.scratch_txt(v),
            None => std::ptr::null(),
        }
    }

    /// Helper method, same as [`Self::scratch_txt`] but for two strings
    pub fn scratch_txt_two(
        &mut self,
        txt_0: impl AsRef<str>,
        txt_1: impl AsRef<str>,
    ) -> (*const std::os::raw::c_char, *const std::os::raw::c_char) {
        self.refresh_buffer();

        let first_offset = self.push(txt_0);
        let second_offset = self.push(txt_1);

        unsafe { (self.offset(first_offset), self.offset(second_offset)) }
    }

    /// Helper method, same as [`Self::scratch_txt`] but with one optional value
    pub fn scratch_txt_with_opt(
        &mut self,
        txt_0: impl AsRef<str>,
        txt_1: Option<impl AsRef<str>>,
    ) -> (*const std::os::raw::c_char, *const std::os::raw::c_char) {
        match txt_1 {
            Some(value) => self.scratch_txt_two(txt_0, value),
            None => (self.scratch_txt(txt_0), std::ptr::null()),
        }
    }

    /// Attempts to clear the buffer if it's over the maximum length allowed.
    /// This is to prevent us from making a giant vec over time.
    pub fn refresh_buffer(&mut self) {
        if self.buffer.len() > self.max_len {
            self.buffer.clear();
        }
    }

    /// Given a position, gives an offset from the start of the scratch buffer.
    ///
    /// # Safety
    /// This can return a pointer to undefined data if given a `pos >= self.buffer.len()`.
    /// This is marked as unsafe to reflect that.
    pub unsafe fn offset(&self, pos: usize) -> *const std::os::raw::c_char {
        unsafe { self.buffer.as_ptr().add(pos) as *const _ }
    }

    /// Pushes a new scratch sheet text and return the byte index where the sub-string
    /// starts.
    pub fn push(&mut self, txt: impl AsRef<str>) -> usize {
        let txt = txt.as_ref();
        let len = self.buffer.len();
        let bytes = txt.as_bytes();
        if bytes.contains(&0) {
            self.buffer
                .extend(bytes.iter().map(|&b| if b == 0 { b'?' } else { b }));
        } else {
            self.buffer.extend(bytes);
        }
        self.buffer.push(b'\0');

        len
    }
}

thread_local! {
    static TLS_SCRATCH: RefCell<UiBuffer> = RefCell::new(UiBuffer::new(1024));
}

/// Creates a temporary, NUL-terminated C string pointer backed by a thread-local scratch buffer.
///
/// The returned pointer is only valid until the next scratch-string call on the same thread.
///
/// This API is **not re-entrant**: any nested call to `tls_scratch_txt`/`with_scratch_txt` (or `Ui::scratch_txt`)
/// on the same thread will overwrite the backing buffer and invalidate previously returned pointers.
pub(crate) fn tls_scratch_txt(txt: impl AsRef<str>) -> *const c_char {
    TLS_SCRATCH.with(|buf| buf.borrow_mut().scratch_txt(txt))
}

/// Calls `f` with a temporary, NUL-terminated C string pointer backed by a thread-local scratch buffer.
///
/// The pointer is only valid for the duration of the call (and will be overwritten by subsequent
/// scratch-string operations on the same thread). Like [`tls_scratch_txt`], this is not re-entrant.
pub fn with_scratch_txt<R>(txt: impl AsRef<str>, f: impl FnOnce(*const c_char) -> R) -> R {
    TLS_SCRATCH.with(|buf| {
        let mut buf = buf.borrow_mut();
        let ptr = buf.scratch_txt(txt);
        f(ptr)
    })
}

/// Same as [`tls_scratch_txt`] but returns two pointers that stay valid together.
pub(crate) fn tls_scratch_txt_two(
    txt_0: impl AsRef<str>,
    txt_1: impl AsRef<str>,
) -> (*const c_char, *const c_char) {
    TLS_SCRATCH.with(|buf| buf.borrow_mut().scratch_txt_two(txt_0, txt_1))
}

/// Calls `f` with two temporary, NUL-terminated C string pointers backed by a thread-local scratch buffer.
///
/// Both pointers are valid together for the duration of the call (and will be overwritten by
/// subsequent scratch-string operations on the same thread).
pub fn with_scratch_txt_two<R>(
    txt_0: impl AsRef<str>,
    txt_1: impl AsRef<str>,
    f: impl FnOnce(*const c_char, *const c_char) -> R,
) -> R {
    TLS_SCRATCH.with(|buf| {
        let mut buf = buf.borrow_mut();
        let (a, b) = buf.scratch_txt_two(txt_0, txt_1);
        f(a, b)
    })
}

/// Calls `f` with three temporary, NUL-terminated C string pointers backed by a thread-local scratch buffer.
///
/// All pointers are valid together for the duration of the call (and will be overwritten by
/// subsequent scratch-string operations on the same thread).
pub fn with_scratch_txt_three<R>(
    txt_0: impl AsRef<str>,
    txt_1: impl AsRef<str>,
    txt_2: impl AsRef<str>,
    f: impl FnOnce(*const c_char, *const c_char, *const c_char) -> R,
) -> R {
    TLS_SCRATCH.with(|buf| {
        let mut buf = buf.borrow_mut();
        buf.refresh_buffer();
        let o0 = buf.push(txt_0);
        let o1 = buf.push(txt_1);
        let o2 = buf.push(txt_2);
        unsafe { f(buf.offset(o0), buf.offset(o1), buf.offset(o2)) }
    })
}

/// Calls `f` with a list of temporary, NUL-terminated C string pointers backed by a thread-local scratch buffer.
///
/// The pointers are only valid for the duration of the call (and will be overwritten by subsequent
/// scratch-string operations on the same thread).
pub fn with_scratch_txt_slice<R>(txts: &[&str], f: impl FnOnce(&[*const c_char]) -> R) -> R {
    TLS_SCRATCH.with(|buf| {
        let mut buf = buf.borrow_mut();
        buf.refresh_buffer();

        let total_bytes: usize = txts.iter().map(|s| s.len() + 1).sum();
        buf.buffer.reserve(total_bytes);

        let mut offsets: Vec<usize> = Vec::with_capacity(txts.len());
        for &s in txts {
            offsets.push(buf.push(s));
        }

        let mut ptrs: Vec<*const c_char> = Vec::with_capacity(txts.len());
        for off in offsets {
            ptrs.push(unsafe { buf.offset(off) });
        }

        f(&ptrs)
    })
}

/// Calls `f` with a list of temporary, NUL-terminated C string pointers and one optional pointer backed by
/// a thread-local scratch buffer.
///
/// The returned pointers are only valid for the duration of the call (and will be overwritten by subsequent
/// scratch-string operations on the same thread).
pub fn with_scratch_txt_slice_with_opt<R>(
    txts: &[&str],
    txt_opt: Option<&str>,
    f: impl FnOnce(&[*const c_char], *const c_char) -> R,
) -> R {
    TLS_SCRATCH.with(|buf| {
        let mut buf = buf.borrow_mut();
        buf.refresh_buffer();

        let total_bytes: usize = txts.iter().map(|s| s.len() + 1).sum::<usize>()
            + txt_opt.map(|s| s.len() + 1).unwrap_or(0);
        buf.buffer.reserve(total_bytes);

        let mut offsets: Vec<usize> = Vec::with_capacity(txts.len());
        for &s in txts {
            offsets.push(buf.push(s));
        }

        let opt_off = txt_opt.map(|s| buf.push(s));

        let mut ptrs: Vec<*const c_char> = Vec::with_capacity(txts.len());
        for off in offsets {
            ptrs.push(unsafe { buf.offset(off) });
        }

        let opt_ptr = match opt_off {
            Some(off) => unsafe { buf.offset(off) },
            None => std::ptr::null(),
        };

        f(&ptrs, opt_ptr)
    })
}

/// A UTF-8 encoded, growable, implicitly nul-terminated string.
#[derive(Clone, Hash, Ord, Eq, PartialOrd, PartialEq)]
pub struct ImString(pub(crate) Vec<u8>);

impl ImString {
    /// Creates a new `ImString` from an existing string.
    pub fn new<T: Into<String>>(value: T) -> ImString {
        let value = value.into();
        assert!(!value.contains('\0'), "ImString contained null byte");
        unsafe {
            let mut s = ImString::from_utf8_unchecked(value.into_bytes());
            s.refresh_len();
            s
        }
    }

    /// Creates a new empty `ImString` with a particular capacity
    #[inline]
    pub fn with_capacity(capacity: usize) -> ImString {
        let mut v = Vec::with_capacity(capacity + 1);
        v.push(b'\0');
        ImString(v)
    }

    /// Converts a vector of bytes to a `ImString` without checking that the string contains valid
    /// UTF-8
    ///
    /// # Safety
    ///
    /// It is up to the caller to guarantee the vector contains valid UTF-8 and no null terminator.
    #[inline]
    pub unsafe fn from_utf8_unchecked(mut v: Vec<u8>) -> ImString {
        v.push(b'\0');
        ImString(v)
    }

    /// Converts a vector of bytes to a `ImString` without checking that the string contains valid
    /// UTF-8
    ///
    /// # Safety
    ///
    /// It is up to the caller to guarantee the vector contains valid UTF-8 and a null terminator.
    #[inline]
    pub unsafe fn from_utf8_with_nul_unchecked(v: Vec<u8>) -> ImString {
        ImString(v)
    }

    /// Truncates this `ImString`, removing all contents
    #[inline]
    pub fn clear(&mut self) {
        self.0.clear();
        self.0.push(b'\0');
    }

    /// Appends the given character to the end of this `ImString`
    #[inline]
    pub fn push(&mut self, ch: char) {
        let mut buf = [0; 4];
        self.push_str(ch.encode_utf8(&mut buf));
    }

    /// Appends a given string slice to the end of this `ImString`
    #[inline]
    pub fn push_str(&mut self, string: &str) {
        assert!(!string.contains('\0'), "ImString contained null byte");
        self.0.pop();
        self.0.extend(string.bytes());
        self.0.push(b'\0');
        unsafe {
            self.refresh_len();
        }
    }

    /// Returns the capacity of this `ImString` in bytes
    #[inline]
    pub fn capacity(&self) -> usize {
        self.0.capacity() - 1
    }

    /// Returns the capacity of this `ImString` in bytes, including the implicit null byte
    #[inline]
    pub fn capacity_with_nul(&self) -> usize {
        self.0.capacity()
    }

    /// Ensures that the capacity of this `ImString` is at least `additional` bytes larger than the
    /// current length.
    ///
    /// The capacity may be increased by more than `additional` bytes.
    pub fn reserve(&mut self, additional: usize) {
        self.0.reserve(additional);
    }

    /// Ensures that the capacity of this `ImString` is at least `additional` bytes larger than the
    /// current length
    pub fn reserve_exact(&mut self, additional: usize) {
        self.0.reserve_exact(additional);
    }

    /// Returns a raw pointer to the underlying buffer
    #[inline]
    pub fn as_ptr(&self) -> *const c_char {
        self.0.as_ptr() as *const c_char
    }

    /// Returns a raw mutable pointer to the underlying buffer.
    ///
    /// If the underlying data is modified, `refresh_len` *must* be called afterwards.
    #[inline]
    pub fn as_mut_ptr(&mut self) -> *mut c_char {
        self.0.as_mut_ptr() as *mut c_char
    }

    /// Ensures the internal buffer length matches the requested size (including the trailing NUL).
    ///
    /// This is primarily used to prepare the backing storage for C APIs that write into the buffer
    /// using an explicit `BufSize` parameter (e.g. `InputText`).
    pub(crate) fn ensure_buf_size(&mut self, buf_size: usize) {
        if self.0.len() < buf_size {
            self.0.resize(buf_size, 0);
        } else if self.0.len() > buf_size {
            self.0.truncate(buf_size);
            if let Some(last) = self.0.last_mut() {
                *last = 0;
            } else {
                self.0.push(0);
            }
        } else if let Some(last) = self.0.last_mut() {
            *last = 0;
        }
    }

    /// Refreshes the length of the string by searching for the null terminator
    ///
    /// # Safety
    ///
    /// This function is unsafe because it assumes the initialized bytes before the null terminator
    /// contain valid UTF-8.
    pub unsafe fn refresh_len(&mut self) {
        if let Some(pos) = self.0.iter().position(|&b| b == 0) {
            self.0.truncate(pos + 1);
        } else {
            self.0.push(0);
        }
    }

    /// Returns the length of this `ImString` in bytes, excluding the null terminator
    pub fn len(&self) -> usize {
        self.0.len().saturating_sub(1)
    }

    /// Returns true if this `ImString` is empty
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Converts to a string slice
    pub fn to_str(&self) -> &str {
        unsafe { str::from_utf8_unchecked(&self.0[..self.len()]) }
    }
}

impl Default for ImString {
    fn default() -> Self {
        ImString::with_capacity(0)
    }
}

impl fmt::Display for ImString {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(self.to_str(), f)
    }
}

impl fmt::Debug for ImString {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(self.to_str(), f)
    }
}

impl Deref for ImString {
    type Target = str;
    fn deref(&self) -> &str {
        self.to_str()
    }
}

impl AsRef<str> for ImString {
    fn as_ref(&self) -> &str {
        self.to_str()
    }
}

impl From<String> for ImString {
    fn from(s: String) -> ImString {
        ImString::new(s)
    }
}

impl From<&str> for ImString {
    fn from(s: &str) -> ImString {
        ImString::new(s)
    }
}

impl Index<RangeFull> for ImString {
    type Output = str;
    fn index(&self, _index: RangeFull) -> &str {
        self.to_str()
    }
}

/// Represents a borrowed string that can be either a Rust string slice or an ImString
pub type ImStr<'a> = Cow<'a, str>;

/// Creates an ImString from a string literal at compile time
#[macro_export]
macro_rules! im_str {
    ($e:expr) => {{ $crate::ImString::new($e) }};
}

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

    #[test]
    fn im_string_ensure_buf_size_resizes_and_nul_terminates() {
        let mut s = ImString::new("abc");
        s.ensure_buf_size(16);
        assert_eq!(s.0.len(), 16);
        assert_eq!(&s.0[..3], b"abc");
        assert_eq!(s.0[3], 0);
        assert!(s.0[4..].iter().all(|&b| b == 0));
    }

    #[test]
    fn im_string_refresh_len_does_not_scan_spare_capacity() {
        let mut v = vec![b'x'; 16];
        v[..4].copy_from_slice(b"abcd");
        v[10] = 0;
        v.truncate(4);

        let mut s = ImString(v);
        unsafe { s.refresh_len() };
        assert_eq!(s.to_str(), "abcd");
        assert_eq!(s.0.last().copied(), Some(0));
    }

    #[test]
    fn ui_buffer_push_appends_nul() {
        let mut buf = UiBuffer::new(1024);
        let start = buf.push("abc");
        assert_eq!(start, 0);
        assert_eq!(&buf.buffer, b"abc\0");
    }

    #[test]
    fn ui_buffer_sanitizes_interior_nul() {
        let mut buf = UiBuffer::new(1024);
        let ptr = buf.scratch_txt("a\0b");
        let s = unsafe { CStr::from_ptr(ptr) }.to_str().unwrap();
        assert_eq!(s, "a?b");
    }

    #[test]
    fn tls_scratch_txt_is_nul_terminated() {
        let ptr = tls_scratch_txt("hello");
        let s = unsafe { CStr::from_ptr(ptr) }.to_str().unwrap();
        assert_eq!(s, "hello");
    }

    #[test]
    fn tls_scratch_txt_two_returns_two_valid_strings() {
        let (a_ptr, b_ptr) = tls_scratch_txt_two("a", "bcd");
        let a = unsafe { CStr::from_ptr(a_ptr) }.to_str().unwrap();
        let b = unsafe { CStr::from_ptr(b_ptr) }.to_str().unwrap();
        assert_eq!(a, "a");
        assert_eq!(b, "bcd");
    }

    #[test]
    fn with_scratch_txt_slice_returns_sequential_pointers() {
        with_scratch_txt_slice(&["a", "bc", "def"], |ptrs| {
            assert_eq!(ptrs.len(), 3);

            let a = unsafe { CStr::from_ptr(ptrs[0]) }.to_str().unwrap();
            let b = unsafe { CStr::from_ptr(ptrs[1]) }.to_str().unwrap();
            let c = unsafe { CStr::from_ptr(ptrs[2]) }.to_str().unwrap();
            assert_eq!(a, "a");
            assert_eq!(b, "bc");
            assert_eq!(c, "def");

            let ab = (ptrs[1] as usize) - (ptrs[0] as usize);
            let bc = (ptrs[2] as usize) - (ptrs[1] as usize);
            assert_eq!(ab, "a".len() + 1);
            assert_eq!(bc, "bc".len() + 1);
        });
    }

    #[test]
    fn with_scratch_txt_slice_with_opt_returns_null_for_none() {
        with_scratch_txt_slice_with_opt(&["a", "bc"], None, |ptrs, opt_ptr| {
            assert_eq!(ptrs.len(), 2);
            assert!(opt_ptr.is_null());

            let a = unsafe { CStr::from_ptr(ptrs[0]) }.to_str().unwrap();
            let b = unsafe { CStr::from_ptr(ptrs[1]) }.to_str().unwrap();
            assert_eq!(a, "a");
            assert_eq!(b, "bc");
        });
    }

    #[test]
    fn with_scratch_txt_slice_with_opt_appends_opt_string() {
        with_scratch_txt_slice_with_opt(&["a", "bc"], Some("fmt"), |ptrs, opt_ptr| {
            assert_eq!(ptrs.len(), 2);
            assert!(!opt_ptr.is_null());

            let a = unsafe { CStr::from_ptr(ptrs[0]) }.to_str().unwrap();
            let b = unsafe { CStr::from_ptr(ptrs[1]) }.to_str().unwrap();
            let fmt = unsafe { CStr::from_ptr(opt_ptr) }.to_str().unwrap();
            assert_eq!(a, "a");
            assert_eq!(b, "bc");
            assert_eq!(fmt, "fmt");

            let ab = (ptrs[1] as usize) - (ptrs[0] as usize);
            let bf = (opt_ptr as usize) - (ptrs[1] as usize);
            assert_eq!(ab, "a".len() + 1);
            assert_eq!(bf, "bc".len() + 1);
        });
    }

    #[test]
    #[should_panic(expected = "null byte")]
    fn imstring_new_rejects_interior_nul() {
        let _ = ImString::new("a\0b");
    }

    #[test]
    #[should_panic(expected = "null byte")]
    fn imstring_push_str_rejects_interior_nul() {
        let mut s = ImString::new("a");
        s.push_str("b\0c");
    }
}