pub struct Context { /* private fields */ }Expand description
An imgui context.
A context needs to be created to access most library functions. Due to current Dear ImGui design choices, at most one active Context can exist at any time. This limitation will likely be removed in a future Dear ImGui version.
If you need more than one context, you can use suspended contexts. As long as only one context is active at a time, it’s possible to have multiple independent contexts.
§Examples
Creating a new active context:
let ctx = dear_imgui_rs::Context::create();
// ctx is dropped naturally when it goes out of scope, which deactivates and destroys the
// contextNever try to create an active context when another one is active:
let ctx1 = dear_imgui_rs::Context::create();
let ctx2 = dear_imgui_rs::Context::create(); // PANICImplementations§
Source§impl Context
impl Context
Sourcepub fn clipboard_text(&self) -> Option<String>
pub fn clipboard_text(&self) -> Option<String>
Returns the current clipboard text, if available.
This calls Dear ImGui’s clipboard callbacks (configured via
Context::set_clipboard_backend). When no backend is installed, this returns None.
Note: returned data is copied into a new String.
Sourcepub fn set_clipboard_text(&self, text: impl AsRef<str>)
pub fn set_clipboard_text(&self, text: impl AsRef<str>)
Sets the clipboard text.
This calls Dear ImGui’s clipboard callbacks (configured via
Context::set_clipboard_backend). If no backend is installed, this is a no-op.
Interior NUL bytes are sanitized to ? to match other scratch-string helpers.
Sourcepub fn set_clipboard_backend<T>(&mut self, backend: T)where
T: ClipboardBackend,
pub fn set_clipboard_backend<T>(&mut self, backend: T)where
T: ClipboardBackend,
Sets the clipboard backend used for clipboard operations
Source§impl Context
impl Context
Sourcepub fn try_create() -> Result<Context, ImGuiError>
pub fn try_create() -> Result<Context, ImGuiError>
Tries to create a new active Dear ImGui context.
Returns an error if another context is already active or creation fails.
Tries to create a new active Dear ImGui context with a shared font atlas.
Multiple contexts may share the atlas while using legacy renderer-managed texture handling.
Once a managed renderer claims the atlas, registering another context returns
ImGuiError::SharedFontAtlasManaged.
If its prior managed Context was dropped without a committed renderer reset, this returns
ImGuiError::SharedFontAtlasRendererReleasePending.
Sourcepub fn create() -> Context
pub fn create() -> Context
Creates a new active Dear ImGui context (panics on error).
This aligns with imgui-rs behavior. For fallible creation use try_create().
Creates a new active Dear ImGui context with a shared font atlas (panics on error).
This panics if a managed renderer has already claimed the atlas. Use
Context::try_create_with_shared_font_atlas to handle ownership and pending-release
errors.
Sourcepub fn as_raw(&self) -> *mut ImGuiContext
pub fn as_raw(&self) -> *mut ImGuiContext
Returns the raw ImGuiContext* for FFI integrations.
Sourcepub fn binding(&self) -> ContextBinding
pub fn binding(&self) -> ContextBinding
Returns a persistent capability for calling against this Context while it is alive.
Sourcepub fn alive_token(&self) -> ContextAliveToken
pub fn alive_token(&self) -> ContextAliveToken
Returns a token that can be used to check whether this context is still alive.
Useful for extension crates that store raw pointers and need to avoid calling into FFI
after the owning Context has been dropped.
Sourcepub fn register_attachment<Marker>(
&mut self,
role: ContextAttachmentRole,
attachment: Rc<dyn ContextAttachment>,
) -> Result<ContextAttachmentLease, ContextAttachmentError>where
Marker: 'static,
pub fn register_attachment<Marker>(
&mut self,
role: ContextAttachmentRole,
attachment: Rc<dyn ContextAttachment>,
) -> Result<ContextAttachmentLease, ContextAttachmentError>where
Marker: 'static,
Registers a typed lifecycle attachment owned by this Context.
The marker type identifies the attachment independently of its erased implementation. Platform and renderer roles are exclusive, and a renderer requires an active platform.
Sourcepub fn preflight_attachment_registration<Marker>(
&self,
role: ContextAttachmentRole,
) -> Result<(), ContextAttachmentError>where
Marker: 'static,
pub fn preflight_attachment_registration<Marker>(
&self,
role: ContextAttachmentRole,
) -> Result<(), ContextAttachmentError>where
Marker: 'static,
Validate a typed lifecycle attachment registration without mutating the registry.
Backends use this to preflight a multi-Context transaction before registering any attachment. A successful result remains valid until the attachment registry or Context lifecycle changes.
Sourcepub fn prepare_platform_attachment_release(
&mut self,
handle: &ContextAttachmentHandle,
) -> Result<ContextPlatformAttachmentRelease<'_>, ContextPlatformAttachmentReleaseError>
pub fn prepare_platform_attachment_release( &mut self, handle: &ContextAttachmentHandle, ) -> Result<ContextPlatformAttachmentRelease<'_>, ContextPlatformAttachmentReleaseError>
Prepares an explicit release of this Context’s exact platform attachment generation.
Preparation fails while a renderer attachment is active. No frame, callback, or native
state is changed on failure. The returned permit exclusively borrows this Context; perform
any fallible platform cleanup through ContextPlatformAttachmentRelease::context_mut
and call ContextPlatformAttachmentRelease::commit only after native cleanup succeeds.
Source§impl Context
impl Context
Sourcepub fn font_atlas(&self) -> &FontAtlas
pub fn font_atlas(&self) -> &FontAtlas
Borrow the font atlas from the IO structure.
Font-atlas mutation is exposed through this shared view because Dear ImGui permits one native atlas to be registered with multiple contexts. Mutating methods validate the native atlas lock before entering FFI.
Attempts to clone the interior shared font atlas if it exists.
Source§impl Context
impl Context
Sourcepub fn prepare_frame(&mut self, options: FramePrepareOptions)
pub fn prepare_frame(&mut self, options: FramePrepareOptions)
Prepare IO values commonly needed before starting a frame.
This does not call NewFrame(). Engine backends can call it from their input/window update
stage and then open the actual Dear ImGui frame later in the schedule with
Context::begin_frame.
Sourcepub fn frame_lifecycle_state(&self) -> FrameLifecycleState
pub fn frame_lifecycle_state(&self) -> FrameLifecycleState
Return the current frame lifecycle state for this context.
Sourcepub fn end_frame(&mut self) -> bool
pub fn end_frame(&mut self) -> bool
End an open frame without producing render data.
Returns true when an open native frame was closed and false when the Context was
already idle or rendered. The operation is idempotent so engine teardown can revoke UI
access before detaching platform and renderer state.
Sourcepub fn begin_frame(&mut self) -> FrameToken<'_>
pub fn begin_frame(&mut self) -> FrameToken<'_>
Begin a Dear ImGui frame and return an explicit frame token.
Engine integrations should prefer this when the frame is owned by a schedule rather than a
single function. Draw UI through FrameToken::ui and then consume the token with
FrameToken::render or FrameToken::render_snapshot.
Sourcepub fn try_begin_frame(
&mut self,
) -> Result<FrameToken<'_>, RendererConsumerError>
pub fn try_begin_frame( &mut self, ) -> Result<FrameToken<'_>, RendererConsumerError>
Begin a frame while returning detached-completion failures to the caller.
Sourcepub fn frame(&mut self) -> &mut Ui
pub fn frame(&mut self) -> &mut Ui
Creates a new frame and returns a Ui object for building the interface.
Note: you must update io.DisplaySize (and usually io.DeltaTime) before calling this,
unless you are using a platform backend that does it for you (e.g. dear-imgui-winit).
Sourcepub fn try_frame(&mut self) -> Result<&mut Ui, RendererConsumerError>
pub fn try_frame(&mut self) -> Result<&mut Ui, RendererConsumerError>
Create a frame while returning detached-completion failures to the caller.
Native frame-order, display-size, docking, and font-atlas programmer errors retain their documented panic behavior. This method makes the asynchronous renderer completion boundary fallible so event-loop and engine integrations can recover without a later panic.
Sourcepub fn frame_with_result<F, R>(
&mut self,
consumer: &SynchronousRendererConsumer,
f: F,
) -> FrameResult<'_, R>
pub fn frame_with_result<F, R>( &mut self, consumer: &SynchronousRendererConsumer, f: F, ) -> FrameResult<'_, R>
Begin a frame, run a UI-building closure, render the frame, and return both values.
This is a convenience for callers that want the old callback style but also want the draw
data produced by closing the frame. Use Context::begin_frame when the UI is built across
several engine systems.
Sourcepub fn render(
&mut self,
consumer: &SynchronousRendererConsumer,
) -> PendingFrame<'_>
pub fn render( &mut self, consumer: &SynchronousRendererConsumer, ) -> PendingFrame<'_>
Render a managed-texture frame and return its non-drawable pending capability.
Sourcepub fn try_render(
&mut self,
consumer: &SynchronousRendererConsumer,
) -> Result<PendingFrame<'_>, SnapshotError>
pub fn try_render( &mut self, consumer: &SynchronousRendererConsumer, ) -> Result<PendingFrame<'_>, SnapshotError>
Render a managed-texture frame while returning capture or consumer failures.
Sourcepub fn render_legacy(&mut self) -> ReconciledFrame<'_>
pub fn render_legacy(&mut self) -> ReconciledFrame<'_>
Render a frame for a legacy renderer that does not implement managed texture requests.
§Panics
Panics when the active renderer advertises RENDERER_HAS_TEXTURES; managed renderers must
use Self::render with their synchronous consumer and reconcile every request.
Sourcepub fn render_snapshot(
&mut self,
consumer: &DetachedRendererConsumer,
) -> Result<FrameSnapshot, SnapshotError>
pub fn render_snapshot( &mut self, consumer: &DetachedRendererConsumer, ) -> Result<FrameSnapshot, SnapshotError>
Render the current frame and build a thread-safe main-viewport snapshot.
This Context-level entry point supports engine schedules that open and close the native
frame in separate systems and therefore cannot retain a FrameToken. The snapshot is
still bound to the supplied renderer consumer, Context, generation, and ordered epoch.
Source§impl Context
impl Context
Sourcepub fn platform_io(&self) -> &PlatformIo
pub fn platform_io(&self) -> &PlatformIo
Get shared access to the platform IO.
Note: ImGuiPlatformIO exists even when multi-viewport is disabled. We expose it
unconditionally so callers can use ImGui 1.92+ texture management via PlatformIO.Textures[].
Sourcepub fn platform_io_mut(&mut self) -> &mut PlatformIo
pub fn platform_io_mut(&mut self) -> &mut PlatformIo
Get mutable access to the platform IO.
Note: ImGuiPlatformIO exists even when multi-viewport is disabled. We expose it
unconditionally so callers can use ImGui 1.92+ texture management via PlatformIO.Textures[].
Sourcepub fn main_viewport(&mut self) -> &mut Viewport
pub fn main_viewport(&mut self) -> &mut Viewport
Returns a reference to the main Dear ImGui viewport.
The returned reference is owned by this ImGui context and must not be used after the context is destroyed.
Source§impl Context
impl Context
Sourcepub fn ini_settings_retention(
&self,
) -> Result<IniSettingsRetention, IniSettingsRetentionError>
pub fn ini_settings_retention( &self, ) -> Result<IniSettingsRetention, IniSettingsRetentionError>
Returns the Context-owned .ini retention configuration.
Native state modified through unsafe FFI is validated before it is returned.
Sourcepub fn set_ini_settings_retention(
&mut self,
retention: IniSettingsRetention,
) -> Result<(), IniSettingsRetentionError>
pub fn set_ini_settings_retention( &mut self, retention: IniSettingsRetention, ) -> Result<(), IniSettingsRetentionError>
Atomically configures the session date and .ini retention behavior.
This must be called before loading settings and before the first Dear ImGui frame. Automatic cleanup runs while settings are loaded, and Dear ImGui copies the platform session date at frame start. Mutating the policy after either boundary would silently produce mixed state.
Enabling IniSettingsRetention::AutoDiscard removes supported settings that have no
LastUsed field on the next load, including settings written before date recording was
enabled.
let mut context = Context::create();
context.io_mut().set_ini_settings_auto_discard_months(None);
let _ = IniSettingsRetention::disabled();let mut context = Context::create();
context.platform_io_mut().set_session_date(None);Sourcepub fn set_ini_filename<P>(
&mut self,
filename: Option<P>,
) -> Result<(), ImGuiError>
pub fn set_ini_filename<P>( &mut self, filename: Option<P>, ) -> Result<(), ImGuiError>
Sets the INI filename for settings persistence
§Errors
Returns an error if the filename contains null bytes
Sourcepub fn set_log_filename<P>(
&mut self,
filename: Option<P>,
) -> Result<(), ImGuiError>
pub fn set_log_filename<P>( &mut self, filename: Option<P>, ) -> Result<(), ImGuiError>
Sourcepub fn set_platform_name<S>(
&mut self,
name: Option<S>,
) -> Result<(), ImGuiError>
pub fn set_platform_name<S>( &mut self, name: Option<S>, ) -> Result<(), ImGuiError>
Sourcepub fn set_renderer_name<S>(
&mut self,
name: Option<S>,
) -> Result<(), ImGuiError>
pub fn set_renderer_name<S>( &mut self, name: Option<S>, ) -> Result<(), ImGuiError>
Sourcepub fn load_ini_settings(&mut self, data: &str)
pub fn load_ini_settings(&mut self, data: &str)
Loads settings from a string slice containing settings in .Ini file format
Sourcepub fn save_ini_settings(&mut self, buf: &mut String)
pub fn save_ini_settings(&mut self, buf: &mut String)
Saves settings to a mutable string buffer in .Ini file format
Sourcepub fn load_ini_settings_from_disk<P>(
&mut self,
filename: P,
) -> Result<(), ImGuiError>
pub fn load_ini_settings_from_disk<P>( &mut self, filename: P, ) -> Result<(), ImGuiError>
Loads settings from a .ini file on disk.
This is a convenience wrapper over ImGui::LoadIniSettingsFromDisk.
Note: this is not available on wasm32 targets.
Sourcepub fn save_ini_settings_to_disk<P>(
&mut self,
filename: P,
) -> Result<(), ImGuiError>
pub fn save_ini_settings_to_disk<P>( &mut self, filename: P, ) -> Result<(), ImGuiError>
Saves settings to a .ini file on disk.
This is a convenience wrapper over ImGui::SaveIniSettingsToDisk.
Note: this is not available on wasm32 targets.
Source§impl Context
impl Context
Sourcepub fn preflight_renderer_consumer(&self) -> Result<(), RendererConsumerError>
pub fn preflight_renderer_consumer(&self) -> Result<(), RendererConsumerError>
Validate whether this Context can attach a managed renderer consumer.
This check is non-mutating: it neither reserves a consumer generation nor claims the font atlas for managed rendering. It is intended for integrations that must validate several Contexts before attaching any renderer. A successful preflight is only a snapshot of the current state; both consumer creation methods repeat the validation when they commit.
Pending detached completions are not polled by this method. Call
Self::poll_snapshot_completions first when retrying after a consumer entered its
draining phase.
Sourcepub fn create_synchronous_renderer_consumer(
&mut self,
) -> Result<SynchronousRendererConsumer, RendererConsumerError>
pub fn create_synchronous_renderer_consumer( &mut self, ) -> Result<SynchronousRendererConsumer, RendererConsumerError>
Register the sole synchronous renderer consumer for this Context.
The generation is fixed to synchronous rendering when it is created and cannot be used to build detached snapshots.
A SharedFontAtlas must be registered with exactly one context
before it can enter managed renderer mode. If multiple contexts still share the atlas, this
returns RendererConsumerError::SharedFontAtlasRequiresExclusiveContext. Multiple-context
shared atlases remain available to legacy renderer-managed texture handling.
Sourcepub fn create_detached_renderer_consumer(
&mut self,
) -> Result<DetachedRendererConsumer, RendererConsumerError>
pub fn create_detached_renderer_consumer( &mut self, ) -> Result<DetachedRendererConsumer, RendererConsumerError>
Register the sole detached renderer consumer for this Context.
The generation is fixed to pointer-free snapshot rendering when it is created. Dropping the capability begins draining any outstanding snapshot epochs.
Sourcepub fn poll_snapshot_completions(
&mut self,
) -> Result<SnapshotCompletionProgress, RendererConsumerError>
pub fn poll_snapshot_completions( &mut self, ) -> Result<SnapshotCompletionProgress, RendererConsumerError>
Merge all currently available detached completion messages.
Sourcepub fn prepare_renderer_texture_reset<'context, 'consumer>(
&'context mut self,
consumer: &'consumer impl RendererConsumerCapability,
) -> Result<RendererTextureReset<'context, 'consumer>, RendererConsumerError>
pub fn prepare_renderer_texture_reset<'context, 'consumer>( &'context mut self, consumer: &'consumer impl RendererConsumerCapability, ) -> Result<RendererTextureReset<'context, 'consumer>, RendererConsumerError>
Validate an idle renderer generation before destroying its complete GPU texture map.
This two-phase transaction is the only safe renderer-reset path. Prepare the reset while
the renderer is still intact, release every GPU resource keyed by this consumer, then call
RendererTextureReset::commit. If preparation fails, the backend can return without
partially destroying its resource map. Dropping the permit without commit does not mutate
native texture state.
A single-call reset is intentionally unavailable because the Context cannot prove that an external renderer released its GPU map first:
use dear_imgui_rs::Context;
let mut context = Context::create();
let consumer = context.create_synchronous_renderer_consumer().unwrap();
let _ = context.reset_renderer_texture_bindings(&consumer);Source§impl Context
impl Context
Sourcepub fn suspend(self) -> Result<SuspendedContext, ContextSuspensionError>
pub fn suspend(self) -> Result<SuspendedContext, ContextSuspensionError>
Suspends this Context so another Context can become active.
Rejection retains this Context in ContextSuspensionError, allowing the caller to end an
open frame, leave a binding scope, or otherwise repair the conflict and retry.
Sourcepub fn suspend_or_panic(self) -> SuspendedContext
pub fn suspend_or_panic(self) -> SuspendedContext
Suspends this Context or panics with the rejection reason.
§Panics
Panics if a Context binding scope is active, this Context is not current, or a frame is
still open. Use Context::suspend when any of those states is recoverable.
Source§impl Context
impl Context
Sourcepub fn register_texture(
&mut self,
texture: OwnedTextureData,
) -> ManagedTextureId
pub fn register_texture( &mut self, texture: OwnedTextureData, ) -> ManagedTextureId
Transfer an owned user texture into this Context’s managed registry.
Sourcepub fn with_texture<R>(
&self,
id: ManagedTextureId,
f: impl for<'texture> FnOnce(ManagedTextureRef<'texture>) -> R,
) -> Result<R, ManagedTextureError>
pub fn with_texture<R>( &self, id: ManagedTextureId, f: impl for<'texture> FnOnce(ManagedTextureRef<'texture>) -> R, ) -> Result<R, ManagedTextureError>
Read an active managed texture inside a non-escaping closure.
The facade deliberately has no raw-pointer accessor.
use dear_imgui_rs::{Context, ManagedTextureId, sys};
fn leak_native(context: &Context, id: ManagedTextureId) -> *const sys::ImTextureData {
context.with_texture(id, |texture| texture.as_raw()).unwrap()
}Sourcepub fn with_texture_mut<R>(
&mut self,
id: ManagedTextureId,
f: impl for<'texture> FnOnce(ManagedTextureMut<'texture>) -> R,
) -> Result<R, ManagedTextureError>
pub fn with_texture_mut<R>( &mut self, id: ManagedTextureId, f: impl for<'texture> FnOnce(ManagedTextureMut<'texture>) -> R, ) -> Result<R, ManagedTextureError>
Mutate an active managed texture inside a non-escaping closure.
Renderer-owned state can only be changed by request-bound feedback.
use dear_imgui_rs::{Context, ManagedTextureId, TextureStatus};
fn bypass_renderer(context: &mut Context, id: ManagedTextureId) {
context
.with_texture_mut(id, |mut texture| texture.set_status(TextureStatus::OK))
.unwrap();
}Sourcepub fn try_with_texture_mut<R>(
&mut self,
id: ManagedTextureId,
f: impl for<'texture> FnOnce(ManagedTextureMut<'texture>) -> Result<R, TextureDataError>,
) -> Result<R, ManagedTextureMutationError>
pub fn try_with_texture_mut<R>( &mut self, id: ManagedTextureId, f: impl for<'texture> FnOnce(ManagedTextureMut<'texture>) -> Result<R, TextureDataError>, ) -> Result<R, ManagedTextureMutationError>
Mutate an active managed texture with flattened access and pixel-validation errors.
§Errors
Returns ManagedTextureMutationError::Access when id is foreign, stale, unknown, or
retiring. Returns ManagedTextureMutationError::Data when the closure returns a pixel
validation error. Each ManagedTextureMut operation is transactional, but the closure is
not: successful operations performed before a later error remain applied and immediately
invalidate older renderer feedback.
use dear_imgui_rs::{
Context, ManagedTextureMutationError, OwnedTextureData, TextureDataError, TextureFormat,
};
let mut context = Context::create();
let texture = OwnedTextureData::from_pixels(TextureFormat::RGBA32, 1, 1, &[0; 4])?;
let id = context.register_texture(texture);
let error = context
.try_with_texture_mut(id, |mut texture| texture.replace_pixels(&[0; 3]))
.unwrap_err();
assert!(matches!(
error,
ManagedTextureMutationError::Data(TextureDataError::ByteLengthMismatch {
expected: 4,
actual: 3,
})
));Sourcepub fn remove_texture(
&mut self,
id: ManagedTextureId,
) -> Result<(), ManagedTextureError>
pub fn remove_texture( &mut self, id: ManagedTextureId, ) -> Result<(), ManagedTextureError>
Stop accepting new draw references and retire a managed texture.