Skip to main content

dear_imgui_rs/context/
clipboard.rs

1use crate::clipboard::{ClipboardBackend, ClipboardContext};
2use crate::sys;
3
4use super::Context;
5use super::binding::{CTX_MUTEX, with_bound_context};
6
7impl Context {
8    /// Returns the current clipboard text, if available.
9    ///
10    /// Copies the text returned by the current platform clipboard callback. This can be
11    /// Dear ImGui's default implementation, the platform backend, or a backend installed via
12    /// [`Context::set_clipboard_backend`]. Returns `None` if the callback or text is unavailable.
13    #[doc(alias = "GetClipboardText")]
14    pub fn clipboard_text(&self) -> Option<String> {
15        let _guard = CTX_MUTEX.lock();
16        unsafe {
17            with_bound_context(self.raw, || {
18                let ptr = sys::igGetClipboardText();
19                if ptr.is_null() {
20                    return None;
21                }
22                Some(std::ffi::CStr::from_ptr(ptr).to_string_lossy().into_owned())
23            })
24        }
25    }
26
27    /// Sets the clipboard text.
28    ///
29    /// Calls the current platform clipboard setter, including Dear ImGui's default or a
30    /// replacement installed via [`Context::set_clipboard_backend`].
31    ///
32    /// Interior NUL bytes are sanitized to `?` to match other scratch-string helpers.
33    #[doc(alias = "SetClipboardText")]
34    pub fn set_clipboard_text(&self, text: impl AsRef<str>) {
35        let _guard = CTX_MUTEX.lock();
36        unsafe {
37            with_bound_context(self.raw, || {
38                sys::igSetClipboardText(self.ui.scratch_txt(text.as_ref()));
39            });
40        }
41    }
42
43    /// Sets the clipboard backend used for native clipboard operations.
44    ///
45    /// On WebAssembly the context retains the backend without installing its callbacks.
46    pub fn set_clipboard_backend<T: ClipboardBackend>(&mut self, backend: T) {
47        let _guard = CTX_MUTEX.lock();
48
49        let clipboard_ctx = Box::new(ClipboardContext::new(
50            backend,
51            self.ui.scratch_buffers.clone(),
52        ));
53
54        #[cfg(not(target_arch = "wasm32"))]
55        unsafe {
56            let platform_io = sys::igGetPlatformIO_ContextPtr(self.raw);
57            if platform_io.is_null() {
58                panic!("Context::set_clipboard_backend() requires a valid ImGui context");
59            }
60            (*platform_io).Platform_SetClipboardTextFn = Some(crate::clipboard::set_clipboard_text);
61            (*platform_io).Platform_GetClipboardTextFn = Some(crate::clipboard::get_clipboard_text);
62            (*platform_io).Platform_ClipboardUserData =
63                clipboard_ctx.as_ref() as *const ClipboardContext as *mut _;
64        }
65
66        self.clipboard_ctx = clipboard_ctx;
67    }
68}