repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/epaint/src/shape_transform.rs
crates/epaint/src/shape_transform.rs
use std::sync::Arc; use crate::{ CircleShape, Color32, ColorMode, CubicBezierShape, EllipseShape, Mesh, PathShape, QuadraticBezierShape, RectShape, Shape, TextShape, color, }; /// Remember to handle [`Color32::PLACEHOLDER`] specially! pub fn adjust_colors( shape: &mut Shape, adjust_color: impl Fn(&mut Color32) + Send + Sync + Copy + 'static, ) { #![expect(clippy::match_same_arms)] match shape { Shape::Noop => {} Shape::Vec(shapes) => { for shape in shapes { adjust_colors(shape, adjust_color); } } Shape::LineSegment { stroke, points: _ } => { adjust_color(&mut stroke.color); } Shape::Path(PathShape { points: _, closed: _, fill, stroke, }) | Shape::QuadraticBezier(QuadraticBezierShape { points: _, closed: _, fill, stroke, }) | Shape::CubicBezier(CubicBezierShape { points: _, closed: _, fill, stroke, }) => { adjust_color(fill); adjust_color_mode(&mut stroke.color, adjust_color); } Shape::Circle(CircleShape { center: _, radius: _, fill, stroke, }) | Shape::Ellipse(EllipseShape { center: _, radius: _, fill, stroke, }) | Shape::Rect(RectShape { rect: _, corner_radius: _, fill, stroke, stroke_kind: _, round_to_pixels: _, blur_width: _, brush: _, }) => { adjust_color(fill); adjust_color(&mut stroke.color); } Shape::Text(TextShape { pos: _, galley, underline, fallback_color, override_text_color, opacity_factor: _, angle: _, }) => { adjust_color(&mut underline.color); adjust_color(fallback_color); if let Some(override_text_color) = override_text_color { adjust_color(override_text_color); } if !galley.is_empty() { let galley = Arc::make_mut(galley); for placed_row in &mut galley.rows { let row = Arc::make_mut(&mut placed_row.row); for vertex in &mut row.visuals.mesh.vertices { adjust_color(&mut vertex.color); } } } } Shape::Mesh(mesh) => { let Mesh { indices: _, vertices, texture_id: _, } = Arc::make_mut(mesh); for v in vertices { adjust_color(&mut v.color); } } Shape::Callback(_) => { // Can't tint user callback code } } } fn adjust_color_mode( color_mode: &mut ColorMode, adjust_color: impl Fn(&mut Color32) + Send + Sync + Copy + 'static, ) { match color_mode { color::ColorMode::Solid(color) => adjust_color(color), color::ColorMode::UV(callback) => { let callback = Arc::clone(callback); *color_mode = color::ColorMode::UV(Arc::new(Box::new(move |rect, pos| { let mut color = callback(rect, pos); adjust_color(&mut color); color }))); } } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/epaint/src/texture_handle.rs
crates/epaint/src/texture_handle.rs
use std::sync::Arc; use crate::{ ImageData, ImageDelta, TextureId, TextureManager, emath::NumExt as _, mutex::RwLock, textures::TextureOptions, }; /// Used to paint images. /// /// An _image_ is pixels stored in RAM, and represented using [`ImageData`]. /// Before you can paint it however, you need to convert it to a _texture_. /// /// If you are using egui, use `egui::Context::load_texture`. /// /// The [`TextureHandle`] can be cloned cheaply. /// When the last [`TextureHandle`] for specific texture is dropped, the texture is freed. /// /// See also [`TextureManager`]. #[must_use] pub struct TextureHandle { tex_mngr: Arc<RwLock<TextureManager>>, id: TextureId, } impl Drop for TextureHandle { fn drop(&mut self) { self.tex_mngr.write().free(self.id); } } impl Clone for TextureHandle { fn clone(&self) -> Self { self.tex_mngr.write().retain(self.id); Self { tex_mngr: Arc::clone(&self.tex_mngr), id: self.id, } } } impl PartialEq for TextureHandle { #[inline] fn eq(&self, other: &Self) -> bool { self.id == other.id } } impl Eq for TextureHandle {} impl std::hash::Hash for TextureHandle { #[inline] fn hash<H: std::hash::Hasher>(&self, state: &mut H) { self.id.hash(state); } } impl TextureHandle { /// If you are using egui, use `egui::Context::load_texture` instead. pub fn new(tex_mngr: Arc<RwLock<TextureManager>>, id: TextureId) -> Self { Self { tex_mngr, id } } #[inline] pub fn id(&self) -> TextureId { self.id } /// Assign a new image to an existing texture. #[expect(clippy::needless_pass_by_ref_mut)] // Intentionally hide interiority of mutability pub fn set(&mut self, image: impl Into<ImageData>, options: TextureOptions) { self.tex_mngr .write() .set(self.id, ImageDelta::full(image.into(), options)); } /// Assign a new image to a subregion of the whole texture. #[expect(clippy::needless_pass_by_ref_mut)] // Intentionally hide interiority of mutability pub fn set_partial( &mut self, pos: [usize; 2], image: impl Into<ImageData>, options: TextureOptions, ) { self.tex_mngr .write() .set(self.id, ImageDelta::partial(pos, image.into(), options)); } /// width x height pub fn size(&self) -> [usize; 2] { self.tex_mngr .read() .meta(self.id) .map_or([0, 0], |tex| tex.size) } /// width x height pub fn size_vec2(&self) -> crate::Vec2 { let [w, h] = self.size(); crate::Vec2::new(w as f32, h as f32) } /// `width x height x bytes_per_pixel` pub fn byte_size(&self) -> usize { self.tex_mngr .read() .meta(self.id) .map_or(0, |tex| tex.bytes_used()) } /// width / height pub fn aspect_ratio(&self) -> f32 { let [w, h] = self.size(); w as f32 / h.at_least(1) as f32 } /// Debug-name. pub fn name(&self) -> String { self.tex_mngr .read() .meta(self.id) .map_or_else(|| "<none>".to_owned(), |tex| tex.name.clone()) } } impl From<&TextureHandle> for TextureId { #[inline(always)] fn from(handle: &TextureHandle) -> Self { handle.id() } } impl From<&mut TextureHandle> for TextureId { #[inline(always)] fn from(handle: &mut TextureHandle) -> Self { handle.id() } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/epaint/src/corner_radius_f32.rs
crates/epaint/src/corner_radius_f32.rs
use crate::CornerRadius; /// How rounded the corners of things should be, in `f32`. /// /// This is used for calculations, but storage is usually done with the more compact [`CornerRadius`]. #[derive(Copy, Clone, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct CornerRadiusF32 { /// Radius of the rounding of the North-West (left top) corner. pub nw: f32, /// Radius of the rounding of the North-East (right top) corner. pub ne: f32, /// Radius of the rounding of the South-West (left bottom) corner. pub sw: f32, /// Radius of the rounding of the South-East (right bottom) corner. pub se: f32, } impl From<CornerRadius> for CornerRadiusF32 { #[inline] fn from(cr: CornerRadius) -> Self { Self { nw: cr.nw as f32, ne: cr.ne as f32, sw: cr.sw as f32, se: cr.se as f32, } } } impl From<CornerRadiusF32> for CornerRadius { #[inline] fn from(cr: CornerRadiusF32) -> Self { Self { nw: cr.nw.round() as u8, ne: cr.ne.round() as u8, sw: cr.sw.round() as u8, se: cr.se.round() as u8, } } } impl Default for CornerRadiusF32 { #[inline] fn default() -> Self { Self::ZERO } } impl From<f32> for CornerRadiusF32 { #[inline] fn from(radius: f32) -> Self { Self { nw: radius, ne: radius, sw: radius, se: radius, } } } impl CornerRadiusF32 { /// No rounding on any corner. pub const ZERO: Self = Self { nw: 0.0, ne: 0.0, sw: 0.0, se: 0.0, }; /// Same rounding on all four corners. #[inline] pub const fn same(radius: f32) -> Self { Self { nw: radius, ne: radius, sw: radius, se: radius, } } /// Do all corners have the same rounding? #[inline] pub fn is_same(&self) -> bool { self.nw == self.ne && self.nw == self.sw && self.nw == self.se } /// Make sure each corner has a rounding of at least this. #[inline] pub fn at_least(&self, min: f32) -> Self { Self { nw: self.nw.max(min), ne: self.ne.max(min), sw: self.sw.max(min), se: self.se.max(min), } } /// Make sure each corner has a rounding of at most this. #[inline] pub fn at_most(&self, max: f32) -> Self { Self { nw: self.nw.min(max), ne: self.ne.min(max), sw: self.sw.min(max), se: self.se.min(max), } } } impl std::ops::Add for CornerRadiusF32 { type Output = Self; #[inline] fn add(self, rhs: Self) -> Self { Self { nw: self.nw + rhs.nw, ne: self.ne + rhs.ne, sw: self.sw + rhs.sw, se: self.se + rhs.se, } } } impl std::ops::AddAssign for CornerRadiusF32 { #[inline] fn add_assign(&mut self, rhs: Self) { *self = Self { nw: self.nw + rhs.nw, ne: self.ne + rhs.ne, sw: self.sw + rhs.sw, se: self.se + rhs.se, }; } } impl std::ops::AddAssign<f32> for CornerRadiusF32 { #[inline] fn add_assign(&mut self, rhs: f32) { *self = Self { nw: self.nw + rhs, ne: self.ne + rhs, sw: self.sw + rhs, se: self.se + rhs, }; } } impl std::ops::Sub for CornerRadiusF32 { type Output = Self; #[inline] fn sub(self, rhs: Self) -> Self { Self { nw: self.nw - rhs.nw, ne: self.ne - rhs.ne, sw: self.sw - rhs.sw, se: self.se - rhs.se, } } } impl std::ops::SubAssign for CornerRadiusF32 { #[inline] fn sub_assign(&mut self, rhs: Self) { *self = Self { nw: self.nw - rhs.nw, ne: self.ne - rhs.ne, sw: self.sw - rhs.sw, se: self.se - rhs.se, }; } } impl std::ops::SubAssign<f32> for CornerRadiusF32 { #[inline] fn sub_assign(&mut self, rhs: f32) { *self = Self { nw: self.nw - rhs, ne: self.ne - rhs, sw: self.sw - rhs, se: self.se - rhs, }; } } impl std::ops::Div<f32> for CornerRadiusF32 { type Output = Self; #[inline] fn div(self, rhs: f32) -> Self { Self { nw: self.nw / rhs, ne: self.ne / rhs, sw: self.sw / rhs, se: self.se / rhs, } } } impl std::ops::DivAssign<f32> for CornerRadiusF32 { #[inline] fn div_assign(&mut self, rhs: f32) { *self = Self { nw: self.nw / rhs, ne: self.ne / rhs, sw: self.sw / rhs, se: self.se / rhs, }; } } impl std::ops::Mul<f32> for CornerRadiusF32 { type Output = Self; #[inline] fn mul(self, rhs: f32) -> Self { Self { nw: self.nw * rhs, ne: self.ne * rhs, sw: self.sw * rhs, se: self.se * rhs, } } } impl std::ops::MulAssign<f32> for CornerRadiusF32 { #[inline] fn mul_assign(&mut self, rhs: f32) { *self = Self { nw: self.nw * rhs, ne: self.ne * rhs, sw: self.sw * rhs, se: self.se * rhs, }; } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/epaint/src/texture_atlas.rs
crates/epaint/src/texture_atlas.rs
use ecolor::Color32; use emath::{Rect, remap_clamp}; use crate::{ColorImage, ImageDelta, TextOptions}; #[derive(Clone, Copy, Debug, Eq, PartialEq)] struct Rectu { /// inclusive min_x: usize, /// inclusive min_y: usize, /// exclusive max_x: usize, /// exclusive max_y: usize, } impl Rectu { const NOTHING: Self = Self { min_x: usize::MAX, min_y: usize::MAX, max_x: 0, max_y: 0, }; const EVERYTHING: Self = Self { min_x: 0, min_y: 0, max_x: usize::MAX, max_y: usize::MAX, }; } #[derive(Copy, Clone, Debug)] struct PrerasterizedDisc { r: f32, uv: Rectu, } /// A pre-rasterized disc (filled circle), somewhere in the texture atlas. #[derive(Copy, Clone, Debug)] pub struct PreparedDisc { /// The radius of this disc in texels. pub r: f32, /// Width in texels. pub w: f32, /// Where in the texture atlas the disc is. /// Normalized in 0-1 range. pub uv: Rect, } /// Contains font data in an atlas, where each character occupied a small rectangle. /// /// More characters can be added, possibly expanding the texture. #[derive(Clone)] pub struct TextureAtlas { image: ColorImage, /// What part of the image that is dirty dirty: Rectu, /// Used for when allocating new rectangles. cursor: (usize, usize), row_height: usize, /// Set when someone requested more space than was available. overflowed: bool, /// pre-rasterized discs of radii `2^i`, where `i` is the index. discs: Vec<PrerasterizedDisc>, /// Controls how to convert glyph coverage to alpha. options: TextOptions, } impl TextureAtlas { pub fn new(size: [usize; 2], options: TextOptions) -> Self { assert!(size[0] >= 1024, "Tiny texture atlas"); let mut atlas = Self { image: ColorImage::filled(size, Color32::TRANSPARENT), dirty: Rectu::EVERYTHING, cursor: (0, 0), row_height: 0, overflowed: false, discs: vec![], // will be filled in below options, }; // Make the top left pixel fully white for `WHITE_UV`, i.e. painting something with solid color: let (pos, image) = atlas.allocate((1, 1)); assert_eq!( pos, (0, 0), "Expected the first allocation to be at (0, 0), but was at {pos:?}" ); image[pos] = Color32::WHITE; // Allocate a series of anti-aliased discs used to render small filled circles: // TODO(emilk): these circles can be packed A LOT better. // In fact, the whole texture atlas could be packed a lot better. // for r in [1, 2, 4, 8, 16, 32, 64] { // let w = 2 * r + 3; // let hw = w as i32 / 2; const LARGEST_CIRCLE_RADIUS: f32 = 8.0; // keep small so that the initial texture atlas is small for i in 0.. { let r = 2.0_f32.powf(i as f32 / 2.0 - 1.0); if r > LARGEST_CIRCLE_RADIUS { break; } let hw = (r + 0.5).ceil() as i32; let w = (2 * hw + 1) as usize; let ((x, y), image) = atlas.allocate((w, w)); for dx in -hw..=hw { for dy in -hw..=hw { let distance_to_center = ((dx * dx + dy * dy) as f32).sqrt(); let coverage = remap_clamp(distance_to_center, (r - 0.5)..=(r + 0.5), 1.0..=0.0); image[((x as i32 + hw + dx) as usize, (y as i32 + hw + dy) as usize)] = options.alpha_from_coverage.color_from_coverage(coverage); } } atlas.discs.push(PrerasterizedDisc { r, uv: Rectu { min_x: x, min_y: y, max_x: x + w, max_y: y + w, }, }); } atlas } pub fn options(&self) -> &TextOptions { &self.options } pub fn size(&self) -> [usize; 2] { self.image.size } /// Returns the locations and sizes of pre-rasterized discs (filled circles) in this atlas. pub fn prepared_discs(&self) -> Vec<PreparedDisc> { let size = self.size(); let inv_w = 1.0 / size[0] as f32; let inv_h = 1.0 / size[1] as f32; self.discs .iter() .map(|disc| { let r = disc.r; let Rectu { min_x, min_y, max_x, max_y, } = disc.uv; let w = max_x - min_x; let uv = Rect::from_min_max( emath::pos2(min_x as f32 * inv_w, min_y as f32 * inv_h), emath::pos2(max_x as f32 * inv_w, max_y as f32 * inv_h), ); PreparedDisc { r, w: w as f32, uv } }) .collect() } fn max_height(&self) -> usize { // the initial width is set to the max size self.image.height().max(self.image.width()) } /// When this get high, it might be time to clear and start over! pub fn fill_ratio(&self) -> f32 { if self.overflowed { 1.0 } else { (self.cursor.1 + self.row_height) as f32 / self.max_height() as f32 } } /// The texture options suitable for a font texture #[inline] pub fn texture_options() -> crate::textures::TextureOptions { crate::textures::TextureOptions::LINEAR } /// The full font atlas image. #[inline] pub fn image(&self) -> &ColorImage { &self.image } /// Call to get the change to the image since last call. pub fn take_delta(&mut self) -> Option<ImageDelta> { let texture_options = Self::texture_options(); let dirty = std::mem::replace(&mut self.dirty, Rectu::NOTHING); if dirty == Rectu::NOTHING { None } else if dirty == Rectu::EVERYTHING { Some(ImageDelta::full(self.image.clone(), texture_options)) } else { let pos = [dirty.min_x, dirty.min_y]; let size = [dirty.max_x - dirty.min_x, dirty.max_y - dirty.min_y]; let region = self.image.region_by_pixels(pos, size); Some(ImageDelta::partial(pos, region, texture_options)) } } /// Returns the coordinates of where the rect ended up, /// and invalidates the region. pub fn allocate(&mut self, (w, h): (usize, usize)) -> ((usize, usize), &mut ColorImage) { /// On some low-precision GPUs (my old iPad) characters get muddled up /// if we don't add some empty pixels between the characters. /// On modern high-precision GPUs this is not needed. const PADDING: usize = 1; assert!( w <= self.image.width(), "Tried to allocate a {} wide glyph in a {} wide texture atlas", w, self.image.width() ); if self.cursor.0 + w > self.image.width() { // New row: self.cursor.0 = 0; self.cursor.1 += self.row_height + PADDING; self.row_height = 0; } self.row_height = self.row_height.max(h); let required_height = self.cursor.1 + self.row_height; if required_height > self.max_height() { // This is a bad place to be - we need to start reusing space :/ log::warn!("epaint texture atlas overflowed!"); self.cursor = (0, self.image.height() / 3); // Restart a bit down - the top of the atlas has too many important things in it self.overflowed = true; // this will signal the user that we need to recreate the texture atlas next frame. } else if resize_to_min_height(&mut self.image, required_height) { self.dirty = Rectu::EVERYTHING; } let pos = self.cursor; self.cursor.0 += w + PADDING; self.dirty.min_x = self.dirty.min_x.min(pos.0); self.dirty.min_y = self.dirty.min_y.min(pos.1); self.dirty.max_x = self.dirty.max_x.max(pos.0 + w); self.dirty.max_y = self.dirty.max_y.max(pos.1 + h); (pos, &mut self.image) } } fn resize_to_min_height(image: &mut ColorImage, required_height: usize) -> bool { while required_height >= image.height() { image.size[1] *= 2; // double the height } if image.width() * image.height() > image.pixels.len() { image .pixels .resize(image.width() * image.height(), Color32::TRANSPARENT); true } else { false } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/epaint/src/textures.rs
crates/epaint/src/textures.rs
use crate::{ImageData, ImageDelta, TextureId}; // ---------------------------------------------------------------------------- /// Low-level manager for allocating textures. /// /// Communicates with the painting subsystem using [`Self::take_delta`]. #[derive(Default)] pub struct TextureManager { /// We allocate texture id:s linearly. next_id: u64, /// Information about currently allocated textures. metas: ahash::HashMap<TextureId, TextureMeta>, delta: TexturesDelta, } impl TextureManager { /// Allocate a new texture. /// /// The given name can be useful for later debugging. /// /// The returned [`TextureId`] will be [`TextureId::Managed`], with an index /// starting from zero and increasing with each call to [`Self::alloc`]. /// /// The first texture you allocate will be `TextureId::Managed(0) == TextureId::default()` and /// MUST have a white pixel at (0,0) ([`crate::WHITE_UV`]). /// /// The texture is given a retain-count of `1`, requiring one call to [`Self::free`] to free it. pub fn alloc(&mut self, name: String, image: ImageData, options: TextureOptions) -> TextureId { let id = TextureId::Managed(self.next_id); self.next_id += 1; self.metas.entry(id).or_insert_with(|| TextureMeta { name, size: image.size(), bytes_per_pixel: image.bytes_per_pixel(), retain_count: 1, options, }); self.delta.set.push((id, ImageDelta::full(image, options))); id } /// Assign a new image to an existing texture, /// or update a region of it. pub fn set(&mut self, id: TextureId, delta: ImageDelta) { if let Some(meta) = self.metas.get_mut(&id) { if let Some(pos) = delta.pos { debug_assert!( pos[0] + delta.image.width() <= meta.size[0] && pos[1] + delta.image.height() <= meta.size[1], "Partial texture update is outside the bounds of texture {id:?}", ); } else { // whole update meta.size = delta.image.size(); meta.bytes_per_pixel = delta.image.bytes_per_pixel(); // since we update the whole image, we can discard all old enqueued deltas self.delta.set.retain(|(x, _)| x != &id); } self.delta.set.push((id, delta)); } else { debug_assert!(false, "Tried setting texture {id:?} which is not allocated"); } } /// Free an existing texture. pub fn free(&mut self, id: TextureId) { if let std::collections::hash_map::Entry::Occupied(mut entry) = self.metas.entry(id) { let meta = entry.get_mut(); meta.retain_count -= 1; if meta.retain_count == 0 { entry.remove(); self.delta.free.push(id); } } else { debug_assert!(false, "Tried freeing texture {id:?} which is not allocated"); } } /// Increase the retain-count of the given texture. /// /// For each time you call [`Self::retain`] you must call [`Self::free`] on additional time. pub fn retain(&mut self, id: TextureId) { if let Some(meta) = self.metas.get_mut(&id) { meta.retain_count += 1; } else { debug_assert!( false, "Tried retaining texture {id:?} which is not allocated", ); } } /// Take and reset changes since last frame. /// /// These should be applied to the painting subsystem each frame. pub fn take_delta(&mut self) -> TexturesDelta { std::mem::take(&mut self.delta) } /// Get meta-data about a specific texture. pub fn meta(&self, id: TextureId) -> Option<&TextureMeta> { self.metas.get(&id) } /// Get meta-data about all allocated textures in some arbitrary order. pub fn allocated(&self) -> impl ExactSizeIterator<Item = (&TextureId, &TextureMeta)> { self.metas.iter() } /// Total number of allocated textures. pub fn num_allocated(&self) -> usize { self.metas.len() } } /// Meta-data about an allocated texture. #[derive(Clone, Debug, PartialEq, Eq)] pub struct TextureMeta { /// A human-readable name useful for debugging. pub name: String, /// width x height pub size: [usize; 2], /// 4 or 1 pub bytes_per_pixel: usize, /// Free when this reaches zero. pub retain_count: usize, /// The texture filtering mode to use when rendering. pub options: TextureOptions, } impl TextureMeta { /// Size in bytes. /// width x height x [`Self::bytes_per_pixel`]. pub fn bytes_used(&self) -> usize { self.size[0] * self.size[1] * self.bytes_per_pixel } } // ---------------------------------------------------------------------------- /// How the texture texels are filtered. #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct TextureOptions { /// How to filter when magnifying (when texels are larger than pixels). pub magnification: TextureFilter, /// How to filter when minifying (when texels are smaller than pixels). pub minification: TextureFilter, /// How to wrap the texture when the texture coordinates are outside the [0, 1] range. pub wrap_mode: TextureWrapMode, /// How to filter between texture mipmaps. /// /// Mipmaps ensures textures look smooth even when the texture is very small and pixels are much /// larger than individual texels. /// /// # Notes /// /// - This may not be available on all backends (currently only `egui_glow`). pub mipmap_mode: Option<TextureFilter>, } impl TextureOptions { /// Linear magnification and minification. pub const LINEAR: Self = Self { magnification: TextureFilter::Linear, minification: TextureFilter::Linear, wrap_mode: TextureWrapMode::ClampToEdge, mipmap_mode: None, }; /// Nearest magnification and minification. pub const NEAREST: Self = Self { magnification: TextureFilter::Nearest, minification: TextureFilter::Nearest, wrap_mode: TextureWrapMode::ClampToEdge, mipmap_mode: None, }; /// Linear magnification and minification, but with the texture repeated. pub const LINEAR_REPEAT: Self = Self { magnification: TextureFilter::Linear, minification: TextureFilter::Linear, wrap_mode: TextureWrapMode::Repeat, mipmap_mode: None, }; /// Linear magnification and minification, but with the texture mirrored and repeated. pub const LINEAR_MIRRORED_REPEAT: Self = Self { magnification: TextureFilter::Linear, minification: TextureFilter::Linear, wrap_mode: TextureWrapMode::MirroredRepeat, mipmap_mode: None, }; /// Nearest magnification and minification, but with the texture repeated. pub const NEAREST_REPEAT: Self = Self { magnification: TextureFilter::Nearest, minification: TextureFilter::Nearest, wrap_mode: TextureWrapMode::Repeat, mipmap_mode: None, }; /// Nearest magnification and minification, but with the texture mirrored and repeated. pub const NEAREST_MIRRORED_REPEAT: Self = Self { magnification: TextureFilter::Nearest, minification: TextureFilter::Nearest, wrap_mode: TextureWrapMode::MirroredRepeat, mipmap_mode: None, }; pub const fn with_mipmap_mode(self, mipmap_mode: Option<TextureFilter>) -> Self { Self { mipmap_mode, ..self } } } impl Default for TextureOptions { /// The default is linear for both magnification and minification. fn default() -> Self { Self::LINEAR } } /// How the texture texels are filtered. #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub enum TextureFilter { /// Show the nearest pixel value. /// /// When zooming in you will get sharp, square pixels/texels. /// When zooming out you will get a very crisp (and aliased) look. Nearest, /// Linearly interpolate the nearest neighbors, creating a smoother look when zooming in and out. Linear, } /// Defines how textures are wrapped around objects when texture coordinates fall outside the [0, 1] range. #[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub enum TextureWrapMode { /// Stretches the edge pixels to fill beyond the texture's bounds. /// /// This is what you want to use for a normal image in a GUI. #[default] ClampToEdge, /// Tiles the texture across the surface, repeating it horizontally and vertically. Repeat, /// Mirrors the texture with each repetition, creating symmetrical tiling. MirroredRepeat, } // ---------------------------------------------------------------------------- /// What has been allocated and freed during the last period. /// /// These are commands given to the integration painter. #[derive(Clone, Default, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[must_use = "The painter must take care of this"] pub struct TexturesDelta { /// New or changed textures. Apply before painting. pub set: Vec<(TextureId, ImageDelta)>, /// Textures to free after painting. pub free: Vec<TextureId>, } impl TexturesDelta { pub fn is_empty(&self) -> bool { self.set.is_empty() && self.free.is_empty() } pub fn append(&mut self, mut newer: Self) { self.set.extend(newer.set); self.free.append(&mut newer.free); } pub fn clear(&mut self) { self.set.clear(); self.free.clear(); } } impl std::fmt::Debug for TexturesDelta { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { use std::fmt::Write as _; let mut debug_struct = f.debug_struct("TexturesDelta"); if !self.set.is_empty() { let mut string = String::new(); for (tex_id, delta) in &self.set { let size = delta.image.size(); if let Some(pos) = delta.pos { write!( string, "{:?} partial ([{} {}] - [{} {}]), ", tex_id, pos[0], pos[1], pos[0] + size[0], pos[1] + size[1] ) .ok(); } else { write!(string, "{:?} full {}x{}, ", tex_id, size[0], size[1]).ok(); } } debug_struct.field("set", &string); } if !self.free.is_empty() { debug_struct.field("free", &self.free); } debug_struct.finish() } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/epaint/src/brush.rs
crates/epaint/src/brush.rs
use crate::{Rect, TextureId}; /// Controls texturing of a [`crate::RectShape`]. #[derive(Copy, Clone, Debug, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct Brush { /// If the rect should be filled with a texture, which one? /// /// The texture is multiplied with [`crate::RectShape::fill`]. pub fill_texture_id: TextureId, /// What UV coordinates to use for the texture? /// /// To display a texture, set [`Self::fill_texture_id`], /// and set this to `Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0))`. /// /// Use [`Rect::ZERO`] to turn off texturing. pub uv: Rect, }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/epaint/src/color.rs
crates/epaint/src/color.rs
use std::{fmt::Debug, sync::Arc}; use ecolor::Color32; use emath::{Pos2, Rect}; /// How paths will be colored. #[derive(Clone)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub enum ColorMode { /// The entire path is one solid color, this is the default. Solid(Color32), /// Provide a callback which takes in the path's bounding box and a position and converts it to a color. /// When used with a path, the bounding box will have a margin of [`TessellationOptions::feathering_size_in_pixels`](`crate::tessellator::TessellationOptions::feathering_size_in_pixels`) /// /// **This cannot be serialized** #[cfg_attr(feature = "serde", serde(skip))] UV(Arc<dyn Fn(Rect, Pos2) -> Color32 + Send + Sync>), } impl Default for ColorMode { fn default() -> Self { Self::Solid(Color32::TRANSPARENT) } } impl Debug for ColorMode { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Solid(arg0) => f.debug_tuple("Solid").field(arg0).finish(), Self::UV(_arg0) => f.debug_tuple("UV").field(&"<closure>").finish(), } } } impl PartialEq for ColorMode { fn eq(&self, other: &Self) -> bool { match (self, other) { (Self::Solid(l0), Self::Solid(r0)) => l0 == r0, (Self::UV(_l0), Self::UV(_r0)) => false, _ => false, } } } impl ColorMode { pub const TRANSPARENT: Self = Self::Solid(Color32::TRANSPARENT); }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/epaint/src/util/mod.rs
crates/epaint/src/util/mod.rs
/// Hash the given value with a predictable hasher. #[inline] pub fn hash(value: impl std::hash::Hash) -> u64 { ahash::RandomState::with_seeds(1, 2, 3, 4).hash_one(value) } /// Hash the given value with the given hasher. #[inline] pub fn hash_with(value: impl std::hash::Hash, mut hasher: impl std::hash::Hasher) -> u64 { value.hash(&mut hasher); hasher.finish() }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/epaint/src/text/cursor.rs
crates/epaint/src/text/cursor.rs
//! Different types of text cursors, i.e. ways to point into a [`super::Galley`]. /// Character cursor. /// /// The default cursor is zero. #[derive(Clone, Copy, Debug, Default)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct CCursor { /// Character offset (NOT byte offset!). pub index: usize, /// If this cursors sits right at the border of a wrapped row break (NOT paragraph break) /// do we prefer the next row? /// This is *almost* always what you want, *except* for when /// explicitly clicking the end of a row or pressing the end key. pub prefer_next_row: bool, } impl CCursor { #[inline] pub fn new(index: usize) -> Self { Self { index, prefer_next_row: false, } } } /// Two `CCursor`s are considered equal if they refer to the same character boundary, /// even if one prefers the start of the next row. impl PartialEq for CCursor { #[inline] fn eq(&self, other: &Self) -> bool { self.index == other.index } } impl std::ops::Add<usize> for CCursor { type Output = Self; fn add(self, rhs: usize) -> Self::Output { Self { index: self.index.saturating_add(rhs), prefer_next_row: self.prefer_next_row, } } } impl std::ops::Sub<usize> for CCursor { type Output = Self; fn sub(self, rhs: usize) -> Self::Output { Self { index: self.index.saturating_sub(rhs), prefer_next_row: self.prefer_next_row, } } } impl std::ops::AddAssign<usize> for CCursor { fn add_assign(&mut self, rhs: usize) { self.index = self.index.saturating_add(rhs); } } impl std::ops::SubAssign<usize> for CCursor { fn sub_assign(&mut self, rhs: usize) { self.index = self.index.saturating_sub(rhs); } } /// Row/column cursor. /// /// This refers to rows and columns in layout terms--text wrapping creates multiple rows. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct LayoutCursor { /// 0 is first row, and so on. /// Note that a single paragraph can span multiple rows. /// (a paragraph is text separated by `\n`). pub row: usize, /// Character based (NOT bytes). /// It is fine if this points to something beyond the end of the current row. /// When moving up/down it may again be within the next row. pub column: usize, }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/epaint/src/text/fonts.rs
crates/epaint/src/text/fonts.rs
use std::{ borrow::Cow, collections::BTreeMap, sync::{ Arc, atomic::{AtomicU64, Ordering}, }, }; use crate::{ TextureAtlas, text::{ Galley, LayoutJob, LayoutSection, TextOptions, font::{Font, FontFace, GlyphInfo}, }, }; use emath::{NumExt as _, OrderedFloat}; #[cfg(feature = "default_fonts")] use epaint_default_fonts::{EMOJI_ICON, HACK_REGULAR, NOTO_EMOJI_REGULAR, UBUNTU_LIGHT}; // ---------------------------------------------------------------------------- /// How to select a sized font. #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct FontId { /// Height in points. pub size: f32, /// What font family to use. pub family: FontFamily, // TODO(emilk): weight (bold), italics, … } impl Default for FontId { #[inline] fn default() -> Self { Self { size: 14.0, family: FontFamily::Proportional, } } } impl FontId { #[inline] pub const fn new(size: f32, family: FontFamily) -> Self { Self { size, family } } #[inline] pub const fn proportional(size: f32) -> Self { Self::new(size, FontFamily::Proportional) } #[inline] pub const fn monospace(size: f32) -> Self { Self::new(size, FontFamily::Monospace) } } impl std::hash::Hash for FontId { #[inline(always)] fn hash<H: std::hash::Hasher>(&self, state: &mut H) { let Self { size, family } = self; emath::OrderedFloat(*size).hash(state); family.hash(state); } } // ---------------------------------------------------------------------------- /// Font of unknown size. /// /// Which style of font: [`Monospace`][`FontFamily::Monospace`], [`Proportional`][`FontFamily::Proportional`], /// or by user-chosen name. #[derive(Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub enum FontFamily { /// A font where some characters are wider than other (e.g. 'w' is wider than 'i'). /// /// Proportional fonts are easier to read and should be the preferred choice in most situations. #[default] Proportional, /// A font where each character is the same width (`w` is the same width as `i`). /// /// Useful for code snippets, or when you need to align numbers or text. Monospace, /// One of the names in [`FontDefinitions::families`]. /// /// ``` /// # use epaint::FontFamily; /// // User-chosen names: /// FontFamily::Name("arial".into()); /// FontFamily::Name("serif".into()); /// ``` Name(Arc<str>), } impl std::fmt::Display for FontFamily { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Monospace => "Monospace".fmt(f), Self::Proportional => "Proportional".fmt(f), Self::Name(name) => (*name).fmt(f), } } } // ---------------------------------------------------------------------------- /// A `.ttf` or `.otf` file and a font face index. #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct FontData { /// The content of a `.ttf` or `.otf` file. pub font: Cow<'static, [u8]>, /// Which font face in the file to use. /// When in doubt, use `0`. pub index: u32, /// Extra scale and vertical tweak to apply to all text of this font. pub tweak: FontTweak, /// The font weight (100-900), if available. /// Standard values: 100 (Thin), 200 (Extra Light), 300 (Light), 400 (Regular), /// 500 (Medium), 600 (Semi Bold), 700 (Bold), 800 (Extra Bold), 900 (Black). /// `None` if the weight could not be determined. pub weight: Option<u16>, } impl FontData { pub fn from_static(font: &'static [u8]) -> Self { Self { font: Cow::Borrowed(font), index: 0, tweak: Default::default(), weight: None, } } pub fn from_owned(font: Vec<u8>) -> Self { Self { font: Cow::Owned(font), index: 0, tweak: Default::default(), weight: None, } } pub fn tweak(self, tweak: FontTweak) -> Self { Self { tweak, ..self } } /// Set the font weight (100-900). /// /// This is typically read automatically from the font file when loaded, /// but can be overridden manually if needed. /// /// Standard weight values: /// - 100: Thin /// - 200: Extra Light /// - 300: Light /// - 400: Regular/Normal /// - 500: Medium /// - 600: Semi Bold /// - 700: Bold /// - 800: Extra Bold /// - 900: Black /// /// # Example /// ``` /// # use epaint::text::FontData; /// let font_data = FontData::from_static(include_bytes!("../../../epaint_default_fonts/fonts/Ubuntu-Light.ttf")) /// .weight(300); // Override to Light weight /// assert_eq!(font_data.weight, Some(300)); /// ``` pub fn weight(self, weight: u16) -> Self { Self { weight: Some(weight), ..self } } } impl AsRef<[u8]> for FontData { fn as_ref(&self) -> &[u8] { self.font.as_ref() } } // ---------------------------------------------------------------------------- /// Extra scale and vertical tweak to apply to all text of a certain font. #[derive(Copy, Clone, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct FontTweak { /// Scale the font's glyphs by this much. /// this is only a visual effect and does not affect the text layout. /// /// Default: `1.0` (no scaling). pub scale: f32, /// Shift font's glyphs downwards by this fraction of the font size (in points). /// this is only a visual effect and does not affect the text layout. /// /// Affects larger font sizes more. /// /// A positive value shifts the text downwards. /// A negative value shifts it upwards. /// /// Example value: `-0.2`. pub y_offset_factor: f32, /// Shift font's glyphs downwards by this amount of logical points. /// this is only a visual effect and does not affect the text layout. /// /// Affects all font sizes equally. /// /// Example value: `2.0`. pub y_offset: f32, /// Override the global font hinting setting for this specific font. /// /// `None` means use the global setting. pub hinting_override: Option<bool>, } impl Default for FontTweak { fn default() -> Self { Self { scale: 1.0, y_offset_factor: 0.0, y_offset: 0.0, hinting_override: None, } } } // ---------------------------------------------------------------------------- pub type Blob = Arc<dyn AsRef<[u8]> + Send + Sync>; fn blob_from_font_data(data: &FontData) -> Blob { match data.clone().font { Cow::Borrowed(bytes) => Arc::new(bytes) as Blob, Cow::Owned(bytes) => Arc::new(bytes) as Blob, } } /// Describes the font data and the sizes to use. /// /// Often you would start with [`FontDefinitions::default()`] and then add/change the contents. /// /// This is how you install your own custom fonts: /// ``` /// # use {epaint::text::{FontDefinitions, FontFamily, FontData}}; /// # struct FakeEguiCtx {}; /// # impl FakeEguiCtx { fn set_fonts(&self, _: FontDefinitions) {} } /// # let egui_ctx = FakeEguiCtx {}; /// let mut fonts = FontDefinitions::default(); /// /// // Install my own font (maybe supporting non-latin characters): /// fonts.font_data.insert("my_font".to_owned(), /// std::sync::Arc::new( /// // .ttf and .otf supported /// FontData::from_static(include_bytes!("../../../epaint_default_fonts/fonts/Ubuntu-Light.ttf")) /// ) /// ); /// /// // Put my font first (highest priority): /// fonts.families.get_mut(&FontFamily::Proportional).unwrap() /// .insert(0, "my_font".to_owned()); /// /// // Put my font as last fallback for monospace: /// fonts.families.get_mut(&FontFamily::Monospace).unwrap() /// .push("my_font".to_owned()); /// /// egui_ctx.set_fonts(fonts); /// ``` #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] pub struct FontDefinitions { /// List of font names and their definitions. /// /// `epaint` has built-in-default for these, but you can override them if you like. pub font_data: BTreeMap<String, Arc<FontData>>, /// Which fonts (names) to use for each [`FontFamily`]. /// /// The list should be a list of keys into [`Self::font_data`]. /// When looking for a character glyph `epaint` will start with /// the first font and then move to the second, and so on. /// So the first font is the primary, and then comes a list of fallbacks in order of priority. pub families: BTreeMap<FontFamily, Vec<String>>, } #[derive(Debug, Clone)] pub struct FontInsert { /// Font name pub name: String, /// A `.ttf` or `.otf` file and a font face index. pub data: FontData, /// Sets the font family and priority pub families: Vec<InsertFontFamily>, } #[derive(Debug, Clone)] pub struct InsertFontFamily { /// Font family pub family: FontFamily, /// Fallback or Primary font pub priority: FontPriority, } #[derive(Debug, Clone)] pub enum FontPriority { /// Prefer this font before all existing ones. /// /// If a desired glyph exists in this font, it will be used. Highest, /// Use this font as a fallback, after all existing ones. /// /// This font will only be used if the glyph is not found in any of the previously installed fonts. Lowest, } impl FontInsert { pub fn new(name: &str, data: FontData, families: Vec<InsertFontFamily>) -> Self { Self { name: name.to_owned(), data, families, } } } impl Default for FontDefinitions { /// Specifies the default fonts if the feature `default_fonts` is enabled, /// otherwise this is the same as [`Self::empty`]. #[cfg(not(feature = "default_fonts"))] fn default() -> Self { Self::empty() } /// Specifies the default fonts if the feature `default_fonts` is enabled, /// otherwise this is the same as [`Self::empty`]. #[cfg(feature = "default_fonts")] fn default() -> Self { let mut font_data: BTreeMap<String, Arc<FontData>> = BTreeMap::new(); let mut families = BTreeMap::new(); font_data.insert( "Hack".to_owned(), Arc::new(FontData::from_static(HACK_REGULAR)), ); // Some good looking emojis. Use as first priority: font_data.insert( "NotoEmoji-Regular".to_owned(), Arc::new(FontData::from_static(NOTO_EMOJI_REGULAR).tweak(FontTweak { scale: 0.81, // Make smaller ..Default::default() })), ); font_data.insert( "Ubuntu-Light".to_owned(), Arc::new(FontData::from_static(UBUNTU_LIGHT)), ); // Bigger emojis, and more. <http://jslegers.github.io/emoji-icon-font/>: font_data.insert( "emoji-icon-font".to_owned(), Arc::new(FontData::from_static(EMOJI_ICON).tweak(FontTweak { scale: 0.90, // Make smaller ..Default::default() })), ); families.insert( FontFamily::Monospace, vec![ "Hack".to_owned(), "Ubuntu-Light".to_owned(), // fallback for √ etc "NotoEmoji-Regular".to_owned(), "emoji-icon-font".to_owned(), ], ); families.insert( FontFamily::Proportional, vec![ "Ubuntu-Light".to_owned(), "NotoEmoji-Regular".to_owned(), "emoji-icon-font".to_owned(), ], ); Self { font_data, families, } } } impl FontDefinitions { /// No fonts. pub fn empty() -> Self { let mut families = BTreeMap::new(); families.insert(FontFamily::Monospace, vec![]); families.insert(FontFamily::Proportional, vec![]); Self { font_data: Default::default(), families, } } /// List of all the builtin font names used by `epaint`. #[cfg(feature = "default_fonts")] pub fn builtin_font_names() -> &'static [&'static str] { &[ "Ubuntu-Light", "NotoEmoji-Regular", "emoji-icon-font", "Hack", ] } /// List of all the builtin font names used by `epaint`. #[cfg(not(feature = "default_fonts"))] pub fn builtin_font_names() -> &'static [&'static str] { &[] } } /// Unique ID for looking up a single font face/file. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub(crate) struct FontFaceKey(u64); impl FontFaceKey { pub const INVALID: Self = Self(0); fn new() -> Self { static KEY_COUNTER: AtomicU64 = AtomicU64::new(1); Self(crate::util::hash( KEY_COUNTER.fetch_add(1, Ordering::Relaxed), )) } } // Safe, because we hash the value in the constructor. impl nohash_hasher::IsEnabled for FontFaceKey {} /// Cached data for working with a font family (e.g. doing character lookups). #[derive(Debug)] pub(super) struct CachedFamily { pub fonts: Vec<FontFaceKey>, /// Lazily calculated. pub characters: Option<BTreeMap<char, Vec<String>>>, pub replacement_glyph: (FontFaceKey, GlyphInfo), pub glyph_info_cache: ahash::HashMap<char, (FontFaceKey, GlyphInfo)>, } impl CachedFamily { fn new( fonts: Vec<FontFaceKey>, fonts_by_id: &mut nohash_hasher::IntMap<FontFaceKey, FontFace>, ) -> Self { if fonts.is_empty() { return Self { fonts, characters: None, replacement_glyph: (FontFaceKey::INVALID, GlyphInfo::INVISIBLE), glyph_info_cache: Default::default(), }; } let mut slf = Self { fonts, characters: None, replacement_glyph: (FontFaceKey::INVALID, GlyphInfo::INVISIBLE), glyph_info_cache: Default::default(), }; const PRIMARY_REPLACEMENT_CHAR: char = '◻'; // white medium square const FALLBACK_REPLACEMENT_CHAR: char = '?'; // fallback for the fallback let replacement_glyph = slf .glyph_info_no_cache_or_fallback(PRIMARY_REPLACEMENT_CHAR, fonts_by_id) .or_else(|| slf.glyph_info_no_cache_or_fallback(FALLBACK_REPLACEMENT_CHAR, fonts_by_id)) .unwrap_or_else(|| { log::warn!( "Failed to find replacement characters {PRIMARY_REPLACEMENT_CHAR:?} or {FALLBACK_REPLACEMENT_CHAR:?}. Will use empty glyph." ); (FontFaceKey::INVALID, GlyphInfo::INVISIBLE) }); slf.replacement_glyph = replacement_glyph; slf } pub(crate) fn glyph_info_no_cache_or_fallback( &mut self, c: char, fonts_by_id: &mut nohash_hasher::IntMap<FontFaceKey, FontFace>, ) -> Option<(FontFaceKey, GlyphInfo)> { for font_key in &self.fonts { let font_face = fonts_by_id.get_mut(font_key).expect("Nonexistent font ID"); if let Some(glyph_info) = font_face.glyph_info(c) { self.glyph_info_cache.insert(c, (*font_key, glyph_info)); return Some((*font_key, glyph_info)); } } None } } // ---------------------------------------------------------------------------- /// The collection of fonts used by `epaint`. /// /// Required in order to paint text. Create one and reuse. Cheap to clone. /// /// Each [`Fonts`] comes with a font atlas textures that needs to be used when painting. /// /// If you are using `egui`, use `egui::Context::set_fonts` and `egui::Context::fonts`. /// /// You need to call [`Self::begin_pass`] and [`Self::font_image_delta`] once every frame. pub struct Fonts { pub fonts: FontsImpl, galley_cache: GalleyCache, } impl Fonts { /// Create a new [`Fonts`] for text layout. /// This call is expensive, so only create one [`Fonts`] and then reuse it. pub fn new(options: TextOptions, definitions: FontDefinitions) -> Self { Self { fonts: FontsImpl::new(options, definitions), galley_cache: Default::default(), } } /// Call at the start of each frame with the latest known [`TextOptions`]. /// /// Call after painting the previous frame, but before using [`Fonts`] for the new frame. /// /// This function will react to changes in [`TextOptions`], /// as well as notice when the font atlas is getting full, and handle that. pub fn begin_pass(&mut self, options: TextOptions) { let text_options_changed = self.fonts.options() != &options; let font_atlas_almost_full = self.fonts.atlas.fill_ratio() > 0.8; let needs_recreate = text_options_changed || font_atlas_almost_full; if needs_recreate { let definitions = self.fonts.definitions.clone(); *self = Self { fonts: FontsImpl::new(options, definitions), galley_cache: Default::default(), }; } self.galley_cache.flush_cache(); } /// Call at the end of each frame (before painting) to get the change to the font texture since last call. pub fn font_image_delta(&mut self) -> Option<crate::ImageDelta> { self.fonts.atlas.take_delta() } #[inline] pub fn options(&self) -> &TextOptions { self.texture_atlas().options() } #[inline] pub fn definitions(&self) -> &FontDefinitions { &self.fonts.definitions } /// The font atlas. /// Pass this to [`crate::Tessellator`]. pub fn texture_atlas(&self) -> &TextureAtlas { &self.fonts.atlas } /// The full font atlas image. #[inline] pub fn image(&self) -> crate::ColorImage { self.fonts.atlas.image().clone() } /// Current size of the font image. /// Pass this to [`crate::Tessellator`]. pub fn font_image_size(&self) -> [usize; 2] { self.fonts.atlas.size() } /// Can we display this glyph? pub fn has_glyph(&mut self, font_id: &FontId, c: char) -> bool { self.fonts.font(&font_id.family).has_glyph(c) } /// Can we display all the glyphs in this text? pub fn has_glyphs(&mut self, font_id: &FontId, s: &str) -> bool { self.fonts.font(&font_id.family).has_glyphs(s) } pub fn num_galleys_in_cache(&self) -> usize { self.galley_cache.num_galleys_in_cache() } /// How full is the font atlas? /// /// This increases as new fonts and/or glyphs are used, /// but can also decrease in a call to [`Self::begin_pass`]. pub fn font_atlas_fill_ratio(&self) -> f32 { self.fonts.atlas.fill_ratio() } /// Returns a [`FontsView`] with the given `pixels_per_point` that can be used to do text layout. pub fn with_pixels_per_point(&mut self, pixels_per_point: f32) -> FontsView<'_> { FontsView { fonts: &mut self.fonts, galley_cache: &mut self.galley_cache, pixels_per_point, } } } // ---------------------------------------------------------------------------- /// The context's collection of fonts, with this context's `pixels_per_point`. This is what you use to do text layout. pub struct FontsView<'a> { pub fonts: &'a mut FontsImpl, galley_cache: &'a mut GalleyCache, pixels_per_point: f32, } impl FontsView<'_> { #[inline] pub fn options(&self) -> &TextOptions { self.fonts.options() } #[inline] pub fn definitions(&self) -> &FontDefinitions { &self.fonts.definitions } /// The full font atlas image. #[inline] pub fn image(&self) -> crate::ColorImage { self.fonts.atlas.image().clone() } /// Current size of the font image. /// Pass this to [`crate::Tessellator`]. pub fn font_image_size(&self) -> [usize; 2] { self.fonts.atlas.size() } /// Width of this character in points. /// /// If the font doesn't exist, this will return `0.0`. pub fn glyph_width(&mut self, font_id: &FontId, c: char) -> f32 { self.fonts .font(&font_id.family) .glyph_width(c, font_id.size) } /// Can we display this glyph? pub fn has_glyph(&mut self, font_id: &FontId, c: char) -> bool { self.fonts.font(&font_id.family).has_glyph(c) } /// Can we display all the glyphs in this text? pub fn has_glyphs(&mut self, font_id: &FontId, s: &str) -> bool { self.fonts.font(&font_id.family).has_glyphs(s) } /// Height of one row of text in points. /// /// Returns a value rounded to [`emath::GUI_ROUNDING`]. #[inline] pub fn row_height(&mut self, font_id: &FontId) -> f32 { self.fonts .font(&font_id.family) .scaled_metrics(self.pixels_per_point, font_id.size) .row_height } /// List of all known font families. pub fn families(&self) -> Vec<FontFamily> { self.fonts.definitions.families.keys().cloned().collect() } /// Layout some text. /// /// This is the most advanced layout function. /// See also [`Self::layout`], [`Self::layout_no_wrap`] and /// [`Self::layout_delayed_color`]. /// /// The implementation uses memoization so repeated calls are cheap. #[inline] pub fn layout_job(&mut self, job: LayoutJob) -> Arc<Galley> { let allow_split_paragraphs = true; // Optimization for editing text with many paragraphs. self.galley_cache.layout( self.fonts, self.pixels_per_point, job, allow_split_paragraphs, ) } pub fn num_galleys_in_cache(&self) -> usize { self.galley_cache.num_galleys_in_cache() } /// How full is the font atlas? /// /// This increases as new fonts and/or glyphs are used, /// but can also decrease in a call to [`Fonts::begin_pass`]. pub fn font_atlas_fill_ratio(&self) -> f32 { self.fonts.atlas.fill_ratio() } /// Will wrap text at the given width and line break at `\n`. /// /// The implementation uses memoization so repeated calls are cheap. #[inline] pub fn layout( &mut self, text: String, font_id: FontId, color: crate::Color32, wrap_width: f32, ) -> Arc<Galley> { let job = LayoutJob::simple(text, font_id, color, wrap_width); self.layout_job(job) } /// Will line break at `\n`. /// /// The implementation uses memoization so repeated calls are cheap. #[inline] pub fn layout_no_wrap( &mut self, text: String, font_id: FontId, color: crate::Color32, ) -> Arc<Galley> { let job = LayoutJob::simple(text, font_id, color, f32::INFINITY); self.layout_job(job) } /// Like [`Self::layout`], made for when you want to pick a color for the text later. /// /// The implementation uses memoization so repeated calls are cheap. #[inline] pub fn layout_delayed_color( &mut self, text: String, font_id: FontId, wrap_width: f32, ) -> Arc<Galley> { self.layout(text, font_id, crate::Color32::PLACEHOLDER, wrap_width) } } // ---------------------------------------------------------------------------- /// The collection of fonts used by `epaint`. /// /// Required in order to paint text. pub struct FontsImpl { definitions: FontDefinitions, atlas: TextureAtlas, fonts_by_id: nohash_hasher::IntMap<FontFaceKey, FontFace>, fonts_by_name: ahash::HashMap<String, FontFaceKey>, family_cache: ahash::HashMap<FontFamily, CachedFamily>, } impl FontsImpl { /// Create a new [`FontsImpl`] for text layout. /// This call is expensive, so only create one [`FontsImpl`] and then reuse it. pub fn new(options: TextOptions, definitions: FontDefinitions) -> Self { let texture_width = options.max_texture_side.at_most(16 * 1024); let initial_height = 32; // Keep initial font atlas small, so it is fast to upload to GPU. This will expand as needed anyways. let atlas = TextureAtlas::new([texture_width, initial_height], options); let mut fonts_by_id: nohash_hasher::IntMap<FontFaceKey, FontFace> = Default::default(); let mut fonts_by_name: ahash::HashMap<String, FontFaceKey> = Default::default(); for (name, font_data) in &definitions.font_data { let tweak = font_data.tweak; let blob = blob_from_font_data(font_data); let font_face = FontFace::new( options, name.clone(), blob, font_data.index, tweak, font_data.weight, ) .unwrap_or_else(|err| panic!("Error parsing {name:?} TTF/OTF font file: {err}")); let key = FontFaceKey::new(); fonts_by_id.insert(key, font_face); fonts_by_name.insert(name.clone(), key); } Self { definitions, atlas, fonts_by_id, fonts_by_name, family_cache: Default::default(), } } pub fn options(&self) -> &TextOptions { self.atlas.options() } /// Get the right font implementation from [`FontFamily`]. pub fn font(&mut self, family: &FontFamily) -> Font<'_> { let cached_family = self.family_cache.entry(family.clone()).or_insert_with(|| { let fonts = &self.definitions.families.get(family); let fonts = fonts.unwrap_or_else(|| panic!("FontFamily::{family:?} is not bound to any fonts")); let fonts: Vec<FontFaceKey> = fonts .iter() .map(|font_name| { *self .fonts_by_name .get(font_name) .unwrap_or_else(|| panic!("No font data found for {font_name:?}")) }) .collect(); CachedFamily::new(fonts, &mut self.fonts_by_id) }); Font { fonts_by_id: &mut self.fonts_by_id, cached_family, atlas: &mut self.atlas, } } /// Get the weight of a font by name, if available. /// /// Returns the weight value (100-900) read from the font file's OS/2 table, /// or `None` if the font is not found or doesn't contain weight information. /// /// # Example /// ``` /// # use epaint::text::{FontDefinitions, FontsImpl}; /// # use epaint::TextOptions; /// let fonts_impl = FontsImpl::new(TextOptions::default(), FontDefinitions::default()); /// if let Some(weight) = fonts_impl.font_weight("Hack") { /// println!("Hack font weight: {}", weight); /// } /// ``` pub fn font_weight(&self, font_name: &str) -> Option<u16> { let key = self.fonts_by_name.get(font_name)?; let font_face = self.fonts_by_id.get(key)?; font_face.weight() } } // ---------------------------------------------------------------------------- struct CachedGalley { /// When it was last used last_used: u32, /// Hashes of all other entries this one depends on for quick re-layout. /// Their `last_used`s should be updated alongside this one to make sure they're /// not evicted. children: Option<Arc<[u64]>>, galley: Arc<Galley>, } #[derive(Default)] struct GalleyCache { /// Frame counter used to do garbage collection on the cache generation: u32, cache: nohash_hasher::IntMap<u64, CachedGalley>, } impl GalleyCache { fn layout_internal( &mut self, fonts: &mut FontsImpl, mut job: LayoutJob, pixels_per_point: f32, allow_split_paragraphs: bool, ) -> (u64, Arc<Galley>) { if job.wrap.max_width.is_finite() { // Protect against rounding errors in egui layout code. // Say the user asks to wrap at width 200.0. // The text layout wraps, and reports that the final width was 196.0 points. // This then trickles up the `Ui` chain and gets stored as the width for a tooltip (say). // On the next frame, this is then set as the max width for the tooltip, // and we end up calling the text layout code again, this time with a wrap width of 196.0. // Except, somewhere in the `Ui` chain with added margins etc, a rounding error was introduced, // so that we actually set a wrap-width of 195.9997 instead. // Now the text that fit perfrectly at 196.0 needs to wrap one word earlier, // and so the text re-wraps and reports a new width of 185.0 points. // And then the cycle continues. // So we limit max_width to integers. // Related issues: // * https://github.com/emilk/egui/issues/4927 // * https://github.com/emilk/egui/issues/4928 // * https://github.com/emilk/egui/issues/5084 // * https://github.com/emilk/egui/issues/5163 job.wrap.max_width = job.wrap.max_width.round(); } let hash = crate::util::hash((&job, OrderedFloat(pixels_per_point))); // TODO(emilk): even faster hasher? let galley = match self.cache.entry(hash) { std::collections::hash_map::Entry::Occupied(entry) => { // The job was found in cache - no need to re-layout. let cached = entry.into_mut(); cached.last_used = self.generation; let galley = Arc::clone(&cached.galley); if let Some(children) = &cached.children { // The point of `allow_split_paragraphs` is to split large jobs into paragraph, // and then cache each paragraph individually. // That way, if we edit a single paragraph, only that paragraph will be re-layouted. // For that to work we need to keep all the child/paragraph // galleys alive while the parent galley is alive: for child_hash in Arc::clone(children).iter() { if let Some(cached_child) = self.cache.get_mut(child_hash) { cached_child.last_used = self.generation; } } } galley } std::collections::hash_map::Entry::Vacant(entry) => { let job = Arc::new(job); if allow_split_paragraphs && should_cache_each_paragraph_individually(&job) { let (child_galleys, child_hashes) = self.layout_each_paragraph_individually(fonts, &job, pixels_per_point); debug_assert_eq!( child_hashes.len(), child_galleys.len(), "Bug in `layout_each_paragraph_individually`" ); let galley = Arc::new(Galley::concat(job, &child_galleys, pixels_per_point)); self.cache.insert( hash, CachedGalley { last_used: self.generation, children: Some(child_hashes.into()), galley: Arc::clone(&galley), }, ); galley } else { let galley = super::layout(fonts, pixels_per_point, job); let galley = Arc::new(galley); entry.insert(CachedGalley { last_used: self.generation, children: None, galley: Arc::clone(&galley), }); galley } } }; (hash, galley) } fn layout( &mut self, fonts: &mut FontsImpl, pixels_per_point: f32,
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
true
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/epaint/src/text/font.rs
crates/epaint/src/text/font.rs
#![expect(clippy::mem_forget)] use emath::{GuiRounding as _, OrderedFloat, Vec2, vec2}; use self_cell::self_cell; use skrifa::{ MetadataProvider as _, raw::{TableProvider as _, tables::kern::SubtableKind}, }; use std::collections::BTreeMap; use vello_cpu::{color, kurbo}; use crate::{ TextOptions, TextureAtlas, text::{ FontTweak, fonts::{Blob, CachedFamily, FontFaceKey}, }, }; // ---------------------------------------------------------------------------- #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct UvRect { /// X/Y offset for nice rendering (unit: points). pub offset: Vec2, /// Screen size (in points) of this glyph. /// Note that the height is different from the font height. pub size: Vec2, /// Top left corner UV in texture. pub min: [u16; 2], /// Bottom right corner (exclusive). pub max: [u16; 2], } impl UvRect { pub fn is_nothing(&self) -> bool { self.min == self.max } } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct GlyphInfo { /// Used for pair-kerning. /// /// Doesn't need to be unique. /// /// Is `None` for a special "invisible" glyph. pub(crate) id: Option<skrifa::GlyphId>, /// In [`skrifa`]s "unscaled" coordinate system. pub advance_width_unscaled: OrderedFloat<f32>, } impl GlyphInfo { /// A valid, but invisible, glyph of zero-width. pub const INVISIBLE: Self = Self { id: None, advance_width_unscaled: OrderedFloat(0.0), }; } // Subpixel binning, taken from cosmic-text: // https://github.com/pop-os/cosmic-text/blob/974ddaed96b334f560b606ebe5d2ca2d2f9f23ef/src/glyph_cache.rs /// Bin for subpixel positioning of glyphs. /// /// For accurate glyph positioning, we want to render each glyph at a subpixel coordinate. However, we also want to /// cache each glyph's bitmap. As a compromise, we bin each subpixel offset into one of four fractional values. This /// means one glyph can have up to four subpixel-positioned bitmaps in the cache. #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] pub(super) enum SubpixelBin { #[default] Zero, One, Two, Three, } impl SubpixelBin { /// Bin the given position and return the new integral coordinate. fn new(pos: f32) -> (i32, Self) { let trunc = pos as i32; let fract = pos - trunc as f32; #[expect(clippy::collapsible_else_if)] if pos.is_sign_negative() { if fract > -0.125 { (trunc, Self::Zero) } else if fract > -0.375 { (trunc - 1, Self::Three) } else if fract > -0.625 { (trunc - 1, Self::Two) } else if fract > -0.875 { (trunc - 1, Self::One) } else { (trunc - 1, Self::Zero) } } else { if fract < 0.125 { (trunc, Self::Zero) } else if fract < 0.375 { (trunc, Self::One) } else if fract < 0.625 { (trunc, Self::Two) } else if fract < 0.875 { (trunc, Self::Three) } else { (trunc + 1, Self::Zero) } } } pub fn as_float(&self) -> f32 { match self { Self::Zero => 0.0, Self::One => 0.25, Self::Two => 0.5, Self::Three => 0.75, } } } #[derive(Clone, Copy, Debug, PartialEq, Default)] pub struct GlyphAllocation { /// Used for pair-kerning. /// /// Doesn't need to be unique. /// Use [`skrifa::GlyphId::NOTDEF`] if you just want to have an id, and don't care. pub(crate) id: skrifa::GlyphId, /// Unit: screen pixels. pub advance_width_px: f32, /// UV rectangle for drawing. pub uv_rect: UvRect, } #[derive(Hash, PartialEq, Eq)] struct GlyphCacheKey(u64); impl nohash_hasher::IsEnabled for GlyphCacheKey {} impl GlyphCacheKey { fn new(glyph_id: skrifa::GlyphId, metrics: &ScaledMetrics, bin: SubpixelBin) -> Self { let ScaledMetrics { pixels_per_point, px_scale_factor, .. } = *metrics; debug_assert!( 0.0 < pixels_per_point && pixels_per_point.is_finite(), "Bad pixels_per_point {pixels_per_point}" ); debug_assert!( 0.0 < px_scale_factor && px_scale_factor.is_finite(), "Bad px_scale_factor: {px_scale_factor}" ); Self(crate::util::hash(( glyph_id, pixels_per_point.to_bits(), px_scale_factor.to_bits(), bin, ))) } } // ---------------------------------------------------------------------------- struct DependentFontData<'a> { skrifa: skrifa::FontRef<'a>, charmap: skrifa::charmap::Charmap<'a>, outline_glyphs: skrifa::outline::OutlineGlyphCollection<'a>, metrics: skrifa::metrics::Metrics, glyph_metrics: skrifa::metrics::GlyphMetrics<'a>, hinting_instance: Option<skrifa::outline::HintingInstance>, } self_cell! { struct FontCell { owner: Blob, #[covariant] dependent: DependentFontData, } } impl FontCell { fn px_scale_factor(&self, scale: f32) -> f32 { let units_per_em = self.borrow_dependent().metrics.units_per_em as f32; scale / units_per_em } fn allocate_glyph_uncached( &mut self, atlas: &mut TextureAtlas, metrics: &ScaledMetrics, glyph_info: &GlyphInfo, bin: SubpixelBin, location: &skrifa::instance::Location, ) -> Option<GlyphAllocation> { let glyph_id = glyph_info.id?; debug_assert!( glyph_id != skrifa::GlyphId::NOTDEF, "Can't allocate glyph for id 0" ); let mut path = kurbo::BezPath::new(); let mut pen = VelloPen { path: &mut path, x_offset: bin.as_float() as f64, }; self.with_dependent_mut(|_, font_data| { let outline = font_data.outline_glyphs.get(glyph_id)?; if let Some(hinting_instance) = &mut font_data.hinting_instance { let size = skrifa::instance::Size::new(metrics.scale); if hinting_instance.size() != size { hinting_instance .reconfigure( &font_data.outline_glyphs, size, location, skrifa::outline::Target::Smooth { mode: skrifa::outline::SmoothMode::Normal, symmetric_rendering: true, preserve_linear_metrics: true, }, ) .ok()?; } let draw_settings = skrifa::outline::DrawSettings::hinted(hinting_instance, false); outline.draw(draw_settings, &mut pen).ok()?; } else { let draw_settings = skrifa::outline::DrawSettings::unhinted( skrifa::instance::Size::new(metrics.scale), location, ); outline.draw(draw_settings, &mut pen).ok()?; } Some(()) })?; let bounds = path.control_box().expand(); let width = bounds.width() as u16; let height = bounds.height() as u16; let mut ctx = vello_cpu::RenderContext::new(width, height); ctx.set_transform(kurbo::Affine::translate((-bounds.x0, -bounds.y0))); ctx.set_paint(color::OpaqueColor::<color::Srgb>::WHITE); ctx.fill_path(&path); let mut dest = vello_cpu::Pixmap::new(width, height); ctx.render_to_pixmap(&mut dest); let uv_rect = if width == 0 || height == 0 { UvRect::default() } else { let glyph_pos = { let alpha_from_coverage = atlas.options().alpha_from_coverage; let (glyph_pos, image) = atlas.allocate((width as usize, height as usize)); let pixels = dest.data_as_u8_slice(); for y in 0..height as usize { for x in 0..width as usize { image[(x + glyph_pos.0, y + glyph_pos.1)] = alpha_from_coverage .color_from_coverage( pixels[((y * width as usize) + x) * 4 + 3] as f32 / 255.0, ); } } glyph_pos }; let offset_in_pixels = vec2(bounds.x0 as f32, bounds.y0 as f32); let offset = offset_in_pixels / metrics.pixels_per_point + metrics.y_offset_in_points * Vec2::Y; UvRect { offset, size: vec2(width as f32, height as f32) / metrics.pixels_per_point, min: [glyph_pos.0 as u16, glyph_pos.1 as u16], max: [ (glyph_pos.0 + width as usize) as u16, (glyph_pos.1 + height as usize) as u16, ], } }; Some(GlyphAllocation { id: glyph_id, advance_width_px: glyph_info.advance_width_unscaled.0 * metrics.px_scale_factor, uv_rect, }) } } struct VelloPen<'a> { path: &'a mut kurbo::BezPath, x_offset: f64, } impl skrifa::outline::OutlinePen for VelloPen<'_> { fn move_to(&mut self, x: f32, y: f32) { self.path.move_to((x as f64 + self.x_offset, -y as f64)); } fn line_to(&mut self, x: f32, y: f32) { self.path.line_to((x as f64 + self.x_offset, -y as f64)); } fn quad_to(&mut self, cx0: f32, cy0: f32, x: f32, y: f32) { self.path.quad_to( (cx0 as f64 + self.x_offset, -cy0 as f64), (x as f64 + self.x_offset, -y as f64), ); } fn curve_to(&mut self, cx0: f32, cy0: f32, cx1: f32, cy1: f32, x: f32, y: f32) { self.path.curve_to( (cx0 as f64 + self.x_offset, -cy0 as f64), (cx1 as f64 + self.x_offset, -cy1 as f64), (x as f64 + self.x_offset, -y as f64), ); } fn close(&mut self) { self.path.close_path(); } } /// A specific font face. /// The interface uses points as the unit for everything. pub struct FontFace { name: String, font: FontCell, tweak: FontTweak, /// The font weight (100-900) if available from the font file. weight: Option<u16>, /// Variable font location (for weight axis, etc.) location: skrifa::instance::Location, glyph_info_cache: ahash::HashMap<char, GlyphInfo>, glyph_alloc_cache: ahash::HashMap<GlyphCacheKey, GlyphAllocation>, } impl FontFace { pub fn new( options: TextOptions, name: String, font_data: Blob, index: u32, tweak: FontTweak, preferred_weight: Option<u16>, ) -> Result<Self, Box<dyn std::error::Error>> { let font = FontCell::try_new(font_data, |font_data| { let skrifa_font = skrifa::FontRef::from_index(AsRef::<[u8]>::as_ref(font_data.as_ref()), index)?; let charmap = skrifa_font.charmap(); let glyphs = skrifa_font.outline_glyphs(); // Note: We use default location here during initialization because // the actual weight will be applied via the stored location during rendering. // The metrics won't be significantly different at this unscaled size. let metrics = skrifa_font.metrics( skrifa::instance::Size::unscaled(), skrifa::instance::LocationRef::default(), ); let glyph_metrics = skrifa_font.glyph_metrics( skrifa::instance::Size::unscaled(), skrifa::instance::LocationRef::default(), ); let hinting_enabled = tweak.hinting_override.unwrap_or(options.font_hinting); let hinting_instance = hinting_enabled .then(|| { // It doesn't really matter what we put here for options. Since the size is `unscaled()`, we will // always reconfigure this hinting instance with the real options when rendering for the first time. skrifa::outline::HintingInstance::new( &glyphs, skrifa::instance::Size::unscaled(), skrifa::instance::LocationRef::default(), skrifa::outline::Target::default(), ) .ok() }) .flatten(); Ok::<DependentFontData<'_>, Box<dyn std::error::Error>>(DependentFontData { skrifa: skrifa_font, charmap, outline_glyphs: glyphs, metrics, glyph_metrics, hinting_instance, }) })?; // Use preferred_weight if provided, otherwise try to read from the OS/2 table or fvar default let weight = preferred_weight.or_else(|| { // First try OS/2 table if let Some(w) = font .borrow_dependent() .skrifa .os2() .ok() .map(|os2| os2.us_weight_class()) { return Some(w); } // If no OS/2 or preferred_weight, try to get default from variable font's fvar table font.borrow_dependent() .skrifa .axes() .iter() .find(|axis| axis.tag() == skrifa::raw::types::Tag::new(b"wght")) .map(|axis| axis.default_value() as u16) }); // Create location for variable font with weight axis // If weight is provided (either from preferred_weight, OS/2, or fvar default), use it // Otherwise fall back to Location::default() which uses all axis defaults let location = if let Some(w) = weight { font.borrow_dependent() .skrifa .axes() .location([("wght", w as f32)]) } else { skrifa::instance::Location::default() }; Ok(Self { name, font, tweak, weight, location, glyph_info_cache: Default::default(), glyph_alloc_cache: Default::default(), }) } /// Get the font weight (100-900) if available from the font file. pub fn weight(&self) -> Option<u16> { self.weight } /// Code points that will always be replaced by the replacement character. /// /// See also [`invisible_char`]. fn ignore_character(&self, chr: char) -> bool { use crate::text::FontDefinitions; if !FontDefinitions::builtin_font_names().contains(&self.name.as_str()) { return false; } matches!( chr, // Strip out a religious symbol with secondary nefarious interpretation: '\u{534d}' | '\u{5350}' | // Ignore ubuntu-specific stuff in `Ubuntu-Light.ttf`: '\u{E0FF}' | '\u{EFFD}' | '\u{F0FF}' | '\u{F200}' ) } /// An un-ordered iterator over all supported characters. fn characters(&self) -> impl Iterator<Item = char> + '_ { self.font .borrow_dependent() .charmap .mappings() .filter_map(|(chr, _)| char::from_u32(chr).filter(|c| !self.ignore_character(*c))) } /// `\n` will result in `None` pub(super) fn glyph_info(&mut self, c: char) -> Option<GlyphInfo> { if let Some(glyph_info) = self.glyph_info_cache.get(&c) { return Some(*glyph_info); } if self.ignore_character(c) { return None; // these will result in the replacement character when rendering } if c == '\t' && let Some(space) = self.glyph_info(' ') { let glyph_info = GlyphInfo { advance_width_unscaled: (crate::text::TAB_SIZE as f32 * space.advance_width_unscaled.0) .into(), ..space }; self.glyph_info_cache.insert(c, glyph_info); return Some(glyph_info); } if c == '\u{2009}' { // Thin space, often used as thousands deliminator: 1 234 567 890 // https://www.compart.com/en/unicode/U+2009 // https://en.wikipedia.org/wiki/Thin_space if let Some(space) = self.glyph_info(' ') { let em = self.font.borrow_dependent().metrics.units_per_em as f32; let advance_width = f32::min(em / 6.0, space.advance_width_unscaled.0 * 0.5); // TODO(emilk): make configurable let glyph_info = GlyphInfo { advance_width_unscaled: advance_width.into(), ..space }; self.glyph_info_cache.insert(c, glyph_info); return Some(glyph_info); } } if invisible_char(c) { let glyph_info = GlyphInfo::INVISIBLE; self.glyph_info_cache.insert(c, glyph_info); return Some(glyph_info); } let font_data = self.font.borrow_dependent(); // Add new character: let glyph_id = font_data .charmap .map(c) .filter(|id| *id != skrifa::GlyphId::NOTDEF)?; let glyph_info = GlyphInfo { id: Some(glyph_id), advance_width_unscaled: font_data .glyph_metrics .advance_width(glyph_id) .unwrap_or_default() .into(), }; self.glyph_info_cache.insert(c, glyph_info); Some(glyph_info) } #[inline] pub(super) fn pair_kerning_pixels( &self, metrics: &ScaledMetrics, last_glyph_id: skrifa::GlyphId, glyph_id: skrifa::GlyphId, ) -> f32 { let skrifa_font = &self.font.borrow_dependent().skrifa; let Ok(kern) = skrifa_font.kern() else { return 0.0; }; kern.subtables() .find_map(|st| match st.ok()?.kind().ok()? { SubtableKind::Format0(table_ref) => table_ref.kerning(last_glyph_id, glyph_id), SubtableKind::Format1(_) => None, SubtableKind::Format2(subtable2) => subtable2.kerning(last_glyph_id, glyph_id), SubtableKind::Format3(table_ref) => table_ref.kerning(last_glyph_id, glyph_id), }) .unwrap_or_default() as f32 * metrics.px_scale_factor } #[inline] pub fn pair_kerning( &self, metrics: &ScaledMetrics, last_glyph_id: skrifa::GlyphId, glyph_id: skrifa::GlyphId, ) -> f32 { self.pair_kerning_pixels(metrics, last_glyph_id, glyph_id) / metrics.pixels_per_point } #[inline(always)] pub fn scaled_metrics(&self, pixels_per_point: f32, font_size: f32) -> ScaledMetrics { let pt_scale_factor = self.font.px_scale_factor(font_size * self.tweak.scale); let font_data = self.font.borrow_dependent(); let ascent = (font_data.metrics.ascent * pt_scale_factor).round_ui(); let descent = (font_data.metrics.descent * pt_scale_factor).round_ui(); let line_gap = (font_data.metrics.leading * pt_scale_factor).round_ui(); let scale = font_size * self.tweak.scale * pixels_per_point; let px_scale_factor = self.font.px_scale_factor(scale); let y_offset_in_points = ((font_size * self.tweak.scale * self.tweak.y_offset_factor) + self.tweak.y_offset) .round_ui(); ScaledMetrics { pixels_per_point, px_scale_factor, scale, y_offset_in_points, ascent, row_height: ascent - descent + line_gap, } } pub fn allocate_glyph( &mut self, atlas: &mut TextureAtlas, metrics: &ScaledMetrics, glyph_info: GlyphInfo, chr: char, h_pos: f32, ) -> (GlyphAllocation, i32) { let advance_width_px = glyph_info.advance_width_unscaled.0 * metrics.px_scale_factor; let Some(glyph_id) = glyph_info.id else { // Invisible. return (GlyphAllocation::default(), h_pos as i32); }; // CJK scripts contain a lot of characters and could hog the glyph atlas if we stored 4 subpixel offsets per // glyph. let (h_pos_round, bin) = if is_cjk(chr) { (h_pos.round() as i32, SubpixelBin::Zero) } else { SubpixelBin::new(h_pos) }; let entry = match self .glyph_alloc_cache .entry(GlyphCacheKey::new(glyph_id, metrics, bin)) { std::collections::hash_map::Entry::Occupied(glyph_alloc) => { let mut glyph_alloc = *glyph_alloc.get(); glyph_alloc.advance_width_px = advance_width_px; // Hack to get `\t` and thin space to work, since they use the same glyph id as ` ` (space). return (glyph_alloc, h_pos_round); } std::collections::hash_map::Entry::Vacant(entry) => entry, }; let allocation = self .font .allocate_glyph_uncached(atlas, metrics, &glyph_info, bin, &self.location) .unwrap_or_default(); entry.insert(allocation); (allocation, h_pos_round) } } // TODO(emilk): rename? /// Wrapper over multiple [`FontFace`] (e.g. a primary + fallbacks for emojis) pub struct Font<'a> { pub(super) fonts_by_id: &'a mut nohash_hasher::IntMap<FontFaceKey, FontFace>, pub(super) cached_family: &'a mut CachedFamily, pub(super) atlas: &'a mut TextureAtlas, } impl Font<'_> { pub fn preload_characters(&mut self, s: &str) { for c in s.chars() { self.glyph_info(c); } } /// All supported characters, and in which font they are available in. pub fn characters(&mut self) -> &BTreeMap<char, Vec<String>> { self.cached_family.characters.get_or_insert_with(|| { let mut characters: BTreeMap<char, Vec<String>> = Default::default(); for font_id in &self.cached_family.fonts { let font = self.fonts_by_id.get(font_id).expect("Nonexistent font ID"); for chr in font.characters() { characters.entry(chr).or_default().push(font.name.clone()); } } characters }) } pub fn scaled_metrics(&self, pixels_per_point: f32, font_size: f32) -> ScaledMetrics { self.cached_family .fonts .first() .and_then(|key| self.fonts_by_id.get(key)) .map(|font_face| font_face.scaled_metrics(pixels_per_point, font_size)) .unwrap_or_default() } /// Width of this character in points. pub fn glyph_width(&mut self, c: char, font_size: f32) -> f32 { let (key, glyph_info) = self.glyph_info(c); if let Some(font) = &self.fonts_by_id.get(&key) { glyph_info.advance_width_unscaled.0 * font.font.px_scale_factor(font_size) } else { 0.0 } } /// Can we display this glyph? pub fn has_glyph(&mut self, c: char) -> bool { self.glyph_info(c) != self.cached_family.replacement_glyph // TODO(emilk): this is a false negative if the user asks about the replacement character itself 🤦‍♂️ } /// Can we display all the glyphs in this text? pub fn has_glyphs(&mut self, s: &str) -> bool { s.chars().all(|c| self.has_glyph(c)) } /// `\n` will (intentionally) show up as the replacement character. pub(crate) fn glyph_info(&mut self, c: char) -> (FontFaceKey, GlyphInfo) { if let Some(font_index_glyph_info) = self.cached_family.glyph_info_cache.get(&c) { return *font_index_glyph_info; } let font_index_glyph_info = self .cached_family .glyph_info_no_cache_or_fallback(c, self.fonts_by_id); let font_index_glyph_info = font_index_glyph_info.unwrap_or(self.cached_family.replacement_glyph); self.cached_family .glyph_info_cache .insert(c, font_index_glyph_info); font_index_glyph_info } } /// Metrics for a font at a specific screen-space scale. #[derive(Clone, Copy, Debug, PartialEq, Default)] pub struct ScaledMetrics { /// The DPI part of the screen-space scale. pub pixels_per_point: f32, /// Scale factor, relative to the font's units per em (so, probably much less than 1). /// /// Translates "unscaled" units to physical (screen) pixels. pub px_scale_factor: f32, /// Absolute scale in screen pixels, for skrifa. pub scale: f32, /// Vertical offset, in UI points (not screen-space). pub y_offset_in_points: f32, /// This is the distance from the top to the baseline. /// /// Unit: points. pub ascent: f32, /// Height of one row of text in points. /// /// Returns a value rounded to [`emath::GUI_ROUNDING`]. pub row_height: f32, } /// Code points that will always be invisible (zero width). /// /// See also [`FontFace::ignore_character`]. #[inline] fn invisible_char(c: char) -> bool { if c == '\r' { // A character most vile and pernicious. Don't display it. return true; } // See https://github.com/emilk/egui/issues/336 // From https://www.fileformat.info/info/unicode/category/Cf/list.htm // TODO(emilk): heed bidi characters matches!( c, '\u{200B}' // ZERO WIDTH SPACE | '\u{200C}' // ZERO WIDTH NON-JOINER | '\u{200D}' // ZERO WIDTH JOINER | '\u{200E}' // LEFT-TO-RIGHT MARK | '\u{200F}' // RIGHT-TO-LEFT MARK | '\u{202A}' // LEFT-TO-RIGHT EMBEDDING | '\u{202B}' // RIGHT-TO-LEFT EMBEDDING | '\u{202C}' // POP DIRECTIONAL FORMATTING | '\u{202D}' // LEFT-TO-RIGHT OVERRIDE | '\u{202E}' // RIGHT-TO-LEFT OVERRIDE | '\u{2060}' // WORD JOINER | '\u{2061}' // FUNCTION APPLICATION | '\u{2062}' // INVISIBLE TIMES | '\u{2063}' // INVISIBLE SEPARATOR | '\u{2064}' // INVISIBLE PLUS | '\u{2066}' // LEFT-TO-RIGHT ISOLATE | '\u{2067}' // RIGHT-TO-LEFT ISOLATE | '\u{2068}' // FIRST STRONG ISOLATE | '\u{2069}' // POP DIRECTIONAL ISOLATE | '\u{206A}' // INHIBIT SYMMETRIC SWAPPING | '\u{206B}' // ACTIVATE SYMMETRIC SWAPPING | '\u{206C}' // INHIBIT ARABIC FORM SHAPING | '\u{206D}' // ACTIVATE ARABIC FORM SHAPING | '\u{206E}' // NATIONAL DIGIT SHAPES | '\u{206F}' // NOMINAL DIGIT SHAPES | '\u{FEFF}' // ZERO WIDTH NO-BREAK SPACE ) } #[inline] pub(super) fn is_cjk_ideograph(c: char) -> bool { ('\u{4E00}' <= c && c <= '\u{9FFF}') || ('\u{3400}' <= c && c <= '\u{4DBF}') || ('\u{2B740}' <= c && c <= '\u{2B81F}') } #[inline] pub(super) fn is_kana(c: char) -> bool { ('\u{3040}' <= c && c <= '\u{309F}') // Hiragana block || ('\u{30A0}' <= c && c <= '\u{30FF}') // Katakana block } #[inline] pub(super) fn is_cjk(c: char) -> bool { // TODO(bigfarts): Add support for Korean Hangul. is_cjk_ideograph(c) || is_kana(c) } #[inline] pub(super) fn is_cjk_break_allowed(c: char) -> bool { // See: https://en.wikipedia.org/wiki/Line_breaking_rules_in_East_Asian_languages#Characters_not_permitted_on_the_start_of_a_line. !")]}〕〉》」』】〙〗〟'\"⦆»ヽヾーァィゥェォッャュョヮヵヶぁぃぅぇぉっゃゅょゎゕゖㇰㇱㇲㇳㇴㇵㇶㇷㇸㇹㇺㇻㇼㇽㇾㇿ々〻‐゠–〜?!‼⁇⁈⁉・、:;,。.".contains(c) }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/epaint/src/text/mod.rs
crates/epaint/src/text/mod.rs
//! Everything related to text, fonts, text layout, cursors etc. pub mod cursor; mod font; mod fonts; mod text_layout; mod text_layout_types; /// One `\t` character is this many spaces wide. pub const TAB_SIZE: usize = 4; pub use { fonts::{ FontData, FontDefinitions, FontFamily, FontId, FontInsert, FontPriority, FontTweak, Fonts, FontsImpl, FontsView, InsertFontFamily, }, text_layout::*, text_layout_types::*, }; /// Suggested character to use to replace those in password text fields. pub const PASSWORD_REPLACEMENT_CHAR: char = '•'; /// Controls how we render text #[derive(Clone, Copy, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct TextOptions { /// Maximum size of the font texture. pub max_texture_side: usize, /// Controls how to convert glyph coverage to alpha. pub alpha_from_coverage: crate::AlphaFromCoverage, /// Whether to enable font hinting /// /// (round some font coordinates to pixels for sharper text). /// /// Default is `true`. pub font_hinting: bool, } impl Default for TextOptions { fn default() -> Self { Self { max_texture_side: 2048, // Small but portable alpha_from_coverage: crate::AlphaFromCoverage::default(), font_hinting: true, } } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/epaint/src/text/text_layout.rs
crates/epaint/src/text/text_layout.rs
#![expect(clippy::unwrap_used)] // TODO(emilk): remove unwraps use std::sync::Arc; use emath::{Align, GuiRounding as _, NumExt as _, Pos2, Rect, Vec2, pos2, vec2}; use crate::{ Color32, Mesh, Stroke, Vertex, stroke::PathStroke, text::{ font::{ScaledMetrics, is_cjk, is_cjk_break_allowed}, fonts::FontFaceKey, }, }; use super::{FontsImpl, Galley, Glyph, LayoutJob, LayoutSection, PlacedRow, Row, RowVisuals}; // ---------------------------------------------------------------------------- /// Represents GUI scale and convenience methods for rounding to pixels. #[derive(Clone, Copy)] struct PointScale { pub pixels_per_point: f32, } impl PointScale { #[inline(always)] pub fn new(pixels_per_point: f32) -> Self { Self { pixels_per_point } } #[inline(always)] pub fn pixels_per_point(&self) -> f32 { self.pixels_per_point } #[inline(always)] pub fn round_to_pixel(&self, point: f32) -> f32 { (point * self.pixels_per_point).round() / self.pixels_per_point } #[inline(always)] pub fn floor_to_pixel(&self, point: f32) -> f32 { (point * self.pixels_per_point).floor() / self.pixels_per_point } } // ---------------------------------------------------------------------------- /// Temporary storage before line-wrapping. #[derive(Clone)] struct Paragraph { /// Start of the next glyph to be added. In screen-space / physical pixels. pub cursor_x_px: f32, /// This is included in case there are no glyphs pub section_index_at_start: u32, pub glyphs: Vec<Glyph>, /// In case of an empty paragraph ("\n"), use this as height. pub empty_paragraph_height: f32, } impl Paragraph { pub fn from_section_index(section_index_at_start: u32) -> Self { Self { cursor_x_px: 0.0, section_index_at_start, glyphs: vec![], empty_paragraph_height: 0.0, } } } /// Layout text into a [`Galley`]. /// /// In most cases you should use [`crate::FontsView::layout_job`] instead /// since that memoizes the input, making subsequent layouting of the same text much faster. pub fn layout(fonts: &mut FontsImpl, pixels_per_point: f32, job: Arc<LayoutJob>) -> Galley { profiling::function_scope!(); if job.wrap.max_rows == 0 { // Early-out: no text return Galley { job, rows: Default::default(), rect: Rect::ZERO, mesh_bounds: Rect::NOTHING, num_vertices: 0, num_indices: 0, pixels_per_point, elided: true, intrinsic_size: Vec2::ZERO, }; } // For most of this we ignore the y coordinate: let mut paragraphs = vec![Paragraph::from_section_index(0)]; for (section_index, section) in job.sections.iter().enumerate() { layout_section( fonts, pixels_per_point, &job, section_index as u32, section, &mut paragraphs, ); } let point_scale = PointScale::new(pixels_per_point); let intrinsic_size = calculate_intrinsic_size(point_scale, &job, &paragraphs); let mut elided = false; let mut rows = rows_from_paragraphs(paragraphs, &job, &mut elided); if elided && let Some(last_placed) = rows.last_mut() { let last_row = Arc::make_mut(&mut last_placed.row); replace_last_glyph_with_overflow_character(fonts, pixels_per_point, &job, last_row); if let Some(last) = last_row.glyphs.last() { last_row.size.x = last.max_x(); } } let justify = job.justify && job.wrap.max_width.is_finite(); if justify || job.halign != Align::LEFT { let num_rows = rows.len(); for (i, placed_row) in rows.iter_mut().enumerate() { let is_last_row = i + 1 == num_rows; let justify_row = justify && !placed_row.ends_with_newline && !is_last_row; halign_and_justify_row( point_scale, placed_row, job.halign, job.wrap.max_width, justify_row, ); } } // Calculate the Y positions and tessellate the text: galley_from_rows(point_scale, job, rows, elided, intrinsic_size) } // Ignores the Y coordinate. fn layout_section( fonts: &mut FontsImpl, pixels_per_point: f32, job: &LayoutJob, section_index: u32, section: &LayoutSection, out_paragraphs: &mut Vec<Paragraph>, ) { let LayoutSection { leading_space, byte_range, format, } = section; let mut font = fonts.font(&format.font_id.family); let font_size = format.font_id.size; let font_metrics = font.scaled_metrics(pixels_per_point, font_size); let line_height = section .format .line_height .unwrap_or(font_metrics.row_height); let extra_letter_spacing = section.format.extra_letter_spacing; let mut paragraph = out_paragraphs.last_mut().unwrap(); if paragraph.glyphs.is_empty() { paragraph.empty_paragraph_height = line_height; // TODO(emilk): replace this hack with actually including `\n` in the glyphs? } paragraph.cursor_x_px += leading_space * pixels_per_point; let mut last_glyph_id = None; // Optimization: only recompute `ScaledMetrics` when the concrete `FontImpl` changes. let mut current_font = FontFaceKey::INVALID; let mut current_font_face_metrics = ScaledMetrics::default(); for chr in job.text[byte_range.clone()].chars() { if job.break_on_newline && chr == '\n' { out_paragraphs.push(Paragraph::from_section_index(section_index)); paragraph = out_paragraphs.last_mut().unwrap(); paragraph.empty_paragraph_height = line_height; // TODO(emilk): replace this hack with actually including `\n` in the glyphs? } else { let (font_id, glyph_info) = font.glyph_info(chr); let mut font_face = font.fonts_by_id.get_mut(&font_id); if current_font != font_id { current_font = font_id; current_font_face_metrics = font_face .as_ref() .map(|font_face| font_face.scaled_metrics(pixels_per_point, font_size)) .unwrap_or_default(); } if let (Some(font_face), Some(last_glyph_id), Some(glyph_id)) = (&font_face, last_glyph_id, glyph_info.id) { paragraph.cursor_x_px += font_face.pair_kerning_pixels( &current_font_face_metrics, last_glyph_id, glyph_id, ); // Only apply extra_letter_spacing to glyphs after the first one: paragraph.cursor_x_px += extra_letter_spacing * pixels_per_point; } let (glyph_alloc, physical_x) = if let Some(font_face) = font_face.as_mut() { font_face.allocate_glyph( font.atlas, &current_font_face_metrics, glyph_info, chr, paragraph.cursor_x_px, ) } else { Default::default() }; paragraph.glyphs.push(Glyph { chr, pos: pos2(physical_x as f32 / pixels_per_point, f32::NAN), advance_width: glyph_alloc.advance_width_px / pixels_per_point, line_height, font_face_height: current_font_face_metrics.row_height, font_face_ascent: current_font_face_metrics.ascent, font_height: font_metrics.row_height, font_ascent: font_metrics.ascent, uv_rect: glyph_alloc.uv_rect, section_index, first_vertex: 0, // filled in later }); paragraph.cursor_x_px += glyph_alloc.advance_width_px; last_glyph_id = Some(glyph_alloc.id); } } } /// Calculate the intrinsic size of the text. /// /// The result is eventually passed to `Response::intrinsic_size`. /// This works by calculating the size of each `Paragraph` (instead of each `Row`). fn calculate_intrinsic_size( point_scale: PointScale, job: &LayoutJob, paragraphs: &[Paragraph], ) -> Vec2 { let mut intrinsic_size = Vec2::ZERO; for (idx, paragraph) in paragraphs.iter().enumerate() { let width = paragraph .glyphs .last() .map(|l| l.max_x()) .unwrap_or_default(); intrinsic_size.x = f32::max(intrinsic_size.x, width); let mut height = paragraph .glyphs .iter() .map(|g| g.line_height) .max_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)) .unwrap_or(paragraph.empty_paragraph_height); if idx == 0 { height = f32::max(height, job.first_row_min_height); } intrinsic_size.y += point_scale.round_to_pixel(height); } intrinsic_size } // Ignores the Y coordinate. fn rows_from_paragraphs( paragraphs: Vec<Paragraph>, job: &LayoutJob, elided: &mut bool, ) -> Vec<PlacedRow> { let num_paragraphs = paragraphs.len(); let mut rows = vec![]; for (i, paragraph) in paragraphs.into_iter().enumerate() { if job.wrap.max_rows <= rows.len() { *elided = true; break; } let is_last_paragraph = (i + 1) == num_paragraphs; if paragraph.glyphs.is_empty() { rows.push(PlacedRow { pos: pos2(0.0, f32::NAN), row: Arc::new(Row { section_index_at_start: paragraph.section_index_at_start, glyphs: vec![], visuals: Default::default(), size: vec2(0.0, paragraph.empty_paragraph_height), }), ends_with_newline: !is_last_paragraph, }); } else { let paragraph_max_x = paragraph.glyphs.last().unwrap().max_x(); if paragraph_max_x <= job.effective_wrap_width() { // Early-out optimization: the whole paragraph fits on one row. rows.push(PlacedRow { pos: pos2(0.0, f32::NAN), row: Arc::new(Row { section_index_at_start: paragraph.section_index_at_start, glyphs: paragraph.glyphs, visuals: Default::default(), size: vec2(paragraph_max_x, 0.0), }), ends_with_newline: !is_last_paragraph, }); } else { line_break(&paragraph, job, &mut rows, elided); let placed_row = rows.last_mut().unwrap(); placed_row.ends_with_newline = !is_last_paragraph; } } } rows } fn line_break( paragraph: &Paragraph, job: &LayoutJob, out_rows: &mut Vec<PlacedRow>, elided: &mut bool, ) { let wrap_width = job.effective_wrap_width(); // Keeps track of good places to insert row break if we exceed `wrap_width`. let mut row_break_candidates = RowBreakCandidates::default(); let mut first_row_indentation = paragraph.glyphs[0].pos.x; let mut row_start_x = 0.0; let mut row_start_idx = 0; for i in 0..paragraph.glyphs.len() { if job.wrap.max_rows <= out_rows.len() { *elided = true; break; } let potential_row_width = paragraph.glyphs[i].max_x() - row_start_x; if wrap_width < potential_row_width { // Row break: if first_row_indentation > 0.0 && !row_break_candidates.has_good_candidate(job.wrap.break_anywhere) { // Allow the first row to be completely empty, because we know there will be more space on the next row: // TODO(emilk): this records the height of this first row as zero, though that is probably fine since first_row_indentation usually comes with a first_row_min_height. out_rows.push(PlacedRow { pos: pos2(0.0, f32::NAN), row: Arc::new(Row { section_index_at_start: paragraph.section_index_at_start, glyphs: vec![], visuals: Default::default(), size: Vec2::ZERO, }), ends_with_newline: false, }); row_start_x += first_row_indentation; first_row_indentation = 0.0; } else if let Some(last_kept_index) = row_break_candidates.get(job.wrap.break_anywhere) { let glyphs: Vec<Glyph> = paragraph.glyphs[row_start_idx..=last_kept_index] .iter() .copied() .map(|mut glyph| { glyph.pos.x -= row_start_x; glyph }) .collect(); let section_index_at_start = glyphs[0].section_index; let paragraph_max_x = glyphs.last().unwrap().max_x(); out_rows.push(PlacedRow { pos: pos2(0.0, f32::NAN), row: Arc::new(Row { section_index_at_start, glyphs, visuals: Default::default(), size: vec2(paragraph_max_x, 0.0), }), ends_with_newline: false, }); // Start a new row: row_start_idx = last_kept_index + 1; row_start_x = paragraph.glyphs[row_start_idx].pos.x; row_break_candidates.forget_before_idx(row_start_idx); } else { // Found no place to break, so we have to overrun wrap_width. } } row_break_candidates.add(i, &paragraph.glyphs[i..]); } if row_start_idx < paragraph.glyphs.len() { // Final row of text: if job.wrap.max_rows <= out_rows.len() { *elided = true; // can't fit another row } else { let glyphs: Vec<Glyph> = paragraph.glyphs[row_start_idx..] .iter() .copied() .map(|mut glyph| { glyph.pos.x -= row_start_x; glyph }) .collect(); let section_index_at_start = glyphs[0].section_index; let paragraph_min_x = glyphs[0].pos.x; let paragraph_max_x = glyphs.last().unwrap().max_x(); out_rows.push(PlacedRow { pos: pos2(paragraph_min_x, 0.0), row: Arc::new(Row { section_index_at_start, glyphs, visuals: Default::default(), size: vec2(paragraph_max_x - paragraph_min_x, 0.0), }), ends_with_newline: false, }); } } } /// Trims the last glyphs in the row and replaces it with an overflow character (e.g. `…`). /// /// Called before we have any Y coordinates. fn replace_last_glyph_with_overflow_character( fonts: &mut FontsImpl, pixels_per_point: f32, job: &LayoutJob, row: &mut Row, ) { let Some(overflow_character) = job.wrap.overflow_character else { return; }; let mut section_index = row .glyphs .last() .map(|g| g.section_index) .unwrap_or(row.section_index_at_start); loop { let section = &job.sections[section_index as usize]; let extra_letter_spacing = section.format.extra_letter_spacing; let mut font = fonts.font(&section.format.font_id.family); let font_size = section.format.font_id.size; let (font_id, glyph_info) = font.glyph_info(overflow_character); let mut font_face = font.fonts_by_id.get_mut(&font_id); let font_face_metrics = font_face .as_mut() .map(|f| f.scaled_metrics(pixels_per_point, font_size)) .unwrap_or_default(); let overflow_glyph_x = if let Some(prev_glyph) = row.glyphs.last() { // Kern the overflow character properly let pair_kerning = font_face .as_mut() .map(|font_face| { if let (Some(prev_glyph_id), Some(overflow_glyph_id)) = ( font_face.glyph_info(prev_glyph.chr).and_then(|g| g.id), font_face.glyph_info(overflow_character).and_then(|g| g.id), ) { font_face.pair_kerning(&font_face_metrics, prev_glyph_id, overflow_glyph_id) } else { 0.0 } }) .unwrap_or_default(); prev_glyph.max_x() + extra_letter_spacing + pair_kerning } else { 0.0 // TODO(emilk): heed paragraph leading_space 😬 }; let replacement_glyph_width = font_face .as_mut() .and_then(|f| f.glyph_info(overflow_character)) .map(|i| i.advance_width_unscaled.0 * font_face_metrics.px_scale_factor) .unwrap_or_default(); // Check if we're within width budget: if overflow_glyph_x + replacement_glyph_width <= job.effective_wrap_width() || row.glyphs.is_empty() { // we are done let (replacement_glyph_alloc, physical_x) = font_face .as_mut() .map(|f| { f.allocate_glyph( font.atlas, &font_face_metrics, glyph_info, overflow_character, overflow_glyph_x * pixels_per_point, ) }) .unwrap_or_default(); let font_metrics = font.scaled_metrics(pixels_per_point, font_size); let line_height = section .format .line_height .unwrap_or(font_metrics.row_height); row.glyphs.push(Glyph { chr: overflow_character, pos: pos2(physical_x as f32 / pixels_per_point, f32::NAN), advance_width: replacement_glyph_alloc.advance_width_px / pixels_per_point, line_height, font_face_height: font_face_metrics.row_height, font_face_ascent: font_face_metrics.ascent, font_height: font_metrics.row_height, font_ascent: font_metrics.ascent, uv_rect: replacement_glyph_alloc.uv_rect, section_index, first_vertex: 0, // filled in later }); return; } // We didn't fit - pop the last glyph and try again. if let Some(last_glyph) = row.glyphs.pop() { section_index = last_glyph.section_index; } else { section_index = row.section_index_at_start; } } } /// Horizontally aligned the text on a row. /// /// Ignores the Y coordinate. fn halign_and_justify_row( point_scale: PointScale, placed_row: &mut PlacedRow, halign: Align, wrap_width: f32, justify: bool, ) { #![expect(clippy::useless_let_if_seq)] // False positive let row = Arc::make_mut(&mut placed_row.row); if row.glyphs.is_empty() { return; } let num_leading_spaces = row .glyphs .iter() .take_while(|glyph| glyph.chr.is_whitespace()) .count(); let glyph_range = if num_leading_spaces == row.glyphs.len() { // There is only whitespace (0, row.glyphs.len()) } else { let num_trailing_spaces = row .glyphs .iter() .rev() .take_while(|glyph| glyph.chr.is_whitespace()) .count(); (num_leading_spaces, row.glyphs.len() - num_trailing_spaces) }; let num_glyphs_in_range = glyph_range.1 - glyph_range.0; assert!(num_glyphs_in_range > 0, "Should have at least one glyph"); let original_min_x = row.glyphs[glyph_range.0].logical_rect().min.x; let original_max_x = row.glyphs[glyph_range.1 - 1].logical_rect().max.x; let original_width = original_max_x - original_min_x; let target_width = if justify && num_glyphs_in_range > 1 { wrap_width } else { original_width }; let (target_min_x, target_max_x) = match halign { Align::LEFT => (0.0, target_width), Align::Center => (-target_width / 2.0, target_width / 2.0), Align::RIGHT => (-target_width, 0.0), }; let num_spaces_in_range = row.glyphs[glyph_range.0..glyph_range.1] .iter() .filter(|glyph| glyph.chr.is_whitespace()) .count(); let mut extra_x_per_glyph = if num_glyphs_in_range == 1 { 0.0 } else { (target_width - original_width) / (num_glyphs_in_range as f32 - 1.0) }; extra_x_per_glyph = extra_x_per_glyph.at_least(0.0); // Don't contract let mut extra_x_per_space = 0.0; if 0 < num_spaces_in_range && num_spaces_in_range < num_glyphs_in_range { // Add an integral number of pixels between each glyph, // and add the balance to the spaces: extra_x_per_glyph = point_scale.floor_to_pixel(extra_x_per_glyph); extra_x_per_space = (target_width - original_width - extra_x_per_glyph * (num_glyphs_in_range as f32 - 1.0)) / (num_spaces_in_range as f32); } placed_row.pos.x = point_scale.round_to_pixel(target_min_x); let mut translate_x = -original_min_x - extra_x_per_glyph * glyph_range.0 as f32; for glyph in &mut row.glyphs { glyph.pos.x += translate_x; glyph.pos.x = point_scale.round_to_pixel(glyph.pos.x); translate_x += extra_x_per_glyph; if glyph.chr.is_whitespace() { translate_x += extra_x_per_space; } } // Note we ignore the leading/trailing whitespace here! row.size.x = target_max_x - target_min_x; } /// Calculate the Y positions and tessellate the text. fn galley_from_rows( point_scale: PointScale, job: Arc<LayoutJob>, mut rows: Vec<PlacedRow>, elided: bool, intrinsic_size: Vec2, ) -> Galley { let mut first_row_min_height = job.first_row_min_height; let mut cursor_y = 0.0; for placed_row in &mut rows { let mut max_row_height = first_row_min_height.at_least(placed_row.height()); let row = Arc::make_mut(&mut placed_row.row); first_row_min_height = 0.0; for glyph in &row.glyphs { max_row_height = max_row_height.at_least(glyph.line_height); } max_row_height = point_scale.round_to_pixel(max_row_height); // Now position each glyph vertically: for glyph in &mut row.glyphs { let format = &job.sections[glyph.section_index as usize].format; glyph.pos.y = glyph.font_face_ascent // Apply valign to the different in height of the entire row, and the height of this `Font`: + format.valign.to_factor() * (max_row_height - glyph.line_height) // When mixing different `FontImpl` (e.g. latin and emojis), // we always center the difference: + 0.5 * (glyph.font_height - glyph.font_face_height); glyph.pos.y = point_scale.round_to_pixel(glyph.pos.y); } placed_row.pos.y = cursor_y; row.size.y = max_row_height; cursor_y += max_row_height; cursor_y = point_scale.round_to_pixel(cursor_y); // TODO(emilk): it would be better to do the calculations in pixels instead. } let format_summary = format_summary(&job); let mut rect = Rect::ZERO; let mut mesh_bounds = Rect::NOTHING; let mut num_vertices = 0; let mut num_indices = 0; for placed_row in &mut rows { rect |= placed_row.rect(); let row = Arc::make_mut(&mut placed_row.row); row.visuals = tessellate_row(point_scale, &job, &format_summary, row); mesh_bounds |= row.visuals.mesh_bounds.translate(placed_row.pos.to_vec2()); num_vertices += row.visuals.mesh.vertices.len(); num_indices += row.visuals.mesh.indices.len(); row.section_index_at_start = u32::MAX; // No longer in use. for glyph in &mut row.glyphs { glyph.section_index = u32::MAX; // No longer in use. } } let mut galley = Galley { job, rows, elided, rect, mesh_bounds, num_vertices, num_indices, pixels_per_point: point_scale.pixels_per_point, intrinsic_size, }; if galley.job.round_output_to_gui { galley.round_output_to_gui(); } galley } #[derive(Default)] struct FormatSummary { any_background: bool, any_underline: bool, any_strikethrough: bool, } fn format_summary(job: &LayoutJob) -> FormatSummary { let mut format_summary = FormatSummary::default(); for section in &job.sections { format_summary.any_background |= section.format.background != Color32::TRANSPARENT; format_summary.any_underline |= section.format.underline != Stroke::NONE; format_summary.any_strikethrough |= section.format.strikethrough != Stroke::NONE; } format_summary } fn tessellate_row( point_scale: PointScale, job: &LayoutJob, format_summary: &FormatSummary, row: &mut Row, ) -> RowVisuals { if row.glyphs.is_empty() { return Default::default(); } let mut mesh = Mesh::default(); mesh.reserve_triangles(row.glyphs.len() * 2); mesh.reserve_vertices(row.glyphs.len() * 4); if format_summary.any_background { add_row_backgrounds(point_scale, job, row, &mut mesh); } let glyph_index_start = mesh.indices.len(); let glyph_vertex_start = mesh.vertices.len(); tessellate_glyphs(point_scale, job, row, &mut mesh); let glyph_vertex_end = mesh.vertices.len(); if format_summary.any_underline { add_row_hline(point_scale, row, &mut mesh, |glyph| { let format = &job.sections[glyph.section_index as usize].format; let stroke = format.underline; let y = glyph.logical_rect().bottom(); (stroke, y) }); } if format_summary.any_strikethrough { add_row_hline(point_scale, row, &mut mesh, |glyph| { let format = &job.sections[glyph.section_index as usize].format; let stroke = format.strikethrough; let y = glyph.logical_rect().center().y; (stroke, y) }); } let mesh_bounds = mesh.calc_bounds(); RowVisuals { mesh, mesh_bounds, glyph_index_start, glyph_vertex_range: glyph_vertex_start..glyph_vertex_end, } } /// Create background for glyphs that have them. /// Creates as few rectangular regions as possible. fn add_row_backgrounds(point_scale: PointScale, job: &LayoutJob, row: &Row, mesh: &mut Mesh) { if row.glyphs.is_empty() { return; } let mut end_run = |start: Option<(Color32, Rect, f32)>, stop_x: f32| { if let Some((color, start_rect, expand)) = start { let rect = Rect::from_min_max(start_rect.left_top(), pos2(stop_x, start_rect.bottom())); let rect = rect.expand(expand); let rect = rect.round_to_pixels(point_scale.pixels_per_point()); mesh.add_colored_rect(rect, color); } }; let mut run_start = None; let mut last_rect = Rect::NAN; for glyph in &row.glyphs { let format = &job.sections[glyph.section_index as usize].format; let color = format.background; let rect = glyph.logical_rect(); if color == Color32::TRANSPARENT { end_run(run_start.take(), last_rect.right()); } else if let Some((existing_color, start, expand)) = run_start { if existing_color == color && start.top() == rect.top() && start.bottom() == rect.bottom() && format.expand_bg == expand { // continue the same background rectangle } else { end_run(run_start.take(), last_rect.right()); run_start = Some((color, rect, format.expand_bg)); } } else { run_start = Some((color, rect, format.expand_bg)); } last_rect = rect; } end_run(run_start.take(), last_rect.right()); } fn tessellate_glyphs(point_scale: PointScale, job: &LayoutJob, row: &mut Row, mesh: &mut Mesh) { for glyph in &mut row.glyphs { glyph.first_vertex = mesh.vertices.len() as u32; let uv_rect = glyph.uv_rect; if !uv_rect.is_nothing() { let mut left_top = glyph.pos + uv_rect.offset; left_top.x = point_scale.round_to_pixel(left_top.x); left_top.y = point_scale.round_to_pixel(left_top.y); let rect = Rect::from_min_max(left_top, left_top + uv_rect.size); let uv = Rect::from_min_max( pos2(uv_rect.min[0] as f32, uv_rect.min[1] as f32), pos2(uv_rect.max[0] as f32, uv_rect.max[1] as f32), ); let format = &job.sections[glyph.section_index as usize].format; let color = format.color; if format.italics { let idx = mesh.vertices.len() as u32; mesh.add_triangle(idx, idx + 1, idx + 2); mesh.add_triangle(idx + 2, idx + 1, idx + 3); let top_offset = rect.height() * 0.25 * Vec2::X; mesh.vertices.push(Vertex { pos: rect.left_top() + top_offset, uv: uv.left_top(), color, }); mesh.vertices.push(Vertex { pos: rect.right_top() + top_offset, uv: uv.right_top(), color, }); mesh.vertices.push(Vertex { pos: rect.left_bottom(), uv: uv.left_bottom(), color, }); mesh.vertices.push(Vertex { pos: rect.right_bottom(), uv: uv.right_bottom(), color, }); } else { mesh.add_rect_with_uv(rect, uv, color); } } } } /// Add a horizontal line over a row of glyphs with a stroke and y decided by a callback. fn add_row_hline( point_scale: PointScale, row: &Row, mesh: &mut Mesh, stroke_and_y: impl Fn(&Glyph) -> (Stroke, f32), ) { let mut path = crate::tessellator::Path::default(); // reusing path to avoid re-allocations. let mut end_line = |start: Option<(Stroke, Pos2)>, stop_x: f32| { if let Some((stroke, start)) = start { let stop = pos2(stop_x, start.y); path.clear(); path.add_line_segment([start, stop]); let feathering = 1.0 / point_scale.pixels_per_point(); path.stroke_open(feathering, &PathStroke::from(stroke), mesh); } }; let mut line_start = None; let mut last_right_x = f32::NAN; for glyph in &row.glyphs { let (stroke, mut y) = stroke_and_y(glyph); stroke.round_center_to_pixel(point_scale.pixels_per_point, &mut y); if stroke.is_empty() { end_line(line_start.take(), last_right_x); } else if let Some((existing_stroke, start)) = line_start { if existing_stroke == stroke && start.y == y { // continue the same line } else { end_line(line_start.take(), last_right_x); line_start = Some((stroke, pos2(glyph.pos.x, y))); } } else { line_start = Some((stroke, pos2(glyph.pos.x, y))); } last_right_x = glyph.max_x(); } end_line(line_start.take(), last_right_x); } // ---------------------------------------------------------------------------- /// Keeps track of good places to break a long row of text. /// Will focus primarily on spaces, secondarily on things like `-` #[derive(Clone, Copy, Default)] struct RowBreakCandidates { /// Breaking at ` ` or other whitespace /// is always the primary candidate.
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
true
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/epaint/src/text/text_layout_types.rs
crates/epaint/src/text/text_layout_types.rs
use std::ops::Range; use std::sync::Arc; use super::{ cursor::{CCursor, LayoutCursor}, font::UvRect, }; use crate::{Color32, FontId, Mesh, Stroke, text::FontsView}; use emath::{Align, GuiRounding as _, NumExt as _, OrderedFloat, Pos2, Rect, Vec2, pos2, vec2}; /// Describes the task of laying out text. /// /// This supports mixing different fonts, color and formats (underline etc). /// /// Pass this to [`crate::FontsView::layout_job`] or [`crate::text::layout`]. /// /// ## Example: /// ``` /// use epaint::{Color32, text::{LayoutJob, TextFormat}, FontFamily, FontId}; /// /// let mut job = LayoutJob::default(); /// job.append( /// "Hello ", /// 0.0, /// TextFormat { /// font_id: FontId::new(14.0, FontFamily::Proportional), /// color: Color32::WHITE, /// ..Default::default() /// }, /// ); /// job.append( /// "World!", /// 0.0, /// TextFormat { /// font_id: FontId::new(14.0, FontFamily::Monospace), /// color: Color32::BLACK, /// ..Default::default() /// }, /// ); /// ``` /// /// As you can see, constructing a [`LayoutJob`] is currently a lot of work. /// It would be nice to have a helper macro for it! #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct LayoutJob { /// The complete text of this job, referenced by [`LayoutSection`]. pub text: String, /// The different section, which can have different fonts, colors, etc. pub sections: Vec<LayoutSection>, /// Controls the text wrapping and elision. pub wrap: TextWrapping, /// The first row must be at least this high. /// This is in case we lay out text that is the continuation /// of some earlier text (sharing the same row), /// in which case this will be the height of the earlier text. /// In other cases, set this to `0.0`. pub first_row_min_height: f32, /// If `true`, all `\n` characters will result in a new _paragraph_, /// starting on a new row. /// /// If `false`, all `\n` characters will be ignored /// and show up as the replacement character. /// /// Default: `true`. pub break_on_newline: bool, /// How to horizontally align the text (`Align::LEFT`, `Align::Center`, `Align::RIGHT`). pub halign: Align, /// Justify text so that word-wrapped rows fill the whole [`TextWrapping::max_width`]. pub justify: bool, /// Round output sizes using [`emath::GuiRounding`], to avoid rounding errors in layout code. pub round_output_to_gui: bool, } impl Default for LayoutJob { #[inline] fn default() -> Self { Self { text: Default::default(), sections: Default::default(), wrap: Default::default(), first_row_min_height: 0.0, break_on_newline: true, halign: Align::LEFT, justify: false, round_output_to_gui: true, } } } impl LayoutJob { /// Break on `\n` and at the given wrap width. #[inline] pub fn simple(text: String, font_id: FontId, color: Color32, wrap_width: f32) -> Self { Self { sections: vec![LayoutSection { leading_space: 0.0, byte_range: 0..text.len(), format: TextFormat::simple(font_id, color), }], text, wrap: TextWrapping { max_width: wrap_width, ..Default::default() }, break_on_newline: true, ..Default::default() } } /// Break on `\n` #[inline] pub fn simple_format(text: String, format: TextFormat) -> Self { Self { sections: vec![LayoutSection { leading_space: 0.0, byte_range: 0..text.len(), format, }], text, break_on_newline: true, ..Default::default() } } /// Does not break on `\n`, but shows the replacement character instead. #[inline] pub fn simple_singleline(text: String, font_id: FontId, color: Color32) -> Self { Self { sections: vec![LayoutSection { leading_space: 0.0, byte_range: 0..text.len(), format: TextFormat::simple(font_id, color), }], text, wrap: Default::default(), break_on_newline: false, ..Default::default() } } #[inline] pub fn single_section(text: String, format: TextFormat) -> Self { Self { sections: vec![LayoutSection { leading_space: 0.0, byte_range: 0..text.len(), format, }], text, wrap: Default::default(), break_on_newline: true, ..Default::default() } } #[inline] pub fn is_empty(&self) -> bool { self.sections.is_empty() } /// Helper for adding a new section when building a [`LayoutJob`]. pub fn append(&mut self, text: &str, leading_space: f32, format: TextFormat) { let start = self.text.len(); self.text += text; let byte_range = start..self.text.len(); self.sections.push(LayoutSection { leading_space, byte_range, format, }); } /// The height of the tallest font used in the job. /// /// Returns a value rounded to [`emath::GUI_ROUNDING`]. pub fn font_height(&self, fonts: &mut FontsView<'_>) -> f32 { let mut max_height = 0.0_f32; for section in &self.sections { max_height = max_height.max(fonts.row_height(&section.format.font_id)); } max_height } /// The wrap with, with a small margin in some cases. pub fn effective_wrap_width(&self) -> f32 { if self.round_output_to_gui { // On a previous pass we may have rounded down by at most 0.5 and reported that as a width. // egui may then set that width as the max width for subsequent frames, and it is important // that we then don't wrap earlier. self.wrap.max_width + 0.5 } else { self.wrap.max_width } } } impl std::hash::Hash for LayoutJob { #[inline] fn hash<H: std::hash::Hasher>(&self, state: &mut H) { let Self { text, sections, wrap, first_row_min_height, break_on_newline, halign, justify, round_output_to_gui, } = self; text.hash(state); sections.hash(state); wrap.hash(state); emath::OrderedFloat(*first_row_min_height).hash(state); break_on_newline.hash(state); halign.hash(state); justify.hash(state); round_output_to_gui.hash(state); } } // ---------------------------------------------------------------------------- #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct LayoutSection { /// Can be used for first row indentation. pub leading_space: f32, /// Range into the galley text pub byte_range: Range<usize>, pub format: TextFormat, } impl std::hash::Hash for LayoutSection { #[inline] fn hash<H: std::hash::Hasher>(&self, state: &mut H) { let Self { leading_space, byte_range, format, } = self; OrderedFloat(*leading_space).hash(state); byte_range.hash(state); format.hash(state); } } // ---------------------------------------------------------------------------- /// Formatting option for a section of text. #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct TextFormat { pub font_id: FontId, /// Extra spacing between letters, in points. /// /// Default: 0.0. pub extra_letter_spacing: f32, /// Explicit line height of the text in points. /// /// This is the distance between the bottom row of two subsequent lines of text. /// /// If `None` (the default), the line height is determined by the font. /// /// For even text it is recommended you round this to an even number of _pixels_. pub line_height: Option<f32>, /// Text color pub color: Color32, pub background: Color32, /// Amount to expand background fill by. /// /// Default: 1.0 pub expand_bg: f32, pub italics: bool, pub underline: Stroke, pub strikethrough: Stroke, /// If you use a small font and [`Align::TOP`] you /// can get the effect of raised text. /// /// If you use a small font and [`Align::BOTTOM`] /// you get the effect of a subscript. /// /// If you use [`Align::Center`], you get text that is centered /// around a common center-line, which is nice when mixining emojis /// and normal text in e.g. a button. pub valign: Align, } impl Default for TextFormat { #[inline] fn default() -> Self { Self { font_id: FontId::default(), extra_letter_spacing: 0.0, line_height: None, color: Color32::GRAY, background: Color32::TRANSPARENT, expand_bg: 1.0, italics: false, underline: Stroke::NONE, strikethrough: Stroke::NONE, valign: Align::BOTTOM, } } } impl std::hash::Hash for TextFormat { #[inline] fn hash<H: std::hash::Hasher>(&self, state: &mut H) { let Self { font_id, extra_letter_spacing, line_height, color, background, expand_bg, italics, underline, strikethrough, valign, } = self; font_id.hash(state); emath::OrderedFloat(*extra_letter_spacing).hash(state); if let Some(line_height) = *line_height { emath::OrderedFloat(line_height).hash(state); } color.hash(state); background.hash(state); emath::OrderedFloat(*expand_bg).hash(state); italics.hash(state); underline.hash(state); strikethrough.hash(state); valign.hash(state); } } impl TextFormat { #[inline] pub fn simple(font_id: FontId, color: Color32) -> Self { Self { font_id, color, ..Default::default() } } } // ---------------------------------------------------------------------------- /// How to wrap and elide text. /// /// This enum is used in high-level APIs where providing a [`TextWrapping`] is too verbose. #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub enum TextWrapMode { /// The text should expand the `Ui` size when reaching its boundary. Extend, /// The text should wrap to the next line when reaching the `Ui` boundary. Wrap, /// The text should be elided using "…" when reaching the `Ui` boundary. /// /// Note that using [`TextWrapping`] and [`LayoutJob`] offers more control over the elision. Truncate, } /// Controls the text wrapping and elision of a [`LayoutJob`]. #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct TextWrapping { /// Wrap text so that no row is wider than this. /// /// If you would rather truncate text that doesn't fit, set [`Self::max_rows`] to `1`. /// /// Set `max_width` to [`f32::INFINITY`] to turn off wrapping and elision. /// /// Note that `\n` always produces a new row /// if [`LayoutJob::break_on_newline`] is `true`. pub max_width: f32, /// Maximum amount of rows the text galley should have. /// /// If this limit is reached, text will be truncated /// and [`Self::overflow_character`] appended to the final row. /// You can detect this by checking [`Galley::elided`]. /// /// If set to `0`, no text will be outputted. /// /// If set to `1`, a single row will be outputted, /// eliding the text after [`Self::max_width`] is reached. /// When you set `max_rows = 1`, it is recommended you also set [`Self::break_anywhere`] to `true`. /// /// Default value: `usize::MAX`. pub max_rows: usize, /// If `true`: Allow breaking between any characters. /// If `false` (default): prefer breaking between words, etc. /// /// NOTE: Due to limitations in the current implementation, /// when truncating text using [`Self::max_rows`] the text may be truncated /// in the middle of a word even if [`Self::break_anywhere`] is `false`. /// Therefore it is recommended to set [`Self::break_anywhere`] to `true` /// whenever [`Self::max_rows`] is set to `1`. pub break_anywhere: bool, /// Character to use to represent elided text. /// /// The default is `…`. /// /// If not set, no character will be used (but the text will still be elided). pub overflow_character: Option<char>, } impl std::hash::Hash for TextWrapping { #[inline] fn hash<H: std::hash::Hasher>(&self, state: &mut H) { let Self { max_width, max_rows, break_anywhere, overflow_character, } = self; emath::OrderedFloat(*max_width).hash(state); max_rows.hash(state); break_anywhere.hash(state); overflow_character.hash(state); } } impl Default for TextWrapping { fn default() -> Self { Self { max_width: f32::INFINITY, max_rows: usize::MAX, break_anywhere: false, overflow_character: Some('…'), } } } impl TextWrapping { /// Create a [`TextWrapping`] from a [`TextWrapMode`] and an available width. pub fn from_wrap_mode_and_width(mode: TextWrapMode, max_width: f32) -> Self { match mode { TextWrapMode::Extend => Self::no_max_width(), TextWrapMode::Wrap => Self::wrap_at_width(max_width), TextWrapMode::Truncate => Self::truncate_at_width(max_width), } } /// A row can be as long as it need to be. pub fn no_max_width() -> Self { Self { max_width: f32::INFINITY, ..Default::default() } } /// A row can be at most `max_width` wide but can wrap in any number of lines. pub fn wrap_at_width(max_width: f32) -> Self { Self { max_width, ..Default::default() } } /// Elide text that doesn't fit within the given width, replaced with `…`. pub fn truncate_at_width(max_width: f32) -> Self { Self { max_width, max_rows: 1, break_anywhere: true, ..Default::default() } } } // ---------------------------------------------------------------------------- /// Text that has been laid out, ready for painting. /// /// You can create a [`Galley`] using [`crate::FontsView::layout_job`]; /// /// Needs to be recreated if the underlying font atlas texture changes, which /// happens under the following conditions: /// - `pixels_per_point` or `max_texture_size` change. These parameters are set /// in [`crate::text::Fonts::begin_pass`]. When using `egui` they are set /// from `egui::InputState` and can change at any time. /// - The atlas has become full. This can happen any time a new glyph is added /// to the atlas, which in turn can happen any time new text is laid out. /// /// The name comes from typography, where a "galley" is a metal tray /// containing a column of set type, usually the size of a page of text. #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct Galley { /// The job that this galley is the result of. /// Contains the original string and style sections. pub job: Arc<LayoutJob>, /// Rows of text, from top to bottom, and their offsets. /// /// The number of characters in all rows sum up to `job.text.chars().count()` /// unless [`Self::elided`] is `true`. /// /// Note that a paragraph (a piece of text separated with `\n`) /// can be split up into multiple rows. pub rows: Vec<PlacedRow>, /// Set to true the text was truncated due to [`TextWrapping::max_rows`]. pub elided: bool, /// Bounding rect. /// /// `rect.top()` is always 0.0. /// /// With [`LayoutJob::halign`]: /// * [`Align::LEFT`]: `rect.left() == 0.0` /// * [`Align::Center`]: `rect.center() == 0.0` /// * [`Align::RIGHT`]: `rect.right() == 0.0` pub rect: Rect, /// Tight bounding box around all the meshes in all the rows. /// Can be used for culling. pub mesh_bounds: Rect, /// Total number of vertices in all the row meshes. pub num_vertices: usize, /// Total number of indices in all the row meshes. pub num_indices: usize, /// The number of physical pixels for each logical point. /// Since this affects the layout, we keep track of it /// so that we can warn if this has changed once we get to /// tessellation. pub pixels_per_point: f32, pub(crate) intrinsic_size: Vec2, } #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct PlacedRow { /// The position of this [`Row`] relative to the galley. /// /// This is rounded to the closest _pixel_ in order to produce crisp, pixel-perfect text. pub pos: Pos2, /// The underlying unpositioned [`Row`]. pub row: Arc<Row>, /// If true, this [`PlacedRow`] came from a paragraph ending with a `\n`. /// The `\n` itself is omitted from row's [`Row::glyphs`]. /// A `\n` in the input text always creates a new [`PlacedRow`] below it, /// so that text that ends with `\n` has an empty [`PlacedRow`] last. /// This also implies that the last [`PlacedRow`] in a [`Galley`] always has `ends_with_newline == false`. pub ends_with_newline: bool, } impl PlacedRow { /// Logical bounding rectangle on font heights etc. /// /// This ignores / includes the `LayoutSection::leading_space`. pub fn rect(&self) -> Rect { Rect::from_min_size(self.pos, self.row.size) } /// Same as [`Self::rect`] but excluding the `LayoutSection::leading_space`. pub fn rect_without_leading_space(&self) -> Rect { let x = self.glyphs.first().map_or(self.pos.x, |g| g.pos.x); let size_x = self.size.x - x; Rect::from_min_size(Pos2::new(x, self.pos.y), Vec2::new(size_x, self.size.y)) } } impl std::ops::Deref for PlacedRow { type Target = Row; fn deref(&self) -> &Self::Target { &self.row } } #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct Row { /// This is included in case there are no glyphs. /// /// Only used during layout, then set to an invalid value in order to /// enable the paragraph-concat optimization path without having to /// adjust `section_index` when concatting. pub(crate) section_index_at_start: u32, /// One for each `char`. pub glyphs: Vec<Glyph>, /// Logical size based on font heights etc. /// Includes leading and trailing whitespace. pub size: Vec2, /// The mesh, ready to be rendered. pub visuals: RowVisuals, } /// The tessellated output of a row. #[derive(Clone, Debug, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct RowVisuals { /// The tessellated text, using non-normalized (texel) UV coordinates. /// That is, you need to divide the uv coordinates by the texture size. pub mesh: Mesh, /// Bounds of the mesh, and can be used for culling. /// Does NOT include leading or trailing whitespace glyphs!! pub mesh_bounds: Rect, /// The number of triangle indices added before the first glyph triangle. /// /// This can be used to insert more triangles after the background but before the glyphs, /// i.e. for text selection visualization. pub glyph_index_start: usize, /// The range of vertices in the mesh that contain glyphs (as opposed to background, underlines, strikethorugh, etc). /// /// The glyph vertices comes after backgrounds (if any), but before any underlines and strikethrough. pub glyph_vertex_range: Range<usize>, } impl Default for RowVisuals { fn default() -> Self { Self { mesh: Default::default(), mesh_bounds: Rect::NOTHING, glyph_index_start: 0, glyph_vertex_range: 0..0, } } } #[derive(Copy, Clone, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct Glyph { /// The character this glyph represents. pub chr: char, /// Baseline position, relative to the row. /// Logical position: pos.y is the same for all chars of the same [`TextFormat`]. pub pos: Pos2, /// Logical width of the glyph. pub advance_width: f32, /// Height of this row of text. /// /// Usually same as [`Self::font_height`], /// unless explicitly overridden by [`TextFormat::line_height`]. pub line_height: f32, /// The ascent of this font. pub font_ascent: f32, /// The row/line height of this font. pub font_height: f32, /// The ascent of the sub-font within the font (`FontFace`). pub font_face_ascent: f32, /// The row/line height of the sub-font within the font (`FontFace`). pub font_face_height: f32, /// Position and size of the glyph in the font texture, in texels. pub uv_rect: UvRect, /// Index into [`LayoutJob::sections`]. Decides color etc. /// /// Only used during layout, then set to an invalid value in order to /// enable the paragraph-concat optimization path without having to /// adjust `section_index` when concatting. pub(crate) section_index: u32, /// Which is our first vertex in [`RowVisuals::mesh`]. pub first_vertex: u32, } impl Glyph { #[inline] pub fn size(&self) -> Vec2 { Vec2::new(self.advance_width, self.line_height) } #[inline] pub fn max_x(&self) -> f32 { self.pos.x + self.advance_width } /// Same y range for all characters with the same [`TextFormat`]. #[inline] pub fn logical_rect(&self) -> Rect { Rect::from_min_size(self.pos - vec2(0.0, self.font_ascent), self.size()) } } // ---------------------------------------------------------------------------- impl Row { /// The text on this row, excluding the implicit `\n` if any. pub fn text(&self) -> String { self.glyphs.iter().map(|g| g.chr).collect() } /// Excludes the implicit `\n` after the [`Row`], if any. #[inline] pub fn char_count_excluding_newline(&self) -> usize { self.glyphs.len() } /// Closest char at the desired x coordinate in row-relative coordinates. /// Returns something in the range `[0, char_count_excluding_newline()]`. pub fn char_at(&self, desired_x: f32) -> usize { for (i, glyph) in self.glyphs.iter().enumerate() { if desired_x < glyph.logical_rect().center().x { return i; } } self.char_count_excluding_newline() } pub fn x_offset(&self, column: usize) -> f32 { if let Some(glyph) = self.glyphs.get(column) { glyph.pos.x } else { self.size.x } } #[inline] pub fn height(&self) -> f32 { self.size.y } } impl PlacedRow { #[inline] pub fn min_y(&self) -> f32 { self.rect().top() } #[inline] pub fn max_y(&self) -> f32 { self.rect().bottom() } /// Includes the implicit `\n` after the [`PlacedRow`], if any. #[inline] pub fn char_count_including_newline(&self) -> usize { self.row.glyphs.len() + (self.ends_with_newline as usize) } } impl Galley { #[inline] pub fn is_empty(&self) -> bool { self.job.is_empty() } /// The full, non-elided text of the input job. #[inline] pub fn text(&self) -> &str { &self.job.text } #[inline] pub fn size(&self) -> Vec2 { self.rect.size() } /// This is the size that a non-wrapped, non-truncated, non-justified version of the text /// would have. /// /// Useful for advanced layouting. #[inline] pub fn intrinsic_size(&self) -> Vec2 { // We do the rounding here instead of in `round_output_to_gui` so that rounding // errors don't accumulate when concatenating multiple galleys. if self.job.round_output_to_gui { self.intrinsic_size.round_ui() } else { self.intrinsic_size } } pub(crate) fn round_output_to_gui(&mut self) { for placed_row in &mut self.rows { // Optimization: only call `make_mut` if necessary (can cause a deep clone) let rounded_size = placed_row.row.size.round_ui(); if placed_row.row.size != rounded_size { Arc::make_mut(&mut placed_row.row).size = rounded_size; } } let rect = &mut self.rect; let did_exceed_wrap_width_by_a_lot = rect.width() > self.job.wrap.max_width + 1.0; *rect = rect.round_ui(); if did_exceed_wrap_width_by_a_lot { // If the user picked a too aggressive wrap width (e.g. more narrow than any individual glyph), // we should let the user know by reporting that our width is wider than the wrap width. } else { // Make sure we don't report being wider than the wrap width the user picked: rect.max.x = rect .max .x .at_most(rect.min.x + self.job.wrap.max_width) .floor_ui(); } } /// Append each galley under the previous one. pub fn concat(job: Arc<LayoutJob>, galleys: &[Arc<Self>], pixels_per_point: f32) -> Self { profiling::function_scope!(); let mut merged_galley = Self { job, rows: Vec::new(), elided: false, rect: Rect::ZERO, mesh_bounds: Rect::NOTHING, num_vertices: 0, num_indices: 0, pixels_per_point, intrinsic_size: Vec2::ZERO, }; for (i, galley) in galleys.iter().enumerate() { let current_y_offset = merged_galley.rect.height(); let is_last_galley = i + 1 == galleys.len(); merged_galley .rows .extend(galley.rows.iter().enumerate().map(|(row_idx, placed_row)| { let new_pos = placed_row.pos + current_y_offset * Vec2::Y; let new_pos = new_pos.round_to_pixels(pixels_per_point); merged_galley.mesh_bounds |= placed_row.visuals.mesh_bounds.translate(new_pos.to_vec2()); merged_galley.rect |= Rect::from_min_size(new_pos, placed_row.size); let mut ends_with_newline = placed_row.ends_with_newline; let is_last_row_in_galley = row_idx + 1 == galley.rows.len(); // Since we remove the `\n` when splitting rows, we need to add it back here ends_with_newline |= !is_last_galley && is_last_row_in_galley; super::PlacedRow { pos: new_pos, row: Arc::clone(&placed_row.row), ends_with_newline, } })); merged_galley.num_vertices += galley.num_vertices; merged_galley.num_indices += galley.num_indices; // Note that if `galley.elided` is true this will be the last `Galley` in // the vector and the loop will end. merged_galley.elided |= galley.elided; merged_galley.intrinsic_size.x = f32::max(merged_galley.intrinsic_size.x, galley.intrinsic_size.x); merged_galley.intrinsic_size.y += galley.intrinsic_size.y; } if merged_galley.job.round_output_to_gui { merged_galley.round_output_to_gui(); } merged_galley } } impl AsRef<str> for Galley { #[inline] fn as_ref(&self) -> &str { self.text() } } impl std::borrow::Borrow<str> for Galley { #[inline] fn borrow(&self) -> &str { self.text() } } impl std::ops::Deref for Galley { type Target = str; #[inline] fn deref(&self) -> &str { self.text() } } // ---------------------------------------------------------------------------- /// ## Physical positions impl Galley { /// Zero-width rect past the last character. fn end_pos(&self) -> Rect { if let Some(row) = self.rows.last() { let x = row.rect().right(); Rect::from_min_max(pos2(x, row.min_y()), pos2(x, row.max_y())) } else { // Empty galley Rect::from_min_max(pos2(0.0, 0.0), pos2(0.0, 0.0)) } } /// Returns a 0-width Rect. fn pos_from_layout_cursor(&self, layout_cursor: &LayoutCursor) -> Rect { let Some(row) = self.rows.get(layout_cursor.row) else { return self.end_pos(); }; let x = row.x_offset(layout_cursor.column); Rect::from_min_max(pos2(x, row.min_y()), pos2(x, row.max_y())) } /// Returns a 0-width Rect. pub fn pos_from_cursor(&self, cursor: CCursor) -> Rect { self.pos_from_layout_cursor(&self.layout_from_cursor(cursor)) } /// Cursor at the given position within the galley. /// /// A cursor above the galley is considered /// same as a cursor at the start, /// and a cursor below the galley is considered /// same as a cursor at the end. /// This allows implementing text-selection by dragging above/below the galley. pub fn cursor_from_pos(&self, pos: Vec2) -> CCursor { // Vertical margin around galley improves text selection UX const VMARGIN: f32 = 5.0; if let Some(first_row) = self.rows.first() && pos.y < first_row.min_y() - VMARGIN { return self.begin(); } if let Some(last_row) = self.rows.last() && last_row.max_y() + VMARGIN < pos.y { return self.end(); } let mut best_y_dist = f32::INFINITY; let mut cursor = CCursor::default(); let mut ccursor_index = 0; for row in &self.rows { let min_y = row.min_y(); let max_y = row.max_y(); let is_pos_within_row = min_y <= pos.y && pos.y <= max_y; let y_dist = (min_y - pos.y).abs().min((max_y - pos.y).abs()); if is_pos_within_row || y_dist < best_y_dist { best_y_dist = y_dist; // char_at is `Row` not `PlacedRow` relative which means we have to subtract the pos. let column = row.char_at(pos.x - row.pos.x); let prefer_next_row = column < row.char_count_excluding_newline(); cursor = CCursor { index: ccursor_index + column, prefer_next_row, }; if is_pos_within_row { return cursor; } } ccursor_index += row.char_count_including_newline(); } cursor } } /// ## Cursor positions impl Galley { /// Cursor to the first character. /// /// This is the same as [`CCursor::default`]. #[inline] #[expect(clippy::unused_self)] pub fn begin(&self) -> CCursor { CCursor::default() } /// Cursor to one-past last character. pub fn end(&self) -> CCursor { if self.rows.is_empty() { return Default::default(); } let mut ccursor = CCursor { index: 0, prefer_next_row: true, }; for row in &self.rows { let row_char_count = row.char_count_including_newline(); ccursor.index += row_char_count; } ccursor } } /// ## Cursor conversions impl Galley { // The returned cursor is clamped.
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
true
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/epaint/src/shapes/text_shape.rs
crates/epaint/src/shapes/text_shape.rs
use std::sync::Arc; use emath::{Align2, Rot2}; use crate::*; /// How to paint some text on screen. /// /// This needs to be recreated if `pixels_per_point` (dpi scale) changes. #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct TextShape { /// Where the origin of [`Self::galley`] is. /// /// Usually the top left corner of the first character. pub pos: Pos2, /// The laid out text, from [`FontsView::layout_job`]. pub galley: Arc<Galley>, /// Add this underline to the whole text. /// You can also set an underline when creating the galley. pub underline: Stroke, /// Any [`Color32::PLACEHOLDER`] in the galley will be replaced by the given color. /// Affects everything: backgrounds, glyphs, strikethrough, underline, etc. pub fallback_color: Color32, /// If set, the text color in the galley will be ignored and replaced /// with the given color. /// /// This only affects the glyphs and will NOT replace background color nor strikethrough/underline color. pub override_text_color: Option<Color32>, /// If set, the text will be rendered with the given opacity in gamma space /// Affects everything: backgrounds, glyphs, strikethrough, underline, etc. pub opacity_factor: f32, /// Rotate text by this many radians clockwise. /// The pivot is `pos` (the upper left corner of the text). pub angle: f32, } impl TextShape { /// The given fallback color will be used for any uncolored part of the galley (using [`Color32::PLACEHOLDER`]). /// /// Any non-placeholder color in the galley takes precedence over this fallback color. #[inline] pub fn new(pos: Pos2, galley: Arc<Galley>, fallback_color: Color32) -> Self { Self { pos, galley, underline: Stroke::NONE, fallback_color, override_text_color: None, opacity_factor: 1.0, angle: 0.0, } } /// The visual bounding rectangle #[inline] pub fn visual_bounding_rect(&self) -> Rect { self.galley .mesh_bounds .rotate_bb(emath::Rot2::from_angle(self.angle)) .translate(self.pos.to_vec2()) } #[inline] pub fn with_underline(mut self, underline: Stroke) -> Self { self.underline = underline; self } /// Use the given color for the text, regardless of what color is already in the galley. #[inline] pub fn with_override_text_color(mut self, override_text_color: Color32) -> Self { self.override_text_color = Some(override_text_color); self } /// Set text rotation to `angle` radians clockwise. /// The pivot is `pos` (the upper left corner of the text). #[inline] pub fn with_angle(mut self, angle: f32) -> Self { self.angle = angle; self } /// Set the text rotation to the `angle` radians clockwise. /// The pivot is determined by the given `anchor` point on the text bounding box. #[inline] pub fn with_angle_and_anchor(mut self, angle: f32, anchor: Align2) -> Self { self.angle = angle; let a0 = anchor.pos_in_rect(&self.galley.rect).to_vec2(); let a1 = Rot2::from_angle(angle) * a0; self.pos += a0 - a1; self } /// Render text with this opacity in gamma space #[inline] pub fn with_opacity_factor(mut self, opacity_factor: f32) -> Self { self.opacity_factor = opacity_factor; self } /// Move the shape by this many points, in-place. pub fn transform(&mut self, transform: emath::TSTransform) { let Self { pos, galley, underline, fallback_color: _, override_text_color: _, opacity_factor: _, angle: _, } = self; *pos = transform * *pos; underline.width *= transform.scaling; let Galley { job: _, rows, elided: _, rect, mesh_bounds, num_vertices: _, num_indices: _, pixels_per_point: _, intrinsic_size, } = Arc::make_mut(galley); *rect = transform.scaling * *rect; *mesh_bounds = transform.scaling * *mesh_bounds; *intrinsic_size = transform.scaling * *intrinsic_size; for text::PlacedRow { pos, row, ends_with_newline: _, } in rows { *pos *= transform.scaling; let text::Row { section_index_at_start: _, glyphs: _, // TODO(emilk): would it make sense to transform these? size, visuals, } = Arc::make_mut(row); *size *= transform.scaling; let text::RowVisuals { mesh, mesh_bounds, glyph_index_start: _, glyph_vertex_range: _, } = visuals; *mesh_bounds = transform.scaling * *mesh_bounds; for v in &mut mesh.vertices { v.pos *= transform.scaling; } } } } impl From<TextShape> for Shape { #[inline(always)] fn from(shape: TextShape) -> Self { Self::Text(shape) } } #[cfg(test)] mod tests { use super::{super::*, *}; use crate::text::FontDefinitions; use emath::almost_equal; #[test] fn text_bounding_box_under_rotation() { let mut fonts = Fonts::new(TextOptions::default(), FontDefinitions::default()); let font = FontId::monospace(12.0); let mut t = crate::Shape::text( &mut fonts.with_pixels_per_point(1.0), Pos2::ZERO, emath::Align2::CENTER_CENTER, "testing123", font, Color32::BLACK, ); let size_orig = t.visual_bounding_rect().size(); // 90 degree rotation if let Shape::Text(ts) = &mut t { ts.angle = std::f32::consts::PI / 2.0; } let size_rot = t.visual_bounding_rect().size(); // make sure the box is actually rotated assert!(almost_equal(size_orig.x, size_rot.y, 1e-4)); assert!(almost_equal(size_orig.y, size_rot.x, 1e-4)); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/epaint/src/shapes/shape.rs
crates/epaint/src/shapes/shape.rs
//! The different shapes that can be painted. use std::sync::Arc; use emath::{Align2, Pos2, Rangef, Rect, TSTransform, Vec2, pos2}; use crate::{ Color32, CornerRadius, Mesh, Stroke, StrokeKind, TextureId, stroke::PathStroke, text::{FontId, FontsView, Galley}, }; use super::{ CircleShape, CubicBezierShape, EllipseShape, PaintCallback, PathShape, QuadraticBezierShape, RectShape, TextShape, }; /// A paint primitive such as a circle or a piece of text. /// Coordinates are all screen space points (not physical pixels). /// /// You should generally recreate your [`Shape`]s each frame, /// but storing them should also be fine with one exception: /// [`Shape::Text`] depends on the current `pixels_per_point` (dpi scale) /// and so must be recreated every time `pixels_per_point` changes. #[must_use = "Add a Shape to a Painter"] #[derive(Clone, Debug, PartialEq)] pub enum Shape { /// Paint nothing. This can be useful as a placeholder. Noop, /// Recursively nest more shapes - sometimes a convenience to be able to do. /// For performance reasons it is better to avoid it. Vec(Vec<Self>), /// Circle with optional outline and fill. Circle(CircleShape), /// Ellipse with optional outline and fill. Ellipse(EllipseShape), /// A line between two points. LineSegment { points: [Pos2; 2], stroke: Stroke }, /// A series of lines between points. /// The path can have a stroke and/or fill (if closed). Path(PathShape), /// Rectangle with optional outline and fill. Rect(RectShape), /// Text. /// /// This needs to be recreated if `pixels_per_point` (dpi scale) changes. Text(TextShape), /// A general triangle mesh. /// /// Can be used to display images. /// /// Wrapped in an [`Arc`] to minimize the size of [`Shape`]. Mesh(Arc<Mesh>), /// A quadratic [Bézier Curve](https://en.wikipedia.org/wiki/B%C3%A9zier_curve). QuadraticBezier(QuadraticBezierShape), /// A cubic [Bézier Curve](https://en.wikipedia.org/wiki/B%C3%A9zier_curve). CubicBezier(CubicBezierShape), /// Backend-specific painting. Callback(PaintCallback), } #[test] fn shape_size() { assert_eq!( std::mem::size_of::<Shape>(), 64, "Shape changed size! If it shrank - good! Update this test. If it grew - bad! Try to find a way to avoid it." ); assert!( std::mem::size_of::<Shape>() <= 64, "Shape is getting way too big!" ); } #[test] fn shape_impl_send_sync() { fn assert_send_sync<T: Send + Sync>() {} assert_send_sync::<Shape>(); } impl From<Vec<Self>> for Shape { #[inline(always)] fn from(shapes: Vec<Self>) -> Self { Self::Vec(shapes) } } impl From<Mesh> for Shape { #[inline(always)] fn from(mesh: Mesh) -> Self { Self::Mesh(mesh.into()) } } impl From<Arc<Mesh>> for Shape { #[inline(always)] fn from(mesh: Arc<Mesh>) -> Self { Self::Mesh(mesh) } } /// ## Constructors impl Shape { /// A line between two points. /// More efficient than calling [`Self::line`]. #[inline] pub fn line_segment(points: [Pos2; 2], stroke: impl Into<Stroke>) -> Self { Self::LineSegment { points, stroke: stroke.into(), } } /// A horizontal line. pub fn hline(x: impl Into<Rangef>, y: f32, stroke: impl Into<Stroke>) -> Self { let x = x.into(); Self::LineSegment { points: [pos2(x.min, y), pos2(x.max, y)], stroke: stroke.into(), } } /// A vertical line. pub fn vline(x: f32, y: impl Into<Rangef>, stroke: impl Into<Stroke>) -> Self { let y = y.into(); Self::LineSegment { points: [pos2(x, y.min), pos2(x, y.max)], stroke: stroke.into(), } } /// A line through many points. /// /// Use [`Self::line_segment`] instead if your line only connects two points. #[inline] pub fn line(points: Vec<Pos2>, stroke: impl Into<PathStroke>) -> Self { Self::Path(PathShape::line(points, stroke)) } /// A line that closes back to the start point again. #[inline] pub fn closed_line(points: Vec<Pos2>, stroke: impl Into<PathStroke>) -> Self { Self::Path(PathShape::closed_line(points, stroke)) } /// Turn a line into equally spaced dots. pub fn dotted_line( path: &[Pos2], color: impl Into<Color32>, spacing: f32, radius: f32, ) -> Vec<Self> { let mut shapes = Vec::new(); points_from_line(path, spacing, radius, color.into(), &mut shapes); shapes } /// Turn a line into dashes. pub fn dashed_line( path: &[Pos2], stroke: impl Into<Stroke>, dash_length: f32, gap_length: f32, ) -> Vec<Self> { let mut shapes = Vec::new(); dashes_from_line( path, stroke.into(), &[dash_length], &[gap_length], &mut shapes, 0., ); shapes } /// Turn a line into dashes with different dash/gap lengths and a start offset. pub fn dashed_line_with_offset( path: &[Pos2], stroke: impl Into<Stroke>, dash_lengths: &[f32], gap_lengths: &[f32], dash_offset: f32, ) -> Vec<Self> { let mut shapes = Vec::new(); dashes_from_line( path, stroke.into(), dash_lengths, gap_lengths, &mut shapes, dash_offset, ); shapes } /// Turn a line into dashes. If you need to create many dashed lines use this instead of /// [`Self::dashed_line`]. pub fn dashed_line_many( points: &[Pos2], stroke: impl Into<Stroke>, dash_length: f32, gap_length: f32, shapes: &mut Vec<Self>, ) { dashes_from_line( points, stroke.into(), &[dash_length], &[gap_length], shapes, 0., ); } /// Turn a line into dashes with different dash/gap lengths and a start offset. If you need to /// create many dashed lines use this instead of [`Self::dashed_line_with_offset`]. pub fn dashed_line_many_with_offset( points: &[Pos2], stroke: impl Into<Stroke>, dash_lengths: &[f32], gap_lengths: &[f32], dash_offset: f32, shapes: &mut Vec<Self>, ) { dashes_from_line( points, stroke.into(), dash_lengths, gap_lengths, shapes, dash_offset, ); } /// A convex polygon with a fill and optional stroke. /// /// The most performant winding order is clockwise. #[inline] pub fn convex_polygon( points: Vec<Pos2>, fill: impl Into<Color32>, stroke: impl Into<PathStroke>, ) -> Self { Self::Path(PathShape::convex_polygon(points, fill, stroke)) } #[inline] pub fn circle_filled(center: Pos2, radius: f32, fill_color: impl Into<Color32>) -> Self { Self::Circle(CircleShape::filled(center, radius, fill_color)) } #[inline] pub fn circle_stroke(center: Pos2, radius: f32, stroke: impl Into<Stroke>) -> Self { Self::Circle(CircleShape::stroke(center, radius, stroke)) } #[inline] pub fn ellipse_filled(center: Pos2, radius: Vec2, fill_color: impl Into<Color32>) -> Self { Self::Ellipse(EllipseShape::filled(center, radius, fill_color)) } #[inline] pub fn ellipse_stroke(center: Pos2, radius: Vec2, stroke: impl Into<Stroke>) -> Self { Self::Ellipse(EllipseShape::stroke(center, radius, stroke)) } /// See also [`Self::rect_stroke`]. #[inline] pub fn rect_filled( rect: Rect, corner_radius: impl Into<CornerRadius>, fill_color: impl Into<Color32>, ) -> Self { Self::Rect(RectShape::filled(rect, corner_radius, fill_color)) } /// See also [`Self::rect_filled`]. #[inline] pub fn rect_stroke( rect: Rect, corner_radius: impl Into<CornerRadius>, stroke: impl Into<Stroke>, stroke_kind: StrokeKind, ) -> Self { Self::Rect(RectShape::stroke(rect, corner_radius, stroke, stroke_kind)) } #[expect(clippy::needless_pass_by_value)] pub fn text( fonts: &mut FontsView<'_>, pos: Pos2, anchor: Align2, text: impl ToString, font_id: FontId, color: Color32, ) -> Self { let galley = fonts.layout_no_wrap(text.to_string(), font_id, color); let rect = anchor.anchor_size(pos, galley.size()); Self::galley(rect.min, galley, color) } /// Any uncolored parts of the [`Galley`] (using [`Color32::PLACEHOLDER`]) will be replaced with the given color. /// /// Any non-placeholder color in the galley takes precedence over this fallback color. #[inline] pub fn galley(pos: Pos2, galley: Arc<Galley>, fallback_color: Color32) -> Self { TextShape::new(pos, galley, fallback_color).into() } /// All text color in the [`Galley`] will be replaced with the given color. #[inline] pub fn galley_with_override_text_color( pos: Pos2, galley: Arc<Galley>, text_color: Color32, ) -> Self { TextShape::new(pos, galley, text_color) .with_override_text_color(text_color) .into() } #[inline] #[deprecated = "Use `Shape::galley` or `Shape::galley_with_override_text_color` instead"] pub fn galley_with_color(pos: Pos2, galley: Arc<Galley>, text_color: Color32) -> Self { Self::galley_with_override_text_color(pos, galley, text_color) } #[inline] pub fn mesh(mesh: impl Into<Arc<Mesh>>) -> Self { let mesh = mesh.into(); debug_assert!(mesh.is_valid(), "Invalid mesh: {mesh:#?}"); Self::Mesh(mesh) } /// An image at the given position. /// /// `uv` should normally be `Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0))` /// unless you want to crop or flip the image. /// /// `tint` is a color multiplier. Use [`Color32::WHITE`] if you don't want to tint the image. pub fn image(texture_id: TextureId, rect: Rect, uv: Rect, tint: Color32) -> Self { let mut mesh = Mesh::with_texture(texture_id); mesh.add_rect_with_uv(rect, uv, tint); Self::mesh(mesh) } /// The visual bounding rectangle (includes stroke widths) pub fn visual_bounding_rect(&self) -> Rect { match self { Self::Noop => Rect::NOTHING, Self::Vec(shapes) => { let mut rect = Rect::NOTHING; for shape in shapes { rect |= shape.visual_bounding_rect(); } rect } Self::Circle(circle_shape) => circle_shape.visual_bounding_rect(), Self::Ellipse(ellipse_shape) => ellipse_shape.visual_bounding_rect(), Self::LineSegment { points, stroke } => { if stroke.is_empty() { Rect::NOTHING } else { Rect::from_two_pos(points[0], points[1]).expand(stroke.width / 2.0) } } Self::Path(path_shape) => path_shape.visual_bounding_rect(), Self::Rect(rect_shape) => rect_shape.visual_bounding_rect(), Self::Text(text_shape) => text_shape.visual_bounding_rect(), Self::Mesh(mesh) => mesh.calc_bounds(), Self::QuadraticBezier(bezier) => bezier.visual_bounding_rect(), Self::CubicBezier(bezier) => bezier.visual_bounding_rect(), Self::Callback(custom) => custom.rect, } } } /// ## Inspection and transforms impl Shape { #[inline(always)] pub fn texture_id(&self) -> crate::TextureId { if let Self::Mesh(mesh) = self { mesh.texture_id } else if let Self::Rect(rect_shape) = self { rect_shape.fill_texture_id() } else { crate::TextureId::default() } } /// Scale the shape by `factor`, in-place. /// /// A wrapper around [`Self::transform`]. #[inline(always)] pub fn scale(&mut self, factor: f32) { self.transform(TSTransform::from_scaling(factor)); } /// Move the shape by `delta`, in-place. /// /// A wrapper around [`Self::transform`]. #[inline(always)] pub fn translate(&mut self, delta: Vec2) { self.transform(TSTransform::from_translation(delta)); } /// Transform (move/scale) the shape in-place. /// /// If using a [`PaintCallback`], note that only the rect is scaled as opposed /// to other shapes where the stroke is also scaled. pub fn transform(&mut self, transform: TSTransform) { match self { Self::Noop => {} Self::Vec(shapes) => { for shape in shapes { shape.transform(transform); } } Self::Circle(circle_shape) => { circle_shape.center = transform * circle_shape.center; circle_shape.radius *= transform.scaling; circle_shape.stroke.width *= transform.scaling; } Self::Ellipse(ellipse_shape) => { ellipse_shape.center = transform * ellipse_shape.center; ellipse_shape.radius *= transform.scaling; ellipse_shape.stroke.width *= transform.scaling; } Self::LineSegment { points, stroke } => { for p in points { *p = transform * *p; } stroke.width *= transform.scaling; } Self::Path(path_shape) => { for p in &mut path_shape.points { *p = transform * *p; } path_shape.stroke.width *= transform.scaling; } Self::Rect(rect_shape) => { rect_shape.rect = transform * rect_shape.rect; rect_shape.corner_radius *= transform.scaling; rect_shape.stroke.width *= transform.scaling; rect_shape.blur_width *= transform.scaling; } Self::Text(text_shape) => { text_shape.transform(transform); } Self::Mesh(mesh) => { Arc::make_mut(mesh).transform(transform); } Self::QuadraticBezier(bezier) => { for p in &mut bezier.points { *p = transform * *p; } bezier.stroke.width *= transform.scaling; } Self::CubicBezier(bezier) => { for p in &mut bezier.points { *p = transform * *p; } bezier.stroke.width *= transform.scaling; } Self::Callback(shape) => { shape.rect = transform * shape.rect; } } } } // ---------------------------------------------------------------------------- /// Creates equally spaced filled circles from a line. fn points_from_line( path: &[Pos2], spacing: f32, radius: f32, color: Color32, shapes: &mut Vec<Shape>, ) { let mut position_on_segment = 0.0; for window in path.windows(2) { let (start, end) = (window[0], window[1]); let vector = end - start; let segment_length = vector.length(); while position_on_segment < segment_length { let new_point = start + vector * (position_on_segment / segment_length); shapes.push(Shape::circle_filled(new_point, radius, color)); position_on_segment += spacing; } position_on_segment -= segment_length; } } /// Creates dashes from a line. fn dashes_from_line( path: &[Pos2], stroke: Stroke, dash_lengths: &[f32], gap_lengths: &[f32], shapes: &mut Vec<Shape>, dash_offset: f32, ) { assert_eq!( dash_lengths.len(), gap_lengths.len(), "Mismatched dash and gap lengths, got dash_lengths: {}, gap_lengths: {}", dash_lengths.len(), gap_lengths.len() ); let mut position_on_segment = dash_offset; let mut drawing_dash = false; let mut step = 0; let steps = dash_lengths.len(); for window in path.windows(2) { let (start, end) = (window[0], window[1]); let vector = end - start; let segment_length = vector.length(); let mut start_point = start; while position_on_segment < segment_length { let new_point = start + vector * (position_on_segment / segment_length); if drawing_dash { // This is the end point. shapes.push(Shape::line_segment([start_point, new_point], stroke)); position_on_segment += gap_lengths[step]; // Increment step counter step += 1; if step >= steps { step = 0; } } else { // Start a new dash. start_point = new_point; position_on_segment += dash_lengths[step]; } drawing_dash = !drawing_dash; } // If the segment ends and the dash is not finished, add the segment's end point. if drawing_dash { shapes.push(Shape::line_segment([start_point, end], stroke)); } position_on_segment -= segment_length; } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/epaint/src/shapes/ellipse_shape.rs
crates/epaint/src/shapes/ellipse_shape.rs
use crate::*; /// How to paint an ellipse. #[derive(Copy, Clone, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct EllipseShape { pub center: Pos2, /// Radius is the vector (a, b) where the width of the Ellipse is 2a and the height is 2b pub radius: Vec2, pub fill: Color32, pub stroke: Stroke, } impl EllipseShape { #[inline] pub fn filled(center: Pos2, radius: Vec2, fill_color: impl Into<Color32>) -> Self { Self { center, radius, fill: fill_color.into(), stroke: Default::default(), } } #[inline] pub fn stroke(center: Pos2, radius: Vec2, stroke: impl Into<Stroke>) -> Self { Self { center, radius, fill: Default::default(), stroke: stroke.into(), } } /// The visual bounding rectangle (includes stroke width) pub fn visual_bounding_rect(&self) -> Rect { if self.fill == Color32::TRANSPARENT && self.stroke.is_empty() { Rect::NOTHING } else { Rect::from_center_size( self.center, self.radius * 2.0 + Vec2::splat(self.stroke.width), ) } } } impl From<EllipseShape> for Shape { #[inline(always)] fn from(shape: EllipseShape) -> Self { Self::Ellipse(shape) } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/epaint/src/shapes/bezier_shape.rs
crates/epaint/src/shapes/bezier_shape.rs
#![expect(clippy::many_single_char_names)] use std::ops::Range; use crate::{Color32, PathShape, PathStroke, Shape}; use emath::{Pos2, Rect, RectTransform}; // ---------------------------------------------------------------------------- /// A cubic [Bézier Curve](https://en.wikipedia.org/wiki/B%C3%A9zier_curve). /// /// See also [`QuadraticBezierShape`]. #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct CubicBezierShape { /// The first point is the starting point and the last one is the ending point of the curve. /// The middle points are the control points. pub points: [Pos2; 4], pub closed: bool, pub fill: Color32, pub stroke: PathStroke, } impl CubicBezierShape { /// Creates a cubic Bézier curve based on 4 points and stroke. /// /// The first point is the starting point and the last one is the ending point of the curve. /// The middle points are the control points. pub fn from_points_stroke( points: [Pos2; 4], closed: bool, fill: Color32, stroke: impl Into<PathStroke>, ) -> Self { Self { points, closed, fill, stroke: stroke.into(), } } /// Transform the curve with the given transform. pub fn transform(&self, transform: &RectTransform) -> Self { let mut points = [Pos2::default(); 4]; for (i, origin_point) in self.points.iter().enumerate() { points[i] = transform * *origin_point; } Self { points, closed: self.closed, fill: self.fill, stroke: self.stroke.clone(), } } /// Convert the cubic Bézier curve to one or two [`PathShape`]'s. /// When the curve is closed and it has to intersect with the base line, it will be converted into two shapes. /// Otherwise, it will be converted into one shape. /// The `tolerance` will be used to control the max distance between the curve and the base line. /// The `epsilon` is used when comparing two floats. pub fn to_path_shapes(&self, tolerance: Option<f32>, epsilon: Option<f32>) -> Vec<PathShape> { let mut pathshapes = Vec::new(); let mut points_vec = self.flatten_closed(tolerance, epsilon); for points in points_vec.drain(..) { let pathshape = PathShape { points, closed: self.closed, fill: self.fill, stroke: self.stroke.clone(), }; pathshapes.push(pathshape); } pathshapes } /// The visual bounding rectangle (includes stroke width) pub fn visual_bounding_rect(&self) -> Rect { if self.fill == Color32::TRANSPARENT && self.stroke.is_empty() { Rect::NOTHING } else { self.logical_bounding_rect().expand(self.stroke.width / 2.0) } } /// Logical bounding rectangle (ignoring stroke width) pub fn logical_bounding_rect(&self) -> Rect { //temporary solution let (mut min_x, mut max_x) = if self.points[0].x < self.points[3].x { (self.points[0].x, self.points[3].x) } else { (self.points[3].x, self.points[0].x) }; let (mut min_y, mut max_y) = if self.points[0].y < self.points[3].y { (self.points[0].y, self.points[3].y) } else { (self.points[3].y, self.points[0].y) }; // find the inflection points and get the x value cubic_for_each_local_extremum( self.points[0].x, self.points[1].x, self.points[2].x, self.points[3].x, &mut |t| { let x = self.sample(t).x; if x < min_x { min_x = x; } if x > max_x { max_x = x; } }, ); // find the inflection points and get the y value cubic_for_each_local_extremum( self.points[0].y, self.points[1].y, self.points[2].y, self.points[3].y, &mut |t| { let y = self.sample(t).y; if y < min_y { min_y = y; } if y > max_y { max_y = y; } }, ); Rect { min: Pos2 { x: min_x, y: min_y }, max: Pos2 { x: max_x, y: max_y }, } } /// split the original cubic curve into a new one within a range. pub fn split_range(&self, t_range: Range<f32>) -> Self { debug_assert!( 0.0 <= t_range.start && t_range.end <= 1.0 && t_range.start <= t_range.end, "range should be in [0.0,1.0]" ); let from = self.sample(t_range.start); let to = self.sample(t_range.end); let d_from = self.points[1] - self.points[0].to_vec2(); let d_ctrl = self.points[2] - self.points[1].to_vec2(); let d_to = self.points[3] - self.points[2].to_vec2(); let q = QuadraticBezierShape { points: [d_from, d_ctrl, d_to], closed: self.closed, fill: self.fill, stroke: self.stroke.clone(), }; let delta_t = t_range.end - t_range.start; let q_start = q.sample(t_range.start); let q_end = q.sample(t_range.end); let ctrl1 = from + q_start.to_vec2() * delta_t; let ctrl2 = to - q_end.to_vec2() * delta_t; Self { points: [from, ctrl1, ctrl2, to], closed: self.closed, fill: self.fill, stroke: self.stroke.clone(), } } // copied from <https://docs.rs/lyon_geom/latest/src/lyon_geom/cubic_bezier.rs.html#384-396> // Computes the number of quadratic bézier segments to approximate a cubic one. // Derived by Raph Levien from section 10.6 of Sedeberg's CAGD notes // https://scholarsarchive.byu.edu/cgi/viewcontent.cgi?article=1000&context=facpub#section.10.6 // and the error metric from the caffein owl blog post http://caffeineowl.com/graphics/2d/vectorial/cubic2quad01.html pub fn num_quadratics(&self, tolerance: f32) -> u32 { debug_assert!(tolerance > 0.0, "the tolerance should be positive"); let x = self.points[0].x - 3.0 * self.points[1].x + 3.0 * self.points[2].x - self.points[3].x; let y = self.points[0].y - 3.0 * self.points[1].y + 3.0 * self.points[2].y - self.points[3].y; let err = x * x + y * y; (err / (432.0 * tolerance * tolerance)) .powf(1.0 / 6.0) .ceil() .max(1.0) as u32 } /// Find out the t value for the point where the curve is intersected with the base line. /// The base line is the line from P0 to P3. /// If the curve only has two intersection points with the base line, they should be 0.0 and 1.0. /// In this case, the "fill" will be simple since the curve is a convex line. /// If the curve has more than two intersection points with the base line, the "fill" will be a problem. /// We need to find out where is the 3rd t value (0<t<1) /// And the original cubic curve will be split into two curves (0.0..t and t..1.0). /// B(t) = (1-t)^3*P0 + 3*t*(1-t)^2*P1 + 3*t^2*(1-t)*P2 + t^3*P3 /// or B(t) = (P3 - 3*P2 + 3*P1 - P0)*t^3 + (3*P2 - 6*P1 + 3*P0)*t^2 + (3*P1 - 3*P0)*t + P0 /// this B(t) should be on the line between P0 and P3. Therefore: /// (B.x - P0.x)/(P3.x - P0.x) = (B.y - P0.y)/(P3.y - P0.y), or: /// B.x * (P3.y - P0.y) - B.y * (P3.x - P0.x) + P0.x * (P0.y - P3.y) + P0.y * (P3.x - P0.x) = 0 /// B.x = (P3.x - 3 * P2.x + 3 * P1.x - P0.x) * t^3 + (3 * P2.x - 6 * P1.x + 3 * P0.x) * t^2 + (3 * P1.x - 3 * P0.x) * t + P0.x /// B.y = (P3.y - 3 * P2.y + 3 * P1.y - P0.y) * t^3 + (3 * P2.y - 6 * P1.y + 3 * P0.y) * t^2 + (3 * P1.y - 3 * P0.y) * t + P0.y /// Combine the above three equations and iliminate B.x and B.y, we get: /// ```text /// t^3 * ( (P3.x - 3*P2.x + 3*P1.x - P0.x) * (P3.y - P0.y) - (P3.y - 3*P2.y + 3*P1.y - P0.y) * (P3.x - P0.x)) /// + t^2 * ( (3 * P2.x - 6 * P1.x + 3 * P0.x) * (P3.y - P0.y) - (3 * P2.y - 6 * P1.y + 3 * P0.y) * (P3.x - P0.x)) /// + t^1 * ( (3 * P1.x - 3 * P0.x) * (P3.y - P0.y) - (3 * P1.y - 3 * P0.y) * (P3.x - P0.x)) /// + (P0.x * (P3.y - P0.y) - P0.y * (P3.x - P0.x)) + P0.x * (P0.y - P3.y) + P0.y * (P3.x - P0.x) /// = 0 /// ``` /// or `a * t^3 + b * t^2 + c * t + d = 0` /// /// let x = t - b / (3 * a), then we have: /// ```text /// x^3 + p * x + q = 0, where: /// p = (3.0 * a * c - b^2) / (3.0 * a^2) /// q = (2.0 * b^3 - 9.0 * a * b * c + 27.0 * a^2 * d) / (27.0 * a^3) /// ``` /// /// when p > 0, there will be one real root, two complex roots /// when p = 0, there will be two real roots, when p=q=0, there will be three real roots but all 0. /// when p < 0, there will be three unique real roots. this is what we need. (x1, x2, x3) /// t = x + b / (3 * a), then we have: t1, t2, t3. /// the one between 0.0 and 1.0 is what we need. /// <`https://baike.baidu.com/item/%E4%B8%80%E5%85%83%E4%B8%89%E6%AC%A1%E6%96%B9%E7%A8%8B/8388473 /`> /// pub fn find_cross_t(&self, epsilon: f32) -> Option<f32> { let p0 = self.points[0]; let p1 = self.points[1]; let p2 = self.points[2]; let p3 = self.points[3]; let a = (p3.x - 3.0 * p2.x + 3.0 * p1.x - p0.x) * (p3.y - p0.y) - (p3.y - 3.0 * p2.y + 3.0 * p1.y - p0.y) * (p3.x - p0.x); let b = (3.0 * p2.x - 6.0 * p1.x + 3.0 * p0.x) * (p3.y - p0.y) - (3.0 * p2.y - 6.0 * p1.y + 3.0 * p0.y) * (p3.x - p0.x); let c = (3.0 * p1.x - 3.0 * p0.x) * (p3.y - p0.y) - (3.0 * p1.y - 3.0 * p0.y) * (p3.x - p0.x); let d = p0.x * (p3.y - p0.y) - p0.y * (p3.x - p0.x) + p0.x * (p0.y - p3.y) + p0.y * (p3.x - p0.x); let h = -b / (3.0 * a); let p = (3.0 * a * c - b * b) / (3.0 * a * a); let q = (2.0 * b * b * b - 9.0 * a * b * c + 27.0 * a * a * d) / (27.0 * a * a * a); if p > 0.0 { return None; } let r = (-(p / 3.0).powi(3)).sqrt(); let theta = (-q / (2.0 * r)).acos() / 3.0; let t1 = 2.0 * r.cbrt() * theta.cos() + h; let t2 = 2.0 * r.cbrt() * (theta + 120.0 * std::f32::consts::PI / 180.0).cos() + h; let t3 = 2.0 * r.cbrt() * (theta + 240.0 * std::f32::consts::PI / 180.0).cos() + h; if t1 > epsilon && t1 < 1.0 - epsilon { return Some(t1); } if t2 > epsilon && t2 < 1.0 - epsilon { return Some(t2); } if t3 > epsilon && t3 < 1.0 - epsilon { return Some(t3); } None } /// Calculate the point (x,y) at t based on the cubic Bézier curve equation. /// t is in [0.0,1.0] /// [Bézier Curve](https://en.wikipedia.org/wiki/B%C3%A9zier_curve#Cubic_B.C3.A9zier_curves) /// pub fn sample(&self, t: f32) -> Pos2 { debug_assert!( t >= 0.0 && t <= 1.0, "the sample value should be in [0.0,1.0]" ); let h = 1.0 - t; let a = t * t * t; let b = 3.0 * t * t * h; let c = 3.0 * t * h * h; let d = h * h * h; let result = self.points[3].to_vec2() * a + self.points[2].to_vec2() * b + self.points[1].to_vec2() * c + self.points[0].to_vec2() * d; result.to_pos2() } /// find a set of points that approximate the cubic Bézier curve. /// the number of points is determined by the tolerance. /// the points may not be evenly distributed in the range [0.0,1.0] (t value) pub fn flatten(&self, tolerance: Option<f32>) -> Vec<Pos2> { let tolerance = tolerance.unwrap_or_else(|| (self.points[0].x - self.points[3].x).abs() * 0.001); let mut result = vec![self.points[0]]; self.for_each_flattened_with_t(tolerance, &mut |p, _t| { result.push(p); }); result } /// find a set of points that approximate the cubic Bézier curve. /// the number of points is determined by the tolerance. /// the points may not be evenly distributed in the range [0.0,1.0] (t value) /// this api will check whether the curve will cross the base line or not when closed = true. /// The result will be a vec of vec of Pos2. it will store two closed aren in different vec. /// The epsilon is used to compare a float value. pub fn flatten_closed(&self, tolerance: Option<f32>, epsilon: Option<f32>) -> Vec<Vec<Pos2>> { let tolerance = tolerance.unwrap_or_else(|| (self.points[0].x - self.points[3].x).abs() * 0.001); let epsilon = epsilon.unwrap_or(1.0e-5); let mut result = Vec::new(); let mut first_half = Vec::new(); let mut second_half = Vec::new(); let mut flipped = false; first_half.push(self.points[0]); let cross = self.find_cross_t(epsilon); match cross { Some(cross) => { if self.closed { self.for_each_flattened_with_t(tolerance, &mut |p, t| { if t < cross { first_half.push(p); } else { if !flipped { // when just crossed the base line, flip the order of the points // add the cross point to the first half as the last point // and add the cross point to the second half as the first point flipped = true; let cross_point = self.sample(cross); first_half.push(cross_point); second_half.push(cross_point); } second_half.push(p); } }); } else { self.for_each_flattened_with_t(tolerance, &mut |p, _t| { first_half.push(p); }); } } None => { self.for_each_flattened_with_t(tolerance, &mut |p, _t| { first_half.push(p); }); } } result.push(first_half); if !second_half.is_empty() { result.push(second_half); } result } // from lyon_geom::cubic_bezier.rs /// Iterates through the curve invoking a callback at each point. pub fn for_each_flattened_with_t<F: FnMut(Pos2, f32)>(&self, tolerance: f32, callback: &mut F) { flatten_cubic_bezier_with_t(self, tolerance, callback); } } impl From<CubicBezierShape> for Shape { #[inline(always)] fn from(shape: CubicBezierShape) -> Self { Self::CubicBezier(shape) } } // ---------------------------------------------------------------------------- /// A quadratic [Bézier Curve](https://en.wikipedia.org/wiki/B%C3%A9zier_curve). /// /// See also [`CubicBezierShape`]. #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct QuadraticBezierShape { /// The first point is the starting point and the last one is the ending point of the curve. /// The middle point is the control points. pub points: [Pos2; 3], pub closed: bool, pub fill: Color32, pub stroke: PathStroke, } impl QuadraticBezierShape { /// Create a new quadratic Bézier shape based on the 3 points and stroke. /// /// The first point is the starting point and the last one is the ending point of the curve. /// The middle point is the control points. /// The points should be in the order [start, control, end] pub fn from_points_stroke( points: [Pos2; 3], closed: bool, fill: Color32, stroke: impl Into<PathStroke>, ) -> Self { Self { points, closed, fill, stroke: stroke.into(), } } /// Transform the curve with the given transform. pub fn transform(&self, transform: &RectTransform) -> Self { let mut points = [Pos2::default(); 3]; for (i, origin_point) in self.points.iter().enumerate() { points[i] = transform * *origin_point; } Self { points, closed: self.closed, fill: self.fill, stroke: self.stroke.clone(), } } /// Convert the quadratic Bézier curve to one [`PathShape`]. /// The `tolerance` will be used to control the max distance between the curve and the base line. pub fn to_path_shape(&self, tolerance: Option<f32>) -> PathShape { let points = self.flatten(tolerance); PathShape { points, closed: self.closed, fill: self.fill, stroke: self.stroke.clone(), } } /// The visual bounding rectangle (includes stroke width) pub fn visual_bounding_rect(&self) -> Rect { if self.fill == Color32::TRANSPARENT && self.stroke.is_empty() { Rect::NOTHING } else { self.logical_bounding_rect().expand(self.stroke.width / 2.0) } } /// Logical bounding rectangle (ignoring stroke width) pub fn logical_bounding_rect(&self) -> Rect { let (mut min_x, mut max_x) = if self.points[0].x < self.points[2].x { (self.points[0].x, self.points[2].x) } else { (self.points[2].x, self.points[0].x) }; let (mut min_y, mut max_y) = if self.points[0].y < self.points[2].y { (self.points[0].y, self.points[2].y) } else { (self.points[2].y, self.points[0].y) }; quadratic_for_each_local_extremum( self.points[0].x, self.points[1].x, self.points[2].x, &mut |t| { let x = self.sample(t).x; if x < min_x { min_x = x; } if x > max_x { max_x = x; } }, ); quadratic_for_each_local_extremum( self.points[0].y, self.points[1].y, self.points[2].y, &mut |t| { let y = self.sample(t).y; if y < min_y { min_y = y; } if y > max_y { max_y = y; } }, ); Rect { min: Pos2 { x: min_x, y: min_y }, max: Pos2 { x: max_x, y: max_y }, } } /// Calculate the point (x,y) at t based on the quadratic Bézier curve equation. /// t is in [0.0,1.0] /// [Bézier Curve](https://en.wikipedia.org/wiki/B%C3%A9zier_curve#Quadratic_B.C3.A9zier_curves) /// pub fn sample(&self, t: f32) -> Pos2 { debug_assert!( t >= 0.0 && t <= 1.0, "the sample value should be in [0.0,1.0]" ); let h = 1.0 - t; let a = t * t; let b = 2.0 * t * h; let c = h * h; let result = self.points[2].to_vec2() * a + self.points[1].to_vec2() * b + self.points[0].to_vec2() * c; result.to_pos2() } /// find a set of points that approximate the quadratic Bézier curve. /// the number of points is determined by the tolerance. /// the points may not be evenly distributed in the range [0.0,1.0] (t value) pub fn flatten(&self, tolerance: Option<f32>) -> Vec<Pos2> { let tolerance = tolerance.unwrap_or_else(|| (self.points[0].x - self.points[2].x).abs() * 0.001); let mut result = vec![self.points[0]]; self.for_each_flattened_with_t(tolerance, &mut |p, _t| { result.push(p); }); result } // copied from https://docs.rs/lyon_geom/latest/lyon_geom/ /// Compute a flattened approximation of the curve, invoking a callback at /// each step. /// /// The callback takes the point and corresponding curve parameter at each step. /// /// This implements the algorithm described by Raph Levien at /// <https://raphlinus.github.io/graphics/curves/2019/12/23/flatten-quadbez.html> pub fn for_each_flattened_with_t<F>(&self, tolerance: f32, callback: &mut F) where F: FnMut(Pos2, f32), { let params = FlatteningParameters::from_curve(self, tolerance); if params.is_point { return; } let count = params.count as u32; for index in 1..count { let t = params.t_at_iteration(index as f32); callback(self.sample(t), t); } callback(self.sample(1.0), 1.0); } } impl From<QuadraticBezierShape> for Shape { #[inline(always)] fn from(shape: QuadraticBezierShape) -> Self { Self::QuadraticBezier(shape) } } // ---------------------------------------------------------------------------- // lyon_geom::flatten_cubic.rs // copied from https://docs.rs/lyon_geom/latest/lyon_geom/ fn flatten_cubic_bezier_with_t<F: FnMut(Pos2, f32)>( curve: &CubicBezierShape, tolerance: f32, callback: &mut F, ) { // debug_assert!(tolerance >= S::EPSILON * S::EPSILON); let quadratics_tolerance = tolerance * 0.2; let flattening_tolerance = tolerance * 0.8; let num_quadratics = curve.num_quadratics(quadratics_tolerance); let step = 1.0 / num_quadratics as f32; let n = num_quadratics; let mut t0 = 0.0; for _ in 0..(n - 1) { let t1 = t0 + step; let quadratic = single_curve_approximation(&curve.split_range(t0..t1)); quadratic.for_each_flattened_with_t(flattening_tolerance, &mut |point, t_sub| { let t = t0 + step * t_sub; callback(point, t); }); t0 = t1; } // Do the last step manually to make sure we finish at t = 1.0 exactly. let quadratic = single_curve_approximation(&curve.split_range(t0..1.0)); quadratic.for_each_flattened_with_t(flattening_tolerance, &mut |point, t_sub| { let t = t0 + step * t_sub; callback(point, t); }); } // from lyon_geom::quadratic_bezier.rs // copied from https://docs.rs/lyon_geom/latest/lyon_geom/ struct FlatteningParameters { count: f32, integral_from: f32, integral_step: f32, inv_integral_from: f32, div_inv_integral_diff: f32, is_point: bool, } impl FlatteningParameters { // https://raphlinus.github.io/graphics/curves/2019/12/23/flatten-quadbez.html pub fn from_curve(curve: &QuadraticBezierShape, tolerance: f32) -> Self { #![expect(clippy::useless_let_if_seq)] // Map the quadratic bézier segment to y = x^2 parabola. let from = curve.points[0]; let ctrl = curve.points[1]; let to = curve.points[2]; let ddx = 2.0 * ctrl.x - from.x - to.x; let ddy = 2.0 * ctrl.y - from.y - to.y; let cross = (to.x - from.x) * ddy - (to.y - from.y) * ddx; let inv_cross = 1.0 / cross; let parabola_from = ((ctrl.x - from.x) * ddx + (ctrl.y - from.y) * ddy) * inv_cross; let parabola_to = ((to.x - ctrl.x) * ddx + (to.y - ctrl.y) * ddy) * inv_cross; // Note, scale can be NaN, for example with straight lines. When it happens the NaN will // propagate to other parameters. We catch it all by setting the iteration count to zero // and leave the rest as garbage. let scale = cross.abs() / (ddx.hypot(ddy) * (parabola_to - parabola_from).abs()); let integral_from = approx_parabola_integral(parabola_from); let integral_to = approx_parabola_integral(parabola_to); let integral_diff = integral_to - integral_from; let inv_integral_from = approx_parabola_inv_integral(integral_from); let inv_integral_to = approx_parabola_inv_integral(integral_to); let div_inv_integral_diff = 1.0 / (inv_integral_to - inv_integral_from); // the original author thinks it can be stored as integer if it's not generic. // but if so, we have to handle the edge case of the integral being infinite. let mut count = (0.5 * integral_diff.abs() * (scale / tolerance).sqrt()).ceil(); let mut is_point = false; // If count is NaN the curve can be approximated by a single straight line or a point. if !count.is_finite() { count = 0.0; is_point = (to.x - from.x).hypot(to.y - from.y) < tolerance * tolerance; } let integral_step = integral_diff / count; Self { count, integral_from, integral_step, inv_integral_from, div_inv_integral_diff, is_point, } } fn t_at_iteration(&self, iteration: f32) -> f32 { let u = approx_parabola_inv_integral(self.integral_from + self.integral_step * iteration); (u - self.inv_integral_from) * self.div_inv_integral_diff } } /// Compute an approximation to integral (1 + 4x^2) ^ -0.25 dx used in the flattening code. fn approx_parabola_integral(x: f32) -> f32 { let d: f32 = 0.67; let quarter = 0.25; x / (1.0 - d + (d.powi(4) + quarter * x * x).sqrt().sqrt()) } /// Approximate the inverse of the function above. fn approx_parabola_inv_integral(x: f32) -> f32 { let b = 0.39; let quarter = 0.25; x * (1.0 - b + (b * b + quarter * x * x).sqrt()) } fn single_curve_approximation(curve: &CubicBezierShape) -> QuadraticBezierShape { let c1_x = (curve.points[1].x * 3.0 - curve.points[0].x) * 0.5; let c1_y = (curve.points[1].y * 3.0 - curve.points[0].y) * 0.5; let c2_x = (curve.points[2].x * 3.0 - curve.points[3].x) * 0.5; let c2_y = (curve.points[2].y * 3.0 - curve.points[3].y) * 0.5; let c = Pos2 { x: (c1_x + c2_x) * 0.5, y: (c1_y + c2_y) * 0.5, }; QuadraticBezierShape { points: [curve.points[0], c, curve.points[3]], closed: curve.closed, fill: curve.fill, stroke: curve.stroke.clone(), } } fn quadratic_for_each_local_extremum<F: FnMut(f32)>(p0: f32, p1: f32, p2: f32, cb: &mut F) { // A quadratic Bézier curve can be derived by a linear function: // p(t) = p0 + t(p1 - p0) + t^2(p2 - 2p1 + p0) // The derivative is: // p'(t) = (p1 - p0) + 2(p2 - 2p1 + p0)t or: // f(x) = a* x + b let a = p2 - 2.0 * p1 + p0; // let b = p1 - p0; // no need to check for zero, since we're only interested in local extrema if a == 0.0 { return; } let t = (p0 - p1) / a; if t > 0.0 && t < 1.0 { cb(t); } } fn cubic_for_each_local_extremum<F: FnMut(f32)>(p0: f32, p1: f32, p2: f32, p3: f32, cb: &mut F) { // See www.faculty.idc.ac.il/arik/quality/appendixa.html for an explanation // A cubic Bézier curve can be derived by the following equation: // B'(t) = 3(1-t)^2(p1-p0) + 6(1-t)t(p2-p1) + 3t^2(p3-p2) or // f(x) = a * x² + b * x + c let a = 3.0 * (p3 + 3.0 * (p1 - p2) - p0); let b = 6.0 * (p2 - 2.0 * p1 + p0); let c = 3.0 * (p1 - p0); let in_range = |t: f32| t <= 1.0 && t >= 0.0; // linear situation if a == 0.0 { if b != 0.0 { let t = -c / b; if in_range(t) { cb(t); } } return; } let discr = b * b - 4.0 * a * c; // no Real solution if discr < 0.0 { return; } // one Real solution if discr == 0.0 { let t = -b / (2.0 * a); if in_range(t) { cb(t); } return; } // two Real solutions let discr = discr.sqrt(); let t1 = (-b - discr) / (2.0 * a); let t2 = (-b + discr) / (2.0 * a); if in_range(t1) { cb(t1); } if in_range(t2) { cb(t2); } } #[cfg(test)] mod tests { use emath::pos2; use super::*; #[test] fn test_quadratic_bounding_box() { let curve = QuadraticBezierShape { points: [ Pos2 { x: 110.0, y: 170.0 }, Pos2 { x: 10.0, y: 10.0 }, Pos2 { x: 180.0, y: 30.0 }, ], closed: false, fill: Default::default(), stroke: Default::default(), }; let bbox = curve.logical_bounding_rect(); assert!((bbox.min.x - 72.96).abs() < 0.01); assert!((bbox.min.y - 27.78).abs() < 0.01); assert!((bbox.max.x - 180.0).abs() < 0.01); assert!((bbox.max.y - 170.0).abs() < 0.01); let mut result = vec![curve.points[0]]; //add the start point curve.for_each_flattened_with_t(0.1, &mut |pos, _t| { result.push(pos); }); assert_eq!(result.len(), 26); let curve = QuadraticBezierShape { points: [ Pos2 { x: 110.0, y: 170.0 }, Pos2 { x: 180.0, y: 30.0 }, Pos2 { x: 10.0, y: 10.0 }, ], closed: false, fill: Default::default(), stroke: Default::default(), }; let bbox = curve.logical_bounding_rect(); assert!((bbox.min.x - 10.0).abs() < 0.01); assert!((bbox.min.y - 10.0).abs() < 0.01); assert!((bbox.max.x - 130.42).abs() < 0.01); assert!((bbox.max.y - 170.0).abs() < 0.01); let mut result = vec![curve.points[0]]; //add the start point curve.for_each_flattened_with_t(0.1, &mut |pos, _t| { result.push(pos); }); assert_eq!(result.len(), 25); } #[test] fn test_quadratic_different_tolerance() { let curve = QuadraticBezierShape { points: [ Pos2 { x: 110.0, y: 170.0 }, Pos2 { x: 180.0, y: 30.0 }, Pos2 { x: 10.0, y: 10.0 }, ], closed: false, fill: Default::default(), stroke: Default::default(), }; let mut result = vec![curve.points[0]]; //add the start point curve.for_each_flattened_with_t(1.0, &mut |pos, _t| { result.push(pos); }); assert_eq!(result.len(), 9); let mut result = vec![curve.points[0]]; //add the start point curve.for_each_flattened_with_t(0.1, &mut |pos, _t| { result.push(pos); }); assert_eq!(result.len(), 25); let mut result = vec![curve.points[0]]; //add the start point curve.for_each_flattened_with_t(0.01, &mut |pos, _t| { result.push(pos); }); assert_eq!(result.len(), 77); let mut result = vec![curve.points[0]]; //add the start point curve.for_each_flattened_with_t(0.001, &mut |pos, _t| { result.push(pos); }); assert_eq!(result.len(), 240); } #[test] fn test_cubic_bounding_box() { let curve = CubicBezierShape { points: [ pos2(10.0, 10.0), pos2(110.0, 170.0), pos2(180.0, 30.0), pos2(270.0, 210.0), ], closed: false, fill: Default::default(), stroke: Default::default(), }; let bbox = curve.logical_bounding_rect(); assert_eq!(bbox.min.x, 10.0); assert_eq!(bbox.min.y, 10.0); assert_eq!(bbox.max.x, 270.0); assert_eq!(bbox.max.y, 210.0); let curve = CubicBezierShape { points: [ pos2(10.0, 10.0), pos2(110.0, 170.0), pos2(270.0, 210.0), pos2(180.0, 30.0), ], closed: false, fill: Default::default(), stroke: Default::default(), }; let bbox = curve.logical_bounding_rect(); assert_eq!(bbox.min.x, 10.0); assert_eq!(bbox.min.y, 10.0); assert!((bbox.max.x - 206.50).abs() < 0.01); assert!((bbox.max.y - 148.48).abs() < 0.01); let curve = CubicBezierShape { points: [ pos2(110.0, 170.0), pos2(10.0, 10.0), pos2(270.0, 210.0), pos2(180.0, 30.0), ], closed: false, fill: Default::default(), stroke: Default::default(), }; let bbox = curve.logical_bounding_rect();
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
true
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/epaint/src/shapes/mod.rs
crates/epaint/src/shapes/mod.rs
mod bezier_shape; mod circle_shape; mod ellipse_shape; mod paint_callback; mod path_shape; mod rect_shape; mod shape; mod text_shape; pub use self::{ bezier_shape::{CubicBezierShape, QuadraticBezierShape}, circle_shape::CircleShape, ellipse_shape::EllipseShape, paint_callback::{PaintCallback, PaintCallbackInfo}, path_shape::PathShape, rect_shape::RectShape, shape::Shape, text_shape::TextShape, };
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/epaint/src/shapes/circle_shape.rs
crates/epaint/src/shapes/circle_shape.rs
use crate::{Color32, Pos2, Rect, Shape, Stroke, Vec2}; /// How to paint a circle. #[derive(Copy, Clone, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct CircleShape { pub center: Pos2, pub radius: f32, pub fill: Color32, pub stroke: Stroke, } impl CircleShape { #[inline] pub fn filled(center: Pos2, radius: f32, fill_color: impl Into<Color32>) -> Self { Self { center, radius, fill: fill_color.into(), stroke: Default::default(), } } #[inline] pub fn stroke(center: Pos2, radius: f32, stroke: impl Into<Stroke>) -> Self { Self { center, radius, fill: Default::default(), stroke: stroke.into(), } } /// The visual bounding rectangle (includes stroke width) pub fn visual_bounding_rect(&self) -> Rect { if self.fill == Color32::TRANSPARENT && self.stroke.is_empty() { Rect::NOTHING } else { Rect::from_center_size( self.center, Vec2::splat(self.radius * 2.0 + self.stroke.width), ) } } } impl From<CircleShape> for Shape { #[inline(always)] fn from(shape: CircleShape) -> Self { Self::Circle(shape) } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/epaint/src/shapes/rect_shape.rs
crates/epaint/src/shapes/rect_shape.rs
use std::sync::Arc; use crate::*; /// How to paint a rectangle. #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct RectShape { pub rect: Rect, /// How rounded the corners of the rectangle are. /// /// Use [`CornerRadius::ZERO`] for for sharp corners. /// /// This is the corner radii of the rectangle. /// If there is a stroke, then the stroke will have an inner and outer corner radius, /// and those will depend on [`StrokeKind`] and the stroke width. /// /// For [`StrokeKind::Inside`], the outside of the stroke coincides with the rectangle, /// so the rounding will in this case specify the outer corner radius. pub corner_radius: CornerRadius, /// How to fill the rectangle. pub fill: Color32, /// The thickness and color of the outline. /// /// Whether or not the stroke is inside or outside the edge of [`Self::rect`], /// is controlled by [`Self::stroke_kind`]. pub stroke: Stroke, /// Is the stroke on the inside, outside, or centered on the rectangle? /// /// If you want to perfectly tile rectangles, use [`StrokeKind::Inside`]. pub stroke_kind: StrokeKind, /// Snap the rectangle to pixels? /// /// Rounding produces sharper rectangles. /// /// If `None`, [`crate::TessellationOptions::round_rects_to_pixels`] will be used. pub round_to_pixels: Option<bool>, /// If larger than zero, the edges of the rectangle /// (for both fill and stroke) will be blurred. /// /// This can be used to produce shadows and glow effects. /// /// The blur is currently implemented using a simple linear blur in sRGBA gamma space. pub blur_width: f32, /// Controls texturing, if any. /// /// Since most rectangles do not have a texture, this is optional and in an `Arc`, /// so that [`RectShape`] is kept small.. pub brush: Option<Arc<Brush>>, } #[test] fn rect_shape_size() { assert_eq!( std::mem::size_of::<RectShape>(), 48, "RectShape changed size! If it shrank - good! Update this test. If it grew - bad! Try to find a way to avoid it." ); assert!( std::mem::size_of::<RectShape>() <= 64, "RectShape is getting way too big!" ); } impl RectShape { /// See also [`Self::filled`] and [`Self::stroke`]. #[inline] pub fn new( rect: Rect, corner_radius: impl Into<CornerRadius>, fill_color: impl Into<Color32>, stroke: impl Into<Stroke>, stroke_kind: StrokeKind, ) -> Self { Self { rect, corner_radius: corner_radius.into(), fill: fill_color.into(), stroke: stroke.into(), stroke_kind, round_to_pixels: None, blur_width: 0.0, brush: Default::default(), } } #[inline] pub fn filled( rect: Rect, corner_radius: impl Into<CornerRadius>, fill_color: impl Into<Color32>, ) -> Self { Self::new( rect, corner_radius, fill_color, Stroke::NONE, StrokeKind::Outside, // doesn't matter ) } #[inline] pub fn stroke( rect: Rect, corner_radius: impl Into<CornerRadius>, stroke: impl Into<Stroke>, stroke_kind: StrokeKind, ) -> Self { let fill = Color32::TRANSPARENT; Self::new(rect, corner_radius, fill, stroke, stroke_kind) } /// Set if the stroke is on the inside, outside, or centered on the rectangle. #[inline] pub fn with_stroke_kind(mut self, stroke_kind: StrokeKind) -> Self { self.stroke_kind = stroke_kind; self } /// Snap the rectangle to pixels? /// /// Rounding produces sharper rectangles. /// /// If `None`, [`crate::TessellationOptions::round_rects_to_pixels`] will be used. #[inline] pub fn with_round_to_pixels(mut self, round_to_pixels: bool) -> Self { self.round_to_pixels = Some(round_to_pixels); self } /// If larger than zero, the edges of the rectangle /// (for both fill and stroke) will be blurred. /// /// This can be used to produce shadows and glow effects. /// /// The blur is currently implemented using a simple linear blur in `sRGBA` gamma space. #[inline] pub fn with_blur_width(mut self, blur_width: f32) -> Self { self.blur_width = blur_width; self } /// Set the texture to use when painting this rectangle, if any. #[inline] pub fn with_texture(mut self, fill_texture_id: TextureId, uv: Rect) -> Self { self.brush = Some(Arc::new(Brush { fill_texture_id, uv, })); self } /// The visual bounding rectangle (includes stroke width) #[inline] pub fn visual_bounding_rect(&self) -> Rect { if self.fill == Color32::TRANSPARENT && self.stroke.is_empty() { Rect::NOTHING } else { let expand = match self.stroke_kind { StrokeKind::Inside => 0.0, StrokeKind::Middle => self.stroke.width / 2.0, StrokeKind::Outside => self.stroke.width, }; self.rect.expand(expand + self.blur_width / 2.0) } } /// The texture to use when painting this rectangle, if any. /// /// If no texture is set, this will return [`TextureId::default`]. pub fn fill_texture_id(&self) -> TextureId { self.brush .as_ref() .map_or_else(TextureId::default, |brush| brush.fill_texture_id) } } impl From<RectShape> for Shape { #[inline(always)] fn from(shape: RectShape) -> Self { Self::Rect(shape) } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/epaint/src/shapes/paint_callback.rs
crates/epaint/src/shapes/paint_callback.rs
use std::{any::Any, sync::Arc}; use crate::*; /// Information passed along with [`PaintCallback`] ([`Shape::Callback`]). pub struct PaintCallbackInfo { /// Viewport in points. /// /// This specifies where on the screen to paint, and the borders of this /// Rect is the [-1, +1] of the Normalized Device Coordinates. /// /// Note than only a portion of this may be visible due to [`Self::clip_rect`]. /// /// This comes from [`PaintCallback::rect`]. pub viewport: Rect, /// Clip rectangle in points. pub clip_rect: Rect, /// Pixels per point. pub pixels_per_point: f32, /// Full size of the screen, in pixels. pub screen_size_px: [u32; 2], } #[test] fn test_viewport_rounding() { for i in 0..=10_000 { // Two adjacent viewports should never overlap: let x = i as f32 / 97.0; let left = Rect::from_min_max(pos2(0.0, 0.0), pos2(100.0, 100.0)).with_max_x(x); let right = Rect::from_min_max(pos2(0.0, 0.0), pos2(100.0, 100.0)).with_min_x(x); for pixels_per_point in [0.618, 1.0, std::f32::consts::PI] { let left = ViewportInPixels::from_points(&left, pixels_per_point, [100, 100]); let right = ViewportInPixels::from_points(&right, pixels_per_point, [100, 100]); assert_eq!(left.left_px + left.width_px, right.left_px); } } } impl PaintCallbackInfo { /// The viewport rectangle. This is what you would use in e.g. `glViewport`. pub fn viewport_in_pixels(&self) -> ViewportInPixels { ViewportInPixels::from_points(&self.viewport, self.pixels_per_point, self.screen_size_px) } /// The "scissor" or "clip" rectangle. This is what you would use in e.g. `glScissor`. pub fn clip_rect_in_pixels(&self) -> ViewportInPixels { ViewportInPixels::from_points(&self.clip_rect, self.pixels_per_point, self.screen_size_px) } } /// If you want to paint some 3D shapes inside an egui region, you can use this. /// /// This is advanced usage, and is backend specific. #[derive(Clone)] pub struct PaintCallback { /// Where to paint. /// /// This will become [`PaintCallbackInfo::viewport`]. pub rect: Rect, /// Paint something custom (e.g. 3D stuff). /// /// The concrete value of `callback` depends on the rendering backend used. For instance, the /// `glow` backend requires that callback be an `egui_glow::CallbackFn` while the `wgpu` /// backend requires a `egui_wgpu::Callback`. /// /// If the type cannot be downcast to the type expected by the current backend the callback /// will not be drawn. /// /// The rendering backend is responsible for first setting the active viewport to /// [`Self::rect`]. /// /// The rendering backend is also responsible for restoring any state, such as the bound shader /// program, vertex array, etc. /// /// Shape has to be clone, therefore this has to be an `Arc` instead of a `Box`. pub callback: Arc<dyn Any + Send + Sync>, } impl std::fmt::Debug for PaintCallback { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("CustomShape") .field("rect", &self.rect) .finish_non_exhaustive() } } impl std::cmp::PartialEq for PaintCallback { fn eq(&self, other: &Self) -> bool { self.rect.eq(&other.rect) && Arc::ptr_eq(&self.callback, &other.callback) } } impl From<PaintCallback> for Shape { #[inline(always)] fn from(shape: PaintCallback) -> Self { Self::Callback(shape) } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/epaint/src/shapes/path_shape.rs
crates/epaint/src/shapes/path_shape.rs
use crate::*; /// A path which can be stroked and/or filled (if closed). #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct PathShape { /// Filled paths should prefer clockwise order. pub points: Vec<Pos2>, /// If true, connect the first and last of the points together. /// This is required if `fill != TRANSPARENT`. pub closed: bool, /// Fill is only supported for convex polygons. pub fill: Color32, /// Color and thickness of the line. pub stroke: PathStroke, // TODO(emilk): Add texture support either by supplying uv for each point, // or by some transform from points to uv (e.g. a callback or a linear transform matrix). } impl PathShape { /// A line through many points. /// /// Use [`Shape::line_segment`] instead if your line only connects two points. #[inline] pub fn line(points: Vec<Pos2>, stroke: impl Into<PathStroke>) -> Self { Self { points, closed: false, fill: Default::default(), stroke: stroke.into(), } } /// A line that closes back to the start point again. #[inline] pub fn closed_line(points: Vec<Pos2>, stroke: impl Into<PathStroke>) -> Self { Self { points, closed: true, fill: Default::default(), stroke: stroke.into(), } } /// A convex polygon with a fill and optional stroke. /// /// The most performant winding order is clockwise. #[inline] pub fn convex_polygon( points: Vec<Pos2>, fill: impl Into<Color32>, stroke: impl Into<PathStroke>, ) -> Self { Self { points, closed: true, fill: fill.into(), stroke: stroke.into(), } } /// The visual bounding rectangle (includes stroke width) #[inline] pub fn visual_bounding_rect(&self) -> Rect { if self.fill == Color32::TRANSPARENT && self.stroke.is_empty() { Rect::NOTHING } else { Rect::from_points(&self.points).expand(self.stroke.width / 2.0) } } } impl From<PathShape> for Shape { #[inline(always)] fn from(shape: PathShape) -> Self { Self::Path(shape) } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/epaint/benches/benchmark.rs
crates/epaint/benches/benchmark.rs
use criterion::{Criterion, criterion_group, criterion_main}; use epaint::{ ClippedShape, Color32, Mesh, PathStroke, Pos2, Rect, Shape, Stroke, TessellationOptions, Tessellator, TextureAtlas, Vec2, pos2, tessellator::Path, }; use std::hint::black_box; #[global_allocator] static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc; // Much faster allocator fn single_dashed_lines(c: &mut Criterion) { c.bench_function("single_dashed_lines", move |b| { b.iter(|| { let mut v = Vec::new(); let line = [pos2(0.0, 0.0), pos2(50.0, 0.0), pos2(100.0, 1.0)]; for _ in 0..100 { v.extend(Shape::dashed_line( &line, Stroke::new(1.5, Color32::RED), 10.0, 2.5, )); } black_box(v); }); }); } fn many_dashed_lines(c: &mut Criterion) { c.bench_function("many_dashed_lines", move |b| { b.iter(|| { let mut v = Vec::new(); let line = [pos2(0.0, 0.0), pos2(50.0, 0.0), pos2(100.0, 1.0)]; for _ in 0..100 { Shape::dashed_line_many(&line, Stroke::new(1.5, Color32::RED), 10.0, 2.5, &mut v); } black_box(v); }); }); } fn tessellate_circles(c: &mut Criterion) { c.bench_function("tessellate_circles_100k", move |b| { let radii: [f32; 10] = [1.0, 2.0, 3.6, 4.0, 5.7, 8.0, 10.0, 13.0, 15.0, 17.0]; let mut clipped_shapes = vec![]; for r in radii { for _ in 0..10_000 { let clip_rect = Rect::from_min_size(Pos2::ZERO, Vec2::splat(1024.0)); let shape = Shape::circle_filled(Pos2::new(10.0, 10.0), r, Color32::WHITE); clipped_shapes.push(ClippedShape { clip_rect, shape }); } } assert_eq!( clipped_shapes.len(), 100_000, "length of clipped shapes should be 100k, but was {}", clipped_shapes.len() ); let pixels_per_point = 2.0; let options = TessellationOptions::default(); let atlas = TextureAtlas::new([4096, 256], Default::default()); let font_tex_size = atlas.size(); let prepared_discs = atlas.prepared_discs(); b.iter(|| { let mut tessellator = Tessellator::new( pixels_per_point, options, font_tex_size, prepared_discs.clone(), ); let clipped_primitives = tessellator.tessellate_shapes(clipped_shapes.clone()); black_box(clipped_primitives); }); }); } fn thick_line_solid(c: &mut Criterion) { c.bench_function("thick_solid_line", move |b| { let line = [pos2(0.0, 0.0), pos2(50.0, 0.0), pos2(100.0, 1.0)]; let mut path = Path::default(); path.add_open_points(&line); b.iter(|| { let mut mesh = Mesh::default(); path.stroke_closed(1.5, &Stroke::new(2.0, Color32::RED).into(), &mut mesh); black_box(mesh); }); }); } fn thick_large_line_solid(c: &mut Criterion) { c.bench_function("thick_large_solid_line", move |b| { let line = (0..1000).map(|i| pos2(i as f32, 10.0)).collect::<Vec<_>>(); let mut path = Path::default(); path.add_open_points(&line); b.iter(|| { let mut mesh = Mesh::default(); path.stroke_closed(1.5, &Stroke::new(2.0, Color32::RED).into(), &mut mesh); black_box(mesh); }); }); } fn thin_line_solid(c: &mut Criterion) { c.bench_function("thin_solid_line", move |b| { let line = [pos2(0.0, 0.0), pos2(50.0, 0.0), pos2(100.0, 1.0)]; let mut path = Path::default(); path.add_open_points(&line); b.iter(|| { let mut mesh = Mesh::default(); path.stroke_closed(1.5, &Stroke::new(0.5, Color32::RED).into(), &mut mesh); black_box(mesh); }); }); } fn thin_large_line_solid(c: &mut Criterion) { c.bench_function("thin_large_solid_line", move |b| { let line = (0..1000).map(|i| pos2(i as f32, 10.0)).collect::<Vec<_>>(); let mut path = Path::default(); path.add_open_points(&line); b.iter(|| { let mut mesh = Mesh::default(); path.stroke_closed(1.5, &Stroke::new(0.5, Color32::RED).into(), &mut mesh); black_box(mesh); }); }); } fn thick_line_uv(c: &mut Criterion) { c.bench_function("thick_uv_line", move |b| { let line = [pos2(0.0, 0.0), pos2(50.0, 0.0), pos2(100.0, 1.0)]; let mut path = Path::default(); path.add_open_points(&line); b.iter(|| { let mut mesh = Mesh::default(); path.stroke_closed( 1.5, &PathStroke::new_uv(2.0, |_, p| { black_box(p * 2.0); Color32::RED }), &mut mesh, ); black_box(mesh); }); }); } fn thick_large_line_uv(c: &mut Criterion) { c.bench_function("thick_large_uv_line", move |b| { let line = (0..1000).map(|i| pos2(i as f32, 10.0)).collect::<Vec<_>>(); let mut path = Path::default(); path.add_open_points(&line); b.iter(|| { let mut mesh = Mesh::default(); path.stroke_closed( 1.5, &PathStroke::new_uv(2.0, |_, p| { black_box(p * 2.0); Color32::RED }), &mut mesh, ); black_box(mesh); }); }); } fn thin_line_uv(c: &mut Criterion) { c.bench_function("thin_uv_line", move |b| { let line = [pos2(0.0, 0.0), pos2(50.0, 0.0), pos2(100.0, 1.0)]; let mut path = Path::default(); path.add_open_points(&line); b.iter(|| { let mut mesh = Mesh::default(); path.stroke_closed( 1.5, &PathStroke::new_uv(2.0, |_, p| { black_box(p * 2.0); Color32::RED }), &mut mesh, ); black_box(mesh); }); }); } fn thin_large_line_uv(c: &mut Criterion) { c.bench_function("thin_large_uv_line", move |b| { let line = (0..1000).map(|i| pos2(i as f32, 10.0)).collect::<Vec<_>>(); let mut path = Path::default(); path.add_open_points(&line); b.iter(|| { let mut mesh = Mesh::default(); path.stroke_closed( 1.5, &PathStroke::new_uv(2.0, |_, p| { black_box(p * 2.0); Color32::RED }), &mut mesh, ); black_box(mesh); }); }); } fn rgba_values() -> [[u8; 4]; 1000] { core::array::from_fn(|i| [5, 7, 11, 13].map(|m| (i * m) as u8)) } fn from_rgba_unmultiplied_0(c: &mut Criterion) { c.bench_function("from_rgba_unmultiplied_0", move |b| { let values = black_box(rgba_values().map(|[r, g, b, _]| [r, g, b, 0])); b.iter(|| { for [r, g, b, a] in values { let color = ecolor::Color32::from_rgba_unmultiplied(r, g, b, a); black_box(color); } }); }); } fn from_rgba_unmultiplied_other(c: &mut Criterion) { c.bench_function("from_rgba_unmultiplied_other", move |b| { let values = black_box(rgba_values().map(|[r, g, b, a]| [r, g, b, a.clamp(1, 254)])); b.iter(|| { for [r, g, b, a] in values { let color = ecolor::Color32::from_rgba_unmultiplied(r, g, b, a); black_box(color); } }); }); } fn from_rgba_unmultiplied_255(c: &mut Criterion) { c.bench_function("from_rgba_unmultiplied_255", move |b| { let values = black_box(rgba_values().map(|[r, g, b, _]| [r, g, b, 255])); b.iter(|| { for [r, g, b, a] in values { let color = ecolor::Color32::from_rgba_unmultiplied(r, g, b, a); black_box(color); } }); }); } criterion_group!( benches, single_dashed_lines, many_dashed_lines, tessellate_circles, thick_line_solid, thick_large_line_solid, thin_line_solid, thin_large_line_solid, thick_line_uv, thick_large_line_uv, thin_line_uv, thin_large_line_uv, from_rgba_unmultiplied_0, from_rgba_unmultiplied_other, from_rgba_unmultiplied_255, ); criterion_main!(benches);
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_extras/src/lib.rs
crates/egui_extras/src/lib.rs
//! This is a crate that adds some features on top top of [`egui`](https://github.com/emilk/egui). //! //! This crate are for experimental features, and features that require big dependencies that does not belong in `egui`. //! //! ## Feature flags #![cfg_attr(feature = "document-features", doc = document_features::document_features!())] //! #![expect(clippy::manual_range_contains)] #[cfg(feature = "chrono")] mod datepicker; pub mod syntax_highlighting; #[doc(hidden)] pub mod image; mod layout; pub mod loaders; mod sizing; mod strip; mod table; #[cfg(feature = "chrono")] pub use crate::datepicker::DatePickerButton; pub(crate) use crate::layout::StripLayout; pub use crate::sizing::Size; pub use crate::strip::*; pub use crate::table::*; pub use loaders::install_image_loaders; // --------------------------------------------------------------------------- /// Panic in debug builds, log otherwise. macro_rules! log_or_panic { ($fmt: literal) => {$crate::log_or_panic!($fmt,)}; ($fmt: literal, $($arg: tt)*) => {{ if cfg!(debug_assertions) { panic!($fmt, $($arg)*); } else { log::error!($fmt, $($arg)*); } }}; } pub(crate) use log_or_panic;
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_extras/src/image.rs
crates/egui_extras/src/image.rs
#[cfg(feature = "svg")] use egui::SizeHint; // ---------------------------------------------------------------------------- /// Load a (non-svg) image. /// /// Requires the "image" feature. You must also opt-in to the image formats you need /// with e.g. `image = { version = "0.25", features = ["jpeg", "png"] }`. /// /// # Errors /// On invalid image or unsupported image format. #[cfg(feature = "image")] pub fn load_image_bytes(image_bytes: &[u8]) -> Result<egui::ColorImage, egui::load::LoadError> { profiling::function_scope!(); let image = image::load_from_memory(image_bytes).map_err(|err| match err { image::ImageError::Unsupported(err) => match err.kind() { image::error::UnsupportedErrorKind::Format(format) => { egui::load::LoadError::FormatNotSupported { detected_format: Some(format.to_string()), } } _ => egui::load::LoadError::Loading(err.to_string()), }, err => egui::load::LoadError::Loading(err.to_string()), })?; let size = [image.width() as _, image.height() as _]; let image_buffer = image.to_rgba8(); let pixels = image_buffer.as_flat_samples(); // TODO(emilk): if this is a PNG, looks for DPI info to calculate the source size, // e.g. for screenshots taken on a high-DPI/retina display. Ok(egui::ColorImage::from_rgba_unmultiplied( size, pixels.as_slice(), )) } /// Load an SVG and rasterize it into an egui image. /// /// Requires the "svg" feature. /// /// # Errors /// On invalid image #[cfg(feature = "svg")] pub fn load_svg_bytes( svg_bytes: &[u8], options: &resvg::usvg::Options<'_>, ) -> Result<egui::ColorImage, String> { load_svg_bytes_with_size(svg_bytes, Default::default(), options) } /// Load an SVG and rasterize it into an egui image with a scaling parameter. /// /// Requires the "svg" feature. /// /// # Errors /// On invalid image #[cfg(feature = "svg")] pub fn load_svg_bytes_with_size( svg_bytes: &[u8], size_hint: SizeHint, options: &resvg::usvg::Options<'_>, ) -> Result<egui::ColorImage, String> { use egui::Vec2; use resvg::{ tiny_skia::Pixmap, usvg::{Transform, Tree}, }; profiling::function_scope!(); let rtree = Tree::from_data(svg_bytes, options).map_err(|err| err.to_string())?; let source_size = Vec2::new(rtree.size().width(), rtree.size().height()); let scaled_size = match size_hint { SizeHint::Size { width, height, maintain_aspect_ratio, } => { if maintain_aspect_ratio { // As large as possible, without exceeding the given size: let mut size = source_size; size *= width as f32 / source_size.x; if size.y > height as f32 { size *= height as f32 / size.y; } size } else { Vec2::new(width as _, height as _) } } SizeHint::Height(h) => source_size * (h as f32 / source_size.y), SizeHint::Width(w) => source_size * (w as f32 / source_size.x), SizeHint::Scale(scale) => scale.into_inner() * source_size, }; let scaled_size = scaled_size.round(); let (w, h) = (scaled_size.x as u32, scaled_size.y as u32); let mut pixmap = Pixmap::new(w, h).ok_or_else(|| format!("Failed to create SVG Pixmap of size {w}x{h}"))?; resvg::render( &rtree, Transform::from_scale(w as f32 / source_size.x, h as f32 / source_size.y), &mut pixmap.as_mut(), ); let image = egui::ColorImage::from_rgba_premultiplied([w as _, h as _], pixmap.data()) .with_source_size(source_size); Ok(image) }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_extras/src/strip.rs
crates/egui_extras/src/strip.rs
use crate::{ Size, layout::{CellDirection, CellSize, StripLayout, StripLayoutFlags}, sizing::Sizing, }; use egui::{Response, Ui}; /// Builder for creating a new [`Strip`]. /// /// This can be used to do dynamic layouts. /// /// In contrast to normal egui behavior, strip cells do *not* grow with its children! /// /// First use [`Self::size`] and [`Self::sizes`] to allocate space for the rows or columns will follow. /// Then build the strip with [`Self::horizontal`]/[`Self::vertical`], and add 'cells' /// to it using [`Strip::cell`]. The number of cells MUST match the number of pre-allocated sizes. /// /// ### Example /// ``` /// # egui::__run_test_ui(|ui| { /// use egui_extras::{StripBuilder, Size}; /// StripBuilder::new(ui) /// .size(Size::remainder().at_least(100.0)) // top cell /// .size(Size::exact(40.0)) // bottom cell /// .vertical(|mut strip| { /// // Add the top 'cell' /// strip.cell(|ui| { /// ui.label("Fixed"); /// }); /// // We add a nested strip in the bottom cell: /// strip.strip(|builder| { /// builder.sizes(Size::remainder(), 2).horizontal(|mut strip| { /// strip.cell(|ui| { /// ui.label("Top Left"); /// }); /// strip.cell(|ui| { /// ui.label("Top Right"); /// }); /// }); /// }); /// }); /// # }); /// ``` pub struct StripBuilder<'a> { ui: &'a mut Ui, sizing: Sizing, clip: bool, cell_layout: egui::Layout, sense: egui::Sense, } impl<'a> StripBuilder<'a> { /// Create new strip builder. pub fn new(ui: &'a mut Ui) -> Self { let cell_layout = *ui.layout(); Self { ui, sizing: Default::default(), clip: false, cell_layout, sense: egui::Sense::hover(), } } /// Should we clip the contents of each cell? Default: `false`. #[inline] pub fn clip(mut self, clip: bool) -> Self { self.clip = clip; self } /// What layout should we use for the individual cells? #[inline] pub fn cell_layout(mut self, cell_layout: egui::Layout) -> Self { self.cell_layout = cell_layout; self } /// What should strip cells sense for? Default: [`egui::Sense::hover()`]. #[inline] pub fn sense(mut self, sense: egui::Sense) -> Self { self.sense = sense; self } /// Allocate space for one column/row. #[inline] pub fn size(mut self, size: Size) -> Self { self.sizing.add(size); self } /// Allocate space for several columns/rows at once. #[inline] pub fn sizes(mut self, size: Size, count: usize) -> Self { for _ in 0..count { self.sizing.add(size); } self } /// Build horizontal strip: Cells are positions from left to right. /// Takes the available horizontal width, so there can't be anything right of the strip or the container will grow slowly! /// /// Returns a [`egui::Response`] for hover events. pub fn horizontal<F>(self, strip: F) -> Response where F: for<'b> FnOnce(Strip<'a, 'b>), { let widths = self.sizing.to_lengths( self.ui.available_rect_before_wrap().width(), self.ui.spacing().item_spacing.x, ); let mut layout = StripLayout::new( self.ui, CellDirection::Horizontal, self.cell_layout, self.sense, ); strip(Strip { layout: &mut layout, direction: CellDirection::Horizontal, clip: self.clip, sizes: widths, size_index: 0, }); layout.allocate_rect() } /// Build vertical strip: Cells are positions from top to bottom. /// Takes the full available vertical height, so there can't be anything below of the strip or the container will grow slowly! /// /// Returns a [`egui::Response`] for hover events. pub fn vertical<F>(self, strip: F) -> Response where F: for<'b> FnOnce(Strip<'a, 'b>), { let heights = self.sizing.to_lengths( self.ui.available_rect_before_wrap().height(), self.ui.spacing().item_spacing.y, ); let mut layout = StripLayout::new( self.ui, CellDirection::Vertical, self.cell_layout, self.sense, ); strip(Strip { layout: &mut layout, direction: CellDirection::Vertical, clip: self.clip, sizes: heights, size_index: 0, }); layout.allocate_rect() } } /// A Strip of cells which go in one direction. Each cell has a fixed size. /// In contrast to normal egui behavior, strip cells do *not* grow with its children! pub struct Strip<'a, 'b> { layout: &'b mut StripLayout<'a>, direction: CellDirection, clip: bool, sizes: Vec<f32>, size_index: usize, } impl Strip<'_, '_> { #[cfg_attr(debug_assertions, track_caller)] fn next_cell_size(&mut self) -> (CellSize, CellSize) { let size = if let Some(size) = self.sizes.get(self.size_index) { self.size_index += 1; *size } else { crate::log_or_panic!( "Added more `Strip` cells than were pre-allocated ({} pre-allocated)", self.sizes.len() ); 8.0 // anything will look wrong, so pick something that is obviously wrong }; match self.direction { CellDirection::Horizontal => (CellSize::Absolute(size), CellSize::Remainder), CellDirection::Vertical => (CellSize::Remainder, CellSize::Absolute(size)), } } /// Add cell contents. #[cfg_attr(debug_assertions, track_caller)] pub fn cell(&mut self, add_contents: impl FnOnce(&mut Ui)) { let (width, height) = self.next_cell_size(); let flags = StripLayoutFlags { clip: self.clip, ..Default::default() }; self.layout.add( flags, width, height, egui::Id::new(self.size_index), add_contents, ); } /// Add an empty cell. #[cfg_attr(debug_assertions, track_caller)] pub fn empty(&mut self) { let (width, height) = self.next_cell_size(); self.layout.empty(width, height); } /// Add a strip as cell. pub fn strip(&mut self, strip_builder: impl FnOnce(StripBuilder<'_>)) { let clip = self.clip; self.cell(|ui| { strip_builder(StripBuilder::new(ui).clip(clip)); }); } } impl Drop for Strip<'_, '_> { fn drop(&mut self) { while self.size_index < self.sizes.len() { self.empty(); } } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_extras/src/table.rs
crates/egui_extras/src/table.rs
//! Table view with (optional) fixed header and scrolling body. //! Cell widths are precalculated with given size hints so we can have tables like this: //! | fixed size | all available space/minimum | 30% of available width | fixed size | //! Takes all available height, so if you want something below the table, put it in a strip. use egui::{ Align, Id, NumExt as _, Rangef, Rect, Response, ScrollArea, Ui, Vec2, Vec2b, scroll_area::{ScrollAreaOutput, ScrollBarVisibility, ScrollSource}, }; use crate::{ StripLayout, layout::{CellDirection, CellSize, StripLayoutFlags}, }; // -----------------------------------------------------------------=---------- #[derive(Clone, Copy, Debug, PartialEq)] enum InitialColumnSize { /// Absolute size in points Absolute(f32), /// Base on content Automatic(f32), /// Take all available space Remainder, } /// Specifies the properties of a column, like its width range. #[derive(Clone, Copy, Debug, PartialEq)] pub struct Column { initial_width: InitialColumnSize, width_range: Rangef, /// Clip contents if too narrow? clip: bool, resizable: Option<bool>, /// If set, we should accurately measure the size of this column this frame /// so that we can correctly auto-size it. This is done as a `sizing_pass`. auto_size_this_frame: bool, } impl Column { /// Automatically sized based on content. /// /// If you have many thousands of rows and are therefore using [`TableBody::rows`] /// or [`TableBody::heterogeneous_rows`], then the automatic size will only be based /// on the currently visible rows. pub fn auto() -> Self { Self::auto_with_initial_suggestion(100.0) } /// Automatically sized. /// /// The given fallback is a loose suggestion, that may be used to wrap /// cell contents, if they contain a wrapping layout. /// In most cases though, the given value is ignored. pub fn auto_with_initial_suggestion(suggested_width: f32) -> Self { Self::new(InitialColumnSize::Automatic(suggested_width)) } /// With this initial width. pub fn initial(width: f32) -> Self { Self::new(InitialColumnSize::Absolute(width)) } /// Always this exact width, never shrink or grow. pub fn exact(width: f32) -> Self { Self::new(InitialColumnSize::Absolute(width)) .range(width..=width) .clip(true) } /// Take all the space remaining after the other columns have /// been sized. /// /// If you have multiple [`Column::remainder`] they all /// share the remaining space equally. pub fn remainder() -> Self { Self::new(InitialColumnSize::Remainder) } fn new(initial_width: InitialColumnSize) -> Self { Self { initial_width, width_range: Rangef::new(0.0, f32::INFINITY), resizable: None, clip: false, auto_size_this_frame: false, } } /// Can this column be resized by dragging the column separator? /// /// If you don't call this, the fallback value of /// [`TableBuilder::resizable`] is used (which by default is `false`). #[inline] pub fn resizable(mut self, resizable: bool) -> Self { self.resizable = Some(resizable); self } /// If `true`: Allow the column to shrink enough to clip the contents. /// If `false`: The column will always be wide enough to contain all its content. /// /// Clipping can make sense if you expect a column to contain a lot of things, /// and you don't want it too take up too much space. /// If you turn on clipping you should also consider calling [`Self::at_least`]. /// /// Default: `false`. #[inline] pub fn clip(mut self, clip: bool) -> Self { self.clip = clip; self } /// Won't shrink below this width (in points). /// /// Default: 0.0 #[inline] pub fn at_least(mut self, minimum: f32) -> Self { self.width_range.min = minimum; self } /// Won't grow above this width (in points). /// /// Default: [`f32::INFINITY`] #[inline] pub fn at_most(mut self, maximum: f32) -> Self { self.width_range.max = maximum; self } /// Allowed range of movement (in points), if in a resizable [`Table`]. #[inline] pub fn range(mut self, range: impl Into<Rangef>) -> Self { self.width_range = range.into(); self } /// If set, the column will be automatically sized based on the content this frame. /// /// Do not set this every frame, just on a specific action. #[inline] pub fn auto_size_this_frame(mut self, auto_size_this_frame: bool) -> Self { self.auto_size_this_frame = auto_size_this_frame; self } fn is_auto(&self) -> bool { match self.initial_width { InitialColumnSize::Automatic(_) => true, InitialColumnSize::Absolute(_) | InitialColumnSize::Remainder => false, } } } fn to_sizing(columns: &[Column]) -> crate::sizing::Sizing { use crate::Size; let mut sizing = crate::sizing::Sizing::default(); for column in columns { let size = match column.initial_width { InitialColumnSize::Absolute(width) => Size::exact(width), InitialColumnSize::Automatic(suggested_width) => Size::initial(suggested_width), InitialColumnSize::Remainder => Size::remainder(), } .with_range(column.width_range); sizing.add(size); } sizing } // -----------------------------------------------------------------=---------- struct TableScrollOptions { vscroll: bool, drag_to_scroll: bool, stick_to_bottom: bool, scroll_to_row: Option<(usize, Option<Align>)>, scroll_offset_y: Option<f32>, min_scrolled_height: f32, max_scroll_height: f32, auto_shrink: Vec2b, scroll_bar_visibility: ScrollBarVisibility, animated: bool, } impl Default for TableScrollOptions { fn default() -> Self { Self { vscroll: true, drag_to_scroll: true, stick_to_bottom: false, scroll_to_row: None, scroll_offset_y: None, min_scrolled_height: 200.0, max_scroll_height: f32::INFINITY, auto_shrink: Vec2b::TRUE, scroll_bar_visibility: ScrollBarVisibility::VisibleWhenNeeded, animated: true, } } } // -----------------------------------------------------------------=---------- /// Builder for a [`Table`] with (optional) fixed header and scrolling body. /// /// You must pre-allocate all columns with [`Self::column`]/[`Self::columns`]. /// /// If you have multiple [`Table`]:s in the same [`Ui`] /// you will need to give them unique id:s by with [`Self::id_salt`]. /// /// ### Example /// ``` /// # egui::__run_test_ui(|ui| { /// use egui_extras::{TableBuilder, Column}; /// TableBuilder::new(ui) /// .column(Column::auto().resizable(true)) /// .column(Column::remainder()) /// .header(20.0, |mut header| { /// header.col(|ui| { /// ui.heading("First column"); /// }); /// header.col(|ui| { /// ui.heading("Second column"); /// }); /// }) /// .body(|mut body| { /// body.row(30.0, |mut row| { /// row.col(|ui| { /// ui.label("Hello"); /// }); /// row.col(|ui| { /// ui.button("world!"); /// }); /// }); /// }); /// # }); /// ``` pub struct TableBuilder<'a> { ui: &'a mut Ui, id_salt: Id, columns: Vec<Column>, striped: Option<bool>, resizable: bool, cell_layout: egui::Layout, scroll_options: TableScrollOptions, sense: egui::Sense, } impl<'a> TableBuilder<'a> { pub fn new(ui: &'a mut Ui) -> Self { let cell_layout = *ui.layout(); Self { ui, id_salt: Id::new("__table_state"), columns: Default::default(), striped: None, resizable: false, cell_layout, scroll_options: Default::default(), sense: egui::Sense::hover(), } } /// Give this table a unique id within the parent [`Ui`]. /// /// This is required if you have multiple tables in the same [`Ui`]. #[inline] #[deprecated = "Renamed id_salt"] pub fn id_source(self, id_salt: impl std::hash::Hash) -> Self { self.id_salt(id_salt) } /// Give this table a unique id within the parent [`Ui`]. /// /// This is required if you have multiple tables in the same [`Ui`]. #[inline] pub fn id_salt(mut self, id_salt: impl std::hash::Hash) -> Self { self.id_salt = Id::new(id_salt); self } /// Enable striped row background for improved readability. /// /// Default is whatever is in [`egui::Visuals::striped`]. #[inline] pub fn striped(mut self, striped: bool) -> Self { self.striped = Some(striped); self } /// What should table cells sense for? (default: [`egui::Sense::hover()`]). #[inline] pub fn sense(mut self, sense: egui::Sense) -> Self { self.sense = sense; self } /// Make the columns resizable by dragging. /// /// You can set this for individual columns with [`Column::resizable`]. /// [`Self::resizable`] is used as a fallback for any column for which you don't call /// [`Column::resizable`]. /// /// If the _last_ column is [`Column::remainder`], then it won't be resizable /// (and instead use up the remainder). /// /// Default is `false`. #[inline] pub fn resizable(mut self, resizable: bool) -> Self { self.resizable = resizable; self } /// Enable vertical scrolling in body (default: `true`) #[inline] pub fn vscroll(mut self, vscroll: bool) -> Self { self.scroll_options.vscroll = vscroll; self } /// Enables scrolling the table's contents using mouse drag (default: `true`). /// /// See [`ScrollArea::drag_to_scroll`] for more. #[inline] pub fn drag_to_scroll(mut self, drag_to_scroll: bool) -> Self { self.scroll_options.drag_to_scroll = drag_to_scroll; self } /// Should the scroll handle stick to the bottom position even as the content size changes /// dynamically? The scroll handle remains stuck until manually changed, and will become stuck /// once again when repositioned to the bottom. Default: `false`. #[inline] pub fn stick_to_bottom(mut self, stick: bool) -> Self { self.scroll_options.stick_to_bottom = stick; self } /// Set a row to scroll to. /// /// `align` specifies if the row should be positioned in the top, center, or bottom of the view /// (using [`Align::TOP`], [`Align::Center`] or [`Align::BOTTOM`]). /// If `align` is `None`, the table will scroll just enough to bring the cursor into view. /// /// See also: [`Self::vertical_scroll_offset`]. #[inline] pub fn scroll_to_row(mut self, row: usize, align: Option<Align>) -> Self { self.scroll_options.scroll_to_row = Some((row, align)); self } /// Set the vertical scroll offset position, in points. /// /// See also: [`Self::scroll_to_row`]. #[inline] pub fn vertical_scroll_offset(mut self, offset: f32) -> Self { self.scroll_options.scroll_offset_y = Some(offset); self } /// The minimum height of a vertical scroll area which requires scroll bars. /// /// The scroll area will only become smaller than this if the content is smaller than this /// (and so we don't require scroll bars). /// /// Default: `200.0`. #[inline] pub fn min_scrolled_height(mut self, min_scrolled_height: f32) -> Self { self.scroll_options.min_scrolled_height = min_scrolled_height; self } /// Don't make the scroll area higher than this (add scroll-bars instead!). /// /// In other words: add scroll-bars when this height is reached. /// Default: `800.0`. #[inline] pub fn max_scroll_height(mut self, max_scroll_height: f32) -> Self { self.scroll_options.max_scroll_height = max_scroll_height; self } /// For each axis (x,y): /// * If true, add blank space outside the table, keeping the table small. /// * If false, add blank space inside the table, expanding the table to fit the containing ui. /// /// Default: `true`. /// /// See [`ScrollArea::auto_shrink`] for more. #[inline] pub fn auto_shrink(mut self, auto_shrink: impl Into<Vec2b>) -> Self { self.scroll_options.auto_shrink = auto_shrink.into(); self } /// Set the visibility of both horizontal and vertical scroll bars. /// /// With `ScrollBarVisibility::VisibleWhenNeeded` (default), the scroll bar will be visible only when needed. #[inline] pub fn scroll_bar_visibility(mut self, scroll_bar_visibility: ScrollBarVisibility) -> Self { self.scroll_options.scroll_bar_visibility = scroll_bar_visibility; self } /// Should the scroll area animate `scroll_to_*` functions? /// /// Default: `true`. #[inline] pub fn animate_scrolling(mut self, animated: bool) -> Self { self.scroll_options.animated = animated; self } /// What layout should we use for the individual cells? #[inline] pub fn cell_layout(mut self, cell_layout: egui::Layout) -> Self { self.cell_layout = cell_layout; self } /// Allocate space for one column. #[inline] pub fn column(mut self, column: Column) -> Self { self.columns.push(column); self } /// Allocate space for several columns at once. #[inline] pub fn columns(mut self, column: Column, count: usize) -> Self { for _ in 0..count { self.columns.push(column); } self } fn available_width(&self) -> f32 { self.ui.available_rect_before_wrap().width() - (self.scroll_options.vscroll as i32 as f32) * self.ui.spacing().scroll.allocated_width() } /// Reset all column widths. pub fn reset(&self) { let state_id = self.ui.id().with(self.id_salt); TableState::reset(self.ui, state_id); } /// Create a header row which always stays visible and at the top pub fn header(self, height: f32, add_header_row: impl FnOnce(TableRow<'_, '_>)) -> Table<'a> { let available_width = self.available_width(); let Self { ui, id_salt, mut columns, striped, resizable, cell_layout, scroll_options, sense, } = self; for (i, column) in columns.iter_mut().enumerate() { let column_resize_id = ui.id().with("resize_column").with(i); if let Some(response) = ui.ctx().read_response(column_resize_id) && response.double_clicked() { column.auto_size_this_frame = true; } } let striped = striped.unwrap_or_else(|| ui.visuals().striped); let state_id = ui.id().with(id_salt); let (is_sizing_pass, state) = TableState::load(ui, state_id, resizable, &columns, available_width); let mut max_used_widths = vec![0.0; columns.len()]; let table_top = ui.cursor().top(); let mut ui_builder = egui::UiBuilder::new(); if is_sizing_pass { ui_builder = ui_builder.sizing_pass(); } ui.scope_builder(ui_builder, |ui| { let mut layout = StripLayout::new(ui, CellDirection::Horizontal, cell_layout, sense); let mut response: Option<Response> = None; add_header_row(TableRow { layout: &mut layout, columns: &columns, widths: &state.column_widths, max_used_widths: &mut max_used_widths, row_index: 0, col_index: 0, height, striped: false, hovered: false, selected: false, overline: false, response: &mut response, }); layout.allocate_rect(); }); Table { ui, table_top, state_id, columns, available_width, state, max_used_widths, is_sizing_pass, resizable, striped, cell_layout, scroll_options, sense, } } /// Create table body without a header row pub fn body<F>(self, add_body_contents: F) -> ScrollAreaOutput<()> where F: for<'b> FnOnce(TableBody<'b>), { let available_width = self.available_width(); let Self { ui, id_salt, columns, striped, resizable, cell_layout, scroll_options, sense, } = self; let striped = striped.unwrap_or_else(|| ui.visuals().striped); let state_id = ui.id().with(id_salt); let (is_sizing_pass, state) = TableState::load(ui, state_id, resizable, &columns, available_width); let max_used_widths = vec![0.0; columns.len()]; let table_top = ui.cursor().top(); Table { ui, table_top, state_id, columns, available_width, state, max_used_widths, is_sizing_pass, resizable, striped, cell_layout, scroll_options, sense, } .body(add_body_contents) } } // ---------------------------------------------------------------------------- #[derive(Clone, Debug)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] struct TableState { column_widths: Vec<f32>, /// If known from previous frame #[cfg_attr(feature = "serde", serde(skip))] max_used_widths: Vec<f32>, } impl TableState { /// Return true if we should do a sizing pass. fn load( ui: &Ui, state_id: egui::Id, resizable: bool, columns: &[Column], available_width: f32, ) -> (bool, Self) { let rect = Rect::from_min_size(ui.available_rect_before_wrap().min, Vec2::ZERO); ui.ctx().check_for_id_clash(state_id, rect, "Table"); #[cfg(feature = "serde")] let state = ui.data_mut(|d| d.get_persisted::<Self>(state_id)); #[cfg(not(feature = "serde"))] let state = ui.data_mut(|d| d.get_temp::<Self>(state_id)); // Make sure that the stored widths aren't out-dated: let state = state.filter(|state| state.column_widths.len() == columns.len()); let is_sizing_pass = ui.is_sizing_pass() || state.is_none() && columns.iter().any(|c| c.is_auto()); let mut state = state.unwrap_or_else(|| { let initial_widths = to_sizing(columns).to_lengths(available_width, ui.spacing().item_spacing.x); Self { column_widths: initial_widths, max_used_widths: Default::default(), } }); if !is_sizing_pass && state.max_used_widths.len() == columns.len() { // Make sure any non-resizable `remainder` columns are updated // to take up the remainder of the current available width. // Also handles changing item spacing. let mut sizing = crate::sizing::Sizing::default(); for ((prev_width, max_used), column) in state .column_widths .iter() .zip(&state.max_used_widths) .zip(columns) { use crate::Size; let column_resizable = column.resizable.unwrap_or(resizable); let size = if column_resizable { // Resiable columns keep their width: Size::exact(*prev_width) } else { match column.initial_width { InitialColumnSize::Absolute(width) => Size::exact(width), InitialColumnSize::Automatic(_) => Size::exact(*prev_width), InitialColumnSize::Remainder => Size::remainder(), } .at_least(column.width_range.min.max(*max_used)) .at_most(column.width_range.max) }; sizing.add(size); } state.column_widths = sizing.to_lengths(available_width, ui.spacing().item_spacing.x); } (is_sizing_pass, state) } fn store(self, ui: &egui::Ui, state_id: egui::Id) { #![expect(clippy::needless_return)] #[cfg(feature = "serde")] { return ui.data_mut(|d| d.insert_persisted(state_id, self)); } #[cfg(not(feature = "serde"))] { return ui.data_mut(|d| d.insert_temp(state_id, self)); } } fn reset(ui: &egui::Ui, state_id: egui::Id) { ui.data_mut(|d| d.remove::<Self>(state_id)); } } // ---------------------------------------------------------------------------- /// Table struct which can construct a [`TableBody`]. /// /// Is created by [`TableBuilder`] by either calling [`TableBuilder::body`] or after creating a header row with [`TableBuilder::header`]. pub struct Table<'a> { ui: &'a mut Ui, table_top: f32, state_id: egui::Id, columns: Vec<Column>, available_width: f32, state: TableState, /// Accumulated maximum used widths for each column. max_used_widths: Vec<f32>, /// During the sizing pass we calculate the width of columns with [`Column::auto`]. is_sizing_pass: bool, resizable: bool, striped: bool, cell_layout: egui::Layout, scroll_options: TableScrollOptions, sense: egui::Sense, } impl Table<'_> { /// Access the contained [`egui::Ui`]. /// /// You can use this to e.g. modify the [`egui::Style`] with [`egui::Ui::style_mut`]. pub fn ui_mut(&mut self) -> &mut egui::Ui { self.ui } /// Create table body after adding a header row pub fn body<F>(self, add_body_contents: F) -> ScrollAreaOutput<()> where F: for<'b> FnOnce(TableBody<'b>), { let Table { ui, table_top, state_id, columns, resizable, mut available_width, mut state, mut max_used_widths, is_sizing_pass, striped, cell_layout, scroll_options, sense, } = self; let TableScrollOptions { vscroll, drag_to_scroll, stick_to_bottom, scroll_to_row, scroll_offset_y, min_scrolled_height, max_scroll_height, auto_shrink, scroll_bar_visibility, animated, } = scroll_options; let cursor_position = ui.cursor().min; let mut scroll_area = ScrollArea::new([false, vscroll]) .id_salt(state_id.with("__scroll_area")) .scroll_source(ScrollSource { drag: drag_to_scroll, ..Default::default() }) .stick_to_bottom(stick_to_bottom) .min_scrolled_height(min_scrolled_height) .max_height(max_scroll_height) .auto_shrink(auto_shrink) .scroll_bar_visibility(scroll_bar_visibility) .animated(animated); if let Some(scroll_offset_y) = scroll_offset_y { scroll_area = scroll_area.vertical_scroll_offset(scroll_offset_y); } let columns_ref = &columns; let widths_ref = &state.column_widths; let max_used_widths_ref = &mut max_used_widths; let scroll_area_out = scroll_area.show(ui, move |ui| { let mut scroll_to_y_range = None; let clip_rect = ui.clip_rect(); let mut ui_builder = egui::UiBuilder::new(); if is_sizing_pass { ui_builder = ui_builder.sizing_pass(); } ui.scope_builder(ui_builder, |ui| { let hovered_row_index_id = self.state_id.with("__table_hovered_row"); let hovered_row_index = ui.data_mut(|data| data.remove_temp::<usize>(hovered_row_index_id)); let layout = StripLayout::new(ui, CellDirection::Horizontal, cell_layout, sense); add_body_contents(TableBody { layout, columns: columns_ref, widths: widths_ref, max_used_widths: max_used_widths_ref, striped, row_index: 0, y_range: clip_rect.y_range(), scroll_to_row: scroll_to_row.map(|(r, _)| r), scroll_to_y_range: &mut scroll_to_y_range, hovered_row_index, hovered_row_index_id, }); if scroll_to_row.is_some() && scroll_to_y_range.is_none() { // TableBody::row didn't find the correct row, so scroll to the bottom: scroll_to_y_range = Some(Rangef::new(f32::INFINITY, f32::INFINITY)); } }); if let Some(y_range) = scroll_to_y_range { let x = 0.0; // ignored, we only have vertical scrolling let rect = egui::Rect::from_x_y_ranges(x..=x, y_range); let align = scroll_to_row.and_then(|(_, a)| a); ui.scroll_to_rect(rect, align); } }); let bottom = ui.min_rect().bottom(); let spacing_x = ui.spacing().item_spacing.x; let mut x = cursor_position.x - spacing_x * 0.5; for (i, column_width) in state.column_widths.iter_mut().enumerate() { let column = &columns[i]; let column_is_resizable = column.resizable.unwrap_or(resizable); let width_range = column.width_range; let is_last_column = i + 1 == columns.len(); if is_last_column && column.initial_width == InitialColumnSize::Remainder && !ui.is_sizing_pass() { // If the last column is 'remainder', then let it fill the remainder! let eps = 0.1; // just to avoid some rounding errors. *column_width = available_width - eps; if !column.clip { *column_width = column_width.at_least(max_used_widths[i]); } *column_width = width_range.clamp(*column_width); break; } if ui.is_sizing_pass() { if column.clip { // If we clip, we don't need to be as wide as the max used width *column_width = column_width.min(max_used_widths[i]); } else { *column_width = max_used_widths[i]; } } else if !column.clip { // Unless we clip we don't want to shrink below the // size that was actually used: *column_width = column_width.at_least(max_used_widths[i]); } *column_width = width_range.clamp(*column_width); x += *column_width + spacing_x; if column.is_auto() && (is_sizing_pass || !column_is_resizable) { *column_width = width_range.clamp(max_used_widths[i]); } else if column_is_resizable { let column_resize_id = state_id.with("resize_column").with(i); let mut p0 = egui::pos2(x, table_top); let mut p1 = egui::pos2(x, bottom); let line_rect = egui::Rect::from_min_max(p0, p1) .expand(ui.style().interaction.resize_grab_radius_side); let resize_response = ui.interact(line_rect, column_resize_id, egui::Sense::click_and_drag()); if column.auto_size_this_frame { // Auto-size: resize to what is needed. *column_width = width_range.clamp(max_used_widths[i]); } else if resize_response.dragged() && let Some(pointer) = ui.ctx().pointer_latest_pos() { let mut new_width = *column_width + pointer.x - x; if !column.clip { // Unless we clip we don't want to shrink below the // size that was actually used. // However, we still want to allow content that shrinks when you try // to make the column less wide, so we allow some small shrinkage each frame: // big enough to allow shrinking over time, small enough not to look ugly when // shrinking fails. This is a bit of a HACK around immediate mode. let max_shrinkage_per_frame = 8.0; new_width = new_width.at_least(max_used_widths[i] - max_shrinkage_per_frame); } new_width = width_range.clamp(new_width); let x = x - *column_width + new_width; (p0.x, p1.x) = (x, x); *column_width = new_width; } let dragging_something_else = ui.input(|i| i.pointer.any_down() || i.pointer.any_pressed()); let resize_hover = resize_response.hovered() && !dragging_something_else; if resize_hover || resize_response.dragged() { ui.set_cursor_icon(egui::CursorIcon::ResizeColumn); } let stroke = if resize_response.dragged() { ui.style().visuals.widgets.active.bg_stroke } else if resize_hover { ui.style().visuals.widgets.hovered.bg_stroke } else { // ui.visuals().widgets.inactive.bg_stroke ui.visuals().widgets.noninteractive.bg_stroke }; ui.painter().line_segment([p0, p1], stroke); } available_width -= *column_width + spacing_x; } state.max_used_widths = max_used_widths; state.store(ui, state_id); scroll_area_out } } /// The body of a table. /// /// Is created by calling `body` on a [`Table`] (after adding a header row) or [`TableBuilder`] (without a header row). pub struct TableBody<'a> { layout: StripLayout<'a>, columns: &'a [Column], /// Current column widths. widths: &'a [f32], /// Accumulated maximum used widths for each column. max_used_widths: &'a mut [f32], striped: bool, row_index: usize, y_range: Rangef, /// Look for this row to scroll to. scroll_to_row: Option<usize>, /// If we find the correct row to scroll to, /// this is set to the y-range of the row. scroll_to_y_range: &'a mut Option<Rangef>, hovered_row_index: Option<usize>, /// Used to store the hovered row index between frames. hovered_row_index_id: egui::Id, } impl<'a> TableBody<'a> { /// Access the contained [`egui::Ui`]. /// /// You can use this to e.g. modify the [`egui::Style`] with [`egui::Ui::style_mut`]. pub fn ui_mut(&mut self) -> &mut egui::Ui { self.layout.ui } /// Where in screen-space is the table body? pub fn max_rect(&self) -> Rect { self.layout .rect .translate(egui::vec2(0.0, self.scroll_offset_y())) } fn scroll_offset_y(&self) -> f32 { self.y_range.min - self.layout.rect.top() } /// Return a vector containing all column widths for this table body. /// /// This is primarily meant for use with [`TableBody::heterogeneous_rows`] in cases where row /// heights are expected to according to the width of one or more cells -- for example, if text /// is wrapped rather than clipped within the cell. pub fn widths(&self) -> &[f32] { self.widths } /// Add a single row with the given height. ///
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
true
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_extras/src/layout.rs
crates/egui_extras/src/layout.rs
use egui::{Id, Pos2, Rect, Response, Sense, Ui, UiBuilder, emath::GuiRounding as _}; #[derive(Clone, Copy)] pub(crate) enum CellSize { /// Absolute size in points Absolute(f32), /// Take all available space Remainder, } /// Cells are positioned in two dimensions, cells go in one direction and form lines. /// /// In a strip there's only one line which goes in the direction of the strip: /// /// In a horizontal strip, a [`StripLayout`] with horizontal [`CellDirection`] is used. /// Its cells go from left to right inside this [`StripLayout`]. /// /// In a table there's a [`StripLayout`] for each table row with a horizontal [`CellDirection`]. /// Its cells go from left to right. And the lines go from top to bottom. pub(crate) enum CellDirection { /// Cells go from left to right. Horizontal, /// Cells go from top to bottom. Vertical, } /// Flags used by [`StripLayout::add`]. #[derive(Clone, Copy, Default)] pub(crate) struct StripLayoutFlags { pub(crate) clip: bool, pub(crate) striped: bool, pub(crate) hovered: bool, pub(crate) selected: bool, pub(crate) overline: bool, /// Used when we want to accurately measure the size of this cell. pub(crate) sizing_pass: bool, } /// Positions cells in [`CellDirection`] and starts a new line on [`StripLayout::end_line`] pub struct StripLayout<'l> { pub(crate) ui: &'l mut Ui, direction: CellDirection, pub(crate) rect: Rect, pub(crate) cursor: Pos2, /// Keeps track of the max used position, /// so we know how much space we used. max: Pos2, cell_layout: egui::Layout, sense: Sense, } impl<'l> StripLayout<'l> { pub(crate) fn new( ui: &'l mut Ui, direction: CellDirection, cell_layout: egui::Layout, sense: Sense, ) -> Self { let rect = ui.available_rect_before_wrap(); let pos = rect.left_top(); Self { ui, direction, rect, cursor: pos, max: pos, cell_layout, sense, } } fn cell_rect(&self, width: &CellSize, height: &CellSize) -> Rect { Rect { min: self.cursor, max: Pos2 { x: match width { CellSize::Absolute(width) => self.cursor.x + width, CellSize::Remainder => self.rect.right(), }, y: match height { CellSize::Absolute(height) => self.cursor.y + height, CellSize::Remainder => self.rect.bottom(), }, }, } } fn set_pos(&mut self, rect: Rect) { self.max.x = self.max.x.max(rect.right()); self.max.y = self.max.y.max(rect.bottom()); match self.direction { CellDirection::Horizontal => { self.cursor.x = rect.right() + self.ui.spacing().item_spacing.x; } CellDirection::Vertical => { self.cursor.y = rect.bottom() + self.ui.spacing().item_spacing.y; } } } pub(crate) fn empty(&mut self, width: CellSize, height: CellSize) { self.set_pos(self.cell_rect(&width, &height)); } /// This is the innermost part of [`crate::Table`] and [`crate::Strip`]. /// /// Return the used space (`min_rect`) plus the [`Response`] of the whole cell. pub(crate) fn add( &mut self, flags: StripLayoutFlags, width: CellSize, height: CellSize, child_ui_id_salt: Id, add_cell_contents: impl FnOnce(&mut Ui), ) -> (Rect, Response) { let max_rect = self.cell_rect(&width, &height); // Make sure we don't have a gap in the stripe/frame/selection background: let item_spacing = self.ui.spacing().item_spacing; let gapless_rect = max_rect.expand2(0.5 * item_spacing).round_ui(); if flags.striped { self.ui.painter().rect_filled( gapless_rect, egui::CornerRadius::ZERO, self.ui.visuals().faint_bg_color, ); } if flags.selected { self.ui.painter().rect_filled( gapless_rect, egui::CornerRadius::ZERO, self.ui.visuals().selection.bg_fill, ); } if flags.hovered && !flags.selected && self.sense.interactive() { self.ui.painter().rect_filled( gapless_rect, egui::CornerRadius::ZERO, self.ui.visuals().widgets.hovered.bg_fill, ); } let mut child_ui = self.cell(flags, max_rect, child_ui_id_salt, add_cell_contents); let used_rect = child_ui.min_rect(); // Make sure we catch clicks etc on the _whole_ cell: child_ui.set_min_size(max_rect.size()); let allocation_rect = if self.ui.is_sizing_pass() { used_rect } else if flags.clip { max_rect } else { max_rect | used_rect }; self.set_pos(allocation_rect); self.ui.advance_cursor_after_rect(allocation_rect); let response = child_ui.response(); (used_rect, response) } /// only needed for layouts with multiple lines, like [`Table`](crate::Table). pub fn end_line(&mut self) { match self.direction { CellDirection::Horizontal => { self.cursor.y = self.max.y + self.ui.spacing().item_spacing.y; self.cursor.x = self.rect.left(); } CellDirection::Vertical => { self.cursor.x = self.max.x + self.ui.spacing().item_spacing.x; self.cursor.y = self.rect.top(); } } } /// Skip a lot of space. pub(crate) fn skip_space(&mut self, delta: egui::Vec2) { let before = self.cursor; self.cursor += delta; let rect = Rect::from_two_pos(before, self.cursor); self.ui.allocate_rect(rect, Sense::hover()); } /// Return the Ui to which the contents where added fn cell( &mut self, flags: StripLayoutFlags, max_rect: Rect, child_ui_id_salt: egui::Id, add_cell_contents: impl FnOnce(&mut Ui), ) -> Ui { let mut ui_builder = UiBuilder::new() .id_salt(child_ui_id_salt) .ui_stack_info(egui::UiStackInfo::new(egui::UiKind::TableCell)) .max_rect(max_rect) .layout(self.cell_layout) .sense(self.sense); if flags.sizing_pass { ui_builder = ui_builder.sizing_pass(); } let mut child_ui = self.ui.new_child(ui_builder); if flags.clip { let margin = egui::Vec2::splat(self.ui.visuals().clip_rect_margin); let margin = margin.min(0.5 * self.ui.spacing().item_spacing); let clip_rect = max_rect.expand2(margin); child_ui.shrink_clip_rect(clip_rect); if !child_ui.is_sizing_pass() { // Better to truncate (if we can), rather than hard clipping: child_ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate); } } if flags.selected { let stroke_color = child_ui.style().visuals.selection.stroke.color; child_ui.style_mut().visuals.override_text_color = Some(stroke_color); } if flags.overline { child_ui.painter().hline( max_rect.x_range(), max_rect.top(), child_ui.visuals().widgets.noninteractive.bg_stroke, ); } add_cell_contents(&mut child_ui); child_ui } /// Allocate the rect in [`Self::ui`] so that the scrollview knows about our size pub fn allocate_rect(&mut self) -> Response { let mut rect = self.rect; rect.set_right(self.max.x); rect.set_bottom(self.max.y); self.ui.allocate_rect(rect, Sense::hover()) } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_extras/src/sizing.rs
crates/egui_extras/src/sizing.rs
use egui::Rangef; /// Size hint for table column/strip cell. #[derive(Clone, Debug, Copy)] pub enum Size { /// Absolute size in points, with a given range of allowed sizes to resize within. Absolute { initial: f32, range: Rangef }, /// Relative size relative to all available space. Relative { fraction: f32, range: Rangef }, /// Multiple remainders each get the same space. Remainder { range: Rangef }, } impl Size { /// Exactly this big, with no room for resize. pub fn exact(points: f32) -> Self { Self::Absolute { initial: points, range: Rangef::new(points, points), } } /// Initially this big, but can resize. pub fn initial(points: f32) -> Self { Self::Absolute { initial: points, range: Rangef::new(0.0, f32::INFINITY), } } /// Relative size relative to all available space. Values must be in range `0.0..=1.0`. pub fn relative(fraction: f32) -> Self { debug_assert!( 0.0 <= fraction && fraction <= 1.0, "fraction should be in the range [0, 1], but was {fraction}" ); Self::Relative { fraction, range: Rangef::new(0.0, f32::INFINITY), } } /// Multiple remainders each get the same space. pub fn remainder() -> Self { Self::Remainder { range: Rangef::new(0.0, f32::INFINITY), } } /// Won't shrink below this size (in points). #[inline] pub fn at_least(mut self, minimum: f32) -> Self { self.range_mut().min = minimum; self } /// Won't grow above this size (in points). #[inline] pub fn at_most(mut self, maximum: f32) -> Self { self.range_mut().max = maximum; self } #[inline] pub fn with_range(mut self, range: Rangef) -> Self { *self.range_mut() = range; self } /// Allowed range of movement (in points), if in a resizable [`Table`](crate::table::Table). pub fn range(self) -> Rangef { match self { Self::Absolute { range, .. } | Self::Relative { range, .. } | Self::Remainder { range, .. } => range, } } pub fn range_mut(&mut self) -> &mut Rangef { match self { Self::Absolute { range, .. } | Self::Relative { range, .. } | Self::Remainder { range, .. } => range, } } #[inline] pub fn is_absolute(&self) -> bool { matches!(self, Self::Absolute { .. }) } #[inline] pub fn is_relative(&self) -> bool { matches!(self, Self::Relative { .. }) } #[inline] pub fn is_remainder(&self) -> bool { matches!(self, Self::Remainder { .. }) } } #[derive(Clone, Default)] pub struct Sizing { pub(crate) sizes: Vec<Size>, } impl Sizing { pub fn add(&mut self, size: Size) { self.sizes.push(size); } pub fn to_lengths(&self, length: f32, spacing: f32) -> Vec<f32> { if self.sizes.is_empty() { return vec![]; } let mut num_remainders = 0; let sum_non_remainder = self .sizes .iter() .map(|&size| match size { Size::Absolute { initial, .. } => initial, Size::Relative { fraction, range } => { assert!( 0.0 <= fraction && fraction <= 1.0, "fraction should be in the range [0, 1], but was {fraction}" ); range.clamp(length * fraction) } Size::Remainder { .. } => { num_remainders += 1; 0.0 } }) .sum::<f32>() + spacing * (self.sizes.len() - 1) as f32; let avg_remainder_length = if num_remainders == 0 { 0.0 } else { let mut remainder_length = length - sum_non_remainder; let avg_remainder_length = 0.0f32.max(remainder_length / num_remainders as f32).floor(); for &size in &self.sizes { if let Size::Remainder { range } = size && avg_remainder_length < range.min { remainder_length -= range.min; num_remainders -= 1; } } if num_remainders > 0 { 0.0f32.max(remainder_length / num_remainders as f32) } else { 0.0 } }; self.sizes .iter() .map(|&size| match size { Size::Absolute { initial, .. } => initial, Size::Relative { fraction, range } => range.clamp(length * fraction), Size::Remainder { range } => range.clamp(avg_remainder_length), }) .collect() } } impl From<Vec<Size>> for Sizing { fn from(sizes: Vec<Size>) -> Self { Self { sizes } } } #[test] fn test_sizing() { let sizing: Sizing = vec![].into(); assert_eq!(sizing.to_lengths(50.0, 0.0), Vec::<f32>::new()); let sizing: Sizing = vec![Size::remainder().at_least(20.0), Size::remainder()].into(); assert_eq!(sizing.to_lengths(50.0, 0.0), vec![25.0, 25.0]); assert_eq!(sizing.to_lengths(30.0, 0.0), vec![20.0, 10.0]); assert_eq!(sizing.to_lengths(20.0, 0.0), vec![20.0, 0.0]); assert_eq!(sizing.to_lengths(10.0, 0.0), vec![20.0, 0.0]); assert_eq!(sizing.to_lengths(20.0, 10.0), vec![20.0, 0.0]); assert_eq!(sizing.to_lengths(30.0, 10.0), vec![20.0, 0.0]); assert_eq!(sizing.to_lengths(40.0, 10.0), vec![20.0, 10.0]); assert_eq!(sizing.to_lengths(110.0, 10.0), vec![50.0, 50.0]); let sizing: Sizing = vec![Size::relative(0.5).at_least(10.0), Size::exact(10.0)].into(); assert_eq!(sizing.to_lengths(50.0, 0.0), vec![25.0, 10.0]); assert_eq!(sizing.to_lengths(30.0, 0.0), vec![15.0, 10.0]); assert_eq!(sizing.to_lengths(20.0, 0.0), vec![10.0, 10.0]); assert_eq!(sizing.to_lengths(10.0, 0.0), vec![10.0, 10.0]); }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_extras/src/loaders.rs
crates/egui_extras/src/loaders.rs
// TODO(jprochazk): automatic cache eviction /// Installs a set of image loaders. /// /// Calling this enables the use of [`egui::Image`] and [`egui::Ui::image`]. /// /// ⚠ This will do nothing and you won't see any images unless you also enable some feature flags on `egui_extras`: /// /// - `file` feature: `file://` loader on non-Wasm targets /// - `http` feature: `http(s)://` loader /// - `image` feature: Loader of png, jpeg etc using the [`image`] crate /// - `svg` feature: `.svg` loader /// /// Calling this multiple times on the same [`egui::Context`] is safe. /// It will never install duplicate loaders. /// /// - If you just want to be able to load `file://` and `http://` URIs, enable the `all_loaders` feature. /// - The supported set of image formats is configured by adding the [`image`](https://crates.io/crates/image) /// crate as your direct dependency, and enabling features on it: /// /// ```toml,ignore /// egui_extras = { version = "*", features = ["all_loaders"] } /// image = { version = "0.25", features = ["jpeg", "png"] } # Add the types you want support for /// ``` /// /// ⚠ You have to configure both the supported loaders in `egui_extras` _and_ the supported image formats /// in `image` to get any output! /// /// ## Loader-specific information /// /// ⚠ The exact way bytes, images, and textures are loaded is subject to change, /// but the supported protocols and file extensions are not. /// /// The `file` loader is a [`BytesLoader`][`egui::load::BytesLoader`]. /// It will attempt to load `file://` URIs, and infer the content type from the extension. /// The path will be passed to [`std::fs::read`] after trimming the `file://` prefix, /// and is resolved the same way as with `std::fs::read(path)`: /// - Relative paths are relative to the current working directory /// - Absolute paths are left as is. /// /// The `http` loader is a [`BytesLoader`][`egui::load::BytesLoader`]. /// It will attempt to load `http://` and `https://` URIs, and infer the content type from the `Content-Type` header. /// /// The `image` loader is an [`ImageLoader`][`egui::load::ImageLoader`]. /// It will attempt to load any URI with any extension other than `svg`. /// It will also try to load any URI without an extension. /// The content type specified by [`BytesPoll::Ready::mime`][`egui::load::BytesPoll::Ready::mime`] always takes precedence. /// This means that even if the URI has a `png` extension, and the `png` image format is enabled, if the content type is /// not one of the supported and enabled image formats, the loader will return [`LoadError::NotSupported`][`egui::load::LoadError::NotSupported`], /// allowing a different loader to attempt to load the image. /// /// The `svg` loader is an [`ImageLoader`][`egui::load::ImageLoader`]. /// It will attempt to load any URI with an `svg` extension. It will _not_ attempt to load a URI without an extension. /// The content type specified by [`BytesPoll::Ready::mime`][`egui::load::BytesPoll::Ready::mime`] always takes precedence, /// and must include `svg` for it to be considered supported. For example, `image/svg+xml` would be loaded by the `svg` loader. /// /// See [`egui::load`] for more information about how loaders work. pub fn install_image_loaders(ctx: &egui::Context) { #[cfg(all(not(target_arch = "wasm32"), feature = "file"))] if !ctx.is_loader_installed(self::file_loader::FileLoader::ID) { ctx.add_bytes_loader(std::sync::Arc::new(self::file_loader::FileLoader::default())); log::trace!("installed FileLoader"); } #[cfg(feature = "http")] if !ctx.is_loader_installed(self::http_loader::EhttpLoader::ID) { ctx.add_bytes_loader(std::sync::Arc::new( self::http_loader::EhttpLoader::default(), )); log::trace!("installed EhttpLoader"); } #[cfg(feature = "image")] if !ctx.is_loader_installed(self::image_loader::ImageCrateLoader::ID) { ctx.add_image_loader(std::sync::Arc::new( self::image_loader::ImageCrateLoader::default(), )); log::trace!("installed ImageCrateLoader"); } #[cfg(feature = "gif")] if !ctx.is_loader_installed(self::gif_loader::GifLoader::ID) { ctx.add_image_loader(std::sync::Arc::new(self::gif_loader::GifLoader::default())); log::trace!("installed GifLoader"); } #[cfg(feature = "webp")] if !ctx.is_loader_installed(self::webp_loader::WebPLoader::ID) { ctx.add_image_loader(std::sync::Arc::new(self::webp_loader::WebPLoader::default())); log::trace!("installed WebPLoader"); } #[cfg(feature = "svg")] if !ctx.is_loader_installed(self::svg_loader::SvgLoader::ID) { ctx.add_image_loader(std::sync::Arc::new(self::svg_loader::SvgLoader::default())); log::trace!("installed SvgLoader"); } #[cfg(all( any(target_arch = "wasm32", not(feature = "file")), not(feature = "http"), not(feature = "image"), not(feature = "svg") ))] log::warn!("`install_image_loaders` was called, but no loaders are enabled"); let _ = ctx; } #[cfg(not(target_arch = "wasm32"))] pub mod file_loader; #[cfg(feature = "http")] pub mod http_loader; #[cfg(feature = "gif")] pub mod gif_loader; #[cfg(feature = "image")] pub mod image_loader; #[cfg(feature = "svg")] pub mod svg_loader; #[cfg(feature = "webp")] pub mod webp_loader;
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_extras/src/syntax_highlighting.rs
crates/egui_extras/src/syntax_highlighting.rs
//! Syntax highlighting for code. //! //! Turn on the `syntect` feature for great syntax highlighting of any language. //! Otherwise, a very simple fallback will be used, that works okish for C, C++, Rust, and Python. use egui::TextStyle; use egui::text::LayoutJob; /// View some code with syntax highlighting and selection. pub fn code_view_ui( ui: &mut egui::Ui, theme: &CodeTheme, code: &str, language: &str, ) -> egui::Response { let layout_job = highlight(ui.ctx(), ui.style(), theme, code, language); ui.add(egui::Label::new(layout_job).selectable(true)) } /// Add syntax highlighting to a code string. /// /// The results are memoized, so you can call this every frame without performance penalty. pub fn highlight( ctx: &egui::Context, style: &egui::Style, theme: &CodeTheme, code: &str, language: &str, ) -> LayoutJob { highlight_inner(ctx, style, theme, code, language, None) } /// Add syntax highlighting to a code string, with custom `syntect` settings /// /// The results are memoized, so you can call this every frame without performance penalty. /// /// The `syntect` settings are memoized by *address*, so a stable reference should /// be used to avoid unnecessary recomputation. #[cfg(feature = "syntect")] pub fn highlight_with( ctx: &egui::Context, style: &egui::Style, theme: &CodeTheme, code: &str, language: &str, settings: &SyntectSettings, ) -> LayoutJob { highlight_inner( ctx, style, theme, code, language, Some(HighlightSettings(settings)), ) } fn highlight_inner( ctx: &egui::Context, style: &egui::Style, theme: &CodeTheme, code: &str, language: &str, settings: Option<HighlightSettings<'_>>, ) -> LayoutJob { // We take in both context and style so that in situations where ui is not available such as when // performing it at a separate thread (ctx, ctx.global_style()) can be used and when ui is available // (ui.ctx(), ui.style()) can be used #[expect(non_local_definitions)] impl egui::cache::ComputerMut< (&egui::FontId, &CodeTheme, &str, &str, HighlightSettings<'_>), LayoutJob, > for Highlighter { fn compute( &mut self, (font_id, theme, code, lang, settings): ( &egui::FontId, &CodeTheme, &str, &str, HighlightSettings<'_>, ), ) -> LayoutJob { Self::highlight(font_id.clone(), theme, code, lang, settings) } } type HighlightCache = egui::cache::FrameCache<LayoutJob, Highlighter>; let font_id = style .override_font_id .clone() .unwrap_or_else(|| TextStyle::Monospace.resolve(style)); // Private type, so that users can't interfere with it in the `IdTypeMap` #[cfg(feature = "syntect")] #[derive(Clone, Default)] struct PrivateSettings(std::sync::Arc<SyntectSettings>); // Dummy private settings, to minimize code changes without `syntect` #[cfg(not(feature = "syntect"))] #[derive(Clone, Default)] struct PrivateSettings(std::sync::Arc<()>); ctx.memory_mut(|mem| { let settings = settings.unwrap_or_else(|| { HighlightSettings( &mem.data .get_temp_mut_or_default::<PrivateSettings>(egui::Id::NULL) .0, ) }); mem.caches .cache::<HighlightCache>() .get((&font_id, theme, code, language, settings)) }) } fn monospace_font_size(style: &egui::Style) -> f32 { TextStyle::Monospace.resolve(style).size } // ---------------------------------------------------------------------------- #[cfg(not(feature = "syntect"))] #[derive(Clone, Copy, PartialEq, enum_map::Enum)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] enum TokenType { Comment, Keyword, Literal, StringLiteral, Punctuation, Whitespace, } #[cfg(feature = "syntect")] #[derive(Clone, Copy, Hash, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] enum SyntectTheme { Base16EightiesDark, Base16MochaDark, Base16OceanDark, Base16OceanLight, InspiredGitHub, SolarizedDark, SolarizedLight, } #[cfg(feature = "syntect")] impl SyntectTheme { fn all() -> impl ExactSizeIterator<Item = Self> { [ Self::Base16EightiesDark, Self::Base16MochaDark, Self::Base16OceanDark, Self::Base16OceanLight, Self::InspiredGitHub, Self::SolarizedDark, Self::SolarizedLight, ] .iter() .copied() } fn name(&self) -> &'static str { match self { Self::Base16EightiesDark => "Base16 Eighties (dark)", Self::Base16MochaDark => "Base16 Mocha (dark)", Self::Base16OceanDark => "Base16 Ocean (dark)", Self::Base16OceanLight => "Base16 Ocean (light)", Self::InspiredGitHub => "InspiredGitHub (light)", Self::SolarizedDark => "Solarized (dark)", Self::SolarizedLight => "Solarized (light)", } } fn syntect_key_name(&self) -> &'static str { match self { Self::Base16EightiesDark => "base16-eighties.dark", Self::Base16MochaDark => "base16-mocha.dark", Self::Base16OceanDark => "base16-ocean.dark", Self::Base16OceanLight => "base16-ocean.light", Self::InspiredGitHub => "InspiredGitHub", Self::SolarizedDark => "Solarized (dark)", Self::SolarizedLight => "Solarized (light)", } } pub fn is_dark(&self) -> bool { match self { Self::Base16EightiesDark | Self::Base16MochaDark | Self::Base16OceanDark | Self::SolarizedDark => true, Self::Base16OceanLight | Self::InspiredGitHub | Self::SolarizedLight => false, } } } /// A selected color theme. #[derive(Clone, Hash, PartialEq)] #[cfg_attr( feature = "serde", derive(serde::Deserialize, serde::Serialize), serde(default) )] pub struct CodeTheme { dark_mode: bool, #[cfg(feature = "syntect")] syntect_theme: SyntectTheme, #[cfg(feature = "syntect")] font_id: egui::FontId, #[cfg(not(feature = "syntect"))] formats: enum_map::EnumMap<TokenType, egui::TextFormat>, } impl Default for CodeTheme { fn default() -> Self { Self::dark(12.0) } } impl CodeTheme { /// Selects either dark or light theme based on the given style. pub fn from_style(style: &egui::Style) -> Self { let font_id = style .override_font_id .clone() .unwrap_or_else(|| TextStyle::Monospace.resolve(style)); if style.visuals.dark_mode { Self::dark_with_font_id(font_id) } else { Self::light_with_font_id(font_id) } } /// ### Example /// /// ``` /// # egui::__run_test_ui(|ui| { /// use egui_extras::syntax_highlighting::CodeTheme; /// let theme = CodeTheme::dark(12.0); /// # }); /// ``` pub fn dark(font_size: f32) -> Self { Self::dark_with_font_id(egui::FontId::monospace(font_size)) } /// ### Example /// /// ``` /// # egui::__run_test_ui(|ui| { /// use egui_extras::syntax_highlighting::CodeTheme; /// let theme = CodeTheme::light(12.0); /// # }); /// ``` pub fn light(font_size: f32) -> Self { Self::light_with_font_id(egui::FontId::monospace(font_size)) } /// Load code theme from egui memory. /// /// There is one dark and one light theme stored at any one time. pub fn from_memory(ctx: &egui::Context, style: &egui::Style) -> Self { #![expect(clippy::needless_return)] let (id, default) = if style.visuals.dark_mode { (egui::Id::new("dark"), Self::dark as fn(f32) -> Self) } else { (egui::Id::new("light"), Self::light as fn(f32) -> Self) }; #[cfg(feature = "serde")] { return ctx.data_mut(|d| { d.get_persisted(id) .unwrap_or_else(|| default(monospace_font_size(style))) }); } #[cfg(not(feature = "serde"))] { return ctx.data_mut(|d| { d.get_temp(id) .unwrap_or_else(|| default(monospace_font_size(style))) }); } } /// Store theme to egui memory. /// /// There is one dark and one light theme stored at any one time. pub fn store_in_memory(self, ctx: &egui::Context) { let id = if ctx.global_style().visuals.dark_mode { egui::Id::new("dark") } else { egui::Id::new("light") }; #[cfg(feature = "serde")] ctx.data_mut(|d| d.insert_persisted(id, self)); #[cfg(not(feature = "serde"))] ctx.data_mut(|d| d.insert_temp(id, self)); } } #[cfg(feature = "syntect")] impl CodeTheme { fn dark_with_font_id(font_id: egui::FontId) -> Self { Self { dark_mode: true, syntect_theme: SyntectTheme::Base16MochaDark, font_id, } } fn light_with_font_id(font_id: egui::FontId) -> Self { Self { dark_mode: false, syntect_theme: SyntectTheme::SolarizedLight, font_id, } } pub fn is_dark(&self) -> bool { self.dark_mode } /// Show UI for changing the color theme. pub fn ui(&mut self, ui: &mut egui::Ui) { ui.horizontal(|ui| { ui.selectable_value(&mut self.dark_mode, true, "🌙 Dark theme") .on_hover_text("Use the dark mode theme"); ui.selectable_value(&mut self.dark_mode, false, "☀ Light theme") .on_hover_text("Use the light mode theme"); }); for theme in SyntectTheme::all() { if theme.is_dark() == self.dark_mode { ui.radio_value(&mut self.syntect_theme, theme, theme.name()); } } } } #[cfg(not(feature = "syntect"))] impl CodeTheme { // The syntect version takes it by value. This could be avoided by specializing the from_style // function, but at the cost of more code duplication. #[expect(clippy::needless_pass_by_value)] fn dark_with_font_id(font_id: egui::FontId) -> Self { #![expect(clippy::mem_forget)] use egui::{Color32, TextFormat}; Self { dark_mode: true, formats: enum_map::enum_map![ TokenType::Comment => TextFormat::simple(font_id.clone(), Color32::from_gray(120)), TokenType::Keyword => TextFormat::simple(font_id.clone(), Color32::from_rgb(255, 100, 100)), TokenType::Literal => TextFormat::simple(font_id.clone(), Color32::from_rgb(87, 165, 171)), TokenType::StringLiteral => TextFormat::simple(font_id.clone(), Color32::from_rgb(109, 147, 226)), TokenType::Punctuation => TextFormat::simple(font_id.clone(), Color32::LIGHT_GRAY), TokenType::Whitespace => TextFormat::simple(font_id.clone(), Color32::TRANSPARENT), ], } } // The syntect version takes it by value #[expect(clippy::needless_pass_by_value)] fn light_with_font_id(font_id: egui::FontId) -> Self { #![expect(clippy::mem_forget)] use egui::{Color32, TextFormat}; Self { dark_mode: false, #[cfg(not(feature = "syntect"))] formats: enum_map::enum_map![ TokenType::Comment => TextFormat::simple(font_id.clone(), Color32::GRAY), TokenType::Keyword => TextFormat::simple(font_id.clone(), Color32::from_rgb(235, 0, 0)), TokenType::Literal => TextFormat::simple(font_id.clone(), Color32::from_rgb(153, 134, 255)), TokenType::StringLiteral => TextFormat::simple(font_id.clone(), Color32::from_rgb(37, 203, 105)), TokenType::Punctuation => TextFormat::simple(font_id.clone(), Color32::DARK_GRAY), TokenType::Whitespace => TextFormat::simple(font_id.clone(), Color32::TRANSPARENT), ], } } /// Show UI for changing the color theme. pub fn ui(&mut self, ui: &mut egui::Ui) { ui.horizontal_top(|ui| { let selected_id = egui::Id::NULL; #[cfg(feature = "serde")] let mut selected_tt: TokenType = ui.data_mut(|d| *d.get_persisted_mut_or(selected_id, TokenType::Comment)); #[cfg(not(feature = "serde"))] let mut selected_tt: TokenType = ui.data_mut(|d| *d.get_temp_mut_or(selected_id, TokenType::Comment)); ui.vertical(|ui| { ui.set_width(150.0); egui::widgets::global_theme_preference_buttons(ui); ui.add_space(8.0); ui.separator(); ui.add_space(8.0); ui.scope(|ui| { for (tt, tt_name) in [ (TokenType::Comment, "// comment"), (TokenType::Keyword, "keyword"), (TokenType::Literal, "literal"), (TokenType::StringLiteral, "\"string literal\""), (TokenType::Punctuation, "punctuation ;"), // (TokenType::Whitespace, "whitespace"), ] { let format = &mut self.formats[tt]; ui.style_mut().override_font_id = Some(format.font_id.clone()); ui.visuals_mut().override_text_color = Some(format.color); ui.radio_value(&mut selected_tt, tt, tt_name); } }); let reset_value = if self.dark_mode { Self::dark(monospace_font_size(ui.style())) } else { Self::light(monospace_font_size(ui.style())) }; if ui .add_enabled(*self != reset_value, egui::Button::new("Reset theme")) .clicked() { *self = reset_value; } }); ui.add_space(16.0); #[cfg(feature = "serde")] ui.data_mut(|d| d.insert_persisted(selected_id, selected_tt)); #[cfg(not(feature = "serde"))] ui.data_mut(|d| d.insert_temp(selected_id, selected_tt)); egui::Frame::group(ui.style()) .inner_margin(egui::Vec2::splat(2.0)) .show(ui, |ui| { // ui.group(|ui| { ui.style_mut().override_text_style = Some(egui::TextStyle::Small); ui.spacing_mut().slider_width = 128.0; // Controls color picker size egui::widgets::color_picker::color_picker_color32( ui, &mut self.formats[selected_tt].color, egui::color_picker::Alpha::Opaque, ); }); }); } } // ---------------------------------------------------------------------------- #[cfg(feature = "syntect")] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct SyntectSettings { pub ps: syntect::parsing::SyntaxSet, pub ts: syntect::highlighting::ThemeSet, } #[cfg(feature = "syntect")] impl Default for SyntectSettings { fn default() -> Self { profiling::function_scope!(); Self { ps: syntect::parsing::SyntaxSet::load_defaults_newlines(), ts: syntect::highlighting::ThemeSet::load_defaults(), } } } /// Highlight settings are memoized by reference address, rather than value #[cfg(feature = "syntect")] #[derive(Copy, Clone)] struct HighlightSettings<'a>(&'a SyntectSettings); #[cfg(not(feature = "syntect"))] #[derive(Copy, Clone)] struct HighlightSettings<'a>(&'a ()); impl std::hash::Hash for HighlightSettings<'_> { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { std::ptr::hash(self.0, state); } } #[derive(Default)] struct Highlighter; impl Highlighter { fn highlight( font_id: egui::FontId, theme: &CodeTheme, code: &str, lang: &str, settings: HighlightSettings<'_>, ) -> LayoutJob { Self::highlight_impl(theme, code, lang, settings).unwrap_or_else(|| { // Fallback: LayoutJob::simple( code.into(), font_id, if theme.dark_mode { egui::Color32::LIGHT_GRAY } else { egui::Color32::DARK_GRAY }, f32::INFINITY, ) }) } #[cfg(feature = "syntect")] fn highlight_impl( theme: &CodeTheme, text: &str, language: &str, highlighter: HighlightSettings<'_>, ) -> Option<LayoutJob> { profiling::function_scope!(); use syntect::easy::HighlightLines; use syntect::highlighting::FontStyle; use syntect::util::LinesWithEndings; let syntax = highlighter .0 .ps .find_syntax_by_name(language) .or_else(|| highlighter.0.ps.find_syntax_by_extension(language))?; let syn_theme = theme.syntect_theme.syntect_key_name(); let mut h = HighlightLines::new(syntax, &highlighter.0.ts.themes[syn_theme]); use egui::text::{LayoutSection, TextFormat}; let mut job = LayoutJob { text: text.into(), ..Default::default() }; for line in LinesWithEndings::from(text) { for (style, range) in h.highlight_line(line, &highlighter.0.ps).ok()? { let fg = style.foreground; let text_color = egui::Color32::from_rgb(fg.r, fg.g, fg.b); let italics = style.font_style.contains(FontStyle::ITALIC); let underline = style.font_style.contains(FontStyle::ITALIC); let underline = if underline { egui::Stroke::new(1.0, text_color) } else { egui::Stroke::NONE }; job.sections.push(LayoutSection { leading_space: 0.0, byte_range: as_byte_range(text, range), format: TextFormat { font_id: theme.font_id.clone(), color: text_color, italics, underline, ..Default::default() }, }); } } Some(job) } } #[cfg(feature = "syntect")] fn as_byte_range(whole: &str, range: &str) -> std::ops::Range<usize> { let whole_start = whole.as_ptr() as usize; let range_start = range.as_ptr() as usize; assert!( whole_start <= range_start, "range must be within whole, but was {range}" ); assert!( range_start + range.len() <= whole_start + whole.len(), "range_start + range length must be smaller than whole_start + whole length, but was {}", range_start + range.len() ); let offset = range_start - whole_start; offset..(offset + range.len()) } // ---------------------------------------------------------------------------- #[cfg(not(feature = "syntect"))] impl Highlighter { fn highlight_impl( theme: &CodeTheme, mut text: &str, language: &str, _settings: HighlightSettings<'_>, ) -> Option<LayoutJob> { profiling::function_scope!(); let language = Language::new(language)?; // Extremely simple syntax highlighter for when we compile without syntect let mut job = LayoutJob::default(); while !text.is_empty() { if language.double_slash_comments && text.starts_with("//") || language.hash_comments && text.starts_with('#') { let end = text.find('\n').unwrap_or(text.len()); job.append(&text[..end], 0.0, theme.formats[TokenType::Comment].clone()); text = &text[end..]; } else if text.starts_with('"') { let end = text[1..] .find('"') .map(|i| i + 2) .or_else(|| text.find('\n')) .unwrap_or(text.len()); job.append( &text[..end], 0.0, theme.formats[TokenType::StringLiteral].clone(), ); text = &text[end..]; } else if text.starts_with(|c: char| c.is_ascii_alphanumeric()) { let end = text[1..] .find(|c: char| !c.is_ascii_alphanumeric()) .map_or_else(|| text.len(), |i| i + 1); let word = &text[..end]; let tt = if language.is_keyword(word) { TokenType::Keyword } else { TokenType::Literal }; job.append(word, 0.0, theme.formats[tt].clone()); text = &text[end..]; } else if text.starts_with(|c: char| c.is_ascii_whitespace()) { let end = text[1..] .find(|c: char| !c.is_ascii_whitespace()) .map_or_else(|| text.len(), |i| i + 1); job.append( &text[..end], 0.0, theme.formats[TokenType::Whitespace].clone(), ); text = &text[end..]; } else { let mut it = text.char_indices(); it.next(); let end = it.next().map_or(text.len(), |(idx, _chr)| idx); job.append( &text[..end], 0.0, theme.formats[TokenType::Punctuation].clone(), ); text = &text[end..]; } } Some(job) } } #[cfg(not(feature = "syntect"))] struct Language { /// `// comment` double_slash_comments: bool, /// `# comment` hash_comments: bool, keywords: std::collections::BTreeSet<&'static str>, } #[cfg(not(feature = "syntect"))] impl Language { fn new(language: &str) -> Option<Self> { match language.to_lowercase().as_str() { "c" | "h" | "hpp" | "cpp" | "c++" => Some(Self::cpp()), "py" | "python" => Some(Self::python()), "rs" | "rust" => Some(Self::rust()), "toml" => Some(Self::toml()), _ => { None // unsupported language } } } fn is_keyword(&self, word: &str) -> bool { self.keywords.contains(word) } fn cpp() -> Self { Self { double_slash_comments: true, hash_comments: false, keywords: [ "alignas", "alignof", "and_eq", "and", "asm", "atomic_cancel", "atomic_commit", "atomic_noexcept", "auto", "bitand", "bitor", "bool", "break", "case", "catch", "char", "char16_t", "char32_t", "char8_t", "class", "co_await", "co_return", "co_yield", "compl", "concept", "const_cast", "const", "consteval", "constexpr", "constinit", "continue", "decltype", "default", "delete", "do", "double", "dynamic_cast", "else", "enum", "explicit", "export", "extern", "false", "float", "for", "friend", "goto", "if", "inline", "int", "long", "mutable", "namespace", "new", "noexcept", "not_eq", "not", "nullptr", "operator", "or_eq", "or", "private", "protected", "public", "reflexpr", "register", "reinterpret_cast", "requires", "return", "short", "signed", "sizeof", "static_assert", "static_cast", "static", "struct", "switch", "synchronized", "template", "this", "thread_local", "throw", "true", "try", "typedef", "typeid", "typename", "union", "unsigned", "using", "virtual", "void", "volatile", "wchar_t", "while", "xor_eq", "xor", ] .into_iter() .collect(), } } fn python() -> Self { Self { double_slash_comments: false, hash_comments: true, keywords: [ "and", "as", "assert", "break", "class", "continue", "def", "del", "elif", "else", "except", "False", "finally", "for", "from", "global", "if", "import", "in", "is", "lambda", "None", "nonlocal", "not", "or", "pass", "raise", "return", "True", "try", "while", "with", "yield", ] .into_iter() .collect(), } } fn rust() -> Self { Self { double_slash_comments: true, hash_comments: false, keywords: [ "as", "async", "await", "break", "const", "continue", "crate", "dyn", "else", "enum", "extern", "false", "fn", "for", "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", "ref", "return", "self", "Self", "static", "struct", "super", "trait", "true", "type", "unsafe", "use", "where", "while", ] .into_iter() .collect(), } } fn toml() -> Self { Self { double_slash_comments: false, hash_comments: true, keywords: Default::default(), } } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_extras/src/datepicker/button.rs
crates/egui_extras/src/datepicker/button.rs
use super::popup::DatePickerPopup; use chrono::NaiveDate; use egui::{Area, Button, Frame, InnerResponse, Key, Order, RichText, Ui, Widget}; use std::ops::RangeInclusive; #[derive(Default, Clone)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub(crate) struct DatePickerButtonState { pub picker_visible: bool, } /// Shows a date, and will open a date picker popup when clicked. pub struct DatePickerButton<'a> { selection: &'a mut NaiveDate, id_salt: Option<&'a str>, combo_boxes: bool, arrows: bool, calendar: bool, calendar_week: bool, show_icon: bool, format: String, highlight_weekends: bool, start_end_years: Option<RangeInclusive<i32>>, } impl<'a> DatePickerButton<'a> { pub fn new(selection: &'a mut NaiveDate) -> Self { Self { selection, id_salt: None, combo_boxes: true, arrows: true, calendar: true, calendar_week: true, show_icon: true, format: "%Y-%m-%d".to_owned(), highlight_weekends: true, start_end_years: None, } } /// Add id source. /// Must be set if multiple date picker buttons are in the same Ui. #[inline] pub fn id_salt(mut self, id_salt: &'a str) -> Self { self.id_salt = Some(id_salt); self } /// Add id source. /// Must be set if multiple date picker buttons are in the same Ui. #[inline] #[deprecated = "Renamed id_salt"] pub fn id_source(self, id_salt: &'a str) -> Self { self.id_salt(id_salt) } /// Show combo boxes in date picker popup. (Default: true) #[inline] pub fn combo_boxes(mut self, combo_boxes: bool) -> Self { self.combo_boxes = combo_boxes; self } /// Show arrows in date picker popup. (Default: true) #[inline] pub fn arrows(mut self, arrows: bool) -> Self { self.arrows = arrows; self } /// Show calendar in date picker popup. (Default: true) #[inline] pub fn calendar(mut self, calendar: bool) -> Self { self.calendar = calendar; self } /// Show calendar week in date picker popup. (Default: true) #[inline] pub fn calendar_week(mut self, week: bool) -> Self { self.calendar_week = week; self } /// Show the calendar icon on the button. (Default: true) #[inline] pub fn show_icon(mut self, show_icon: bool) -> Self { self.show_icon = show_icon; self } /// Change the format shown on the button. (Default: %Y-%m-%d) /// See [`chrono::format::strftime`] for valid formats. #[inline] pub fn format(mut self, format: impl Into<String>) -> Self { self.format = format.into(); self } /// Highlight weekend days. (Default: true) #[inline] pub fn highlight_weekends(mut self, highlight_weekends: bool) -> Self { self.highlight_weekends = highlight_weekends; self } /// Set the start and end years for the date picker. (Default: today's year - 100 to today's year + 10) /// This will limit the years you can choose from in the dropdown to the specified range. /// /// For example, if you want to provide the range of years from 2000 to 2035, you can use: /// `start_end_years(2000..=2035)`. #[inline] pub fn start_end_years(mut self, start_end_years: RangeInclusive<i32>) -> Self { self.start_end_years = Some(start_end_years); self } } impl Widget for DatePickerButton<'_> { fn ui(self, ui: &mut Ui) -> egui::Response { let id = ui.make_persistent_id(self.id_salt); let mut button_state = ui .data_mut(|data| data.get_persisted::<DatePickerButtonState>(id)) .unwrap_or_default(); let mut text = if self.show_icon { RichText::new(format!("{} 📆", self.selection.format(&self.format))) } else { RichText::new(format!("{}", self.selection.format(&self.format))) }; let visuals = ui.visuals().widgets.open; if button_state.picker_visible { text = text.color(visuals.text_color()); } let mut button = Button::new(text); if button_state.picker_visible { button = button.fill(visuals.weak_bg_fill).stroke(visuals.bg_stroke); } let mut button_response = ui.add(button); if button_response.clicked() { button_state.picker_visible = true; ui.data_mut(|data| data.insert_persisted(id, button_state.clone())); } if button_state.picker_visible { let width = 333.0; let mut pos = button_response.rect.left_bottom(); let width_with_padding = width + ui.style().spacing.item_spacing.x + ui.style().spacing.window_margin.leftf() + ui.style().spacing.window_margin.rightf(); if pos.x + width_with_padding > ui.clip_rect().right() { pos.x = button_response.rect.right() - width_with_padding; } // Check to make sure the calendar never is displayed out of window pos.x = pos.x.max(ui.style().spacing.window_margin.leftf()); //TODO(elwerene): Better positioning let InnerResponse { inner: saved, response: area_response, } = Area::new(ui.make_persistent_id(self.id_salt)) .kind(egui::UiKind::Picker) .order(Order::Foreground) .fixed_pos(pos) .show(ui.ctx(), |ui| { let frame = Frame::popup(ui.style()); frame .show(ui, |ui| { ui.set_min_width(width); ui.set_max_width(width); DatePickerPopup { selection: self.selection, button_id: id, combo_boxes: self.combo_boxes, arrows: self.arrows, calendar: self.calendar, calendar_week: self.calendar_week, highlight_weekends: self.highlight_weekends, start_end_years: self.start_end_years, } .draw(ui) }) .inner }); if saved { button_response.mark_changed(); } // We don't want to close our popup if any other popup is open, since other popups would // most likely be the combo boxes in the date picker. let any_popup_open = ui.any_popup_open(); if !button_response.clicked() && !any_popup_open && (ui.input(|i| i.key_pressed(Key::Escape)) || area_response.clicked_elsewhere()) { button_state.picker_visible = false; ui.data_mut(|data| data.insert_persisted(id, button_state)); } } button_response } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_extras/src/datepicker/mod.rs
crates/egui_extras/src/datepicker/mod.rs
#![expect(clippy::unwrap_used)] // TODO(emilk): avoid unwraps mod button; mod popup; pub use button::DatePickerButton; use chrono::{Datelike as _, Duration, NaiveDate, Weekday}; #[derive(Debug)] struct Week { number: u8, days: Vec<NaiveDate>, } fn month_data(year: i32, month: u32) -> Vec<Week> { let first = NaiveDate::from_ymd_opt(year, month, 1).expect("Could not create NaiveDate"); let mut start = first; while start.weekday() != Weekday::Mon { start = start.checked_sub_signed(Duration::days(1)).unwrap(); } let mut weeks = vec![]; let mut week = vec![]; while start < first || start.month() == first.month() || start.weekday() != Weekday::Mon { week.push(start); if start.weekday() == Weekday::Sun { weeks.push(Week { number: start.iso_week().week() as u8, days: std::mem::take(&mut week), }); } start = start.checked_add_signed(Duration::days(1)).unwrap(); } weeks }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_extras/src/datepicker/popup.rs
crates/egui_extras/src/datepicker/popup.rs
use chrono::{Datelike as _, NaiveDate, Weekday}; use egui::{Align, Button, Color32, ComboBox, Direction, Id, Layout, RichText, Ui, Vec2}; use super::{button::DatePickerButtonState, month_data}; use crate::{Column, Size, StripBuilder, TableBuilder}; #[derive(Default, Clone)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] struct DatePickerPopupState { year: i32, month: u32, day: u32, setup: bool, } impl DatePickerPopupState { fn last_day_of_month(&self) -> u32 { let date: NaiveDate = NaiveDate::from_ymd_opt(self.year, self.month, 1).expect("Could not create NaiveDate"); date.with_day(31) .map(|_| 31) .or_else(|| date.with_day(30).map(|_| 30)) .or_else(|| date.with_day(29).map(|_| 29)) .unwrap_or(28) } } pub(crate) struct DatePickerPopup<'a> { pub selection: &'a mut NaiveDate, pub button_id: Id, pub combo_boxes: bool, pub arrows: bool, pub calendar: bool, pub calendar_week: bool, pub highlight_weekends: bool, pub start_end_years: Option<std::ops::RangeInclusive<i32>>, } impl DatePickerPopup<'_> { /// Returns `true` if user pressed `Save` button. pub fn draw(&mut self, ui: &mut Ui) -> bool { let id = ui.make_persistent_id("date_picker"); let today = chrono::offset::Utc::now().date_naive(); let mut popup_state = ui .data_mut(|data| data.get_persisted::<DatePickerPopupState>(id)) .unwrap_or_default(); if !popup_state.setup { popup_state.year = self.selection.year(); popup_state.month = self.selection.month(); popup_state.day = self.selection.day(); popup_state.setup = true; ui.data_mut(|data| data.insert_persisted(id, popup_state.clone())); } let weeks = month_data(popup_state.year, popup_state.month); let (mut close, mut saved) = (false, false); let height = 20.0; let spacing = 2.0; ui.spacing_mut().item_spacing = Vec2::splat(spacing); ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend); // Don't wrap any text StripBuilder::new(ui) .clip(false) .sizes( Size::exact(height), match (self.combo_boxes, self.arrows) { (true, true) => 2, (true, false) | (false, true) => 1, (false, false) => 0, }, ) .sizes( Size::exact((spacing + height) * (weeks.len() + 1) as f32), self.calendar as usize, ) .size(Size::exact(height)) .vertical(|mut strip| { if self.combo_boxes { strip.strip(|builder| { builder.sizes(Size::remainder(), 3).horizontal(|mut strip| { strip.cell(|ui| { ComboBox::from_id_salt("date_picker_year") .selected_text(popup_state.year.to_string()) .show_ui(ui, |ui| { let (start_year, end_year) = match &self.start_end_years { Some(range) => (*range.start(), *range.end()), None => (today.year() - 100, today.year() + 10), }; for year in start_year..=end_year { if ui .selectable_value( &mut popup_state.year, year, year.to_string(), ) .changed() { popup_state.day = popup_state .day .min(popup_state.last_day_of_month()); ui.memory_mut(|mem| { mem.data .insert_persisted(id, popup_state.clone()); }); } } }); }); strip.cell(|ui| { ComboBox::from_id_salt("date_picker_month") .selected_text(month_name(popup_state.month)) .show_ui(ui, |ui| { for month in 1..=12 { if ui .selectable_value( &mut popup_state.month, month, month_name(month), ) .changed() { popup_state.day = popup_state .day .min(popup_state.last_day_of_month()); ui.memory_mut(|mem| { mem.data .insert_persisted(id, popup_state.clone()); }); } } }); }); strip.cell(|ui| { ComboBox::from_id_salt("date_picker_day") .selected_text(popup_state.day.to_string()) .show_ui(ui, |ui| { for day in 1..=popup_state.last_day_of_month() { if ui .selectable_value( &mut popup_state.day, day, day.to_string(), ) .changed() { ui.memory_mut(|mem| { mem.data .insert_persisted(id, popup_state.clone()); }); } } }); }); }); }); } if self.arrows { strip.strip(|builder| { builder.sizes(Size::remainder(), 6).horizontal(|mut strip| { strip.cell(|ui| { ui.with_layout(Layout::top_down_justified(Align::Center), |ui| { if ui .button("<<<") .on_hover_text("subtract one year") .clicked() { popup_state.year -= 1; popup_state.day = popup_state.day.min(popup_state.last_day_of_month()); ui.data_mut(|data| { data.insert_persisted(id, popup_state.clone()); }); } }); }); strip.cell(|ui| { ui.with_layout(Layout::top_down_justified(Align::Center), |ui| { if ui .button("<<") .on_hover_text("subtract one month") .clicked() { popup_state.month -= 1; if popup_state.month == 0 { popup_state.month = 12; popup_state.year -= 1; } popup_state.day = popup_state.day.min(popup_state.last_day_of_month()); ui.data_mut(|data| { data.insert_persisted(id, popup_state.clone()); }); } }); }); strip.cell(|ui| { ui.with_layout(Layout::top_down_justified(Align::Center), |ui| { if ui.button("<").on_hover_text("subtract one day").clicked() { popup_state.day -= 1; if popup_state.day == 0 { popup_state.month -= 1; if popup_state.month == 0 { popup_state.year -= 1; popup_state.month = 12; } popup_state.day = popup_state.last_day_of_month(); } ui.data_mut(|data| { data.insert_persisted(id, popup_state.clone()); }); } }); }); strip.cell(|ui| { ui.with_layout(Layout::top_down_justified(Align::Center), |ui| { if ui.button(">").on_hover_text("add one day").clicked() { popup_state.day += 1; if popup_state.day > popup_state.last_day_of_month() { popup_state.day = 1; popup_state.month += 1; if popup_state.month > 12 { popup_state.month = 1; popup_state.year += 1; } } ui.data_mut(|data| { data.insert_persisted(id, popup_state.clone()); }); } }); }); strip.cell(|ui| { ui.with_layout(Layout::top_down_justified(Align::Center), |ui| { if ui.button(">>").on_hover_text("add one month").clicked() { popup_state.month += 1; if popup_state.month > 12 { popup_state.month = 1; popup_state.year += 1; } popup_state.day = popup_state.day.min(popup_state.last_day_of_month()); ui.data_mut(|data| { data.insert_persisted(id, popup_state.clone()); }); } }); }); strip.cell(|ui| { ui.with_layout(Layout::top_down_justified(Align::Center), |ui| { if ui.button(">>>").on_hover_text("add one year").clicked() { popup_state.year += 1; popup_state.day = popup_state.day.min(popup_state.last_day_of_month()); ui.data_mut(|data| { data.insert_persisted(id, popup_state.clone()); }); } }); }); }); }); } if self.calendar { strip.cell(|ui| { ui.spacing_mut().item_spacing = Vec2::new(1.0, 2.0); TableBuilder::new(ui) .vscroll(false) .columns(Column::remainder(), if self.calendar_week { 8 } else { 7 }) .header(height, |mut header| { if self.calendar_week { header.col(|ui| { ui.with_layout( Layout::centered_and_justified(Direction::TopDown), |ui| { ui.label("Week"); }, ); }); } //TODO(elwerene): Locale for name in ["Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"] { header.col(|ui| { ui.with_layout( Layout::centered_and_justified(Direction::TopDown), |ui| { ui.label(name); }, ); }); } }) .body(|mut body| { for week in weeks { body.row(height, |mut row| { if self.calendar_week { row.col(|ui| { ui.label(week.number.to_string()); }); } for day in week.days { row.col(|ui| { ui.with_layout( Layout::top_down_justified(Align::Center), |ui| { let fill_color = if popup_state.year == day.year() && popup_state.month == day.month() && popup_state.day == day.day() { ui.visuals().selection.bg_fill } else if (day.weekday() == Weekday::Sat || day.weekday() == Weekday::Sun) && self.highlight_weekends { if ui.visuals().dark_mode { Color32::DARK_RED } else { Color32::LIGHT_RED } } else { ui.visuals().extreme_bg_color }; let mut text_color = ui .visuals() .widgets .inactive .text_color(); if day.month() != popup_state.month { text_color = text_color.linear_multiply(0.5); } let button_response = ui.add( Button::new( RichText::new( day.day().to_string(), ) .color(text_color), ) .fill(fill_color), ); if day == today { // Encircle today's date let stroke = ui .visuals() .widgets .inactive .fg_stroke; ui.painter().circle_stroke( button_response.rect.center(), 8.0, stroke, ); } if button_response.clicked() { popup_state.year = day.year(); popup_state.month = day.month(); popup_state.day = day.day(); ui.data_mut(|data| { data.insert_persisted( id, popup_state.clone(), ); }); } }, ); }); } }); } }); }); } strip.strip(|builder| { builder.sizes(Size::remainder(), 3).horizontal(|mut strip| { strip.empty(); strip.cell(|ui| { ui.with_layout(Layout::top_down_justified(Align::Center), |ui| { if ui.button("Cancel").clicked() { close = true; } }); }); strip.cell(|ui| { ui.with_layout(Layout::top_down_justified(Align::Center), |ui| { if ui.button("Save").clicked() { *self.selection = NaiveDate::from_ymd_opt( popup_state.year, popup_state.month, popup_state.day, ) .expect("Could not create NaiveDate"); saved = true; close = true; } }); }); }); }); }); if close { popup_state.setup = false; ui.data_mut(|data| { data.insert_persisted(id, popup_state); data.get_persisted_mut_or_default::<DatePickerButtonState>(self.button_id) .picker_visible = false; }); } saved && close } } fn month_name(i: u32) -> &'static str { match i { 1 => "January", 2 => "February", 3 => "March", 4 => "April", 5 => "May", 6 => "June", 7 => "July", 8 => "August", 9 => "September", 10 => "October", 11 => "November", 12 => "December", _ => panic!("Unknown month: {i}"), } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_extras/src/loaders/image_loader.rs
crates/egui_extras/src/loaders/image_loader.rs
use ahash::HashMap; use egui::{ ColorImage, decode_animated_image_uri, load::{Bytes, BytesPoll, ImageLoadResult, ImageLoader, ImagePoll, LoadError, SizeHint}, mutex::Mutex, }; use image::ImageFormat; use std::{mem::size_of, path::Path, sync::Arc, task::Poll}; #[cfg(not(target_arch = "wasm32"))] use std::thread; type Entry = Poll<Result<Arc<ColorImage>, String>>; #[derive(Default)] pub struct ImageCrateLoader { cache: Arc<Mutex<HashMap<String, Entry>>>, } impl ImageCrateLoader { pub const ID: &'static str = egui::generate_loader_id!(ImageCrateLoader); } fn is_supported_uri(uri: &str) -> bool { let Some(ext) = Path::new(uri) .extension() .and_then(|ext| ext.to_str().map(|ext| ext.to_lowercase())) else { // `true` because if there's no extension, assume that we support it return true; }; // Uses only the enabled image crate features ImageFormat::from_extension(ext).is_some_and(|format| format.reading_enabled()) } fn is_supported_mime(mime: &str) -> bool { // some mime types e.g. reflect binary files or mark the content as a download, which // may be a valid image or not, in this case, defer the decision on the format guessing // or the image crate and return true here let mimes_to_defer = [ "application/octet-stream", "application/x-msdownload", "application/force-download", ]; for m in &mimes_to_defer { // use contains instead of direct equality, as e.g. encoding info might be appended if mime.contains(m) { return true; } } // Some servers may return a media type with an optional parameter, e.g. "image/jpeg; charset=utf-8". let (mime_type, _) = mime.split_once(';').unwrap_or((mime, "")); // Uses only the enabled image crate features ImageFormat::from_mime_type(mime_type).is_some_and(|format| format.reading_enabled()) } impl ImageLoader for ImageCrateLoader { fn id(&self) -> &str { Self::ID } fn load(&self, ctx: &egui::Context, uri: &str, _: SizeHint) -> ImageLoadResult { // three stages of guessing if we support loading the image: // 1. URI extension (only done for files) // 2. Mime from `BytesPoll::Ready` // 3. image::guess_format (used internally by image::load_from_memory) // TODO(lucasmerlin): Egui currently changes all URIs for webp and gif files to include // the frame index (#0), which breaks if the animated image loader is disabled. // We work around this by removing the frame index from the URI here let uri = decode_animated_image_uri(uri).map_or(uri, |(uri, _frame_index)| uri); // (1) if uri.starts_with("file://") && !is_supported_uri(uri) { return Err(LoadError::NotSupported); } #[cfg(not(target_arch = "wasm32"))] #[expect(clippy::unnecessary_wraps)] // needed here to match other return types fn load_image( ctx: &egui::Context, uri: &str, cache: &Arc<Mutex<HashMap<String, Entry>>>, bytes: &Bytes, ) -> ImageLoadResult { let uri = uri.to_owned(); cache.lock().insert(uri.clone(), Poll::Pending); // Do the image parsing on a bg thread thread::Builder::new() .name(format!("egui_extras::ImageLoader::load({uri:?})")) .spawn({ let ctx = ctx.clone(); let cache = Arc::clone(cache); let uri = uri.clone(); let bytes = bytes.clone(); move || { log::trace!("ImageLoader - started loading {uri:?}"); let result = crate::image::load_image_bytes(&bytes) .map(Arc::new) .map_err(|err| err.to_string()); let repaint = { let mut cache = cache.lock(); if let std::collections::hash_map::Entry::Occupied(mut entry) = cache.entry(uri.clone()) { let entry = entry.get_mut(); *entry = Poll::Ready(result); log::trace!("ImageLoader - finished loading {uri:?}"); true } else { log::trace!("ImageLoader - canceled loading {uri:?}\nNote: This can happen if `forget_image` is called while the image is still loading."); false } }; // We may not lock Context while the cache lock is held, since this can // deadlock. // Example deadlock scenario: // - loader thread: lock cache // - main thread: lock ctx (e.g. in `Context::has_pending_images`) // - loader thread: try to lock ctx (in `request_repaint`) // - main thread: try to lock cache (from `Self::has_pending`) if repaint { ctx.request_repaint(); } } }) .expect("failed to spawn thread"); Ok(ImagePoll::Pending { size: None }) } #[cfg(target_arch = "wasm32")] fn load_image( _ctx: &egui::Context, uri: &str, cache: &Arc<Mutex<HashMap<String, Entry>>>, bytes: &Bytes, ) -> ImageLoadResult { let mut cache_lock = cache.lock(); log::trace!("started loading {uri:?}"); let result = crate::image::load_image_bytes(bytes) .map(Arc::new) .map_err(|err| err.to_string()); log::trace!("finished loading {uri:?}"); cache_lock.insert(uri.into(), std::task::Poll::Ready(result.clone())); match result { Ok(image) => Ok(ImagePoll::Ready { image }), Err(err) => Err(LoadError::Loading(err)), } } let entry = self.cache.lock().get(uri).cloned(); if let Some(entry) = entry { match entry { Poll::Ready(Ok(image)) => Ok(ImagePoll::Ready { image }), Poll::Ready(Err(err)) => Err(LoadError::Loading(err)), Poll::Pending => Ok(ImagePoll::Pending { size: None }), } } else { match ctx.try_load_bytes(uri) { Ok(BytesPoll::Ready { bytes, mime, .. }) => { // (2) if let Some(mime) = mime && !is_supported_mime(&mime) { return Err(LoadError::FormatNotSupported { detected_format: Some(mime), }); } load_image(ctx, uri, &self.cache, &bytes) } Ok(BytesPoll::Pending { size }) => Ok(ImagePoll::Pending { size }), Err(err) => Err(err), } } } fn forget(&self, uri: &str) { let _ = self.cache.lock().remove(uri); } fn forget_all(&self) { self.cache.lock().clear(); } fn byte_size(&self) -> usize { self.cache .lock() .values() .map(|result| match result { Poll::Ready(Ok(image)) => image.pixels.len() * size_of::<egui::Color32>(), Poll::Ready(Err(err)) => err.len(), Poll::Pending => 0, }) .sum() } fn has_pending(&self) -> bool { self.cache.lock().values().any(|result| result.is_pending()) } } #[cfg(test)] mod tests { use super::*; #[test] fn check_support() { assert!(is_supported_uri("https://test.png")); assert!(is_supported_uri("test.jpeg")); assert!(is_supported_uri("http://test.gif")); assert!(is_supported_uri("file://test")); assert!(!is_supported_uri("test.svg")); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_extras/src/loaders/svg_loader.rs
crates/egui_extras/src/loaders/svg_loader.rs
use std::{ mem::size_of, sync::{ Arc, atomic::{AtomicU64, Ordering::Relaxed}, }, }; use ahash::HashMap; use egui::{ ColorImage, load::{BytesPoll, ImageLoadResult, ImageLoader, ImagePoll, LoadError, SizeHint}, mutex::Mutex, }; struct Entry { last_used: AtomicU64, result: Result<Arc<ColorImage>, String>, } pub struct SvgLoader { pass_index: AtomicU64, cache: Mutex<HashMap<String, HashMap<SizeHint, Entry>>>, options: resvg::usvg::Options<'static>, } impl SvgLoader { pub const ID: &'static str = egui::generate_loader_id!(SvgLoader); } fn is_supported(uri: &str) -> bool { uri.ends_with(".svg") } impl Default for SvgLoader { fn default() -> Self { // opt is mutated when `svg_text` feature flag is enabled #[allow(clippy::allow_attributes, unused_mut)] let mut options = resvg::usvg::Options::default(); #[cfg(feature = "svg_text")] options.fontdb_mut().load_system_fonts(); Self { pass_index: AtomicU64::new(0), cache: Mutex::new(HashMap::default()), options, } } } impl ImageLoader for SvgLoader { fn id(&self) -> &str { Self::ID } fn load(&self, ctx: &egui::Context, uri: &str, size_hint: SizeHint) -> ImageLoadResult { if !is_supported(uri) { return Err(LoadError::NotSupported); } let mut cache = self.cache.lock(); let bucket = cache.entry(uri.to_owned()).or_default(); if let Some(entry) = bucket.get(&size_hint) { entry .last_used .store(self.pass_index.load(Relaxed), Relaxed); match entry.result.clone() { Ok(image) => Ok(ImagePoll::Ready { image }), Err(err) => Err(LoadError::Loading(err)), } } else { match ctx.try_load_bytes(uri) { Ok(BytesPoll::Ready { bytes, .. }) => { log::trace!("Started loading {uri:?}"); let result = crate::image::load_svg_bytes_with_size(&bytes, size_hint, &self.options) .map(Arc::new); log::trace!("Finished loading {uri:?}"); bucket.insert( size_hint, Entry { last_used: AtomicU64::new(self.pass_index.load(Relaxed)), result: result.clone(), }, ); match result { Ok(image) => Ok(ImagePoll::Ready { image }), Err(err) => Err(LoadError::Loading(err)), } } Ok(BytesPoll::Pending { size }) => Ok(ImagePoll::Pending { size }), Err(err) => Err(err), } } } fn forget(&self, uri: &str) { self.cache.lock().retain(|key, _| key != uri); } fn forget_all(&self) { self.cache.lock().clear(); } fn byte_size(&self) -> usize { self.cache .lock() .values() .flat_map(|bucket| bucket.values()) .map(|entry| match &entry.result { Ok(image) => image.pixels.len() * size_of::<egui::Color32>(), Err(err) => err.len(), }) .sum() } fn end_pass(&self, pass_index: u64) { self.pass_index.store(pass_index, Relaxed); let mut cache = self.cache.lock(); cache.retain(|_key, bucket| { if 2 <= bucket.len() { // There are multiple images of the same URI (e.g. SVGs of different scales). // This could be because someone has an SVG in a resizable container, // and so we get a lot of different sizes of it. // This could wast RAM, so we remove the ones that are not used in this frame. bucket.retain(|_, texture| pass_index <= texture.last_used.load(Relaxed) + 1); } !bucket.is_empty() }); } } #[cfg(test)] mod tests { use super::*; #[test] fn check_support() { // inverse of same test in `image_loader.rs` assert!(!is_supported("https://test.png")); assert!(!is_supported("test.jpeg")); assert!(!is_supported("http://test.gif")); assert!(!is_supported("test.webp")); assert!(!is_supported("file://test")); assert!(is_supported("test.svg")); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_extras/src/loaders/gif_loader.rs
crates/egui_extras/src/loaders/gif_loader.rs
use ahash::HashMap; use egui::{ ColorImage, FrameDurations, Id, decode_animated_image_uri, has_gif_magic_header, load::{BytesPoll, ImageLoadResult, ImageLoader, ImagePoll, LoadError, SizeHint}, mutex::Mutex, }; use image::AnimationDecoder as _; use std::{io::Cursor, mem::size_of, sync::Arc, time::Duration}; /// Array of Frames and the duration for how long each frame should be shown #[derive(Debug, Clone)] pub struct AnimatedImage { frames: Vec<Arc<ColorImage>>, frame_durations: FrameDurations, } impl AnimatedImage { fn load_gif(data: &[u8]) -> Result<Self, String> { let decoder = image::codecs::gif::GifDecoder::new(Cursor::new(data)) .map_err(|err| format!("Failed to decode gif: {err}"))?; let mut images = vec![]; let mut durations = vec![]; for frame in decoder.into_frames() { let frame = frame.map_err(|err| format!("Failed to decode gif: {err}"))?; let img = frame.buffer(); let pixels = img.as_flat_samples(); let delay: Duration = frame.delay().into(); images.push(Arc::new(ColorImage::from_rgba_unmultiplied( [img.width() as usize, img.height() as usize], pixels.as_slice(), ))); durations.push(delay); } Ok(Self { frames: images, frame_durations: FrameDurations::new(durations), }) } } impl AnimatedImage { pub fn byte_len(&self) -> usize { size_of::<Self>() + self .frames .iter() .map(|image| { image.pixels.len() * size_of::<egui::Color32>() + size_of::<Duration>() }) .sum::<usize>() } /// Gets image at index pub fn get_image(&self, index: usize) -> Arc<ColorImage> { Arc::clone(&self.frames[index % self.frames.len()]) } } type Entry = Result<Arc<AnimatedImage>, String>; #[derive(Default)] pub struct GifLoader { cache: Mutex<HashMap<String, Entry>>, } impl GifLoader { pub const ID: &'static str = egui::generate_loader_id!(GifLoader); } impl ImageLoader for GifLoader { fn id(&self) -> &str { Self::ID } fn load(&self, ctx: &egui::Context, frame_uri: &str, _: SizeHint) -> ImageLoadResult { let (image_uri, frame_index) = decode_animated_image_uri(frame_uri).map_err(|_err| LoadError::NotSupported)?; let mut cache = self.cache.lock(); if let Some(entry) = cache.get(image_uri).cloned() { match entry { Ok(image) => Ok(ImagePoll::Ready { image: image.get_image(frame_index), }), Err(err) => Err(LoadError::Loading(err)), } } else { match ctx.try_load_bytes(image_uri) { Ok(BytesPoll::Ready { bytes, .. }) => { if !has_gif_magic_header(&bytes) { return Err(LoadError::NotSupported); } log::trace!("started loading {image_uri:?}"); let result = AnimatedImage::load_gif(&bytes).map(Arc::new); if let Ok(v) = &result { ctx.data_mut(|data| { *data.get_temp_mut_or_default(Id::new(image_uri)) = v.frame_durations.clone(); }); } log::trace!("finished loading {image_uri:?}"); cache.insert(image_uri.into(), result.clone()); match result { Ok(image) => Ok(ImagePoll::Ready { image: image.get_image(frame_index), }), Err(err) => Err(LoadError::Loading(err)), } } Ok(BytesPoll::Pending { size }) => Ok(ImagePoll::Pending { size }), Err(err) => Err(err), } } } fn forget(&self, uri: &str) { let _ = self.cache.lock().remove(uri); } fn forget_all(&self) { self.cache.lock().clear(); } fn byte_size(&self) -> usize { self.cache .lock() .values() .map(|v| match v { Ok(v) => v.byte_len(), Err(e) => e.len(), }) .sum() } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_extras/src/loaders/http_loader.rs
crates/egui_extras/src/loaders/http_loader.rs
use ahash::HashMap; use egui::{ load::{Bytes, BytesLoadResult, BytesLoader, BytesPoll, LoadError}, mutex::Mutex, }; use std::{sync::Arc, task::Poll}; #[derive(Clone)] struct File { bytes: Arc<[u8]>, mime: Option<String>, } impl File { fn from_response(uri: &str, response: ehttp::Response) -> Result<Self, String> { if !response.ok { match response.text() { Some(response_text) => { return Err(format!( "failed to load {uri:?}: {} {} {response_text}", response.status, response.status_text )); } None => { return Err(format!( "failed to load {uri:?}: {} {}", response.status, response.status_text )); } } } let mime = response.content_type().map(|v| v.to_owned()); let bytes = response.bytes.into(); Ok(Self { bytes, mime }) } } type Entry = Poll<Result<File, String>>; #[derive(Default)] pub struct EhttpLoader { cache: Arc<Mutex<HashMap<String, Entry>>>, } impl EhttpLoader { pub const ID: &'static str = egui::generate_loader_id!(EhttpLoader); } const PROTOCOLS: &[&str] = &["http://", "https://"]; fn starts_with_one_of(s: &str, prefixes: &[&str]) -> bool { prefixes.iter().any(|prefix| s.starts_with(prefix)) } impl BytesLoader for EhttpLoader { fn id(&self) -> &str { Self::ID } fn load(&self, ctx: &egui::Context, uri: &str) -> BytesLoadResult { if !starts_with_one_of(uri, PROTOCOLS) { return Err(LoadError::NotSupported); } let mut cache = self.cache.lock(); if let Some(entry) = cache.get(uri).cloned() { match entry { Poll::Ready(Ok(file)) => Ok(BytesPoll::Ready { size: None, bytes: Bytes::Shared(file.bytes), mime: file.mime, }), Poll::Ready(Err(err)) => Err(LoadError::Loading(err)), Poll::Pending => Ok(BytesPoll::Pending { size: None }), } } else { log::trace!("started loading {uri:?}"); let uri = uri.to_owned(); cache.insert(uri.clone(), Poll::Pending); drop(cache); ehttp::fetch(ehttp::Request::get(uri.clone()), { let ctx = ctx.clone(); let cache = Arc::clone(&self.cache); move |response| { let result = match response { Ok(response) => File::from_response(&uri, response), Err(err) => { // Log details; return summary log::error!("Failed to load {uri:?}: {err}"); Err(format!("Failed to load {uri:?}")) } }; let repaint = { let mut cache = cache.lock(); if let std::collections::hash_map::Entry::Occupied(mut entry) = cache.entry(uri.clone()) { let entry = entry.get_mut(); *entry = Poll::Ready(result); log::trace!("Finished loading {uri:?}"); true } else { log::trace!( "Canceled loading {uri:?}\nNote: This can happen if `forget_image` is called while the image is still loading." ); false } }; // We may not lock Context while the cache lock is held (see ImageLoader::load // for details). if repaint { ctx.request_repaint(); } } }); Ok(BytesPoll::Pending { size: None }) } } fn forget(&self, uri: &str) { let _ = self.cache.lock().remove(uri); } fn forget_all(&self) { self.cache.lock().clear(); } fn byte_size(&self) -> usize { self.cache .lock() .values() .map(|entry| match entry { Poll::Ready(Ok(file)) => { file.bytes.len() + file.mime.as_ref().map_or(0, |m| m.len()) } Poll::Ready(Err(err)) => err.len(), _ => 0, }) .sum() } fn has_pending(&self) -> bool { self.cache.lock().values().any(|entry| entry.is_pending()) } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_extras/src/loaders/webp_loader.rs
crates/egui_extras/src/loaders/webp_loader.rs
use ahash::HashMap; use egui::{ ColorImage, FrameDurations, Id, decode_animated_image_uri, has_webp_header, load::{BytesPoll, ImageLoadResult, ImageLoader, ImagePoll, LoadError, SizeHint}, mutex::Mutex, }; use image::{AnimationDecoder as _, ColorType, ImageDecoder as _, Rgba, codecs::webp::WebPDecoder}; use std::{io::Cursor, mem::size_of, sync::Arc, time::Duration}; #[derive(Clone)] enum WebP { Static(Arc<ColorImage>), Animated(AnimatedImage), } impl WebP { fn load(data: &[u8]) -> Result<Self, String> { let mut decoder = WebPDecoder::new(Cursor::new(data)) .map_err(|error| format!("WebP decode failure ({error})"))?; if decoder.has_animation() { decoder .set_background_color(Rgba([0, 0, 0, 0])) .map_err(|error| { format!("Failure to set default background color for animated WebP ({error})") })?; let mut images = vec![]; let mut durations = vec![]; for frame in decoder.into_frames() { let frame = frame.map_err(|error| format!("WebP frame decode failure ({error})"))?; let image = frame.buffer(); let pixels = image.as_flat_samples(); images.push(Arc::new(ColorImage::from_rgba_unmultiplied( [image.width() as usize, image.height() as usize], pixels.as_slice(), ))); let delay: Duration = frame.delay().into(); durations.push(delay); } Ok(Self::Animated(AnimatedImage { frames: images, frame_durations: FrameDurations::new(durations), })) } else { // color_type() of WebPDecoder only returns Rgb8/Rgba8 variants of ColorType let create_image = match decoder.color_type() { ColorType::Rgb8 => ColorImage::from_rgb, ColorType::Rgba8 => ColorImage::from_rgba_unmultiplied, unreachable => { return Err(format!( "Unreachable WebP color type, expected Rgb8/Rgba8, got {unreachable:?}" )); } }; let (width, height) = decoder.dimensions(); let size = decoder.total_bytes() as usize; let mut data = vec![0; size]; decoder .read_image(&mut data) .map_err(|error| format!("WebP image read failure ({error})"))?; Ok(Self::Static(Arc::new(create_image( [width as usize, height as usize], &data, )))) } } fn get_image(&self, frame_index: usize) -> Arc<ColorImage> { match self { Self::Static(image) => Arc::clone(image), Self::Animated(animation) => animation.get_image_by_index(frame_index), } } pub fn byte_len(&self) -> usize { size_of::<Self>() + match self { Self::Static(image) => image.pixels.len() * size_of::<egui::Color32>(), Self::Animated(animation) => animation.byte_len(), } } } #[derive(Debug, Clone)] pub struct AnimatedImage { frames: Vec<Arc<ColorImage>>, frame_durations: FrameDurations, } impl AnimatedImage { pub fn byte_len(&self) -> usize { size_of::<Self>() + self .frames .iter() .map(|image| { image.pixels.len() * size_of::<egui::Color32>() + size_of::<Duration>() }) .sum::<usize>() } pub fn get_image_by_index(&self, index: usize) -> Arc<ColorImage> { Arc::clone(&self.frames[index % self.frames.len()]) } } type Entry = Result<WebP, String>; #[derive(Default)] pub struct WebPLoader { cache: Mutex<HashMap<String, Entry>>, } impl WebPLoader { pub const ID: &'static str = egui::generate_loader_id!(WebPLoader); } impl ImageLoader for WebPLoader { fn id(&self) -> &str { Self::ID } fn load(&self, ctx: &egui::Context, frame_uri: &str, _: SizeHint) -> ImageLoadResult { let (image_uri, frame_index) = decode_animated_image_uri(frame_uri).map_err(|_error| LoadError::NotSupported)?; let mut cache = self.cache.lock(); if let Some(entry) = cache.get(image_uri).cloned() { match entry { Ok(image) => Ok(ImagePoll::Ready { image: image.get_image(frame_index), }), Err(error) => Err(LoadError::Loading(error)), } } else { match ctx.try_load_bytes(image_uri) { Ok(BytesPoll::Ready { bytes, .. }) => { if !has_webp_header(&bytes) { return Err(LoadError::NotSupported); } log::trace!("started loading {image_uri:?}"); let result = WebP::load(&bytes); if let Ok(WebP::Animated(animated_image)) = &result { ctx.data_mut(|data| { *data.get_temp_mut_or_default(Id::new(image_uri)) = animated_image.frame_durations.clone(); }); } log::trace!("finished loading {image_uri:?}"); cache.insert(image_uri.into(), result.clone()); match result { Ok(image) => Ok(ImagePoll::Ready { image: image.get_image(frame_index), }), Err(error) => Err(LoadError::Loading(error)), } } Ok(BytesPoll::Pending { size }) => Ok(ImagePoll::Pending { size }), Err(error) => Err(error), } } } fn forget(&self, uri: &str) { let _ = self.cache.lock().remove(uri); } fn forget_all(&self) { self.cache.lock().clear(); } fn byte_size(&self) -> usize { self.cache .lock() .values() .map(|entry| match entry { Ok(entry_value) => entry_value.byte_len(), Err(error) => error.len(), }) .sum() } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_extras/src/loaders/file_loader.rs
crates/egui_extras/src/loaders/file_loader.rs
use ahash::HashMap; use egui::{ load::{Bytes, BytesLoadResult, BytesLoader, BytesPoll, LoadError}, mutex::Mutex, }; use std::{sync::Arc, task::Poll, thread}; #[derive(Clone)] struct File { bytes: Arc<[u8]>, mime: Option<String>, } type Entry = Poll<Result<File, String>>; #[derive(Default)] pub struct FileLoader { /// Cache for loaded files cache: Arc<Mutex<HashMap<String, Entry>>>, } impl FileLoader { pub const ID: &'static str = egui::generate_loader_id!(FileLoader); } const PROTOCOL: &str = "file://"; /// Remove the leading slash from the path if the target OS is Windows. /// /// This is because Windows paths are not supposed to start with a slash. /// For example, `file:///C:/path/to/file` is a valid URI, but `/C:/path/to/file` is not a valid path. #[inline] fn trim_extra_slash(s: &str) -> &str { if cfg!(target_os = "windows") { s.trim_start_matches('/') } else { s } } impl BytesLoader for FileLoader { fn id(&self) -> &str { Self::ID } fn load(&self, ctx: &egui::Context, uri: &str) -> BytesLoadResult { // File loader only supports the `file` protocol. let Some(path) = uri.strip_prefix(PROTOCOL).map(trim_extra_slash) else { return Err(LoadError::NotSupported); }; let mut cache = self.cache.lock(); if let Some(entry) = cache.get(uri).cloned() { // `path` has either begun loading, is loaded, or has failed to load. match entry { Poll::Ready(Ok(file)) => Ok(BytesPoll::Ready { size: None, bytes: Bytes::Shared(file.bytes), mime: file.mime, }), Poll::Ready(Err(err)) => Err(LoadError::Loading(err)), Poll::Pending => Ok(BytesPoll::Pending { size: None }), } } else { log::trace!("started loading {uri:?}"); // We need to load the file at `path`. // Set the file to `pending` until we finish loading it. let path = path.to_owned(); cache.insert(uri.to_owned(), Poll::Pending); drop(cache); // Spawn a thread to read the file, so that we don't block the render for too long. thread::Builder::new() .name(format!("egui_extras::FileLoader::load({uri:?})")) .spawn({ let ctx = ctx.clone(); let cache = Arc::clone(&self.cache); let uri = uri.to_owned(); move || { let result = match std::fs::read(&path) { Ok(bytes) => { #[cfg(feature = "file")] let mime = mime_guess2::from_path(&path) .first_raw() .map(|v| v.to_owned()); #[cfg(not(feature = "file"))] let mime = None; Ok(File { bytes: bytes.into(), mime, }) } Err(err) => Err(err.to_string()), }; let repaint = { let mut cache = cache.lock(); if let std::collections::hash_map::Entry::Occupied(mut entry) = cache.entry(uri.clone()) { let entry = entry.get_mut(); *entry = Poll::Ready(result); log::trace!("Finished loading {uri:?}"); true } else { log::trace!("Canceled loading {uri:?}\nNote: This can happen if `forget_image` is called while the image is still loading."); false } }; // We may not lock Context while the cache lock is held (see ImageLoader::load // for details). if repaint { ctx.request_repaint(); } } }) .expect("failed to spawn thread"); Ok(BytesPoll::Pending { size: None }) } } fn forget(&self, uri: &str) { let _ = self.cache.lock().remove(uri); } fn forget_all(&self) { self.cache.lock().clear(); } fn byte_size(&self) -> usize { self.cache .lock() .values() .map(|entry| match entry { Poll::Ready(Ok(file)) => { file.bytes.len() + file.mime.as_ref().map_or(0, |m| m.len()) } Poll::Ready(Err(err)) => err.len(), _ => 0, }) .sum() } fn has_pending(&self) -> bool { self.cache.lock().values().any(|entry| entry.is_pending()) } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_app/src/lib.rs
crates/egui_demo_app/src/lib.rs
//! Demo app for egui mod apps; mod backend_panel; mod frame_history; mod wrap_app; pub use wrap_app::{Anchor, WrapApp}; /// Time of day as seconds since midnight. Used for clock in demo app. pub(crate) fn seconds_since_midnight() -> f64 { use chrono::Timelike as _; let time = chrono::Local::now().time(); time.num_seconds_from_midnight() as f64 + 1e-9 * (time.nanosecond() as f64) } /// Trait that wraps different parts of the demo app. pub trait DemoApp { fn demo_ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame); #[cfg(feature = "glow")] fn on_exit(&mut self, _gl: Option<&eframe::glow::Context>) {} } // ---------------------------------------------------------------------------- #[cfg(feature = "accessibility_inspector")] pub mod accessibility_inspector; #[cfg(target_arch = "wasm32")] mod web; #[cfg(target_arch = "wasm32")] pub use web::*;
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_app/src/wrap_app.rs
crates/egui_demo_app/src/wrap_app.rs
use egui_demo_lib::{DemoWindows, is_mobile}; #[cfg(feature = "glow")] use eframe::glow; #[cfg(target_arch = "wasm32")] use core::any::Any; use crate::DemoApp; #[derive(Default)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] struct EasyMarkApp { editor: egui_demo_lib::easy_mark::EasyMarkEditor, } impl DemoApp for EasyMarkApp { fn demo_ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { self.editor.panels(ui); } } // ---------------------------------------------------------------------------- impl DemoApp for DemoWindows { fn demo_ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { self.ui(ui); } } // ---------------------------------------------------------------------------- #[derive(Default)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct FractalClockApp { fractal_clock: crate::apps::FractalClock, pub mock_time: Option<f64>, } impl DemoApp for FractalClockApp { fn demo_ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { egui::Frame::dark_canvas(ui.style()) .stroke(egui::Stroke::NONE) .corner_radius(0) .show(ui, |ui| { self.fractal_clock.ui( ui, self.mock_time .or_else(|| Some(crate::seconds_since_midnight())), ); }); } } // ---------------------------------------------------------------------------- #[derive(Default)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct ColorTestApp { color_test: egui_demo_lib::ColorTest, } impl DemoApp for ColorTestApp { fn demo_ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { egui::CentralPanel::default().show_inside(ui, |ui| { if frame.is_web() { ui.label( "NOTE: Some old browsers stuck on WebGL1 without sRGB support will not pass the color test.", ); ui.separator(); } egui::ScrollArea::both().auto_shrink(false).show(ui, |ui| { self.color_test.ui(ui); }); }); } } #[derive(Copy, Clone, Debug, Default, Eq, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub enum Anchor { #[default] Demo, EasyMarkEditor, #[cfg(feature = "http")] Http, #[cfg(feature = "image_viewer")] ImageViewer, Clock, #[cfg(any(feature = "glow", feature = "wgpu"))] Custom3d, /// Rendering test Rendering, } impl Anchor { #[cfg(target_arch = "wasm32")] fn all() -> Vec<Self> { vec![ Self::Demo, Self::EasyMarkEditor, #[cfg(feature = "http")] Self::Http, Self::Clock, #[cfg(any(feature = "glow", feature = "wgpu"))] Self::Custom3d, Self::Rendering, ] } #[cfg(target_arch = "wasm32")] fn from_str_case_insensitive(anchor: &str) -> Option<Self> { let anchor = anchor.to_lowercase(); Self::all().into_iter().find(|x| x.to_string() == anchor) } } impl std::fmt::Display for Anchor { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut name = format!("{self:?}"); name.make_ascii_lowercase(); f.write_str(&name) } } impl From<Anchor> for egui::WidgetText { fn from(value: Anchor) -> Self { Self::from(value.to_string()) } } // ---------------------------------------------------------------------------- #[derive(Clone, Copy, Debug)] #[must_use] enum Command { Nothing, ResetEverything, } // ---------------------------------------------------------------------------- /// The state that we persist (serialize). #[derive(Default)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] pub struct State { demo: DemoWindows, easy_mark_editor: EasyMarkApp, #[cfg(feature = "http")] http: crate::apps::HttpApp, #[cfg(feature = "image_viewer")] image_viewer: crate::apps::ImageViewer, pub clock: FractalClockApp, rendering_test: ColorTestApp, selected_anchor: Anchor, backend_panel: super::backend_panel::BackendPanel, } /// Wraps many demo/test apps into one. pub struct WrapApp { pub state: State, #[cfg(any(feature = "glow", feature = "wgpu"))] custom3d: Option<crate::apps::Custom3d>, dropped_files: Vec<egui::DroppedFile>, } impl WrapApp { pub fn new(cc: &eframe::CreationContext<'_>) -> Self { // This gives us image support: egui_extras::install_image_loaders(&cc.egui_ctx); #[cfg(feature = "accessibility_inspector")] cc.egui_ctx .add_plugin(crate::accessibility_inspector::AccessibilityInspectorPlugin::default()); #[allow(clippy::allow_attributes, unused_mut)] let mut slf = Self { state: State::default(), #[cfg(any(feature = "glow", feature = "wgpu"))] custom3d: crate::apps::Custom3d::new(cc), dropped_files: Default::default(), }; #[cfg(feature = "persistence")] if let Some(storage) = cc.storage && let Some(state) = eframe::get_value(storage, eframe::APP_KEY) { slf.state = state; } slf } pub fn apps_iter_mut( &mut self, ) -> impl Iterator<Item = (&'static str, Anchor, &mut dyn DemoApp)> { let mut vec = vec![ ( "✨ Demos", Anchor::Demo, &mut self.state.demo as &mut dyn DemoApp, ), ( "🖹 EasyMark editor", Anchor::EasyMarkEditor, &mut self.state.easy_mark_editor as &mut dyn DemoApp, ), #[cfg(feature = "http")] ( "⬇ HTTP", Anchor::Http, &mut self.state.http as &mut dyn DemoApp, ), ( "🕑 Fractal Clock", Anchor::Clock, &mut self.state.clock as &mut dyn DemoApp, ), #[cfg(feature = "image_viewer")] ( "🖼 Image Viewer", Anchor::ImageViewer, &mut self.state.image_viewer as &mut dyn DemoApp, ), ]; #[cfg(any(feature = "glow", feature = "wgpu"))] if let Some(custom3d) = &mut self.custom3d { vec.push(( "🔺 3D painting", Anchor::Custom3d, custom3d as &mut dyn DemoApp, )); } vec.push(( "🎨 Rendering test", Anchor::Rendering, &mut self.state.rendering_test as &mut dyn DemoApp, )); vec.into_iter() } } impl eframe::App for WrapApp { #[cfg(feature = "persistence")] fn save(&mut self, storage: &mut dyn eframe::Storage) { eframe::set_value(storage, eframe::APP_KEY, &self.state); } fn clear_color(&self, visuals: &egui::Visuals) -> [f32; 4] { // Give the area behind the floating windows a different color, because it looks better: let color = egui::lerp( egui::Rgba::from(visuals.panel_fill)..=egui::Rgba::from(visuals.extreme_bg_color), 0.5, ); let color = egui::Color32::from(color); color.to_normalized_gamma_f32() } fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { #[cfg(target_arch = "wasm32")] if let Some(anchor) = frame .info() .web_info .location .hash .strip_prefix('#') .and_then(Anchor::from_str_case_insensitive) { self.state.selected_anchor = anchor; } #[cfg(not(target_arch = "wasm32"))] if ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::F11)) { let fullscreen = ui.input(|i| i.viewport().fullscreen.unwrap_or(false)); ui.send_viewport_cmd(egui::ViewportCommand::Fullscreen(!fullscreen)); } let mut cmd = Command::Nothing; egui::Panel::top("wrap_app_top_bar") .frame(egui::Frame::new().inner_margin(4)) .show_inside(ui, |ui| { ui.horizontal_wrapped(|ui| { ui.visuals_mut().button_frame = false; self.bar_contents(ui, frame, &mut cmd); }); }); self.state.backend_panel.update(ui.ctx(), frame); egui::CentralPanel::no_frame().show_inside(ui, |ui| { if !is_mobile(ui.ctx()) { cmd = self.backend_panel(ui, frame); } self.show_selected_app(ui, frame); }); self.state.backend_panel.end_of_frame(ui.ctx()); self.ui_file_drag_and_drop(ui.ctx()); self.run_cmd(ui.ctx(), cmd); } #[cfg(feature = "glow")] fn on_exit(&mut self, gl: Option<&glow::Context>) { if let Some(custom3d) = &mut self.custom3d { custom3d.on_exit(gl); } } #[cfg(target_arch = "wasm32")] fn as_any_mut(&mut self) -> Option<&mut dyn Any> { Some(&mut *self) } } impl WrapApp { fn backend_panel(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) -> Command { // The backend-panel can be toggled on/off. // We show a little animation when the user switches it. let is_open = self.state.backend_panel.open || ui.memory(|mem| mem.everything_is_visible()); let mut cmd = Command::Nothing; egui::Panel::left("backend_panel") .resizable(false) .show_animated_inside(ui, is_open, |ui| { ui.add_space(4.0); ui.vertical_centered(|ui| { ui.heading("💻 Backend"); }); ui.separator(); self.backend_panel_contents(ui, frame, &mut cmd); }); cmd } fn run_cmd(&mut self, ctx: &egui::Context, cmd: Command) { match cmd { Command::Nothing => {} Command::ResetEverything => { self.state = Default::default(); ctx.memory_mut(|mem| *mem = Default::default()); } } } fn backend_panel_contents( &mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame, cmd: &mut Command, ) { self.state.backend_panel.ui(ui, frame); ui.separator(); ui.horizontal(|ui| { if ui .button("Reset egui") .on_hover_text("Forget scroll, positions, sizes etc") .clicked() { ui.memory_mut(|mem| *mem = Default::default()); ui.close(); } if ui.button("Reset everything").clicked() { *cmd = Command::ResetEverything; ui.close(); } }); } fn show_selected_app(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { let selected_anchor = self.state.selected_anchor; for (_name, anchor, app) in self.apps_iter_mut() { if anchor == selected_anchor || ui.memory(|mem| mem.everything_is_visible()) { app.demo_ui(ui, frame); } } } fn bar_contents(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame, cmd: &mut Command) { egui::widgets::global_theme_preference_switch(ui); ui.separator(); if is_mobile(ui.ctx()) { ui.menu_button("💻 Backend", |ui| { ui.set_style(ui.global_style()); // ignore the "menu" style set by `menu_button`. self.backend_panel_contents(ui, frame, cmd); }); } else { ui.toggle_value(&mut self.state.backend_panel.open, "💻 Backend"); } ui.separator(); let mut selected_anchor = self.state.selected_anchor; for (name, anchor, _app) in self.apps_iter_mut() { if ui .selectable_label(selected_anchor == anchor, name) .clicked() { selected_anchor = anchor; if frame.is_web() { ui.open_url(egui::OpenUrl::same_tab(format!("#{anchor}"))); } } } self.state.selected_anchor = selected_anchor; ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { if false { // TODO(emilk): fix the overlap on small screens if clock_button(ui, crate::seconds_since_midnight()).clicked() { self.state.selected_anchor = Anchor::Clock; if frame.is_web() { ui.open_url(egui::OpenUrl::same_tab("#clock")); } } } egui::warn_if_debug_build(ui); }); } fn ui_file_drag_and_drop(&mut self, ctx: &egui::Context) { use egui::{Align2, Color32, Id, LayerId, Order, TextStyle}; use std::fmt::Write as _; // Preview hovering files: if !ctx.input(|i| i.raw.hovered_files.is_empty()) { let text = ctx.input(|i| { let mut text = "Dropping files:\n".to_owned(); for file in &i.raw.hovered_files { if let Some(path) = &file.path { write!(text, "\n{}", path.display()).ok(); } else if !file.mime.is_empty() { write!(text, "\n{}", file.mime).ok(); } else { text += "\n???"; } } text }); let painter = ctx.layer_painter(LayerId::new(Order::Foreground, Id::new("file_drop_target"))); let content_rect = ctx.content_rect(); painter.rect_filled(content_rect, 0.0, Color32::from_black_alpha(192)); painter.text( content_rect.center(), Align2::CENTER_CENTER, text, TextStyle::Heading.resolve(&ctx.global_style()), Color32::WHITE, ); } // Collect dropped files: ctx.input(|i| { if !i.raw.dropped_files.is_empty() { self.dropped_files.clone_from(&i.raw.dropped_files); } }); // Show dropped files (if any): if !self.dropped_files.is_empty() { let mut open = true; egui::Window::new("Dropped files") .open(&mut open) .show(ctx, |ui| { for file in &self.dropped_files { let mut info = if let Some(path) = &file.path { path.display().to_string() } else if !file.name.is_empty() { file.name.clone() } else { "???".to_owned() }; let mut additional_info = vec![]; if !file.mime.is_empty() { additional_info.push(format!("type: {}", file.mime)); } if let Some(bytes) = &file.bytes { additional_info.push(format!("{} bytes", bytes.len())); } if !additional_info.is_empty() { info += &format!(" ({})", additional_info.join(", ")); } ui.label(info); } }); if !open { self.dropped_files.clear(); } } } } fn clock_button(ui: &mut egui::Ui, seconds_since_midnight: f64) -> egui::Response { let time = seconds_since_midnight; let time = format!( "{:02}:{:02}:{:02}.{:02}", (time % (24.0 * 60.0 * 60.0) / 3600.0).floor(), (time % (60.0 * 60.0) / 60.0).floor(), (time % 60.0).floor(), (time % 1.0 * 100.0).floor() ); ui.button(egui::RichText::new(time).monospace()) }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_app/src/backend_panel.rs
crates/egui_demo_app/src/backend_panel.rs
/// How often we repaint the demo app by default #[derive(Clone, Copy, Debug, Eq, PartialEq)] enum RunMode { /// This is the default for the demo. /// /// If this is selected, egui is only updated if are input events /// (like mouse movements) or there are some animations in the GUI. /// /// Reactive mode saves CPU. /// /// The downside is that the UI can become out-of-date if something it is supposed to monitor changes. /// For instance, a GUI for a thermostat need to repaint each time the temperature changes. /// To ensure the UI is up to date you need to call `egui::Context::request_repaint()` each /// time such an event happens. You can also chose to call `request_repaint()` once every second /// or after every single frame - this is called [`Continuous`](RunMode::Continuous) mode, /// and for games and interactive tools that need repainting every frame anyway, this should be the default. Reactive, /// This will call `egui::Context::request_repaint()` at the end of each frame /// to request the backend to repaint as soon as possible. /// /// On most platforms this will mean that egui will run at the display refresh rate of e.g. 60 Hz. /// /// For this demo it is not any reason to do so except to /// demonstrate how quickly egui runs. /// /// For games or other interactive apps, this is probably what you want to do. /// It will guarantee that egui is always up-to-date. Continuous, } /// Default for demo is Reactive since /// 1) We want to use minimal CPU /// 2) There are no external events that could invalidate the UI /// so there are no events to miss. impl Default for RunMode { fn default() -> Self { Self::Reactive } } // ---------------------------------------------------------------------------- #[derive(Default)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] pub struct BackendPanel { pub open: bool, #[cfg_attr(feature = "serde", serde(skip))] // go back to [`RunMode::Reactive`] mode each time we start run_mode: RunMode, #[cfg_attr(feature = "serde", serde(skip))] frame_history: crate::frame_history::FrameHistory, egui_windows: EguiWindows, } impl BackendPanel { pub fn update(&mut self, ctx: &egui::Context, frame: &eframe::Frame) { self.frame_history .on_new_frame(ctx.input(|i| i.time), frame.info().cpu_usage); match self.run_mode { RunMode::Continuous => { // Tell the backend to repaint as soon as possible ctx.request_repaint(); } RunMode::Reactive => { // let the computer rest for a bit } } } pub fn end_of_frame(&mut self, ctx: &egui::Context) { self.egui_windows.windows(ctx); } pub fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { integration_ui(ui, frame); ui.separator(); self.run_mode_ui(ui); ui.separator(); self.frame_history.ui(ui); ui.separator(); ui.label("egui windows:"); self.egui_windows.checkboxes(ui); #[cfg(debug_assertions)] if ui.global_style().debug.debug_on_hover_with_all_modifiers { ui.separator(); ui.label("Press down all modifiers and hover a widget to see a callstack for it"); } #[cfg(target_arch = "wasm32")] { ui.separator(); let mut screen_reader = ui.options(|o| o.screen_reader); ui.checkbox(&mut screen_reader, "🔈 Screen reader").on_hover_text("Experimental feature: checking this will turn on the screen reader on supported platforms"); ui.options_mut(|o| o.screen_reader = screen_reader); } if cfg!(debug_assertions) && cfg!(target_arch = "wasm32") { ui.separator(); // For testing panic handling on web: #[expect(clippy::manual_assert)] if ui.button("panic!()").clicked() { panic!("intentional panic!"); } } if !cfg!(target_arch = "wasm32") { ui.separator(); if ui.button("Quit").clicked() { ui.send_viewport_cmd(egui::ViewportCommand::Close); } } } fn run_mode_ui(&mut self, ui: &mut egui::Ui) { ui.horizontal(|ui| { let run_mode = &mut self.run_mode; ui.label("Mode:"); ui.radio_value(run_mode, RunMode::Reactive, "Reactive") .on_hover_text("Repaint when there are animations or input (e.g. mouse movement)"); ui.radio_value(run_mode, RunMode::Continuous, "Continuous") .on_hover_text("Repaint everything each frame"); }); if self.run_mode == RunMode::Continuous { ui.label(format!( "Repainting the UI each frame. FPS: {:.1}", self.frame_history.fps() )); } else { ui.label("Only running UI code when there are animations or input."); // Add a test for `request_repaint_after`, but only in debug // builds to keep the noise down in the official demo. if cfg!(debug_assertions) { ui.collapsing("More…", |ui| { ui.horizontal(|ui| { ui.label("Total ui frames:"); ui.monospace(ui.ctx().cumulative_frame_nr().to_string()); }); ui.horizontal(|ui| { ui.label("Total ui passes:"); ui.monospace(ui.ctx().cumulative_pass_nr().to_string()); }); if ui .button("Wait 2s, then request repaint after another 3s") .clicked() { log::info!("Waiting 2s before requesting repaint…"); let ctx = ui.ctx().clone(); call_after_delay(std::time::Duration::from_secs(2), move || { log::info!("Request a repaint in 3s…"); ctx.request_repaint_after(std::time::Duration::from_secs(3)); }); } ui.horizontal(|ui| { if ui.button("Request discard").clicked() { ui.request_discard("Manual button click"); if !ui.ctx().will_discard() { ui.label("Discard denied!"); } } }); }); } } } } fn integration_ui(ui: &mut egui::Ui, _frame: &mut eframe::Frame) { ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = 0.0; ui.label("egui running inside "); ui.hyperlink_to( "eframe", "https://github.com/emilk/egui/tree/main/crates/eframe", ); ui.label("."); }); #[cfg(target_arch = "wasm32")] ui.collapsing("Web info (location)", |ui| { ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend); ui.monospace(format!("{:#?}", _frame.info().web_info.location)); }); #[cfg(feature = "glow")] if _frame.gl().is_some() { ui.horizontal(|ui| { ui.label("Renderer:"); ui.hyperlink_to("glow", "https://github.com/grovesNL/glow"); }); } #[cfg(feature = "wgpu")] if let Some(render_state) = _frame.wgpu_render_state() { let wgpu_adapter_details_ui = |ui: &mut egui::Ui, adapter: &eframe::wgpu::Adapter| { let info = &adapter.get_info(); let wgpu::AdapterInfo { name, vendor, device, device_type, driver, driver_info, backend, } = &info; // Example values: // > name: "llvmpipe (LLVM 16.0.6, 256 bits)", device_type: Cpu, backend: Vulkan, driver: "llvmpipe", driver_info: "Mesa 23.1.6-arch1.4 (LLVM 16.0.6)" // > name: "Apple M1 Pro", device_type: IntegratedGpu, backend: Metal, driver: "", driver_info: "" // > name: "ANGLE (Apple, Apple M1 Pro, OpenGL 4.1)", device_type: IntegratedGpu, backend: Gl, driver: "", driver_info: "" egui::Grid::new("adapter_info").show(ui, |ui| { ui.label("Backend:"); ui.label(format!("{backend:?}")); ui.end_row(); ui.label("Device Type:"); ui.label(format!("{device_type:?}")); ui.end_row(); if !name.is_empty() { ui.label("Name:"); ui.label(format!("{name:?}")); ui.end_row(); } if !driver.is_empty() { ui.label("Driver:"); ui.label(format!("{driver:?}")); ui.end_row(); } if !driver_info.is_empty() { ui.label("Driver info:"); ui.label(format!("{driver_info:?}")); ui.end_row(); } if *vendor != 0 { // TODO(emilk): decode using https://github.com/gfx-rs/wgpu/blob/767ac03245ee937d3dc552edc13fe7ab0a860eec/wgpu-hal/src/auxil/mod.rs#L7 ui.label("Vendor:"); ui.label(format!("0x{vendor:04X}")); ui.end_row(); } if *device != 0 { ui.label("Device:"); ui.label(format!("0x{device:02X}")); ui.end_row(); } }); }; let wgpu_adapter_ui = |ui: &mut egui::Ui, adapter: &eframe::wgpu::Adapter| { let info = &adapter.get_info(); ui.label(format!("{:?}", info.backend)).on_hover_ui(|ui| { wgpu_adapter_details_ui(ui, adapter); }); }; egui::Grid::new("wgpu_info").num_columns(2).show(ui, |ui| { ui.label("Renderer:"); ui.hyperlink_to("wgpu", "https://wgpu.rs/"); ui.end_row(); ui.label("Backend:"); wgpu_adapter_ui(ui, &render_state.adapter); ui.end_row(); #[cfg(not(target_arch = "wasm32"))] if 1 < render_state.available_adapters.len() { ui.label("Others:"); ui.vertical(|ui| { for adapter in &*render_state.available_adapters { if adapter.get_info() != render_state.adapter.get_info() { wgpu_adapter_ui(ui, adapter); } } }); ui.end_row(); } }); } #[cfg(not(target_arch = "wasm32"))] { ui.horizontal(|ui| { { let mut fullscreen = ui.input(|i| i.viewport().fullscreen.unwrap_or(false)); if ui .checkbox(&mut fullscreen, "🗖 Fullscreen (F11)") .on_hover_text("Fullscreen the window") .changed() { ui.send_viewport_cmd(egui::ViewportCommand::Fullscreen(fullscreen)); } } let mut size = None; egui::ComboBox::from_id_salt("viewport-size-combo") .selected_text("Resize to…") .show_ui(ui, |ui| { ui.selectable_value( &mut size, Some(egui::vec2(375.0, 667.0)), "📱 iPhone SE 2nd Gen", ); ui.selectable_value(&mut size, Some(egui::vec2(393.0, 852.0)), "📱 iPhone 15"); ui.selectable_value( &mut size, Some(egui::vec2(1280.0, 720.0)), "🖥 Desktop 720p", ); ui.selectable_value( &mut size, Some(egui::vec2(1920.0, 1080.0)), "🖥 Desktop 1080p", ); }); if let Some(size) = size { ui.send_viewport_cmd(egui::ViewportCommand::InnerSize(size)); ui.send_viewport_cmd(egui::ViewportCommand::Fullscreen(false)); ui.close(); } }); } } // ---------------------------------------------------------------------------- #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] struct EguiWindows { // egui stuff: settings: bool, inspection: bool, memory: bool, output_events: bool, #[cfg_attr(feature = "serde", serde(skip))] output_event_history: std::collections::VecDeque<egui::output::OutputEvent>, } impl Default for EguiWindows { fn default() -> Self { Self::none() } } impl EguiWindows { fn none() -> Self { Self { settings: false, inspection: false, memory: false, output_events: false, output_event_history: Default::default(), } } fn checkboxes(&mut self, ui: &mut egui::Ui) { let Self { settings, inspection, memory, output_events, output_event_history: _, } = self; ui.checkbox(settings, "🔧 Settings"); ui.checkbox(inspection, "🔍 Inspection"); ui.checkbox(memory, "📝 Memory"); ui.checkbox(output_events, "📤 Output Events"); } fn windows(&mut self, ctx: &egui::Context) { let Self { settings, inspection, memory, output_events, output_event_history, } = self; ctx.output(|o| { for event in &o.events { output_event_history.push_back(event.clone()); } }); while output_event_history.len() > 1000 { output_event_history.pop_front(); } egui::Window::new("🔧 Settings") .open(settings) .vscroll(true) .show(ctx, |ui| { ctx.settings_ui(ui); }); egui::Window::new("🔍 Inspection") .open(inspection) .vscroll(true) .show(ctx, |ui| { ctx.inspection_ui(ui); }); egui::Window::new("📝 Memory") .open(memory) .resizable(false) .show(ctx, |ui| { ctx.memory_ui(ui); }); egui::Window::new("📤 Output Events") .open(output_events) .resizable(true) .default_width(520.0) .show(ctx, |ui| { ui.label( "Recent output events from egui. \ These are emitted when you interact with widgets, or move focus between them with TAB. \ They can be hooked up to a screen reader on supported platforms.", ); ui.separator(); egui::ScrollArea::vertical() .stick_to_bottom(true) .show(ui, |ui| { for event in output_event_history { ui.label(format!("{event:?}")); } }); }); } } // ---------------------------------------------------------------------------- #[cfg(not(target_arch = "wasm32"))] fn call_after_delay(delay: std::time::Duration, f: impl FnOnce() + Send + 'static) { std::thread::Builder::new() .name("call_after_delay".to_owned()) .spawn(move || { std::thread::sleep(delay); f(); }) .expect("Failed to spawn a thread"); } #[cfg(target_arch = "wasm32")] fn call_after_delay(delay: std::time::Duration, f: impl FnOnce() + Send + 'static) { #![expect(clippy::unwrap_used)] use wasm_bindgen::prelude::*; let window = web_sys::window().unwrap(); let closure = Closure::once(f); let delay_ms = delay.as_millis() as _; window .set_timeout_with_callback_and_timeout_and_arguments_0( closure.as_ref().unchecked_ref(), delay_ms, ) .unwrap(); closure.forget(); // We must forget it, or else the callback is canceled on drop }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_app/src/accessibility_inspector.rs
crates/egui_demo_app/src/accessibility_inspector.rs
use std::mem; use accesskit::{Action, ActionRequest, NodeId}; use accesskit_consumer::{FilterResult, Node, Tree, TreeChangeHandler}; use eframe::epaint::text::TextWrapMode; use egui::{ Button, Color32, Event, Frame, FullOutput, Id, Key, KeyboardShortcut, Label, Modifiers, Panel, RawInput, RichText, ScrollArea, Ui, collapsing_header::CollapsingState, }; /// This [`egui::Plugin`] adds an inspector panel. /// /// It can be opened with the `(Cmd/Ctrl)+Alt+I`. It shows the current AccessKit tree and details /// for the selected node. /// Useful when debugging accessibility issues or trying to understand the structure of the Ui. /// /// Add via /// ``` /// # use egui_demo_app::accessibility_inspector::AccessibilityInspectorPlugin; /// # let ctx = egui::Context::default(); /// ctx.add_plugin(AccessibilityInspectorPlugin::default()); /// ``` #[derive(Default, Debug)] pub struct AccessibilityInspectorPlugin { pub open: bool, tree: Option<accesskit_consumer::Tree>, selected_node: Option<Id>, queued_action: Option<ActionRequest>, } struct ChangeHandler; impl TreeChangeHandler for ChangeHandler { fn node_added(&mut self, _node: &Node<'_>) {} fn node_updated(&mut self, _old_node: &Node<'_>, _new_node: &Node<'_>) {} fn focus_moved(&mut self, _old_node: Option<&Node<'_>>, _new_node: Option<&Node<'_>>) {} fn node_removed(&mut self, _node: &Node<'_>) {} } impl egui::Plugin for AccessibilityInspectorPlugin { fn debug_name(&self) -> &'static str { "Accessibility Inspector" } fn input_hook(&mut self, input: &mut RawInput) { if let Some(queued_action) = self.queued_action.take() { input .events .push(Event::AccessKitActionRequest(queued_action)); } } fn output_hook(&mut self, output: &mut FullOutput) { if let Some(update) = output.platform_output.accesskit_update.clone() { self.tree = match mem::take(&mut self.tree) { None => { // Create a new tree if it doesn't exist Some(Tree::new(update, true)) } Some(mut tree) => { // Update the tree with the latest accesskit data tree.update_and_process_changes(update, &mut ChangeHandler); Some(tree) } } } } fn on_begin_pass(&mut self, ui: &mut Ui) { if ui.input_mut(|i| { i.consume_shortcut(&KeyboardShortcut::new( Modifiers::COMMAND | Modifiers::ALT, Key::I, )) }) { self.open = !self.open; } if !self.open { return; } ui.enable_accesskit(); Panel::right(Self::id()).show_inside(ui, |ui| { ui.heading("🔎 AccessKit Inspector"); if let Some(selected_node) = self.selected_node { Panel::bottom(Self::id().with("details_panel")) .frame(Frame::new()) .show_separator_line(false) .show_inside(ui, |ui| { self.selection_ui(ui, selected_node); }); } ui.style_mut().wrap_mode = Some(TextWrapMode::Truncate); ScrollArea::vertical().show(ui, |ui| { if let Some(tree) = &self.tree { Self::node_ui(ui, &tree.state().root(), &mut self.selected_node); } }); }); } } impl AccessibilityInspectorPlugin { fn id() -> Id { Id::new("Accessibility Inspector") } fn selection_ui(&mut self, ui: &mut Ui, selected_node: Id) { ui.separator(); if let Some(tree) = &self.tree && let Some(node) = tree.state().node_by_id(NodeId::from(selected_node.value())) { let node_response = ui.ctx().read_response(selected_node); if let Some(widget_response) = node_response { ui.debug_painter().debug_rect( widget_response.rect, ui.style_mut().visuals.selection.bg_fill, "", ); } egui::Grid::new("node_details_grid") .num_columns(2) .show(ui, |ui| { ui.label("Node ID"); ui.strong(format!("{selected_node:?}")); ui.end_row(); ui.label("Role"); ui.strong(format!("{:?}", node.role())); ui.end_row(); ui.label("Label"); ui.add( Label::new(RichText::new(node.label().unwrap_or_default()).strong()) .truncate(), ); ui.end_row(); ui.label("Value"); ui.add( Label::new(RichText::new(node.value().unwrap_or_default()).strong()) .truncate(), ); ui.end_row(); ui.label("Children"); ui.label(RichText::new(node.children().len().to_string()).strong()); ui.end_row(); }); ui.label("Actions"); ui.horizontal_wrapped(|ui| { // Iterate through all possible actions via the `Action::n` helper. let mut current_action = 0; let all_actions = std::iter::from_fn(|| { let action = Action::n(current_action); current_action += 1; action }); for action in all_actions { if node.supports_action(action, &|_node| FilterResult::Include) && ui.button(format!("{action:?}")).clicked() { let action_request = ActionRequest { target: node.id(), action, data: None, }; self.queued_action = Some(action_request); } } }); } else { ui.label("Node not found"); } } fn node_ui(ui: &mut Ui, node: &Node<'_>, selected_node: &mut Option<Id>) { if node.id() == Self::id().value().into() || node .value() .as_deref() .is_some_and(|l| l.contains("AccessKit Inspector")) { return; } let label = node .label() .or_else(|| node.value()) .unwrap_or_else(|| node.id().0.to_string()); let label = format!("({:?}) {}", node.role(), label); // Safety: This is safe since the `accesskit::NodeId` was created from an `egui::Id`. #[expect(unsafe_code)] let egui_node_id = unsafe { Id::from_high_entropy_bits(node.id().0) }; ui.push_id(node.id(), |ui| { let child_count = node.children().len(); let has_children = child_count > 0; let default_open = child_count == 1 && node.role() != accesskit::Role::Label; let mut collapsing = CollapsingState::load_with_default_open( ui.ctx(), egui_node_id.with("ak_collapse"), default_open, ); let header_response = ui.horizontal(|ui| { let text = if collapsing.is_open() { "⏷" } else { "⏵" }; if ui .add_visible(has_children, Button::new(text).frame_when_inactive(false)) .clicked() { collapsing.set_open(!collapsing.is_open()); } let label_response = ui.selectable_value(selected_node, Some(egui_node_id), label.clone()); if label_response.hovered() { let widget_response = ui.ctx().read_response(egui_node_id); if let Some(widget_response) = widget_response { ui.debug_painter() .debug_rect(widget_response.rect, Color32::RED, ""); } } }); if has_children { collapsing.show_body_indented(&header_response.response, ui, |ui| { node.children().for_each(|c| { Self::node_ui(ui, &c, selected_node); }); }); } collapsing.store(ui.ctx()); }); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_app/src/frame_history.rs
crates/egui_demo_app/src/frame_history.rs
use egui::util::History; pub struct FrameHistory { frame_times: History<f32>, } impl Default for FrameHistory { fn default() -> Self { let max_age: f32 = 1.0; let max_len = (max_age * 300.0).round() as usize; Self { frame_times: History::new(0..max_len, max_age), } } } impl FrameHistory { // Called first pub fn on_new_frame(&mut self, now: f64, previous_frame_time: Option<f32>) { let previous_frame_time = previous_frame_time.unwrap_or_default(); if let Some(latest) = self.frame_times.latest_mut() { *latest = previous_frame_time; // rewrite history now that we know } self.frame_times.add(now, previous_frame_time); // projected } pub fn mean_frame_time(&self) -> f32 { self.frame_times.average().unwrap_or_default() } pub fn fps(&self) -> f32 { 1.0 / self.frame_times.mean_time_interval().unwrap_or_default() } pub fn ui(&self, ui: &mut egui::Ui) { ui.label(format!( "Mean CPU usage: {:.2} ms / frame", 1e3 * self.mean_frame_time() )) .on_hover_text( "Includes all app logic, egui layout, tessellation, and rendering.\n\ Does not include waiting for vsync.", ); egui::warn_if_debug_build(ui); if !cfg!(target_arch = "wasm32") { egui::CollapsingHeader::new("📊 CPU usage history") .default_open(false) .show(ui, |ui| { self.graph(ui); }); } } fn graph(&self, ui: &mut egui::Ui) -> egui::Response { use egui::{Pos2, Rect, Sense, Shape, Stroke, TextStyle, emath, epaint, pos2, vec2}; ui.label("egui CPU usage history"); let history = &self.frame_times; // TODO(emilk): we should not use `slider_width` as default graph width. let height = ui.spacing().slider_width; let size = vec2(ui.available_size_before_wrap().x, height); let (rect, response) = ui.allocate_at_least(size, Sense::hover()); let style = ui.style().noninteractive(); let graph_top_cpu_usage = 0.010; let graph_rect = Rect::from_x_y_ranges(history.max_age()..=0.0, graph_top_cpu_usage..=0.0); let to_screen = emath::RectTransform::from_to(graph_rect, rect); let mut shapes = Vec::with_capacity(3 + 2 * history.len()); shapes.push(Shape::Rect(epaint::RectShape::new( rect, style.corner_radius, ui.visuals().extreme_bg_color, ui.style().noninteractive().bg_stroke, egui::StrokeKind::Inside, ))); let rect = rect.shrink(4.0); let color = ui.visuals().text_color(); let line_stroke = Stroke::new(1.0, color); if let Some(pointer_pos) = response.hover_pos() { let y = pointer_pos.y; shapes.push(Shape::line_segment( [pos2(rect.left(), y), pos2(rect.right(), y)], line_stroke, )); let cpu_usage = to_screen.inverse().transform_pos(pointer_pos).y; let text = format!("{:.1} ms", 1e3 * cpu_usage); shapes.push(ui.fonts_mut(|f| { Shape::text( f, pos2(rect.left(), y), egui::Align2::LEFT_BOTTOM, text, TextStyle::Monospace.resolve(ui.style()), color, ) })); } let circle_color = color; let radius = 2.0; let right_side_time = ui.input(|i| i.time); // Time at right side of screen for (time, cpu_usage) in history.iter() { let age = (right_side_time - time) as f32; let pos = to_screen.transform_pos_clamped(Pos2::new(age, cpu_usage)); shapes.push(Shape::line_segment( [pos2(pos.x, rect.bottom()), pos], line_stroke, )); if cpu_usage < graph_top_cpu_usage { shapes.push(Shape::circle_filled(pos, radius, circle_color)); } } ui.painter().extend(shapes); response } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_app/src/web.rs
crates/egui_demo_app/src/web.rs
use eframe::wasm_bindgen::{self, prelude::*}; use crate::WrapApp; /// Our handle to the web app from JavaScript. #[derive(Clone)] #[wasm_bindgen] pub struct WebHandle { runner: eframe::WebRunner, } #[wasm_bindgen] impl WebHandle { /// Installs a panic hook, then returns. #[allow(clippy::allow_attributes, clippy::new_without_default)] #[wasm_bindgen(constructor)] pub fn new() -> Self { // Redirect [`log`] message to `console.log` and friends: let log_level = if cfg!(debug_assertions) { log::LevelFilter::Trace } else { log::LevelFilter::Debug }; eframe::WebLogger::init(log_level).ok(); Self { runner: eframe::WebRunner::new(), } } /// Call this once from JavaScript to start your app. /// /// # Errors /// Returns an error if the app could not start. #[wasm_bindgen] pub async fn start( &self, canvas: web_sys::HtmlCanvasElement, ) -> Result<(), wasm_bindgen::JsValue> { self.runner .start( canvas, eframe::WebOptions::default(), Box::new(|cc| Ok(Box::new(WrapApp::new(cc)))), ) .await } #[wasm_bindgen] pub fn destroy(&self) { self.runner.destroy(); } /// Example on how to call into your app from JavaScript. #[wasm_bindgen] pub fn example(&self) { if let Some(_app) = self.runner.app_mut::<WrapApp>() { // _app.example(); } } /// The JavaScript can check whether or not your app has crashed: #[wasm_bindgen] pub fn has_panicked(&self) -> bool { self.runner.has_panicked() } #[wasm_bindgen] pub fn panic_message(&self) -> Option<String> { self.runner.panic_summary().map(|s| s.message()) } #[wasm_bindgen] pub fn panic_callstack(&self) -> Option<String> { self.runner.panic_summary().map(|s| s.callstack()) } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_app/src/main.rs
crates/egui_demo_app/src/main.rs
//! Demo app for egui #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] // hide console window on Windows in release #![expect(rustdoc::missing_crate_level_docs)] // it's an example #![allow(clippy::allow_attributes, clippy::never_loop)] #[global_allocator] static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc; // Much faster allocator, can give 20% speedups: https://github.com/emilk/egui/pull/7029 // When compiling natively: fn main() { for arg in std::env::args().skip(1) { match arg.as_str() { "--profile" => { #[cfg(feature = "puffin")] start_puffin_server(); #[cfg(not(feature = "puffin"))] panic!( "Unknown argument: {arg} - you need to enable the 'puffin' feature to use this." ); } _ => { panic!("Unknown argument: {arg}"); } } } { // Silence wgpu log spam (https://github.com/gfx-rs/wgpu/issues/3206) let mut rust_log = std::env::var("RUST_LOG").unwrap_or_else(|_| { if cfg!(debug_assertions) { "debug".to_owned() } else { "info".to_owned() } }); for loud_crate in ["naga", "wgpu_core", "wgpu_hal"] { if !rust_log.contains(&format!("{loud_crate}=")) { rust_log += &format!(",{loud_crate}=warn"); } } // SAFETY: we call this from the main thread without any other threads running. #[expect(unsafe_code)] unsafe { std::env::set_var("RUST_LOG", rust_log); } } env_logger::init(); // Log to stderr (if you run with `RUST_LOG=debug`). let options = eframe::NativeOptions { viewport: egui::ViewportBuilder::default() .with_inner_size([1280.0, 1024.0]) .with_drag_and_drop(true), #[cfg(feature = "wgpu")] renderer: eframe::Renderer::Wgpu, ..Default::default() }; let result = eframe::run_native( "egui demo app", options, Box::new(|cc| Ok(Box::new(egui_demo_app::WrapApp::new(cc)))), ); match result { Ok(()) => {} Err(err) => { // This produces a nicer error message than returning the `Result`: print_error_and_exit(&err); } } } fn print_error_and_exit(err: &eframe::Error) -> ! { #![expect(clippy::print_stderr)] #![expect(clippy::exit)] eprintln!("Error: {err}"); std::process::exit(1) } #[cfg(feature = "puffin")] fn start_puffin_server() { puffin::set_scopes_on(true); // tell puffin to collect data match puffin_http::Server::new("127.0.0.1:8585") { Ok(puffin_server) => { log::info!("Run: cargo install puffin_viewer && puffin_viewer --url 127.0.0.1:8585"); std::process::Command::new("puffin_viewer") .arg("--url") .arg("127.0.0.1:8585") .spawn() .ok(); // We can store the server if we want, but in this case we just want // it to keep running. Dropping it closes the server, so let's not drop it! #[expect(clippy::mem_forget)] std::mem::forget(puffin_server); } Err(err) => { log::error!("Failed to start puffin server: {err}"); } } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_app/src/apps/http_app.rs
crates/egui_demo_app/src/apps/http_app.rs
use egui::Image; use poll_promise::Promise; struct Resource { /// HTTP response response: ehttp::Response, text: Option<String>, /// If set, the response was an image. image: Option<Image<'static>>, /// If set, the response was text with some supported syntax highlighting (e.g. ".rs" or ".md"). colored_text: Option<ColoredText>, } impl Resource { fn from_response(ctx: &egui::Context, response: ehttp::Response) -> Self { let content_type = response.content_type().unwrap_or_default(); if content_type.starts_with("image/") { ctx.include_bytes(response.url.clone(), response.bytes.clone()); let image = Image::from_uri(response.url.clone()); Self { response, text: None, colored_text: None, image: Some(image), } } else { let text = response.text(); let colored_text = text.and_then(|text| syntax_highlighting(ctx, &response, text)); let text = text.map(|text| text.to_owned()); Self { response, text, colored_text, image: None, } } } } #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct HttpApp { url: String, #[cfg_attr(feature = "serde", serde(skip))] promise: Option<Promise<ehttp::Result<Resource>>>, } impl Default for HttpApp { fn default() -> Self { Self { url: "https://raw.githubusercontent.com/emilk/egui/main/README.md".to_owned(), promise: Default::default(), } } } impl crate::DemoApp for HttpApp { fn demo_ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { egui::Panel::bottom("http_bottom").show_inside(ui, |ui| { let layout = egui::Layout::top_down(egui::Align::Center).with_main_justify(true); ui.allocate_ui_with_layout(ui.available_size(), layout, |ui| { ui.add(egui_demo_lib::egui_github_link_file!()) }) }); egui::CentralPanel::default().show_inside(ui, |ui| { let prev_url = self.url.clone(); let trigger_fetch = ui_url(ui, frame, &mut self.url); ui.horizontal_wrapped(|ui| { ui.spacing_mut().item_spacing.x = 0.0; ui.label("HTTP requests made using "); ui.hyperlink_to("ehttp", "https://www.github.com/emilk/ehttp"); ui.label("."); }); if trigger_fetch { let ctx = ui.ctx().clone(); let (sender, promise) = Promise::new(); let request = ehttp::Request::get(&self.url); ehttp::fetch(request, move |response| { ctx.forget_image(&prev_url); ctx.request_repaint(); // wake up UI thread let resource = response.map(|response| Resource::from_response(&ctx, response)); sender.send(resource); }); self.promise = Some(promise); } ui.separator(); if let Some(promise) = &self.promise { if let Some(result) = promise.ready() { match result { Ok(resource) => { ui_resource(ui, resource); } Err(error) => { // This should only happen if the fetch API isn't available or something similar. ui.colored_label( ui.visuals().error_fg_color, if error.is_empty() { "Error" } else { error }, ); } } } else { ui.spinner(); } } }); } } fn ui_url(ui: &mut egui::Ui, frame: &eframe::Frame, url: &mut String) -> bool { let mut trigger_fetch = false; ui.horizontal(|ui| { ui.label("URL:"); trigger_fetch |= ui .add(egui::TextEdit::singleline(url).desired_width(f32::INFINITY)) .lost_focus(); }); if frame.is_web() { ui.label("HINT: paste the url of this page into the field above!"); } ui.horizontal(|ui| { if ui.button("Source code for this example").clicked() { *url = format!( "https://raw.githubusercontent.com/emilk/egui/main/{}", file!() ); trigger_fetch = true; } if ui.button("Random image").clicked() { let seed = ui.input(|i| i.time); let side = 640; *url = format!("https://picsum.photos/seed/{seed}/{side}"); trigger_fetch = true; } }); trigger_fetch } fn ui_resource(ui: &mut egui::Ui, resource: &Resource) { let Resource { response, text, image, colored_text, } = resource; ui.monospace(format!("url: {}", response.url)); ui.monospace(format!( "status: {} ({})", response.status, response.status_text )); ui.monospace(format!( "content-type: {}", response.content_type().unwrap_or_default() )); ui.monospace(format!( "size: {:.1} kB", response.bytes.len() as f32 / 1000.0 )); ui.separator(); egui::ScrollArea::vertical() .auto_shrink(false) .show(ui, |ui| { egui::CollapsingHeader::new("Response headers") .default_open(false) .show(ui, |ui| { egui::Grid::new("response_headers") .spacing(egui::vec2(ui.spacing().item_spacing.x * 2.0, 0.0)) .show(ui, |ui| { for (k, v) in &response.headers { ui.label(k); ui.label(v); ui.end_row(); } }) }); ui.separator(); if let Some(text) = &text { let tooltip = "Click to copy the response body"; if ui.button("📋").on_hover_text(tooltip).clicked() { ui.copy_text(text.clone()); } ui.separator(); } if let Some(image) = image { ui.add(image.clone()); } else if let Some(colored_text) = colored_text { colored_text.ui(ui); } else if let Some(text) = &text { ui.add(egui::Label::new(text).selectable(true)); } else { ui.monospace("[binary]"); } }); } // ---------------------------------------------------------------------------- // Syntax highlighting: fn syntax_highlighting( ctx: &egui::Context, response: &ehttp::Response, text: &str, ) -> Option<ColoredText> { let extension_and_rest: Vec<&str> = response.url.rsplitn(2, '.').collect(); let extension = extension_and_rest.first()?; let theme = egui_extras::syntax_highlighting::CodeTheme::from_style(&ctx.global_style()); Some(ColoredText(egui_extras::syntax_highlighting::highlight( ctx, &ctx.global_style(), &theme, text, extension, ))) } struct ColoredText(egui::text::LayoutJob); impl ColoredText { pub fn ui(&self, ui: &mut egui::Ui) { let mut job = self.0.clone(); job.wrap.max_width = ui.available_width(); let galley = ui.fonts_mut(|f| f.layout_job(job)); ui.add(egui::Label::new(galley).selectable(true)); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_app/src/apps/custom3d_wgpu.rs
crates/egui_demo_app/src/apps/custom3d_wgpu.rs
#![expect(clippy::unwrap_used)] // TODO(emilk): avoid unwraps use std::num::NonZeroU64; use eframe::{ egui_wgpu::wgpu::util::DeviceExt as _, egui_wgpu::{self, wgpu}, }; pub struct Custom3d { angle: f32, } impl Custom3d { pub fn new<'a>(cc: &'a eframe::CreationContext<'a>) -> Option<Self> { // Get the WGPU render state from the eframe creation context. This can also be retrieved // from `eframe::Frame` when you don't have a `CreationContext` available. let wgpu_render_state = cc.wgpu_render_state.as_ref()?; let device = &wgpu_render_state.device; let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("custom3d"), source: wgpu::ShaderSource::Wgsl(include_str!("./custom3d_wgpu_shader.wgsl").into()), }); let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("custom3d"), entries: &[wgpu::BindGroupLayoutEntry { binding: 0, visibility: wgpu::ShaderStages::VERTEX, ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: NonZeroU64::new(16), }, count: None, }], }); let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("custom3d"), bind_group_layouts: &[&bind_group_layout], push_constant_ranges: &[], }); let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: Some("custom3d"), layout: Some(&pipeline_layout), vertex: wgpu::VertexState { module: &shader, entry_point: None, buffers: &[], compilation_options: wgpu::PipelineCompilationOptions::default(), }, fragment: Some(wgpu::FragmentState { module: &shader, entry_point: Some("fs_main"), targets: &[Some(wgpu_render_state.target_format.into())], compilation_options: wgpu::PipelineCompilationOptions::default(), }), primitive: wgpu::PrimitiveState::default(), depth_stencil: None, multisample: wgpu::MultisampleState::default(), multiview: None, cache: None, }); let uniform_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("custom3d"), contents: bytemuck::cast_slice(&[0.0_f32; 4]), // 16 bytes aligned! // Mapping at creation (as done by the create_buffer_init utility) doesn't require us to to add the MAP_WRITE usage // (this *happens* to workaround this bug ) usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::UNIFORM, }); let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("custom3d"), layout: &bind_group_layout, entries: &[wgpu::BindGroupEntry { binding: 0, resource: uniform_buffer.as_entire_binding(), }], }); // Because the graphics pipeline must have the same lifetime as the egui render pass, // instead of storing the pipeline in our `Custom3D` struct, we insert it into the // `paint_callback_resources` type map, which is stored alongside the render pass. wgpu_render_state .renderer .write() .callback_resources .insert(TriangleRenderResources { pipeline, bind_group, uniform_buffer, }); Some(Self { angle: 0.0 }) } } impl crate::DemoApp for Custom3d { fn demo_ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { // TODO(emilk): Use `ScrollArea::inner_margin` egui::CentralPanel::default().show_inside(ui, |ui| { egui::ScrollArea::both().auto_shrink(false).show(ui, |ui| { ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = 0.0; ui.label("The triangle is being painted using "); ui.hyperlink_to("WGPU", "https://wgpu.rs"); ui.label(" (Portable Rust graphics API awesomeness)"); }); ui.label( "It's not a very impressive demo, but it shows you can embed 3D inside of egui.", ); egui::Frame::canvas(ui.style()).show(ui, |ui| { self.custom_painting(ui); }); ui.label("Drag to rotate!"); ui.add(egui_demo_lib::egui_github_link_file!()); }); }); } } // Callbacks in egui_wgpu have 3 stages: // * prepare (per callback impl) // * finish_prepare (once) // * paint (per callback impl) // // The prepare callback is called every frame before paint and is given access to the wgpu // Device and Queue, which can be used, for instance, to update buffers and uniforms before // rendering. // If [`egui_wgpu::Renderer`] has [`egui_wgpu::FinishPrepareCallback`] registered, // it will be called after all `prepare` callbacks have been called. // You can use this to update any shared resources that need to be updated once per frame // after all callbacks have been processed. // // On both prepare methods you can use the main `CommandEncoder` that is passed-in, // return an arbitrary number of user-defined `CommandBuffer`s, or both. // The main command buffer, as well as all user-defined ones, will be submitted together // to the GPU in a single call. // // The paint callback is called after finish prepare and is given access to egui's main render pass, // which can be used to issue draw commands. struct CustomTriangleCallback { angle: f32, } impl egui_wgpu::CallbackTrait for CustomTriangleCallback { fn prepare( &self, device: &wgpu::Device, queue: &wgpu::Queue, _screen_descriptor: &egui_wgpu::ScreenDescriptor, _egui_encoder: &mut wgpu::CommandEncoder, resources: &mut egui_wgpu::CallbackResources, ) -> Vec<wgpu::CommandBuffer> { let resources: &TriangleRenderResources = resources.get().unwrap(); resources.prepare(device, queue, self.angle); Vec::new() } fn paint( &self, _info: egui::PaintCallbackInfo, render_pass: &mut wgpu::RenderPass<'static>, resources: &egui_wgpu::CallbackResources, ) { let resources: &TriangleRenderResources = resources.get().unwrap(); resources.paint(render_pass); } } impl Custom3d { fn custom_painting(&mut self, ui: &mut egui::Ui) { let (rect, response) = ui.allocate_exact_size(egui::Vec2::splat(300.0), egui::Sense::drag()); self.angle += response.drag_motion().x * 0.01; ui.painter().add(egui_wgpu::Callback::new_paint_callback( rect, CustomTriangleCallback { angle: self.angle }, )); } } struct TriangleRenderResources { pipeline: wgpu::RenderPipeline, bind_group: wgpu::BindGroup, uniform_buffer: wgpu::Buffer, } impl TriangleRenderResources { fn prepare(&self, _device: &wgpu::Device, queue: &wgpu::Queue, angle: f32) { // Update our uniform buffer with the angle from the UI queue.write_buffer( &self.uniform_buffer, 0, bytemuck::cast_slice(&[angle, 0.0, 0.0, 0.0]), ); } fn paint(&self, render_pass: &mut wgpu::RenderPass<'_>) { // Draw our triangle! render_pass.set_pipeline(&self.pipeline); render_pass.set_bind_group(0, &self.bind_group, &[]); render_pass.draw(0..3, 0..1); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_app/src/apps/mod.rs
crates/egui_demo_app/src/apps/mod.rs
#[cfg(all(feature = "glow", not(feature = "wgpu")))] mod custom3d_glow; #[cfg(feature = "wgpu")] mod custom3d_wgpu; mod fractal_clock; #[cfg(feature = "http")] mod http_app; #[cfg(feature = "image_viewer")] mod image_viewer; #[cfg(feature = "image_viewer")] pub use image_viewer::ImageViewer; #[cfg(all(feature = "glow", not(feature = "wgpu")))] pub use custom3d_glow::Custom3d; #[cfg(feature = "wgpu")] pub use custom3d_wgpu::Custom3d; pub use fractal_clock::FractalClock; #[cfg(feature = "http")] pub use http_app::HttpApp;
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_app/src/apps/fractal_clock.rs
crates/egui_demo_app/src/apps/fractal_clock.rs
use egui::{ Color32, Painter, Pos2, Rect, Shape, Stroke, Ui, Vec2, containers::{CollapsingHeader, Frame}, emath, pos2, widgets::Slider, }; use std::f32::consts::TAU; #[derive(PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] pub struct FractalClock { paused: bool, time: f64, zoom: f32, start_line_width: f32, depth: usize, length_factor: f32, luminance_factor: f32, width_factor: f32, line_count: usize, } impl Default for FractalClock { fn default() -> Self { Self { paused: false, time: 0.0, zoom: 0.25, start_line_width: 2.5, depth: 9, length_factor: 0.8, luminance_factor: 0.8, width_factor: 0.9, line_count: 0, } } } impl FractalClock { pub fn ui(&mut self, ui: &mut Ui, seconds_since_midnight: Option<f64>) { if !self.paused { self.time = seconds_since_midnight.unwrap_or_else(|| ui.input(|i| i.time)); ui.request_repaint(); } let painter = Painter::new( ui.ctx().clone(), ui.layer_id(), ui.available_rect_before_wrap(), ); self.paint(&painter); // Make sure we allocate what we used (everything) ui.expand_to_include_rect(painter.clip_rect()); Frame::popup(ui.style()) .stroke(Stroke::NONE) .show(ui, |ui| { ui.set_max_width(270.0); CollapsingHeader::new("Settings") .show(ui, |ui| self.options_ui(ui, seconds_since_midnight)); }); } fn options_ui(&mut self, ui: &mut Ui, seconds_since_midnight: Option<f64>) { if seconds_since_midnight.is_some() { ui.label(format!( "Local time: {:02}:{:02}:{:02}.{:03}", (self.time % (24.0 * 60.0 * 60.0) / 3600.0).floor(), (self.time % (60.0 * 60.0) / 60.0).floor(), (self.time % 60.0).floor(), (self.time % 1.0 * 100.0).floor() )); } else { ui.label("The fractal_clock clock is not showing the correct time"); } ui.label(format!("Painted line count: {}", self.line_count)); ui.checkbox(&mut self.paused, "Paused"); ui.add(Slider::new(&mut self.zoom, 0.0..=1.0).text("zoom")); ui.add(Slider::new(&mut self.start_line_width, 0.0..=5.0).text("Start line width")); ui.add(Slider::new(&mut self.depth, 0..=14).text("depth")); ui.add(Slider::new(&mut self.length_factor, 0.0..=1.0).text("length factor")); ui.add(Slider::new(&mut self.luminance_factor, 0.0..=1.0).text("luminance factor")); ui.add(Slider::new(&mut self.width_factor, 0.0..=1.0).text("width factor")); egui::reset_button(ui, self, "Reset"); ui.hyperlink_to( "Inspired by a screensaver by Rob Mayoff", "http://www.dqd.com/~mayoff/programs/FractalClock/", ); ui.add(egui_demo_lib::egui_github_link_file!()); } fn paint(&mut self, painter: &Painter) { struct Hand { length: f32, angle: f32, vec: Vec2, } impl Hand { fn from_length_angle(length: f32, angle: f32) -> Self { Self { length, angle, vec: length * Vec2::angled(angle), } } } let angle_from_period = |period| TAU * (self.time.rem_euclid(period) / period) as f32 - TAU / 4.0; let hands = [ // Second hand: Hand::from_length_angle(self.length_factor, angle_from_period(60.0)), // Minute hand: Hand::from_length_angle(self.length_factor, angle_from_period(60.0 * 60.0)), // Hour hand: Hand::from_length_angle(0.5, angle_from_period(12.0 * 60.0 * 60.0)), ]; let mut shapes: Vec<Shape> = Vec::new(); let rect = painter.clip_rect(); let to_screen = emath::RectTransform::from_to( Rect::from_center_size(Pos2::ZERO, rect.square_proportions() / self.zoom), rect, ); let mut paint_line = |points: [Pos2; 2], color: Color32, width: f32| { let line = [to_screen * points[0], to_screen * points[1]]; // culling if rect.intersects(Rect::from_two_pos(line[0], line[1])) { shapes.push(Shape::line_segment(line, (width, color))); } }; let hand_rotations = [ hands[0].angle - hands[2].angle + TAU / 2.0, hands[1].angle - hands[2].angle + TAU / 2.0, ]; let hand_rotors = [ hands[0].length * emath::Rot2::from_angle(hand_rotations[0]), hands[1].length * emath::Rot2::from_angle(hand_rotations[1]), ]; #[derive(Clone, Copy)] struct Node { pos: Pos2, dir: Vec2, } let mut nodes = Vec::new(); let mut width = self.start_line_width; for (i, hand) in hands.iter().enumerate() { let center = pos2(0.0, 0.0); let end = center + hand.vec; paint_line([center, end], Color32::from_additive_luminance(255), width); if i < 2 { nodes.push(Node { pos: end, dir: hand.vec, }); } } let mut luminance = 0.7; // Start dimmer than main hands let mut new_nodes = Vec::new(); for _ in 0..self.depth { new_nodes.clear(); new_nodes.reserve(nodes.len() * 2); luminance *= self.luminance_factor; width *= self.width_factor; let luminance_u8 = (255.0 * luminance).round() as u8; if luminance_u8 == 0 { break; } for &rotor in &hand_rotors { for a in &nodes { let new_dir = rotor * a.dir; let b = Node { pos: a.pos + new_dir, dir: new_dir, }; paint_line( [a.pos, b.pos], Color32::from_additive_luminance(luminance_u8), width, ); new_nodes.push(b); } } std::mem::swap(&mut nodes, &mut new_nodes); } self.line_count = shapes.len(); painter.extend(shapes); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_app/src/apps/custom3d_glow.rs
crates/egui_demo_app/src/apps/custom3d_glow.rs
#![expect(clippy::undocumented_unsafe_blocks)] use std::sync::Arc; use eframe::egui_glow; use egui::mutex::Mutex; use egui_glow::glow; pub struct Custom3d { /// Behind an `Arc<Mutex<…>>` so we can pass it to [`egui::PaintCallback`] and paint later. rotating_triangle: Arc<Mutex<RotatingTriangle>>, angle: f32, } impl Custom3d { pub fn new<'a>(cc: &'a eframe::CreationContext<'a>) -> Option<Self> { let gl = cc.gl.as_ref()?; Some(Self { rotating_triangle: Arc::new(Mutex::new(RotatingTriangle::new(gl)?)), angle: 0.0, }) } } impl crate::DemoApp for Custom3d { fn demo_ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { // TODO(emilk): Use `ScrollArea::inner_margin` egui::CentralPanel::default().show_inside(ui, |ui| { egui::ScrollArea::both().auto_shrink(false).show(ui, |ui| { ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = 0.0; ui.label("The triangle is being painted using "); ui.hyperlink_to("glow", "https://github.com/grovesNL/glow"); ui.label(" (OpenGL)."); }); ui.label( "It's not a very impressive demo, but it shows you can embed 3D inside of egui.", ); egui::Frame::canvas(ui.style()).show(ui, |ui| { self.custom_painting(ui); }); ui.label("Drag to rotate!"); ui.add(egui_demo_lib::egui_github_link_file!()); }); }); } fn on_exit(&mut self, gl: Option<&glow::Context>) { if let Some(gl) = gl { self.rotating_triangle.lock().destroy(gl); } } } impl Custom3d { fn custom_painting(&mut self, ui: &mut egui::Ui) { let (rect, response) = ui.allocate_exact_size(egui::Vec2::splat(300.0), egui::Sense::drag()); self.angle += response.drag_motion().x * 0.01; // Clone locals so we can move them into the paint callback: let angle = self.angle; let rotating_triangle = self.rotating_triangle.clone(); let cb = egui_glow::CallbackFn::new(move |_info, painter| { rotating_triangle.lock().paint(painter.gl(), angle); }); let callback = egui::PaintCallback { rect, callback: Arc::new(cb), }; ui.painter().add(callback); } } struct RotatingTriangle { program: glow::Program, vertex_array: glow::VertexArray, } #[expect(unsafe_code)] // we need unsafe code to use glow impl RotatingTriangle { fn new(gl: &glow::Context) -> Option<Self> { use glow::HasContext as _; let shader_version = egui_glow::ShaderVersion::get(gl); unsafe { let program = gl.create_program().expect("Cannot create program"); if !shader_version.is_new_shader_interface() { log::warn!("Custom 3D painting hasn't been ported to {shader_version:?}"); return None; } let (vertex_shader_source, fragment_shader_source) = ( r#" const vec2 verts[3] = vec2[3]( vec2(0.0, 1.0), vec2(-1.0, -1.0), vec2(1.0, -1.0) ); const vec4 colors[3] = vec4[3]( vec4(1.0, 0.0, 0.0, 1.0), vec4(0.0, 1.0, 0.0, 1.0), vec4(0.0, 0.0, 1.0, 1.0) ); out vec4 v_color; uniform float u_angle; void main() { v_color = colors[gl_VertexID]; gl_Position = vec4(verts[gl_VertexID], 0.0, 1.0); gl_Position.x *= cos(u_angle); } "#, r#" precision mediump float; in vec4 v_color; out vec4 out_color; void main() { out_color = v_color; } "#, ); let shader_sources = [ (glow::VERTEX_SHADER, vertex_shader_source), (glow::FRAGMENT_SHADER, fragment_shader_source), ]; let shaders: Vec<_> = shader_sources .iter() .map(|(shader_type, shader_source)| { let shader = gl .create_shader(*shader_type) .expect("Cannot create shader"); gl.shader_source( shader, &format!( "{}\n{}", shader_version.version_declaration(), shader_source ), ); gl.compile_shader(shader); assert!( gl.get_shader_compile_status(shader), "Failed to compile custom_3d_glow {shader_type}: {}", gl.get_shader_info_log(shader) ); gl.attach_shader(program, shader); shader }) .collect(); gl.link_program(program); assert!( gl.get_program_link_status(program), "{}", gl.get_program_info_log(program) ); for shader in shaders { gl.detach_shader(program, shader); gl.delete_shader(shader); } let vertex_array = gl .create_vertex_array() .expect("Cannot create vertex array"); Some(Self { program, vertex_array, }) } } fn destroy(&self, gl: &glow::Context) { use glow::HasContext as _; unsafe { gl.delete_program(self.program); gl.delete_vertex_array(self.vertex_array); } } fn paint(&self, gl: &glow::Context, angle: f32) { use glow::HasContext as _; unsafe { gl.use_program(Some(self.program)); gl.uniform_1_f32( gl.get_uniform_location(self.program, "u_angle").as_ref(), angle, ); gl.bind_vertex_array(Some(self.vertex_array)); gl.draw_arrays(glow::TRIANGLES, 0, 3); } } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_app/src/apps/image_viewer.rs
crates/egui_demo_app/src/apps/image_viewer.rs
use egui::ImageFit; use egui::Slider; use egui::Vec2; use egui::emath::Rot2; #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct ImageViewer { current_uri: String, uri_edit_text: String, image_options: egui::ImageOptions, chosen_fit: ChosenFit, fit: ImageFit, maintain_aspect_ratio: bool, max_size: Vec2, alt_text: String, } #[derive(Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] enum ChosenFit { ExactSize, Fraction, OriginalSize, } impl ChosenFit { fn as_str(&self) -> &'static str { match self { Self::ExactSize => "exact size", Self::Fraction => "fraction", Self::OriginalSize => "original size", } } } impl Default for ImageViewer { fn default() -> Self { Self { current_uri: "https://picsum.photos/seed/1.759706314/1024".to_owned(), uri_edit_text: "https://picsum.photos/seed/1.759706314/1024".to_owned(), image_options: egui::ImageOptions::default(), chosen_fit: ChosenFit::Fraction, fit: ImageFit::Fraction(Vec2::splat(1.0)), maintain_aspect_ratio: true, max_size: Vec2::splat(2048.0), alt_text: "My Image".to_owned(), } } } impl crate::DemoApp for ImageViewer { fn demo_ui(&mut self, ui: &mut egui::Ui, _: &mut eframe::Frame) { egui::Panel::top("url bar").show_inside(ui, |ui| { ui.horizontal_centered(|ui| { let label = ui.label("URI:"); ui.text_edit_singleline(&mut self.uri_edit_text) .labelled_by(label.id); if ui.small_button("✔").clicked() { ui.ctx().forget_image(&self.current_uri); self.uri_edit_text = self.uri_edit_text.trim().to_owned(); self.current_uri = self.uri_edit_text.clone(); } #[cfg(not(target_arch = "wasm32"))] if ui.button("file…").clicked() && let Some(path) = rfd::FileDialog::new().pick_file() { self.uri_edit_text = format!("file://{}", path.display()); self.current_uri = self.uri_edit_text.clone(); } }); }); egui::Panel::left("controls").show_inside(ui, |ui| { // uv ui.label("UV"); ui.add(Slider::new(&mut self.image_options.uv.min.x, 0.0..=1.0).text("min x")); ui.add(Slider::new(&mut self.image_options.uv.min.y, 0.0..=1.0).text("min y")); ui.add(Slider::new(&mut self.image_options.uv.max.x, 0.0..=1.0).text("max x")); ui.add(Slider::new(&mut self.image_options.uv.max.y, 0.0..=1.0).text("max y")); // rotation ui.add_space(2.0); let had_rotation = self.image_options.rotation.is_some(); let mut has_rotation = had_rotation; ui.checkbox(&mut has_rotation, "Rotation"); match (had_rotation, has_rotation) { (true, false) => self.image_options.rotation = None, (false, true) => { self.image_options.rotation = Some((Rot2::from_angle(0.0), Vec2::new(0.5, 0.5))); } (true, true) | (false, false) => {} } if let Some((rot, origin)) = self.image_options.rotation.as_mut() { let mut angle = rot.angle(); ui.label("angle"); ui.drag_angle(&mut angle); *rot = Rot2::from_angle(angle); ui.add(Slider::new(&mut origin.x, 0.0..=1.0).text("origin x")); ui.add(Slider::new(&mut origin.y, 0.0..=1.0).text("origin y")); } // bg_fill ui.add_space(2.0); ui.horizontal(|ui| { ui.color_edit_button_srgba(&mut self.image_options.bg_fill); ui.label("Background color"); }); // tint ui.add_space(2.0); ui.horizontal(|ui| { ui.color_edit_button_srgba(&mut self.image_options.tint); ui.label("Tint"); }); // fit ui.add_space(10.0); ui.label( "The chosen fit will determine how the image tries to fill the available space", ); egui::ComboBox::from_label("Fit") .selected_text(self.chosen_fit.as_str()) .show_ui(ui, |ui| { ui.selectable_value( &mut self.chosen_fit, ChosenFit::ExactSize, ChosenFit::ExactSize.as_str(), ); ui.selectable_value( &mut self.chosen_fit, ChosenFit::Fraction, ChosenFit::Fraction.as_str(), ); ui.selectable_value( &mut self.chosen_fit, ChosenFit::OriginalSize, ChosenFit::OriginalSize.as_str(), ); }); match self.chosen_fit { ChosenFit::ExactSize => { if !matches!(self.fit, ImageFit::Exact(_)) { self.fit = ImageFit::Exact(Vec2::splat(128.0)); } let ImageFit::Exact(size) = &mut self.fit else { unreachable!() }; ui.add(Slider::new(&mut size.x, 0.0..=2048.0).text("width")); ui.add(Slider::new(&mut size.y, 0.0..=2048.0).text("height")); } ChosenFit::Fraction => { if !matches!(self.fit, ImageFit::Fraction(_)) { self.fit = ImageFit::Fraction(Vec2::splat(1.0)); } let ImageFit::Fraction(fract) = &mut self.fit else { unreachable!() }; ui.add(Slider::new(&mut fract.x, 0.0..=1.0).text("width")); ui.add(Slider::new(&mut fract.y, 0.0..=1.0).text("height")); } ChosenFit::OriginalSize => { if !matches!(self.fit, ImageFit::Original { .. }) { self.fit = ImageFit::Original { scale: 1.0 }; } let ImageFit::Original { scale } = &mut self.fit else { unreachable!() }; ui.add(Slider::new(scale, 0.1..=4.0).text("scale")); } } // max size ui.add_space(5.0); ui.label("The calculated size will not exceed the maximum size"); ui.add(Slider::new(&mut self.max_size.x, 0.0..=2048.0).text("width")); ui.add(Slider::new(&mut self.max_size.y, 0.0..=2048.0).text("height")); // aspect ratio ui.add_space(5.0); ui.label("Aspect ratio is maintained by scaling both sides as necessary"); ui.checkbox(&mut self.maintain_aspect_ratio, "Maintain aspect ratio"); // alt text ui.add_space(5.0); ui.label("Alt text"); ui.text_edit_singleline(&mut self.alt_text); // forget all images if ui.button("Forget all images").clicked() { ui.ctx().forget_all_images(); } }); egui::CentralPanel::default().show_inside(ui, |ui| { egui::ScrollArea::both().show(ui, |ui| { let mut image = egui::Image::from_uri(&self.current_uri); image = image.uv(self.image_options.uv); image = image.bg_fill(self.image_options.bg_fill); image = image.tint(self.image_options.tint); let (angle, origin) = self .image_options .rotation .map_or((0.0, Vec2::splat(0.5)), |(rot, origin)| { (rot.angle(), origin) }); image = image.rotate(angle, origin); match self.fit { ImageFit::Original { scale } => image = image.fit_to_original_size(scale), ImageFit::Fraction(fract) => image = image.fit_to_fraction(fract), ImageFit::Exact(size) => image = image.fit_to_exact_size(size), } image = image.maintain_aspect_ratio(self.maintain_aspect_ratio); image = image.max_size(self.max_size); if !self.alt_text.is_empty() { image = image.alt_text(&self.alt_text); } ui.add_sized(ui.available_size(), image); }); }); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_app/tests/test_demo_app.rs
crates/egui_demo_app/tests/test_demo_app.rs
use egui::Vec2; use egui::accesskit::Role; use egui_demo_app::{Anchor, WrapApp}; use egui_kittest::SnapshotResults; use egui_kittest::kittest::Queryable as _; #[test] fn test_demo_app() { let mut harness = egui_kittest::Harness::builder() .with_size(Vec2::new(900.0, 600.0)) .wgpu() .build_eframe(|cc| WrapApp::new(cc)); let app = harness.state_mut(); // Mock the fractal clock time so snapshots are consistent. app.state.clock.mock_time = Some(36383.0); let apps = app .apps_iter_mut() .map(|(name, anchor, _)| (name, anchor)) .collect::<Vec<_>>(); #[cfg(feature = "wgpu")] assert!( apps.iter() .any(|(_, anchor)| matches!(anchor, Anchor::Custom3d)), "Expected to find the Custom3d app.", ); let mut results = SnapshotResults::new(); for (name, anchor) in apps { harness.get_by_role_and_label(Role::Button, name).click(); match anchor { // The widget gallery demo shows the current date, so we can't use it for snapshot testing Anchor::Demo => { continue; } // This is already tested extensively elsewhere Anchor::Rendering => { continue; } // We don't want to rely on a network connection for tests #[cfg(feature = "http")] Anchor::Http => { continue; } // Load a local image where we know it exists and loads quickly #[cfg(feature = "image_viewer")] Anchor::ImageViewer => { harness.step(); harness .get_by_role_and_label(Role::TextInput, "URI:") .focus(); harness.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); harness .get_by_role_and_label(Role::TextInput, "URI:") .type_text("file://../eframe/data/icon.png"); harness.get_by_role_and_label(Role::Button, "✔").click(); // Wait for the image to load harness.try_run_realtime().ok(); } _ => {} } // Can't use Harness::run because fractal clock keeps requesting repaints harness.run_steps(4); results.add(harness.try_snapshot(anchor.to_string())); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui-wgpu/src/setup.rs
crates/egui-wgpu/src/setup.rs
use std::sync::Arc; #[derive(Clone)] pub enum WgpuSetup { /// Construct a wgpu setup using some predefined settings & heuristics. /// This is the default option. You can customize most behaviours overriding the /// supported backends, power preferences, and device description. /// /// By default can also be configured with various environment variables: /// * `WGPU_BACKEND`: `vulkan`, `dx12`, `metal`, `opengl`, `webgpu` /// * `WGPU_POWER_PREF`: `low`, `high` or `none` /// * `WGPU_TRACE`: Path to a file to output a wgpu trace file. /// /// Each instance flag also comes with an environment variable (for details see [`wgpu::InstanceFlags`]): /// * `WGPU_VALIDATION`: Enables validation (enabled by default in debug builds). /// * `WGPU_DEBUG`: Generate debug information in shaders and objects (enabled by default in debug builds). /// * `WGPU_ALLOW_UNDERLYING_NONCOMPLIANT_ADAPTER`: Whether wgpu should expose adapters that run on top of non-compliant adapters. /// * `WGPU_GPU_BASED_VALIDATION`: Enable GPU-based validation. CreateNew(WgpuSetupCreateNew), /// Run on an existing wgpu setup. Existing(WgpuSetupExisting), } impl Default for WgpuSetup { fn default() -> Self { Self::CreateNew(WgpuSetupCreateNew::default()) } } impl std::fmt::Debug for WgpuSetup { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::CreateNew(create_new) => f .debug_tuple("WgpuSetup::CreateNew") .field(create_new) .finish(), Self::Existing { .. } => f.debug_tuple("WgpuSetup::Existing").finish(), } } } impl WgpuSetup { /// Creates a new [`wgpu::Instance`] or clones the existing one. /// /// Does *not* store the wgpu instance, so calling this repeatedly may /// create a new instance every time! pub async fn new_instance(&self) -> wgpu::Instance { match self { Self::CreateNew(create_new) => { #[allow(clippy::allow_attributes, unused_mut)] let mut backends = create_new.instance_descriptor.backends; // Don't try WebGPU if we're not in a secure context. #[cfg(target_arch = "wasm32")] if backends.contains(wgpu::Backends::BROWSER_WEBGPU) { let is_secure_context = wgpu::web_sys::window().is_some_and(|w| w.is_secure_context()); if !is_secure_context { log::info!( "WebGPU is only available in secure contexts, i.e. on HTTPS and on localhost." ); backends.remove(wgpu::Backends::BROWSER_WEBGPU); } } log::debug!("Creating wgpu instance with backends {backends:?}"); wgpu::util::new_instance_with_webgpu_detection(&create_new.instance_descriptor) .await } Self::Existing(existing) => existing.instance.clone(), } } } impl From<WgpuSetupCreateNew> for WgpuSetup { fn from(create_new: WgpuSetupCreateNew) -> Self { Self::CreateNew(create_new) } } impl From<WgpuSetupExisting> for WgpuSetup { fn from(existing: WgpuSetupExisting) -> Self { Self::Existing(existing) } } /// Method for selecting an adapter on native. /// /// This can be used for fully custom adapter selection. /// If available, `wgpu::Surface` is passed to allow checking for surface compatibility. pub type NativeAdapterSelectorMethod = Arc< dyn Fn(&[wgpu::Adapter], Option<&wgpu::Surface<'_>>) -> Result<wgpu::Adapter, String> + Send + Sync, >; /// Configuration for creating a new wgpu setup. /// /// Used for [`WgpuSetup::CreateNew`]. pub struct WgpuSetupCreateNew { /// Instance descriptor for creating a wgpu instance. /// /// The most important field is [`wgpu::InstanceDescriptor::backends`], which /// controls which backends are supported (wgpu will pick one of these). /// If you only want to support WebGL (and not WebGPU), /// you can set this to [`wgpu::Backends::GL`]. /// By default on web, WebGPU will be used if available. /// WebGL will only be used as a fallback, /// and only if you have enabled the `webgl` feature of crate `wgpu`. pub instance_descriptor: wgpu::InstanceDescriptor, /// Power preference for the adapter if [`Self::native_adapter_selector`] is not set or targeting web. pub power_preference: wgpu::PowerPreference, /// Optional selector for native adapters. /// /// This field has no effect when targeting web! /// Otherwise, if set [`Self::power_preference`] is ignored and the adapter is instead selected by this method. /// Note that [`Self::instance_descriptor`]'s [`wgpu::InstanceDescriptor::backends`] /// are still used to filter the adapter enumeration in the first place. /// /// Defaults to `None`. pub native_adapter_selector: Option<NativeAdapterSelectorMethod>, /// Configuration passed on device request, given an adapter pub device_descriptor: Arc<dyn Fn(&wgpu::Adapter) -> wgpu::DeviceDescriptor<'static> + Send + Sync>, } impl Clone for WgpuSetupCreateNew { fn clone(&self) -> Self { Self { instance_descriptor: self.instance_descriptor.clone(), power_preference: self.power_preference, native_adapter_selector: self.native_adapter_selector.clone(), device_descriptor: Arc::clone(&self.device_descriptor), } } } impl std::fmt::Debug for WgpuSetupCreateNew { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("WgpuSetupCreateNew") .field("instance_descriptor", &self.instance_descriptor) .field("power_preference", &self.power_preference) .field( "native_adapter_selector", &self.native_adapter_selector.is_some(), ) .finish() } } impl Default for WgpuSetupCreateNew { fn default() -> Self { Self { instance_descriptor: wgpu::InstanceDescriptor { // Add GL backend, primarily because WebGPU is not stable enough yet. // (note however, that the GL backend needs to be opted-in via the wgpu feature flag "webgl") backends: wgpu::Backends::from_env() .unwrap_or(wgpu::Backends::PRIMARY | wgpu::Backends::GL), flags: wgpu::InstanceFlags::from_build_config().with_env(), backend_options: wgpu::BackendOptions::from_env_or_default(), memory_budget_thresholds: wgpu::MemoryBudgetThresholds::default(), }, power_preference: wgpu::PowerPreference::from_env() .unwrap_or(wgpu::PowerPreference::HighPerformance), native_adapter_selector: None, device_descriptor: Arc::new(|adapter| { let base_limits = if adapter.get_info().backend == wgpu::Backend::Gl { wgpu::Limits::downlevel_webgl2_defaults() } else { wgpu::Limits::default() }; wgpu::DeviceDescriptor { label: Some("egui wgpu device"), required_limits: wgpu::Limits { // When using a depth buffer, we have to be able to create a texture // large enough for the entire surface, and we want to support 4k+ displays. max_texture_dimension_2d: 8192, ..base_limits }, ..Default::default() } }), } } } /// Configuration for using an existing wgpu setup. /// /// Used for [`WgpuSetup::Existing`]. #[derive(Clone)] pub struct WgpuSetupExisting { pub instance: wgpu::Instance, pub adapter: wgpu::Adapter, pub device: wgpu::Device, pub queue: wgpu::Queue, }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui-wgpu/src/winit.rs
crates/egui-wgpu/src/winit.rs
#![expect(clippy::missing_errors_doc)] #![expect(clippy::undocumented_unsafe_blocks)] #![expect(clippy::unwrap_used)] // TODO(emilk): avoid unwraps #![expect(unsafe_code)] use crate::{RenderState, SurfaceErrorAction, WgpuConfiguration, renderer}; use crate::{ RendererOptions, capture::{CaptureReceiver, CaptureSender, CaptureState, capture_channel}, }; use egui::{Context, Event, UserData, ViewportId, ViewportIdMap, ViewportIdSet}; use std::{num::NonZeroU32, sync::Arc}; struct SurfaceState { surface: wgpu::Surface<'static>, alpha_mode: wgpu::CompositeAlphaMode, width: u32, height: u32, resizing: bool, } /// Everything you need to paint egui with [`wgpu`] on [`winit`]. /// /// Alternatively you can use [`crate::Renderer`] directly. /// /// NOTE: all egui viewports share the same painter. pub struct Painter { context: Context, configuration: WgpuConfiguration, options: RendererOptions, support_transparent_backbuffer: bool, screen_capture_state: Option<CaptureState>, instance: wgpu::Instance, render_state: Option<RenderState>, // Per viewport/window: depth_texture_view: ViewportIdMap<wgpu::TextureView>, msaa_texture_view: ViewportIdMap<wgpu::TextureView>, surfaces: ViewportIdMap<SurfaceState>, capture_tx: CaptureSender, capture_rx: CaptureReceiver, } impl Painter { /// Manages [`wgpu`] state, including surface state, required to render egui. /// /// Only the [`wgpu::Instance`] is initialized here. Device selection and the initialization /// of render + surface state is deferred until the painter is given its first window target /// via [`set_window()`](Self::set_window). (Ensuring that a device that's compatible with the /// native window is chosen) /// /// Before calling [`paint_and_update_textures()`](Self::paint_and_update_textures) a /// [`wgpu::Surface`] must be initialized (and corresponding render state) by calling /// [`set_window()`](Self::set_window) once you have /// a [`winit::window::Window`] with a valid `.raw_window_handle()` /// associated. pub async fn new( context: Context, configuration: WgpuConfiguration, support_transparent_backbuffer: bool, options: RendererOptions, ) -> Self { let (capture_tx, capture_rx) = capture_channel(); let instance = configuration.wgpu_setup.new_instance().await; Self { context, configuration, options, support_transparent_backbuffer, screen_capture_state: None, instance, render_state: None, depth_texture_view: Default::default(), surfaces: Default::default(), msaa_texture_view: Default::default(), capture_tx, capture_rx, } } /// Get the [`RenderState`]. /// /// Will return [`None`] if the render state has not been initialized yet. pub fn render_state(&self) -> Option<RenderState> { self.render_state.clone() } fn configure_surface( surface_state: &SurfaceState, render_state: &RenderState, config: &WgpuConfiguration, ) { profiling::function_scope!(); let width = surface_state.width; let height = surface_state.height; let mut surf_config = wgpu::SurfaceConfiguration { usage: wgpu::TextureUsages::RENDER_ATTACHMENT, format: render_state.target_format, present_mode: config.present_mode, alpha_mode: surface_state.alpha_mode, view_formats: vec![render_state.target_format], ..surface_state .surface .get_default_config(&render_state.adapter, width, height) .expect("The surface isn't supported by this adapter") }; if let Some(desired_maximum_frame_latency) = config.desired_maximum_frame_latency { surf_config.desired_maximum_frame_latency = desired_maximum_frame_latency; } surface_state .surface .configure(&render_state.device, &surf_config); } /// Updates (or clears) the [`winit::window::Window`] associated with the [`Painter`] /// /// This creates a [`wgpu::Surface`] for the given Window (as well as initializing render /// state if needed) that is used for egui rendering. /// /// This must be called before trying to render via /// [`paint_and_update_textures`](Self::paint_and_update_textures) /// /// # Portability /// /// _In particular it's important to note that on Android a it's only possible to create /// a window surface between `Resumed` and `Paused` lifecycle events, and Winit will panic on /// attempts to query the raw window handle while paused._ /// /// On Android [`set_window`](Self::set_window) should be called with `Some(window)` for each /// `Resumed` event and `None` for each `Paused` event. Currently, on all other platforms /// [`set_window`](Self::set_window) may be called with `Some(window)` as soon as you have a /// valid [`winit::window::Window`]. /// /// # Errors /// If the provided wgpu configuration does not match an available device. pub async fn set_window( &mut self, viewport_id: ViewportId, window: Option<Arc<winit::window::Window>>, ) -> Result<(), crate::WgpuError> { profiling::scope!("Painter::set_window"); // profile_function gives bad names for async functions if let Some(window) = window { let size = window.inner_size(); if !self.surfaces.contains_key(&viewport_id) { let surface = self.instance.create_surface(window)?; self.add_surface(surface, viewport_id, size).await?; } } else { log::warn!("No window - clearing all surfaces"); self.surfaces.clear(); } Ok(()) } /// Updates (or clears) the [`winit::window::Window`] associated with the [`Painter`] without taking ownership of the window. /// /// Like [`set_window`](Self::set_window) except: /// /// # Safety /// The user is responsible for ensuring that the window is alive for as long as it is set. pub async unsafe fn set_window_unsafe( &mut self, viewport_id: ViewportId, window: Option<&winit::window::Window>, ) -> Result<(), crate::WgpuError> { profiling::scope!("Painter::set_window_unsafe"); // profile_function gives bad names for async functions if let Some(window) = window { let size = window.inner_size(); if !self.surfaces.contains_key(&viewport_id) { let surface = unsafe { self.instance .create_surface_unsafe(wgpu::SurfaceTargetUnsafe::from_window(&window)?)? }; self.add_surface(surface, viewport_id, size).await?; } } else { log::warn!("No window - clearing all surfaces"); self.surfaces.clear(); } Ok(()) } async fn add_surface( &mut self, surface: wgpu::Surface<'static>, viewport_id: ViewportId, size: winit::dpi::PhysicalSize<u32>, ) -> Result<(), crate::WgpuError> { let render_state = if let Some(render_state) = &self.render_state { render_state } else { let render_state = RenderState::create( &self.configuration, &self.instance, Some(&surface), self.options, ) .await?; self.render_state.get_or_insert(render_state) }; let alpha_mode = if self.support_transparent_backbuffer { let supported_alpha_modes = surface.get_capabilities(&render_state.adapter).alpha_modes; // Prefer pre multiplied over post multiplied! if supported_alpha_modes.contains(&wgpu::CompositeAlphaMode::PreMultiplied) { wgpu::CompositeAlphaMode::PreMultiplied } else if supported_alpha_modes.contains(&wgpu::CompositeAlphaMode::PostMultiplied) { wgpu::CompositeAlphaMode::PostMultiplied } else { log::warn!( "Transparent window was requested, but the active wgpu surface does not support a `CompositeAlphaMode` with transparency." ); wgpu::CompositeAlphaMode::Auto } } else { wgpu::CompositeAlphaMode::Auto }; self.surfaces.insert( viewport_id, SurfaceState { surface, width: size.width, height: size.height, alpha_mode, resizing: false, }, ); let Some(width) = NonZeroU32::new(size.width) else { log::debug!("The window width was zero; skipping generate textures"); return Ok(()); }; let Some(height) = NonZeroU32::new(size.height) else { log::debug!("The window height was zero; skipping generate textures"); return Ok(()); }; self.resize_and_generate_depth_texture_view_and_msaa_view(viewport_id, width, height); Ok(()) } /// Returns the maximum texture dimension supported if known /// /// This API will only return a known dimension after `set_window()` has been called /// at least once, since the underlying device and render state are initialized lazily /// once we have a window (that may determine the choice of adapter/device). pub fn max_texture_side(&self) -> Option<usize> { self.render_state .as_ref() .map(|rs| rs.device.limits().max_texture_dimension_2d as usize) } fn resize_and_generate_depth_texture_view_and_msaa_view( &mut self, viewport_id: ViewportId, width_in_pixels: NonZeroU32, height_in_pixels: NonZeroU32, ) { profiling::function_scope!(); let width = width_in_pixels.get(); let height = height_in_pixels.get(); let render_state = self.render_state.as_ref().unwrap(); let surface_state = self.surfaces.get_mut(&viewport_id).unwrap(); surface_state.width = width; surface_state.height = height; Self::configure_surface(surface_state, render_state, &self.configuration); if let Some(depth_format) = self.options.depth_stencil_format { self.depth_texture_view.insert( viewport_id, render_state .device .create_texture(&wgpu::TextureDescriptor { label: Some("egui_depth_texture"), size: wgpu::Extent3d { width, height, depth_or_array_layers: 1, }, mip_level_count: 1, sample_count: self.options.msaa_samples.max(1), dimension: wgpu::TextureDimension::D2, format: depth_format, usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING, view_formats: &[depth_format], }) .create_view(&wgpu::TextureViewDescriptor::default()), ); } if let Some(render_state) = (self.options.msaa_samples > 1) .then_some(self.render_state.as_ref()) .flatten() { let texture_format = render_state.target_format; self.msaa_texture_view.insert( viewport_id, render_state .device .create_texture(&wgpu::TextureDescriptor { label: Some("egui_msaa_texture"), size: wgpu::Extent3d { width, height, depth_or_array_layers: 1, }, mip_level_count: 1, sample_count: self.options.msaa_samples.max(1), dimension: wgpu::TextureDimension::D2, format: texture_format, usage: wgpu::TextureUsages::RENDER_ATTACHMENT, view_formats: &[texture_format], }) .create_view(&wgpu::TextureViewDescriptor::default()), ); } } /// Handles changes of the resizing state. /// /// Should be called prior to the first [`Painter::on_window_resized`] call and after the last in /// the chain. Used to apply platform-specific logic, e.g. OSX Metal window resize jitter fix. pub fn on_window_resize_state_change(&mut self, viewport_id: ViewportId, resizing: bool) { profiling::function_scope!(); let Some(state) = self.surfaces.get_mut(&viewport_id) else { return; }; if state.resizing == resizing { if resizing { log::debug!( "Painter::on_window_resize_state_change() redundant call while resizing" ); } else { log::debug!( "Painter::on_window_resize_state_change() redundant call after resizing" ); } return; } // Resizing is a bit tricky on macOS. // It requires enabling ["present_with_transaction"](https://developer.apple.com/documentation/quartzcore/cametallayer/presentswithtransaction) // flag to avoid jittering during the resize. Even though resize jittering on macOS // is common across rendering backends, the solution for wgpu/metal is known. // // See https://github.com/emilk/egui/issues/903 #[cfg(all(target_os = "macos", feature = "macos-window-resize-jitter-fix"))] { // SAFETY: The cast is checked with if condition. If the used backend is not metal // it gracefully fails. The pointer casts are valid as it's 1-to-1 type mapping. // This is how wgpu currently exposes this backend-specific flag. unsafe { if let Some(hal_surface) = state.surface.as_hal::<wgpu::hal::api::Metal>() { let raw = std::ptr::from_ref::<wgpu::hal::metal::Surface>(&*hal_surface).cast_mut(); (*raw).present_with_transaction = resizing; Self::configure_surface( state, self.render_state.as_ref().unwrap(), &self.configuration, ); } } } state.resizing = resizing; } pub fn on_window_resized( &mut self, viewport_id: ViewportId, width_in_pixels: NonZeroU32, height_in_pixels: NonZeroU32, ) { profiling::function_scope!(); if self.surfaces.contains_key(&viewport_id) { self.resize_and_generate_depth_texture_view_and_msaa_view( viewport_id, width_in_pixels, height_in_pixels, ); } else { log::warn!( "Ignoring window resize notification with no surface created via Painter::set_window()" ); } } /// Returns two things: /// /// The approximate number of seconds spent on vsync-waiting (if any), /// and the captures captured screenshot if it was requested. /// /// If `capture_data` isn't empty, a screenshot will be captured. pub fn paint_and_update_textures( &mut self, viewport_id: ViewportId, pixels_per_point: f32, clear_color: [f32; 4], clipped_primitives: &[epaint::ClippedPrimitive], textures_delta: &epaint::textures::TexturesDelta, capture_data: Vec<UserData>, ) -> f32 { profiling::function_scope!(); let capture = !capture_data.is_empty(); let mut vsync_sec = 0.0; let Some(render_state) = self.render_state.as_mut() else { return vsync_sec; }; let Some(surface_state) = self.surfaces.get(&viewport_id) else { return vsync_sec; }; let mut encoder = render_state .device .create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("encoder"), }); // Upload all resources for the GPU. let screen_descriptor = renderer::ScreenDescriptor { size_in_pixels: [surface_state.width, surface_state.height], pixels_per_point, }; let user_cmd_bufs = { let mut renderer = render_state.renderer.write(); for (id, image_delta) in &textures_delta.set { renderer.update_texture( &render_state.device, &render_state.queue, *id, image_delta, ); } renderer.update_buffers( &render_state.device, &render_state.queue, &mut encoder, clipped_primitives, &screen_descriptor, ) }; let output_frame = { profiling::scope!("get_current_texture"); // This is what vsync-waiting happens on my Mac. let start = web_time::Instant::now(); let output_frame = surface_state.surface.get_current_texture(); vsync_sec += start.elapsed().as_secs_f32(); output_frame }; let output_frame = match output_frame { Ok(frame) => frame, Err(err) => match (*self.configuration.on_surface_error)(err) { SurfaceErrorAction::RecreateSurface => { Self::configure_surface(surface_state, render_state, &self.configuration); return vsync_sec; } SurfaceErrorAction::SkipFrame => { return vsync_sec; } }, }; let mut capture_buffer = None; { let renderer = render_state.renderer.read(); let target_texture = if capture { let capture_state = self.screen_capture_state.get_or_insert_with(|| { CaptureState::new(&render_state.device, &output_frame.texture) }); capture_state.update(&render_state.device, &output_frame.texture); &capture_state.texture } else { &output_frame.texture }; let target_view = target_texture.create_view(&wgpu::TextureViewDescriptor::default()); let (view, resolve_target) = (self.options.msaa_samples > 1) .then_some(self.msaa_texture_view.get(&viewport_id)) .flatten() .map_or((&target_view, None), |texture_view| { (texture_view, Some(&target_view)) }); let render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: Some("egui_render"), color_attachments: &[Some(wgpu::RenderPassColorAttachment { view, resolve_target, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color { r: clear_color[0] as f64, g: clear_color[1] as f64, b: clear_color[2] as f64, a: clear_color[3] as f64, }), store: wgpu::StoreOp::Store, }, depth_slice: None, })], depth_stencil_attachment: self.depth_texture_view.get(&viewport_id).map(|view| { wgpu::RenderPassDepthStencilAttachment { view, depth_ops: self .options .depth_stencil_format .is_some_and(|depth_stencil_format| { depth_stencil_format.has_depth_aspect() }) .then_some(wgpu::Operations { load: wgpu::LoadOp::Clear(1.0), // It is very unlikely that the depth buffer is needed after egui finished rendering // so no need to store it. (this can improve performance on tiling GPUs like mobile chips or Apple Silicon) store: wgpu::StoreOp::Discard, }), stencil_ops: self .options .depth_stencil_format .is_some_and(|depth_stencil_format| { depth_stencil_format.has_stencil_aspect() }) .then_some(wgpu::Operations { load: wgpu::LoadOp::Clear(0), store: wgpu::StoreOp::Discard, }), } }), timestamp_writes: None, occlusion_query_set: None, }); // Forgetting the pass' lifetime means that we are no longer compile-time protected from // runtime errors caused by accessing the parent encoder before the render pass is dropped. // Since we don't pass it on to the renderer, we should be perfectly safe against this mistake here! renderer.render( &mut render_pass.forget_lifetime(), clipped_primitives, &screen_descriptor, ); if capture && let Some(capture_state) = &mut self.screen_capture_state { capture_buffer = Some(capture_state.copy_textures( &render_state.device, &output_frame, &mut encoder, )); } } let encoded = { profiling::scope!("CommandEncoder::finish"); encoder.finish() }; // Submit the commands: both the main buffer and user-defined ones. { profiling::scope!("Queue::submit"); // wgpu doesn't document where vsync can happen. Maybe here? let start = web_time::Instant::now(); render_state .queue .submit(user_cmd_bufs.into_iter().chain([encoded])); vsync_sec += start.elapsed().as_secs_f32(); }; // Free textures marked for destruction **after** queue submit since they might still be used in the current frame. // Calling `wgpu::Texture::destroy` on a texture that is still in use would invalidate the command buffer(s) it is used in. // However, once we called `wgpu::Queue::submit`, it is up for wgpu to determine how long the underlying gpu resource has to live. { let mut renderer = render_state.renderer.write(); for id in &textures_delta.free { renderer.free_texture(id); } } if let Some(capture_buffer) = capture_buffer && let Some(screen_capture_state) = &mut self.screen_capture_state { screen_capture_state.read_screen_rgba( self.context.clone(), capture_buffer, capture_data, self.capture_tx.clone(), viewport_id, ); } { profiling::scope!("present"); // wgpu doesn't document where vsync can happen. Maybe here? let start = web_time::Instant::now(); output_frame.present(); vsync_sec += start.elapsed().as_secs_f32(); } vsync_sec } /// Call this at the beginning of each frame to receive the requested screenshots. pub fn handle_screenshots(&self, events: &mut Vec<Event>) { for (viewport_id, user_data, screenshot) in self.capture_rx.try_iter() { let screenshot = Arc::new(screenshot); for data in user_data { events.push(Event::Screenshot { viewport_id, user_data: data, image: Arc::clone(&screenshot), }); } } } pub fn gc_viewports(&mut self, active_viewports: &ViewportIdSet) { self.surfaces.retain(|id, _| active_viewports.contains(id)); self.depth_texture_view .retain(|id, _| active_viewports.contains(id)); self.msaa_texture_view .retain(|id, _| active_viewports.contains(id)); } #[expect(clippy::needless_pass_by_ref_mut, clippy::unused_self)] pub fn destroy(&mut self) { // TODO(emilk): something here? } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui-wgpu/src/lib.rs
crates/egui-wgpu/src/lib.rs
//! This crates provides bindings between [`egui`](https://github.com/emilk/egui) and [wgpu](https://crates.io/crates/wgpu). //! //! If you're targeting WebGL you also need to turn on the //! `webgl` feature of the `wgpu` crate: //! //! ```toml //! # Enable both WebGL and WebGPU backends on web. //! wgpu = { version = "*", features = ["webgpu", "webgl"] } //! ``` //! //! You can control whether WebGL or WebGPU will be picked at runtime by configuring //! [`WgpuConfiguration::wgpu_setup`]. //! The default is to prefer WebGPU and fall back on WebGL. //! //! ## Feature flags #![doc = document_features::document_features!()] //! pub use wgpu; /// Low-level painting of [`egui`](https://github.com/emilk/egui) on [`wgpu`]. mod renderer; mod setup; pub use renderer::*; pub use setup::{NativeAdapterSelectorMethod, WgpuSetup, WgpuSetupCreateNew, WgpuSetupExisting}; /// Helpers for capturing screenshots of the UI. #[cfg(feature = "capture")] pub mod capture; /// Module for painting [`egui`](https://github.com/emilk/egui) with [`wgpu`] on [`winit`]. #[cfg(feature = "winit")] pub mod winit; use std::sync::Arc; use epaint::mutex::RwLock; /// An error produced by egui-wgpu. #[derive(thiserror::Error, Debug)] pub enum WgpuError { #[error(transparent)] RequestAdapterError(#[from] wgpu::RequestAdapterError), #[error("Adapter selection failed: {0}")] CustomNativeAdapterSelectionError(String), #[error("There was no valid format for the surface at all.")] NoSurfaceFormatsAvailable, #[error(transparent)] RequestDeviceError(#[from] wgpu::RequestDeviceError), #[error(transparent)] CreateSurfaceError(#[from] wgpu::CreateSurfaceError), #[cfg(feature = "winit")] #[error(transparent)] HandleError(#[from] ::winit::raw_window_handle::HandleError), } /// Access to the render state for egui. #[derive(Clone)] pub struct RenderState { /// Wgpu adapter used for rendering. pub adapter: wgpu::Adapter, /// All the available adapters. /// /// This is not available on web. /// On web, we always select WebGPU is available, then fall back to WebGL if not. #[cfg(not(target_arch = "wasm32"))] pub available_adapters: Vec<wgpu::Adapter>, /// Wgpu device used for rendering, created from the adapter. pub device: wgpu::Device, /// Wgpu queue used for rendering, created from the adapter. pub queue: wgpu::Queue, /// The target texture format used for presenting to the window. pub target_format: wgpu::TextureFormat, /// Egui renderer responsible for drawing the UI. pub renderer: Arc<RwLock<Renderer>>, } async fn request_adapter( instance: &wgpu::Instance, power_preference: wgpu::PowerPreference, compatible_surface: Option<&wgpu::Surface<'_>>, available_adapters: &[wgpu::Adapter], ) -> Result<wgpu::Adapter, WgpuError> { profiling::function_scope!(); let adapter = instance .request_adapter(&wgpu::RequestAdapterOptions { power_preference, compatible_surface, // We don't expose this as an option right now since it's fairly rarely useful: // * only has an effect on native // * fails if there's no software rasterizer available // * can achieve the same with `native_adapter_selector` force_fallback_adapter: false, }) .await .inspect_err(|_err| { if cfg!(target_arch = "wasm32") { // Nothing to add here } else if available_adapters.is_empty() { if std::env::var("DYLD_LIBRARY_PATH").is_ok() { // DYLD_LIBRARY_PATH can sometimes lead to loading dylibs that cause // us to find zero adapters. Very strange. // I don't want to debug this again. // See https://github.com/rerun-io/rerun/issues/11351 for more log::warn!( "No wgpu adapter found. This could be because DYLD_LIBRARY_PATH causes dylibs to be loaded that interfere with Metal device creation. Try restarting with DYLD_LIBRARY_PATH=''" ); } else { log::info!("No wgpu adapter found"); } } else if available_adapters.len() == 1 { log::info!( "The only available wgpu adapter was not suitable: {}", adapter_info_summary(&available_adapters[0].get_info()) ); } else { log::info!( "No suitable wgpu adapter found out of the {} available ones: {}", available_adapters.len(), describe_adapters(available_adapters) ); } })?; if cfg!(target_arch = "wasm32") { log::debug!( "Picked wgpu adapter: {}", adapter_info_summary(&adapter.get_info()) ); } else { // native: if available_adapters.len() == 1 { log::debug!( "Picked the only available wgpu adapter: {}", adapter_info_summary(&adapter.get_info()) ); } else { log::info!( "There were {} available wgpu adapters: {}", available_adapters.len(), describe_adapters(available_adapters) ); log::debug!( "Picked wgpu adapter: {}", adapter_info_summary(&adapter.get_info()) ); } } Ok(adapter) } impl RenderState { /// Creates a new [`RenderState`], containing everything needed for drawing egui with wgpu. /// /// # Errors /// Wgpu initialization may fail due to incompatible hardware or driver for a given config. pub async fn create( config: &WgpuConfiguration, instance: &wgpu::Instance, compatible_surface: Option<&wgpu::Surface<'static>>, options: RendererOptions, ) -> Result<Self, WgpuError> { profiling::scope!("RenderState::create"); // async yield give bad names using `profile_function` // This is always an empty list on web. #[cfg(not(target_arch = "wasm32"))] let available_adapters = { let backends = if let WgpuSetup::CreateNew(create_new) = &config.wgpu_setup { create_new.instance_descriptor.backends } else { wgpu::Backends::all() }; instance.enumerate_adapters(backends) }; let (adapter, device, queue) = match config.wgpu_setup.clone() { WgpuSetup::CreateNew(WgpuSetupCreateNew { instance_descriptor: _, power_preference, native_adapter_selector: _native_adapter_selector, device_descriptor, }) => { let adapter = { #[cfg(target_arch = "wasm32")] { request_adapter(instance, power_preference, compatible_surface, &[]).await } #[cfg(not(target_arch = "wasm32"))] if let Some(native_adapter_selector) = _native_adapter_selector { native_adapter_selector(&available_adapters, compatible_surface) .map_err(WgpuError::CustomNativeAdapterSelectionError) } else { request_adapter( instance, power_preference, compatible_surface, &available_adapters, ) .await } }?; let (device, queue) = { profiling::scope!("request_device"); adapter .request_device(&(*device_descriptor)(&adapter)) .await? }; (adapter, device, queue) } WgpuSetup::Existing(WgpuSetupExisting { instance: _, adapter, device, queue, }) => (adapter, device, queue), }; let surface_formats = { profiling::scope!("get_capabilities"); compatible_surface.map_or_else( || vec![wgpu::TextureFormat::Rgba8Unorm], |s| s.get_capabilities(&adapter).formats, ) }; let target_format = crate::preferred_framebuffer_format(&surface_formats)?; let renderer = Renderer::new(&device, target_format, options); // On wasm, depending on feature flags, wgpu objects may or may not implement sync. // It doesn't make sense to switch to Rc for that special usecase, so simply disable the lint. #[allow(clippy::allow_attributes, clippy::arc_with_non_send_sync)] // For wasm Ok(Self { adapter, #[cfg(not(target_arch = "wasm32"))] available_adapters, device, queue, target_format, renderer: Arc::new(RwLock::new(renderer)), }) } } fn describe_adapters(adapters: &[wgpu::Adapter]) -> String { if adapters.is_empty() { "(none)".to_owned() } else if adapters.len() == 1 { adapter_info_summary(&adapters[0].get_info()) } else { adapters .iter() .map(|a| format!("{{{}}}", adapter_info_summary(&a.get_info()))) .collect::<Vec<_>>() .join(", ") } } /// Specifies which action should be taken as consequence of a [`wgpu::SurfaceError`] pub enum SurfaceErrorAction { /// Do nothing and skip the current frame. SkipFrame, /// Instructs egui to recreate the surface, then skip the current frame. RecreateSurface, } /// Configuration for using wgpu with eframe or the egui-wgpu winit feature. #[derive(Clone)] pub struct WgpuConfiguration { /// Present mode used for the primary surface. pub present_mode: wgpu::PresentMode, /// Desired maximum number of frames that the presentation engine should queue in advance. /// /// Use `1` for low-latency, and `2` for high-throughput. /// /// See [`wgpu::SurfaceConfiguration::desired_maximum_frame_latency`] for details. /// /// `None` = `wgpu` default. pub desired_maximum_frame_latency: Option<u32>, /// How to create the wgpu adapter & device pub wgpu_setup: WgpuSetup, /// Callback for surface errors. pub on_surface_error: Arc<dyn Fn(wgpu::SurfaceError) -> SurfaceErrorAction + Send + Sync>, } #[test] fn wgpu_config_impl_send_sync() { fn assert_send_sync<T: Send + Sync>() {} assert_send_sync::<WgpuConfiguration>(); } impl std::fmt::Debug for WgpuConfiguration { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let Self { present_mode, desired_maximum_frame_latency, wgpu_setup, on_surface_error: _, } = self; f.debug_struct("WgpuConfiguration") .field("present_mode", &present_mode) .field( "desired_maximum_frame_latency", &desired_maximum_frame_latency, ) .field("wgpu_setup", &wgpu_setup) .finish_non_exhaustive() } } impl Default for WgpuConfiguration { fn default() -> Self { Self { present_mode: wgpu::PresentMode::AutoVsync, desired_maximum_frame_latency: None, wgpu_setup: Default::default(), on_surface_error: Arc::new(|err| { if err == wgpu::SurfaceError::Outdated { // This error occurs when the app is minimized on Windows. // Silently return here to prevent spamming the console with: // "The underlying surface has changed, and therefore the swap chain must be updated" } else { log::warn!("Dropped frame with error: {err}"); } SurfaceErrorAction::SkipFrame }), } } } /// Find the framebuffer format that egui prefers /// /// # Errors /// Returns [`WgpuError::NoSurfaceFormatsAvailable`] if the given list of formats is empty. pub fn preferred_framebuffer_format( formats: &[wgpu::TextureFormat], ) -> Result<wgpu::TextureFormat, WgpuError> { for &format in formats { if matches!( format, wgpu::TextureFormat::Rgba8Unorm | wgpu::TextureFormat::Bgra8Unorm ) { return Ok(format); } } formats .first() .copied() .ok_or(WgpuError::NoSurfaceFormatsAvailable) } /// Take's epi's depth/stencil bits and returns the corresponding wgpu format. pub fn depth_format_from_bits(depth_buffer: u8, stencil_buffer: u8) -> Option<wgpu::TextureFormat> { match (depth_buffer, stencil_buffer) { (0, 8) => Some(wgpu::TextureFormat::Stencil8), (16, 0) => Some(wgpu::TextureFormat::Depth16Unorm), (24, 0) => Some(wgpu::TextureFormat::Depth24Plus), (24, 8) => Some(wgpu::TextureFormat::Depth24PlusStencil8), (32, 0) => Some(wgpu::TextureFormat::Depth32Float), (32, 8) => Some(wgpu::TextureFormat::Depth32FloatStencil8), _ => None, } } // --------------------------------------------------------------------------- /// A human-readable summary about an adapter pub fn adapter_info_summary(info: &wgpu::AdapterInfo) -> String { let wgpu::AdapterInfo { name, vendor, device, device_type, driver, driver_info, backend, } = &info; // Example values: // > name: "llvmpipe (LLVM 16.0.6, 256 bits)", device_type: Cpu, backend: Vulkan, driver: "llvmpipe", driver_info: "Mesa 23.1.6-arch1.4 (LLVM 16.0.6)" // > name: "Apple M1 Pro", device_type: IntegratedGpu, backend: Metal, driver: "", driver_info: "" // > name: "ANGLE (Apple, Apple M1 Pro, OpenGL 4.1)", device_type: IntegratedGpu, backend: Gl, driver: "", driver_info: "" let mut summary = format!("backend: {backend:?}, device_type: {device_type:?}"); if !name.is_empty() { summary += &format!(", name: {name:?}"); } if !driver.is_empty() { summary += &format!(", driver: {driver:?}"); } if !driver_info.is_empty() { summary += &format!(", driver_info: {driver_info:?}"); } if *vendor != 0 { #[cfg(not(target_arch = "wasm32"))] { summary += &format!(", vendor: {} (0x{vendor:04X})", parse_vendor_id(*vendor)); } #[cfg(target_arch = "wasm32")] { summary += &format!(", vendor: 0x{vendor:04X}"); } } if *device != 0 { summary += &format!(", device: 0x{device:02X}"); } summary } /// Tries to parse the adapter's vendor ID to a human-readable string. #[cfg(not(target_arch = "wasm32"))] pub fn parse_vendor_id(vendor_id: u32) -> &'static str { match vendor_id { wgpu::hal::auxil::db::amd::VENDOR => "AMD", wgpu::hal::auxil::db::apple::VENDOR => "Apple", wgpu::hal::auxil::db::arm::VENDOR => "ARM", wgpu::hal::auxil::db::broadcom::VENDOR => "Broadcom", wgpu::hal::auxil::db::imgtec::VENDOR => "Imagination Technologies", wgpu::hal::auxil::db::intel::VENDOR => "Intel", wgpu::hal::auxil::db::mesa::VENDOR => "Mesa", wgpu::hal::auxil::db::nvidia::VENDOR => "NVIDIA", wgpu::hal::auxil::db::qualcomm::VENDOR => "Qualcomm", _ => "Unknown", } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui-wgpu/src/renderer.rs
crates/egui-wgpu/src/renderer.rs
#![expect(clippy::unwrap_used)] // TODO(emilk): avoid unwraps use std::{borrow::Cow, num::NonZeroU64, ops::Range}; use ahash::HashMap; use bytemuck::Zeroable as _; use epaint::{PaintCallbackInfo, Primitive, Vertex, emath::NumExt as _}; use wgpu::util::DeviceExt as _; // Only implements Send + Sync on wasm32 in order to allow storing wgpu resources on the type map. #[cfg(not(all( target_arch = "wasm32", not(feature = "fragile-send-sync-non-atomic-wasm"), )))] /// You can use this for storage when implementing [`CallbackTrait`]. pub type CallbackResources = type_map::concurrent::TypeMap; #[cfg(all( target_arch = "wasm32", not(feature = "fragile-send-sync-non-atomic-wasm"), ))] /// You can use this for storage when implementing [`CallbackTrait`]. pub type CallbackResources = type_map::TypeMap; /// You can use this to do custom [`wgpu`] rendering in an egui app. /// /// Implement [`CallbackTrait`] and call [`Callback::new_paint_callback`]. /// /// This can be turned into a [`epaint::PaintCallback`] and [`epaint::Shape`]. pub struct Callback(Box<dyn CallbackTrait>); impl Callback { /// Creates a new [`epaint::PaintCallback`] from a callback trait instance. pub fn new_paint_callback( rect: epaint::emath::Rect, callback: impl CallbackTrait + 'static, ) -> epaint::PaintCallback { epaint::PaintCallback { rect, callback: std::sync::Arc::new(Self(Box::new(callback))), } } } /// A callback trait that can be used to compose an [`epaint::PaintCallback`] via [`Callback`] /// for custom WGPU rendering. /// /// Callbacks in [`Renderer`] are done in three steps: /// * [`CallbackTrait::prepare`]: called for all registered callbacks before the main egui render pass. /// * [`CallbackTrait::finish_prepare`]: called for all registered callbacks after all callbacks finished calling prepare. /// * [`CallbackTrait::paint`]: called for all registered callbacks during the main egui render pass. /// /// Each callback has access to an instance of [`CallbackResources`] that is stored in the [`Renderer`]. /// This can be used to store wgpu resources that need to be accessed during the [`CallbackTrait::paint`] step. /// /// The callbacks implementing [`CallbackTrait`] itself must always be Send + Sync, but resources stored in /// [`Renderer::callback_resources`] are not required to implement Send + Sync when building for wasm. /// (this is because wgpu stores references to the JS heap in most of its resources which can not be shared with other threads). /// /// /// # Command submission /// /// ## Command Encoder /// /// The passed-in [`wgpu::CommandEncoder`] is egui's and can be used directly to register /// wgpu commands for simple use cases. /// This allows reusing the same [`wgpu::CommandEncoder`] for all callbacks and egui /// rendering itself. /// /// ## Command Buffers /// /// For more complicated use cases, one can also return a list of arbitrary /// [`wgpu::CommandBuffer`]s and have complete control over how they get created and fed. /// In particular, this gives an opportunity to parallelize command registration and /// prevents a faulty callback from poisoning the main wgpu pipeline. /// /// When using eframe, the main egui command buffer, as well as all user-defined /// command buffers returned by this function, are guaranteed to all be submitted /// at once in a single call. /// /// Command Buffers returned by [`CallbackTrait::finish_prepare`] will always be issued *after* /// those returned by [`CallbackTrait::prepare`]. /// Order within command buffers returned by [`CallbackTrait::prepare`] is dependent /// on the order the respective [`epaint::Shape::Callback`]s were submitted in. /// /// # Example /// /// See the [`custom3d_wgpu`](https://github.com/emilk/egui/blob/main/crates/egui_demo_app/src/apps/custom3d_wgpu.rs) demo source for a detailed usage example. pub trait CallbackTrait: Send + Sync { fn prepare( &self, _device: &wgpu::Device, _queue: &wgpu::Queue, _screen_descriptor: &ScreenDescriptor, _egui_encoder: &mut wgpu::CommandEncoder, _callback_resources: &mut CallbackResources, ) -> Vec<wgpu::CommandBuffer> { Vec::new() } /// Called after all [`CallbackTrait::prepare`] calls are done. fn finish_prepare( &self, _device: &wgpu::Device, _queue: &wgpu::Queue, _egui_encoder: &mut wgpu::CommandEncoder, _callback_resources: &mut CallbackResources, ) -> Vec<wgpu::CommandBuffer> { Vec::new() } /// Called after all [`CallbackTrait::finish_prepare`] calls are done. /// /// It is given access to the [`wgpu::RenderPass`] so that it can issue draw commands /// into the same [`wgpu::RenderPass`] that is used for all other egui elements. fn paint( &self, info: PaintCallbackInfo, render_pass: &mut wgpu::RenderPass<'static>, callback_resources: &CallbackResources, ); } /// Information about the screen used for rendering. pub struct ScreenDescriptor { /// Size of the window in physical pixels. pub size_in_pixels: [u32; 2], /// High-DPI scale factor (pixels per point). pub pixels_per_point: f32, } impl ScreenDescriptor { /// size in "logical" points fn screen_size_in_points(&self) -> [f32; 2] { [ self.size_in_pixels[0] as f32 / self.pixels_per_point, self.size_in_pixels[1] as f32 / self.pixels_per_point, ] } } /// Uniform buffer used when rendering. #[derive(Clone, Copy, Debug, PartialEq, bytemuck::Pod, bytemuck::Zeroable)] #[repr(C)] struct UniformBuffer { screen_size_in_points: [f32; 2], dithering: u32, /// 1 to do manual filtering for more predictable kittest snapshot images. /// /// See also <https://github.com/emilk/egui/issues/5295>. predictable_texture_filtering: u32, } struct SlicedBuffer { buffer: wgpu::Buffer, slices: Vec<Range<usize>>, capacity: wgpu::BufferAddress, } pub struct Texture { /// The texture may be None if the `TextureId` is just a handle to a user-provided bind-group. pub texture: Option<wgpu::Texture>, /// Bindgroup for the texture + sampler. pub bind_group: wgpu::BindGroup, /// Options describing the sampler used in the bind group. This may be None if the `TextureId` /// is just a handle to a user-provided bind-group. pub options: Option<epaint::textures::TextureOptions>, } /// Ways to configure [`Renderer`] during creation. #[derive(Clone, Copy, Debug)] pub struct RendererOptions { /// Set the level of the multisampling anti-aliasing (MSAA). /// /// Must be a power-of-two. Higher = more smooth 3D. /// /// A value of `0` or `1` turns it off (default). /// /// `egui` already performs anti-aliasing via "feathering" /// (controlled by [`egui::epaint::TessellationOptions`]), /// but if you are embedding 3D in egui you may want to turn on multisampling. pub msaa_samples: u32, /// What format to use for the depth and stencil buffers, /// e.g. [`wgpu::TextureFormat::Depth32FloatStencil8`]. /// /// egui doesn't need depth/stencil, so the default value is `None` (no depth or stancil buffers). pub depth_stencil_format: Option<wgpu::TextureFormat>, /// Controls whether to apply dithering to minimize banding artifacts. /// /// Dithering assumes an sRGB output and thus will apply noise to any input value that lies between /// two 8bit values after applying the sRGB OETF function, i.e. if it's not a whole 8bit value in "gamma space". /// This means that only inputs from texture interpolation and vertex colors should be affected in practice. /// /// Defaults to true. pub dithering: bool, /// Perform texture filtering in software? /// /// This is useful when you want predictable rendering across /// different hardware, e.g. for kittest snapshots. /// /// Default is `false`. /// /// See also <https://github.com/emilk/egui/issues/5295>. pub predictable_texture_filtering: bool, } impl RendererOptions { /// Set options that produce the most predicatable output. /// /// Useful for image snapshot tests. pub const PREDICTABLE: Self = Self { msaa_samples: 1, depth_stencil_format: None, dithering: false, predictable_texture_filtering: true, }; } impl Default for RendererOptions { fn default() -> Self { Self { msaa_samples: 0, depth_stencil_format: None, dithering: true, predictable_texture_filtering: false, } } } /// Renderer for a egui based GUI. pub struct Renderer { pipeline: wgpu::RenderPipeline, index_buffer: SlicedBuffer, vertex_buffer: SlicedBuffer, uniform_buffer: wgpu::Buffer, previous_uniform_buffer_content: UniformBuffer, uniform_bind_group: wgpu::BindGroup, texture_bind_group_layout: wgpu::BindGroupLayout, /// Map of egui texture IDs to textures and their associated bindgroups (texture view + /// sampler). The texture may be None if the `TextureId` is just a handle to a user-provided /// sampler. textures: HashMap<epaint::TextureId, Texture>, next_user_texture_id: u64, samplers: HashMap<epaint::textures::TextureOptions, wgpu::Sampler>, options: RendererOptions, /// Storage for resources shared with all invocations of [`CallbackTrait`]'s methods. /// /// See also [`CallbackTrait`]. pub callback_resources: CallbackResources, } impl Renderer { /// Creates a renderer for a egui UI. /// /// `output_color_format` should preferably be [`wgpu::TextureFormat::Rgba8Unorm`] or /// [`wgpu::TextureFormat::Bgra8Unorm`], i.e. in gamma-space. pub fn new( device: &wgpu::Device, output_color_format: wgpu::TextureFormat, options: RendererOptions, ) -> Self { profiling::function_scope!(); let shader = wgpu::ShaderModuleDescriptor { label: Some("egui"), source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("egui.wgsl"))), }; let module = { profiling::scope!("create_shader_module"); device.create_shader_module(shader) }; let uniform_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("egui_uniform_buffer"), contents: bytemuck::cast_slice(&[UniformBuffer { screen_size_in_points: [0.0, 0.0], dithering: u32::from(options.dithering), predictable_texture_filtering: u32::from(options.predictable_texture_filtering), }]), usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, }); let uniform_bind_group_layout = { profiling::scope!("create_bind_group_layout"); device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("egui_uniform_bind_group_layout"), entries: &[wgpu::BindGroupLayoutEntry { binding: 0, visibility: wgpu::ShaderStages::VERTEX | wgpu::ShaderStages::FRAGMENT, ty: wgpu::BindingType::Buffer { has_dynamic_offset: false, min_binding_size: NonZeroU64::new(std::mem::size_of::<UniformBuffer>() as _), ty: wgpu::BufferBindingType::Uniform, }, count: None, }], }) }; let uniform_bind_group = { profiling::scope!("create_bind_group"); device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("egui_uniform_bind_group"), layout: &uniform_bind_group_layout, entries: &[wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { buffer: &uniform_buffer, offset: 0, size: None, }), }], }) }; let texture_bind_group_layout = { profiling::scope!("create_bind_group_layout"); device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("egui_texture_bind_group_layout"), entries: &[ wgpu::BindGroupLayoutEntry { binding: 0, visibility: wgpu::ShaderStages::FRAGMENT, ty: wgpu::BindingType::Texture { multisampled: false, sample_type: wgpu::TextureSampleType::Float { filterable: true }, view_dimension: wgpu::TextureViewDimension::D2, }, count: None, }, wgpu::BindGroupLayoutEntry { binding: 1, visibility: wgpu::ShaderStages::FRAGMENT, ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), count: None, }, ], }) }; let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("egui_pipeline_layout"), bind_group_layouts: &[&uniform_bind_group_layout, &texture_bind_group_layout], push_constant_ranges: &[], }); let depth_stencil = options .depth_stencil_format .map(|format| wgpu::DepthStencilState { format, depth_write_enabled: false, depth_compare: wgpu::CompareFunction::Always, stencil: wgpu::StencilState::default(), bias: wgpu::DepthBiasState::default(), }); let pipeline = { profiling::scope!("create_render_pipeline"); device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: Some("egui_pipeline"), layout: Some(&pipeline_layout), vertex: wgpu::VertexState { entry_point: Some("vs_main"), module: &module, buffers: &[wgpu::VertexBufferLayout { array_stride: 5 * 4, step_mode: wgpu::VertexStepMode::Vertex, // 0: vec2 position // 1: vec2 texture coordinates // 2: uint color attributes: &wgpu::vertex_attr_array![0 => Float32x2, 1 => Float32x2, 2 => Uint32], }], compilation_options: wgpu::PipelineCompilationOptions::default() }, primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, unclipped_depth: false, conservative: false, cull_mode: None, front_face: wgpu::FrontFace::default(), polygon_mode: wgpu::PolygonMode::default(), strip_index_format: None, }, depth_stencil, multisample: wgpu::MultisampleState { alpha_to_coverage_enabled: false, count: options.msaa_samples.max(1), mask: !0, }, fragment: Some(wgpu::FragmentState { module: &module, entry_point: Some(if output_color_format.is_srgb() { log::warn!("Detected a linear (sRGBA aware) framebuffer {output_color_format:?}. egui prefers Rgba8Unorm or Bgra8Unorm"); "fs_main_linear_framebuffer" } else { "fs_main_gamma_framebuffer" // this is what we prefer }), targets: &[Some(wgpu::ColorTargetState { format: output_color_format, blend: Some(wgpu::BlendState { color: wgpu::BlendComponent { src_factor: wgpu::BlendFactor::One, dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha, operation: wgpu::BlendOperation::Add, }, alpha: wgpu::BlendComponent { src_factor: wgpu::BlendFactor::OneMinusDstAlpha, dst_factor: wgpu::BlendFactor::One, operation: wgpu::BlendOperation::Add, }, }), write_mask: wgpu::ColorWrites::ALL, })], compilation_options: wgpu::PipelineCompilationOptions::default() }), multiview: None, cache: None, } ) }; const VERTEX_BUFFER_START_CAPACITY: wgpu::BufferAddress = (std::mem::size_of::<Vertex>() * 1024) as _; const INDEX_BUFFER_START_CAPACITY: wgpu::BufferAddress = (std::mem::size_of::<u32>() * 1024 * 3) as _; Self { pipeline, vertex_buffer: SlicedBuffer { buffer: create_vertex_buffer(device, VERTEX_BUFFER_START_CAPACITY), slices: Vec::with_capacity(64), capacity: VERTEX_BUFFER_START_CAPACITY, }, index_buffer: SlicedBuffer { buffer: create_index_buffer(device, INDEX_BUFFER_START_CAPACITY), slices: Vec::with_capacity(64), capacity: INDEX_BUFFER_START_CAPACITY, }, uniform_buffer, // Buffers on wgpu are zero initialized, so this is indeed its current state! previous_uniform_buffer_content: UniformBuffer::zeroed(), uniform_bind_group, texture_bind_group_layout, textures: HashMap::default(), next_user_texture_id: 0, samplers: HashMap::default(), options, callback_resources: CallbackResources::default(), } } /// Executes the egui renderer onto an existing wgpu renderpass. /// /// Note that the lifetime of `render_pass` is `'static` which requires a call to [`wgpu::RenderPass::forget_lifetime`]. /// This allows users to pass resources that live outside of the callback resources to the render pass. /// The render pass internally keeps all referenced resources alive as long as necessary. /// The only consequence of `forget_lifetime` is that any operation on the parent encoder will cause a runtime error /// instead of a compile time error. pub fn render( &self, render_pass: &mut wgpu::RenderPass<'static>, paint_jobs: &[epaint::ClippedPrimitive], screen_descriptor: &ScreenDescriptor, ) { profiling::function_scope!(); let pixels_per_point = screen_descriptor.pixels_per_point; let size_in_pixels = screen_descriptor.size_in_pixels; // Whether or not we need to reset the render pass because a paint callback has just // run. let mut needs_reset = true; let mut index_buffer_slices = self.index_buffer.slices.iter(); let mut vertex_buffer_slices = self.vertex_buffer.slices.iter(); for epaint::ClippedPrimitive { clip_rect, primitive, } in paint_jobs { if needs_reset { render_pass.set_viewport( 0.0, 0.0, size_in_pixels[0] as f32, size_in_pixels[1] as f32, 0.0, 1.0, ); render_pass.set_pipeline(&self.pipeline); render_pass.set_bind_group(0, &self.uniform_bind_group, &[]); needs_reset = false; } { let rect = ScissorRect::new(clip_rect, pixels_per_point, size_in_pixels); if rect.width == 0 || rect.height == 0 { // Skip rendering zero-sized clip areas. if let Primitive::Mesh(_) = primitive { // If this is a mesh, we need to advance the index and vertex buffer iterators: index_buffer_slices.next().unwrap(); vertex_buffer_slices.next().unwrap(); } continue; } render_pass.set_scissor_rect(rect.x, rect.y, rect.width, rect.height); } match primitive { Primitive::Mesh(mesh) => { let index_buffer_slice = index_buffer_slices.next().unwrap(); let vertex_buffer_slice = vertex_buffer_slices.next().unwrap(); if let Some(Texture { bind_group, .. }) = self.textures.get(&mesh.texture_id) { render_pass.set_bind_group(1, bind_group, &[]); render_pass.set_index_buffer( self.index_buffer.buffer.slice( index_buffer_slice.start as u64..index_buffer_slice.end as u64, ), wgpu::IndexFormat::Uint32, ); render_pass.set_vertex_buffer( 0, self.vertex_buffer.buffer.slice( vertex_buffer_slice.start as u64..vertex_buffer_slice.end as u64, ), ); render_pass.draw_indexed(0..mesh.indices.len() as u32, 0, 0..1); } else { log::warn!("Missing texture: {:?}", mesh.texture_id); } } Primitive::Callback(callback) => { let Some(cbfn) = callback.callback.downcast_ref::<Callback>() else { // We already warned in the `prepare` callback continue; }; let info = PaintCallbackInfo { viewport: callback.rect, clip_rect: *clip_rect, pixels_per_point, screen_size_px: size_in_pixels, }; let viewport_px = info.viewport_in_pixels(); if viewport_px.width_px > 0 && viewport_px.height_px > 0 { profiling::scope!("callback"); needs_reset = true; // We're setting a default viewport for the render pass as a // courtesy for the user, so that they don't have to think about // it in the simple case where they just want to fill the whole // paint area. // // The user still has the possibility of setting their own custom // viewport during the paint callback, effectively overriding this // one. render_pass.set_viewport( viewport_px.left_px as f32, viewport_px.top_px as f32, viewport_px.width_px as f32, viewport_px.height_px as f32, 0.0, 1.0, ); cbfn.0.paint(info, render_pass, &self.callback_resources); } } } } render_pass.set_scissor_rect(0, 0, size_in_pixels[0], size_in_pixels[1]); } /// Should be called before [`Self::render`]. pub fn update_texture( &mut self, device: &wgpu::Device, queue: &wgpu::Queue, id: epaint::TextureId, image_delta: &epaint::ImageDelta, ) { profiling::function_scope!(); let width = image_delta.image.width() as u32; let height = image_delta.image.height() as u32; let size = wgpu::Extent3d { width, height, depth_or_array_layers: 1, }; let data_color32 = match &image_delta.image { epaint::ImageData::Color(image) => { assert_eq!( width as usize * height as usize, image.pixels.len(), "Mismatch between texture size and texel count" ); Cow::Borrowed(&image.pixels) } }; let data_bytes: &[u8] = bytemuck::cast_slice(data_color32.as_slice()); let queue_write_data_to_texture = |texture, origin| { profiling::scope!("write_texture"); queue.write_texture( wgpu::TexelCopyTextureInfo { texture, mip_level: 0, origin, aspect: wgpu::TextureAspect::All, }, data_bytes, wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(4 * width), rows_per_image: Some(height), }, size, ); }; // Use same label for all resources associated with this texture id (no point in retyping the type) let label_str = format!("egui_texid_{id:?}"); let label = Some(label_str.as_str()); let (texture, origin, bind_group) = if let Some(pos) = image_delta.pos { // update the existing texture let Texture { texture, bind_group, options, } = self .textures .remove(&id) .expect("Tried to update a texture that has not been allocated yet."); let texture = texture.expect("Tried to update user texture."); let options = options.expect("Tried to update user texture."); let origin = wgpu::Origin3d { x: pos[0] as u32, y: pos[1] as u32, z: 0, }; ( texture, origin, // If the TextureOptions are the same as the previous ones, we can reuse the bind group. Otherwise we // have to recreate it. if image_delta.options == options { Some(bind_group) } else { None }, ) } else { // allocate a new texture let texture = { profiling::scope!("create_texture"); device.create_texture(&wgpu::TextureDescriptor { label, size, mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2, format: wgpu::TextureFormat::Rgba8Unorm, usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, view_formats: &[wgpu::TextureFormat::Rgba8Unorm], }) }; let origin = wgpu::Origin3d::ZERO; (texture, origin, None) }; let bind_group = bind_group.unwrap_or_else(|| { let sampler = self .samplers .entry(image_delta.options) .or_insert_with(|| create_sampler(image_delta.options, device)); device.create_bind_group(&wgpu::BindGroupDescriptor { label, layout: &self.texture_bind_group_layout, entries: &[ wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView( &texture.create_view(&wgpu::TextureViewDescriptor::default()), ), }, wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(sampler), }, ], }) }); queue_write_data_to_texture(&texture, origin); self.textures.insert( id, Texture { texture: Some(texture), bind_group, options: Some(image_delta.options), }, ); } pub fn free_texture(&mut self, id: &epaint::TextureId) { if let Some(texture) = self.textures.remove(id).and_then(|t| t.texture) { texture.destroy(); } } /// Get the WGPU texture and bind group associated to a texture that has been allocated by egui. /// /// This could be used by custom paint hooks to render images that have been added through /// [`epaint::Context::load_texture`](https://docs.rs/egui/latest/egui/struct.Context.html#method.load_texture). pub fn texture(&self, id: &epaint::TextureId) -> Option<&Texture> { self.textures.get(id) } /// Registers a [`wgpu::Texture`] with a [`epaint::TextureId`]. /// /// This enables the application to reference the texture inside an image ui element. /// This effectively enables off-screen rendering inside the egui UI. Texture must have /// the texture format [`wgpu::TextureFormat::Rgba8Unorm`]. pub fn register_native_texture( &mut self, device: &wgpu::Device, texture: &wgpu::TextureView, texture_filter: wgpu::FilterMode, ) -> epaint::TextureId { self.register_native_texture_with_sampler_options( device, texture, wgpu::SamplerDescriptor { label: Some(format!("egui_user_image_{}", self.next_user_texture_id).as_str()), mag_filter: texture_filter, min_filter: texture_filter, ..Default::default() }, ) } /// Registers a [`wgpu::Texture`] with an existing [`epaint::TextureId`]. /// /// This enables applications to reuse [`epaint::TextureId`]s. pub fn update_egui_texture_from_wgpu_texture( &mut self, device: &wgpu::Device, texture: &wgpu::TextureView, texture_filter: wgpu::FilterMode, id: epaint::TextureId, ) { self.update_egui_texture_from_wgpu_texture_with_sampler_options( device, texture, wgpu::SamplerDescriptor { label: Some(format!("egui_user_image_{}", self.next_user_texture_id).as_str()), mag_filter: texture_filter, min_filter: texture_filter, ..Default::default() }, id, ); } /// Registers a [`wgpu::Texture`] with a [`epaint::TextureId`] while also accepting custom /// [`wgpu::SamplerDescriptor`] options. /// /// This allows applications to specify individual minification/magnification filters as well as /// custom mipmap and tiling options. /// /// The texture must have the format [`wgpu::TextureFormat::Rgba8Unorm`]. /// Any compare function supplied in the [`wgpu::SamplerDescriptor`] will be ignored. #[expect(clippy::needless_pass_by_value)] // false positive pub fn register_native_texture_with_sampler_options( &mut self, device: &wgpu::Device, texture: &wgpu::TextureView, sampler_descriptor: wgpu::SamplerDescriptor<'_>, ) -> epaint::TextureId { profiling::function_scope!(); let sampler = device.create_sampler(&wgpu::SamplerDescriptor { compare: None, ..sampler_descriptor }); let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some(format!("egui_user_image_{}", self.next_user_texture_id).as_str()), layout: &self.texture_bind_group_layout, entries: &[ wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(texture), },
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
true
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui-wgpu/src/capture.rs
crates/egui-wgpu/src/capture.rs
use egui::{UserData, ViewportId}; use epaint::ColorImage; use std::sync::{Arc, mpsc}; use wgpu::{BindGroupLayout, MultisampleState, StoreOp}; /// A texture and a buffer for reading the rendered frame back to the cpu. /// /// The texture is required since [`wgpu::TextureUsages::COPY_SRC`] is not an allowed /// flag for the surface texture on all platforms. This means that anytime we want to /// capture the frame, we first render it to this texture, and then we can copy it to /// both the surface texture (via a render pass) and the buffer (via a texture to buffer copy), /// from where we can pull it back /// to the cpu. pub struct CaptureState { padding: BufferPadding, pub texture: wgpu::Texture, pipeline: wgpu::RenderPipeline, bind_group: wgpu::BindGroup, } pub type CaptureReceiver = mpsc::Receiver<(ViewportId, Vec<UserData>, ColorImage)>; pub type CaptureSender = mpsc::Sender<(ViewportId, Vec<UserData>, ColorImage)>; pub use mpsc::channel as capture_channel; impl CaptureState { pub fn new(device: &wgpu::Device, surface_texture: &wgpu::Texture) -> Self { let shader = device.create_shader_module(wgpu::include_wgsl!("texture_copy.wgsl")); let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: Some("texture_copy"), layout: None, vertex: wgpu::VertexState { module: &shader, entry_point: Some("vs_main"), compilation_options: Default::default(), buffers: &[], }, fragment: Some(wgpu::FragmentState { module: &shader, entry_point: Some("fs_main"), compilation_options: Default::default(), targets: &[Some(surface_texture.format().into())], }), primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() }, depth_stencil: None, multisample: MultisampleState::default(), multiview: None, cache: None, }); let bind_group_layout = pipeline.get_bind_group_layout(0); let (texture, padding, bind_group) = Self::create_texture(device, surface_texture, &bind_group_layout); Self { padding, texture, pipeline, bind_group, } } fn create_texture( device: &wgpu::Device, surface_texture: &wgpu::Texture, layout: &BindGroupLayout, ) -> (wgpu::Texture, BufferPadding, wgpu::BindGroup) { let texture = device.create_texture(&wgpu::TextureDescriptor { label: Some("egui_screen_capture_texture"), size: surface_texture.size(), mip_level_count: surface_texture.mip_level_count(), sample_count: surface_texture.sample_count(), dimension: surface_texture.dimension(), format: surface_texture.format(), usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_SRC, view_formats: &[], }); let padding = BufferPadding::new(surface_texture.width()); let view = texture.create_view(&Default::default()); let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { layout, entries: &[wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&view), }], label: None, }); (texture, padding, bind_group) } /// Updates the [`CaptureState`] if the size of the surface texture has changed pub fn update(&mut self, device: &wgpu::Device, texture: &wgpu::Texture) { if self.texture.size() != texture.size() { let (new_texture, padding, bind_group) = Self::create_texture(device, texture, &self.pipeline.get_bind_group_layout(0)); self.texture = new_texture; self.padding = padding; self.bind_group = bind_group; } } /// Handles copying from the [`CaptureState`] texture to the surface texture and the buffer. /// Pass the returned buffer to [`CaptureState::read_screen_rgba`] to read the data back to the cpu. pub fn copy_textures( &mut self, device: &wgpu::Device, output_frame: &wgpu::SurfaceTexture, encoder: &mut wgpu::CommandEncoder, ) -> wgpu::Buffer { debug_assert_eq!( self.texture.size(), output_frame.texture.size(), "Texture sizes must match, `CaptureState::update` was probably not called" ); // It would be more efficient to reuse the Buffer, e.g. via some kind of ring buffer, but // for most screenshot use cases this should be fine. When taking many screenshots (e.g. for a video) // it might make sense to revisit this and implement a more efficient solution. #[allow(clippy::allow_attributes, clippy::arc_with_non_send_sync)] // For wasm let buffer = device.create_buffer(&wgpu::BufferDescriptor { label: Some("egui_screen_capture_buffer"), size: (self.padding.padded_bytes_per_row * self.texture.height()) as u64, usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, mapped_at_creation: false, }); let padding = self.padding; let tex = &mut self.texture; let tex_extent = tex.size(); encoder.copy_texture_to_buffer( tex.as_image_copy(), wgpu::TexelCopyBufferInfo { buffer: &buffer, layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(padding.padded_bytes_per_row), rows_per_image: None, }, }, tex_extent, ); let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: Some("texture_copy"), color_attachments: &[Some(wgpu::RenderPassColorAttachment { view: &output_frame.texture.create_view(&Default::default()), resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), store: StoreOp::Store, }, depth_slice: None, })], depth_stencil_attachment: None, occlusion_query_set: None, timestamp_writes: None, }); pass.set_pipeline(&self.pipeline); pass.set_bind_group(0, &self.bind_group, &[]); pass.draw(0..3, 0..1); buffer } /// Handles copying from the [`CaptureState`] texture to the surface texture and the cpu /// This function is non-blocking and will send the data to the given sender when it's ready. /// Pass in the buffer returned from [`CaptureState::copy_textures`]. /// Make sure to call this after the encoder has been submitted. pub fn read_screen_rgba( &self, ctx: egui::Context, buffer: wgpu::Buffer, data: Vec<UserData>, tx: CaptureSender, viewport_id: ViewportId, ) { #[allow(clippy::allow_attributes, clippy::arc_with_non_send_sync)] // For wasm let buffer = Arc::new(buffer); let buffer_clone = Arc::clone(&buffer); let buffer_slice = buffer_clone.slice(..); let format = self.texture.format(); let tex_extent = self.texture.size(); let padding = self.padding; let to_rgba = match format { wgpu::TextureFormat::Rgba8Unorm => [0, 1, 2, 3], wgpu::TextureFormat::Bgra8Unorm => [2, 1, 0, 3], _ => { log::error!( "Screen can't be captured unless the surface format is Rgba8Unorm or Bgra8Unorm. Current surface format is {format:?}" ); return; } }; buffer_slice.map_async(wgpu::MapMode::Read, move |result| { if let Err(err) = result { log::error!("Failed to map buffer for reading: {err}"); return; } let buffer_slice = buffer.slice(..); let mut pixels = Vec::with_capacity((tex_extent.width * tex_extent.height) as usize); for padded_row in buffer_slice .get_mapped_range() .chunks(padding.padded_bytes_per_row as usize) { let row = &padded_row[..padding.unpadded_bytes_per_row as usize]; for color in row.chunks(4) { pixels.push(epaint::Color32::from_rgba_premultiplied( color[to_rgba[0]], color[to_rgba[1]], color[to_rgba[2]], color[to_rgba[3]], )); } } buffer.unmap(); tx.send(( viewport_id, data, ColorImage::new( [tex_extent.width as usize, tex_extent.height as usize], pixels, ), )) .ok(); ctx.request_repaint(); }); } } #[derive(Copy, Clone)] struct BufferPadding { unpadded_bytes_per_row: u32, padded_bytes_per_row: u32, } impl BufferPadding { fn new(width: u32) -> Self { let bytes_per_pixel = std::mem::size_of::<u32>() as u32; let unpadded_bytes_per_row = width * bytes_per_pixel; let padded_bytes_per_row = wgpu::util::align_to(unpadded_bytes_per_row, wgpu::COPY_BYTES_PER_ROW_ALIGNMENT); Self { unpadded_bytes_per_row, padded_bytes_per_row, } } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/eframe/src/lib.rs
crates/eframe/src/lib.rs
//! eframe - the [`egui`] framework crate //! //! If you are planning to write an app for web or native, //! and want to use [`egui`] for everything, then `eframe` is for you! //! //! To get started, see the [examples](https://github.com/emilk/egui/tree/main/examples). //! To learn how to set up `eframe` for web and native, go to <https://github.com/emilk/eframe_template/> and follow the instructions there! //! //! In short, you implement [`App`] (especially [`App::update`]) and then //! call [`crate::run_native`] from your `main.rs`, and/or use `eframe::WebRunner` from your `lib.rs`. //! //! ## Compiling for web //! You need to install the `wasm32` target with `rustup target add wasm32-unknown-unknown`. //! //! Build the `.wasm` using `cargo build --target wasm32-unknown-unknown` //! and then use [`wasm-bindgen`](https://github.com/rustwasm/wasm-bindgen) to generate the JavaScript glue code. //! //! See the [`eframe_template` repository](https://github.com/emilk/eframe_template/) for more. //! //! ## Simplified usage //! If your app is only for native, and you don't need advanced features like state persistence, //! then you can use the simpler function [`run_simple_native`]. //! //! ## Usage, native: //! ``` no_run //! use eframe::egui; //! //! fn main() { //! let native_options = eframe::NativeOptions::default(); //! eframe::run_native("My egui App", native_options, Box::new(|cc| Ok(Box::new(MyEguiApp::new(cc))))); //! } //! //! #[derive(Default)] //! struct MyEguiApp {} //! //! impl MyEguiApp { //! fn new(cc: &eframe::CreationContext<'_>) -> Self { //! // Customize egui here with cc.egui_ctx.set_fonts and cc.egui_ctx.set_global_style. //! // Restore app state using cc.storage (requires the "persistence" feature). //! // Use the cc.gl (a glow::Context) to create graphics shaders and buffers that you can use //! // for e.g. egui::PaintCallback. //! Self::default() //! } //! } //! //! impl eframe::App for MyEguiApp { //! fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { //! egui::CentralPanel::default().show_inside(ui, |ui| { //! ui.heading("Hello World!"); //! }); //! } //! } //! ``` //! //! ## Usage, web: //! ``` no_run //! # #[cfg(target_arch = "wasm32")] //! use wasm_bindgen::prelude::*; //! //! /// Your handle to the web app from JavaScript. //! # #[cfg(target_arch = "wasm32")] //! #[derive(Clone)] //! #[wasm_bindgen] //! pub struct WebHandle { //! runner: eframe::WebRunner, //! } //! //! # #[cfg(target_arch = "wasm32")] //! #[wasm_bindgen] //! impl WebHandle { //! /// Installs a panic hook, then returns. //! #[expect(clippy::new_without_default)] //! #[wasm_bindgen(constructor)] //! pub fn new() -> Self { //! // Redirect [`log`] message to `console.log` and friends: //! eframe::WebLogger::init(log::LevelFilter::Debug).ok(); //! //! Self { //! runner: eframe::WebRunner::new(), //! } //! } //! //! /// Call this once from JavaScript to start your app. //! #[wasm_bindgen] //! pub async fn start(&self, canvas: web_sys::HtmlCanvasElement) -> Result<(), wasm_bindgen::JsValue> { //! self.runner //! .start( //! canvas, //! eframe::WebOptions::default(), //! Box::new(|cc| Ok(Box::new(MyEguiApp::new(cc))),) //! ) //! .await //! } //! //! // The following are optional: //! //! /// Shut down eframe and clean up resources. //! #[wasm_bindgen] //! pub fn destroy(&self) { //! self.runner.destroy(); //! } //! //! /// Example on how to call into your app from JavaScript. //! #[wasm_bindgen] //! pub fn example(&self) { //! if let Some(app) = self.runner.app_mut::<MyEguiApp>() { //! app.example(); //! } //! } //! //! /// The JavaScript can check whether or not your app has crashed: //! #[wasm_bindgen] //! pub fn has_panicked(&self) -> bool { //! self.runner.has_panicked() //! } //! //! #[wasm_bindgen] //! pub fn panic_message(&self) -> Option<String> { //! self.runner.panic_summary().map(|s| s.message()) //! } //! //! #[wasm_bindgen] //! pub fn panic_callstack(&self) -> Option<String> { //! self.runner.panic_summary().map(|s| s.callstack()) //! } //! } //! ``` //! //! ## Feature flags #![doc = document_features::document_features!()] //! //! ## Instrumentation //! This crate supports using the [profiling](https://crates.io/crates/profiling) crate for instrumentation. //! You can enable features on the profiling crates in your application to add instrumentation for all //! crates that support it, including egui. See the profiling crate docs for more information. //! ```toml //! [dependencies] //! profiling = "1.0" //! [features] //! profile-with-puffin = ["profiling/profile-with-puffin"] //! ``` //! #![warn(missing_docs)] // let's keep eframe well-documented // Limitation imposed by `accesskit_winit`: // https://github.com/AccessKit/accesskit/tree/accesskit-v0.18.0/platforms/winit#android-activity-compatibility` #[cfg(all( target_os = "android", feature = "accesskit", feature = "android-native-activity" ))] compile_error!("`accesskit` feature is only available with `android-game-activity`"); // Re-export all useful libraries: pub use {egui, egui::emath, egui::epaint}; #[cfg(feature = "glow")] pub use {egui_glow, glow}; #[cfg(feature = "wgpu_no_default_features")] pub use {egui_wgpu, wgpu}; mod epi; // Re-export everything in `epi` so `eframe` users don't have to care about what `epi` is: pub use epi::*; pub(crate) mod stopwatch; // ---------------------------------------------------------------------------- // When compiling for web #[cfg(target_arch = "wasm32")] pub use wasm_bindgen; #[cfg(target_arch = "wasm32")] pub use web_sys; #[cfg(target_arch = "wasm32")] pub mod web; #[cfg(target_arch = "wasm32")] pub use web::{WebLogger, WebRunner}; // ---------------------------------------------------------------------------- // When compiling natively #[cfg(not(target_arch = "wasm32"))] #[cfg(any(feature = "glow", feature = "wgpu_no_default_features"))] mod native; #[cfg(not(target_arch = "wasm32"))] #[cfg(any(feature = "glow", feature = "wgpu_no_default_features"))] pub use native::run::EframeWinitApplication; #[cfg(not(any(target_arch = "wasm32", target_os = "ios")))] #[cfg(any(feature = "glow", feature = "wgpu_no_default_features"))] pub use native::run::EframePumpStatus; #[cfg(not(target_arch = "wasm32"))] #[cfg(any(feature = "glow", feature = "wgpu_no_default_features"))] #[cfg(feature = "persistence")] pub use native::file_storage::storage_dir; #[cfg(not(target_arch = "wasm32"))] pub mod icon_data; /// This is how you start a native (desktop) app. /// /// The first argument is name of your app, which is an identifier /// used for the save location of persistence (see [`App::save`]). /// It is also used as the application id on wayland. /// If you set no title on the viewport, the app id will be used /// as the title. /// /// For details about application ID conventions, see the /// [Desktop Entry Spec](https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html#desktop-file-id) /// /// Call from `fn main` like this: /// ``` no_run /// use eframe::egui; /// /// fn main() -> eframe::Result { /// let native_options = eframe::NativeOptions::default(); /// eframe::run_native("MyApp", native_options, Box::new(|cc| Ok(Box::new(MyEguiApp::new(cc))))) /// } /// /// #[derive(Default)] /// struct MyEguiApp {} /// /// impl MyEguiApp { /// fn new(cc: &eframe::CreationContext<'_>) -> Self { /// // Customize egui here with cc.egui_ctx.set_fonts and cc.egui_ctx.set_global_style. /// // Restore app state using cc.storage (requires the "persistence" feature). /// // Use the cc.gl (a glow::Context) to create graphics shaders and buffers that you can use /// // for e.g. egui::PaintCallback. /// Self::default() /// } /// } /// /// impl eframe::App for MyEguiApp { /// fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { /// egui::CentralPanel::default().show_inside(ui, |ui| { /// ui.heading("Hello World!"); /// }); /// } /// } /// ``` /// /// # Errors /// This function can fail if we fail to set up a graphics context. #[cfg(not(target_arch = "wasm32"))] #[cfg(any(feature = "glow", feature = "wgpu_no_default_features"))] #[allow(clippy::allow_attributes, clippy::needless_pass_by_value)] pub fn run_native( app_name: &str, mut native_options: NativeOptions, app_creator: AppCreator<'_>, ) -> Result { let renderer = init_native(app_name, &mut native_options); match renderer { #[cfg(feature = "glow")] Renderer::Glow => { log::debug!("Using the glow renderer"); native::run::run_glow(app_name, native_options, app_creator) } #[cfg(feature = "wgpu_no_default_features")] Renderer::Wgpu => { log::debug!("Using the wgpu renderer"); native::run::run_wgpu(app_name, native_options, app_creator) } } } /// Provides a proxy for your native eframe application to run on your own event loop. /// /// See `run_native` for details about `app_name`. /// /// Call from `fn main` like this: /// ``` no_run /// use eframe::{egui, UserEvent}; /// use winit::event_loop::{ControlFlow, EventLoop}; /// /// fn main() -> eframe::Result { /// let native_options = eframe::NativeOptions::default(); /// let eventloop = EventLoop::<UserEvent>::with_user_event().build()?; /// eventloop.set_control_flow(ControlFlow::Poll); /// /// let mut winit_app = eframe::create_native( /// "MyExtApp", /// native_options, /// Box::new(|cc| Ok(Box::new(MyEguiApp::new(cc)))), /// &eventloop, /// ); /// /// eventloop.run_app(&mut winit_app)?; /// /// Ok(()) /// } /// /// #[derive(Default)] /// struct MyEguiApp {} /// /// impl MyEguiApp { /// fn new(cc: &eframe::CreationContext<'_>) -> Self { /// Self::default() /// } /// } /// /// impl eframe::App for MyEguiApp { /// fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { /// egui::CentralPanel::default().show_inside(ui, |ui| { /// ui.heading("Hello World!"); /// }); /// } /// } /// ``` /// /// See the `external_eventloop` example for a more complete example. #[cfg(not(target_arch = "wasm32"))] #[cfg(any(feature = "glow", feature = "wgpu_no_default_features"))] pub fn create_native<'a>( app_name: &str, mut native_options: NativeOptions, app_creator: AppCreator<'a>, event_loop: &winit::event_loop::EventLoop<UserEvent>, ) -> EframeWinitApplication<'a> { let renderer = init_native(app_name, &mut native_options); match renderer { #[cfg(feature = "glow")] Renderer::Glow => { log::debug!("Using the glow renderer"); EframeWinitApplication::new(native::run::create_glow( app_name, native_options, app_creator, event_loop, )) } #[cfg(feature = "wgpu_no_default_features")] Renderer::Wgpu => { log::debug!("Using the wgpu renderer"); EframeWinitApplication::new(native::run::create_wgpu( app_name, native_options, app_creator, event_loop, )) } } } #[cfg(not(target_arch = "wasm32"))] #[cfg(any(feature = "glow", feature = "wgpu_no_default_features"))] fn init_native(app_name: &str, native_options: &mut NativeOptions) -> Renderer { #[cfg(not(feature = "__screenshot"))] assert!( std::env::var("EFRAME_SCREENSHOT_TO").is_err(), "EFRAME_SCREENSHOT_TO found without compiling with the '__screenshot' feature" ); if native_options.viewport.title.is_none() { native_options.viewport.title = Some(app_name.to_owned()); } let renderer = native_options.renderer; #[cfg(all(feature = "glow", feature = "wgpu_no_default_features"))] { match native_options.renderer { Renderer::Glow => "glow", Renderer::Wgpu => "wgpu", }; log::info!("Both the glow and wgpu renderers are available. Using {renderer}."); } renderer } // ---------------------------------------------------------------------------- /// The simplest way to get started when writing a native app. /// /// This does NOT support persistence of custom user data. For that you need to use [`run_native`]. /// However, it DOES support persistence of egui data (window positions and sizes, how far the user has scrolled in a /// [`ScrollArea`](egui::ScrollArea), etc.) if the persistence feature is enabled. /// /// # Example /// ``` no_run /// fn main() -> eframe::Result { /// // Our application state: /// let mut name = "Arthur".to_owned(); /// let mut age = 42; /// /// let options = eframe::NativeOptions::default(); /// eframe::run_ui_native("My egui App", options, move |ui, _frame| { /// // Wrap everything in a CentralPanel so we get some margins and a background color: /// egui::CentralPanel::default().show_inside(ui, |ui| { /// ui.heading("My egui Application"); /// ui.horizontal(|ui| { /// let name_label = ui.label("Your name: "); /// ui.text_edit_singleline(&mut name) /// .labelled_by(name_label.id); /// }); /// ui.add(egui::Slider::new(&mut age, 0..=120).text("age")); /// if ui.button("Increment").clicked() { /// age += 1; /// } /// ui.label(format!("Hello '{name}', age {age}")); /// }); /// }) /// } /// ``` /// /// # Errors /// This function can fail if we fail to set up a graphics context. #[cfg(not(target_arch = "wasm32"))] #[cfg(any(feature = "glow", feature = "wgpu_no_default_features"))] pub fn run_ui_native( app_name: &str, native_options: NativeOptions, ui_fun: impl FnMut(&mut egui::Ui, &mut Frame) + 'static, ) -> Result { struct SimpleApp<U> { ui_fun: U, } impl<U: FnMut(&mut egui::Ui, &mut Frame) + 'static> App for SimpleApp<U> { fn ui(&mut self, ui: &mut egui::Ui, frame: &mut Frame) { (self.ui_fun)(ui, frame); } } run_native( app_name, native_options, Box::new(|_cc| Ok(Box::new(SimpleApp { ui_fun }))), ) } /// The simplest way to get started when writing a native app. /// /// This does NOT support persistence of custom user data. For that you need to use [`run_native`]. /// However, it DOES support persistence of egui data (window positions and sizes, how far the user has scrolled in a /// [`ScrollArea`](egui::ScrollArea), etc.) if the persistence feature is enabled. /// /// # Example /// ``` no_run /// fn main() -> eframe::Result { /// // Our application state: /// let mut name = "Arthur".to_owned(); /// let mut age = 42; /// /// let options = eframe::NativeOptions::default(); /// eframe::run_simple_native("My egui App", options, move |ctx, _frame| { /// egui::CentralPanel::default().show(ctx, |ui| { /// ui.heading("My egui Application"); /// ui.horizontal(|ui| { /// let name_label = ui.label("Your name: "); /// ui.text_edit_singleline(&mut name) /// .labelled_by(name_label.id); /// }); /// ui.add(egui::Slider::new(&mut age, 0..=120).text("age")); /// if ui.button("Increment").clicked() { /// age += 1; /// } /// ui.label(format!("Hello '{name}', age {age}")); /// }); /// }) /// } /// ``` /// /// # Errors /// This function can fail if we fail to set up a graphics context. #[deprecated = "Use run_ui_native instead"] #[cfg(not(target_arch = "wasm32"))] #[cfg(any(feature = "glow", feature = "wgpu_no_default_features"))] pub fn run_simple_native( app_name: &str, native_options: NativeOptions, update_fun: impl FnMut(&egui::Context, &mut Frame) + 'static, ) -> Result { struct SimpleApp<U> { update_fun: U, } impl<U: FnMut(&egui::Context, &mut Frame) + 'static> App for SimpleApp<U> { fn ui(&mut self, _ui: &mut egui::Ui, _frame: &mut Frame) {} fn update(&mut self, ctx: &egui::Context, frame: &mut Frame) { (self.update_fun)(ctx, frame); } } run_native( app_name, native_options, Box::new(|_cc| Ok(Box::new(SimpleApp { update_fun }))), ) } // ---------------------------------------------------------------------------- /// The different problems that can occur when trying to run `eframe`. #[derive(Debug)] pub enum Error { /// Something went wrong in user code when creating the app. AppCreation(Box<dyn std::error::Error + Send + Sync>), /// An error from [`winit`]. #[cfg(not(target_arch = "wasm32"))] Winit(winit::error::OsError), /// An error from [`winit::event_loop::EventLoop`]. #[cfg(not(target_arch = "wasm32"))] WinitEventLoop(winit::error::EventLoopError), /// An error from [`glutin`] when using [`glow`]. #[cfg(all(feature = "glow", not(target_arch = "wasm32")))] Glutin(glutin::error::Error), /// An error from [`glutin`] when using [`glow`]. #[cfg(all(feature = "glow", not(target_arch = "wasm32")))] NoGlutinConfigs(glutin::config::ConfigTemplate, Box<dyn std::error::Error>), /// An error from [`glutin`] when using [`glow`]. #[cfg(feature = "glow")] OpenGL(egui_glow::PainterError), /// An error from [`wgpu`]. #[cfg(feature = "wgpu_no_default_features")] Wgpu(egui_wgpu::WgpuError), } impl std::error::Error for Error {} #[cfg(not(target_arch = "wasm32"))] impl From<winit::error::OsError> for Error { #[inline] fn from(err: winit::error::OsError) -> Self { Self::Winit(err) } } #[cfg(not(target_arch = "wasm32"))] impl From<winit::error::EventLoopError> for Error { #[inline] fn from(err: winit::error::EventLoopError) -> Self { Self::WinitEventLoop(err) } } #[cfg(all(feature = "glow", not(target_arch = "wasm32")))] impl From<glutin::error::Error> for Error { #[inline] fn from(err: glutin::error::Error) -> Self { Self::Glutin(err) } } #[cfg(feature = "glow")] impl From<egui_glow::PainterError> for Error { #[inline] fn from(err: egui_glow::PainterError) -> Self { Self::OpenGL(err) } } #[cfg(feature = "wgpu_no_default_features")] impl From<egui_wgpu::WgpuError> for Error { #[inline] fn from(err: egui_wgpu::WgpuError) -> Self { Self::Wgpu(err) } } impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::AppCreation(err) => write!(f, "app creation error: {err}"), #[cfg(not(target_arch = "wasm32"))] Self::Winit(err) => { write!(f, "winit error: {err}") } #[cfg(not(target_arch = "wasm32"))] Self::WinitEventLoop(err) => { write!(f, "winit EventLoopError: {err}") } #[cfg(all(feature = "glow", not(target_arch = "wasm32")))] Self::Glutin(err) => { write!(f, "glutin error: {err}") } #[cfg(all(feature = "glow", not(target_arch = "wasm32")))] Self::NoGlutinConfigs(template, err) => { write!( f, "Found no glutin configs matching the template: {template:?}. Error: {err}" ) } #[cfg(feature = "glow")] Self::OpenGL(err) => { write!(f, "egui_glow: {err}") } #[cfg(feature = "wgpu_no_default_features")] Self::Wgpu(err) => { write!(f, "WGPU error: {err}") } } } } /// Short for `Result<T, eframe::Error>`. pub type Result<T = (), E = Error> = std::result::Result<T, E>;
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/eframe/src/epi.rs
crates/eframe/src/epi.rs
//! Platform-agnostic interface for writing apps using [`egui`] (epi = egui programming interface). //! //! `epi` provides interfaces for window management and serialization. //! //! Start by looking at the [`App`] trait, and implement [`App::update`]. #![warn(missing_docs)] // Let's keep `epi` well-documented. #[cfg(target_arch = "wasm32")] use std::any::Any; #[cfg(not(target_arch = "wasm32"))] #[cfg(any(feature = "glow", feature = "wgpu_no_default_features"))] pub use crate::native::winit_integration::UserEvent; #[cfg(not(target_arch = "wasm32"))] use raw_window_handle::{ DisplayHandle, HandleError, HasDisplayHandle, HasWindowHandle, RawDisplayHandle, RawWindowHandle, WindowHandle, }; #[cfg(not(target_arch = "wasm32"))] use static_assertions::assert_not_impl_any; #[cfg(not(target_arch = "wasm32"))] #[cfg(any(feature = "glow", feature = "wgpu_no_default_features"))] pub use winit::{event_loop::EventLoopBuilder, window::WindowAttributes}; /// Hook into the building of an event loop before it is run /// /// You can configure any platform specific details required on top of the default configuration /// done by `EFrame`. #[cfg(not(target_arch = "wasm32"))] #[cfg(any(feature = "glow", feature = "wgpu_no_default_features"))] pub type EventLoopBuilderHook = Box<dyn FnOnce(&mut EventLoopBuilder<UserEvent>)>; /// Hook into the building of a the native window. /// /// You can configure any platform specific details required on top of the default configuration /// done by `eframe`. #[cfg(not(target_arch = "wasm32"))] #[cfg(any(feature = "glow", feature = "wgpu_no_default_features"))] pub type WindowBuilderHook = Box<dyn FnOnce(egui::ViewportBuilder) -> egui::ViewportBuilder>; type DynError = Box<dyn std::error::Error + Send + Sync>; /// This is how your app is created. /// /// You can use the [`CreationContext`] to setup egui, restore state, setup OpenGL things, etc. pub type AppCreator<'app> = Box<dyn 'app + FnOnce(&CreationContext<'_>) -> Result<Box<dyn 'app + App>, DynError>>; /// Data that is passed to [`AppCreator`] that can be used to setup and initialize your app. pub struct CreationContext<'s> { /// The egui Context. /// /// You can use this to customize the look of egui, e.g to call [`egui::Context::set_fonts`], /// [`egui::Context::set_visuals_of`] etc. pub egui_ctx: egui::Context, /// Information about the surrounding environment. pub integration_info: IntegrationInfo, /// You can use the storage to restore app state(requires the "persistence" feature). pub storage: Option<&'s dyn Storage>, /// The [`glow::Context`] allows you to initialize OpenGL resources (e.g. shaders) that /// you might want to use later from a [`egui::PaintCallback`]. /// /// Only available when compiling with the `glow` feature and using [`Renderer::Glow`]. #[cfg(feature = "glow")] pub gl: Option<std::sync::Arc<glow::Context>>, /// The `get_proc_address` wrapper of underlying GL context #[cfg(feature = "glow")] pub get_proc_address: Option<&'s dyn Fn(&std::ffi::CStr) -> *const std::ffi::c_void>, /// The underlying WGPU render state. /// /// Only available when compiling with the `wgpu` feature and using [`Renderer::Wgpu`]. /// /// Can be used to manage GPU resources for custom rendering with WGPU using [`egui::PaintCallback`]s. #[cfg(feature = "wgpu_no_default_features")] pub wgpu_render_state: Option<egui_wgpu::RenderState>, /// Raw platform window handle #[cfg(not(target_arch = "wasm32"))] pub(crate) raw_window_handle: Result<RawWindowHandle, HandleError>, /// Raw platform display handle for window #[cfg(not(target_arch = "wasm32"))] pub(crate) raw_display_handle: Result<RawDisplayHandle, HandleError>, } #[expect(unsafe_code)] #[cfg(not(target_arch = "wasm32"))] impl HasWindowHandle for CreationContext<'_> { fn window_handle(&self) -> Result<WindowHandle<'_>, HandleError> { // Safety: the lifetime is correct. unsafe { Ok(WindowHandle::borrow_raw(self.raw_window_handle.clone()?)) } } } #[expect(unsafe_code)] #[cfg(not(target_arch = "wasm32"))] impl HasDisplayHandle for CreationContext<'_> { fn display_handle(&self) -> Result<DisplayHandle<'_>, HandleError> { // Safety: the lifetime is correct. unsafe { Ok(DisplayHandle::borrow_raw(self.raw_display_handle.clone()?)) } } } impl CreationContext<'_> { /// Create a new empty [CreationContext] for testing [App]s in kittest. #[doc(hidden)] pub fn _new_kittest(egui_ctx: egui::Context) -> Self { Self { egui_ctx, integration_info: IntegrationInfo::mock(), storage: None, #[cfg(feature = "glow")] gl: None, #[cfg(feature = "glow")] get_proc_address: None, #[cfg(feature = "wgpu_no_default_features")] wgpu_render_state: None, #[cfg(not(target_arch = "wasm32"))] raw_window_handle: Err(HandleError::NotSupported), #[cfg(not(target_arch = "wasm32"))] raw_display_handle: Err(HandleError::NotSupported), } } } // ---------------------------------------------------------------------------- /// Implement this trait to write apps that can be compiled for both web/wasm and desktop/native using [`eframe`](https://github.com/emilk/egui/tree/main/crates/eframe). pub trait App { /// Called once before each call to [`Self::ui`], /// and additionally also called when the UI is hidden, but [`egui::Context::request_repaint`] was called. /// /// You may NOT show any ui or do any painting during the call to [`Self::logic`]. /// /// The [`egui::Context`] can be cloned and saved if you like. /// /// To force another call to [`Self::logic`], call [`egui::Context::request_repaint`] at any time (e.g. from another thread). fn logic(&mut self, ctx: &egui::Context, frame: &mut Frame) { _ = (ctx, frame); } /// Called each time the UI needs repainting, which may be many times per second. /// /// The given [`egui::Ui`] has no margin or background color. /// You can wrap your UI code in [`egui::CentralPanel`] or a [`egui::Frame::central_panel`] to remedy this. /// /// The [`egui::Ui::ctx`] can be cloned and saved if you like. /// To force a repaint, call [`egui::Context::request_repaint`] at any time (e.g. from another thread). /// /// This is called for the root viewport ([`egui::ViewportId::ROOT`]). /// Use [`egui::Context::show_viewport_deferred`] to spawn additional viewports (windows). /// (A "viewport" in egui means an native OS window). fn ui(&mut self, ui: &mut egui::Ui, frame: &mut Frame); /// Called each time the UI needs repainting, which may be many times per second. /// /// Put your widgets into a [`egui::Panel`], [`egui::CentralPanel`], [`egui::Window`] or [`egui::Area`]. /// /// The [`egui::Context`] can be cloned and saved if you like. /// /// To force a repaint, call [`egui::Context::request_repaint`] at any time (e.g. from another thread). /// /// This is called for the root viewport ([`egui::ViewportId::ROOT`]). /// Use [`egui::Context::show_viewport_deferred`] to spawn additional viewports (windows). /// (A "viewport" in egui means an native OS window). #[deprecated = "Use Self::ui instead"] fn update(&mut self, ctx: &egui::Context, frame: &mut Frame) { _ = (ctx, frame); } /// Get a handle to the app. /// /// Can be used from web to interact or other external context. /// /// You need to implement this if you want to be able to access the application from JS using [`crate::WebRunner::app_mut`]. /// /// This is needed because downcasting `Box<dyn App>` -> `Box<dyn Any>` to get &`ConcreteApp` is not simple in current rust. /// /// Just copy-paste this as your implementation: /// ```ignore /// #[cfg(target_arch = "wasm32")] /// fn as_any_mut(&mut self) -> Option<&mut dyn std::any::Any> { /// Some(&mut *self) /// } /// ``` #[cfg(target_arch = "wasm32")] fn as_any_mut(&mut self) -> Option<&mut dyn Any> { None } /// Called on shutdown, and perhaps at regular intervals. Allows you to save state. /// /// Only called when the "persistence" feature is enabled. /// /// On web the state is stored to "Local Storage". /// /// On native the path is picked using [`crate::storage_dir`]. /// The path can be customized via [`NativeOptions::persistence_path`]. fn save(&mut self, _storage: &mut dyn Storage) {} /// Called once on shutdown, after [`Self::save`]. /// /// If you need to abort an exit check `ctx.input(|i| i.viewport().close_requested())` /// and respond with [`egui::ViewportCommand::CancelClose`]. /// /// To get a [`glow`] context you need to compile with the `glow` feature flag, /// and run eframe with the glow backend. #[cfg(feature = "glow")] fn on_exit(&mut self, _gl: Option<&glow::Context>) {} /// Called once on shutdown, after [`Self::save`]. /// /// If you need to abort an exit use [`Self::on_close_event`]. #[cfg(not(feature = "glow"))] fn on_exit(&mut self) {} // --------- // Settings: /// Time between automatic calls to [`Self::save`] fn auto_save_interval(&self) -> std::time::Duration { std::time::Duration::from_secs(30) } /// Background color values for the app, e.g. what is sent to `gl.clearColor`. /// /// This is the background of your windows if you don't set a central panel. /// /// ATTENTION: /// Since these float values go to the render as-is, any color space conversion as done /// e.g. by converting from [`egui::Color32`] to [`egui::Rgba`] may cause incorrect results. /// egui recommends that rendering backends use a normal "gamma-space" (non-sRGB-aware) blending, /// which means the values you return here should also be in `sRGB` gamma-space in the 0-1 range. /// You can use [`egui::Color32::to_normalized_gamma_f32`] for this. fn clear_color(&self, _visuals: &egui::Visuals) -> [f32; 4] { // NOTE: a bright gray makes the shadows of the windows look weird. // We use a bit of transparency so that if the user switches on the // `transparent()` option they get immediate results. egui::Color32::from_rgba_unmultiplied(12, 12, 12, 180).to_normalized_gamma_f32() // _visuals.window_fill() would also be a natural choice } /// Controls whether or not the egui memory (window positions etc) will be /// persisted (only if the "persistence" feature is enabled). fn persist_egui_memory(&self) -> bool { true } /// A hook for manipulating or filtering raw input before it is processed by [`Self::update`]. /// /// This function provides a way to modify or filter input events before they are processed by egui. /// /// It can be used to prevent specific keyboard shortcuts or mouse events from being processed by egui. /// /// Additionally, it can be used to inject custom keyboard or mouse events into the input stream, which can be useful for implementing features like a virtual keyboard. /// /// # Arguments /// /// * `_ctx` - The context of the egui, which provides access to the current state of the egui. /// * `_raw_input` - The raw input events that are about to be processed. This can be modified to change the input that egui processes. /// /// # Note /// /// This function does not return a value. Any changes to the input should be made directly to `_raw_input`. fn raw_input_hook(&mut self, _ctx: &egui::Context, _raw_input: &mut egui::RawInput) {} } /// Selects the level of hardware graphics acceleration. #[cfg(not(target_arch = "wasm32"))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum HardwareAcceleration { /// Require graphics acceleration. Required, /// Prefer graphics acceleration, but fall back to software. Preferred, /// Do NOT use graphics acceleration. /// /// On some platforms (macOS) this is ignored and treated the same as [`Self::Preferred`]. Off, } /// Options controlling the behavior of a native window. /// /// Additional windows can be opened using (egui viewports)[`egui::viewport`]. /// /// Set the window title and size using [`Self::viewport`]. /// /// ### Application id /// [`egui::ViewportBuilder::with_app_id`] is used for determining the folder to persist the app to. /// /// On native the path is picked using [`crate::storage_dir`]. /// /// If you don't set an app id, the title argument to [`crate::run_native`] /// will be used as app id instead. #[cfg(not(target_arch = "wasm32"))] pub struct NativeOptions { /// Controls the native window of the root viewport. /// /// This is where you set things like window title and size. /// /// If you don't set an icon, a default egui icon will be used. /// To avoid this, set the icon to [`egui::IconData::default`]. pub viewport: egui::ViewportBuilder, /// Turn on vertical syncing, limiting the FPS to the display refresh rate. /// /// The default is `true`. pub vsync: bool, /// Set the level of the multisampling anti-aliasing (MSAA). /// /// Must be a power-of-two. Higher = more smooth 3D. /// /// A value of `0` turns it off (default). /// /// `egui` already performs anti-aliasing via "feathering" /// (controlled by [`egui::epaint::TessellationOptions`]), /// but if you are embedding 3D in egui you may want to turn on multisampling. pub multisampling: u16, /// Sets the number of bits in the depth buffer. /// /// `egui` doesn't need the depth buffer, so the default value is 0. pub depth_buffer: u8, /// Sets the number of bits in the stencil buffer. /// /// `egui` doesn't need the stencil buffer, so the default value is 0. pub stencil_buffer: u8, /// Specify whether or not hardware acceleration is preferred, required, or not. /// /// Default: [`HardwareAcceleration::Preferred`]. pub hardware_acceleration: HardwareAcceleration, /// What rendering backend to use. #[cfg(any(feature = "glow", feature = "wgpu_no_default_features"))] pub renderer: Renderer, /// This controls what happens when you close the main eframe window. /// /// If `true`, execution will continue after the eframe window is closed. /// If `false`, the app will close once the eframe window is closed. /// /// This is `true` by default, and the `false` option is only there /// so we can revert if we find any bugs. /// /// This feature was introduced in <https://github.com/emilk/egui/pull/1889>. /// /// When `true`, [`winit::platform::run_on_demand::EventLoopExtRunOnDemand`] is used. /// When `false`, [`winit::event_loop::EventLoop::run`] is used. pub run_and_return: bool, /// Hook into the building of an event loop before it is run. /// /// Specify a callback here in case you need to make platform specific changes to the /// event loop before it is run. /// /// Note: A [`NativeOptions`] clone will not include any `event_loop_builder` hook. #[cfg(any(feature = "glow", feature = "wgpu_no_default_features"))] pub event_loop_builder: Option<EventLoopBuilderHook>, /// Hook into the building of a window. /// /// Specify a callback here in case you need to make platform specific changes to the /// window appearance. /// /// Note: A [`NativeOptions`] clone will not include any `window_builder` hook. #[cfg(any(feature = "glow", feature = "wgpu_no_default_features"))] pub window_builder: Option<WindowBuilderHook>, #[cfg(feature = "glow")] /// Needed for cross compiling for VirtualBox VMSVGA driver with OpenGL ES 2.0 and OpenGL 2.1 which doesn't support SRGB texture. /// See <https://github.com/emilk/egui/pull/1993>. /// /// For OpenGL ES 2.0: set this to [`egui_glow::ShaderVersion::Es100`] to solve blank texture problem (by using the "fallback shader"). pub shader_version: Option<egui_glow::ShaderVersion>, /// On desktop: make the window position to be centered at initialization. /// /// Platform specific: /// /// Wayland desktop currently not supported. pub centered: bool, /// Configures wgpu instance/device/adapter/surface creation and renderloop. #[cfg(feature = "wgpu_no_default_features")] pub wgpu_options: egui_wgpu::WgpuConfiguration, /// Controls whether or not the native window position and size will be /// persisted (only if the "persistence" feature is enabled). pub persist_window: bool, /// The folder where `eframe` will store the app state. If not set, eframe will use a default /// data storage path for each target system. pub persistence_path: Option<std::path::PathBuf>, /// Controls whether to apply dithering to minimize banding artifacts. /// /// Dithering assumes an sRGB output and thus will apply noise to any input value that lies between /// two 8bit values after applying the sRGB OETF function, i.e. if it's not a whole 8bit value in "gamma space". /// This means that only inputs from texture interpolation and vertex colors should be affected in practice. /// /// Defaults to true. pub dithering: bool, /// Android application for `winit`'s event loop. /// /// This value is required on Android to correctly create the event loop. See /// [`EventLoopBuilder::build`] and [`with_android_app`] for details. /// /// [`EventLoopBuilder::build`]: winit::event_loop::EventLoopBuilder::build /// [`with_android_app`]: winit::platform::android::EventLoopBuilderExtAndroid::with_android_app #[cfg(target_os = "android")] pub android_app: Option<winit::platform::android::activity::AndroidApp>, } #[cfg(not(target_arch = "wasm32"))] impl Clone for NativeOptions { fn clone(&self) -> Self { Self { viewport: self.viewport.clone(), #[cfg(any(feature = "glow", feature = "wgpu_no_default_features"))] event_loop_builder: None, // Skip any builder callbacks if cloning #[cfg(any(feature = "glow", feature = "wgpu_no_default_features"))] window_builder: None, // Skip any builder callbacks if cloning #[cfg(feature = "wgpu_no_default_features")] wgpu_options: self.wgpu_options.clone(), persistence_path: self.persistence_path.clone(), #[cfg(target_os = "android")] android_app: self.android_app.clone(), ..*self } } } #[cfg(not(target_arch = "wasm32"))] impl Default for NativeOptions { fn default() -> Self { Self { viewport: Default::default(), vsync: true, multisampling: 0, depth_buffer: 0, stencil_buffer: 0, hardware_acceleration: HardwareAcceleration::Preferred, #[cfg(any(feature = "glow", feature = "wgpu_no_default_features"))] renderer: Renderer::default(), run_and_return: true, #[cfg(any(feature = "glow", feature = "wgpu_no_default_features"))] event_loop_builder: None, #[cfg(any(feature = "glow", feature = "wgpu_no_default_features"))] window_builder: None, #[cfg(feature = "glow")] shader_version: None, centered: false, #[cfg(feature = "wgpu_no_default_features")] wgpu_options: egui_wgpu::WgpuConfiguration::default(), persist_window: true, persistence_path: None, dithering: true, #[cfg(target_os = "android")] android_app: None, } } } // ---------------------------------------------------------------------------- /// Options when using `eframe` in a web page. #[cfg(target_arch = "wasm32")] pub struct WebOptions { /// What rendering backend to use. #[cfg(any(feature = "glow", feature = "wgpu_no_default_features"))] pub renderer: Renderer, /// Sets the number of bits in the depth buffer. /// /// `egui` doesn't need the depth buffer, so the default value is 0. /// Unused by webgl context as of writing. pub depth_buffer: u8, /// Which version of WebGL context to select /// /// Default: [`WebGlContextOption::BestFirst`]. #[cfg(feature = "glow")] pub webgl_context_option: WebGlContextOption, /// Configures wgpu instance/device/adapter/surface creation and renderloop. #[cfg(feature = "wgpu_no_default_features")] pub wgpu_options: egui_wgpu::WgpuConfiguration, /// Controls whether to apply dithering to minimize banding artifacts. /// /// Dithering assumes an sRGB output and thus will apply noise to any input value that lies between /// two 8bit values after applying the sRGB OETF function, i.e. if it's not a whole 8bit value in "gamma space". /// This means that only inputs from texture interpolation and vertex colors should be affected in practice. /// /// Defaults to true. pub dithering: bool, /// If the web event corresponding to an egui event should be propagated /// to the rest of the web page. /// /// The default is `true`, meaning /// [`stopPropagation`](https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation) /// is called on every event, and the event is not propagated to the rest of the web page. pub should_stop_propagation: Box<dyn Fn(&egui::Event) -> bool>, /// Whether the web event corresponding to an egui event should have `prevent_default` called /// on it or not. /// /// Defaults to true. pub should_prevent_default: Box<dyn Fn(&egui::Event) -> bool>, /// Maximum rate at which to repaint. This can be used to artificially reduce the repaint rate below /// vsync in order to save resources. pub max_fps: Option<u32>, } #[cfg(target_arch = "wasm32")] impl Default for WebOptions { fn default() -> Self { Self { #[cfg(any(feature = "glow", feature = "wgpu_no_default_features"))] renderer: Renderer::default(), depth_buffer: 0, #[cfg(feature = "glow")] webgl_context_option: WebGlContextOption::BestFirst, #[cfg(feature = "wgpu_no_default_features")] wgpu_options: egui_wgpu::WgpuConfiguration::default(), dithering: true, should_stop_propagation: Box::new(|_| true), should_prevent_default: Box::new(|_| true), max_fps: None, } } } // ---------------------------------------------------------------------------- /// WebGL Context options #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub enum WebGlContextOption { /// Force Use WebGL1. WebGl1, /// Force use WebGL2. WebGl2, /// Use WebGL2 first. BestFirst, /// Use WebGL1 first CompatibilityFirst, } // ---------------------------------------------------------------------------- /// What rendering backend to use. /// /// You need to enable the "glow" and "wgpu" features to have a choice. #[cfg(any(feature = "glow", feature = "wgpu_no_default_features"))] #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))] pub enum Renderer { /// Use [`egui_glow`] renderer for [`glow`](https://github.com/grovesNL/glow). #[cfg(feature = "glow")] Glow, /// Use [`egui_wgpu`] renderer for [`wgpu`](https://github.com/gfx-rs/wgpu). #[cfg(feature = "wgpu_no_default_features")] Wgpu, } #[cfg(any(feature = "glow", feature = "wgpu_no_default_features"))] impl Default for Renderer { fn default() -> Self { #[cfg(not(feature = "glow"))] #[cfg(not(feature = "wgpu_no_default_features"))] compile_error!( "eframe: you must enable at least one of the rendering backend features: 'glow' or 'wgpu'" ); #[cfg(feature = "glow")] #[cfg(not(feature = "wgpu_no_default_features"))] return Self::Glow; #[cfg(not(feature = "glow"))] #[cfg(feature = "wgpu_no_default_features")] return Self::Wgpu; // It's weird that the user has enabled both glow and wgpu, // but let's pick the better of the two (wgpu): #[cfg(feature = "glow")] #[cfg(feature = "wgpu_no_default_features")] return Self::Wgpu; } } #[cfg(any(feature = "glow", feature = "wgpu_no_default_features"))] impl std::fmt::Display for Renderer { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { #[cfg(feature = "glow")] Self::Glow => "glow".fmt(f), #[cfg(feature = "wgpu_no_default_features")] Self::Wgpu => "wgpu".fmt(f), } } } #[cfg(any(feature = "glow", feature = "wgpu_no_default_features"))] impl std::str::FromStr for Renderer { type Err = String; fn from_str(name: &str) -> Result<Self, String> { match name.to_lowercase().as_str() { #[cfg(feature = "glow")] "glow" => Ok(Self::Glow), #[cfg(feature = "wgpu_no_default_features")] "wgpu" => Ok(Self::Wgpu), _ => Err(format!( "eframe renderer {name:?} is not available. Make sure that the corresponding eframe feature is enabled." )), } } } // ---------------------------------------------------------------------------- /// Represents the surroundings of your app. /// /// It provides methods to inspect the surroundings (are we on the web?), /// access to persistent storage, and access to the rendering backend. pub struct Frame { /// Information about the integration. pub(crate) info: IntegrationInfo, /// A place where you can store custom data in a way that persists when you restart the app. pub(crate) storage: Option<Box<dyn Storage>>, /// A reference to the underlying [`glow`] (OpenGL) context. #[cfg(feature = "glow")] pub(crate) gl: Option<std::sync::Arc<glow::Context>>, /// Used to convert user custom [`glow::Texture`] to [`egui::TextureId`] #[cfg(all(feature = "glow", not(target_arch = "wasm32")))] pub(crate) glow_register_native_texture: Option<Box<dyn FnMut(glow::Texture) -> egui::TextureId>>, /// Can be used to manage GPU resources for custom rendering with WGPU using [`egui::PaintCallback`]s. #[cfg(feature = "wgpu_no_default_features")] #[doc(hidden)] pub wgpu_render_state: Option<egui_wgpu::RenderState>, /// Raw platform window handle #[cfg(not(target_arch = "wasm32"))] pub(crate) raw_window_handle: Result<RawWindowHandle, HandleError>, /// Raw platform display handle for window #[cfg(not(target_arch = "wasm32"))] pub(crate) raw_display_handle: Result<RawDisplayHandle, HandleError>, } // Implementing `Clone` would violate the guarantees of `HasWindowHandle` and `HasDisplayHandle`. #[cfg(not(target_arch = "wasm32"))] assert_not_impl_any!(Frame: Clone); #[expect(unsafe_code)] #[cfg(not(target_arch = "wasm32"))] impl HasWindowHandle for Frame { fn window_handle(&self) -> Result<WindowHandle<'_>, HandleError> { // Safety: the lifetime is correct. unsafe { Ok(WindowHandle::borrow_raw(self.raw_window_handle.clone()?)) } } } #[expect(unsafe_code)] #[cfg(not(target_arch = "wasm32"))] impl HasDisplayHandle for Frame { fn display_handle(&self) -> Result<DisplayHandle<'_>, HandleError> { // Safety: the lifetime is correct. unsafe { Ok(DisplayHandle::borrow_raw(self.raw_display_handle.clone()?)) } } } impl Frame { /// Create a new empty [Frame] for testing [App]s in kittest. #[doc(hidden)] pub fn _new_kittest() -> Self { Self { #[cfg(feature = "glow")] gl: None, #[cfg(all(feature = "glow", not(target_arch = "wasm32")))] glow_register_native_texture: None, info: IntegrationInfo::mock(), #[cfg(not(target_arch = "wasm32"))] raw_display_handle: Err(HandleError::NotSupported), #[cfg(not(target_arch = "wasm32"))] raw_window_handle: Err(HandleError::NotSupported), storage: None, #[cfg(feature = "wgpu_no_default_features")] wgpu_render_state: None, } } /// True if you are in a web environment. /// /// Equivalent to `cfg!(target_arch = "wasm32")` #[expect(clippy::unused_self)] pub fn is_web(&self) -> bool { cfg!(target_arch = "wasm32") } /// Information about the integration. pub fn info(&self) -> &IntegrationInfo { &self.info } /// A place where you can store custom data in a way that persists when you restart the app. pub fn storage(&self) -> Option<&dyn Storage> { self.storage.as_deref() } /// A place where you can store custom data in a way that persists when you restart the app. pub fn storage_mut(&mut self) -> Option<&mut (dyn Storage + 'static)> { self.storage.as_deref_mut() } /// A reference to the underlying [`glow`] (OpenGL) context. /// /// This can be used, for instance, to: /// * Render things to offscreen buffers. /// * Read the pixel buffer from the previous frame (`glow::Context::read_pixels`). /// * Render things behind the egui windows. /// /// Note that all egui painting is deferred to after the call to [`App::update`] /// ([`egui`] only collects [`egui::Shape`]s and then eframe paints them all in one go later on). /// /// To get a [`glow`] context you need to compile with the `glow` feature flag, /// and run eframe using [`Renderer::Glow`]. #[cfg(feature = "glow")] pub fn gl(&self) -> Option<&std::sync::Arc<glow::Context>> { self.gl.as_ref() } /// Register your own [`glow::Texture`], /// and then you can use the returned [`egui::TextureId`] to render your texture with [`egui`]. /// /// This function will take the ownership of your [`glow::Texture`], so please do not delete your [`glow::Texture`] after registering. #[cfg(all(feature = "glow", not(target_arch = "wasm32")))] pub fn register_native_glow_texture(&mut self, native: glow::Texture) -> egui::TextureId { #[expect(clippy::unwrap_used)] self.glow_register_native_texture.as_mut().unwrap()(native) } /// The underlying WGPU render state. /// /// Only available when compiling with the `wgpu` feature and using [`Renderer::Wgpu`]. /// /// Can be used to manage GPU resources for custom rendering with WGPU using [`egui::PaintCallback`]s. #[cfg(feature = "wgpu_no_default_features")] pub fn wgpu_render_state(&self) -> Option<&egui_wgpu::RenderState> { self.wgpu_render_state.as_ref() } } /// Information about the web environment (if applicable). #[derive(Clone, Debug)] #[cfg(target_arch = "wasm32")] pub struct WebInfo { /// The browser user agent. pub user_agent: String, /// Information about the URL. pub location: Location, } /// Information about the URL. /// /// Everything has been percent decoded (`%20` -> ` ` etc). #[cfg(target_arch = "wasm32")] #[derive(Clone, Debug)] pub struct Location { /// The full URL (`location.href`) without the hash, percent-decoded. /// /// Example: `"http://www.example.com:80/index.html?foo=bar"`. pub url: String, /// `location.protocol` /// /// Example: `"http:"`. pub protocol: String, /// `location.host` /// /// Example: `"example.com:80"`. pub host: String, /// `location.hostname` /// /// Example: `"example.com"`. pub hostname: String, /// `location.port` /// /// Example: `"80"`. pub port: String, /// The "#fragment" part of "www.example.com/index.html?query#fragment". /// /// Note that the leading `#` is included in the string. /// Also known as "hash-link" or "anchor". pub hash: String, /// The "query" part of "www.example.com/index.html?query#fragment". /// /// Note that the leading `?` is NOT included in the string. ///
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
true
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/eframe/src/stopwatch.rs
crates/eframe/src/stopwatch.rs
#![allow(clippy::allow_attributes, dead_code)] // not used on all platforms use web_time::Instant; pub struct Stopwatch { total_time_ns: u128, /// None = not running start: Option<Instant>, } impl Stopwatch { pub fn new() -> Self { Self { total_time_ns: 0, start: None, } } pub fn start(&mut self) { assert!(self.start.is_none(), "Stopwatch already running"); self.start = Some(Instant::now()); } pub fn pause(&mut self) { let start = self.start.take().expect("Stopwatch is not running"); let duration = start.elapsed(); self.total_time_ns += duration.as_nanos(); } pub fn resume(&mut self) { assert!(self.start.is_none(), "Stopwatch still running"); self.start = Some(Instant::now()); } pub fn total_time_ns(&self) -> u128 { if let Some(start) = self.start { // Running let duration = start.elapsed(); self.total_time_ns + duration.as_nanos() } else { // Paused self.total_time_ns } } pub fn total_time_sec(&self) -> f32 { self.total_time_ns() as f32 * 1e-9 } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/eframe/src/icon_data.rs
crates/eframe/src/icon_data.rs
//! Helpers for loading [`egui::IconData`]. use egui::IconData; /// Helpers for working with [`IconData`]. pub trait IconDataExt { /// Convert into [`image::RgbaImage`] /// /// # Errors /// If `width*height != 4 * rgba.len()`, or if the image is too big. fn to_image(&self) -> Result<image::RgbaImage, String>; /// Encode as PNG. /// /// # Errors /// The image is invalid, or the PNG encoder failed. fn to_png_bytes(&self) -> Result<Vec<u8>, String>; } /// Load the contents of .png file. /// /// # Errors /// If this is not a valid png. pub fn from_png_bytes(png_bytes: &[u8]) -> Result<IconData, image::ImageError> { profiling::function_scope!(); let image = image::load_from_memory(png_bytes)?; Ok(from_image(image)) } fn from_image(image: image::DynamicImage) -> IconData { let image = image.into_rgba8(); IconData { width: image.width(), height: image.height(), rgba: image.into_raw(), } } impl IconDataExt for IconData { fn to_image(&self) -> Result<image::RgbaImage, String> { profiling::function_scope!(); let Self { rgba, width, height, } = self.clone(); image::RgbaImage::from_raw(width, height, rgba).ok_or_else(|| "Invalid IconData".to_owned()) } fn to_png_bytes(&self) -> Result<Vec<u8>, String> { profiling::function_scope!(); let image = self.to_image()?; let mut png_bytes: Vec<u8> = Vec::new(); image .write_to( &mut std::io::Cursor::new(&mut png_bytes), image::ImageFormat::Png, ) .map_err(|err| err.to_string())?; Ok(png_bytes) } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/eframe/src/native/wgpu_integration.rs
crates/eframe/src/native/wgpu_integration.rs
//! Note that this file contains code very similar to [`super::glow_integration`]. //! When making changes to one you often also want to apply it to the other. //! //! This is also very complex code, and not very pretty. //! There is a bunch of improvements we could do, //! like removing a bunch of `unwraps`. use std::{cell::RefCell, num::NonZeroU32, rc::Rc, sync::Arc, time::Instant}; use egui_winit::ActionRequested; use parking_lot::Mutex; use raw_window_handle::{HasDisplayHandle as _, HasWindowHandle as _}; use winit::{ event_loop::{ActiveEventLoop, EventLoop, EventLoopProxy}, window::{Window, WindowId}, }; use ahash::HashMap; use egui::{ DeferredViewportUiCallback, FullOutput, ImmediateViewport, OrderedViewportIdMap, ViewportBuilder, ViewportClass, ViewportId, ViewportIdPair, ViewportIdSet, ViewportInfo, ViewportOutput, }; #[cfg(feature = "accesskit")] use egui_winit::accesskit_winit; use winit_integration::UserEvent; use crate::{ App, AppCreator, CreationContext, NativeOptions, Result, Storage, native::{epi_integration::EpiIntegration, winit_integration::EventResult}, }; use super::{epi_integration, event_loop_context, winit_integration, winit_integration::WinitApp}; // ---------------------------------------------------------------------------- // Types: pub struct WgpuWinitApp<'app> { repaint_proxy: Arc<Mutex<EventLoopProxy<UserEvent>>>, app_name: String, native_options: NativeOptions, /// Set at initialization, then taken and set to `None` in `init_run_state`. app_creator: Option<AppCreator<'app>>, /// Set when we are actually up and running. running: Option<WgpuWinitRunning<'app>>, } /// State that is initialized when the application is first starts running via /// a Resumed event. On Android this ensures that any graphics state is only /// initialized once the application has an associated `SurfaceView`. struct WgpuWinitRunning<'app> { integration: EpiIntegration, /// The users application. app: Box<dyn 'app + App>, /// Wrapped in an `Rc<RefCell<…>>` so it can be re-entrantly shared via a weak-pointer. shared: Rc<RefCell<SharedState>>, } /// Everything needed by the immediate viewport renderer.\ /// /// This is shared by all viewports. /// /// Wrapped in an `Rc<RefCell<…>>` so it can be re-entrantly shared via a weak-pointer. pub struct SharedState { egui_ctx: egui::Context, viewports: Viewports, painter: egui_wgpu::winit::Painter, viewport_from_window: HashMap<WindowId, ViewportId>, focused_viewport: Option<ViewportId>, resized_viewport: Option<ViewportId>, } pub type Viewports = egui::OrderedViewportIdMap<Viewport>; pub struct Viewport { ids: ViewportIdPair, class: ViewportClass, builder: ViewportBuilder, deferred_commands: Vec<egui::viewport::ViewportCommand>, info: ViewportInfo, actions_requested: Vec<ActionRequested>, /// `None` for sync viewports. viewport_ui_cb: Option<Arc<DeferredViewportUiCallback>>, /// Window surface state that's initialized when the app starts running via a Resumed event /// and on Android will also be destroyed if the application is paused. window: Option<Arc<Window>>, /// `window` and `egui_winit` are initialized together. egui_winit: Option<egui_winit::State>, } // ---------------------------------------------------------------------------- impl<'app> WgpuWinitApp<'app> { pub fn new( event_loop: &EventLoop<UserEvent>, app_name: &str, native_options: NativeOptions, app_creator: AppCreator<'app>, ) -> Self { profiling::function_scope!(); #[cfg(feature = "__screenshot")] assert!( std::env::var("EFRAME_SCREENSHOT_TO").is_err(), "EFRAME_SCREENSHOT_TO not yet implemented for wgpu backend" ); Self { repaint_proxy: Arc::new(Mutex::new(event_loop.create_proxy())), app_name: app_name.to_owned(), native_options, running: None, app_creator: Some(app_creator), } } /// Create a window for all viewports lacking one. fn initialized_all_windows(&mut self, event_loop: &ActiveEventLoop) { let Some(running) = &mut self.running else { return; }; let mut shared = running.shared.borrow_mut(); let SharedState { viewports, painter, viewport_from_window, .. } = &mut *shared; for viewport in viewports.values_mut() { viewport.initialize_window( event_loop, &running.integration.egui_ctx, viewport_from_window, painter, ); } } #[cfg(target_os = "android")] fn recreate_window(&self, event_loop: &ActiveEventLoop, running: &WgpuWinitRunning<'app>) { let SharedState { egui_ctx, viewports, viewport_from_window, painter, .. } = &mut *running.shared.borrow_mut(); initialize_or_update_viewport( viewports, ViewportIdPair::ROOT, ViewportClass::Root, self.native_options.viewport.clone(), None, painter, ) .initialize_window(event_loop, egui_ctx, viewport_from_window, painter); } #[cfg(target_os = "android")] fn drop_window(&mut self) -> Result<(), egui_wgpu::WgpuError> { if let Some(running) = &mut self.running { let mut shared = running.shared.borrow_mut(); shared.viewports.remove(&ViewportId::ROOT); pollster::block_on(shared.painter.set_window(ViewportId::ROOT, None))?; } Ok(()) } fn init_run_state( &mut self, egui_ctx: egui::Context, event_loop: &ActiveEventLoop, storage: Option<Box<dyn Storage>>, window: Window, builder: ViewportBuilder, ) -> crate::Result<&mut WgpuWinitRunning<'app>> { profiling::function_scope!(); let mut painter = pollster::block_on(egui_wgpu::winit::Painter::new( egui_ctx.clone(), self.native_options.wgpu_options.clone(), self.native_options.viewport.transparent.unwrap_or(false), egui_wgpu::RendererOptions { msaa_samples: self.native_options.multisampling as _, depth_stencil_format: egui_wgpu::depth_format_from_bits( self.native_options.depth_buffer, self.native_options.stencil_buffer, ), dithering: self.native_options.dithering, ..Default::default() }, )); let mut viewport_info = ViewportInfo::default(); egui_winit::update_viewport_info(&mut viewport_info, &egui_ctx, &window, true); { // Tell egui right away about native_pixels_per_point etc, // so that the app knows about it during app creation: let pixels_per_point = egui_winit::pixels_per_point(&egui_ctx, &window); egui_ctx.input_mut(|i| { i.raw .viewports .insert(ViewportId::ROOT, viewport_info.clone()); i.pixels_per_point = pixels_per_point; }); } let window = Arc::new(window); { profiling::scope!("set_window"); pollster::block_on(painter.set_window(ViewportId::ROOT, Some(Arc::clone(&window))))?; } let wgpu_render_state = painter.render_state(); let integration = EpiIntegration::new( egui_ctx.clone(), &window, &self.app_name, &self.native_options, storage, #[cfg(feature = "glow")] None, #[cfg(feature = "glow")] None, wgpu_render_state.clone(), ); { let event_loop_proxy = Arc::clone(&self.repaint_proxy); egui_ctx.set_request_repaint_callback(move |info| { log::trace!("request_repaint_callback: {info:?}"); let when = Instant::now() + info.delay; let cumulative_pass_nr = info.current_cumulative_pass_nr; event_loop_proxy .lock() .send_event(UserEvent::RequestRepaint { when, cumulative_pass_nr, viewport_id: info.viewport_id, }) .ok(); }); } #[allow(clippy::allow_attributes, unused_mut)] // used for accesskit let mut egui_winit = egui_winit::State::new( egui_ctx.clone(), ViewportId::ROOT, event_loop, Some(window.scale_factor() as f32), event_loop.system_theme(), painter.max_texture_side(), ); #[cfg(feature = "accesskit")] { let event_loop_proxy = self.repaint_proxy.lock().clone(); egui_winit.init_accesskit(event_loop, &window, event_loop_proxy); } let app_creator = std::mem::take(&mut self.app_creator) .expect("Single-use AppCreator has unexpectedly already been taken"); let cc = CreationContext { egui_ctx: egui_ctx.clone(), integration_info: integration.frame.info().clone(), storage: integration.frame.storage(), #[cfg(feature = "glow")] gl: None, #[cfg(feature = "glow")] get_proc_address: None, wgpu_render_state, raw_display_handle: window.display_handle().map(|h| h.as_raw()), raw_window_handle: window.window_handle().map(|h| h.as_raw()), }; let app = { profiling::scope!("user_app_creator"); app_creator(&cc).map_err(crate::Error::AppCreation)? }; let mut viewport_from_window = HashMap::default(); viewport_from_window.insert(window.id(), ViewportId::ROOT); let mut viewports = Viewports::default(); viewports.insert( ViewportId::ROOT, Viewport { ids: ViewportIdPair::ROOT, class: ViewportClass::Root, builder, deferred_commands: vec![], info: viewport_info, actions_requested: Default::default(), viewport_ui_cb: None, window: Some(window), egui_winit: Some(egui_winit), }, ); let shared = Rc::new(RefCell::new(SharedState { egui_ctx, viewport_from_window, viewports, painter, focused_viewport: Some(ViewportId::ROOT), resized_viewport: None, })); { // Create a weak pointer so that we don't keep state alive for too long. let shared = Rc::downgrade(&shared); let beginning = integration.beginning; egui::Context::set_immediate_viewport_renderer(move |_egui_ctx, immediate_viewport| { if let Some(shared) = shared.upgrade() { render_immediate_viewport(beginning, &shared, immediate_viewport); } else { log::warn!("render_sync_callback called after window closed"); } }); } Ok(self.running.insert(WgpuWinitRunning { integration, app, shared, })) } } impl WinitApp for WgpuWinitApp<'_> { fn egui_ctx(&self) -> Option<&egui::Context> { self.running.as_ref().map(|r| &r.integration.egui_ctx) } fn window(&self, window_id: WindowId) -> Option<Arc<Window>> { self.running .as_ref() .and_then(|r| { let shared = r.shared.borrow(); let id = shared.viewport_from_window.get(&window_id)?; shared.viewports.get(id).map(|v| v.window.clone()) }) .flatten() } fn window_id_from_viewport_id(&self, id: ViewportId) -> Option<WindowId> { Some( self.running .as_ref()? .shared .borrow() .viewports .get(&id)? .window .as_ref()? .id(), ) } fn save(&mut self) { log::debug!("WinitApp::save called"); if let Some(running) = self.running.as_mut() { running.save(); } } fn save_and_destroy(&mut self) { if let Some(mut running) = self.running.take() { running.save_and_destroy(); } } fn run_ui_and_paint( &mut self, event_loop: &ActiveEventLoop, window_id: WindowId, ) -> Result<EventResult> { self.initialized_all_windows(event_loop); if let Some(running) = &mut self.running { running.run_ui_and_paint(window_id) } else { Ok(EventResult::Wait) } } fn resumed(&mut self, event_loop: &ActiveEventLoop) -> crate::Result<EventResult> { log::debug!("Event::Resumed"); let running = if let Some(running) = &self.running { #[cfg(target_os = "android")] self.recreate_window(event_loop, running); running } else { let storage = if let Some(file) = &self.native_options.persistence_path { epi_integration::create_storage_with_file(file) } else { epi_integration::create_storage( self.native_options .viewport .app_id .as_ref() .unwrap_or(&self.app_name), ) }; let egui_ctx = winit_integration::create_egui_context(storage.as_deref()); let (window, builder) = create_window( &egui_ctx, event_loop, storage.as_deref(), &mut self.native_options, )?; self.init_run_state(egui_ctx, event_loop, storage, window, builder)? }; let viewport = &running.shared.borrow().viewports[&ViewportId::ROOT]; if let Some(window) = &viewport.window { Ok(EventResult::RepaintNow(window.id())) } else { Ok(EventResult::Wait) } } fn suspended(&mut self, _: &ActiveEventLoop) -> crate::Result<EventResult> { #[cfg(target_os = "android")] self.drop_window()?; Ok(EventResult::Save) } fn device_event( &mut self, _: &ActiveEventLoop, _: winit::event::DeviceId, event: winit::event::DeviceEvent, ) -> crate::Result<EventResult> { if let winit::event::DeviceEvent::MouseMotion { delta } = event && let Some(running) = &mut self.running { let mut shared = running.shared.borrow_mut(); if let Some(viewport) = shared .focused_viewport .and_then(|viewport| shared.viewports.get_mut(&viewport)) { if let Some(egui_winit) = viewport.egui_winit.as_mut() { egui_winit.on_mouse_motion(delta); } if let Some(window) = viewport.window.as_ref() { return Ok(EventResult::RepaintNext(window.id())); } } } Ok(EventResult::Wait) } fn window_event( &mut self, event_loop: &ActiveEventLoop, window_id: WindowId, event: winit::event::WindowEvent, ) -> crate::Result<EventResult> { self.initialized_all_windows(event_loop); if let Some(running) = &mut self.running { Ok(running.on_window_event(window_id, &event)) } else { // running is removed to get ready for exiting Ok(EventResult::Exit) } } #[cfg(feature = "accesskit")] fn on_accesskit_event(&mut self, event: accesskit_winit::Event) -> crate::Result<EventResult> { if let Some(running) = &mut self.running { let mut shared_lock = running.shared.borrow_mut(); let SharedState { viewport_from_window, viewports, .. } = &mut *shared_lock; if let Some(viewport) = viewport_from_window .get(&event.window_id) .and_then(|id| viewports.get_mut(id)) && let Some(egui_winit) = &mut viewport.egui_winit { return Ok(winit_integration::on_accesskit_window_event( egui_winit, event.window_id, &event.window_event, )); } } Ok(EventResult::Wait) } } impl WgpuWinitRunning<'_> { /// Saves the application state fn save(&mut self) { let shared = self.shared.borrow(); // This is done because of the "save on suspend" logic on Android. Once the application is suspended, there is no window associated to it. let window = if let Some(Viewport { window, .. }) = shared.viewports.get(&ViewportId::ROOT) { window.as_deref() } else { None }; self.integration.save(self.app.as_mut(), window); } fn save_and_destroy(&mut self) { profiling::function_scope!(); self.save(); #[cfg(feature = "glow")] self.app.on_exit(None); #[cfg(not(feature = "glow"))] self.app.on_exit(); let mut shared = self.shared.borrow_mut(); shared.painter.destroy(); } /// This is called both for the root viewport, and all deferred viewports fn run_ui_and_paint(&mut self, window_id: WindowId) -> Result<EventResult> { profiling::function_scope!(); let Some(viewport_id) = self .shared .borrow() .viewport_from_window .get(&window_id) .copied() else { return Ok(EventResult::Wait); }; profiling::finish_frame!(); let Self { app, integration, shared, } = self; let mut frame_timer = crate::stopwatch::Stopwatch::new(); frame_timer.start(); let (viewport_ui_cb, raw_input) = { profiling::scope!("Prepare"); let mut shared_lock = shared.borrow_mut(); let SharedState { viewports, painter, .. } = &mut *shared_lock; if viewport_id != ViewportId::ROOT { let Some(viewport) = viewports.get(&viewport_id) else { return Ok(EventResult::Wait); }; if viewport.viewport_ui_cb.is_none() { // This will only happen if this is an immediate viewport. // That means that the viewport cannot be rendered by itself and needs his parent to be rendered. if let Some(viewport) = viewports.get(&viewport.ids.parent) && let Some(window) = viewport.window.as_ref() { return Ok(EventResult::RepaintNext(window.id())); } return Ok(EventResult::Wait); } } let Some(viewport) = viewports.get_mut(&viewport_id) else { return Ok(EventResult::Wait); }; let Viewport { viewport_ui_cb, window, egui_winit, info, .. } = viewport; let viewport_ui_cb = viewport_ui_cb.clone(); let Some(window) = window else { return Ok(EventResult::Wait); }; egui_winit::update_viewport_info(info, &integration.egui_ctx, window, false); { profiling::scope!("set_window"); pollster::block_on(painter.set_window(viewport_id, Some(Arc::clone(window))))?; } let Some(egui_winit) = egui_winit.as_mut() else { return Ok(EventResult::Wait); }; let mut raw_input = egui_winit.take_egui_input(window); integration.pre_update(); raw_input.time = Some(integration.beginning.elapsed().as_secs_f64()); raw_input.viewports = viewports .iter() .map(|(id, viewport)| (*id, viewport.info.clone())) .collect(); painter.handle_screenshots(&mut raw_input.events); (viewport_ui_cb, raw_input) }; // ------------------------------------------------------------ // Runs the update, which could call immediate viewports, // so make sure we hold no locks here! let full_output = integration.update(app.as_mut(), viewport_ui_cb.as_deref(), raw_input); // ------------------------------------------------------------ let mut shared_mut = shared.borrow_mut(); let SharedState { egui_ctx, viewports, painter, viewport_from_window, .. } = &mut *shared_mut; let FullOutput { platform_output, textures_delta, shapes, pixels_per_point, viewport_output, } = full_output; remove_viewports_not_in(viewports, painter, viewport_from_window, &viewport_output); let Some(viewport) = viewports.get_mut(&viewport_id) else { return Ok(EventResult::Wait); }; viewport.info.events.clear(); // they should have been processed let Viewport { window: Some(window), egui_winit: Some(egui_winit), .. } = viewport else { return Ok(EventResult::Wait); }; egui_winit.handle_platform_output(window, platform_output); let clipped_primitives = egui_ctx.tessellate(shapes, pixels_per_point); let mut screenshot_commands = vec![]; viewport.actions_requested.retain(|cmd| { if let ActionRequested::Screenshot(info) = cmd { screenshot_commands.push(info.clone()); false } else { true } }); let vsync_secs = painter.paint_and_update_textures( viewport_id, pixels_per_point, app.clear_color(&egui_ctx.global_style().visuals), &clipped_primitives, &textures_delta, screenshot_commands, ); for action in viewport.actions_requested.drain(..) { match action { ActionRequested::Screenshot { .. } => { // already handled above } ActionRequested::Cut => { egui_winit.egui_input_mut().events.push(egui::Event::Cut); } ActionRequested::Copy => { egui_winit.egui_input_mut().events.push(egui::Event::Copy); } ActionRequested::Paste => { if let Some(contents) = egui_winit.clipboard_text() { let contents = contents.replace("\r\n", "\n"); if !contents.is_empty() { egui_winit .egui_input_mut() .events .push(egui::Event::Paste(contents)); } } } } } integration.post_rendering(window); let active_viewports_ids: ViewportIdSet = viewport_output.keys().copied().collect(); handle_viewport_output( &integration.egui_ctx, &viewport_output, viewports, painter, viewport_from_window, ); // Prune dead viewports: viewports.retain(|id, _| active_viewports_ids.contains(id)); viewport_from_window.retain(|_, id| active_viewports_ids.contains(id)); painter.gc_viewports(&active_viewports_ids); let window = viewport_from_window .get(&window_id) .and_then(|id| viewports.get(id)) .and_then(|vp| vp.window.as_ref()); integration.report_frame_time(frame_timer.total_time_sec() - vsync_secs); // don't count auto-save time as part of regular frame time integration.maybe_autosave(app.as_mut(), window.map(|w| w.as_ref())); if let Some(window) = window && window.is_minimized() == Some(true) { // On Mac, a minimized Window uses up all CPU: // https://github.com/emilk/egui/issues/325 profiling::scope!("minimized_sleep"); std::thread::sleep(std::time::Duration::from_millis(10)); } if integration.should_close() { Ok(EventResult::CloseRequested) } else { Ok(EventResult::Wait) } } fn on_window_event( &mut self, window_id: WindowId, event: &winit::event::WindowEvent, ) -> EventResult { let Self { integration, shared, .. } = self; let mut shared = shared.borrow_mut(); let viewport_id = shared.viewport_from_window.get(&window_id).copied(); // On Windows, if a window is resized by the user, it should repaint synchronously, inside the // event handler. If this is not done, the compositor will assume that the window does not want // to redraw and continue ahead. // // In eframe's case, that causes the window to rapidly flicker, as it struggles to deliver // new frames to the compositor in time. The flickering is technically glutin or glow's fault, but we should be responding properly // to resizes anyway, as doing so avoids dropping frames. // // See: https://github.com/emilk/egui/issues/903 let mut repaint_asap = false; // On MacOS the asap repaint is not enough. The drawn frames must be synchronized with // the CoreAnimation transactions driving the window resize process. // // Thus, Painter, responsible for wgpu surfaces and their resize, has to be notified of the // resize lifecycle, yet winit does not provide any events for that. To work around, // the last resized viewport is tracked until any next non-resize event is received. // // Accidental state change during the resize process due to an unexpected event fire // is ok, state will switch back upon next resize event. // // See: https://github.com/emilk/egui/issues/903 if let Some(id) = viewport_id && shared.resized_viewport == viewport_id { shared.painter.on_window_resize_state_change(id, false); shared.resized_viewport = None; } match event { winit::event::WindowEvent::Focused(focused) => { let focused = if cfg!(target_os = "macos") && let Some(viewport_id) = viewport_id && let Some(viewport) = shared.viewports.get(&viewport_id) && let Some(window) = &viewport.window { // TODO(emilk): remove this work-around once we update winit // https://github.com/rust-windowing/winit/issues/4371 // https://github.com/emilk/egui/issues/7588 window.has_focus() } else { *focused }; shared.focused_viewport = focused.then_some(viewport_id).flatten(); } winit::event::WindowEvent::Resized(physical_size) => { // Resize with 0 width and height is used by winit to signal a minimize event on Windows. // See: https://github.com/rust-windowing/winit/issues/208 // This solves an issue where the app would panic when minimizing on Windows. if let Some(id) = viewport_id && let (Some(width), Some(height)) = ( NonZeroU32::new(physical_size.width), NonZeroU32::new(physical_size.height), ) { if shared.resized_viewport != viewport_id { shared.resized_viewport = viewport_id; shared.painter.on_window_resize_state_change(id, true); } shared.painter.on_window_resized(id, width, height); repaint_asap = true; } } winit::event::WindowEvent::CloseRequested => { if viewport_id == Some(ViewportId::ROOT) && integration.should_close() { log::debug!( "Received WindowEvent::CloseRequested for main viewport - shutting down." ); return EventResult::CloseRequested; } log::debug!("Received WindowEvent::CloseRequested for viewport {viewport_id:?}"); if let Some(viewport_id) = viewport_id && let Some(viewport) = shared.viewports.get_mut(&viewport_id) { // Tell viewport it should close: viewport.info.events.push(egui::ViewportEvent::Close); // We may need to repaint both us and our parent to close the window, // and perhaps twice (once to notice the close-event, once again to enforce it). // `request_repaint_of` does a double-repaint though: integration.egui_ctx.request_repaint_of(viewport_id); integration.egui_ctx.request_repaint_of(viewport.ids.parent); } } _ => {} } let event_response = viewport_id .and_then(|viewport_id| { let viewport = shared.viewports.get_mut(&viewport_id)?; Some(integration.on_window_event( viewport.window.as_deref()?, viewport.egui_winit.as_mut()?, event, )) }) .unwrap_or_default(); if integration.should_close() { EventResult::CloseRequested } else if event_response.repaint { if repaint_asap { EventResult::RepaintNow(window_id) } else { EventResult::RepaintNext(window_id) } } else { EventResult::Wait } } } impl Viewport { /// Create winit window, if needed. fn initialize_window( &mut self, event_loop: &ActiveEventLoop, egui_ctx: &egui::Context, windows_id: &mut HashMap<WindowId, ViewportId>, painter: &mut egui_wgpu::winit::Painter, ) { if self.window.is_some() { return; // we already have one } profiling::function_scope!(); let viewport_id = self.ids.this; match egui_winit::create_window(egui_ctx, event_loop, &self.builder) { Ok(window) => { windows_id.insert(window.id(), viewport_id); let window = Arc::new(window); if let Err(err) = pollster::block_on(painter.set_window(viewport_id, Some(Arc::clone(&window)))) { log::error!("on set_window: viewport_id {viewport_id:?} {err}"); } self.egui_winit = Some(egui_winit::State::new( egui_ctx.clone(), viewport_id, event_loop, Some(window.scale_factor() as f32), event_loop.system_theme(), painter.max_texture_side(), )); egui_winit::update_viewport_info(&mut self.info, egui_ctx, &window, true); self.window = Some(window); } Err(err) => { log::error!("Failed to create window: {err}"); } } } } fn create_window( egui_ctx: &egui::Context,
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
true
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/eframe/src/native/epi_integration.rs
crates/eframe/src/native/epi_integration.rs
//! Common tools used by [`super::glow_integration`] and [`super::wgpu_integration`]. use web_time::Instant; use std::path::PathBuf; use winit::event_loop::ActiveEventLoop; use raw_window_handle::{HasDisplayHandle as _, HasWindowHandle as _}; use egui::{DeferredViewportUiCallback, ViewportBuilder, ViewportId}; use egui_winit::{EventResponse, WindowSettings}; use crate::epi; #[cfg_attr(target_os = "ios", allow(dead_code, unused_variables, unused_mut))] pub fn viewport_builder( egui_zoom_factor: f32, event_loop: &ActiveEventLoop, native_options: &mut epi::NativeOptions, window_settings: Option<WindowSettings>, ) -> ViewportBuilder { profiling::function_scope!(); let mut viewport_builder = native_options.viewport.clone(); // On some Linux systems, a window size larger than the monitor causes crashes, // and on Windows the window does not appear at all. let clamp_size_to_monitor_size = viewport_builder.clamp_size_to_monitor_size.unwrap_or(true); // Always use the default window size / position on iOS. Trying to restore the previous position // causes the window to be shown too small. #[cfg(not(target_os = "ios"))] let inner_size_points = if let Some(mut window_settings) = window_settings { // Restore pos/size from previous session if clamp_size_to_monitor_size { window_settings.clamp_size_to_sane_values(largest_monitor_point_size( egui_zoom_factor, event_loop, )); } window_settings.clamp_position_to_monitors(egui_zoom_factor, event_loop); viewport_builder = window_settings.initialize_viewport_builder( egui_zoom_factor, event_loop, viewport_builder, ); window_settings.inner_size_points() } else { if let Some(pos) = viewport_builder.position { viewport_builder = viewport_builder.with_position(pos); } if clamp_size_to_monitor_size && let Some(initial_window_size) = viewport_builder.inner_size { let initial_window_size = egui::NumExt::at_most( initial_window_size, largest_monitor_point_size(egui_zoom_factor, event_loop), ); viewport_builder = viewport_builder.with_inner_size(initial_window_size); } viewport_builder.inner_size }; #[cfg(not(target_os = "ios"))] if native_options.centered { profiling::scope!("center"); if let Some(monitor) = event_loop .primary_monitor() .or_else(|| event_loop.available_monitors().next()) { let monitor_size = monitor .size() .to_logical::<f32>(egui_zoom_factor as f64 * monitor.scale_factor()); let inner_size = inner_size_points.unwrap_or(egui::Vec2 { x: 800.0, y: 600.0 }); if 0.0 < monitor_size.width && 0.0 < monitor_size.height { let x = (monitor_size.width - inner_size.x) / 2.0; let y = (monitor_size.height - inner_size.y) / 2.0; viewport_builder = viewport_builder.with_position([x, y]); } } } match std::mem::take(&mut native_options.window_builder) { Some(hook) => hook(viewport_builder), None => viewport_builder, } } pub fn apply_window_settings( window: &winit::window::Window, window_settings: Option<WindowSettings>, ) { profiling::function_scope!(); if let Some(window_settings) = window_settings { window_settings.initialize_window(window); } } #[cfg(not(target_os = "ios"))] fn largest_monitor_point_size(egui_zoom_factor: f32, event_loop: &ActiveEventLoop) -> egui::Vec2 { profiling::function_scope!(); let mut max_size = egui::Vec2::ZERO; let available_monitors = { profiling::scope!("available_monitors"); event_loop.available_monitors() }; for monitor in available_monitors { let size = monitor .size() .to_logical::<f32>(egui_zoom_factor as f64 * monitor.scale_factor()); let size = egui::vec2(size.width, size.height); max_size = max_size.max(size); } if max_size == egui::Vec2::ZERO { egui::Vec2::splat(16000.0) } else { max_size } } // ---------------------------------------------------------------------------- /// For loading/saving app state and/or egui memory to disk. pub fn create_storage(_app_name: &str) -> Option<Box<dyn epi::Storage>> { #[cfg(feature = "persistence")] if let Some(storage) = super::file_storage::FileStorage::from_app_id(_app_name) { return Some(Box::new(storage)); } None } #[allow(clippy::allow_attributes, clippy::unnecessary_wraps)] pub fn create_storage_with_file(_file: impl Into<PathBuf>) -> Option<Box<dyn epi::Storage>> { #[cfg(feature = "persistence")] return Some(Box::new( super::file_storage::FileStorage::from_ron_filepath(_file), )); #[cfg(not(feature = "persistence"))] None } // ---------------------------------------------------------------------------- /// Everything needed to make a winit-based integration for [`epi`]. /// /// Only one instance per app (not one per viewport). pub struct EpiIntegration { pub frame: epi::Frame, last_auto_save: Instant, pub beginning: Instant, is_first_frame: bool, pub egui_ctx: egui::Context, pending_full_output: egui::FullOutput, /// When set, it is time to close the native window. close: bool, can_drag_window: bool, #[cfg(feature = "persistence")] persist_window: bool, app_icon_setter: super::app_icon::AppTitleIconSetter, } impl EpiIntegration { #[allow(clippy::allow_attributes, clippy::too_many_arguments)] pub fn new( egui_ctx: egui::Context, window: &winit::window::Window, app_name: &str, native_options: &crate::NativeOptions, storage: Option<Box<dyn epi::Storage>>, #[cfg(feature = "glow")] gl: Option<std::sync::Arc<glow::Context>>, #[cfg(feature = "glow")] glow_register_native_texture: Option< Box<dyn FnMut(glow::Texture) -> egui::TextureId>, >, #[cfg(feature = "wgpu_no_default_features")] wgpu_render_state: Option< egui_wgpu::RenderState, >, ) -> Self { let frame = epi::Frame { info: epi::IntegrationInfo { cpu_usage: None }, storage, #[cfg(feature = "glow")] gl, #[cfg(feature = "glow")] glow_register_native_texture, #[cfg(feature = "wgpu_no_default_features")] wgpu_render_state, raw_display_handle: window.display_handle().map(|h| h.as_raw()), raw_window_handle: window.window_handle().map(|h| h.as_raw()), }; let icon = native_options .viewport .icon .clone() .unwrap_or_else(|| std::sync::Arc::new(load_default_egui_icon())); let app_icon_setter = super::app_icon::AppTitleIconSetter::new( native_options .viewport .title .clone() .unwrap_or_else(|| app_name.to_owned()), Some(icon), ); Self { frame, last_auto_save: Instant::now(), egui_ctx, pending_full_output: Default::default(), close: false, can_drag_window: false, #[cfg(feature = "persistence")] persist_window: native_options.persist_window, app_icon_setter, beginning: Instant::now(), is_first_frame: true, } } /// If `true`, it is time to close the native window. pub fn should_close(&self) -> bool { self.close } pub fn on_window_event( &mut self, window: &winit::window::Window, egui_winit: &mut egui_winit::State, event: &winit::event::WindowEvent, ) -> EventResponse { profiling::function_scope!(egui_winit::short_window_event_description(event)); use winit::event::{ElementState, MouseButton, WindowEvent}; if let WindowEvent::MouseInput { button: MouseButton::Left, state: ElementState::Pressed, .. } = event { self.can_drag_window = true; } egui_winit.on_window_event(window, event) } pub fn pre_update(&mut self) { self.app_icon_setter.update(); } /// Run user code - this can create immediate viewports, so hold no locks over this! /// /// If `viewport_ui_cb` is None, we are in the root viewport and will call [`crate::App::update`]. pub fn update( &mut self, app: &mut dyn epi::App, viewport_ui_cb: Option<&DeferredViewportUiCallback>, mut raw_input: egui::RawInput, ) -> egui::FullOutput { raw_input.time = Some(self.beginning.elapsed().as_secs_f64()); let close_requested = raw_input.viewport().close_requested(); app.raw_input_hook(&self.egui_ctx, &mut raw_input); let full_output = self.egui_ctx.run_ui(raw_input, |ui| { if let Some(viewport_ui_cb) = viewport_ui_cb { // Child viewport profiling::scope!("viewport_callback"); viewport_ui_cb(ui); } else { { profiling::scope!("App::logic"); app.logic(ui.ctx(), &mut self.frame); } { profiling::scope!("App::update"); #[expect(deprecated)] app.update(ui.ctx(), &mut self.frame); } { profiling::scope!("App::ui"); app.ui(ui, &mut self.frame); } } }); let is_root_viewport = viewport_ui_cb.is_none(); if is_root_viewport && close_requested { let canceled = full_output.viewport_output[&ViewportId::ROOT] .commands .contains(&egui::ViewportCommand::CancelClose); if canceled { log::debug!("Closing of root viewport canceled with ViewportCommand::CancelClose"); } else { log::debug!("Closing root viewport (ViewportCommand::CancelClose was not sent)"); self.close = true; } } self.pending_full_output.append(full_output); std::mem::take(&mut self.pending_full_output) } pub fn report_frame_time(&mut self, seconds: f32) { self.frame.info.cpu_usage = Some(seconds); } pub fn post_rendering(&mut self, window: &winit::window::Window) { profiling::function_scope!(); if std::mem::take(&mut self.is_first_frame) { // We keep hidden until we've painted something. See https://github.com/emilk/egui/pull/2279 window.set_visible(true); } } // ------------------------------------------------------------------------ // Persistence stuff: pub fn maybe_autosave( &mut self, app: &mut dyn epi::App, window: Option<&winit::window::Window>, ) { let now = Instant::now(); if now - self.last_auto_save > app.auto_save_interval() { self.save(app, window); self.last_auto_save = now; } } pub fn save(&mut self, app: &mut dyn epi::App, window: Option<&winit::window::Window>) { #[cfg(not(feature = "persistence"))] let _ = (self, app, window); #[cfg(feature = "persistence")] if let Some(storage) = self.frame.storage_mut() { profiling::function_scope!(); if let Some(window) = window && self.persist_window { profiling::scope!("native_window"); epi::set_value( storage, STORAGE_WINDOW_KEY, &WindowSettings::from_window(self.egui_ctx.zoom_factor(), window), ); } if app.persist_egui_memory() { profiling::scope!("egui_memory"); self.egui_ctx .memory(|mem| epi::set_value(storage, STORAGE_EGUI_MEMORY_KEY, mem)); } { profiling::scope!("App::save"); app.save(storage); } profiling::scope!("Storage::flush"); storage.flush(); } } } fn load_default_egui_icon() -> egui::IconData { profiling::function_scope!(); #[expect(clippy::unwrap_used)] crate::icon_data::from_png_bytes(&include_bytes!("../../data/icon.png")[..]).unwrap() } #[cfg(feature = "persistence")] const STORAGE_EGUI_MEMORY_KEY: &str = "egui"; #[cfg(feature = "persistence")] const STORAGE_WINDOW_KEY: &str = "window"; pub fn load_window_settings(_storage: Option<&dyn epi::Storage>) -> Option<WindowSettings> { profiling::function_scope!(); #[cfg(feature = "persistence")] { epi::get_value(_storage?, STORAGE_WINDOW_KEY) } #[cfg(not(feature = "persistence"))] None } pub fn load_egui_memory(_storage: Option<&dyn epi::Storage>) -> Option<egui::Memory> { profiling::function_scope!(); #[cfg(feature = "persistence")] { epi::get_value(_storage?, STORAGE_EGUI_MEMORY_KEY) } #[cfg(not(feature = "persistence"))] None }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/eframe/src/native/glow_integration.rs
crates/eframe/src/native/glow_integration.rs
//! Note that this file contains code very similar to [`super::wgpu_integration`]. //! When making changes to one you often also want to apply it to the other. //! //! This is also very complex code, and not very pretty. //! There is a bunch of improvements we could do, //! like removing a bunch of `unwraps`. #![expect(clippy::undocumented_unsafe_blocks)] #![expect(clippy::unwrap_used)] use std::{cell::RefCell, num::NonZeroU32, rc::Rc, sync::Arc, time::Instant}; use egui_winit::ActionRequested; use glutin::{ config::GlConfig as _, context::NotCurrentGlContext as _, display::GetGlDisplay as _, prelude::{GlDisplay as _, PossiblyCurrentGlContext as _}, surface::GlSurface as _, }; use raw_window_handle::HasWindowHandle as _; use winit::{ event_loop::{ActiveEventLoop, EventLoop, EventLoopProxy}, window::{Window, WindowId}, }; use ahash::HashMap; use egui::{ DeferredViewportUiCallback, ImmediateViewport, OrderedViewportIdMap, ViewportBuilder, ViewportClass, ViewportId, ViewportIdPair, ViewportInfo, ViewportOutput, }; #[cfg(feature = "accesskit")] use egui_winit::accesskit_winit; use crate::{ App, AppCreator, CreationContext, NativeOptions, Result, Storage, native::epi_integration::EpiIntegration, }; use super::{ epi_integration, event_loop_context, winit_integration::{EventResult, UserEvent, WinitApp, create_egui_context}, }; // ---------------------------------------------------------------------------- // Types: pub struct GlowWinitApp<'app> { repaint_proxy: Arc<egui::mutex::Mutex<EventLoopProxy<UserEvent>>>, app_name: String, native_options: NativeOptions, running: Option<GlowWinitRunning<'app>>, // Note that since this `AppCreator` is FnOnce we are currently unable to support // re-initializing the `GlowWinitRunning` state on Android if the application // suspends and resumes. app_creator: Option<AppCreator<'app>>, } /// State that is initialized when the application is first starts running via /// a Resumed event. On Android this ensures that any graphics state is only /// initialized once the application has an associated `SurfaceView`. struct GlowWinitRunning<'app> { integration: EpiIntegration, app: Box<dyn 'app + App>, // These needs to be shared with the immediate viewport renderer, hence the Rc/Arc/RefCells: glutin: Rc<RefCell<GlutinWindowContext>>, // NOTE: one painter shared by all viewports. painter: Rc<RefCell<egui_glow::Painter>>, } /// This struct will contain both persistent and temporary glutin state. /// /// Platform Quirks: /// * Microsoft Windows: requires that we create a window before opengl context. /// * Android: window and surface should be destroyed when we receive a suspend event. recreate on resume event. /// /// winit guarantees that we will get a Resumed event on startup on all platforms. /// * Before Resumed event: `gl_config`, `gl_context` can be created at any time. on windows, a window must be created to get `gl_context`. /// * Resumed: `gl_surface` will be created here. `window` will be re-created here for android. /// * Suspended: on android, we drop window + surface. on other platforms, we don't get Suspended event. /// /// The setup is divided between the `new` fn and `on_resume` fn. we can just assume that `on_resume` is a continuation of /// `new` fn on all platforms. only on android, do we get multiple resumed events because app can be suspended. struct GlutinWindowContext { egui_ctx: egui::Context, swap_interval: glutin::surface::SwapInterval, gl_config: glutin::config::Config, max_texture_side: Option<usize>, current_gl_context: Option<glutin::context::PossiblyCurrentContext>, not_current_gl_context: Option<glutin::context::NotCurrentContext>, viewports: OrderedViewportIdMap<Viewport>, viewport_from_window: HashMap<WindowId, ViewportId>, window_from_viewport: OrderedViewportIdMap<WindowId>, focused_viewport: Option<ViewportId>, } struct Viewport { ids: ViewportIdPair, class: ViewportClass, builder: ViewportBuilder, deferred_commands: Vec<egui::viewport::ViewportCommand>, info: ViewportInfo, actions_requested: Vec<egui_winit::ActionRequested>, /// The user-callback that shows the ui. /// None for immediate viewports. viewport_ui_cb: Option<Arc<DeferredViewportUiCallback>>, // These three live and die together. // TODO(emilk): clump them together into one struct! gl_surface: Option<glutin::surface::Surface<glutin::surface::WindowSurface>>, window: Option<Arc<Window>>, egui_winit: Option<egui_winit::State>, } // ---------------------------------------------------------------------------- impl<'app> GlowWinitApp<'app> { pub fn new( event_loop: &EventLoop<UserEvent>, app_name: &str, native_options: NativeOptions, app_creator: AppCreator<'app>, ) -> Self { profiling::function_scope!(); Self { repaint_proxy: Arc::new(egui::mutex::Mutex::new(event_loop.create_proxy())), app_name: app_name.to_owned(), native_options, running: None, app_creator: Some(app_creator), } } #[expect(unsafe_code)] fn create_glutin_windowed_context( egui_ctx: &egui::Context, event_loop: &ActiveEventLoop, storage: Option<&dyn Storage>, native_options: &mut NativeOptions, ) -> Result<(GlutinWindowContext, egui_glow::Painter)> { profiling::function_scope!(); let window_settings = epi_integration::load_window_settings(storage); let winit_window_builder = epi_integration::viewport_builder( egui_ctx.zoom_factor(), event_loop, native_options, window_settings, ) .with_visible(false); // Start hidden until we render the first frame to fix white flash on startup (https://github.com/emilk/egui/pull/3631) let mut glutin_window_context = unsafe { GlutinWindowContext::new(egui_ctx, winit_window_builder, native_options, event_loop)? }; // Creates the window - must come before we create our glow context glutin_window_context.initialize_window(ViewportId::ROOT, event_loop)?; { let viewport = &glutin_window_context.viewports[&ViewportId::ROOT]; let window = viewport.window.as_ref().unwrap(); // Can't fail - we just called `initialize_all_viewports` epi_integration::apply_window_settings(window, window_settings); } let gl = unsafe { profiling::scope!("glow::Context::from_loader_function"); Arc::new(glow::Context::from_loader_function(|s| { let s = std::ffi::CString::new(s) .expect("failed to construct C string from string for gl proc address"); glutin_window_context.get_proc_address(&s) })) }; let painter = egui_glow::Painter::new( gl, "", native_options.shader_version, native_options.dithering, )?; Ok((glutin_window_context, painter)) } fn init_run_state( &mut self, event_loop: &ActiveEventLoop, ) -> Result<&mut GlowWinitRunning<'app>> { profiling::function_scope!(); let storage = if let Some(file) = &self.native_options.persistence_path { epi_integration::create_storage_with_file(file) } else { epi_integration::create_storage( self.native_options .viewport .app_id .as_ref() .unwrap_or(&self.app_name), ) }; let egui_ctx = create_egui_context(storage.as_deref()); let (mut glutin, painter) = Self::create_glutin_windowed_context( &egui_ctx, event_loop, storage.as_deref(), &mut self.native_options, )?; let gl = Arc::clone(painter.gl()); let max_texture_side = painter.max_texture_side(); glutin.max_texture_side = Some(max_texture_side); for viewport in glutin.viewports.values_mut() { if let Some(egui_winit) = viewport.egui_winit.as_mut() { egui_winit.set_max_texture_side(max_texture_side); } } let painter = Rc::new(RefCell::new(painter)); let integration = EpiIntegration::new( egui_ctx, &glutin.window(ViewportId::ROOT), &self.app_name, &self.native_options, storage, Some(Arc::clone(&gl)), Some(Box::new({ let painter = Rc::clone(&painter); move |native| painter.borrow_mut().register_native_texture(native) })), #[cfg(feature = "wgpu_no_default_features")] None, ); { let event_loop_proxy = Arc::clone(&self.repaint_proxy); integration .egui_ctx .set_request_repaint_callback(move |info| { log::trace!("request_repaint_callback: {info:?}"); let when = Instant::now() + info.delay; let cumulative_pass_nr = info.current_cumulative_pass_nr; event_loop_proxy .lock() .send_event(UserEvent::RequestRepaint { viewport_id: info.viewport_id, when, cumulative_pass_nr, }) .ok(); }); } #[cfg(feature = "accesskit")] { let event_loop_proxy = self.repaint_proxy.lock().clone(); let viewport = glutin.viewports.get_mut(&ViewportId::ROOT).unwrap(); // we always have a root if let Viewport { window: Some(window), egui_winit: Some(egui_winit), .. } = viewport { egui_winit.init_accesskit(event_loop, window, event_loop_proxy); } } if self .native_options .viewport .mouse_passthrough .unwrap_or(false) && let Err(err) = glutin.window(ViewportId::ROOT).set_cursor_hittest(false) { log::warn!("set_cursor_hittest(false) failed: {err}"); } let app_creator = std::mem::take(&mut self.app_creator) .expect("Single-use AppCreator has unexpectedly already been taken"); let app: Box<dyn 'app + App> = { // Use latest raw_window_handle for eframe compatibility use raw_window_handle::{HasDisplayHandle as _, HasWindowHandle as _}; let get_proc_address = |addr: &_| glutin.get_proc_address(addr); let window = glutin.window(ViewportId::ROOT); let cc = CreationContext { egui_ctx: integration.egui_ctx.clone(), integration_info: integration.frame.info().clone(), storage: integration.frame.storage(), gl: Some(gl), get_proc_address: Some(&get_proc_address), #[cfg(feature = "wgpu_no_default_features")] wgpu_render_state: None, raw_display_handle: window.display_handle().map(|h| h.as_raw()), raw_window_handle: window.window_handle().map(|h| h.as_raw()), }; profiling::scope!("app_creator"); app_creator(&cc).map_err(crate::Error::AppCreation)? }; let glutin = Rc::new(RefCell::new(glutin)); { // Create weak pointers so that we don't keep // state alive for too long. let glutin = Rc::downgrade(&glutin); let painter = Rc::downgrade(&painter); let beginning = integration.beginning; egui::Context::set_immediate_viewport_renderer(move |egui_ctx, immediate_viewport| { if let (Some(glutin), Some(painter)) = (glutin.upgrade(), painter.upgrade()) { render_immediate_viewport( egui_ctx, &glutin, &painter, beginning, immediate_viewport, ); } else { log::warn!("render_sync_callback called after window closed"); } }); } Ok(self.running.insert(GlowWinitRunning { integration, app, glutin, painter, })) } } impl WinitApp for GlowWinitApp<'_> { fn egui_ctx(&self) -> Option<&egui::Context> { self.running.as_ref().map(|r| &r.integration.egui_ctx) } fn window(&self, window_id: WindowId) -> Option<Arc<Window>> { let running = self.running.as_ref()?; let glutin = running.glutin.borrow(); let viewport_id = *glutin.viewport_from_window.get(&window_id)?; if let Some(viewport) = glutin.viewports.get(&viewport_id) { viewport.window.clone() } else { None } } fn window_id_from_viewport_id(&self, id: ViewportId) -> Option<WindowId> { self.running .as_ref()? .glutin .borrow() .window_from_viewport .get(&id) .copied() } fn save(&mut self) { log::debug!("WinitApp::save called"); if let Some(running) = self.running.as_mut() { profiling::function_scope!(); // This is used because of the "save on suspend" logic on Android. Once the application is suspended, there is no window associated to it, which was causing panics when `.window().expect()` was used. let window_opt = running.glutin.borrow().window_opt(ViewportId::ROOT); running .integration .save(running.app.as_mut(), window_opt.as_deref()); } } fn save_and_destroy(&mut self) { if let Some(mut running) = self.running.take() { profiling::function_scope!(); running.integration.save( running.app.as_mut(), Some(&running.glutin.borrow().window(ViewportId::ROOT)), ); running.app.on_exit(Some(running.painter.borrow().gl())); running.painter.borrow_mut().destroy(); } } fn run_ui_and_paint( &mut self, event_loop: &ActiveEventLoop, window_id: WindowId, ) -> Result<EventResult> { if let Some(running) = &mut self.running { running.run_ui_and_paint(event_loop, window_id) } else { Ok(EventResult::Wait) } } fn resumed(&mut self, event_loop: &ActiveEventLoop) -> crate::Result<EventResult> { log::debug!("Event::Resumed"); let running = if let Some(running) = &mut self.running { // Not the first resume event. Create all outstanding windows. running .glutin .borrow_mut() .initialize_all_windows(event_loop); running } else { // First resume event. Create our root window etc. self.init_run_state(event_loop)? }; let window_id = running.glutin.borrow().window_from_viewport[&ViewportId::ROOT]; Ok(EventResult::RepaintNow(window_id)) } fn suspended(&mut self, _: &ActiveEventLoop) -> crate::Result<EventResult> { if let Some(running) = &mut self.running { running.glutin.borrow_mut().on_suspend()?; } Ok(EventResult::Save) } fn device_event( &mut self, _: &ActiveEventLoop, _: winit::event::DeviceId, event: winit::event::DeviceEvent, ) -> crate::Result<EventResult> { if let winit::event::DeviceEvent::MouseMotion { delta } = event && let Some(running) = &mut self.running { let mut glutin = running.glutin.borrow_mut(); if let Some(viewport) = glutin .focused_viewport .and_then(|viewport| glutin.viewports.get_mut(&viewport)) { if let Some(egui_winit) = viewport.egui_winit.as_mut() { egui_winit.on_mouse_motion(delta); } if let Some(window) = viewport.window.as_ref() { return Ok(EventResult::RepaintNext(window.id())); } } } Ok(EventResult::Wait) } fn window_event( &mut self, _: &ActiveEventLoop, window_id: WindowId, event: winit::event::WindowEvent, ) -> Result<EventResult> { if let Some(running) = &mut self.running { Ok(running.on_window_event(window_id, &event)) } else { Ok(EventResult::Exit) } } #[cfg(feature = "accesskit")] fn on_accesskit_event(&mut self, event: accesskit_winit::Event) -> crate::Result<EventResult> { use super::winit_integration; if let Some(running) = &self.running { let mut glutin = running.glutin.borrow_mut(); if let Some(viewport_id) = glutin.viewport_from_window.get(&event.window_id).copied() && let Some(viewport) = glutin.viewports.get_mut(&viewport_id) && let Some(egui_winit) = &mut viewport.egui_winit { return Ok(winit_integration::on_accesskit_window_event( egui_winit, event.window_id, &event.window_event, )); } } Ok(EventResult::Wait) } } impl GlowWinitRunning<'_> { fn run_ui_and_paint( &mut self, event_loop: &ActiveEventLoop, window_id: WindowId, ) -> Result<EventResult> { profiling::function_scope!(); let Some(viewport_id) = self .glutin .borrow() .viewport_from_window .get(&window_id) .copied() else { return Ok(EventResult::Wait); }; profiling::finish_frame!(); let mut frame_timer = crate::stopwatch::Stopwatch::new(); frame_timer.start(); { let glutin = self.glutin.borrow(); let viewport = &glutin.viewports[&viewport_id]; let is_immediate = viewport.viewport_ui_cb.is_none(); if is_immediate && viewport_id != ViewportId::ROOT { // This will only happen if this is an immediate viewport. // That means that the viewport cannot be rendered by itself and needs his parent to be rendered. if let Some(parent_viewport) = glutin.viewports.get(&viewport.ids.parent) && let Some(window) = parent_viewport.window.as_ref() { return Ok(EventResult::RepaintNext(window.id())); } return Ok(EventResult::Wait); } } let (raw_input, viewport_ui_cb) = { let mut glutin = self.glutin.borrow_mut(); let egui_ctx = glutin.egui_ctx.clone(); let Some(viewport) = glutin.viewports.get_mut(&viewport_id) else { return Ok(EventResult::Wait); }; let Some(window) = viewport.window.as_ref() else { return Ok(EventResult::Wait); }; egui_winit::update_viewport_info(&mut viewport.info, &egui_ctx, window, false); let Some(egui_winit) = viewport.egui_winit.as_mut() else { return Ok(EventResult::Wait); }; let mut raw_input = egui_winit.take_egui_input(window); let viewport_ui_cb = viewport.viewport_ui_cb.clone(); self.integration.pre_update(); raw_input.time = Some(self.integration.beginning.elapsed().as_secs_f64()); raw_input.viewports = glutin .viewports .iter() .map(|(id, viewport)| (*id, viewport.info.clone())) .collect(); (raw_input, viewport_ui_cb) }; // HACK: In order to get the right clear_color, the system theme needs to be set, which // usually only happens in the `update` call. So we call Options::begin_pass early // to set the right theme. Without this there would be a black flash on the first frame. self.integration .egui_ctx .options_mut(|opt| opt.begin_pass(&raw_input)); let clear_color = self .app .clear_color(&self.integration.egui_ctx.global_style().visuals); let has_many_viewports = self.glutin.borrow().viewports.len() > 1; let clear_before_update = !has_many_viewports; // HACK: for some reason, an early clear doesn't "take" on Mac with multiple viewports. if clear_before_update { // clear before we call update, so users can paint between clear-color and egui windows: let mut glutin = self.glutin.borrow_mut(); let GlutinWindowContext { viewports, current_gl_context, not_current_gl_context, .. } = &mut *glutin; let viewport = &viewports[&viewport_id]; let Some(window) = viewport.window.as_ref() else { return Ok(EventResult::Wait); }; let Some(gl_surface) = viewport.gl_surface.as_ref() else { return Ok(EventResult::Wait); }; let screen_size_in_pixels: [u32; 2] = window.inner_size().into(); { frame_timer.pause(); change_gl_context(current_gl_context, not_current_gl_context, gl_surface); frame_timer.resume(); } self.painter .borrow() .clear(screen_size_in_pixels, clear_color); } // ------------------------------------------------------------ // The update function, which could call immediate viewports, // so make sure we don't hold any locks here required by the immediate viewports rendeer. let full_output = self.integration .update(self.app.as_mut(), viewport_ui_cb.as_deref(), raw_input); // ------------------------------------------------------------ let Self { integration, app, glutin, painter, .. } = self; let mut glutin = glutin.borrow_mut(); let mut painter = painter.borrow_mut(); let egui::FullOutput { platform_output, textures_delta, shapes, pixels_per_point, viewport_output, } = full_output; glutin.remove_viewports_not_in(&viewport_output); let GlutinWindowContext { viewports, current_gl_context, not_current_gl_context, .. } = &mut *glutin; let Some(viewport) = viewports.get_mut(&viewport_id) else { return Ok(EventResult::Wait); }; viewport.info.events.clear(); // they should have been processed let window = viewport.window.clone().unwrap(); let gl_surface = viewport.gl_surface.as_ref().unwrap(); let egui_winit = viewport.egui_winit.as_mut().unwrap(); egui_winit.handle_platform_output(&window, platform_output); let clipped_primitives = integration.egui_ctx.tessellate(shapes, pixels_per_point); { // We may need to switch contexts again, because of immediate viewports: frame_timer.pause(); change_gl_context(current_gl_context, not_current_gl_context, gl_surface); frame_timer.resume(); } let screen_size_in_pixels: [u32; 2] = window.inner_size().into(); if !clear_before_update { painter.clear(screen_size_in_pixels, clear_color); } painter.paint_and_update_textures( screen_size_in_pixels, pixels_per_point, &clipped_primitives, &textures_delta, ); { for action in viewport.actions_requested.drain(..) { match action { ActionRequested::Screenshot(user_data) => { let screenshot = painter.read_screen_rgba(screen_size_in_pixels); egui_winit .egui_input_mut() .events .push(egui::Event::Screenshot { viewport_id, user_data, image: screenshot.into(), }); } ActionRequested::Cut => { egui_winit.egui_input_mut().events.push(egui::Event::Cut); } ActionRequested::Copy => { egui_winit.egui_input_mut().events.push(egui::Event::Copy); } ActionRequested::Paste => { if let Some(contents) = egui_winit.clipboard_text() { let contents = contents.replace("\r\n", "\n"); if !contents.is_empty() { egui_winit .egui_input_mut() .events .push(egui::Event::Paste(contents)); } } } } } integration.post_rendering(&window); } { // vsync - don't count as frame-time: frame_timer.pause(); profiling::scope!("swap_buffers"); let context = current_gl_context.as_ref().ok_or_else(|| { egui_glow::PainterError::from( "failed to get current context to swap buffers".to_owned(), ) })?; gl_surface.swap_buffers(context)?; frame_timer.resume(); } // give it time to settle: #[cfg(feature = "__screenshot")] if integration.egui_ctx.cumulative_pass_nr() == 2 && let Ok(path) = std::env::var("EFRAME_SCREENSHOT_TO") { save_screenshot_and_exit(&path, &painter, screen_size_in_pixels); } glutin.handle_viewport_output(event_loop, &integration.egui_ctx, &viewport_output); integration.report_frame_time(frame_timer.total_time_sec()); // don't count auto-save time as part of regular frame time integration.maybe_autosave(app.as_mut(), Some(&window)); if window.is_minimized() == Some(true) { // On Mac, a minimized Window uses up all CPU: // https://github.com/emilk/egui/issues/325 profiling::scope!("minimized_sleep"); std::thread::sleep(std::time::Duration::from_millis(10)); } if integration.should_close() { Ok(EventResult::CloseRequested) } else { Ok(EventResult::Wait) } } fn on_window_event( &mut self, window_id: WindowId, event: &winit::event::WindowEvent, ) -> EventResult { let mut glutin = self.glutin.borrow_mut(); let viewport_id = glutin.viewport_from_window.get(&window_id).copied(); // On Windows, if a window is resized by the user, it should repaint synchronously, inside the // event handler. // // If this is not done, the compositor will assume that the window does not want to redraw, // and continue ahead. // // In eframe's case, that causes the window to rapidly flicker, as it struggles to deliver // new frames to the compositor in time. // // The flickering is technically glutin or glow's fault, but we should be responding properly // to resizes anyway, as doing so avoids dropping frames. // // See: https://github.com/emilk/egui/issues/903 let mut repaint_asap = false; match event { winit::event::WindowEvent::Focused(focused) => { let focused = if cfg!(target_os = "macos") && let Some(viewport_id) = viewport_id && let Some(viewport) = glutin.viewports.get(&viewport_id) && let Some(window) = &viewport.window { // TODO(emilk): remove this work-around once we update winit // https://github.com/rust-windowing/winit/issues/4371 // https://github.com/emilk/egui/issues/7588 window.has_focus() } else { *focused }; glutin.focused_viewport = focused.then_some(viewport_id).flatten(); } winit::event::WindowEvent::Resized(physical_size) => { // Resize with 0 width and height is used by winit to signal a minimize event on Windows. // See: https://github.com/rust-windowing/winit/issues/208 // This solves an issue where the app would panic when minimizing on Windows. if 0 < physical_size.width && 0 < physical_size.height && let Some(viewport_id) = viewport_id { repaint_asap = true; glutin.resize(viewport_id, *physical_size); } } winit::event::WindowEvent::CloseRequested => { if viewport_id == Some(ViewportId::ROOT) && self.integration.should_close() { log::debug!( "Received WindowEvent::CloseRequested for main viewport - shutting down." ); return EventResult::CloseRequested; } log::debug!("Received WindowEvent::CloseRequested for viewport {viewport_id:?}"); if let Some(viewport_id) = viewport_id && let Some(viewport) = glutin.viewports.get_mut(&viewport_id) { // Tell viewport it should close: viewport.info.events.push(egui::ViewportEvent::Close); // We may need to repaint both us and our parent to close the window, // and perhaps twice (once to notice the close-event, once again to enforce it). // `request_repaint_of` does a double-repaint though: self.integration.egui_ctx.request_repaint_of(viewport_id); self.integration .egui_ctx .request_repaint_of(viewport.ids.parent); } } _ => {} } if self.integration.should_close() { return EventResult::CloseRequested; } let mut event_response = egui_winit::EventResponse { consumed: false, repaint: false, }; if let Some(viewport_id) = viewport_id { if let Some(viewport) = glutin.viewports.get_mut(&viewport_id) { if let (Some(window), Some(egui_winit)) = (&viewport.window, &mut viewport.egui_winit) { event_response = self.integration.on_window_event(window, egui_winit, event); } } else { log::trace!("Ignoring event: no viewport for {viewport_id:?}"); } } else { log::trace!("Ignoring event: no viewport_id"); } if event_response.repaint { if repaint_asap { EventResult::RepaintNow(window_id) } else { EventResult::RepaintNext(window_id) } } else { EventResult::Wait } } } fn change_gl_context( current_gl_context: &mut Option<glutin::context::PossiblyCurrentContext>, not_current_gl_context: &mut Option<glutin::context::NotCurrentContext>, gl_surface: &glutin::surface::Surface<glutin::surface::WindowSurface>, ) { profiling::function_scope!(); if !cfg!(target_os = "windows") {
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
true
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/eframe/src/native/app_icon.rs
crates/eframe/src/native/app_icon.rs
//! Set the native app icon at runtime. //! //! TODO(emilk): port this to [`winit`]. use std::sync::Arc; use egui::IconData; pub struct AppTitleIconSetter { title: String, icon_data: Option<Arc<IconData>>, status: AppIconStatus, } impl AppTitleIconSetter { pub fn new(title: String, mut icon_data: Option<Arc<IconData>>) -> Self { if let Some(icon) = &icon_data && **icon == IconData::default() { icon_data = None; } Self { title, icon_data, status: AppIconStatus::NotSetTryAgain, } } /// Call once per frame; we will set the icon when we can. pub fn update(&mut self) { if self.status == AppIconStatus::NotSetTryAgain { self.status = set_title_and_icon(&self.title, self.icon_data.as_deref()); } } } /// In which state the app icon is (as far as we know). #[derive(PartialEq, Eq)] enum AppIconStatus { /// We did not set it or failed to do it. In any case we won't try again. NotSetIgnored, /// We haven't set the icon yet, we should try again next frame. /// /// This can happen repeatedly due to lazy window creation on some platforms. NotSetTryAgain, /// We successfully set the icon and it should be visible now. #[allow(clippy::allow_attributes, dead_code)] // Not used on Linux Set, } /// Sets app icon at runtime. /// /// By setting the icon at runtime and not via resource files etc. we ensure that we'll get the chance /// to set the same icon when the process/window is started from python (which sets its own icon ahead of us!). /// /// Since window creation can be lazy, call this every frame until it's either successfully or gave up. /// (See [`AppIconStatus`]) fn set_title_and_icon(_title: &str, _icon_data: Option<&IconData>) -> AppIconStatus { profiling::function_scope!(); #[cfg(target_os = "windows")] { if let Some(icon_data) = _icon_data { return set_app_icon_windows(icon_data); } } #[cfg(target_os = "macos")] return set_title_and_icon_mac(_title, _icon_data); #[allow(clippy::allow_attributes, unreachable_code)] AppIconStatus::NotSetIgnored } /// Set icon for Windows applications. #[cfg(target_os = "windows")] #[expect(unsafe_code)] fn set_app_icon_windows(icon_data: &IconData) -> AppIconStatus { use crate::icon_data::IconDataExt as _; use windows_sys::Win32::UI::Input::KeyboardAndMouse::GetActiveWindow; use windows_sys::Win32::UI::WindowsAndMessaging::{ CreateIconFromResourceEx, GetSystemMetrics, HICON, ICON_BIG, ICON_SMALL, LR_DEFAULTCOLOR, SM_CXICON, SM_CXSMICON, SendMessageW, WM_SETICON, }; // We would get fairly far already with winit's `set_window_icon` (which is exposed to eframe) actually! // However, it only sets ICON_SMALL, i.e. doesn't allow us to set a higher resolution icon for the task bar. // Also, there is scaling issues, detailed below. // TODO(andreas): This does not set the task bar icon for when our application is started from python. // Things tried so far: // * Querying for an owning window and setting icon there (there doesn't seem to be an owning window) // * using undocumented SetConsoleIcon method (successfully queried via GetProcAddress) // SAFETY: WinApi function without side-effects. let window_handle = unsafe { GetActiveWindow() }; if window_handle.is_null() { // The Window isn't available yet. Try again later! return AppIconStatus::NotSetTryAgain; } fn create_hicon_with_scale(unscaled_image: &image::RgbaImage, target_size: i32) -> HICON { let image_scaled = image::imageops::resize( unscaled_image, target_size as _, target_size as _, image::imageops::Lanczos3, ); // Creating transparent icons with WinApi is a huge mess. // We'd need to go through CreateIconIndirect's ICONINFO struct which then // takes a mask HBITMAP and a color HBITMAP and creating each of these is pain. // Instead we workaround this by creating a png which CreateIconFromResourceEx magically understands. // This is a pretty horrible hack as we spend a lot of time encoding, but at least the code is a lot shorter. let mut image_scaled_bytes: Vec<u8> = Vec::new(); if image_scaled .write_to( &mut std::io::Cursor::new(&mut image_scaled_bytes), image::ImageFormat::Png, ) .is_err() { return std::ptr::null_mut(); } // SAFETY: Creating an HICON which should be readonly on our data. unsafe { CreateIconFromResourceEx( image_scaled_bytes.as_mut_ptr(), image_scaled_bytes.len() as u32, 1, // Means this is an icon, not a cursor. 0x00030000, // Version number of the HICON target_size, // Note that this method can scale, but it does so *very* poorly. So let's avoid that! target_size, LR_DEFAULTCOLOR, ) } } let unscaled_image = match icon_data.to_image() { Ok(unscaled_image) => unscaled_image, Err(err) => { log::warn!("Invalid icon: {err}"); return AppIconStatus::NotSetIgnored; } }; // Only setting ICON_BIG with the icon size for big icons (SM_CXICON) works fine // but the scaling it does then for the small icon is pretty bad. // Instead we set the correct sizes manually and take over the scaling ourselves. // For this to work we first need to set the big icon and then the small one. // // Note that ICON_SMALL may be used even if we don't render a title bar as it may be used in alt+tab! { // SAFETY: WinAPI getter function with no known side effects. let icon_size_big = unsafe { GetSystemMetrics(SM_CXICON) }; let icon_big = create_hicon_with_scale(&unscaled_image, icon_size_big); if icon_big.is_null() { log::warn!("Failed to create HICON (for big icon) from embedded png data."); return AppIconStatus::NotSetIgnored; // We could try independently with the small icon but what's the point, it would look bad! } else { // SAFETY: Unsafe WinApi function, takes objects previously created with WinAPI, all checked for null prior. unsafe { SendMessageW( window_handle, WM_SETICON, ICON_BIG as usize, icon_big as isize, ); } } } { // SAFETY: WinAPI getter function with no known side effects. let icon_size_small = unsafe { GetSystemMetrics(SM_CXSMICON) }; let icon_small = create_hicon_with_scale(&unscaled_image, icon_size_small); if icon_small.is_null() { log::warn!("Failed to create HICON (for small icon) from embedded png data."); return AppIconStatus::NotSetIgnored; } else { // SAFETY: Unsafe WinApi function, takes objects previously created with WinAPI, all checked for null prior. unsafe { SendMessageW( window_handle, WM_SETICON, ICON_SMALL as usize, icon_small as isize, ); } } } // It _probably_ worked out. AppIconStatus::Set } /// Set icon & app title for `MacOS` applications. #[cfg(target_os = "macos")] #[expect(unsafe_code)] fn set_title_and_icon_mac(title: &str, icon_data: Option<&IconData>) -> AppIconStatus { use crate::icon_data::IconDataExt as _; profiling::function_scope!(); use objc2::ClassType as _; use objc2_app_kit::{NSApplication, NSImage}; use objc2_foundation::NSString; // Do NOT use png even though creating `NSImage` from it is much easier than from raw images data! // // Some MacOS versions have a bug where creating an `NSImage` from a png will cause it to load an arbitrary `libpng.dylib`. // If this dylib isn't the right version, the application will crash with SIGBUS. // For details see https://github.com/emilk/egui/issues/7155 let image = if let Some(icon_data) = icon_data { match icon_data.to_image() { Ok(image) => Some(image), Err(err) => { log::warn!("Failed to read icon data: {err}"); return AppIconStatus::NotSetIgnored; } } } else { None }; // TODO(madsmtm): Move this into `objc2-app-kit` unsafe extern "C" { static NSApp: Option<&'static NSApplication>; } // SAFETY: we don't do anything dangerous here unsafe { let Some(app) = NSApp else { log::debug!("NSApp is null"); return AppIconStatus::NotSetIgnored; }; if let Some(image) = image { use objc2_app_kit::{NSBitmapImageRep, NSDeviceRGBColorSpace}; use objc2_foundation::NSSize; log::trace!( "NSBitmapImageRep::initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel" ); let Some(image_rep) = NSBitmapImageRep::initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel( NSBitmapImageRep::alloc(), [image.as_raw().as_ptr().cast_mut()].as_mut_ptr(), image.width() as isize, image.height() as isize, 8, // bits per sample 4, // samples per pixel true, // has alpha false, // is not planar NSDeviceRGBColorSpace, (image.width() * 4) as isize, // bytes per row 32 // bits per pixel ) else { log::warn!("Failed to create NSBitmapImageRep from app icon data."); return AppIconStatus::NotSetIgnored; }; log::trace!("NSImage::initWithSize"); let app_icon = NSImage::initWithSize( NSImage::alloc(), NSSize::new(image.width() as f64, image.height() as f64), ); log::trace!("NSImage::addRepresentation"); app_icon.addRepresentation(&image_rep); profiling::scope!("setApplicationIconImage_"); log::trace!("setApplicationIconImage…"); app.setApplicationIconImage(Some(&app_icon)); } // Change the title in the top bar - for python processes this would be again "python" otherwise. if let Some(main_menu) = app.mainMenu() && let Some(item) = main_menu.itemAtIndex(0) && let Some(app_menu) = item.submenu() { profiling::scope!("setTitle_"); app_menu.setTitle(&NSString::from_str(title)); } // The title in the Dock apparently can't be changed. // At least these people didn't figure it out either: // https://stackoverflow.com/questions/69831167/qt-change-application-title-dynamically-on-macos // https://stackoverflow.com/questions/28808226/changing-cocoa-app-icon-title-and-menu-labels-at-runtime } AppIconStatus::Set }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/eframe/src/native/mod.rs
crates/eframe/src/native/mod.rs
mod app_icon; mod epi_integration; mod event_loop_context; pub mod run; /// File storage which can be used by native backends. #[cfg(feature = "persistence")] pub mod file_storage; pub(crate) mod winit_integration; #[cfg(feature = "glow")] mod glow_integration; #[cfg(feature = "wgpu_no_default_features")] mod wgpu_integration;
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/eframe/src/native/run.rs
crates/eframe/src/native/run.rs
use std::time::Instant; use winit::{ application::ApplicationHandler, event_loop::{ActiveEventLoop, ControlFlow, EventLoop}, window::WindowId, }; use ahash::HashMap; use super::winit_integration::{UserEvent, WinitApp}; use crate::{ Result, epi, native::{event_loop_context, winit_integration::EventResult}, }; // ---------------------------------------------------------------------------- fn create_event_loop(native_options: &mut epi::NativeOptions) -> Result<EventLoop<UserEvent>> { #[cfg(target_os = "android")] use winit::platform::android::EventLoopBuilderExtAndroid as _; profiling::function_scope!(); let mut builder = winit::event_loop::EventLoop::with_user_event(); #[cfg(target_os = "android")] let mut builder = builder.with_android_app(native_options.android_app.take().ok_or_else(|| { crate::Error::AppCreation(Box::from( "`NativeOptions` is missing required `android_app`", )) })?); if let Some(hook) = std::mem::take(&mut native_options.event_loop_builder) { hook(&mut builder); } profiling::scope!("EventLoopBuilder::build"); Ok(builder.build()?) } /// Access a thread-local event loop. /// /// We reuse the event-loop so we can support closing and opening an eframe window /// multiple times. This is just a limitation of winit. #[cfg(not(target_os = "ios"))] fn with_event_loop<R>( mut native_options: epi::NativeOptions, f: impl FnOnce(&mut EventLoop<UserEvent>, epi::NativeOptions) -> R, ) -> Result<R> { thread_local!(static EVENT_LOOP: std::cell::RefCell<Option<EventLoop<UserEvent>>> = const { std::cell::RefCell::new(None) }); EVENT_LOOP.with(|event_loop| { // Since we want to reference NativeOptions when creating the EventLoop we can't // do that as part of the lazy thread local storage initialization and so we instead // create the event loop lazily here let mut event_loop_lock = event_loop.borrow_mut(); let event_loop = if let Some(event_loop) = &mut *event_loop_lock { event_loop } else { event_loop_lock.insert(create_event_loop(&mut native_options)?) }; Ok(f(event_loop, native_options)) }) } /// Wraps a [`WinitApp`] to implement [`ApplicationHandler`]. This handles redrawing, exit states, and /// some events, but otherwise forwards events to the [`WinitApp`]. struct WinitAppWrapper<T: WinitApp> { windows_next_repaint_times: HashMap<WindowId, Instant>, winit_app: T, return_result: Result<(), crate::Error>, run_and_return: bool, } impl<T: WinitApp> WinitAppWrapper<T> { fn new(winit_app: T, run_and_return: bool) -> Self { Self { windows_next_repaint_times: HashMap::default(), winit_app, return_result: Ok(()), run_and_return, } } fn handle_event_result( &mut self, event_loop: &ActiveEventLoop, event_result: Result<EventResult>, ) { let mut exit = false; let mut save = false; log::trace!("event_result: {event_result:?}"); let mut event_result = event_result; if cfg!(target_os = "windows") && let Ok(EventResult::RepaintNow(window_id)) = event_result { log::trace!("RepaintNow of {window_id:?}"); self.windows_next_repaint_times .insert(window_id, Instant::now()); // Fix flickering on Windows, see https://github.com/emilk/egui/pull/2280 event_result = self.winit_app.run_ui_and_paint(event_loop, window_id); } let combined_result = event_result.map(|event_result| match event_result { EventResult::Wait => { event_loop.set_control_flow(ControlFlow::Wait); event_result } EventResult::RepaintNow(window_id) => { log::trace!("RepaintNow of {window_id:?}",); self.windows_next_repaint_times .insert(window_id, Instant::now()); event_result } EventResult::RepaintNext(window_id) => { log::trace!("RepaintNext of {window_id:?}",); self.windows_next_repaint_times .insert(window_id, Instant::now()); event_result } EventResult::RepaintAt(window_id, repaint_time) => { self.windows_next_repaint_times.insert( window_id, self.windows_next_repaint_times .get(&window_id) .map_or(repaint_time, |last| (*last).min(repaint_time)), ); event_result } EventResult::Save => { save = true; event_result } EventResult::Exit => { exit = true; event_result } EventResult::CloseRequested => { // The windows need to be dropped whilst the event loop is running to allow for proper cleanup. self.winit_app.save_and_destroy(); event_result } }); if let Err(err) = combined_result { log::error!("Exiting because of error: {err}"); exit = true; self.return_result = Err(err); } if save { log::debug!("Received an EventResult::Save - saving app state"); self.winit_app.save(); } if exit { if self.run_and_return { log::debug!("Asking to exit event loop…"); event_loop.exit(); } else { log::debug!("Quitting - saving app state…"); self.winit_app.save_and_destroy(); log::debug!("Exiting with return code 0"); std::process::exit(0); } } self.check_redraw_requests(event_loop); } fn check_redraw_requests(&mut self, event_loop: &ActiveEventLoop) { let now = Instant::now(); self.windows_next_repaint_times .retain(|window_id, repaint_time| { if now < *repaint_time { return true; // not yet ready } event_loop.set_control_flow(ControlFlow::Poll); if let Some(window) = self.winit_app.window(*window_id) { log::trace!("request_redraw for {window_id:?}"); window.request_redraw(); } else { log::trace!("No window found for {window_id:?}"); } false }); let next_repaint_time = self.windows_next_repaint_times.values().min().copied(); if let Some(next_repaint_time) = next_repaint_time { event_loop.set_control_flow(ControlFlow::WaitUntil(next_repaint_time)); } } } impl<T: WinitApp> ApplicationHandler<UserEvent> for WinitAppWrapper<T> { fn suspended(&mut self, event_loop: &ActiveEventLoop) { profiling::scope!("Event::Suspended"); event_loop_context::with_event_loop_context(event_loop, move || { let event_result = self.winit_app.suspended(event_loop); self.handle_event_result(event_loop, event_result); }); } fn resumed(&mut self, event_loop: &ActiveEventLoop) { profiling::scope!("Event::Resumed"); // Nb: Make sure this guard is dropped after this function returns. event_loop_context::with_event_loop_context(event_loop, move || { let event_result = self.winit_app.resumed(event_loop); self.handle_event_result(event_loop, event_result); }); } fn exiting(&mut self, event_loop: &ActiveEventLoop) { // On Mac, Cmd-Q we get here and then `run_app_on_demand` doesn't return (despite its name), // so we need to save state now: log::debug!("Received Event::LoopExiting - saving app state…"); event_loop_context::with_event_loop_context(event_loop, move || { self.winit_app.save_and_destroy(); }); } fn device_event( &mut self, event_loop: &ActiveEventLoop, device_id: winit::event::DeviceId, event: winit::event::DeviceEvent, ) { profiling::function_scope!(egui_winit::short_device_event_description(&event)); // Nb: Make sure this guard is dropped after this function returns. event_loop_context::with_event_loop_context(event_loop, move || { let event_result = self.winit_app.device_event(event_loop, device_id, event); self.handle_event_result(event_loop, event_result); }); } fn user_event(&mut self, event_loop: &ActiveEventLoop, event: UserEvent) { profiling::function_scope!(match &event { UserEvent::RequestRepaint { .. } => "UserEvent::RequestRepaint", #[cfg(feature = "accesskit")] UserEvent::AccessKitActionRequest(_) => "UserEvent::AccessKitActionRequest", }); event_loop_context::with_event_loop_context(event_loop, move || { let event_result = match event { UserEvent::RequestRepaint { when, cumulative_pass_nr, viewport_id, } => { let current_pass_nr = self .winit_app .egui_ctx() .map_or(0, |ctx| ctx.cumulative_pass_nr_for(viewport_id)); if current_pass_nr == cumulative_pass_nr || current_pass_nr == cumulative_pass_nr + 1 { log::trace!("UserEvent::RequestRepaint scheduling repaint at {when:?}"); if let Some(window_id) = self.winit_app.window_id_from_viewport_id(viewport_id) { Ok(EventResult::RepaintAt(window_id, when)) } else { Ok(EventResult::Wait) } } else { log::trace!("Got outdated UserEvent::RequestRepaint"); Ok(EventResult::Wait) // old request - we've already repainted } } #[cfg(feature = "accesskit")] UserEvent::AccessKitActionRequest(request) => { self.winit_app.on_accesskit_event(request) } }; self.handle_event_result(event_loop, event_result); }); } fn new_events(&mut self, event_loop: &ActiveEventLoop, cause: winit::event::StartCause) { if let winit::event::StartCause::ResumeTimeReached { .. } = cause { log::trace!("Woke up to check next_repaint_time"); } self.check_redraw_requests(event_loop); } fn window_event( &mut self, event_loop: &ActiveEventLoop, window_id: WindowId, event: winit::event::WindowEvent, ) { profiling::function_scope!(egui_winit::short_window_event_description(&event)); // Nb: Make sure this guard is dropped after this function returns. event_loop_context::with_event_loop_context(event_loop, move || { let event_result = match event { winit::event::WindowEvent::RedrawRequested => { self.winit_app.run_ui_and_paint(event_loop, window_id) } _ => self.winit_app.window_event(event_loop, window_id, event), }; self.handle_event_result(event_loop, event_result); }); } } #[cfg(not(target_os = "ios"))] fn run_and_return(event_loop: &mut EventLoop<UserEvent>, winit_app: impl WinitApp) -> Result { use winit::platform::run_on_demand::EventLoopExtRunOnDemand as _; log::trace!("Entering the winit event loop (run_app_on_demand)…"); let mut app = WinitAppWrapper::new(winit_app, true); event_loop.run_app_on_demand(&mut app)?; log::debug!("eframe window closed"); app.return_result } fn run_and_exit(event_loop: EventLoop<UserEvent>, winit_app: impl WinitApp) -> Result { log::trace!("Entering the winit event loop (run_app)…"); // When to repaint what window let mut app = WinitAppWrapper::new(winit_app, false); event_loop.run_app(&mut app)?; log::debug!("winit event loop unexpectedly returned"); Ok(()) } // ---------------------------------------------------------------------------- #[cfg(feature = "glow")] pub fn run_glow( app_name: &str, mut native_options: epi::NativeOptions, app_creator: epi::AppCreator<'_>, ) -> Result { use super::glow_integration::GlowWinitApp; #[cfg(not(target_os = "ios"))] if native_options.run_and_return { return with_event_loop(native_options, |event_loop, native_options| { let glow_eframe = GlowWinitApp::new(event_loop, app_name, native_options, app_creator); run_and_return(event_loop, glow_eframe) })?; } let event_loop = create_event_loop(&mut native_options)?; let glow_eframe = GlowWinitApp::new(&event_loop, app_name, native_options, app_creator); run_and_exit(event_loop, glow_eframe) } #[cfg(feature = "glow")] pub fn create_glow<'a>( app_name: &str, native_options: epi::NativeOptions, app_creator: epi::AppCreator<'a>, event_loop: &EventLoop<UserEvent>, ) -> impl ApplicationHandler<UserEvent> + 'a { use super::glow_integration::GlowWinitApp; let glow_eframe = GlowWinitApp::new(event_loop, app_name, native_options, app_creator); WinitAppWrapper::new(glow_eframe, true) } // ---------------------------------------------------------------------------- #[cfg(feature = "wgpu_no_default_features")] pub fn run_wgpu( app_name: &str, mut native_options: epi::NativeOptions, app_creator: epi::AppCreator<'_>, ) -> Result { use super::wgpu_integration::WgpuWinitApp; #[cfg(not(target_os = "ios"))] if native_options.run_and_return { return with_event_loop(native_options, |event_loop, native_options| { let wgpu_eframe = WgpuWinitApp::new(event_loop, app_name, native_options, app_creator); run_and_return(event_loop, wgpu_eframe) })?; } let event_loop = create_event_loop(&mut native_options)?; let wgpu_eframe = WgpuWinitApp::new(&event_loop, app_name, native_options, app_creator); run_and_exit(event_loop, wgpu_eframe) } #[cfg(feature = "wgpu_no_default_features")] pub fn create_wgpu<'a>( app_name: &str, native_options: epi::NativeOptions, app_creator: epi::AppCreator<'a>, event_loop: &EventLoop<UserEvent>, ) -> impl ApplicationHandler<UserEvent> + 'a { use super::wgpu_integration::WgpuWinitApp; let wgpu_eframe = WgpuWinitApp::new(event_loop, app_name, native_options, app_creator); WinitAppWrapper::new(wgpu_eframe, true) } // ---------------------------------------------------------------------------- /// A proxy to the eframe application that implements [`ApplicationHandler`]. /// /// This can be run directly on your own [`EventLoop`] by itself or with other /// windows you manage outside of eframe. pub struct EframeWinitApplication<'a> { wrapper: Box<dyn ApplicationHandler<UserEvent> + 'a>, control_flow: ControlFlow, } impl ApplicationHandler<UserEvent> for EframeWinitApplication<'_> { fn resumed(&mut self, event_loop: &ActiveEventLoop) { self.wrapper.resumed(event_loop); } fn window_event( &mut self, event_loop: &ActiveEventLoop, window_id: winit::window::WindowId, event: winit::event::WindowEvent, ) { self.wrapper.window_event(event_loop, window_id, event); } fn new_events(&mut self, event_loop: &ActiveEventLoop, cause: winit::event::StartCause) { self.wrapper.new_events(event_loop, cause); } fn user_event(&mut self, event_loop: &ActiveEventLoop, event: UserEvent) { self.wrapper.user_event(event_loop, event); } fn device_event( &mut self, event_loop: &ActiveEventLoop, device_id: winit::event::DeviceId, event: winit::event::DeviceEvent, ) { self.wrapper.device_event(event_loop, device_id, event); } fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) { self.wrapper.about_to_wait(event_loop); self.control_flow = event_loop.control_flow(); } fn suspended(&mut self, event_loop: &ActiveEventLoop) { self.wrapper.suspended(event_loop); } fn exiting(&mut self, event_loop: &ActiveEventLoop) { self.wrapper.exiting(event_loop); } fn memory_warning(&mut self, event_loop: &ActiveEventLoop) { self.wrapper.memory_warning(event_loop); } } impl<'a> EframeWinitApplication<'a> { pub(crate) fn new<T: ApplicationHandler<UserEvent> + 'a>(app: T) -> Self { Self { wrapper: Box::new(app), control_flow: ControlFlow::default(), } } /// Pump the `EventLoop` to check for and dispatch pending events to this application. /// /// Returns either the exit code for the application or the final state of the [`ControlFlow`] /// after all events have been dispatched in this iteration. /// /// This is useful when your [`EventLoop`] is not the main event loop for your application. /// See the `external_eventloop_async` example. #[cfg(not(target_os = "ios"))] pub fn pump_eframe_app( &mut self, event_loop: &mut EventLoop<UserEvent>, timeout: Option<std::time::Duration>, ) -> EframePumpStatus { use winit::platform::pump_events::{EventLoopExtPumpEvents as _, PumpStatus}; match event_loop.pump_app_events(timeout, self) { PumpStatus::Continue => EframePumpStatus::Continue(self.control_flow), PumpStatus::Exit(code) => EframePumpStatus::Exit(code), } } } /// Either an exit code or a [`ControlFlow`] from the [`ActiveEventLoop`]. /// /// The result of [`EframeWinitApplication::pump_eframe_app`]. #[cfg(not(target_os = "ios"))] pub enum EframePumpStatus { /// The final state of the [`ControlFlow`] after all events have been dispatched /// /// Callers should perform the action that is appropriate for the [`ControlFlow`] value. Continue(ControlFlow), /// The exit code for the application Exit(i32), }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/eframe/src/native/file_storage.rs
crates/eframe/src/native/file_storage.rs
use std::{ collections::HashMap, io::Write as _, path::{Path, PathBuf}, }; /// The folder where `eframe` will store its state. /// /// The given `app_id` is either the /// [`egui::ViewportBuilder::app_id`] of [`crate::NativeOptions::viewport`] /// or the title argument to [`crate::run_native`]. /// /// On native, the path is: /// * Linux: `/home/UserName/.local/share/APP_ID` /// * macOS: `/Users/UserName/Library/Application Support/APP_ID` /// * Windows: `C:\Users\UserName\AppData\Roaming\APP_ID\data` pub fn storage_dir(app_id: &str) -> Option<PathBuf> { use egui::os::OperatingSystem as OS; use std::env::var_os; match OS::from_target_os() { OS::Nix => var_os("XDG_DATA_HOME") .map(PathBuf::from) .filter(|p| p.is_absolute()) .or_else(|| home::home_dir().map(|p| p.join(".local").join("share"))) .map(|p| { p.join( app_id .to_lowercase() .replace(|c: char| c.is_ascii_whitespace(), ""), ) }), OS::Mac => home::home_dir().map(|p| { p.join("Library") .join("Application Support") .join(app_id.replace(|c: char| c.is_ascii_whitespace(), "-")) }), OS::Windows => roaming_appdata().map(|p| p.join(app_id).join("data")), OS::Unknown | OS::Android | OS::IOS => None, } } // Adapted from // https://github.com/rust-lang/cargo/blob/6e11c77384989726bb4f412a0e23b59c27222c34/crates/home/src/windows.rs#L19-L37 #[cfg(all(windows, not(target_vendor = "uwp")))] #[expect(unsafe_code)] fn roaming_appdata() -> Option<PathBuf> { use std::ffi::OsString; use std::os::windows::ffi::OsStringExt as _; use std::ptr; use std::slice; use windows_sys::Win32::Foundation::S_OK; use windows_sys::Win32::System::Com::CoTaskMemFree; use windows_sys::Win32::UI::Shell::{ FOLDERID_RoamingAppData, KF_FLAG_DONT_VERIFY, SHGetKnownFolderPath, }; unsafe extern "C" { fn wcslen(buf: *const u16) -> usize; } let mut path_raw = ptr::null_mut(); // SAFETY: SHGetKnownFolderPath allocates for us, we don't pass any pointers to it. // See https://learn.microsoft.com/en-us/windows/win32/api/shlobj_core/nf-shlobj_core-shgetknownfolderpath let result = unsafe { SHGetKnownFolderPath( &FOLDERID_RoamingAppData, KF_FLAG_DONT_VERIFY as u32, std::ptr::null_mut(), &mut path_raw, ) }; let path = if result == S_OK { // SAFETY: SHGetKnownFolderPath indicated success and is supposed to allocate a null-terminated string for us. let path_slice = unsafe { slice::from_raw_parts(path_raw, wcslen(path_raw)) }; Some(PathBuf::from(OsString::from_wide(path_slice))) } else { None }; // SAFETY: // This memory got allocated by SHGetKnownFolderPath, we didn't touch anything in the process. // A null ptr is a no-op for `CoTaskMemFree`, so in case this failed we're still good. // https://learn.microsoft.com/en-us/windows/win32/api/combaseapi/nf-combaseapi-cotaskmemfree unsafe { CoTaskMemFree(path_raw.cast()) }; path } #[cfg(any(not(windows), target_vendor = "uwp"))] fn roaming_appdata() -> Option<PathBuf> { None } // ---------------------------------------------------------------------------- /// A key-value store backed by a [RON](https://github.com/ron-rs/ron) file on disk. /// Used to restore egui state, glow window position/size and app state. pub struct FileStorage { ron_filepath: PathBuf, kv: HashMap<String, String>, dirty: bool, last_save_join_handle: Option<std::thread::JoinHandle<()>>, } impl Drop for FileStorage { fn drop(&mut self) { if let Some(join_handle) = self.last_save_join_handle.take() { profiling::scope!("wait_for_save"); join_handle.join().ok(); } } } impl FileStorage { /// Store the state in this .ron file. pub(crate) fn from_ron_filepath(ron_filepath: impl Into<PathBuf>) -> Self { profiling::function_scope!(); let ron_filepath: PathBuf = ron_filepath.into(); log::debug!("Loading app state from {}…", ron_filepath.display()); Self { kv: read_ron(&ron_filepath).unwrap_or_default(), ron_filepath, dirty: false, last_save_join_handle: None, } } /// Find a good place to put the files that the OS likes. pub fn from_app_id(app_id: &str) -> Option<Self> { profiling::function_scope!(); if let Some(data_dir) = storage_dir(app_id) { if let Err(err) = std::fs::create_dir_all(&data_dir) { log::warn!( "Saving disabled: Failed to create app path at {}: {err}", data_dir.display() ); None } else { Some(Self::from_ron_filepath(data_dir.join("app.ron"))) } } else { log::warn!("Saving disabled: Failed to find path to data_dir."); None } } } impl crate::Storage for FileStorage { fn get_string(&self, key: &str) -> Option<String> { self.kv.get(key).cloned() } fn set_string(&mut self, key: &str, value: String) { if self.kv.get(key) != Some(&value) { self.kv.insert(key.to_owned(), value); self.dirty = true; } } fn flush(&mut self) { if self.dirty { profiling::scope!("FileStorage::flush"); self.dirty = false; let file_path = self.ron_filepath.clone(); let kv = self.kv.clone(); if let Some(join_handle) = self.last_save_join_handle.take() { // wait for previous save to complete. join_handle.join().ok(); } let result = std::thread::Builder::new() .name("eframe_persist".to_owned()) .spawn(move || { save_to_disk(&file_path, &kv); }); match result { Ok(join_handle) => { self.last_save_join_handle = Some(join_handle); } Err(err) => { log::warn!("Failed to spawn thread to save app state: {err}"); } } } } } fn save_to_disk(file_path: &PathBuf, kv: &HashMap<String, String>) { profiling::function_scope!(); if let Some(parent_dir) = file_path.parent() && !parent_dir.exists() && let Err(err) = std::fs::create_dir_all(parent_dir) { log::warn!("Failed to create directory {}: {err}", parent_dir.display()); } match std::fs::File::create(file_path) { Ok(file) => { let mut writer = std::io::BufWriter::new(file); let config = Default::default(); profiling::scope!("ron::serialize"); if let Err(err) = ron::Options::default() .to_io_writer_pretty(&mut writer, &kv, config) .and_then(|_| writer.flush().map_err(|err| err.into())) { log::warn!("Failed to serialize app state: {err}"); } else { log::trace!("Persisted to {}", file_path.display()); } } Err(err) => { log::warn!("Failed to create file {}: {err}", file_path.display()); } } } // ---------------------------------------------------------------------------- fn read_ron<T>(ron_path: impl AsRef<Path>) -> Option<T> where T: serde::de::DeserializeOwned, { profiling::function_scope!(); match std::fs::File::open(ron_path) { Ok(file) => { let reader = std::io::BufReader::new(file); match ron::de::from_reader(reader) { Ok(value) => Some(value), Err(err) => { log::warn!("Failed to parse RON: {err}"); None } } } Err(_err) => { // File probably doesn't exist. That's fine. None } } } #[cfg(test)] mod tests { use super::*; fn directories_storage_dir(app_id: &str) -> Option<PathBuf> { directories::ProjectDirs::from("", "", app_id) .map(|proj_dirs| proj_dirs.data_dir().to_path_buf()) } #[test] fn storage_path_matches_directories() { use super::storage_dir; for app_id in [ "MyApp", "My App", "my_app", "my-app", "My.App", "my/app", "my:app", r"my\app", ] { assert_eq!(directories_storage_dir(app_id), storage_dir(app_id)); } } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/eframe/src/native/event_loop_context.rs
crates/eframe/src/native/event_loop_context.rs
use std::cell::Cell; use winit::event_loop::ActiveEventLoop; thread_local! { static CURRENT_EVENT_LOOP: Cell<Option<*const ActiveEventLoop>> = const { Cell::new(None) }; } struct EventLoopGuard; impl EventLoopGuard { fn new(event_loop: &ActiveEventLoop) -> Self { CURRENT_EVENT_LOOP.with(|cell| { assert!( cell.get().is_none(), "Attempted to set a new event loop while one is already set" ); cell.set(Some(std::ptr::from_ref::<ActiveEventLoop>(event_loop))); }); Self } } impl Drop for EventLoopGuard { fn drop(&mut self) { CURRENT_EVENT_LOOP.with(|cell| cell.set(None)); } } // Helper function to safely use the current event loop #[expect(unsafe_code)] pub fn with_current_event_loop<F, R>(f: F) -> Option<R> where F: FnOnce(&ActiveEventLoop) -> R, { CURRENT_EVENT_LOOP.with(|cell| { cell.get().map(|ptr| { // SAFETY: // 1. The pointer is guaranteed to be valid when it's Some, as the EventLoopGuard that created it // lives at least as long as the reference, and clears it when it's dropped. Only run_with_event_loop creates // a new EventLoopGuard, and does not leak it. // 2. Since the pointer was created from a borrow which lives at least as long as this pointer there are // no mutable references to the ActiveEventLoop. let event_loop = unsafe { &*ptr }; f(event_loop) }) }) } // The only public interface to use the event loop pub fn with_event_loop_context(event_loop: &ActiveEventLoop, f: impl FnOnce()) { // NOTE: For safety, this guard must NOT be leaked. let _guard = EventLoopGuard::new(event_loop); f(); }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/eframe/src/native/winit_integration.rs
crates/eframe/src/native/winit_integration.rs
use std::{sync::Arc, time::Instant}; use winit::{ event_loop::ActiveEventLoop, window::{Window, WindowId}, }; use egui::ViewportId; #[cfg(feature = "accesskit")] use egui_winit::accesskit_winit; /// Create an egui context, restoring it from storage if possible. pub fn create_egui_context(storage: Option<&dyn crate::Storage>) -> egui::Context { profiling::function_scope!(); pub const IS_DESKTOP: bool = cfg!(any( target_os = "freebsd", target_os = "linux", target_os = "macos", target_os = "openbsd", target_os = "windows", )); let egui_ctx = egui::Context::default(); egui_ctx.set_embed_viewports(!IS_DESKTOP); egui_ctx.options_mut(|o| { // eframe supports multi-pass (Context::request_discard). #[expect(clippy::unwrap_used)] { o.max_passes = 2.try_into().unwrap(); } }); let memory = crate::native::epi_integration::load_egui_memory(storage).unwrap_or_default(); egui_ctx.memory_mut(|mem| *mem = memory); egui_ctx } /// The custom even `eframe` uses with the [`winit`] event loop. #[derive(Debug)] pub enum UserEvent { /// A repaint is requested. RequestRepaint { /// What to repaint. viewport_id: ViewportId, /// When to repaint. when: Instant, /// What the cumulative pass number was when the repaint was _requested_. cumulative_pass_nr: u64, }, /// A request related to [`accesskit`](https://accesskit.dev/). #[cfg(feature = "accesskit")] AccessKitActionRequest(accesskit_winit::Event), } #[cfg(feature = "accesskit")] impl From<accesskit_winit::Event> for UserEvent { fn from(inner: accesskit_winit::Event) -> Self { Self::AccessKitActionRequest(inner) } } pub trait WinitApp { fn egui_ctx(&self) -> Option<&egui::Context>; fn window(&self, window_id: WindowId) -> Option<Arc<Window>>; fn window_id_from_viewport_id(&self, id: ViewportId) -> Option<WindowId>; fn save(&mut self); fn save_and_destroy(&mut self); fn run_ui_and_paint( &mut self, event_loop: &ActiveEventLoop, window_id: WindowId, ) -> crate::Result<EventResult>; fn suspended(&mut self, event_loop: &ActiveEventLoop) -> crate::Result<EventResult>; fn resumed(&mut self, event_loop: &ActiveEventLoop) -> crate::Result<EventResult>; fn device_event( &mut self, event_loop: &ActiveEventLoop, device_id: winit::event::DeviceId, event: winit::event::DeviceEvent, ) -> crate::Result<EventResult>; fn window_event( &mut self, event_loop: &ActiveEventLoop, window_id: WindowId, event: winit::event::WindowEvent, ) -> crate::Result<EventResult>; #[cfg(feature = "accesskit")] fn on_accesskit_event(&mut self, event: accesskit_winit::Event) -> crate::Result<EventResult>; } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum EventResult { Wait, /// Causes a synchronous repaint inside the event handler. This should only /// be used in special situations if the window must be repainted while /// handling a specific event. This occurs on Windows when handling resizes. /// /// `RepaintNow` creates a new frame synchronously, and should therefore /// only be used for extremely urgent repaints. RepaintNow(WindowId), /// Queues a repaint for once the event loop handles its next redraw. Exists /// so that multiple input events can be handled in one frame. Does not /// cause any delay like `RepaintNow`. RepaintNext(WindowId), RepaintAt(WindowId, Instant), /// Causes a save of the client state when the persistence feature is enabled. Save, /// Starts the process of ending eframe execution whilst allowing for proper /// clean up of resources. /// /// # Warning /// This event **must** occur before [`Exit`] to correctly exit eframe code. /// If in doubt, return this event. /// /// [`Exit`]: [EventResult::Exit] CloseRequested, /// The event loop will exit, now. /// The correct circumstance to return this event is in response to a winit "Destroyed" event. /// /// # Warning /// The [`CloseRequested`] **must** occur before this event to ensure that winit /// is able to remove any open windows. Otherwise the window(s) will remain open /// until the program terminates. /// /// [`CloseRequested`]: EventResult::CloseRequested Exit, } #[cfg(feature = "accesskit")] pub(crate) fn on_accesskit_window_event( egui_winit: &mut egui_winit::State, window_id: WindowId, event: &accesskit_winit::WindowEvent, ) -> EventResult { match event { accesskit_winit::WindowEvent::InitialTreeRequested => { egui_winit.egui_ctx().enable_accesskit(); // Because we can't provide the initial tree synchronously // (because that would require the activation handler to access // the same mutable state as the winit event handler), some // AccessKit platform adapters will use a placeholder tree // until we send the first tree update. To minimize the possible // bad effects of that workaround, repaint and send the tree // immediately. EventResult::RepaintNow(window_id) } accesskit_winit::WindowEvent::ActionRequested(request) => { egui_winit.on_accesskit_action_request(request.clone()); // As a form of user input, accessibility actions should cause // a repaint, but not until the next regular frame. EventResult::RepaintNext(window_id) } accesskit_winit::WindowEvent::AccessibilityDeactivated => { egui_winit.egui_ctx().disable_accesskit(); // Disabling AccessKit support should have no visible effect, // so there's no need to repaint. EventResult::Wait } } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/eframe/src/web/web_painter.rs
crates/eframe/src/web/web_painter.rs
use egui::{Event, UserData}; use wasm_bindgen::JsValue; /// Renderer for a browser canvas. /// As of writing we're not allowing to decide on the painter at runtime, /// therefore this trait is merely there for specifying and documenting the interface. pub(crate) trait WebPainter { // Create a new web painter targeting a given canvas. // fn new(canvas: HtmlCanvasElement, options: &WebOptions) -> Result<Self, String> // where // Self: Sized; /// Reference to the canvas in use. fn canvas(&self) -> &web_sys::HtmlCanvasElement; /// Maximum size of a texture in one direction. fn max_texture_side(&self) -> usize; /// Update all internal textures and paint gui. /// When `capture` isn't empty, the rendered screen should be captured. /// Once the screenshot is ready, the screenshot should be returned via [`Self::handle_screenshots`]. fn paint_and_update_textures( &mut self, clear_color: [f32; 4], clipped_primitives: &[egui::ClippedPrimitive], pixels_per_point: f32, textures_delta: &egui::TexturesDelta, capture: Vec<UserData>, ) -> Result<(), JsValue>; fn handle_screenshots(&mut self, events: &mut Vec<Event>); /// Destroy all resources. fn destroy(&mut self); }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/eframe/src/web/web_painter_glow.rs
crates/eframe/src/web/web_painter_glow.rs
use egui::{Event, UserData, ViewportId}; use egui_glow::glow; use std::sync::Arc; use wasm_bindgen::JsCast as _; use wasm_bindgen::JsValue; use web_sys::HtmlCanvasElement; use crate::{WebGlContextOption, WebOptions}; use super::web_painter::WebPainter; pub(crate) struct WebPainterGlow { canvas: HtmlCanvasElement, painter: egui_glow::Painter, screenshots: Vec<(egui::ColorImage, Vec<UserData>)>, } impl WebPainterGlow { pub fn gl(&self) -> &std::sync::Arc<glow::Context> { self.painter.gl() } pub fn new( _ctx: egui::Context, canvas: HtmlCanvasElement, options: &WebOptions, ) -> Result<Self, String> { let (gl, shader_prefix) = init_glow_context_from_canvas(&canvas, options.webgl_context_option)?; #[allow(clippy::allow_attributes, clippy::arc_with_non_send_sync)] // For wasm let gl = std::sync::Arc::new(gl); let painter = egui_glow::Painter::new(gl, shader_prefix, None, options.dithering) .map_err(|err| format!("Error starting glow painter: {err}"))?; Ok(Self { canvas, painter, screenshots: Vec::new(), }) } } impl WebPainter for WebPainterGlow { fn max_texture_side(&self) -> usize { self.painter.max_texture_side() } fn canvas(&self) -> &HtmlCanvasElement { &self.canvas } fn paint_and_update_textures( &mut self, clear_color: [f32; 4], clipped_primitives: &[egui::ClippedPrimitive], pixels_per_point: f32, textures_delta: &egui::TexturesDelta, capture: Vec<UserData>, ) -> Result<(), JsValue> { let canvas_dimension = [self.canvas.width(), self.canvas.height()]; for (id, image_delta) in &textures_delta.set { self.painter.set_texture(*id, image_delta); } egui_glow::painter::clear(self.painter.gl(), canvas_dimension, clear_color); self.painter .paint_primitives(canvas_dimension, pixels_per_point, clipped_primitives); if !capture.is_empty() { let image = self.painter.read_screen_rgba(canvas_dimension); self.screenshots.push((image, capture)); } for &id in &textures_delta.free { self.painter.free_texture(id); } Ok(()) } fn destroy(&mut self) { self.painter.destroy(); } fn handle_screenshots(&mut self, events: &mut Vec<Event>) { for (image, data) in self.screenshots.drain(..) { let image = Arc::new(image); for data in data { events.push(Event::Screenshot { viewport_id: ViewportId::default(), image: Arc::clone(&image), user_data: data, }); } } } } /// Returns glow context and shader prefix. fn init_glow_context_from_canvas( canvas: &HtmlCanvasElement, options: WebGlContextOption, ) -> Result<(glow::Context, &'static str), String> { let result = match options { // Force use WebGl1 WebGlContextOption::WebGl1 => init_webgl1(canvas), // Force use WebGl2 WebGlContextOption::WebGl2 => init_webgl2(canvas), // Trying WebGl2 first WebGlContextOption::BestFirst => init_webgl2(canvas).or_else(|| init_webgl1(canvas)), // Trying WebGl1 first (useful for testing). WebGlContextOption::CompatibilityFirst => { init_webgl1(canvas).or_else(|| init_webgl2(canvas)) } }; if let Some(result) = result { Ok(result) } else { Err("WebGL isn't supported".into()) } } fn init_webgl1(canvas: &HtmlCanvasElement) -> Option<(glow::Context, &'static str)> { let gl1_ctx = canvas .get_context("webgl") .expect("Failed to query about WebGL2 context"); let gl1_ctx = gl1_ctx?; log::debug!("WebGL1 selected."); let gl1_ctx = gl1_ctx .dyn_into::<web_sys::WebGlRenderingContext>() .unwrap(); let shader_prefix = if webgl1_requires_brightening(&gl1_ctx) { log::debug!("Enabling webkitGTK brightening workaround."); "#define APPLY_BRIGHTENING_GAMMA" } else { "" }; let gl = glow::Context::from_webgl1_context(gl1_ctx); Some((gl, shader_prefix)) } fn init_webgl2(canvas: &HtmlCanvasElement) -> Option<(glow::Context, &'static str)> { let gl2_ctx = canvas .get_context("webgl2") .expect("Failed to query about WebGL2 context"); let gl2_ctx = gl2_ctx?; log::debug!("WebGL2 selected."); let gl2_ctx = gl2_ctx .dyn_into::<web_sys::WebGl2RenderingContext>() .unwrap(); let gl = glow::Context::from_webgl2_context(gl2_ctx); let shader_prefix = ""; Some((gl, shader_prefix)) } fn webgl1_requires_brightening(gl: &web_sys::WebGlRenderingContext) -> bool { // See https://github.com/emilk/egui/issues/794 // detect WebKitGTK // WebKitGTK use WebKit default unmasked vendor and renderer // but safari use same vendor and renderer // so exclude "Mac OS X" user-agent. let user_agent = web_sys::window().unwrap().navigator().user_agent().unwrap(); !user_agent.contains("Mac OS X") && is_safari_and_webkit_gtk(gl) } /// detecting Safari and `webkitGTK`. /// /// Safari and `webkitGTK` use unmasked renderer :Apple GPU /// /// If we detect safari or `webkitGTKs` returns true. /// /// This function used to avoid displaying linear color with `sRGB` supported systems. fn is_safari_and_webkit_gtk(gl: &web_sys::WebGlRenderingContext) -> bool { // This call produces a warning in Firefox ("WEBGL_debug_renderer_info is deprecated in Firefox and will be removed.") // but unless we call it we get errors in Chrome when we call `get_parameter` below. // TODO(emilk): do something smart based on user agent? if gl .get_extension("WEBGL_debug_renderer_info") .unwrap() .is_some() && let Ok(renderer) = gl.get_parameter(web_sys::WebglDebugRendererInfo::UNMASKED_RENDERER_WEBGL) && let Some(renderer) = renderer.as_string() && renderer.contains("Apple") { true } else { false } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/eframe/src/web/backend.rs
crates/eframe/src/web/backend.rs
use std::collections::BTreeMap; use egui::mutex::Mutex; use crate::epi; use super::percent_decode; // ---------------------------------------------------------------------------- /// Data gathered between frames. #[derive(Default)] pub(crate) struct WebInput { /// Required because we don't get a position on touchend pub primary_touch: Option<egui::TouchId>, /// Helps to track the delta scale from gesture events pub accumulated_scale: f32, /// Helps to track the delta rotation from gesture events pub accumulated_rotation: f32, /// The raw input to `egui`. pub raw: egui::RawInput, } impl WebInput { pub fn new_frame(&mut self, canvas_size: egui::Vec2) -> egui::RawInput { let mut raw_input = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Default::default(), canvas_size)), time: Some(super::now_sec()), ..self.raw.take() }; raw_input .viewports .entry(egui::ViewportId::ROOT) .or_default() .native_pixels_per_point = Some(super::native_pixels_per_point()); raw_input } /// On alt-tab, or user clicking another HTML element. pub fn set_focus(&mut self, focused: bool) { if self.raw.focused == focused { return; } // log::debug!("on_web_page_focus_change: {focused}"); self.raw.modifiers = egui::Modifiers::default(); // Avoid sticky modifier keys on alt-tab: self.raw.focused = focused; self.raw.events.push(egui::Event::WindowFocused(focused)); self.primary_touch = None; } } // ---------------------------------------------------------------------------- /// Stores when to do the next repaint. pub(crate) struct NeedRepaint { /// Time in seconds when the next repaint should happen. next_repaint: Mutex<f64>, /// Rate limit for repaint. 0 means "unlimited". The rate may still be limited by vsync. max_fps: u32, } impl NeedRepaint { pub fn new(max_fps: Option<u32>) -> Self { Self { next_repaint: Mutex::new(f64::NEG_INFINITY), // start with a repaint max_fps: max_fps.unwrap_or(0), } } } impl NeedRepaint { /// Returns the time (in [`now_sec`] scale) when /// we should next repaint. pub fn when_to_repaint(&self) -> f64 { *self.next_repaint.lock() } /// Unschedule repainting. pub fn clear(&self) { *self.next_repaint.lock() = f64::INFINITY; } pub fn repaint_after(&self, num_seconds: f64) { let mut time = super::now_sec() + num_seconds; time = self.round_repaint_time_to_rate(time); let mut repaint_time = self.next_repaint.lock(); *repaint_time = repaint_time.min(time); } /// Request a repaint. Depending on the presence of rate limiting, this may not be instant. pub fn repaint(&self) { let time = self.round_repaint_time_to_rate(super::now_sec()); let mut repaint_time = self.next_repaint.lock(); *repaint_time = repaint_time.min(time); } pub fn repaint_asap(&self) { *self.next_repaint.lock() = f64::NEG_INFINITY; } pub fn needs_repaint(&self) -> bool { self.when_to_repaint() <= super::now_sec() } fn round_repaint_time_to_rate(&self, time: f64) -> f64 { if self.max_fps == 0 { time } else { let interval = 1.0 / self.max_fps as f64; (time / interval).ceil() * interval } } } // ---------------------------------------------------------------------------- /// The User-Agent of the user's browser. pub fn user_agent() -> Option<String> { web_sys::window()?.navigator().user_agent().ok() } /// Get the [`epi::Location`] from the browser. pub fn web_location() -> epi::Location { let location = web_sys::window().unwrap().location(); let hash = percent_decode(&location.hash().unwrap_or_default()); let query = location .search() .unwrap_or_default() .strip_prefix('?') .unwrap_or_default() .to_owned(); epi::Location { // TODO(emilk): should we really percent-decode the url? 🤷‍♂️ url: percent_decode(&location.href().unwrap_or_default()), protocol: percent_decode(&location.protocol().unwrap_or_default()), host: percent_decode(&location.host().unwrap_or_default()), hostname: percent_decode(&location.hostname().unwrap_or_default()), port: percent_decode(&location.port().unwrap_or_default()), hash, query_map: parse_query_map(&query), query, origin: percent_decode(&location.origin().unwrap_or_default()), } } /// query is percent-encoded fn parse_query_map(query: &str) -> BTreeMap<String, Vec<String>> { let mut map: BTreeMap<String, Vec<String>> = Default::default(); for pair in query.split('&') { if !pair.is_empty() { if let Some((key, value)) = pair.split_once('=') { map.entry(percent_decode(key)) .or_default() .push(percent_decode(value)); } else { map.entry(percent_decode(pair)) .or_default() .push(String::new()); } } } map } // TODO(emilk): this test is never acgtually run, because this whole module is wasm32 only 🤦‍♂️ #[test] fn test_parse_query() { assert_eq!(parse_query_map(""), BTreeMap::default()); assert_eq!(parse_query_map("foo"), BTreeMap::from_iter([("foo", "")])); assert_eq!( parse_query_map("foo=bar"), BTreeMap::from_iter([("foo", "bar")]) ); assert_eq!( parse_query_map("foo=bar&baz=42"), BTreeMap::from_iter([("foo", "bar"), ("baz", "42")]) ); assert_eq!( parse_query_map("foo&baz=42"), BTreeMap::from_iter([("foo", ""), ("baz", "42")]) ); assert_eq!( parse_query_map("foo&baz&&"), BTreeMap::from_iter([("foo", ""), ("baz", "")]) ); assert_eq!( parse_query_map("badger=data.rrd%3Fparam1%3Dfoo%26param2%3Dbar&mushroom=snake"), BTreeMap::from_iter([ ("badger", "data.rrd?param1=foo&param2=bar"), ("mushroom", "snake") ]) ); }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/eframe/src/web/storage.rs
crates/eframe/src/web/storage.rs
fn local_storage() -> Option<web_sys::Storage> { web_sys::window()?.local_storage().ok()? } /// Read data from local storage. pub fn local_storage_get(key: &str) -> Option<String> { local_storage().map(|storage| storage.get_item(key).ok())?? } /// Write data to local storage. pub fn local_storage_set(key: &str, value: &str) { local_storage().map(|storage| storage.set_item(key, value)); } #[cfg(feature = "persistence")] pub(crate) fn load_memory(ctx: &egui::Context) { if let Some(memory_string) = local_storage_get("egui_memory_ron") { match ron::from_str(&memory_string) { Ok(memory) => { ctx.memory_mut(|m| *m = memory); } Err(err) => { log::warn!("Failed to parse memory RON: {err}"); } } } } #[cfg(not(feature = "persistence"))] pub(crate) fn load_memory(_: &egui::Context) {} #[cfg(feature = "persistence")] pub(crate) fn save_memory(ctx: &egui::Context) { match ctx.memory(ron::to_string) { Ok(ron) => { local_storage_set("egui_memory_ron", &ron); } Err(err) => { log::warn!("Failed to serialize memory as RON: {err}"); } } } #[cfg(not(feature = "persistence"))] pub(crate) fn save_memory(_: &egui::Context) {}
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/eframe/src/web/web_painter_wgpu.rs
crates/eframe/src/web/web_painter_wgpu.rs
use std::sync::Arc; use egui::{Event, UserData, ViewportId}; use egui_wgpu::{ RenderState, SurfaceErrorAction, capture::{CaptureReceiver, CaptureSender, CaptureState, capture_channel}, }; use wasm_bindgen::JsValue; use web_sys::HtmlCanvasElement; use super::web_painter::WebPainter; pub(crate) struct WebPainterWgpu { canvas: HtmlCanvasElement, surface: wgpu::Surface<'static>, surface_configuration: wgpu::SurfaceConfiguration, render_state: Option<RenderState>, on_surface_error: Arc<dyn Fn(wgpu::SurfaceError) -> SurfaceErrorAction>, depth_stencil_format: Option<wgpu::TextureFormat>, depth_texture_view: Option<wgpu::TextureView>, screen_capture_state: Option<CaptureState>, capture_tx: CaptureSender, capture_rx: CaptureReceiver, ctx: egui::Context, } impl WebPainterWgpu { pub fn render_state(&self) -> Option<RenderState> { self.render_state.clone() } pub fn generate_depth_texture_view( &self, render_state: &RenderState, width_in_pixels: u32, height_in_pixels: u32, ) -> Option<wgpu::TextureView> { let device = &render_state.device; self.depth_stencil_format.map(|depth_stencil_format| { device .create_texture(&wgpu::TextureDescriptor { label: Some("egui_depth_texture"), size: wgpu::Extent3d { width: width_in_pixels, height: height_in_pixels, depth_or_array_layers: 1, }, mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2, format: depth_stencil_format, usage: wgpu::TextureUsages::RENDER_ATTACHMENT, view_formats: &[depth_stencil_format], }) .create_view(&wgpu::TextureViewDescriptor::default()) }) } pub async fn new( ctx: egui::Context, canvas: web_sys::HtmlCanvasElement, options: &crate::WebOptions, ) -> Result<Self, String> { log::debug!("Creating wgpu painter"); let instance = options.wgpu_options.wgpu_setup.new_instance().await; let surface = instance .create_surface(wgpu::SurfaceTarget::Canvas(canvas.clone())) .map_err(|err| format!("failed to create wgpu surface: {err}"))?; let depth_stencil_format = egui_wgpu::depth_format_from_bits(options.depth_buffer, 0); let render_state = RenderState::create( &options.wgpu_options, &instance, Some(&surface), egui_wgpu::RendererOptions { dithering: options.dithering, depth_stencil_format, ..Default::default() }, ) .await .map_err(|err| err.to_string())?; let default_configuration = surface .get_default_config(&render_state.adapter, 0, 0) // Width/height is set later. .ok_or("The surface isn't supported by this adapter")?; let surface_configuration = wgpu::SurfaceConfiguration { format: render_state.target_format, present_mode: options.wgpu_options.present_mode, view_formats: vec![render_state.target_format], ..default_configuration }; log::debug!("wgpu painter initialized."); let (capture_tx, capture_rx) = capture_channel(); Ok(Self { canvas, render_state: Some(render_state), surface, surface_configuration, depth_stencil_format, depth_texture_view: None, on_surface_error: Arc::clone(&options.wgpu_options.on_surface_error) as _, screen_capture_state: None, capture_tx, capture_rx, ctx, }) } } impl WebPainter for WebPainterWgpu { fn canvas(&self) -> &HtmlCanvasElement { &self.canvas } fn max_texture_side(&self) -> usize { self.render_state.as_ref().map_or(0, |state| { state.device.limits().max_texture_dimension_2d as _ }) } fn paint_and_update_textures( &mut self, clear_color: [f32; 4], clipped_primitives: &[egui::ClippedPrimitive], pixels_per_point: f32, textures_delta: &egui::TexturesDelta, capture_data: Vec<UserData>, ) -> Result<(), JsValue> { let capture = !capture_data.is_empty(); let size_in_pixels = [self.canvas.width(), self.canvas.height()]; let Some(render_state) = &self.render_state else { return Err(JsValue::from_str( "Can't paint, wgpu renderer was already disposed", )); }; let mut encoder = render_state .device .create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("egui_webpainter_paint_and_update_textures"), }); // Upload all resources for the GPU. let screen_descriptor = egui_wgpu::ScreenDescriptor { size_in_pixels, pixels_per_point, }; let user_cmd_bufs = { let mut renderer = render_state.renderer.write(); for (id, image_delta) in &textures_delta.set { renderer.update_texture( &render_state.device, &render_state.queue, *id, image_delta, ); } renderer.update_buffers( &render_state.device, &render_state.queue, &mut encoder, clipped_primitives, &screen_descriptor, ) }; // Resize surface if needed let is_zero_sized_surface = size_in_pixels[0] == 0 || size_in_pixels[1] == 0; let frame_and_capture_buffer = if is_zero_sized_surface { None } else { if size_in_pixels[0] != self.surface_configuration.width || size_in_pixels[1] != self.surface_configuration.height { self.surface_configuration.width = size_in_pixels[0]; self.surface_configuration.height = size_in_pixels[1]; self.surface .configure(&render_state.device, &self.surface_configuration); self.depth_texture_view = self.generate_depth_texture_view( render_state, size_in_pixels[0], size_in_pixels[1], ); } let output_frame = match self.surface.get_current_texture() { Ok(frame) => frame, Err(err) => match (*self.on_surface_error)(err) { SurfaceErrorAction::RecreateSurface => { self.surface .configure(&render_state.device, &self.surface_configuration); return Ok(()); } SurfaceErrorAction::SkipFrame => { return Ok(()); } }, }; { let renderer = render_state.renderer.read(); let target_texture = if capture { let capture_state = self.screen_capture_state.get_or_insert_with(|| { CaptureState::new(&render_state.device, &output_frame.texture) }); capture_state.update(&render_state.device, &output_frame.texture); &capture_state.texture } else { &output_frame.texture }; let target_view = target_texture.create_view(&wgpu::TextureViewDescriptor::default()); let render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { color_attachments: &[Some(wgpu::RenderPassColorAttachment { view: &target_view, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color { r: clear_color[0] as f64, g: clear_color[1] as f64, b: clear_color[2] as f64, a: clear_color[3] as f64, }), store: wgpu::StoreOp::Store, }, depth_slice: None, })], depth_stencil_attachment: self.depth_texture_view.as_ref().map(|view| { wgpu::RenderPassDepthStencilAttachment { view, depth_ops: self .depth_stencil_format .is_some_and(|depth_stencil_format| { depth_stencil_format.has_depth_aspect() }) .then_some(wgpu::Operations { load: wgpu::LoadOp::Clear(1.0), // It is very unlikely that the depth buffer is needed after egui finished rendering // so no need to store it. (this can improve performance on tiling GPUs like mobile chips or Apple Silicon) store: wgpu::StoreOp::Discard, }), stencil_ops: self .depth_stencil_format .is_some_and(|depth_stencil_format| { depth_stencil_format.has_stencil_aspect() }) .then_some(wgpu::Operations { load: wgpu::LoadOp::Clear(0), store: wgpu::StoreOp::Discard, }), } }), label: Some("egui_render"), occlusion_query_set: None, timestamp_writes: None, }); // Forgetting the pass' lifetime means that we are no longer compile-time protected from // runtime errors caused by accessing the parent encoder before the render pass is dropped. // Since we don't pass it on to the renderer, we should be perfectly safe against this mistake here! renderer.render( &mut render_pass.forget_lifetime(), clipped_primitives, &screen_descriptor, ); } let mut capture_buffer = None; if capture && let Some(capture_state) = &mut self.screen_capture_state { capture_buffer = Some(capture_state.copy_textures( &render_state.device, &output_frame, &mut encoder, )); } Some((output_frame, capture_buffer)) }; // Submit the commands: both the main buffer and user-defined ones. render_state .queue .submit(user_cmd_bufs.into_iter().chain([encoder.finish()])); if let Some((frame, capture_buffer)) = frame_and_capture_buffer { if let Some(capture_buffer) = capture_buffer && let Some(capture_state) = &self.screen_capture_state { capture_state.read_screen_rgba( self.ctx.clone(), capture_buffer, capture_data, self.capture_tx.clone(), ViewportId::ROOT, ); } frame.present(); } // Free textures marked for destruction **after** queue submit since they might still be used in the current frame. // Calling `wgpu::Texture::destroy` on a texture that is still in use would invalidate the command buffer(s) it is used in. // However, once we called `wgpu::Queue::submit`, it is up for wgpu to determine how long the underlying gpu resource has to live. { let mut renderer = render_state.renderer.write(); for id in &textures_delta.free { renderer.free_texture(id); } } Ok(()) } fn handle_screenshots(&mut self, events: &mut Vec<Event>) { for (viewport_id, user_data, screenshot) in self.capture_rx.try_iter() { let screenshot = Arc::new(screenshot); for data in user_data { events.push(Event::Screenshot { viewport_id, user_data: data, image: Arc::clone(&screenshot), }); } } } fn destroy(&mut self) { self.render_state = None; } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/eframe/src/web/app_runner.rs
crates/eframe/src/web/app_runner.rs
use std::sync::Arc; use egui::{TexturesDelta, UserData, ViewportCommand}; use crate::{App, epi, web::web_painter::WebPainter}; use super::{NeedRepaint, now_sec, text_agent::TextAgent}; pub struct AppRunner { #[allow(clippy::allow_attributes, dead_code)] pub(crate) web_options: crate::WebOptions, pub(crate) frame: epi::Frame, egui_ctx: egui::Context, painter: Box<dyn WebPainter>, pub(crate) input: super::WebInput, app: Box<dyn epi::App>, pub(crate) needs_repaint: Arc<NeedRepaint>, last_save_time: f64, pub(crate) text_agent: TextAgent, // If not empty, the painter should capture n frames from now. // zero means capture the exact next frame. screenshot_commands_with_frame_delay: Vec<(UserData, usize)>, // Output for the last run: textures_delta: TexturesDelta, clipped_primitives: Option<Vec<egui::ClippedPrimitive>>, } impl Drop for AppRunner { fn drop(&mut self) { log::debug!("AppRunner has fully dropped"); } } impl AppRunner { /// # Errors /// Failure to initialize WebGL renderer, or failure to create app. #[cfg_attr( not(feature = "wgpu_no_default_features"), expect(clippy::unused_async) )] pub async fn new( canvas: web_sys::HtmlCanvasElement, web_options: crate::WebOptions, app_creator: epi::AppCreator<'static>, text_agent: TextAgent, ) -> Result<Self, String> { let egui_ctx = egui::Context::default(); #[allow(clippy::allow_attributes, unused_assignments)] #[cfg(feature = "glow")] let mut gl = None; #[allow(clippy::allow_attributes, unused_assignments)] #[cfg(feature = "wgpu_no_default_features")] let mut wgpu_render_state = None; let painter = match web_options.renderer { #[cfg(feature = "glow")] epi::Renderer::Glow => { log::debug!("Using the glow renderer"); let painter = super::web_painter_glow::WebPainterGlow::new( egui_ctx.clone(), canvas, &web_options, )?; gl = Some(Arc::clone(painter.gl())); Box::new(painter) as Box<dyn WebPainter> } #[cfg(feature = "wgpu_no_default_features")] epi::Renderer::Wgpu => { log::debug!("Using the wgpu renderer"); let painter = super::web_painter_wgpu::WebPainterWgpu::new( egui_ctx.clone(), canvas, &web_options, ) .await?; wgpu_render_state = painter.render_state(); Box::new(painter) as Box<dyn WebPainter> } }; let info = epi::IntegrationInfo { web_info: epi::WebInfo { user_agent: super::user_agent().unwrap_or_default(), location: super::web_location(), }, cpu_usage: None, }; let storage = LocalStorage::default(); egui_ctx.set_os(egui::os::OperatingSystem::from_user_agent( &super::user_agent().unwrap_or_default(), )); super::storage::load_memory(&egui_ctx); egui_ctx.options_mut(|o| { // On web by default egui follows the zoom factor of the browser, // and lets the browser handle the zoom shortcuts. // A user can still zoom egui separately by calling [`egui::Context::set_zoom_factor`]. o.zoom_with_keyboard = false; o.zoom_factor = 1.0; }); // Tell egui right away about native_pixels_per_point // so that the app knows about it during app creation: egui_ctx.input_mut(|i| { let viewport_info = i.raw.viewports.entry(egui::ViewportId::ROOT).or_default(); viewport_info.native_pixels_per_point = Some(super::native_pixels_per_point()); i.pixels_per_point = super::native_pixels_per_point(); }); let cc = epi::CreationContext { egui_ctx: egui_ctx.clone(), integration_info: info.clone(), storage: Some(&storage), #[cfg(feature = "glow")] gl: gl.clone(), #[cfg(feature = "glow")] get_proc_address: None, #[cfg(feature = "wgpu_no_default_features")] wgpu_render_state: wgpu_render_state.clone(), }; let app = app_creator(&cc).map_err(|err| err.to_string())?; let frame = epi::Frame { info, storage: Some(Box::new(storage)), #[cfg(feature = "glow")] gl, #[cfg(feature = "wgpu_no_default_features")] wgpu_render_state, }; let needs_repaint: Arc<NeedRepaint> = Arc::new(NeedRepaint::new(web_options.max_fps)); { let needs_repaint = Arc::clone(&needs_repaint); egui_ctx.set_request_repaint_callback(move |info| { needs_repaint.repaint_after(info.delay.as_secs_f64()); }); } let mut runner = Self { web_options, frame, egui_ctx, painter, input: Default::default(), app, needs_repaint, last_save_time: now_sec(), text_agent, screenshot_commands_with_frame_delay: vec![], textures_delta: Default::default(), clipped_primitives: None, }; runner.input.raw.max_texture_side = Some(runner.painter.max_texture_side()); runner .input .raw .viewports .entry(egui::ViewportId::ROOT) .or_default() .native_pixels_per_point = Some(super::native_pixels_per_point()); runner.input.raw.system_theme = super::system_theme(); Ok(runner) } pub fn egui_ctx(&self) -> &egui::Context { &self.egui_ctx } /// Get mutable access to the concrete [`App`] we enclose. /// /// This will panic if your app does not implement [`App::as_any_mut`]. pub fn app_mut<ConcreteApp: 'static + App>(&mut self) -> &mut ConcreteApp { self.app .as_any_mut() .expect("Your app must implement `as_any_mut`, but it doesn't") .downcast_mut::<ConcreteApp>() .expect("app_mut got the wrong type of App") } pub fn auto_save_if_needed(&mut self) { let time_since_last_save = now_sec() - self.last_save_time; if time_since_last_save > self.app.auto_save_interval().as_secs_f64() { self.save(); } } pub fn save(&mut self) { if self.app.persist_egui_memory() { super::storage::save_memory(&self.egui_ctx); } if let Some(storage) = self.frame.storage_mut() { self.app.save(storage); } self.last_save_time = now_sec(); } pub fn canvas(&self) -> &web_sys::HtmlCanvasElement { self.painter.canvas() } pub fn destroy(mut self) { log::debug!("Destroying AppRunner"); self.painter.destroy(); } pub fn has_outstanding_paint_data(&self) -> bool { self.clipped_primitives.is_some() } /// Does the eframe app have focus? /// /// Technically: does either the canvas or the [`TextAgent`] have focus? pub fn has_focus(&self) -> bool { let window = web_sys::window().unwrap(); let document = window.document().unwrap(); if document.hidden() { return false; } super::has_focus(self.canvas()) || self.text_agent.has_focus() } pub fn update_focus(&mut self) { let has_focus = self.has_focus(); if self.input.raw.focused != has_focus { log::trace!("{} Focus changed to {has_focus}", self.canvas().id()); self.input.set_focus(has_focus); if !has_focus { // We lost focus - good idea to save self.save(); } self.egui_ctx().request_repaint(); } } /// Runs the logic, but doesn't paint the result. /// /// The result can be painted later with a call to [`Self::run_and_paint`] or [`Self::paint`]. pub fn logic(&mut self) { // We sometimes miss blur/focus events due to the text agent, so let's just poll each frame: self.update_focus(); // We might have received a screenshot self.painter.handle_screenshots(&mut self.input.raw.events); let canvas_size = super::canvas_size_in_points(self.canvas(), self.egui_ctx()); let mut raw_input = self.input.new_frame(canvas_size); if super::DEBUG_RESIZE { log::info!( "egui running at canvas size: {}x{}, DPR: {}, zoom_factor: {}. egui size: {}x{} points", self.canvas().width(), self.canvas().height(), super::native_pixels_per_point(), self.egui_ctx.zoom_factor(), canvas_size.x, canvas_size.y, ); } self.app.raw_input_hook(&self.egui_ctx, &mut raw_input); let full_output = self.egui_ctx.run_ui(raw_input, |ui| { self.app.logic(ui.ctx(), &mut self.frame); #[expect(deprecated)] self.app.update(ui.ctx(), &mut self.frame); self.app.ui(ui, &mut self.frame); }); let egui::FullOutput { platform_output, textures_delta, shapes, pixels_per_point, viewport_output, } = full_output; if viewport_output.len() > 1 { log::warn!("Multiple viewports not yet supported on the web"); } for (_viewport_id, viewport_output) in viewport_output { for command in viewport_output.commands { match command { ViewportCommand::Screenshot(user_data) => { self.screenshot_commands_with_frame_delay .push((user_data, 1)); } _ => { // TODO(emilk): handle some of the commands log::warn!( "Unhandled egui viewport command: {command:?} - not implemented in web backend" ); } } } } self.handle_platform_output(platform_output); self.textures_delta.append(textures_delta); self.clipped_primitives = Some(self.egui_ctx.tessellate(shapes, pixels_per_point)); } /// Paint the results of the last call to [`Self::logic`]. pub fn paint(&mut self) { let textures_delta = std::mem::take(&mut self.textures_delta); let clipped_primitives = std::mem::take(&mut self.clipped_primitives); if let Some(clipped_primitives) = clipped_primitives { let mut screenshot_commands = vec![]; self.screenshot_commands_with_frame_delay .retain_mut(|(user_data, frame_delay)| { if *frame_delay == 0 { screenshot_commands.push(user_data.clone()); false } else { *frame_delay -= 1; true } }); if !self.screenshot_commands_with_frame_delay.is_empty() { self.egui_ctx().request_repaint(); } if let Err(err) = self.painter.paint_and_update_textures( self.app.clear_color(&self.egui_ctx.global_style().visuals), &clipped_primitives, self.egui_ctx.pixels_per_point(), &textures_delta, screenshot_commands, ) { log::error!("Failed to paint: {}", super::string_from_js_value(&err)); } } } pub fn report_frame_time(&mut self, cpu_usage_seconds: f32) { self.frame.info.cpu_usage = Some(cpu_usage_seconds); } fn handle_platform_output(&self, platform_output: egui::PlatformOutput) { #[cfg(feature = "web_screen_reader")] if self.egui_ctx.options(|o| o.screen_reader) { super::screen_reader::speak(&platform_output.events_description()); } let egui::PlatformOutput { commands, cursor_icon, events: _, // already handled mutable_text_under_cursor: _, // TODO(#4569): https://github.com/emilk/egui/issues/4569 ime, accesskit_update: _, // not currently implemented num_completed_passes: _, // handled by `Context::run` request_discard_reasons: _, // handled by `Context::run` } = platform_output; for command in commands { match command { egui::OutputCommand::CopyText(text) => { super::set_clipboard_text(&text); } egui::OutputCommand::CopyImage(image) => { super::set_clipboard_image(&image); } egui::OutputCommand::OpenUrl(open_url) => { super::open_url(&open_url.url, open_url.new_tab); } } } super::set_cursor_icon(cursor_icon); if self.has_focus() { // The eframe app has focus. if ime.is_some() { // We are editing text: give the focus to the text agent. self.text_agent.focus(); } else { // We are not editing text - give the focus to the canvas. self.text_agent.blur(); self.canvas().focus().ok(); } } if let Err(err) = self .text_agent .move_to(ime, self.canvas(), self.egui_ctx.zoom_factor()) { log::error!( "failed to update text agent position: {}", super::string_from_js_value(&err) ); } } } // ---------------------------------------------------------------------------- #[derive(Default)] struct LocalStorage {} impl epi::Storage for LocalStorage { fn get_string(&self, key: &str) -> Option<String> { super::storage::local_storage_get(key) } fn set_string(&mut self, key: &str, value: String) { super::storage::local_storage_set(key, &value); } fn flush(&mut self) {} }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/eframe/src/web/mod.rs
crates/eframe/src/web/mod.rs
//! [`egui`] bindings for web apps (compiling to WASM). #![expect(clippy::missing_errors_doc)] // So many `-> Result<_, JsValue>` #![expect(clippy::unwrap_used)] // TODO(emilk): remove unwraps mod app_runner; mod backend; mod events; mod input; mod panic_handler; mod text_agent; mod web_logger; mod web_runner; /// Access to the browser screen reader. #[cfg(feature = "web_screen_reader")] pub mod screen_reader; /// Access to local browser storage. pub mod storage; pub(crate) use app_runner::AppRunner; pub use panic_handler::{PanicHandler, PanicSummary}; pub use web_logger::WebLogger; pub use web_runner::WebRunner; #[cfg(not(any(feature = "glow", feature = "wgpu_no_default_features")))] compile_error!("You must enable either the 'glow' or 'wgpu' feature"); mod web_painter; #[cfg(feature = "glow")] mod web_painter_glow; #[cfg(feature = "wgpu_no_default_features")] mod web_painter_wgpu; pub use backend::*; use egui::Theme; use wasm_bindgen::prelude::*; use web_sys::{Document, MediaQueryList, Node}; use input::{ button_from_mouse_event, modifiers_from_kb_event, modifiers_from_mouse_event, modifiers_from_wheel_event, pos_from_mouse_event, primary_touch_pos, push_touches, text_from_keyboard_event, translate_key, }; // ---------------------------------------------------------------------------- /// Debug browser resizing? const DEBUG_RESIZE: bool = false; pub(crate) fn string_from_js_value(value: &JsValue) -> String { value.as_string().unwrap_or_else(|| format!("{value:#?}")) } /// Returns the `Element` with active focus. /// /// Elements can only be focused if they are: /// - `<a>`/`<area>` with an `href` attribute /// - `<input>`/`<select>`/`<textarea>`/`<button>` which aren't `disabled` /// - any other element with a `tabindex` attribute pub(crate) fn focused_element(root: &Node) -> Option<web_sys::Element> { if let Some(document) = root.dyn_ref::<Document>() { document.active_element() } else if let Some(shadow) = root.dyn_ref::<web_sys::ShadowRoot>() { shadow.active_element() } else { None } } pub(crate) fn has_focus<T: JsCast>(element: &T) -> bool { fn try_has_focus<T: JsCast>(element: &T) -> Option<bool> { let element = element.dyn_ref::<web_sys::Element>()?; let root = element.get_root_node(); let focused_element = focused_element(&root)?; Some(element == &focused_element) } try_has_focus(element).unwrap_or(false) } /// Current time in seconds (since undefined point in time). /// /// Monotonically increasing. pub fn now_sec() -> f64 { web_sys::window() .expect("should have a Window") .performance() .expect("should have a Performance") .now() / 1000.0 } /// The native GUI scale factor, taking into account the browser zoom. /// /// Corresponds to [`window.devicePixelRatio`](https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio) in JavaScript. pub fn native_pixels_per_point() -> f32 { let pixels_per_point = web_sys::window().unwrap().device_pixel_ratio() as f32; if pixels_per_point > 0.0 && pixels_per_point.is_finite() { pixels_per_point } else { 1.0 } } /// Ask the browser about the preferred system theme. /// /// `None` means unknown. pub fn system_theme() -> Option<egui::Theme> { let window = web_sys::window()?; if does_prefer_color_scheme(&window, Theme::Dark) == Some(true) { Some(Theme::Dark) } else if does_prefer_color_scheme(&window, Theme::Light) == Some(true) { Some(Theme::Light) } else { None } } fn does_prefer_color_scheme(window: &web_sys::Window, theme: Theme) -> Option<bool> { Some(prefers_color_scheme(window, theme).ok()??.matches()) } fn prefers_color_scheme( window: &web_sys::Window, theme: Theme, ) -> Result<Option<MediaQueryList>, JsValue> { let theme = match theme { Theme::Dark => "dark", Theme::Light => "light", }; window.match_media(format!("(prefers-color-scheme: {theme})").as_str()) } /// Returns the canvas in client coordinates. fn canvas_content_rect(canvas: &web_sys::HtmlCanvasElement) -> egui::Rect { let bounding_rect = canvas.get_bounding_client_rect(); let mut rect = egui::Rect::from_min_max( egui::pos2(bounding_rect.left() as f32, bounding_rect.top() as f32), egui::pos2(bounding_rect.right() as f32, bounding_rect.bottom() as f32), ); // We need to subtract padding and border: if let Some(window) = web_sys::window() && let Ok(Some(style)) = window.get_computed_style(canvas) { let get_property = |name: &str| -> Option<f32> { let property = style.get_property_value(name).ok()?; property.trim_end_matches("px").parse::<f32>().ok() }; rect.min.x += get_property("padding-left").unwrap_or_default(); rect.min.y += get_property("padding-top").unwrap_or_default(); rect.max.x -= get_property("padding-right").unwrap_or_default(); rect.max.y -= get_property("padding-bottom").unwrap_or_default(); } rect } fn canvas_size_in_points(canvas: &web_sys::HtmlCanvasElement, ctx: &egui::Context) -> egui::Vec2 { // ctx.pixels_per_point can be outdated let pixels_per_point = ctx.zoom_factor() * native_pixels_per_point(); egui::vec2( canvas.width() as f32 / pixels_per_point, canvas.height() as f32 / pixels_per_point, ) } // ---------------------------------------------------------------------------- /// Set the cursor icon. fn set_cursor_icon(cursor: egui::CursorIcon) -> Option<()> { let document = web_sys::window()?.document()?; document .body()? .style() .set_property("cursor", cursor_web_name(cursor)) .ok() } /// Set the clipboard text. fn set_clipboard_text(s: &str) { if let Some(window) = web_sys::window() { if !window.is_secure_context() { log::error!( "Clipboard is not available because we are not in a secure context. \ See https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts" ); return; } let promise = window.navigator().clipboard().write_text(s); let future = wasm_bindgen_futures::JsFuture::from(promise); let future = async move { if let Err(err) = future.await { log::error!("Copy/cut action failed: {}", string_from_js_value(&err)); } }; wasm_bindgen_futures::spawn_local(future); } } /// Set the clipboard image. fn set_clipboard_image(image: &egui::ColorImage) { if let Some(window) = web_sys::window() { if !window.is_secure_context() { log::error!( "Clipboard is not available because we are not in a secure context. \ See https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts" ); return; } let png_bytes = to_image(image).and_then(|image| to_png_bytes(&image)); let png_bytes = match png_bytes { Ok(png_bytes) => png_bytes, Err(err) => { log::error!("Failed to encode image to png: {err}"); return; } }; let mime = "image/png"; let item = match create_clipboard_item(mime, &png_bytes) { Ok(item) => item, Err(err) => { log::error!("Failed to copy image: {}", string_from_js_value(&err)); return; } }; let items = js_sys::Array::of1(&item); let promise = window.navigator().clipboard().write(&items); let future = wasm_bindgen_futures::JsFuture::from(promise); let future = async move { if let Err(err) = future.await { log::error!( "Copy/cut image action failed: {}", string_from_js_value(&err) ); } }; wasm_bindgen_futures::spawn_local(future); } } fn to_image(image: &egui::ColorImage) -> Result<image::RgbaImage, String> { profiling::function_scope!(); image::RgbaImage::from_raw( image.width() as _, image.height() as _, bytemuck::cast_slice(&image.pixels).to_vec(), ) .ok_or_else(|| "Invalid IconData".to_owned()) } fn to_png_bytes(image: &image::RgbaImage) -> Result<Vec<u8>, String> { profiling::function_scope!(); let mut png_bytes: Vec<u8> = Vec::new(); image .write_to( &mut std::io::Cursor::new(&mut png_bytes), image::ImageFormat::Png, ) .map_err(|err| err.to_string())?; Ok(png_bytes) } fn create_clipboard_item(mime: &str, bytes: &[u8]) -> Result<web_sys::ClipboardItem, JsValue> { let array = js_sys::Uint8Array::from(bytes); let blob_parts = js_sys::Array::new(); blob_parts.push(&array); let options = web_sys::BlobPropertyBag::new(); options.set_type(mime); let blob = web_sys::Blob::new_with_u8_array_sequence_and_options(&blob_parts, &options)?; let items = js_sys::Object::new(); #[expect(unsafe_code, unused_unsafe)] // Weird false positive // SAFETY: I hope so unsafe { js_sys::Reflect::set(&items, &JsValue::from_str(mime), &blob)? }; let clipboard_item = web_sys::ClipboardItem::new_with_record_from_str_to_blob_promise(&items)?; Ok(clipboard_item) } fn cursor_web_name(cursor: egui::CursorIcon) -> &'static str { match cursor { egui::CursorIcon::Alias => "alias", egui::CursorIcon::AllScroll => "all-scroll", egui::CursorIcon::Cell => "cell", egui::CursorIcon::ContextMenu => "context-menu", egui::CursorIcon::Copy => "copy", egui::CursorIcon::Crosshair => "crosshair", egui::CursorIcon::Default => "default", egui::CursorIcon::Grab => "grab", egui::CursorIcon::Grabbing => "grabbing", egui::CursorIcon::Help => "help", egui::CursorIcon::Move => "move", egui::CursorIcon::NoDrop => "no-drop", egui::CursorIcon::None => "none", egui::CursorIcon::NotAllowed => "not-allowed", egui::CursorIcon::PointingHand => "pointer", egui::CursorIcon::Progress => "progress", egui::CursorIcon::ResizeHorizontal => "ew-resize", egui::CursorIcon::ResizeNeSw => "nesw-resize", egui::CursorIcon::ResizeNwSe => "nwse-resize", egui::CursorIcon::ResizeVertical => "ns-resize", egui::CursorIcon::ResizeEast => "e-resize", egui::CursorIcon::ResizeSouthEast => "se-resize", egui::CursorIcon::ResizeSouth => "s-resize", egui::CursorIcon::ResizeSouthWest => "sw-resize", egui::CursorIcon::ResizeWest => "w-resize", egui::CursorIcon::ResizeNorthWest => "nw-resize", egui::CursorIcon::ResizeNorth => "n-resize", egui::CursorIcon::ResizeNorthEast => "ne-resize", egui::CursorIcon::ResizeColumn => "col-resize", egui::CursorIcon::ResizeRow => "row-resize", egui::CursorIcon::Text => "text", egui::CursorIcon::VerticalText => "vertical-text", egui::CursorIcon::Wait => "wait", egui::CursorIcon::ZoomIn => "zoom-in", egui::CursorIcon::ZoomOut => "zoom-out", } } /// Open the given url in the browser. pub fn open_url(url: &str, new_tab: bool) -> Option<()> { let name = if new_tab { "_blank" } else { "_self" }; web_sys::window()? .open_with_url_and_target(url, name) .ok()?; Some(()) } /// e.g. "#fragment" part of "www.example.com/index.html#fragment", /// /// Percent decoded pub fn location_hash() -> String { percent_decode( &web_sys::window() .unwrap() .location() .hash() .unwrap_or_default(), ) } /// Percent-decodes a string. pub fn percent_decode(s: &str) -> String { percent_encoding::percent_decode_str(s) .decode_utf8_lossy() .to_string() } /// Are we running inside the Safari browser? pub fn is_safari_browser() -> bool { web_sys::window().is_some_and(|window| window.has_own_property(&JsValue::from("safari"))) }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/eframe/src/web/events.rs
crates/eframe/src/web/events.rs
use crate::web::string_from_js_value; use super::{ AppRunner, Closure, DEBUG_RESIZE, JsCast as _, JsValue, WebRunner, button_from_mouse_event, location_hash, modifiers_from_kb_event, modifiers_from_mouse_event, modifiers_from_wheel_event, native_pixels_per_point, pos_from_mouse_event, prefers_color_scheme, primary_touch_pos, push_touches, text_from_keyboard_event, translate_key, }; use js_sys::Reflect; use web_sys::{Document, EventTarget, ShadowRoot}; // TODO(emilk): there are more calls to `prevent_default` and `stop_propagation` // than what is probably needed. // ------------------------------------------------------------------------ /// Calls `request_animation_frame` to schedule repaint. /// /// It will only paint if needed, but will always call `request_animation_frame` immediately. pub(crate) fn paint_and_schedule(runner_ref: &WebRunner) -> Result<(), JsValue> { // Only paint and schedule if there has been no panic if let Some(mut runner_lock) = runner_ref.try_lock() { paint_if_needed(&mut runner_lock); drop(runner_lock); runner_ref.request_animation_frame()?; } Ok(()) } fn paint_if_needed(runner: &mut AppRunner) { if runner.needs_repaint.needs_repaint() { if runner.has_outstanding_paint_data() { // We have already run the logic, e.g. in an on-click event, // so let's only present the results: runner.paint(); // We schedule another repaint asap, so that we can run the actual logic // again, which may schedule a new repaint (if there's animations): runner.needs_repaint.repaint_asap(); } else { // Clear the `needs_repaint` flags _before_ // running the logic, as the logic could cause it to be set again. runner.needs_repaint.clear(); let mut stopwatch = crate::stopwatch::Stopwatch::new(); stopwatch.start(); // Run user code… runner.logic(); // …and paint the result. runner.paint(); runner.report_frame_time(stopwatch.total_time_sec()); } } runner.auto_save_if_needed(); } // ------------------------------------------------------------------------ pub(crate) fn install_event_handlers(runner_ref: &WebRunner) -> Result<(), JsValue> { let window = web_sys::window().unwrap(); let document = window.document().unwrap(); let canvas = runner_ref.try_lock().unwrap().canvas().clone(); install_blur_focus(runner_ref, &document)?; install_blur_focus(runner_ref, &canvas)?; prevent_default_and_stop_propagation( runner_ref, &canvas, &[ // Allow users to use ctrl-p for e.g. a command palette: "afterprint", // By default, right-clicks open a browser context menu. // We don't want to do that (right clicks are handled by egui): "contextmenu", ], )?; install_keydown(runner_ref, &canvas)?; install_keyup(runner_ref, &canvas)?; // It seems copy/cut/paste events only work on the document, // so we check if we have focus inside of the handler. install_copy_cut_paste(runner_ref, &document)?; // Use `document` here to notice if the user releases a drag outside of the canvas: // See https://github.com/emilk/egui/issues/3157 install_mousemove(runner_ref, &document)?; install_pointerup(runner_ref, &document)?; install_pointerdown(runner_ref, &canvas)?; install_mouseleave(runner_ref, &canvas)?; install_touchstart(runner_ref, &canvas)?; // Use `document` here to notice if the user drag outside of the canvas: // See https://github.com/emilk/egui/issues/3157 install_touchmove(runner_ref, &document)?; install_touchend(runner_ref, &document)?; install_touchcancel(runner_ref, &canvas)?; install_wheel(runner_ref, &canvas)?; install_gesture(runner_ref, &canvas)?; install_drag_and_drop(runner_ref, &canvas)?; install_window_events(runner_ref, &window)?; install_color_scheme_change_event(runner_ref, &window)?; Ok(()) } fn install_blur_focus(runner_ref: &WebRunner, target: &EventTarget) -> Result<(), JsValue> { // NOTE: because of the text agent we sometime miss 'blur' events, // so we also poll the focus state each frame in `AppRunner::logic`. for event_name in ["blur", "focus", "visibilitychange"] { let closure = move |_event: web_sys::MouseEvent, runner: &mut AppRunner| { log::trace!("{} {event_name:?}", runner.canvas().id()); runner.update_focus(); }; runner_ref.add_event_listener(target, event_name, closure)?; } Ok(()) } fn install_keydown(runner_ref: &WebRunner, target: &EventTarget) -> Result<(), JsValue> { runner_ref.add_event_listener( target, "keydown", |event: web_sys::KeyboardEvent, runner| { if !runner.input.raw.focused { return; } let modifiers = modifiers_from_kb_event(&event); if !modifiers.ctrl && !modifiers.command // When text agent is focused, it is responsible for handling input events && !runner.text_agent.has_focus() && let Some(text) = text_from_keyboard_event(&event) { let egui_event = egui::Event::Text(text); let should_stop_propagation = (runner.web_options.should_stop_propagation)(&egui_event); let should_prevent_default = (runner.web_options.should_prevent_default)(&egui_event); runner.input.raw.events.push(egui_event); runner.needs_repaint.repaint_asap(); // If this is indeed text, then prevent any other action. if should_prevent_default { event.prevent_default(); } // Use web options to tell if the event should be propagated to parent elements. if should_stop_propagation { event.stop_propagation(); } } on_keydown(event, runner); }, ) } #[expect(clippy::needless_pass_by_value)] // So that we can pass it directly to `add_event_listener` pub(crate) fn on_keydown(event: web_sys::KeyboardEvent, runner: &mut AppRunner) { let has_focus = runner.input.raw.focused; if !has_focus { return; } if event.is_composing() || event.key_code() == 229 { // https://web.archive.org/web/20200526195704/https://www.fxsitecompat.dev/en-CA/docs/2018/keydown-and-keyup-events-are-now-fired-during-ime-composition/ return; } let modifiers = modifiers_from_kb_event(&event); runner.input.raw.modifiers = modifiers; let key = event.key(); let egui_key = translate_key(&key); if let Some(egui_key) = egui_key { let egui_event = egui::Event::Key { key: egui_key, physical_key: None, // TODO(fornwall) pressed: true, repeat: false, // egui will fill this in for us! modifiers, }; let should_stop_propagation = (runner.web_options.should_stop_propagation)(&egui_event); runner.input.raw.events.push(egui_event); runner.needs_repaint.repaint_asap(); let prevent_default = should_prevent_default_for_key(runner, &modifiers, egui_key); if false { log::debug!( "On keydown {:?} {egui_key:?}, has_focus: {has_focus}, egui_wants_keyboard: {}, prevent_default: {prevent_default}", event.key().as_str(), runner.egui_ctx().egui_wants_keyboard_input() ); } if prevent_default { event.prevent_default(); } // Use web options to tell if the web event should be propagated to parent elements based on the egui event. if should_stop_propagation { event.stop_propagation(); } } } /// If the canvas (or text agent) has focus: /// should we prevent the default browser event action when the user presses this key? fn should_prevent_default_for_key( runner: &AppRunner, modifiers: &egui::Modifiers, egui_key: egui::Key, ) -> bool { // NOTE: We never want to prevent: // * F5 / cmd-R (refresh) // * cmd-shift-C (debug tools) // * cmd/ctrl-c/v/x (lest we prevent copy/paste/cut events) // Prevent cmd/ctrl plus these keys from triggering the default browser action: let keys = [ egui::Key::Comma, // cmd-, opens options on macOS, which egui apps may wanna "steal" egui::Key::O, // open egui::Key::P, // print (cmd-P is common for command palette) egui::Key::S, // save ]; for key in keys { if egui_key == key && (modifiers.ctrl || modifiers.command || modifiers.mac_cmd) { return true; } } if egui_key == egui::Key::Space && !runner.text_agent.has_focus() { // Space scrolls the web page, but we don't want that while canvas has focus // However, don't prevent it if text agent has focus, or we can't type space! return true; } matches!( egui_key, // Prevent browser from focusing the next HTML element. // egui uses Tab to move focus within the egui app. egui::Key::Tab // So we don't go back to previous page while canvas has focus | egui::Key::Backspace // Don't scroll web page while canvas has focus. // Also, cmd-left is "back" on Mac (https://github.com/emilk/egui/issues/58) | egui::Key::ArrowDown | egui::Key::ArrowLeft | egui::Key::ArrowRight | egui::Key::ArrowUp ) } fn install_keyup(runner_ref: &WebRunner, target: &EventTarget) -> Result<(), JsValue> { runner_ref.add_event_listener(target, "keyup", on_keyup) } #[expect(clippy::needless_pass_by_value)] // So that we can pass it directly to `add_event_listener` pub(crate) fn on_keyup(event: web_sys::KeyboardEvent, runner: &mut AppRunner) { let modifiers = modifiers_from_kb_event(&event); runner.input.raw.modifiers = modifiers; let mut should_stop_propagation = true; if let Some(key) = translate_key(&event.key()) { let egui_event = egui::Event::Key { key, physical_key: None, // TODO(fornwall) pressed: false, repeat: false, modifiers, }; should_stop_propagation &= (runner.web_options.should_stop_propagation)(&egui_event); runner.input.raw.events.push(egui_event); } if event.key() == "Meta" || event.key() == "Control" { // When pressing Cmd+A (select all) or Ctrl+C (copy), // chromium will not fire a `keyup` for the letter key. // This leads to stuck keys, unless we do this hack. // See https://github.com/emilk/egui/issues/4724 let keys_down = runner.egui_ctx().input(|i| i.keys_down.clone()); #[expect(clippy::iter_over_hash_type)] for key in keys_down { let egui_event = egui::Event::Key { key, physical_key: None, pressed: false, repeat: false, modifiers, }; should_stop_propagation &= (runner.web_options.should_stop_propagation)(&egui_event); runner.input.raw.events.push(egui_event); } } runner.needs_repaint.repaint_asap(); // Use web options to tell if the web event should be propagated to parent elements based on the egui event. let has_focus = runner.input.raw.focused; if has_focus && should_stop_propagation { event.stop_propagation(); } } fn install_copy_cut_paste(runner_ref: &WebRunner, target: &EventTarget) -> Result<(), JsValue> { runner_ref.add_event_listener(target, "paste", |event: web_sys::ClipboardEvent, runner| { if !runner.input.raw.focused { return; // The eframe app is not interested } if let Some(data) = event.clipboard_data() && let Ok(text) = data.get_data("text") { let text = text.replace("\r\n", "\n"); let mut should_stop_propagation = true; let mut should_prevent_default = true; if !text.is_empty() { let egui_event = egui::Event::Paste(text); should_stop_propagation = (runner.web_options.should_stop_propagation)(&egui_event); should_prevent_default = (runner.web_options.should_prevent_default)(&egui_event); runner.input.raw.events.push(egui_event); runner.needs_repaint.repaint_asap(); } // Use web options to tell if the web event should be propagated to parent elements based on the egui event. if should_stop_propagation { event.stop_propagation(); } if should_prevent_default { event.prevent_default(); } } })?; runner_ref.add_event_listener(target, "cut", |event: web_sys::ClipboardEvent, runner| { if !runner.input.raw.focused { return; // The eframe app is not interested } runner.input.raw.events.push(egui::Event::Cut); // In Safari we are only allowed to write to the clipboard during the // event callback, which is why we run the app logic here and now: runner.logic(); // Make sure we paint the output of the above logic call asap: runner.needs_repaint.repaint_asap(); // Use web options to tell if the web event should be propagated to parent elements based on the egui event. if (runner.web_options.should_stop_propagation)(&egui::Event::Cut) { event.stop_propagation(); } if (runner.web_options.should_prevent_default)(&egui::Event::Cut) { event.prevent_default(); } })?; runner_ref.add_event_listener(target, "copy", |event: web_sys::ClipboardEvent, runner| { if !runner.input.raw.focused { return; // The eframe app is not interested } runner.input.raw.events.push(egui::Event::Copy); // In Safari we are only allowed to write to the clipboard during the // event callback, which is why we run the app logic here and now: runner.logic(); // Make sure we paint the output of the above logic call asap: runner.needs_repaint.repaint_asap(); // Use web options to tell if the web event should be propagated to parent elements based on the egui event. if (runner.web_options.should_stop_propagation)(&egui::Event::Copy) { event.stop_propagation(); } if (runner.web_options.should_prevent_default)(&egui::Event::Copy) { event.prevent_default(); } })?; Ok(()) } fn install_window_events(runner_ref: &WebRunner, window: &EventTarget) -> Result<(), JsValue> { // Save-on-close runner_ref.add_event_listener(window, "onbeforeunload", |_: web_sys::Event, runner| { runner.save(); })?; // We want to handle the case of dragging the browser from one monitor to another, // which can cause the DPR to change without any resize event (e.g. Safari). install_dpr_change_event(runner_ref)?; // No need to subscribe to "resize": we already subscribe to the canvas // size using a ResizeObserver, and we also subscribe to DPR changes of the monitor. for event_name in &["load", "pagehide", "pageshow", "popstate"] { runner_ref.add_event_listener(window, event_name, move |_: web_sys::Event, runner| { if DEBUG_RESIZE { log::debug!("{event_name:?}"); } runner.needs_repaint.repaint_asap(); })?; } runner_ref.add_event_listener(window, "hashchange", |_: web_sys::Event, runner| { // `epi::Frame::info(&self)` clones `epi::IntegrationInfo`, but we need to modify the original here runner.frame.info.web_info.location.hash = location_hash(); runner.needs_repaint.repaint_asap(); // tell the user about the new hash })?; Ok(()) } fn install_dpr_change_event(web_runner: &WebRunner) -> Result<(), JsValue> { let original_dpr = native_pixels_per_point(); let window = web_sys::window().unwrap(); let Some(media_query_list) = window.match_media(&format!("(resolution: {original_dpr}dppx)"))? else { log::error!( "Failed to create MediaQueryList: eframe won't be able to detect changes in DPR" ); return Ok(()); }; let closure = move |_: web_sys::Event, app_runner: &mut AppRunner, web_runner: &WebRunner| { let new_dpr = native_pixels_per_point(); log::debug!("Device Pixel Ratio changed from {original_dpr} to {new_dpr}"); if true { // Explicitly resize canvas to match the new DPR. // This is a bit ugly, but I haven't found a better way to do it. let canvas = app_runner.canvas(); canvas.set_width((canvas.width() as f32 * new_dpr / original_dpr).round() as _); canvas.set_height((canvas.height() as f32 * new_dpr / original_dpr).round() as _); log::debug!("Resized canvas to {}x{}", canvas.width(), canvas.height()); } // It may be tempting to call `resize_observer.observe(&canvas)` here, // but unfortunately this has no effect. if let Err(err) = install_dpr_change_event(web_runner) { log::error!( "Failed to install DPR change event: {}", string_from_js_value(&err) ); } }; let options = web_sys::AddEventListenerOptions::default(); options.set_once(true); web_runner.add_event_listener_ex(&media_query_list, "change", &options, closure) } fn install_color_scheme_change_event( runner_ref: &WebRunner, window: &web_sys::Window, ) -> Result<(), JsValue> { for theme in [egui::Theme::Dark, egui::Theme::Light] { if let Some(media_query_list) = prefers_color_scheme(window, theme)? { runner_ref.add_event_listener::<web_sys::MediaQueryListEvent>( &media_query_list, "change", |_event, runner| { if let Some(theme) = super::system_theme() { runner.input.raw.system_theme = Some(theme); runner.needs_repaint.repaint_asap(); } }, )?; } } Ok(()) } fn prevent_default_and_stop_propagation( runner_ref: &WebRunner, target: &EventTarget, event_names: &[&'static str], ) -> Result<(), JsValue> { for event_name in event_names { let closure = move |event: web_sys::MouseEvent, _runner: &mut AppRunner| { event.prevent_default(); event.stop_propagation(); // log::debug!("Preventing event {event_name:?}"); }; runner_ref.add_event_listener(target, event_name, closure)?; } Ok(()) } fn install_pointerdown(runner_ref: &WebRunner, target: &EventTarget) -> Result<(), JsValue> { runner_ref.add_event_listener( target, "pointerdown", |event: web_sys::PointerEvent, runner: &mut AppRunner| { let modifiers = modifiers_from_mouse_event(&event); runner.input.raw.modifiers = modifiers; let mut should_stop_propagation = true; if let Some(button) = button_from_mouse_event(&event) { let pos = pos_from_mouse_event(runner.canvas(), &event, runner.egui_ctx()); let modifiers = runner.input.raw.modifiers; let egui_event = egui::Event::PointerButton { pos, button, pressed: true, modifiers, }; should_stop_propagation = (runner.web_options.should_stop_propagation)(&egui_event); runner.input.raw.events.push(egui_event); // In Safari we are only allowed to write to the clipboard during the // event callback, which is why we run the app logic here and now: runner.logic(); // Make sure we paint the output of the above logic call asap: runner.needs_repaint.repaint_asap(); } // Use web options to tell if the web event should be propagated to parent elements based on the egui event. if should_stop_propagation { event.stop_propagation(); } // Note: prevent_default breaks VSCode tab focusing, hence why we don't call it here. }, ) } fn install_pointerup(runner_ref: &WebRunner, target: &EventTarget) -> Result<(), JsValue> { runner_ref.add_event_listener( target, "pointerup", |event: web_sys::PointerEvent, runner| { let modifiers = modifiers_from_mouse_event(&event); runner.input.raw.modifiers = modifiers; let pos = pos_from_mouse_event(runner.canvas(), &event, runner.egui_ctx()); if is_interested_in_pointer_event( runner, egui::pos2(event.client_x() as f32, event.client_y() as f32), ) && let Some(button) = button_from_mouse_event(&event) { let modifiers = runner.input.raw.modifiers; let egui_event = egui::Event::PointerButton { pos, button, pressed: false, modifiers, }; let should_stop_propagation = (runner.web_options.should_stop_propagation)(&egui_event); let should_prevent_default = (runner.web_options.should_prevent_default)(&egui_event); runner.input.raw.events.push(egui_event); // Previously on iOS, the canvas would not receive focus on // any touch event, which resulted in the on-screen keyboard // not working when focusing on a text field in an egui app. // This attempts to fix that by forcing the focus on any // click on the canvas. runner.canvas().focus().ok(); // In Safari we are only allowed to do certain things // (like playing audio, start a download, etc) // on user action, such as a click. // So we need to run the app logic here and now: runner.logic(); // Make sure we paint the output of the above logic call asap: runner.needs_repaint.repaint_asap(); if should_prevent_default { event.prevent_default(); } // Use web options to tell if the web event should be propagated to parent elements based on the egui event. if should_stop_propagation { event.stop_propagation(); } } }, ) } /// Returns true if the cursor is above the canvas, or if we're dragging something. /// Pass in the position in browser viewport coordinates (usually event.clientX/Y). fn is_interested_in_pointer_event(runner: &AppRunner, pos: egui::Pos2) -> bool { let root_node = runner.canvas().get_root_node(); let element_at_point = if let Some(document) = root_node.dyn_ref::<Document>() { document.element_from_point(pos.x, pos.y) } else if let Some(shadow) = root_node.dyn_ref::<ShadowRoot>() { shadow.element_from_point(pos.x, pos.y) } else { None }; let is_hovering_canvas = element_at_point.is_some_and(|element| element.eq(runner.canvas())); let is_pointer_down = runner .egui_ctx() .input(|i| i.pointer.any_down() || i.any_touches()); is_hovering_canvas || is_pointer_down } fn install_mousemove(runner_ref: &WebRunner, target: &EventTarget) -> Result<(), JsValue> { runner_ref.add_event_listener(target, "mousemove", |event: web_sys::MouseEvent, runner| { let modifiers = modifiers_from_mouse_event(&event); runner.input.raw.modifiers = modifiers; let pos = pos_from_mouse_event(runner.canvas(), &event, runner.egui_ctx()); if is_interested_in_pointer_event( runner, egui::pos2(event.client_x() as f32, event.client_y() as f32), ) { let egui_event = egui::Event::PointerMoved(pos); let should_stop_propagation = (runner.web_options.should_stop_propagation)(&egui_event); let should_prevent_default = (runner.web_options.should_prevent_default)(&egui_event); runner.input.raw.events.push(egui_event); runner.needs_repaint.repaint(); // Use web options to tell if the web event should be propagated to parent elements based on the egui event. if should_stop_propagation { event.stop_propagation(); } if should_prevent_default { event.prevent_default(); } } }) } fn install_mouseleave(runner_ref: &WebRunner, target: &EventTarget) -> Result<(), JsValue> { runner_ref.add_event_listener( target, "mouseleave", |event: web_sys::MouseEvent, runner| { runner.input.raw.events.push(egui::Event::PointerGone); runner.needs_repaint.repaint_asap(); // Use web options to tell if the web event should be propagated to parent elements based on the egui event. if (runner.web_options.should_stop_propagation)(&egui::Event::PointerGone) { event.stop_propagation(); } if (runner.web_options.should_prevent_default)(&egui::Event::PointerGone) { event.prevent_default(); } }, ) } fn install_touchstart(runner_ref: &WebRunner, target: &EventTarget) -> Result<(), JsValue> { runner_ref.add_event_listener( target, "touchstart", |event: web_sys::TouchEvent, runner| { let mut should_stop_propagation = true; let mut should_prevent_default = true; if let Some((pos, _)) = primary_touch_pos(runner, &event) { let egui_event = egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, modifiers: runner.input.raw.modifiers, }; should_stop_propagation = (runner.web_options.should_stop_propagation)(&egui_event); should_prevent_default = (runner.web_options.should_prevent_default)(&egui_event); runner.input.raw.events.push(egui_event); } push_touches(runner, egui::TouchPhase::Start, &event); runner.needs_repaint.repaint_asap(); // Use web options to tell if the web event should be propagated to parent elements based on the egui event. if should_stop_propagation { event.stop_propagation(); } if should_prevent_default { event.prevent_default(); } }, ) } fn install_touchmove(runner_ref: &WebRunner, target: &EventTarget) -> Result<(), JsValue> { runner_ref.add_event_listener(target, "touchmove", |event: web_sys::TouchEvent, runner| { if let Some((pos, touch)) = primary_touch_pos(runner, &event) && is_interested_in_pointer_event( runner, egui::pos2(touch.client_x() as f32, touch.client_y() as f32), ) { let egui_event = egui::Event::PointerMoved(pos); let should_stop_propagation = (runner.web_options.should_stop_propagation)(&egui_event); let should_prevent_default = (runner.web_options.should_prevent_default)(&egui_event); runner.input.raw.events.push(egui_event); push_touches(runner, egui::TouchPhase::Move, &event); runner.needs_repaint.repaint(); // Use web options to tell if the web event should be propagated to parent elements based on the egui event. if should_stop_propagation { event.stop_propagation(); } if should_prevent_default { event.prevent_default(); } } }) } fn install_touchend(runner_ref: &WebRunner, target: &EventTarget) -> Result<(), JsValue> { runner_ref.add_event_listener(target, "touchend", |event: web_sys::TouchEvent, runner| { if let Some((pos, touch)) = primary_touch_pos(runner, &event) && is_interested_in_pointer_event( runner, egui::pos2(touch.client_x() as f32, touch.client_y() as f32), ) { // First release mouse to click: let mut should_stop_propagation = true; let mut should_prevent_default = true; let egui_event = egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers: runner.input.raw.modifiers, }; should_stop_propagation &= (runner.web_options.should_stop_propagation)(&egui_event); should_prevent_default &= (runner.web_options.should_prevent_default)(&egui_event); runner.input.raw.events.push(egui_event); // Then remove hover effect: should_stop_propagation &= (runner.web_options.should_stop_propagation)(&egui::Event::PointerGone); should_prevent_default &= (runner.web_options.should_prevent_default)(&egui::Event::PointerGone); runner.input.raw.events.push(egui::Event::PointerGone); push_touches(runner, egui::TouchPhase::End, &event); runner.needs_repaint.repaint_asap(); // Use web options to tell if the web event should be propagated to parent elements based on the egui event. if should_stop_propagation { event.stop_propagation(); } if should_prevent_default { event.prevent_default(); } // Fix virtual keyboard IOS // Need call focus at the same time of event if runner.text_agent.has_focus() { runner.text_agent.set_focus(false); runner.text_agent.set_focus(true); } } }) } fn install_touchcancel(runner_ref: &WebRunner, target: &EventTarget) -> Result<(), JsValue> { runner_ref.add_event_listener( target, "touchcancel", |event: web_sys::TouchEvent, runner| { push_touches(runner, egui::TouchPhase::Cancel, &event); event.stop_propagation(); event.prevent_default(); }, )?; Ok(()) } fn install_wheel(runner_ref: &WebRunner, target: &EventTarget) -> Result<(), JsValue> { runner_ref.add_event_listener(target, "wheel", |event: web_sys::WheelEvent, runner| { let unit = match event.delta_mode() { web_sys::WheelEvent::DOM_DELTA_PIXEL => egui::MouseWheelUnit::Point, web_sys::WheelEvent::DOM_DELTA_LINE => egui::MouseWheelUnit::Line, web_sys::WheelEvent::DOM_DELTA_PAGE => egui::MouseWheelUnit::Page, _ => return, }; let delta = -egui::vec2(event.delta_x() as f32, event.delta_y() as f32); let modifiers = modifiers_from_wheel_event(&event); let egui_event = if modifiers.ctrl && !runner.input.raw.modifiers.ctrl { // The browser is saying the ctrl key is down, but it isn't _really_. // This happens on pinch-to-zoom on multitouch trackpads // egui will treat ctrl+scroll as zoom, so it all works. // However, we explicitly handle it here in order to better match the pinch-to-zoom // speed of a native app, without being sensitive to egui's `scroll_zoom_speed` setting. let pinch_to_zoom_sensitivity = 0.01; // Feels good on a Mac trackpad in 2024 let zoom_factor = (pinch_to_zoom_sensitivity * delta.y).exp(); egui::Event::Zoom(zoom_factor) } else { egui::Event::MouseWheel { unit, delta, modifiers,
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
true
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/eframe/src/web/panic_handler.rs
crates/eframe/src/web/panic_handler.rs
use std::sync::Arc; use egui::mutex::Mutex; use wasm_bindgen::prelude::*; /// Detects panics, logs them using `console.error`, and stores the panics message and callstack. /// /// This lets you query `PanicHandler` for the panic message (if any) so you can show it in the HTML. /// /// Chep to clone (ref-counted). #[derive(Clone)] pub struct PanicHandler(Arc<Mutex<PanicHandlerInner>>); impl PanicHandler { /// Install a panic hook. pub fn install() -> Self { let handler = Self(Arc::new(Mutex::new(Default::default()))); let handler_clone = handler.clone(); let previous_hook = std::panic::take_hook(); std::panic::set_hook(Box::new(move |panic_info| { let summary = PanicSummary::new(panic_info); // Log it using console.error error(format!( "{}\n\nStack:\n\n{}", summary.message(), summary.callstack() )); // Remember the summary: handler_clone.0.lock().summary = Some(summary); // Propagate panic info to the previously registered panic hook previous_hook(panic_info); })); handler } /// Has there been a panic? pub fn has_panicked(&self) -> bool { self.0.lock().summary.is_some() } /// What was the panic message and callstack? pub fn panic_summary(&self) -> Option<PanicSummary> { self.0.lock().summary.clone() } } #[derive(Clone, Default)] struct PanicHandlerInner { summary: Option<PanicSummary>, } /// Contains a summary about a panics. /// /// This is basically a human-readable version of [`std::panic::PanicHookInfo`] /// with an added callstack. #[derive(Clone, Debug)] pub struct PanicSummary { message: String, callstack: String, } impl PanicSummary { /// Construct a summary from a panic. pub fn new(info: &std::panic::PanicHookInfo<'_>) -> Self { let message = info.to_string(); let callstack = Error::new().stack(); Self { message, callstack } } /// The panic message. pub fn message(&self) -> String { self.message.clone() } /// The backtrace. pub fn callstack(&self) -> String { self.callstack.clone() } } #[wasm_bindgen] extern "C" { #[wasm_bindgen(js_namespace = console)] fn error(msg: String); type Error; #[wasm_bindgen(constructor)] fn new() -> Error; #[wasm_bindgen(structural, method, getter)] fn stack(error: &Error) -> String; }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/eframe/src/web/text_agent.rs
crates/eframe/src/web/text_agent.rs
//! The text agent is a hidden `<input>` element used to capture //! IME and mobile keyboard input events. use std::cell::Cell; use wasm_bindgen::prelude::*; use web_sys::{Document, Node}; use super::{AppRunner, WebRunner}; pub struct TextAgent { input: web_sys::HtmlInputElement, prev_ime_output: Cell<Option<egui::output::IMEOutput>>, } impl TextAgent { /// Attach the agent to the document. pub fn attach(runner_ref: &WebRunner, root: Node) -> Result<Self, JsValue> { let document = web_sys::window().unwrap().document().unwrap(); // create an `<input>` element let input = document .create_element("input")? .dyn_into::<web_sys::HtmlElement>()?; input.set_autofocus(true)?; let input = input.dyn_into::<web_sys::HtmlInputElement>()?; input.set_type("text"); input.set_attribute("autocapitalize", "off")?; // append it to `<body>` and hide it outside of the viewport let style = input.style(); style.set_property("background-color", "transparent")?; style.set_property("border", "none")?; style.set_property("outline", "none")?; style.set_property("width", "1px")?; style.set_property("height", "1px")?; style.set_property("caret-color", "transparent")?; style.set_property("position", "absolute")?; style.set_property("top", "0")?; style.set_property("left", "0")?; if root.has_type::<Document>() { // root object is a document, append to its body root.dyn_into::<Document>()? .body() .unwrap() .append_child(&input)?; } else { // append input into root directly root.append_child(&input)?; } // attach event listeners let on_input = { let input = input.clone(); move |event: web_sys::InputEvent, runner: &mut AppRunner| { let text = input.value(); // Fix android virtual keyboard Gboard // This removes the virtual keyboard's suggestion. if !event.is_composing() { input.blur().ok(); input.focus().ok(); } // if `is_composing` is true, then user is using IME, for example: emoji, pinyin, kanji, hangul, etc. // In that case, the browser emits both `input` and `compositionupdate` events, // and we need to ignore the `input` event. if !text.is_empty() && !event.is_composing() { input.set_value(""); let event = egui::Event::Text(text); runner.input.raw.events.push(event); runner.needs_repaint.repaint_asap(); } } }; let on_composition_start = { let input = input.clone(); move |_: web_sys::CompositionEvent, runner: &mut AppRunner| { input.set_value(""); let event = egui::Event::Ime(egui::ImeEvent::Enabled); runner.input.raw.events.push(event); // Repaint moves the text agent into place, // see `move_to` in `AppRunner::handle_platform_output`. runner.needs_repaint.repaint_asap(); } }; let on_composition_update = { move |event: web_sys::CompositionEvent, runner: &mut AppRunner| { let Some(text) = event.data() else { return }; let event = egui::Event::Ime(egui::ImeEvent::Preedit(text)); runner.input.raw.events.push(event); runner.needs_repaint.repaint_asap(); } }; let on_composition_end = { let input = input.clone(); move |event: web_sys::CompositionEvent, runner: &mut AppRunner| { let Some(text) = event.data() else { return }; input.set_value(""); let event = egui::Event::Ime(egui::ImeEvent::Commit(text)); runner.input.raw.events.push(event); runner.needs_repaint.repaint_asap(); } }; runner_ref.add_event_listener(&input, "input", on_input)?; runner_ref.add_event_listener(&input, "compositionstart", on_composition_start)?; runner_ref.add_event_listener(&input, "compositionupdate", on_composition_update)?; runner_ref.add_event_listener(&input, "compositionend", on_composition_end)?; // The canvas doesn't get keydown/keyup events when the text agent is focused, // so we need to forward them to the runner: runner_ref.add_event_listener(&input, "keydown", super::events::on_keydown)?; runner_ref.add_event_listener(&input, "keyup", super::events::on_keyup)?; Ok(Self { input, prev_ime_output: Default::default(), }) } pub fn move_to( &self, ime: Option<egui::output::IMEOutput>, canvas: &web_sys::HtmlCanvasElement, zoom_factor: f32, ) -> Result<(), JsValue> { // Don't move the text agent unless the position actually changed: if self.prev_ime_output.get() == ime { return Ok(()); } self.prev_ime_output.set(ime); let Some(ime) = ime else { return Ok(()) }; let mut canvas_rect = super::canvas_content_rect(canvas); // Fix for safari with virtual keyboard flapping position if is_mobile_safari() { canvas_rect.min.y = canvas.offset_top() as f32; } let cursor_rect = ime.cursor_rect.translate(canvas_rect.min.to_vec2()); let style = self.input.style(); // This is where the IME input will point to: style.set_property( "left", &format!("{}px", cursor_rect.center().x * zoom_factor), )?; style.set_property( "top", &format!("{}px", cursor_rect.center().y * zoom_factor), )?; Ok(()) } pub fn set_focus(&self, on: bool) { if on { self.focus(); } else { self.blur(); } } pub fn has_focus(&self) -> bool { super::has_focus(&self.input) } pub fn focus(&self) { if self.has_focus() { return; } log::trace!("Focusing text agent"); if let Err(err) = self.input.focus() { log::error!("failed to set focus: {}", super::string_from_js_value(&err)); } } pub fn blur(&self) { if !self.has_focus() { return; } log::trace!("Blurring text agent"); if let Err(err) = self.input.blur() { log::error!("failed to set focus: {}", super::string_from_js_value(&err)); } } } impl Drop for TextAgent { fn drop(&mut self) { self.input.remove(); } } /// Returns `true` if the app is likely running on a mobile device on navigator Safari. fn is_mobile_safari() -> bool { (|| { let user_agent = web_sys::window()?.navigator().user_agent().ok()?; let is_ios = user_agent.contains("iPhone") || user_agent.contains("iPad") || user_agent.contains("iPod"); let is_safari = user_agent.contains("Safari"); Some(is_ios && is_safari) })() .unwrap_or(false) }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/eframe/src/web/web_runner.rs
crates/eframe/src/web/web_runner.rs
use std::{cell::RefCell, rc::Rc}; use wasm_bindgen::prelude::*; use crate::{App, epi}; use super::{ AppRunner, PanicHandler, events::{self, ResizeObserverContext}, text_agent::TextAgent, }; /// This is how `eframe` runs your web application /// /// This is cheap to clone. /// /// See [the crate level docs](crate) for an example. #[derive(Clone)] pub struct WebRunner { /// Have we ever panicked? panic_handler: PanicHandler, /// If we ever panic during running, this `RefCell` is poisoned. /// So before we use it, we need to check [`Self::panic_handler`]. app_runner: Rc<RefCell<Option<AppRunner>>>, /// In case of a panic, unsubscribe these. /// They have to be in a separate `Rc` so that we don't need to pass them to /// the panic handler, since they aren't `Send`. events_to_unsubscribe: Rc<RefCell<Vec<EventToUnsubscribe>>>, /// Current animation frame in flight. frame: Rc<RefCell<Option<AnimationFrameRequest>>>, resize_observer: Rc<RefCell<Option<ResizeObserverContext>>>, } impl WebRunner { /// Will install a panic handler that will catch and log any panics #[expect(clippy::new_without_default)] pub fn new() -> Self { let panic_handler = PanicHandler::install(); Self { panic_handler, app_runner: Rc::new(RefCell::new(None)), events_to_unsubscribe: Rc::new(RefCell::new(Default::default())), frame: Default::default(), resize_observer: Default::default(), } } /// Create the application, install callbacks, and start running the app. /// /// # Errors /// Failing to initialize graphics, or failure to create app. pub async fn start( &self, canvas: web_sys::HtmlCanvasElement, web_options: crate::WebOptions, app_creator: epi::AppCreator<'static>, ) -> Result<(), JsValue> { self.destroy(); { // Make sure the canvas can be given focus. // https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex canvas.set_tab_index(0); // Don't outline the canvas when it has focus: canvas.style().set_property("outline", "none")?; } { // First set up the app runner: let text_agent = TextAgent::attach(self, canvas.get_root_node())?; let app_runner = AppRunner::new(canvas.clone(), web_options, app_creator, text_agent).await?; self.app_runner.replace(Some(app_runner)); } { let resize_observer = events::ResizeObserverContext::new(self)?; // Properly size the canvas. Will also call `self.request_animation_frame()` (eventually) resize_observer.observe(&canvas); self.resize_observer.replace(Some(resize_observer)); } events::install_event_handlers(self)?; log::info!("event handlers installed."); Ok(()) } /// Has there been a panic? pub fn has_panicked(&self) -> bool { self.panic_handler.has_panicked() } /// What was the panic message and callstack? pub fn panic_summary(&self) -> Option<super::PanicSummary> { self.panic_handler.panic_summary() } fn unsubscribe_from_all_events(&self) { let events_to_unsubscribe: Vec<_> = std::mem::take(&mut *self.events_to_unsubscribe.borrow_mut()); if !events_to_unsubscribe.is_empty() { log::debug!("Unsubscribing from {} events", events_to_unsubscribe.len()); for x in events_to_unsubscribe { if let Err(err) = x.unsubscribe() { log::warn!( "Failed to unsubscribe from event: {}", super::string_from_js_value(&err) ); } } } self.resize_observer.replace(None); } /// Shut down eframe and clean up resources. pub fn destroy(&self) { self.unsubscribe_from_all_events(); if let Some(frame) = self.frame.take() { let window = web_sys::window().unwrap(); window.cancel_animation_frame(frame.id).ok(); } if let Some(runner) = self.app_runner.replace(None) { runner.destroy(); } } /// Returns `None` if there has been a panic, or if we have been destroyed. /// In that case, just return to JS. pub(crate) fn try_lock(&self) -> Option<std::cell::RefMut<'_, AppRunner>> { if self.panic_handler.has_panicked() { // Unsubscribe from all events so that we don't get any more callbacks // that will try to access the poisoned runner. self.unsubscribe_from_all_events(); None } else { let lock = self.app_runner.try_borrow_mut().ok()?; std::cell::RefMut::filter_map(lock, |lock| -> Option<&mut AppRunner> { lock.as_mut() }) .ok() } } /// Get mutable access to the concrete [`App`] we enclose. /// /// This will panic if your app does not implement [`App::as_any_mut`], /// and return `None` if this runner has panicked. pub fn app_mut<ConcreteApp: 'static + App>( &self, ) -> Option<std::cell::RefMut<'_, ConcreteApp>> { self.try_lock() .map(|lock| std::cell::RefMut::map(lock, |runner| runner.app_mut::<ConcreteApp>())) } /// Convenience function to reduce boilerplate and ensure that all event handlers /// are dealt with in the same way. /// /// All events added with this method will automatically be unsubscribed on panic, /// or when [`Self::destroy`] is called. pub fn add_event_listener<E: wasm_bindgen::JsCast>( &self, target: &web_sys::EventTarget, event_name: &'static str, mut closure: impl FnMut(E, &mut AppRunner) + 'static, ) -> Result<(), wasm_bindgen::JsValue> { let options = web_sys::AddEventListenerOptions::default(); self.add_event_listener_ex( target, event_name, &options, move |event, app_runner, _web_runner| closure(event, app_runner), ) } /// Convenience function to reduce boilerplate and ensure that all event handlers /// are dealt with in the same way. /// /// All events added with this method will automatically be unsubscribed on panic, /// or when [`Self::destroy`] is called. pub fn add_event_listener_ex<E: wasm_bindgen::JsCast>( &self, target: &web_sys::EventTarget, event_name: &'static str, options: &web_sys::AddEventListenerOptions, mut closure: impl FnMut(E, &mut AppRunner, &Self) + 'static, ) -> Result<(), wasm_bindgen::JsValue> { let web_runner = self.clone(); // Create a JS closure based on the FnMut provided let closure = Closure::wrap(Box::new(move |event: web_sys::Event| { // Only call the wrapped closure if the egui code has not panicked if let Some(mut runner_lock) = web_runner.try_lock() { // Cast the event to the expected event type let event = event.unchecked_into::<E>(); closure(event, &mut runner_lock, &web_runner); } }) as Box<dyn FnMut(web_sys::Event)>); // Add the event listener to the target target.add_event_listener_with_callback_and_add_event_listener_options( event_name, closure.as_ref().unchecked_ref(), options, )?; let handle = TargetEvent { target: target.clone(), event_name: event_name.to_owned(), closure, }; // Remember it so we unsubscribe on panic. // Otherwise we get calls into `self.runner` after it has been poisoned by a panic. self.events_to_unsubscribe .borrow_mut() .push(EventToUnsubscribe::TargetEvent(handle)); Ok(()) } /// Request an animation frame from the browser in which we can perform a paint. /// /// It is safe to call `request_animation_frame` multiple times in quick succession, /// this function guarantees that only one animation frame is scheduled at a time. pub(crate) fn request_animation_frame(&self) -> Result<(), wasm_bindgen::JsValue> { if self.frame.borrow().is_some() { // there is already an animation frame in flight return Ok(()); } let window = web_sys::window().unwrap(); let closure = Closure::once({ let web_runner = self.clone(); move || { // We can paint now, so clear the animation frame. // This drops the `closure` and allows another // animation frame to be scheduled let _ = web_runner.frame.take(); events::paint_and_schedule(&web_runner) } }); let id = window.request_animation_frame(closure.as_ref().unchecked_ref())?; self.frame.borrow_mut().replace(AnimationFrameRequest { id, _closure: closure, }); Ok(()) } } // ---------------------------------------------------------------------------- // https://rustwasm.github.io/wasm-bindgen/api/wasm_bindgen/closure/struct.Closure.html#using-fnonce-and-closureonce-with-requestanimationframe struct AnimationFrameRequest { /// Represents the ID of a frame in flight. id: i32, /// The callback given to `request_animation_frame`, stored here both to prevent it /// from being canceled, and from having to `.forget()` it. _closure: Closure<dyn FnMut() -> Result<(), JsValue>>, } struct TargetEvent { target: web_sys::EventTarget, event_name: String, closure: Closure<dyn FnMut(web_sys::Event)>, } #[expect(unused)] struct IntervalHandle { handle: i32, closure: Closure<dyn FnMut()>, } enum EventToUnsubscribe { TargetEvent(TargetEvent), #[expect(unused)] IntervalHandle(IntervalHandle), } impl EventToUnsubscribe { pub fn unsubscribe(self) -> Result<(), JsValue> { match self { Self::TargetEvent(handle) => { handle.target.remove_event_listener_with_callback( handle.event_name.as_str(), handle.closure.as_ref().unchecked_ref(), )?; Ok(()) } Self::IntervalHandle(handle) => { let window = web_sys::window().unwrap(); window.clear_interval_with_handle(handle.handle); Ok(()) } } } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/eframe/src/web/web_logger.rs
crates/eframe/src/web/web_logger.rs
/// Implements [`log::Log`] to log messages to `console.log`, `console.warn`, etc. pub struct WebLogger { filter: log::LevelFilter, } impl WebLogger { /// Install a new `WebLogger`, piping all [`log`] events to the web console. pub fn init(filter: log::LevelFilter) -> Result<(), log::SetLoggerError> { log::set_max_level(filter); log::set_boxed_logger(Box::new(Self::new(filter))) } /// Create a new [`WebLogger`] with the given filter, /// but don't install it. pub fn new(filter: log::LevelFilter) -> Self { Self { filter } } } impl log::Log for WebLogger { fn enabled(&self, metadata: &log::Metadata<'_>) -> bool { /// Never log anything less serious than a `INFO` from these crates. const CRATES_AT_INFO_LEVEL: &[&str] = &[ // wgpu crates spam a lot on debug level, which is really annoying "naga", "wgpu_core", "wgpu_hal", ]; if CRATES_AT_INFO_LEVEL .iter() .any(|crate_name| metadata.target().starts_with(crate_name)) { return metadata.level() <= log::LevelFilter::Info; } metadata.level() <= self.filter } fn log(&self, record: &log::Record<'_>) { #![expect(clippy::match_same_arms)] if !self.enabled(record.metadata()) { return; } let msg = if let (Some(file), Some(line)) = (record.file(), record.line()) { let file = shorten_file_path(file); format!("[{}] {file}:{line}: {}", record.target(), record.args()) } else { format!("[{}] {}", record.target(), record.args()) }; match record.level() { // NOTE: the `console::trace` includes a stack trace, which is super-noisy. log::Level::Trace => console::debug(&msg), log::Level::Debug => console::debug(&msg), log::Level::Info => console::info(&msg), log::Level::Warn => console::warn(&msg), // Using console.error causes crashes for unknown reason // https://github.com/emilk/egui/pull/2961 // log::Level::Error => console::error(&msg), log::Level::Error => console::warn(&format!("ERROR: {msg}")), } } fn flush(&self) {} } /// js-bindings for console.log, console.warn, etc mod console { use wasm_bindgen::prelude::*; #[wasm_bindgen] extern "C" { /// `console.trace` #[wasm_bindgen(js_namespace = console)] pub fn trace(s: &str); /// `console.debug` #[wasm_bindgen(js_namespace = console)] pub fn debug(s: &str); /// `console.info` #[wasm_bindgen(js_namespace = console)] pub fn info(s: &str); /// `console.warn` #[wasm_bindgen(js_namespace = console)] pub fn warn(s: &str); // Using console.error causes crashes for unknown reason // https://github.com/emilk/egui/pull/2961 // /// `console.error` // #[wasm_bindgen(js_namespace = console)] // pub fn error(s: &str); } } /// Shorten a path to a Rust source file. /// /// Example input: /// * `/Users/emilk/.cargo/registry/src/github.com-1ecc6299db9ec823/tokio-1.24.1/src/runtime/runtime.rs` /// * `crates/rerun/src/main.rs` /// * `/rustc/d5a82bbd26e1ad8b7401f6a718a9c57c96905483/library/core/src/ops/function.rs` /// /// Example output: /// * `tokio-1.24.1/src/runtime/runtime.rs` /// * `rerun/src/main.rs` /// * `core/src/ops/function.rs` #[allow(clippy::allow_attributes, dead_code)] // only used on web and in tests fn shorten_file_path(file_path: &str) -> &str { if let Some(i) = file_path.rfind("/src/") { if let Some(prev_slash) = file_path[..i].rfind('/') { &file_path[prev_slash + 1..] } else { file_path } } else { file_path } } #[test] fn test_shorten_file_path() { for (before, after) in [ ( "/Users/emilk/.cargo/registry/src/github.com-1ecc6299db9ec823/tokio-1.24.1/src/runtime/runtime.rs", "tokio-1.24.1/src/runtime/runtime.rs", ), ("crates/rerun/src/main.rs", "rerun/src/main.rs"), ( "/rustc/d5a82bbd26e1ad8b7401f6a718a9c57c96905483/library/core/src/ops/function.rs", "core/src/ops/function.rs", ), ("/weird/path/file.rs", "/weird/path/file.rs"), ] { assert_eq!(shorten_file_path(before), after); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/eframe/src/web/input.rs
crates/eframe/src/web/input.rs
use super::{AppRunner, canvas_content_rect}; pub fn pos_from_mouse_event( canvas: &web_sys::HtmlCanvasElement, event: &web_sys::MouseEvent, ctx: &egui::Context, ) -> egui::Pos2 { let rect = canvas_content_rect(canvas); let zoom_factor = ctx.zoom_factor(); egui::Pos2 { x: (event.client_x() as f32 - rect.left()) / zoom_factor, y: (event.client_y() as f32 - rect.top()) / zoom_factor, } } pub fn button_from_mouse_event(event: &web_sys::MouseEvent) -> Option<egui::PointerButton> { match event.button() { 0 => Some(egui::PointerButton::Primary), 1 => Some(egui::PointerButton::Middle), 2 => Some(egui::PointerButton::Secondary), 3 => Some(egui::PointerButton::Extra1), 4 => Some(egui::PointerButton::Extra2), _ => None, } } /// A single touch is translated to a pointer movement. When a second touch is added, the pointer /// should not jump to a different position. Therefore, we do not calculate the average position /// of all touches, but we keep using the same touch as long as it is available. pub fn primary_touch_pos( runner: &mut AppRunner, event: &web_sys::TouchEvent, ) -> Option<(egui::Pos2, web_sys::Touch)> { let all_touches: Vec<_> = (0..event.touches().length()) .filter_map(|i| event.touches().get(i)) // On touchend we don't get anything in `touches`, but we still get `changed_touches`, so include those: .chain((0..event.changed_touches().length()).filter_map(|i| event.changed_touches().get(i))) .collect(); if let Some(primary_touch) = runner.input.primary_touch { // Is the primary touch is gone? if !all_touches .iter() .any(|touch| primary_touch == egui::TouchId::from(touch.identifier())) { runner.input.primary_touch = None; } } if runner.input.primary_touch.is_none() { runner.input.primary_touch = all_touches .first() .map(|touch| egui::TouchId::from(touch.identifier())); } let primary_touch = runner.input.primary_touch; if let Some(primary_touch) = primary_touch { for touch in all_touches { if primary_touch == egui::TouchId::from(touch.identifier()) { let canvas_rect = canvas_content_rect(runner.canvas()); return Some(( pos_from_touch(canvas_rect, &touch, runner.egui_ctx()), touch, )); } } } None } fn pos_from_touch( canvas_rect: egui::Rect, touch: &web_sys::Touch, egui_ctx: &egui::Context, ) -> egui::Pos2 { let zoom_factor = egui_ctx.zoom_factor(); egui::Pos2 { x: (touch.client_x() as f32 - canvas_rect.left()) / zoom_factor, y: (touch.client_y() as f32 - canvas_rect.top()) / zoom_factor, } } pub fn push_touches(runner: &mut AppRunner, phase: egui::TouchPhase, event: &web_sys::TouchEvent) { let canvas_rect = canvas_content_rect(runner.canvas()); for touch_idx in 0..event.changed_touches().length() { if let Some(touch) = event.changed_touches().item(touch_idx) { runner.input.raw.events.push(egui::Event::Touch { device_id: egui::TouchDeviceId(0), id: egui::TouchId::from(touch.identifier()), phase, pos: pos_from_touch(canvas_rect, &touch, runner.egui_ctx()), force: Some(touch.force()), }); } } } /// The text input from a keyboard event (e.g. `X` when pressing the `X` key). pub fn text_from_keyboard_event(event: &web_sys::KeyboardEvent) -> Option<String> { let key = event.key(); let is_function_key = key.starts_with('F') && key.len() > 1; if is_function_key { return None; } let is_control_key = matches!( key.as_str(), "Alt" | "ArrowDown" | "ArrowLeft" | "ArrowRight" | "ArrowUp" | "Backspace" | "CapsLock" | "ContextMenu" | "Control" | "Delete" | "End" | "Enter" | "Esc" | "Escape" | "GroupNext" // https://github.com/emilk/egui/issues/510 | "Help" | "Home" | "Insert" | "Meta" | "NumLock" | "PageDown" | "PageUp" | "Pause" | "ScrollLock" | "Shift" | "Tab" ); if is_control_key { return None; } Some(key) } /// Web sends all keys as strings, so it is up to us to figure out if it is /// a real text input or the name of a key. pub fn translate_key(key: &str) -> Option<egui::Key> { egui::Key::from_name(key) } pub fn modifiers_from_kb_event(event: &web_sys::KeyboardEvent) -> egui::Modifiers { egui::Modifiers { alt: event.alt_key(), ctrl: event.ctrl_key(), shift: event.shift_key(), // Ideally we should know if we are running or mac or not, // but this works good enough for now. mac_cmd: event.meta_key(), // Ideally we should know if we are running or mac or not, // but this works good enough for now. command: event.ctrl_key() || event.meta_key(), } } pub fn modifiers_from_mouse_event(event: &web_sys::MouseEvent) -> egui::Modifiers { egui::Modifiers { alt: event.alt_key(), ctrl: event.ctrl_key(), shift: event.shift_key(), // Ideally we should know if we are running or mac or not, // but this works good enough for now. mac_cmd: event.meta_key(), // Ideally we should know if we are running or mac or not, // but this works good enough for now. command: event.ctrl_key() || event.meta_key(), } } pub fn modifiers_from_wheel_event(event: &web_sys::WheelEvent) -> egui::Modifiers { egui::Modifiers { alt: event.alt_key(), ctrl: event.ctrl_key(), shift: event.shift_key(), // Ideally we should know if we are running or mac or not, // but this works good enough for now. mac_cmd: event.meta_key(), // Ideally we should know if we are running or mac or not, // but this works good enough for now. command: event.ctrl_key() || event.meta_key(), } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/eframe/src/web/screen_reader.rs
crates/eframe/src/web/screen_reader.rs
/// Speak the given text out loud. pub fn speak(text: &str) { if text.is_empty() { return; } if let Some(window) = web_sys::window() { log::debug!("Speaking {text:?}"); if let Ok(speech_synthesis) = window.speech_synthesis() { speech_synthesis.cancel(); // interrupt previous speech, if any if let Ok(utterance) = web_sys::SpeechSynthesisUtterance::new_with_text(text) { utterance.set_rate(1.0); utterance.set_pitch(1.0); utterance.set_volume(1.0); speech_synthesis.speak(&utterance); } } } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/viewport.rs
crates/egui/src/viewport.rs
//! egui supports multiple viewports, corresponding to multiple native windows. //! //! Not all egui backends support multiple viewports, but `eframe` native does //! (but not on web). //! //! You can spawn a new viewport using [`Context::show_viewport_deferred`] and [`Context::show_viewport_immediate`]. //! These needs to be called every frame the viewport should be visible. //! //! This is implemented by the native `eframe` backend, but not the web one. //! //! ## Viewport classes //! The viewports form a tree of parent-child relationships. //! //! There are different classes of viewports. //! //! ### Root viewport //! The root viewport is the original viewport, and cannot be closed without closing the application. //! //! ### Deferred viewports //! These are created with [`Context::show_viewport_deferred`]. //! Deferred viewports take a closure that is called by the integration at a later time, perhaps multiple times. //! Deferred viewports are repainted independently of the parent viewport. //! This means communication with them needs to be done via channels, or `Arc/Mutex`. //! //! This is the most performant type of child viewport, though a bit more cumbersome to work with compared to immediate viewports. //! //! ### Immediate viewports //! These are created with [`Context::show_viewport_immediate`]. //! Immediate viewports take a `FnOnce` closure, similar to other egui functions, and is called immediately. //! This makes communication with them much simpler than with deferred viewports, but this simplicity comes at a cost: whenever the parent viewports needs to be repainted, so will the child viewport, and vice versa. //! This means that if you have `N` viewports you are potentially doing `N` times as much CPU work. However, if all your viewports are showing animations, and thus are repainting constantly anyway, this doesn't matter. //! //! In short: immediate viewports are simpler to use, but can waste a lot of CPU time. //! //! ### Embedded viewports //! These are not real, independent viewports, but is a fallback mode for when the integration does not support real viewports. //! In your callback is called with [`ViewportClass::EmbeddedWindow`] it means the viewport is embedded inside of //! a regular [`crate::Window`], trapped in the parent viewport. //! //! //! ## Using the viewports //! Only one viewport is active at any one time, identified with [`Context::viewport_id`]. //! You can modify the current (change the title, resize the window, etc) by sending //! a [`ViewportCommand`] to it using [`Context::send_viewport_cmd`]. //! You can interact with other viewports using [`Context::send_viewport_cmd_to`]. //! //! There is an example in <https://github.com/emilk/egui/tree/main/examples/multiple_viewports/src/main.rs>. //! //! You can find all available viewports in [`crate::RawInput::viewports`] and the active viewport in //! [`crate::InputState::viewport`]: //! //! ```no_run //! # let ctx = &egui::Context::default(); //! ctx.input(|i| { //! dbg!(&i.viewport()); // Current viewport //! dbg!(&i.raw.viewports); // All viewports //! }); //! ``` //! //! ## For integrations //! * There is a [`crate::InputState::viewport`] with information about the current viewport. //! * There is a [`crate::RawInput::viewports`] with information about all viewports. //! * The repaint callback set by [`Context::set_request_repaint_callback`] points to which viewport should be repainted. //! * [`crate::FullOutput::viewport_output`] is a list of viewports which should result in their own independent windows. //! * To support immediate viewports you need to call [`Context::set_immediate_viewport_renderer`]. //! * If you support viewports, you need to call [`Context::set_embed_viewports`] with `false`, or all new viewports will be embedded (the default behavior). //! //! ## Future work //! There are several more things related to viewports that we want to add. //! Read more at <https://github.com/emilk/egui/issues/3556>. use std::sync::Arc; use epaint::{Pos2, Vec2}; use crate::{Context, Id, Ui}; // ---------------------------------------------------------------------------- /// The different types of viewports supported by egui. #[derive(Clone, Copy, Default, Hash, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub enum ViewportClass { /// The root viewport; i.e. the original window. #[default] Root, /// A viewport run independently from the parent viewport. /// /// This is the preferred type of viewport from a performance perspective. /// /// Create these with [`crate::Context::show_viewport_deferred`]. Deferred, /// A viewport run inside the parent viewport. /// /// This is the easier type of viewport to use, but it is less performant /// at it requires both parent and child to repaint if any one of them needs repainting, /// which effectively produces double work for two viewports, and triple work for three viewports, etc. /// /// Create these with [`crate::Context::show_viewport_immediate`]. Immediate, /// The fallback, when the egui integration doesn't support viewports, /// or [`crate::Context::embed_viewports`] is set to `true`. /// /// If you get this, it is because you are already wrapped in a [`crate::Window`] /// inside of the parent viewport. EmbeddedWindow, } // ---------------------------------------------------------------------------- /// A unique identifier of a viewport. /// /// This is returned by [`Context::viewport_id`] and [`Context::parent_viewport_id`]. #[derive(Clone, Copy, Hash, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct ViewportId(pub Id); // We implement `PartialOrd` and `Ord` so we can use `ViewportId` in a `BTreeMap`, // which allows predicatable iteration order, frame-to-frame. impl PartialOrd for ViewportId { fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { Some(self.cmp(other)) } } impl Ord for ViewportId { fn cmp(&self, other: &Self) -> std::cmp::Ordering { self.0.value().cmp(&other.0.value()) } } impl Default for ViewportId { #[inline] fn default() -> Self { Self::ROOT } } impl std::fmt::Debug for ViewportId { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.0.short_debug_format().fmt(f) } } impl ViewportId { /// The `ViewportId` of the root viewport. pub const ROOT: Self = Self(Id::NULL); #[inline] pub fn from_hash_of(source: impl std::hash::Hash) -> Self { Self(Id::new(source)) } } impl From<ViewportId> for Id { #[inline] fn from(id: ViewportId) -> Self { id.0 } } impl nohash_hasher::IsEnabled for ViewportId {} /// A fast hash set of [`ViewportId`]. pub type ViewportIdSet = nohash_hasher::IntSet<ViewportId>; /// A fast hash map from [`ViewportId`] to `T`. pub type ViewportIdMap<T> = nohash_hasher::IntMap<ViewportId, T>; /// An order map from [`ViewportId`] to `T`. pub type OrderedViewportIdMap<T> = std::collections::BTreeMap<ViewportId, T>; // ---------------------------------------------------------------------------- /// Image data for an application icon. /// /// Use a square image, e.g. 256x256 pixels. /// You can use a transparent background. #[derive(Clone, Default, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct IconData { /// RGBA pixels, with separate/unmultiplied alpha. pub rgba: Vec<u8>, /// Image width. This should be a multiple of 4. pub width: u32, /// Image height. This should be a multiple of 4. pub height: u32, } impl IconData { #[inline] pub fn is_empty(&self) -> bool { self.rgba.is_empty() } } impl std::fmt::Debug for IconData { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("IconData") .field("width", &self.width) .field("height", &self.height) .finish_non_exhaustive() } } impl From<IconData> for epaint::ColorImage { fn from(icon: IconData) -> Self { profiling::function_scope!(); let IconData { rgba, width, height, } = icon; Self::from_rgba_premultiplied([width as usize, height as usize], &rgba) } } impl From<&IconData> for epaint::ColorImage { fn from(icon: &IconData) -> Self { profiling::function_scope!(); let IconData { rgba, width, height, } = icon; Self::from_rgba_premultiplied([*width as usize, *height as usize], rgba) } } // ---------------------------------------------------------------------------- /// A pair of [`ViewportId`], used to identify a viewport and its parent. #[derive(Debug, Hash, Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct ViewportIdPair { pub this: ViewportId, pub parent: ViewportId, } impl Default for ViewportIdPair { #[inline] fn default() -> Self { Self::ROOT } } impl ViewportIdPair { /// The `ViewportIdPair` of the root viewport, which is its own parent. pub const ROOT: Self = Self { this: ViewportId::ROOT, parent: ViewportId::ROOT, }; #[inline] pub fn from_self_and_parent(this: ViewportId, parent: ViewportId) -> Self { Self { this, parent } } } /// The user-code that shows the ui in the viewport, used for deferred viewports. pub type DeferredViewportUiCallback = dyn Fn(&mut Ui) + Sync + Send; /// Render the given viewport, calling the given ui callback. pub type ImmediateViewportRendererCallback = dyn for<'a> Fn(&Context, ImmediateViewport<'a>); /// Control the building of a new egui viewport (i.e. native window). /// /// See [`crate::viewport`] for how to build new viewports (native windows). /// /// The fields are public, but you should use the builder pattern to set them, /// and that's where you'll find the documentation too. /// /// Since egui is immediate mode, `ViewportBuilder` is accumulative in nature. /// Setting any option to `None` means "keep the current value", /// or "Use the default" if it is the first call. /// /// The default values are implementation defined, so you may want to explicitly /// configure the size of the window, and what buttons are shown. #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct ViewportBuilder { /// The title of the viewport. /// `eframe` will use this as the title of the native window. pub title: Option<String>, /// This is wayland only. See [`Self::with_app_id`]. pub app_id: Option<String>, /// The desired outer position of the window. pub position: Option<Pos2>, pub inner_size: Option<Vec2>, pub min_inner_size: Option<Vec2>, pub max_inner_size: Option<Vec2>, /// Whether clamp the window's size to monitor's size. The default is `true` on linux, otherwise it is `false`. /// /// Note: On some Linux systems, a window size larger than the monitor causes crashes pub clamp_size_to_monitor_size: Option<bool>, pub fullscreen: Option<bool>, pub maximized: Option<bool>, pub resizable: Option<bool>, pub transparent: Option<bool>, pub decorations: Option<bool>, pub icon: Option<Arc<IconData>>, pub active: Option<bool>, pub visible: Option<bool>, // macOS: pub fullsize_content_view: Option<bool>, pub movable_by_window_background: Option<bool>, pub title_shown: Option<bool>, pub titlebar_buttons_shown: Option<bool>, pub titlebar_shown: Option<bool>, pub has_shadow: Option<bool>, // windows: pub drag_and_drop: Option<bool>, pub taskbar: Option<bool>, pub close_button: Option<bool>, pub minimize_button: Option<bool>, pub maximize_button: Option<bool>, pub window_level: Option<WindowLevel>, pub mouse_passthrough: Option<bool>, // X11 pub window_type: Option<X11WindowType>, } impl ViewportBuilder { /// Sets the initial title of the window in the title bar. /// /// Look at winit for more details #[inline] pub fn with_title(mut self, title: impl Into<String>) -> Self { self.title = Some(title.into()); self } /// Sets whether the window should have a border, a title bar, etc. /// /// The default is `true`. /// /// Look at winit for more details #[inline] pub fn with_decorations(mut self, decorations: bool) -> Self { self.decorations = Some(decorations); self } /// Sets whether the window should be put into fullscreen upon creation. /// /// The default is `None`. /// /// Look at winit for more details /// This will use borderless #[inline] pub fn with_fullscreen(mut self, fullscreen: bool) -> Self { self.fullscreen = Some(fullscreen); self } /// Request that the window is maximized upon creation. /// /// The default is `false`. /// /// Look at winit for more details #[inline] pub fn with_maximized(mut self, maximized: bool) -> Self { self.maximized = Some(maximized); self } /// Sets whether the window is resizable or not. /// /// The default is `true`. /// /// Look at winit for more details #[inline] pub fn with_resizable(mut self, resizable: bool) -> Self { self.resizable = Some(resizable); self } /// Sets whether the background of the window should be transparent. /// /// You should avoid having a [`crate::CentralPanel`], or make sure its frame is also transparent. /// /// In `eframe` you control the transparency with `eframe::App::clear_color()`. /// /// If this is `true`, writing colors with alpha values different than /// `1.0` will produce a transparent window. On some platforms this /// is more of a hint for the system and you'd still have the alpha /// buffer. /// /// The default is `false`. /// If this is not working, it's because the graphic context doesn't support transparency, /// you will need to set the transparency in the eframe! /// /// ## Platform-specific /// /// **macOS:** When using this feature to create an overlay-like UI, you likely want to combine this with [`Self::with_has_shadow`] set to `false` in order to avoid ghosting artifacts. #[inline] pub fn with_transparent(mut self, transparent: bool) -> Self { self.transparent = Some(transparent); self } /// The application icon, e.g. in the Windows task bar or the alt-tab menu. /// /// The default icon is a white `e` on a black background (for "egui" or "eframe"). /// If you prefer the OS default, set this to `IconData::default()`. #[inline] pub fn with_icon(mut self, icon: impl Into<Arc<IconData>>) -> Self { self.icon = Some(icon.into()); self } /// Whether the window will be initially focused or not. /// /// The window should be assumed as not focused by default /// /// ## Platform-specific: /// /// **Android / iOS / X11 / Wayland / Orbital:** Unsupported. /// /// Look at winit for more details #[inline] pub fn with_active(mut self, active: bool) -> Self { self.active = Some(active); self } /// Sets whether the window will be initially visible or hidden. /// /// The default is to show the window. /// /// Look at winit for more details #[inline] pub fn with_visible(mut self, visible: bool) -> Self { self.visible = Some(visible); self } /// macOS: Makes the window content appear behind the titlebar. /// /// You often want to combine this with [`Self::with_titlebar_shown`] /// and [`Self::with_title_shown`]. #[inline] pub fn with_fullsize_content_view(mut self, value: bool) -> Self { self.fullsize_content_view = Some(value); self } /// macOS: Set to `true` to allow the window to be moved by dragging the background. /// Enabling this feature can result in unexpected behavior with draggable UI widgets such as sliders. #[inline] pub fn with_movable_by_background(mut self, value: bool) -> Self { self.movable_by_window_background = Some(value); self } /// macOS: Set to `false` to hide the window title. #[inline] pub fn with_title_shown(mut self, title_shown: bool) -> Self { self.title_shown = Some(title_shown); self } /// macOS: Set to `false` to hide the titlebar button (close, minimize, maximize) #[inline] pub fn with_titlebar_buttons_shown(mut self, titlebar_buttons_shown: bool) -> Self { self.titlebar_buttons_shown = Some(titlebar_buttons_shown); self } /// macOS: Set to `false` to make the titlebar transparent, allowing the content to appear behind it. #[inline] pub fn with_titlebar_shown(mut self, shown: bool) -> Self { self.titlebar_shown = Some(shown); self } /// macOS: Set to `false` to make the window render without a drop shadow. /// /// The default is `true`. /// /// Disabling this feature can solve ghosting issues experienced if using [`Self::with_transparent`]. /// /// Look at winit for more details #[inline] pub fn with_has_shadow(mut self, has_shadow: bool) -> Self { self.has_shadow = Some(has_shadow); self } /// windows: Whether show or hide the window icon in the taskbar. #[inline] pub fn with_taskbar(mut self, show: bool) -> Self { self.taskbar = Some(show); self } /// Requests the window to be of specific dimensions. /// /// If this is not set, some platform-specific dimensions will be used. /// /// Should be bigger than 0 /// Look at winit for more details #[inline] pub fn with_inner_size(mut self, size: impl Into<Vec2>) -> Self { self.inner_size = Some(size.into()); self } /// Sets the minimum dimensions a window can have. /// /// If this is not set, the window will have no minimum dimensions (aside /// from reserved). /// /// Should be bigger than 0 /// Look at winit for more details #[inline] pub fn with_min_inner_size(mut self, size: impl Into<Vec2>) -> Self { self.min_inner_size = Some(size.into()); self } /// Sets the maximum dimensions a window can have. /// /// If this is not set, the window will have no maximum or will be set to /// the primary monitor's dimensions by the platform. /// /// Should be bigger than 0 /// Look at winit for more details #[inline] pub fn with_max_inner_size(mut self, size: impl Into<Vec2>) -> Self { self.max_inner_size = Some(size.into()); self } /// Sets whether clamp the window's size to monitor's size. The default is `true` on linux, otherwise it is `false`. /// /// Note: On some Linux systems, a window size larger than the monitor causes crashes #[inline] pub fn with_clamp_size_to_monitor_size(mut self, value: bool) -> Self { self.clamp_size_to_monitor_size = Some(value); self } /// Does not work on X11. #[inline] pub fn with_close_button(mut self, value: bool) -> Self { self.close_button = Some(value); self } /// Does not work on X11. #[inline] pub fn with_minimize_button(mut self, value: bool) -> Self { self.minimize_button = Some(value); self } /// Does not work on X11. #[inline] pub fn with_maximize_button(mut self, value: bool) -> Self { self.maximize_button = Some(value); self } /// On Windows: enable drag and drop support. Drag and drop can /// not be disabled on other platforms. /// /// See [winit's documentation][drag_and_drop] for information on why you /// might want to disable this on windows. /// /// [drag_and_drop]: https://docs.rs/winit/latest/x86_64-pc-windows-msvc/winit/platform/windows/trait.WindowAttributesExtWindows.html#tymethod.with_drag_and_drop #[inline] pub fn with_drag_and_drop(mut self, value: bool) -> Self { self.drag_and_drop = Some(value); self } /// The initial "outer" position of the window, /// i.e. where the top-left corner of the frame/chrome should be. /// /// **`eframe` notes**: /// /// - **iOS:** Sets the top left coordinates of the window in the screen space coordinate system. /// - **Web:** Sets the top-left coordinates relative to the viewport. Doesn't account for CSS /// [`transform`]. /// - **Android / Wayland:** Unsupported. /// /// [`transform`]: https://developer.mozilla.org/en-US/docs/Web/CSS/transform #[inline] pub fn with_position(mut self, pos: impl Into<Pos2>) -> Self { self.position = Some(pos.into()); self } /// ### On Wayland /// On Wayland this sets the Application ID for the window. /// /// The application ID is used in several places of the compositor, e.g. for /// grouping windows of the same application. It is also important for /// connecting the configuration of a `.desktop` file with the window, by /// using the application ID as file name. This allows e.g. a proper icon /// handling under Wayland. /// /// See [Waylands XDG shell documentation][xdg-shell] for more information /// on this Wayland-specific option. /// /// The `app_id` should match the `.desktop` file distributed with your program. /// /// For details about application ID conventions, see the /// [Desktop Entry Spec](https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html#desktop-file-id) /// /// [xdg-shell]: https://wayland.app/protocols/xdg-shell#xdg_toplevel:request:set_app_id /// /// ### eframe /// On eframe, the `app_id` of the root window is also used to determine /// the storage location of persistence files. #[inline] pub fn with_app_id(mut self, app_id: impl Into<String>) -> Self { self.app_id = Some(app_id.into()); self } /// Control if window is always-on-top, always-on-bottom, or neither. /// /// For platform compatibility see [`crate::viewport::WindowLevel`] documentation #[inline] pub fn with_window_level(mut self, level: WindowLevel) -> Self { self.window_level = Some(level); self } /// This window is always on top /// /// For platform compatibility see [`crate::viewport::WindowLevel`] documentation #[inline] pub fn with_always_on_top(self) -> Self { self.with_window_level(WindowLevel::AlwaysOnTop) } /// On desktop: mouse clicks pass through the window, used for non-interactable overlays. /// /// Generally you would use this in conjunction with [`Self::with_transparent`] /// and [`Self::with_always_on_top`]. #[inline] pub fn with_mouse_passthrough(mut self, value: bool) -> Self { self.mouse_passthrough = Some(value); self } /// ### On X11 /// This sets the window type. /// Maps directly to [`_NET_WM_WINDOW_TYPE`](https://specifications.freedesktop.org/wm-spec/wm-spec-1.5.html). #[inline] pub fn with_window_type(mut self, value: X11WindowType) -> Self { self.window_type = Some(value); self } /// Update this `ViewportBuilder` with a delta, /// returning a list of commands and a bool indicating if the window needs to be recreated. #[must_use] pub fn patch(&mut self, new_vp_builder: Self) -> (Vec<ViewportCommand>, bool) { #![expect(clippy::useless_let_if_seq)] // False positive let Self { title: new_title, app_id: new_app_id, position: new_position, inner_size: new_inner_size, min_inner_size: new_min_inner_size, max_inner_size: new_max_inner_size, clamp_size_to_monitor_size: new_clamp_size_to_monitor_size, fullscreen: new_fullscreen, maximized: new_maximized, resizable: new_resizable, transparent: new_transparent, decorations: new_decorations, icon: new_icon, active: new_active, visible: new_visible, drag_and_drop: new_drag_and_drop, fullsize_content_view: new_fullsize_content_view, movable_by_window_background: new_movable_by_window_background, title_shown: new_title_shown, titlebar_buttons_shown: new_titlebar_buttons_shown, titlebar_shown: new_titlebar_shown, has_shadow: new_has_shadow, close_button: new_close_button, minimize_button: new_minimize_button, maximize_button: new_maximize_button, window_level: new_window_level, mouse_passthrough: new_mouse_passthrough, taskbar: new_taskbar, window_type: new_window_type, } = new_vp_builder; let mut commands = Vec::new(); if let Some(new_title) = new_title && Some(&new_title) != self.title.as_ref() { self.title = Some(new_title.clone()); commands.push(ViewportCommand::Title(new_title)); } if let Some(new_position) = new_position && Some(new_position) != self.position { self.position = Some(new_position); commands.push(ViewportCommand::OuterPosition(new_position)); } if let Some(new_inner_size) = new_inner_size && Some(new_inner_size) != self.inner_size { self.inner_size = Some(new_inner_size); commands.push(ViewportCommand::InnerSize(new_inner_size)); } if let Some(new_min_inner_size) = new_min_inner_size && Some(new_min_inner_size) != self.min_inner_size { self.min_inner_size = Some(new_min_inner_size); commands.push(ViewportCommand::MinInnerSize(new_min_inner_size)); } if let Some(new_max_inner_size) = new_max_inner_size && Some(new_max_inner_size) != self.max_inner_size { self.max_inner_size = Some(new_max_inner_size); commands.push(ViewportCommand::MaxInnerSize(new_max_inner_size)); } if let Some(new_fullscreen) = new_fullscreen && Some(new_fullscreen) != self.fullscreen { self.fullscreen = Some(new_fullscreen); commands.push(ViewportCommand::Fullscreen(new_fullscreen)); } if let Some(new_maximized) = new_maximized && Some(new_maximized) != self.maximized { self.maximized = Some(new_maximized); commands.push(ViewportCommand::Maximized(new_maximized)); } if let Some(new_resizable) = new_resizable && Some(new_resizable) != self.resizable { self.resizable = Some(new_resizable); commands.push(ViewportCommand::Resizable(new_resizable)); } if let Some(new_transparent) = new_transparent && Some(new_transparent) != self.transparent { self.transparent = Some(new_transparent); commands.push(ViewportCommand::Transparent(new_transparent)); } if let Some(new_decorations) = new_decorations && Some(new_decorations) != self.decorations { self.decorations = Some(new_decorations); commands.push(ViewportCommand::Decorations(new_decorations)); } if let Some(new_icon) = new_icon { let is_new = match &self.icon { Some(existing) => !Arc::ptr_eq(&new_icon, existing), None => true, }; if is_new { commands.push(ViewportCommand::Icon(Some(Arc::clone(&new_icon)))); self.icon = Some(new_icon); } } if let Some(new_visible) = new_visible && Some(new_visible) != self.visible { self.visible = Some(new_visible); commands.push(ViewportCommand::Visible(new_visible)); } if let Some(new_mouse_passthrough) = new_mouse_passthrough && Some(new_mouse_passthrough) != self.mouse_passthrough { self.mouse_passthrough = Some(new_mouse_passthrough); commands.push(ViewportCommand::MousePassthrough(new_mouse_passthrough)); } if let Some(new_window_level) = new_window_level && Some(new_window_level) != self.window_level { self.window_level = Some(new_window_level); commands.push(ViewportCommand::WindowLevel(new_window_level)); } // -------------------------------------------------------------- // Things we don't have commands for require a full window recreation. // The reason we don't have commands for them is that `winit` doesn't support // changing them without recreating the window. let mut recreate_window = false; if new_clamp_size_to_monitor_size.is_some() && self.clamp_size_to_monitor_size != new_clamp_size_to_monitor_size { self.clamp_size_to_monitor_size = new_clamp_size_to_monitor_size; recreate_window = true; } if new_active.is_some() && self.active != new_active { self.active = new_active; recreate_window = true; } if new_app_id.is_some() && self.app_id != new_app_id { self.app_id = new_app_id; recreate_window = true; } if new_close_button.is_some() && self.close_button != new_close_button { self.close_button = new_close_button; recreate_window = true; } if new_minimize_button.is_some() && self.minimize_button != new_minimize_button { self.minimize_button = new_minimize_button; recreate_window = true; } if new_maximize_button.is_some() && self.maximize_button != new_maximize_button { self.maximize_button = new_maximize_button; recreate_window = true; } if new_title_shown.is_some() && self.title_shown != new_title_shown { self.title_shown = new_title_shown; recreate_window = true; } if new_titlebar_buttons_shown.is_some() && self.titlebar_buttons_shown != new_titlebar_buttons_shown { self.titlebar_buttons_shown = new_titlebar_buttons_shown; recreate_window = true; } if new_titlebar_shown.is_some() && self.titlebar_shown != new_titlebar_shown { self.titlebar_shown = new_titlebar_shown; recreate_window = true; } if new_has_shadow.is_some() && self.has_shadow != new_has_shadow { self.has_shadow = new_has_shadow; recreate_window = true; } if new_taskbar.is_some() && self.taskbar != new_taskbar { self.taskbar = new_taskbar; recreate_window = true; } if new_fullsize_content_view.is_some() && self.fullsize_content_view != new_fullsize_content_view { self.fullsize_content_view = new_fullsize_content_view; recreate_window = true; } if new_movable_by_window_background.is_some() && self.movable_by_window_background != new_movable_by_window_background { self.movable_by_window_background = new_movable_by_window_background; recreate_window = true; } if new_drag_and_drop.is_some() && self.drag_and_drop != new_drag_and_drop { self.drag_and_drop = new_drag_and_drop; recreate_window = true; } if new_window_type.is_some() && self.window_type != new_window_type { self.window_type = new_window_type; recreate_window = true; } (commands, recreate_window) } } /// For winit platform compatibility, see [`winit::WindowLevel` documentation](https://docs.rs/winit/latest/winit/window/enum.WindowLevel.html#platform-specific) #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
true
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/layers.rs
crates/egui/src/layers.rs
//! Handles paint layers, i.e. how things //! are sometimes painted behind or in front of other things. use crate::{Id, IdMap, Rect, ahash, epaint}; use epaint::{ClippedShape, Shape, emath::TSTransform}; /// Different layer categories #[derive(Clone, Copy, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub enum Order { /// Painted behind all floating windows Background, /// Normal moveable windows that you reorder by click Middle, /// Popups, menus etc that should always be painted on top of windows /// Foreground objects can also have tooltips Foreground, /// Things floating on top of everything else, like tooltips. /// You cannot interact with these. Tooltip, /// Debug layer, always painted last / on top Debug, } impl Order { const COUNT: usize = 5; const ALL: [Self; Self::COUNT] = [ Self::Background, Self::Middle, Self::Foreground, Self::Tooltip, Self::Debug, ]; pub const TOP: Self = Self::Debug; #[inline(always)] pub fn allow_interaction(&self) -> bool { match self { Self::Background | Self::Middle | Self::Foreground | Self::Tooltip | Self::Debug => { true } } } /// Short and readable summary pub fn short_debug_format(&self) -> &'static str { match self { Self::Background => "backg", Self::Middle => "middl", Self::Foreground => "foreg", Self::Tooltip => "toolt", Self::Debug => "debug", } } } /// An identifier for a paint layer. /// Also acts as an identifier for [`crate::Area`]:s. #[derive(Clone, Copy, Hash, Eq, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct LayerId { pub order: Order, pub id: Id, } impl LayerId { pub fn new(order: Order, id: Id) -> Self { Self { order, id } } pub fn debug() -> Self { Self { order: Order::Debug, id: Id::new("debug"), } } pub fn background() -> Self { Self { order: Order::Background, id: Id::new("background"), } } #[inline(always)] #[deprecated = "Use `Memory::allows_interaction` instead"] pub fn allow_interaction(&self) -> bool { self.order.allow_interaction() } /// Short and readable summary pub fn short_debug_format(&self) -> String { format!( "{} {}", self.order.short_debug_format(), self.id.short_debug_format() ) } } impl std::fmt::Debug for LayerId { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let Self { order, id } = self; write!(f, "LayerId {{ {order:?} {id:?} }}") } } /// A unique identifier of a specific [`Shape`] in a [`PaintList`]. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct ShapeIdx(pub usize); /// A list of [`Shape`]s paired with a clip rectangle. #[derive(Clone, Default)] pub struct PaintList(Vec<ClippedShape>); impl PaintList { #[inline(always)] pub fn is_empty(&self) -> bool { self.0.is_empty() } pub fn next_idx(&self) -> ShapeIdx { ShapeIdx(self.0.len()) } /// Returns the index of the new [`Shape`] that can be used with `PaintList::set`. #[inline(always)] pub fn add(&mut self, clip_rect: Rect, shape: Shape) -> ShapeIdx { let idx = self.next_idx(); self.0.push(ClippedShape { clip_rect, shape }); idx } pub fn extend<I: IntoIterator<Item = Shape>>(&mut self, clip_rect: Rect, shapes: I) { self.0.extend( shapes .into_iter() .map(|shape| ClippedShape { clip_rect, shape }), ); } /// Modify an existing [`Shape`]. /// /// Sometimes you want to paint a frame behind some contents, but don't know how large the frame needs to be /// until the contents have been added, and therefor also painted to the [`PaintList`]. /// /// The solution is to allocate a [`Shape`] using `let idx = paint_list.add(cr, Shape::Noop);` /// and then later setting it using `paint_list.set(idx, cr, frame);`. #[inline(always)] pub fn set(&mut self, idx: ShapeIdx, clip_rect: Rect, shape: Shape) { if self.0.len() <= idx.0 { log::warn!("Index {} is out of bounds for PaintList", idx.0); return; } self.0[idx.0] = ClippedShape { clip_rect, shape }; } /// Set the given shape to be empty (a `Shape::Noop`). #[inline(always)] pub fn reset_shape(&mut self, idx: ShapeIdx) { self.0[idx.0].shape = Shape::Noop; } /// Mutate the shape at the given index, if any. pub fn mutate_shape(&mut self, idx: ShapeIdx, f: impl FnOnce(&mut ClippedShape)) { self.0.get_mut(idx.0).map(f); } /// Transform each [`Shape`] and clip rectangle by this much, in-place pub fn transform(&mut self, transform: TSTransform) { for ClippedShape { clip_rect, shape } in &mut self.0 { *clip_rect = transform.mul_rect(*clip_rect); shape.transform(transform); } } /// Transform each [`Shape`] and clip rectangle in range by this much, in-place pub fn transform_range(&mut self, start: ShapeIdx, end: ShapeIdx, transform: TSTransform) { for ClippedShape { clip_rect, shape } in &mut self.0[start.0..end.0] { *clip_rect = transform.mul_rect(*clip_rect); shape.transform(transform); } } /// Read-only access to all held shapes. pub fn all_entries(&self) -> impl ExactSizeIterator<Item = &ClippedShape> { self.0.iter() } } /// This is where painted [`Shape`]s end up during a frame. #[derive(Clone, Default)] pub struct GraphicLayers([IdMap<PaintList>; Order::COUNT]); impl GraphicLayers { /// Get or insert the [`PaintList`] for the given [`LayerId`]. pub fn entry(&mut self, layer_id: LayerId) -> &mut PaintList { self.0[layer_id.order as usize] .entry(layer_id.id) .or_default() } /// Get the [`PaintList`] for the given [`LayerId`]. pub fn get(&self, layer_id: LayerId) -> Option<&PaintList> { self.0[layer_id.order as usize].get(&layer_id.id) } /// Get the [`PaintList`] for the given [`LayerId`]. pub fn get_mut(&mut self, layer_id: LayerId) -> Option<&mut PaintList> { self.0[layer_id.order as usize].get_mut(&layer_id.id) } pub fn drain( &mut self, area_order: &[LayerId], to_global: &ahash::HashMap<LayerId, TSTransform>, ) -> Vec<ClippedShape> { profiling::function_scope!(); let mut all_shapes: Vec<_> = Default::default(); for &order in &Order::ALL { let order_map = &mut self.0[order as usize]; // If a layer is empty at the start of the frame // then nobody has added to it, and it is old and defunct. // Free it to save memory: order_map.retain(|_, list| !list.is_empty()); // First do the layers part of area_order: for layer_id in area_order { if layer_id.order == order && let Some(list) = order_map.get_mut(&layer_id.id) { if let Some(to_global) = to_global.get(layer_id) { for clipped_shape in &mut list.0 { clipped_shape.transform(*to_global); } } all_shapes.append(&mut list.0); } } // Also draw areas that are missing in `area_order`: // NOTE: We don't think we end up here in normal situations. // This is just a safety net in case we have some bug somewhere. #[expect(clippy::iter_over_hash_type)] for (id, list) in order_map { let layer_id = LayerId::new(order, *id); if let Some(to_global) = to_global.get(&layer_id) { for clipped_shape in &mut list.0 { clipped_shape.transform(*to_global); } } all_shapes.append(&mut list.0); } } all_shapes } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/lib.rs
crates/egui/src/lib.rs
//! `egui`: an easy-to-use GUI in pure Rust! //! //! Try the live web demo: <https://www.egui.rs/#demo>. Read more about egui at <https://github.com/emilk/egui>. //! //! `egui` is in heavy development, with each new version having breaking changes. //! You need to have rust 1.92.0 or later to use `egui`. //! //! To quickly get started with egui, you can take a look at [`eframe_template`](https://github.com/emilk/eframe_template) //! which uses [`eframe`](https://docs.rs/eframe). //! //! To create a GUI using egui you first need a [`Context`] (by convention referred to by `ctx`). //! Then you add a [`Window`] or a [`Panel`] to get a [`Ui`], which is what you'll be using to add all the buttons and labels that you need. //! //! //! ## Feature flags #![cfg_attr(feature = "document-features", doc = document_features::document_features!())] //! //! //! # Using egui //! //! To see what is possible to build with egui you can check out the online demo at <https://www.egui.rs/#demo>. //! //! If you like the "learning by doing" approach, clone <https://github.com/emilk/eframe_template> and get started using egui right away. //! //! ### A simple example //! //! Here is a simple counter that can be incremented and decremented using two buttons: //! ``` //! fn ui_counter(ui: &mut egui::Ui, counter: &mut i32) { //! // Put the buttons and label on the same row: //! ui.horizontal(|ui| { //! if ui.button("−").clicked() { //! *counter -= 1; //! } //! ui.label(counter.to_string()); //! if ui.button("+").clicked() { //! *counter += 1; //! } //! }); //! } //! ``` //! //! In some GUI frameworks this would require defining multiple types and functions with callbacks or message handlers, //! but thanks to `egui` being immediate mode everything is one self-contained function! //! //! ### Quick start //! //! ``` //! # egui::__run_test_ui(|ui| { //! # let mut my_string = String::new(); //! # let mut my_boolean = true; //! # let mut my_f32 = 42.0; //! ui.label("This is a label"); //! ui.hyperlink("https://github.com/emilk/egui"); //! ui.text_edit_singleline(&mut my_string); //! if ui.button("Click me").clicked() { } //! ui.add(egui::Slider::new(&mut my_f32, 0.0..=100.0)); //! ui.add(egui::DragValue::new(&mut my_f32)); //! //! ui.checkbox(&mut my_boolean, "Checkbox"); //! //! #[derive(PartialEq)] //! enum Enum { First, Second, Third } //! # let mut my_enum = Enum::First; //! ui.horizontal(|ui| { //! ui.radio_value(&mut my_enum, Enum::First, "First"); //! ui.radio_value(&mut my_enum, Enum::Second, "Second"); //! ui.radio_value(&mut my_enum, Enum::Third, "Third"); //! }); //! //! ui.separator(); //! //! # let my_image = egui::TextureId::default(); //! ui.image((my_image, egui::Vec2::new(640.0, 480.0))); //! //! ui.collapsing("Click to see what is hidden!", |ui| { //! ui.label("Not much, as it turns out"); //! }); //! # }); //! ``` //! //! ## Viewports //! Some egui backends support multiple _viewports_, which is what egui calls the native OS windows it resides in. //! See [`crate::viewport`] for more information. //! //! ## Coordinate system //! The left-top corner of the screen is `(0.0, 0.0)`, //! with X increasing to the right and Y increasing downwards. //! //! `egui` uses logical _points_ as its coordinate system. //! Those related to physical _pixels_ by the `pixels_per_point` scale factor. //! For example, a high-dpi screen can have `pixels_per_point = 2.0`, //! meaning there are two physical screen pixels for each logical point. //! //! Angles are in radians, and are measured clockwise from the X-axis, which has angle=0. //! //! # Integrating with egui //! //! Most likely you are using an existing `egui` backend/integration such as [`eframe`](https://docs.rs/eframe), [`bevy_egui`](https://docs.rs/bevy_egui), //! or [`egui-miniquad`](https://github.com/not-fl3/egui-miniquad), //! but if you want to integrate `egui` into a new game engine or graphics backend, this is the section for you. //! //! You need to collect [`RawInput`] and handle [`FullOutput`]. The basic structure is this: //! //! ``` no_run //! # fn handle_platform_output(_: egui::PlatformOutput) {} //! # fn gather_input() -> egui::RawInput { egui::RawInput::default() } //! # fn paint(textures_delta: egui::TexturesDelta, _: Vec<egui::ClippedPrimitive>) {} //! let mut ctx = egui::Context::default(); //! //! // Game loop: //! loop { //! let raw_input: egui::RawInput = gather_input(); //! //! let full_output = ctx.run(raw_input, |ctx| { //! egui::CentralPanel::default().show(&ctx, |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); //! } //! ``` //! //! For a reference OpenGL renderer, see [the `egui_glow` painter](https://github.com/emilk/egui/blob/main/crates/egui_glow/src/painter.rs). //! //! //! ### Debugging your renderer //! //! #### Things look jagged //! //! * Turn off backface culling. //! //! #### My text is blurry //! //! * Make sure you set the proper `pixels_per_point` in the input to egui. //! * Make sure the texture sampler is not off by half a pixel. Try nearest-neighbor sampler to check. //! //! #### My windows are too transparent or too dark //! //! * egui uses premultiplied alpha, so make sure your blending function is `(ONE, ONE_MINUS_SRC_ALPHA)`. //! * Make sure your texture sampler is clamped (`GL_CLAMP_TO_EDGE`). //! * egui prefers gamma color spaces for all blending so: //! * Do NOT use an sRGBA-aware texture (NOT `GL_SRGB8_ALPHA8`). //! * Multiply texture and vertex colors in gamma space //! * Turn OFF sRGBA/gamma framebuffer (NO `GL_FRAMEBUFFER_SRGB`). //! //! //! # Understanding immediate mode //! //! `egui` is an immediate mode GUI library. //! //! Immediate mode has its roots in gaming, where everything on the screen is painted at the //! display refresh rate, i.e. at 60+ frames per second. //! In immediate mode GUIs, the entire interface is laid out and painted at the same high rate. //! This makes immediate mode GUIs especially well suited for highly interactive applications. //! //! It is useful to fully grok what "immediate mode" implies. //! //! Here is an example to illustrate it: //! //! ``` //! # egui::__run_test_ui(|ui| { //! if ui.button("click me").clicked() { //! take_action() //! } //! # }); //! # fn take_action() {} //! ``` //! //! This code is being executed each frame at maybe 60 frames per second. //! Each frame egui does these things: //! //! * lays out the letters `click me` in order to figure out the size of the button //! * decides where on screen to place the button //! * check if the mouse is hovering or clicking that location //! * choose button colors based on if it is being hovered or clicked //! * add a [`Shape::Rect`] and [`Shape::Text`] to the list of shapes to be painted later this frame //! * return a [`Response`] with the [`clicked`](`Response::clicked`) member so the user can check for interactions //! //! There is no button being created and stored somewhere. //! The only output of this call is some colored shapes, and a [`Response`]. //! //! Similarly, consider this code: //! //! ``` //! # egui::__run_test_ui(|ui| { //! # let mut value: f32 = 0.0; //! ui.add(egui::Slider::new(&mut value, 0.0..=100.0).text("My value")); //! # }); //! ``` //! //! Here egui will read `value` (an `f32`) to display the slider, then look if the mouse is dragging the slider and if so change the `value`. //! Note that `egui` does not store the slider value for you - it only displays the current value, and changes it //! by how much the slider has been dragged in the previous few milliseconds. //! This means it is responsibility of the egui user to store the state (`value`) so that it persists between frames. //! //! It can be useful to read the code for the toggle switch example widget to get a better understanding //! of how egui works: <https://github.com/emilk/egui/blob/main/crates/egui_demo_lib/src/demo/toggle_switch.rs>. //! //! Read more about the pros and cons of immediate mode at <https://github.com/emilk/egui#why-immediate-mode>. //! //! ## Multi-pass immediate mode //! By default, egui usually only does one pass for each rendered frame. //! However, egui supports multi-pass immediate mode. //! Another pass can be requested with [`Context::request_discard`]. //! //! This is used by some widgets to cover up "first-frame jitters". //! For instance, the [`Grid`] needs to know the width of all columns before it can properly place the widgets. //! But it cannot know the width of widgets to come. //! So it stores the max widths of previous frames and uses that. //! This means the first time a `Grid` is shown it will _guess_ the widths of the columns, and will usually guess wrong. //! This means the contents of the grid will be wrong for one frame, before settling to the correct places. //! Therefore `Grid` calls [`Context::request_discard`] when it is first shown, so the wrong placement is never //! visible to the end user. //! //! This is an example of a form of multi-pass immediate mode, where earlier passes are used for sizing, //! and later passes for layout. //! //! See [`Context::request_discard`] and [`Options::max_passes`] for more. //! //! # Misc //! //! ## How widgets works //! //! ``` //! # egui::__run_test_ui(|ui| { //! if ui.button("click me").clicked() { take_action() } //! # }); //! # fn take_action() {} //! ``` //! //! is short for //! //! ``` //! # egui::__run_test_ui(|ui| { //! let button = egui::Button::new("click me"); //! if ui.add(button).clicked() { take_action() } //! # }); //! # fn take_action() {} //! ``` //! //! which is short for //! //! ``` //! # use egui::Widget; //! # egui::__run_test_ui(|ui| { //! let button = egui::Button::new("click me"); //! let response = button.ui(ui); //! if response.clicked() { take_action() } //! # }); //! # fn take_action() {} //! ``` //! //! [`Button`] uses the builder pattern to create the data required to show it. The [`Button`] is then discarded. //! //! [`Button`] implements `trait` [`Widget`], which looks like this: //! ``` //! # use egui::*; //! pub trait Widget { //! /// Allocate space, interact, paint, and return a [`Response`]. //! fn ui(self, ui: &mut Ui) -> Response; //! } //! ``` //! //! //! ## Widget interaction //! Each widget has a [`Sense`], which defines whether or not the widget //! is sensitive to clicking and/or drags. //! //! For instance, a [`Button`] only has a [`Sense::click`] (by default). //! This means if you drag a button it will not respond with [`Response::dragged`]. //! Instead, the drag will continue through the button to the first //! widget behind it that is sensitive to dragging, which for instance could be //! a [`ScrollArea`]. This lets you scroll by dragging a scroll area (important //! on touch screens), just as long as you don't drag on a widget that is sensitive //! to drags (e.g. a [`Slider`]). //! //! When widgets overlap it is the last added one //! that is considered to be on top and which will get input priority. //! //! The widget interaction logic is run at the _start_ of each frame, //! based on the output from the previous frame. //! This means that when a new widget shows up you cannot click it in the same //! frame (i.e. in the same fraction of a second), but unless the user //! is spider-man, they wouldn't be fast enough to do so anyways. //! //! By running the interaction code early, egui can actually //! tell you if a widget is being interacted with _before_ you add it, //! as long as you know its [`Id`] before-hand (e.g. using [`Ui::next_auto_id`]), //! by calling [`Context::read_response`]. //! This can be useful in some circumstances in order to style a widget, //! or to respond to interactions before adding the widget //! (perhaps on top of other widgets). //! //! //! ## Auto-sizing panels and windows //! In egui, all panels and windows auto-shrink to fit the content. //! If the window or panel is also resizable, this can lead to a weird behavior //! where you can drag the edge of the panel/window to make it larger, and //! when you release the panel/window shrinks again. //! This is an artifact of immediate mode, and here are some alternatives on how to avoid it: //! //! 1. Turn off resizing with [`Window::resizable`], [`Panel::resizable`]. //! 2. Wrap your panel contents in a [`ScrollArea`], or use [`Window::vscroll`] and [`Window::hscroll`]. //! 3. Use a justified layout: //! //! ``` //! # egui::__run_test_ui(|ui| { //! ui.with_layout(egui::Layout::top_down_justified(egui::Align::Center), |ui| { //! ui.button("I am becoming wider as needed"); //! }); //! # }); //! ``` //! //! 4. Fill in extra space with emptiness: //! //! ``` //! # egui::__run_test_ui(|ui| { //! ui.allocate_space(ui.available_size()); // put this LAST in your panel/window code //! # }); //! ``` //! //! ## Sizes //! You can control the size of widgets using [`Ui::add_sized`]. //! //! ``` //! # egui::__run_test_ui(|ui| { //! # let mut my_value = 0.0_f32; //! ui.add_sized([40.0, 20.0], egui::DragValue::new(&mut my_value)); //! # }); //! ``` //! //! ## Code snippets //! //! ``` //! # use egui::TextWrapMode; //! # egui::__run_test_ui(|ui| { //! # let mut some_bool = true; //! // Miscellaneous tips and tricks //! //! ui.horizontal_wrapped(|ui| { //! ui.spacing_mut().item_spacing.x = 0.0; // remove spacing between widgets //! // `radio_value` also works for enums, integers, and more. //! ui.radio_value(&mut some_bool, false, "Off"); //! ui.radio_value(&mut some_bool, true, "On"); //! }); //! //! ui.group(|ui| { //! ui.label("Within a frame"); //! ui.set_min_height(200.0); //! }); //! //! // A `scope` creates a temporary [`Ui`] in which you can change settings: //! ui.scope(|ui| { //! ui.visuals_mut().override_text_color = Some(egui::Color32::RED); //! ui.style_mut().override_text_style = Some(egui::TextStyle::Monospace); //! ui.style_mut().wrap_mode = Some(TextWrapMode::Truncate); //! //! ui.label("This text will be red, monospace, and won't wrap to a new line"); //! }); // the temporary settings are reverted here //! # }); //! ``` //! //! ## Installing additional fonts //! The default egui fonts only support latin and cryllic characters, and some emojis. //! To use egui with e.g. asian characters you need to install your own font (`.ttf` or `.otf`) using [`Context::set_fonts`]. //! //! ## Instrumentation //! This crate supports using the [profiling](https://crates.io/crates/profiling) crate for instrumentation. //! You can enable features on the profiling crates in your application to add instrumentation for all //! crates that support it, including egui. See the profiling crate docs for more information. //! ```toml //! [dependencies] //! profiling = "1.0" //! [features] //! profile-with-puffin = ["profiling/profile-with-puffin"] //! ``` //! //! ## Custom allocator //! egui apps can run significantly (~20%) faster by using a custom allocator, like [mimalloc](https://crates.io/crates/mimalloc) or [talc](https://crates.io/crates/talc). //! #![expect(clippy::float_cmp)] #![expect(clippy::manual_range_contains)] mod animation_manager; mod atomics; pub mod cache; pub mod containers; mod context; mod data; pub mod debug_text; mod drag_and_drop; pub(crate) mod grid; pub mod gui_zoom; mod hit_test; mod id; mod input_state; mod interaction; pub mod introspection; pub mod layers; mod layout; pub mod load; mod memory; #[deprecated = "Use `egui::containers::menu` instead"] pub mod menu; pub mod os; mod painter; mod pass_state; pub(crate) mod placer; mod plugin; pub mod response; mod sense; pub mod style; pub mod text_selection; mod ui; mod ui_builder; mod ui_stack; pub mod util; pub mod viewport; mod widget_rect; pub mod widget_style; pub mod widget_text; pub mod widgets; #[cfg(feature = "callstack")] #[cfg(debug_assertions)] mod callstack; pub use accesskit; #[deprecated = "Use the ahash crate directly."] pub use ahash; pub use epaint; pub use epaint::ecolor; pub use epaint::emath; #[cfg(feature = "color-hex")] pub use ecolor::hex_color; pub use ecolor::{Color32, Rgba}; pub use emath::{ Align, Align2, NumExt, Pos2, Rangef, Rect, RectAlign, Vec2, Vec2b, lerp, pos2, remap, remap_clamp, vec2, }; pub use epaint::{ ClippedPrimitive, ColorImage, CornerRadius, ImageData, Margin, Mesh, PaintCallback, PaintCallbackInfo, Shadow, Shape, Stroke, StrokeKind, TextureHandle, TextureId, mutex, text::{FontData, FontDefinitions, FontFamily, FontId, FontTweak}, textures::{TextureFilter, TextureOptions, TextureWrapMode, TexturesDelta}, }; pub mod text { pub use crate::text_selection::CCursorRange; pub use epaint::text::{ FontData, FontDefinitions, FontFamily, Fonts, Galley, LayoutJob, LayoutSection, TAB_SIZE, TextFormat, TextWrapping, cursor::CCursor, }; } pub use self::{ atomics::*, containers::{menu::MenuBar, *}, context::{Context, RepaintCause, RequestRepaintInfo}, data::{ Key, UserData, input::*, output::{ self, CursorIcon, FullOutput, OpenUrl, OutputCommand, PlatformOutput, UserAttentionType, WidgetInfo, }, }, drag_and_drop::DragAndDrop, epaint::text::TextWrapMode, grid::Grid, id::{Id, IdMap}, input_state::{InputOptions, InputState, MultiTouchInfo, PointerState, SurrenderFocusOn}, layers::{LayerId, Order}, layout::*, load::SizeHint, memory::{FocusDirection, Memory, Options, Theme, ThemePreference}, painter::Painter, plugin::Plugin, response::{InnerResponse, Response}, sense::Sense, style::{FontSelection, Spacing, Style, TextStyle, Visuals}, text::{Galley, TextFormat}, ui::Ui, ui_builder::UiBuilder, ui_stack::*, viewport::*, widget_rect::{InteractOptions, WidgetRect, WidgetRects}, widget_text::{RichText, WidgetText}, widgets::*, }; #[deprecated = "Renamed to CornerRadius"] pub type Rounding = CornerRadius; // ---------------------------------------------------------------------------- /// Helper function that adds a label when compiling with debug assertions enabled. pub fn warn_if_debug_build(ui: &mut crate::Ui) { if cfg!(debug_assertions) { ui.label( RichText::new("⚠ Debug build ⚠") .small() .color(ui.visuals().warn_fg_color), ) .on_hover_text("egui was compiled with debug assertions enabled."); } } // ---------------------------------------------------------------------------- /// Include an image in the binary. /// /// This is a wrapper over `include_bytes!`, and behaves in the same way. /// /// It produces an [`ImageSource`] which can be used directly in [`Ui::image`] or [`Image::new`]: /// /// ``` /// # egui::__run_test_ui(|ui| { /// ui.image(egui::include_image!("../assets/ferris.png")); /// ui.add( /// egui::Image::new(egui::include_image!("../assets/ferris.png")) /// .max_width(200.0) /// .corner_radius(10), /// ); /// /// let image_source: egui::ImageSource = egui::include_image!("../assets/ferris.png"); /// assert_eq!(image_source.uri(), Some("bytes://../assets/ferris.png")); /// # }); /// ``` #[macro_export] macro_rules! include_image { ($path:expr $(,)?) => { $crate::ImageSource::Bytes { uri: ::std::borrow::Cow::Borrowed(concat!("bytes://", $path)), bytes: $crate::load::Bytes::Static(include_bytes!($path)), } }; } /// Create a [`Hyperlink`] to the current [`file!()`] (and line) on Github /// /// ``` /// # egui::__run_test_ui(|ui| { /// ui.add(egui::github_link_file_line!("https://github.com/YOUR/PROJECT/blob/main/", "(source code)")); /// # }); /// ``` #[macro_export] macro_rules! github_link_file_line { ($github_url: expr, $label: expr) => {{ let url = format!("{}{}#L{}", $github_url, file!(), line!()); $crate::Hyperlink::from_label_and_url($label, url) }}; } /// Create a [`Hyperlink`] to the current [`file!()`] on github. /// /// ``` /// # egui::__run_test_ui(|ui| { /// ui.add(egui::github_link_file!("https://github.com/YOUR/PROJECT/blob/main/", "(source code)")); /// # }); /// ``` #[macro_export] macro_rules! github_link_file { ($github_url: expr, $label: expr) => {{ let url = format!("{}{}", $github_url, file!()); $crate::Hyperlink::from_label_and_url($label, url) }}; } // ---------------------------------------------------------------------------- /// The minus character: <https://www.compart.com/en/unicode/U+2212> pub(crate) const MINUS_CHAR_STR: &str = "−"; /// The default egui fonts supports around 1216 emojis in total. /// Here are some of the most useful: /// ∞⊗⎗⎘⎙⏏⏴⏵⏶⏷ /// ⏩⏪⏭⏮⏸⏹⏺■▶📾🔀🔁🔃 /// ☀☁★☆☐☑☜☝☞☟⛃⛶✔ /// ↺↻⟲⟳⬅➡⬆⬇⬈⬉⬊⬋⬌⬍⮨⮩⮪⮫ /// ♡ /// 📅📆 /// 📈📉📊 /// 📋📌📎📤📥🔆 /// 🔈🔉🔊🔍🔎🔗🔘 /// 🕓🖧🖩🖮🖱🖴🖵🖼🗀🗁🗋🗐🗑🗙🚫❓ /// /// NOTE: In egui all emojis are monochrome! /// /// You can explore them all in the Font Book in [the online demo](https://www.egui.rs/#demo). /// /// In addition, egui supports a few special emojis that are not part of the unicode standard. /// This module contains some of them: pub mod special_emojis { /// Tux, the Linux penguin. pub const OS_LINUX: char = '🐧'; /// The Windows logo. pub const OS_WINDOWS: char = ''; /// The Android logo. pub const OS_ANDROID: char = ''; /// The Apple logo. pub const OS_APPLE: char = ''; /// The Github logo. pub const GITHUB: char = ''; /// The word `git`. pub const GIT: char = ''; // I really would like to have ferris here. } /// The different types of built-in widgets in egui #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub enum WidgetType { Label, // TODO(emilk): emit Label events /// e.g. a hyperlink Link, TextEdit, Button, Checkbox, RadioButton, /// A group of radio buttons. RadioGroup, SelectableLabel, ComboBox, Slider, DragValue, ColorButton, Image, CollapsingHeader, Panel, ProgressIndicator, Window, ResizeHandle, ScrollBar, /// If you cannot fit any of the above slots. /// /// If this is something you think should be added, file an issue. Other, } // ---------------------------------------------------------------------------- /// For use in tests; especially doctests. pub fn __run_test_ctx(mut run_ui: impl FnMut(&Context)) { let ctx = Context::default(); ctx.set_fonts(FontDefinitions::empty()); // prevent fonts from being loaded (save CPU time) let _ = ctx.run_ui(Default::default(), |ui| { run_ui(ui.ctx()); }); } /// For use in tests; especially doctests. pub fn __run_test_ui(add_contents: impl Fn(&mut Ui)) { let ctx = Context::default(); ctx.set_fonts(FontDefinitions::empty()); // prevent fonts from being loaded (save CPU time) let _ = ctx.run_ui(Default::default(), |ui| { add_contents(ui); }); } pub fn accesskit_root_id() -> Id { Id::new("accesskit_root") }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/widget_text.rs
crates/egui/src/widget_text.rs
use emath::GuiRounding as _; use epaint::text::TextFormat; use std::fmt::Formatter; use std::{borrow::Cow, sync::Arc}; use crate::{ Align, Color32, FontFamily, FontSelection, Galley, Style, TextStyle, TextWrapMode, Ui, Visuals, text::{LayoutJob, TextWrapping}, }; /// Text and optional style choices for it. /// /// The style choices (font, color) are applied to the entire text. /// For more detailed control, use [`crate::text::LayoutJob`] instead. /// /// A [`RichText`] can be used in most widgets and helper functions, e.g. [`Ui::label`] and [`Ui::button`]. /// /// ### Example /// ``` /// use egui::{RichText, Color32}; /// /// RichText::new("Plain"); /// RichText::new("colored").color(Color32::RED); /// RichText::new("Large and underlined").size(20.0).underline(); /// ``` #[derive(Clone, Debug, PartialEq)] pub struct RichText { text: String, size: Option<f32>, extra_letter_spacing: f32, line_height: Option<f32>, family: Option<FontFamily>, text_style: Option<TextStyle>, background_color: Color32, expand_bg: f32, text_color: Option<Color32>, code: bool, strong: bool, weak: bool, strikethrough: bool, underline: bool, italics: bool, raised: bool, } impl Default for RichText { fn default() -> Self { Self { text: Default::default(), size: Default::default(), extra_letter_spacing: Default::default(), line_height: Default::default(), family: Default::default(), text_style: Default::default(), background_color: Default::default(), expand_bg: 1.0, text_color: Default::default(), code: Default::default(), strong: Default::default(), weak: Default::default(), strikethrough: Default::default(), underline: Default::default(), italics: Default::default(), raised: Default::default(), } } } impl From<&str> for RichText { #[inline] fn from(text: &str) -> Self { Self::new(text) } } impl From<&String> for RichText { #[inline] fn from(text: &String) -> Self { Self::new(text) } } impl From<&mut String> for RichText { #[inline] fn from(text: &mut String) -> Self { Self::new(text.clone()) } } impl From<String> for RichText { #[inline] fn from(text: String) -> Self { Self::new(text) } } impl From<&Box<str>> for RichText { #[inline] fn from(text: &Box<str>) -> Self { Self::new(text.clone()) } } impl From<&mut Box<str>> for RichText { #[inline] fn from(text: &mut Box<str>) -> Self { Self::new(text.clone()) } } impl From<Box<str>> for RichText { #[inline] fn from(text: Box<str>) -> Self { Self::new(text) } } impl From<Cow<'_, str>> for RichText { #[inline] fn from(text: Cow<'_, str>) -> Self { Self::new(text) } } impl RichText { #[inline] pub fn new(text: impl Into<String>) -> Self { Self { text: text.into(), ..Default::default() } } #[inline] pub fn is_empty(&self) -> bool { self.text.is_empty() } #[inline] pub fn text(&self) -> &str { &self.text } /// Select the font size (in points). /// This overrides the value from [`Self::text_style`]. #[inline] pub fn size(mut self, size: f32) -> Self { self.size = Some(size); self } /// Extra spacing between letters, in points. /// /// Default: 0.0. /// /// For even text it is recommended you round this to an even number of _pixels_, /// e.g. using [`crate::Painter::round_to_pixel`]. #[inline] pub fn extra_letter_spacing(mut self, extra_letter_spacing: f32) -> Self { self.extra_letter_spacing = extra_letter_spacing; self } /// Explicit line height of the text in points. /// /// This is the distance between the bottom row of two subsequent lines of text. /// /// If `None` (the default), the line height is determined by the font. /// /// For even text it is recommended you round this to an even number of _pixels_, /// e.g. using [`crate::Painter::round_to_pixel`]. #[inline] pub fn line_height(mut self, line_height: Option<f32>) -> Self { self.line_height = line_height; self } /// Select the font family. /// /// This overrides the value from [`Self::text_style`]. /// /// Only the families available in [`crate::FontDefinitions::families`] may be used. #[inline] pub fn family(mut self, family: FontFamily) -> Self { self.family = Some(family); self } /// Select the font and size. /// This overrides the value from [`Self::text_style`]. #[inline] pub fn font(mut self, font_id: crate::FontId) -> Self { let crate::FontId { size, family } = font_id; self.size = Some(size); self.family = Some(family); self } /// Override the [`TextStyle`]. #[inline] pub fn text_style(mut self, text_style: TextStyle) -> Self { self.text_style = Some(text_style); self } /// Set the [`TextStyle`] unless it has already been set #[inline] pub fn fallback_text_style(mut self, text_style: TextStyle) -> Self { self.text_style.get_or_insert(text_style); self } /// Use [`TextStyle::Heading`]. #[inline] pub fn heading(self) -> Self { self.text_style(TextStyle::Heading) } /// Use [`TextStyle::Monospace`]. #[inline] pub fn monospace(self) -> Self { self.text_style(TextStyle::Monospace) } /// Monospace label with different background color. #[inline] pub fn code(mut self) -> Self { self.code = true; self.text_style(TextStyle::Monospace) } /// Extra strong text (stronger color). #[inline] pub fn strong(mut self) -> Self { self.strong = true; self } /// Extra weak text (fainter color). #[inline] pub fn weak(mut self) -> Self { self.weak = true; self } /// Draw a line under the text. /// /// If you want to control the line color, use [`LayoutJob`] instead. #[inline] pub fn underline(mut self) -> Self { self.underline = true; self } /// Draw a line through the text, crossing it out. /// /// If you want to control the strikethrough line color, use [`LayoutJob`] instead. #[inline] pub fn strikethrough(mut self) -> Self { self.strikethrough = true; self } /// Tilt the characters to the right. #[inline] pub fn italics(mut self) -> Self { self.italics = true; self } /// Smaller text. #[inline] pub fn small(self) -> Self { self.text_style(TextStyle::Small) } /// For e.g. exponents. #[inline] pub fn small_raised(self) -> Self { self.text_style(TextStyle::Small).raised() } /// Align text to top. Only applicable together with [`Self::small()`]. #[inline] pub fn raised(mut self) -> Self { self.raised = true; self } /// Fill-color behind the text. #[inline] pub fn background_color(mut self, background_color: impl Into<Color32>) -> Self { self.background_color = background_color.into(); self } /// Override text color. /// /// If not set, [`Color32::PLACEHOLDER`] will be used, /// which will be replaced with a color chosen by the widget that paints the text. #[inline] pub fn color(mut self, color: impl Into<Color32>) -> Self { self.text_color = Some(color.into()); self } /// Read the font height of the selected text style. /// /// Returns a value rounded to [`emath::GUI_ROUNDING`]. pub fn font_height(&self, fonts: &mut epaint::FontsView<'_>, style: &Style) -> f32 { let mut font_id = self.text_style.as_ref().map_or_else( || FontSelection::Default.resolve(style), |text_style| text_style.resolve(style), ); if let Some(size) = self.size { font_id.size = size; } if let Some(family) = &self.family { font_id.family = family.clone(); } fonts.row_height(&font_id) } /// Append to an existing [`LayoutJob`] /// /// Note that the color of the [`RichText`] must be set, or may default to an undesirable color. /// /// ### Example /// ``` /// use egui::{Style, RichText, text::LayoutJob, Color32, FontSelection, Align}; /// /// let style = Style::default(); /// let mut layout_job = LayoutJob::default(); /// RichText::new("Normal") /// .color(style.visuals.text_color()) /// .append_to( /// &mut layout_job, /// &style, /// FontSelection::Default, /// Align::Center, /// ); /// RichText::new("Large and underlined") /// .color(style.visuals.text_color()) /// .size(20.0) /// .underline() /// .append_to( /// &mut layout_job, /// &style, /// FontSelection::Default, /// Align::Center, /// ); /// ``` pub fn append_to( self, layout_job: &mut LayoutJob, style: &Style, fallback_font: FontSelection, default_valign: Align, ) { let (text, format) = self.into_text_and_format(style, fallback_font, default_valign); layout_job.append(&text, 0.0, format); } fn into_layout_job( self, style: &Style, fallback_font: FontSelection, default_valign: Align, ) -> LayoutJob { let (text, text_format) = self.into_text_and_format(style, fallback_font, default_valign); LayoutJob::single_section(text, text_format) } fn into_text_and_format( self, style: &Style, fallback_font: FontSelection, default_valign: Align, ) -> (String, crate::text::TextFormat) { let text_color = self.get_text_color(&style.visuals); let Self { text, size, extra_letter_spacing, line_height, family, text_style, background_color, expand_bg, text_color: _, // already used by `get_text_color` code, strong: _, // already used by `get_text_color` weak: _, // already used by `get_text_color` strikethrough, underline, italics, raised, } = self; let line_color = text_color.unwrap_or_else(|| style.visuals.text_color()); let text_color = text_color.unwrap_or(crate::Color32::PLACEHOLDER); let font_id = { let mut font_id = style.override_font_id.clone().unwrap_or_else(|| { (text_style.as_ref().or(style.override_text_style.as_ref())) .map(|text_style| text_style.resolve(style)) .unwrap_or_else(|| fallback_font.resolve(style)) }); if let Some(size) = size { font_id.size = size; } if let Some(family) = family { font_id.family = family; } font_id }; let background_color = if code { style.visuals.code_bg_color } else { background_color }; let underline = if underline { crate::Stroke::new(1.0, line_color) } else { crate::Stroke::NONE }; let strikethrough = if strikethrough { crate::Stroke::new(1.0, line_color) } else { crate::Stroke::NONE }; let valign = if raised { crate::Align::TOP } else { default_valign }; ( text, crate::text::TextFormat { font_id, extra_letter_spacing, line_height, color: text_color, background: background_color, italics, underline, strikethrough, valign, expand_bg, }, ) } fn get_text_color(&self, visuals: &Visuals) -> Option<Color32> { if let Some(text_color) = self.text_color { Some(text_color) } else if self.strong { Some(visuals.strong_text_color()) } else if self.weak { Some(visuals.weak_text_color()) } else { visuals.override_text_color } } } // ---------------------------------------------------------------------------- /// This is how you specify text for a widget. /// /// A lot of widgets use `impl Into<WidgetText>` as an argument, /// allowing you to pass in [`String`], [`RichText`], [`LayoutJob`], and more. /// /// Often a [`WidgetText`] is just a simple [`String`], /// but it can be a [`RichText`] (text with color, style, etc), /// a [`LayoutJob`] (for when you want full control of how the text looks) /// or text that has already been laid out in a [`Galley`]. /// /// You can color the text however you want, or use [`Color32::PLACEHOLDER`] /// which will be replaced with a color chosen by the widget that paints the text. #[derive(Clone)] pub enum WidgetText { /// Plain unstyled text. /// /// We have this as a special case, as it is the common-case, /// and it uses less memory than [`Self::RichText`]. Text(String), /// Text and optional style choices for it. /// /// Prefer [`Self::Text`] if there is no styling, as it will be faster. RichText(Arc<RichText>), /// Use this [`LayoutJob`] when laying out the text. /// /// Only [`LayoutJob::text`] and [`LayoutJob::sections`] are guaranteed to be respected. /// /// [`TextWrapping::max_width`](epaint::text::TextWrapping::max_width), [`LayoutJob::halign`], [`LayoutJob::justify`] /// and [`LayoutJob::first_row_min_height`] will likely be determined by the [`crate::Layout`] /// of the [`Ui`] the widget is placed in. /// If you want all parts of the [`LayoutJob`] respected, then convert it to a /// [`Galley`] and use [`Self::Galley`] instead. /// /// You can color the text however you want, or use [`Color32::PLACEHOLDER`] /// which will be replaced with a color chosen by the widget that paints the text. LayoutJob(Arc<LayoutJob>), /// Use exactly this galley when painting the text. /// /// You can color the text however you want, or use [`Color32::PLACEHOLDER`] /// which will be replaced with a color chosen by the widget that paints the text. Galley(Arc<Galley>), } impl std::fmt::Debug for WidgetText { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { let text = self.text(); match self { Self::Text(_) => write!(f, "Text({text:?})"), Self::RichText(_) => write!(f, "RichText({text:?})"), Self::LayoutJob(_) => write!(f, "LayoutJob({text:?})"), Self::Galley(_) => write!(f, "Galley({text:?})"), } } } impl Default for WidgetText { fn default() -> Self { Self::Text(String::new()) } } impl WidgetText { #[inline] pub fn is_empty(&self) -> bool { match self { Self::Text(text) => text.is_empty(), Self::RichText(text) => text.is_empty(), Self::LayoutJob(job) => job.is_empty(), Self::Galley(galley) => galley.is_empty(), } } #[inline] pub fn text(&self) -> &str { match self { Self::Text(text) => text, Self::RichText(text) => text.text(), Self::LayoutJob(job) => &job.text, Self::Galley(galley) => galley.text(), } } /// Map the contents based on the provided closure. /// /// - [`Self::Text`] => convert to [`RichText`] and call f /// - [`Self::RichText`] => call f /// - else do nothing #[must_use] fn map_rich_text<F>(self, f: F) -> Self where F: FnOnce(RichText) -> RichText, { match self { Self::Text(text) => Self::RichText(Arc::new(f(RichText::new(text)))), Self::RichText(text) => Self::RichText(Arc::new(f(Arc::unwrap_or_clone(text)))), other => other, } } /// Override the [`TextStyle`] if, and only if, this is a [`RichText`]. /// /// Prefer using [`RichText`] directly! #[inline] pub fn text_style(self, text_style: TextStyle) -> Self { self.map_rich_text(|text| text.text_style(text_style)) } /// Set the [`TextStyle`] unless it has already been set /// /// Prefer using [`RichText`] directly! #[inline] pub fn fallback_text_style(self, text_style: TextStyle) -> Self { self.map_rich_text(|text| text.fallback_text_style(text_style)) } /// Override text color if, and only if, this is a [`RichText`]. /// /// Prefer using [`RichText`] directly! #[inline] pub fn color(self, color: impl Into<Color32>) -> Self { self.map_rich_text(|text| text.color(color)) } /// Prefer using [`RichText`] directly! #[inline] pub fn heading(self) -> Self { self.map_rich_text(|text| text.heading()) } /// Prefer using [`RichText`] directly! #[inline] pub fn monospace(self) -> Self { self.map_rich_text(|text| text.monospace()) } /// Prefer using [`RichText`] directly! #[inline] pub fn code(self) -> Self { self.map_rich_text(|text| text.code()) } /// Prefer using [`RichText`] directly! #[inline] pub fn strong(self) -> Self { self.map_rich_text(|text| text.strong()) } /// Prefer using [`RichText`] directly! #[inline] pub fn weak(self) -> Self { self.map_rich_text(|text| text.weak()) } /// Prefer using [`RichText`] directly! #[inline] pub fn underline(self) -> Self { self.map_rich_text(|text| text.underline()) } /// Prefer using [`RichText`] directly! #[inline] pub fn strikethrough(self) -> Self { self.map_rich_text(|text| text.strikethrough()) } /// Prefer using [`RichText`] directly! #[inline] pub fn italics(self) -> Self { self.map_rich_text(|text| text.italics()) } /// Prefer using [`RichText`] directly! #[inline] pub fn small(self) -> Self { self.map_rich_text(|text| text.small()) } /// Prefer using [`RichText`] directly! #[inline] pub fn small_raised(self) -> Self { self.map_rich_text(|text| text.small_raised()) } /// Prefer using [`RichText`] directly! #[inline] pub fn raised(self) -> Self { self.map_rich_text(|text| text.raised()) } /// Prefer using [`RichText`] directly! #[inline] pub fn background_color(self, background_color: impl Into<Color32>) -> Self { self.map_rich_text(|text| text.background_color(background_color)) } /// Returns a value rounded to [`emath::GUI_ROUNDING`]. pub(crate) fn font_height(&self, fonts: &mut epaint::FontsView<'_>, style: &Style) -> f32 { match self { Self::Text(_) => fonts.row_height(&FontSelection::Default.resolve(style)), Self::RichText(text) => text.font_height(fonts, style), Self::LayoutJob(job) => job.font_height(fonts), Self::Galley(galley) => { if let Some(placed_row) = galley.rows.first() { placed_row.height().round_ui() } else { galley.size().y.round_ui() } } } } pub fn into_layout_job( self, style: &Style, fallback_font: FontSelection, default_valign: Align, ) -> Arc<LayoutJob> { match self { Self::Text(text) => Arc::new(LayoutJob::simple_format( text, TextFormat { font_id: FontSelection::Default.resolve(style), color: crate::Color32::PLACEHOLDER, valign: default_valign, ..Default::default() }, )), Self::RichText(text) => Arc::new(Arc::unwrap_or_clone(text).into_layout_job( style, fallback_font, default_valign, )), Self::LayoutJob(job) => job, Self::Galley(galley) => Arc::clone(&galley.job), } } /// Layout with wrap mode based on the containing [`Ui`]. /// /// `wrap_mode`: override for [`Ui::wrap_mode`] pub fn into_galley( self, ui: &Ui, wrap_mode: Option<TextWrapMode>, available_width: f32, fallback_font: impl Into<FontSelection>, ) -> Arc<Galley> { let valign = ui.text_valign(); let style = ui.style(); let wrap_mode = wrap_mode.unwrap_or_else(|| ui.wrap_mode()); let text_wrapping = TextWrapping::from_wrap_mode_and_width(wrap_mode, available_width); self.into_galley_impl(ui.ctx(), style, text_wrapping, fallback_font.into(), valign) } pub fn into_galley_impl( self, ctx: &crate::Context, style: &Style, text_wrapping: TextWrapping, fallback_font: FontSelection, default_valign: Align, ) -> Arc<Galley> { match self { Self::Text(text) => { let color = style .visuals .override_text_color .unwrap_or(crate::Color32::PLACEHOLDER); let mut layout_job = LayoutJob::simple_format( text, TextFormat { // We want the style overrides to take precedence over the fallback font font_id: FontSelection::default() .resolve_with_fallback(style, fallback_font), color, valign: default_valign, ..Default::default() }, ); layout_job.wrap = text_wrapping; ctx.fonts_mut(|f| f.layout_job(layout_job)) } Self::RichText(text) => { let mut layout_job = Arc::unwrap_or_clone(text).into_layout_job( style, fallback_font, default_valign, ); layout_job.wrap = text_wrapping; ctx.fonts_mut(|f| f.layout_job(layout_job)) } Self::LayoutJob(job) => { let mut job = Arc::unwrap_or_clone(job); job.wrap = text_wrapping; ctx.fonts_mut(|f| f.layout_job(job)) } Self::Galley(galley) => galley, } } } impl From<&str> for WidgetText { #[inline] fn from(text: &str) -> Self { Self::Text(text.to_owned()) } } impl From<&String> for WidgetText { #[inline] fn from(text: &String) -> Self { Self::Text(text.clone()) } } impl From<String> for WidgetText { #[inline] fn from(text: String) -> Self { Self::Text(text) } } impl From<&Box<str>> for WidgetText { #[inline] fn from(text: &Box<str>) -> Self { Self::Text(text.to_string()) } } impl From<Box<str>> for WidgetText { #[inline] fn from(text: Box<str>) -> Self { Self::Text(text.into()) } } impl From<Cow<'_, str>> for WidgetText { #[inline] fn from(text: Cow<'_, str>) -> Self { Self::Text(text.into_owned()) } } impl From<RichText> for WidgetText { #[inline] fn from(rich_text: RichText) -> Self { Self::RichText(Arc::new(rich_text)) } } impl From<Arc<RichText>> for WidgetText { #[inline] fn from(rich_text: Arc<RichText>) -> Self { Self::RichText(rich_text) } } impl From<LayoutJob> for WidgetText { #[inline] fn from(layout_job: LayoutJob) -> Self { Self::LayoutJob(Arc::new(layout_job)) } } impl From<Arc<LayoutJob>> for WidgetText { #[inline] fn from(layout_job: Arc<LayoutJob>) -> Self { Self::LayoutJob(layout_job) } } impl From<Arc<Galley>> for WidgetText { #[inline] fn from(galley: Arc<Galley>) -> Self { Self::Galley(galley) } } #[cfg(test)] mod tests { use crate::WidgetText; #[test] fn ensure_small_widget_text() { assert_eq!(size_of::<WidgetText>(), size_of::<String>()); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/response.rs
crates/egui/src/response.rs
use std::{any::Any, sync::Arc}; use crate::{ Context, CursorIcon, Id, LayerId, PointerButton, Popup, PopupKind, Sense, Tooltip, Ui, WidgetRect, WidgetText, emath::{Align, Pos2, Rect, Vec2}, pass_state, }; // ---------------------------------------------------------------------------- /// The result of adding a widget to a [`Ui`]. /// /// A [`Response`] lets you know whether a widget is being hovered, clicked or dragged. /// It also lets you easily show a tooltip on hover. /// /// Whenever something gets added to a [`Ui`], a [`Response`] object is returned. /// [`Ui::add`] returns a [`Response`], as does [`Ui::button`], and all similar shortcuts. /// /// ⚠️ The `Response` contains a clone of [`Context`], and many methods lock the `Context`. /// It can therefore be a deadlock to use `Context` from within a context-locking closures, /// such as [`Context::input`]. #[derive(Clone, Debug)] pub struct Response { // CONTEXT: /// Used for optionally showing a tooltip and checking for more interactions. pub ctx: Context, // IN: /// Which layer the widget is part of. pub layer_id: LayerId, /// The [`Id`] of the widget/area this response pertains. pub id: Id, /// The area of the screen we are talking about. pub rect: Rect, /// The rectangle sensing interaction. /// /// This is sometimes smaller than [`Self::rect`] because of clipping /// (e.g. when inside a scroll area). pub interact_rect: Rect, /// The senses (click and/or drag) that the widget was interested in (if any). /// /// Note: if [`Self::enabled`] is `false`, then /// the widget _effectively_ doesn't sense anything, /// but can still have the same `Sense`. /// This is because the sense informs the styling of the widget, /// but we don't want to change the style when a widget is disabled /// (that is handled by the `Painter` directly). pub sense: Sense, // OUT: /// Where the pointer (mouse/touch) were when this widget was clicked or dragged. /// `None` if the widget is not being interacted with. #[doc(hidden)] pub interact_pointer_pos: Option<Pos2>, /// The intrinsic / desired size of the widget. /// /// This is the size that a non-wrapped, non-truncated, non-justified version of the widget /// would have. /// /// If this is `None`, use [`Self::rect`] instead. /// /// At the time of writing, this is only used by external crates /// for improved layouting. /// See for instance [`egui_flex`](https://github.com/lucasmerlin/hello_egui/tree/main/crates/egui_flex). pub intrinsic_size: Option<Vec2>, #[doc(hidden)] pub flags: Flags, } /// A bit set for various boolean properties of `Response`. #[doc(hidden)] #[derive(Copy, Clone, Debug)] pub struct Flags(u16); bitflags::bitflags! { impl Flags: u16 { /// Was the widget enabled? /// If `false`, there was no interaction attempted (not even hover). const ENABLED = 1<<0; /// The pointer is above this widget with no other blocking it. const CONTAINS_POINTER = 1<<1; /// The pointer is hovering above this widget or the widget was clicked/tapped this frame. const HOVERED = 1<<2; /// The widget is highlighted via a call to [`Response::highlight`] or /// [`Context::highlight_widget`]. const HIGHLIGHTED = 1<<3; /// This widget was clicked this frame. /// /// Which pointer and how many times we don't know, /// and ask [`crate::InputState`] about at runtime. /// /// This is only set to true if the widget was clicked /// by an actual mouse. const CLICKED = 1<<4; /// This widget should act as if clicked due /// to something else than a click. /// /// This is set to true if the widget has keyboard focus and /// the user hit the Space or Enter key. const FAKE_PRIMARY_CLICKED = 1<<5; /// This widget was long-pressed on a touch screen to simulate a secondary click. const LONG_TOUCHED = 1<<6; /// The widget started being dragged this frame. const DRAG_STARTED = 1<<7; /// The widget is being dragged. const DRAGGED = 1<<8; /// The widget was being dragged, but now it has been released. const DRAG_STOPPED = 1<<9; /// Is the pointer button currently down on this widget? /// This is true if the pointer is pressing down or dragging a widget const IS_POINTER_BUTTON_DOWN_ON = 1<<10; /// Was the underlying data changed? /// /// e.g. the slider was dragged, text was entered in a [`TextEdit`](crate::TextEdit) etc. /// Always `false` for something like a [`Button`](crate::Button). /// /// Note that this can be `true` even if the user did not interact with the widget, /// for instance if an existing slider value was clamped to the given range. const CHANGED = 1<<11; /// Should this container be closed? const CLOSE = 1<<12; } } impl Response { /// Returns true if this widget was clicked this frame by the primary button. /// /// A click is registered when the mouse or touch is released within /// a certain amount of time and distance from when and where it was pressed. /// /// This will also return true if the widget was clicked via accessibility integration, /// or if the widget had keyboard focus and the use pressed Space/Enter. /// /// Note that the widget must be sensing clicks with [`Sense::click`]. /// [`crate::Button`] senses clicks; [`crate::Label`] does not (unless you call [`crate::Label::sense`]). /// /// You can use [`Self::interact`] to sense more things *after* adding a widget. #[inline(always)] pub fn clicked(&self) -> bool { self.flags.contains(Flags::FAKE_PRIMARY_CLICKED) || self.clicked_by(PointerButton::Primary) } /// Returns true if this widget was clicked this frame by the given mouse button. /// /// This will NOT return true if the widget was "clicked" via /// some accessibility integration, or if the widget had keyboard focus and the /// user pressed Space/Enter. For that, use [`Self::clicked`] instead. /// /// This will likewise ignore the press-and-hold action on touch screens. /// Use [`Self::secondary_clicked`] instead to also detect that. #[inline] pub fn clicked_by(&self, button: PointerButton) -> bool { self.flags.contains(Flags::CLICKED) && self.ctx.input(|i| i.pointer.button_clicked(button)) } /// Returns true if this widget was clicked this frame by the secondary mouse button (e.g. the right mouse button). /// /// This also returns true if the widget was pressed-and-held on a touch screen. #[inline] pub fn secondary_clicked(&self) -> bool { self.flags.contains(Flags::LONG_TOUCHED) || self.clicked_by(PointerButton::Secondary) } /// Was this long-pressed on a touch screen? /// /// Usually you want to check [`Self::secondary_clicked`] instead. #[inline] pub fn long_touched(&self) -> bool { self.flags.contains(Flags::LONG_TOUCHED) } /// Returns true if this widget was clicked this frame by the middle mouse button. #[inline] pub fn middle_clicked(&self) -> bool { self.clicked_by(PointerButton::Middle) } /// Returns true if this widget was double-clicked this frame by the primary button. #[inline] pub fn double_clicked(&self) -> bool { self.double_clicked_by(PointerButton::Primary) } /// Returns true if this widget was triple-clicked this frame by the primary button. #[inline] pub fn triple_clicked(&self) -> bool { self.triple_clicked_by(PointerButton::Primary) } /// Returns true if this widget was double-clicked this frame by the given button. #[inline] pub fn double_clicked_by(&self, button: PointerButton) -> bool { self.flags.contains(Flags::CLICKED) && self.ctx.input(|i| i.pointer.button_double_clicked(button)) } /// Returns true if this widget was triple-clicked this frame by the given button. #[inline] pub fn triple_clicked_by(&self, button: PointerButton) -> bool { self.flags.contains(Flags::CLICKED) && self.ctx.input(|i| i.pointer.button_triple_clicked(button)) } /// Was this widget middle-clicked or clicked while holding down a modifier key? /// /// This is used by [`crate::Hyperlink`] to check if a URL should be opened /// in a new tab, using [`crate::OpenUrl::new_tab`]. pub fn clicked_with_open_in_background(&self) -> bool { self.middle_clicked() || self.clicked() && self.ctx.input(|i| i.modifiers.any()) } /// `true` if there was a click *outside* the rect of this widget. /// /// Clicks on widgets contained in this one counts as clicks inside this widget, /// so that clicking a button in an area will not be considered as clicking "elsewhere" from the area. /// /// Clicks on other layers above this widget *will* be considered as clicking elsewhere. pub fn clicked_elsewhere(&self) -> bool { let (pointer_interact_pos, any_click) = self .ctx .input(|i| (i.pointer.interact_pos(), i.pointer.any_click())); // We do not use self.clicked(), because we want to catch all clicks within our frame, // even if we aren't clickable (or even enabled). // This is important for windows and such that should close then the user clicks elsewhere. if any_click { if self.contains_pointer() || self.hovered() { false } else if let Some(pos) = pointer_interact_pos { let layer_under_pointer = self.ctx.layer_id_at(pos); if layer_under_pointer != Some(self.layer_id) { true } else { !self.interact_rect.contains(pos) } } else { false // clicked without a pointer, weird } } else { false } } /// Was the widget enabled? /// If false, there was no interaction attempted /// and the widget should be drawn in a gray disabled look. #[inline(always)] pub fn enabled(&self) -> bool { self.flags.contains(Flags::ENABLED) } /// The pointer is hovering above this widget or the widget was clicked/tapped this frame. /// /// In contrast to [`Self::contains_pointer`], this will be `false` whenever some other widget is being dragged. /// `hovered` is always `false` for disabled widgets. #[inline(always)] pub fn hovered(&self) -> bool { self.flags.contains(Flags::HOVERED) } /// Returns true if the pointer is contained by the response rect, and no other widget is covering it. /// /// In contrast to [`Self::hovered`], this can be `true` even if some other widget is being dragged. /// This means it is useful for styling things like drag-and-drop targets. /// `contains_pointer` can also be `true` for disabled widgets. /// /// This is slightly different from [`Ui::rect_contains_pointer`] and [`Context::rect_contains_pointer`], in that /// [`Self::contains_pointer`] also checks that no other widget is covering this response rectangle. #[inline(always)] pub fn contains_pointer(&self) -> bool { self.flags.contains(Flags::CONTAINS_POINTER) } /// The widget is highlighted via a call to [`Self::highlight`] or [`Context::highlight_widget`]. #[doc(hidden)] #[inline(always)] pub fn highlighted(&self) -> bool { self.flags.contains(Flags::HIGHLIGHTED) } /// This widget has the keyboard focus (i.e. is receiving key presses). /// /// This function only returns true if the UI as a whole (e.g. window) /// also has the keyboard focus. That makes this function suitable /// for style choices, e.g. a thicker border around focused widgets. pub fn has_focus(&self) -> bool { self.ctx.input(|i| i.focused) && self.ctx.memory(|mem| mem.has_focus(self.id)) } /// True if this widget has keyboard focus this frame, but didn't last frame. pub fn gained_focus(&self) -> bool { self.ctx.memory(|mem| mem.gained_focus(self.id)) } /// The widget had keyboard focus and lost it, /// either because the user pressed tab or clicked somewhere else, /// or (in case of a [`crate::TextEdit`]) because the user pressed enter. /// /// ``` /// # egui::__run_test_ui(|ui| { /// # let mut my_text = String::new(); /// # fn do_request(_: &str) {} /// let response = ui.text_edit_singleline(&mut my_text); /// if response.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) { /// do_request(&my_text); /// } /// # }); /// ``` pub fn lost_focus(&self) -> bool { self.ctx.memory(|mem| mem.lost_focus(self.id)) } /// Request that this widget get keyboard focus. pub fn request_focus(&self) { self.ctx.memory_mut(|mem| mem.request_focus(self.id)); } /// Surrender keyboard focus for this widget. pub fn surrender_focus(&self) { self.ctx.memory_mut(|mem| mem.surrender_focus(self.id)); } /// Did a drag on this widget begin this frame? /// /// This is only true if the widget sense drags. /// If the widget also senses clicks, this will only become true if the pointer has moved a bit. /// /// This will only be true for a single frame. #[inline] pub fn drag_started(&self) -> bool { self.flags.contains(Flags::DRAG_STARTED) } /// Did a drag on this widget by the button begin this frame? /// /// This is only true if the widget sense drags. /// If the widget also senses clicks, this will only become true if the pointer has moved a bit. /// /// This will only be true for a single frame. #[inline] pub fn drag_started_by(&self, button: PointerButton) -> bool { self.drag_started() && self.ctx.input(|i| i.pointer.button_down(button)) } /// The widget is being dragged. /// /// To find out which button(s), use [`Self::dragged_by`]. /// /// If the widget is only sensitive to drags, this is `true` as soon as the pointer presses down on it. /// If the widget also senses clicks, this won't be true until the pointer has moved a bit, /// or the user has pressed down for long enough. /// See [`crate::input_state::PointerState::is_decidedly_dragging`] for details. /// /// If you want to avoid the delay, use [`Self::is_pointer_button_down_on`] instead. /// /// If the widget is NOT sensitive to drags, this will always be `false`. /// [`crate::DragValue`] senses drags; [`crate::Label`] does not (unless you call [`crate::Label::sense`]). /// You can use [`Self::interact`] to sense more things *after* adding a widget. #[inline(always)] pub fn dragged(&self) -> bool { self.flags.contains(Flags::DRAGGED) } /// See [`Self::dragged`]. #[inline] pub fn dragged_by(&self, button: PointerButton) -> bool { self.dragged() && self.ctx.input(|i| i.pointer.button_down(button)) } /// The widget was being dragged, but now it has been released. #[inline] pub fn drag_stopped(&self) -> bool { self.flags.contains(Flags::DRAG_STOPPED) } /// The widget was being dragged by the button, but now it has been released. pub fn drag_stopped_by(&self, button: PointerButton) -> bool { self.drag_stopped() && self.ctx.input(|i| i.pointer.button_released(button)) } /// If dragged, how many points were we dragged in since last frame? #[inline] pub fn drag_delta(&self) -> Vec2 { if self.dragged() { let mut delta = self.ctx.input(|i| i.pointer.delta()); if let Some(from_global) = self.ctx.layer_transform_from_global(self.layer_id) { delta *= from_global.scaling; } delta } else { Vec2::ZERO } } /// If dragged, how many points have we been dragged since the start of the drag? #[inline] pub fn total_drag_delta(&self) -> Option<Vec2> { if self.dragged() { let mut delta = self.ctx.input(|i| i.pointer.total_drag_delta())?; if let Some(from_global) = self.ctx.layer_transform_from_global(self.layer_id) { delta *= from_global.scaling; } Some(delta) } else { None } } /// If dragged, how far did the mouse move since last frame? /// /// This will use raw mouse movement if provided by the integration, otherwise will fall back to [`Response::drag_delta`] /// Raw mouse movement is unaccelerated and unclamped by screen boundaries, and does not relate to any position on the screen. /// This may be useful in certain situations such as draggable values and 3D cameras, where screen position does not matter. #[inline] pub fn drag_motion(&self) -> Vec2 { if self.dragged() { self.ctx .input(|i| i.pointer.motion().unwrap_or_else(|| i.pointer.delta())) } else { Vec2::ZERO } } /// If the user started dragging this widget this frame, store the payload for drag-and-drop. #[doc(alias = "drag and drop")] pub fn dnd_set_drag_payload<Payload: Any + Send + Sync>(&self, payload: Payload) { if self.drag_started() { crate::DragAndDrop::set_payload(&self.ctx, payload); } if self.hovered() && !self.sense.senses_click() { // Things that can be drag-dropped should use the Grab cursor icon, // but if the thing is _also_ clickable, that can be annoying. self.ctx.set_cursor_icon(CursorIcon::Grab); } } /// Drag-and-Drop: Return what is being held over this widget, if any. /// /// Only returns something if [`Self::contains_pointer`] is true, /// and the user is drag-dropping something of this type. #[doc(alias = "drag and drop")] pub fn dnd_hover_payload<Payload: Any + Send + Sync>(&self) -> Option<Arc<Payload>> { // NOTE: we use `response.contains_pointer` here instead of `hovered`, because // `hovered` is always false when another widget is being dragged. if self.contains_pointer() { crate::DragAndDrop::payload::<Payload>(&self.ctx) } else { None } } /// Drag-and-Drop: Return what is being dropped onto this widget, if any. /// /// Only returns something if [`Self::contains_pointer`] is true, /// the user is drag-dropping something of this type, /// and they released it this frame. #[doc(alias = "drag and drop")] pub fn dnd_release_payload<Payload: Any + Send + Sync>(&self) -> Option<Arc<Payload>> { // NOTE: we use `response.contains_pointer` here instead of `hovered`, because // `hovered` is always false when another widget is being dragged. if self.contains_pointer() && self.ctx.input(|i| i.pointer.any_released()) { crate::DragAndDrop::take_payload::<Payload>(&self.ctx) } else { None } } /// Where the pointer (mouse/touch) were when this widget was clicked or dragged. /// /// `None` if the widget is not being interacted with. #[inline] pub fn interact_pointer_pos(&self) -> Option<Pos2> { self.interact_pointer_pos } /// If it is a good idea to show a tooltip, where is pointer? /// /// None if the pointer is outside the response area. #[inline] pub fn hover_pos(&self) -> Option<Pos2> { if self.hovered() { let mut pos = self.ctx.input(|i| i.pointer.hover_pos())?; if let Some(from_global) = self.ctx.layer_transform_from_global(self.layer_id) { pos = from_global * pos; } Some(pos) } else { None } } /// Is the pointer button currently down on this widget? /// /// This is true if the pointer is pressing down or dragging a widget, /// even when dragging outside the widget. /// /// This could also be thought of as "is this widget being interacted with?". #[inline(always)] pub fn is_pointer_button_down_on(&self) -> bool { self.flags.contains(Flags::IS_POINTER_BUTTON_DOWN_ON) } /// Was the underlying data changed? /// /// e.g. the slider was dragged, text was entered in a [`TextEdit`](crate::TextEdit) etc. /// Always `false` for something like a [`Button`](crate::Button). /// /// Can sometimes be `true` even though the data didn't changed /// (e.g. if the user entered a character and erased it the same frame). /// /// This is not set if the *view* of the data was changed. /// For instance, moving the cursor in a [`TextEdit`](crate::TextEdit) does not set this to `true`. /// /// Note that this can be `true` even if the user did not interact with the widget, /// for instance if an existing slider value was clamped to the given range. #[inline(always)] pub fn changed(&self) -> bool { self.flags.contains(Flags::CHANGED) } /// Report the data shown by this widget changed. /// /// This must be called by widgets that represent some mutable data, /// e.g. checkboxes, sliders etc. /// /// This should be called when the *content* changes, but not when the view does. /// So we call this when the text of a [`crate::TextEdit`], but not when the cursor changes. #[inline(always)] pub fn mark_changed(&mut self) { self.flags.set(Flags::CHANGED, true); } /// Should the container be closed? /// /// Will e.g. be set by calling [`Ui::close`] in a child [`Ui`] or by calling /// [`Self::set_close`]. pub fn should_close(&self) -> bool { self.flags.contains(Flags::CLOSE) } /// Set the [`Flags::CLOSE`] flag. /// /// Can be used to e.g. signal that a container should be closed. pub fn set_close(&mut self) { self.flags.set(Flags::CLOSE, true); } /// Show this UI if the widget was hovered (i.e. a tooltip). /// /// The text will not be visible if the widget is not enabled. /// For that, use [`Self::on_disabled_hover_ui`] instead. /// /// If you call this multiple times the tooltips will stack underneath the previous ones. /// /// The widget can contain interactive widgets, such as buttons and links. /// If so, it will stay open as the user moves their pointer over it. /// By default, the text of a tooltip is NOT selectable (i.e. interactive), /// but you can change this by setting [`style::Interaction::selectable_labels` from within the tooltip: /// /// ``` /// # egui::__run_test_ui(|ui| { /// ui.label("Hover me").on_hover_ui(|ui| { /// ui.style_mut().interaction.selectable_labels = true; /// ui.label("This text can be selected"); /// }); /// # }); /// ``` #[doc(alias = "tooltip")] pub fn on_hover_ui(self, add_contents: impl FnOnce(&mut Ui)) -> Self { Tooltip::for_enabled(&self).show(add_contents); self } /// Show this UI when hovering if the widget is disabled. pub fn on_disabled_hover_ui(self, add_contents: impl FnOnce(&mut Ui)) -> Self { Tooltip::for_disabled(&self).show(add_contents); self } /// Like `on_hover_ui`, but show the ui next to cursor. pub fn on_hover_ui_at_pointer(self, add_contents: impl FnOnce(&mut Ui)) -> Self { Tooltip::for_enabled(&self) .at_pointer() .gap(12.0) .show(add_contents); self } /// Always show this tooltip, even if disabled and the user isn't hovering it. /// /// This can be used to give attention to a widget during a tutorial. pub fn show_tooltip_ui(&self, add_contents: impl FnOnce(&mut Ui)) { Popup::from_response(self) .kind(PopupKind::Tooltip) .show(add_contents); } /// Always show this tooltip, even if disabled and the user isn't hovering it. /// /// This can be used to give attention to a widget during a tutorial. pub fn show_tooltip_text(&self, text: impl Into<WidgetText>) { self.show_tooltip_ui(|ui| { ui.label(text); }); } /// Was the tooltip open last frame? pub fn is_tooltip_open(&self) -> bool { Tooltip::was_tooltip_open_last_frame(&self.ctx, self.id) } /// Like `on_hover_text`, but show the text next to cursor. #[doc(alias = "tooltip")] pub fn on_hover_text_at_pointer(self, text: impl Into<WidgetText>) -> Self { self.on_hover_ui_at_pointer(|ui| { // Prevent `Area` auto-sizing from shrinking tooltips with dynamic content. // See https://github.com/emilk/egui/issues/5167 ui.set_max_width(ui.spacing().tooltip_width); ui.add(crate::widgets::Label::new(text)); }) } /// Show this text if the widget was hovered (i.e. a tooltip). /// /// The text will not be visible if the widget is not enabled. /// For that, use [`Self::on_disabled_hover_text`] instead. /// /// If you call this multiple times the tooltips will stack underneath the previous ones. #[doc(alias = "tooltip")] pub fn on_hover_text(self, text: impl Into<WidgetText>) -> Self { self.on_hover_ui(|ui| { // Prevent `Area` auto-sizing from shrinking tooltips with dynamic content. // See https://github.com/emilk/egui/issues/5167 ui.set_max_width(ui.spacing().tooltip_width); ui.add(crate::widgets::Label::new(text)); }) } /// Highlight this widget, to make it look like it is hovered, even if it isn't. /// /// The highlight takes one frame to take effect if you call this after the widget has been fully rendered. /// /// See also [`Context::highlight_widget`]. #[inline] pub fn highlight(mut self) -> Self { self.ctx.highlight_widget(self.id); self.flags.set(Flags::HIGHLIGHTED, true); self } /// Show this text when hovering if the widget is disabled. pub fn on_disabled_hover_text(self, text: impl Into<WidgetText>) -> Self { self.on_disabled_hover_ui(|ui| { // Prevent `Area` auto-sizing from shrinking tooltips with dynamic content. // See https://github.com/emilk/egui/issues/5167 ui.set_max_width(ui.spacing().tooltip_width); ui.add(crate::widgets::Label::new(text)); }) } /// When hovered, use this icon for the mouse cursor. #[inline] pub fn on_hover_cursor(self, cursor: CursorIcon) -> Self { if self.hovered() { self.ctx.set_cursor_icon(cursor); } self } /// When hovered or dragged, use this icon for the mouse cursor. #[inline] pub fn on_hover_and_drag_cursor(self, cursor: CursorIcon) -> Self { if self.hovered() || self.dragged() { self.ctx.set_cursor_icon(cursor); } self } /// Sense more interactions (e.g. sense clicks on a [`Response`] returned from a label). /// /// The interaction will occur on the same plane as the original widget, /// i.e. if the response was from a widget behind button, the interaction will also be behind that button. /// egui gives priority to the _last_ added widget (the one on top gets clicked first). /// /// Note that this call will not add any hover-effects to the widget, so when possible /// it is better to give the widget a [`Sense`] instead, e.g. using [`crate::Label::sense`]. /// /// Using this method on a `Response` that is the result of calling `union` on multiple `Response`s /// is undefined behavior. /// /// ``` /// # egui::__run_test_ui(|ui| { /// let horiz_response = ui.horizontal(|ui| { /// ui.label("hello"); /// }).response; /// assert!(!horiz_response.clicked()); // ui's don't sense clicks by default /// let horiz_response = horiz_response.interact(egui::Sense::click()); /// if horiz_response.clicked() { /// // The background behind the label was clicked /// } /// # }); /// ``` #[must_use] pub fn interact(&self, sense: Sense) -> Self { // We could check here if the new Sense equals the old one to avoid the extra create_widget // call. But that would break calling `interact` on a response from `Context::read_response` // or `Ui::response`. (See https://github.com/emilk/egui/pull/7713 for more details.) self.ctx.create_widget( WidgetRect { layer_id: self.layer_id, id: self.id, rect: self.rect, interact_rect: self.interact_rect, sense: self.sense | sense, enabled: self.enabled(), }, true, Default::default(), ) } /// Adjust the scroll position until this UI becomes visible. /// /// If `align` is [`Align::TOP`] it means "put the top of the rect at the top of the scroll area", etc. /// If `align` is `None`, it'll scroll enough to bring the UI into view. /// /// See also: [`Ui::scroll_to_cursor`], [`Ui::scroll_to_rect`]. [`Ui::scroll_with_delta`]. /// /// ``` /// # egui::__run_test_ui(|ui| { /// egui::ScrollArea::vertical().show(ui, |ui| { /// for i in 0..1000 { /// let response = ui.button("Scroll to me"); /// if response.clicked() { /// response.scroll_to_me(Some(egui::Align::Center)); /// } /// } /// }); /// # }); /// ``` pub fn scroll_to_me(&self, align: Option<Align>) { self.scroll_to_me_animation(align, self.ctx.global_style().scroll_animation); } /// Like [`Self::scroll_to_me`], but allows you to specify the [`crate::style::ScrollAnimation`]. pub fn scroll_to_me_animation( &self, align: Option<Align>, animation: crate::style::ScrollAnimation, ) { self.ctx.pass_state_mut(|state| { state.scroll_target[0] = Some(pass_state::ScrollTarget::new( self.rect.x_range(), align, animation, )); state.scroll_target[1] = Some(pass_state::ScrollTarget::new( self.rect.y_range(), align, animation, )); }); } /// For accessibility. /// /// Call after interacting and potential calls to [`Self::mark_changed`]. pub fn widget_info(&self, make_info: impl Fn() -> crate::WidgetInfo) { use crate::output::OutputEvent; let event = if self.clicked() { Some(OutputEvent::Clicked(make_info())) } else if self.double_clicked() { Some(OutputEvent::DoubleClicked(make_info())) } else if self.triple_clicked() { Some(OutputEvent::TripleClicked(make_info())) } else if self.gained_focus() { Some(OutputEvent::FocusGained(make_info())) } else if self.changed() { Some(OutputEvent::ValueChanged(make_info())) } else { None }; if let Some(event) = event { self.output_event(event); } else { self.ctx.accesskit_node_builder(self.id, |builder| { self.fill_accesskit_node_from_widget_info(builder, make_info()); }); self.ctx.register_widget_info(self.id, make_info); } } pub fn output_event(&self, event: crate::output::OutputEvent) { self.ctx.accesskit_node_builder(self.id, |builder| { self.fill_accesskit_node_from_widget_info(builder, event.widget_info().clone()); }); self.ctx .register_widget_info(self.id, || event.widget_info().clone()); self.ctx.output_mut(|o| o.events.push(event)); } pub(crate) fn fill_accesskit_node_common(&self, builder: &mut accesskit::Node) { if !self.enabled() { builder.set_disabled(); } builder.set_bounds(accesskit::Rect { x0: self.rect.min.x.into(), y0: self.rect.min.y.into(),
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
true
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/painter.rs
crates/egui/src/painter.rs
use std::sync::Arc; use emath::GuiRounding as _; use epaint::{ CircleShape, ClippedShape, CornerRadius, PathStroke, RectShape, Shape, Stroke, StrokeKind, text::{FontsView, Galley, LayoutJob}, }; use crate::{ Color32, Context, FontId, emath::{Align2, Pos2, Rangef, Rect, Vec2}, layers::{LayerId, PaintList, ShapeIdx}, }; /// Helper to paint shapes and text to a specific region on a specific layer. /// /// All coordinates are screen coordinates in the unit points (one point can consist of many physical pixels). /// /// A [`Painter`] never outlive a single frame/pass. #[derive(Clone)] pub struct Painter { /// Source of fonts and destination of shapes ctx: Context, /// For quick access, without having to go via [`Context`]. pixels_per_point: f32, /// Where we paint layer_id: LayerId, /// Everything painted in this [`Painter`] will be clipped against this. /// This means nothing outside of this rectangle will be visible on screen. clip_rect: Rect, /// If set, all shapes will have their colors modified to be closer to this. /// This is used to implement grayed out interfaces. fade_to_color: Option<Color32>, /// If set, all shapes will have their colors modified with [`Color32::gamma_multiply`] with /// this value as the factor. /// This is used to make interfaces semi-transparent. opacity_factor: f32, } impl Painter { /// Create a painter to a specific layer within a certain clip rectangle. pub fn new(ctx: Context, layer_id: LayerId, clip_rect: Rect) -> Self { let pixels_per_point = ctx.pixels_per_point(); Self { ctx, pixels_per_point, layer_id, clip_rect, fade_to_color: None, opacity_factor: 1.0, } } /// Redirect where you are painting. #[must_use] #[inline] pub fn with_layer_id(mut self, layer_id: LayerId) -> Self { self.layer_id = layer_id; self } /// Create a painter for a sub-region of this [`Painter`]. /// /// The clip-rect of the returned [`Painter`] will be the intersection /// of the given rectangle and the `clip_rect()` of the parent [`Painter`]. pub fn with_clip_rect(&self, rect: Rect) -> Self { let mut new_self = self.clone(); new_self.clip_rect = rect.intersect(self.clip_rect); new_self } /// Redirect where you are painting. /// /// It is undefined behavior to change the [`LayerId`] /// of [`crate::Ui::painter`]. pub fn set_layer_id(&mut self, layer_id: LayerId) { self.layer_id = layer_id; } /// If set, colors will be modified to look like this #[deprecated = "Use `multiply_opacity` instead"] pub fn set_fade_to_color(&mut self, fade_to_color: Option<Color32>) { self.fade_to_color = fade_to_color; } /// Set the opacity (alpha multiplier) of everything painted by this painter from this point forward. /// /// `opacity` must be between 0.0 and 1.0, where 0.0 means fully transparent (i.e., invisible) /// and 1.0 means fully opaque. /// /// See also: [`Self::opacity`] and [`Self::multiply_opacity`]. pub fn set_opacity(&mut self, opacity: f32) { if opacity.is_finite() { self.opacity_factor = opacity.clamp(0.0, 1.0); } } /// Like [`Self::set_opacity`], but multiplies the given value with the current opacity. /// /// See also: [`Self::set_opacity`] and [`Self::opacity`]. pub fn multiply_opacity(&mut self, opacity: f32) { if opacity.is_finite() { self.opacity_factor *= opacity.clamp(0.0, 1.0); } } /// Read the current opacity of the underlying painter. /// /// See also: [`Self::set_opacity`] and [`Self::multiply_opacity`]. #[inline] pub fn opacity(&self) -> f32 { self.opacity_factor } /// If `false`, nothing you paint will show up. /// /// Also checks [`Context::will_discard`]. pub fn is_visible(&self) -> bool { self.fade_to_color != Some(Color32::TRANSPARENT) && !self.ctx.will_discard() } /// If `false`, nothing added to the painter will be visible pub fn set_invisible(&mut self) { self.fade_to_color = Some(Color32::TRANSPARENT); } /// Get a reference to the parent [`Context`]. #[inline] pub fn ctx(&self) -> &Context { &self.ctx } /// Number of physical pixels for each logical UI point. #[inline] pub fn pixels_per_point(&self) -> f32 { self.pixels_per_point } /// Read-only access to the shared [`FontsView`]. /// /// See [`Context`] documentation for how locks work. #[inline] pub fn fonts<R>(&self, reader: impl FnOnce(&FontsView<'_>) -> R) -> R { self.ctx.fonts(reader) } /// Read-write access to the shared [`FontsView`]. /// /// See [`Context`] documentation for how locks work. #[inline] pub fn fonts_mut<R>(&self, reader: impl FnOnce(&mut FontsView<'_>) -> R) -> R { self.ctx.fonts_mut(reader) } /// Where we paint #[inline] pub fn layer_id(&self) -> LayerId { self.layer_id } /// Everything painted in this [`Painter`] will be clipped against this. /// This means nothing outside of this rectangle will be visible on screen. #[inline] pub fn clip_rect(&self) -> Rect { self.clip_rect } /// Constrain the rectangle in which we can paint. /// /// Short for `painter.set_clip_rect(painter.clip_rect().intersect(new_clip_rect))`. /// /// See also: [`Self::clip_rect`] and [`Self::set_clip_rect`]. #[inline] pub fn shrink_clip_rect(&mut self, new_clip_rect: Rect) { self.clip_rect = self.clip_rect.intersect(new_clip_rect); } /// Everything painted in this [`Painter`] will be clipped against this. /// This means nothing outside of this rectangle will be visible on screen. /// /// Warning: growing the clip rect might cause unexpected results! /// When in doubt, use [`Self::shrink_clip_rect`] instead. #[inline] pub fn set_clip_rect(&mut self, clip_rect: Rect) { self.clip_rect = clip_rect; } /// Useful for pixel-perfect rendering of lines that are one pixel wide (or any odd number of pixels). #[inline] pub fn round_to_pixel_center(&self, point: f32) -> f32 { point.round_to_pixel_center(self.pixels_per_point()) } /// Useful for pixel-perfect rendering of lines that are one pixel wide (or any odd number of pixels). #[deprecated = "Use `emath::GuiRounding` with `painter.pixels_per_point()` instead"] #[inline] pub fn round_pos_to_pixel_center(&self, pos: Pos2) -> Pos2 { pos.round_to_pixel_center(self.pixels_per_point()) } /// Useful for pixel-perfect rendering of filled shapes. #[deprecated = "Use `emath::GuiRounding` with `painter.pixels_per_point()` instead"] #[inline] pub fn round_to_pixel(&self, point: f32) -> f32 { point.round_to_pixels(self.pixels_per_point()) } /// Useful for pixel-perfect rendering. #[deprecated = "Use `emath::GuiRounding` with `painter.pixels_per_point()` instead"] #[inline] pub fn round_vec_to_pixels(&self, vec: Vec2) -> Vec2 { vec.round_to_pixels(self.pixels_per_point()) } /// Useful for pixel-perfect rendering. #[deprecated = "Use `emath::GuiRounding` with `painter.pixels_per_point()` instead"] #[inline] pub fn round_pos_to_pixels(&self, pos: Pos2) -> Pos2 { pos.round_to_pixels(self.pixels_per_point()) } /// Useful for pixel-perfect rendering. #[deprecated = "Use `emath::GuiRounding` with `painter.pixels_per_point()` instead"] #[inline] pub fn round_rect_to_pixels(&self, rect: Rect) -> Rect { rect.round_to_pixels(self.pixels_per_point()) } } /// ## Low level impl Painter { #[inline] fn paint_list<R>(&self, writer: impl FnOnce(&mut PaintList) -> R) -> R { self.ctx.graphics_mut(|g| writer(g.entry(self.layer_id))) } fn transform_shape(&self, shape: &mut Shape) { if let Some(fade_to_color) = self.fade_to_color { tint_shape_towards(shape, fade_to_color); } if self.opacity_factor < 1.0 { multiply_opacity(shape, self.opacity_factor); } } /// It is up to the caller to make sure there is room for this. /// Can be used for free painting. /// NOTE: all coordinates are screen coordinates! pub fn add(&self, shape: impl Into<Shape>) -> ShapeIdx { if self.fade_to_color == Some(Color32::TRANSPARENT) || self.opacity_factor == 0.0 { self.paint_list(|l| l.add(self.clip_rect, Shape::Noop)) } else { let mut shape = shape.into(); self.transform_shape(&mut shape); self.paint_list(|l| l.add(self.clip_rect, shape)) } } /// Add many shapes at once. /// /// Calling this once is generally faster than calling [`Self::add`] multiple times. pub fn extend<I: IntoIterator<Item = Shape>>(&self, shapes: I) { if self.fade_to_color == Some(Color32::TRANSPARENT) || self.opacity_factor == 0.0 { return; } if self.fade_to_color.is_some() || self.opacity_factor < 1.0 { let shapes = shapes.into_iter().map(|mut shape| { self.transform_shape(&mut shape); shape }); self.paint_list(|l| l.extend(self.clip_rect, shapes)); } else { self.paint_list(|l| l.extend(self.clip_rect, shapes)); } } /// Modify an existing [`Shape`]. pub fn set(&self, idx: ShapeIdx, shape: impl Into<Shape>) { if self.fade_to_color == Some(Color32::TRANSPARENT) { return; } let mut shape = shape.into(); self.transform_shape(&mut shape); self.paint_list(|l| l.set(idx, self.clip_rect, shape)); } /// Access all shapes added this frame. pub fn for_each_shape(&self, mut reader: impl FnMut(&ClippedShape)) { self.ctx.graphics(|g| { if let Some(list) = g.get(self.layer_id) { for c in list.all_entries() { reader(c); } } }); } } /// ## Debug painting impl Painter { #[expect(clippy::needless_pass_by_value)] pub fn debug_rect(&self, rect: Rect, color: Color32, text: impl ToString) { self.rect( rect, 0.0, color.additive().linear_multiply(0.015), (1.0, color), StrokeKind::Outside, ); self.text( rect.min, Align2::LEFT_TOP, text.to_string(), FontId::monospace(12.0), color, ); } pub fn error(&self, pos: Pos2, text: impl std::fmt::Display) -> Rect { let color = self.ctx.global_style().visuals.error_fg_color; self.debug_text(pos, Align2::LEFT_TOP, color, format!("🔥 {text}")) } /// Text with a background. /// /// See also [`Context::debug_text`]. #[expect(clippy::needless_pass_by_value)] pub fn debug_text( &self, pos: Pos2, anchor: Align2, color: Color32, text: impl ToString, ) -> Rect { let galley = self.layout_no_wrap(text.to_string(), FontId::monospace(12.0), color); let rect = anchor.anchor_size(pos, galley.size()); let frame_rect = rect.expand(2.0); let is_text_bright = color.is_additive() || epaint::Rgba::from(color).intensity() > 0.5; let bg_color = if is_text_bright { Color32::from_black_alpha(150) } else { Color32::from_white_alpha(150) }; self.add(Shape::rect_filled(frame_rect, 0.0, bg_color)); self.galley(rect.min, galley, color); frame_rect } } /// # Paint different primitives impl Painter { /// Paints a line from the first point to the second. pub fn line_segment(&self, points: [Pos2; 2], stroke: impl Into<Stroke>) -> ShapeIdx { self.add(Shape::LineSegment { points, stroke: stroke.into(), }) } /// Paints a line connecting the points. /// NOTE: all coordinates are screen coordinates! pub fn line(&self, points: Vec<Pos2>, stroke: impl Into<PathStroke>) -> ShapeIdx { self.add(Shape::line(points, stroke)) } /// Paints a horizontal line. pub fn hline(&self, x: impl Into<Rangef>, y: f32, stroke: impl Into<Stroke>) -> ShapeIdx { self.add(Shape::hline(x, y, stroke)) } /// Paints a vertical line. pub fn vline(&self, x: f32, y: impl Into<Rangef>, stroke: impl Into<Stroke>) -> ShapeIdx { self.add(Shape::vline(x, y, stroke)) } pub fn circle( &self, center: Pos2, radius: f32, fill_color: impl Into<Color32>, stroke: impl Into<Stroke>, ) -> ShapeIdx { self.add(CircleShape { center, radius, fill: fill_color.into(), stroke: stroke.into(), }) } pub fn circle_filled( &self, center: Pos2, radius: f32, fill_color: impl Into<Color32>, ) -> ShapeIdx { self.add(CircleShape { center, radius, fill: fill_color.into(), stroke: Default::default(), }) } pub fn circle_stroke(&self, center: Pos2, radius: f32, stroke: impl Into<Stroke>) -> ShapeIdx { self.add(CircleShape { center, radius, fill: Default::default(), stroke: stroke.into(), }) } /// See also [`Self::rect_filled`] and [`Self::rect_stroke`]. pub fn rect( &self, rect: Rect, corner_radius: impl Into<CornerRadius>, fill_color: impl Into<Color32>, stroke: impl Into<Stroke>, stroke_kind: StrokeKind, ) -> ShapeIdx { self.add(RectShape::new( rect, corner_radius, fill_color, stroke, stroke_kind, )) } pub fn rect_filled( &self, rect: Rect, corner_radius: impl Into<CornerRadius>, fill_color: impl Into<Color32>, ) -> ShapeIdx { self.add(RectShape::filled(rect, corner_radius, fill_color)) } pub fn rect_stroke( &self, rect: Rect, corner_radius: impl Into<CornerRadius>, stroke: impl Into<Stroke>, stroke_kind: StrokeKind, ) -> ShapeIdx { self.add(RectShape::stroke(rect, corner_radius, stroke, stroke_kind)) } /// Show an arrow starting at `origin` and going in the direction of `vec`, with the length `vec.length()`. pub fn arrow(&self, origin: Pos2, vec: Vec2, stroke: impl Into<Stroke>) { use crate::emath::Rot2; let rot = Rot2::from_angle(std::f32::consts::TAU / 10.0); let tip_length = vec.length() / 4.0; let tip = origin + vec; let dir = vec.normalized(); let stroke = stroke.into(); self.line_segment([origin, tip], stroke); self.line_segment([tip, tip - tip_length * (rot * dir)], stroke); self.line_segment([tip, tip - tip_length * (rot.inverse() * dir)], stroke); } /// An image at the given position. /// /// `uv` should normally be `Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0))` /// unless you want to crop or flip the image. /// /// `tint` is a color multiplier. Use [`Color32::WHITE`] if you don't want to tint the image. /// /// Usually it is easier to use [`crate::Image::paint_at`] instead: /// /// ``` /// # egui::__run_test_ui(|ui| { /// # let rect = egui::Rect::from_min_size(Default::default(), egui::Vec2::splat(100.0)); /// egui::Image::new(egui::include_image!("../assets/ferris.png")) /// .corner_radius(5) /// .tint(egui::Color32::LIGHT_BLUE) /// .paint_at(ui, rect); /// # }); /// ``` pub fn image( &self, texture_id: epaint::TextureId, rect: Rect, uv: Rect, tint: Color32, ) -> ShapeIdx { self.add(Shape::image(texture_id, rect, uv, tint)) } } /// ## Text impl Painter { /// Lay out and paint some text. /// /// To center the text at the given position, use `Align2::CENTER_CENTER`. /// /// To find out the size of text before painting it, use /// [`Self::layout`] or [`Self::layout_no_wrap`]. /// /// Returns where the text ended up. #[expect(clippy::needless_pass_by_value)] pub fn text( &self, pos: Pos2, anchor: Align2, text: impl ToString, font_id: FontId, text_color: Color32, ) -> Rect { let galley = self.layout_no_wrap(text.to_string(), font_id, text_color); let rect = anchor.anchor_size(pos, galley.size()); self.galley(rect.min, galley, text_color); rect } /// Will wrap text at the given width and line break at `\n`. /// /// Paint the results with [`Self::galley`]. #[inline] #[must_use] pub fn layout( &self, text: String, font_id: FontId, color: crate::Color32, wrap_width: f32, ) -> Arc<Galley> { self.fonts_mut(|f| f.layout(text, font_id, color, wrap_width)) } /// Will line break at `\n`. /// /// Paint the results with [`Self::galley`]. #[inline] #[must_use] pub fn layout_no_wrap( &self, text: String, font_id: FontId, color: crate::Color32, ) -> Arc<Galley> { self.fonts_mut(|f| f.layout(text, font_id, color, f32::INFINITY)) } /// Lay out this text layut job in a galley. /// /// Paint the results with [`Self::galley`]. #[inline] #[must_use] pub fn layout_job(&self, layout_job: LayoutJob) -> Arc<Galley> { self.fonts_mut(|f| f.layout_job(layout_job)) } /// Paint text that has already been laid out in a [`Galley`]. /// /// You can create the [`Galley`] with [`Self::layout`] or [`Self::layout_job`]. /// /// Any uncolored parts of the [`Galley`] (using [`Color32::PLACEHOLDER`]) will be replaced with the given color. /// /// Any non-placeholder color in the galley takes precedence over this fallback color. #[inline] pub fn galley(&self, pos: Pos2, galley: Arc<Galley>, fallback_color: Color32) { if !galley.is_empty() { self.add(Shape::galley(pos, galley, fallback_color)); } } /// Paint text that has already been laid out in a [`Galley`]. /// /// You can create the [`Galley`] with [`Self::layout`]. /// /// All text color in the [`Galley`] will be replaced with the given color. #[inline] pub fn galley_with_override_text_color( &self, pos: Pos2, galley: Arc<Galley>, text_color: Color32, ) { if !galley.is_empty() { self.add(Shape::galley_with_override_text_color( pos, galley, text_color, )); } } } fn tint_shape_towards(shape: &mut Shape, target: Color32) { epaint::shape_transform::adjust_colors(shape, move |color| { if *color != Color32::PLACEHOLDER { *color = crate::ecolor::tint_color_towards(*color, target); } }); } fn multiply_opacity(shape: &mut Shape, opacity: f32) { epaint::shape_transform::adjust_colors(shape, move |color| { if *color != Color32::PLACEHOLDER { *color = color.gamma_multiply(opacity); } }); }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/placer.rs
crates/egui/src/placer.rs
use crate::{Layout, Painter, Pos2, Rect, Region, Vec2, grid, vec2}; #[cfg(debug_assertions)] use crate::{Align2, Color32, Stroke}; pub(crate) struct Placer { /// If set this will take precedence over [`crate::layout`]. grid: Option<grid::GridLayout>, layout: Layout, region: Region, } impl Placer { pub(crate) fn new(max_rect: Rect, layout: Layout) -> Self { let region = layout.region_from_max_rect(max_rect); Self { grid: None, layout, region, } } #[inline(always)] pub(crate) fn set_grid(&mut self, grid: grid::GridLayout) { self.grid = Some(grid); } pub(crate) fn save_grid(&mut self) { if let Some(grid) = &mut self.grid { grid.save(); } } #[inline(always)] pub(crate) fn grid(&self) -> Option<&grid::GridLayout> { self.grid.as_ref() } #[inline(always)] pub(crate) fn is_grid(&self) -> bool { self.grid.is_some() } #[inline(always)] pub(crate) fn layout(&self) -> &Layout { &self.layout } #[inline(always)] pub(crate) fn prefer_right_to_left(&self) -> bool { self.layout.prefer_right_to_left() } #[inline(always)] pub(crate) fn min_rect(&self) -> Rect { self.region.min_rect } #[inline(always)] pub(crate) fn max_rect(&self) -> Rect { self.region.max_rect } #[inline(always)] pub(crate) fn force_set_min_rect(&mut self, min_rect: Rect) { self.region.min_rect = min_rect; } #[inline(always)] pub(crate) fn cursor(&self) -> Rect { self.region.cursor } #[inline(always)] pub(crate) fn set_cursor(&mut self, cursor: Rect) { self.region.cursor = cursor; } } impl Placer { pub(crate) fn align_size_within_rect(&self, size: Vec2, outer: Rect) -> Rect { if let Some(grid) = &self.grid { grid.align_size_within_rect(size, outer) } else { self.layout.align_size_within_rect(size, outer) } } pub(crate) fn available_rect_before_wrap(&self) -> Rect { if let Some(grid) = &self.grid { grid.available_rect(&self.region) } else { self.layout.available_rect_before_wrap(&self.region) } } /// Amount of space available for a widget. /// For wrapping layouts, this is the maximum (after wrap). pub(crate) fn available_size(&self) -> Vec2 { if let Some(grid) = &self.grid { grid.available_rect(&self.region).size() } else { self.layout.available_size(&self.region) } } /// Returns where to put the next widget that is of the given size. /// The returned `frame_rect` will always be justified along the cross axis. /// This is what you then pass to `advance_after_rects`. /// Use `justify_and_align` to get the inner `widget_rect`. pub(crate) fn next_space(&self, child_size: Vec2, item_spacing: Vec2) -> Rect { debug_assert!( 0.0 <= child_size.x && 0.0 <= child_size.y, "Negative child size: {child_size:?}" ); self.region.sanity_check(); if let Some(grid) = &self.grid { grid.next_cell(self.region.cursor, child_size) } else { self.layout .next_frame(&self.region, child_size, item_spacing) } } /// Where do we expect a zero-sized widget to be placed? pub(crate) fn next_widget_position(&self) -> Pos2 { if let Some(grid) = &self.grid { grid.next_cell(self.region.cursor, Vec2::ZERO).center() } else { self.layout.next_widget_position(&self.region) } } /// Apply justify or alignment after calling `next_space`. pub(crate) fn justify_and_align(&self, rect: Rect, child_size: Vec2) -> Rect { debug_assert!(!rect.any_nan(), "rect: {rect:?}"); debug_assert!(!child_size.any_nan(), "child_size is NaN: {child_size:?}"); if let Some(grid) = &self.grid { grid.justify_and_align(rect, child_size) } else { self.layout.justify_and_align(rect, child_size) } } /// Advance the cursor by this many points. /// [`Self::min_rect`] will expand to contain the cursor. /// /// Note that `advance_cursor` isn't supported when in a grid layout. pub(crate) fn advance_cursor(&mut self, amount: f32) { debug_assert!( self.grid.is_none(), "You cannot advance the cursor when in a grid layout" ); self.layout.advance_cursor(&mut self.region, amount); } /// Advance cursor after a widget was added to a specific rectangle /// and expand the region `min_rect`. /// /// * `frame_rect`: the frame inside which a widget was e.g. centered /// * `widget_rect`: the actual rect used by the widget pub(crate) fn advance_after_rects( &mut self, frame_rect: Rect, widget_rect: Rect, item_spacing: Vec2, ) { debug_assert!(!frame_rect.any_nan(), "frame_rect: {frame_rect:?}"); debug_assert!( !widget_rect.any_nan(), "widget_rect is NaN: {widget_rect:?}" ); self.region.sanity_check(); if let Some(grid) = &mut self.grid { grid.advance(&mut self.region.cursor, frame_rect, widget_rect); } else { self.layout.advance_after_rects( &mut self.region.cursor, frame_rect, widget_rect, item_spacing, ); } self.expand_to_include_rect(frame_rect); // e.g. for centered layouts: pretend we used whole frame self.region.sanity_check(); } /// Move to the next row in a grid layout or wrapping layout. /// Otherwise does nothing. pub(crate) fn end_row(&mut self, item_spacing: Vec2, painter: &Painter) { if let Some(grid) = &mut self.grid { grid.end_row(&mut self.region.cursor, painter); } else { self.layout.end_row(&mut self.region, item_spacing); } } /// Set row height in horizontal wrapping layout. pub(crate) fn set_row_height(&mut self, height: f32) { self.layout.set_row_height(&mut self.region, height); } } impl Placer { /// Expand the `min_rect` and `max_rect` of this ui to include a child at the given rect. pub(crate) fn expand_to_include_rect(&mut self, rect: Rect) { self.region.expand_to_include_rect(rect); } /// Expand the `min_rect` and `max_rect` of this ui to include a child at the given x-coordinate. pub(crate) fn expand_to_include_x(&mut self, x: f32) { self.region.expand_to_include_x(x); } /// Expand the `min_rect` and `max_rect` of this ui to include a child at the given y-coordinate. pub(crate) fn expand_to_include_y(&mut self, y: f32) { self.region.expand_to_include_y(y); } fn next_widget_space_ignore_wrap_justify(&self, size: Vec2) -> Rect { self.layout .next_widget_space_ignore_wrap_justify(&self.region, size) } /// Set the maximum width of the ui. /// You won't be able to shrink it below the current minimum size. pub(crate) fn set_max_width(&mut self, width: f32) { let rect = self.next_widget_space_ignore_wrap_justify(vec2(width, 0.0)); let region = &mut self.region; region.max_rect.min.x = rect.min.x; region.max_rect.max.x = rect.max.x; region.max_rect |= region.min_rect; // make sure we didn't shrink too much region.cursor.min.x = region.max_rect.min.x; region.cursor.max.x = region.max_rect.max.x; region.sanity_check(); } /// Set the maximum height of the ui. /// You won't be able to shrink it below the current minimum size. pub(crate) fn set_max_height(&mut self, height: f32) { let rect = self.next_widget_space_ignore_wrap_justify(vec2(0.0, height)); let region = &mut self.region; region.max_rect.min.y = rect.min.y; region.max_rect.max.y = rect.max.y; region.max_rect |= region.min_rect; // make sure we didn't shrink too much region.cursor.min.y = region.max_rect.min.y; region.cursor.max.y = region.max_rect.max.y; region.sanity_check(); } /// Set the minimum width of the ui. /// This can't shrink the ui, only make it larger. pub(crate) fn set_min_width(&mut self, width: f32) { if width <= 0.0 { return; } let rect = self.next_widget_space_ignore_wrap_justify(vec2(width, 0.0)); self.region.expand_to_include_x(rect.min.x); self.region.expand_to_include_x(rect.max.x); } /// Set the minimum height of the ui. /// This can't shrink the ui, only make it larger. pub(crate) fn set_min_height(&mut self, height: f32) { if height <= 0.0 { return; } let rect = self.next_widget_space_ignore_wrap_justify(vec2(0.0, height)); self.region.expand_to_include_y(rect.min.y); self.region.expand_to_include_y(rect.max.y); } } impl Placer { #[cfg(debug_assertions)] pub(crate) fn debug_paint_cursor(&self, painter: &crate::Painter, text: impl ToString) { let stroke = Stroke::new(1.0, Color32::DEBUG_COLOR); if let Some(grid) = &self.grid { let rect = grid.next_cell(self.cursor(), Vec2::splat(0.0)); painter.rect_stroke(rect, 1.0, stroke, epaint::StrokeKind::Inside); let align = Align2::CENTER_CENTER; painter.debug_text(align.pos_in_rect(&rect), align, stroke.color, text); } else { self.layout .paint_text_at_cursor(painter, &self.region, stroke, text); } } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/widget_style.rs
crates/egui/src/widget_style.rs
use emath::Vec2; use epaint::{Color32, FontId, Shadow, Stroke, text::TextWrapMode}; use crate::{ Frame, Response, Style, TextStyle, style::{WidgetVisuals, Widgets}, }; /// General text style pub struct TextVisuals { /// Font used pub font_id: FontId, /// Font color pub color: Color32, /// Text decoration pub underline: Stroke, pub strikethrough: Stroke, } /// General widget style pub struct WidgetStyle { pub frame: Frame, pub text: TextVisuals, pub stroke: Stroke, } pub struct ButtonStyle { pub frame: Frame, pub text_style: TextVisuals, } pub struct CheckboxStyle { /// Frame around pub frame: Frame, /// Text next to it pub text_style: TextVisuals, /// Checkbox size pub checkbox_size: f32, /// Checkmark size pub check_size: f32, /// Frame of the checkbox itself pub checkbox_frame: Frame, /// Checkmark stroke pub check_stroke: Stroke, } pub struct LabelStyle { /// Frame around pub frame: Frame, /// Text style pub text: TextVisuals, /// Wrap mode used pub wrap_mode: TextWrapMode, } pub struct SeparatorStyle { /// How much space is allocated in the layout direction pub spacing: f32, /// How to paint it pub stroke: Stroke, } #[derive(Default, Clone, Copy, Debug, PartialEq, Eq)] pub enum WidgetState { Noninteractive, #[default] Inactive, Hovered, Active, } impl Widgets { pub fn state(&self, state: WidgetState) -> &WidgetVisuals { match state { WidgetState::Noninteractive => &self.noninteractive, WidgetState::Inactive => &self.inactive, WidgetState::Hovered => &self.hovered, WidgetState::Active => &self.active, } } } impl Response { pub fn widget_state(&self) -> WidgetState { if !self.sense.interactive() { WidgetState::Noninteractive } else if self.is_pointer_button_down_on() || self.has_focus() || self.clicked() { WidgetState::Active } else if self.hovered() || self.highlighted() { WidgetState::Hovered } else { WidgetState::Inactive } } } impl Style { pub fn widget_style(&self, state: WidgetState) -> WidgetStyle { let visuals = self.visuals.widgets.state(state); let font_id = self.override_font_id.clone(); WidgetStyle { frame: Frame { fill: visuals.bg_fill, stroke: visuals.bg_stroke, corner_radius: visuals.corner_radius, inner_margin: self.spacing.button_padding.into(), ..Default::default() }, stroke: visuals.fg_stroke, text: TextVisuals { color: self .visuals .override_text_color .unwrap_or_else(|| visuals.text_color()), font_id: font_id.unwrap_or_else(|| TextStyle::Body.resolve(self)), strikethrough: Stroke::NONE, underline: Stroke::NONE, }, } } pub fn button_style(&self, state: WidgetState, selected: bool) -> ButtonStyle { let mut visuals = *self.visuals.widgets.state(state); let mut ws = self.widget_style(state); if selected { visuals.weak_bg_fill = self.visuals.selection.bg_fill; visuals.bg_fill = self.visuals.selection.bg_fill; visuals.fg_stroke = self.visuals.selection.stroke; ws.text.color = self.visuals.selection.stroke.color; } ButtonStyle { frame: Frame { fill: visuals.weak_bg_fill, stroke: visuals.bg_stroke, corner_radius: visuals.corner_radius, outer_margin: (-Vec2::splat(visuals.expansion)).into(), inner_margin: (self.spacing.button_padding + Vec2::splat(visuals.expansion) - Vec2::splat(visuals.bg_stroke.width)) .into(), ..Default::default() }, text_style: ws.text, } } pub fn checkbox_style(&self, state: WidgetState) -> CheckboxStyle { let visuals = self.visuals.widgets.state(state); let ws = self.widget_style(state); CheckboxStyle { frame: Frame::new(), checkbox_size: self.spacing.icon_width, check_size: self.spacing.icon_width_inner, checkbox_frame: Frame { fill: visuals.bg_fill, corner_radius: visuals.corner_radius, stroke: visuals.bg_stroke, // Use the inner_margin for the expansion inner_margin: visuals.expansion.into(), ..Default::default() }, text_style: ws.text, check_stroke: ws.stroke, } } pub fn label_style(&self, state: WidgetState) -> LabelStyle { let ws = self.widget_style(state); LabelStyle { frame: Frame { fill: ws.frame.fill, inner_margin: 0.0.into(), outer_margin: 0.0.into(), stroke: Stroke::NONE, shadow: Shadow::NONE, corner_radius: 0.into(), }, text: ws.text, wrap_mode: TextWrapMode::Wrap, } } pub fn separator_style(&self, _state: WidgetState) -> SeparatorStyle { let visuals = self.visuals.noninteractive(); SeparatorStyle { spacing: 6.0, stroke: visuals.bg_stroke, } } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/id.rs
crates/egui/src/id.rs
// TODO(emilk): have separate types `PositionId` and `UniqueId`. ? use std::num::NonZeroU64; /// egui tracks widgets frame-to-frame using [`Id`]s. /// /// For instance, if you start dragging a slider one frame, egui stores /// the sliders [`Id`] as the current active id so that next frame when /// you move the mouse the same slider changes, even if the mouse has /// moved outside the slider. /// /// For some widgets [`Id`]s are also used to persist some state about the /// widgets, such as Window position or whether not a collapsing header region is open. /// /// This implies that the [`Id`]s must be unique. /// /// For simple things like sliders and buttons that don't have any memory and /// doesn't move we can use the location of the widget as a source of identity. /// For instance, a slider only needs a unique and persistent ID while you are /// dragging the slider. As long as it is still while moving, that is fine. /// /// For things that need to persist state even after moving (windows, collapsing headers) /// the location of the widgets is obviously not good enough. For instance, /// a collapsing region needs to remember whether or not it is open even /// if the layout next frame is different and the collapsing is not lower down /// on the screen. /// /// Then there are widgets that need no identifiers at all, like labels, /// because they have no state nor are interacted with. /// /// This is niche-optimized to that `Option<Id>` is the same size as `Id`. #[derive(Clone, Copy, Hash, Eq, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct Id(NonZeroU64); impl nohash_hasher::IsEnabled for Id {} impl Id { /// A special [`Id`], in particular as a key to [`crate::Memory::data`] /// for when there is no particular widget to attach the data. /// /// The null [`Id`] is still a valid id to use in all circumstances, /// though obviously it will lead to a lot of collisions if you do use it! pub const NULL: Self = Self(NonZeroU64::MAX); #[inline] const fn from_hash(hash: u64) -> Self { if let Some(nonzero) = NonZeroU64::new(hash) { Self(nonzero) } else { Self(NonZeroU64::MIN) // The hash was exactly zero (very bad luck) } } /// Generate a new [`Id`] by hashing some source (e.g. a string or integer). pub fn new(source: impl std::hash::Hash) -> Self { Self::from_hash(ahash::RandomState::with_seeds(1, 2, 3, 4).hash_one(source)) } /// Generate a new [`Id`] by hashing the parent [`Id`] and the given argument. pub fn with(self, child: impl std::hash::Hash) -> Self { use std::hash::{BuildHasher as _, Hasher as _}; let mut hasher = ahash::RandomState::with_seeds(1, 2, 3, 4).build_hasher(); hasher.write_u64(self.0.get()); child.hash(&mut hasher); Self::from_hash(hasher.finish()) } /// Short and readable summary pub fn short_debug_format(&self) -> String { format!("{:04X}", self.value() as u16) } /// The inner value of the [`Id`]. /// /// This is a high-entropy hash, or [`Self::NULL`]. #[inline(always)] pub fn value(&self) -> u64 { self.0.get() } pub(crate) fn accesskit_id(&self) -> accesskit::NodeId { self.value().into() } /// Create a new [`Id`] from a high-entropy value. No hashing is done. /// /// This can be useful if you have an [`Id`] that was converted to some other type /// (e.g. accesskit::NodeId) and you want to convert it back to an [`Id`]. /// /// # Safety /// You need to ensure that the value is high-entropy since it might be used in /// a [`IdSet`] or [`IdMap`], which rely on the assumption that [`Id`]s have good entropy. /// /// The method is not unsafe in terms of memory safety. /// /// # Panics /// If the value is zero, this will panic. #[doc(hidden)] #[expect(unsafe_code)] pub unsafe fn from_high_entropy_bits(value: u64) -> Self { Self(NonZeroU64::new(value).expect("Id must be non-zero.")) } } impl std::fmt::Debug for Id { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{:04X}", self.value() as u16) } } /// Convenience impl From<&'static str> for Id { #[inline] fn from(string: &'static str) -> Self { Self::new(string) } } impl From<String> for Id { #[inline] fn from(string: String) -> Self { Self::new(string) } } #[test] fn id_size() { assert_eq!(std::mem::size_of::<Id>(), 8); assert_eq!(std::mem::size_of::<Option<Id>>(), 8); } // ---------------------------------------------------------------------------- /// `IdSet` is a `HashSet<Id>` optimized by knowing that [`Id`] has good entropy, and doesn't need more hashing. pub type IdSet = nohash_hasher::IntSet<Id>; /// `IdMap<V>` is a `HashMap<Id, V>` optimized by knowing that [`Id`] has good entropy, and doesn't need more hashing. pub type IdMap<V> = nohash_hasher::IntMap<Id, V>;
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/introspection.rs
crates/egui/src/introspection.rs
//! Showing UI:s for egui/epaint types. use crate::{ Color32, CursorIcon, FontFamily, FontId, Label, Mesh, NumExt as _, Rect, Response, Sense, Shape, Slider, TextStyle, TextWrapMode, Ui, Widget, epaint, memory, pos2, remap_clamp, vec2, }; pub fn font_family_ui(ui: &mut Ui, font_family: &mut FontFamily) { let families = ui.fonts(|f| f.families()); ui.horizontal(|ui| { for alternative in families { let text = alternative.to_string(); ui.radio_value(font_family, alternative, text); } }); } pub fn font_id_ui(ui: &mut Ui, font_id: &mut FontId) { let families = ui.fonts(|f| f.families()); ui.horizontal(|ui| { ui.add(Slider::new(&mut font_id.size, 4.0..=40.0).max_decimals(1)); for alternative in families { let text = alternative.to_string(); ui.radio_value(&mut font_id.family, alternative, text); } }); } // Show font texture in demo Ui pub(crate) fn font_texture_ui(ui: &mut Ui, [width, height]: [usize; 2]) -> Response { ui.vertical(|ui| { let color = if ui.visuals().dark_mode { Color32::WHITE } else { Color32::BLACK }; ui.label(format!("Texture size: {width} x {height} (hover to zoom)")); if width <= 1 || height <= 1 { return; } let mut size = vec2(width as f32, height as f32); if size.x > ui.available_width() { size *= ui.available_width() / size.x; } let (rect, response) = ui.allocate_at_least(size, Sense::hover()); let mut mesh = Mesh::default(); mesh.add_rect_with_uv(rect, [pos2(0.0, 0.0), pos2(1.0, 1.0)].into(), color); ui.painter().add(Shape::mesh(mesh)); let (tex_w, tex_h) = (width as f32, height as f32); response .on_hover_cursor(CursorIcon::ZoomIn) .on_hover_ui_at_pointer(|ui| { if let Some(pos) = ui.ctx().pointer_latest_pos() { let (_id, zoom_rect) = ui.allocate_space(vec2(128.0, 128.0)); let u = remap_clamp(pos.x, rect.x_range(), 0.0..=tex_w); let v = remap_clamp(pos.y, rect.y_range(), 0.0..=tex_h); let texel_radius = 32.0; let u = u.at_least(texel_radius).at_most(tex_w - texel_radius); let v = v.at_least(texel_radius).at_most(tex_h - texel_radius); let uv_rect = Rect::from_min_max( pos2((u - texel_radius) / tex_w, (v - texel_radius) / tex_h), pos2((u + texel_radius) / tex_w, (v + texel_radius) / tex_h), ); let mut mesh = Mesh::default(); mesh.add_rect_with_uv(zoom_rect, uv_rect, color); ui.painter().add(Shape::mesh(mesh)); } }); }) .response } impl Widget for &epaint::stats::PaintStats { fn ui(self, ui: &mut Ui) -> Response { ui.vertical(|ui| { ui.label( "egui generates intermediate level shapes like circles and text. \ These are later tessellated into triangles.", ); ui.add_space(10.0); ui.style_mut().override_text_style = Some(TextStyle::Monospace); let epaint::stats::PaintStats { shapes, shape_text, shape_path, shape_mesh, shape_vec, num_callbacks, text_shape_vertices, text_shape_indices, clipped_primitives, vertices, indices, } = self; ui.label("Intermediate:"); label(ui, shapes, "shapes").on_hover_text("Boxes, circles, etc"); ui.horizontal(|ui| { label(ui, shape_text, "text"); ui.small("(mostly cached)"); }); label(ui, shape_path, "paths"); label(ui, shape_mesh, "nested meshes"); label(ui, shape_vec, "nested shapes"); ui.label(format!("{num_callbacks:6} callbacks")); ui.add_space(10.0); ui.label("Text shapes:"); label(ui, text_shape_vertices, "vertices"); label(ui, text_shape_indices, "indices") .on_hover_text("Three 32-bit indices per triangles"); ui.add_space(10.0); ui.label("Tessellated (and culled):"); label(ui, clipped_primitives, "primitives lists") .on_hover_text("Number of separate clip rectangles"); label(ui, vertices, "vertices"); label(ui, indices, "indices").on_hover_text("Three 32-bit indices per triangles"); ui.add_space(10.0); // ui.label("Total:"); // ui.label(self.total().format("")); }) .response } } fn label(ui: &mut Ui, alloc_info: &epaint::stats::AllocInfo, what: &str) -> Response { ui.add(Label::new(alloc_info.format(what)).wrap_mode(TextWrapMode::Extend)) } impl Widget for &mut epaint::TessellationOptions { fn ui(self, ui: &mut Ui) -> Response { ui.vertical(|ui| { let epaint::TessellationOptions { feathering, feathering_size_in_pixels, coarse_tessellation_culling, prerasterized_discs, round_text_to_pixels, round_line_segments_to_pixels, round_rects_to_pixels, debug_paint_clip_rects, debug_paint_text_rects, debug_ignore_clip_rects, bezier_tolerance, epsilon: _, parallel_tessellation, validate_meshes, } = self; ui.horizontal(|ui| { ui.checkbox(feathering, "Feathering (antialias)") .on_hover_text("Apply feathering to smooth out the edges of shapes. Turn off for small performance gain."); if *feathering { ui.add(crate::DragValue::new(feathering_size_in_pixels).range(0.0..=10.0).speed(0.025).suffix(" px")); } }); ui.checkbox(prerasterized_discs, "Speed up filled circles with pre-rasterization"); ui.horizontal(|ui| { ui.label("Spline tolerance"); let speed = 0.01 * *bezier_tolerance; ui.add( crate::DragValue::new(bezier_tolerance).range(0.0001..=10.0) .speed(speed) ); }); ui.add_enabled(epaint::HAS_RAYON, crate::Checkbox::new(parallel_tessellation, "Parallelize tessellation") ).on_hover_text("Only available if epaint was compiled with the rayon feature") .on_disabled_hover_text("epaint was not compiled with the rayon feature"); ui.checkbox(validate_meshes, "Validate meshes").on_hover_text("Check that incoming meshes are valid, i.e. that all indices are in range, etc."); ui.collapsing("Align to pixel grid", |ui| { ui.checkbox(round_text_to_pixels, "Text") .on_hover_text("Most text already is, so don't expect to see a large change."); ui.checkbox(round_line_segments_to_pixels, "Line segments") .on_hover_text("Makes line segments appear crisp on any display."); ui.checkbox(round_rects_to_pixels, "Rectangles") .on_hover_text("Makes line segments appear crisp on any display."); }); ui.collapsing("Debug", |ui| { ui.checkbox( coarse_tessellation_culling, "Do coarse culling in the tessellator", ); ui.checkbox(debug_ignore_clip_rects, "Ignore clip rectangles"); ui.checkbox(debug_paint_clip_rects, "Paint clip rectangles"); ui.checkbox(debug_paint_text_rects, "Paint text bounds"); }); }) .response } } impl Widget for &memory::InteractionState { fn ui(self, ui: &mut Ui) -> Response { let memory::InteractionState { potential_click_id, potential_drag_id, } = self; ui.vertical(|ui| { ui.label(format!("potential_click_id: {potential_click_id:?}")); ui.label(format!("potential_drag_id: {potential_drag_id:?}")); }) .response } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/os.rs
crates/egui/src/os.rs
/// An `enum` of common operating systems. #[expect(clippy::upper_case_acronyms)] // `Ios` looks too ugly #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum OperatingSystem { /// Unknown OS - could be wasm Unknown, /// Android OS Android, /// Apple iPhone OS IOS, /// Linux or Unix other than Android Nix, /// macOS Mac, /// Windows Windows, } impl Default for OperatingSystem { fn default() -> Self { Self::from_target_os() } } impl OperatingSystem { /// Uses the compile-time `target_arch` to identify the OS. pub const fn from_target_os() -> Self { if cfg!(target_arch = "wasm32") { Self::Unknown } else if cfg!(target_os = "android") { Self::Android } else if cfg!(target_os = "ios") { Self::IOS } else if cfg!(target_os = "macos") { Self::Mac } else if cfg!(target_os = "windows") { Self::Windows } else if cfg!(target_os = "linux") || cfg!(target_os = "dragonfly") || cfg!(target_os = "freebsd") || cfg!(target_os = "netbsd") || cfg!(target_os = "openbsd") { Self::Nix } else { Self::Unknown } } /// Helper: try to guess from the user-agent of a browser. pub fn from_user_agent(user_agent: &str) -> Self { if user_agent.contains("Android") { Self::Android } else if user_agent.contains("like Mac") { Self::IOS } else if user_agent.contains("Win") { Self::Windows } else if user_agent.contains("Mac") { Self::Mac } else if user_agent.contains("Linux") || user_agent.contains("X11") || user_agent.contains("Unix") { Self::Nix } else { log::warn!( "egui: Failed to guess operating system from User-Agent {user_agent:?}. Please file an issue at https://github.com/emilk/egui/issues" ); Self::Unknown } } /// Are we either macOS or iOS? pub fn is_mac(&self) -> bool { matches!(self, Self::Mac | Self::IOS) } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/ui_builder.rs
crates/egui/src/ui_builder.rs
use std::{hash::Hash, sync::Arc}; use crate::ClosableTag; #[expect(unused_imports)] // Used for doclinks use crate::Ui; use crate::{Id, LayerId, Layout, Rect, Sense, Style, UiStackInfo}; /// Build a [`Ui`] as the child of another [`Ui`]. /// /// By default, everything is inherited from the parent, /// except for `max_rect` which by default is set to /// the parent [`Ui::available_rect_before_wrap`]. #[must_use] #[derive(Clone, Default)] pub struct UiBuilder { pub id_salt: Option<Id>, pub global_scope: bool, pub ui_stack_info: UiStackInfo, pub layer_id: Option<LayerId>, pub max_rect: Option<Rect>, pub layout: Option<Layout>, pub disabled: bool, pub invisible: bool, pub sizing_pass: bool, pub style: Option<Arc<Style>>, pub sense: Option<Sense>, pub accessibility_parent: Option<Id>, } impl UiBuilder { #[inline] pub fn new() -> Self { Self::default() } /// Seed the child `Ui` with this `id_salt`, which will be mixed /// with the [`Ui::id`] of the parent. /// /// You should give each [`Ui`] an `id_salt` that is unique /// within the parent, or give it none at all. #[inline] pub fn id_salt(mut self, id_salt: impl Hash) -> Self { self.id_salt = Some(Id::new(id_salt)); self } /// Set an id of the new `Ui` that is independent of the parent `Ui`. /// This way child widgets can be moved in the ui tree without losing state. /// You have to ensure that in a frame the child widgets do not get rendered in multiple places. /// /// You should set the same unique `id` at every place in the ui tree where you want the /// child widgets to share state. /// If the child widgets are not moved in the ui tree, use [`UiBuilder::id_salt`] instead. /// /// This is a shortcut for `.id_salt(my_id).global_scope(true)`. #[inline] pub fn id(mut self, id: impl Hash) -> Self { self.id_salt = Some(Id::new(id)); self.global_scope = true; self } /// Make the new `Ui` child ids independent of the parent `Ui`. /// This way child widgets can be moved in the ui tree without losing state. /// You have to ensure that in a frame the child widgets do not get rendered in multiple places. /// /// You should set the same globally unique `id_salt` at every place in the ui tree where you want the /// child widgets to share state. #[inline] pub fn global_scope(mut self, global_scope: bool) -> Self { self.global_scope = global_scope; self } /// Provide some information about the new `Ui` being built. #[inline] pub fn ui_stack_info(mut self, ui_stack_info: UiStackInfo) -> Self { self.ui_stack_info = ui_stack_info; self } /// Show the [`Ui`] in a different [`LayerId`] from its parent. #[inline] pub fn layer_id(mut self, layer_id: LayerId) -> Self { self.layer_id = Some(layer_id); self } /// Set the max rectangle, within which widgets will go. /// /// New widgets will *try* to fit within this rectangle. /// /// Text labels will wrap to fit within `max_rect`. /// Separator lines will span the `max_rect`. /// /// If a new widget doesn't fit within the `max_rect` then the /// [`Ui`] will make room for it by expanding both `min_rect` and /// /// If not set, this will be set to the parent /// [`Ui::available_rect_before_wrap`]. #[inline] pub fn max_rect(mut self, max_rect: Rect) -> Self { self.max_rect = Some(max_rect); self } /// Override the layout. /// /// Will otherwise be inherited from the parent. #[inline] pub fn layout(mut self, layout: Layout) -> Self { self.layout = Some(layout); self } /// Make the new `Ui` disabled, i.e. grayed-out and non-interactive. /// /// Note that if the parent `Ui` is disabled, the child will always be disabled. #[inline] pub fn disabled(mut self) -> Self { self.disabled = true; self } /// Make the contents invisible. /// /// Will also disable the `Ui` (see [`Self::disabled`]). /// /// If the parent `Ui` is invisible, the child will always be invisible. #[inline] pub fn invisible(mut self) -> Self { self.invisible = true; self.disabled = true; self } /// Set to true in special cases where we do one frame /// where we size up the contents of the Ui, without actually showing it. /// /// If the `sizing_pass` flag is set on the parent, /// the child will inherit it automatically. #[inline] pub fn sizing_pass(mut self) -> Self { self.sizing_pass = true; self } /// Override the style. /// /// Otherwise will inherit the style of the parent. #[inline] pub fn style(mut self, style: impl Into<Arc<Style>>) -> Self { self.style = Some(style.into()); self } /// Set if you want sense clicks and/or drags. Default is [`Sense::hover`]. /// /// The sense will be registered below the Senses of any widgets contained in this [`Ui`], so /// if the user clicks a button contained within this [`Ui`], that button will receive the click /// instead. /// /// The response can be read early with [`Ui::response`]. #[inline] pub fn sense(mut self, sense: Sense) -> Self { self.sense = Some(sense); self } /// Make this [`Ui`] closable. /// /// Calling [`Ui::close`] in a child [`Ui`] will mark this [`Ui`] for closing. /// After [`Ui::close`] was called, [`Ui::should_close`] and [`crate::Response::should_close`] will /// return `true` (for this frame). /// /// This works by adding a [`ClosableTag`] to the [`UiStackInfo`]. #[inline] pub fn closable(mut self) -> Self { self.ui_stack_info .tags .insert(ClosableTag::NAME, Some(Arc::new(ClosableTag::default()))); self } /// Set the accessibility parent for this [`Ui`]. /// /// This will override the automatic parent assignment for accessibility purposes. /// If not set, the parent [`Ui`]'s ID will be used as the accessibility parent. #[inline] pub fn accessibility_parent(mut self, parent_id: Id) -> Self { self.accessibility_parent = Some(parent_id); self } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/callstack.rs
crates/egui/src/callstack.rs
#[derive(Clone)] struct Frame { /// `_main` is usually as the deepest depth. depth: usize, name: String, file_and_line: String, } /// Capture a callstack, skipping the frames that are not interesting. /// /// In particular: slips everything before `egui::Context::run`, /// and skipping all frames in the `egui::` namespace. #[inline(never)] pub fn capture() -> String { let mut frames = vec![]; let mut depth = 0; backtrace::trace(|frame| { // Resolve this instruction pointer to a symbol name backtrace::resolve_frame(frame, |symbol| { let mut file_and_line = symbol.filename().map(shorten_source_file_path); if let Some(file_and_line) = &mut file_and_line && let Some(line_nr) = symbol.lineno() { file_and_line.push_str(&format!(":{line_nr}")); } let file_and_line = file_and_line.unwrap_or_default(); let name = symbol .name() .map(|name| clean_symbol_name(name.to_string())) .unwrap_or_default(); frames.push(Frame { depth, name, file_and_line, }); }); depth += 1; // note: we can resolve multiple symbols on the same frame. true // keep going to the next frame }); if frames.is_empty() { return "Failed to capture a backtrace. A common cause of this is compiling with panic=\"abort\" (https://github.com/rust-lang/backtrace-rs/issues/397)".to_owned(); } // Inclusive: let mut min_depth = 0; let mut max_depth = usize::MAX; for frame in &frames { if frame.name.starts_with("egui::callstack::capture") { min_depth = frame.depth + 1; } if frame.name.starts_with("egui::context::Context::run") { max_depth = frame.depth; } } /// Is this the name of some sort of useful entry point? fn is_start_name(name: &str) -> bool { name == "main" || name == "_main" || name.starts_with("eframe::run_native") || name.starts_with("egui::context::Context::run") } let mut has_kept_any_start_names = false; frames.reverse(); // main on top, i.e. chronological order. Same as Python. // Remove frames that are uninteresting: frames.retain(|frame| { // Keep the first "start" frame we can detect (e.g. `main`) to give the user a sense of chronology: if is_start_name(&frame.name) && !has_kept_any_start_names { has_kept_any_start_names = true; return true; } if frame.depth < min_depth || max_depth < frame.depth { return false; } // Remove stuff that isn't user calls: let skip_prefixes = [ // "backtrace::", // not needed, since we cut at egui::callstack::capture "egui::", "<egui::", "<F as egui::widgets::Widget>", "egui_plot::", "egui_extras::", "core::ptr::drop_in_place<egui::ui::Ui>", "eframe::", "core::ops::function::FnOnce::call_once", "<alloc::boxed::Box<F,A> as core::ops::function::FnOnce<Args>>::call_once", ]; for prefix in skip_prefixes { if frame.name.starts_with(prefix) { return false; } } true }); let mut deepest_depth = 0; let mut widest_file_line = 0; for frame in &frames { deepest_depth = frame.depth.max(deepest_depth); widest_file_line = frame.file_and_line.len().max(widest_file_line); } let widest_depth = deepest_depth.to_string().len(); let mut formatted = String::new(); if !frames.is_empty() { let mut last_depth = frames[0].depth; for frame in &frames { let Frame { depth, name, file_and_line, } = frame; if frame.depth + 1 < last_depth || last_depth + 1 < frame.depth { // Show that some frames were elided formatted.push_str(&format!("{:widest_depth$} …\n", "")); } formatted.push_str(&format!( "{depth:widest_depth$}: {file_and_line:widest_file_line$} {name}\n" )); last_depth = frame.depth; } } formatted } fn clean_symbol_name(mut s: String) -> String { // We get a hex suffix (at least on macOS) which is quite unhelpful, // e.g. `my_crate::my_function::h3bedd97b1e03baa5`. // Let's strip that. if let Some(h) = s.rfind("::h") { let hex = &s[h + 3..]; if hex.len() == 16 && hex.chars().all(|c| c.is_ascii_hexdigit()) { s.truncate(h); } } s } #[test] fn test_clean_symbol_name() { assert_eq!( clean_symbol_name("my_crate::my_function::h3bedd97b1e03baa5".to_owned()), "my_crate::my_function" ); } /// Shorten a path to a Rust source file from a callstack. /// /// Example input: /// * `/Users/emilk/.cargo/registry/src/github.com-1ecc6299db9ec823/tokio-1.24.1/src/runtime/runtime.rs` /// * `crates/rerun/src/main.rs` /// * `/rustc/d5a82bbd26e1ad8b7401f6a718a9c57c96905483/library/core/src/ops/function.rs` fn shorten_source_file_path(path: &std::path::Path) -> String { // Look for `src` and strip everything up to it. let components: Vec<_> = path.iter().map(|path| path.to_string_lossy()).collect(); let mut src_idx = None; for (i, c) in components.iter().enumerate() { if c == "src" { src_idx = Some(i); } } // Look for the last `src`: if let Some(src_idx) = src_idx { // Before `src` comes the name of the crate - let's include that: let first_index = src_idx.saturating_sub(1); let mut output = components[first_index].to_string(); for component in &components[first_index + 1..] { output.push('/'); output.push_str(component); } output } else { // No `src` directory found - weird! path.display().to_string() } } #[test] fn test_shorten_path() { for (before, after) in [ ( "/Users/emilk/.cargo/registry/src/github.com-1ecc6299db9ec823/tokio-1.24.1/src/runtime/runtime.rs", "tokio-1.24.1/src/runtime/runtime.rs", ), ("crates/rerun/src/main.rs", "rerun/src/main.rs"), ( "/rustc/d5a82bbd26e1ad8b7401f6a718a9c57c96905483/library/core/src/ops/function.rs", "core/src/ops/function.rs", ), ("/weird/path/file.rs", "/weird/path/file.rs"), ] { use std::str::FromStr as _; let before = std::path::PathBuf::from_str(before).unwrap(); assert_eq!(shorten_source_file_path(&before), after); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false