Skip to main content

Context

Struct Context 

Source
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
// context

Never 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(); // PANIC

Implementations§

Source§

impl Context

Source

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.

Source

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.

Source

pub fn set_clipboard_backend<T>(&mut self, backend: T)

Sets the clipboard backend used for clipboard operations

Source§

impl Context

Source

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.

Source

pub fn try_create_with_shared_font_atlas( shared_font_atlas: SharedFontAtlas, ) -> Result<Context, ImGuiError>

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.

Source

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().

Source

pub fn create_with_shared_font_atlas( shared_font_atlas: SharedFontAtlas, ) -> Context

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.

Source

pub fn as_raw(&self) -> *mut ImGuiContext

Returns the raw ImGuiContext* for FFI integrations.

Source

pub fn id(&self) -> ContextId

Returns the process-unique identity of this Context.

Source

pub fn binding(&self) -> ContextBinding

Returns a persistent capability for calling against this Context while it is alive.

Source

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.

Source

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.

Source

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.

Source

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

pub fn io_mut(&mut self) -> &mut Io

Returns a mutable reference to this context’s IO object.

Source

pub fn io(&self) -> &Io

Get shared access to this context’s IO object.

Source

pub fn style(&self) -> &Style

Get access to the Style structure

Source

pub fn style_mut(&mut self) -> &mut Style

Get mutable access to the Style structure

Source§

impl Context

Source

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.

Source

pub fn clone_shared_font_atlas(&self) -> Option<SharedFontAtlas>

Attempts to clone the interior shared font atlas if it exists.

Source§

impl Context

Source

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.

Source

pub fn frame_lifecycle_state(&self) -> FrameLifecycleState

Return the current frame lifecycle state for this context.

Source

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.

Source

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.

Source

pub fn try_begin_frame( &mut self, ) -> Result<FrameToken<'_>, RendererConsumerError>

Begin a frame while returning detached-completion failures to the caller.

Source

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).

Source

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.

Source

pub fn frame_with_result<F, R>( &mut self, consumer: &SynchronousRendererConsumer, f: F, ) -> FrameResult<'_, R>
where F: FnOnce(&Ui) -> 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.

Source

pub fn render( &mut self, consumer: &SynchronousRendererConsumer, ) -> PendingFrame<'_>

Render a managed-texture frame and return its non-drawable pending capability.

Source

pub fn try_render( &mut self, consumer: &SynchronousRendererConsumer, ) -> Result<PendingFrame<'_>, SnapshotError>

Render a managed-texture frame while returning capture or consumer failures.

Source

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.

Source

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

Source

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[].

Source

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[].

Source

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

Source

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.

Source

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);
Source

pub fn set_ini_filename<P>( &mut self, filename: Option<P>, ) -> Result<(), ImGuiError>
where P: Into<PathBuf>,

Sets the INI filename for settings persistence

§Errors

Returns an error if the filename contains null bytes

Source

pub fn set_log_filename<P>( &mut self, filename: Option<P>, ) -> Result<(), ImGuiError>
where P: Into<PathBuf>,

Sets the log filename

§Errors

Returns an error if the filename contains null bytes

Source

pub fn set_platform_name<S>( &mut self, name: Option<S>, ) -> Result<(), ImGuiError>
where S: Into<String>,

Sets the platform name

§Errors

Returns an error if the name contains null bytes

Source

pub fn set_renderer_name<S>( &mut self, name: Option<S>, ) -> Result<(), ImGuiError>
where S: Into<String>,

Sets the renderer name

§Errors

Returns an error if the name contains null bytes

Source

pub fn load_ini_settings(&mut self, data: &str)

Loads settings from a string slice containing settings in .Ini file format

Source

pub fn save_ini_settings(&mut self, buf: &mut String)

Saves settings to a mutable string buffer in .Ini file format

Source

pub fn load_ini_settings_from_disk<P>( &mut self, filename: P, ) -> Result<(), ImGuiError>
where P: Into<PathBuf>,

Loads settings from a .ini file on disk.

This is a convenience wrapper over ImGui::LoadIniSettingsFromDisk.

Note: this is not available on wasm32 targets.

Source

pub fn save_ini_settings_to_disk<P>( &mut self, filename: P, ) -> Result<(), ImGuiError>
where P: Into<PathBuf>,

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

Source

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.

Source

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.

Source

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.

Source

pub fn poll_snapshot_completions( &mut self, ) -> Result<SnapshotCompletionProgress, RendererConsumerError>

Merge all currently available detached completion messages.

Source

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

Source

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.

Source

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

Source

pub fn register_texture( &mut self, texture: OwnedTextureData, ) -> ManagedTextureId

Transfer an owned user texture into this Context’s managed registry.

Source

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()
}
Source

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();
}
Source

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,
    })
));
Source

pub fn remove_texture( &mut self, id: ManagedTextureId, ) -> Result<(), ManagedTextureError>

Stop accepting new draw references and retire a managed texture.

Trait Implementations§

Source§

impl Debug for Context

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Drop for Context

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.