#![warn(missing_docs)] // Let's keep `Context` well-documented. use alloc::{borrow::Cow, sync::Arc}; use core::{cell::RefCell, panic::Location, time::Duration}; use emath::GuiRounding as _; use epaint::{ ClippedPrimitive, ClippedShape, Color32, ImageData, Pos2, Rect, StrokeKind, TessellationOptions, TextureId, Vec2, emath::{self, TSTransform}, mutex::RwLock, stats::PaintStats, tessellator, text::{FontInsert, FontPriority, Fonts, FontsView, LineBreaker, ViewportKey}, vec2, }; use crate::{ Align2, CursorIcon, DeferredViewportUiCallback, FontDefinitions, FontProvider, GlyphRasterizer, Grid, Id, ImmediateViewport, ImmediateViewportRendererCallback, Key, KeyboardShortcut, Label, LayerId, Memory, MissingGlyphPolicy, ModifierNames, Modifiers, NumExt as _, Order, Painter, RawInput, Response, RichText, SafeAreaInsets, ScrollArea, Sense, Style, TextStyle, TextureHandle, TextureOptions, Ui, UiBuilder, ViewportBuilder, ViewportCommand, ViewportId, ViewportIdMap, ViewportIdPair, ViewportIdSet, ViewportOutput, Visuals, Widget as _, WidgetRect, WidgetText, animation_manager::AnimationManager, containers::{self, area::AreaState}, data::output::PlatformOutput, epaint, hit_test::WidgetHits, input_state::{InputState, MultiTouchInfo, PointerEvent, SurrenderFocusOn}, interaction::InteractionSnapshot, layers::GraphicLayers, load::{self, Bytes, Loaders, SizedTexture}, memory::{Options, Theme}, os::OperatingSystem, output::{FullOutput, LogicOutput}, pass_state::PassState, plugin::{self, TypedPluginHandle}, resize, response, scroll_area, theme, util::IdTypeMap, viewport::ViewportClass, widget_style::{StyleArgs, WidgetStyle}, }; use crate::IdMap; /// Information given to the backend about when it is time to repaint the ui. /// /// This is given in the callback set by [`Context::set_request_repaint_callback`], /// and to the observer set by [`Context::set_repaint_observer`]. #[derive(Clone, Copy, Debug)] pub struct RequestRepaintInfo { /// This is used to specify what viewport that should repaint. pub viewport_id: ViewportId, /// Repaint after this duration. If zero, repaint as soon as possible. pub delay: Duration, /// The number of fully completed passes, of the entire lifetime of the [`Context`]. /// /// This can be compared to [`Context::cumulative_pass_nr`] to see if we we still /// need another repaint (ui pass / frame), or if one has already happened. pub current_cumulative_pass_nr: u64, } // ---------------------------------------------------------------------------- thread_local! { static IMMEDIATE_VIEWPORT_RENDERER: RefCell>> = Default::default(); } // ---------------------------------------------------------------------------- struct WrappedTextureManager(Arc>); impl Default for WrappedTextureManager { fn default() -> Self { let mut tex_mngr = epaint::textures::TextureManager::default(); // Will be filled in later let font_id = tex_mngr.alloc( "egui_font_texture".into(), epaint::ColorImage::filled([0, 0], Color32::TRANSPARENT).into(), Default::default(), ); assert_eq!( font_id, TextureId::default(), "font id should be equal to TextureId::default(), but was {font_id:?}", ); Self(Arc::new(RwLock::new(tex_mngr))) } } // ---------------------------------------------------------------------------- /// Repaint-logic impl ContextImpl { /// This is where we update the repaint logic. fn begin_pass_repaint_logic(&mut self, viewport_id: ViewportId) { let viewport = self.viewports.entry(viewport_id).or_default(); core::mem::swap( &mut viewport.repaint.prev_causes, &mut viewport.repaint.causes, ); viewport.repaint.causes.clear(); viewport.repaint.prev_pass_paint_delay = viewport.repaint.repaint_delay; if viewport.repaint.outstanding == 0 { // We are repainting now, so we can wait a while for the next repaint. viewport.repaint.repaint_delay = Duration::MAX; } else { viewport.repaint.repaint_delay = Duration::ZERO; viewport.repaint.outstanding -= 1; if let Some(callback) = &self.request_repaint_callback { (callback)(RequestRepaintInfo { viewport_id, delay: Duration::ZERO, current_cumulative_pass_nr: viewport.repaint.cumulative_pass_nr, }); } } } fn request_repaint(&mut self, viewport_id: ViewportId, cause: RepaintCause) { self.request_repaint_after(Duration::ZERO, viewport_id, cause); } fn request_repaint_after( &mut self, delay: Duration, viewport_id: ViewportId, cause: RepaintCause, ) { let viewport = self.viewports.entry(viewport_id).or_default(); if delay == Duration::ZERO { // Each request results in two repaints, just to give some things time to settle. // This solves some corner-cases of missing repaints on frame-delayed responses. viewport.repaint.outstanding = 1; } else { // For non-zero delays, we only repaint once, because // otherwise we would just schedule an immediate repaint _now_, // which would then clear the delay and repaint again. // Hovering a tooltip is a good example of a case where we want to repaint after a delay. } viewport.repaint.causes.push(cause); let info = RequestRepaintInfo { viewport_id, delay, current_cumulative_pass_nr: viewport.repaint.cumulative_pass_nr, }; if let Some(observer) = &self.repaint_observer { (observer)(info); } // We save some CPU time by only calling the callback if we need to. // If the new delay is greater or equal to the previous lowest, // it means we have already called the callback, and don't need to do it again. if delay < viewport.repaint.repaint_delay { viewport.repaint.repaint_delay = delay; if let Some(callback) = &self.request_repaint_callback { (callback)(info); } } } #[must_use] fn requested_immediate_repaint_prev_pass(&self, viewport_id: &ViewportId) -> bool { self.viewports .get(viewport_id) .is_some_and(|v| v.repaint.requested_immediate_repaint_prev_pass()) } #[must_use] fn has_requested_repaint(&self, viewport_id: &ViewportId) -> bool { self.viewports .get(viewport_id) .is_some_and(|v| 0 < v.repaint.outstanding || v.repaint.repaint_delay < Duration::MAX) } } // ---------------------------------------------------------------------------- /// The root [`Ui`] of the current pass of a viewport. /// /// See [`Context::root_ui`]. #[derive(Default)] #[expect(clippy::large_enum_variant, reason = "There is only one per viewport")] enum RootUi { /// Not yet created this pass. /// /// It is created on demand by [`Context::root_ui`]. #[default] Pending, /// Created, and ready to be borrowed by [`Context::root_ui`]. Available(Ui), /// Currently borrowed by a call to [`Context::root_ui`]. Borrowed, } /// State stored per viewport. /// /// Mostly for internal use. /// Things here may move and change without warning. #[derive(Default)] pub struct ViewportState { /// The type of viewport. /// /// This will never be [`ViewportClass::EmbeddedWindow`], /// since those don't result in real viewports. pub class: ViewportClass, /// The latest delta pub builder: ViewportBuilder, /// The user-code that shows the GUI, used for deferred viewports. /// /// `None` for immediate viewports. pub viewport_ui_cb: Option>, pub input: InputState, /// State that is collected during a pass and then cleared. pub this_pass: PassState, /// The final [`PassState`] from last pass. /// /// Only read from. pub prev_pass: PassState, /// Has this viewport been updated this pass? pub used: bool, /// State related to repaint scheduling. repaint: ViewportRepaintInfo, // ---------------------- // Updated at the start of the pass: // /// Which widgets are under the pointer? pub hits: WidgetHits, /// What widgets are being interacted with this pass? /// /// Based on the widgets from last pass, and input in this pass. pub interact_widgets: InteractionSnapshot, // ---------------------- // The output of a pass: // pub graphics: GraphicLayers, // Most of the things in `PlatformOutput` are not actually viewport dependent. pub output: PlatformOutput, pub commands: Vec, // ---------------------- // Cross-frame statistics: pub num_multipass_in_row: usize, /// The last theme we sent to the native window via [`ViewportCommand::SetTheme`], /// used to avoid sending redundant commands. /// /// See [`crate::Options::sync_window_theme`]. pub(crate) last_sent_window_theme: Option, /// The root [`Ui`] of the current pass. /// /// Only set between [`Context::begin_pass`] and [`Context::end_pass`]. root_ui: RootUi, } /// What called [`Context::request_repaint`] or [`Context::request_discard`]? #[derive(Clone, PartialEq, Eq, Hash)] pub struct RepaintCause { /// What file had the call that requested the repaint? pub file: &'static str, /// What line number of the call that requested the repaint? pub line: u32, /// Explicit reason; human readable. pub reason: Cow<'static, str>, } impl core::fmt::Debug for RepaintCause { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "{}:{} {}", self.file, self.line, self.reason) } } impl core::fmt::Display for RepaintCause { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "{}:{} {}", self.file, self.line, self.reason) } } impl RepaintCause { /// Capture the file and line number of the call site. #[expect(clippy::new_without_default)] #[track_caller] pub fn new() -> Self { let caller = Location::caller(); Self { file: caller.file(), line: caller.line(), reason: "".into(), } } /// Capture the file and line number of the call site, /// as well as add a reason. #[track_caller] pub fn new_reason(reason: impl Into>) -> Self { let caller = Location::caller(); Self { file: caller.file(), line: caller.line(), reason: reason.into(), } } } /// Per-viewport state related to repaint scheduling. struct ViewportRepaintInfo { /// Monotonically increasing counter. /// /// Incremented at the end of [`Context::run_ui`]. /// This can be smaller than [`Self::cumulative_pass_nr`], /// but never larger. cumulative_frame_nr: u64, /// Monotonically increasing counter, counting the number of passes. /// This can be larger than [`Self::cumulative_frame_nr`], /// but never smaller. cumulative_pass_nr: u64, /// The duration which the backend will poll for new events /// before forcing another egui update, even if there's no new events. /// /// Also used to suppress multiple calls to the repaint callback during the same pass. /// /// This is also returned in [`crate::ViewportOutput`]. repaint_delay: Duration, /// While positive, keep requesting repaints. Decrement at the start of each pass. outstanding: u8, /// What caused repaints during this pass? causes: Vec, /// What triggered a repaint the previous pass? /// (i.e: why are we updating now?) prev_causes: Vec, /// What was the output of `repaint_delay` on the previous pass? /// /// If this was zero, we are repainting as quickly as possible /// (as far as we know). prev_pass_paint_delay: Duration, } impl Default for ViewportRepaintInfo { fn default() -> Self { Self { cumulative_frame_nr: 0, cumulative_pass_nr: 0, // We haven't scheduled a repaint yet. repaint_delay: Duration::MAX, // Let's run a couple of frames at the start, because why not. outstanding: 1, causes: Default::default(), prev_causes: Default::default(), prev_pass_paint_delay: Duration::MAX, } } } impl ViewportRepaintInfo { pub fn requested_immediate_repaint_prev_pass(&self) -> bool { self.prev_pass_paint_delay == Duration::ZERO } } // ---------------------------------------------------------------------------- #[derive(Default)] struct ContextImpl { fonts: Option, font_definitions: FontDefinitions, glyph_rasterizers: Vec, font_providers: Vec>, missing_glyph_policy: MissingGlyphPolicy, line_breaker: Option>, /// Set when the rasterizers or providers change, acted on at the start of the next pass. /// /// The [`Fonts`] must outlive the pass that is laying out text with them, /// so they are never dropped in the middle of one. reload_fonts: bool, memory: Memory, animation_manager: AnimationManager, plugins: plugin::Plugins, called_on_exit: bool, safe_area: SafeAreaInsets, /// All viewports share the same texture manager and texture namespace. /// /// In all viewports, [`TextureId::default`] is special, and points to the font atlas. /// The font-atlas texture _may_ be different across viewports, as they may have different /// `pixels_per_point`, so we do special book-keeping for that. /// See . tex_manager: WrappedTextureManager, /// Set during the pass, becomes active at the start of the next pass. new_zoom_factor: Option, os: OperatingSystem, /// How deeply nested are we? viewport_stack: Vec, /// What is the last viewport rendered? last_viewport: ViewportId, paint_stats: PaintStats, request_repaint_callback: Option>, repaint_observer: Option>, viewport_parents: ViewportIdMap, viewports: ViewportIdMap, embed_viewports: bool, is_accesskit_enabled: bool, loaders: Arc, themes: theme::Themes, } impl ContextImpl { fn begin_pass(&mut self, mut new_raw_input: RawInput) { let viewport_id = new_raw_input.viewport_id; let parent_id = new_raw_input .viewports .get(&viewport_id) .and_then(|v| v.parent) .unwrap_or_default(); let ids = ViewportIdPair::from_self_and_parent(viewport_id, parent_id); if let Some(safe_area) = new_raw_input.safe_area_insets { self.safe_area = safe_area; } let is_outermost_viewport = self.viewport_stack.is_empty(); // not necessarily root, just outermost immediate viewport self.viewport_stack.push(ids); self.begin_pass_repaint_logic(viewport_id); let viewport = self.viewports.entry(viewport_id).or_default(); if is_outermost_viewport && let Some(new_zoom_factor) = self.new_zoom_factor.take() { let ratio = self.memory.options.zoom_factor / new_zoom_factor; self.memory.options.zoom_factor = new_zoom_factor; let input = &viewport.input; // This is a bit hacky, but is required to avoid jitter: let mut rect = input.content_rect(); rect.min = (ratio * rect.min.to_vec2()).to_pos2(); rect.max = (ratio * rect.max.to_vec2()).to_pos2(); new_raw_input.screen_rect = Some(rect); // We should really scale everything else in the input too, // but the `screen_rect` is the most important part. } let native_pixels_per_point = new_raw_input .viewport() .native_pixels_per_point .unwrap_or(1.0); let pixels_per_point = self.memory.options.zoom_factor * native_pixels_per_point; let all_viewport_ids: ViewportIdSet = self.all_viewport_ids(); let viewport = self.viewports.entry(self.viewport_id()).or_default(); self.memory.begin_pass(&new_raw_input, &all_viewport_ids); viewport.input = core::mem::take(&mut viewport.input).begin_pass( new_raw_input, viewport.repaint.requested_immediate_repaint_prev_pass(), pixels_per_point, self.memory.options.input_options, ); let repaint_after = viewport.input.wants_repaint_after(); let content_rect = viewport.input.content_rect(); viewport.this_pass.begin_pass(); { // Areas that are not interactable are click-through: skip them in the hit-test. let mut layers: Vec = viewport .prev_pass .widgets .layer_ids() .filter(|layer_id| self.memory.areas().is_interactable(*layer_id)) .collect(); layers.sort_by(|&a, &b| self.memory.areas().compare_order(a, b)); viewport.hits = if let Some(pos) = viewport.input.pointer.interact_pos() { let interact_radius = self.memory.options.style().interaction.interact_radius; crate::hit_test::hit_test( &viewport.prev_pass.widgets, &layers, &self.memory.to_global, pos, interact_radius, ) } else { WidgetHits::default() }; viewport.interact_widgets = crate::interaction::interact( &viewport.interact_widgets, &viewport.prev_pass.widgets, &viewport.hits, &viewport.input, self.memory.interaction_mut(), ); } // Ensure we register the background area so panels and background ui can catch clicks: self.memory.areas_mut().set_state( LayerId::background(), AreaState { pivot_pos: Some(content_rect.left_top()), pivot: Align2::LEFT_TOP, size: Some(content_rect.size()), interactable: true, last_became_visible_at: None, }, ); if self.is_accesskit_enabled { profiling::scope!("accesskit"); use crate::pass_state::AccessKitPassState; let id = crate::accesskit_root_id(); let mut root_node = accesskit::Node::new(accesskit::Role::Window); let pixels_per_point = viewport.input.pixels_per_point(); root_node.set_transform(accesskit::Affine::scale(pixels_per_point.into())); let mut nodes = IdMap::default(); nodes.insert(id, root_node); viewport.this_pass.accesskit_state = Some(AccessKitPassState { nodes, parent_map: IdMap::default(), }); } self.update_fonts_mut(); if let Some(delay) = repaint_after { self.request_repaint_after(delay, viewport_id, RepaintCause::new()); } } /// Load fonts unless already loaded. fn update_fonts_mut(&mut self) { profiling::function_scope!(); let input = &self.viewport().input; let max_texture_side = input.max_texture_side; if core::mem::take(&mut self.reload_fonts) { // The rasterizers or providers changed during the last pass. self.fonts = None; } if let Some(font_definitions) = self.memory.new_font_definitions.take() { // New font definition loaded, so we need to reload all fonts. self.fonts = None; self.font_definitions = font_definitions; log::trace!("Loading new font definitions"); } if !self.memory.add_fonts.is_empty() { let fonts = self.memory.add_fonts.drain(..); for font in fonts { self.fonts = None; // recreate all the fonts for family in font.families { let fam = self .font_definitions .families .entry(family.family) .or_default(); match family.priority { FontPriority::Highest => fam.insert(0, font.name.clone()), FontPriority::Lowest => fam.push(font.name.clone()), } } self.font_definitions .font_data .insert(font.name, Arc::new(font.data)); } log::trace!("Adding new fonts"); } let Visuals { mut text_options, .. } = self.memory.options.style().visuals; text_options.max_texture_side = max_texture_side; let mut is_new = false; let viewport_id = self.viewport_id(); let fonts = self.fonts.get_or_insert_with(|| { log::trace!("Creating new Fonts"); is_new = true; profiling::scope!("Fonts::new"); let mut fonts = Fonts::new(text_options, self.font_definitions.clone()) .with_font_providers(self.font_providers.clone()) .with_missing_glyph_policy(self.missing_glyph_policy); fonts.set_glyph_rasterizers(self.glyph_rasterizers.clone()); fonts }); if let Some(line_breaker) = &self.line_breaker { fonts.set_line_breaker(Arc::clone(line_breaker)); } { profiling::scope!("Fonts::begin_pass"); fonts.begin_pass(text_options, ViewportKey::new(viewport_id.0.value())); } } fn accesskit_node_builder(&mut self, id: Id) -> Option<&mut accesskit::Node> { let this_pass = &mut self.viewport().this_pass; let state = this_pass.accesskit_state.as_mut()?; if !is_accesskit_visible(&this_pass.widgets, &state.parent_map, id) { return None; } let builders = &mut state.nodes; if let std::collections::hash_map::Entry::Vacant(entry) = builders.entry(id) { entry.insert(Default::default()); /// Find the first ancestor that already has an accesskit node. fn find_accesskit_parent( parent_map: &IdMap, node_map: &IdMap, id: Id, ) -> Option { if let Some(parent_id) = parent_map.get(&id) { if node_map.contains_key(parent_id) { Some(*parent_id) } else { find_accesskit_parent(parent_map, node_map, *parent_id) } } else { None } } let parent_id = find_accesskit_parent(&state.parent_map, builders, id) .unwrap_or_else(crate::accesskit_root_id); let parent_builder = builders.get_mut(&parent_id)?; parent_builder.push_child(id.accesskit_id()); } builders.get_mut(&id) } fn pixels_per_point(&mut self) -> f32 { self.viewport().input.pixels_per_point } /// Return the `ViewportId` of the current viewport. /// /// For the root viewport this will return [`ViewportId::ROOT`]. pub(crate) fn viewport_id(&self) -> ViewportId { self.viewport_stack.last().copied().unwrap_or_default().this } /// Return the `ViewportId` of his parent. /// /// For the root viewport this will return [`ViewportId::ROOT`]. pub(crate) fn parent_viewport_id(&self) -> ViewportId { let viewport_id = self.viewport_id(); *self .viewport_parents .get(&viewport_id) .unwrap_or(&ViewportId::ROOT) } fn all_viewport_ids(&self) -> ViewportIdSet { core::iter::chain(self.viewports.keys().copied(), [ViewportId::ROOT]).collect() } /// The current active viewport pub(crate) fn viewport(&mut self) -> &mut ViewportState { self.viewports.entry(self.viewport_id()).or_default() } fn viewport_for(&mut self, viewport_id: ViewportId) -> &mut ViewportState { self.viewports.entry(viewport_id).or_default() } } // ---------------------------------------------------------------------------- /// Your handle to egui. /// /// This is the first thing you need when working with egui. /// Contains the [`InputState`], [`Memory`], [`PlatformOutput`], and more. /// /// [`Context`] is cheap to clone, and any clones refers to the same mutable data /// ([`Context`] uses refcounting internally). /// /// ## Locking /// All methods are marked `&self`; [`Context`] has interior mutability protected by an [`RwLock`]. /// /// To access parts of a `Context` you need to use some of the helper functions that take closures: /// /// ``` /// # let ctx = egui::Context::default(); /// if ctx.input(|i| i.key_pressed(egui::Key::A)) { /// ctx.copy_text("Hello!".to_owned()); /// } /// ``` /// /// Within such a closure you may NOT recursively lock the same [`Context`], as that can lead to a deadlock. /// Therefore it is important that any lock of [`Context`] is short-lived. /// /// These are effectively transactional accesses. /// /// [`Ui`] has many of the same accessor functions, and the same applies there. /// /// ## Example: /// /// ``` no_run /// # fn handle_platform_output(_: egui::PlatformOutput) {} /// # fn paint(textures_delta: egui::TexturesDelta, _: Vec) {} /// let mut ctx = egui::Context::default(); /// /// // Game loop: /// loop { /// let raw_input = egui::RawInput::default(); /// let full_output = ctx.run_ui(raw_input, |ui| { /// egui::CentralPanel::default().show(ui, |ui| { /// ui.label("Hello world!"); /// if ui.button("Click me").clicked() { /// // take some action here /// } /// }); /// }); /// handle_platform_output(full_output.platform_output); /// let clipped_primitives = ctx.tessellate(full_output.shapes, full_output.pixels_per_point); /// paint(full_output.textures_delta, clipped_primitives); /// } /// ``` #[derive(Clone)] pub struct Context(Arc>); impl core::fmt::Debug for Context { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("Context").finish_non_exhaustive() } } impl core::cmp::PartialEq for Context { fn eq(&self, other: &Self) -> bool { Arc::ptr_eq(&self.0, &other.0) } } impl Default for Context { fn default() -> Self { let ctx_impl = ContextImpl { embed_viewports: true, viewports: core::iter::once((ViewportId::ROOT, ViewportState::default())).collect(), ..Default::default() }; let ctx = Self(Arc::new(RwLock::new(ctx_impl))); ctx.add_plugin(plugin::CallbackPlugin::default()); // Register built-in plugins: ctx.add_plugin(crate::debug_text::DebugTextPlugin::default()); ctx.add_plugin(crate::text_selection::LabelSelectionState::default()); ctx.add_plugin(crate::DragAndDrop::default()); // Register the default theme for all built-in widgets: theme::DefaultStyle::register(&ctx); ctx } } impl Context { /// Add a [`GlyphRasterizer`], e.g. the browser on web, or for custom glyphs. /// /// Depending on [`FontPriority`] this is either a fallback or an override /// (see [`GlyphRasterizer`] for details). /// /// Rasterizers are asked in the order they were added. /// `eframe` adds the browser rasterizer on web. /// /// Adding a rasterizer whose [`GlyphRasterizer::key`] is already installed is a no-op, /// so this is safe to call every frame. /// /// The rasterizer becomes active at the start of the next pass. pub fn add_glyph_rasterizer(&self, glyph_rasterizer: GlyphRasterizer) { let changed = self.write(|ctx| { let changed = glyph_rasterizer.insert_into(&mut ctx.glyph_rasterizers); ctx.reload_fonts |= changed; changed }); if changed { self.apply_font_changes_now_if_unused(); self.request_repaint(); } } /// Replace all [`GlyphRasterizer`]s. See [`Self::add_glyph_rasterizer`]. /// /// Pass an empty list to only use the installed fonts. /// Note that this also removes the browser rasterizer that `eframe` adds on web. /// /// The rasterizers become active at the start of the next pass. pub fn set_glyph_rasterizers(&self, glyph_rasterizers: Vec) { self.write(|ctx| { ctx.glyph_rasterizers = glyph_rasterizers; ctx.reload_fonts = true; }); self.apply_font_changes_now_if_unused(); self.request_repaint(); } /// Add a [`FontProvider`], asked for fonts for characters that no installed font has. /// /// Fonts it finds are appended to the fallback chain of the requested font family. /// Providers are asked in the order they were added. /// /// `eframe` adds a system font provider on native (see its `system_fonts` feature). /// /// The provider becomes active at the start of the next pass. pub fn add_font_provider(&self, font_provider: Arc) { self.write(|ctx| { ctx.font_providers.push(font_provider); ctx.reload_fonts = true; }); self.apply_font_changes_now_if_unused(); self.request_repaint(); } /// Replace all [`FontProvider`]s. See [`Self::add_font_provider`]. /// /// Pass an empty list to only use the installed fonts. /// /// The providers become active at the start of the next pass. pub fn set_font_providers(&self, font_providers: Vec>) { self.write(|ctx| { ctx.font_providers = font_providers; ctx.reload_fonts = true; }); self.apply_font_changes_now_if_unused(); self.request_repaint(); } /// What to do with a character that nothing can draw: no installed font has it, /// no [`FontProvider`] finds a font for it, and no [`GlyphRasterizer`] handles it. /// /// The default is to draw a box ("tofu"). Tests may prefer [`MissingGlyphPolicy::Panic`] /// (`egui_kittest` sets it by default). /// /// The policy takes effect at the start of the next pass. pub fn set_missing_glyph_policy(&self, policy: MissingGlyphPolicy) { let changed = self.write(|ctx| { let changed = ctx.missing_glyph_policy != policy; ctx.missing_glyph_policy = policy; ctx.reload_fonts |= changed; changed }); if changed { self.apply_font_changes_now_if_unused(); self.request_repaint(); } } /// Find where rows of text may end with this [`LineBreaker`], /// e.g. one that knows where Thai words end, or the Japanese kinsoku rules. /// /// The default is [`crate::text::SimpleLineBreaker`]. /// /// The line breaker takes effect at the start of the next pass. pub fn set_line_breaker(&self, line_breaker: Arc) { self.write(|ctx| ctx.line_breaker = Some(line_breaker)); self.apply_font_changes_now_if_unused(); self.request_repaint(); } /// See [`Self::set_missing_glyph_policy`]. pub fn missing_glyph_policy(&self) -> MissingGlyphPolicy { self.read(|ctx| ctx.missing_glyph_policy) } /// Do read-only (shared access) transaction on Context fn read(&self, reader: impl FnOnce(&ContextImpl) -> R) -> R { reader(&self.0.read()) } /// Do read-write (exclusive access) transaction on Context fn write(&self, writer: impl FnOnce(&mut ContextImpl) -> R) -> R { writer(&mut self.0.write()) } /// Run the ui code for one frame. /// /// At most [`Options::max_passes`] calls will be issued to `run_ui`, /// and only on the rare occasion that [`Context::request_discard`] is called. /// Usually, it `run_ui` will only be called once. /// /// The [`Ui`] given to the callback will cover the entire [`Self::content_rect`], /// with no margin or background color. Use [`crate::Frame`] to add that. /// /// You can organize your GUI using [`crate::Panel`]. /// /// Instead of calling `run_ui`, you can alternatively use [`Self::run_pass`], /// or [`Self::begin_pass`] and [`Context::end_pass`]. /// /// ``` /// // One egui context that you keep reusing: /// let mut ctx = egui::Context::default(); /// /// // Each frame: /// let input = egui::RawInput::default(); /// let full_output = ctx.run_ui(input, |ui| { /// ui.label("Hello egui!"); /// }); /// // handle full_output /// # full_output.drop_without_applying_deltas(); /// ``` #[must_use] pub fn run_ui(&self, new_input: RawInput, mut run_ui: impl FnMut(&mut Ui)) -> FullOutput { self.run_pass(new_input, |ctx| ctx.root_ui(|ui| run_ui(ui))) } /// Run the ui code for one frame, without being handed the root [`Ui`]. /// /// This is the same as [`Self::run_ui`], except the callback is given the [`Context`] /// rather than the root [`Ui`]. /// Use [`Self::root_ui`] to access the root [`Ui`] from anywhere during the pass, /// e.g. to add a [`crate::Panel`] to it. /// /// This is useful for integrations where the ui code is split over several places /// that only share a [`Context`] (which is cheap to clone), and not a `&mut Ui`. /// /// Prefer [`Self::run_ui`] when you can. /// /// ``` /// // One egui context that you keep reusing: /// let mut ctx = egui::Context::default(); /// /// // Each frame: /// let input = egui::RawInput::default(); /// let full_output = ctx.run_pass(input, |ctx| { /// ctx.root_ui(|ui| { /// egui::Panel::top("top").show(ui, |ui| { /// ui.label("Hello egui!"); /// }); /// }); /// }); /// // handle full_output /// # full_output.drop_without_applying_deltas(); /// ``` #[must_use] pub fn run_pass(&self, new_input: RawInput, mut run_pass: impl FnMut(&Self)) -> FullOutput { self.run_pass_dyn(new_input, &mut run_pass) } #[must_use] fn run_pass_dyn(&self, new_input: RawInput, run_pass: &mut dyn FnMut(&Self)) -> FullOutput { let plugins = self.read(|ctx| ctx.plugins.ordered_plugins()); self.run_dyn(new_input, &mut |ctx| { ctx.root_ui(|ui| plugins.on_begin_pass(ui)); run_pass(ctx); ctx.root_ui(|ui| plugins.on_end_pass(ui)); }) } /// Access the root [`Ui`] of the current pass. /// /// The root [`Ui`] covers the entire [`Self::viewport_rect`]. /// It is the [`Ui`] given to the callback of [`Self::run_ui`], /// and the one that eframe gives to your app each frame. /// /// This lets you add e.g. a [`crate::Panel`] from code that only has access to a [`Context`], /// such as when the ui code is split over several places that share a [`Context`]. /// Panels added this way share the root [`Ui`], so they stack correctly. /// /// The root [`Ui`] is created on demand on the first call during a pass, /// so this also works when using [`Self::begin_pass`] and [`Self::end_pass`] directly. /// /// # Panics /// This panics if the root [`Ui`] is already borrowed, e.g. if called from within /// the callback of [`Self::run_ui`], or from within another call to `root_ui`. /// In those cases, use the `&mut Ui` you already have instead. /// /// ``` /// # egui::__run_test_ctx(|ctx| { /// ctx.root_ui(|ui| { /// egui::Panel::left("left").show(ui, |ui| { /// ui.label("Hello egui!"); /// }); /// }); /// # }); /// ``` pub fn root_ui(&self, add_contents: impl FnOnce(&mut Ui) -> R) -> R { let mut root_ui = self.take_root_ui(); let result = add_contents(&mut root_ui); self.write(|ctx| ctx.viewport().root_ui = RootUi::Available(root_ui)); result } /// Take the root [`Ui`] out of the viewport state, creating it if needed. /// /// The [`Ui`] must be put back with [`RootUi::Available`] when done, /// so that the next call to [`Self::root_ui`] can find it. fn take_root_ui(&self) -> Ui { let root_ui = self.write(|ctx| core::mem::replace(&mut ctx.viewport().root_ui, RootUi::Borrowed)); match root_ui { RootUi::Available(root_ui) => root_ui, RootUi::Pending => Ui::new( self.clone(), self.viewport_id().root_ui_id(), UiBuilder::new() .layer_id(LayerId::background()) .max_rect(self.viewport_rect()), ), RootUi::Borrowed => { panic!( "Context::root_ui was called while the root Ui was already borrowed. \ You are probably calling it from within `Context::run_ui` or `Context::root_ui`. \ Use the `&mut Ui` you were given instead." ); } } } /// Drop the root [`Ui`] of the current pass, if any, /// remembering how much of it was used. /// /// Called at the end of each pass. fn finish_root_ui(&self) { let root_ui = self.write(|ctx| core::mem::take(&mut ctx.viewport().root_ui)); match root_ui { RootUi::Pending => {} RootUi::Available(root_ui) => { self.pass_state_mut(|state| { state.root_ui_available_rect = Some(root_ui.available_rect_before_wrap()); state.root_ui_min_rect = Some(root_ui.min_rect()); }); // Drop outside of the lock, since `Ui::drop` locks the `Context`. drop(root_ui); } RootUi::Borrowed => { log::error!("Context::end_pass was called while the root Ui was borrowed"); } } } #[must_use] fn run_dyn(&self, mut new_input: RawInput, run_ui: &mut dyn FnMut(&Self)) -> FullOutput { profiling::function_scope!(); let viewport_id = new_input.viewport_id; let max_passes = self.write(|ctx| ctx.memory.options.max_passes.get()); let mut output = FullOutput::default(); debug_assert_eq!( output.platform_output.num_completed_passes, 0, "output must be fresh, but had {} passes", output.platform_output.num_completed_passes ); loop { profiling::scope!( "pass", output .platform_output .num_completed_passes .to_string() .as_str() ); // We must move the `num_passes` (back) to the viewport output so that [`Self::will_discard`] // has access to the latest pass count. self.write(|ctx| { let viewport = ctx.viewport_for(viewport_id); viewport.output.num_completed_passes = core::mem::take(&mut output.platform_output.num_completed_passes); output.platform_output.request_discard_reasons.clear(); }); self.begin_pass(new_input.take()); run_ui(self); output.append(self.end_pass()); debug_assert!( 0 < output.platform_output.num_completed_passes, "Completed passes was lower than 0, was {}", output.platform_output.num_completed_passes ); if !output.platform_output.requested_discard() { break; // no need for another pass } if max_passes <= output.platform_output.num_completed_passes { log::debug!( "Ignoring call request_discard, because max_passes={max_passes}. Requested from {:?}", output.platform_output.request_discard_reasons ); break; } } self.write(|ctx| { let did_multipass = 1 < output.platform_output.num_completed_passes; let viewport = ctx.viewport_for(viewport_id); if did_multipass { viewport.num_multipass_in_row += 1; } else { viewport.num_multipass_in_row = 0; } viewport.repaint.cumulative_frame_nr += 1; }); output } /// Request an ordered native IME cancellation fence for an application interruption. /// /// Call at the actual target/caret interruption and retain the returned id alongside that /// target. Another interruption must request a new id, even for the same owner/generation. /// Unpublished requests survive hidden/no-descriptor iterations; the next IME output for /// this viewport carries the latest request once. Discarded passes retain it only for the /// same final IME owner/context. This does not acknowledge cancellation. /// /// Process-unique token exhaustion returns `None`; keep stale-input protection in that case. /// Unsupported integrations may never emit [`crate::Event::ImeResetCompleted`]. Do not use /// idle time, ordinary empty preedit, or generic Enabled/Disabled as a substitute. pub fn request_ime_reset(&self, viewport_id: ViewportId) -> Option { self.memory_mut(|memory| memory.request_ime_reset(viewport_id)) } /// Run app logic without showing any ui. /// /// Use this instead of [`Self::run_ui`] when nothing will be shown, /// e.g. because the window is minimized or occluded, /// but you still want to let the app tick its logic /// (so that it can e.g. ask to be shown again with [`ViewportCommand::Focus`]). /// /// An integration should run [`Self::run_ui`] anyway, hidden or not, once something has /// sent [`ViewportCommand::RequestPaintWhileHidden`]: that command asks for the ui of a /// hidden window to run and be painted, which is how an app that sits in the background /// is screenshotted or driven. /// /// No pass is run, so `f` must not show any ui. /// This means everything egui knows about the ui is left untouched: /// no widget state is garbage-collected, no animation advances, /// and nothing loses focus. /// /// Of `new_input`, only the window state ([`RawInput::viewports`] and /// [`RawInput::focused`]) is used, so that `f` can tell that the window is hidden. /// The ui input (events, time, …) is _not_ interpreted, and is left for the next /// call to [`Self::run_ui`]: [`Self::input`] is otherwise still that of the last pass. /// /// The returned [`LogicOutput`] is what [`FullOutput`] would have carried: /// anything `f` asked the integration to do. /// There is nothing to paint. #[must_use] pub fn run_logic(&self, new_input: &RawInput, logic: impl FnOnce(&Self)) -> LogicOutput { profiling::function_scope!(); let viewport_id = new_input.viewport_id; self.write(|ctx| { // Consume any outstanding repaint request, so that a new request from `logic` // reaches the integration instead of being considered already served: ctx.begin_pass_repaint_logic(viewport_id); // Tell `logic` about the windows, but leave the ui input alone: let raw = &mut ctx.viewport_for(viewport_id).input.raw; raw.viewport_id = viewport_id; raw.viewports = new_input.viewports.clone(); raw.focused = new_input.focused; }); logic(self); self.write(|ctx| { let mut platform_output = core::mem::take(&mut ctx.viewport_for(viewport_id).output); if let Some(ime) = &mut platform_output.ime && let Some(request) = ctx.memory.take_ime_reset(viewport_id) { ime.reset_request = Some(request); ime.should_interrupt_composition = true; } LogicOutput { platform_output, viewport_commands: ctx .viewports .iter_mut() .filter(|(_, viewport)| !viewport.commands.is_empty()) .map(|(&id, viewport)| (id, core::mem::take(&mut viewport.commands))) .collect(), } }) } /// An alternative to calling [`Self::run_ui`]. /// /// It is usually better to use [`Self::run_ui`], because /// `run_ui` supports multi-pass layout using [`Self::request_discard`]. /// /// ``` /// // One egui context that you keep reusing: /// let mut ctx = egui::Context::default(); /// /// // Each frame: /// let input = egui::RawInput::default(); /// ctx.begin_pass(input); /// /// // … add panels and windows here, e.g. using `ctx.root_ui(…)` … /// /// let full_output = ctx.end_pass(); /// // handle full_output /// # full_output.drop_without_applying_deltas(); /// ``` pub fn begin_pass(&self, mut new_input: RawInput) { profiling::function_scope!(); let plugins = self.read(|ctx| ctx.plugins.ordered_plugins()); plugins.on_input(self, &mut new_input); self.write(|ctx| ctx.begin_pass(new_input)); } } /// ## Borrows parts of [`Context`] /// These functions all lock the [`Context`]. /// Please see the documentation of [`Context`] for how locking works! impl Context { /// Read-only access to [`InputState`]. /// /// Note that this locks the [`Context`]. /// /// ``` /// # let mut ctx = egui::Context::default(); /// ctx.input(|i| { /// // ⚠️ Using `ctx` (even from other `Arc` reference) again here will lead to a deadlock! /// }); /// /// if let Some(pos) = ctx.input(|i| i.pointer.hover_pos()) { /// // This is fine! /// } /// ``` #[inline] pub fn input(&self, reader: impl FnOnce(&InputState) -> R) -> R { self.write(move |ctx| reader(&ctx.viewport().input)) } /// This will create a `InputState::default()` if there is no input state for that viewport #[inline] pub fn input_for(&self, id: ViewportId, reader: impl FnOnce(&InputState) -> R) -> R { self.write(move |ctx| reader(&ctx.viewport_for(id).input)) } /// Read-write access to [`InputState`]. #[inline] pub fn input_mut(&self, writer: impl FnOnce(&mut InputState) -> R) -> R { self.input_mut_for(self.viewport_id(), writer) } /// This will create a `InputState::default()` if there is no input state for that viewport #[inline] pub fn input_mut_for(&self, id: ViewportId, writer: impl FnOnce(&mut InputState) -> R) -> R { self.write(move |ctx| writer(&mut ctx.viewport_for(id).input)) } /// Read-only access to [`Memory`]. #[inline] pub fn memory(&self, reader: impl FnOnce(&Memory) -> R) -> R { self.read(move |ctx| reader(&ctx.memory)) } /// Read-write access to [`Memory`]. #[inline] pub fn memory_mut(&self, writer: impl FnOnce(&mut Memory) -> R) -> R { self.write(move |ctx| writer(&mut ctx.memory)) } /// Read-only access to [`IdTypeMap`], which stores superficial widget state. #[inline] pub fn data(&self, reader: impl FnOnce(&IdTypeMap) -> R) -> R { self.read(move |ctx| reader(&ctx.memory.data)) } /// Read-write access to [`IdTypeMap`], which stores superficial widget state. #[inline] pub fn data_mut(&self, writer: impl FnOnce(&mut IdTypeMap) -> R) -> R { self.write(move |ctx| writer(&mut ctx.memory.data)) } /// Read-write access to [`GraphicLayers`], where painted [`crate::Shape`]s are written to. #[inline] pub fn graphics_mut(&self, writer: impl FnOnce(&mut GraphicLayers) -> R) -> R { self.write(move |ctx| writer(&mut ctx.viewport().graphics)) } /// Read-only access to [`GraphicLayers`], where painted [`crate::Shape`]s are written to. #[inline] pub fn graphics(&self, reader: impl FnOnce(&GraphicLayers) -> R) -> R { self.write(move |ctx| reader(&ctx.viewport().graphics)) } /// Read-only access to [`PlatformOutput`]. /// /// This is what egui outputs each pass and frame. /// /// ``` /// # let mut ctx = egui::Context::default(); /// ctx.output_mut(|o| o.cursor_icon = egui::CursorIcon::Progress); /// ``` #[inline] pub fn output(&self, reader: impl FnOnce(&PlatformOutput) -> R) -> R { self.write(move |ctx| reader(&ctx.viewport().output)) } /// Read-write access to [`PlatformOutput`]. #[inline] pub fn output_mut(&self, writer: impl FnOnce(&mut PlatformOutput) -> R) -> R { self.write(move |ctx| writer(&mut ctx.viewport().output)) } /// Read-only access to [`PassState`]. /// /// This is only valid during the call to [`Self::run_ui`] (between [`Self::begin_pass`] and [`Self::end_pass`]). #[inline] pub(crate) fn pass_state(&self, reader: impl FnOnce(&PassState) -> R) -> R { self.write(move |ctx| reader(&ctx.viewport().this_pass)) } /// Read-write access to [`PassState`]. /// /// This is only valid during the call to [`Self::run_ui`] (between [`Self::begin_pass`] and [`Self::end_pass`]). #[inline] pub(crate) fn pass_state_mut(&self, writer: impl FnOnce(&mut PassState) -> R) -> R { self.write(move |ctx| writer(&mut ctx.viewport().this_pass)) } /// Read-only access to the [`PassState`] from the previous pass. /// /// This is swapped at the end of each pass. #[inline] pub(crate) fn prev_pass_state(&self, reader: impl FnOnce(&PassState) -> R) -> R { self.write(move |ctx| reader(&ctx.viewport().prev_pass)) } /// Read-only access to [`Fonts`]. /// /// Not valid until first call to [`Context::run_ui()`]. /// That's because since we don't know the proper `pixels_per_point` until then. #[inline] pub fn fonts(&self, reader: impl FnOnce(&FontsView<'_>) -> R) -> R { self.write(move |ctx| { let pixels_per_point = ctx.pixels_per_point(); let viewport_id = ctx.viewport_id(); reader( &ctx.fonts .as_mut() .expect("No fonts available until first call to Context::run()") .with_pixels_per_point_for_viewport( pixels_per_point, ViewportKey::new(viewport_id.0.value()), ), ) }) } /// Read-write access to [`Fonts`]. /// /// Not valid until first call to [`Context::run_ui()`]. /// That's because since we don't know the proper `pixels_per_point` until then. #[inline] pub fn fonts_mut(&self, reader: impl FnOnce(&mut FontsView<'_>) -> R) -> R { self.write(move |ctx| { let pixels_per_point = ctx.pixels_per_point(); let viewport_id = ctx.viewport_id(); reader( &mut ctx .fonts .as_mut() .expect("No fonts available until first call to Context::run()") .with_pixels_per_point_for_viewport( pixels_per_point, ViewportKey::new(viewport_id.0.value()), ), ) }) } /// Read-only access to [`Options`]. #[inline] pub fn options(&self, reader: impl FnOnce(&Options) -> R) -> R { self.read(move |ctx| reader(&ctx.memory.options)) } /// Read-write access to [`Options`]. #[inline] pub fn options_mut(&self, writer: impl FnOnce(&mut Options) -> R) -> R { self.write(move |ctx| writer(&mut ctx.memory.options)) } /// Read-only access to [`TessellationOptions`]. #[inline] pub fn tessellation_options(&self, reader: impl FnOnce(&TessellationOptions) -> R) -> R { self.read(move |ctx| reader(&ctx.memory.options.tessellation_options)) } /// Read-write access to [`TessellationOptions`]. #[inline] pub fn tessellation_options_mut( &self, writer: impl FnOnce(&mut TessellationOptions) -> R, ) -> R { self.write(move |ctx| writer(&mut ctx.memory.options.tessellation_options)) } /// If the given [`Id`] has been used previously the same pass at different position, /// then an error will be printed on screen. /// /// This function is already called for all widgets that do any interaction, /// but you can call this from widgets that store state but that does not interact. /// /// The given [`Rect`] should be approximately where the widget will be. /// The most important thing is that [`Rect::min`] is approximately correct, /// because that's where the warning will be painted. If you don't know what size to pick, just pick [`Vec2::ZERO`]. pub fn check_for_id_clash(&self, id: Id, new_rect: Rect, what: &str) { let prev_rect = self.pass_state_mut(move |state| state.used_ids.insert(id, new_rect)); if !self.options(|opt| opt.warn_on_id_clash) { return; } let Some(prev_rect) = prev_rect else { return }; // It is ok to reuse the same ID for e.g. a frame around a widget, // or to check for interaction with the same widget twice: let is_same_rect = prev_rect.expand(0.1).contains_rect(new_rect) || new_rect.expand(0.1).contains_rect(prev_rect); if is_same_rect { return; } let show_error = |widget_rect: Rect, text: String| { let content_rect = self.content_rect(); let text = format!("🔥 {text}"); let color = self.global_style().visuals.error_fg_color; let painter = self.debug_painter(); painter.rect_stroke(widget_rect, 0.0, (1.0, color), StrokeKind::Outside); let below = widget_rect.bottom() + 32.0 < content_rect.bottom(); let text_rect = if below { painter.debug_text( widget_rect.left_bottom() + vec2(0.0, 2.0), Align2::LEFT_TOP, color, text, ) } else { painter.debug_text( widget_rect.left_top() - vec2(0.0, 2.0), Align2::LEFT_BOTTOM, color, text, ) }; if let Some(pointer_pos) = self.pointer_hover_pos() && text_rect.contains(pointer_pos) { let tooltip_pos = if below { text_rect.left_bottom() + vec2(2.0, 4.0) } else { text_rect.left_top() + vec2(2.0, -4.0) }; painter.error( tooltip_pos, format!("Widget is {} this text.\n\n\ ID clashes happens when things like Windows or CollapsingHeaders share names,\n\ or when things like Plot and Grid:s aren't given unique id_salt:s.\n\n\ Sometimes the solution is to use ui.push_id.", if below { "above" } else { "below" }), ); } }; let id_str = id.short_debug_format(); if prev_rect.min.distance(new_rect.min) < 4.0 { show_error(new_rect, format!("Double use of {what} ID {id_str}")); } else { show_error(prev_rect, format!("First use of {what} ID {id_str}")); show_error(new_rect, format!("Second use of {what} ID {id_str}")); } } // --------------------------------------------------------------------- /// Create a widget and check for interaction. /// /// If this is not called, the widget doesn't exist. /// /// You should use [`Ui::interact`] instead. /// /// If the widget already exists, its state (sense, Rect, etc) will be updated. /// /// `allow_focus` should usually be true, unless you call this function multiple times with the /// same widget, then `allow_focus` should only be true once (like in [`Ui::new`] (true) and [`Ui::remember_min_rect`] (false)). pub(crate) fn create_widget( &self, w: WidgetRect, allow_focus: bool, options: crate::InteractOptions, ) -> Response { debug_assert!(!w.rect.any_nan(), "widget rect is NaN: {:?}", w.rect); let interested_in_focus = w.enabled && w.sense.is_focusable() && self.memory(|mem| mem.allows_interaction(w.layer_id)); // Remember this widget self.write(|ctx| { let viewport = ctx.viewport(); // We add all widgets here, even non-interactive ones, // because we need this list not only for checking for blocking widgets, // but also to know when we have reached the widget we are checking for cover. viewport.this_pass.widgets.insert(w.layer_id, w, options); if allow_focus && interested_in_focus { ctx.memory.interested_in_focus(w.id, w.layer_id); } }); if allow_focus && !interested_in_focus { // Not interested or allowed input: self.memory_mut(|mem| mem.ignore_focus(w.id)); } if w.sense.interactive() || w.sense.is_focusable() { self.check_for_id_clash(w.id, w.rect, "widget"); } // Response inspection is also used to choose styling before a widget processes input. // Apply click-away focus changes only when the widget is actually registered, so a // TextEdit can preserve its selection for an action later in this pass (egui#8763). let res = self.get_response_with_focus_policy(w, true); #[cfg(debug_assertions)] if res.contains_pointer() { let plugins = self.read(|ctx| ctx.plugins.ordered_plugins()); plugins.on_widget_under_pointer(self, &w); } if allow_focus && w.sense.is_focusable() { // Make sure anything that can receive focus has an AccessKit node. // TODO(mwcampbell): For nodes that are filled from widget info, // some information is written to the node twice. self.accesskit_node_builder(w.id, |builder| res.fill_accesskit_node_common(builder)); } // A `Ui` registers with `Rect::NOTHING` before its real rect is known; scrolling needs the real one. if w.rect == Rect::NOTHING { return res; } self.write(|ctx| { use crate::{Align, pass_state::ScrollTarget, style::ScrollAnimation}; let viewport = ctx.viewport_for(ctx.viewport_id()); viewport .input .consume_accesskit_action_requests(res.id, |request| { use accesskit::Action; // TODO(lucasmerlin): Correctly handle the scroll unit: // https://github.com/AccessKit/accesskit/blob/e639c0e0d8ccbfd9dff302d972fa06f9766d608e/common/src/lib.rs#L2621 const DISTANCE: f32 = 100.0; match &request.action { Action::ScrollIntoView => { viewport.this_pass.scroll_target = [ Some(ScrollTarget::new( res.rect.x_range(), Some(Align::Center), ScrollAnimation::none(), )), Some(ScrollTarget::new( res.rect.y_range(), Some(Align::Center), ScrollAnimation::none(), )), ]; } Action::ScrollDown => { viewport.this_pass.scroll_delta.0 += DISTANCE * Vec2::UP; } Action::ScrollUp => { viewport.this_pass.scroll_delta.0 += DISTANCE * Vec2::DOWN; } Action::ScrollLeft => { viewport.this_pass.scroll_delta.0 += DISTANCE * Vec2::LEFT; } Action::ScrollRight => { viewport.this_pass.scroll_delta.0 += DISTANCE * Vec2::RIGHT; } _ => return false, } true }); }); res } /// Allow widgets inside `rect` to intentionally change ids during the current pass. /// /// This suppresses [`crate::style::DebugOptions::warn_if_rect_changes_id`] for widgets /// fully contained by `rect`. Use this for regions that intentionally replace their widget /// set, such as a data-driven table after its backing collection changes. /// /// This has no effect on duplicate-id checks or widget interaction. pub fn allow_widget_id_changes_in(&self, rect: Rect) { #[cfg(debug_assertions)] self.pass_state_mut(|state| state.widget_id_change_warning_exclusions.push(rect)); #[cfg(not(debug_assertions))] let _ = (self, rect); } /// Read the response of some widget, which may be called _before_ creating the widget (!). /// /// This is because widget interaction happens at the start of the pass, using the widget rects from the previous pass. /// /// If the widget was not visible the previous pass (or this pass), this will return `None`. /// /// If you try to read a [`Ui`]'s response, while still inside, this will return the [`Rect`] from the previous frame. pub fn read_response(&self, id: Id) -> Option { self.write(|ctx| { let viewport = ctx.viewport(); let widget_rect = viewport .this_pass .widgets .get(id) .or_else(|| viewport.prev_pass.widgets.get(id)) .copied(); widget_rect.map(|mut rect| { // If the Rect is invalid the Ui hasn't registered its final Rect yet. // We return the Rect from last frame instead. if !(rect.rect.is_positive() && rect.rect.is_finite()) && let Some(prev_rect) = viewport.prev_pass.widgets.get(id) { rect.rect = prev_rect.rect; } rect }) }) .map(|widget_rect| self.get_response(widget_rect)) } /// Rectangles that could receive pointer input in the last completed pass. /// /// This exposes the same widget rectangles egui uses for hit-testing, after /// filtering out disabled widgets, non-interactive widgets, and layers that /// are currently blocked from interaction. The returned rectangles are in /// global viewport coordinates, with layer transforms applied. /// /// This is meant for integrations that must declare platform input regions /// before pointer events can be delivered to egui, such as transparent or /// click-through overlays. #[must_use] pub fn interactive_rects_last_pass(&self) -> Vec { self.read(|ctx| { let Some(viewport) = ctx.viewports.get(&ctx.viewport_id()) else { return Vec::new(); }; let mut layers: Vec = viewport.prev_pass.widgets.layer_ids().collect(); layers.sort_by(|&a, &b| ctx.memory.areas().compare_order(a, b)); let mut rects = Vec::new(); for layer_id in layers { if !ctx.memory.allows_interaction(layer_id) { continue; } let to_global = ctx.memory.to_global.get(&layer_id).copied(); for widget in viewport.prev_pass.widgets.get_layer(layer_id) { if !widget.enabled || !widget.sense.interactive() { continue; } let rect = if let Some(to_global) = to_global { to_global * widget.interact_rect } else { widget.interact_rect }; if rect.is_positive() && rect.is_finite() { rects.push(rect); } } } rects }) } /// Do all interaction for an existing widget, without (re-)registering it. pub(crate) fn get_response(&self, widget_rect: WidgetRect) -> Response { self.get_response_with_focus_policy(widget_rect, false) } fn get_response_with_focus_policy( &self, widget_rect: WidgetRect, apply_click_away: bool, ) -> Response { use response::Flags; let WidgetRect { id, parent_id: _, layer_id, rect, interact_rect, sense, enabled, visible, } = widget_rect; // previous pass + "highlight next pass" == "highlight this pass" let highlighted = self.prev_pass_state(|fs| fs.highlight_next_pass.contains(&id)); let mut res = Response { ctx: self.clone(), layer_id, id, rect, interact_rect, sense, flags: Flags::empty(), interact_pointer_pos_or_nan: Pos2::NAN, intrinsic_size_or_nan: Vec2::NAN, }; res.flags.set(Flags::ENABLED, enabled); res.flags.set(Flags::VISIBLE, visible); res.flags.set(Flags::HIGHLIGHTED, highlighted); self.write(|ctx| { let viewport = ctx.viewports.entry(ctx.viewport_id()).or_default(); res.flags.set( Flags::CONTAINS_POINTER, viewport.interact_widgets.contains_pointer.contains(&id), ); let input = &viewport.input; let memory = &mut ctx.memory; if enabled && sense.senses_click() && memory.has_focus(id) && (input.key_pressed(Key::Space) || input.key_pressed(Key::Enter)) { // Space/enter works like a primary click for e.g. selected buttons res.flags.set(Flags::FAKE_PRIMARY_CLICKED, true); } if enabled && sense.senses_click() && input.has_accesskit_action_request(id, accesskit::Action::Click) { res.flags.set(Flags::FAKE_PRIMARY_CLICKED, true); } if enabled && sense.senses_click() && Some(id) == viewport.interact_widgets.long_touched { res.flags.set(Flags::LONG_TOUCHED, true); } let interaction = memory.interaction(); res.flags.set( Flags::IS_POINTER_BUTTON_DOWN_ON, interaction.potential_click_id == Some(id) || interaction.potential_drag_id == Some(id), ); if res.enabled() { res.flags.set( Flags::HOVERED, viewport.interact_widgets.hovered.contains(&id), ); res.flags.set( Flags::DRAGGED, Some(id) == viewport.interact_widgets.dragged, ); res.flags.set( Flags::DRAG_STARTED, Some(id) == viewport.interact_widgets.drag_started, ); res.flags.set( Flags::DRAG_STOPPED, Some(id) == viewport.interact_widgets.drag_stopped, ); } let clicked = Some(id) == viewport.interact_widgets.clicked; for pointer_event in &input.pointer.pointer_events { match pointer_event { PointerEvent::Moved(_) | PointerEvent::Pressed { .. } => {} PointerEvent::Released { click, .. } => { if enabled && sense.senses_click() && clicked && click.is_some() { res.flags.set(Flags::CLICKED, true); } res.flags.set(Flags::IS_POINTER_BUTTON_DOWN_ON, false); res.flags.set(Flags::DRAGGED, false); } } } // is_pointer_button_down_on is false when released, but we want interact_pointer_pos // to still work. let is_interacted_with = res.is_pointer_button_down_on() || res.long_touched() || clicked || res.drag_stopped(); if is_interacted_with && let Some(mut pos) = input.pointer.interact_pos() { if let Some(to_global) = memory.to_global.get(&res.layer_id) { pos = to_global.inverse() * pos; } res.interact_pointer_pos_or_nan = pos; } if input.pointer.any_down() && !is_interacted_with { // We don't hover widgets while interacting with *other* widgets: res.flags.set(Flags::HOVERED, false); } if apply_click_away && !res.hovered() { let triggered = match memory.options.input_options.surrender_focus_on { SurrenderFocusOn::Presses => input.pointer.any_pressed(), SurrenderFocusOn::Clicks => input.pointer.any_click(), SurrenderFocusOn::Never => false, }; if triggered && memory.has_focus(id) { memory.surrender_focus(id); } } }); res } /// This is called by [`Response::widget_info`], but can also be called directly. /// /// With some debug flags it will store the widget info in [`crate::WidgetRects`] for later display. #[inline] pub fn register_widget_info(&self, id: Id, make_info: impl Fn() -> crate::WidgetInfo) { #[cfg(debug_assertions)] self.write(|ctx| { if ctx.memory.options.style().debug.show_interactive_widgets { ctx.viewport().this_pass.widgets.set_info(id, make_info()); } }); #[cfg(not(debug_assertions))] { _ = (self, id, make_info); } } /// Get a full-screen painter for a new or existing layer pub fn layer_painter(&self, layer_id: LayerId) -> Painter { let content_rect = self.content_rect(); Painter::new(self.clone(), layer_id, content_rect) } /// Paint on top of _everything_ else (even on top of tooltips and popups). pub fn debug_painter(&self) -> Painter { Self::layer_painter(self, LayerId::debug()) } /// Is the user holding down all modifier keys to inspect widgets on hover? /// /// See [`crate::style::DebugOptions::debug_on_hover_with_all_modifiers`]. /// /// Always returns `false` unless compiled with `debug_assertions`. pub fn is_inspecting_widgets(&self) -> bool { cfg_select! { debug_assertions => { self.global_style().debug.debug_on_hover_with_all_modifiers && self.input(|i| i.modifiers.all()) } _ => { _ = self; false } } } /// Print this text next to the cursor at the end of the pass. /// /// If you call this multiple times, the text will be appended. /// /// This only works if compiled with `debug_assertions`. /// /// ``` /// # let ctx = egui::Context::default(); /// # let state = true; /// ctx.debug_text(format!("State: {state:?}")); /// ``` /// /// This is just a convenience for calling [`crate::debug_text::print`]. #[track_caller] pub fn debug_text(&self, text: impl Into) { crate::debug_text::print(self, text); } /// Current time in seconds, relative to some unknown epoch. pub fn time(&self) -> f64 { self.input(|i| i.time) } /// What operating system are we running on? /// /// When compiling natively, this is /// figured out from the `target_os`. /// /// For web, this can be figured out from the user-agent, /// and is done so by [`eframe`](https://github.com/emilk/egui/tree/main/crates/eframe). pub fn os(&self) -> OperatingSystem { self.read(|ctx| ctx.os) } /// Set the operating system we are running on. /// /// If you are writing wasm-based integration for egui you /// may want to set this based on e.g. the user-agent. pub fn set_os(&self, os: OperatingSystem) { self.write(|ctx| ctx.os = os); } /// Set the cursor icon. /// /// Equivalent to: /// ``` /// # let ctx = egui::Context::default(); /// ctx.output_mut(|o| o.cursor_icon = egui::CursorIcon::PointingHand); /// ``` pub fn set_cursor_icon(&self, cursor_icon: CursorIcon) { self.output_mut(|o| o.cursor_icon = cursor_icon); } /// Request that the integration display this RGBA bitmap as the OS /// cursor for the next frame, instead of the standard `cursor_icon`. /// Backends that don't support custom cursors (web, eframe with /// non-winit integrations) silently fall back to the icon. /// /// Pass `None` to clear and revert to `cursor_icon` selection. /// /// The integration is expected to dedupe by `Arc` pointer identity, /// so reusing the same `Arc<[u8]>` across frames is cheap. pub fn set_cursor_image(&self, image: Option) { self.output_mut(|o| o.cursor_image = image); } /// Add a command to [`PlatformOutput::commands`], /// for the integration to execute at the end of the frame. pub fn send_cmd(&self, cmd: crate::OutputCommand) { self.output_mut(|o| o.commands.push(cmd)); } /// Open an URL in a browser. /// /// Equivalent to: /// ``` /// # let ctx = egui::Context::default(); /// # let open_url = egui::OpenUrl::same_tab("http://www.example.com"); /// ctx.send_cmd(egui::OutputCommand::OpenUrl(open_url)); /// ``` pub fn open_url(&self, open_url: crate::OpenUrl) { self.send_cmd(crate::OutputCommand::OpenUrl(open_url)); } /// Copy the given text to the system clipboard. /// /// Note that in web applications, the clipboard is only accessible in secure contexts (e.g., /// HTTPS or localhost). If this method is used outside of a secure context, it will log an /// error and do nothing. See . pub fn copy_text(&self, text: String) { self.send_cmd(crate::OutputCommand::CopyText(text)); } /// Copy the given image to the system clipboard. /// /// Note that in web applications, the clipboard is only accessible in secure contexts (e.g., /// HTTPS or localhost). If this method is used outside of a secure context, it will log an /// error and do nothing. See . pub fn copy_image(&self, image: crate::ColorImage) { self.send_cmd(crate::OutputCommand::CopyImage(image)); } fn can_show_modifier_symbols(&self) -> bool { let ModifierNames { alt, ctrl, shift, mac_cmd, .. } = ModifierNames::SYMBOLS; let font_id = TextStyle::Body.resolve(&self.global_style()); self.fonts_mut(|f| { [alt, ctrl, shift, mac_cmd] .iter() .all(|symbols| f.has_glyphs(&font_id, symbols)) }) } /// Format the given modifiers in a human-readable way (e.g. `Ctrl+Shift+X`). pub fn format_modifiers(&self, modifiers: Modifiers) -> String { let os = self.os(); let is_mac = os.is_mac(); if is_mac && self.can_show_modifier_symbols() { ModifierNames::SYMBOLS.format(&modifiers, is_mac) } else { ModifierNames::NAMES.format(&modifiers, is_mac) } } /// Format the given shortcut in a human-readable way (e.g. `Ctrl+Shift+X`). /// /// Can be used to get the text for [`crate::Button::shortcut_text`]. pub fn format_shortcut(&self, shortcut: &KeyboardShortcut) -> String { let os = self.os(); let is_mac = os.is_mac(); if is_mac && self.can_show_modifier_symbols() { shortcut.format(&ModifierNames::SYMBOLS, is_mac) } else { shortcut.format(&ModifierNames::NAMES, is_mac) } } /// The total number of completed frames. /// /// Starts at zero, and is incremented once at the end of each call to [`Self::run_ui`]. /// /// This is always smaller or equal to [`Self::cumulative_pass_nr`]. pub fn cumulative_frame_nr(&self) -> u64 { self.cumulative_frame_nr_for(self.viewport_id()) } /// The total number of completed frames. /// /// Starts at zero, and is incremented once at the end of each call to [`Self::run_ui`]. /// /// This is always smaller or equal to [`Self::cumulative_pass_nr_for`]. pub fn cumulative_frame_nr_for(&self, id: ViewportId) -> u64 { self.read(|ctx| { ctx.viewports .get(&id) .map(|v| v.repaint.cumulative_frame_nr) .unwrap_or_else(|| { debug_assert!( false, "cumulative_frame_nr_for failed to find the viewport {id:?}" ); 0 }) }) } /// The total number of completed passes (usually there is one pass per rendered frame). /// /// Starts at zero, and is incremented for each completed pass inside of [`Self::run_ui`] (usually once). /// /// If you instead want to know which pass index this is within the current frame, /// use [`Self::current_pass_index`]. pub fn cumulative_pass_nr(&self) -> u64 { self.cumulative_pass_nr_for(self.viewport_id()) } /// The total number of completed passes (usually there is one pass per rendered frame). /// /// Starts at zero, and is incremented for each completed pass inside of [`Self::run_ui`] (usually once). pub fn cumulative_pass_nr_for(&self, id: ViewportId) -> u64 { self.read(|ctx| { ctx.viewports .get(&id) .map_or(0, |v| v.repaint.cumulative_pass_nr) }) } /// The index of the current pass in the current frame, starting at zero. /// /// Usually this is zero, but if something called [`Self::request_discard`] to do multi-pass layout, /// then this will be incremented for each pass. /// /// This just reads the value of [`PlatformOutput::num_completed_passes`]. /// /// To know the total number of passes ever completed, use [`Self::cumulative_pass_nr`]. pub fn current_pass_index(&self) -> usize { self.output(|o| o.num_completed_passes) } /// Call this if there is need to repaint the UI, i.e. if you are showing an animation. /// /// If this is called at least once in a frame, then there will be another frame right after this. /// Call as many times as you wish, only one repaint will be issued. /// /// To request repaint with a delay, use [`Self::request_repaint_after`]. /// /// If called from outside the UI thread, the UI thread will wake up and run, /// provided the egui integration has set that up via [`Self::set_request_repaint_callback`] /// (this will work on `eframe`). /// /// This will repaint the current viewport. #[track_caller] pub fn request_repaint(&self) { self.request_repaint_of(self.viewport_id()); } /// Call this if there is need to repaint the UI, i.e. if you are showing an animation. /// /// If this is called at least once in a frame, then there will be another frame right after this. /// Call as many times as you wish, only one repaint will be issued. /// /// To request repaint with a delay, use [`Self::request_repaint_after_for`]. /// /// If called from outside the UI thread, the UI thread will wake up and run, /// provided the egui integration has set that up via [`Self::set_request_repaint_callback`] /// (this will work on `eframe`). /// /// This will repaint the specified viewport. #[track_caller] pub fn request_repaint_of(&self, id: ViewportId) { let cause = RepaintCause::new(); self.write(|ctx| ctx.request_repaint(id, cause)); } /// Request repaint after at most the specified duration elapses. /// /// The backend can chose to repaint sooner, for instance if some other code called /// this method with a lower duration, or if new events arrived. /// /// The function can be multiple times, but only the *smallest* duration will be considered. /// So, if the function is called two times with `1 second` and `2 seconds`, egui will repaint /// after `1 second` /// /// This is primarily useful for applications who would like to save battery by avoiding wasted /// redraws when the app is not in focus. But sometimes the GUI of the app might become stale /// and outdated if it is not updated for too long. /// /// Let's say, something like a stopwatch widget that displays the time in seconds. You would waste /// resources repainting multiple times within the same second (when you have no input), /// just calculate the difference of duration between current time and next second change, /// and call this function, to make sure that you are displaying the latest updated time, but /// not wasting resources on needless repaints within the same second. /// /// ### Quirk: /// Duration begins at the next frame. Let's say for example that it's a very inefficient app /// and takes 500 milliseconds per frame at 2 fps. The widget / user might want a repaint in /// next 500 milliseconds. Now, app takes 1000 ms per frame (1 fps) because the backend event /// timeout takes 500 milliseconds AFTER the vsync swap buffer. /// So, it's not that we are requesting repaint within X duration. We are rather timing out /// during app idle time where we are not receiving any new input events. /// /// This repaints the current viewport. #[track_caller] pub fn request_repaint_after(&self, duration: Duration) { self.request_repaint_after_for(duration, self.viewport_id()); } /// Repaint after this many seconds. /// /// See [`Self::request_repaint_after`] for details. #[track_caller] pub fn request_repaint_after_secs(&self, seconds: f32) { if let Ok(duration) = core::time::Duration::try_from_secs_f32(seconds) { self.request_repaint_after(duration); } } /// Request repaint after at most the specified duration elapses. /// /// The backend can chose to repaint sooner, for instance if some other code called /// this method with a lower duration, or if new events arrived. /// /// The function can be multiple times, but only the *smallest* duration will be considered. /// So, if the function is called two times with `1 second` and `2 seconds`, egui will repaint /// after `1 second` /// /// This is primarily useful for applications who would like to save battery by avoiding wasted /// redraws when the app is not in focus. But sometimes the GUI of the app might become stale /// and outdated if it is not updated for too long. /// /// Let's say, something like a stopwatch widget that displays the time in seconds. You would waste /// resources repainting multiple times within the same second (when you have no input), /// just calculate the difference of duration between current time and next second change, /// and call this function, to make sure that you are displaying the latest updated time, but /// not wasting resources on needless repaints within the same second. /// /// ### Quirk: /// Duration begins at the next frame. Let's say for example that it's a very inefficient app /// and takes 500 milliseconds per frame at 2 fps. The widget / user might want a repaint in /// next 500 milliseconds. Now, app takes 1000 ms per frame (1 fps) because the backend event /// timeout takes 500 milliseconds AFTER the vsync swap buffer. /// So, it's not that we are requesting repaint within X duration. We are rather timing out /// during app idle time where we are not receiving any new input events. /// /// This repaints the specified viewport. #[track_caller] pub fn request_repaint_after_for(&self, duration: Duration, id: ViewportId) { let cause = RepaintCause::new(); self.write(|ctx| ctx.request_repaint_after(duration, id, cause)); } /// Was a repaint requested last pass for the current viewport? #[must_use] pub fn requested_repaint_last_pass(&self) -> bool { self.requested_repaint_last_pass_for(&self.viewport_id()) } /// Was a repaint requested last pass for the given viewport? #[must_use] pub fn requested_repaint_last_pass_for(&self, viewport_id: &ViewportId) -> bool { self.read(|ctx| ctx.requested_immediate_repaint_prev_pass(viewport_id)) } /// Has a repaint been requested for the current viewport? #[must_use] pub fn has_requested_repaint(&self) -> bool { self.has_requested_repaint_for(&self.viewport_id()) } /// Has a repaint been requested for the given viewport? #[must_use] pub fn has_requested_repaint_for(&self, viewport_id: &ViewportId) -> bool { self.read(|ctx| ctx.has_requested_repaint(viewport_id)) } /// Why are we repainting? /// /// This can be helpful in debugging why egui is constantly repainting. pub fn repaint_causes(&self) -> Vec { self.read(|ctx| { ctx.viewports .get(&ctx.viewport_id()) .map(|v| v.repaint.prev_causes.clone()) }) .unwrap_or_default() } /// For integrations: this callback will be called when an egui user calls [`Self::request_repaint`] or [`Self::request_repaint_after`]. /// /// This lets you wake up a sleeping UI thread. /// /// Note that only one callback can be set. Any new call overrides the previous callback. pub fn set_request_repaint_callback( &self, callback: impl Fn(RequestRepaintInfo) + Send + Sync + 'static, ) { let callback = Box::new(callback); self.write(|ctx| ctx.request_repaint_callback = Some(callback)); } /// For integrations: this observer will be called for every repaint request, /// i.e. every call to [`Self::request_repaint`], [`Self::request_repaint_after`] and their variants, /// including the ones egui makes itself. /// /// The callback set with [`Self::set_request_repaint_callback`] is only called when a request /// makes the next repaint of a viewport come sooner. The observer also sees the requests /// that don't, e.g. a request for a later delay than one already scheduled. /// An integration can use this to see everything that was requested during a pass, /// for instance to make its own scheduling decisions, or to count repaint requests. /// /// The observer is called on the thread that made the request, while the [`Context`] is locked, /// so it must not call back into the [`Context`]. /// /// Note that only one observer can be set. Any new call overrides the previous observer. pub fn set_repaint_observer( &self, observer: impl Fn(RequestRepaintInfo) + Send + Sync + 'static, ) { let observer = Box::new(observer); self.write(|ctx| ctx.repaint_observer = Some(observer)); } /// Request to discard the visual output of this pass, /// and to immediately do another one. /// /// This can be called to cover up visual glitches during a "sizing pass". /// For instance, when a [`crate::Grid`] is first shown we don't yet know the /// width and heights of its columns and rows. egui will do a best guess, /// but it will likely be wrong. Next pass it can read the sizes from the previous /// pass, and from there on the widths will be stable. /// This means the first pass will look glitchy, and ideally should not be shown to the user. /// So [`crate::Grid`] calls [`Self::request_discard`] to cover up this glitches. /// /// There is a limit to how many passes egui will perform, set by [`Options::max_passes`] (default=2). /// Therefore, the request might be declined. /// /// You can check if the current pass will be discarded with [`Self::will_discard`]. /// /// You should be very conservative with when you call [`Self::request_discard`], /// as it will cause an extra ui pass, potentially leading to extra CPU use and frame judder. /// /// The given reason should be a human-readable string that explains why `request_discard` /// was called. This will be shown in certain debug situations, to help you figure out /// why a pass was discarded. #[track_caller] pub fn request_discard(&self, reason: impl Into>) { let cause = RepaintCause::new_reason(reason); self.output_mut(|o| o.request_discard_reasons.push(cause)); log::trace!( "request_discard: {}", if self.will_discard() { "allowed" } else { "denied" } ); } /// Will the visual output of this pass be discarded? /// /// If true, you can early-out from expensive graphics operations. /// /// See [`Self::request_discard`] for more. pub fn will_discard(&self) -> bool { self.write(|ctx| { let vp = ctx.viewport(); // NOTE: `num_passes` is incremented vp.output.requested_discard() && vp.output.num_completed_passes + 1 < ctx.memory.options.max_passes.get() }) } } /// Plugins impl Context { /// Call the given callback at the start of each pass of each viewport. /// /// This is a convenience wrapper around [`Self::add_plugin`]. pub fn on_begin_pass(&self, debug_name: &'static str, cb: plugin::ContextCallback) { self.with_plugin(|p: &mut crate::plugin::CallbackPlugin| { p.on_begin_plugins.push((debug_name, cb)); }); } /// Call the given callback at the end of each pass of each viewport. /// /// This is a convenience wrapper around [`Self::add_plugin`]. pub fn on_end_pass(&self, debug_name: &'static str, cb: plugin::ContextCallback) { self.with_plugin(|p: &mut crate::plugin::CallbackPlugin| { p.on_end_plugins.push((debug_name, cb)); }); } /// Register a [`Plugin`](plugin::Plugin) /// /// Plugins are called in the order they are added. /// /// A plugin of the same type can only be added once (further calls with the same type will be ignored). /// This way it's convenient to add plugins in `eframe::run_simple_native`. pub fn add_plugin(&self, plugin: impl plugin::Plugin + 'static) { let handle = plugin::PluginHandle::new(plugin); let added = self.write(|ctx| ctx.plugins.add(Arc::clone(&handle))); if added { handle.lock().dyn_plugin_mut().setup(self); } } /// Notify all plugins that the integration is shutting down. /// /// Integrations should call this before persisting [`Memory`] and before destroying their /// renderer and other resources. Only the first call invokes the plugins. pub fn on_exit(&self) { let plugins = self.write(|ctx| { if ctx.called_on_exit { None } else { ctx.called_on_exit = true; Some(ctx.plugins.ordered_plugins()) } }); if let Some(plugins) = plugins { plugins.on_exit(self); } } /// Call the provided closure with the plugin of type `T`, if it was registered. /// /// Returns `None` if the plugin was not registered. pub fn with_plugin( &self, f: impl FnOnce(&mut T) -> R, ) -> Option { let plugin = self.read(|ctx| ctx.plugins.get(core::any::TypeId::of::())); plugin.map(|plugin| f(plugin.lock().typed_plugin_mut())) } /// Get a handle to the plugin of type `T`. /// /// ## Panics /// If the plugin of type `T` was not registered, this will panic. pub fn plugin(&self) -> TypedPluginHandle { if let Some(plugin) = self.plugin_opt() { plugin } else { panic!("Plugin of type {:?} not found", core::any::type_name::()); } } /// Get a handle to the plugin of type `T`, if it was registered. pub fn plugin_opt(&self) -> Option> { let plugin = self.read(|ctx| ctx.plugins.get(core::any::TypeId::of::())); plugin.map(TypedPluginHandle::new) } /// Get a handle to the plugin of type `T`, or insert its default. pub fn plugin_or_default(&self) -> TypedPluginHandle { if let Some(plugin) = self.plugin_opt() { plugin } else { let default_plugin = T::default(); self.add_plugin(default_plugin); self.plugin() } } } /// Experimental theming, gated behind the `experimental_theme` feature. impl Context { /// Register a [`StyleProvider`](crate::theme::StyleProvider) for the specified widget type. /// /// A theme can only be added once for a specified widget. /// If a theme is already registered for this widget, this is a no-op (useful for `eframe::run_simple_native`). /// /// If you want to add the theme anyway, use [`Self::replace_widget_theme`] instead. /// /// The types you need to call this (e.g. `StyleProvider`) are only public /// with the `experimental_theme` feature. #[cfg_attr(not(feature = "experimental"), doc(hidden))] pub fn add_widget_theme( &self, theme: impl theme::StyleProvider + Send + Sync + 'static, ) { self.write(|ctx| ctx.themes.register::(theme, false)); } /// Register a [`StyleProvider`](crate::theme::StyleProvider) for the specified widget. /// /// Overwrite any theme already registered for the specified widget [`WidgetStyle`]. /// This allow to live edit a theme. /// /// The types you need to call this (e.g. `StyleProvider`) are only public /// with the `experimental_theme` feature. #[cfg_attr(not(feature = "experimental"), doc(hidden))] pub fn replace_widget_theme( &self, theme: impl theme::StyleProvider + Send + Sync + 'static, ) { self.write(|ctx| ctx.themes.register::(theme, true)); } /// Compute the `WidgetStyle` using the registered theme. /// /// The types you need to call this (e.g. `StyleArgs`) are only public /// with the `experimental_theme` feature. #[cfg_attr(not(feature = "experimental"), doc(hidden))] pub fn get_widget_style( &self, modifiers: &StyleArgs<'_>, ) -> S { let theme = self.read(move |ctx| ctx.themes.get::()); theme.lock().style(modifiers) } } impl Context { /// Tell `egui` which fonts to use. /// /// The default `egui` fonts only support latin and cyrillic alphabets, /// but you can call this to install additional fonts that support e.g. korean characters. /// /// The new fonts will become active at the start of the next pass, /// or right away if no text has been laid out yet this pass. /// This will overwrite the existing fonts. /// /// These fonts will be used before any system fallback. pub fn set_fonts(&self, font_definitions: FontDefinitions) { profiling::function_scope!(); let update_fonts = self.read(|ctx| { // NOTE: this comparison is expensive since it checks TTF data for equality // TODO(valadaptive): add_font only checks the *names* for equality. Change this? ctx.fonts .as_ref() .is_none_or(|fonts| fonts.definitions() != &font_definitions) }); if update_fonts { self.memory_mut(|mem| mem.new_font_definitions = Some(font_definitions)); self.apply_font_changes_now_if_unused(); } } /// Add an additional font to `egui`. /// /// The default `egui` fonts only support latin and cyrillic alphabets, /// but you can call this to install additional fonts that support e.g. korean characters. /// /// The new font will become active at the start of the next pass, /// or right away if no text has been laid out yet this pass. /// This will keep the existing fonts. /// /// This font will be used before any system fallback. pub fn add_font(&self, new_font: FontInsert) { profiling::function_scope!(); let mut update_fonts = true; self.read(|ctx| { if let Some(current_fonts) = ctx.fonts.as_ref() && current_fonts .definitions() .font_data .contains_key(&new_font.name) { update_fonts = false; // no need to update } }); if update_fonts { self.memory_mut(|mem| mem.add_fonts.push(new_font)); self.apply_font_changes_now_if_unused(); } } /// Apply queued font changes right away if no text has been laid out yet this pass. /// /// Nothing is laid out with the old fonts, so there is nothing to keep consistent, /// and text later in this pass already gets the new fonts, providers and rasterizers. /// Without this, an app that sets up its fonts during its first pass /// (e.g. from inside an `egui_kittest` harness, which has no earlier hook) /// would lay out that whole pass with the fonts it started with, or with none. fn apply_font_changes_now_if_unused(&self) { self.write(|ctx| { let viewport_key = ViewportKey::new(ctx.viewport_id().0.value()); let unused = ctx .fonts .as_ref() .is_some_and(|fonts| !fonts.used_since_begin_pass(viewport_key)); if unused { ctx.update_fonts_mut(); } }); } /// Does the OS use dark or light mode? /// This is used when the theme preference is set to [`crate::ThemePreference::System`]. pub fn system_theme(&self) -> Option { self.memory(|mem| mem.options.system_theme) } /// The [`Theme`] used to select the appropriate [`Style`] (dark or light) /// used by all subsequent popups, menus, etc. pub fn theme(&self) -> Theme { self.options(|opt| opt.theme()) } /// The [`Theme`] used to select between dark and light [`Self::global_style`] /// as the active style used by all subsequent popups, menus, etc. /// /// Example: /// ``` /// # let mut ctx = egui::Context::default(); /// ctx.set_theme(egui::Theme::Light); // Switch to light mode /// ``` pub fn set_theme(&self, theme_preference: impl Into) { self.options_mut(|opt| opt.theme_preference = theme_preference.into()); } /// The language of the user interface, as a BCP 47 tag. /// /// See [`Options::language`]. pub fn language(&self) -> Option { self.options(|opt| opt.language.clone()) } /// Set the language of the user interface, as a BCP 47 tag (`"ar"`, `"pt-BR"`). /// /// See [`Options::language`]. /// /// ``` /// # let ctx = egui::Context::default(); /// ctx.set_language(Some("ar".to_owned())); /// ``` pub fn set_language(&self, language: Option) { self.options_mut(|opt| opt.language = language); } /// The currently active [`Style`] used by all subsequent popups, menus, etc. pub fn global_style(&self) -> Arc