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/tests/egui_tests/tests/test_sides.rs
tests/egui_tests/tests/test_sides.rs
use egui::{TextWrapMode, Vec2, containers::Sides}; use egui_kittest::{Harness, SnapshotResults}; #[test] fn sides_container_tests() { let mut results = SnapshotResults::new(); test_variants("default", |sides| sides, &mut results); test_variants( "shrink_left", |sides| sides.shrink_left().truncate(), &mut results, ); test_variants( "shrink_right", |sides| sides.shrink_right().truncate(), &mut results, ); test_variants( "wrap_left", |sides| sides.shrink_left().wrap_mode(TextWrapMode::Wrap), &mut results, ); test_variants( "wrap_right", |sides| sides.shrink_right().wrap_mode(TextWrapMode::Wrap), &mut results, ); } fn test_variants( name: &str, mut create_sides: impl FnMut(Sides) -> Sides, results: &mut SnapshotResults, ) { for (variant_name, left_text, right_text, fit_contents) in [ ("short", "Left", "Right", false), ( "long", "Very long left content that should not fit.", "Very long right text that should also not fit.", false, ), ("short_fit_contents", "Left", "Right", true), ( "long_fit_contents", "Very long left content that should not fit.", "Very long right text that should also not fit.", true, ), ] { let mut harness = Harness::builder() .with_size(Vec2::new(400.0, 50.0)) .build_ui(|ui| { create_sides(Sides::new()).show( ui, |left| { left.label(left_text); }, |right| { right.label(right_text); }, ); }); if fit_contents { harness.fit_contents(); } results.add(harness.try_snapshot(format!("sides/{name}_{variant_name}"))); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/tests/egui_tests/tests/test_widgets.rs
tests/egui_tests/tests/test_widgets.rs
#![expect(clippy::unwrap_used)] // it's a test use egui::accesskit::Role; use egui::load::SizedTexture; use egui::{ Align, AtomExt as _, AtomLayout, Button, Color32, ColorImage, Direction, DragValue, Event, Grid, IntoAtoms as _, Layout, PointerButton, Response, Slider, Stroke, StrokeKind, TextEdit, TextWrapMode, TextureHandle, TextureOptions, Ui, UiBuilder, Vec2, Widget as _, include_image, }; use egui_kittest::kittest::{Queryable as _, by}; use egui_kittest::{Harness, Node, SnapshotResult, SnapshotResults}; #[test] fn widget_tests() { let mut results = SnapshotResults::new(); test_widget("button", |ui| ui.button("Button"), &mut results); test_widget( "button_image", |ui| { Button::image_and_text( include_image!("../../../crates/eframe/data/icon.png"), "Button", ) .ui(ui) }, &mut results, ); test_widget( "button_image_shortcut", |ui| { Button::image_and_text( include_image!("../../../crates/eframe/data/icon.png"), "Open", ) .shortcut_text("⌘O") .ui(ui) }, &mut results, ); results.add(VisualTests::test("button_image_shortcut_selected", |ui| { Button::image_and_text( include_image!("../../../crates/eframe/data/icon.png"), "Open", ) .shortcut_text("⌘O") .selected(true) .ui(ui) })); test_widget( "selectable_value", |ui| ui.selectable_label(false, "Selectable"), &mut results, ); test_widget( "selectable_value_selected", |ui| ui.selectable_label(true, "Selectable"), &mut results, ); test_widget( "checkbox", |ui| ui.checkbox(&mut false, "Checkbox"), &mut results, ); test_widget( "checkbox_checked", |ui| ui.checkbox(&mut true, "Checkbox"), &mut results, ); test_widget("radio", |ui| ui.radio(false, "Radio"), &mut results); test_widget("radio_checked", |ui| ui.radio(true, "Radio"), &mut results); test_widget( "drag_value", |ui| DragValue::new(&mut 12.0).ui(ui), &mut results, ); test_widget( "text_edit", |ui| { ui.spacing_mut().text_edit_width = 45.0; ui.text_edit_singleline(&mut "Hi!".to_owned()) }, &mut results, ); test_widget( "text_edit_clip", |ui| { ui.spacing_mut().text_edit_width = 45.0; TextEdit::singleline(&mut "This is a very very long text".to_owned()) .clip_text(true) .ui(ui) }, &mut results, ); test_widget( "text_edit_no_clip", |ui| { ui.spacing_mut().text_edit_width = 45.0; TextEdit::singleline(&mut "This is a very very long text".to_owned()) .clip_text(false) .ui(ui) }, &mut results, ); test_widget( "text_edit_placeholder_clip", |ui| { ui.spacing_mut().text_edit_width = 45.0; TextEdit::singleline(&mut String::new()) .hint_text("This is a very very long placeholder") .clip_text(true) .ui(ui) }, &mut results, ); test_widget( "slider", |ui| { ui.spacing_mut().slider_width = 45.0; Slider::new(&mut 12.0, 0.0..=100.0).ui(ui) }, &mut results, ); let source = include_image!("../../../crates/eframe/data/icon.png"); let interesting_atoms = vec![ ("minimal", ("Hello World!").into_atoms()), ( "image", (source.clone().atom_max_height(12.0), "With Image").into_atoms(), ), ( "multi_grow", ("g".atom_grow(true), "2", "g".atom_grow(true), "4").into_atoms(), ), ]; for atoms in interesting_atoms { results.add(test_widget_layout(&format!("atoms_{}", atoms.0), |ui| { AtomLayout::new(atoms.1.clone()).ui(ui) })); } } fn test_widget(name: &str, mut w: impl FnMut(&mut Ui) -> Response, results: &mut SnapshotResults) { results.add(test_widget_layout(name, &mut w)); results.add(VisualTests::test(name, &mut w)); } fn test_widget_layout(name: &str, mut w: impl FnMut(&mut Ui) -> Response) -> SnapshotResult { let test_size = Vec2::new(110.0, 45.0); struct Row { main_dir: Direction, main_align: Align, main_justify: bool, } struct Col { cross_align: Align, cross_justify: bool, } let mut rows = Vec::new(); let mut cols = Vec::new(); for main_justify in [false, true] { for main_dir in [ Direction::LeftToRight, Direction::TopDown, Direction::RightToLeft, Direction::BottomUp, ] { for main_align in [Align::Min, Align::Center, Align::Max] { rows.push(Row { main_dir, main_align, main_justify, }); } } } for cross_justify in [false, true] { for cross_align in [Align::Min, Align::Center, Align::Max] { cols.push(Col { cross_align, cross_justify, }); } } let mut harness = Harness::builder().build_ui(|ui| { egui_extras::install_image_loaders(ui.ctx()); { let mut wrap_test_size = test_size; wrap_test_size.x /= 3.0; ui.heading("Wrapping"); let modes = [ TextWrapMode::Extend, TextWrapMode::Truncate, TextWrapMode::Wrap, ]; Grid::new("wrapping") .spacing(Vec2::new(test_size.x / 2.0, 4.0)) .show(ui, |ui| { for mode in &modes { ui.label(format!("{mode:?}")); } ui.end_row(); for mode in &modes { let (_, rect) = ui.allocate_space(wrap_test_size); let mut child_ui = ui.new_child(UiBuilder::new().max_rect(rect)); child_ui.style_mut().wrap_mode = Some(*mode); w(&mut child_ui); ui.painter().rect_stroke( rect, 0.0, Stroke::new(1.0, Color32::WHITE), StrokeKind::Outside, ); } }); } ui.heading("Layout"); Grid::new("layout").striped(true).show(ui, |ui| { ui.label(""); for col in &cols { ui.label(format!( "cross_align: {:?}\ncross_justify:{:?}", col.cross_align, col.cross_justify )); } ui.end_row(); for row in &rows { ui.label(format!( "main_dir: {:?}\nmain_align: {:?}\nmain_justify: {:?}", row.main_dir, row.main_align, row.main_justify )); for col in &cols { let layout = Layout { main_dir: row.main_dir, main_align: row.main_align, main_justify: row.main_justify, cross_align: col.cross_align, cross_justify: col.cross_justify, main_wrap: false, }; let (_, rect) = ui.allocate_space(test_size); let mut child_ui = ui.new_child(UiBuilder::new().layout(layout).max_rect(rect)); w(&mut child_ui); ui.painter().rect_stroke( rect, 0.0, Stroke::new(1.0, Color32::WHITE), StrokeKind::Outside, ); } ui.end_row(); } }); }); harness.fit_contents(); harness.try_snapshot(format!("layout/{name}")) } /// Utility to create a snapshot test of the different states of a egui widget. /// This renders each state to a texture to work around the fact only a single widget can be /// hovered / pressed / focused at a time. struct VisualTests<'a> { name: String, w: &'a mut dyn FnMut(&mut Ui) -> Response, results: Vec<(String, ColorImage)>, } impl<'a> VisualTests<'a> { pub fn test(name: &str, mut w: impl FnMut(&mut Ui) -> Response) -> SnapshotResult { let mut vis = VisualTests::new(name, &mut w); vis.add_default_states(); vis.render() } pub fn new(name: &str, w: &'a mut dyn FnMut(&mut Ui) -> Response) -> Self { Self { name: name.to_owned(), w, results: Vec::new(), } } fn add_default_states(&mut self) { self.add("idle", |_| {}); self.add_node("hover", |node| { node.hover(); }); self.add("pressed", |harness| { harness.get_next_widget().hover(); let rect = harness.get_next_widget().rect(); harness.input_mut().events.push(Event::PointerButton { button: PointerButton::Primary, pos: rect.center(), pressed: true, modifiers: Default::default(), }); }); self.add_node("focussed", |node| { node.focus(); }); self.add_disabled(); } fn single_test(&mut self, f: impl FnOnce(&mut Harness<'_>), enabled: bool) -> ColorImage { let mut harness = Harness::builder().with_step_dt(0.05).build_ui(|ui| { egui_extras::install_image_loaders(ui.ctx()); ui.add_enabled_ui(enabled, |ui| { (self.w)(ui); }); }); harness.fit_contents(); // Wait for images to load harness.try_run_realtime().ok(); f(&mut harness); harness.run(); let image = harness.render().expect("Failed to render harness"); ColorImage::from_rgba_unmultiplied( [image.width() as usize, image.height() as usize], image.as_ref(), ) } pub fn add(&mut self, name: &str, test: impl FnOnce(&mut Harness<'_>)) { let image = self.single_test(test, true); self.results.push((name.to_owned(), image)); } pub fn add_disabled(&mut self) { let image = self.single_test(|_| {}, false); self.results.push(("disabled".to_owned(), image)); } pub fn add_node(&mut self, name: &str, test: impl FnOnce(&Node<'_>)) { self.add(name, |harness| { let node = harness.get_next_widget(); test(&node); }); } pub fn render(self) -> SnapshotResult { let mut results = Some(self.results); let mut images: Option<Vec<(String, TextureHandle, SizedTexture)>> = None; let mut harness = Harness::new_ui(|ui| { let results = images.get_or_insert_with(|| { results .take() .unwrap() .into_iter() .map(|(name, image)| { let size = Vec2::new(image.width() as f32, image.height() as f32); let texture_handle = ui.ctx() .load_texture(name.clone(), image, TextureOptions::default()); let texture = SizedTexture::new(texture_handle.id(), size); (name.clone(), texture_handle, texture) }) .collect() }); Grid::new("results").show(ui, |ui| { for (name, _, image) in results { ui.label(&*name); ui.scope(|ui| { ui.image(*image); }); ui.end_row(); } }); }); harness.fit_contents(); harness.try_snapshot(format!("visuals/{}", self.name)) } } trait HarnessExt { fn get_next_widget(&self) -> Node<'_>; } impl HarnessExt for Harness<'_> { fn get_next_widget(&self) -> Node<'_> { self.get_all(by().predicate(|node| node.role() != Role::GenericContainer)) .next() .unwrap() } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/tests/test_inline_glow_paint/src/main.rs
tests/test_inline_glow_paint/src/main.rs
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] // hide console window on Windows in release #![expect( // it's a test: clippy::undocumented_unsafe_blocks, clippy::unwrap_used, rustdoc::missing_crate_level_docs )] // Test that we can paint to the screen using glow directly. use eframe::egui; use eframe::glow; fn main() -> Result<(), Box<dyn std::error::Error>> { env_logger::init(); // Log to stderr (if you run with `RUST_LOG=debug`). let options = eframe::NativeOptions { renderer: eframe::Renderer::Glow, ..Default::default() }; eframe::run_native( "My test app", options, Box::new(|_cc| Ok(Box::<MyTestApp>::default())), )?; Ok(()) } #[derive(Default)] struct MyTestApp {} impl eframe::App for MyTestApp { fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { use glow::HasContext as _; let gl = frame.gl().unwrap(); #[expect(unsafe_code)] unsafe { gl.disable(glow::SCISSOR_TEST); gl.viewport(0, 0, 100, 100); gl.clear_color(1.0, 0.0, 1.0, 1.0); // purple gl.clear(glow::COLOR_BUFFER_BIT); } egui::Window::new("Floating Window").show(ui.ctx(), |ui| { ui.label("The background should be purple."); }); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/tests/test_egui_extras_compilation/src/main.rs
tests/test_egui_extras_compilation/src/main.rs
//! Regression test for <https://github.com/emilk/egui/issues/4771> fn main() {}
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/tests/test_size_pass/src/main.rs
tests/test_size_pass/src/main.rs
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] // hide console window on Windows in release #![expect(rustdoc::missing_crate_level_docs)] // it's a test use eframe::egui; fn main() -> eframe::Result { env_logger::init(); // Use `RUST_LOG=debug` to see logs. let options = eframe::NativeOptions::default(); eframe::run_ui_native("My egui App", options, move |ui, _frame| { // A bottom panel to force the tooltips to consider if the fit below or under the widget: egui::Panel::bottom("bottom").show_inside(ui, |ui| { ui.horizontal(|ui| { ui.vertical(|ui| { ui.label("Single tooltips:"); for i in 0..3 { ui.label(format!("Hover label {i} for a tooltip")) .on_hover_text("There is some text here"); } }); ui.vertical(|ui| { ui.label("Double tooltips:"); for i in 0..3 { ui.label(format!("Hover label {i} for two tooltips")) .on_hover_text("First tooltip") .on_hover_text("Second tooltip"); } }); }); ui.with_layout(egui::Layout::right_to_left(egui::Align::BOTTOM), |ui| { ui.label("Hover for tooltip") .on_hover_text("This is a rather long tooltip that needs careful positioning."); }); }); egui::CentralPanel::default().show_inside(ui, |ui| { ui.horizontal(|ui| { if ui.button("Reset egui memory").clicked() { ui.memory_mut(|mem| *mem = Default::default()); } ui.with_layout(egui::Layout::right_to_left(egui::Align::BOTTOM), |ui| { ui.label("Hover for tooltip").on_hover_text( "This is a rather long tooltip that needs careful positioning.", ); ui.label("Hover for interactive tooltip").on_hover_ui(|ui| { ui.label("This tooltip has a button:"); let _ = ui.button("Clicking me does nothing"); }); }); }); let has_tooltip = ui .label("This label has a tooltip at the mouse cursor") .on_hover_text_at_pointer("Told you!") .is_tooltip_open(); let response = ui.label("This label gets a tooltip when the previous label is hovered"); if has_tooltip { response.show_tooltip_text("The ever-present tooltip!"); } ui.separator(); ui.label("The menu should be as wide as the widest button"); ui.menu_button("Click for menu", |ui| { let _ = ui.button("Narrow").clicked(); let _ = ui.button("Very wide text").clicked(); let _ = ui.button("Narrow").clicked(); }); ui.label("Hover for tooltip").on_hover_ui(|ui| { ui.label("A separator:"); ui.separator(); }); ui.separator(); let alternatives = [ "Short", "Min", "Very very long text that will extend", "Short", ]; let mut selected = 1; egui::ComboBox::from_label("ComboBox").show_index( ui, &mut selected, alternatives.len(), |i| alternatives[i], ); egui::ComboBox::from_id_salt("combo") .selected_text("ComboBox") .width(100.0) .show_ui(ui, |ui| { ui.debug_painter() .debug_rect(ui.max_rect(), egui::Color32::RED, ""); ui.label("Hello"); ui.label("World"); ui.label("Hellooooooooooooooooooooooooo"); }); ui.separator(); let time = ui.input(|i| i.time); ui.label("Hover for a tooltip with changing content") .on_hover_text(format!("A number: {}", time % 10.0)); }); }) }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/tests/test_viewports/src/main.rs
tests/test_viewports/src/main.rs
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] // hide console window on Windows in release #![expect(clippy::unwrap_used, rustdoc::missing_crate_level_docs)] // it's a test use std::sync::Arc; use eframe::egui; use egui::{Id, InnerResponse, UiBuilder, ViewportBuilder, ViewportId, mutex::RwLock}; // Drag-and-drop between windows is not yet implemented, but if you wanna work on it, enable this: pub const DRAG_AND_DROP_TEST: bool = false; fn main() { env_logger::init(); // Use `RUST_LOG=debug` to see logs. let _ = eframe::run_native( "Viewports", eframe::NativeOptions { viewport: egui::ViewportBuilder::default().with_inner_size([450.0, 400.0]), #[cfg(feature = "wgpu")] renderer: eframe::Renderer::Wgpu, ..Default::default() }, Box::new(|_cc| Ok(Box::<App>::default())), ); } pub struct ViewportState { pub id: ViewportId, pub visible: bool, pub immediate: bool, pub title: String, pub children: Vec<Arc<RwLock<Self>>>, } impl ViewportState { pub fn new_deferred( title: &'static str, children: Vec<Arc<RwLock<Self>>>, ) -> Arc<RwLock<Self>> { Arc::new(RwLock::new(Self { id: ViewportId::from_hash_of(title), visible: false, immediate: false, title: title.into(), children, })) } pub fn new_immediate( title: &'static str, children: Vec<Arc<RwLock<Self>>>, ) -> Arc<RwLock<Self>> { Arc::new(RwLock::new(Self { id: ViewportId::from_hash_of(title), visible: false, immediate: true, title: title.into(), children, })) } pub fn show(vp_state: Arc<RwLock<Self>>, ctx: &egui::Context, close_button: bool) { if !vp_state.read().visible { return; } let vp_id = vp_state.read().id; let immediate = vp_state.read().immediate; let title = vp_state.read().title.clone(); let viewport = ViewportBuilder::default() .with_title(&title) .with_close_button(close_button) .with_inner_size([500.0, 500.0]); if immediate { let mut vp_state = vp_state.write(); ctx.show_viewport_immediate(vp_id, viewport, move |ui, class| { if ui.input(|i| i.viewport().close_requested()) { vp_state.visible = false; } show_as_popup(ui, class, |ui: &mut egui::Ui| { generic_child_ui(ui, &mut vp_state, close_button); }); }); } else { let count = Arc::new(RwLock::new(0)); ctx.show_viewport_deferred(vp_id, viewport, move |ui, class| { let mut vp_state = vp_state.write(); if ui.input(|i| i.viewport().close_requested()) { vp_state.visible = false; } let count = Arc::clone(&count); show_as_popup(ui, class, move |ui: &mut egui::Ui| { let current_count = *count.read(); ui.label(format!("Callback has been reused {current_count} times")); *count.write() += 1; generic_child_ui(ui, &mut vp_state, close_button); }); }); } } pub fn set_visible_recursive(&mut self, visible: bool) { self.visible = visible; for child in &self.children { child.write().set_visible_recursive(true); } } } pub struct App { top: Vec<Arc<RwLock<ViewportState>>>, close_button: bool, } impl Default for App { fn default() -> Self { Self { top: vec![ ViewportState::new_deferred( "Top Deferred Viewport", vec![ ViewportState::new_deferred( "DD: Deferred Viewport in Deferred Viewport", vec![], ), ViewportState::new_immediate( "DS: Immediate Viewport in Deferred Viewport", vec![], ), ], ), ViewportState::new_immediate( "Top Immediate Viewport", vec![ ViewportState::new_deferred( "SD: Deferred Viewport in Immediate Viewport", vec![], ), ViewportState::new_immediate( "SS: Immediate Viewport in Immediate Viewport", vec![], ), ], ), ], close_button: true, } } } impl eframe::App for App { fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { egui::CentralPanel::default().show_inside(ui, |ui| { ui.heading("Root viewport"); { let mut embed_viewports = ui.embed_viewports(); ui.checkbox(&mut embed_viewports, "Embed all viewports"); if ui.button("Open all viewports").clicked() { for viewport in &self.top { viewport.write().set_visible_recursive(true); } } ui.set_embed_viewports(embed_viewports); } ui.checkbox(&mut self.close_button, "with close button"); generic_ui(ui, &self.top, self.close_button); }); } } /// This will make the content as a popup if cannot has his own native window fn show_as_popup( ui: &mut egui::Ui, class: egui::ViewportClass, content: impl FnOnce(&mut egui::Ui), ) { if class == egui::ViewportClass::EmbeddedWindow { // Not a real viewport - already has a frame content(ui); } else { egui::CentralPanel::default().show_inside(ui, content); } } fn generic_child_ui(ui: &mut egui::Ui, vp_state: &mut ViewportState, close_button: bool) { ui.horizontal(|ui| { ui.label("Title:"); if ui.text_edit_singleline(&mut vp_state.title).changed() { // Title changes ui.send_viewport_cmd_to( vp_state.id, egui::ViewportCommand::Title(vp_state.title.clone()), ); } }); generic_ui(ui, &vp_state.children, close_button); } fn generic_ui(ui: &mut egui::Ui, children: &[Arc<RwLock<ViewportState>>], close_button: bool) { let container_id = ui.id(); let ctx = ui.ctx().clone(); ui.label(format!( "Frame nr: {} (this increases when this viewport is being rendered)", ctx.cumulative_pass_nr() )); ui.horizontal(|ui| { let mut show_spinner = ui.data_mut(|data| *data.get_temp_mut_or(container_id.with("show_spinner"), false)); ui.checkbox(&mut show_spinner, "Show Spinner (forces repaint)"); if show_spinner { ui.spinner(); } ui.data_mut(|data| data.insert_temp(container_id.with("show_spinner"), show_spinner)); }); ui.add_space(8.0); ui.label(format!("Viewport Id: {:?}", ctx.viewport_id())); ui.label(format!( "Parent Viewport Id: {:?}", ctx.parent_viewport_id() )); ui.collapsing("Info", |ui| { ui.label(format!("zoom_factor: {}", ctx.zoom_factor())); ui.label(format!("pixels_per_point: {}", ctx.pixels_per_point())); if let Some(native_pixels_per_point) = ctx.input(|i| i.viewport().native_pixels_per_point) { ui.label(format!( "native_pixels_per_point: {native_pixels_per_point:?}" )); } if let Some(monitor_size) = ctx.input(|i| i.viewport().monitor_size) { ui.label(format!("monitor_size: {monitor_size:?} (points)")); } if let Some(viewport_rect) = ui.input(|i| i.raw.screen_rect) { ui.label(format!( "Viewport Rect: Pos: {:?}, Size: {:?} (points)", viewport_rect.min, viewport_rect.size() )); } if let Some(inner_rect) = ctx.input(|i| i.viewport().inner_rect) { ui.label(format!( "Inner Rect: Pos: {:?}, Size: {:?} (points)", inner_rect.min, inner_rect.size() )); } if let Some(outer_rect) = ctx.input(|i| i.viewport().outer_rect) { ui.label(format!( "Outer Rect: Pos: {:?}, Size: {:?} (points)", outer_rect.min, outer_rect.size() )); } }); if ctx.viewport_id() != ctx.parent_viewport_id() { let parent = ctx.parent_viewport_id(); if ui.button("Set parent pos 0,0").clicked() { ctx.send_viewport_cmd_to( parent, egui::ViewportCommand::OuterPosition(egui::pos2(0.0, 0.0)), ); } } if DRAG_AND_DROP_TEST { drag_and_drop_test(ui); } if !children.is_empty() { ui.separator(); ui.heading("Children:"); for child in children { let visible = { let mut child_lock = child.write(); let ViewportState { visible, title, .. } = &mut *child_lock; ui.checkbox(visible, title.as_str()); *visible }; if visible { ViewportState::show(Arc::clone(child), &ctx, close_button); } } } } // ---------------------------------------------------------------------------- // Drag-and-drop between windows is not yet implemented, but there is some test code for it here: fn drag_and_drop_test(ui: &mut egui::Ui) { use std::collections::HashMap; use std::sync::OnceLock; let container_id = ui.id(); const COLS: usize = 2; static DATA: OnceLock<RwLock<DragAndDrop>> = OnceLock::new(); let data = DATA.get_or_init(Default::default); data.write().init(container_id); #[derive(Default)] struct DragAndDrop { containers_data: HashMap<Id, Vec<Vec<Id>>>, data: HashMap<Id, String>, counter: usize, is_dragged: Option<Id>, } impl DragAndDrop { fn init(&mut self, container: Id) { if !self.containers_data.contains_key(&container) { for i in 0..COLS { self.insert( container, i, format!("From: {container:?}, and is: {}", self.counter), ); } } } fn insert(&mut self, container: Id, col: usize, value: impl Into<String>) { assert!(col < COLS, "The coll should be less than: {COLS}"); let value: String = value.into(); let id = Id::new(format!("%{}% {}", self.counter, &value)); self.data.insert(id, value); let viewport_data = self.containers_data.entry(container).or_insert_with(|| { let mut res = Vec::new(); res.resize_with(COLS, Default::default); res }); self.counter += 1; viewport_data[col].push(id); } fn cols(&self, container: Id, col: usize) -> Vec<(Id, String)> { assert!(col < COLS, "The col should be less than: {COLS}"); let container_data = &self.containers_data[&container]; container_data[col] .iter() .map(|id| (*id, self.data[id].clone())) .collect() } /// Move element ID to Viewport and col fn mov(&mut self, to: Id, col: usize) { let Some(id) = self.is_dragged.take() else { return; }; assert!(col < COLS, "The col should be less than: {COLS}"); // Should be a better way to do this! #[expect(clippy::iter_over_hash_type)] for container_data in self.containers_data.values_mut() { for ids in container_data { ids.retain(|i| *i != id); } } if let Some(container_data) = self.containers_data.get_mut(&to) { container_data[col].push(id); } } fn dragging(&mut self, id: Id) { self.is_dragged = Some(id); } } ui.separator(); ui.label("Drag and drop:"); ui.columns(COLS, |ui| { for col in 0..COLS { let data = DATA.get().unwrap(); let ui = &mut ui[col]; let mut is_dragged = None; let res = drop_target(ui, |ui| { ui.set_min_height(60.0); for (id, value) in data.read().cols(container_id, col) { drag_source(ui, id, |ui| { ui.add(egui::Label::new(value).sense(egui::Sense::click())); if ui.ctx().is_being_dragged(id) { is_dragged = Some(id); } }); } }); if let Some(id) = is_dragged { data.write().dragging(id); } if res.response.hovered() && ui.input(|i| i.pointer.any_released()) { data.write().mov(container_id, col); } } }); } // This is taken from crates/egui_demo_lib/src/debo/drag_and_drop.rs fn drag_source<R>( ui: &mut egui::Ui, id: egui::Id, body: impl FnOnce(&mut egui::Ui) -> R, ) -> InnerResponse<R> { let is_being_dragged = ui.ctx().is_being_dragged(id); if !is_being_dragged { let res = ui.scope(body); // Check for drags: let response = ui.interact(res.response.rect, id, egui::Sense::drag()); if response.hovered() { ui.set_cursor_icon(egui::CursorIcon::Grab); } res } else { ui.set_cursor_icon(egui::CursorIcon::Grabbing); // Paint the body to a new layer: let layer_id = egui::LayerId::new(egui::Order::Tooltip, id); let res = ui.scope_builder(UiBuilder::new().layer_id(layer_id), body); if let Some(pointer_pos) = ui.ctx().pointer_interact_pos() { let delta = pointer_pos - res.response.rect.center(); ui.ctx().set_transform_layer( layer_id, eframe::emath::TSTransform::from_translation(delta), ); } res } } // TODO(emilk): Update to be more like `crates/egui_demo_lib/src/debo/drag_and_drop.rs` fn drop_target<R>( ui: &mut egui::Ui, body: impl FnOnce(&mut egui::Ui) -> R, ) -> egui::InnerResponse<R> { let is_being_dragged = ui.ctx().dragged_id().is_some(); let margin = egui::Vec2::splat(ui.visuals().clip_rect_margin); // 3.0 let background_id = ui.painter().add(egui::Shape::Noop); let available_rect = ui.available_rect_before_wrap(); let inner_rect = available_rect.shrink2(margin); let mut content_ui = ui.new_child(UiBuilder::new().max_rect(inner_rect)); let ret = body(&mut content_ui); let outer_rect = egui::Rect::from_min_max(available_rect.min, content_ui.min_rect().max + margin); let (rect, response) = ui.allocate_at_least(outer_rect.size(), egui::Sense::hover()); let style = if is_being_dragged && response.hovered() { ui.visuals().widgets.active } else { ui.visuals().widgets.inactive }; let fill = style.bg_fill; let stroke = style.bg_stroke; ui.painter().set( background_id, egui::epaint::RectShape::new( rect, style.corner_radius, fill, stroke, egui::StrokeKind::Inside, ), ); egui::InnerResponse::new(ret, response) }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/tests/test_ui_stack/src/main.rs
tests/test_ui_stack/src/main.rs
#![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 use std::sync::Arc; use eframe::egui; use eframe::egui::{Rangef, Shape, UiKind}; use egui_extras::Column; fn main() -> eframe::Result { env_logger::init(); // Log to stderr (if you run with `RUST_LOG=debug`). let options = eframe::NativeOptions { viewport: egui::ViewportBuilder::default().with_inner_size([320.0, 240.0]), ..Default::default() }; eframe::run_native( "Stack Frame Demo", options, Box::new(|cc| { // This gives us image support: egui_extras::install_image_loaders(&cc.egui_ctx); Ok(Box::<MyApp>::default()) }), ) } #[derive(Default)] struct MyApp { show_settings: bool, show_inspection: bool, show_memory: bool, } impl eframe::App for MyApp { fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { ui.all_styles_mut(|style| style.interaction.tooltip_delay = 0.0); egui::Panel::left("side_panel_left").show_inside(ui, |ui| { ui.heading("Information"); ui.label( "This is a demo/test environment of the `UiStack` feature. The tables display \ the UI stack in various contexts. You can hover on the IDs to display the \ corresponding origin/`max_rect`.\n\n\ The \"Full span test\" labels showcase an implementation of full-span \ highlighting. Hover to see them in action!", ); ui.add_space(10.0); ui.checkbox(&mut self.show_settings, "🔧 Settings"); ui.checkbox(&mut self.show_inspection, "🔍 Inspection"); ui.checkbox(&mut self.show_memory, "📝 Memory"); ui.add_space(10.0); if ui.button("Reset egui memory").clicked() { ui.memory_mut(|mem| *mem = Default::default()); } ui.add_space(20.0); egui::ScrollArea::both().auto_shrink(false).show(ui, |ui| { stack_ui(ui); // full span test ui.add_space(20.0); full_span_widget(ui, false); // nested frames test ui.add_space(20.0); egui::Frame::new() .stroke(ui.visuals().noninteractive().bg_stroke) .inner_margin(4) .outer_margin(4) .show(ui, |ui| { full_span_widget(ui, false); stack_ui(ui); egui::Frame::new() .stroke(ui.visuals().noninteractive().bg_stroke) .inner_margin(8) .outer_margin(6) .show(ui, |ui| { full_span_widget(ui, false); stack_ui(ui); }); }); }); }); egui::Panel::right("side_panel_right").show_inside(ui, |ui| { egui::ScrollArea::both().auto_shrink(false).show(ui, |ui| { stack_ui(ui); // full span test ui.add_space(20.0); full_span_widget(ui, false); }); }); egui::CentralPanel::default().show_inside(ui, |ui| { egui::ScrollArea::both().auto_shrink(false).show(ui, |ui| { ui.label("stack here:"); stack_ui(ui); // full span test ui.add_space(20.0); full_span_widget(ui, false); // tooltip test ui.add_space(20.0); ui.label("Hover me").on_hover_ui(|ui| { full_span_widget(ui, true); ui.add_space(20.0); stack_ui(ui); }); // combobox test ui.add_space(20.0); egui::ComboBox::from_id_salt("combo_box") .selected_text("click me") .show_ui(ui, |ui| { full_span_widget(ui, true); ui.add_space(20.0); stack_ui(ui); }); // Ui nesting test ui.add_space(20.0); ui.label("UI nesting test:"); egui::Frame::new() .stroke(ui.visuals().noninteractive().bg_stroke) .inner_margin(4) .show(ui, |ui| { ui.horizontal(|ui| { ui.vertical(|ui| { ui.scope(stack_ui); }); }); }); // table test let mut cell_stack = None; ui.add_space(20.0); ui.label("Table test:"); egui_extras::TableBuilder::new(ui) .vscroll(false) .column(Column::auto()) .column(Column::auto()) .header(20.0, |mut header| { header.col(|ui| { ui.strong("column 1"); }); header.col(|ui| { ui.strong("column 2"); }); }) .body(|mut body| { body.row(20.0, |mut row| { row.col(|ui| { full_span_widget(ui, false); }); row.col(|ui| { ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend); ui.label("See stack below"); cell_stack = Some(Arc::clone(ui.stack())); }); }); }); if let Some(cell_stack) = cell_stack { ui.label("Cell's stack:"); stack_ui_impl(ui, &cell_stack); } }); }); egui::Panel::bottom("bottom_panel") .resizable(true) .show_inside(ui, |ui| { egui::ScrollArea::vertical() .auto_shrink(false) .show(ui, |ui| { stack_ui(ui); // full span test ui.add_space(20.0); full_span_widget(ui, false); }); }); egui::Window::new("Window") .pivot(egui::Align2::RIGHT_TOP) .show(ui.ctx(), |ui| { full_span_widget(ui, false); ui.add_space(20.0); stack_ui(ui); }); let ctx = ui.ctx().clone(); egui::Window::new("🔧 Settings") .open(&mut self.show_settings) .vscroll(true) .show(&ctx, |ui| { ctx.settings_ui(ui); }); egui::Window::new("🔍 Inspection") .open(&mut self.show_inspection) .vscroll(true) .show(&ctx, |ui| { ctx.inspection_ui(ui); }); egui::Window::new("📝 Memory") .open(&mut self.show_memory) .resizable(false) .show(&ctx, |ui| { ctx.memory_ui(ui); }); } } /// Demo of a widget that highlights its background all the way to the edge of its container when /// hovered. fn full_span_widget(ui: &mut egui::Ui, permanent: bool) { let bg_shape_idx = ui.painter().add(Shape::Noop); let response = ui.label("Full span test"); let ui_stack = ui.stack(); let rect = egui::Rect::from_x_y_ranges( full_span_horizontal_range(ui_stack), response.rect.y_range(), ); if permanent || response.hovered() { ui.painter().set( bg_shape_idx, Shape::rect_filled(rect, 0.0, ui.visuals().selection.bg_fill), ); } } /// Find the horizontal range of the enclosing container. fn full_span_horizontal_range(ui_stack: &egui::UiStack) -> Rangef { for node in ui_stack.iter() { if node.has_visible_frame() || node.is_panel_ui() || node.is_root_ui() || node.kind() == Some(UiKind::TableCell) { return (node.max_rect + node.frame().inner_margin).x_range(); } } // should never happen Rangef::EVERYTHING } fn stack_ui(ui: &mut egui::Ui) { let ui_stack = Arc::clone(ui.stack()); ui.scope(|ui| { stack_ui_impl(ui, &ui_stack); }); } fn stack_ui_impl(ui: &mut egui::Ui, stack: &egui::UiStack) { egui::Frame::new() .stroke(ui.style().noninteractive().fg_stroke) .inner_margin(4) .show(ui, |ui| { ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend); egui_extras::TableBuilder::new(ui) .column(Column::auto()) .column(Column::auto()) .column(Column::auto()) .column(Column::auto()) .column(Column::auto()) .column(Column::auto()) .header(20.0, |mut header| { header.col(|ui| { ui.strong("id"); }); header.col(|ui| { ui.strong("kind"); }); header.col(|ui| { ui.strong("stroke"); }); header.col(|ui| { ui.strong("inner"); }); header.col(|ui| { ui.strong("outer"); }); header.col(|ui| { ui.strong("direction"); }); }) .body(|mut body| { for node in stack.iter() { body.row(20.0, |mut row| { row.col(|ui| { if ui.label(format!("{:?}", node.id)).hovered() { ui.debug_painter().debug_rect( node.max_rect, egui::Color32::GREEN, "max", ); ui.debug_painter().circle_filled( node.min_rect.min, 2.0, egui::Color32::RED, ); } }); row.col(|ui| { let s = if let Some(kind) = node.kind() { format!("{kind:?}") } else { "-".to_owned() }; ui.label(s); }); row.col(|ui| { let frame = node.frame(); if frame.stroke == egui::Stroke::NONE { ui.label("-"); } else { let mut layout_job = egui::text::LayoutJob::default(); layout_job.append( "⬛ ", 0.0, egui::TextFormat::simple( egui::TextStyle::Body.resolve(ui.style()), frame.stroke.color, ), ); layout_job.append( format!("{}px", frame.stroke.width).as_str(), 0.0, egui::TextFormat::simple( egui::TextStyle::Body.resolve(ui.style()), ui.style().visuals.text_color(), ), ); ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend); ui.label(layout_job); } }); row.col(|ui| { ui.label(print_margin(&node.frame().inner_margin)); }); row.col(|ui| { ui.label(print_margin(&node.frame().outer_margin)); }); row.col(|ui| { ui.label(format!("{:?}", node.layout_direction)); }); }); } }); }); } fn print_margin(margin: &egui::Margin) -> String { if margin.is_same() { format!("{}px", margin.left) } else { let s1 = if margin.left == margin.right { format!("H: {}px", margin.left) } else { format!("L: {}px R: {}px", margin.left, margin.right) }; let s2 = if margin.top == margin.bottom { format!("V: {}px", margin.top) } else { format!("T: {}px B: {}px", margin.top, margin.bottom) }; format!("{s1} / {s2}") } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_glow/src/winit.rs
crates/egui_glow/src/winit.rs
pub use egui_winit::{self, EventResponse}; use egui::{ViewportId, ViewportOutput}; use egui_winit::winit; use crate::shader_version::ShaderVersion; /// Use [`egui`] from a [`glow`] app based on [`winit`]. pub struct EguiGlow { pub egui_ctx: egui::Context, pub egui_winit: egui_winit::State, pub painter: crate::Painter, viewport_info: egui::ViewportInfo, // output from the last update: shapes: Vec<egui::epaint::ClippedShape>, pixels_per_point: f32, textures_delta: egui::TexturesDelta, } impl EguiGlow { /// For automatic shader version detection set `shader_version` to `None`. pub fn new( event_loop: &winit::event_loop::ActiveEventLoop, gl: std::sync::Arc<glow::Context>, shader_version: Option<ShaderVersion>, native_pixels_per_point: Option<f32>, dithering: bool, ) -> Self { #[expect(clippy::unwrap_used)] // TODO(emilk): return error instead of unwrap let painter = crate::Painter::new(gl, "", shader_version, dithering) .map_err(|err| { log::error!("error occurred in initializing painter:\n{err}"); }) .unwrap(); let egui_ctx = egui::Context::default(); let egui_winit = egui_winit::State::new( egui_ctx.clone(), ViewportId::ROOT, event_loop, native_pixels_per_point, event_loop.system_theme(), Some(painter.max_texture_side()), ); Self { egui_ctx, egui_winit, painter, viewport_info: Default::default(), shapes: Default::default(), pixels_per_point: native_pixels_per_point.unwrap_or(1.0), textures_delta: Default::default(), } } pub fn on_window_event( &mut self, window: &winit::window::Window, event: &winit::event::WindowEvent, ) -> EventResponse { self.egui_winit.on_window_event(window, event) } /// Call [`Self::paint`] later to paint. pub fn run(&mut self, window: &winit::window::Window, run_ui: impl FnMut(&mut egui::Ui)) { let raw_input = self.egui_winit.take_egui_input(window); let egui::FullOutput { platform_output, textures_delta, shapes, pixels_per_point, viewport_output, } = self.egui_ctx.run_ui(raw_input, run_ui); if viewport_output.len() > 1 { log::warn!("Multiple viewports not yet supported by EguiGlow"); } for (_, ViewportOutput { commands, .. }) in viewport_output { let mut actions_requested = Default::default(); egui_winit::process_viewport_commands( &self.egui_ctx, &mut self.viewport_info, commands, window, &mut actions_requested, ); for action in actions_requested { log::warn!("{action:?} not yet supported by EguiGlow"); } } self.egui_winit .handle_platform_output(window, platform_output); self.shapes = shapes; self.pixels_per_point = pixels_per_point; self.textures_delta.append(textures_delta); } /// Paint the results of the last call to [`Self::run`]. pub fn paint(&mut self, window: &winit::window::Window) { let shapes = std::mem::take(&mut self.shapes); let mut textures_delta = std::mem::take(&mut self.textures_delta); for (id, image_delta) in textures_delta.set { self.painter.set_texture(id, &image_delta); } let pixels_per_point = self.pixels_per_point; let clipped_primitives = self.egui_ctx.tessellate(shapes, pixels_per_point); let dimensions: [u32; 2] = window.inner_size().into(); self.painter .paint_primitives(dimensions, pixels_per_point, &clipped_primitives); for id in textures_delta.free.drain(..) { self.painter.free_texture(id); } } /// Call to release the allocated graphics resources. pub fn destroy(&mut self) { self.painter.destroy(); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_glow/src/lib.rs
crates/egui_glow/src/lib.rs
//! [`egui`] bindings for [`glow`](https://github.com/grovesNL/glow). //! //! The main type you want to look at is [`Painter`]. //! //! If you are writing an app, you may want to look at [`eframe`](https://docs.rs/eframe) instead. //! //! ## Feature flags #![cfg_attr(feature = "document-features", doc = document_features::document_features!())] //! #![expect(clippy::undocumented_unsafe_blocks)] pub mod painter; pub use glow; pub use painter::{CallbackFn, Painter, PainterError}; mod misc_util; mod shader_version; mod vao; pub use shader_version::ShaderVersion; #[cfg(feature = "winit")] pub mod winit; #[cfg(feature = "winit")] pub use winit::*; /// Check for OpenGL error and report it using `log::error`. /// /// Only active in debug builds! /// /// ``` no_run /// # let glow_context = todo!(); /// use egui_glow::check_for_gl_error; /// check_for_gl_error!(glow_context); /// check_for_gl_error!(glow_context, "during painting"); /// ``` #[macro_export] macro_rules! check_for_gl_error { ($gl: expr) => {{ if cfg!(debug_assertions) { $crate::check_for_gl_error_impl($gl, file!(), line!(), "") } }}; ($gl: expr, $context: literal) => {{ if cfg!(debug_assertions) { $crate::check_for_gl_error_impl($gl, file!(), line!(), $context) } }}; } /// Check for OpenGL error and report it using `log::error`. /// /// WARNING: slow! Only use during setup! /// /// ``` no_run /// # let glow_context = todo!(); /// use egui_glow::check_for_gl_error_even_in_release; /// check_for_gl_error_even_in_release!(glow_context); /// check_for_gl_error_even_in_release!(glow_context, "during painting"); /// ``` #[macro_export] macro_rules! check_for_gl_error_even_in_release { ($gl: expr) => {{ $crate::check_for_gl_error_impl($gl, file!(), line!(), "") }}; ($gl: expr, $context: literal) => {{ $crate::check_for_gl_error_impl($gl, file!(), line!(), $context) }}; } #[doc(hidden)] pub fn check_for_gl_error_impl(gl: &glow::Context, file: &str, line: u32, context: &str) { use glow::HasContext as _; #[expect(unsafe_code)] let error_code = unsafe { gl.get_error() }; if error_code != glow::NO_ERROR { let error_str = match error_code { glow::INVALID_ENUM => "GL_INVALID_ENUM", glow::INVALID_VALUE => "GL_INVALID_VALUE", glow::INVALID_OPERATION => "GL_INVALID_OPERATION", glow::STACK_OVERFLOW => "GL_STACK_OVERFLOW", glow::STACK_UNDERFLOW => "GL_STACK_UNDERFLOW", glow::OUT_OF_MEMORY => "GL_OUT_OF_MEMORY", glow::INVALID_FRAMEBUFFER_OPERATION => "GL_INVALID_FRAMEBUFFER_OPERATION", glow::CONTEXT_LOST => "GL_CONTEXT_LOST", 0x8031 => "GL_TABLE_TOO_LARGE1", 0x9242 => "CONTEXT_LOST_WEBGL", _ => "<unknown>", }; if context.is_empty() { log::error!( "GL error, at {file}:{line}: {error_str} (0x{error_code:X}). Please file a bug at https://github.com/emilk/egui/issues" ); } else { log::error!( "GL error, at {file}:{line} ({context}): {error_str} (0x{error_code:X}). Please file a bug at https://github.com/emilk/egui/issues" ); } } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_glow/src/painter.rs
crates/egui_glow/src/painter.rs
#![expect(clippy::unwrap_used)] #![expect(unsafe_code)] use std::{collections::HashMap, sync::Arc}; use egui::{ emath::Rect, epaint::{Mesh, PaintCallbackInfo, Primitive, Vertex}, }; use glow::HasContext as _; use memoffset::offset_of; use crate::check_for_gl_error; use crate::misc_util::{compile_shader, link_program}; use crate::shader_version::ShaderVersion; use crate::vao; /// Re-exported [`glow::Context`]. pub use glow::Context; const VERT_SRC: &str = include_str!("shader/vertex.glsl"); const FRAG_SRC: &str = include_str!("shader/fragment.glsl"); trait TextureFilterExt { fn glow_code(&self, mipmap: Option<egui::TextureFilter>) -> u32; } impl TextureFilterExt for egui::TextureFilter { fn glow_code(&self, mipmap: Option<egui::TextureFilter>) -> u32 { match (self, mipmap) { (Self::Linear, None) => glow::LINEAR, (Self::Nearest, None) => glow::NEAREST, (Self::Linear, Some(Self::Linear)) => glow::LINEAR_MIPMAP_LINEAR, (Self::Nearest, Some(Self::Linear)) => glow::NEAREST_MIPMAP_LINEAR, (Self::Linear, Some(Self::Nearest)) => glow::LINEAR_MIPMAP_NEAREST, (Self::Nearest, Some(Self::Nearest)) => glow::NEAREST_MIPMAP_NEAREST, } } } trait TextureWrapModeExt { fn glow_code(&self) -> u32; } impl TextureWrapModeExt for egui::TextureWrapMode { fn glow_code(&self) -> u32 { match self { Self::ClampToEdge => glow::CLAMP_TO_EDGE, Self::Repeat => glow::REPEAT, Self::MirroredRepeat => glow::MIRRORED_REPEAT, } } } #[derive(Debug)] pub struct PainterError(String); impl std::error::Error for PainterError {} impl std::fmt::Display for PainterError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "OpenGL: {}", self.0) } } impl From<String> for PainterError { #[inline] fn from(value: String) -> Self { Self(value) } } /// An OpenGL painter using [`glow`]. /// /// This is responsible for painting egui and managing egui textures. /// You can access the underlying [`glow::Context`] with [`Self::gl`]. /// /// This struct must be destroyed with [`Painter::destroy`] before dropping, to ensure OpenGL /// objects have been properly deleted and are not leaked. /// /// NOTE: all egui viewports share the same painter. pub struct Painter { gl: Arc<glow::Context>, max_texture_side: usize, program: glow::Program, u_screen_size: glow::UniformLocation, u_sampler: glow::UniformLocation, is_webgl_1: bool, vao: crate::vao::VertexArrayObject, srgb_textures: bool, supports_srgb_framebuffer: bool, vbo: glow::Buffer, element_array_buffer: glow::Buffer, textures: HashMap<egui::TextureId, glow::Texture>, next_native_tex_id: u64, /// Stores outdated OpenGL textures that are yet to be deleted textures_to_destroy: Vec<glow::Texture>, /// Used to make sure we are destroyed correctly. destroyed: bool, } /// A callback function that can be used to compose an [`egui::PaintCallback`] for custom rendering /// with [`glow`]. /// /// The callback is passed, the [`egui::PaintCallbackInfo`] and the [`Painter`] which can be used to /// access the OpenGL context. /// /// # Example /// /// See the [`custom3d_glow`](https://github.com/emilk/egui/blob/main/crates/egui_demo_app/src/apps/custom3d_wgpu.rs) demo source for a detailed usage example. pub struct CallbackFn { f: Box<dyn Fn(PaintCallbackInfo, &Painter) + Sync + Send>, } impl CallbackFn { pub fn new<F: Fn(PaintCallbackInfo, &Painter) + Sync + Send + 'static>(callback: F) -> Self { let f = Box::new(callback); Self { f } } } impl Painter { /// Create painter. /// /// Set `pp_fb_extent` to the framebuffer size to enable `sRGB` support on OpenGL ES and WebGL. /// /// Set `shader_prefix` if you want to turn on shader workaround e.g. `"#define APPLY_BRIGHTENING_GAMMA\n"` /// (see <https://github.com/emilk/egui/issues/794>). /// /// # Errors /// will return `Err` below cases /// * failed to compile shader /// * failed to create postprocess on webgl with `sRGB` support /// * failed to create buffer pub fn new( gl: Arc<glow::Context>, shader_prefix: &str, shader_version: Option<ShaderVersion>, dithering: bool, ) -> Result<Self, PainterError> { profiling::function_scope!(); crate::check_for_gl_error_even_in_release!(&gl, "before Painter::new"); // some useful debug info. all three of them are present in gl 1.1. unsafe { let version = gl.get_parameter_string(glow::VERSION); let renderer = gl.get_parameter_string(glow::RENDERER); let vendor = gl.get_parameter_string(glow::VENDOR); log::debug!( "\nopengl version: {version}\nopengl renderer: {renderer}\nopengl vendor: {vendor}" ); } #[cfg(not(target_arch = "wasm32"))] if gl.version().major < 2 { // this checks on desktop that we are not using opengl 1.1 microsoft sw rendering context. // ShaderVersion::get fn will segfault due to SHADING_LANGUAGE_VERSION (added in gl2.0) return Err(PainterError("egui_glow requires opengl 2.0+. ".to_owned())); } let max_texture_side = unsafe { gl.get_parameter_i32(glow::MAX_TEXTURE_SIZE) } as usize; let shader_version = shader_version.unwrap_or_else(|| ShaderVersion::get(&gl)); let is_webgl_1 = shader_version == ShaderVersion::Es100; let shader_version_declaration = shader_version.version_declaration(); log::debug!("Shader header: {shader_version_declaration:?}."); let supported_extensions = gl.supported_extensions(); log::trace!("OpenGL extensions: {supported_extensions:?}"); let srgb_textures = false; // egui wants normal sRGB-unaware textures let supports_srgb_framebuffer = !cfg!(target_arch = "wasm32") && supported_extensions.iter().any(|extension| { // {GL,GLX,WGL}_ARB_framebuffer_sRGB, … extension.ends_with("ARB_framebuffer_sRGB") }); log::debug!("SRGB framebuffer Support: {supports_srgb_framebuffer}"); unsafe { let vert = compile_shader( &gl, glow::VERTEX_SHADER, &format!( "{}\n#define NEW_SHADER_INTERFACE {}\n{}\n{}", shader_version_declaration, shader_version.is_new_shader_interface() as i32, shader_prefix, VERT_SRC ), )?; let frag = compile_shader( &gl, glow::FRAGMENT_SHADER, &format!( "{}\n#define NEW_SHADER_INTERFACE {}\n#define DITHERING {}\n{}\n{}", shader_version_declaration, shader_version.is_new_shader_interface() as i32, dithering as i32, shader_prefix, FRAG_SRC ), )?; let program = link_program(&gl, [vert, frag].iter())?; gl.detach_shader(program, vert); gl.detach_shader(program, frag); gl.delete_shader(vert); gl.delete_shader(frag); let u_screen_size = gl.get_uniform_location(program, "u_screen_size").unwrap(); let u_sampler = gl.get_uniform_location(program, "u_sampler").unwrap(); let vbo = gl.create_buffer()?; let a_pos_loc = gl.get_attrib_location(program, "a_pos").unwrap(); let a_tc_loc = gl.get_attrib_location(program, "a_tc").unwrap(); let a_srgba_loc = gl.get_attrib_location(program, "a_srgba").unwrap(); let stride = std::mem::size_of::<Vertex>() as i32; let buffer_infos = vec![ vao::BufferInfo { location: a_pos_loc, vector_size: 2, data_type: glow::FLOAT, normalized: false, stride, offset: offset_of!(Vertex, pos) as i32, }, vao::BufferInfo { location: a_tc_loc, vector_size: 2, data_type: glow::FLOAT, normalized: false, stride, offset: offset_of!(Vertex, uv) as i32, }, vao::BufferInfo { location: a_srgba_loc, vector_size: 4, data_type: glow::UNSIGNED_BYTE, normalized: false, stride, offset: offset_of!(Vertex, color) as i32, }, ]; let vao = crate::vao::VertexArrayObject::new(&gl, vbo, buffer_infos); let element_array_buffer = gl.create_buffer()?; crate::check_for_gl_error_even_in_release!(&gl, "after Painter::new"); Ok(Self { gl, max_texture_side, program, u_screen_size, u_sampler, is_webgl_1, vao, srgb_textures, supports_srgb_framebuffer, vbo, element_array_buffer, textures: Default::default(), next_native_tex_id: 1 << 32, textures_to_destroy: Vec::new(), destroyed: false, }) } } /// Access the shared glow context. pub fn gl(&self) -> &Arc<glow::Context> { &self.gl } pub fn max_texture_side(&self) -> usize { self.max_texture_side } /// The framebuffer we use as an intermediate render target, /// or `None` if we are painting to the screen framebuffer directly. /// /// This is the framebuffer that is bound when [`egui::Shape::Callback`] is called, /// and is where any callbacks should ultimately render onto. /// /// So if in a [`egui::Shape::Callback`] you need to use an offscreen FBO, you should /// then restore to this afterwards with /// `gl.bind_framebuffer(glow::FRAMEBUFFER, painter.intermediate_fbo());` #[expect(clippy::unused_self)] pub fn intermediate_fbo(&self) -> Option<glow::Framebuffer> { // We don't currently ever render to an offscreen buffer, // but we may want to start to in order to do anti-aliasing on web, for instance. None } unsafe fn prepare_painting( &mut self, [width_in_pixels, height_in_pixels]: [u32; 2], pixels_per_point: f32, ) { unsafe { self.gl.enable(glow::SCISSOR_TEST); // egui outputs mesh in both winding orders self.gl.disable(glow::CULL_FACE); self.gl.disable(glow::DEPTH_TEST); self.gl.color_mask(true, true, true, true); self.gl.enable(glow::BLEND); self.gl .blend_equation_separate(glow::FUNC_ADD, glow::FUNC_ADD); self.gl.blend_func_separate( // egui outputs colors with premultiplied alpha: glow::ONE, glow::ONE_MINUS_SRC_ALPHA, // Less important, but this is technically the correct alpha blend function // when you want to make use of the framebuffer alpha (for screenshots, compositing, etc). glow::ONE_MINUS_DST_ALPHA, glow::ONE, ); if self.supports_srgb_framebuffer { self.gl.disable(glow::FRAMEBUFFER_SRGB); check_for_gl_error!(&self.gl, "FRAMEBUFFER_SRGB"); } let width_in_points = width_in_pixels as f32 / pixels_per_point; let height_in_points = height_in_pixels as f32 / pixels_per_point; self.gl .viewport(0, 0, width_in_pixels as i32, height_in_pixels as i32); self.gl.use_program(Some(self.program)); self.gl .uniform_2_f32(Some(&self.u_screen_size), width_in_points, height_in_points); self.gl.uniform_1_i32(Some(&self.u_sampler), 0); self.gl.active_texture(glow::TEXTURE0); self.vao.bind(&self.gl); self.gl .bind_buffer(glow::ELEMENT_ARRAY_BUFFER, Some(self.element_array_buffer)); } check_for_gl_error!(&self.gl, "prepare_painting"); } pub fn clear(&self, screen_size_in_pixels: [u32; 2], clear_color: [f32; 4]) { clear(&self.gl, screen_size_in_pixels, clear_color); } /// You are expected to have cleared the color buffer before calling this. pub fn paint_and_update_textures( &mut self, screen_size_px: [u32; 2], pixels_per_point: f32, clipped_primitives: &[egui::ClippedPrimitive], textures_delta: &egui::TexturesDelta, ) { profiling::function_scope!(); for (id, image_delta) in &textures_delta.set { self.set_texture(*id, image_delta); } self.paint_primitives(screen_size_px, pixels_per_point, clipped_primitives); for &id in &textures_delta.free { self.free_texture(id); } } /// Main entry-point for painting a frame. /// /// You should call `target.clear_color(..)` before /// and `target.finish()` after this. /// /// The following OpenGL features will be set: /// - Scissor test will be enabled /// - Cull face will be disabled /// - Blend will be enabled /// /// The scissor area and blend parameters will be changed. /// /// As well as this, the following objects will be unset: /// - Vertex Buffer /// - Element Buffer /// - Texture (and active texture will be set to 0) /// - Program /// /// Please be mindful of these effects when integrating into your program, and also be mindful /// of the effects your program might have on this code. Look at the source if in doubt. pub fn paint_primitives( &mut self, screen_size_px: [u32; 2], pixels_per_point: f32, clipped_primitives: &[egui::ClippedPrimitive], ) { profiling::function_scope!(); self.assert_not_destroyed(); unsafe { self.prepare_painting(screen_size_px, pixels_per_point) }; for egui::ClippedPrimitive { clip_rect, primitive, } in clipped_primitives { set_clip_rect(&self.gl, screen_size_px, pixels_per_point, *clip_rect); match primitive { Primitive::Mesh(mesh) => { self.paint_mesh(mesh); } Primitive::Callback(callback) => { if callback.rect.is_positive() { profiling::scope!("callback"); let info = egui::PaintCallbackInfo { viewport: callback.rect, clip_rect: *clip_rect, pixels_per_point, screen_size_px, }; let viewport_px = info.viewport_in_pixels(); unsafe { self.gl.viewport( viewport_px.left_px, viewport_px.from_bottom_px, viewport_px.width_px, viewport_px.height_px, ); } if let Some(callback) = callback.callback.downcast_ref::<CallbackFn>() { (callback.f)(info, self); } else { log::warn!( "Warning: Unsupported render callback. Expected egui_glow::CallbackFn" ); } check_for_gl_error!(&self.gl, "callback"); // Restore state: unsafe { self.prepare_painting(screen_size_px, pixels_per_point) }; } } } } unsafe { self.vao.unbind(&self.gl); self.gl.bind_buffer(glow::ELEMENT_ARRAY_BUFFER, None); self.gl.disable(glow::SCISSOR_TEST); check_for_gl_error!(&self.gl, "painting"); } } #[inline(never)] // Easier profiling fn paint_mesh(&mut self, mesh: &Mesh) { debug_assert!(mesh.is_valid(), "Mesh is not valid"); if let Some(texture) = self.texture(mesh.texture_id) { unsafe { self.gl.bind_buffer(glow::ARRAY_BUFFER, Some(self.vbo)); self.gl.buffer_data_u8_slice( glow::ARRAY_BUFFER, bytemuck::cast_slice(&mesh.vertices), glow::STREAM_DRAW, ); self.gl .bind_buffer(glow::ELEMENT_ARRAY_BUFFER, Some(self.element_array_buffer)); self.gl.buffer_data_u8_slice( glow::ELEMENT_ARRAY_BUFFER, bytemuck::cast_slice(&mesh.indices), glow::STREAM_DRAW, ); self.gl.bind_texture(glow::TEXTURE_2D, Some(texture)); } unsafe { self.gl.draw_elements( glow::TRIANGLES, mesh.indices.len() as i32, glow::UNSIGNED_INT, 0, ); } check_for_gl_error!(&self.gl, "paint_mesh"); } else { log::warn!("Failed to find texture {:?}", mesh.texture_id); } } // ------------------------------------------------------------------------ pub fn set_texture(&mut self, tex_id: egui::TextureId, delta: &egui::epaint::ImageDelta) { profiling::function_scope!(); self.assert_not_destroyed(); let glow_texture = *self .textures .entry(tex_id) .or_insert_with(|| unsafe { self.gl.create_texture().unwrap() }); unsafe { self.gl.bind_texture(glow::TEXTURE_2D, Some(glow_texture)); } match &delta.image { egui::ImageData::Color(image) => { assert_eq!( image.width() * image.height(), image.pixels.len(), "Mismatch between texture size and texel count" ); let data: &[u8] = bytemuck::cast_slice(image.pixels.as_ref()); self.upload_texture_srgb(delta.pos, image.size, delta.options, data); } } } fn upload_texture_srgb( &mut self, pos: Option<[usize; 2]>, [w, h]: [usize; 2], options: egui::TextureOptions, data: &[u8], ) { profiling::function_scope!(); assert_eq!( data.len(), w * h * 4, "Mismatch between texture size and texel count, by {}", data.len() % (w * h * 4) ); assert!( w <= self.max_texture_side && h <= self.max_texture_side, "Got a texture image of size {}x{}, but the maximum supported texture side is only {}", w, h, self.max_texture_side ); unsafe { self.gl.tex_parameter_i32( glow::TEXTURE_2D, glow::TEXTURE_MAG_FILTER, options.magnification.glow_code(None) as i32, ); self.gl.tex_parameter_i32( glow::TEXTURE_2D, glow::TEXTURE_MIN_FILTER, options.minification.glow_code(options.mipmap_mode) as i32, ); self.gl.tex_parameter_i32( glow::TEXTURE_2D, glow::TEXTURE_WRAP_S, options.wrap_mode.glow_code() as i32, ); self.gl.tex_parameter_i32( glow::TEXTURE_2D, glow::TEXTURE_WRAP_T, options.wrap_mode.glow_code() as i32, ); check_for_gl_error!(&self.gl, "tex_parameter"); let (internal_format, src_format) = if self.is_webgl_1 { let format = if self.srgb_textures { glow::SRGB_ALPHA } else { glow::RGBA }; (format, format) } else if self.srgb_textures { (glow::SRGB8_ALPHA8, glow::RGBA) } else { (glow::RGBA8, glow::RGBA) }; self.gl.pixel_store_i32(glow::UNPACK_ALIGNMENT, 1); let level = 0; if let Some([x, y]) = pos { profiling::scope!("gl.tex_sub_image_2d"); self.gl.tex_sub_image_2d( glow::TEXTURE_2D, level, x as _, y as _, w as _, h as _, src_format, glow::UNSIGNED_BYTE, glow::PixelUnpackData::Slice(Some(data)), ); check_for_gl_error!(&self.gl, "tex_sub_image_2d"); } else { let border = 0; profiling::scope!("gl.tex_image_2d"); self.gl.tex_image_2d( glow::TEXTURE_2D, level, internal_format as _, w as _, h as _, border, src_format, glow::UNSIGNED_BYTE, glow::PixelUnpackData::Slice(Some(data)), ); check_for_gl_error!(&self.gl, "tex_image_2d"); } if options.mipmap_mode.is_some() { self.gl.generate_mipmap(glow::TEXTURE_2D); check_for_gl_error!(&self.gl, "generate_mipmap"); } } } pub fn free_texture(&mut self, tex_id: egui::TextureId) { if let Some(old_tex) = self.textures.remove(&tex_id) { unsafe { self.gl.delete_texture(old_tex) }; } } /// Get the [`glow::Texture`] bound to a [`egui::TextureId`]. pub fn texture(&self, texture_id: egui::TextureId) -> Option<glow::Texture> { self.textures.get(&texture_id).copied() } pub fn register_native_texture(&mut self, native: glow::Texture) -> egui::TextureId { self.assert_not_destroyed(); let id = egui::TextureId::User(self.next_native_tex_id); self.next_native_tex_id += 1; self.textures.insert(id, native); id } pub fn replace_native_texture(&mut self, id: egui::TextureId, replacing: glow::Texture) { if let Some(old_tex) = self.textures.insert(id, replacing) { self.textures_to_destroy.push(old_tex); } } pub fn read_screen_rgba(&self, [w, h]: [u32; 2]) -> egui::ColorImage { profiling::function_scope!(); let mut pixels = vec![0_u8; (w * h * 4) as usize]; unsafe { self.gl.read_pixels( 0, 0, w as _, h as _, glow::RGBA, glow::UNSIGNED_BYTE, glow::PixelPackData::Slice(Some(&mut pixels)), ); } let mut flipped = Vec::with_capacity((w * h * 4) as usize); for row in pixels.chunks_exact((w * 4) as usize).rev() { flipped.extend_from_slice(bytemuck::cast_slice(row)); } egui::ColorImage::new([w as usize, h as usize], flipped) } pub fn read_screen_rgb(&self, [w, h]: [u32; 2]) -> Vec<u8> { profiling::function_scope!(); let mut pixels = vec![0_u8; (w * h * 3) as usize]; unsafe { self.gl.read_pixels( 0, 0, w as _, h as _, glow::RGB, glow::UNSIGNED_BYTE, glow::PixelPackData::Slice(Some(&mut pixels)), ); } pixels } unsafe fn destroy_gl(&self) { unsafe { self.gl.delete_program(self.program); #[expect(clippy::iter_over_hash_type)] for tex in self.textures.values() { self.gl.delete_texture(*tex); } self.gl.delete_buffer(self.vbo); self.gl.delete_buffer(self.element_array_buffer); for t in &self.textures_to_destroy { self.gl.delete_texture(*t); } } } /// This function must be called before [`Painter`] is dropped, as [`Painter`] has some OpenGL objects /// that should be deleted. pub fn destroy(&mut self) { if !self.destroyed { unsafe { self.destroy_gl(); } self.destroyed = true; } } fn assert_not_destroyed(&self) { assert!(!self.destroyed, "the egui glow has already been destroyed!"); } } pub fn clear(gl: &glow::Context, screen_size_in_pixels: [u32; 2], clear_color: [f32; 4]) { profiling::function_scope!(); unsafe { gl.disable(glow::SCISSOR_TEST); gl.viewport( 0, 0, screen_size_in_pixels[0] as i32, screen_size_in_pixels[1] as i32, ); gl.clear_color( clear_color[0], clear_color[1], clear_color[2], clear_color[3], ); gl.clear(glow::COLOR_BUFFER_BIT); } } impl Drop for Painter { fn drop(&mut self) { if !self.destroyed { log::warn!( "You forgot to call destroy() on the egui glow painter. Resources will leak!" ); } } } fn set_clip_rect( gl: &glow::Context, [width_px, height_px]: [u32; 2], pixels_per_point: f32, clip_rect: Rect, ) { // Transform clip rect to physical pixels: let clip_min_x = pixels_per_point * clip_rect.min.x; let clip_min_y = pixels_per_point * clip_rect.min.y; let clip_max_x = pixels_per_point * clip_rect.max.x; let clip_max_y = pixels_per_point * clip_rect.max.y; // Round to integer: let clip_min_x = clip_min_x.round() as i32; let clip_min_y = clip_min_y.round() as i32; let clip_max_x = clip_max_x.round() as i32; let clip_max_y = clip_max_y.round() as i32; // Clamp: let clip_min_x = clip_min_x.clamp(0, width_px as i32); let clip_min_y = clip_min_y.clamp(0, height_px as i32); let clip_max_x = clip_max_x.clamp(clip_min_x, width_px as i32); let clip_max_y = clip_max_y.clamp(clip_min_y, height_px as i32); unsafe { gl.scissor( clip_min_x, height_px as i32 - clip_max_y, clip_max_x - clip_min_x, clip_max_y - clip_min_y, ); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_glow/src/misc_util.rs
crates/egui_glow/src/misc_util.rs
#![expect(unsafe_code)] use glow::HasContext as _; pub(crate) unsafe fn compile_shader( gl: &glow::Context, shader_type: u32, source: &str, ) -> Result<glow::Shader, String> { unsafe { let shader = gl.create_shader(shader_type)?; gl.shader_source(shader, source); gl.compile_shader(shader); if gl.get_shader_compile_status(shader) { Ok(shader) } else { Err(gl.get_shader_info_log(shader)) } } } pub(crate) unsafe fn link_program<'a, T: IntoIterator<Item = &'a glow::Shader>>( gl: &glow::Context, shaders: T, ) -> Result<glow::Program, String> { unsafe { let program = gl.create_program()?; for shader in shaders { gl.attach_shader(program, *shader); } gl.link_program(program); if gl.get_program_link_status(program) { Ok(program) } else { Err(gl.get_program_info_log(program)) } } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_glow/src/shader_version.rs
crates/egui_glow/src/shader_version.rs
#![expect(clippy::undocumented_unsafe_blocks)] #![expect(clippy::unwrap_used)] // TODO(emilk): avoid unwraps #![expect(unsafe_code)] use std::convert::TryInto as _; /// Helper for parsing and interpreting the OpenGL shader version. #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum ShaderVersion { Gl120, /// OpenGL 1.4 or later Gl140, /// e.g. WebGL1 Es100, /// e.g. WebGL2 Es300, } impl ShaderVersion { pub fn get(gl: &glow::Context) -> Self { use glow::HasContext as _; let shading_lang_string = unsafe { gl.get_parameter_string(glow::SHADING_LANGUAGE_VERSION) }; let shader_version = Self::parse(&shading_lang_string); log::debug!("Shader version: {shader_version:?} ({shading_lang_string:?})."); shader_version } #[inline] pub(crate) fn parse(glsl_ver: &str) -> Self { let start = glsl_ver.find(|c| char::is_ascii_digit(&c)).unwrap(); let es = glsl_ver[..start].contains(" ES "); let ver = glsl_ver[start..] .split_once(' ') .map_or(&glsl_ver[start..], |x| x.0); let [maj, min]: [u8; 2] = ver .splitn(3, '.') .take(2) .map(|x| x.parse().unwrap_or_default()) .collect::<Vec<u8>>() .try_into() .unwrap(); if es { if maj >= 3 { Self::Es300 } else { Self::Es100 } } else if maj > 1 || (maj == 1 && min >= 40) { Self::Gl140 } else { Self::Gl120 } } /// Goes on top of the shader. pub fn version_declaration(&self) -> &'static str { match self { Self::Gl120 => "#version 120\n", Self::Gl140 => "#version 140\n", Self::Es100 => "#version 100\n", Self::Es300 => "#version 300 es\n", } } /// If true, use `in/out`. If `false`, use `varying` and `gl_FragColor`. pub fn is_new_shader_interface(&self) -> bool { match self { Self::Gl120 | Self::Es100 => false, Self::Es300 | Self::Gl140 => true, } } pub fn is_embedded(&self) -> bool { match self { Self::Gl120 | Self::Gl140 => false, Self::Es100 | Self::Es300 => true, } } } #[test] fn test_shader_version() { use ShaderVersion::{Es100, Es300, Gl120, Gl140}; for (s, v) in [ ("1.2 OpenGL foo bar", Gl120), ("3.0", Gl140), ("0.0", Gl120), ("OpenGL ES GLSL 3.00 (WebGL2)", Es300), ("OpenGL ES GLSL 1.00 (WebGL)", Es100), ("OpenGL ES GLSL ES 1.00 foo bar", Es100), ("WebGL GLSL ES 3.00 foo bar", Es300), ("WebGL GLSL ES 3.00", Es300), ("WebGL GLSL ES 1.0 foo bar", Es100), ] { assert_eq!(ShaderVersion::parse(s), v); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_glow/src/vao.rs
crates/egui_glow/src/vao.rs
#![expect(unsafe_code)] #![expect(clippy::unwrap_used)] use glow::HasContext as _; use crate::check_for_gl_error; // ---------------------------------------------------------------------------- #[derive(Debug)] pub(crate) struct BufferInfo { pub location: u32, // pub vector_size: i32, pub data_type: u32, //GL_FLOAT,GL_UNSIGNED_BYTE pub normalized: bool, pub stride: i32, pub offset: i32, } // ---------------------------------------------------------------------------- /// Wrapper around either Emulated VAO or GL's VAO. pub(crate) struct VertexArrayObject { // If `None`, we emulate VAO:s. vao: Option<crate::glow::VertexArray>, vbo: glow::Buffer, buffer_infos: Vec<BufferInfo>, } impl VertexArrayObject { pub(crate) unsafe fn new( gl: &glow::Context, vbo: glow::Buffer, buffer_infos: Vec<BufferInfo>, ) -> Self { let vao = if supports_vao(gl) { unsafe { let vao = gl.create_vertex_array().unwrap(); check_for_gl_error!(gl, "create_vertex_array"); // Store state in the VAO: gl.bind_vertex_array(Some(vao)); gl.bind_buffer(glow::ARRAY_BUFFER, Some(vbo)); for attribute in &buffer_infos { gl.vertex_attrib_pointer_f32( attribute.location, attribute.vector_size, attribute.data_type, attribute.normalized, attribute.stride, attribute.offset, ); check_for_gl_error!(gl, "vertex_attrib_pointer_f32"); gl.enable_vertex_attrib_array(attribute.location); check_for_gl_error!(gl, "enable_vertex_attrib_array"); } gl.bind_vertex_array(None); Some(vao) } } else { log::debug!("VAO not supported"); None }; Self { vao, vbo, buffer_infos, } } pub(crate) unsafe fn bind(&self, gl: &glow::Context) { unsafe { if let Some(vao) = self.vao { gl.bind_vertex_array(Some(vao)); check_for_gl_error!(gl, "bind_vertex_array"); } else { gl.bind_buffer(glow::ARRAY_BUFFER, Some(self.vbo)); check_for_gl_error!(gl, "bind_buffer"); for attribute in &self.buffer_infos { gl.vertex_attrib_pointer_f32( attribute.location, attribute.vector_size, attribute.data_type, attribute.normalized, attribute.stride, attribute.offset, ); check_for_gl_error!(gl, "vertex_attrib_pointer_f32"); gl.enable_vertex_attrib_array(attribute.location); check_for_gl_error!(gl, "enable_vertex_attrib_array"); } } } } pub(crate) unsafe fn unbind(&self, gl: &glow::Context) { unsafe { if self.vao.is_some() { gl.bind_vertex_array(None); } else { gl.bind_buffer(glow::ARRAY_BUFFER, None); for attribute in &self.buffer_infos { gl.disable_vertex_attrib_array(attribute.location); } } } } } // ---------------------------------------------------------------------------- fn supports_vao(gl: &glow::Context) -> bool { const WEBGL_PREFIX: &str = "WebGL "; const OPENGL_ES_PREFIX: &str = "OpenGL ES "; let version_string = unsafe { gl.get_parameter_string(glow::VERSION) }; log::debug!("GL version: {version_string:?}."); // Examples: // * "WebGL 2.0 (OpenGL ES 3.0 Chromium)" // * "WebGL 2.0" if let Some(pos) = version_string.rfind(WEBGL_PREFIX) { let version_str = &version_string[pos + WEBGL_PREFIX.len()..]; if version_str.contains("1.0") { // need to test OES_vertex_array_object . let supported_extensions = gl.supported_extensions(); log::debug!("Supported OpenGL extensions: {supported_extensions:?}"); supported_extensions.contains("OES_vertex_array_object") || supported_extensions.contains("GL_OES_vertex_array_object") } else { true } } else if version_string.contains(OPENGL_ES_PREFIX) { // glow targets es2.0+ so we don't concern about OpenGL ES-CM,OpenGL ES-CL if version_string.contains("2.0") { // need to test OES_vertex_array_object . let supported_extensions = gl.supported_extensions(); log::debug!("Supported OpenGL extensions: {supported_extensions:?}"); supported_extensions.contains("OES_vertex_array_object") || supported_extensions.contains("GL_OES_vertex_array_object") } else { true } } else { // from OpenGL 3 vao into core if version_string.starts_with('2') { // I found APPLE_vertex_array_object , GL_ATI_vertex_array_object ,ARB_vertex_array_object // but APPLE's and ATI's very old extension. let supported_extensions = gl.supported_extensions(); log::debug!("Supported OpenGL extensions: {supported_extensions:?}"); supported_extensions.contains("ARB_vertex_array_object") || supported_extensions.contains("GL_ARB_vertex_array_object") } else { true } } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_glow/examples/pure_glow.rs
crates/egui_glow/examples/pure_glow.rs
//! Example how to use pure `egui_glow`. #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] // hide console window on Windows in release #![expect(rustdoc::missing_crate_level_docs, clippy::unwrap_used)] // it's an example #![expect(clippy::undocumented_unsafe_blocks)] #![expect(unsafe_code)] use std::num::NonZeroU32; use std::sync::Arc; use egui_winit::winit; use winit::raw_window_handle::HasWindowHandle as _; /// The majority of `GlutinWindowContext` is taken from `eframe` struct GlutinWindowContext { window: winit::window::Window, gl_context: glutin::context::PossiblyCurrentContext, gl_display: glutin::display::Display, gl_surface: glutin::surface::Surface<glutin::surface::WindowSurface>, } impl GlutinWindowContext { // refactor this function to use `glutin-winit` crate eventually. // preferably add android support at the same time. #[expect(unsafe_code)] unsafe fn new(event_loop: &winit::event_loop::ActiveEventLoop) -> Self { use glutin::context::NotCurrentGlContext as _; use glutin::display::GetGlDisplay as _; use glutin::display::GlDisplay as _; use glutin::prelude::GlSurface as _; let winit_window_builder = winit::window::WindowAttributes::default() .with_resizable(true) .with_inner_size(winit::dpi::LogicalSize { width: 800.0, height: 600.0, }) .with_title("egui_glow example") // Keep hidden until we've painted something. See https://github.com/emilk/egui/pull/2279 .with_visible(false); let config_template_builder = glutin::config::ConfigTemplateBuilder::new() .prefer_hardware_accelerated(None) .with_depth_size(0) .with_stencil_size(0) .with_transparency(false); log::debug!("trying to get gl_config"); let (mut window, gl_config) = glutin_winit::DisplayBuilder::new() // let glutin-winit helper crate handle the complex parts of opengl context creation .with_preference(glutin_winit::ApiPreference::FallbackEgl) // https://github.com/emilk/egui/issues/2520#issuecomment-1367841150 .with_window_attributes(Some(winit_window_builder.clone())) .build( event_loop, config_template_builder, |mut config_iterator| { config_iterator.next().expect( "failed to find a matching configuration for creating glutin config", ) }, ) .expect("failed to create gl_config"); let gl_display = gl_config.display(); log::debug!("found gl_config: {:?}", &gl_config); let raw_window_handle = window.as_ref().map(|w| { w.window_handle() .expect("failed to get window handle") .as_raw() }); log::debug!("raw window handle: {raw_window_handle:?}"); let context_attributes = glutin::context::ContextAttributesBuilder::new().build(raw_window_handle); // by default, glutin will try to create a core opengl context. but, if it is not available, try to create a gl-es context using this fallback attributes let fallback_context_attributes = glutin::context::ContextAttributesBuilder::new() .with_context_api(glutin::context::ContextApi::Gles(None)) .build(raw_window_handle); let not_current_gl_context = unsafe { gl_display .create_context(&gl_config, &context_attributes) .unwrap_or_else(|_| { log::debug!("failed to create gl_context with attributes: {:?}. retrying with fallback context attributes: {:?}", &context_attributes, &fallback_context_attributes); gl_config .display() .create_context(&gl_config, &fallback_context_attributes) .expect("failed to create context even with fallback attributes") }) }; // this is where the window is created, if it has not been created while searching for suitable gl_config let window = window.take().unwrap_or_else(|| { log::debug!("window doesn't exist yet. creating one now with finalize_window"); glutin_winit::finalize_window(event_loop, winit_window_builder.clone(), &gl_config) .expect("failed to finalize glutin window") }); let (width, height): (u32, u32) = window.inner_size().into(); let width = NonZeroU32::new(width).unwrap_or(NonZeroU32::MIN); let height = NonZeroU32::new(height).unwrap_or(NonZeroU32::MIN); let surface_attributes = glutin::surface::SurfaceAttributesBuilder::<glutin::surface::WindowSurface>::new() .build( window .window_handle() .expect("failed to get window handle") .as_raw(), width, height, ); log::debug!( "creating surface with attributes: {:?}", &surface_attributes ); let gl_surface = unsafe { gl_display .create_window_surface(&gl_config, &surface_attributes) .unwrap() }; log::debug!("surface created successfully: {gl_surface:?}.making context current"); let gl_context = not_current_gl_context.make_current(&gl_surface).unwrap(); gl_surface .set_swap_interval( &gl_context, glutin::surface::SwapInterval::Wait(NonZeroU32::MIN), ) .unwrap(); Self { window, gl_context, gl_display, gl_surface, } } fn window(&self) -> &winit::window::Window { &self.window } fn resize(&self, physical_size: winit::dpi::PhysicalSize<u32>) { use glutin::surface::GlSurface as _; self.gl_surface.resize( &self.gl_context, physical_size.width.try_into().unwrap(), physical_size.height.try_into().unwrap(), ); } fn swap_buffers(&self) -> glutin::error::Result<()> { use glutin::surface::GlSurface as _; self.gl_surface.swap_buffers(&self.gl_context) } fn get_proc_address(&self, addr: &std::ffi::CStr) -> *const std::ffi::c_void { use glutin::display::GlDisplay as _; self.gl_display.get_proc_address(addr) } } #[derive(Debug)] pub enum UserEvent { Redraw(std::time::Duration), } struct GlowApp { proxy: winit::event_loop::EventLoopProxy<UserEvent>, gl_window: Option<GlutinWindowContext>, gl: Option<Arc<glow::Context>>, egui_glow: Option<egui_glow::EguiGlow>, repaint_delay: std::time::Duration, clear_color: [f32; 3], } impl GlowApp { fn new(proxy: winit::event_loop::EventLoopProxy<UserEvent>) -> Self { Self { proxy, gl_window: None, gl: None, egui_glow: None, repaint_delay: std::time::Duration::MAX, clear_color: [0.1, 0.1, 0.1], } } } impl winit::application::ApplicationHandler<UserEvent> for GlowApp { fn resumed(&mut self, event_loop: &winit::event_loop::ActiveEventLoop) { let (gl_window, gl) = create_display(event_loop); let gl = std::sync::Arc::new(gl); gl_window.window().set_visible(true); let egui_glow = egui_glow::EguiGlow::new(event_loop, Arc::clone(&gl), None, None, true); let event_loop_proxy = egui::mutex::Mutex::new(self.proxy.clone()); egui_glow .egui_ctx .set_request_repaint_callback(move |info| { event_loop_proxy .lock() .send_event(UserEvent::Redraw(info.delay)) .expect("Cannot send event"); }); self.gl_window = Some(gl_window); self.gl = Some(gl); self.egui_glow = Some(egui_glow); } fn window_event( &mut self, event_loop: &winit::event_loop::ActiveEventLoop, _window_id: winit::window::WindowId, event: winit::event::WindowEvent, ) { let mut redraw = || { let mut quit = false; self.egui_glow .as_mut() .unwrap() .run(self.gl_window.as_mut().unwrap().window(), |ui| { egui::Panel::left("my_side_panel").show_inside(ui, |ui| { ui.heading("Hello World!"); if ui.button("Quit").clicked() { quit = true; } ui.color_edit_button_rgb(self.clear_color.as_mut().try_into().unwrap()); }); }); if quit { event_loop.exit(); } else { event_loop.set_control_flow(if self.repaint_delay.is_zero() { self.gl_window.as_mut().unwrap().window().request_redraw(); winit::event_loop::ControlFlow::Poll } else if let Some(repaint_after_instant) = std::time::Instant::now().checked_add(self.repaint_delay) { winit::event_loop::ControlFlow::WaitUntil(repaint_after_instant) } else { winit::event_loop::ControlFlow::Wait }); } { unsafe { use glow::HasContext as _; self.gl.as_mut().unwrap().clear_color( self.clear_color[0], self.clear_color[1], self.clear_color[2], 1.0, ); self.gl.as_mut().unwrap().clear(glow::COLOR_BUFFER_BIT); } // draw things behind egui here self.egui_glow .as_mut() .unwrap() .paint(self.gl_window.as_mut().unwrap().window()); // draw things on top of egui here self.gl_window.as_mut().unwrap().swap_buffers().unwrap(); self.gl_window.as_mut().unwrap().window().set_visible(true); } }; use winit::event::WindowEvent; if matches!(event, WindowEvent::CloseRequested | WindowEvent::Destroyed) { event_loop.exit(); return; } if matches!(event, WindowEvent::RedrawRequested) { redraw(); return; } if let winit::event::WindowEvent::Resized(physical_size) = &event { self.gl_window.as_mut().unwrap().resize(*physical_size); } let event_response = self .egui_glow .as_mut() .unwrap() .on_window_event(self.gl_window.as_mut().unwrap().window(), &event); if event_response.repaint { self.gl_window.as_mut().unwrap().window().request_redraw(); } } fn user_event(&mut self, _event_loop: &winit::event_loop::ActiveEventLoop, event: UserEvent) { match event { UserEvent::Redraw(delay) => self.repaint_delay = delay, } } fn new_events( &mut self, _event_loop: &winit::event_loop::ActiveEventLoop, cause: winit::event::StartCause, ) { if let winit::event::StartCause::ResumeTimeReached { .. } = &cause { self.gl_window.as_mut().unwrap().window().request_redraw(); } } fn exiting(&mut self, _event_loop: &winit::event_loop::ActiveEventLoop) { self.egui_glow.as_mut().unwrap().destroy(); } } fn main() { let event_loop = winit::event_loop::EventLoop::<UserEvent>::with_user_event() .build() .unwrap(); let proxy = event_loop.create_proxy(); let mut app = GlowApp::new(proxy); event_loop.run_app(&mut app).expect("failed to run app"); } fn create_display( event_loop: &winit::event_loop::ActiveEventLoop, ) -> (GlutinWindowContext, glow::Context) { let glutin_window_context = unsafe { GlutinWindowContext::new(event_loop) }; let gl = unsafe { 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) }) }; (glutin_window_context, gl) }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_kittest/src/config.rs
crates/egui_kittest/src/config.rs
#![cfg(feature = "snapshot")] use std::io; use std::path::PathBuf; /// Configuration for `egui_kittest`. /// /// It's loaded once (per process) by searching for a `kittest.toml` file in the project root /// (the directory containing `Cargo.lock`). #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(default, deny_unknown_fields)] pub struct Config { /// The output path for image snapshots. /// /// Default is "tests/snapshots" (relative to the working directory / crate root). output_path: PathBuf, /// The per-pixel threshold. /// /// Default is 0.6. threshold: f32, /// The number of pixels that can differ before the test is considered failed. /// /// Default is 0. failed_pixel_count_threshold: usize, windows: OsConfig, mac: OsConfig, linux: OsConfig, } impl Default for Config { fn default() -> Self { Self { output_path: PathBuf::from("tests/snapshots"), threshold: 0.6, failed_pixel_count_threshold: 0, windows: Default::default(), mac: Default::default(), linux: Default::default(), } } } #[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] #[serde(default, deny_unknown_fields)] pub struct OsConfig { /// Override the per-pixel threshold for this OS. threshold: Option<f32>, /// Override the failed pixel count threshold for this OS. failed_pixel_count_threshold: Option<usize>, } fn find_kittest_toml() -> io::Result<std::path::PathBuf> { let mut current_dir = std::env::current_dir()?; loop { let current_kittest = current_dir.join("kittest.toml"); // Check if Cargo.toml exists in this directory if current_kittest.exists() { return Ok(current_kittest); } // Move up one directory if !current_dir.pop() { return Err(io::Error::new( io::ErrorKind::NotFound, "kittest.toml not found", )); } } } fn load_config() -> Config { if let Ok(config_path) = find_kittest_toml() { match std::fs::read_to_string(&config_path) { Ok(config_str) => match toml::from_str(&config_str) { Ok(config) => config, Err(e) => panic!("Failed to parse {}: {e}", &config_path.display()), }, Err(err) => { panic!("Failed to read {}: {}", config_path.display(), err); } } } else { Config::default() } } /// Get the global configuration. /// /// See [`Config::global`] for details. pub fn config() -> &'static Config { Config::global() } impl Config { /// Get or load the global configuration. /// /// This is either /// - Based on a `kittest.toml`, found by searching from the current working directory /// (for tests that is the crate root) upwards. /// - The default [Config], if no `kittest.toml` is found. pub fn global() -> &'static Self { static INSTANCE: std::sync::LazyLock<Config> = std::sync::LazyLock::new(load_config); &INSTANCE } /// The output path for image snapshots. /// /// Default is "tests/snapshots". pub fn output_path(&self) -> PathBuf { self.output_path.clone() } } #[cfg(feature = "snapshot")] impl Config { pub fn os_threshold(&self) -> crate::OsThreshold<f32> { let fallback = self.threshold; crate::OsThreshold { windows: self.windows.threshold.unwrap_or(fallback), macos: self.mac.threshold.unwrap_or(fallback), linux: self.linux.threshold.unwrap_or(fallback), fallback, } } pub fn os_failed_pixel_count_threshold(&self) -> crate::OsThreshold<usize> { let fallback = self.failed_pixel_count_threshold; crate::OsThreshold { windows: self .windows .failed_pixel_count_threshold .unwrap_or(fallback), macos: self.mac.failed_pixel_count_threshold.unwrap_or(fallback), linux: self.linux.failed_pixel_count_threshold.unwrap_or(fallback), fallback, } } /// The threshold. /// /// Default is 1.0. pub fn threshold(&self) -> f32 { self.os_threshold().threshold() } /// The number of pixels that can differ before the test is considered failed. /// /// Default is 0. pub fn failed_pixel_count_threshold(&self) -> usize { self.os_failed_pixel_count_threshold().threshold() } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_kittest/src/app_kind.rs
crates/egui_kittest/src/app_kind.rs
use egui::Frame; type AppKindContextState<'a, State> = Box<dyn FnMut(&egui::Context, &mut State) + 'a>; type AppKindUiState<'a, State> = Box<dyn FnMut(&mut egui::Ui, &mut State) + 'a>; type AppKindContext<'a> = Box<dyn FnMut(&egui::Context) + 'a>; type AppKindUi<'a> = Box<dyn FnMut(&mut egui::Ui) + 'a>; /// In order to access the [`eframe::App`] trait from the generic `State`, we store a function pointer /// here that will return the dyn trait from the struct. In the builder we have the correct where /// clause to be able to create this. /// Later we can use it anywhere to get the [`eframe::App`] from the `State`. #[cfg(feature = "eframe")] type AppKindEframe<'a, State> = (fn(&mut State) -> &mut dyn eframe::App, eframe::Frame); pub(crate) enum AppKind<'a, State> { Context(AppKindContext<'a>), Ui(AppKindUi<'a>), ContextState(AppKindContextState<'a, State>), UiState(AppKindUiState<'a, State>), #[cfg(feature = "eframe")] Eframe(AppKindEframe<'a, State>), } impl<State> AppKind<'_, State> { pub fn run( &mut self, ui: &mut egui::Ui, state: &mut State, sizing_pass: bool, ) -> Option<egui::Response> { match self { AppKind::Context(f) => { debug_assert!(!sizing_pass, "Context closures cannot do a sizing pass"); f(ui); None } AppKind::ContextState(f) => { debug_assert!(!sizing_pass, "Context closures cannot do a sizing pass"); f(ui, state); None } #[cfg(feature = "eframe")] AppKind::Eframe((get_app, frame)) => { let app = get_app(state); app.logic(ui, frame); #[expect(deprecated)] app.update(ui, frame); app.ui(ui, frame); None } kind_ui => Some(kind_ui.run_ui(ui, state, sizing_pass)), } } fn run_ui( &mut self, ui: &mut egui::Ui, state: &mut State, sizing_pass: bool, ) -> egui::Response { let mut builder = egui::UiBuilder::new(); if sizing_pass { builder.sizing_pass = true; } ui.scope_builder(builder, |ui| { Frame::central_panel(ui.style()) // Only set outer margin, so we show no frame for tests with only free-floating windows/popups: .outer_margin(8.0) .inner_margin(0.0) .show(ui, |ui| match self { AppKind::Ui(f) => f(ui), AppKind::UiState(f) => f(ui, state), _ => unreachable!( "run_ui should only be called with AppKind::Ui or AppKind UiState" ), }); }) .response } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_kittest/src/texture_to_image.rs
crates/egui_kittest/src/texture_to_image.rs
use egui_wgpu::wgpu; use egui_wgpu::wgpu::{Device, Extent3d, Queue, Texture}; use image::RgbaImage; use std::iter; use std::mem::size_of; use std::sync::mpsc::channel; use crate::wgpu::WAIT_TIMEOUT; pub(crate) fn texture_to_image(device: &Device, queue: &Queue, texture: &Texture) -> RgbaImage { let buffer_dimensions = BufferDimensions::new(texture.width() as usize, texture.height() as usize); let output_buffer = device.create_buffer(&wgpu::BufferDescriptor { label: Some("Texture to bytes output buffer"), size: (buffer_dimensions.padded_bytes_per_row * buffer_dimensions.height) as u64, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, }); let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("Texture to bytes encoder"), }); // Copy the data from the texture to the buffer encoder.copy_texture_to_buffer( texture.as_image_copy(), wgpu::TexelCopyBufferInfo { buffer: &output_buffer, layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(buffer_dimensions.padded_bytes_per_row as u32), rows_per_image: None, }, }, Extent3d { width: texture.width(), height: texture.height(), depth_or_array_layers: 1, }, ); let submission_index = queue.submit(iter::once(encoder.finish())); // Note that we're not calling `.await` here. let buffer_slice = output_buffer.slice(..); // Sets the buffer up for mapping, sending over the result of the mapping back to us when it is finished. let (sender, receiver) = channel(); buffer_slice.map_async(wgpu::MapMode::Read, move |v| drop(sender.send(v))); // Poll the device in a blocking manner so that our future resolves. device .poll(wgpu::PollType::Wait { submission_index: Some(submission_index), timeout: Some(WAIT_TIMEOUT), }) .expect("Failed to poll device"); receiver.recv().unwrap().unwrap(); let buffer_slice = output_buffer.slice(..); let data = buffer_slice.get_mapped_range(); let data = data .chunks_exact(buffer_dimensions.padded_bytes_per_row) .flat_map(|row| row.iter().take(buffer_dimensions.unpadded_bytes_per_row)) .copied() .collect::<Vec<_>>(); RgbaImage::from_raw(texture.width(), texture.height(), data).expect("Failed to create image") } struct BufferDimensions { height: usize, unpadded_bytes_per_row: usize, padded_bytes_per_row: usize, } impl BufferDimensions { fn new(width: usize, height: usize) -> Self { let bytes_per_pixel = size_of::<u32>(); let unpadded_bytes_per_row = width * bytes_per_pixel; let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as usize; let padded_bytes_per_row_padding = (align - unpadded_bytes_per_row % align) % align; let padded_bytes_per_row = unpadded_bytes_per_row + padded_bytes_per_row_padding; Self { height, 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/egui_kittest/src/node.rs
crates/egui_kittest/src/node.rs
use egui::accesskit::ActionRequest; use egui::mutex::Mutex; use egui::{Modifiers, PointerButton, Pos2, accesskit}; use kittest::{AccessKitNode, NodeT, debug_fmt_node}; use std::fmt::{Debug, Formatter}; pub(crate) enum EventType { Event(egui::Event), Modifiers(Modifiers), } pub(crate) type EventQueue = Mutex<Vec<EventType>>; #[derive(Clone, Copy)] pub struct Node<'tree> { pub(crate) accesskit_node: AccessKitNode<'tree>, pub(crate) queue: &'tree EventQueue, } impl Debug for Node<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { debug_fmt_node(self, f) } } impl<'tree> NodeT<'tree> for Node<'tree> { fn accesskit_node(&self) -> AccessKitNode<'tree> { self.accesskit_node } fn new_related(&self, child_node: AccessKitNode<'tree>) -> Self { Self { queue: self.queue, accesskit_node: child_node, } } } impl Node<'_> { fn event(&self, event: egui::Event) { self.queue.lock().push(EventType::Event(event)); } fn modifiers(&self, modifiers: Modifiers) { self.queue.lock().push(EventType::Modifiers(modifiers)); } pub fn hover(&self) { self.event(egui::Event::PointerMoved(self.rect().center())); } /// Click at the node center with the primary button. pub fn click(&self) { self.click_button(PointerButton::Primary); } #[deprecated = "Use `click()` instead."] pub fn simulate_click(&self) { self.click(); } pub fn click_secondary(&self) { self.click_button(PointerButton::Secondary); } pub fn click_button(&self, button: PointerButton) { self.hover(); for pressed in [true, false] { self.event(egui::Event::PointerButton { pos: self.rect().center(), button, pressed, modifiers: Modifiers::default(), }); } } pub fn click_modifiers(&self, modifiers: Modifiers) { self.click_button_modifiers(PointerButton::Primary, modifiers); } pub fn click_button_modifiers(&self, button: PointerButton, modifiers: Modifiers) { self.hover(); self.modifiers(modifiers); for pressed in [true, false] { self.event(egui::Event::PointerButton { pos: self.rect().center(), button, pressed, modifiers, }); } self.modifiers(Modifiers::default()); } /// Click the node via accesskit. /// /// This will trigger a [`accesskit::Action::Click`] action. /// In contrast to `click()`, this can also click widgets that are not currently visible. pub fn click_accesskit(&self) { self.event(egui::Event::AccessKitActionRequest( accesskit::ActionRequest { target: self.accesskit_node.id(), action: accesskit::Action::Click, data: None, }, )); } pub fn rect(&self) -> egui::Rect { let rect = self .accesskit_node .bounding_box() .expect("Every egui node should have a rect"); egui::Rect { min: Pos2::new(rect.x0 as f32, rect.y0 as f32), max: Pos2::new(rect.x1 as f32, rect.y1 as f32), } } pub fn focus(&self) { self.event(egui::Event::AccessKitActionRequest(ActionRequest { action: accesskit::Action::Focus, target: self.accesskit_node.id(), data: None, })); } #[deprecated = "Use `Harness::key_down` instead."] pub fn key_down(&self, key: egui::Key) { self.event(egui::Event::Key { key, pressed: true, modifiers: Modifiers::default(), repeat: false, physical_key: None, }); } #[deprecated = "Use `Harness::key_up` instead."] pub fn key_up(&self, key: egui::Key) { self.event(egui::Event::Key { key, pressed: false, modifiers: Modifiers::default(), repeat: false, physical_key: None, }); } pub fn type_text(&self, text: &str) { self.event(egui::Event::Text(text.to_owned())); } pub fn value(&self) -> Option<String> { self.accesskit_node.value() } pub fn is_focused(&self) -> bool { self.accesskit_node.is_focused() } /// Scroll the node into view. pub fn scroll_to_me(&self) { self.event(egui::Event::AccessKitActionRequest(ActionRequest { action: accesskit::Action::ScrollIntoView, target: self.accesskit_node.id(), data: None, })); } /// Scroll the [`egui::ScrollArea`] containing this node down (100px). pub fn scroll_down(&self) { self.event(egui::Event::AccessKitActionRequest(ActionRequest { action: accesskit::Action::ScrollDown, target: self.accesskit_node.id(), data: None, })); } /// Scroll the [`egui::ScrollArea`] containing this node up (100px). pub fn scroll_up(&self) { self.event(egui::Event::AccessKitActionRequest(ActionRequest { action: accesskit::Action::ScrollUp, target: self.accesskit_node.id(), data: None, })); } /// Scroll the [`egui::ScrollArea`] containing this node left (100px). pub fn scroll_left(&self) { self.event(egui::Event::AccessKitActionRequest(ActionRequest { action: accesskit::Action::ScrollLeft, target: self.accesskit_node.id(), data: None, })); } /// Scroll the [`egui::ScrollArea`] containing this node right (100px). pub fn scroll_right(&self) { self.event(egui::Event::AccessKitActionRequest(ActionRequest { action: accesskit::Action::ScrollRight, target: self.accesskit_node.id(), data: None, })); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_kittest/src/builder.rs
crates/egui_kittest/src/builder.rs
use crate::app_kind::AppKind; use crate::{Harness, LazyRenderer, TestRenderer}; use egui::{Pos2, Rect, Vec2}; use std::marker::PhantomData; /// Builder for [`Harness`]. #[must_use] pub struct HarnessBuilder<State = ()> { pub(crate) screen_rect: Rect, pub(crate) pixels_per_point: f32, pub(crate) theme: egui::Theme, pub(crate) os: egui::os::OperatingSystem, pub(crate) max_steps: u64, pub(crate) step_dt: f32, pub(crate) state: PhantomData<State>, pub(crate) renderer: Box<dyn TestRenderer>, pub(crate) wait_for_pending_images: bool, #[cfg(feature = "snapshot")] pub(crate) default_snapshot_options: crate::SnapshotOptions, } impl<State> Default for HarnessBuilder<State> { fn default() -> Self { Self { screen_rect: Rect::from_min_size(Pos2::ZERO, Vec2::new(800.0, 600.0)), pixels_per_point: 1.0, theme: egui::Theme::Dark, state: PhantomData, renderer: Box::new(LazyRenderer::default()), max_steps: 4, step_dt: 1.0 / 4.0, wait_for_pending_images: true, os: egui::os::OperatingSystem::Nix, #[cfg(feature = "snapshot")] default_snapshot_options: crate::SnapshotOptions::default(), } } } impl<State> HarnessBuilder<State> { /// Set the size of the window. #[inline] pub fn with_size(mut self, size: impl Into<Vec2>) -> Self { let size = size.into(); self.screen_rect.set_width(size.x); self.screen_rect.set_height(size.y); self } /// Set the `pixels_per_point` of the window. #[inline] pub fn with_pixels_per_point(mut self, pixels_per_point: f32) -> Self { self.pixels_per_point = pixels_per_point; self } /// Set the desired theme (dark or light). #[inline] pub fn with_theme(mut self, theme: egui::Theme) -> Self { self.theme = theme; self } /// Set the default options used for snapshot tests on this harness. #[cfg(feature = "snapshot")] #[inline] pub fn with_options(mut self, options: crate::SnapshotOptions) -> Self { self.default_snapshot_options = options; self } /// Override the [`egui::os::OperatingSystem`] reported to egui. /// /// This affects e.g. the way shortcuts are displayed. So for snapshot tests, /// it makes sense to set this to a specific OS, so snapshots don't change when running /// the same tests on different OSes. /// /// Default is [`egui::os::OperatingSystem::Nix`]. /// Use [`egui::os::OperatingSystem::from_target_os()`] to use the current OS (this restores /// eguis default behavior). #[inline] pub fn with_os(mut self, os: egui::os::OperatingSystem) -> Self { self.os = os; self } /// Set the maximum number of steps to run when calling [`Harness::run`]. /// /// Default is 4. /// With the default `step_dt`, this means 1 second of simulation. #[inline] pub fn with_max_steps(mut self, max_steps: u64) -> Self { self.max_steps = max_steps; self } /// Set the time delta for a single [`Harness::step`]. /// /// Default is 1.0 / 4.0 (4fps). /// The default is low so we don't waste cpu waiting for animations. #[inline] pub fn with_step_dt(mut self, step_dt: f32) -> Self { self.step_dt = step_dt; self } /// Should we wait for pending images? /// /// If `true`, [`Harness::run`] and related methods will check if there are pending images /// (via [`egui::Context::has_pending_images`]) and sleep for [`Self::with_step_dt`] up to /// [`Self::with_max_steps`] times. /// /// Default: `true` #[inline] pub fn with_wait_for_pending_images(mut self, wait_for_pending_images: bool) -> Self { self.wait_for_pending_images = wait_for_pending_images; self } /// Set the [`TestRenderer`] to use for rendering. /// /// By default, a [`LazyRenderer`] is used. #[inline] pub fn renderer(mut self, renderer: impl TestRenderer + 'static) -> Self { self.renderer = Box::new(renderer); self } /// Enable wgpu rendering with a default setup suitable for testing. /// /// This sets up a [`crate::wgpu::WgpuTestRenderer`] with the default setup. #[cfg(feature = "wgpu")] pub fn wgpu(self) -> Self { self.renderer(crate::wgpu::WgpuTestRenderer::default()) } /// Enable wgpu rendering with the given setup. #[cfg(feature = "wgpu")] pub fn wgpu_setup(self, setup: egui_wgpu::WgpuSetup) -> Self { self.renderer(crate::wgpu::WgpuTestRenderer::from_setup(setup)) } /// Create a new Harness with the given app closure and a state. /// /// The app closure will immediately be called once to create the initial ui. /// /// If you don't need to create Windows / Panels, you can use [`HarnessBuilder::build_ui`] instead. /// /// # Example /// ```rust /// # use egui::CentralPanel; /// # use egui_kittest::{Harness, kittest::Queryable}; /// let checked = false; /// let mut harness = Harness::builder() /// .with_size(egui::Vec2::new(300.0, 200.0)) /// .build_state(|ctx, checked| { /// CentralPanel::default().show(ctx, |ui| { /// ui.checkbox(checked, "Check me!"); /// }); /// }, checked); /// /// harness.get_by_label("Check me!").click(); /// harness.run(); /// /// assert_eq!(*harness.state(), true); /// ``` #[track_caller] #[deprecated = "use `build_ui_state` instead"] pub fn build_state<'a>( self, app: impl FnMut(&egui::Context, &mut State) + 'a, state: State, ) -> Harness<'a, State> { Harness::from_builder(self, AppKind::ContextState(Box::new(app)), state, None) } /// Create a new Harness with the given ui closure and a state. /// /// The ui closure will immediately be called once to create the initial ui. /// /// If you need to create Windows / Panels, you can use [`HarnessBuilder::build`] instead. /// /// # Example /// ```rust /// # use egui_kittest::{Harness, kittest::Queryable}; /// let mut checked = false; /// let mut harness = Harness::builder() /// .with_size(egui::Vec2::new(300.0, 200.0)) /// .build_ui_state(|ui, checked| { /// ui.checkbox(checked, "Check me!"); /// }, checked); /// /// harness.get_by_label("Check me!").click(); /// harness.run(); /// /// assert_eq!(*harness.state(), true); /// ``` #[track_caller] pub fn build_ui_state<'a>( self, app: impl FnMut(&mut egui::Ui, &mut State) + 'a, state: State, ) -> Harness<'a, State> { Harness::from_builder(self, AppKind::UiState(Box::new(app)), state, None) } /// Create a new [Harness] from the given eframe creation closure. /// The app can be accessed via the [`Harness::state`] / [`Harness::state_mut`] methods. #[cfg(feature = "eframe")] #[track_caller] pub fn build_eframe<'a>( self, build: impl FnOnce(&mut eframe::CreationContext<'a>) -> State, ) -> Harness<'a, State> where State: eframe::App, { let ctx = egui::Context::default(); let mut cc = eframe::CreationContext::_new_kittest(ctx.clone()); let mut frame = eframe::Frame::_new_kittest(); self.renderer.setup_eframe(&mut cc, &mut frame); let app = build(&mut cc); let kind = AppKind::Eframe((|state| state, frame)); Harness::from_builder(self, kind, app, Some(ctx)) } } impl HarnessBuilder { /// Create a new Harness with the given app closure. /// /// The app closure will immediately be called once to create the initial ui. /// /// If you don't need to create Windows / Panels, you can use [`HarnessBuilder::build_ui`] instead. /// /// # Example /// ```rust /// # use egui::CentralPanel; /// # use egui_kittest::{Harness, kittest::Queryable}; /// let mut harness = Harness::builder() /// .with_size(egui::Vec2::new(300.0, 200.0)) /// .build(|ctx| { /// CentralPanel::default().show(ctx, |ui| { /// ui.label("Hello, world!"); /// }); /// }); /// ``` #[must_use] #[track_caller] #[deprecated = "use `build_ui` instead"] pub fn build<'a>(self, app: impl FnMut(&egui::Context) + 'a) -> Harness<'a> { Harness::from_builder(self, AppKind::Context(Box::new(app)), (), None) } /// Create a new Harness with the given ui closure. /// /// The ui closure will immediately be called once to create the initial ui. /// /// If you need to create Windows / Panels, you can use [`HarnessBuilder::build`] instead. /// /// # Example /// ```rust /// # use egui_kittest::{Harness, kittest::Queryable}; /// let mut harness = Harness::builder() /// .with_size(egui::Vec2::new(300.0, 200.0)) /// .build_ui(|ui| { /// ui.label("Hello, world!"); /// }); /// ``` #[must_use] #[track_caller] pub fn build_ui<'a>(self, app: impl FnMut(&mut egui::Ui) + 'a) -> Harness<'a> { Harness::from_builder(self, AppKind::Ui(Box::new(app)), (), None) } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_kittest/src/lib.rs
crates/egui_kittest/src/lib.rs
#![cfg_attr(doc, doc = include_str!("../README.md"))] //! //! ## Feature flags #![cfg_attr(feature = "document-features", doc = document_features::document_features!())] #![expect(clippy::unwrap_used)] // TODO(emilk): avoid unwraps mod builder; #[cfg(feature = "snapshot")] mod snapshot; #[cfg(feature = "snapshot")] pub use crate::snapshot::*; mod app_kind; mod config; mod node; mod renderer; #[cfg(feature = "wgpu")] mod texture_to_image; #[cfg(feature = "wgpu")] pub mod wgpu; // re-exports: pub use { self::{builder::*, node::*, renderer::*}, kittest, }; use std::{ fmt::{Debug, Display, Formatter}, time::Duration, }; use egui::{ Color32, Key, Modifiers, PointerButton, Pos2, Rect, RepaintCause, Shape, Vec2, ViewportId, epaint::{ClippedShape, RectShape}, style::ScrollAnimation, }; use kittest::Queryable; use crate::app_kind::AppKind; #[derive(Debug, Clone)] pub struct ExceededMaxStepsError { pub max_steps: u64, pub repaint_causes: Vec<RepaintCause>, } impl Display for ExceededMaxStepsError { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!( f, "Harness::run exceeded max_steps ({}). If your expect your ui to keep repainting \ (e.g. when showing a spinner) call Harness::step or Harness::run_steps instead.\ \nRepaint causes: {:#?}", self.max_steps, self.repaint_causes, ) } } /// The test Harness. This contains everything needed to run the test. /// /// Create a new Harness using [`Harness::new`] or [`Harness::builder`]. /// /// The [Harness] has a optional generic state that can be used to pass data to the app / ui closure. /// In _most cases_ it should be fine to just store the state in the closure itself. /// The state functions are useful if you need to access the state after the harness has been created. /// /// Some egui style options are changed from the defaults: /// - The cursor blinking is disabled /// - The scroll animation is disabled pub struct Harness<'a, State = ()> { pub ctx: egui::Context, input: egui::RawInput, kittest: kittest::State, output: egui::FullOutput, app: AppKind<'a, State>, response: Option<egui::Response>, state: State, renderer: Box<dyn TestRenderer>, max_steps: u64, step_dt: f32, wait_for_pending_images: bool, queued_events: EventQueue, #[cfg(feature = "snapshot")] default_snapshot_options: SnapshotOptions, #[cfg(feature = "snapshot")] snapshot_results: SnapshotResults, } impl<State> Debug for Harness<'_, State> { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { self.kittest.fmt(f) } } impl<'a, State> Harness<'a, State> { #[track_caller] pub(crate) fn from_builder( builder: HarnessBuilder<State>, mut app: AppKind<'a, State>, mut state: State, ctx: Option<egui::Context>, ) -> Self { let HarnessBuilder { screen_rect, pixels_per_point, theme, os, max_steps, step_dt, state: _, mut renderer, wait_for_pending_images, #[cfg(feature = "snapshot")] default_snapshot_options, } = builder; let ctx = ctx.unwrap_or_default(); ctx.set_theme(theme); ctx.set_os(os); ctx.enable_accesskit(); ctx.all_styles_mut(|style| { // Disable cursor blinking so it doesn't interfere with snapshots style.visuals.text_cursor.blink = false; style.scroll_animation = ScrollAnimation::none(); style.animation_time = 0.0; }); let mut input = egui::RawInput { screen_rect: Some(screen_rect), ..Default::default() }; let viewport = input.viewports.get_mut(&ViewportId::ROOT).unwrap(); viewport.native_pixels_per_point = Some(pixels_per_point); let mut response = None; // We need to run egui for a single frame so that the AccessKit state can be initialized // and users can immediately start querying for widgets. let mut output = ctx.run_ui(input.clone(), |ui| { response = app.run(ui, &mut state, false); }); renderer.handle_delta(&output.textures_delta); let mut harness = Self { app, ctx, input, kittest: kittest::State::new( output .platform_output .accesskit_update .take() .expect("AccessKit was disabled"), ), output, response, state, renderer, max_steps, step_dt, wait_for_pending_images, queued_events: Default::default(), #[cfg(feature = "snapshot")] default_snapshot_options, #[cfg(feature = "snapshot")] snapshot_results: SnapshotResults::default(), }; // Run the harness until it is stable, ensuring that all Areas are shown and animations are done harness.run_ok(); harness } /// Create a [`Harness`] via a [`HarnessBuilder`]. pub fn builder() -> HarnessBuilder<State> { HarnessBuilder::default() } /// Create a new Harness with the given app closure and a state. /// /// The app closure will immediately be called once to create the initial ui. /// /// If you don't need to create Windows / Panels, you can use [`Harness::new_ui`] instead. /// /// If you e.g. want to customize the size of the window, you can use [`Harness::builder`]. /// /// # Example /// ```rust /// # use egui::CentralPanel; /// # use egui_kittest::{Harness, kittest::Queryable}; /// let mut checked = false; /// let mut harness = Harness::new_state(|ctx, checked| { /// CentralPanel::default().show(ctx, |ui| { /// ui.checkbox(checked, "Check me!"); /// }); /// }, checked); /// /// harness.get_by_label("Check me!").click(); /// harness.run(); /// /// assert_eq!(*harness.state(), true); /// ``` #[track_caller] #[deprecated = "use `new_ui_state` instead"] pub fn new_state(app: impl FnMut(&egui::Context, &mut State) + 'a, state: State) -> Self { #[expect(deprecated)] Self::builder().build_state(app, state) } /// Create a new Harness with the given ui closure and a state. /// /// The ui closure will immediately be called once to create the initial ui. /// /// If you need to create Windows / Panels, you can use [`Harness::new`] instead. /// /// If you e.g. want to customize the size of the ui, you can use [`Harness::builder`]. /// /// # Example /// ```rust /// # use egui_kittest::{Harness, kittest::Queryable}; /// let mut checked = false; /// let mut harness = Harness::new_ui_state(|ui, checked| { /// ui.checkbox(checked, "Check me!"); /// }, checked); /// /// harness.get_by_label("Check me!").click(); /// harness.run(); /// /// assert_eq!(*harness.state(), true); /// ``` #[track_caller] pub fn new_ui_state(app: impl FnMut(&mut egui::Ui, &mut State) + 'a, state: State) -> Self { Self::builder().build_ui_state(app, state) } /// Create a new [Harness] from the given eframe creation closure. #[cfg(feature = "eframe")] #[track_caller] pub fn new_eframe(builder: impl FnOnce(&mut eframe::CreationContext<'a>) -> State) -> Self where State: eframe::App, { Self::builder().build_eframe(builder) } /// Set the size of the window. /// Note: If you only want to set the size once at the beginning, /// prefer using [`HarnessBuilder::with_size`]. #[inline] pub fn set_size(&mut self, size: Vec2) -> &mut Self { self.input.screen_rect = Some(Rect::from_min_size(Pos2::ZERO, size)); self } /// Set the `pixels_per_point` of the window. /// Note: If you only want to set the `pixels_per_point` once at the beginning, /// prefer using [`HarnessBuilder::with_pixels_per_point`]. #[inline] pub fn set_pixels_per_point(&mut self, pixels_per_point: f32) -> &mut Self { self.ctx.set_pixels_per_point(pixels_per_point); self } /// Run a frame for each queued event (or a single frame if there are no events). /// This will call the app closure with each queued event and /// update the Harness. pub fn step(&mut self) { let events = std::mem::take(&mut *self.queued_events.lock()); if events.is_empty() { self._step(false); } for event in events { match event { EventType::Event(event) => { self.input.events.push(event); } EventType::Modifiers(modifiers) => { self.input.modifiers = modifiers; } } self._step(false); } } /// Run a single step. This will not process any events. fn _step(&mut self, sizing_pass: bool) { self.input.predicted_dt = self.step_dt; let mut output = self.ctx.run_ui(self.input.take(), |ui| { self.response = self.app.run(ui, &mut self.state, sizing_pass); }); self.kittest.update( output .platform_output .accesskit_update .take() .expect("AccessKit was disabled"), ); self.renderer.handle_delta(&output.textures_delta); self.output = output; } /// Calculate the rect that includes all popups and tooltips. fn compute_total_rect_with_popups(&self) -> Option<Rect> { // Start with the standard response rect let mut used = if let Some(response) = self.response.as_ref() { response.rect } else { return None; }; // Add all visible areas from other orders (popups, tooltips, etc.) self.ctx.memory(|mem| { mem.areas() .visible_layer_ids() .into_iter() .filter(|layer_id| layer_id.order != egui::Order::Background) .filter_map(|layer_id| mem.area_rect(layer_id.id)) .for_each(|area_rect| used |= area_rect); }); Some(used) } /// Resize the test harness to fit the contents. This only works when creating the Harness via /// [`Harness::new_ui`] / [`Harness::new_ui_state`] or /// [`HarnessBuilder::build_ui`] / [`HarnessBuilder::build_ui_state`]. pub fn fit_contents(&mut self) { self._step(true); // Calculate size including all content (main UI + popups + tooltips) if let Some(rect) = self.compute_total_rect_with_popups() { self.set_size(rect.size()); } self.run_ok(); } /// Run until /// - all animations are done /// - no more repaints are requested /// /// Returns the number of frames that were run. /// /// # Panics /// Panics if the number of steps exceeds the maximum number of steps set /// in [`HarnessBuilder::with_max_steps`]. /// /// See also: /// - [`Harness::try_run`]. /// - [`Harness::try_run_realtime`]. /// - [`Harness::run_ok`]. /// - [`Harness::step`]. /// - [`Harness::run_steps`]. #[track_caller] pub fn run(&mut self) -> u64 { match self.try_run() { Ok(steps) => steps, Err(err) => { panic!("{err}"); } } } fn _try_run(&mut self, sleep: bool) -> Result<u64, ExceededMaxStepsError> { let mut steps = 0; loop { steps += 1; self.step(); let wait_for_images = self.wait_for_pending_images && self.ctx.has_pending_images(); // We only care about immediate repaints if self.root_viewport_output().repaint_delay != Duration::ZERO && !wait_for_images { break; } else if sleep || wait_for_images { std::thread::sleep(Duration::from_secs_f32(self.step_dt)); } if steps > self.max_steps { return Err(ExceededMaxStepsError { max_steps: self.max_steps, repaint_causes: self.ctx.repaint_causes(), }); } } Ok(steps) } /// Run until /// - all animations are done /// - no more repaints are requested /// - the maximum number of steps is reached (See [`HarnessBuilder::with_max_steps`]) /// /// Returns the number of steps that were run. /// /// # Errors /// Returns an error if the maximum number of steps is exceeded. /// /// See also: /// - [`Harness::run`]. /// - [`Harness::run_ok`]. /// - [`Harness::step`]. /// - [`Harness::run_steps`]. /// - [`Harness::try_run_realtime`]. pub fn try_run(&mut self) -> Result<u64, ExceededMaxStepsError> { self._try_run(false) } /// Run until /// - all animations are done /// - no more repaints are requested /// - the maximum number of steps is reached (See [`HarnessBuilder::with_max_steps`]) /// /// Returns the number of steps that were run, or None if the maximum number of steps was exceeded. /// /// See also: /// - [`Harness::run`]. /// - [`Harness::try_run`]. /// - [`Harness::step`]. /// - [`Harness::run_steps`]. /// - [`Harness::try_run_realtime`]. pub fn run_ok(&mut self) -> Option<u64> { self.try_run().ok() } /// Run multiple frames, sleeping for [`HarnessBuilder::with_step_dt`] between frames. /// /// This is useful to e.g. wait for an async operation to complete (e.g. loading of images). /// Runs until /// - all animations are done /// - no more repaints are requested /// - the maximum number of steps is reached (See [`HarnessBuilder::with_max_steps`]) /// /// Returns the number of steps that were run. /// /// # Errors /// Returns an error if the maximum number of steps is exceeded. /// /// See also: /// - [`Harness::run`]. /// - [`Harness::run_ok`]. /// - [`Harness::step`]. /// - [`Harness::run_steps`]. /// - [`Harness::try_run`]. pub fn try_run_realtime(&mut self) -> Result<u64, ExceededMaxStepsError> { self._try_run(true) } /// Run a number of steps. /// Equivalent to calling [`Harness::step`] x times. pub fn run_steps(&mut self, steps: usize) { for _ in 0..steps { self.step(); } } /// Access the [`egui::RawInput`] for the next frame. pub fn input(&self) -> &egui::RawInput { &self.input } /// Access the [`egui::RawInput`] for the next frame mutably. pub fn input_mut(&mut self) -> &mut egui::RawInput { &mut self.input } /// Access the [`egui::FullOutput`] for the last frame. pub fn output(&self) -> &egui::FullOutput { &self.output } /// Access the [`kittest::State`]. pub fn kittest_state(&self) -> &kittest::State { &self.kittest } /// Access the state. pub fn state(&self) -> &State { &self.state } /// Access the state mutably. pub fn state_mut(&mut self) -> &mut State { &mut self.state } /// Queue an event to be processed in the next frame. pub fn event(&self, event: egui::Event) { self.queued_events.lock().push(EventType::Event(event)); } /// Queue an event with modifiers. /// /// Queues the modifiers to be pressed, then the event, then the modifiers to be released. pub fn event_modifiers(&self, event: egui::Event, modifiers: Modifiers) { let mut queue = self.queued_events.lock(); queue.push(EventType::Modifiers(modifiers)); queue.push(EventType::Event(event)); queue.push(EventType::Modifiers(Modifiers::default())); } fn modifiers(&self, modifiers: Modifiers) { self.queued_events .lock() .push(EventType::Modifiers(modifiers)); } pub fn key_down(&self, key: egui::Key) { self.event(egui::Event::Key { key, pressed: true, modifiers: Modifiers::default(), repeat: false, physical_key: None, }); } pub fn key_down_modifiers(&self, modifiers: Modifiers, key: egui::Key) { self.event_modifiers( egui::Event::Key { key, pressed: true, modifiers, repeat: false, physical_key: None, }, modifiers, ); } pub fn key_up(&self, key: egui::Key) { self.event(egui::Event::Key { key, pressed: false, modifiers: Modifiers::default(), repeat: false, physical_key: None, }); } pub fn key_up_modifiers(&self, modifiers: Modifiers, key: egui::Key) { self.event_modifiers( egui::Event::Key { key, pressed: false, modifiers, repeat: false, physical_key: None, }, modifiers, ); } /// Press the given keys in combination. /// /// For e.g. [`Key::A`] + [`Key::B`] this would generate: /// - Press [`Key::A`] /// - Press [`Key::B`] /// - Release [`Key::B`] /// - Release [`Key::A`] pub fn key_combination(&self, keys: &[Key]) { for key in keys { self.key_down(*key); } for key in keys.iter().rev() { self.key_up(*key); } } /// Press the given keys in combination, with modifiers. /// /// For e.g. [`Modifiers::COMMAND`] + [`Key::A`] + [`Key::B`] this would generate: /// - Press [`Modifiers::COMMAND`] /// - Press [`Key::A`] /// - Press [`Key::B`] /// - Release [`Key::B`] /// - Release [`Key::A`] /// - Release [`Modifiers::COMMAND`] pub fn key_combination_modifiers(&self, modifiers: Modifiers, keys: &[Key]) { self.modifiers(modifiers); for pressed in [true, false] { for key in keys { self.event(egui::Event::Key { key: *key, pressed, modifiers, repeat: false, physical_key: None, }); } } self.modifiers(Modifiers::default()); } /// Press a key. /// /// This will create a key down event and a key up event. pub fn key_press(&self, key: egui::Key) { self.key_combination(&[key]); } /// Press a key with modifiers. /// /// This will /// - set the modifiers /// - create a key down event /// - create a key up event /// - reset the modifiers pub fn key_press_modifiers(&self, modifiers: Modifiers, key: egui::Key) { self.key_combination_modifiers(modifiers, &[key]); } /// Move mouse cursor to this position. pub fn hover_at(&self, pos: egui::Pos2) { self.event(egui::Event::PointerMoved(pos)); } /// Start dragging from a position. pub fn drag_at(&self, pos: egui::Pos2) { self.event(egui::Event::PointerButton { pos, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE, }); } /// Stop dragging and remove cursor. pub fn drop_at(&self, pos: egui::Pos2) { self.event(egui::Event::PointerButton { pos, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE, }); self.remove_cursor(); } /// Remove the cursor from the screen. /// /// Will fire a [`egui::Event::PointerGone`] event. /// /// If you click a button and then take a snapshot, the button will be shown as hovered. /// If you don't want that, you can call this method after clicking. pub fn remove_cursor(&self) { self.event(egui::Event::PointerGone); } /// Mask something. Useful for snapshot tests. /// /// Call this _after_ [`Self::run`] and before [`Self::snapshot`]. /// This will add a [`RectShape`] to the output shapes, for the current frame. /// Will be overwritten on the next call to [`Self::run`]. pub fn mask(&mut self, rect: Rect) { self.output.shapes.push(ClippedShape { clip_rect: Rect::EVERYTHING, shape: Shape::Rect(RectShape::filled(rect, 0.0, Color32::MAGENTA)), }); } /// Render the last output to an image. /// /// # Errors /// Returns an error if the rendering fails. #[cfg(any(feature = "wgpu", feature = "snapshot"))] pub fn render(&mut self) -> Result<image::RgbaImage, String> { let mut output = self.output.clone(); if let Some(mouse_pos) = self.ctx.input(|i| i.pointer.hover_pos()) { // Paint a mouse cursor: let triangle = vec![ mouse_pos, mouse_pos + egui::vec2(16.0, 8.0), mouse_pos + egui::vec2(8.0, 16.0), ]; output.shapes.push(ClippedShape { clip_rect: self.ctx.content_rect(), shape: egui::epaint::PathShape::convex_polygon( triangle, Color32::WHITE, egui::Stroke::new(1.0, Color32::BLACK), ) .into(), }); } self.renderer.render(&self.ctx, &output) } /// Get the root viewport output fn root_viewport_output(&self) -> &egui::ViewportOutput { self.output .viewport_output .get(&ViewportId::ROOT) .expect("Missing root viewport") } /// The root node of the test harness. pub fn root(&self) -> Node<'_> { Node { accesskit_node: self.kittest.root(), queue: &self.queued_events, } } #[deprecated = "Use `Harness::root` instead."] pub fn node(&self) -> Node<'_> { self.root() } } /// Utilities for stateless harnesses. impl<'a> Harness<'a> { /// Create a new Harness with the given app closure. /// Use the [`Harness::run`], [`Harness::step`], etc... methods to run the app. /// /// The app closure will immediately be called once to create the initial ui. /// /// If you don't need to create Windows / Panels, you can use [`Harness::new_ui`] instead. /// /// If you e.g. want to customize the size of the window, you can use [`Harness::builder`]. /// /// # Example /// ```rust /// # use egui::CentralPanel; /// # use egui_kittest::Harness; /// let mut harness = Harness::new(|ctx| { /// CentralPanel::default().show(ctx, |ui| { /// ui.label("Hello, world!"); /// }); /// }); /// ``` #[track_caller] #[deprecated = "use `new_ui` instead"] pub fn new(app: impl FnMut(&egui::Context) + 'a) -> Self { #[expect(deprecated)] Self::builder().build(app) } /// Create a new Harness with the given ui closure. /// Use the [`Harness::run`], [`Harness::step`], etc... methods to run the app. /// /// The ui closure will immediately be called once to create the initial ui. /// /// If you need to create Windows / Panels, you can use [`Harness::new`] instead. /// /// If you e.g. want to customize the size of the ui, you can use [`Harness::builder`]. /// /// # Example /// ```rust /// # use egui_kittest::Harness; /// let mut harness = Harness::new_ui(|ui| { /// ui.label("Hello, world!"); /// }); /// ``` #[track_caller] pub fn new_ui(app: impl FnMut(&mut egui::Ui) + 'a) -> Self { Self::builder().build_ui(app) } } impl<'tree, 'node, State> Queryable<'tree, 'node, Node<'tree>> for Harness<'_, State> where 'node: 'tree, { fn queryable_node(&'node self) -> Node<'tree> { self.root() } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_kittest/src/renderer.rs
crates/egui_kittest/src/renderer.rs
use egui::TexturesDelta; pub trait TestRenderer { /// We use this to pass the glow / wgpu render state to [`eframe::Frame`]. #[cfg(feature = "eframe")] fn setup_eframe(&self, _cc: &mut eframe::CreationContext<'_>, _frame: &mut eframe::Frame) {} /// Handle a [`TexturesDelta`] by updating the renderer's textures. fn handle_delta(&mut self, delta: &TexturesDelta); /// Render the [`crate::Harness`] and return the resulting image. /// /// # Errors /// Returns an error if the rendering fails. #[cfg(any(feature = "wgpu", feature = "snapshot"))] fn render( &mut self, ctx: &egui::Context, output: &egui::FullOutput, ) -> Result<image::RgbaImage, String>; } /// A lazy renderer that initializes the renderer on the first render call. /// /// By default, this will create a wgpu renderer if the wgpu feature is enabled. pub enum LazyRenderer { Uninitialized { texture_ops: Vec<egui::TexturesDelta>, builder: Option<Box<dyn FnOnce() -> Box<dyn TestRenderer>>>, }, Initialized { renderer: Box<dyn TestRenderer>, }, } impl Default for LazyRenderer { fn default() -> Self { #[cfg(feature = "wgpu")] return Self::new(crate::wgpu::WgpuTestRenderer::new); #[cfg(not(feature = "wgpu"))] return Self::Uninitialized { texture_ops: Vec::new(), builder: None, }; } } impl LazyRenderer { pub fn new<T: TestRenderer + 'static>(create_renderer: impl FnOnce() -> T + 'static) -> Self { Self::Uninitialized { texture_ops: Vec::new(), builder: Some(Box::new(move || Box::new(create_renderer()))), } } } impl TestRenderer for LazyRenderer { fn handle_delta(&mut self, delta: &TexturesDelta) { match self { Self::Uninitialized { texture_ops, .. } => texture_ops.push(delta.clone()), Self::Initialized { renderer } => renderer.handle_delta(delta), } } #[cfg(any(feature = "wgpu", feature = "snapshot"))] fn render( &mut self, ctx: &egui::Context, output: &egui::FullOutput, ) -> Result<image::RgbaImage, String> { match self { Self::Uninitialized { texture_ops, builder: build, } => { let mut renderer = build.take().ok_or({ "No default renderer available. \ Enable the wgpu feature or set one via HarnessBuilder::renderer" })?(); for delta in texture_ops.drain(..) { renderer.handle_delta(&delta); } let image = renderer.render(ctx, output)?; *self = Self::Initialized { renderer }; Ok(image) } Self::Initialized { renderer } => renderer.render(ctx, output), } } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_kittest/src/wgpu.rs
crates/egui_kittest/src/wgpu.rs
use std::sync::Arc; use std::{iter::once, time::Duration}; use egui::TexturesDelta; use egui_wgpu::{RenderState, ScreenDescriptor, WgpuSetup, wgpu}; use image::RgbaImage; use crate::texture_to_image::texture_to_image; /// Timeout for waiting on the GPU to finish rendering. /// /// Windows will reset native drivers after 2 seconds of being stuck (known was TDR - timeout detection & recovery). /// However, software rasterizers like lavapipe may not do that and take longer if there's a lot of work in flight. /// In the end, what we really want to protect here against is undetected errors that lead to device loss /// and therefore infinite waits it happens occasionally on MacOS/Metal as of writing. pub(crate) const WAIT_TIMEOUT: Duration = Duration::from_secs(10); /// Default wgpu setup used for the wgpu renderer. pub fn default_wgpu_setup() -> egui_wgpu::WgpuSetup { let mut setup = egui_wgpu::WgpuSetupCreateNew::default(); // WebGPU not supported yet since we rely on blocking screenshots. setup .instance_descriptor .backends .remove(wgpu::Backends::BROWSER_WEBGPU); // Prefer software rasterizers. setup.native_adapter_selector = Some(Arc::new(|adapters, _surface| { let mut adapters = adapters.iter().collect::<Vec<_>>(); // Adapters are already sorted by preferred backend by wgpu, but let's be explicit. adapters.sort_by_key(|a| match a.get_info().backend { wgpu::Backend::Metal => 0, wgpu::Backend::Vulkan => 1, wgpu::Backend::Dx12 => 2, wgpu::Backend::Gl => 4, wgpu::Backend::BrowserWebGpu => 6, wgpu::Backend::Noop => 7, }); // Prefer CPU adapters, otherwise if we can't, prefer discrete GPU over integrated GPU. adapters.sort_by_key(|a| match a.get_info().device_type { wgpu::DeviceType::Cpu => 0, // CPU is the best for our purposes! wgpu::DeviceType::DiscreteGpu => 1, wgpu::DeviceType::Other | wgpu::DeviceType::IntegratedGpu | wgpu::DeviceType::VirtualGpu => 2, }); adapters .first() .map(|a| (*a).clone()) .ok_or_else(|| "No adapter found".to_owned()) })); egui_wgpu::WgpuSetup::CreateNew(setup) } pub fn create_render_state(setup: WgpuSetup) -> egui_wgpu::RenderState { let instance = pollster::block_on(setup.new_instance()); pollster::block_on(egui_wgpu::RenderState::create( &egui_wgpu::WgpuConfiguration { wgpu_setup: setup, ..Default::default() }, &instance, None, egui_wgpu::RendererOptions::PREDICTABLE, )) .expect("Failed to create render state") } /// Utility to render snapshots from a [`crate::Harness`] using [`egui_wgpu`]. pub struct WgpuTestRenderer { render_state: RenderState, } impl Default for WgpuTestRenderer { fn default() -> Self { Self::new() } } impl WgpuTestRenderer { /// Create a new [`WgpuTestRenderer`] with the default setup. pub fn new() -> Self { Self { render_state: create_render_state(default_wgpu_setup()), } } /// Create a new [`WgpuTestRenderer`] with the given setup. pub fn from_setup(setup: WgpuSetup) -> Self { Self { render_state: create_render_state(setup), } } /// Create a new [`WgpuTestRenderer`] from an existing [`RenderState`]. /// /// # Panics /// Panics if the [`RenderState`] has been used before. pub fn from_render_state(render_state: RenderState) -> Self { assert!( render_state .renderer .read() .texture(&egui::epaint::TextureId::Managed(0)) .is_none(), "The RenderState passed in has been used before, pass in a fresh RenderState instead." ); Self { render_state } } } impl crate::TestRenderer for WgpuTestRenderer { #[cfg(feature = "eframe")] fn setup_eframe(&self, cc: &mut eframe::CreationContext<'_>, frame: &mut eframe::Frame) { cc.wgpu_render_state = Some(self.render_state.clone()); frame.wgpu_render_state = Some(self.render_state.clone()); } fn handle_delta(&mut self, delta: &TexturesDelta) { let mut renderer = self.render_state.renderer.write(); for (id, image) in &delta.set { renderer.update_texture( &self.render_state.device, &self.render_state.queue, *id, image, ); } } /// Render the [`crate::Harness`] and return the resulting image. fn render( &mut self, ctx: &egui::Context, output: &egui::FullOutput, ) -> Result<RgbaImage, String> { let mut renderer = self.render_state.renderer.write(); let mut encoder = self.render_state .device .create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("Egui Command Encoder"), }); let size = ctx.content_rect().size() * ctx.pixels_per_point(); let screen = ScreenDescriptor { pixels_per_point: ctx.pixels_per_point(), size_in_pixels: [size.x.round() as u32, size.y.round() as u32], }; let tessellated = ctx.tessellate(output.shapes.clone(), ctx.pixels_per_point()); let user_buffers = renderer.update_buffers( &self.render_state.device, &self.render_state.queue, &mut encoder, &tessellated, &screen, ); let texture = self .render_state .device .create_texture(&wgpu::TextureDescriptor { label: Some("Egui Texture"), size: wgpu::Extent3d { width: screen.size_in_pixels[0], height: screen.size_in_pixels[1], depth_or_array_layers: 1, }, mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2, format: self.render_state.target_format, usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC, view_formats: &[], }); let texture_view = texture.create_view(&wgpu::TextureViewDescriptor::default()); { let mut pass = encoder .begin_render_pass(&wgpu::RenderPassDescriptor { label: Some("Egui Render Pass"), color_attachments: &[Some(wgpu::RenderPassColorAttachment { view: &texture_view, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), store: wgpu::StoreOp::Store, }, depth_slice: None, })], ..Default::default() }) .forget_lifetime(); renderer.render(&mut pass, &tessellated, &screen); } self.render_state .queue .submit(user_buffers.into_iter().chain(once(encoder.finish()))); self.render_state .device .poll(wgpu::PollType::Wait { submission_index: None, timeout: Some(WAIT_TIMEOUT), }) .map_err(|err| format!("PollError: {err}"))?; Ok(texture_to_image( &self.render_state.device, &self.render_state.queue, &texture, )) } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_kittest/src/snapshot.rs
crates/egui_kittest/src/snapshot.rs
use std::fmt::Display; use std::io::ErrorKind; use std::path::PathBuf; use image::ImageError; use crate::{Harness, config::config}; pub type SnapshotResult = Result<(), SnapshotError>; #[non_exhaustive] #[derive(Clone, Debug)] pub struct SnapshotOptions { /// The threshold for the image comparison. /// /// Can be configured via kittest.toml. The fallback is `0.6` (which is enough for most egui /// tests to pass across different wgpu backends). pub threshold: f32, /// The number of pixels that can differ before the snapshot is considered a failure. /// /// Preferably, you should use `threshold` to control the sensitivity of the image comparison. /// As a last resort, you can use this to allow a certain number of pixels to differ. /// Can be configured via kittest.toml. The fallback is `0` (meaning no pixels can differ). pub failed_pixel_count_threshold: usize, /// The path where the snapshots will be saved. /// /// This is relative to the current working directory (usually the crate root when /// running tests). /// /// Can be configured via kittest.toml. The fallback is `tests/snapshots`. pub output_path: PathBuf, } /// Helper struct to define the number of pixels that can differ before the snapshot is considered a failure. /// /// This is useful if you want to set different thresholds for different operating systems. /// /// [`OsThreshold::default`] gets the default from the config file (`kittest.toml`). /// For `usize`, it's the `failed_pixel_count_threshold` value. /// For `f32`, it's the `threshold` value. /// /// Example usage: /// ```no_run /// use egui_kittest::{OsThreshold, SnapshotOptions}; /// let mut harness = egui_kittest::Harness::new_ui(|ui| { /// ui.label("Hi!"); /// }); /// harness.snapshot_options( /// "os_threshold_example", /// &SnapshotOptions::new() /// .threshold(OsThreshold::new(0.0).windows(10.0)) /// .failed_pixel_count_threshold(OsThreshold::new(0).windows(10).macos(53) /// )) /// ``` #[derive(Debug, Clone, Copy)] pub struct OsThreshold<T> { pub windows: T, pub macos: T, pub linux: T, pub fallback: T, } impl Default for OsThreshold<usize> { /// Returns the default `failed_pixel_count_threshold` as configured in `kittest.toml` /// /// The fallback is `0`. fn default() -> Self { config().os_failed_pixel_count_threshold() } } impl Default for OsThreshold<f32> { /// Returns the default `threshold` as configured in `kittest.toml` /// /// The fallback is `0.6`. fn default() -> Self { config().os_threshold() } } impl From<usize> for OsThreshold<usize> { fn from(value: usize) -> Self { Self::new(value) } } impl From<f32> for OsThreshold<f32> { fn from(value: f32) -> Self { Self::new(value) } } impl<T> OsThreshold<T> where T: Copy, { /// Use the same value for all pub fn new(same: T) -> Self { Self { windows: same, macos: same, linux: same, fallback: same, } } /// Set the threshold for Windows. #[inline] pub fn windows(mut self, threshold: T) -> Self { self.windows = threshold; self } /// Set the threshold for macOS. #[inline] pub fn macos(mut self, threshold: T) -> Self { self.macos = threshold; self } /// Set the threshold for Linux. #[inline] pub fn linux(mut self, threshold: T) -> Self { self.linux = threshold; self } /// Get the threshold for the current operating system. pub fn threshold(&self) -> T { if cfg!(target_os = "windows") { self.windows } else if cfg!(target_os = "macos") { self.macos } else if cfg!(target_os = "linux") { self.linux } else { self.fallback } } } impl From<OsThreshold<Self>> for usize { fn from(threshold: OsThreshold<Self>) -> Self { threshold.threshold() } } impl From<OsThreshold<Self>> for f32 { fn from(threshold: OsThreshold<Self>) -> Self { threshold.threshold() } } impl Default for SnapshotOptions { fn default() -> Self { Self { threshold: config().threshold(), output_path: config().output_path(), failed_pixel_count_threshold: config().failed_pixel_count_threshold(), } } } impl SnapshotOptions { /// Create a new [`SnapshotOptions`] with the default values. pub fn new() -> Self { Default::default() } /// Change the threshold for the image comparison. /// The default is `0.6` (which is enough for most egui tests to pass across different /// wgpu backends). #[inline] pub fn threshold(mut self, threshold: impl Into<f32>) -> Self { self.threshold = threshold.into(); self } /// Change the path where the snapshots will be saved. /// The default is `tests/snapshots`. #[inline] pub fn output_path(mut self, output_path: impl Into<PathBuf>) -> Self { self.output_path = output_path.into(); self } /// Change the number of pixels that can differ before the snapshot is considered a failure. /// /// Preferably, you should use [`Self::threshold`] to control the sensitivity of the image comparison. /// As a last resort, you can use this to allow a certain number of pixels to differ. #[inline] pub fn failed_pixel_count_threshold( mut self, failed_pixel_count_threshold: impl Into<OsThreshold<usize>>, ) -> Self { let failed_pixel_count_threshold = failed_pixel_count_threshold.into().threshold(); self.failed_pixel_count_threshold = failed_pixel_count_threshold; self } } #[derive(Debug)] pub enum SnapshotError { /// Image did not match snapshot Diff { /// Name of the test name: String, /// Count of pixels that were different (above the per-pixel threshold). diff: i32, /// Path where the diff image was saved diff_path: PathBuf, }, /// Error opening the existing snapshot (it probably doesn't exist, check the /// [`ImageError`] for more information) OpenSnapshot { /// Path where the snapshot was expected to be path: PathBuf, /// The error that occurred err: ImageError, }, /// The size of the image did not match the snapshot SizeMismatch { /// Name of the test name: String, /// Expected size expected: (u32, u32), /// Actual size actual: (u32, u32), }, /// Error writing the snapshot output WriteSnapshot { /// Path where a file was expected to be written path: PathBuf, /// The error that occurred err: ImageError, }, /// Error rendering the image RenderError { /// The error that occurred err: String, }, } const HOW_TO_UPDATE_SCREENSHOTS: &str = "Run `UPDATE_SNAPSHOTS=1 cargo test --all-features` to update the snapshots."; impl Display for SnapshotError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Diff { name, diff, diff_path, } => { let diff_path = std::path::absolute(diff_path).unwrap_or_else(|_| diff_path.clone()); write!( f, "'{name}' Image did not match snapshot. Diff: {diff}, {}. {HOW_TO_UPDATE_SCREENSHOTS}", diff_path.display() ) } Self::OpenSnapshot { path, err } => { let path = std::path::absolute(path).unwrap_or_else(|_| path.clone()); match err { ImageError::IoError(io) => match io.kind() { ErrorKind::NotFound => { write!( f, "Missing snapshot: {}. {HOW_TO_UPDATE_SCREENSHOTS}", path.display() ) } err => { write!( f, "Error reading snapshot: {err}\nAt: {}. {HOW_TO_UPDATE_SCREENSHOTS}", path.display() ) } }, err => { write!( f, "Error decoding snapshot: {err}\nAt: {}. Make sure git-lfs is setup correctly. Read the instructions here: https://github.com/emilk/egui/blob/main/CONTRIBUTING.md#making-a-pr", path.display() ) } } } Self::SizeMismatch { name, expected, actual, } => { write!( f, "'{name}' Image size did not match snapshot. Expected: {expected:?}, Actual: {actual:?}. {HOW_TO_UPDATE_SCREENSHOTS}" ) } Self::WriteSnapshot { path, err } => { let path = std::path::absolute(path).unwrap_or_else(|_| path.clone()); write!(f, "Error writing snapshot: {err}\nAt: {}", path.display()) } Self::RenderError { err } => { write!(f, "Error rendering image: {err}") } } } } #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Mode { Test, UpdateFailing, UpdateAll, } impl Mode { fn from_env() -> Self { let Ok(value) = std::env::var("UPDATE_SNAPSHOTS") else { return Self::Test; }; match value.as_str() { "false" | "0" | "no" | "off" => Self::Test, "true" | "1" | "yes" | "on" => Self::UpdateFailing, "force" => Self::UpdateAll, unknown => { panic!("Unsupported value for UPDATE_SNAPSHOTS: {unknown:?}"); } } } fn is_update(&self) -> bool { match self { Self::Test => false, Self::UpdateFailing | Self::UpdateAll => true, } } } /// Image snapshot test with custom options. /// /// If you want to change the default options for your whole project, it's recommended to create a /// new `my_image_snapshot` function in your project that calls this function with the desired options. /// You could additionally use the /// [disallowed_methods](https://rust-lang.github.io/rust-clippy/master/#disallowed_methods) /// lint to disable use of the [`image_snapshot`] to prevent accidentally using the wrong defaults. /// /// The snapshot files will be saved under [`SnapshotOptions::output_path`]. /// The snapshot will be saved under `{output_path}/{name}.png`. /// The new image from the most recent test run will be saved under `{output_path}/{name}.new.png`. /// If the new image didn't match the snapshot, a diff image will be saved under `{output_path}/{name}.diff.png`. /// /// If the env-var `UPDATE_SNAPSHOTS` is set, then the old image will backed up under `{output_path}/{name}.old.png`. /// and then new image will be written to `{output_path}/{name}.png` /// /// # Errors /// Returns a [`SnapshotError`] if the image does not match the snapshot or if there was an error /// reading or writing the snapshot. pub fn try_image_snapshot_options( new: &image::RgbaImage, name: impl Into<String>, options: &SnapshotOptions, ) -> SnapshotResult { try_image_snapshot_options_impl(new, name.into(), options) } fn try_image_snapshot_options_impl( new: &image::RgbaImage, name: String, options: &SnapshotOptions, ) -> SnapshotResult { #![expect(clippy::print_stdout)] let mode = Mode::from_env(); let SnapshotOptions { threshold, output_path, failed_pixel_count_threshold, } = options; let parent_path = if let Some(parent) = PathBuf::from(&name).parent() { output_path.join(parent) } else { output_path.clone() }; std::fs::create_dir_all(parent_path).ok(); // The one that is checked in to git let snapshot_path = output_path.join(format!("{name}.png")); // These should be in .gitignore: let diff_path = output_path.join(format!("{name}.diff.png")); let old_backup_path = output_path.join(format!("{name}.old.png")); let new_path = output_path.join(format!("{name}.new.png")); // Delete old temporary files if they exist: std::fs::remove_file(&diff_path).ok(); std::fs::remove_file(&old_backup_path).ok(); std::fs::remove_file(&new_path).ok(); let update_snapshot = || { // Keep the old version so the user can compare it: std::fs::rename(&snapshot_path, &old_backup_path).ok(); // Write the new file to the checked in path: new.save(&snapshot_path) .map_err(|err| SnapshotError::WriteSnapshot { err, path: snapshot_path.clone(), })?; // No need for an explicit `.new` file: std::fs::remove_file(&new_path).ok(); println!("Updated snapshot: {}", snapshot_path.display()); Ok(()) }; let write_new_png = || { new.save(&new_path) .map_err(|err| SnapshotError::WriteSnapshot { err, path: new_path.clone(), })?; Ok(()) }; let previous = match image::open(&snapshot_path) { Ok(image) => image.to_rgba8(), Err(err) => { // No previous snapshot - probably a new test. if mode.is_update() { return update_snapshot(); } else { write_new_png()?; return Err(SnapshotError::OpenSnapshot { path: snapshot_path.clone(), err, }); } } }; if previous.dimensions() != new.dimensions() { if mode.is_update() { return update_snapshot(); } else { write_new_png()?; return Err(SnapshotError::SizeMismatch { name, expected: previous.dimensions(), actual: new.dimensions(), }); } } // Compare existing image to the new one: let threshold = if mode == Mode::UpdateAll { 0.0 // Produce diff for any error, however small } else { *threshold }; let result = dify::diff::get_results(previous, new.clone(), threshold, true, None, &None, &None); let Some((num_wrong_pixels, diff_image)) = result else { return Ok(()); // Difference below threshold }; let below_threshold = num_wrong_pixels as i64 <= *failed_pixel_count_threshold as i64; if !below_threshold { diff_image .save(diff_path.clone()) .map_err(|err| SnapshotError::WriteSnapshot { path: diff_path.clone(), err, })?; } match mode { Mode::Test => { if below_threshold { Ok(()) } else { write_new_png()?; Err(SnapshotError::Diff { name, diff: num_wrong_pixels, diff_path, }) } } Mode::UpdateFailing => { if below_threshold { Ok(()) } else { update_snapshot() } } Mode::UpdateAll => update_snapshot(), } } /// Image snapshot test. /// /// This uses the default [`SnapshotOptions`]. Use [`try_image_snapshot_options`] if you want to /// e.g. change the threshold or output path. /// /// The snapshot files will be saved under [`SnapshotOptions::output_path`]. /// The snapshot will be saved under `{output_path}/{name}.png`. /// The new image from the most recent test run will be saved under `{output_path}/{name}.new.png`. /// If the new image didn't match the snapshot, a diff image will be saved under `{output_path}/{name}.diff.png`. /// /// # Errors /// Returns a [`SnapshotError`] if the image does not match the snapshot or if there was an error /// reading or writing the snapshot. pub fn try_image_snapshot(current: &image::RgbaImage, name: impl Into<String>) -> SnapshotResult { try_image_snapshot_options(current, name, &SnapshotOptions::default()) } /// Image snapshot test with custom options. /// /// If you want to change the default options for your whole project, it's recommended to create a /// new `my_image_snapshot` function in your project that calls this function with the desired options. /// You could additionally use the /// [disallowed_methods](https://rust-lang.github.io/rust-clippy/master/#disallowed_methods) /// lint to disable use of the [`image_snapshot`] to prevent accidentally using the wrong defaults. /// /// The snapshot files will be saved under [`SnapshotOptions::output_path`]. /// The snapshot will be saved under `{output_path}/{name}.png`. /// The new image from the most recent test run will be saved under `{output_path}/{name}.new.png`. /// If the new image didn't match the snapshot, a diff image will be saved under `{output_path}/{name}.diff.png`. /// /// # Panics /// Panics if the image does not match the snapshot or if there was an error reading or writing the /// snapshot. #[track_caller] pub fn image_snapshot_options( current: &image::RgbaImage, name: impl Into<String>, options: &SnapshotOptions, ) { match try_image_snapshot_options(current, name, options) { Ok(_) => {} Err(err) => { panic!("{err}"); } } } /// Image snapshot test. /// /// The snapshot will be saved under `tests/snapshots/{name}.png`. /// The new image from the last test run will be saved under `tests/snapshots/{name}.new.png`. /// If the new image didn't match the snapshot, a diff image will be saved under `tests/snapshots/{name}.diff.png`. /// /// # Panics /// Panics if the image does not match the snapshot or if there was an error reading or writing the /// snapshot. #[track_caller] pub fn image_snapshot(current: &image::RgbaImage, name: impl Into<String>) { match try_image_snapshot(current, name) { Ok(_) => {} Err(err) => { panic!("{err}"); } } } #[cfg(any(feature = "wgpu", feature = "snapshot"))] impl<State> Harness<'_, State> { /// The default options used for snapshot tests. /// set by [`crate::HarnessBuilder::with_options`]. pub fn options(&self) -> &SnapshotOptions { &self.default_snapshot_options } /// Render an image using the setup [`crate::TestRenderer`] and compare it to the snapshot /// with custom options. /// /// These options will override the ones set by [`crate::HarnessBuilder::with_options`]. /// /// If you want to change the default options for your whole project, you could create an /// [extension trait](http://xion.io/post/code/rust-extension-traits.html) to create a /// new `my_image_snapshot` function on the Harness that calls this function with the desired options. /// You could additionally use the /// [disallowed_methods](https://rust-lang.github.io/rust-clippy/master/#disallowed_methods) /// lint to disable use of the [`Harness::snapshot`] to prevent accidentally using the wrong defaults. /// /// The snapshot files will be saved under [`SnapshotOptions::output_path`]. /// The snapshot will be saved under `{output_path}/{name}.png`. /// The new image from the most recent test run will be saved under `{output_path}/{name}.new.png`. /// If the new image didn't match the snapshot, a diff image will be saved under `{output_path}/{name}.diff.png`. /// /// # Errors /// Returns a [`SnapshotError`] if the image does not match the snapshot, if there was an /// error reading or writing the snapshot, if the rendering fails or if no default renderer is available. pub fn try_snapshot_options( &mut self, name: impl Into<String>, options: &SnapshotOptions, ) -> SnapshotResult { let image = self .render() .map_err(|err| SnapshotError::RenderError { err })?; try_image_snapshot_options(&image, name.into(), options) } /// Render an image using the setup [`crate::TestRenderer`] and compare it to the snapshot. /// /// This is like [`Self::try_snapshot_options`] but will use the options set by [`crate::HarnessBuilder::with_options`]. /// /// The snapshot will be saved under `tests/snapshots/{name}.png`. /// The new image from the last test run will be saved under `tests/snapshots/{name}.new.png`. /// If the new image didn't match the snapshot, a diff image will be saved under `tests/snapshots/{name}.diff.png`. /// /// # Errors /// Returns a [`SnapshotError`] if the image does not match the snapshot, if there was an /// error reading or writing the snapshot, if the rendering fails or if no default renderer is available. pub fn try_snapshot(&mut self, name: impl Into<String>) -> SnapshotResult { let image = self .render() .map_err(|err| SnapshotError::RenderError { err })?; try_image_snapshot_options(&image, name.into(), &self.default_snapshot_options) } /// Render an image using the setup [`crate::TestRenderer`] and compare it to the snapshot /// with custom options. /// /// These options will override the ones set by [`crate::HarnessBuilder::with_options`]. /// /// If you want to change the default options for your whole project, you could create an /// [extension trait](http://xion.io/post/code/rust-extension-traits.html) to create a /// new `my_image_snapshot` function on the Harness that calls this function with the desired options. /// You could additionally use the /// [disallowed_methods](https://rust-lang.github.io/rust-clippy/master/#disallowed_methods) /// lint to disable use of the [`Harness::snapshot`] to prevent accidentally using the wrong defaults. /// /// The snapshot files will be saved under [`SnapshotOptions::output_path`]. /// The snapshot will be saved under `{output_path}/{name}.png`. /// The new image from the most recent test run will be saved under `{output_path}/{name}.new.png`. /// If the new image didn't match the snapshot, a diff image will be saved under `{output_path}/{name}.diff.png`. /// /// # Panics /// The result is added to the [`Harness`]'s internal [`SnapshotResults`]. /// /// The harness will panic when dropped if there were any snapshot errors. /// /// Errors happen if the image does not match the snapshot, if there was an error reading or writing the /// snapshot, if the rendering fails or if no default renderer is available. #[track_caller] pub fn snapshot_options(&mut self, name: impl Into<String>, options: &SnapshotOptions) { let result = self.try_snapshot_options(name, options); self.snapshot_results.add(result); } /// Render an image using the setup [`crate::TestRenderer`] and compare it to the snapshot. /// /// This is like [`Self::snapshot_options`] but will use the options set by [`crate::HarnessBuilder::with_options`]. /// /// The snapshot will be saved under `tests/snapshots/{name}.png`. /// The new image from the last test run will be saved under `tests/snapshots/{name}.new.png`. /// If the new image didn't match the snapshot, a diff image will be saved under `tests/snapshots/{name}.diff.png`. /// /// # Panics /// Panics if the image does not match the snapshot, if there was an error reading or writing the /// snapshot, if the rendering fails or if no default renderer is available. #[track_caller] pub fn snapshot(&mut self, name: impl Into<String>) { let result = self.try_snapshot(name); self.snapshot_results.add(result); } /// Render a snapshot, save it to a temp file and open it in the default image viewer. /// /// This method is marked as deprecated to trigger errors in CI (so that it's not accidentally /// committed). #[deprecated = "Only for debugging, don't commit this."] #[cfg(not(target_arch = "wasm32"))] pub fn debug_open_snapshot(&mut self) { let image = self .render() .map_err(|err| SnapshotError::RenderError { err }) .unwrap(); let temp_file = tempfile::Builder::new() .disable_cleanup(true) // we keep the file so it's accessible even after the test ends .prefix("kittest-snapshot") .suffix(".png") .tempfile() .expect("Failed to create temp file"); let path = temp_file.path(); image .save(temp_file.path()) .map_err(|err| SnapshotError::WriteSnapshot { err, path: path.to_path_buf(), }) .unwrap(); #[expect(clippy::print_stdout)] { println!("Wrote debug snapshot to: {}", path.display()); } let result = open::that(path); if let Err(err) = result { #[expect(clippy::print_stderr)] { eprintln!( "Failed to open image {} in default image viewer: {err}", path.display() ); } } } /// This removes the snapshot results from the harness. Useful if you e.g. want to merge it /// with the results from another harness (using [`SnapshotResults::add`]). pub fn take_snapshot_results(&mut self) -> SnapshotResults { std::mem::take(&mut self.snapshot_results) } } /// Utility to collect snapshot errors and display them at the end of the test. /// /// # Example /// ``` /// # let harness = MockHarness; /// # struct MockHarness; /// # impl MockHarness { /// # fn try_snapshot(&self, _: &str) -> Result<(), egui_kittest::SnapshotError> { Ok(()) } /// # } /// /// // [...] Construct a Harness /// /// let mut results = egui_kittest::SnapshotResults::new(); /// /// // Call add for each snapshot in your test /// results.add(harness.try_snapshot("my_test")); /// /// // If there are any errors, SnapshotResults will panic once dropped. /// ``` /// /// # Panics /// Panics if there are any errors when dropped (this way it is impossible to forget to call `unwrap`). /// If you don't want to panic, you can use [`SnapshotResults::into_result`] or [`SnapshotResults::into_inner`]. /// If you want to panic early, you can use [`SnapshotResults::unwrap`]. #[derive(Debug)] pub struct SnapshotResults { errors: Vec<SnapshotError>, handled: bool, location: std::panic::Location<'static>, } impl Default for SnapshotResults { #[track_caller] fn default() -> Self { Self { errors: Vec::new(), handled: true, // If no snapshots were added, we should consider this handled. location: *std::panic::Location::caller(), } } } impl Display for SnapshotResults { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { if self.errors.is_empty() { write!(f, "All snapshots passed") } else { writeln!(f, "Snapshot errors:")?; for error in &self.errors { writeln!(f, " {error}")?; } Ok(()) } } } impl SnapshotResults { #[track_caller] pub fn new() -> Self { Default::default() } /// Check if the result is an error and add it to the list of errors. pub fn add(&mut self, result: SnapshotResult) { self.handled = false; if let Err(err) = result { self.errors.push(err); } } /// Add all errors from another `SnapshotResults`. pub fn extend(&mut self, other: Self) { self.handled = false; self.errors.extend(other.into_inner()); } /// Add all errors from a [`Harness`]. pub fn extend_harness<T>(&mut self, harness: &mut Harness<'_, T>) { self.extend(harness.take_snapshot_results()); } /// Check if there are any errors. pub fn has_errors(&self) -> bool { !self.errors.is_empty() } /// Convert this into a `Result<(), Self>`. #[expect(clippy::missing_errors_doc)] pub fn into_result(self) -> Result<(), Self> { if self.has_errors() { Err(self) } else { Ok(()) } } /// Consume this and return the list of errors. pub fn into_inner(mut self) -> Vec<SnapshotError> { self.handled = true; std::mem::take(&mut self.errors) } /// Panics if there are any errors, displaying each. #[expect(clippy::unused_self)] pub fn unwrap(self) { // Panic is handled in drop } } impl From<SnapshotResults> for Vec<SnapshotError> { fn from(results: SnapshotResults) -> Self { results.into_inner() } } impl Drop for SnapshotResults { fn drop(&mut self) { // Don't panic if we are already panicking (the test probably failed for another reason) if std::thread::panicking() { return; } #[expect(clippy::manual_assert)] if self.has_errors() { panic!("{}", self); } thread_local! { static UNHANDLED_SNAPSHOT_RESULTS_COUNTER: std::cell::RefCell<usize> = const { std::cell::RefCell::new(0) }; } if !self.handled { let count = UNHANDLED_SNAPSHOT_RESULTS_COUNTER.with(|counter| { let mut count = counter.borrow_mut(); *count += 1; *count }); #[expect(clippy::manual_assert)] if count >= 2 { panic!( r#" Multiple SnapshotResults were dropped without being handled. In order to allow consistent snapshot updates, all snapshot results within a test should be merged in a single SnapshotResults instance. Usually this is handled internally in a harness. If you have multiple harnesses, you can merge the results using `Harness::take_snapshot_results` and `SnapshotResults::extend`. The SnapshotResult was constructed at {} "#, self.location ); } } } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_kittest/tests/regression_tests.rs
crates/egui_kittest/tests/regression_tests.rs
use egui::accesskit::{self, Role}; use egui::{Button, ComboBox, Image, Modifiers, Popup, Vec2, Widget as _}; #[cfg(all(feature = "wgpu", feature = "snapshot"))] use egui_kittest::SnapshotResults; use egui_kittest::{Harness, kittest::Queryable as _}; #[test] pub fn focus_should_skip_over_disabled_buttons() { let mut harness = Harness::new_ui(|ui| { ui.add(Button::new("Button 1")); ui.add_enabled(false, Button::new("Button Disabled")); ui.add(Button::new("Button 3")); }); harness.key_press(egui::Key::Tab); harness.run(); let button_1 = harness.get_by_label("Button 1"); assert!(button_1.is_focused()); harness.key_press(egui::Key::Tab); harness.run(); let button_3 = harness.get_by_label("Button 3"); assert!(button_3.is_focused()); harness.key_press(egui::Key::Tab); harness.run(); let button_1 = harness.get_by_label("Button 1"); assert!(button_1.is_focused()); } #[test] pub fn focus_should_skip_over_disabled_drag_values() { let mut value_1: u16 = 1; let mut value_2: u16 = 2; let mut value_3: u16 = 3; let mut harness = Harness::new_ui(|ui| { ui.add(egui::DragValue::new(&mut value_1)); ui.add_enabled(false, egui::DragValue::new(&mut value_2)); ui.add(egui::DragValue::new(&mut value_3)); }); harness.key_press(egui::Key::Tab); harness.run(); let drag_value_1 = harness.get_by(|node| node.numeric_value() == Some(1.0)); assert!(drag_value_1.is_focused()); harness.key_press(egui::Key::Tab); harness.run(); let drag_value_3 = harness.get_by(|node| node.numeric_value() == Some(3.0)); assert!(drag_value_3.is_focused()); } #[test] fn image_failed() { let mut harness = Harness::new_ui(|ui| { Image::new("file://invalid/path") .alt_text("I have an alt text") .max_size(Vec2::new(100.0, 100.0)) .ui(ui); }); harness.run(); harness.fit_contents(); #[cfg(all(feature = "wgpu", feature = "snapshot"))] harness.snapshot("image_snapshots"); } #[test] fn test_combobox() { let items = ["Item 1", "Item 2", "Item 3"]; let mut harness = Harness::builder() .with_size(Vec2::new(300.0, 200.0)) .build_ui_state( |ui, selected| { ComboBox::new("combobox", "Select Something").show_index( ui, selected, items.len(), |idx| *items.get(idx).expect("Invalid index"), ); }, 0, ); harness.run(); #[cfg(all(feature = "wgpu", feature = "snapshot"))] let mut results = SnapshotResults::new(); #[cfg(all(feature = "wgpu", feature = "snapshot"))] results.add(harness.try_snapshot("combobox_closed")); let combobox = harness.get_by_role_and_label(Role::ComboBox, "Select Something"); combobox.click(); harness.run(); #[cfg(all(feature = "wgpu", feature = "snapshot"))] results.add(harness.try_snapshot("combobox_opened")); let item_2 = harness.get_by_role_and_label(Role::Button, "Item 2"); item_2.click(); harness.run(); assert_eq!(harness.state(), &1); // Popup should be closed now assert!(harness.query_by_label("Item 2").is_none()); } /// `https://github.com/emilk/egui/issues/7065` #[test] pub fn slider_should_move_with_fixed_decimals() { let mut value: f32 = 1.0; let mut harness = Harness::new_ui(|ui| { // Movement on arrow-key is relative to slider width; make the slider wide so the movement becomes small. ui.spacing_mut().slider_width = 2000.0; ui.add(egui::Slider::new(&mut value, 0.1..=10.0).fixed_decimals(2)); }); harness.key_press(egui::Key::Tab); harness.run(); let actual_slider = harness.get_by_role(accesskit::Role::SpinButton); assert_eq!(actual_slider.value(), Some("1.00".to_owned())); harness.key_press(egui::Key::ArrowRight); harness.run(); let actual_slider = harness.get_by_role(accesskit::Role::SpinButton); assert_eq!(actual_slider.value(), Some("1.01".to_owned())); harness.key_press(egui::Key::ArrowRight); harness.run(); let actual_slider = harness.get_by_role(accesskit::Role::SpinButton); assert_eq!(actual_slider.value(), Some("1.02".to_owned())); harness.key_press(egui::Key::ArrowLeft); harness.run(); let actual_slider = harness.get_by_role(accesskit::Role::SpinButton); assert_eq!(actual_slider.value(), Some("1.01".to_owned())); harness.key_press(egui::Key::ArrowLeft); harness.run(); let actual_slider = harness.get_by_role(accesskit::Role::SpinButton); assert_eq!(actual_slider.value(), Some("1.00".to_owned())); } #[test] pub fn override_text_color_affects_interactive_widgets() { use egui::{Color32, RichText}; let mut harness = Harness::new_ui(|ui| { _ = ui.button("normal"); _ = ui.checkbox(&mut true, "normal"); _ = ui.radio(true, "normal"); ui.visuals_mut().widgets.inactive.fg_stroke.color = Color32::RED; _ = ui.button("red"); _ = ui.checkbox(&mut true, "red"); _ = ui.radio(true, "red"); // override_text_color takes precedence over `WidgetVisuals`, as it docstring claims ui.visuals_mut().override_text_color = Some(Color32::GREEN); _ = ui.button("green"); _ = ui.checkbox(&mut true, "green"); _ = ui.radio(true, "green"); // Setting the color explicitly with `RichText` overrides style _ = ui.button(RichText::new("blue").color(Color32::BLUE)); _ = ui.checkbox(&mut true, RichText::new("blue").color(Color32::BLUE)); _ = ui.radio(true, RichText::new("blue").color(Color32::BLUE)); }); #[cfg(all(feature = "wgpu", feature = "snapshot"))] let mut results = SnapshotResults::new(); #[cfg(all(feature = "wgpu", feature = "snapshot"))] results.add(harness.try_snapshot("override_text_color_interactive")); } /// <https://github.com/rerun-io/rerun/issues/11301> #[test] pub fn menus_should_close_even_if_submenu_disappears() { const OTHER_BUTTON: &str = "Other button"; const MENU_BUTTON: &str = "Menu"; const SUB_MENU_BUTTON: &str = "Always here"; const TOGGLEABLE_SUB_MENU_BUTTON: &str = "Maybe here"; const INSIDE_SUB_MENU_BUTTON: &str = "Inside submenu"; for frame_delay in (0..3).rev() { let mut harness = Harness::builder().build_ui_state( |ui, state| { let _ = ui.button(OTHER_BUTTON).clicked(); let response = ui.button(MENU_BUTTON); Popup::menu(&response).show(|ui| { let _ = ui.button(SUB_MENU_BUTTON); if *state { ui.menu_button(TOGGLEABLE_SUB_MENU_BUTTON, |ui| { let _ = ui.button(INSIDE_SUB_MENU_BUTTON); }); } }); }, true, ); // Open the main menu harness.get_by_label(MENU_BUTTON).click(); harness.run(); // Open the sub menu harness .get_by_label_contains(TOGGLEABLE_SUB_MENU_BUTTON) .hover(); harness.run(); // Have we opened the submenu successfully? harness.get_by_label(INSIDE_SUB_MENU_BUTTON).hover(); harness.run(); // We click manually, since we want to precisely time that the sub menu disappears when the // button is released let center = harness.get_by_label(OTHER_BUTTON).rect().center(); harness.input_mut().events.push(egui::Event::PointerButton { pos: center, button: egui::PointerButton::Primary, pressed: true, modifiers: Modifiers::default(), }); harness.step(); // Yank the sub menu from under the pointer *harness.state_mut() = false; // See if we handle it with or without a frame delay harness.run_steps(frame_delay); // Actually close the menu by clicking somewhere outside harness.input_mut().events.push(egui::Event::PointerButton { pos: center, button: egui::PointerButton::Primary, pressed: false, modifiers: Modifiers::default(), }); harness.run(); assert!( harness.query_by_label_contains(SUB_MENU_BUTTON).is_none(), "Menu failed to close. frame_delay = {frame_delay}" ); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_kittest/tests/tests.rs
crates/egui_kittest/tests/tests.rs
use egui::{Modifiers, ScrollArea, Vec2, include_image}; use egui_kittest::{Harness, SnapshotResults}; use kittest::Queryable as _; #[test] fn test_shrink() { let mut harness = Harness::new_ui(|ui| { ui.label("Hello, world!"); ui.separator(); ui.label("This is a test"); }); harness.fit_contents(); #[cfg(all(feature = "snapshot", feature = "wgpu"))] harness.snapshot("test_shrink"); } #[test] fn test_tooltip() { let mut harness = Harness::new_ui(|ui| { ui.label("Hello, world!"); ui.separator(); ui.label("This is a test") .on_hover_text("This\nis\na\nvery\ntall\ntooltip!"); }); harness.fit_contents(); #[cfg(all(feature = "snapshot", feature = "wgpu"))] harness.snapshot("test_tooltip_hidden"); harness.get_by_label("This is a test").hover(); harness.run_ok(); harness.fit_contents(); #[cfg(all(feature = "snapshot", feature = "wgpu"))] harness.snapshot("test_tooltip_shown"); } #[test] fn test_modifiers() { #[derive(Default)] struct State { cmd_clicked: bool, cmd_z_pressed: bool, cmd_y_pressed: bool, } let mut harness = Harness::new_ui_state( |ui, state| { if ui.button("Click me").clicked() && ui.input(|i| i.modifiers.command) { state.cmd_clicked = true; } if ui.input(|i| i.modifiers.command && i.key_pressed(egui::Key::Z)) { state.cmd_z_pressed = true; } if ui.input(|i| i.modifiers.command && i.key_pressed(egui::Key::Y)) { state.cmd_y_pressed = true; } }, State::default(), ); harness .get_by_label("Click me") .click_modifiers(Modifiers::COMMAND); harness.run(); harness.key_press_modifiers(Modifiers::COMMAND, egui::Key::Z); harness.run(); harness.key_combination_modifiers(Modifiers::COMMAND, &[egui::Key::Y]); harness.run(); let state = harness.state(); assert!(state.cmd_clicked, "The button wasn't command-clicked"); assert!(state.cmd_z_pressed, "Cmd+Z wasn't pressed"); assert!(state.cmd_y_pressed, "Cmd+Y wasn't pressed"); } #[test] fn should_wait_for_images() { let mut harness = Harness::builder() .with_size(Vec2::new(60.0, 120.0)) .build_ui(|ui| { egui_extras::install_image_loaders(ui.ctx()); let size = Vec2::splat(30.0); ui.label("Url:"); ui.add_sized( size, egui::Image::new( "https://raw.githubusercontent.com\ /emilk/egui/refs/heads/main/crates/eframe/data/icon.png", ), ); ui.label("Include:"); ui.add_sized( size, egui::Image::new(include_image!("../../eframe/data/icon.png")), ); }); harness.snapshot("should_wait_for_images"); } fn test_scroll_harness() -> Harness<'static, bool> { Harness::builder() .with_size(Vec2::new(100.0, 200.0)) .build_ui_state( |ui, state| { ScrollArea::vertical().show(ui, |ui| { for i in 0..20 { ui.label(format!("Item {i}")); } if ui.button("Hidden Button").clicked() { *state = true; } }); }, false, ) } #[test] fn test_scroll_to_me() { let mut harness = test_scroll_harness(); let mut results = SnapshotResults::new(); results.add(harness.try_snapshot("test_scroll_initial")); harness.get_by_label("Hidden Button").scroll_to_me(); harness.run(); results.add(harness.try_snapshot("test_scroll_scrolled")); harness.get_by_label("Hidden Button").click(); harness.run(); assert!( harness.state(), "The button was not clicked after scrolling." ); } #[test] fn test_scroll_down() { let mut harness = test_scroll_harness(); let button = harness.get_by_label("Hidden Button"); button.scroll_down(); button.scroll_down(); harness.run(); harness.get_by_label("Hidden Button").click(); harness.run(); assert!( harness.state(), "The button was not clicked after scrolling down. (Probably not scrolled enough / at all)" ); } #[test] fn test_masking() { let mut harness = Harness::new_ui(|ui| { let timestamp = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap() .as_millis(); ui.label("I should not be masked."); ui.label(format!("Timestamp: {timestamp}")); ui.label("I should also not be masked."); }); harness.fit_contents(); let to_be_masked = harness.get_by_label_contains("Timestamp: "); harness.mask(to_be_masked.rect()); harness.snapshot("test_masking"); } #[test] fn test_remove_cursor() { let hovered = false; let mut harness = Harness::new_ui_state( |ui, state| { let response = ui.button("Click me"); *state = response.hovered(); }, hovered, ); harness.fit_contents(); harness.get_by_label("Click me").click(); harness.run(); assert!(harness.state(), "The button should be hovered"); let hovered_button_snapshot = harness.render().expect("Failed to render"); harness.remove_cursor(); harness.run(); assert!( !harness.state(), "The button should not be hovered after removing cursor" ); let non_hovered_button_snapshot = harness.render().expect("Failed to render"); assert_ne!( hovered_button_snapshot, non_hovered_button_snapshot, "The button appearance should change" ); }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_kittest/tests/accesskit.rs
crates/egui_kittest/tests/accesskit.rs
//! Tests the accesskit accessibility output of egui. use egui::{ CentralPanel, Context, RawInput, Ui, Window, accesskit::{NodeId, Role, TreeUpdate}, }; /// Baseline test that asserts there are no spurious nodes in the /// accesskit output when the ui is empty. /// /// This gives reasonable certainty that any nodes appearing in the other accesskit outputs /// are put there because of the widgets rendered. #[test] fn empty_ui_should_return_tree_with_only_root_window() { let output = accesskit_output_single_egui_frame(|_ui| { // Nothing here beyond the default empty UI }); assert_eq!( output.nodes.len(), 2, "Expected the root node and the top level Ui; found: {output:#?}", ); assert_eq!( output .nodes .iter() .filter(|(_, n)| n.role() == Role::GenericContainer) .count(), 1, "Expected a single Ui as a GenericContainer node.", ); let (id, root) = &output.nodes[0]; assert_eq!(*id, output.tree.unwrap().root); assert_eq!(root.role(), Role::Window); } #[test] fn button_node() { let button_text = "This is a test button!"; let output = accesskit_output_single_egui_frame(|ui| { CentralPanel::default().show_inside(ui, |ui| ui.button(button_text)); }); let (_, button) = output .nodes .iter() .find(|(_, node)| node.role() == Role::Button) .expect("Button should exist in the accesskit output"); assert_eq!(button.label(), Some(button_text)); assert!(!button.is_disabled()); } #[test] fn disabled_button_node() { let button_text = "This is a test button!"; let output = accesskit_output_single_egui_frame(|ui| { CentralPanel::default().show_inside(ui, |ui| { ui.add_enabled(false, egui::Button::new(button_text)) }); }); let (_, button) = output .nodes .iter() .find(|(_, node)| node.role() == Role::Button) .expect("Button should exist in the accesskit output"); assert_eq!(button.label(), Some(button_text)); assert!(button.is_disabled()); } #[test] fn toggle_button_node() { let button_text = "A toggle button"; let mut selected = false; let output = accesskit_output_single_egui_frame(|ui| { CentralPanel::default().show_inside(ui, |ui| ui.toggle_value(&mut selected, button_text)); }); let (_, toggle) = output .nodes .iter() .find(|(_, node)| node.role() == Role::Button) .expect("Toggle button should exist in the accesskit output"); assert_eq!(toggle.label(), Some(button_text)); assert!(!toggle.is_disabled()); } #[test] fn multiple_disabled_widgets() { let output = accesskit_output_single_egui_frame(|ui| { CentralPanel::default().show_inside(ui, |ui| { ui.add_enabled_ui(false, |ui| { let _ = ui.button("Button 1"); let _ = ui.button("Button 2"); let _ = ui.button("Button 3"); }) }); }); assert_eq!( output .nodes .iter() .filter(|(_, node)| node.is_disabled()) .count(), 3, "All widgets should be disabled." ); } #[test] fn window_children() { let output = accesskit_output_single_egui_frame(|ui| { let mut open = true; Window::new("test window") .open(&mut open) .resizable(false) .show(ui.ctx(), |ui| { let _ = ui.button("A button"); }); }); let root = output.tree.as_ref().map(|tree| tree.root).unwrap(); let window_id = assert_window_exists(&output, "test window", root); assert_button_exists(&output, "A button", window_id); assert_button_exists(&output, "Close window", window_id); assert_button_exists(&output, "Hide", window_id); } fn accesskit_output_single_egui_frame(run_ui: impl FnMut(&mut Ui)) -> TreeUpdate { let ctx = Context::default(); // Disable animations, so we do not need to wait for animations to end to see the result. ctx.global_style_mut(|style| style.animation_time = 0.0); ctx.enable_accesskit(); let output = ctx.run_ui(RawInput::default(), run_ui); output .platform_output .accesskit_update .expect("Missing accesskit update") } #[track_caller] fn assert_button_exists(tree: &TreeUpdate, label: &str, parent: NodeId) { let (node_id, _) = tree .nodes .iter() .find(|(_, node)| { !node.is_hidden() && node.role() == Role::Button && node.label() == Some(label) }) .expect("No visible button with that label exists."); assert_parent_child(tree, parent, *node_id); } #[track_caller] fn assert_window_exists(tree: &TreeUpdate, title: &str, parent: NodeId) -> NodeId { let (node_id, _) = tree .nodes .iter() .find(|(_, node)| { !node.is_hidden() && node.role() == Role::Window && node.label() == Some(title) }) .expect("No visible window with that title exists."); assert_parent_child(tree, parent, *node_id); *node_id } #[track_caller] fn assert_parent_child(tree: &TreeUpdate, parent_id: NodeId, child: NodeId) { assert!( has_child_recursively(tree, parent_id, child), "Node is not a child of the given parent." ); } fn has_child_recursively(tree: &TreeUpdate, parent: NodeId, child: NodeId) -> bool { let (_, parent) = tree .nodes .iter() .find(|(id, _)| id == &parent) .expect("Parent does not exist."); for &c in parent.children() { if c == child || has_child_recursively(tree, c, child) { return true; } } false }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_kittest/tests/menu.rs
crates/egui_kittest/tests/menu.rs
use egui::containers::menu::{MenuBar, MenuConfig, SubMenuButton}; use egui::{PopupCloseBehavior, Ui, include_image}; use egui_kittest::{Harness, SnapshotResults}; use kittest::Queryable as _; struct TestMenu { config: MenuConfig, checked: bool, } impl TestMenu { fn new(config: MenuConfig) -> Self { Self { config, checked: false, } } fn ui(&mut self, ui: &mut Ui) { ui.vertical(|ui| { MenuBar::new().config(self.config.clone()).ui(ui, |ui| { egui::Sides::new().show( ui, |ui| { ui.menu_button("Menu A", |ui| { _ = ui.button("Button in Menu A"); ui.menu_button("Submenu A", |ui| { for i in 0..4 { _ = ui.button(format!("Button {i} in Submenu A")); } }); ui.menu_image_text_button( include_image!("../../eframe/data/icon.png"), "Submenu B with icon", |ui| { _ = ui.button("Button in Submenu B"); }, ); SubMenuButton::new("Submenu C (CloseOnClickOutside)") .config( MenuConfig::new() .close_behavior(PopupCloseBehavior::CloseOnClickOutside), ) .ui(ui, |ui| { _ = ui.button("Button in Submenu C"); ui.checkbox(&mut self.checked, "Checkbox in Submenu C"); ui.menu_button("Submenu D", |ui| { if ui .button("Button in Submenu D (close on click)") .clicked() { ui.close(); } }); }); }); ui.menu_image_text_button( include_image!("../../eframe/data/icon.png"), "Menu B with icon", |ui| { _ = ui.button("Button in Menu B"); }, ); _ = ui.button("Menu Button"); ui.menu_button("Menu C", |ui| { _ = ui.button("Button in Menu C"); }); }, |ui| { ui.label("Some other label"); }, ); }); }); } fn into_harness(self) -> Harness<'static, Self> { Harness::builder() .with_size(egui::Vec2::new(500.0, 300.0)) .build_ui_state( |ui, menu| { egui_extras::install_image_loaders(ui.ctx()); menu.ui(ui); }, self, ) } } #[test] fn menu_close_on_click_outside() { // We're intentionally setting CloseOnClick here so we can test if a submenu can override the // close behavior. (Note how Submenu C has CloseOnClickOutside set) let mut harness = TestMenu::new(MenuConfig::new().close_behavior(PopupCloseBehavior::CloseOnClick)) .into_harness(); harness.get_by_label("Menu A").click(); harness.run(); harness .get_by_label_contains("Submenu C (CloseOnClickOutside)") .hover(); harness.run(); // We should be able to check the checkbox without closing the menu // Click a couple of times, just in case for expect_checked in [true, false, true, false] { harness.get_by_label("Checkbox in Submenu C").click(); harness.run(); assert_eq!(expect_checked, harness.state().checked); } // Hovering outside should not close the menu harness.get_by_label("Some other label").hover(); harness.run(); assert!(harness.query_by_label("Checkbox in Submenu C").is_some()); // Clicking outside should close the menu harness.get_by_label("Some other label").click(); harness.run(); assert!(harness.query_by_label("Checkbox in Submenu C").is_none()); } #[test] fn menu_close_on_click() { let mut harness = TestMenu::new(MenuConfig::new().close_behavior(PopupCloseBehavior::CloseOnClick)) .into_harness(); harness.get_by_label("Menu A").click(); harness.run(); harness.get_by_label_contains("Submenu B with icon").hover(); harness.run(); // Clicking the button should close the menu (even if ui.close() is not called by the button) harness.get_by_label("Button in Submenu B").click(); harness.run(); assert!(harness.query_by_label("Button in Submenu B").is_none()); } #[test] fn clicking_submenu_button_should_never_close_menu() { // We test for this since otherwise the menu wouldn't work on touch devices // The other tests use .hover to open submenus, but this test explicitly uses .click let mut harness = TestMenu::new(MenuConfig::new().close_behavior(PopupCloseBehavior::CloseOnClick)) .into_harness(); harness.get_by_label("Menu A").click(); harness.run(); // Clicking the submenu button should not close the menu harness.get_by_label_contains("Submenu B with icon").click(); harness.run(); harness.get_by_label("Button in Submenu B").click(); harness.run(); assert!(harness.query_by_label("Button in Submenu B").is_none()); } #[test] fn menu_snapshots() { let mut harness = TestMenu::new(MenuConfig::new()).into_harness(); let mut results = SnapshotResults::new(); harness.get_by_label("Menu A").hover(); harness.run(); results.add(harness.try_snapshot("menu/closed_hovered")); harness.get_by_label("Menu A").click(); harness.run(); results.add(harness.try_snapshot("menu/opened")); harness .get_by_label_contains("Submenu C (CloseOnClickOutside)") .hover(); harness.run(); results.add(harness.try_snapshot("menu/submenu")); harness.get_by_label_contains("Submenu D").hover(); harness.run(); results.add(harness.try_snapshot("menu/subsubmenu")); }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_kittest/tests/popup.rs
crates/egui_kittest/tests/popup.rs
use kittest::Queryable as _; #[test] fn test_interactive_tooltip() { struct State { link_clicked: bool, } let mut harness = egui_kittest::Harness::new_ui_state( |ui, state| { ui.label("I have a tooltip").on_hover_ui(|ui| { if ui.link("link").clicked() { state.link_clicked = true; } }); }, State { link_clicked: false, }, ); harness.get_by_label_contains("tooltip").hover(); harness.run(); harness.get_by_label("link").hover(); harness.run(); harness.get_by_label("link").click(); harness.run(); assert!(harness.state().link_clicked); }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui-winit/src/safe_area.rs
crates/egui-winit/src/safe_area.rs
#[cfg(target_os = "ios")] pub use ios::get_safe_area_insets; #[cfg(target_os = "ios")] mod ios { use egui::{SafeAreaInsets, epaint::MarginF32}; use objc2::{ClassType, rc::Retained}; use objc2_foundation::{MainThreadMarker, NSObjectProtocol}; use objc2_ui_kit::{UIApplication, UISceneActivationState, UIWindowScene}; /// Gets the ios safe area insets. /// /// A safe area defines the area within a view that isn’t covered by a navigation bar, tab bar, /// toolbar, or other views a window might provide. Safe areas are essential for avoiding a /// device’s interactive and display features, like Dynamic Island on iPhone or the camera /// housing on some Mac models. /// /// Once winit v0.31 has been released this can be removed in favor of /// `winit::Window::safe_area`. pub fn get_safe_area_insets() -> SafeAreaInsets { let Some(main_thread_marker) = MainThreadMarker::new() else { log::error!("Getting safe area insets needs to be performed on the main thread"); return SafeAreaInsets::default(); }; let app = UIApplication::sharedApplication(main_thread_marker); #[expect(unsafe_code)] unsafe { // Look for the first window scene that's in the foreground for scene in app.connectedScenes() { if scene.isKindOfClass(UIWindowScene::class()) && matches!( scene.activationState(), UISceneActivationState::ForegroundActive | UISceneActivationState::ForegroundInactive ) { // Safe to cast, the class kind was checked above let window_scene = Retained::cast::<UIWindowScene>(scene.clone()); if let Some(window) = window_scene.keyWindow() { let insets = window.safeAreaInsets(); return SafeAreaInsets(MarginF32 { top: insets.top as f32, left: insets.left as f32, right: insets.right as f32, bottom: insets.bottom as f32, }); } } } } SafeAreaInsets::default() } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui-winit/src/window_settings.rs
crates/egui-winit/src/window_settings.rs
use egui::ViewportBuilder; /// Can be used to store native window settings (position and size). #[derive(Clone, Copy, Debug, Default)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] pub struct WindowSettings { /// Position of window content in physical pixels. inner_position_pixels: Option<egui::Pos2>, /// Position of window frame/titlebar in physical pixels. outer_position_pixels: Option<egui::Pos2>, fullscreen: bool, maximized: bool, /// Inner size of window in logical pixels inner_size_points: Option<egui::Vec2>, } impl WindowSettings { pub fn from_window(egui_zoom_factor: f32, window: &winit::window::Window) -> Self { let inner_size_points = window .inner_size() .to_logical::<f32>(egui_zoom_factor as f64 * window.scale_factor()); let inner_position_pixels = window .inner_position() .ok() .map(|p| egui::pos2(p.x as f32, p.y as f32)); let outer_position_pixels = window .outer_position() .ok() .map(|p| egui::pos2(p.x as f32, p.y as f32)); Self { inner_position_pixels, outer_position_pixels, fullscreen: window.fullscreen().is_some(), maximized: window.is_maximized(), inner_size_points: Some(egui::vec2( inner_size_points.width, inner_size_points.height, )), } } pub fn inner_size_points(&self) -> Option<egui::Vec2> { self.inner_size_points } pub fn initialize_viewport_builder( &self, egui_zoom_factor: f32, event_loop: &winit::event_loop::ActiveEventLoop, mut viewport_builder: ViewportBuilder, ) -> ViewportBuilder { profiling::function_scope!(); // `WindowBuilder::with_position` expects inner position in Macos, and outer position elsewhere // See [`winit::window::WindowBuilder::with_position`] for details. let pos_px = if cfg!(target_os = "macos") { self.inner_position_pixels } else { self.outer_position_pixels }; if let Some(pos) = pos_px { let monitor_scale_factor = if let Some(inner_size_points) = self.inner_size_points { find_active_monitor(egui_zoom_factor, event_loop, inner_size_points, &pos) .map_or(1.0, |monitor| monitor.scale_factor() as f32) } else { 1.0 }; let scaled_pos = pos / (egui_zoom_factor * monitor_scale_factor); viewport_builder = viewport_builder.with_position(scaled_pos); } if let Some(inner_size_points) = self.inner_size_points { viewport_builder = viewport_builder .with_inner_size(inner_size_points) .with_fullscreen(self.fullscreen) .with_maximized(self.maximized); } viewport_builder } pub fn initialize_window(&self, window: &winit::window::Window) { if cfg!(target_os = "macos") { // Mac sometimes has problems restoring the window to secondary monitors // using only `WindowBuilder::with_position`, so we need this extra step: if let Some(pos) = self.outer_position_pixels { window.set_outer_position(winit::dpi::PhysicalPosition { x: pos.x, y: pos.y }); } } } pub fn clamp_size_to_sane_values(&mut self, largest_monitor_size_points: egui::Vec2) { use egui::NumExt as _; if let Some(size) = &mut self.inner_size_points { // Prevent ridiculously small windows: let min_size = egui::Vec2::splat(64.0); *size = size.at_least(min_size); // Make sure we don't try to create a window larger than the largest monitor // because on Linux that can lead to a crash. *size = size.at_most(largest_monitor_size_points); } } pub fn clamp_position_to_monitors( &mut self, egui_zoom_factor: f32, event_loop: &winit::event_loop::ActiveEventLoop, ) { // If the app last ran on two monitors and only one is now connected, then // the given position is invalid. // If this happens on Mac, the window is clamped into valid area. // If this happens on Windows, the window becomes invisible to the user 🤦‍♂️ // So on Windows we clamp the position to the monitor it is on. if !cfg!(target_os = "windows") { return; } let Some(inner_size_points) = self.inner_size_points else { return; }; if let Some(pos_px) = &mut self.inner_position_pixels { clamp_pos_to_monitors(egui_zoom_factor, event_loop, inner_size_points, pos_px); } if let Some(pos_px) = &mut self.outer_position_pixels { clamp_pos_to_monitors(egui_zoom_factor, event_loop, inner_size_points, pos_px); } } } fn find_active_monitor( egui_zoom_factor: f32, event_loop: &winit::event_loop::ActiveEventLoop, window_size_pts: egui::Vec2, position_px: &egui::Pos2, ) -> Option<winit::monitor::MonitorHandle> { profiling::function_scope!(); let monitors = event_loop.available_monitors(); // default to primary monitor, in case the correct monitor was disconnected. let Some(mut active_monitor) = event_loop .primary_monitor() .or_else(|| event_loop.available_monitors().next()) else { return None; // no monitors 🤷 }; for monitor in monitors { let window_size_px = window_size_pts * (egui_zoom_factor * monitor.scale_factor() as f32); let monitor_x_range = (monitor.position().x - window_size_px.x as i32) ..(monitor.position().x + monitor.size().width as i32); let monitor_y_range = (monitor.position().y - window_size_px.y as i32) ..(monitor.position().y + monitor.size().height as i32); if monitor_x_range.contains(&(position_px.x as i32)) && monitor_y_range.contains(&(position_px.y as i32)) { active_monitor = monitor; } } Some(active_monitor) } fn clamp_pos_to_monitors( egui_zoom_factor: f32, event_loop: &winit::event_loop::ActiveEventLoop, window_size_pts: egui::Vec2, position_px: &mut egui::Pos2, ) { profiling::function_scope!(); let Some(active_monitor) = find_active_monitor(egui_zoom_factor, event_loop, window_size_pts, position_px) else { return; // no monitors 🤷 }; let mut window_size_px = window_size_pts * (egui_zoom_factor * active_monitor.scale_factor() as f32); // Add size of title bar. This is 32 px by default in Win 10/11. if cfg!(target_os = "windows") { window_size_px += egui::Vec2::new( 0.0, 32.0 * egui_zoom_factor * active_monitor.scale_factor() as f32, ); } let monitor_position = egui::Pos2::new( active_monitor.position().x as f32, active_monitor.position().y as f32, ); let monitor_size_px = egui::Vec2::new( active_monitor.size().width as f32, active_monitor.size().height as f32, ); // Window size cannot be negative or the subsequent `clamp` will panic. let window_size = (monitor_size_px - window_size_px).max(egui::Vec2::ZERO); // To get the maximum position, we get the rightmost corner of the display, then // subtract the size of the window to get the bottom right most value window.position // can have. *position_px = position_px.clamp(monitor_position, monitor_position + window_size); }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui-winit/src/lib.rs
crates/egui-winit/src/lib.rs
//! [`egui`] bindings for [`winit`](https://github.com/rust-windowing/winit). //! //! The library translates winit events to egui, handled copy/paste, //! updates the cursor, open links clicked in egui, etc. //! //! ## Feature flags #![cfg_attr(feature = "document-features", doc = document_features::document_features!())] //! #![expect(clippy::manual_range_contains)] #[cfg(feature = "accesskit")] pub use accesskit_winit; pub use egui; #[cfg(feature = "accesskit")] use egui::accesskit; use egui::{Pos2, Rect, Theme, Vec2, ViewportBuilder, ViewportCommand, ViewportId, ViewportInfo}; pub use winit; pub mod clipboard; mod safe_area; mod window_settings; pub use window_settings::WindowSettings; use raw_window_handle::HasDisplayHandle; use winit::{ dpi::{PhysicalPosition, PhysicalSize}, event::ElementState, event_loop::ActiveEventLoop, window::{CursorGrabMode, Window, WindowButtons, WindowLevel}, }; pub fn screen_size_in_pixels(window: &Window) -> egui::Vec2 { let size = if cfg!(target_os = "ios") { // `outer_size` Includes the area behind the "dynamic island". // It is up to the eframe user to make sure the dynamic island doesn't cover anything important. // That will be easier once https://github.com/rust-windowing/winit/pull/3890 lands window.outer_size() } else { window.inner_size() }; egui::vec2(size.width as f32, size.height as f32) } /// Calculate the `pixels_per_point` for a given window, given the current egui zoom factor pub fn pixels_per_point(egui_ctx: &egui::Context, window: &Window) -> f32 { let native_pixels_per_point = window.scale_factor() as f32; let egui_zoom_factor = egui_ctx.zoom_factor(); egui_zoom_factor * native_pixels_per_point } // ---------------------------------------------------------------------------- #[must_use] #[derive(Clone, Copy, Debug, Default)] pub struct EventResponse { /// If true, egui consumed this event, i.e. wants exclusive use of this event /// (e.g. a mouse click on an egui window, or entering text into a text field). /// /// For instance, if you use egui for a game, you should only /// pass on the events to your game when [`Self::consumed`] is `false`. /// /// Note that egui uses `tab` to move focus between elements, so this will always be `true` for tabs. pub consumed: bool, /// Do we need an egui refresh because of this event? pub repaint: bool, } // ---------------------------------------------------------------------------- /// Handles the integration between egui and a winit Window. /// /// Instantiate one of these per viewport/window. pub struct State { /// Shared clone. egui_ctx: egui::Context, viewport_id: ViewportId, start_time: web_time::Instant, egui_input: egui::RawInput, pointer_pos_in_points: Option<egui::Pos2>, any_pointer_button_down: bool, current_cursor_icon: Option<egui::CursorIcon>, clipboard: clipboard::Clipboard, /// If `true`, mouse inputs will be treated as touches. /// Useful for debugging touch support in egui. /// /// Creates duplicate touches, if real touch inputs are coming. simulate_touch_screen: bool, /// Is Some(…) when a touch is being translated to a pointer. /// /// Only one touch will be interpreted as pointer at any time. pointer_touch_id: Option<u64>, /// track ime state has_sent_ime_enabled: bool, #[cfg(feature = "accesskit")] accesskit: Option<accesskit_winit::Adapter>, allow_ime: bool, ime_rect_px: Option<egui::Rect>, } impl State { /// Construct a new instance pub fn new( egui_ctx: egui::Context, viewport_id: ViewportId, display_target: &dyn HasDisplayHandle, native_pixels_per_point: Option<f32>, theme: Option<winit::window::Theme>, max_texture_side: Option<usize>, ) -> Self { profiling::function_scope!(); let egui_input = egui::RawInput { focused: false, // winit will tell us when we have focus ..Default::default() }; let mut slf = Self { egui_ctx, viewport_id, start_time: web_time::Instant::now(), egui_input, pointer_pos_in_points: None, any_pointer_button_down: false, current_cursor_icon: None, clipboard: clipboard::Clipboard::new( display_target.display_handle().ok().map(|h| h.as_raw()), ), simulate_touch_screen: false, pointer_touch_id: None, has_sent_ime_enabled: false, #[cfg(feature = "accesskit")] accesskit: None, allow_ime: false, ime_rect_px: None, }; slf.egui_input .viewports .entry(ViewportId::ROOT) .or_default() .native_pixels_per_point = native_pixels_per_point; slf.egui_input.system_theme = theme.map(to_egui_theme); if let Some(max_texture_side) = max_texture_side { slf.set_max_texture_side(max_texture_side); } slf } #[cfg(feature = "accesskit")] pub fn init_accesskit<T: From<accesskit_winit::Event> + Send>( &mut self, event_loop: &ActiveEventLoop, window: &Window, event_loop_proxy: winit::event_loop::EventLoopProxy<T>, ) { profiling::function_scope!(); self.accesskit = Some(accesskit_winit::Adapter::with_event_loop_proxy( event_loop, window, event_loop_proxy, )); } /// Call this once a graphics context has been created to update the maximum texture dimensions /// that egui will use. pub fn set_max_texture_side(&mut self, max_texture_side: usize) { self.egui_input.max_texture_side = Some(max_texture_side); } /// Fetches text from the clipboard and returns it. pub fn clipboard_text(&mut self) -> Option<String> { self.clipboard.get() } /// Places the text onto the clipboard. pub fn set_clipboard_text(&mut self, text: String) { self.clipboard.set_text(text); } /// Returns [`false`] or the last value that [`Window::set_ime_allowed()`] was called with, used for debouncing. pub fn allow_ime(&self) -> bool { self.allow_ime } /// Set the last value that [`Window::set_ime_allowed()`] was called with. pub fn set_allow_ime(&mut self, allow: bool) { self.allow_ime = allow; } #[inline] pub fn egui_ctx(&self) -> &egui::Context { &self.egui_ctx } /// The current input state. /// This is changed by [`Self::on_window_event`] and cleared by [`Self::take_egui_input`]. #[inline] pub fn egui_input(&self) -> &egui::RawInput { &self.egui_input } /// The current input state. /// This is changed by [`Self::on_window_event`] and cleared by [`Self::take_egui_input`]. #[inline] pub fn egui_input_mut(&mut self) -> &mut egui::RawInput { &mut self.egui_input } /// Prepare for a new frame by extracting the accumulated input, /// /// as well as setting [the time](egui::RawInput::time) and [screen rectangle](egui::RawInput::screen_rect). /// /// You need to set [`egui::RawInput::viewports`] yourself though. /// Use [`update_viewport_info`] to update the info for each /// viewport. pub fn take_egui_input(&mut self, window: &Window) -> egui::RawInput { profiling::function_scope!(); self.egui_input.time = Some(self.start_time.elapsed().as_secs_f64()); // On Windows, a minimized window will have 0 width and height. // See: https://github.com/rust-windowing/winit/issues/208 // This solves an issue where egui window positions would be changed when minimizing on Windows. let screen_size_in_pixels = screen_size_in_pixels(window); let screen_size_in_points = screen_size_in_pixels / pixels_per_point(&self.egui_ctx, window); self.egui_input.screen_rect = (screen_size_in_points.x > 0.0 && screen_size_in_points.y > 0.0) .then(|| Rect::from_min_size(Pos2::ZERO, screen_size_in_points)); // Tell egui which viewport is now active: self.egui_input.viewport_id = self.viewport_id; self.egui_input .viewports .entry(self.viewport_id) .or_default() .native_pixels_per_point = Some(window.scale_factor() as f32); self.egui_input.take() } /// Call this when there is a new event. /// /// The result can be found in [`Self::egui_input`] and be extracted with [`Self::take_egui_input`]. pub fn on_window_event( &mut self, window: &Window, event: &winit::event::WindowEvent, ) -> EventResponse { profiling::function_scope!(short_window_event_description(event)); #[cfg(feature = "accesskit")] if let Some(accesskit) = self.accesskit.as_mut() { accesskit.process_event(window, event); } use winit::event::WindowEvent; #[cfg(target_os = "ios")] match &event { WindowEvent::Resized(_) | WindowEvent::ScaleFactorChanged { .. } | WindowEvent::Focused(true) | WindowEvent::Occluded(false) => { // Once winit v0.31 has been released this can be reworked to get the safe area from // `Window::safe_area`, and updated from a new event which is being discussed in // https://github.com/rust-windowing/winit/issues/3911. self.egui_input_mut().safe_area_insets = Some(safe_area::get_safe_area_insets()); } _ => {} } match event { WindowEvent::ScaleFactorChanged { scale_factor, .. } => { let native_pixels_per_point = *scale_factor as f32; self.egui_input .viewports .entry(self.viewport_id) .or_default() .native_pixels_per_point = Some(native_pixels_per_point); EventResponse { repaint: true, consumed: false, } } WindowEvent::MouseInput { state, button, .. } => { self.on_mouse_button_input(*state, *button); EventResponse { repaint: true, consumed: self.egui_ctx.egui_wants_pointer_input(), } } WindowEvent::MouseWheel { delta, phase, .. } => { self.on_mouse_wheel(window, *delta, *phase); EventResponse { repaint: true, consumed: self.egui_ctx.egui_wants_pointer_input(), } } WindowEvent::CursorMoved { position, .. } => { self.on_cursor_moved(window, *position); EventResponse { repaint: true, consumed: self.egui_ctx.egui_is_using_pointer(), } } WindowEvent::CursorLeft { .. } => { self.pointer_pos_in_points = None; self.egui_input.events.push(egui::Event::PointerGone); EventResponse { repaint: true, consumed: false, } } // WindowEvent::TouchpadPressure {device_id, pressure, stage, .. } => {} // TODO(emilk) WindowEvent::Touch(touch) => { self.on_touch(window, touch); let consumed = match touch.phase { winit::event::TouchPhase::Started | winit::event::TouchPhase::Ended | winit::event::TouchPhase::Cancelled => { self.egui_ctx.egui_wants_pointer_input() } winit::event::TouchPhase::Moved => self.egui_ctx.egui_is_using_pointer(), }; EventResponse { repaint: true, consumed, } } WindowEvent::Ime(ime) => { // on Mac even Cmd-C is pressed during ime, a `c` is pushed to Preedit. // So no need to check is_mac_cmd. // // How winit produce `Ime::Enabled` and `Ime::Disabled` differs in MacOS // and Windows. // // - On Windows, before and after each Commit will produce an Enable/Disabled // event. // - On MacOS, only when user explicit enable/disable ime. No Disabled // after Commit. // // We use input_method_editor_started to manually insert CompositionStart // between Commits. match ime { winit::event::Ime::Enabled => { if cfg!(target_os = "linux") { // This event means different things in X11 and Wayland, but we can just // ignore it and enable IME on the preedit event. // See <https://github.com/rust-windowing/winit/issues/2498> } else { self.ime_event_enable(); } } winit::event::Ime::Preedit(text, Some(_cursor)) => { self.ime_event_enable(); self.egui_input .events .push(egui::Event::Ime(egui::ImeEvent::Preedit(text.clone()))); } winit::event::Ime::Commit(text) => { self.egui_input .events .push(egui::Event::Ime(egui::ImeEvent::Commit(text.clone()))); self.ime_event_disable(); } winit::event::Ime::Disabled | winit::event::Ime::Preedit(_, None) => { self.ime_event_disable(); } } EventResponse { repaint: true, consumed: self.egui_ctx.egui_wants_keyboard_input(), } } WindowEvent::KeyboardInput { event, is_synthetic, .. } => { // Winit generates fake "synthetic" KeyboardInput events when the focus // is changed to the window, or away from it. Synthetic key presses // represent no real key presses and should be ignored. // See https://github.com/rust-windowing/winit/issues/3543 if *is_synthetic && event.state == ElementState::Pressed { EventResponse { repaint: true, consumed: false, } } else { self.on_keyboard_input(event); // When pressing the Tab key, egui focuses the first focusable element, hence Tab always consumes. let consumed = self.egui_ctx.egui_wants_keyboard_input() || event.logical_key == winit::keyboard::Key::Named(winit::keyboard::NamedKey::Tab); EventResponse { repaint: true, consumed, } } } WindowEvent::Focused(focused) => { let focused = if cfg!(target_os = "macos") { // 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 }; self.egui_input.focused = focused; self.egui_input .events .push(egui::Event::WindowFocused(focused)); EventResponse { repaint: true, consumed: false, } } WindowEvent::ThemeChanged(winit_theme) => { self.egui_input.system_theme = Some(to_egui_theme(*winit_theme)); EventResponse { repaint: true, consumed: false, } } WindowEvent::HoveredFile(path) => { self.egui_input.hovered_files.push(egui::HoveredFile { path: Some(path.clone()), ..Default::default() }); EventResponse { repaint: true, consumed: false, } } WindowEvent::HoveredFileCancelled => { self.egui_input.hovered_files.clear(); EventResponse { repaint: true, consumed: false, } } WindowEvent::DroppedFile(path) => { self.egui_input.hovered_files.clear(); self.egui_input.dropped_files.push(egui::DroppedFile { path: Some(path.clone()), ..Default::default() }); EventResponse { repaint: true, consumed: false, } } WindowEvent::ModifiersChanged(state) => { let state = state.state(); let alt = state.alt_key(); let ctrl = state.control_key(); let shift = state.shift_key(); let super_ = state.super_key(); self.egui_input.modifiers.alt = alt; self.egui_input.modifiers.ctrl = ctrl; self.egui_input.modifiers.shift = shift; self.egui_input.modifiers.mac_cmd = cfg!(target_os = "macos") && super_; self.egui_input.modifiers.command = if cfg!(target_os = "macos") { super_ } else { ctrl }; EventResponse { repaint: true, consumed: false, } } // Things that may require repaint: WindowEvent::RedrawRequested | WindowEvent::CursorEntered { .. } | WindowEvent::Destroyed | WindowEvent::Occluded(_) | WindowEvent::Resized(_) | WindowEvent::Moved(_) | WindowEvent::TouchpadPressure { .. } | WindowEvent::CloseRequested => EventResponse { repaint: true, consumed: false, }, // Things we completely ignore: WindowEvent::ActivationTokenDone { .. } | WindowEvent::AxisMotion { .. } | WindowEvent::DoubleTapGesture { .. } => EventResponse { repaint: false, consumed: false, }, WindowEvent::PinchGesture { delta, .. } => { // Positive delta values indicate magnification (zooming in). // Negative delta values indicate shrinking (zooming out). let zoom_factor = (*delta as f32).exp(); self.egui_input.events.push(egui::Event::Zoom(zoom_factor)); EventResponse { repaint: true, consumed: self.egui_ctx.egui_wants_pointer_input(), } } WindowEvent::RotationGesture { delta, .. } => { // Positive delta values indicate counterclockwise rotation // Negative delta values indicate clockwise rotation // This is opposite of egui's sign convention for angles self.egui_input .events .push(egui::Event::Rotate(-delta.to_radians())); EventResponse { repaint: true, consumed: self.egui_ctx.egui_wants_pointer_input(), } } WindowEvent::PanGesture { delta, phase, .. } => { let pixels_per_point = pixels_per_point(&self.egui_ctx, window); self.egui_input.events.push(egui::Event::MouseWheel { unit: egui::MouseWheelUnit::Point, delta: Vec2::new(delta.x, delta.y) / pixels_per_point, phase: to_egui_touch_phase(*phase), modifiers: self.egui_input.modifiers, }); EventResponse { repaint: true, consumed: self.egui_ctx.egui_wants_pointer_input(), } } } } pub fn ime_event_enable(&mut self) { if !self.has_sent_ime_enabled { self.egui_input .events .push(egui::Event::Ime(egui::ImeEvent::Enabled)); self.has_sent_ime_enabled = true; } } pub fn ime_event_disable(&mut self) { self.egui_input .events .push(egui::Event::Ime(egui::ImeEvent::Disabled)); self.has_sent_ime_enabled = false; } pub fn on_mouse_motion(&mut self, delta: (f64, f64)) { self.egui_input.events.push(egui::Event::MouseMoved(Vec2 { x: delta.0 as f32, y: delta.1 as f32, })); } /// Call this when there is a new [`accesskit::ActionRequest`]. /// /// The result can be found in [`Self::egui_input`] and be extracted with [`Self::take_egui_input`]. #[cfg(feature = "accesskit")] pub fn on_accesskit_action_request(&mut self, request: accesskit::ActionRequest) { self.egui_input .events .push(egui::Event::AccessKitActionRequest(request)); } fn on_mouse_button_input( &mut self, state: winit::event::ElementState, button: winit::event::MouseButton, ) { if let Some(pos) = self.pointer_pos_in_points && let Some(button) = translate_mouse_button(button) { let pressed = state == winit::event::ElementState::Pressed; self.egui_input.events.push(egui::Event::PointerButton { pos, button, pressed, modifiers: self.egui_input.modifiers, }); if self.simulate_touch_screen { if pressed { self.any_pointer_button_down = true; self.egui_input.events.push(egui::Event::Touch { device_id: egui::TouchDeviceId(0), id: egui::TouchId(0), phase: egui::TouchPhase::Start, pos, force: None, }); } else { self.any_pointer_button_down = false; self.egui_input.events.push(egui::Event::PointerGone); self.egui_input.events.push(egui::Event::Touch { device_id: egui::TouchDeviceId(0), id: egui::TouchId(0), phase: egui::TouchPhase::End, pos, force: None, }); } } } } fn on_cursor_moved( &mut self, window: &Window, pos_in_pixels: winit::dpi::PhysicalPosition<f64>, ) { let pixels_per_point = pixels_per_point(&self.egui_ctx, window); let pos_in_points = egui::pos2( pos_in_pixels.x as f32 / pixels_per_point, pos_in_pixels.y as f32 / pixels_per_point, ); self.pointer_pos_in_points = Some(pos_in_points); if self.simulate_touch_screen { if self.any_pointer_button_down { self.egui_input .events .push(egui::Event::PointerMoved(pos_in_points)); self.egui_input.events.push(egui::Event::Touch { device_id: egui::TouchDeviceId(0), id: egui::TouchId(0), phase: egui::TouchPhase::Move, pos: pos_in_points, force: None, }); } } else { self.egui_input .events .push(egui::Event::PointerMoved(pos_in_points)); } } fn on_touch(&mut self, window: &Window, touch: &winit::event::Touch) { let pixels_per_point = pixels_per_point(&self.egui_ctx, window); // Emit touch event self.egui_input.events.push(egui::Event::Touch { device_id: egui::TouchDeviceId(egui::epaint::util::hash(touch.device_id)), id: egui::TouchId::from(touch.id), phase: to_egui_touch_phase(touch.phase), pos: egui::pos2( touch.location.x as f32 / pixels_per_point, touch.location.y as f32 / pixels_per_point, ), force: match touch.force { Some(winit::event::Force::Normalized(force)) => Some(force as f32), Some(winit::event::Force::Calibrated { force, max_possible_force, .. }) => Some((force / max_possible_force) as f32), None => None, }, }); // If we're not yet translating a touch or we're translating this very // touch … if self.pointer_touch_id.is_none() || self.pointer_touch_id.unwrap_or_default() == touch.id { // … emit PointerButton resp. PointerMoved events to emulate mouse match touch.phase { winit::event::TouchPhase::Started => { self.pointer_touch_id = Some(touch.id); // First move the pointer to the right location self.on_cursor_moved(window, touch.location); self.on_mouse_button_input( winit::event::ElementState::Pressed, winit::event::MouseButton::Left, ); } winit::event::TouchPhase::Moved => { self.on_cursor_moved(window, touch.location); } winit::event::TouchPhase::Ended => { self.pointer_touch_id = None; self.on_mouse_button_input( winit::event::ElementState::Released, winit::event::MouseButton::Left, ); // The pointer should vanish completely to not get any // hover effects self.pointer_pos_in_points = None; self.egui_input.events.push(egui::Event::PointerGone); } winit::event::TouchPhase::Cancelled => { self.pointer_touch_id = None; self.pointer_pos_in_points = None; self.egui_input.events.push(egui::Event::PointerGone); } } } } fn on_mouse_wheel( &mut self, window: &Window, delta: winit::event::MouseScrollDelta, phase: winit::event::TouchPhase, ) { let pixels_per_point = pixels_per_point(&self.egui_ctx, window); { let (unit, delta) = match delta { winit::event::MouseScrollDelta::LineDelta(x, y) => { (egui::MouseWheelUnit::Line, egui::vec2(x, y)) } winit::event::MouseScrollDelta::PixelDelta(winit::dpi::PhysicalPosition { x, y, }) => ( egui::MouseWheelUnit::Point, egui::vec2(x as f32, y as f32) / pixels_per_point, ), }; let phase = to_egui_touch_phase(phase); let modifiers = self.egui_input.modifiers; self.egui_input.events.push(egui::Event::MouseWheel { unit, delta, phase, modifiers, }); } } fn on_keyboard_input(&mut self, event: &winit::event::KeyEvent) { let winit::event::KeyEvent { // Represents the position of a key independent of the currently active layout. // // It also uniquely identifies the physical key (i.e. it's mostly synonymous with a scancode). // The most prevalent use case for this is games. For example the default keys for the player // to move around might be the W, A, S, and D keys on a US layout. The position of these keys // is more important than their label, so they should map to Z, Q, S, and D on an "AZERTY" // layout. (This value is `KeyCode::KeyW` for the Z key on an AZERTY layout.) physical_key, // Represents the results of a keymap, i.e. what character a certain key press represents. // When telling users "Press Ctrl-F to find", this is where we should // look for the "F" key, because they may have a dvorak layout on // a qwerty keyboard, and so the logical "F" character may not be located on the physical `KeyCode::KeyF` position. logical_key: winit_logical_key, text, state, location: _, // e.g. is it on the numpad? repeat: _, // egui will figure this out for us .. } = event; let pressed = *state == winit::event::ElementState::Pressed; let physical_key = if let winit::keyboard::PhysicalKey::Code(keycode) = *physical_key { key_from_key_code(keycode) } else { None }; let logical_key = key_from_winit_key(winit_logical_key); // Helpful logging to enable when adding new key support log::trace!( "logical {:?} -> {:?}, physical {:?} -> {:?}", event.logical_key, logical_key, event.physical_key, physical_key ); // "Logical OR physical key" is a fallback mechanism for keyboard layouts without Latin characters: it lets them // emit events as if the corresponding keys from the Latin layout were pressed. In this case, clipboard shortcuts // are mapped to the physical keys that normally contain C, X, V, etc. // See also: https://github.com/emilk/egui/issues/3653 if let Some(active_key) = logical_key.or(physical_key) { if pressed { if is_cut_command(self.egui_input.modifiers, active_key) { self.egui_input.events.push(egui::Event::Cut); return; } else if is_copy_command(self.egui_input.modifiers, active_key) { self.egui_input.events.push(egui::Event::Copy); return; } else if is_paste_command(self.egui_input.modifiers, active_key) { if let Some(contents) = self.clipboard.get() { let contents = contents.replace("\r\n", "\n"); if !contents.is_empty() { self.egui_input.events.push(egui::Event::Paste(contents)); } } return; } } self.egui_input.events.push(egui::Event::Key { key: active_key, physical_key, pressed, repeat: false, // egui will fill this in for us! modifiers: self.egui_input.modifiers, }); } if let Some(text) = text .as_ref() .map(|t| t.as_str()) .or_else(|| winit_logical_key.to_text()) { // Make sure there is text, and that it is not control characters // (e.g. delete is sent as "\u{f728}" on macOS). if !text.is_empty() && text.chars().all(is_printable_char) { // On some platforms we get here when the user presses Cmd-C (copy), ctrl-W, etc.
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
true
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui-winit/src/clipboard.rs
crates/egui-winit/src/clipboard.rs
use raw_window_handle::RawDisplayHandle; /// Handles interfacing with the OS clipboard. /// /// If the "clipboard" feature is off, or we cannot connect to the OS clipboard, /// then a fallback clipboard that just works within the same app is used instead. pub struct Clipboard { #[cfg(all( not(any(target_os = "android", target_os = "ios")), feature = "arboard", ))] arboard: Option<arboard::Clipboard>, #[cfg(all( any( target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd" ), feature = "smithay-clipboard" ))] smithay: Option<smithay_clipboard::Clipboard>, /// Fallback manual clipboard. clipboard: String, } impl Clipboard { /// Construct a new instance pub fn new(_raw_display_handle: Option<RawDisplayHandle>) -> Self { Self { #[cfg(all( not(any(target_os = "android", target_os = "ios")), feature = "arboard", ))] arboard: init_arboard(), #[cfg(all( any( target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd" ), feature = "smithay-clipboard" ))] smithay: init_smithay_clipboard(_raw_display_handle), clipboard: Default::default(), } } pub fn get(&mut self) -> Option<String> { #[cfg(all( any( target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd" ), feature = "smithay-clipboard" ))] if let Some(clipboard) = &mut self.smithay { return match clipboard.load() { Ok(text) => Some(text), Err(err) => { log::error!("smithay paste error: {err}"); None } }; } #[cfg(all( not(any(target_os = "android", target_os = "ios")), feature = "arboard", ))] if let Some(clipboard) = &mut self.arboard { return match clipboard.get_text() { Ok(text) => Some(text), Err(err) => { log::error!("arboard paste error: {err}"); None } }; } Some(self.clipboard.clone()) } pub fn set_text(&mut self, text: String) { #[cfg(all( any( target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd" ), feature = "smithay-clipboard" ))] if let Some(clipboard) = &mut self.smithay { clipboard.store(text); return; } #[cfg(all( not(any(target_os = "android", target_os = "ios")), feature = "arboard", ))] if let Some(clipboard) = &mut self.arboard { if let Err(err) = clipboard.set_text(text) { log::error!("arboard copy/cut error: {err}"); } return; } self.clipboard = text; } pub fn set_image(&mut self, image: &egui::ColorImage) { #[cfg(all( not(any(target_os = "android", target_os = "ios")), feature = "arboard", ))] if let Some(clipboard) = &mut self.arboard { if let Err(err) = clipboard.set_image(arboard::ImageData { width: image.width(), height: image.height(), bytes: std::borrow::Cow::Borrowed(bytemuck::cast_slice(&image.pixels)), }) { log::error!("arboard copy/cut error: {err}"); } log::debug!("Copied image to clipboard"); return; } log::error!( "Copying images is not supported. Enable the 'clipboard' feature of `egui-winit` to enable it." ); _ = image; } } #[cfg(all( not(any(target_os = "android", target_os = "ios")), feature = "arboard", ))] fn init_arboard() -> Option<arboard::Clipboard> { profiling::function_scope!(); log::trace!("Initializing arboard clipboard…"); match arboard::Clipboard::new() { Ok(clipboard) => Some(clipboard), Err(err) => { log::warn!("Failed to initialize arboard clipboard: {err}"); None } } } #[cfg(all( any( target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd" ), feature = "smithay-clipboard" ))] fn init_smithay_clipboard( raw_display_handle: Option<RawDisplayHandle>, ) -> Option<smithay_clipboard::Clipboard> { #![expect(clippy::undocumented_unsafe_blocks)] profiling::function_scope!(); if let Some(RawDisplayHandle::Wayland(display)) = raw_display_handle { log::trace!("Initializing smithay clipboard…"); #[expect(unsafe_code)] Some(unsafe { smithay_clipboard::Clipboard::new(display.display.as_ptr()) }) } else { #[cfg(feature = "wayland")] log::debug!("Cannot init smithay clipboard without a Wayland display handle"); #[cfg(not(feature = "wayland"))] log::debug!( "Cannot init smithay clipboard: the 'wayland' feature of 'egui-winit' is not enabled" ); None } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/src/lib.rs
crates/egui_demo_lib/src/lib.rs
//! Demo-code for showing how egui is used. //! //! This library can be used to test 3rd party egui integrations (see for instance <https://github.com/not-fl3/egui-miniquad/blob/master/examples/demo.rs>). //! //! The demo is also used in benchmarks and tests. //! //! ## Feature flags #![cfg_attr(feature = "document-features", doc = document_features::document_features!())] //! #![expect(clippy::unwrap_used)] // TODO(emilk): avoid unwraps mod demo; pub mod easy_mark; mod rendering_test; pub use demo::{Demo, DemoWindows, View, WidgetGallery}; pub use rendering_test::ColorTest; /// View some Rust code with syntax highlighting and selection. pub(crate) fn rust_view_ui(ui: &mut egui::Ui, code: &str) { let language = "rs"; let theme = egui_extras::syntax_highlighting::CodeTheme::from_memory(ui.ctx(), ui.style()); egui_extras::syntax_highlighting::code_view_ui(ui, &theme, code, language); } // ---------------------------------------------------------------------------- /// Create a [`Hyperlink`](egui::Hyperlink) to this egui source code file on github. #[macro_export] macro_rules! egui_github_link_file { () => { $crate::egui_github_link_file!("(source code)") }; ($label: expr) => { egui::github_link_file!( "https://github.com/emilk/egui/blob/main/", egui::RichText::new($label).small() ) }; } /// Create a [`Hyperlink`](egui::Hyperlink) to this egui source code file and line on github. #[macro_export] macro_rules! egui_github_link_file_line { () => { $crate::egui_github_link_file_line!("(source code)") }; ($label: expr) => { egui::github_link_file_line!( "https://github.com/emilk/egui/blob/main/", egui::RichText::new($label).small() ) }; } // ---------------------------------------------------------------------------- pub const LOREM_IPSUM: &str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."; pub const LOREM_IPSUM_LONG: &str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Curabitur pretium tincidunt lacus. Nulla gravida orci a odio. Nullam various, turpis et commodo pharetra, est eros bibendum elit, nec luctus magna felis sollicitudin mauris. Integer in mauris eu nibh euismod gravida. Duis ac tellus et risus vulputate vehicula. Donec lobortis risus a elit. Etiam tempor. Ut ullamcorper, ligula eu tempor congue, eros est euismod turpis, id tincidunt sapien risus a quam. Maecenas fermentum consequat mi. Donec fermentum. Pellentesque malesuada nulla a mi. Duis sapien sem, aliquet nec, commodo eget, consequat quis, neque. Aliquam faucibus, elit ut dictum aliquet, felis nisl adipiscing sapien, sed malesuada diam lacus eget erat. Cras mollis scelerisque nunc. Nullam arcu. Aliquam consequat. Curabitur augue lorem, dapibus quis, laoreet et, pretium ac, nisi. Aenean magna nisl, mollis quis, molestie eu, feugiat in, orci. In hac habitasse platea dictumst."; // ---------------------------------------------------------------------------- #[test] fn test_egui_e2e() { let mut demo_windows = crate::DemoWindows::default(); let ctx = egui::Context::default(); let raw_input = egui::RawInput::default(); const NUM_FRAMES: usize = 5; for _ in 0..NUM_FRAMES { let full_output = ctx.run_ui(raw_input.clone(), |ui| { demo_windows.ui(ui); }); let clipped_primitives = ctx.tessellate(full_output.shapes, full_output.pixels_per_point); assert!(!clipped_primitives.is_empty()); } } #[test] fn test_egui_zero_window_size() { let mut demo_windows = crate::DemoWindows::default(); let ctx = egui::Context::default(); let raw_input = egui::RawInput { screen_rect: Some(egui::Rect::from_min_max(egui::Pos2::ZERO, egui::Pos2::ZERO)), ..Default::default() }; const NUM_FRAMES: usize = 5; for _ in 0..NUM_FRAMES { let full_output = ctx.run_ui(raw_input.clone(), |ui| { demo_windows.ui(ui); }); let clipped_primitives = ctx.tessellate(full_output.shapes, full_output.pixels_per_point); assert!( clipped_primitives.is_empty(), "There should be nothing to show, has at least one primitive with clip_rect: {:?}", clipped_primitives[0].clip_rect ); } } // ---------------------------------------------------------------------------- /// Detect narrow screens. This is used to show a simpler UI on mobile devices, /// especially for the web demo at <https://egui.rs>. pub fn is_mobile(ctx: &egui::Context) -> bool { let screen_size = ctx.content_rect().size(); screen_size.x < 550.0 }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/src/rendering_test.rs
crates/egui_demo_lib/src/rendering_test.rs
use std::collections::HashMap; use egui::{ Align2, Color32, FontId, Image, Mesh, Pos2, Rect, Response, Rgba, RichText, Sense, Shape, Stroke, TextureHandle, TextureOptions, Ui, Vec2, emath::GuiRounding as _, epaint, lerp, pos2, vec2, widgets::color_picker::show_color, }; const GRADIENT_SIZE: Vec2 = vec2(256.0, 18.0); const BLACK: Color32 = Color32::BLACK; const GREEN: Color32 = Color32::GREEN; const RED: Color32 = Color32::RED; const TRANSPARENT: Color32 = Color32::TRANSPARENT; const WHITE: Color32 = Color32::WHITE; /// A test for sanity-checking and diagnosing egui rendering backends. #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct ColorTest { #[cfg_attr(feature = "serde", serde(skip))] tex_mngr: TextureManager, vertex_gradients: bool, texture_gradients: bool, } impl Default for ColorTest { fn default() -> Self { Self { tex_mngr: Default::default(), vertex_gradients: true, texture_gradients: true, } } } impl ColorTest { pub fn ui(&mut self, ui: &mut Ui) { ui.vertical_centered(|ui| { ui.add(crate::egui_github_link_file!()); }); ui.horizontal_wrapped(|ui|{ ui.label("This is made to test that the egui rendering backend is set up correctly."); ui.add(egui::Label::new("❓").sense(egui::Sense::click())) .on_hover_text("The texture sampling should be sRGB-aware, and every other color operation should be done in gamma-space (sRGB). All colors should use pre-multiplied alpha"); }); ui.separator(); pixel_test(ui); ui.separator(); ui.collapsing("Color test", |ui| { self.color_test(ui); }); ui.separator(); ui.heading("Text rendering"); text_on_bg(ui, Color32::from_gray(200), Color32::from_gray(230)); // gray on gray text_on_bg(ui, Color32::from_gray(140), Color32::from_gray(28)); // dark mode normal text // Matches Mac Font book (useful for testing): text_on_bg(ui, Color32::from_gray(39), Color32::from_gray(255)); text_on_bg(ui, Color32::from_gray(220), Color32::from_gray(30)); ui.separator(); blending_and_feathering_test(ui); } fn color_test(&mut self, ui: &mut Ui) { ui.label("If the rendering is done right, all groups of gradients will look uniform."); ui.horizontal(|ui| { ui.checkbox(&mut self.vertex_gradients, "Vertex gradients"); ui.checkbox(&mut self.texture_gradients, "Texture gradients"); }); ui.heading("sRGB color test"); ui.label("Use a color picker to ensure this color is (255, 165, 0) / #ffa500"); ui.scope(|ui| { ui.spacing_mut().item_spacing.y = 0.0; // No spacing between gradients let g = Gradient::one_color(Color32::from_rgb(255, 165, 0)); self.vertex_gradient(ui, "orange rgb(255, 165, 0) - vertex", WHITE, &g); self.tex_gradient(ui, "orange rgb(255, 165, 0) - texture", WHITE, &g); }); ui.separator(); ui.label("Test that vertex color times texture color is done in gamma space:"); ui.scope(|ui| { let tex_color = Color32::from_rgb(64, 128, 255); let vertex_color = Color32::from_rgb(128, 196, 196); let ground_truth = mul_color_gamma(tex_color, vertex_color); ui.horizontal(|ui| { let color_size = ui.spacing().interact_size; ui.label("texture"); show_color(ui, tex_color, color_size); ui.label(" * "); show_color(ui, vertex_color, color_size); ui.label(" vertex color ="); }); ui.spacing_mut().item_spacing.y = 0.0; // No spacing between gradients { let g = Gradient::one_color(ground_truth); self.vertex_gradient(ui, "Ground truth (vertices)", WHITE, &g); self.tex_gradient(ui, "Ground truth (texture)", WHITE, &g); } ui.horizontal(|ui| { let g = Gradient::one_color(tex_color); let tex = self.tex_mngr.get(ui.ctx(), &g); let texel_offset = 0.5 / (g.0.len() as f32); let uv = Rect::from_min_max(pos2(texel_offset, 0.0), pos2(1.0 - texel_offset, 1.0)); ui.add( Image::from_texture((tex.id(), GRADIENT_SIZE)) .tint(vertex_color) .uv(uv), ) .on_hover_text(format!("A texture that is {} texels wide", g.0.len())); ui.label("GPU result"); }); }); ui.separator(); ui.label("Test that blending is done in gamma space:"); ui.scope(|ui| { let background = Color32::from_rgb(200, 60, 10); let foreground = Color32::from_rgba_unmultiplied(108, 65, 200, 82); let ground_truth = background.blend(foreground); ui.horizontal(|ui| { let color_size = ui.spacing().interact_size; ui.label("Background:"); show_color(ui, background, color_size); ui.label(", foreground: "); show_color(ui, foreground, color_size); }); ui.spacing_mut().item_spacing.y = 0.0; // No spacing between gradients { let g = Gradient::one_color(ground_truth); self.vertex_gradient(ui, "Ground truth (vertices)", WHITE, &g); self.tex_gradient(ui, "Ground truth (texture)", WHITE, &g); } { let g = Gradient::one_color(foreground); self.vertex_gradient(ui, "Vertex blending", background, &g); self.tex_gradient(ui, "Texture blending", background, &g); } }); ui.separator(); // TODO(emilk): test color multiplication (image tint), // to make sure vertex and texture color multiplication is done in gamma space. ui.label("Gamma interpolation:"); self.show_gradients(ui, WHITE, (RED, GREEN), Interpolation::Gamma); ui.separator(); self.show_gradients(ui, RED, (TRANSPARENT, GREEN), Interpolation::Gamma); ui.separator(); self.show_gradients(ui, WHITE, (TRANSPARENT, GREEN), Interpolation::Gamma); ui.separator(); self.show_gradients(ui, BLACK, (BLACK, WHITE), Interpolation::Gamma); ui.separator(); self.show_gradients(ui, WHITE, (BLACK, TRANSPARENT), Interpolation::Gamma); ui.separator(); self.show_gradients(ui, BLACK, (TRANSPARENT, WHITE), Interpolation::Gamma); ui.separator(); ui.label("Additive blending: add more and more blue to the red background:"); self.show_gradients( ui, RED, (TRANSPARENT, Color32::from_rgb_additive(0, 0, 255)), Interpolation::Gamma, ); ui.separator(); ui.label("Texture interpolation (texture sampling) should be in gamma space:"); self.show_gradients(ui, WHITE, (RED, GREEN), Interpolation::Gamma); } fn show_gradients( &mut self, ui: &mut Ui, bg_fill: Color32, (left, right): (Color32, Color32), interpolation: Interpolation, ) { let is_opaque = left.is_opaque() && right.is_opaque(); ui.horizontal(|ui| { let color_size = ui.spacing().interact_size; if !is_opaque { ui.label("Background:"); show_color(ui, bg_fill, color_size); } ui.label("gradient"); show_color(ui, left, color_size); ui.label("-"); show_color(ui, right, color_size); }); ui.scope(|ui| { ui.spacing_mut().item_spacing.y = 0.0; // No spacing between gradients if is_opaque { let g = Gradient::ground_truth_gradient(left, right, interpolation); self.vertex_gradient(ui, "Ground Truth (CPU gradient) - vertices", bg_fill, &g); self.tex_gradient(ui, "Ground Truth (CPU gradient) - texture", bg_fill, &g); } else { let g = Gradient::ground_truth_gradient(left, right, interpolation) .with_bg_fill(bg_fill); self.vertex_gradient( ui, "Ground Truth (CPU gradient, CPU blending) - vertices", bg_fill, &g, ); self.tex_gradient( ui, "Ground Truth (CPU gradient, CPU blending) - texture", bg_fill, &g, ); let g = Gradient::ground_truth_gradient(left, right, interpolation); self.vertex_gradient(ui, "CPU gradient, GPU blending - vertices", bg_fill, &g); self.tex_gradient(ui, "CPU gradient, GPU blending - texture", bg_fill, &g); } let g = Gradient::endpoints(left, right); match interpolation { Interpolation::Linear => {} Interpolation::Gamma => { self.tex_gradient(ui, "Texture of width 2 (test texture sampler)", bg_fill, &g); // vertex shader uses gamma self.vertex_gradient( ui, "Triangle mesh of width 2 (test vertex decode and interpolation)", bg_fill, &g, ); } } }); } fn tex_gradient(&mut self, ui: &mut Ui, label: &str, bg_fill: Color32, gradient: &Gradient) { if !self.texture_gradients { return; } ui.horizontal(|ui| { let tex = self.tex_mngr.get(ui.ctx(), gradient); let texel_offset = 0.5 / (gradient.0.len() as f32); let uv = Rect::from_min_max(pos2(texel_offset, 0.0), pos2(1.0 - texel_offset, 1.0)); ui.add( Image::from_texture((tex.id(), GRADIENT_SIZE)) .bg_fill(bg_fill) .uv(uv), ) .on_hover_text(format!( "A texture that is {} texels wide", gradient.0.len() )); ui.label(label); }); } fn vertex_gradient(&self, ui: &mut Ui, label: &str, bg_fill: Color32, gradient: &Gradient) { if !self.vertex_gradients { return; } ui.horizontal(|ui| { vertex_gradient(ui, bg_fill, gradient).on_hover_text(format!( "A triangle mesh that is {} vertices wide", gradient.0.len() )); ui.label(label); }); } } fn vertex_gradient(ui: &mut Ui, bg_fill: Color32, gradient: &Gradient) -> Response { let (rect, response) = ui.allocate_at_least(GRADIENT_SIZE, Sense::hover()); let rect = rect.round_to_pixels(ui.pixels_per_point()); if bg_fill != Default::default() { let mut mesh = Mesh::default(); mesh.add_colored_rect(rect, bg_fill); ui.painter().add(Shape::mesh(mesh)); } { let n = gradient.0.len(); assert!( n >= 2, "A gradient must have at least two colors, but this had {n}" ); let mut mesh = Mesh::default(); for (i, &color) in gradient.0.iter().enumerate() { let t = i as f32 / (n as f32 - 1.0); let x = lerp(rect.x_range(), t); mesh.colored_vertex(pos2(x, rect.top()), color); mesh.colored_vertex(pos2(x, rect.bottom()), color); if i < n - 1 { let i = i as u32; mesh.add_triangle(2 * i, 2 * i + 1, 2 * i + 2); mesh.add_triangle(2 * i + 1, 2 * i + 2, 2 * i + 3); } } ui.painter().add(Shape::mesh(mesh)); } response } #[derive(Clone, Copy)] enum Interpolation { /// egui used to want Linear interpolation for some things, but now we're always in gamma space. #[expect(unused)] Linear, Gamma, } #[derive(Clone, Hash, PartialEq, Eq)] struct Gradient(pub Vec<Color32>); impl Gradient { pub fn one_color(srgba: Color32) -> Self { Self(vec![srgba, srgba]) } pub fn endpoints(left: Color32, right: Color32) -> Self { Self(vec![left, right]) } pub fn ground_truth_gradient( left: Color32, right: Color32, interpolation: Interpolation, ) -> Self { match interpolation { Interpolation::Linear => Self::ground_truth_linear_gradient(left, right), Interpolation::Gamma => Self::ground_truth_gamma_gradient(left, right), } } pub fn ground_truth_linear_gradient(left: Color32, right: Color32) -> Self { let left = Rgba::from(left); let right = Rgba::from(right); let n = 255; Self( (0..=n) .map(|i| { let t = i as f32 / n as f32; Color32::from(lerp(left..=right, t)) }) .collect(), ) } pub fn ground_truth_gamma_gradient(left: Color32, right: Color32) -> Self { let n = 255; Self( (0..=n) .map(|i| { let t = i as f32 / n as f32; left.lerp_to_gamma(right, t) }) .collect(), ) } /// Do premultiplied alpha-aware blending of the gradient on top of the fill color /// in gamma-space. pub fn with_bg_fill(self, bg: Color32) -> Self { Self( self.0 .into_iter() .map(|fg| { let a = fg.a() as f32 / 255.0; Color32::from_rgba_premultiplied( (bg[0] as f32 * (1.0 - a) + fg[0] as f32).round() as u8, (bg[1] as f32 * (1.0 - a) + fg[1] as f32).round() as u8, (bg[2] as f32 * (1.0 - a) + fg[2] as f32).round() as u8, (bg[3] as f32 * (1.0 - a) + fg[3] as f32).round() as u8, ) }) .collect(), ) } pub fn to_pixel_row(&self) -> Vec<Color32> { self.0.clone() } } #[derive(Default)] struct TextureManager(HashMap<Gradient, TextureHandle>); impl TextureManager { fn get(&mut self, ctx: &egui::Context, gradient: &Gradient) -> &TextureHandle { self.0.entry(gradient.clone()).or_insert_with(|| { let pixels = gradient.to_pixel_row(); let width = pixels.len(); let height = 1; ctx.load_texture( "color_test_gradient", epaint::ColorImage::new([width, height], pixels), TextureOptions::LINEAR, ) }) } } /// A visual test that the rendering is correctly aligned on the physical pixel grid. /// /// Requires eyes and a magnifying glass to verify. pub fn pixel_test(ui: &mut Ui) { ui.heading("Pixel alignment test"); ui.label("If anything is blurry, then everything will be blurry, including text."); ui.label("You might need a magnifying glass to check this test."); if cfg!(target_arch = "wasm32") { ui.label("Make sure these test pass even when you zoom in/out and resize the browser."); } ui.add_space(4.0); pixel_test_lines(ui); ui.add_space(4.0); pixel_test_squares(ui); ui.add_space(4.0); pixel_test_strokes(ui); } fn pixel_test_strokes(ui: &mut Ui) { ui.label("The strokes should align to the physical pixel grid."); let color = if ui.style().visuals.dark_mode { egui::Color32::WHITE } else { egui::Color32::BLACK }; let pixels_per_point = ui.pixels_per_point(); for thickness_pixels in 1..=3 { let thickness_pixels = thickness_pixels as f32; let thickness_points = thickness_pixels / pixels_per_point; let num_squares = (pixels_per_point * 10.0).round().max(10.0) as u32; let size_pixels = vec2(ui.min_size().x, num_squares as f32 + thickness_pixels * 2.0); let size_points = size_pixels / pixels_per_point; let (response, painter) = ui.allocate_painter(size_points, Sense::hover()); let mut cursor_pixel = Pos2::new( response.rect.min.x * pixels_per_point + thickness_pixels, response.rect.min.y * pixels_per_point + thickness_pixels, ) .ceil(); let stroke = Stroke::new(thickness_points, color); for size in 1..=num_squares { let rect_points = Rect::from_min_size( Pos2::new(cursor_pixel.x, cursor_pixel.y), Vec2::splat(size as f32), ); painter.rect_stroke( rect_points / pixels_per_point, 0.0, stroke, egui::StrokeKind::Outside, ); cursor_pixel.x += (1 + size) as f32 + thickness_pixels * 2.0; } } } fn pixel_test_squares(ui: &mut Ui) { ui.label("The first square should be exactly one physical pixel big."); ui.label("They should be exactly one physical pixel apart."); ui.label("Each subsequent square should be one physical pixel larger than the previous."); ui.label("They should be perfectly aligned to the physical pixel grid."); let color = if ui.style().visuals.dark_mode { egui::Color32::WHITE } else { egui::Color32::BLACK }; let pixels_per_point = ui.pixels_per_point(); let num_squares = (pixels_per_point * 10.0).round().max(10.0) as u32; let size_pixels = vec2( ((num_squares + 1) * (num_squares + 2) / 2) as f32, num_squares as f32, ); let size_points = size_pixels / pixels_per_point + Vec2::splat(2.0); let (response, painter) = ui.allocate_painter(size_points, Sense::hover()); let mut cursor_pixel = Pos2::new( response.rect.min.x * pixels_per_point, response.rect.min.y * pixels_per_point, ) .ceil(); for size in 1..=num_squares { let rect_points = Rect::from_min_size( Pos2::new(cursor_pixel.x, cursor_pixel.y), Vec2::splat(size as f32), ); painter.rect_filled(rect_points / pixels_per_point, 0.0, color); cursor_pixel.x += (1 + size) as f32; } } fn pixel_test_lines(ui: &mut Ui) { let pixels_per_point = ui.pixels_per_point(); let n = (96.0 * pixels_per_point) as usize; ui.label("The lines should be exactly one physical pixel wide, one physical pixel apart."); ui.label("They should be perfectly white and black."); let hspace_px = pixels_per_point * 4.0; let size_px = Vec2::new(2.0 * n as f32 + hspace_px, n as f32); let size_points = size_px / pixels_per_point + Vec2::splat(2.0); let (response, painter) = ui.allocate_painter(size_points, Sense::hover()); let mut cursor_px = Pos2::new( response.rect.min.x * pixels_per_point, response.rect.min.y * pixels_per_point, ) .ceil(); // Vertical stripes: for x in 0..n / 2 { let rect_px = Rect::from_min_size( Pos2::new(cursor_px.x + 2.0 * x as f32, cursor_px.y), Vec2::new(1.0, n as f32), ); painter.rect_filled(rect_px / pixels_per_point, 0.0, egui::Color32::WHITE); let rect_px = rect_px.translate(vec2(1.0, 0.0)); painter.rect_filled(rect_px / pixels_per_point, 0.0, egui::Color32::BLACK); } cursor_px.x += n as f32 + hspace_px; // Horizontal stripes: for y in 0..n / 2 { let rect_px = Rect::from_min_size( Pos2::new(cursor_px.x, cursor_px.y + 2.0 * y as f32), Vec2::new(n as f32, 1.0), ); painter.rect_filled(rect_px / pixels_per_point, 0.0, egui::Color32::WHITE); let rect_px = rect_px.translate(vec2(0.0, 1.0)); painter.rect_filled(rect_px / pixels_per_point, 0.0, egui::Color32::BLACK); } } fn blending_and_feathering_test(ui: &mut Ui) { ui.label("The left side shows how lines of different widths look."); ui.label("The right side tests text rendering at different opacities and sizes."); ui.label("The top and bottom images should look symmetrical in their intensities."); let size = vec2(512.0, 512.0); let (response, painter) = ui.allocate_painter(size, Sense::hover()); let rect = response.rect; let mut top_half = rect; top_half.set_bottom(top_half.center().y); painter.rect_filled(top_half, 0.0, Color32::BLACK); paint_fine_lines_and_text(&painter, top_half, Color32::WHITE); let mut bottom_half = rect; bottom_half.set_top(bottom_half.center().y); painter.rect_filled(bottom_half, 0.0, Color32::WHITE); paint_fine_lines_and_text(&painter, bottom_half, Color32::BLACK); } fn text_on_bg(ui: &mut egui::Ui, fg: Color32, bg: Color32) { assert!( fg.is_opaque(), "Foreground color must be opaque, but was: {fg:?}", ); assert!( bg.is_opaque(), "Background color must be opaque, but was: {bg:?}", ); ui.horizontal(|ui| { ui.label( RichText::from("▣ The quick brown fox jumps over the lazy dog and runs away.") .background_color(bg) .color(fg), ); ui.label(format!( "({} {} {}) on ({} {} {})", fg.r(), fg.g(), fg.b(), bg.r(), bg.g(), bg.b(), )); }); } fn paint_fine_lines_and_text(painter: &egui::Painter, mut rect: Rect, color: Color32) { { let mut y = 0.0; for opacity in [1.00, 0.50, 0.25, 0.10, 0.05, 0.02, 0.01, 0.00] { painter.text( rect.center_top() + vec2(0.0, y), Align2::LEFT_TOP, format!("{:.0}% white", 100.0 * opacity), FontId::proportional(14.0), Color32::WHITE.gamma_multiply(opacity), ); painter.text( rect.center_top() + vec2(80.0, y), Align2::LEFT_TOP, format!("{:.0}% gray", 100.0 * opacity), FontId::proportional(14.0), Color32::GRAY.gamma_multiply(opacity), ); painter.text( rect.center_top() + vec2(160.0, y), Align2::LEFT_TOP, format!("{:.0}% black", 100.0 * opacity), FontId::proportional(14.0), Color32::BLACK.gamma_multiply(opacity), ); y += 20.0; } for font_size in [6.0, 7.0, 8.0, 9.0, 10.0, 12.0, 14.0] { painter.text( rect.center_top() + vec2(0.0, y), Align2::LEFT_TOP, format!( "{font_size}px - The quick brown fox jumps over the lazy dog and runs away." ), FontId::proportional(font_size), color, ); y += font_size + 1.0; } } rect.max.x = rect.center().x; rect = rect.shrink(16.0); for width in [0.05, 0.1, 0.25, 0.5, 1.0, 2.0, 4.0] { painter.text( rect.left_top(), Align2::CENTER_CENTER, width.to_string(), FontId::monospace(12.0), color, ); painter.add(egui::epaint::CubicBezierShape::from_points_stroke( [ rect.left_top() + vec2(16.0, 0.0), rect.right_top(), rect.right_center(), rect.right_bottom(), ], false, Color32::TRANSPARENT, Stroke::new(width, color), )); rect.min.y += 24.0; rect.max.x -= 24.0; } rect.min.y += 16.0; painter.text( rect.left_top(), Align2::LEFT_CENTER, "transparent --> opaque", FontId::monospace(10.0), color, ); rect.min.y += 12.0; let mut mesh = Mesh::default(); mesh.colored_vertex(rect.left_bottom(), Color32::TRANSPARENT); mesh.colored_vertex(rect.left_top(), Color32::TRANSPARENT); mesh.colored_vertex(rect.right_bottom(), color); mesh.colored_vertex(rect.right_top(), color); mesh.add_triangle(0, 1, 2); mesh.add_triangle(1, 2, 3); painter.add(mesh); } fn mul_color_gamma(left: Color32, right: Color32) -> Color32 { Color32::from_rgba_premultiplied( (left.r() as f32 * right.r() as f32 / 255.0).round() as u8, (left.g() as f32 * right.g() as f32 / 255.0).round() as u8, (left.b() as f32 * right.b() as f32 / 255.0).round() as u8, (left.a() as f32 * right.a() as f32 / 255.0).round() as u8, ) } #[cfg(test)] mod tests { use crate::ColorTest; use egui_kittest::SnapshotResults; use egui_kittest::kittest::Queryable as _; #[test] pub fn rendering_test() { let mut results = SnapshotResults::new(); for dpi in [1.0, 1.25, 1.5, 1.75, 1.6666667, 2.0] { let mut color_test = ColorTest::default(); let mut harness = egui_kittest::Harness::builder() .with_pixels_per_point(dpi) .build_ui(|ui| { color_test.ui(ui); }); { // Expand color-test collapsing header. We accesskit-click since collapsing header // might not be on screen at this point. harness.get_by_label("Color test").click_accesskit(); harness.run(); } harness.fit_contents(); results.add(harness.try_snapshot(format!("rendering_test/dpi_{dpi:.2}"))); } } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/src/easy_mark/easy_mark_viewer.rs
crates/egui_demo_lib/src/easy_mark/easy_mark_viewer.rs
use super::easy_mark_parser as easy_mark; use egui::{ Align, Align2, Hyperlink, Layout, Response, RichText, Sense, Separator, Shape, TextStyle, Ui, vec2, }; /// Parse and display a VERY simple and small subset of Markdown. pub fn easy_mark(ui: &mut Ui, easy_mark: &str) { easy_mark_it(ui, easy_mark::Parser::new(easy_mark)); } pub fn easy_mark_it<'em>(ui: &mut Ui, items: impl Iterator<Item = easy_mark::Item<'em>>) { let initial_size = vec2( ui.available_width(), ui.spacing().interact_size.y, // Assume there will be ); let layout = Layout::left_to_right(Align::BOTTOM).with_main_wrap(true); ui.allocate_ui_with_layout(initial_size, layout, |ui| { ui.spacing_mut().item_spacing.x = 0.0; let row_height = ui.text_style_height(&TextStyle::Body); ui.set_row_height(row_height); for item in items { item_ui(ui, item); } }); } pub fn item_ui(ui: &mut Ui, item: easy_mark::Item<'_>) { let row_height = ui.text_style_height(&TextStyle::Body); let one_indent = row_height / 2.0; match item { easy_mark::Item::Newline => { // ui.label("\n"); // too much spacing (paragraph spacing) ui.allocate_exact_size(vec2(0.0, row_height), Sense::hover()); // make sure we take up some height ui.end_row(); ui.set_row_height(row_height); } easy_mark::Item::Text(style, text) => { let label = rich_text_from_style(text, &style); if style.small && !style.raised { ui.with_layout(Layout::left_to_right(Align::BOTTOM), |ui| { ui.set_min_height(row_height); ui.label(label); }); } else { ui.label(label); } } easy_mark::Item::Hyperlink(style, text, url) => { let label = rich_text_from_style(text, &style); if style.small && !style.raised { ui.with_layout(Layout::left_to_right(Align::BOTTOM), |ui| { ui.set_height(row_height); ui.add(Hyperlink::from_label_and_url(label, url)); }); } else { ui.add(Hyperlink::from_label_and_url(label, url)); } } easy_mark::Item::Separator => { ui.add(Separator::default().horizontal()); } easy_mark::Item::Indentation(indent) => { let indent = indent as f32 * one_indent; ui.allocate_exact_size(vec2(indent, row_height), Sense::hover()); } easy_mark::Item::QuoteIndent => { let rect = ui .allocate_exact_size(vec2(2.0 * one_indent, row_height), Sense::hover()) .0; let rect = rect.expand2(ui.style().spacing.item_spacing * 0.5); ui.painter().line_segment( [rect.center_top(), rect.center_bottom()], (1.0, ui.visuals().weak_text_color()), ); } easy_mark::Item::BulletPoint => { ui.allocate_exact_size(vec2(one_indent, row_height), Sense::hover()); bullet_point(ui, one_indent); ui.allocate_exact_size(vec2(one_indent, row_height), Sense::hover()); } easy_mark::Item::NumberedPoint(number) => { let width = 3.0 * one_indent; numbered_point(ui, width, number); ui.allocate_exact_size(vec2(one_indent, row_height), Sense::hover()); } easy_mark::Item::CodeBlock(_language, code) => { let where_to_put_background = ui.painter().add(Shape::Noop); let mut rect = ui.monospace(code).rect; rect = rect.expand(1.0); // looks better rect.max.x = ui.max_rect().max.x; let code_bg_color = ui.visuals().code_bg_color; ui.painter().set( where_to_put_background, Shape::rect_filled(rect, 1.0, code_bg_color), ); } } } fn rich_text_from_style(text: &str, style: &easy_mark::Style) -> RichText { let easy_mark::Style { heading, quoted, code, strong, underline, strikethrough, italics, small, raised, } = *style; let small = small || raised; // Raised text is also smaller let mut rich_text = RichText::new(text); if heading && !small { rich_text = rich_text.heading().strong(); } if small && !heading { rich_text = rich_text.small(); } if code { rich_text = rich_text.code(); } if strong { rich_text = rich_text.strong(); } else if quoted { rich_text = rich_text.weak(); } if underline { rich_text = rich_text.underline(); } if strikethrough { rich_text = rich_text.strikethrough(); } if italics { rich_text = rich_text.italics(); } if raised { rich_text = rich_text.raised(); } rich_text } fn bullet_point(ui: &mut Ui, width: f32) -> Response { let row_height = ui.text_style_height(&TextStyle::Body); let (rect, response) = ui.allocate_exact_size(vec2(width, row_height), Sense::hover()); ui.painter().circle_filled( rect.center(), rect.height() / 8.0, ui.visuals().strong_text_color(), ); response } fn numbered_point(ui: &mut Ui, width: f32, number: &str) -> Response { let font_id = TextStyle::Body.resolve(ui.style()); let row_height = ui.fonts_mut(|f| f.row_height(&font_id)); let (rect, response) = ui.allocate_exact_size(vec2(width, row_height), Sense::hover()); let text = format!("{number}."); let text_color = ui.visuals().strong_text_color(); ui.painter().text( rect.right_center(), Align2::RIGHT_CENTER, text, font_id, text_color, ); 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_lib/src/easy_mark/easy_mark_editor.rs
crates/egui_demo_lib/src/easy_mark/easy_mark_editor.rs
use egui::{ Key, KeyboardShortcut, Modifiers, ScrollArea, TextBuffer, TextEdit, Ui, text::CCursorRange, }; #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] pub struct EasyMarkEditor { code: String, highlight_editor: bool, show_rendered: bool, #[cfg_attr(feature = "serde", serde(skip))] highlighter: crate::easy_mark::MemoizedEasymarkHighlighter, } impl PartialEq for EasyMarkEditor { fn eq(&self, other: &Self) -> bool { (&self.code, self.highlight_editor, self.show_rendered) == (&other.code, other.highlight_editor, other.show_rendered) } } impl Default for EasyMarkEditor { fn default() -> Self { Self { code: DEFAULT_CODE.trim().to_owned(), highlight_editor: true, show_rendered: true, highlighter: Default::default(), } } } impl EasyMarkEditor { pub fn panels(&mut self, ui: &mut egui::Ui) { egui::Panel::bottom("easy_mark_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(crate::egui_github_link_file!()) }) }); egui::CentralPanel::default().show_inside(ui, |ui| { self.ui(ui); }); } pub fn ui(&mut self, ui: &mut egui::Ui) { egui::Grid::new("controls").show(ui, |ui| { let _response = ui.button("Hotkeys").on_hover_ui(nested_hotkeys_ui); ui.checkbox(&mut self.show_rendered, "Show rendered"); ui.checkbox(&mut self.highlight_editor, "Highlight editor"); egui::reset_button(ui, self, "Reset"); ui.end_row(); }); ui.separator(); if self.show_rendered { ui.columns(2, |columns| { ScrollArea::vertical() .id_salt("source") .show(&mut columns[0], |ui| self.editor_ui(ui)); ScrollArea::vertical() .id_salt("rendered") .show(&mut columns[1], |ui| { // TODO(emilk): we can save some more CPU by caching the rendered output. crate::easy_mark::easy_mark(ui, &self.code); }); }); } else { ScrollArea::vertical() .id_salt("source") .show(ui, |ui| self.editor_ui(ui)); } } fn editor_ui(&mut self, ui: &mut egui::Ui) { let Self { code, highlighter, .. } = self; let response = if self.highlight_editor { let mut layouter = |ui: &egui::Ui, easymark: &dyn TextBuffer, wrap_width: f32| { let mut layout_job = highlighter.highlight(ui.style(), easymark.as_str()); layout_job.wrap.max_width = wrap_width; ui.fonts_mut(|f| f.layout_job(layout_job)) }; ui.add( egui::TextEdit::multiline(code) .desired_width(f32::INFINITY) .font(egui::TextStyle::Monospace) // for cursor height .layouter(&mut layouter), ) } else { ui.add(egui::TextEdit::multiline(code).desired_width(f32::INFINITY)) }; if let Some(mut state) = TextEdit::load_state(ui.ctx(), response.id) && let Some(mut ccursor_range) = state.cursor.char_range() { let any_change = shortcuts(ui, code, &mut ccursor_range); if any_change { state.cursor.set_char_range(Some(ccursor_range)); state.store(ui.ctx(), response.id); } } } } pub const SHORTCUT_BOLD: KeyboardShortcut = KeyboardShortcut::new(Modifiers::COMMAND, Key::B); pub const SHORTCUT_CODE: KeyboardShortcut = KeyboardShortcut::new(Modifiers::COMMAND, Key::N); pub const SHORTCUT_ITALICS: KeyboardShortcut = KeyboardShortcut::new(Modifiers::COMMAND, Key::I); pub const SHORTCUT_SUBSCRIPT: KeyboardShortcut = KeyboardShortcut::new(Modifiers::COMMAND, Key::L); pub const SHORTCUT_SUPERSCRIPT: KeyboardShortcut = KeyboardShortcut::new(Modifiers::COMMAND, Key::Y); pub const SHORTCUT_STRIKETHROUGH: KeyboardShortcut = KeyboardShortcut::new(Modifiers::CTRL.plus(Modifiers::SHIFT), Key::Q); pub const SHORTCUT_UNDERLINE: KeyboardShortcut = KeyboardShortcut::new(Modifiers::CTRL.plus(Modifiers::SHIFT), Key::W); pub const SHORTCUT_INDENT: KeyboardShortcut = KeyboardShortcut::new(Modifiers::CTRL.plus(Modifiers::SHIFT), Key::E); fn nested_hotkeys_ui(ui: &mut egui::Ui) { egui::Grid::new("shortcuts").striped(true).show(ui, |ui| { let mut label = |shortcut, what| { ui.label(what); ui.weak(ui.ctx().format_shortcut(&shortcut)); ui.end_row(); }; label(SHORTCUT_BOLD, "*bold*"); label(SHORTCUT_CODE, "`code`"); label(SHORTCUT_ITALICS, "/italics/"); label(SHORTCUT_SUBSCRIPT, "$subscript$"); label(SHORTCUT_SUPERSCRIPT, "^superscript^"); label(SHORTCUT_STRIKETHROUGH, "~strikethrough~"); label(SHORTCUT_UNDERLINE, "_underline_"); label(SHORTCUT_INDENT, "two spaces"); // Placeholder for tab indent }); } fn shortcuts(ui: &Ui, code: &mut dyn TextBuffer, ccursor_range: &mut CCursorRange) -> bool { let mut any_change = false; if ui.input_mut(|i| i.consume_shortcut(&SHORTCUT_INDENT)) { // This is a placeholder till we can indent the active line any_change = true; let [primary, _secondary] = ccursor_range.sorted_cursors(); let advance = code.insert_text(" ", primary.index); ccursor_range.primary.index += advance; ccursor_range.secondary.index += advance; } for (shortcut, surrounding) in [ (SHORTCUT_BOLD, "*"), (SHORTCUT_CODE, "`"), (SHORTCUT_ITALICS, "/"), (SHORTCUT_SUBSCRIPT, "$"), (SHORTCUT_SUPERSCRIPT, "^"), (SHORTCUT_STRIKETHROUGH, "~"), (SHORTCUT_UNDERLINE, "_"), ] { if ui.input_mut(|i| i.consume_shortcut(&shortcut)) { any_change = true; toggle_surrounding(code, ccursor_range, surrounding); } } any_change } /// E.g. toggle *strong* with `toggle_surrounding(&mut text, &mut cursor, "*")` fn toggle_surrounding( code: &mut dyn TextBuffer, ccursor_range: &mut CCursorRange, surrounding: &str, ) { let [primary, secondary] = ccursor_range.sorted_cursors(); let surrounding_ccount = surrounding.chars().count(); let prefix_crange = primary.index.saturating_sub(surrounding_ccount)..primary.index; let suffix_crange = secondary.index..secondary.index.saturating_add(surrounding_ccount); let already_surrounded = code.char_range(prefix_crange.clone()) == surrounding && code.char_range(suffix_crange.clone()) == surrounding; if already_surrounded { code.delete_char_range(suffix_crange); code.delete_char_range(prefix_crange); ccursor_range.primary.index -= surrounding_ccount; ccursor_range.secondary.index -= surrounding_ccount; } else { code.insert_text(surrounding, secondary.index); let advance = code.insert_text(surrounding, primary.index); ccursor_range.primary.index += advance; ccursor_range.secondary.index += advance; } } // ---------------------------------------------------------------------------- const DEFAULT_CODE: &str = r#" # EasyMark EasyMark is a markup language, designed for extreme simplicity. ``` WARNING: EasyMark is still an evolving specification, and is also missing some features. ``` ---------------- # At a glance - inline text: - normal, `code`, *strong*, ~strikethrough~, _underline_, /italics/, ^raised^, $small$ - `\` escapes the next character - [hyperlink](https://github.com/emilk/egui) - Embedded URL: <https://github.com/emilk/egui> - `# ` header - `---` separator (horizontal line) - `> ` quote - `- ` bullet list - `1. ` numbered list - \`\`\` code fence - a^2^ + b^2^ = c^2^ - $Remember to read the small print$ # Design > /"Why do what everyone else is doing, when everyone else is already doing it?" > \- Emil Goals: 1. easy to parse 2. easy to learn 3. similar to markdown [The reference parser](https://github.com/emilk/egui/blob/main/crates/egui_demo_lib/src/easy_mark/easy_mark_parser.rs) is \~250 lines of code, using only the Rust standard library. The parser uses no look-ahead or recursion. There is never more than one way to accomplish the same thing, and each special character is only used for one thing. For instance `*` is used for *strong* and `-` is used for bullet lists. There is no alternative way to specify the *strong* style or getting a bullet list. Similarity to markdown is kept when possible, but with much less ambiguity and some improvements (like _underlining_). # Details All style changes are single characters, so it is `*strong*`, NOT `**strong**`. Style is reset by a matching character, or at the end of the line. Style change characters and escapes (`\`) work everywhere except for in inline code, code blocks and in URLs. You can mix styles. For instance: /italics _underline_/ and *strong `code`*. You can use styles on URLs: ~my webpage is at <http://www.example.com>~. Newlines are preserved. If you want to continue text on the same line, just do so. Alternatively, escape the newline by ending the line with a backslash (`\`). \ Escaping the newline effectively ignores it. The style characters are chosen to be similar to what they are representing: `_` = _underline_ `~` = ~strikethrough~ (`-` is used for bullet points) `/` = /italics/ `*` = *strong* `$` = $small$ `^` = ^raised^ # To do - Sub-headers (`## h2`, `### h3` etc) - Hotkey Editor - International keyboard algorithm for non-letter keys - ALT+SHIFT+Num1 is not a functioning hotkey - Tab Indent Increment/Decrement CTRL+], CTRL+[ - Images - we want to be able to optionally specify size (width and\/or height) - centering of images is very desirable - captioning (image with a text underneath it) - `![caption=My image][width=200][center](url)` ? - Nicer URL:s - `<url>` and `[url](url)` do the same thing yet look completely different. - let's keep similarity with images - Tables - Inspiration: <https://mycorrhiza.wiki/help/en/mycomarkup> "#;
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/src/easy_mark/easy_mark_highlighter.rs
crates/egui_demo_lib/src/easy_mark/easy_mark_highlighter.rs
use crate::easy_mark::easy_mark_parser; /// Highlight easymark, memoizing previous output to save CPU. /// /// In practice, the highlighter is fast enough not to need any caching. #[derive(Default)] pub struct MemoizedEasymarkHighlighter { style: egui::Style, code: String, output: egui::text::LayoutJob, } impl MemoizedEasymarkHighlighter { pub fn highlight(&mut self, egui_style: &egui::Style, code: &str) -> egui::text::LayoutJob { if (&self.style, self.code.as_str()) != (egui_style, code) { self.style = egui_style.clone(); code.clone_into(&mut self.code); self.output = highlight_easymark(egui_style, code); } self.output.clone() } } pub fn highlight_easymark(egui_style: &egui::Style, mut text: &str) -> egui::text::LayoutJob { let mut job = egui::text::LayoutJob::default(); let mut style = easy_mark_parser::Style::default(); let mut start_of_line = true; while !text.is_empty() { if start_of_line && text.starts_with("```") { let end = text.find("\n```").map_or_else(|| text.len(), |i| i + 4); job.append( &text[..end], 0.0, format_from_style( egui_style, &easy_mark_parser::Style { code: true, ..Default::default() }, ), ); text = &text[end..]; style = Default::default(); continue; } if text.starts_with('`') { style.code = true; let end = text[1..] .find(&['`', '\n'][..]) .map_or_else(|| text.len(), |i| i + 2); job.append(&text[..end], 0.0, format_from_style(egui_style, &style)); text = &text[end..]; style.code = false; continue; } let mut skip; if text.starts_with('\\') && text.len() >= 2 { skip = 2; } else if start_of_line && text.starts_with(' ') { // we don't preview indentation, because it is confusing skip = 1; } else if start_of_line && text.starts_with("# ") { style.heading = true; skip = 2; } else if start_of_line && text.starts_with("> ") { style.quoted = true; skip = 2; // we don't preview indentation, because it is confusing } else if start_of_line && text.starts_with("- ") { skip = 2; // we don't preview indentation, because it is confusing } else if text.starts_with('*') { skip = 1; if style.strong { // Include the character that is ending this style: job.append(&text[..skip], 0.0, format_from_style(egui_style, &style)); text = &text[skip..]; skip = 0; } style.strong ^= true; } else if text.starts_with('$') { skip = 1; if style.small { // Include the character that is ending this style: job.append(&text[..skip], 0.0, format_from_style(egui_style, &style)); text = &text[skip..]; skip = 0; } style.small ^= true; } else if text.starts_with('^') { skip = 1; if style.raised { // Include the character that is ending this style: job.append(&text[..skip], 0.0, format_from_style(egui_style, &style)); text = &text[skip..]; skip = 0; } style.raised ^= true; } else { skip = 0; } // Note: we don't preview underline, strikethrough and italics because it confuses things. // Swallow everything up to the next special character: let line_end = text[skip..] .find('\n') .map_or_else(|| text.len(), |i| skip + i + 1); let end = text[skip..] .find(&['*', '`', '~', '_', '/', '$', '^', '\\', '<', '['][..]) .map_or_else(|| text.len(), |i| (skip + i).max(1)); if line_end <= end { job.append( &text[..line_end], 0.0, format_from_style(egui_style, &style), ); text = &text[line_end..]; start_of_line = true; style = Default::default(); } else { job.append(&text[..end], 0.0, format_from_style(egui_style, &style)); text = &text[end..]; start_of_line = false; } } job } fn format_from_style( egui_style: &egui::Style, emark_style: &easy_mark_parser::Style, ) -> egui::text::TextFormat { use egui::{Align, Color32, Stroke, TextStyle}; let color = if emark_style.strong || emark_style.heading { egui_style.visuals.strong_text_color() } else if emark_style.quoted { egui_style.visuals.weak_text_color() } else { egui_style.visuals.text_color() }; let text_style = if emark_style.heading { TextStyle::Heading } else if emark_style.code { TextStyle::Monospace } else if emark_style.small | emark_style.raised { TextStyle::Small } else { TextStyle::Body }; let background = if emark_style.code { egui_style.visuals.code_bg_color } else { Color32::TRANSPARENT }; let underline = if emark_style.underline { Stroke::new(1.0, color) } else { Stroke::NONE }; let strikethrough = if emark_style.strikethrough { Stroke::new(1.0, color) } else { Stroke::NONE }; let valign = if emark_style.raised { Align::TOP } else { Align::BOTTOM }; egui::text::TextFormat { font_id: text_style.resolve(egui_style), color, background, italics: emark_style.italics, underline, strikethrough, valign, ..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_demo_lib/src/easy_mark/easy_mark_parser.rs
crates/egui_demo_lib/src/easy_mark/easy_mark_parser.rs
//! A parser for `EasyMark`: a very simple markup language. //! //! WARNING: `EasyMark` is subject to change. // //! # `EasyMark` design goals: //! 1. easy to parse //! 2. easy to learn //! 3. similar to markdown #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum Item<'a> { /// `\n` // TODO(emilk): add Style here so empty heading still uses up the right amount of space. Newline, /// Text Text(Style, &'a str), /// title, url Hyperlink(Style, &'a str, &'a str), /// leading space before e.g. a [`Self::BulletPoint`]. Indentation(usize), /// > QuoteIndent, /// - a point well made. BulletPoint, /// 1. numbered list. The string is the number(s). NumberedPoint(&'a str), /// --- Separator, /// language, code CodeBlock(&'a str, &'a str), } #[derive(Copy, Clone, Debug, Default, Eq, PartialEq)] pub struct Style { /// # heading (large text) pub heading: bool, /// > quoted (slightly dimmer color or other font style) pub quoted: bool, /// `code` (monospace, some other color) pub code: bool, /// self.strong* (emphasized, e.g. bold) pub strong: bool, /// _underline_ pub underline: bool, /// ~strikethrough~ pub strikethrough: bool, /// /italics/ pub italics: bool, /// $small$ pub small: bool, /// ^raised^ pub raised: bool, } /// Parser for the `EasyMark` markup language. /// /// See the module-level documentation for details. /// /// # Example: /// ``` /// # use egui_demo_lib::easy_mark::parser::Parser; /// for item in Parser::new("Hello *world*!") { /// } /// /// ``` pub struct Parser<'a> { /// The remainder of the input text s: &'a str, /// Are we at the start of a line? start_of_line: bool, /// Current self.style. Reset after a newline. style: Style, } impl<'a> Parser<'a> { pub fn new(s: &'a str) -> Self { Self { s, start_of_line: true, style: Style::default(), } } /// `1. `, `42. ` etc. fn numbered_list(&mut self) -> Option<Item<'a>> { let n_digits = self.s.chars().take_while(|c| c.is_ascii_digit()).count(); if n_digits > 0 && self.s.chars().skip(n_digits).take(2).eq(". ".chars()) { let number = &self.s[..n_digits]; self.s = &self.s[(n_digits + 2)..]; self.start_of_line = false; return Some(Item::NumberedPoint(number)); } None } // ```{language}\n{code}``` fn code_block(&mut self) -> Option<Item<'a>> { if let Some(language_start) = self.s.strip_prefix("```") && let Some(newline) = language_start.find('\n') { let language = &language_start[..newline]; let code_start = &language_start[newline + 1..]; if let Some(end) = code_start.find("\n```") { let code = &code_start[..end].trim(); self.s = &code_start[end + 4..]; self.start_of_line = false; return Some(Item::CodeBlock(language, code)); } else { self.s = ""; return Some(Item::CodeBlock(language, code_start)); } } None } // `code` fn inline_code(&mut self) -> Option<Item<'a>> { if let Some(rest) = self.s.strip_prefix('`') { self.s = rest; self.start_of_line = false; self.style.code = true; let rest_of_line = &self.s[..self.s.find('\n').unwrap_or(self.s.len())]; if let Some(end) = rest_of_line.find('`') { let item = Item::Text(self.style, &self.s[..end]); self.s = &self.s[end + 1..]; self.style.code = false; return Some(item); } else { let end = rest_of_line.len(); let item = Item::Text(self.style, rest_of_line); self.s = &self.s[end..]; self.style.code = false; return Some(item); } } None } /// `<url>` or `[link](url)` fn url(&mut self) -> Option<Item<'a>> { if self.s.starts_with('<') { let this_line = &self.s[..self.s.find('\n').unwrap_or(self.s.len())]; if let Some(url_end) = this_line.find('>') { let url = &self.s[1..url_end]; self.s = &self.s[url_end + 1..]; self.start_of_line = false; return Some(Item::Hyperlink(self.style, url, url)); } } // [text](url) if self.s.starts_with('[') { let this_line = &self.s[..self.s.find('\n').unwrap_or(self.s.len())]; if let Some(bracket_end) = this_line.find(']') { let text = &this_line[1..bracket_end]; if this_line[bracket_end + 1..].starts_with('(') && let Some(parens_end) = this_line[bracket_end + 2..].find(')') { let parens_end = bracket_end + 2 + parens_end; let url = &self.s[bracket_end + 2..parens_end]; self.s = &self.s[parens_end + 1..]; self.start_of_line = false; return Some(Item::Hyperlink(self.style, text, url)); } } } None } } impl<'a> Iterator for Parser<'a> { type Item = Item<'a>; fn next(&mut self) -> Option<Self::Item> { loop { if self.s.is_empty() { return None; } // \n if self.s.starts_with('\n') { self.s = &self.s[1..]; self.start_of_line = true; self.style = Style::default(); return Some(Item::Newline); } // Ignore line break (continue on the same line) if self.s.starts_with("\\\n") && self.s.len() >= 2 { self.s = &self.s[2..]; self.start_of_line = false; continue; } // \ escape (to show e.g. a backtick) if self.s.starts_with('\\') && self.s.len() >= 2 { let text = &self.s[1..2]; self.s = &self.s[2..]; self.start_of_line = false; return Some(Item::Text(self.style, text)); } if self.start_of_line { // leading space (indentation) if self.s.starts_with(' ') { let length = self.s.find(|c| c != ' ').unwrap_or(self.s.len()); self.s = &self.s[length..]; self.start_of_line = true; // indentation doesn't count return Some(Item::Indentation(length)); } // # Heading if let Some(after) = self.s.strip_prefix("# ") { self.s = after; self.start_of_line = false; self.style.heading = true; continue; } // > quote if let Some(after) = self.s.strip_prefix("> ") { self.s = after; self.start_of_line = true; // quote indentation doesn't count self.style.quoted = true; return Some(Item::QuoteIndent); } // - bullet point if self.s.starts_with("- ") { self.s = &self.s[2..]; self.start_of_line = false; return Some(Item::BulletPoint); } // `1. `, `42. ` etc. if let Some(item) = self.numbered_list() { return Some(item); } // --- separator if let Some(after) = self.s.strip_prefix("---") { self.s = after.trim_start_matches('-'); // remove extra dashes self.s = self.s.strip_prefix('\n').unwrap_or(self.s); // remove trailing newline self.start_of_line = false; return Some(Item::Separator); } // ```{language}\n{code}``` if let Some(item) = self.code_block() { return Some(item); } } // `code` if let Some(item) = self.inline_code() { return Some(item); } if let Some(rest) = self.s.strip_prefix('*') { self.s = rest; self.start_of_line = false; self.style.strong = !self.style.strong; continue; } if let Some(rest) = self.s.strip_prefix('_') { self.s = rest; self.start_of_line = false; self.style.underline = !self.style.underline; continue; } if let Some(rest) = self.s.strip_prefix('~') { self.s = rest; self.start_of_line = false; self.style.strikethrough = !self.style.strikethrough; continue; } if let Some(rest) = self.s.strip_prefix('/') { self.s = rest; self.start_of_line = false; self.style.italics = !self.style.italics; continue; } if let Some(rest) = self.s.strip_prefix('$') { self.s = rest; self.start_of_line = false; self.style.small = !self.style.small; continue; } if let Some(rest) = self.s.strip_prefix('^') { self.s = rest; self.start_of_line = false; self.style.raised = !self.style.raised; continue; } // `<url>` or `[link](url)` if let Some(item) = self.url() { return Some(item); } // Swallow everything up to the next special character: let end = self .s .find(&['*', '`', '~', '_', '/', '$', '^', '\\', '<', '[', '\n'][..]) .map_or_else(|| self.s.len(), |special| special.max(1)); let item = Item::Text(self.style, &self.s[..end]); self.s = &self.s[end..]; self.start_of_line = false; return Some(item); } } } #[test] fn test_easy_mark_parser() { let items: Vec<_> = Parser::new("~strikethrough `code`~").collect(); assert_eq!( items, vec![ Item::Text( Style { strikethrough: true, ..Default::default() }, "strikethrough " ), Item::Text( Style { code: true, strikethrough: true, ..Default::default() }, "code" ), ] ); }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/src/easy_mark/mod.rs
crates/egui_demo_lib/src/easy_mark/mod.rs
//! Experimental markup language mod easy_mark_editor; mod easy_mark_highlighter; pub mod easy_mark_parser; mod easy_mark_viewer; pub use easy_mark_editor::EasyMarkEditor; pub use easy_mark_highlighter::MemoizedEasymarkHighlighter; pub use easy_mark_parser as parser; pub use easy_mark_viewer::easy_mark;
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/src/demo/multi_touch.rs
crates/egui_demo_lib/src/demo/multi_touch.rs
use egui::{ Color32, Event, Frame, Pos2, Rect, Sense, Stroke, Vec2, emath::{RectTransform, Rot2}, vec2, }; pub struct MultiTouch { rotation: f32, translation: Vec2, zoom: f32, last_touch_time: f64, } impl Default for MultiTouch { fn default() -> Self { Self { rotation: 0., translation: Vec2::ZERO, zoom: 1., last_touch_time: 0.0, } } } impl crate::Demo for MultiTouch { fn name(&self) -> &'static str { "👌 Multi Touch" } fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) { egui::Window::new(self.name()) .open(open) .default_size(vec2(544.0, 512.0)) .resizable(true) .constrain_to(ui.available_rect_before_wrap()) .show(ui, |ui| { use crate::View as _; self.ui(ui); }); } } impl crate::View for MultiTouch { fn ui(&mut self, ui: &mut egui::Ui) { ui.vertical_centered(|ui| { ui.add(crate::egui_github_link_file!()); }); ui.strong( "This demo only works on devices with multitouch support (e.g. mobiles, tablets, and trackpads).", ); ui.separator(); ui.label("Try touch gestures Pinch/Stretch, Rotation, and Pressure with 2+ fingers."); let relative_pointer_gesture = ui.input(|i| { i.events.iter().any(|event| { matches!( event, Event::MouseWheel { .. } | Event::Zoom { .. } | Event::Rotate { .. } ) }) }); let num_touches = ui.input(|i| i.multi_touch().map_or(0, |mt| mt.num_touches)); let num_touches_str = format!("{num_touches}-finger touch"); ui.label(format!( "Input source: {}", if ui.input(|i| i.multi_touch().is_some()) { num_touches_str.as_str() } else if relative_pointer_gesture { "cursor" } else { "none" } )); let color = if ui.visuals().dark_mode { Color32::WHITE } else { Color32::BLACK }; Frame::canvas(ui.style()).show(ui, |ui| { // Note that we use `Sense::drag()` although we do not use any pointer events. With // the current implementation, the fact that a touch event of two or more fingers is // recognized, does not mean that the pointer events are suppressed, which are always // generated for the first finger. Therefore, if we do not explicitly consume pointer // events, the window will move around, not only when dragged with a single finger, but // also when a two-finger touch is active. I guess this problem can only be cleanly // solved when the synthetic pointer events are created by egui, and not by the // backend. // set up the drawing canvas with normalized coordinates: let (response, painter) = ui.allocate_painter(ui.available_size_before_wrap(), Sense::drag()); // normalize painter coordinates to ±1 units in each direction with [0,0] in the center: let painter_proportions = response.rect.square_proportions(); let to_screen = RectTransform::from_to( Rect::from_min_size(Pos2::ZERO - painter_proportions, 2. * painter_proportions), response.rect, ); // check for touch input (or the lack thereof) and update zoom and scale factors, plus // color and width: let mut stroke_width = 1.; if ui.input(|i| i.multi_touch().is_some()) || relative_pointer_gesture { ui.input(|input| { // This adjusts the current zoom factor, rotation angle, and translation according // to the dynamic change (for the current frame) of the touch gesture: self.zoom *= input.zoom_delta(); self.rotation += input.rotation_delta(); self.translation += to_screen.inverse().scale() * input.translation_delta(); // touch pressure will make the arrow thicker (not all touch devices support this): stroke_width += 10. * input.multi_touch().map_or(0.0, |touch| touch.force); self.last_touch_time = input.time; }); } else { self.slowly_reset(ui); } let zoom_and_rotate = self.zoom * Rot2::from_angle(self.rotation); let arrow_start_offset = self.translation + zoom_and_rotate * vec2(-0.5, 0.5); // Paints an arrow pointing from bottom-left (-0.5, 0.5) to top-right (0.5, -0.5), but // scaled, rotated, and translated according to the current touch gesture: let arrow_start = Pos2::ZERO + arrow_start_offset; let arrow_direction = zoom_and_rotate * vec2(1., -1.); painter.arrow( to_screen * arrow_start, to_screen.scale() * arrow_direction, Stroke::new(stroke_width, color), ); }); } } impl MultiTouch { fn slowly_reset(&mut self, ui: &egui::Ui) { // This has nothing to do with the touch gesture. It just smoothly brings the // painted arrow back into its original position, for a nice visual effect: let time_since_last_touch = (ui.input(|i| i.time) - self.last_touch_time) as f32; let delay = 0.5; if time_since_last_touch < delay { ui.request_repaint(); } else { // seconds after which half the amount of zoom/rotation will be reverted: let half_life = egui::remap_clamp(time_since_last_touch, delay..=1.0, 1.0..=0.0).powf(4.0); if half_life <= 1e-3 { self.zoom = 1.0; self.rotation = 0.0; self.translation = Vec2::ZERO; } else { let dt = ui.input(|i| i.unstable_dt); let half_life_factor = (-(2_f32.ln()) / half_life * dt).exp(); self.zoom = 1. + ((self.zoom - 1.) * half_life_factor); self.rotation *= half_life_factor; self.translation *= half_life_factor; ui.request_repaint(); } } } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/src/demo/painting.rs
crates/egui_demo_lib/src/demo/painting.rs
use egui::{Color32, Frame, Pos2, Rect, Sense, Stroke, Ui, Window, emath, vec2}; #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] pub struct Painting { /// in 0-1 normalized coordinates lines: Vec<Vec<Pos2>>, stroke: Stroke, } impl Default for Painting { fn default() -> Self { Self { lines: Default::default(), stroke: Stroke::new(1.0, Color32::from_rgb(25, 200, 100)), } } } impl Painting { pub fn ui_control(&mut self, ui: &mut egui::Ui) -> egui::Response { ui.horizontal(|ui| { ui.label("Stroke:"); ui.add(&mut self.stroke); ui.separator(); if ui.button("Clear Painting").clicked() { self.lines.clear(); } }) .response } pub fn ui_content(&mut self, ui: &mut Ui) -> egui::Response { let (mut response, painter) = ui.allocate_painter(ui.available_size_before_wrap(), Sense::drag()); let to_screen = emath::RectTransform::from_to( Rect::from_min_size(Pos2::ZERO, response.rect.square_proportions()), response.rect, ); let from_screen = to_screen.inverse(); if self.lines.is_empty() { self.lines.push(vec![]); } let current_line = self.lines.last_mut().unwrap(); if let Some(pointer_pos) = response.interact_pointer_pos() { let canvas_pos = from_screen * pointer_pos; if current_line.last() != Some(&canvas_pos) { current_line.push(canvas_pos); response.mark_changed(); } } else if !current_line.is_empty() { self.lines.push(vec![]); response.mark_changed(); } let shapes = self .lines .iter() .filter(|line| line.len() >= 2) .map(|line| { let points: Vec<Pos2> = line.iter().map(|p| to_screen * *p).collect(); egui::Shape::line(points, self.stroke) }); painter.extend(shapes); response } } impl crate::Demo for Painting { fn name(&self) -> &'static str { "🖊 Painting" } fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) { use crate::View as _; Window::new(self.name()) .open(open) .default_size(vec2(512.0, 512.0)) .vscroll(false) .constrain_to(ui.available_rect_before_wrap()) .show(ui, |ui| self.ui(ui)); } } impl crate::View for Painting { fn ui(&mut self, ui: &mut Ui) { ui.vertical_centered(|ui| { ui.add(crate::egui_github_link_file!()); }); self.ui_control(ui); ui.label("Paint with your mouse/touch!"); Frame::canvas(ui.style()).show(ui, |ui| { self.ui_content(ui); }); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/src/demo/highlighting.rs
crates/egui_demo_lib/src/demo/highlighting.rs
#[derive(Default)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] pub struct Highlighting {} impl crate::Demo for Highlighting { fn name(&self) -> &'static str { "✨ Highlighting" } fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) { egui::Window::new(self.name()) .default_width(320.0) .open(open) .constrain_to(ui.available_rect_before_wrap()) .show(ui, |ui| { use crate::View as _; self.ui(ui); }); } } impl crate::View for Highlighting { fn ui(&mut self, ui: &mut egui::Ui) { ui.vertical_centered(|ui| { ui.add(crate::egui_github_link_file!()); }); ui.label("This demo demonstrates highlighting a widget."); ui.add_space(4.0); let label_response = ui.label("Hover me to highlight the button!"); ui.add_space(4.0); let mut button_response = ui.button("Hover the button to highlight the label!"); if label_response.hovered() { button_response = button_response.highlight(); } if button_response.hovered() { label_response.highlight(); } } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/src/demo/toggle_switch.rs
crates/egui_demo_lib/src/demo/toggle_switch.rs
//! Source code example of how to create your own widget. //! This is meant to be read as a tutorial, hence the plethora of comments. /// iOS-style toggle switch: /// /// ``` text /// _____________ /// / /.....\ /// | |.......| /// \_______\_____/ /// ``` /// /// ## Example: /// ``` ignore /// toggle_ui(ui, &mut my_bool); /// ``` pub fn toggle_ui(ui: &mut egui::Ui, on: &mut bool) -> egui::Response { // Widget code can be broken up in four steps: // 1. Decide a size for the widget // 2. Allocate space for it // 3. Handle interactions with the widget (if any) // 4. Paint the widget // 1. Deciding widget size: // You can query the `ui` how much space is available, // but in this example we have a fixed size widget based on the height of a standard button: let desired_size = ui.spacing().interact_size.y * egui::vec2(2.0, 1.0); // 2. Allocating space: // This is where we get a region of the screen assigned. // We also tell the Ui to sense clicks in the allocated region. let (rect, mut response) = ui.allocate_exact_size(desired_size, egui::Sense::click()); // 3. Interact: Time to check for clicks! if response.clicked() { *on = !*on; response.mark_changed(); // report back that the value changed } // Attach some meta-data to the response which can be used by screen readers: response.widget_info(|| { egui::WidgetInfo::selected(egui::WidgetType::Checkbox, ui.is_enabled(), *on, "") }); // 4. Paint! // Make sure we need to paint: if ui.is_rect_visible(rect) { // Let's ask for a simple animation from egui. // egui keeps track of changes in the boolean associated with the id and // returns an animated value in the 0-1 range for how much "on" we are. let how_on = ui.ctx().animate_bool_responsive(response.id, *on); // We will follow the current style by asking // "how should something that is being interacted with be painted?". // This will, for instance, give us different colors when the widget is hovered or clicked. let visuals = ui.style().interact_selectable(&response, *on); // All coordinates are in absolute screen coordinates so we use `rect` to place the elements. let rect = rect.expand(visuals.expansion); let radius = 0.5 * rect.height(); ui.painter().rect( rect, radius, visuals.bg_fill, visuals.bg_stroke, egui::StrokeKind::Inside, ); // Paint the circle, animating it from left to right with `how_on`: let circle_x = egui::lerp((rect.left() + radius)..=(rect.right() - radius), how_on); let center = egui::pos2(circle_x, rect.center().y); ui.painter() .circle(center, 0.75 * radius, visuals.bg_fill, visuals.fg_stroke); } // All done! Return the interaction response so the user can check what happened // (hovered, clicked, ...) and maybe show a tooltip: response } /// Here is the same code again, but a bit more compact: #[expect(dead_code)] fn toggle_ui_compact(ui: &mut egui::Ui, on: &mut bool) -> egui::Response { let desired_size = ui.spacing().interact_size.y * egui::vec2(2.0, 1.0); let (rect, mut response) = ui.allocate_exact_size(desired_size, egui::Sense::click()); if response.clicked() { *on = !*on; response.mark_changed(); } response.widget_info(|| { egui::WidgetInfo::selected(egui::WidgetType::Checkbox, ui.is_enabled(), *on, "") }); if ui.is_rect_visible(rect) { let how_on = ui.ctx().animate_bool_responsive(response.id, *on); let visuals = ui.style().interact_selectable(&response, *on); let rect = rect.expand(visuals.expansion); let radius = 0.5 * rect.height(); ui.painter().rect( rect, radius, visuals.bg_fill, visuals.bg_stroke, egui::StrokeKind::Inside, ); let circle_x = egui::lerp((rect.left() + radius)..=(rect.right() - radius), how_on); let center = egui::pos2(circle_x, rect.center().y); ui.painter() .circle(center, 0.75 * radius, visuals.bg_fill, visuals.fg_stroke); } response } // A wrapper that allows the more idiomatic usage pattern: `ui.add(toggle(&mut my_bool))` /// iOS-style toggle switch. /// /// ## Example: /// ``` ignore /// ui.add(toggle(&mut my_bool)); /// ``` pub fn toggle(on: &mut bool) -> impl egui::Widget + '_ { move |ui: &mut egui::Ui| toggle_ui(ui, on) } pub fn url_to_file_source_code() -> String { format!("https://github.com/emilk/egui/blob/main/{}", file!()) }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/src/demo/frame_demo.rs
crates/egui_demo_lib/src/demo/frame_demo.rs
/// Shows off a table with dynamic layout #[derive(PartialEq)] pub struct FrameDemo { frame: egui::Frame, } impl Default for FrameDemo { fn default() -> Self { Self { frame: egui::Frame::new() .inner_margin(12) .outer_margin(24) .corner_radius(14) .shadow(egui::Shadow { offset: [8, 12], blur: 16, spread: 0, color: egui::Color32::from_black_alpha(180), }) .fill(egui::Color32::from_rgba_unmultiplied(97, 0, 255, 128)) .stroke(egui::Stroke::new(1.0, egui::Color32::GRAY)), } } } impl crate::Demo for FrameDemo { fn name(&self) -> &'static str { "▣ Frame" } fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) { egui::Window::new(self.name()) .open(open) .resizable(false) .constrain_to(ui.available_rect_before_wrap()) .show(ui, |ui| { use crate::View as _; self.ui(ui); }); } } impl crate::View for FrameDemo { fn ui(&mut self, ui: &mut egui::Ui) { ui.horizontal(|ui| { ui.vertical(|ui| { ui.add(&mut self.frame); ui.add_space(8.0); ui.set_max_width(ui.min_size().x); ui.vertical_centered(|ui| egui::reset_button(ui, self, "Reset")); }); ui.separator(); ui.vertical(|ui| { // We want to paint a background around the outer margin of the demonstration frame, so we use another frame around it: egui::Frame::default() .stroke(ui.visuals().widgets.noninteractive.bg_stroke) .corner_radius(ui.visuals().widgets.noninteractive.corner_radius) .show(ui, |ui| { self.frame.show(ui, |ui| { ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend); ui.label(egui::RichText::new("Content").color(egui::Color32::WHITE)); }); }); }); }); ui.set_max_width(ui.min_size().x); ui.separator(); ui.vertical_centered(|ui| ui.add(crate::egui_github_link_file!())); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/src/demo/password.rs
crates/egui_demo_lib/src/demo/password.rs
//! Source code example about creating a widget which uses `egui::Memory` to store UI state. //! //! This is meant to be read as a tutorial, hence the plethora of comments. /// Password entry field with ability to toggle character hiding. /// /// ## Example: /// ``` ignore /// password_ui(ui, &mut my_password); /// ``` pub fn password_ui(ui: &mut egui::Ui, password: &mut String) -> egui::Response { // This widget has its own state — show or hide password characters (`show_plaintext`). // In this case we use a simple `bool`, but you can also declare your own type. // It must implement at least `Clone` and be `'static`. // If you use the `persistence` feature, it also must implement `serde::{Deserialize, Serialize}`. // Generate an id for the state let state_id = ui.id().with("show_plaintext"); // Get state for this widget. // You should get state by value, not by reference to avoid borrowing of [`Memory`]. let mut show_plaintext = ui.data_mut(|d| d.get_temp::<bool>(state_id).unwrap_or(false)); // Process ui, change a local copy of the state // We want TextEdit to fill entire space, and have button after that, so in that case we can // change direction to right_to_left. let result = ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { // Toggle the `show_plaintext` bool with a button: let response = ui .selectable_label(show_plaintext, "👁") .on_hover_text("Show/hide password"); if response.clicked() { show_plaintext = !show_plaintext; } // Show the password field: ui.add_sized( ui.available_size(), egui::TextEdit::singleline(password).password(!show_plaintext), ); }); // Store the (possibly changed) state: ui.data_mut(|d| d.insert_temp(state_id, show_plaintext)); // All done! Return the interaction response so the user can check what happened // (hovered, clicked, …) and maybe show a tooltip: result.response } // A wrapper that allows the more idiomatic usage pattern: `ui.add(…)` /// Password entry field with ability to toggle character hiding. /// /// ## Example: /// ``` ignore /// ui.add(password(&mut my_password)); /// ``` pub fn password(password: &mut String) -> impl egui::Widget + '_ { move |ui: &mut egui::Ui| password_ui(ui, password) } pub fn url_to_file_source_code() -> String { format!("https://github.com/emilk/egui/blob/main/{}", file!()) }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/src/demo/code_editor.rs
crates/egui_demo_lib/src/demo/code_editor.rs
// ---------------------------------------------------------------------------- #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] pub struct CodeEditor { language: String, code: String, } impl Default for CodeEditor { fn default() -> Self { Self { language: "rs".into(), code: "// A very simple example\n\ fn main() {\n\ \tprintln!(\"Hello world!\");\n\ }\n\ " .into(), } } } impl crate::Demo for CodeEditor { fn name(&self) -> &'static str { "🖮 Code Editor" } fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) { use crate::View as _; egui::Window::new(self.name()) .open(open) .default_height(500.0) .constrain_to(ui.available_rect_before_wrap()) .show(ui, |ui| self.ui(ui)); } } impl crate::View for CodeEditor { fn ui(&mut self, ui: &mut egui::Ui) { let Self { language, code } = self; ui.horizontal(|ui| { ui.set_height(0.0); ui.label("An example of syntax highlighting in a TextEdit."); ui.add(crate::egui_github_link_file!()); }); if cfg!(feature = "syntect") { ui.horizontal(|ui| { ui.label("Language:"); ui.text_edit_singleline(language); }); ui.horizontal_wrapped(|ui| { ui.spacing_mut().item_spacing.x = 0.0; ui.label("Syntax highlighting powered by "); ui.hyperlink_to("syntect", "https://github.com/trishume/syntect"); ui.label("."); }); } else { ui.horizontal_wrapped(|ui| { ui.spacing_mut().item_spacing.x = 0.0; ui.label("Compile the demo with the "); ui.code("syntax_highlighting"); ui.label(" feature to enable more accurate syntax highlighting using "); ui.hyperlink_to("syntect", "https://github.com/trishume/syntect"); ui.label("."); }); } let mut theme = egui_extras::syntax_highlighting::CodeTheme::from_memory(ui.ctx(), ui.style()); ui.collapsing("Theme", |ui| { ui.group(|ui| { theme.ui(ui); theme.clone().store_in_memory(ui.ctx()); }); }); let mut layouter = |ui: &egui::Ui, buf: &dyn egui::TextBuffer, wrap_width: f32| { let mut layout_job = egui_extras::syntax_highlighting::highlight( ui.ctx(), ui.style(), &theme, buf.as_str(), language, ); layout_job.wrap.max_width = wrap_width; ui.fonts_mut(|f| f.layout_job(layout_job)) }; egui::ScrollArea::vertical().show(ui, |ui| { ui.add( egui::TextEdit::multiline(code) .font(egui::TextStyle::Monospace) // for cursor height .code_editor() .desired_rows(10) .lock_focus(true) .desired_width(f32::INFINITY) .layouter(&mut layouter), ); }); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/src/demo/strip_demo.rs
crates/egui_demo_lib/src/demo/strip_demo.rs
use egui::{Color32, TextStyle}; use egui_extras::{Size, StripBuilder}; /// Shows off a table with dynamic layout #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[derive(Default)] pub struct StripDemo {} impl crate::Demo for StripDemo { fn name(&self) -> &'static str { "▣ Strip" } fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) { egui::Window::new(self.name()) .open(open) .resizable(true) .default_width(400.0) .constrain_to(ui.available_rect_before_wrap()) .show(ui, |ui| { use crate::View as _; self.ui(ui); }); } } impl crate::View for StripDemo { fn ui(&mut self, ui: &mut egui::Ui) { let dark_mode = ui.visuals().dark_mode; let faded_color = ui.visuals().window_fill(); let faded_color = |color: Color32| -> Color32 { use egui::Rgba; let t = if dark_mode { 0.95 } else { 0.8 }; egui::lerp(Rgba::from(color)..=Rgba::from(faded_color), t).into() }; let body_text_size = TextStyle::Body.resolve(ui.style()).size; StripBuilder::new(ui) .size(Size::exact(50.0)) .size(Size::remainder()) .size(Size::relative(0.5).at_least(60.0)) .size(Size::exact(body_text_size)) .vertical(|mut strip| { strip.cell(|ui| { ui.painter().rect_filled( ui.available_rect_before_wrap(), 0.0, faded_color(Color32::BLUE), ); ui.label("width: 100%\nheight: 50px"); }); strip.strip(|builder| { builder.sizes(Size::remainder(), 2).horizontal(|mut strip| { strip.cell(|ui| { ui.painter().rect_filled( ui.available_rect_before_wrap(), 0.0, faded_color(Color32::RED), ); ui.label("width: 50%\nheight: remaining"); }); strip.strip(|builder| { builder.sizes(Size::remainder(), 3).vertical(|mut strip| { strip.empty(); strip.cell(|ui| { ui.painter().rect_filled( ui.available_rect_before_wrap(), 0.0, faded_color(Color32::YELLOW), ); ui.label("width: 50%\nheight: 1/3 of the red region"); }); strip.empty(); }); }); }); }); strip.strip(|builder| { builder .size(Size::remainder()) .size(Size::exact(120.0)) .size(Size::remainder()) .size(Size::exact(70.0)) .horizontal(|mut strip| { strip.empty(); strip.strip(|builder| { builder .size(Size::remainder()) .size(Size::exact(60.0)) .size(Size::remainder()) .vertical(|mut strip| { strip.empty(); strip.cell(|ui| { ui.painter().rect_filled( ui.available_rect_before_wrap(), 0.0, faded_color(Color32::GOLD), ); ui.label("width: 120px\nheight: 60px"); }); }); }); strip.empty(); strip.cell(|ui| { ui.painter().rect_filled( ui.available_rect_before_wrap(), 0.0, faded_color(Color32::GREEN), ); ui.label("width: 70px\n\nheight: 50%, but at least 60px."); }); }); }); strip.cell(|ui| { ui.vertical_centered(|ui| { ui.add(crate::egui_github_link_file!()); }); }); }); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/src/demo/undo_redo.rs
crates/egui_demo_lib/src/demo/undo_redo.rs
use egui::{Button, util::undoer::Undoer}; #[derive(Debug, PartialEq, Eq, Clone)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] pub struct State { pub toggle_value: bool, pub text: String, } impl Default for State { fn default() -> Self { Self { toggle_value: Default::default(), text: "Text with undo/redo".to_owned(), } } } /// Showcase [`egui::util::undoer::Undoer`] #[derive(Debug, Default)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] pub struct UndoRedoDemo { pub state: State, pub undoer: Undoer<State>, } impl crate::Demo for UndoRedoDemo { fn name(&self) -> &'static str { "⟲ Undo Redo" } fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) { egui::Window::new(self.name()) .open(open) .resizable(false) .constrain_to(ui.available_rect_before_wrap()) .show(ui, |ui| { use crate::View as _; self.ui(ui); }); } } impl crate::View for UndoRedoDemo { fn ui(&mut self, ui: &mut egui::Ui) { ui.vertical_centered(|ui| { ui.add(crate::egui_github_link_file!()); }); ui.checkbox(&mut self.state.toggle_value, "Checkbox with undo/redo"); ui.text_edit_singleline(&mut self.state.text); ui.separator(); let can_undo = self.undoer.has_undo(&self.state); let can_redo = self.undoer.has_redo(&self.state); ui.horizontal(|ui| { let undo = ui.add_enabled(can_undo, Button::new("⟲ Undo")).clicked(); let redo = ui.add_enabled(can_redo, Button::new("⟳ Redo")).clicked(); if undo && let Some(undo_text) = self.undoer.undo(&self.state) { self.state = undo_text.clone(); } if redo && let Some(redo_text) = self.undoer.redo(&self.state) { self.state = redo_text.clone(); } }); self.undoer .feed_state(ui.input(|input| input.time), &self.state); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/src/demo/scrolling.rs
crates/egui_demo_lib/src/demo/scrolling.rs
use egui::{ Align, Align2, Color32, DragValue, NumExt as _, Rect, ScrollArea, Sense, Slider, TextStyle, TextWrapMode, Ui, Vec2, Widget as _, pos2, scroll_area::ScrollBarVisibility, }; #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[derive(Clone, Copy, Debug, Default, PartialEq)] enum ScrollDemo { #[default] ScrollAppearance, ScrollTo, ManyLines, LargeCanvas, StickToEnd, Bidirectional, } #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] #[derive(Default, PartialEq)] pub struct Scrolling { appearance: ScrollAppearance, demo: ScrollDemo, scroll_to: ScrollTo, scroll_stick_to: ScrollStickTo, } impl crate::Demo for Scrolling { fn name(&self) -> &'static str { "↕ Scrolling" } fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) { egui::Window::new(self.name()) .open(open) .resizable(true) .hscroll(false) .vscroll(false) .constrain_to(ui.available_rect_before_wrap()) .show(ui, |ui| { use crate::View as _; self.ui(ui); }); } } impl crate::View for Scrolling { fn ui(&mut self, ui: &mut Ui) { ui.horizontal(|ui| { ui.selectable_value(&mut self.demo, ScrollDemo::ScrollAppearance, "Appearance"); ui.selectable_value(&mut self.demo, ScrollDemo::ScrollTo, "Scroll to"); ui.selectable_value( &mut self.demo, ScrollDemo::ManyLines, "Scroll a lot of lines", ); ui.selectable_value( &mut self.demo, ScrollDemo::LargeCanvas, "Scroll a large canvas", ); ui.selectable_value(&mut self.demo, ScrollDemo::StickToEnd, "Stick to end"); ui.selectable_value(&mut self.demo, ScrollDemo::Bidirectional, "Bidirectional"); }); ui.separator(); match self.demo { ScrollDemo::ScrollAppearance => { self.appearance.ui(ui); } ScrollDemo::ScrollTo => { self.scroll_to.ui(ui); } ScrollDemo::ManyLines => { huge_content_lines(ui); } ScrollDemo::LargeCanvas => { huge_content_painter(ui); } ScrollDemo::StickToEnd => { self.scroll_stick_to.ui(ui); } ScrollDemo::Bidirectional => { egui::ScrollArea::both().show(ui, |ui| { ui.style_mut().wrap_mode = Some(TextWrapMode::Extend); for _ in 0..100 { ui.label(crate::LOREM_IPSUM); } }); } } } } #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] #[derive(PartialEq)] struct ScrollAppearance { num_lorem_ipsums: usize, visibility: ScrollBarVisibility, } impl Default for ScrollAppearance { fn default() -> Self { Self { num_lorem_ipsums: 2, visibility: ScrollBarVisibility::default(), } } } impl ScrollAppearance { fn ui(&mut self, ui: &mut egui::Ui) { let Self { num_lorem_ipsums, visibility, } = self; let mut scroll = ui.global_style().spacing.scroll; scroll.ui(ui); ui.add_space(8.0); ui.horizontal(|ui| { ui.label("ScrollBarVisibility:"); for option in ScrollBarVisibility::ALL { ui.selectable_value(visibility, option, format!("{option:?}")); } }); ui.weak("When to show scroll bars; resize the window to see the effect."); ui.add_space(8.0); ui.ctx().all_styles_mut(|s| s.spacing.scroll = scroll); ui.separator(); ui.add( egui::Slider::new(num_lorem_ipsums, 1..=100) .text("Content length") .logarithmic(true), ); ui.separator(); ScrollArea::vertical() .auto_shrink(false) .scroll_bar_visibility(*visibility) .show(ui, |ui| { ui.with_layout( egui::Layout::top_down(egui::Align::LEFT).with_cross_justify(true), |ui| { for _ in 0..*num_lorem_ipsums { ui.label(crate::LOREM_IPSUM_LONG); } }, ); }); } } fn huge_content_lines(ui: &mut egui::Ui) { ui.label( "A lot of rows, but only the visible ones are laid out, so performance is still good:", ); ui.add_space(4.0); let text_style = TextStyle::Body; let row_height = ui.text_style_height(&text_style); let num_rows = 10_000; ScrollArea::vertical().auto_shrink(false).show_rows( ui, row_height, num_rows, |ui, row_range| { for row in row_range { let text = format!("This is row {}/{}", row + 1, num_rows); ui.label(text); } }, ); } fn huge_content_painter(ui: &mut egui::Ui) { // This is similar to the other demo, but is fully manual, for when you want to do custom painting. ui.label("A lot of rows, but only the visible ones are painted, so performance is still good:"); ui.add_space(4.0); let font_id = TextStyle::Body.resolve(ui.style()); let row_height = ui.fonts_mut(|f| f.row_height(&font_id)) + ui.spacing().item_spacing.y; let num_rows = 10_000; ScrollArea::vertical() .auto_shrink(false) .show_viewport(ui, |ui, viewport| { ui.set_height(row_height * num_rows as f32); let first_item = (viewport.min.y / row_height).floor().at_least(0.0) as usize; let last_item = (viewport.max.y / row_height).ceil() as usize + 1; let last_item = last_item.at_most(num_rows); let mut used_rect = Rect::NOTHING; for i in first_item..last_item { let indentation = (i % 100) as f32; let x = ui.min_rect().left() + indentation; let y = ui.min_rect().top() + i as f32 * row_height; let text = format!( "This is row {}/{}, indented by {} pixels", i + 1, num_rows, indentation ); let text_rect = ui.painter().text( pos2(x, y), Align2::LEFT_TOP, text, font_id.clone(), ui.visuals().text_color(), ); used_rect |= text_rect; } ui.allocate_rect(used_rect, Sense::hover()); // make sure it is visible! }); } // ---------------------------------------------------------------------------- #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] #[derive(PartialEq)] struct ScrollTo { track_item: usize, tack_item_align: Option<Align>, offset: f32, delta: f32, } impl Default for ScrollTo { fn default() -> Self { Self { track_item: 25, tack_item_align: Some(Align::Center), offset: 0.0, delta: 64.0, } } } impl crate::View for ScrollTo { fn ui(&mut self, ui: &mut Ui) { ui.label("This shows how you can scroll to a specific item or pixel offset"); let num_items = 500; let mut track_item = false; let mut go_to_scroll_offset = false; let mut scroll_top = false; let mut scroll_bottom = false; let mut scroll_delta = None; ui.horizontal(|ui| { ui.label("Scroll to a specific item index:"); track_item |= ui .add(Slider::new(&mut self.track_item, 1..=num_items).text("Track Item")) .dragged(); }); ui.horizontal(|ui| { ui.label("Item align:"); track_item |= ui .radio_value(&mut self.tack_item_align, Some(Align::Min), "Top") .clicked(); track_item |= ui .radio_value(&mut self.tack_item_align, Some(Align::Center), "Center") .clicked(); track_item |= ui .radio_value(&mut self.tack_item_align, Some(Align::Max), "Bottom") .clicked(); track_item |= ui .radio_value(&mut self.tack_item_align, None, "None (Bring into view)") .clicked(); }); ui.horizontal(|ui| { ui.label("Scroll to a specific offset:"); go_to_scroll_offset |= ui .add(DragValue::new(&mut self.offset).speed(1.0).suffix("px")) .dragged(); }); ui.horizontal(|ui| { scroll_top |= ui.button("Scroll to top").clicked(); scroll_bottom |= ui.button("Scroll to bottom").clicked(); }); ui.horizontal(|ui| { ui.label("Scroll by"); DragValue::new(&mut self.delta) .speed(1.0) .suffix("px") .ui(ui); if ui.button("⬇").clicked() { scroll_delta = Some(self.delta * Vec2::UP); // scroll down (move contents up) } if ui.button("⬆").clicked() { scroll_delta = Some(self.delta * Vec2::DOWN); // scroll up (move contents down) } }); let mut scroll_area = ScrollArea::vertical().max_height(200.0).auto_shrink(false); if go_to_scroll_offset { scroll_area = scroll_area.vertical_scroll_offset(self.offset); } ui.separator(); let (current_scroll, max_scroll) = scroll_area .show(ui, |ui| { if scroll_top { ui.scroll_to_cursor(Some(Align::TOP)); } if let Some(scroll_delta) = scroll_delta { ui.scroll_with_delta(scroll_delta); } ui.vertical(|ui| { for item in 1..=num_items { if track_item && item == self.track_item { let response = ui.colored_label(Color32::YELLOW, format!("This is item {item}")); response.scroll_to_me(self.tack_item_align); } else { ui.label(format!("This is item {item}")); } } }); if scroll_bottom { ui.scroll_to_cursor(Some(Align::BOTTOM)); } let margin = ui.visuals().clip_rect_margin; let current_scroll = ui.clip_rect().top() - ui.min_rect().top() + margin; let max_scroll = ui.min_rect().height() - ui.clip_rect().height() + 2.0 * margin; (current_scroll, max_scroll) }) .inner; ui.separator(); ui.label(format!( "Scroll offset: {current_scroll:.0}/{max_scroll:.0} px" )); ui.separator(); ui.vertical_centered(|ui| { egui::reset_button(ui, self, "Reset"); ui.add(crate::egui_github_link_file!()); }); } } #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] #[derive(Default, PartialEq)] struct ScrollStickTo { n_items: usize, } impl crate::View for ScrollStickTo { fn ui(&mut self, ui: &mut Ui) { ui.label("Rows enter from the bottom, we want the scroll handle to start and stay at bottom unless moved"); ui.add_space(4.0); let text_style = TextStyle::Body; let row_height = ui.text_style_height(&text_style); ScrollArea::vertical().stick_to_bottom(true).show_rows( ui, row_height, self.n_items, |ui, row_range| { for row in row_range { let text = format!("This is row {}", row + 1); ui.label(text); } }, ); self.n_items += 1; ui.request_repaint(); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/src/demo/screenshot.rs
crates/egui_demo_lib/src/demo/screenshot.rs
use egui::{Image, UserData, ViewportCommand, Widget as _}; use std::sync::Arc; /// Showcase [`ViewportCommand::Screenshot`]. #[derive(PartialEq, Eq, Default)] pub struct Screenshot { image: Option<(Arc<egui::ColorImage>, egui::TextureHandle)>, continuous: bool, } impl crate::Demo for Screenshot { fn name(&self) -> &'static str { "📷 Screenshot" } fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) { egui::Window::new(self.name()) .open(open) .resizable(false) .default_width(250.0) .constrain_to(ui.available_rect_before_wrap()) .show(ui, |ui| { use crate::View as _; self.ui(ui); }); } } impl crate::View for Screenshot { fn ui(&mut self, ui: &mut egui::Ui) { ui.set_width(300.0); ui.vertical_centered(|ui| { ui.add(crate::egui_github_link_file!()); }); ui.horizontal_wrapped(|ui| { ui.spacing_mut().item_spacing.x = 0.0; ui.label("This demo showcases how to take screenshots via "); ui.code("ViewportCommand::Screenshot"); ui.label("."); }); ui.horizontal_top(|ui| { let capture = ui.button("📷 Take Screenshot").clicked(); ui.checkbox(&mut self.continuous, "Capture continuously"); if capture || self.continuous { ui.send_viewport_cmd(ViewportCommand::Screenshot(UserData::default())); } }); let image = ui.input(|i| { i.events .iter() .filter_map(|e| { if let egui::Event::Screenshot { image, .. } = e { Some(Arc::clone(image)) } else { None } }) .next_back() }); if let Some(image) = image { self.image = Some(( Arc::clone(&image), ui.ctx() .load_texture("screenshot_demo", image, Default::default()), )); } if let Some((_, texture)) = &self.image { Image::new(texture).shrink_to_fit().ui(ui); } else { ui.group(|ui| { ui.set_width(ui.available_width()); ui.set_height(100.0); ui.centered_and_justified(|ui| { ui.label("No screenshot taken yet."); }); }); } } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/src/demo/scene.rs
crates/egui_demo_lib/src/demo/scene.rs
use egui::{Pos2, Rect, Scene, Vec2}; use super::widget_gallery; #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct SceneDemo { widget_gallery: widget_gallery::WidgetGallery, scene_rect: Rect, } impl Default for SceneDemo { fn default() -> Self { Self { widget_gallery: widget_gallery::WidgetGallery::default().with_date_button(false), // disable date button so that we don't fail the snapshot test scene_rect: Rect::ZERO, // `egui::Scene` will initialize this to something valid } } } impl crate::Demo for SceneDemo { fn name(&self) -> &'static str { "🔍 Scene" } fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) { use crate::View as _; egui::Window::new("Scene") .default_width(300.0) .default_height(300.0) .scroll(false) .open(open) .constrain_to(ui.available_rect_before_wrap()) .show(ui, |ui| self.ui(ui)); } } impl crate::View for SceneDemo { fn ui(&mut self, ui: &mut egui::Ui) { ui.label( "You can pan by scrolling, and zoom using cmd-scroll. \ Double click on the background to reset view.", ); ui.vertical_centered(|ui| { ui.add(crate::egui_github_link_file!()); }); ui.separator(); ui.label(format!("Scene rect: {:#?}", &mut self.scene_rect)); ui.separator(); egui::Frame::group(ui.style()) .inner_margin(0.0) .show(ui, |ui| { let scene = Scene::new() .max_inner_size([350.0, 1000.0]) .zoom_range(0.1..=2.0); let mut reset_view = false; let mut inner_rect = Rect::NAN; let response = scene .show(ui, &mut self.scene_rect, |ui| { reset_view = ui.button("Reset view").clicked(); ui.add_space(16.0); self.widget_gallery.ui(ui); ui.put( Rect::from_min_size(Pos2::new(0.0, -64.0), Vec2::new(200.0, 16.0)), egui::Label::new("You can put a widget anywhere").selectable(false), ); inner_rect = ui.min_rect(); }) .response; if reset_view || response.double_clicked() { self.scene_rect = inner_rect; } }); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/src/demo/panels.rs
crates/egui_demo_lib/src/demo/panels.rs
#[derive(Clone, Default, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct Panels {} impl crate::Demo for Panels { fn name(&self) -> &'static str { "🗖 Panels" } fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) { use crate::View as _; egui::Window::new("Panels") .default_width(600.0) .default_height(400.0) .vscroll(false) .open(open) .constrain_to(ui.available_rect_before_wrap()) .show(ui, |ui| self.ui(ui)); } } impl crate::View for Panels { fn ui(&mut self, ui: &mut egui::Ui) { // Note that the order we add the panels is very important! egui::Panel::top("top_panel") .resizable(true) .min_size(32.0) .show_inside(ui, |ui| { egui::ScrollArea::vertical().show(ui, |ui| { ui.vertical_centered(|ui| { ui.heading("Expandable Upper Panel"); }); lorem_ipsum(ui); }); }); egui::Panel::left("left_panel") .resizable(true) .default_size(150.0) .size_range(80.0..=200.0) .show_inside(ui, |ui| { ui.vertical_centered(|ui| { ui.heading("Left Panel"); }); egui::ScrollArea::vertical().show(ui, |ui| { lorem_ipsum(ui); }); }); egui::Panel::right("right_panel") .resizable(true) .default_size(150.0) .size_range(80.0..=200.0) .show_inside(ui, |ui| { ui.vertical_centered(|ui| { ui.heading("Right Panel"); }); egui::ScrollArea::vertical().show(ui, |ui| { lorem_ipsum(ui); }); }); egui::Panel::bottom("bottom_panel") .resizable(false) .min_size(0.0) .show_inside(ui, |ui| { ui.vertical_centered(|ui| { ui.heading("Bottom Panel"); }); ui.vertical_centered(|ui| { ui.add(crate::egui_github_link_file!()); }); }); // TODO(emilk): This extra panel is superfluous - just use what's left of `ui` instead egui::CentralPanel::default().show_inside(ui, |ui| { ui.vertical_centered(|ui| { ui.heading("Central Panel"); }); egui::ScrollArea::vertical().show(ui, |ui| { lorem_ipsum(ui); }); }); } } fn lorem_ipsum(ui: &mut egui::Ui) { ui.with_layout( egui::Layout::top_down(egui::Align::LEFT).with_cross_justify(true), |ui| { ui.label(egui::RichText::new(crate::LOREM_IPSUM_LONG).small().weak()); ui.add(egui::Separator::default().grow(8.0)); ui.label(egui::RichText::new(crate::LOREM_IPSUM_LONG).small().weak()); }, ); }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/src/demo/dancing_strings.rs
crates/egui_demo_lib/src/demo/dancing_strings.rs
use egui::{ Color32, Pos2, Rect, Ui, containers::{Frame, Window}, emath, epaint, epaint::PathStroke, hex_color, lerp, pos2, remap, vec2, }; #[derive(Default)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] pub struct DancingStrings { colors: bool, } impl crate::Demo for DancingStrings { fn name(&self) -> &'static str { "♫ Dancing Strings" } fn show(&mut self, ui: &mut Ui, open: &mut bool) { use crate::View as _; Window::new(self.name()) .open(open) .default_size(vec2(512.0, 256.0)) .vscroll(false) .constrain_to(ui.available_rect_before_wrap()) .show(ui, |ui| self.ui(ui)); } } impl crate::View for DancingStrings { fn ui(&mut self, ui: &mut Ui) { let color = if ui.visuals().dark_mode { Color32::from_additive_luminance(196) } else { Color32::from_black_alpha(240) }; ui.checkbox(&mut self.colors, "Colored") .on_hover_text("Demonstrates how a path can have varying color across its length."); Frame::canvas(ui.style()).show(ui, |ui| { ui.request_repaint(); let time = ui.input(|i| i.time); let desired_size = ui.available_width() * vec2(1.0, 0.35); let (_id, rect) = ui.allocate_space(desired_size); let to_screen = emath::RectTransform::from_to(Rect::from_x_y_ranges(0.0..=1.0, -1.0..=1.0), rect); let mut shapes = vec![]; for &mode in &[2, 3, 5] { let mode = mode as f64; let n = 120; let speed = 1.5; let points: Vec<Pos2> = (0..=n) .map(|i| { let t = i as f64 / (n as f64); let amp = (time * speed * mode).sin() / mode; let y = amp * (t * std::f64::consts::TAU / 2.0 * mode).sin(); to_screen * pos2(t as f32, y as f32) }) .collect(); let thickness = 10.0 / mode as f32; shapes.push(epaint::Shape::line( points, if self.colors { PathStroke::new_uv(thickness, move |rect, p| { let t = remap(p.x, rect.x_range(), -1.0..=1.0).abs(); let center_color = hex_color!("#5BCEFA"); let outer_color = hex_color!("#F5A9B8"); Color32::from_rgb( lerp(center_color.r() as f32..=outer_color.r() as f32, t) as u8, lerp(center_color.g() as f32..=outer_color.g() as f32, t) as u8, lerp(center_color.b() as f32..=outer_color.b() as f32, t) as u8, ) }) } else { PathStroke::new(thickness, color) }, )); } ui.painter().extend(shapes); }); ui.vertical_centered(|ui| { ui.add(crate::egui_github_link_file!()); }); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/src/demo/popups.rs
crates/egui_demo_lib/src/demo/popups.rs
use crate::rust_view_ui; use egui::color_picker::{Alpha, color_picker_color32}; use egui::containers::menu::{MenuConfig, SubMenuButton}; use egui::{ Align, Align2, Atom, Button, ComboBox, Frame, Id, Layout, Popup, PopupCloseBehavior, RectAlign, RichText, Tooltip, Ui, UiBuilder, include_image, }; /// Showcase [`Popup`]. #[derive(Clone, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] pub struct PopupsDemo { align4: RectAlign, gap: f32, #[cfg_attr(feature = "serde", serde(skip))] close_behavior: PopupCloseBehavior, popup_open: bool, checked: bool, color: egui::Color32, } impl Default for PopupsDemo { fn default() -> Self { Self { align4: RectAlign::default(), gap: 4.0, close_behavior: PopupCloseBehavior::CloseOnClick, popup_open: false, checked: true, color: egui::Color32::RED, } } } impl PopupsDemo { fn apply_options<'a>(&self, popup: Popup<'a>) -> Popup<'a> { popup .align(self.align4) .gap(self.gap) .close_behavior(self.close_behavior) } fn nested_menus(&mut self, ui: &mut Ui) { ui.set_max_width(200.0); // To make sure we wrap long text if ui.button("Open…").clicked() { ui.close(); } ui.menu_button("Popups can have submenus", |ui| { ui.menu_button("SubMenu", |ui| { if ui.button("Open…").clicked() { ui.close(); } let _ = ui.button("Item"); ui.menu_button("Recursive", |ui| self.nested_menus(ui)); }); ui.menu_button("SubMenu", |ui| { if ui.button("Open…").clicked() { ui.close(); } let _ = ui.button("Item"); }); let _ = ui.button("Item"); if ui.button("Open…").clicked() { ui.close(); } }); ui.add_enabled_ui(false, |ui| { ui.menu_button("SubMenus can be disabled", |_| {}); }); ui.menu_image_text_button( include_image!("../../data/icon.png"), "I have an icon!", |ui| { let _ = ui.button("Item1"); let _ = ui.button("Item2"); let _ = ui.button("Item3"); let _ = ui.button("Item4"); if ui.button("Open…").clicked() { ui.close(); } }, ); let _ = ui.button("Very long text for this item that should be wrapped"); SubMenuButton::new("Always CloseOnClickOutside") .config(MenuConfig::new().close_behavior(PopupCloseBehavior::CloseOnClickOutside)) .ui(ui, |ui| { ui.checkbox(&mut self.checked, "Checkbox"); // Customized color SubMenuButton let is_bright = self.color.intensity() > 0.5; let text_color = if is_bright { egui::Color32::BLACK } else { egui::Color32::WHITE }; let button = Button::new(( RichText::new("Background").color(text_color), Atom::grow(), RichText::new(SubMenuButton::RIGHT_ARROW).color(text_color), )) .fill(self.color); SubMenuButton::from_button(button).ui(ui, |ui| { ui.spacing_mut().slider_width = 200.0; color_picker_color32(ui, &mut self.color, Alpha::Opaque); }); if self.checked { ui.menu_button("Only visible when checked", |ui| { if ui.button("Remove myself").clicked() { self.checked = false; } }); } if ui.button("Open…").clicked() { ui.close(); } }); } } impl crate::Demo for PopupsDemo { fn name(&self) -> &'static str { "\u{2755} Popups" } fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) { egui::Window::new(self.name()) .open(open) .resizable(false) .default_width(250.0) .constrain(false) .constrain_to(ui.available_rect_before_wrap()) .show(ui, |ui| { use crate::View as _; self.ui(ui); }); } } impl crate::View for PopupsDemo { fn ui(&mut self, ui: &mut egui::Ui) { let response = Frame::group(ui.style()) .show(ui, |ui| { ui.set_width(ui.available_width()); ui.vertical_centered(|ui| ui.button("Click, right-click and hover me!")) .inner }) .inner; self.apply_options(Popup::menu(&response).id(Id::new("menu"))) .show(|ui| self.nested_menus(ui)); self.apply_options(Popup::context_menu(&response).id(Id::new("context_menu"))) .show(|ui| self.nested_menus(ui)); if self.popup_open { self.apply_options(Popup::from_response(&response).id(Id::new("popup"))) .show(|ui| { ui.label("Popup contents"); }); } let mut tooltip = Tooltip::for_enabled(&response); tooltip.popup = self.apply_options(tooltip.popup); tooltip.show(|ui| { ui.label("Tooltips are popups, too!"); }); Frame::canvas(ui.style()).show(ui, |ui| { let mut reset_btn_ui = ui.new_child( UiBuilder::new() .max_rect(ui.max_rect()) .layout(Layout::right_to_left(Align::Min)), ); if reset_btn_ui .button("⟲") .on_hover_text("Reset to defaults") .clicked() { *self = Self::default(); } ui.set_width(ui.available_width()); ui.style_mut().override_text_style = Some(egui::TextStyle::Monospace); ui.spacing_mut().item_spacing.x = 0.0; let align_combobox = |ui: &mut Ui, label: &str, align: &mut Align2| { let aligns = [ (Align2::LEFT_TOP, "LEFT_TOP"), (Align2::LEFT_CENTER, "LEFT_CENTER"), (Align2::LEFT_BOTTOM, "LEFT_BOTTOM"), (Align2::CENTER_TOP, "CENTER_TOP"), (Align2::CENTER_CENTER, "CENTER_CENTER"), (Align2::CENTER_BOTTOM, "CENTER_BOTTOM"), (Align2::RIGHT_TOP, "RIGHT_TOP"), (Align2::RIGHT_CENTER, "RIGHT_CENTER"), (Align2::RIGHT_BOTTOM, "RIGHT_BOTTOM"), ]; ComboBox::new(label, "") .selected_text(aligns.iter().find(|(a, _)| a == align).unwrap().1) .show_ui(ui, |ui| { for (align2, name) in &aligns { ui.selectable_value(align, *align2, *name); } }); }; rust_view_ui(ui, "let align = RectAlign {"); ui.horizontal(|ui| { rust_view_ui(ui, " parent: Align2::"); align_combobox(ui, "parent", &mut self.align4.parent); rust_view_ui(ui, ","); }); ui.horizontal(|ui| { rust_view_ui(ui, " child: Align2::"); align_combobox(ui, "child", &mut self.align4.child); rust_view_ui(ui, ","); }); rust_view_ui(ui, "};"); ui.horizontal(|ui| { rust_view_ui(ui, "let align = RectAlign::"); let presets = [ (RectAlign::TOP_START, "TOP_START"), (RectAlign::TOP, "TOP"), (RectAlign::TOP_END, "TOP_END"), (RectAlign::RIGHT_START, "RIGHT_START"), (RectAlign::RIGHT, "RIGHT"), (RectAlign::RIGHT_END, "RIGHT_END"), (RectAlign::BOTTOM_START, "BOTTOM_START"), (RectAlign::BOTTOM, "BOTTOM"), (RectAlign::BOTTOM_END, "BOTTOM_END"), (RectAlign::LEFT_START, "LEFT_START"), (RectAlign::LEFT, "LEFT"), (RectAlign::LEFT_END, "LEFT_END"), ]; ComboBox::new("Preset", "") .selected_text( presets .iter() .find(|(a, _)| a == &self.align4) .map_or("<Select Preset>", |(_, name)| *name), ) .show_ui(ui, |ui| { for (align4, name) in &presets { ui.selectable_value(&mut self.align4, *align4, *name); } }); rust_view_ui(ui, ";"); }); ui.horizontal(|ui| { rust_view_ui(ui, "let gap = "); ui.add(egui::DragValue::new(&mut self.gap)); rust_view_ui(ui, ";"); }); rust_view_ui(ui, "let close_behavior"); ui.horizontal(|ui| { rust_view_ui(ui, " = PopupCloseBehavior::"); let close_behaviors = [ ( PopupCloseBehavior::CloseOnClick, "CloseOnClick", "Closes when the user clicks anywhere (inside or outside)", ), ( PopupCloseBehavior::CloseOnClickOutside, "CloseOnClickOutside", "Closes when the user clicks outside the popup", ), ( PopupCloseBehavior::IgnoreClicks, "IgnoreClicks", "Close only when the button is clicked again", ), ]; ComboBox::new("Close behavior", "") .selected_text( close_behaviors .iter() .find_map(|(behavior, text, _)| { (behavior == &self.close_behavior).then_some(*text) }) .unwrap(), ) .show_ui(ui, |ui| { for (close_behavior, name, tooltip) in &close_behaviors { ui.selectable_value(&mut self.close_behavior, *close_behavior, *name) .on_hover_text(*tooltip); } }); rust_view_ui(ui, ";"); }); ui.horizontal(|ui| { rust_view_ui(ui, "let popup_open = "); ui.checkbox(&mut self.popup_open, ""); rust_view_ui(ui, ";"); }); ui.monospace(""); rust_view_ui(ui, "let response = ui.button(\"Click me!\");"); rust_view_ui(ui, "Popup::menu(&response)"); rust_view_ui(ui, " .gap(gap).align(align)"); rust_view_ui(ui, " .close_behavior(close_behavior)"); rust_view_ui(ui, " .show(|ui| { /* menu contents */ });"); }); ui.vertical_centered(|ui| { ui.add(crate::egui_github_link_file!()); }); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/src/demo/drag_and_drop.rs
crates/egui_demo_lib/src/demo/drag_and_drop.rs
use egui::{Color32, Frame, Id, Ui, Window, vec2}; #[derive(Clone, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct DragAndDropDemo { /// columns with items columns: Vec<Vec<String>>, } impl Default for DragAndDropDemo { fn default() -> Self { Self { columns: vec![ vec!["Item A", "Item B", "Item C", "Item D"], vec!["Item E", "Item F", "Item G"], vec!["Item H", "Item I", "Item J", "Item K"], ] .into_iter() .map(|v| v.into_iter().map(ToString::to_string).collect()) .collect(), } } } impl crate::Demo for DragAndDropDemo { fn name(&self) -> &'static str { "✋ Drag and Drop" } fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) { use crate::View as _; Window::new(self.name()) .open(open) .default_size(vec2(256.0, 256.0)) .vscroll(false) .resizable(false) .constrain_to(ui.available_rect_before_wrap()) .show(ui, |ui| self.ui(ui)); } } /// What is being dragged. #[derive(Clone, Copy, Debug, PartialEq, Eq)] struct Location { col: usize, row: usize, } impl crate::View for DragAndDropDemo { fn ui(&mut self, ui: &mut Ui) { ui.label("This is a simple example of drag-and-drop in egui."); ui.label("Drag items between columns."); // If there is a drop, store the location of the item being dragged, and the destination for the drop. let mut from = None; let mut to = None; ui.columns(self.columns.len(), |uis| { for (col_idx, column) in self.columns.clone().into_iter().enumerate() { let ui = &mut uis[col_idx]; let frame = Frame::default().inner_margin(4.0); let (_, dropped_payload) = ui.dnd_drop_zone::<Location, ()>(frame, |ui| { ui.set_min_size(vec2(64.0, 100.0)); for (row_idx, item) in column.iter().enumerate() { let item_id = Id::new(("my_drag_and_drop_demo", col_idx, row_idx)); let item_location = Location { col: col_idx, row: row_idx, }; let response = ui .dnd_drag_source(item_id, item_location, |ui| { ui.label(item); }) .response; // Detect drops onto this item: if let (Some(pointer), Some(hovered_payload)) = ( ui.input(|i| i.pointer.interact_pos()), response.dnd_hover_payload::<Location>(), ) { let rect = response.rect; // Preview insertion: let stroke = egui::Stroke::new(1.0, Color32::WHITE); let insert_row_idx = if *hovered_payload == item_location { // We are dragged onto ourselves ui.painter().hline(rect.x_range(), rect.center().y, stroke); row_idx } else if pointer.y < rect.center().y { // Above us ui.painter().hline(rect.x_range(), rect.top(), stroke); row_idx } else { // Below us ui.painter().hline(rect.x_range(), rect.bottom(), stroke); row_idx + 1 }; if let Some(dragged_payload) = response.dnd_release_payload() { // The user dropped onto this item. from = Some(dragged_payload); to = Some(Location { col: col_idx, row: insert_row_idx, }); } } } }); if let Some(dragged_payload) = dropped_payload { // The user dropped onto the column, but not on any one item. from = Some(dragged_payload); to = Some(Location { col: col_idx, row: usize::MAX, // Inset last }); } } }); if let (Some(from), Some(mut to)) = (from, to) { if from.col == to.col { // Dragging within the same column. // Adjust row index if we are re-ordering: to.row -= (from.row < to.row) as usize; } let item = self.columns[from.col].remove(from.row); let column = &mut self.columns[to.col]; to.row = to.row.min(column.len()); column.insert(to.row, item); } ui.vertical_centered(|ui| { ui.add(crate::egui_github_link_file!()); }); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/src/demo/window_options.rs
crates/egui_demo_lib/src/demo/window_options.rs
use egui::{UiKind, Vec2b}; #[derive(Clone, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct WindowOptions { title: String, title_bar: bool, closable: bool, collapsible: bool, resizable: bool, constrain: bool, scroll2: Vec2b, disabled_time: f64, anchored: bool, anchor: egui::Align2, anchor_offset: egui::Vec2, } impl Default for WindowOptions { fn default() -> Self { Self { title: "🗖 Window Options".to_owned(), title_bar: true, closable: true, collapsible: true, resizable: true, constrain: true, scroll2: Vec2b::TRUE, disabled_time: f64::NEG_INFINITY, anchored: false, anchor: egui::Align2::RIGHT_TOP, anchor_offset: egui::Vec2::ZERO, } } } impl crate::Demo for WindowOptions { fn name(&self) -> &'static str { "🗖 Window Options" } fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) { let Self { title, title_bar, closable, collapsible, resizable, constrain, scroll2, disabled_time, anchored, anchor, anchor_offset, } = self.clone(); let enabled = ui.input(|i| i.time) - disabled_time > 2.0; if !enabled { ui.request_repaint(); } use crate::View as _; let mut window = egui::Window::new(title) .id(egui::Id::new("demo_window_options")) // required since we change the title .resizable(resizable) .constrain(constrain) .collapsible(collapsible) .title_bar(title_bar) .scroll(scroll2) .constrain_to(ui.available_rect_before_wrap()) .enabled(enabled); if closable { window = window.open(open); } if anchored { window = window.anchor(anchor, anchor_offset); } window.show(ui, |ui| self.ui(ui)); } } impl crate::View for WindowOptions { fn ui(&mut self, ui: &mut egui::Ui) { let Self { title, title_bar, closable, collapsible, resizable, constrain, scroll2, disabled_time: _, anchored, anchor, anchor_offset, } = self; ui.horizontal(|ui| { ui.label("title:"); ui.text_edit_singleline(title); }); ui.horizontal(|ui| { ui.group(|ui| { ui.vertical(|ui| { ui.checkbox(title_bar, "title_bar"); ui.checkbox(closable, "closable"); ui.checkbox(collapsible, "collapsible"); ui.checkbox(resizable, "resizable"); ui.checkbox(constrain, "constrain") .on_hover_text("Constrain window to the screen"); ui.checkbox(&mut scroll2[0], "hscroll"); ui.checkbox(&mut scroll2[1], "vscroll"); }); }); ui.group(|ui| { ui.vertical(|ui| { ui.checkbox(anchored, "anchored"); if !*anchored { ui.disable(); } ui.horizontal(|ui| { ui.label("x:"); ui.selectable_value(&mut anchor[0], egui::Align::LEFT, "Left"); ui.selectable_value(&mut anchor[0], egui::Align::Center, "Center"); ui.selectable_value(&mut anchor[0], egui::Align::RIGHT, "Right"); }); ui.horizontal(|ui| { ui.label("y:"); ui.selectable_value(&mut anchor[1], egui::Align::TOP, "Top"); ui.selectable_value(&mut anchor[1], egui::Align::Center, "Center"); ui.selectable_value(&mut anchor[1], egui::Align::BOTTOM, "Bottom"); }); ui.horizontal(|ui| { ui.label("Offset:"); ui.add(egui::DragValue::new(&mut anchor_offset.x)); ui.add(egui::DragValue::new(&mut anchor_offset.y)); }); }); }); }); ui.separator(); let on_top = Some(ui.layer_id()) == ui.ctx().top_layer_id(); ui.label(format!("This window is on top: {on_top}.")); ui.separator(); ui.horizontal(|ui| { if ui.button("Disable for 2 seconds").clicked() { self.disabled_time = ui.input(|i| i.time); } egui::reset_button(ui, self, "Reset"); if ui .button("Close") .on_hover_text("You can collapse / close Windows via Ui::close") .clicked() { // Calling close would close the collapsible within the window // ui.close(); // Instead, we close the window itself ui.close_kind(UiKind::Window); } ui.add(crate::egui_github_link_file!()); }); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/src/demo/font_book.rs
crates/egui_demo_lib/src/demo/font_book.rs
use std::collections::BTreeMap; struct GlyphInfo { name: String, // What fonts it is available in fonts: Vec<String>, } pub struct FontBook { filter: String, font_id: egui::FontId, available_glyphs: BTreeMap<egui::FontFamily, BTreeMap<char, GlyphInfo>>, } impl Default for FontBook { fn default() -> Self { Self { filter: Default::default(), font_id: egui::FontId::proportional(18.0), available_glyphs: Default::default(), } } } impl crate::Demo for FontBook { fn name(&self) -> &'static str { "🔤 Font Book" } fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) { egui::Window::new(self.name()) .open(open) .constrain_to(ui.available_rect_before_wrap()) .show(ui, |ui| { use crate::View as _; self.ui(ui); }); } } impl crate::View for FontBook { fn ui(&mut self, ui: &mut egui::Ui) { ui.vertical_centered(|ui| { ui.add(crate::egui_github_link_file!()); }); ui.label(format!( "The selected font supports {} characters.", self.available_glyphs .get(&self.font_id.family) .map(|map| map.len()) .unwrap_or_default() )); ui.horizontal_wrapped(|ui| { ui.spacing_mut().item_spacing.x = 0.0; ui.label("You can add more characters by installing additional fonts with "); ui.add(egui::Hyperlink::from_label_and_url( egui::RichText::new("Context::set_fonts").text_style(egui::TextStyle::Monospace), "https://docs.rs/egui/latest/egui/struct.Context.html#method.set_fonts", )); ui.label("."); }); ui.separator(); egui::introspection::font_id_ui(ui, &mut self.font_id); ui.horizontal(|ui| { ui.label("Filter:"); ui.add(egui::TextEdit::singleline(&mut self.filter).desired_width(120.0)); self.filter = self.filter.to_lowercase(); if ui.button("x").clicked() { self.filter.clear(); } }); let filter = &self.filter; let available_glyphs = self .available_glyphs .entry(self.font_id.family.clone()) .or_insert_with(|| available_characters(ui, &self.font_id.family)); ui.separator(); egui::ScrollArea::vertical().show(ui, |ui| { ui.horizontal_wrapped(|ui| { ui.spacing_mut().item_spacing = egui::Vec2::splat(2.0); for (&chr, glyph_info) in available_glyphs.iter() { if filter.is_empty() || glyph_info.name.contains(filter) || *filter == chr.to_string() { let button = egui::Button::new( egui::RichText::new(chr.to_string()).font(self.font_id.clone()), ) .frame(false); let tooltip_ui = |ui: &mut egui::Ui| { let font_id = self.font_id.clone(); char_info_ui(ui, chr, glyph_info, font_id); }; if ui.add(button).on_hover_ui(tooltip_ui).clicked() { ui.copy_text(chr.to_string()); } } } }); }); } } fn char_info_ui(ui: &mut egui::Ui, chr: char, glyph_info: &GlyphInfo, font_id: egui::FontId) { let resp = ui.label(egui::RichText::new(chr.to_string()).font(font_id)); egui::Grid::new("char_info") .num_columns(2) .striped(true) .show(ui, |ui| { ui.label("Name"); ui.label(glyph_info.name.clone()); ui.end_row(); ui.label("Hex"); ui.label(format!("{:X}", chr as u32)); ui.end_row(); ui.label("Width"); ui.label(format!("{:.1} pts", resp.rect.width())); ui.end_row(); ui.label("Fonts"); ui.label( format!("{:?}", glyph_info.fonts) .trim_start_matches('[') .trim_end_matches(']'), ); ui.end_row(); }); } fn available_characters(ui: &egui::Ui, family: &egui::FontFamily) -> BTreeMap<char, GlyphInfo> { ui.fonts_mut(|f| { f.fonts .font(family) .characters() .iter() .filter(|(chr, _fonts)| !chr.is_whitespace() && !chr.is_ascii_control()) .map(|(chr, fonts)| { ( *chr, GlyphInfo { name: char_name(*chr), fonts: fonts.clone(), }, ) }) .collect() }) } fn char_name(chr: char) -> String { special_char_name(chr) .map(|s| s.to_owned()) .or_else(|| unicode_names2::name(chr).map(|name| name.to_string().to_lowercase())) .unwrap_or_else(|| "unknown".to_owned()) } fn special_char_name(chr: char) -> Option<&'static str> { #[expect(clippy::match_same_arms)] // many "flag" match chr { // Special private-use-area extensions found in `emoji-icon-font.ttf`: // Private use area extensions: '\u{FE4E5}' => Some("flag japan"), '\u{FE4E6}' => Some("flag usa"), '\u{FE4E7}' => Some("flag"), '\u{FE4E8}' => Some("flag"), '\u{FE4E9}' => Some("flag"), '\u{FE4EA}' => Some("flag great britain"), '\u{FE4EB}' => Some("flag"), '\u{FE4EC}' => Some("flag"), '\u{FE4ED}' => Some("flag"), '\u{FE4EE}' => Some("flag south korea"), '\u{FE82C}' => Some("number sign in square"), '\u{FE82E}' => Some("digit one in square"), '\u{FE82F}' => Some("digit two in square"), '\u{FE830}' => Some("digit three in square"), '\u{FE831}' => Some("digit four in square"), '\u{FE832}' => Some("digit five in square"), '\u{FE833}' => Some("digit six in square"), '\u{FE834}' => Some("digit seven in square"), '\u{FE835}' => Some("digit eight in square"), '\u{FE836}' => Some("digit nine in square"), '\u{FE837}' => Some("digit zero in square"), // Special private-use-area extensions found in `emoji-icon-font.ttf`: // Web services / operating systems / browsers '\u{E600}' => Some("web-dribbble"), '\u{E601}' => Some("web-stackoverflow"), '\u{E602}' => Some("web-vimeo"), '\u{E604}' => Some("web-facebook"), '\u{E605}' => Some("web-googleplus"), '\u{E606}' => Some("web-pinterest"), '\u{E607}' => Some("web-tumblr"), '\u{E608}' => Some("web-linkedin"), '\u{E60A}' => Some("web-stumbleupon"), '\u{E60B}' => Some("web-lastfm"), '\u{E60C}' => Some("web-rdio"), '\u{E60D}' => Some("web-spotify"), '\u{E60E}' => Some("web-qq"), '\u{E60F}' => Some("web-instagram"), '\u{E610}' => Some("web-dropbox"), '\u{E611}' => Some("web-evernote"), '\u{E612}' => Some("web-flattr"), '\u{E613}' => Some("web-skype"), '\u{E614}' => Some("web-renren"), '\u{E615}' => Some("web-sina-weibo"), '\u{E616}' => Some("web-paypal"), '\u{E617}' => Some("web-picasa"), '\u{E618}' => Some("os-android"), '\u{E619}' => Some("web-mixi"), '\u{E61A}' => Some("web-behance"), '\u{E61B}' => Some("web-circles"), '\u{E61C}' => Some("web-vk"), '\u{E61D}' => Some("web-smashing"), '\u{E61E}' => Some("web-forrst"), '\u{E61F}' => Some("os-windows"), '\u{E620}' => Some("web-flickr"), '\u{E621}' => Some("web-picassa"), '\u{E622}' => Some("web-deviantart"), '\u{E623}' => Some("web-steam"), '\u{E624}' => Some("web-github"), '\u{E625}' => Some("web-git"), '\u{E626}' => Some("web-blogger"), '\u{E627}' => Some("web-soundcloud"), '\u{E628}' => Some("web-reddit"), '\u{E629}' => Some("web-delicious"), '\u{E62A}' => Some("browser-chrome"), '\u{E62B}' => Some("browser-firefox"), '\u{E62C}' => Some("browser-ie"), '\u{E62D}' => Some("browser-opera"), '\u{E62E}' => Some("browser-safari"), '\u{E62F}' => Some("web-google-drive"), '\u{E630}' => Some("web-wordpress"), '\u{E631}' => Some("web-joomla"), '\u{E632}' => Some("lastfm"), '\u{E633}' => Some("web-foursquare"), '\u{E634}' => Some("web-yelp"), '\u{E635}' => Some("web-drupal"), '\u{E636}' => Some("youtube"), '\u{F189}' => Some("vk"), '\u{F1A6}' => Some("digg"), '\u{F1CA}' => Some("web-vine"), '\u{F8FF}' => Some("os-apple"), // Special private-use-area extensions found in `Ubuntu-Light.ttf` '\u{F000}' => Some("uniF000"), '\u{F001}' => Some("fi"), '\u{F002}' => Some("fl"), '\u{F506}' => Some("one seventh"), '\u{F507}' => Some("two sevenths"), '\u{F508}' => Some("three sevenths"), '\u{F509}' => Some("four sevenths"), '\u{F50A}' => Some("five sevenths"), '\u{F50B}' => Some("six sevenths"), '\u{F50C}' => Some("one ninth"), '\u{F50D}' => Some("two ninths"), '\u{F50E}' => Some("four ninths"), '\u{F50F}' => Some("five ninths"), '\u{F510}' => Some("seven ninths"), '\u{F511}' => Some("eight ninths"), '\u{F800}' => Some("zero.alt"), '\u{F801}' => Some("one.alt"), '\u{F802}' => Some("two.alt"), '\u{F803}' => Some("three.alt"), '\u{F804}' => Some("four.alt"), '\u{F805}' => Some("five.alt"), '\u{F806}' => Some("six.alt"), '\u{F807}' => Some("seven.alt"), '\u{F808}' => Some("eight.alt"), '\u{F809}' => Some("nine.alt"), '\u{F80A}' => Some("zero.sups"), '\u{F80B}' => Some("one.sups"), '\u{F80C}' => Some("two.sups"), '\u{F80D}' => Some("three.sups"), '\u{F80E}' => Some("four.sups"), '\u{F80F}' => Some("five.sups"), '\u{F810}' => Some("six.sups"), '\u{F811}' => Some("seven.sups"), '\u{F812}' => Some("eight.sups"), '\u{F813}' => Some("nine.sups"), '\u{F814}' => Some("zero.sinf"), '\u{F815}' => Some("one.sinf"), '\u{F816}' => Some("two.sinf"), '\u{F817}' => Some("three.sinf"), '\u{F818}' => Some("four.sinf"), '\u{F819}' => Some("five.sinf"), '\u{F81A}' => Some("six.sinf"), '\u{F81B}' => Some("seven.sinf"), '\u{F81C}' => Some("eight.sinf"), '\u{F81D}' => Some("nine.sinf"), _ => None, } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/src/demo/mod.rs
crates/egui_demo_lib/src/demo/mod.rs
//! Demo-code for showing how egui is used. //! //! The demo-code is also used in benchmarks and tests. // ---------------------------------------------------------------------------- pub mod about; pub mod code_editor; pub mod code_example; pub mod dancing_strings; pub mod demo_app_windows; pub mod drag_and_drop; pub mod extra_viewport; pub mod font_book; pub mod frame_demo; pub mod highlighting; pub mod interactive_container; pub mod misc_demo_window; pub mod modals; pub mod multi_touch; pub mod paint_bezier; pub mod painting; pub mod panels; pub mod password; mod popups; pub mod scene; pub mod screenshot; pub mod scrolling; pub mod sliders; pub mod strip_demo; pub mod table_demo; pub mod tests; pub mod text_edit; pub mod text_layout; pub mod toggle_switch; pub mod tooltips; pub mod undo_redo; pub mod widget_gallery; pub mod window_options; pub use { about::About, demo_app_windows::DemoWindows, misc_demo_window::MiscDemoWindow, widget_gallery::WidgetGallery, }; // ---------------------------------------------------------------------------- /// Something to view in the demo windows pub trait View { fn ui(&mut self, ui: &mut egui::Ui); } /// Something to view pub trait Demo { /// Is the demo enabled for this integration? fn is_enabled(&self, _ctx: &egui::Context) -> bool { true } /// `&'static` so we can also use it as a key to store open/close state. fn name(&self) -> &'static str; /// Show windows, etc fn show(&mut self, ui: &mut egui::Ui, open: &mut bool); }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/src/demo/code_example.rs
crates/egui_demo_lib/src/demo/code_example.rs
#[derive(Debug)] pub struct CodeExample { name: String, age: u32, } impl Default for CodeExample { fn default() -> Self { Self { name: "Arthur".to_owned(), age: 42, } } } impl CodeExample { fn samples_in_grid(&mut self, ui: &mut egui::Ui) { // Note: we keep the code narrow so that the example fits on a mobile screen. let Self { name, age } = self; // for brevity later on show_code(ui, r#"ui.heading("Example");"#); ui.heading("Example"); ui.end_row(); show_code( ui, r#" ui.horizontal(|ui| { ui.label("Name"); ui.text_edit_singleline(name); });"#, ); // Putting things on the same line using ui.horizontal: ui.horizontal(|ui| { ui.label("Name"); ui.text_edit_singleline(name); }); ui.end_row(); show_code( ui, r#" ui.add( egui::DragValue::new(age) .range(0..=120) .suffix(" years"), );"#, ); ui.add(egui::DragValue::new(age).range(0..=120).suffix(" years")); ui.end_row(); show_code( ui, r#" if ui.button("Increment").clicked() { *age += 1; }"#, ); if ui.button("Increment").clicked() { *age += 1; } ui.end_row(); #[expect(clippy::literal_string_with_formatting_args)] show_code(ui, r#"ui.label(format!("{name} is {age}"));"#); ui.label(format!("{name} is {age}")); ui.end_row(); } fn code(&mut self, ui: &mut egui::Ui) { show_code( ui, r" pub struct CodeExample { name: String, age: u32, } impl CodeExample { fn ui(&mut self, ui: &mut egui::Ui) { // Saves us from writing `&mut self.name` etc let Self { name, age } = self;", ); ui.horizontal(|ui| { let font_id = egui::TextStyle::Monospace.resolve(ui.style()); let indentation = 2.0 * 4.0 * ui.fonts_mut(|f| f.glyph_width(&font_id, ' ')); ui.add_space(indentation); egui::Grid::new("code_samples") .striped(true) .num_columns(2) .show(ui, |ui| { self.samples_in_grid(ui); }); }); crate::rust_view_ui(ui, " }\n}"); } } impl crate::Demo for CodeExample { fn name(&self) -> &'static str { "🖮 Code Example" } fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) { use crate::View as _; egui::Window::new(self.name()) .open(open) .min_width(375.0) .default_size([390.0, 500.0]) .scroll(false) .resizable([true, false]) // resizable so we can shrink if the text edit grows .constrain_to(ui.available_rect_before_wrap()) .show(ui, |ui| self.ui(ui)); } } impl crate::View for CodeExample { fn ui(&mut self, ui: &mut egui::Ui) { ui.scope(|ui| { ui.spacing_mut().item_spacing = egui::vec2(8.0, 6.0); self.code(ui); }); ui.separator(); crate::rust_view_ui(ui, &format!("{self:#?}")); ui.separator(); let mut theme = egui_extras::syntax_highlighting::CodeTheme::from_memory(ui.ctx(), ui.style()); ui.collapsing("Theme", |ui| { theme.ui(ui); theme.store_in_memory(ui.ctx()); }); ui.separator(); ui.vertical_centered(|ui| { ui.add(crate::egui_github_link_file!()); }); } } fn show_code(ui: &mut egui::Ui, code: &str) { let code = remove_leading_indentation(code.trim_start_matches('\n')); crate::rust_view_ui(ui, &code); } fn remove_leading_indentation(code: &str) -> String { fn is_indent(c: &u8) -> bool { matches!(*c, b' ' | b'\t') } let first_line_indent = code.bytes().take_while(is_indent).count(); let mut out = String::new(); let mut code = code; while !code.is_empty() { let indent = code.bytes().take_while(is_indent).count(); let start = first_line_indent.min(indent); let end = code .find('\n') .map_or_else(|| code.len(), |endline| endline + 1); out += &code[start..end]; code = &code[end..]; } out }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/src/demo/modals.rs
crates/egui_demo_lib/src/demo/modals.rs
use egui::{ComboBox, Id, Modal, ProgressBar, Ui, Widget as _, Window}; #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] pub struct Modals { user_modal_open: bool, save_modal_open: bool, save_progress: Option<f32>, role: &'static str, name: String, } impl Default for Modals { fn default() -> Self { Self { user_modal_open: false, save_modal_open: false, save_progress: None, role: Self::ROLES[0], name: "John Doe".to_owned(), } } } impl Modals { const ROLES: [&'static str; 2] = ["user", "admin"]; } impl crate::Demo for Modals { fn name(&self) -> &'static str { "🗖 Modals" } fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) { use crate::View as _; Window::new(self.name()) .open(open) .vscroll(false) .resizable(false) .constrain_to(ui.available_rect_before_wrap()) .show(ui, |ui| self.ui(ui)); } } impl crate::View for Modals { fn ui(&mut self, ui: &mut Ui) { let Self { user_modal_open, save_modal_open, save_progress, role, name, } = self; ui.horizontal(|ui| { if ui.button("Open User Modal").clicked() { *user_modal_open = true; } if ui.button("Open Save Modal").clicked() { *save_modal_open = true; } }); ui.label("Click one of the buttons to open a modal."); ui.label("Modals have a backdrop and prevent interaction with the rest of the UI."); ui.label( "You can show modals on top of each other and close the topmost modal with \ escape or by clicking outside the modal.", ); if *user_modal_open { let modal = Modal::new(Id::new("Modal A")).show(ui.ctx(), |ui| { ui.set_width(250.0); ui.heading("Edit User"); ui.label("Name:"); ui.text_edit_singleline(name); ComboBox::new("role", "Role") .selected_text(*role) .show_ui(ui, |ui| { for r in Self::ROLES { ui.selectable_value(role, r, r); } }); ui.separator(); egui::Sides::new().show( ui, |_ui| {}, |ui| { if ui.button("Save").clicked() { *save_modal_open = true; } if ui.button("Cancel").clicked() { // You can call `ui.close()` to close the modal. // (This causes the current modals `should_close` to return true) ui.close(); } }, ); }); if modal.should_close() { *user_modal_open = false; } } if *save_modal_open { let modal = Modal::new(Id::new("Modal B")).show(ui.ctx(), |ui| { ui.set_width(200.0); ui.heading("Save? Are you sure?"); ui.add_space(32.0); egui::Sides::new().show( ui, |_ui| {}, |ui| { if ui.button("Yes Please").clicked() { *save_progress = Some(0.0); } if ui.button("No Thanks").clicked() { ui.close(); } }, ); }); if modal.should_close() { *save_modal_open = false; } } if let Some(progress) = *save_progress { Modal::new(Id::new("Modal C")).show(ui.ctx(), |ui| { ui.set_width(70.0); ui.heading("Saving…"); ProgressBar::new(progress).ui(ui); if progress >= 1.0 { *save_progress = None; *save_modal_open = false; *user_modal_open = false; } else { *save_progress = Some(progress + 0.003); ui.request_repaint(); } }); } ui.vertical_centered(|ui| { ui.add(crate::egui_github_link_file!()); }); } } #[cfg(test)] mod tests { use crate::Demo as _; use crate::demo::modals::Modals; use egui::accesskit::Role; use egui::{Key, Popup}; use egui_kittest::kittest::Queryable as _; use egui_kittest::{Harness, SnapshotResults}; #[test] fn clicking_escape_when_popup_open_should_not_close_modal() { let initial_state = Modals { user_modal_open: true, ..Modals::default() }; let mut harness = Harness::new_ui_state( |ui, modals| { modals.show(ui, &mut true); }, initial_state, ); harness.get_by_role(Role::ComboBox).click(); // Harness::run would fail because we keep requesting repaints to simulate progress. harness.run_ok(); assert!(Popup::is_any_open(&harness.ctx)); assert!(harness.state().user_modal_open); harness.key_press(Key::Escape); harness.run_ok(); assert!(!Popup::is_any_open(&harness.ctx)); assert!(harness.state().user_modal_open); } #[test] fn escape_should_close_top_modal() { let initial_state = Modals { user_modal_open: true, save_modal_open: true, ..Modals::default() }; let mut harness = Harness::new_ui_state( |ui, modals| { modals.show(ui, &mut true); }, initial_state, ); assert!(harness.state().user_modal_open); assert!(harness.state().save_modal_open); harness.key_press(Key::Escape); harness.run(); assert!(harness.state().user_modal_open); assert!(!harness.state().save_modal_open); } #[test] fn should_match_snapshot() { let initial_state = Modals { user_modal_open: true, ..Modals::default() }; let mut harness = Harness::new_ui_state( |ui, modals| { modals.show(ui, &mut true); }, initial_state, ); let mut results = SnapshotResults::new(); harness.run(); results.add(harness.try_snapshot("modals_1")); harness.get_by_label("Save").click(); harness.run_ok(); results.add(harness.try_snapshot("modals_2")); harness.get_by_label("Yes Please").click(); harness.run_ok(); results.add(harness.try_snapshot("modals_3")); } // This tests whether the backdrop actually prevents interaction with lower layers. #[test] fn backdrop_should_prevent_focusing_lower_area() { let initial_state = Modals { save_modal_open: true, save_progress: Some(0.0), ..Modals::default() }; let mut harness = Harness::new_ui_state( |ui, modals| { modals.show(ui, &mut true); }, initial_state, ); harness.run_ok(); harness.get_by_label("Yes Please").click(); harness.run_ok(); // This snapshots should show the progress bar modal on top of the save modal. harness.snapshot("modals_backdrop_should_prevent_focusing_lower_area"); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/src/demo/misc_demo_window.rs
crates/egui_demo_lib/src/demo/misc_demo_window.rs
use std::sync::Arc; use super::{Demo, View}; use egui::{ Align, Align2, Checkbox, CollapsingHeader, Color32, ComboBox, FontId, Resize, RichText, Sense, Slider, Stroke, TextFormat, TextStyle, Ui, Vec2, Window, vec2, }; /// Showcase some ui code #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] pub struct MiscDemoWindow { num_columns: usize, widgets: Widgets, colors: ColorWidgets, custom_collapsing_header: CustomCollapsingHeader, tree: Tree, box_painting: BoxPainting, text_rotation: TextRotation, dummy_bool: bool, dummy_usize: usize, checklist: [bool; 3], } impl Default for MiscDemoWindow { fn default() -> Self { Self { num_columns: 2, widgets: Default::default(), colors: Default::default(), custom_collapsing_header: Default::default(), tree: Tree::demo(), box_painting: Default::default(), text_rotation: Default::default(), dummy_bool: false, dummy_usize: 0, checklist: std::array::from_fn(|i| i == 0), } } } impl Demo for MiscDemoWindow { fn name(&self) -> &'static str { "✨ Misc Demos" } fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) { Window::new(self.name()) .open(open) .vscroll(true) .hscroll(true) .constrain_to(ui.available_rect_before_wrap()) .show(ui, |ui| self.ui(ui)); } } impl View for MiscDemoWindow { fn ui(&mut self, ui: &mut Ui) { ui.set_min_width(250.0); CollapsingHeader::new("Label") .default_open(true) .show(ui, |ui| { label_ui(ui); }); CollapsingHeader::new("Misc widgets") .default_open(false) .show(ui, |ui| { self.widgets.ui(ui); }); CollapsingHeader::new("Text layout") .default_open(false) .show(ui, |ui| { text_layout_demo(ui); ui.vertical_centered(|ui| { ui.add(crate::egui_github_link_file_line!()); }); }); CollapsingHeader::new("Text rotation") .default_open(false) .show(ui, |ui| self.text_rotation.ui(ui)); CollapsingHeader::new("Colors") .default_open(false) .show(ui, |ui| { self.colors.ui(ui); }); CollapsingHeader::new("Custom Collapsing Header") .default_open(false) .show(ui, |ui| self.custom_collapsing_header.ui(ui)); CollapsingHeader::new("Tree") .default_open(false) .show(ui, |ui| self.tree.ui(ui)); CollapsingHeader::new("Checkboxes") .default_open(false) .show(ui, |ui| { ui.label("Checkboxes with empty labels take up very little space:"); ui.spacing_mut().item_spacing = Vec2::ZERO; ui.horizontal_wrapped(|ui| { for _ in 0..64 { ui.checkbox(&mut self.dummy_bool, ""); } }); ui.checkbox(&mut self.dummy_bool, "checkbox"); ui.label("Radiobuttons are similar:"); ui.spacing_mut().item_spacing = Vec2::ZERO; ui.horizontal_wrapped(|ui| { for i in 0..64 { ui.radio_value(&mut self.dummy_usize, i, ""); } }); ui.radio_value(&mut self.dummy_usize, 64, "radio_value"); ui.label("Checkboxes can be in an indeterminate state:"); let mut all_checked = self.checklist.iter().all(|item| *item); let any_checked = self.checklist.iter().any(|item| *item); let indeterminate = any_checked && !all_checked; if ui .add( Checkbox::new(&mut all_checked, "Check/uncheck all") .indeterminate(indeterminate), ) .changed() { for check in &mut self.checklist { *check = all_checked; } } for (i, checked) in self.checklist.iter_mut().enumerate() { ui.checkbox(checked, format!("Item {}", i + 1)); } }); ui.collapsing("Columns", |ui| { ui.add(Slider::new(&mut self.num_columns, 1..=10).text("Columns")); ui.columns(self.num_columns, |cols| { for (i, col) in cols.iter_mut().enumerate() { col.label(format!("Column {} out of {}", i + 1, self.num_columns)); if i + 1 == self.num_columns && col.button("Delete this").clicked() { self.num_columns -= 1; } } }); }); CollapsingHeader::new("Test box rendering") .default_open(false) .show(ui, |ui| self.box_painting.ui(ui)); CollapsingHeader::new("Resize") .default_open(false) .show(ui, |ui| { Resize::default().default_height(100.0).show(ui, |ui| { ui.label("This ui can be resized!"); ui.label("Just pull the handle on the bottom right"); }); }); CollapsingHeader::new("Ui Stack") .default_open(false) .show(ui, ui_stack_demo); CollapsingHeader::new("Misc") .default_open(false) .show(ui, |ui| { ui.horizontal(|ui| { ui.label("You can pretty easily paint your own small icons:"); use std::f32::consts::TAU; let size = Vec2::splat(16.0); let (response, painter) = ui.allocate_painter(size, Sense::hover()); let rect = response.rect; let c = rect.center(); let r = rect.width() / 2.0 - 1.0; let color = Color32::from_gray(128); let stroke = Stroke::new(1.0, color); painter.circle_stroke(c, r, stroke); painter.line_segment([c - vec2(0.0, r), c + vec2(0.0, r)], stroke); painter.line_segment([c, c + r * Vec2::angled(TAU * 1.0 / 8.0)], stroke); painter.line_segment([c, c + r * Vec2::angled(TAU * 3.0 / 8.0)], stroke); }); }); CollapsingHeader::new("Many circles of different sizes") .default_open(false) .show(ui, |ui| { ui.horizontal_wrapped(|ui| { for i in 0..100 { let r = i as f32 * 0.5; let size = Vec2::splat(2.0 * r + 5.0); let (rect, _response) = ui.allocate_at_least(size, Sense::hover()); ui.painter() .circle_filled(rect.center(), r, ui.visuals().text_color()); } }); }); } } // ---------------------------------------------------------------------------- fn label_ui(ui: &mut egui::Ui) { ui.vertical_centered(|ui| { ui.add(crate::egui_github_link_file_line!()); }); ui.horizontal_wrapped(|ui| { // Trick so we don't have to add spaces in the text below: let width = ui.fonts_mut(|f|f.glyph_width(&TextStyle::Body.resolve(ui.style()), ' ')); ui.spacing_mut().item_spacing.x = width; ui.label(RichText::new("Text can have").color(Color32::from_rgb(110, 255, 110))); ui.colored_label(Color32::from_rgb(128, 140, 255), "color"); // Shortcut version ui.label("and tooltips.").on_hover_text( "This is a multiline tooltip that demonstrates that you can easily add tooltips to any element.\nThis is the second line.\nThis is the third.", ); ui.label("You can mix in other widgets into text, like"); let _ = ui.small_button("this button"); ui.label("."); ui.label("The default font supports all latin and cyrillic characters (ИÅđ…), common math symbols (∫√∞²⅓…), and many emojis (💓🌟🖩…).") .on_hover_text("There is currently no support for right-to-left languages."); ui.label("See the 🔤 Font Book for more!"); ui.monospace("There is also a monospace font."); }); ui.add( egui::Label::new( "Labels containing long text can be set to elide the text that doesn't fit on a single line using `Label::truncate`. When hovered, the label will show the full text.", ) .truncate(), ); } // ---------------------------------------------------------------------------- #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] pub struct Widgets { angle: f32, password: String, } impl Default for Widgets { fn default() -> Self { Self { angle: std::f32::consts::TAU / 3.0, password: "hunter2".to_owned(), } } } impl Widgets { pub fn ui(&mut self, ui: &mut Ui) { let Self { angle, password } = self; ui.vertical_centered(|ui| { ui.add(crate::egui_github_link_file_line!()); }); ui.separator(); ui.horizontal(|ui| { ui.label("An angle:"); ui.drag_angle(angle); ui.label(format!("≈ {:.3}τ", *angle / std::f32::consts::TAU)) .on_hover_text("Each τ represents one turn (τ = 2π)"); }) .response .on_hover_text("The angle is stored in radians, but presented in degrees"); ui.separator(); ui.horizontal(|ui| { ui.hyperlink_to("Password:", super::password::url_to_file_source_code()) .on_hover_text("See the example code for how to use egui to store UI state"); ui.add(super::password::password(password)); }); } } // ---------------------------------------------------------------------------- #[derive(PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] struct ColorWidgets { srgba_unmul: [u8; 4], srgba_premul: [u8; 4], rgba_unmul: [f32; 4], rgba_premul: [f32; 4], } impl Default for ColorWidgets { fn default() -> Self { // Approximately the same color. Self { srgba_unmul: [0, 255, 183, 127], srgba_premul: [0, 187, 140, 127], rgba_unmul: [0.0, 1.0, 0.5, 0.5], rgba_premul: [0.0, 0.5, 0.25, 0.5], } } } impl ColorWidgets { fn ui(&mut self, ui: &mut Ui) { egui::reset_button(ui, self, "Reset"); ui.label("egui lets you edit colors stored as either sRGBA or linear RGBA and with or without premultiplied alpha"); let Self { srgba_unmul, srgba_premul, rgba_unmul, rgba_premul, } = self; ui.horizontal(|ui| { ui.color_edit_button_srgba_unmultiplied(srgba_unmul); ui.label(format!( "sRGBA: {} {} {} {}", srgba_unmul[0], srgba_unmul[1], srgba_unmul[2], srgba_unmul[3], )); }); ui.horizontal(|ui| { ui.color_edit_button_srgba_premultiplied(srgba_premul); ui.label(format!( "sRGBA with premultiplied alpha: {} {} {} {}", srgba_premul[0], srgba_premul[1], srgba_premul[2], srgba_premul[3], )); }); ui.horizontal(|ui| { ui.color_edit_button_rgba_unmultiplied(rgba_unmul); ui.label(format!( "Linear RGBA: {:.02} {:.02} {:.02} {:.02}", rgba_unmul[0], rgba_unmul[1], rgba_unmul[2], rgba_unmul[3], )); }); ui.horizontal(|ui| { ui.color_edit_button_rgba_premultiplied(rgba_premul); ui.label(format!( "Linear RGBA with premultiplied alpha: {:.02} {:.02} {:.02} {:.02}", rgba_premul[0], rgba_premul[1], rgba_premul[2], rgba_premul[3], )); }); } } // ---------------------------------------------------------------------------- #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] struct BoxPainting { size: Vec2, corner_radius: f32, stroke_width: f32, num_boxes: usize, } impl Default for BoxPainting { fn default() -> Self { Self { size: vec2(64.0, 32.0), corner_radius: 5.0, stroke_width: 2.0, num_boxes: 1, } } } impl BoxPainting { pub fn ui(&mut self, ui: &mut Ui) { ui.add(Slider::new(&mut self.size.x, 0.0..=500.0).text("width")); ui.add(Slider::new(&mut self.size.y, 0.0..=500.0).text("height")); ui.add(Slider::new(&mut self.corner_radius, 0.0..=50.0).text("corner_radius")); ui.add(Slider::new(&mut self.stroke_width, 0.0..=10.0).text("stroke_width")); ui.add(Slider::new(&mut self.num_boxes, 0..=8).text("num_boxes")); ui.horizontal_wrapped(|ui| { for _ in 0..self.num_boxes { let (rect, _response) = ui.allocate_at_least(self.size, Sense::hover()); ui.painter().rect( rect, self.corner_radius, ui.visuals().text_color().gamma_multiply(0.5), Stroke::new(self.stroke_width, Color32::WHITE), egui::StrokeKind::Inside, ); } }); } } // ---------------------------------------------------------------------------- #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] struct CustomCollapsingHeader { selected: bool, radio_value: bool, } impl Default for CustomCollapsingHeader { fn default() -> Self { Self { selected: true, radio_value: false, } } } impl CustomCollapsingHeader { pub fn ui(&mut self, ui: &mut egui::Ui) { ui.label("Example of a collapsing header with custom header:"); let id = ui.make_persistent_id("my_collapsing_header"); egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, true) .show_header(ui, |ui| { ui.toggle_value(&mut self.selected, "Click to select/unselect"); ui.radio_value(&mut self.radio_value, false, ""); ui.radio_value(&mut self.radio_value, true, ""); }) .body(|ui| { ui.label("The body is always custom"); }); CollapsingHeader::new("Normal collapsing header for comparison").show(ui, |ui| { ui.label("Nothing exciting here"); }); } } // ---------------------------------------------------------------------------- #[derive(Clone, Copy, PartialEq)] enum Action { Keep, Delete, } #[derive(Clone, Default)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] struct Tree(Vec<Self>); impl Tree { pub fn demo() -> Self { Self(vec![ Self(vec![Self::default(); 4]), Self(vec![Self(vec![Self::default(); 2]); 3]), ]) } pub fn ui(&mut self, ui: &mut Ui) -> Action { self.ui_impl(ui, 0, "root") } } impl Tree { fn ui_impl(&mut self, ui: &mut Ui, depth: usize, name: &str) -> Action { CollapsingHeader::new(name) .default_open(depth < 1) .show(ui, |ui| self.children_ui(ui, depth)) .body_returned .unwrap_or(Action::Keep) } fn children_ui(&mut self, ui: &mut Ui, depth: usize) -> Action { if depth > 0 && ui .button(RichText::new("delete").color(ui.visuals().warn_fg_color)) .clicked() { return Action::Delete; } self.0 = std::mem::take(self) .0 .into_iter() .enumerate() .filter_map(|(i, mut tree)| { if tree.ui_impl(ui, depth + 1, &format!("child #{i}")) == Action::Keep { Some(tree) } else { None } }) .collect(); if ui.button("+").clicked() { self.0.push(Self::default()); } Action::Keep } } // ---------------------------------------------------------------------------- fn ui_stack_demo(ui: &mut Ui) { ui.horizontal_wrapped(|ui| { ui.label("The"); ui.code("egui::Ui"); ui.label("core type is typically deeply nested in"); ui.code("egui"); ui.label( "applications. To provide context to nested code, it maintains a stack \ with various information.\n\nThis is how the stack looks like here:", ); }); let stack = Arc::clone(ui.stack()); egui::Frame::new() .inner_margin(ui.spacing().menu_margin) .stroke(ui.visuals().widgets.noninteractive.bg_stroke) .show(ui, |ui| { egui_extras::TableBuilder::new(ui) .column(egui_extras::Column::auto()) .column(egui_extras::Column::auto()) .header(18.0, |mut header| { header.col(|ui| { ui.strong("id"); }); header.col(|ui| { ui.strong("kind"); }); }) .body(|mut body| { for node in stack.iter() { body.row(18.0, |mut row| { row.col(|ui| { let response = ui.label(format!("{:?}", node.id)); if response.hovered() { ui.debug_painter().debug_rect( node.max_rect, Color32::GREEN, "max_rect", ); ui.debug_painter().circle_filled( node.min_rect.min, 2.0, Color32::RED, ); } }); row.col(|ui| { ui.label(if let Some(kind) = node.kind() { format!("{kind:?}") } else { "-".to_owned() }); }); }); } }); }); ui.small("Hover on UI's ids to display their origin and max rect."); } // ---------------------------------------------------------------------------- fn text_layout_demo(ui: &mut Ui) { use egui::text::LayoutJob; let mut job = LayoutJob::default(); let first_row_indentation = 10.0; let (default_color, strong_color) = if ui.visuals().dark_mode { (Color32::LIGHT_GRAY, Color32::WHITE) } else { (Color32::DARK_GRAY, Color32::BLACK) }; job.append( "This", first_row_indentation, TextFormat { color: default_color, font_id: FontId::proportional(20.0), ..Default::default() }, ); job.append( " is a demonstration of ", 0.0, TextFormat { color: default_color, ..Default::default() }, ); job.append( "the egui text layout engine. ", 0.0, TextFormat { color: strong_color, ..Default::default() }, ); job.append( "It supports ", 0.0, TextFormat { color: default_color, ..Default::default() }, ); job.append( "different ", 0.0, TextFormat { color: Color32::from_rgb(110, 255, 110), ..Default::default() }, ); job.append( "colors, ", 0.0, TextFormat { color: Color32::from_rgb(128, 140, 255), ..Default::default() }, ); job.append( "backgrounds, ", 0.0, TextFormat { color: default_color, background: Color32::from_rgb(128, 32, 32), ..Default::default() }, ); job.append( "mixing ", 0.0, TextFormat { font_id: FontId::proportional(20.0), color: default_color, ..Default::default() }, ); job.append( "fonts, ", 0.0, TextFormat { font_id: FontId::monospace(12.0), color: default_color, ..Default::default() }, ); job.append( "raised text, ", 0.0, TextFormat { font_id: FontId::proportional(7.0), color: default_color, valign: Align::TOP, ..Default::default() }, ); job.append( "with ", 0.0, TextFormat { color: default_color, ..Default::default() }, ); job.append( "underlining", 0.0, TextFormat { color: default_color, underline: Stroke::new(1.0, Color32::LIGHT_BLUE), ..Default::default() }, ); job.append( " and ", 0.0, TextFormat { color: default_color, ..Default::default() }, ); job.append( "strikethrough", 0.0, TextFormat { color: default_color, strikethrough: Stroke::new(2.0, Color32::RED.linear_multiply(0.5)), ..Default::default() }, ); job.append( ". Of course, ", 0.0, TextFormat { color: default_color, ..Default::default() }, ); job.append( "you can", 0.0, TextFormat { color: default_color, strikethrough: Stroke::new(1.0, strong_color), ..Default::default() }, ); job.append( " mix these!", 0.0, TextFormat { font_id: FontId::proportional(7.0), color: Color32::LIGHT_BLUE, background: Color32::from_rgb(128, 0, 0), underline: Stroke::new(1.0, strong_color), ..Default::default() }, ); ui.label(job); } // ---------------------------------------------------------------------------- #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] struct TextRotation { size: Vec2, angle: f32, align: egui::Align2, } impl Default for TextRotation { fn default() -> Self { Self { size: vec2(200.0, 200.0), angle: 0.0, align: egui::Align2::LEFT_TOP, } } } impl TextRotation { pub fn ui(&mut self, ui: &mut Ui) { ui.add(Slider::new(&mut self.angle, 0.0..=2.0 * std::f32::consts::PI).text("angle")); let default_color = if ui.visuals().dark_mode { Color32::LIGHT_GRAY } else { Color32::DARK_GRAY }; let aligns = [ (Align2::LEFT_TOP, "LEFT_TOP"), (Align2::LEFT_CENTER, "LEFT_CENTER"), (Align2::LEFT_BOTTOM, "LEFT_BOTTOM"), (Align2::CENTER_TOP, "CENTER_TOP"), (Align2::CENTER_CENTER, "CENTER_CENTER"), (Align2::CENTER_BOTTOM, "CENTER_BOTTOM"), (Align2::RIGHT_TOP, "RIGHT_TOP"), (Align2::RIGHT_CENTER, "RIGHT_CENTER"), (Align2::RIGHT_BOTTOM, "RIGHT_BOTTOM"), ]; ComboBox::new("anchor", "Anchor") .selected_text(aligns.iter().find(|(a, _)| *a == self.align).unwrap().1) .show_ui(ui, |ui| { for (align2, name) in &aligns { ui.selectable_value(&mut self.align, *align2, *name); } }); ui.horizontal_wrapped(|ui| { let (response, painter) = ui.allocate_painter(self.size, Sense::empty()); let rect = response.rect; let start_pos = self.size / 2.0; let s = ui.ctx().fonts_mut(|f| { let mut t = egui::Shape::text( f, rect.min + start_pos, egui::Align2::LEFT_TOP, "sample_text", egui::FontId::new(12.0, egui::FontFamily::Proportional), default_color, ); if let egui::epaint::Shape::Text(ts) = &mut t { let new = ts.clone().with_angle_and_anchor(self.angle, self.align); *ts = new; } t }); if let egui::epaint::Shape::Text(ts) = &s { let align_pt = rect.min + start_pos + self.align.pos_in_rect(&ts.galley.rect).to_vec2(); painter.circle(align_pt, 2.0, Color32::RED, (0.0, Color32::RED)); } painter.rect( rect, 0.0, default_color.gamma_multiply(0.3), (0.0, Color32::BLACK), egui::StrokeKind::Middle, ); painter.add(s); }); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/src/demo/text_edit.rs
crates/egui_demo_lib/src/demo/text_edit.rs
/// Showcase [`egui::TextEdit`]. #[derive(PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] pub struct TextEditDemo { pub text: String, } impl Default for TextEditDemo { fn default() -> Self { Self { text: "Edit this text".to_owned(), } } } impl crate::Demo for TextEditDemo { fn name(&self) -> &'static str { "🖹 TextEdit" } fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) { egui::Window::new(self.name()) .open(open) .resizable(false) .constrain_to(ui.available_rect_before_wrap()) .show(ui, |ui| { use crate::View as _; self.ui(ui); }); } } impl crate::View for TextEditDemo { fn ui(&mut self, ui: &mut egui::Ui) { ui.vertical_centered(|ui| { ui.add(crate::egui_github_link_file!()); }); let Self { text } = self; ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = 0.0; ui.label("Advanced usage of "); ui.code("TextEdit"); ui.label("."); }); let output = egui::TextEdit::multiline(text) .hint_text("Type something!") .show(ui); ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = 0.0; ui.label("Selected text: "); if let Some(text_cursor_range) = output.cursor_range { let selected_text = text_cursor_range.slice_str(text); ui.code(selected_text); } }); let anything_selected = output.cursor_range.is_some_and(|cursor| !cursor.is_empty()); ui.add_enabled( anything_selected, egui::Label::new("Press ctrl+Y to toggle the case of selected text (cmd+Y on Mac)"), ); if ui.input_mut(|i| i.consume_key(egui::Modifiers::COMMAND, egui::Key::Y)) && let Some(text_cursor_range) = output.cursor_range { use egui::TextBuffer as _; let selected_chars = text_cursor_range.as_sorted_char_range(); let selected_text = text.char_range(selected_chars.clone()); let upper_case = selected_text.to_uppercase(); let new_text = if selected_text == upper_case { selected_text.to_lowercase() } else { upper_case }; text.delete_char_range(selected_chars.clone()); text.insert_text(&new_text, selected_chars.start); } ui.horizontal(|ui| { ui.label("Move cursor to the:"); if ui.button("start").clicked() { let text_edit_id = output.response.id; if let Some(mut state) = egui::TextEdit::load_state(ui.ctx(), text_edit_id) { let ccursor = egui::text::CCursor::new(0); state .cursor .set_char_range(Some(egui::text::CCursorRange::one(ccursor))); state.store(ui.ctx(), text_edit_id); ui.memory_mut(|mem| mem.request_focus(text_edit_id)); // give focus back to the [`TextEdit`]. } } if ui.button("end").clicked() { let text_edit_id = output.response.id; if let Some(mut state) = egui::TextEdit::load_state(ui.ctx(), text_edit_id) { let ccursor = egui::text::CCursor::new(text.chars().count()); state .cursor .set_char_range(Some(egui::text::CCursorRange::one(ccursor))); state.store(ui.ctx(), text_edit_id); ui.memory_mut(|mem| mem.request_focus(text_edit_id)); // give focus back to the [`TextEdit`]. } } }); } } #[cfg(test)] mod tests { use egui::{CentralPanel, Key, Modifiers, accesskit}; use egui_kittest::Harness; use egui_kittest::kittest::Queryable as _; #[test] pub fn should_type() { let text = "Hello, world!".to_owned(); let mut harness = Harness::new_ui_state( move |ui, text| { CentralPanel::default().show_inside(ui, |ui| { ui.text_edit_singleline(text); }); }, text, ); harness.run(); let text_edit = harness.get_by_role(accesskit::Role::TextInput); assert_eq!(text_edit.value().as_deref(), Some("Hello, world!")); text_edit.focus(); harness.key_press_modifiers(Modifiers::COMMAND, Key::A); text_edit.type_text("Hi "); harness.run(); harness .get_by_role(accesskit::Role::TextInput) .type_text("there!"); harness.run(); let text_edit = harness.get_by_role(accesskit::Role::TextInput); assert_eq!(text_edit.value().as_deref(), Some("Hi there!")); assert_eq!(harness.state(), "Hi there!"); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/src/demo/widget_gallery.rs
crates/egui_demo_lib/src/demo/widget_gallery.rs
#[derive(Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] enum Enum { First, Second, Third, } /// Shows off one example of each major type of widget. #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct WidgetGallery { enabled: bool, visible: bool, boolean: bool, opacity: f32, radio: Enum, scalar: f32, string: String, color: egui::Color32, animate_progress_bar: bool, #[cfg(feature = "chrono")] #[cfg_attr(feature = "serde", serde(skip))] date: Option<chrono::NaiveDate>, #[cfg(feature = "chrono")] with_date_button: bool, } impl Default for WidgetGallery { fn default() -> Self { Self { enabled: true, visible: true, opacity: 1.0, boolean: false, radio: Enum::First, scalar: 42.0, string: Default::default(), color: egui::Color32::LIGHT_BLUE.linear_multiply(0.5), animate_progress_bar: false, #[cfg(feature = "chrono")] date: None, #[cfg(feature = "chrono")] with_date_button: true, } } } impl WidgetGallery { #[allow(clippy::allow_attributes, unused_mut)] // if not chrono #[inline] pub fn with_date_button(mut self, _with_date_button: bool) -> Self { #[cfg(feature = "chrono")] { self.with_date_button = _with_date_button; } self } } impl crate::Demo for WidgetGallery { fn name(&self) -> &'static str { "🗄 Widget Gallery" } fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) { egui::Window::new(self.name()) .open(open) .resizable([true, false]) // resizable so we can shrink if the text edit grows .default_width(280.0) .constrain_to(ui.available_rect_before_wrap()) .show(ui, |ui| { use crate::View as _; self.ui(ui); }); } } impl crate::View for WidgetGallery { fn ui(&mut self, ui: &mut egui::Ui) { let mut ui_builder = egui::UiBuilder::new(); if !self.enabled { ui_builder = ui_builder.disabled(); } if !self.visible { ui_builder = ui_builder.invisible(); } ui.scope_builder(ui_builder, |ui| { ui.multiply_opacity(self.opacity); egui::Grid::new("my_grid") .num_columns(2) .spacing([40.0, 4.0]) .striped(true) .show(ui, |ui| { self.gallery_grid_contents(ui); }); }); ui.separator(); ui.horizontal(|ui| { ui.checkbox(&mut self.visible, "Visible") .on_hover_text("Uncheck to hide all the widgets."); if self.visible { ui.checkbox(&mut self.enabled, "Interactive") .on_hover_text("Uncheck to inspect how the widgets look when disabled."); (ui.add( egui::DragValue::new(&mut self.opacity) .speed(0.01) .range(0.0..=1.0), ) | ui.label("Opacity")) .on_hover_text("Reduce this value to make widgets semi-transparent"); } }); ui.separator(); ui.vertical_centered(|ui| { let tooltip_text = "The full egui documentation.\nYou can also click the different widgets names in the left column."; ui.hyperlink("https://docs.rs/egui/").on_hover_text(tooltip_text); ui.add(crate::egui_github_link_file!( "Source code of the widget gallery" )); }); } } impl WidgetGallery { fn gallery_grid_contents(&mut self, ui: &mut egui::Ui) { let Self { enabled: _, visible: _, opacity: _, boolean, radio, scalar, string, color, animate_progress_bar, #[cfg(feature = "chrono")] date, #[cfg(feature = "chrono")] with_date_button, } = self; ui.add(doc_link_label("Label", "label")); ui.label("Welcome to the widget gallery!"); ui.end_row(); ui.add(doc_link_label("Hyperlink", "Hyperlink")); use egui::special_emojis::GITHUB; ui.hyperlink_to( format!("{GITHUB} egui on GitHub"), "https://github.com/emilk/egui", ); ui.end_row(); ui.add(doc_link_label("TextEdit", "TextEdit")); ui.add(egui::TextEdit::singleline(string).hint_text("Write something here")); ui.end_row(); ui.add(doc_link_label("Button", "button")); if ui.button("Click me!").clicked() { *boolean = !*boolean; } ui.end_row(); ui.add(doc_link_label("Link", "link")); if ui.link("Click me!").clicked() { *boolean = !*boolean; } ui.end_row(); ui.add(doc_link_label("Checkbox", "checkbox")); ui.checkbox(boolean, "Checkbox"); ui.end_row(); ui.add(doc_link_label("RadioButton", "radio")); ui.horizontal(|ui| { ui.radio_value(radio, Enum::First, "First"); ui.radio_value(radio, Enum::Second, "Second"); ui.radio_value(radio, Enum::Third, "Third"); }); ui.end_row(); ui.add(doc_link_label("SelectableLabel", "SelectableLabel")); ui.horizontal(|ui| { ui.selectable_value(radio, Enum::First, "First"); ui.selectable_value(radio, Enum::Second, "Second"); ui.selectable_value(radio, Enum::Third, "Third"); }); ui.end_row(); ui.add(doc_link_label("ComboBox", "ComboBox")); egui::ComboBox::from_label("Take your pick") .selected_text(format!("{radio:?}")) .show_ui(ui, |ui| { ui.selectable_value(radio, Enum::First, "First"); ui.selectable_value(radio, Enum::Second, "Second"); ui.selectable_value(radio, Enum::Third, "Third"); }); ui.end_row(); ui.add(doc_link_label("Slider", "Slider")); ui.add(egui::Slider::new(scalar, 0.0..=360.0).suffix("°")); ui.end_row(); ui.add(doc_link_label("DragValue", "DragValue")); ui.add(egui::DragValue::new(scalar).speed(1.0)); ui.end_row(); ui.add(doc_link_label("ProgressBar", "ProgressBar")); let progress = *scalar / 360.0; let progress_bar = egui::ProgressBar::new(progress) .show_percentage() .animate(*animate_progress_bar); *animate_progress_bar = ui .add(progress_bar) .on_hover_text("The progress bar can be animated!") .hovered(); ui.end_row(); ui.add(doc_link_label("Color picker", "color_edit")); ui.color_edit_button_srgba(color); ui.end_row(); ui.add(doc_link_label("Image", "Image")); let egui_icon = egui::include_image!("../../data/icon.png"); ui.add(egui::Image::new(egui_icon.clone())); ui.end_row(); ui.add(doc_link_label( "Button with image", "Button::image_and_text", )); if ui .add(egui::Button::image_and_text(egui_icon, "Click me!")) .clicked() { *boolean = !*boolean; } ui.end_row(); #[cfg(feature = "chrono")] if *with_date_button { let date = date.get_or_insert_with(|| chrono::offset::Utc::now().date_naive()); ui.add(doc_link_label_with_crate( "egui_extras", "DatePickerButton", "DatePickerButton", )); ui.add(egui_extras::DatePickerButton::new(date)); ui.end_row(); } ui.add(doc_link_label("Separator", "separator")); ui.separator(); ui.end_row(); ui.add(doc_link_label("CollapsingHeader", "collapsing")); ui.collapsing("Click to see what is hidden!", |ui| { ui.horizontal_wrapped(|ui| { ui.spacing_mut().item_spacing.x = 0.0; ui.label("It's a "); ui.add(doc_link_label("Spinner", "spinner")); ui.add_space(4.0); ui.add(egui::Spinner::new()); }); }); ui.end_row(); ui.hyperlink_to( "Custom widget", super::toggle_switch::url_to_file_source_code(), ); ui.add(super::toggle_switch::toggle(boolean)).on_hover_text( "It's easy to create your own widgets!\n\ This toggle switch is just 15 lines of code.", ); ui.end_row(); } } fn doc_link_label<'a>(title: &'a str, search_term: &'a str) -> impl egui::Widget + 'a { doc_link_label_with_crate("egui", title, search_term) } fn doc_link_label_with_crate<'a>( crate_name: &'a str, title: &'a str, search_term: &'a str, ) -> impl egui::Widget + 'a { let url = format!("https://docs.rs/{crate_name}?search={search_term}"); move |ui: &mut egui::Ui| { ui.hyperlink_to(title, url).on_hover_ui(|ui| { ui.horizontal_wrapped(|ui| { ui.label("Search egui docs for"); ui.code(search_term); }); }) } } #[cfg(feature = "chrono")] #[cfg(test)] mod tests { use super::*; use crate::View as _; use egui::Vec2; use egui_kittest::{Harness, SnapshotResults}; #[test] pub fn should_match_screenshot() { let mut demo = WidgetGallery { // If we don't set a fixed date, the snapshot test will fail. date: Some(chrono::NaiveDate::from_ymd_opt(2024, 1, 1).unwrap()), ..Default::default() }; let mut results = SnapshotResults::new(); for pixels_per_point in [1, 2] { for theme in [egui::Theme::Light, egui::Theme::Dark] { let mut harness = Harness::builder() .with_pixels_per_point(pixels_per_point as f32) .with_theme(theme) .with_size(Vec2::new(380.0, 550.0)) .build_ui(|ui| { egui_extras::install_image_loaders(ui.ctx()); demo.ui(ui); }); harness.fit_contents(); let theme_name = match theme { egui::Theme::Light => "light", egui::Theme::Dark => "dark", }; let image_name = format!("widget_gallery_{theme_name}_x{pixels_per_point}"); harness.snapshot(&image_name); results.extend_harness(&mut harness); } } } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/src/demo/sliders.rs
crates/egui_demo_lib/src/demo/sliders.rs
use egui::{Slider, SliderClamping, SliderOrientation, Ui, style::HandleShape}; /// Showcase sliders #[derive(PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] pub struct Sliders { pub min: f64, pub max: f64, pub logarithmic: bool, pub clamping: SliderClamping, pub smart_aim: bool, pub step: f64, pub use_steps: bool, pub integer: bool, pub vertical: bool, pub value: f64, pub trailing_fill: bool, pub handle_shape: HandleShape, } impl Default for Sliders { fn default() -> Self { Self { min: 0.0, max: 10000.0, logarithmic: true, clamping: SliderClamping::Always, smart_aim: true, step: 10.0, use_steps: false, integer: false, vertical: false, value: 10.0, trailing_fill: false, handle_shape: HandleShape::Circle, } } } impl crate::Demo for Sliders { fn name(&self) -> &'static str { "⬌ Sliders" } fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) { egui::Window::new(self.name()) .open(open) .resizable(false) .constrain_to(ui.available_rect_before_wrap()) .show(ui, |ui| { use crate::View as _; self.ui(ui); }); } } impl crate::View for Sliders { fn ui(&mut self, ui: &mut Ui) { let Self { min, max, logarithmic, clamping, smart_aim, step, use_steps, integer, vertical, value, trailing_fill, handle_shape, } = self; ui.label("You can click a slider value to edit it with the keyboard."); let (type_min, type_max) = if *integer { ((i32::MIN as f64), (i32::MAX as f64)) } else if *logarithmic { (-f64::INFINITY, f64::INFINITY) } else { (-1e5, 1e5) // linear sliders make little sense with huge numbers }; *min = min.clamp(type_min, type_max); *max = max.clamp(type_min, type_max); let orientation = if *vertical { SliderOrientation::Vertical } else { SliderOrientation::Horizontal }; let istep = if *use_steps { *step } else { 0.0 }; if *integer { let mut value_i32 = *value as i32; ui.add( Slider::new(&mut value_i32, (*min as i32)..=(*max as i32)) .logarithmic(*logarithmic) .clamping(*clamping) .smart_aim(*smart_aim) .orientation(orientation) .text("i32 demo slider") .step_by(istep) .trailing_fill(*trailing_fill) .handle_shape(*handle_shape), ); *value = value_i32 as f64; } else { ui.add( Slider::new(value, (*min)..=(*max)) .logarithmic(*logarithmic) .clamping(*clamping) .smart_aim(*smart_aim) .orientation(orientation) .text("f64 demo slider") .step_by(istep) .trailing_fill(*trailing_fill) .handle_shape(*handle_shape), ); ui.label( "Sliders will intelligently pick how many decimals to show. \ You can always see the full precision value by hovering the value.", ); if ui.button("Assign PI").clicked() { self.value = std::f64::consts::PI; } } ui.separator(); ui.label("Slider range:"); ui.add( Slider::new(min, type_min..=type_max) .logarithmic(true) .smart_aim(*smart_aim) .text("left") .trailing_fill(*trailing_fill) .handle_shape(*handle_shape), ); ui.add( Slider::new(max, type_min..=type_max) .logarithmic(true) .smart_aim(*smart_aim) .text("right") .trailing_fill(*trailing_fill) .handle_shape(*handle_shape), ); ui.separator(); ui.checkbox(trailing_fill, "Toggle trailing color"); ui.label("When enabled, trailing color will be painted up until the handle."); ui.separator(); handle_shape.ui(ui); ui.separator(); ui.checkbox(use_steps, "Use steps"); ui.label("When enabled, the minimal value change would be restricted to a given step."); if *use_steps { ui.add(egui::DragValue::new(step).speed(1.0)); } ui.separator(); ui.horizontal(|ui| { ui.label("Slider type:"); ui.radio_value(integer, true, "i32"); ui.radio_value(integer, false, "f64"); }) .response .on_hover_text("All numeric types (f32, usize, …) are supported."); ui.horizontal(|ui| { ui.label("Slider orientation:"); ui.radio_value(vertical, false, "Horizontal"); ui.radio_value(vertical, true, "Vertical"); }); ui.add_space(8.0); ui.checkbox(logarithmic, "Logarithmic"); ui.label("Logarithmic sliders are great for when you want to span a huge range, i.e. from zero to a million."); ui.label("Logarithmic sliders can include infinity and zero."); ui.add_space(8.0); ui.horizontal(|ui| { ui.label("Clamping:"); ui.selectable_value(clamping, SliderClamping::Never, "Never"); ui.selectable_value(clamping, SliderClamping::Edits, "Edits"); ui.selectable_value(clamping, SliderClamping::Always, "Always"); }); ui.label("If true, the slider will clamp incoming and outgoing values to the given range."); ui.label("If false, the slider can show values outside its range, and you cannot enter new values outside the range."); ui.add_space(8.0); ui.checkbox(smart_aim, "Smart Aim"); ui.label("Smart Aim will guide you towards round values when you drag the slider so you you are more likely to hit 250 than 247.23"); ui.add_space(8.0); ui.vertical_centered(|ui| { egui::reset_button(ui, self, "Reset"); ui.add(crate::egui_github_link_file!()); }); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/src/demo/paint_bezier.rs
crates/egui_demo_lib/src/demo/paint_bezier.rs
use egui::{ Color32, Frame, Grid, Pos2, Rect, Sense, Shape, Stroke, StrokeKind, Ui, Vec2, Widget as _, Window, emath, epaint::{self, CubicBezierShape, PathShape, QuadraticBezierShape}, pos2, }; #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] pub struct PaintBezier { /// Bézier curve degree, it can be 3, 4. degree: usize, /// The control points. The [`Self::degree`] first of them are used. control_points: [Pos2; 4], /// Stroke for Bézier curve. stroke: Stroke, /// Fill for Bézier curve. fill: Color32, /// Stroke for auxiliary lines. aux_stroke: Stroke, bounding_box_stroke: Stroke, } impl Default for PaintBezier { fn default() -> Self { Self { degree: 4, control_points: [ pos2(50.0, 50.0), pos2(60.0, 250.0), pos2(200.0, 200.0), pos2(250.0, 50.0), ], stroke: Stroke::new(1.0, Color32::from_rgb(25, 200, 100)), fill: Color32::from_rgb(50, 100, 150).linear_multiply(0.25), aux_stroke: Stroke::new(1.0, Color32::RED.linear_multiply(0.25)), bounding_box_stroke: Stroke::new(0.0, Color32::LIGHT_GREEN.linear_multiply(0.25)), } } } impl PaintBezier { pub fn ui_control(&mut self, ui: &mut egui::Ui) { ui.collapsing("Colors", |ui| { Grid::new("colors") .num_columns(2) .spacing([12.0, 8.0]) .striped(true) .show(ui, |ui| { ui.label("Fill color"); ui.color_edit_button_srgba(&mut self.fill); ui.end_row(); ui.label("Curve Stroke"); ui.add(&mut self.stroke); ui.end_row(); ui.label("Auxiliary Stroke"); ui.add(&mut self.aux_stroke); ui.end_row(); ui.label("Bounding Box Stroke"); ui.add(&mut self.bounding_box_stroke); ui.end_row(); }); }); ui.collapsing("Global tessellation options", |ui| { let mut tessellation_options = ui.ctx().tessellation_options(|to| *to); tessellation_options.ui(ui); ui.tessellation_options_mut(|to| *to = tessellation_options); }); ui.radio_value(&mut self.degree, 3, "Quadratic Bézier"); ui.radio_value(&mut self.degree, 4, "Cubic Bézier"); ui.label("Move the points by dragging them."); ui.small("Only convex curves can be accurately filled."); } pub fn ui_content(&mut self, ui: &mut Ui) -> egui::Response { let (response, painter) = ui.allocate_painter(Vec2::new(ui.available_width(), 300.0), Sense::hover()); let to_screen = emath::RectTransform::from_to( Rect::from_min_size(Pos2::ZERO, response.rect.size()), response.rect, ); let control_point_radius = 8.0; let control_point_shapes: Vec<Shape> = self .control_points .iter_mut() .enumerate() .take(self.degree) .map(|(i, point)| { let size = Vec2::splat(2.0 * control_point_radius); let point_in_screen = to_screen.transform_pos(*point); let point_rect = Rect::from_center_size(point_in_screen, size); let point_id = response.id.with(i); let point_response = ui.interact(point_rect, point_id, Sense::drag()); *point += point_response.drag_delta(); *point = to_screen.from().clamp(*point); let point_in_screen = to_screen.transform_pos(*point); let stroke = ui.style().interact(&point_response).fg_stroke; Shape::circle_stroke(point_in_screen, control_point_radius, stroke) }) .collect(); let points_in_screen: Vec<Pos2> = self .control_points .iter() .take(self.degree) .map(|p| to_screen * *p) .collect(); match self.degree { 3 => { let points = points_in_screen.clone().try_into().unwrap(); let shape = QuadraticBezierShape::from_points_stroke(points, true, self.fill, self.stroke); painter.add(epaint::RectShape::stroke( shape.visual_bounding_rect(), 0.0, self.bounding_box_stroke, StrokeKind::Outside, )); painter.add(shape); } 4 => { let points = points_in_screen.clone().try_into().unwrap(); let shape = CubicBezierShape::from_points_stroke(points, true, self.fill, self.stroke); painter.add(epaint::RectShape::stroke( shape.visual_bounding_rect(), 0.0, self.bounding_box_stroke, StrokeKind::Outside, )); painter.add(shape); } _ => { unreachable!(); } } painter.add(PathShape::line(points_in_screen, self.aux_stroke)); painter.extend(control_point_shapes); response } } impl crate::Demo for PaintBezier { fn name(&self) -> &'static str { ") Bézier Curve" } fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) { use crate::View as _; Window::new(self.name()) .open(open) .vscroll(false) .resizable(false) .default_size([300.0, 350.0]) .constrain_to(ui.available_rect_before_wrap()) .show(ui, |ui| self.ui(ui)); } } impl crate::View for PaintBezier { fn ui(&mut self, ui: &mut Ui) { ui.vertical_centered(|ui| { ui.add(crate::egui_github_link_file!()); }); self.ui_control(ui); Frame::canvas(ui.style()).show(ui, |ui| { self.ui_content(ui); }); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/src/demo/interactive_container.rs
crates/egui_demo_lib/src/demo/interactive_container.rs
use egui::{Frame, Label, RichText, Sense, UiBuilder, Widget as _}; /// Showcase [`egui::Ui::response`]. #[derive(PartialEq, Eq, Default)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] pub struct InteractiveContainerDemo { count: usize, } impl crate::Demo for InteractiveContainerDemo { fn name(&self) -> &'static str { "\u{20E3} Interactive Container" } fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) { egui::Window::new(self.name()) .open(open) .resizable(false) .default_width(250.0) .constrain_to(ui.available_rect_before_wrap()) .show(ui, |ui| { use crate::View as _; self.ui(ui); }); } } impl crate::View for InteractiveContainerDemo { fn ui(&mut self, ui: &mut egui::Ui) { ui.vertical_centered(|ui| { ui.add(crate::egui_github_link_file!()); }); ui.horizontal_wrapped(|ui| { ui.spacing_mut().item_spacing.x = 0.0; ui.label("This demo showcases how to use "); ui.code("Ui::response"); ui.label(" to create interactive container widgets that may contain other widgets."); }); let response = ui .scope_builder( UiBuilder::new() .id_salt("interactive_container") .sense(Sense::click()), |ui| { let response = ui.response(); let visuals = ui.style().interact(&response); let text_color = visuals.text_color(); Frame::canvas(ui.style()) .fill(visuals.bg_fill.gamma_multiply(0.3)) .stroke(visuals.bg_stroke) .inner_margin(ui.spacing().menu_margin) .show(ui, |ui| { ui.set_width(ui.available_width()); ui.add_space(32.0); ui.vertical_centered(|ui| { Label::new( RichText::new(format!("{}", self.count)) .color(text_color) .size(32.0), ) .selectable(false) .ui(ui); }); ui.add_space(32.0); ui.horizontal(|ui| { if ui.button("Reset").clicked() { self.count = 0; } if ui.button("+ 100").clicked() { self.count += 100; } }); }); }, ) .response; if response.clicked() { self.count += 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_lib/src/demo/extra_viewport.rs
crates/egui_demo_lib/src/demo/extra_viewport.rs
#[derive(Default)] pub struct ExtraViewport {} impl crate::Demo for ExtraViewport { fn is_enabled(&self, ctx: &egui::Context) -> bool { !ctx.embed_viewports() } fn name(&self) -> &'static str { "🗖 Extra Viewport" } fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) { if !*open { return; } let id = egui::Id::new(self.name()); ui.show_viewport_immediate( egui::ViewportId(id), egui::ViewportBuilder::default() .with_title(self.name()) .with_inner_size([400.0, 512.0]), |ui, class| { if class == egui::ViewportClass::EmbeddedWindow { // Not a real viewport ui.label("This egui integration does not support multiple viewports"); } else { egui::CentralPanel::default().show_inside(ui, |ui| { viewport_content(ui, open); }); } }, ); } } fn viewport_content(ui: &mut egui::Ui, open: &mut bool) { ui.label("egui and eframe supports having multiple native windows like this, which egui calls 'viewports'."); ui.label(format!( "This viewport has id: {:?}, child of viewport {:?}", ui.viewport_id(), ui.parent_viewport_id() )); ui.label("Here you can see all the open viewports:"); egui::ScrollArea::vertical().show(ui, |ui| { let viewports = ui.input(|i| i.raw.viewports.clone()); let ordered_viewports = viewports .iter() .map(|(id, viewport)| (*id, viewport.clone())) .collect::<egui::OrderedViewportIdMap<_>>(); for (id, viewport) in ordered_viewports { ui.group(|ui| { ui.label(format!("viewport {id:?}")); ui.push_id(id, |ui| { viewport.ui(ui); }); }); } }); if ui.input(|i| i.viewport().close_requested()) { *open = false; } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/src/demo/tooltips.rs
crates/egui_demo_lib/src/demo/tooltips.rs
#[derive(Clone, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct Tooltips { enabled: bool, } impl Default for Tooltips { fn default() -> Self { Self { enabled: true } } } impl crate::Demo for Tooltips { fn name(&self) -> &'static str { "🗖 Tooltips" } fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) { use crate::View as _; egui::Window::new("Tooltips") .constrain(false) // So we can test how tooltips behave close to the screen edge .resizable(true) .default_size([450.0, 300.0]) .scroll(false) .open(open) .constrain_to(ui.available_rect_before_wrap()) .show(ui, |ui| self.ui(ui)); } } impl crate::View for Tooltips { fn ui(&mut self, ui: &mut egui::Ui) { ui.spacing_mut().item_spacing.y = 8.0; ui.vertical_centered(|ui| { ui.add(crate::egui_github_link_file_line!()); }); egui::Panel::right("scroll_test").show_inside(ui, |ui| { ui.label( "The scroll area below has many labels with interactive tooltips. \ The purpose is to test that the tooltips close when you scroll.", ) .on_hover_text("Try hovering a label below, then scroll!"); egui::ScrollArea::vertical() .auto_shrink(false) .show(ui, |ui| { for i in 0..1000 { ui.label(format!("This is line {i}")).on_hover_ui(|ui| { ui.style_mut().interaction.selectable_labels = true; ui.label( "This tooltip is interactive, because the text in it is selectable.", ); }); } }); }); egui::CentralPanel::default().show_inside(ui, |ui| { self.misc_tests(ui); }); } } impl Tooltips { fn misc_tests(&mut self, ui: &mut egui::Ui) { ui.label("All labels in this demo have tooltips.") .on_hover_text("Yes, even this one."); ui.label("Some widgets have multiple tooltips!") .on_hover_text("The first tooltip.") .on_hover_text("The second tooltip."); ui.label("Tooltips can contain interactive widgets.") .on_hover_ui(|ui| { ui.label("This tooltip contains a link:"); ui.hyperlink_to("www.egui.rs", "https://www.egui.rs/") .on_hover_text("The tooltip has a tooltip in it!"); }); ui.label("You can put selectable text in tooltips too.") .on_hover_ui(|ui| { ui.style_mut().interaction.selectable_labels = true; ui.label("You can select this text."); }); ui.label("This tooltip shows at the mouse cursor.") .on_hover_text_at_pointer("Move me around!!"); ui.separator(); // --------------------------------------------------------- let tooltip_ui = |ui: &mut egui::Ui| { ui.horizontal(|ui| { ui.label("This tooltip was created with"); ui.code(".on_hover_ui(…)"); }); }; let disabled_tooltip_ui = |ui: &mut egui::Ui| { ui.label("A different tooltip when widget is disabled."); ui.horizontal(|ui| { ui.label("This tooltip was created with"); ui.code(".on_disabled_hover_ui(…)"); }); }; ui.label("You can have different tooltips depending on whether or not a widget is enabled:") .on_hover_text("Check the tooltip of the button below, and see how it changes depending on whether or not it is enabled."); ui.horizontal(|ui| { ui.checkbox(&mut self.enabled, "Enabled") .on_hover_text("Controls whether or not the following button is enabled."); ui.add_enabled(self.enabled, egui::Button::new("Sometimes clickable")) .on_hover_ui(tooltip_ui) .on_disabled_hover_ui(disabled_tooltip_ui); }); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/src/demo/demo_app_windows.rs
crates/egui_demo_lib/src/demo/demo_app_windows.rs
use std::collections::BTreeSet; use super::About; use crate::Demo; use crate::View as _; use crate::is_mobile; use egui::containers::menu; use egui::style::StyleModifier; use egui::{Modifiers, ScrollArea, Ui}; // ---------------------------------------------------------------------------- struct DemoGroup { demos: Vec<Box<dyn Demo>>, } impl std::ops::Add for DemoGroup { type Output = Self; fn add(self, other: Self) -> Self { let mut demos = self.demos; demos.extend(other.demos); Self { demos } } } impl DemoGroup { pub fn new(demos: Vec<Box<dyn Demo>>) -> Self { Self { demos } } pub fn checkboxes(&mut self, ui: &mut Ui, open: &mut BTreeSet<String>) { let Self { demos } = self; for demo in demos { if demo.is_enabled(ui.ctx()) { let mut is_open = open.contains(demo.name()); ui.toggle_value(&mut is_open, demo.name()); set_open(open, demo.name(), is_open); } } } pub fn windows(&mut self, ui: &mut Ui, open: &mut BTreeSet<String>) { let Self { demos } = self; for demo in demos { let mut is_open = open.contains(demo.name()); demo.show(ui, &mut is_open); set_open(open, demo.name(), is_open); } } } fn set_open(open: &mut BTreeSet<String>, key: &'static str, is_open: bool) { if is_open { if !open.contains(key) { open.insert(key.to_owned()); } } else { open.remove(key); } } // ---------------------------------------------------------------------------- pub struct DemoGroups { about: About, demos: DemoGroup, tests: DemoGroup, } impl Default for DemoGroups { fn default() -> Self { Self { about: About::default(), demos: DemoGroup::new(vec![ Box::<super::paint_bezier::PaintBezier>::default(), Box::<super::code_editor::CodeEditor>::default(), Box::<super::code_example::CodeExample>::default(), Box::<super::dancing_strings::DancingStrings>::default(), Box::<super::drag_and_drop::DragAndDropDemo>::default(), Box::<super::extra_viewport::ExtraViewport>::default(), Box::<super::font_book::FontBook>::default(), Box::<super::frame_demo::FrameDemo>::default(), Box::<super::highlighting::Highlighting>::default(), Box::<super::interactive_container::InteractiveContainerDemo>::default(), Box::<super::MiscDemoWindow>::default(), Box::<super::modals::Modals>::default(), Box::<super::multi_touch::MultiTouch>::default(), Box::<super::painting::Painting>::default(), Box::<super::panels::Panels>::default(), Box::<super::popups::PopupsDemo>::default(), Box::<super::scene::SceneDemo>::default(), Box::<super::screenshot::Screenshot>::default(), Box::<super::scrolling::Scrolling>::default(), Box::<super::sliders::Sliders>::default(), Box::<super::strip_demo::StripDemo>::default(), Box::<super::table_demo::TableDemo>::default(), Box::<super::text_edit::TextEditDemo>::default(), Box::<super::text_layout::TextLayoutDemo>::default(), Box::<super::tooltips::Tooltips>::default(), Box::<super::undo_redo::UndoRedoDemo>::default(), Box::<super::widget_gallery::WidgetGallery>::default(), Box::<super::window_options::WindowOptions>::default(), ]), tests: DemoGroup::new(vec![ Box::<super::tests::ClipboardTest>::default(), Box::<super::tests::CursorTest>::default(), Box::<super::tests::GridTest>::default(), Box::<super::tests::IdTest>::default(), Box::<super::tests::InputEventHistory>::default(), Box::<super::tests::InputTest>::default(), Box::<super::tests::LayoutTest>::default(), Box::<super::tests::ManualLayoutTest>::default(), Box::<super::tests::SvgTest>::default(), Box::<super::tests::TessellationTest>::default(), Box::<super::tests::WindowResizeTest>::default(), ]), } } } impl DemoGroups { pub fn checkboxes(&mut self, ui: &mut Ui, open: &mut BTreeSet<String>) { let Self { about, demos, tests, } = self; { let mut is_open = open.contains(about.name()); ui.toggle_value(&mut is_open, about.name()); set_open(open, about.name(), is_open); } ui.separator(); demos.checkboxes(ui, open); ui.separator(); tests.checkboxes(ui, open); } pub fn windows(&mut self, ui: &mut Ui, open: &mut BTreeSet<String>) { let Self { about, demos, tests, } = self; { let mut is_open = open.contains(about.name()); about.show(ui, &mut is_open); set_open(open, about.name(), is_open); } demos.windows(ui, open); tests.windows(ui, open); } } // ---------------------------------------------------------------------------- /// A menu bar in which you can select different demo windows to show. #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] pub struct DemoWindows { #[cfg_attr(feature = "serde", serde(skip))] groups: DemoGroups, open: BTreeSet<String>, } impl Default for DemoWindows { fn default() -> Self { let mut open = BTreeSet::new(); // Explains egui very well set_open(&mut open, About::default().name(), true); // Explains egui very well set_open( &mut open, super::code_example::CodeExample::default().name(), true, ); // Shows off the features set_open( &mut open, super::widget_gallery::WidgetGallery::default().name(), true, ); Self { groups: Default::default(), open, } } } impl DemoWindows { /// Show the app ui (menu bar and windows). pub fn ui(&mut self, ui: &mut egui::Ui) { if is_mobile(ui.ctx()) { self.mobile_ui(ui); } else { self.desktop_ui(ui); } } fn about_is_open(&self) -> bool { self.open.contains(About::default().name()) } fn mobile_ui(&mut self, ui: &mut egui::Ui) { if self.about_is_open() { let mut close = false; egui::ScrollArea::vertical() .auto_shrink(false) .show(ui, |ui| { self.groups.about.ui(ui); ui.add_space(12.0); ui.vertical_centered_justified(|ui| { if ui .button(egui::RichText::new("Continue to the demo!").size(20.0)) .clicked() { close = true; } }); }); if close { set_open(&mut self.open, About::default().name(), false); } } else { self.mobile_top_bar(ui); self.groups.windows(ui, &mut self.open); } } fn mobile_top_bar(&mut self, ui: &mut egui::Ui) { egui::Panel::top("menu_bar").show_inside(ui, |ui| { menu::MenuBar::new() .config(menu::MenuConfig::new().style(StyleModifier::default())) .ui(ui, |ui| { let font_size = 16.5; ui.menu_button(egui::RichText::new("⏷ demos").size(font_size), |ui| { self.demo_list_ui(ui); }); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { use egui::special_emojis::GITHUB; ui.hyperlink_to( egui::RichText::new("🦋").size(font_size), "https://bsky.app/profile/ernerfeldt.bsky.social", ); ui.hyperlink_to( egui::RichText::new(GITHUB).size(font_size), "https://github.com/emilk/egui", ); }); }); }); } fn desktop_ui(&mut self, ui: &mut egui::Ui) { egui::Panel::right("egui_demo_panel") .resizable(false) .default_size(160.0) .min_size(160.0) .show_inside(ui, |ui| { ui.add_space(4.0); ui.vertical_centered(|ui| { ui.heading("✒ egui demos"); }); ui.separator(); use egui::special_emojis::GITHUB; ui.hyperlink_to( format!("{GITHUB} egui on GitHub"), "https://github.com/emilk/egui", ); ui.hyperlink_to( "@ernerfeldt.bsky.social", "https://bsky.app/profile/ernerfeldt.bsky.social", ); ui.separator(); self.demo_list_ui(ui); }); egui::Panel::top("menu_bar").show_inside(ui, |ui| { menu::MenuBar::new().ui(ui, |ui| { file_menu_button(ui); }); }); self.groups.windows(ui, &mut self.open); } fn demo_list_ui(&mut self, ui: &mut egui::Ui) { ScrollArea::vertical().show(ui, |ui| { ui.with_layout(egui::Layout::top_down_justified(egui::Align::LEFT), |ui| { self.groups.checkboxes(ui, &mut self.open); ui.separator(); if ui.button("Organize windows").clicked() { ui.memory_mut(|mem| mem.reset_areas()); } }); }); } } // ---------------------------------------------------------------------------- fn file_menu_button(ui: &mut Ui) { let organize_shortcut = egui::KeyboardShortcut::new(Modifiers::CTRL | Modifiers::SHIFT, egui::Key::O); let reset_shortcut = egui::KeyboardShortcut::new(Modifiers::CTRL | Modifiers::SHIFT, egui::Key::R); // NOTE: we must check the shortcuts OUTSIDE of the actual "File" menu, // or else they would only be checked if the "File" menu was actually open! if ui.input_mut(|i| i.consume_shortcut(&organize_shortcut)) { ui.memory_mut(|mem| mem.reset_areas()); } if ui.input_mut(|i| i.consume_shortcut(&reset_shortcut)) { ui.memory_mut(|mem| *mem = Default::default()); } ui.menu_button("File", |ui| { ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend); // On the web the browser controls the zoom #[cfg(not(target_arch = "wasm32"))] { egui::gui_zoom::zoom_menu_buttons(ui); ui.weak(format!( "Current zoom: {:.0}%", 100.0 * ui.ctx().zoom_factor() )) .on_hover_text("The UI zoom level, on top of the operating system's default value"); ui.separator(); } if ui .add( egui::Button::new("Organize Windows") .shortcut_text(ui.ctx().format_shortcut(&organize_shortcut)), ) .clicked() { ui.memory_mut(|mem| mem.reset_areas()); } if ui .add( egui::Button::new("Reset egui memory") .shortcut_text(ui.ctx().format_shortcut(&reset_shortcut)), ) .on_hover_text("Forget scroll, positions, sizes etc") .clicked() { ui.memory_mut(|mem| *mem = Default::default()); } }); } #[cfg(test)] mod tests { use crate::{Demo as _, demo::demo_app_windows::DemoGroups}; use egui::Vec2; use egui_kittest::{HarnessBuilder, OsThreshold, SnapshotOptions, SnapshotResults}; #[test] fn demos_should_match_snapshot() { let DemoGroups { demos, tests, about: _, } = DemoGroups::default(); let demos = demos + tests; let mut results = SnapshotResults::new(); for mut demo in demos.demos { // Widget Gallery needs to be customized (to set a specific date) and has its own test if demo.name() == crate::WidgetGallery::default().name() { continue; } let name = remove_leading_emoji(demo.name()); let mut harness = HarnessBuilder::default() .with_size(Vec2::splat(2048.0)) .build_ui(|ui| { egui_extras::install_image_loaders(ui); demo.show(ui, &mut true); }); // Resize to fit every window, plus some margin: harness.set_size(harness.ctx.globally_used_rect().max.to_vec2() + Vec2::splat(16.0)); // Run the app for some more frames... harness.run_ok(); let mut options = SnapshotOptions::default(); if name == "Bézier Curve" { // The Bézier Curve demo needs a threshold of 2.1 to pass on linux: options = options.threshold(OsThreshold::new(0.0).linux(2.1)); } results.add(harness.try_snapshot_options(format!("demos/{name}"), &options)); } } fn remove_leading_emoji(full_name: &str) -> &str { if let Some((start, name)) = full_name.split_once(' ') && start.len() <= 4 && start.bytes().next().is_some_and(|byte| byte >= 128) { return name; } full_name } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/src/demo/text_layout.rs
crates/egui_demo_lib/src/demo/text_layout.rs
/// Showcase text layout #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] pub struct TextLayoutDemo { break_anywhere: bool, max_rows: usize, overflow_character: Option<char>, extra_letter_spacing: f32, line_height_pixels: u32, lorem_ipsum: bool, } impl Default for TextLayoutDemo { fn default() -> Self { Self { max_rows: 6, break_anywhere: true, overflow_character: Some('…'), extra_letter_spacing: 0.0, line_height_pixels: 0, lorem_ipsum: true, } } } impl crate::Demo for TextLayoutDemo { fn name(&self) -> &'static str { "🖹 Text Layout" } fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) { egui::Window::new(self.name()) .open(open) .resizable(true) .constrain_to(ui.available_rect_before_wrap()) .show(ui, |ui| { use crate::View as _; self.ui(ui); }); } } impl crate::View for TextLayoutDemo { fn ui(&mut self, ui: &mut egui::Ui) { let Self { break_anywhere, max_rows, overflow_character, extra_letter_spacing, line_height_pixels, lorem_ipsum, } = self; use egui::text::LayoutJob; let pixels_per_point = ui.pixels_per_point(); let points_per_pixel = 1.0 / pixels_per_point; ui.vertical_centered(|ui| { ui.add(crate::egui_github_link_file_line!()); }); ui.add_space(12.0); egui::Grid::new("TextLayoutDemo") .num_columns(2) .show(ui, |ui| { ui.label("Max rows:"); ui.add(egui::DragValue::new(max_rows)); ui.end_row(); ui.label("Line-break:"); ui.horizontal(|ui| { ui.radio_value(break_anywhere, false, "word boundaries"); ui.radio_value(break_anywhere, true, "anywhere"); }); ui.end_row(); ui.label("Overflow character:"); ui.horizontal(|ui| { ui.selectable_value(overflow_character, None, "None"); ui.selectable_value(overflow_character, Some('…'), "…"); ui.selectable_value(overflow_character, Some('—'), "—"); ui.selectable_value(overflow_character, Some('-'), " - "); }); ui.end_row(); ui.label("Extra letter spacing:"); ui.add(egui::DragValue::new(extra_letter_spacing).speed(0.1)); ui.end_row(); ui.label("Line height:"); ui.horizontal(|ui| { if ui .selectable_label(*line_height_pixels == 0, "Default") .clicked() { *line_height_pixels = 0; } if ui .selectable_label(*line_height_pixels != 0, "Custom") .clicked() { *line_height_pixels = (pixels_per_point * 20.0).round() as _; } if *line_height_pixels != 0 { ui.add(egui::DragValue::new(line_height_pixels).suffix(" pixels")); } }); ui.end_row(); ui.label("Text:"); ui.horizontal(|ui| { ui.selectable_value(lorem_ipsum, true, "Lorem Ipsum"); ui.selectable_value(lorem_ipsum, false, "La Pasionaria"); }); }); ui.add_space(12.0); let text = if *lorem_ipsum { crate::LOREM_IPSUM_LONG } else { TO_BE_OR_NOT_TO_BE }; egui::ScrollArea::vertical() .auto_shrink(false) .show(ui, |ui| { let line_height = (*line_height_pixels != 0) .then_some(points_per_pixel * *line_height_pixels as f32); let mut job = LayoutJob::single_section( text.to_owned(), egui::TextFormat { extra_letter_spacing: *extra_letter_spacing, line_height, ..Default::default() }, ); job.wrap = egui::text::TextWrapping { max_rows: *max_rows, break_anywhere: *break_anywhere, overflow_character: *overflow_character, ..Default::default() }; // NOTE: `Label` overrides some of the wrapping settings, e.g. wrap width ui.label(job); }); } } /// Excerpt from Dolores Ibárruri's farwel speech to the International Brigades: const TO_BE_OR_NOT_TO_BE: &str = "Mothers! Women!\n When the years pass by and the wounds of war are stanched; when the memory of the sad and bloody days dissipates in a present of liberty, of peace and of wellbeing; when the rancor have died out and pride in a free country is felt equally by all Spaniards, speak to your children. Tell them of these men of the International Brigades.\n\ \n\ Recount for them how, coming over seas and mountains, crossing frontiers bristling with bayonets, sought by raving dogs thirsting to tear their flesh, these men reached our country as crusaders for freedom, to fight and die for Spain’s liberty and independence threatened by German and Italian fascism. \ They gave up everything — their loves, their countries, home and fortune, fathers, mothers, wives, brothers, sisters and children — and they came and said to us: “We are here. Your cause, Spain’s cause, is ours. It is the cause of all advanced and progressive mankind.”\n\ \n\ - Dolores Ibárruri, 1938";
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/src/demo/about.rs
crates/egui_demo_lib/src/demo/about.rs
#[derive(Default)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] pub struct About {} impl crate::Demo for About { fn name(&self) -> &'static str { "About egui" } fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) { egui::Window::new(self.name()) .default_width(320.0) .default_height(480.0) .open(open) .resizable([true, false]) .scroll(false) .constrain_to(ui.available_rect_before_wrap()) .show(ui, |ui| { use crate::View as _; self.ui(ui); }); } } impl crate::View for About { fn ui(&mut self, ui: &mut egui::Ui) { use egui::special_emojis::{OS_APPLE, OS_LINUX, OS_WINDOWS}; ui.heading("egui"); ui.label(format!( "egui is an immediate mode GUI library written in Rust. egui runs both on the web and natively on {}{}{}. \ On the web it is compiled to WebAssembly and rendered with WebGL.{}", OS_APPLE, OS_LINUX, OS_WINDOWS, if cfg!(target_arch = "wasm32") { " Everything you see is rendered as textured triangles. There is no DOM, HTML, JS or CSS. Just Rust." } else {""} )); ui.label("egui is designed to be easy to use, portable, and fast."); ui.add_space(12.0); ui.heading("Immediate mode"); about_immediate_mode(ui); ui.add_space(12.0); ui.heading("Links"); links(ui); ui.add_space(12.0); ui.horizontal_wrapped(|ui| { ui.spacing_mut().item_spacing.x = 0.0; ui.label("egui development is sponsored by "); ui.hyperlink_to("Rerun.io", "https://www.rerun.io/"); ui.label(", a startup building an SDK for visualizing streams of multimodal data. "); ui.label("For an example of a real-world egui app, see "); ui.hyperlink_to("rerun.io/viewer", "https://www.rerun.io/viewer"); ui.label(" (runs in your browser)."); }); ui.add_space(12.0); ui.vertical_centered(|ui| { ui.add(crate::egui_github_link_file!()); }); } } fn about_immediate_mode(ui: &mut egui::Ui) { ui.style_mut().spacing.interact_size.y = 0.0; // hack to make `horizontal_wrapped` work better with text. ui.horizontal_wrapped(|ui| { ui.spacing_mut().item_spacing.x = 0.0; ui.label("Immediate mode is a GUI paradigm that lets you create a GUI with less code and simpler control flow. For example, this is how you create a "); let _ = ui.small_button("button"); ui.label(" in egui:"); }); ui.add_space(8.0); crate::rust_view_ui( ui, r#" if ui.button("Save").clicked() { my_state.save(); }"# .trim_start_matches('\n'), ); ui.add_space(8.0); ui.horizontal_wrapped(|ui| { ui.spacing_mut().item_spacing.x = 0.0; ui.label("There are no callbacks or messages, and no button state to store. "); ui.label("Read more about immediate mode "); ui.hyperlink_to("here", "https://github.com/emilk/egui#why-immediate-mode"); ui.label("."); }); } fn links(ui: &mut egui::Ui) { use egui::special_emojis::GITHUB; ui.hyperlink_to( format!("{GITHUB} github.com/emilk/egui"), "https://github.com/emilk/egui", ); ui.hyperlink_to( "@ernerfeldt.bsky.social", "https://bsky.app/profile/ernerfeldt.bsky.social", ); ui.hyperlink_to("📓 egui documentation", "https://docs.rs/egui/"); }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/src/demo/table_demo.rs
crates/egui_demo_lib/src/demo/table_demo.rs
use egui::{TextStyle, TextWrapMode}; #[derive(PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] enum DemoType { Manual, ManyHomogeneous, ManyHeterogenous, } /// Shows off a table with dynamic layout #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct TableDemo { demo: DemoType, striped: bool, overline: bool, resizable: bool, clickable: bool, num_rows: usize, scroll_to_row_slider: usize, scroll_to_row: Option<usize>, selection: std::collections::HashSet<usize>, checked: bool, reversed: bool, } impl Default for TableDemo { fn default() -> Self { Self { demo: DemoType::Manual, striped: true, overline: true, resizable: true, clickable: true, num_rows: 10_000, scroll_to_row_slider: 0, scroll_to_row: None, selection: Default::default(), checked: false, reversed: false, } } } impl crate::Demo for TableDemo { fn name(&self) -> &'static str { "☰ Table" } fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) { egui::Window::new(self.name()) .open(open) .default_width(400.0) .constrain_to(ui.available_rect_before_wrap()) .show(ui, |ui| { use crate::View as _; self.ui(ui); }); } } const NUM_MANUAL_ROWS: usize = 20; impl crate::View for TableDemo { fn ui(&mut self, ui: &mut egui::Ui) { let mut reset = false; ui.vertical(|ui| { ui.horizontal(|ui| { ui.checkbox(&mut self.striped, "Striped"); ui.checkbox(&mut self.overline, "Overline some rows"); ui.checkbox(&mut self.resizable, "Resizable columns"); ui.checkbox(&mut self.clickable, "Clickable rows"); }); ui.label("Table type:"); ui.radio_value(&mut self.demo, DemoType::Manual, "Few, manual rows"); ui.radio_value( &mut self.demo, DemoType::ManyHomogeneous, "Thousands of rows of same height", ); ui.radio_value( &mut self.demo, DemoType::ManyHeterogenous, "Thousands of rows of differing heights", ); if self.demo != DemoType::Manual { ui.add( egui::Slider::new(&mut self.num_rows, 0..=100_000) .logarithmic(true) .text("Num rows"), ); } { let max_rows = if self.demo == DemoType::Manual { NUM_MANUAL_ROWS } else { self.num_rows }; let slider_response = ui.add( egui::Slider::new(&mut self.scroll_to_row_slider, 0..=max_rows) .logarithmic(true) .text("Row to scroll to"), ); if slider_response.changed() { self.scroll_to_row = Some(self.scroll_to_row_slider); } } reset = ui.button("Reset").clicked(); }); ui.separator(); // Leave room for the source code link after the table demo: let body_text_size = TextStyle::Body.resolve(ui.style()).size; use egui_extras::{Size, StripBuilder}; StripBuilder::new(ui) .size(Size::remainder().at_least(100.0)) // for the table .size(Size::exact(body_text_size)) // for the source code link .vertical(|mut strip| { strip.cell(|ui| { egui::ScrollArea::horizontal().show(ui, |ui| { self.table_ui(ui, reset); }); }); strip.cell(|ui| { ui.vertical_centered(|ui| { ui.add(crate::egui_github_link_file!()); }); }); }); } } impl TableDemo { fn table_ui(&mut self, ui: &mut egui::Ui, reset: bool) { use egui_extras::{Column, TableBuilder}; let text_height = egui::TextStyle::Body .resolve(ui.style()) .size .max(ui.spacing().interact_size.y); let available_height = ui.available_height(); let mut table = TableBuilder::new(ui) .striped(self.striped) .resizable(self.resizable) .cell_layout(egui::Layout::left_to_right(egui::Align::Center)) .column(Column::auto()) .column( Column::remainder() .at_least(40.0) .clip(true) .resizable(true), ) .column(Column::auto()) .column(Column::remainder()) .column(Column::remainder()) .min_scrolled_height(0.0) .max_scroll_height(available_height); if self.clickable { table = table.sense(egui::Sense::click()); } if let Some(row_index) = self.scroll_to_row.take() { table = table.scroll_to_row(row_index, None); } if reset { table.reset(); } table .header(20.0, |mut header| { header.col(|ui| { egui::Sides::new().show( ui, |ui| { ui.strong("Row"); }, |ui| { self.reversed ^= ui.button(if self.reversed { "⬆" } else { "⬇" }).clicked(); }, ); }); header.col(|ui| { ui.strong("Clipped text"); }); header.col(|ui| { ui.strong("Expanding content"); }); header.col(|ui| { ui.strong("Interaction"); }); header.col(|ui| { ui.strong("Content"); }); }) .body(|mut body| match self.demo { DemoType::Manual => { for row_index in 0..NUM_MANUAL_ROWS { let row_index = if self.reversed { NUM_MANUAL_ROWS - 1 - row_index } else { row_index }; let is_thick = thick_row(row_index); let row_height = if is_thick { 30.0 } else { 18.0 }; body.row(row_height, |mut row| { row.set_selected(self.selection.contains(&row_index)); row.set_overline(self.overline && row_index % 7 == 3); row.col(|ui| { ui.label(row_index.to_string()); }); row.col(|ui| { ui.label(long_text(row_index)); }); row.col(|ui| { expanding_content(ui); }); row.col(|ui| { ui.checkbox(&mut self.checked, "Click me"); }); row.col(|ui| { ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend); if is_thick { ui.heading("Extra thick row"); } else { ui.label("Normal row"); } }); self.toggle_row_selection(row_index, &row.response()); }); } } DemoType::ManyHomogeneous => { body.rows(text_height, self.num_rows, |mut row| { let row_index = if self.reversed { self.num_rows - 1 - row.index() } else { row.index() }; row.set_selected(self.selection.contains(&row_index)); row.set_overline(self.overline && row_index % 7 == 3); row.col(|ui| { ui.label(row_index.to_string()); }); row.col(|ui| { ui.label(long_text(row_index)); }); row.col(|ui| { expanding_content(ui); }); row.col(|ui| { ui.checkbox(&mut self.checked, "Click me"); }); row.col(|ui| { ui.add( egui::Label::new("Thousands of rows of even height") .wrap_mode(TextWrapMode::Extend), ); }); self.toggle_row_selection(row_index, &row.response()); }); } DemoType::ManyHeterogenous => { let row_height = |i: usize| if thick_row(i) { 30.0 } else { 18.0 }; body.heterogeneous_rows((0..self.num_rows).map(row_height), |mut row| { let row_index = if self.reversed { self.num_rows - 1 - row.index() } else { row.index() }; row.set_selected(self.selection.contains(&row_index)); row.set_overline(self.overline && row_index % 7 == 3); row.col(|ui| { ui.label(row_index.to_string()); }); row.col(|ui| { ui.label(long_text(row_index)); }); row.col(|ui| { expanding_content(ui); }); row.col(|ui| { ui.checkbox(&mut self.checked, "Click me"); }); row.col(|ui| { ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend); if thick_row(row_index) { ui.heading("Extra thick row"); } else { ui.label("Normal row"); } }); self.toggle_row_selection(row_index, &row.response()); }); } }); } fn toggle_row_selection(&mut self, row_index: usize, row_response: &egui::Response) { if row_response.clicked() { if self.selection.contains(&row_index) { self.selection.remove(&row_index); } else { self.selection.insert(row_index); } } } } fn expanding_content(ui: &mut egui::Ui) { ui.add(egui::Separator::default().horizontal()); } fn long_text(row_index: usize) -> String { format!( "Row {row_index} has some long text that you may want to clip, or it will take up too much horizontal space!" ) } fn thick_row(row_index: usize) -> bool { row_index.is_multiple_of(6) }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/src/demo/tests/input_event_history.rs
crates/egui_demo_lib/src/demo/tests/input_event_history.rs
//! Show the history of all the input events to struct HistoryEntry { summary: String, entries: Vec<String>, } #[derive(Default)] struct DeduplicatedHistory { history: std::collections::VecDeque<HistoryEntry>, } impl DeduplicatedHistory { fn add(&mut self, summary: String, full: String) { if let Some(entry) = self.history.back_mut() && entry.summary == summary { entry.entries.push(full); return; } self.history.push_back(HistoryEntry { summary, entries: vec![full], }); if self.history.len() > 100 { self.history.pop_front(); } } fn ui(&self, ui: &mut egui::Ui) { egui::ScrollArea::vertical() .auto_shrink(false) .show(ui, |ui| { ui.spacing_mut().item_spacing.y = 4.0; ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend); for HistoryEntry { summary, entries } in self.history.iter().rev() { ui.horizontal(|ui| { let response = ui.code(summary); if entries.len() < 2 { response } else { response | ui.weak(format!(" x{}", entries.len())) } }) .inner .on_hover_ui(|ui| { ui.spacing_mut().item_spacing.y = 4.0; ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend); for entry in entries.iter().rev() { ui.code(entry); } }); } }); } } #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[derive(Default)] pub struct InputEventHistory { #[cfg_attr(feature = "serde", serde(skip))] history: DeduplicatedHistory, include_pointer_movements: bool, } impl crate::Demo for InputEventHistory { fn name(&self) -> &'static str { "Input Event History" } fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) { egui::Window::new(self.name()) .default_width(800.0) .open(open) .resizable(true) .scroll(false) .constrain_to(ui.available_rect_before_wrap()) .show(ui, |ui| { use crate::View as _; self.ui(ui); }); } } impl crate::View for InputEventHistory { fn ui(&mut self, ui: &mut egui::Ui) { ui.input(|i| { for event in &i.raw.events { if !self.include_pointer_movements && matches!( event, egui::Event::PointerMoved { .. } | egui::Event::MouseMoved { .. } | egui::Event::Touch { .. } ) { continue; } let summary = event_summary(event); let full = format!("{event:#?}"); self.history.add(summary, full); } }); ui.vertical_centered(|ui| { ui.add(crate::egui_github_link_file!()); }); ui.label("Recent history of raw input events to egui."); ui.label("Hover any entry for details."); ui.checkbox( &mut self.include_pointer_movements, "Include pointer/mouse movements", ); ui.add_space(8.0); self.history.ui(ui); } } fn event_summary(event: &egui::Event) -> String { match event { egui::Event::PointerMoved { .. } => "PointerMoved { .. }".to_owned(), egui::Event::MouseMoved { .. } => "MouseMoved { .. }".to_owned(), egui::Event::Zoom { .. } => "Zoom { .. }".to_owned(), egui::Event::Touch { phase, .. } => format!("Touch {{ phase: {phase:?}, .. }}"), egui::Event::MouseWheel { unit, .. } => format!("MouseWheel {{ unit: {unit:?}, .. }}"), _ => format!("{event:?}"), } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/src/demo/tests/window_resize_test.rs
crates/egui_demo_lib/src/demo/tests/window_resize_test.rs
pub struct WindowResizeTest { text: String, } impl Default for WindowResizeTest { fn default() -> Self { Self { text: crate::LOREM_IPSUM_LONG.to_owned(), } } } impl crate::Demo for WindowResizeTest { fn name(&self) -> &'static str { "Window Resize Test" } fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) { use egui::{Resize, ScrollArea, TextEdit, Window}; Window::new("↔ auto-sized") .open(open) .auto_sized() .constrain_to(ui.available_rect_before_wrap()) .show(ui, |ui| { ui.label("This window will auto-size based on its contents."); ui.heading("Resize this area:"); Resize::default().show(ui, |ui| { lorem_ipsum(ui, crate::LOREM_IPSUM); }); ui.heading("Resize the above area!"); }); Window::new("↔ resizable + scroll") .open(open) .vscroll(true) .resizable(true) .default_height(300.0) .constrain_to(ui.available_rect_before_wrap()) .show(ui, |ui| { ui.label( "This window is resizable and has a scroll area. You can shrink it to any size.", ); ui.separator(); lorem_ipsum(ui, crate::LOREM_IPSUM_LONG); }); Window::new("↔ resizable + embedded scroll") .open(open) .vscroll(false) .resizable(true) .default_height(300.0) .constrain_to(ui.available_rect_before_wrap()) .show(ui, |ui| { ui.label("This window is resizable but has no built-in scroll area."); ui.label("However, we have a sub-region with a scroll bar:"); ui.separator(); ScrollArea::vertical().show(ui, |ui| { let lorem_ipsum_extra_long = format!("{}\n\n{}", crate::LOREM_IPSUM_LONG, crate::LOREM_IPSUM_LONG); lorem_ipsum(ui, &lorem_ipsum_extra_long); }); // ui.heading("Some additional text here, that should also be visible"); // this works, but messes with the resizing a bit }); Window::new("↔ resizable without scroll") .open(open) .vscroll(false) .resizable(true) .constrain_to(ui.available_rect_before_wrap()) .show(ui, |ui| { ui.label("This window is resizable but has no scroll area. This means it can only be resized to a size where all the contents is visible."); ui.label("egui will not clip the contents of a window, nor add whitespace to it."); ui.separator(); lorem_ipsum(ui, crate::LOREM_IPSUM); }); Window::new("↔ resizable with TextEdit") .open(open) .vscroll(false) .resizable(true) .default_height(300.0) .constrain_to(ui.available_rect_before_wrap()) .show(ui, |ui| { ui.label("Shows how you can fill an area with a widget."); ui.add_sized(ui.available_size(), TextEdit::multiline(&mut self.text)); }); Window::new("↔ freely resized") .open(open) .vscroll(false) .resizable(true) .default_size([250.0, 150.0]) .constrain_to(ui.available_rect_before_wrap()) .show(ui, |ui| { ui.label("This window has empty space that fills up the available space, preventing auto-shrink."); ui.vertical_centered(|ui| { ui.add(crate::egui_github_link_file!()); }); ui.allocate_space(ui.available_size()); }); } } fn lorem_ipsum(ui: &mut egui::Ui, text: &str) { ui.with_layout( egui::Layout::top_down(egui::Align::LEFT).with_cross_justify(true), |ui| { ui.label(egui::RichText::new(text).weak()); }, ); }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/src/demo/tests/layout_test.rs
crates/egui_demo_lib/src/demo/tests/layout_test.rs
use egui::{Align, Direction, Layout, Resize, Slider, Ui, vec2}; #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] pub struct LayoutTest { // Identical to contents of `egui::Layout` layout: LayoutSettings, // Extra for testing wrapping: wrap_column_width: f32, wrap_row_height: f32, } impl Default for LayoutTest { fn default() -> Self { Self { layout: LayoutSettings::top_down(), wrap_column_width: 150.0, wrap_row_height: 20.0, } } } #[derive(Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] pub struct LayoutSettings { // Similar to the contents of `egui::Layout` main_dir: Direction, main_wrap: bool, cross_align: Align, cross_justify: bool, } impl Default for LayoutSettings { fn default() -> Self { Self::top_down() } } impl LayoutSettings { fn top_down() -> Self { Self { main_dir: Direction::TopDown, main_wrap: false, cross_align: Align::Min, cross_justify: false, } } fn top_down_justified_centered() -> Self { Self { main_dir: Direction::TopDown, main_wrap: false, cross_align: Align::Center, cross_justify: true, } } fn horizontal_wrapped() -> Self { Self { main_dir: Direction::LeftToRight, main_wrap: true, cross_align: Align::Center, cross_justify: false, } } fn layout(&self) -> Layout { Layout::from_main_dir_and_cross_align(self.main_dir, self.cross_align) .with_main_wrap(self.main_wrap) .with_cross_justify(self.cross_justify) } } impl crate::Demo for LayoutTest { fn name(&self) -> &'static str { "Layout Test" } fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) { egui::Window::new(self.name()) .open(open) .resizable(false) .constrain_to(ui.available_rect_before_wrap()) .show(ui, |ui| { use crate::View as _; self.ui(ui); }); } } impl crate::View for LayoutTest { fn ui(&mut self, ui: &mut Ui) { ui.label("Tests and demonstrates the limits of the egui layouts"); self.content_ui(ui); Resize::default() .default_size([150.0, 200.0]) .show(ui, |ui| { if self.layout.main_wrap { if self.layout.main_dir.is_horizontal() { ui.allocate_ui( vec2(ui.available_size_before_wrap().x, self.wrap_row_height), |ui| ui.with_layout(self.layout.layout(), demo_ui), ); } else { ui.allocate_ui( vec2(self.wrap_column_width, ui.available_size_before_wrap().y), |ui| ui.with_layout(self.layout.layout(), demo_ui), ); } } else { ui.with_layout(self.layout.layout(), demo_ui); } }); ui.label("Resize to see effect"); ui.vertical_centered(|ui| { ui.add(crate::egui_github_link_file!()); }); } } impl LayoutTest { pub fn content_ui(&mut self, ui: &mut Ui) { ui.horizontal(|ui| { ui.selectable_value(&mut self.layout, LayoutSettings::top_down(), "Top-down"); ui.selectable_value( &mut self.layout, LayoutSettings::top_down_justified_centered(), "Top-down, centered and justified", ); ui.selectable_value( &mut self.layout, LayoutSettings::horizontal_wrapped(), "Horizontal wrapped", ); }); ui.horizontal(|ui| { ui.label("Main Direction:"); for &dir in &[ Direction::LeftToRight, Direction::RightToLeft, Direction::TopDown, Direction::BottomUp, ] { ui.radio_value(&mut self.layout.main_dir, dir, format!("{dir:?}")); } }); ui.horizontal(|ui| { ui.checkbox(&mut self.layout.main_wrap, "Main wrap") .on_hover_text("Wrap when next widget doesn't fit the current row/column"); if self.layout.main_wrap { if self.layout.main_dir.is_horizontal() { ui.add(Slider::new(&mut self.wrap_row_height, 0.0..=200.0).text("Row height")); } else { ui.add( Slider::new(&mut self.wrap_column_width, 0.0..=200.0).text("Column width"), ); } } }); ui.horizontal(|ui| { ui.label("Cross Align:"); for &align in &[Align::Min, Align::Center, Align::Max] { ui.radio_value(&mut self.layout.cross_align, align, format!("{align:?}")); } }); ui.checkbox(&mut self.layout.cross_justify, "Cross Justified") .on_hover_text("Try to fill full width/height (e.g. buttons)"); } } fn demo_ui(ui: &mut Ui) { ui.add(egui::Label::new("Wrapping text followed by example widgets:").wrap()); let mut dummy = false; ui.checkbox(&mut dummy, "checkbox"); ui.radio_value(&mut dummy, false, "radio"); let _ = ui.button("button"); }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/src/demo/tests/svg_test.rs
crates/egui_demo_lib/src/demo/tests/svg_test.rs
pub struct SvgTest { color: egui::Color32, } impl Default for SvgTest { fn default() -> Self { Self { color: egui::Color32::LIGHT_RED, } } } impl crate::Demo for SvgTest { fn name(&self) -> &'static str { "SVG Test" } fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) { egui::Window::new(self.name()) .open(open) .constrain_to(ui.available_rect_before_wrap()) .show(ui, |ui| { use crate::View as _; self.ui(ui); }); } } impl crate::View for SvgTest { fn ui(&mut self, ui: &mut egui::Ui) { let Self { color } = self; ui.color_edit_button_srgba(color); let img_src = egui::include_image!("../../../data/peace.svg"); // First paint a small version, sized the same as the source… ui.add( egui::Image::new(img_src.clone()) .fit_to_original_size(1.0) .tint(*color), ); // …then a big one, to make sure they are both crisp ui.add(egui::Image::new(img_src).tint(*color)); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/src/demo/tests/manual_layout_test.rs
crates/egui_demo_lib/src/demo/tests/manual_layout_test.rs
#[derive(Clone, Copy, Debug, PartialEq)] enum WidgetType { Label, Button, TextEdit, } #[derive(Clone, Debug, PartialEq)] pub struct ManualLayoutTest { widget_offset: egui::Vec2, widget_size: egui::Vec2, widget_type: WidgetType, text_edit_contents: String, } impl Default for ManualLayoutTest { fn default() -> Self { Self { widget_offset: egui::Vec2::splat(150.0), widget_size: egui::vec2(200.0, 100.0), widget_type: WidgetType::Button, text_edit_contents: crate::LOREM_IPSUM.to_owned(), } } } impl crate::Demo for ManualLayoutTest { fn name(&self) -> &'static str { "Manual Layout Test" } fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) { egui::Window::new(self.name()) .resizable(false) .open(open) .constrain_to(ui.available_rect_before_wrap()) .show(ui, |ui| { use crate::View as _; self.ui(ui); }); } } impl crate::View for ManualLayoutTest { fn ui(&mut self, ui: &mut egui::Ui) { egui::reset_button(ui, self, "Reset"); let Self { widget_offset, widget_size, widget_type, text_edit_contents, } = self; ui.horizontal(|ui| { ui.label("Test widget:"); ui.radio_value(widget_type, WidgetType::Button, "Button"); ui.radio_value(widget_type, WidgetType::Label, "Label"); ui.radio_value(widget_type, WidgetType::TextEdit, "TextEdit"); }); egui::Grid::new("pos_size").show(ui, |ui| { ui.label("Widget position:"); ui.add(egui::Slider::new(&mut widget_offset.x, 0.0..=400.0)); ui.add(egui::Slider::new(&mut widget_offset.y, 0.0..=400.0)); ui.end_row(); ui.label("Widget size:"); ui.add(egui::Slider::new(&mut widget_size.x, 0.0..=400.0)); ui.add(egui::Slider::new(&mut widget_size.y, 0.0..=400.0)); ui.end_row(); }); let widget_rect = egui::Rect::from_min_size(ui.min_rect().min + *widget_offset, *widget_size); ui.add(crate::egui_github_link_file!()); // Showing how to place a widget anywhere in the [`Ui`]: match *widget_type { WidgetType::Button => { ui.put(widget_rect, egui::Button::new("Example button")); } WidgetType::Label => { ui.put(widget_rect, egui::Label::new("Example label")); } WidgetType::TextEdit => { ui.put(widget_rect, egui::TextEdit::multiline(text_edit_contents)); } } } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/src/demo/tests/input_test.rs
crates/egui_demo_lib/src/demo/tests/input_test.rs
struct HistoryEntry { text: String, repeated: usize, } #[derive(Default)] struct DeduplicatedHistory { history: std::collections::VecDeque<HistoryEntry>, } impl DeduplicatedHistory { fn add(&mut self, text: String) { if let Some(entry) = self.history.back_mut() && entry.text == text { entry.repeated += 1; return; } self.history.push_back(HistoryEntry { text, repeated: 1 }); if self.history.len() > 100 { self.history.pop_front(); } } fn ui(&self, ui: &mut egui::Ui) { egui::ScrollArea::vertical() .auto_shrink(false) .show(ui, |ui| { ui.spacing_mut().item_spacing.y = 4.0; for HistoryEntry { text, repeated } in self.history.iter().rev() { ui.horizontal(|ui| { if text.is_empty() { ui.weak("(empty)"); } else { ui.label(text); } if 1 < *repeated { ui.weak(format!(" x{repeated}")); } }); } }); } } #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[derive(Default)] pub struct InputTest { #[cfg_attr(feature = "serde", serde(skip))] history: [DeduplicatedHistory; 4], late_interaction: bool, show_hovers: bool, } impl crate::Demo for InputTest { fn name(&self) -> &'static str { "Input Test" } fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) { egui::Window::new(self.name()) .default_width(800.0) .open(open) .resizable(true) .scroll(false) .constrain_to(ui.available_rect_before_wrap()) .show(ui, |ui| { use crate::View as _; self.ui(ui); }); } } impl crate::View for InputTest { fn ui(&mut self, ui: &mut egui::Ui) { ui.spacing_mut().item_spacing.y = 8.0; ui.vertical_centered(|ui| { ui.add(crate::egui_github_link_file!()); }); ui.horizontal(|ui| { if ui.button("Clear").clicked() { *self = Default::default(); } ui.checkbox(&mut self.show_hovers, "Show hover state"); }); ui.checkbox(&mut self.late_interaction, "Use Response::interact"); ui.label("This tests how egui::Response reports events.\n\ The different buttons are sensitive to different things.\n\ Try interacting with them with any mouse button by clicking, double-clicking, triple-clicking, or dragging them."); ui.columns(4, |columns| { for (i, (sense_name, sense)) in [ ("Sense::hover", egui::Sense::hover()), ("Sense::click", egui::Sense::click()), ("Sense::drag", egui::Sense::drag()), ("Sense::click_and_drag", egui::Sense::click_and_drag()), ] .into_iter() .enumerate() { columns[i].push_id(i, |ui| { let response = if self.late_interaction { let first_response = ui.add(egui::Button::new(sense_name).sense(egui::Sense::hover())); first_response.interact(sense) } else { ui.add(egui::Button::new(sense_name).sense(sense)) }; let info = response_summary(&response, self.show_hovers); self.history[i].add(info.trim().to_owned()); self.history[i].ui(ui); }); } }); } } fn response_summary(response: &egui::Response, show_hovers: bool) -> String { use std::fmt::Write as _; let mut new_info = String::new(); if show_hovers { if response.hovered() { writeln!(new_info, "hovered").ok(); } if response.contains_pointer() { writeln!(new_info, "contains_pointer").ok(); } if response.is_pointer_button_down_on() { writeln!(new_info, "pointer_down_on").ok(); } if let Some(pos) = response.interact_pointer_pos() { writeln!(new_info, "response.interact_pointer_pos: {pos:?}").ok(); } } for &button in &[ egui::PointerButton::Primary, egui::PointerButton::Secondary, egui::PointerButton::Middle, egui::PointerButton::Extra1, egui::PointerButton::Extra2, ] { let button_suffix = if button == egui::PointerButton::Primary { // Reduce visual clutter in common case: String::default() } else { format!(" by {button:?} button") }; // These are in inverse logical/chonological order, because we show them in the ui that way: if response.triple_clicked_by(button) { writeln!(new_info, "Triple-clicked{button_suffix}").ok(); } if response.double_clicked_by(button) { writeln!(new_info, "Double-clicked{button_suffix}").ok(); } if response.clicked_by(button) { writeln!(new_info, "Clicked{button_suffix}").ok(); } if response.drag_stopped_by(button) { writeln!(new_info, "Drag stopped{button_suffix}").ok(); } if response.dragged_by(button) { writeln!(new_info, "Dragged{button_suffix}").ok(); } if response.drag_started_by(button) { writeln!(new_info, "Drag started{button_suffix}").ok(); } } if response.long_touched() { writeln!(new_info, "Clicked with long-press").ok(); } new_info }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/src/demo/tests/clipboard_test.rs
crates/egui_demo_lib/src/demo/tests/clipboard_test.rs
pub struct ClipboardTest { text: String, } impl Default for ClipboardTest { fn default() -> Self { Self { text: "Example text you can copy-and-paste".to_owned(), } } } impl crate::Demo for ClipboardTest { fn name(&self) -> &'static str { "Clipboard Test" } fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) { egui::Window::new(self.name()) .open(open) .constrain_to(ui.available_rect_before_wrap()) .show(ui, |ui| { use crate::View as _; self.ui(ui); }); } } impl crate::View for ClipboardTest { fn ui(&mut self, ui: &mut egui::Ui) { ui.label("egui integrates with the system clipboard."); ui.label("Try copy-cut-pasting text in the text edit below."); let text_edit_response = ui .horizontal(|ui| { let text_edit_response = ui.text_edit_singleline(&mut self.text); if ui.button("📋").clicked() { ui.copy_text(self.text.clone()); } text_edit_response }) .inner; if !cfg!(target_arch = "wasm32") { // These commands are not yet implemented on web ui.horizontal(|ui| { for (name, cmd) in [ ("Copy", egui::ViewportCommand::RequestCopy), ("Cut", egui::ViewportCommand::RequestCut), ("Paste", egui::ViewportCommand::RequestPaste), ] { if ui.button(name).clicked() { // Next frame we should get a copy/cut/paste-event… ui.send_viewport_cmd(cmd); // …that should en up here: text_edit_response.request_focus(); } } }); } ui.separator(); ui.label("You can also copy images:"); ui.horizontal(|ui| { let image_source = egui::include_image!("../../../data/icon.png"); let uri = image_source.uri().unwrap().to_owned(); ui.image(image_source); if let Ok(egui::load::ImagePoll::Ready { image }) = ui.ctx().try_load_image(&uri, Default::default()) && ui.button("📋").clicked() { ui.copy_image((*image).clone()); } }); ui.vertical_centered_justified(|ui| { ui.add(crate::egui_github_link_file!()); }); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/src/demo/tests/mod.rs
crates/egui_demo_lib/src/demo/tests/mod.rs
mod clipboard_test; mod cursor_test; mod grid_test; mod id_test; mod input_event_history; mod input_test; mod layout_test; mod manual_layout_test; mod svg_test; mod tessellation_test; mod window_resize_test; pub use clipboard_test::ClipboardTest; pub use cursor_test::CursorTest; pub use grid_test::GridTest; pub use id_test::IdTest; pub use input_event_history::InputEventHistory; pub use input_test::InputTest; pub use layout_test::LayoutTest; pub use manual_layout_test::ManualLayoutTest; pub use svg_test::SvgTest; pub use tessellation_test::TessellationTest; pub use window_resize_test::WindowResizeTest;
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/src/demo/tests/id_test.rs
crates/egui_demo_lib/src/demo/tests/id_test.rs
#[derive(Default)] pub struct IdTest {} impl crate::Demo for IdTest { fn name(&self) -> &'static str { "ID Test" } fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) { egui::Window::new(self.name()) .open(open) .constrain_to(ui.available_rect_before_wrap()) .show(ui, |ui| { use crate::View as _; self.ui(ui); }); } } impl crate::View for IdTest { fn ui(&mut self, ui: &mut egui::Ui) { // Make sure the warnings are on (by default they are only on in debug builds). ui.options_mut(|opt| opt.warn_on_id_clash = true); ui.heading("Name collision example"); ui.label("\ Widgets that store state require unique and persisting identifiers so we can track their state between frames.\n\ For instance, collapsible headers needs to store whether or not they are open. \ Their Id:s are derived from their names. \ If you fail to give them unique names then clicking one will open both. \ To help you debug this, an error message is printed on screen:"); ui.collapsing("Collapsing header", |ui| { ui.label("Contents of first foldable ui"); }); ui.collapsing("Collapsing header", |ui| { ui.label("Contents of second foldable ui"); }); ui.label("\ Any widget that can be interacted with also need a unique Id. \ For most widgets the Id is generated by a running counter. \ As long as elements are not added or removed, the Id stays the same. \ This is fine, because during interaction (i.e. while dragging a slider), \ the number of widgets previously in the same window is most likely not changing \ (and if it is, the window will have a new layout, and the slider will end up somewhere else, and so aborting the interaction probably makes sense)."); ui.label("So these buttons have automatic Id:s, and therefore there is no name clash:"); let _ = ui.button("Button"); let _ = ui.button("Button"); ui.vertical_centered(|ui| { ui.add(crate::egui_github_link_file!()); }); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/src/demo/tests/cursor_test.rs
crates/egui_demo_lib/src/demo/tests/cursor_test.rs
#[derive(Default)] pub struct CursorTest {} impl crate::Demo for CursorTest { fn name(&self) -> &'static str { "Cursor Test" } fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) { egui::Window::new(self.name()) .open(open) .constrain_to(ui.available_rect_before_wrap()) .show(ui, |ui| { use crate::View as _; self.ui(ui); }); } } impl crate::View for CursorTest { fn ui(&mut self, ui: &mut egui::Ui) { ui.vertical_centered_justified(|ui| { ui.heading("Hover to switch cursor icon:"); for &cursor_icon in &egui::CursorIcon::ALL { let _ = ui .button(format!("{cursor_icon:?}")) .on_hover_cursor(cursor_icon); } ui.add(crate::egui_github_link_file!()); }); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/src/demo/tests/tessellation_test.rs
crates/egui_demo_lib/src/demo/tests/tessellation_test.rs
use std::sync::Arc; use egui::{ Color32, Pos2, Rect, Sense, StrokeKind, Vec2, emath::{GuiRounding as _, TSTransform}, epaint::{self, RectShape}, vec2, }; #[derive(Clone, Debug, PartialEq)] pub struct TessellationTest { shape: RectShape, magnification_pixel_size: f32, tessellation_options: epaint::TessellationOptions, paint_edges: bool, } impl Default for TessellationTest { fn default() -> Self { let shape = Self::interesting_shapes()[0].1.clone(); Self { shape, magnification_pixel_size: 12.0, tessellation_options: Default::default(), paint_edges: false, } } } impl TessellationTest { fn interesting_shapes() -> Vec<(&'static str, RectShape)> { fn sized(size: impl Into<Vec2>) -> Rect { Rect::from_center_size(Pos2::ZERO, size.into()) } let baby_blue = Color32::from_rgb(0, 181, 255); let mut shapes = vec![ ( "Normal", RectShape::new( sized([20.0, 16.0]), 2.0, baby_blue, (1.0, Color32::WHITE), StrokeKind::Inside, ), ), ( "Minimal rounding", RectShape::new( sized([20.0, 16.0]), 1.0, baby_blue, (1.0, Color32::WHITE), StrokeKind::Inside, ), ), ( "Thin filled", RectShape::filled(sized([20.0, 0.5]), 2.0, baby_blue), ), ( "Thin stroked", RectShape::new( sized([20.0, 0.5]), 2.0, baby_blue, (0.5, Color32::WHITE), StrokeKind::Inside, ), ), ( "Blurred", RectShape::filled(sized([20.0, 16.0]), 2.0, baby_blue).with_blur_width(50.0), ), ( "Thick stroke, minimal rounding", RectShape::new( sized([20.0, 16.0]), 1.0, baby_blue, (3.0, Color32::WHITE), StrokeKind::Inside, ), ), ( "Blurred stroke", RectShape::new( sized([20.0, 16.0]), 0.0, baby_blue, (5.0, Color32::WHITE), StrokeKind::Inside, ) .with_blur_width(5.0), ), ( "Additive rectangle", RectShape::new( sized([24.0, 12.0]), 0.0, egui::Color32::LIGHT_RED.additive().linear_multiply(0.025), ( 1.0, egui::Color32::LIGHT_BLUE.additive().linear_multiply(0.1), ), StrokeKind::Outside, ), ), ]; for (_name, shape) in &mut shapes { shape.round_to_pixels = Some(true); } shapes } } impl crate::Demo for TessellationTest { fn name(&self) -> &'static str { "Tessellation Test" } fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) { egui::Window::new(self.name()) .resizable(false) .open(open) .constrain_to(ui.available_rect_before_wrap()) .show(ui, |ui| { use crate::View as _; self.ui(ui); }); } } impl crate::View for TessellationTest { fn ui(&mut self, ui: &mut egui::Ui) { ui.add(crate::egui_github_link_file!()); egui::reset_button(ui, self, "Reset"); ui.horizontal(|ui| { ui.group(|ui| { ui.vertical(|ui| { rect_shape_ui(ui, &mut self.shape); }); }); ui.group(|ui| { ui.vertical(|ui| { ui.heading("Real size"); egui::Frame::dark_canvas(ui.style()).show(ui, |ui| { let (resp, painter) = ui.allocate_painter(Vec2::splat(128.0), Sense::hover()); let canvas = resp.rect; let pixels_per_point = ui.pixels_per_point(); let pixel_size = 1.0 / pixels_per_point; let mut shape = self.shape.clone(); shape.rect = Rect::from_center_size(canvas.center(), shape.rect.size()) .round_to_pixel_center(pixels_per_point) .translate(Vec2::new(pixel_size / 3.0, pixel_size / 5.0)); // Intentionally offset to test the effect of rounding painter.add(shape); }); }); }); }); ui.group(|ui| { ui.heading("Zoomed in"); let magnification_pixel_size = &mut self.magnification_pixel_size; let tessellation_options = &mut self.tessellation_options; egui::Grid::new("TessellationOptions") .num_columns(2) .spacing([12.0, 8.0]) .striped(true) .show(ui, |ui| { ui.label("Magnification"); ui.add( egui::DragValue::new(magnification_pixel_size) .speed(0.5) .range(1.0..=32.0), ); ui.end_row(); ui.label("Feathering width"); ui.horizontal(|ui| { ui.checkbox(&mut tessellation_options.feathering, ""); ui.add_enabled( tessellation_options.feathering, egui::DragValue::new( &mut tessellation_options.feathering_size_in_pixels, ) .speed(0.1) .range(0.0..=4.0) .suffix(" px"), ); }); ui.end_row(); ui.label("Paint edges"); ui.checkbox(&mut self.paint_edges, ""); ui.end_row(); }); let magnification_pixel_size = *magnification_pixel_size; egui::Frame::dark_canvas(ui.style()).show(ui, |ui| { let (resp, painter) = ui.allocate_painter( magnification_pixel_size * (self.shape.rect.size() + Vec2::splat(8.0)), Sense::hover(), ); let canvas = resp.rect; let mut shape = self.shape.clone(); shape.rect = shape.rect.translate(Vec2::new(1.0 / 3.0, 1.0 / 5.0)); // Intentionally offset to test the effect of rounding let mut mesh = epaint::Mesh::default(); let mut tessellator = epaint::Tessellator::new( 1.0, *tessellation_options, ui.fonts(|f| f.font_image_size()), vec![], ); tessellator.tessellate_rect(&shape, &mut mesh); // Scale and position the mesh: mesh.transform( TSTransform::from_translation(canvas.center().to_vec2()) * TSTransform::from_scaling(magnification_pixel_size), ); let mesh = Arc::new(mesh); painter.add(epaint::Shape::mesh(Arc::clone(&mesh))); if self.paint_edges { let stroke = epaint::Stroke::new(0.5, Color32::MAGENTA); for triangle in mesh.triangles() { let a = mesh.vertices[triangle[0] as usize]; let b = mesh.vertices[triangle[1] as usize]; let c = mesh.vertices[triangle[2] as usize]; painter.line_segment([a.pos, b.pos], stroke); painter.line_segment([b.pos, c.pos], stroke); painter.line_segment([c.pos, a.pos], stroke); } } if 3.0 < magnification_pixel_size { // Draw pixel centers: let pixel_radius = 0.75; let pixel_color = Color32::GRAY; for yi in 0.. { let y = (yi as f32 + 0.5) * magnification_pixel_size; if y > canvas.height() / 2.0 { break; } for xi in 0.. { let x = (xi as f32 + 0.5) * magnification_pixel_size; if x > canvas.width() / 2.0 { break; } for offset in [vec2(x, y), vec2(x, -y), vec2(-x, y), vec2(-x, -y)] { painter.circle_filled( canvas.center() + offset, pixel_radius, pixel_color, ); } } } } }); }); } } fn rect_shape_ui(ui: &mut egui::Ui, shape: &mut RectShape) { egui::ComboBox::from_id_salt("prefabs") .selected_text("Prefabs") .show_ui(ui, |ui| { for (name, prefab) in TessellationTest::interesting_shapes() { ui.selectable_value(shape, prefab, name); } }); ui.add_space(4.0); let RectShape { rect, corner_radius, fill, stroke, stroke_kind, blur_width, round_to_pixels, brush: _, } = shape; let round_to_pixels = round_to_pixels.get_or_insert(true); egui::Grid::new("RectShape") .num_columns(2) .spacing([12.0, 8.0]) .striped(true) .show(ui, |ui| { ui.label("Size"); ui.horizontal(|ui| { let mut size = rect.size(); ui.add( egui::DragValue::new(&mut size.x) .speed(0.2) .range(0.0..=64.0), ); ui.add( egui::DragValue::new(&mut size.y) .speed(0.2) .range(0.0..=64.0), ); *rect = Rect::from_center_size(Pos2::ZERO, size); }); ui.end_row(); ui.label("Corner radius"); ui.add(corner_radius); ui.end_row(); ui.label("Fill"); ui.color_edit_button_srgba(fill); ui.end_row(); ui.label("Stroke"); ui.add(stroke); ui.end_row(); ui.label("Stroke kind"); ui.horizontal(|ui| { ui.selectable_value(stroke_kind, StrokeKind::Inside, "Inside"); ui.selectable_value(stroke_kind, StrokeKind::Middle, "Middle"); ui.selectable_value(stroke_kind, StrokeKind::Outside, "Outside"); }); ui.end_row(); ui.label("Blur width"); ui.add( egui::DragValue::new(blur_width) .speed(0.5) .range(0.0..=20.0), ); ui.end_row(); ui.label("Round to pixels"); ui.checkbox(round_to_pixels, ""); ui.end_row(); }); } #[cfg(test)] mod tests { use crate::View as _; use egui_kittest::SnapshotResults; use super::*; #[test] fn snapshot_tessellation_test() { let mut results = SnapshotResults::new(); for (name, shape) in TessellationTest::interesting_shapes() { let mut test = TessellationTest { shape, ..Default::default() }; let mut harness = egui_kittest::Harness::new_ui(|ui| { test.ui(ui); }); harness.fit_contents(); harness.run(); harness.snapshot(format!("tessellation_test/{name}")); results.extend_harness(&mut harness); } } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/src/demo/tests/grid_test.rs
crates/egui_demo_lib/src/demo/tests/grid_test.rs
#[derive(PartialEq)] pub struct GridTest { num_cols: usize, num_rows: usize, min_col_width: f32, max_col_width: f32, text_length: usize, } impl Default for GridTest { fn default() -> Self { Self { num_cols: 4, num_rows: 4, min_col_width: 10.0, max_col_width: 200.0, text_length: 10, } } } impl crate::Demo for GridTest { fn name(&self) -> &'static str { "Grid Test" } fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) { egui::Window::new(self.name()) .open(open) .constrain_to(ui.available_rect_before_wrap()) .show(ui, |ui| { use crate::View as _; self.ui(ui); }); } } impl crate::View for GridTest { fn ui(&mut self, ui: &mut egui::Ui) { ui.add( egui::Slider::new(&mut self.min_col_width, 0.0..=400.0).text("Minimum column width"), ); ui.add( egui::Slider::new(&mut self.max_col_width, 0.0..=400.0).text("Maximum column width"), ); ui.add(egui::Slider::new(&mut self.num_cols, 0..=5).text("Columns")); ui.add(egui::Slider::new(&mut self.num_rows, 0..=20).text("Rows")); ui.separator(); let words = [ "random", "words", "in", "a", "random", "order", "that", "just", "keeps", "going", "with", "some", "more", ]; egui::Grid::new("my_grid") .striped(true) .min_col_width(self.min_col_width) .max_col_width(self.max_col_width) .show(ui, |ui| { for row in 0..self.num_rows { for col in 0..self.num_cols { if col == 0 { ui.label(format!("row {row}")); } else { let word_idx = row * 3 + col * 5; let word_count = (row * 5 + col * 75) % 13; let mut string = String::new(); for word in words.iter().cycle().skip(word_idx).take(word_count) { string += word; string += " "; } ui.label(string); } } ui.end_row(); } }); ui.separator(); ui.add(egui::Slider::new(&mut self.text_length, 1..=40).text("Text length")); egui::Grid::new("parent grid").striped(true).show(ui, |ui| { ui.vertical(|ui| { ui.label("Vertical nest1"); ui.label("Vertical nest2"); }); ui.label("First row, second column"); ui.end_row(); ui.horizontal(|ui| { ui.label("Horizontal nest1"); ui.label("Horizontal nest2"); }); ui.label("Second row, second column"); ui.end_row(); ui.scope(|ui| { ui.label("Scope nest 1"); ui.label("Scope nest 2"); }); ui.label("Third row, second column"); ui.end_row(); egui::Grid::new("nested grid").show(ui, |ui| { ui.label("Grid nest11"); ui.label("Grid nest12"); ui.end_row(); ui.label("Grid nest21"); ui.label("Grid nest22"); ui.end_row(); }); ui.label("Fourth row, second column"); ui.end_row(); let mut dyn_text = String::from("O"); dyn_text.extend(std::iter::repeat_n('h', self.text_length)); ui.label(dyn_text); ui.label("Fifth row, second column"); ui.end_row(); }); ui.vertical_centered(|ui| { egui::reset_button(ui, self, "Reset"); ui.add(crate::egui_github_link_file!()); }); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/tests/misc.rs
crates/egui_demo_lib/tests/misc.rs
use egui::{Color32, accesskit::Role}; use egui_kittest::{Harness, kittest::Queryable as _}; #[test] fn test_kerning() { let mut results = egui_kittest::SnapshotResults::new(); for pixels_per_point in [1.0, 2.0] { for theme in [egui::Theme::Dark, egui::Theme::Light] { let mut harness = Harness::builder() .with_pixels_per_point(pixels_per_point) .with_theme(theme) .build_ui(|ui| { ui.label("Hello world!"); ui.label("Repeated characters: iiiiiiiiiiiii lllllllll mmmmmmmmmmmmmmmm"); ui.label("Thin spaces: −123 456 789"); ui.label("Ligature: fi :)"); ui.label("\ttabbed"); }); harness.run(); harness.fit_contents(); harness.snapshot(format!( "image_kerning/image_{theme}_x{pixels_per_point}", theme = match theme { egui::Theme::Dark => "dark", egui::Theme::Light => "light", } )); results.extend_harness(&mut harness); } } } #[test] fn test_italics() { let mut results = egui_kittest::SnapshotResults::new(); for pixels_per_point in [1.0, 2.0_f32.sqrt(), 2.0] { for theme in [egui::Theme::Dark, egui::Theme::Light] { let mut harness = Harness::builder() .with_pixels_per_point(pixels_per_point) .with_theme(theme) .build_ui(|ui| { ui.label(egui::RichText::new("Small italics").italics().small()); ui.label(egui::RichText::new("Normal italics").italics()); ui.label(egui::RichText::new("Large italics").italics().size(22.0)); }); harness.run(); harness.fit_contents(); harness.snapshot(format!( "italics/image_{theme}_x{pixels_per_point:.2}", theme = match theme { egui::Theme::Dark => "dark", egui::Theme::Light => "light", } )); results.extend_harness(&mut harness); } } } #[test] fn test_text_selection() { let mut harness = Harness::builder().build_ui(|ui| { let visuals = ui.visuals_mut(); visuals.selection.bg_fill = Color32::LIGHT_GREEN; visuals.selection.stroke.color = Color32::DARK_BLUE; ui.label("Some varied ☺ text :)\nAnd it has a second line!"); }); harness.run(); harness.fit_contents(); // Drag to select text: let label = harness.get_by_role(Role::Label); harness.drag_at(label.rect().lerp_inside([0.2, 0.25])); harness.drop_at(label.rect().lerp_inside([0.6, 0.75])); harness.run(); harness.snapshot("text_selection"); }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/tests/image_blending.rs
crates/egui_demo_lib/tests/image_blending.rs
use egui::{hex_color, include_image}; use egui_kittest::Harness; #[test] fn test_image_blending() { let mut results = egui_kittest::SnapshotResults::new(); for pixels_per_point in [1.0, 2.0] { let mut harness = Harness::builder() .with_pixels_per_point(pixels_per_point) .build_ui(|ui| { egui_extras::install_image_loaders(ui.ctx()); egui::Frame::new() .fill(hex_color!("#5981FF")) .show(ui, |ui| { ui.add( egui::Image::new(include_image!("../data/ring.png")) .max_height(18.0) .tint(egui::Color32::GRAY), ); }); }); harness.run(); harness.fit_contents(); harness.snapshot(format!("image_blending/image_x{pixels_per_point}")); results.extend_harness(&mut harness); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui_demo_lib/benches/benchmark.rs
crates/egui_demo_lib/benches/benchmark.rs
use std::fmt::Write as _; use criterion::{BatchSize, Criterion, criterion_group, criterion_main}; use egui::epaint::TextShape; use egui::load::SizedTexture; use egui::{Button, Id, RichText, TextureId, Ui, UiBuilder, Vec2}; use egui_demo_lib::LOREM_IPSUM_LONG; use rand::Rng as _; #[global_allocator] static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc; // Much faster allocator /// Each iteration should be called in their own `Ui` with an intentional id clash, /// to prevent the Context from building a massive map of `WidgetRects` (which would slow the test, /// causing unreliable results). fn create_benchmark_ui(ctx: &egui::Context) -> Ui { Ui::new(ctx.clone(), Id::new("clashing_id"), UiBuilder::new()) } pub fn criterion_benchmark(c: &mut Criterion) { use egui::RawInput; { let ctx = egui::Context::default(); let mut demo_windows = egui_demo_lib::DemoWindows::default(); // The most end-to-end benchmark. c.bench_function("demo_with_tessellate__realistic", |b| { b.iter(|| { let full_output = ctx.run_ui(RawInput::default(), |ui| { demo_windows.ui(ui); }); ctx.tessellate(full_output.shapes, full_output.pixels_per_point) }); }); c.bench_function("demo_no_tessellate", |b| { b.iter(|| { ctx.run_ui(RawInput::default(), |ui| { demo_windows.ui(ui); }) }); }); let full_output = ctx.run_ui(RawInput::default(), |ui| { demo_windows.ui(ui); }); c.bench_function("demo_only_tessellate", |b| { b.iter(|| ctx.tessellate(full_output.shapes.clone(), full_output.pixels_per_point)); }); } if false { let ctx = egui::Context::default(); ctx.memory_mut(|m| m.set_everything_is_visible(true)); // give us everything let mut demo_windows = egui_demo_lib::DemoWindows::default(); c.bench_function("demo_full_no_tessellate", |b| { b.iter(|| { ctx.run_ui(RawInput::default(), |ui| { demo_windows.ui(ui); }) }); }); } { let ctx = egui::Context::default(); let _ = ctx.run_ui(RawInput::default(), |ui| { c.bench_function("label &str", |b| { b.iter_batched_ref( || create_benchmark_ui(ui), |ui| { ui.label("the quick brown fox jumps over the lazy dog"); }, BatchSize::LargeInput, ); }); c.bench_function("label format!", |b| { b.iter_batched_ref( || create_benchmark_ui(ui), |ui| { ui.label("the quick brown fox jumps over the lazy dog".to_owned()); }, BatchSize::LargeInput, ); }); }); } { let ctx = egui::Context::default(); let _ = ctx.run_ui(RawInput::default(), |ui| { let mut group = c.benchmark_group("button"); // To ensure we have a valid image, let's use the font texture. The size // shouldn't be important for this benchmark. let image = SizedTexture::new(TextureId::default(), Vec2::splat(16.0)); group.bench_function("1_button_text", |b| { b.iter_batched_ref( || create_benchmark_ui(ui), |ui| { ui.add(Button::new("Hello World")); }, BatchSize::LargeInput, ); }); group.bench_function("2_button_text_image", |b| { b.iter_batched_ref( || create_benchmark_ui(ui), |ui| { ui.add(Button::image_and_text(image, "Hello World")); }, BatchSize::LargeInput, ); }); group.bench_function("3_button_text_image_right_text", |b| { b.iter_batched_ref( || create_benchmark_ui(ui), |ui| { ui.add(Button::image_and_text(image, "Hello World").right_text("⏵")); }, BatchSize::LargeInput, ); }); group.bench_function("4_button_italic", |b| { b.iter_batched_ref( || create_benchmark_ui(ui), |ui| { ui.add(Button::new(RichText::new("Hello World").italics())); }, BatchSize::LargeInput, ); }); }); } { let ctx = egui::Context::default(); ctx.begin_pass(RawInput::default()); let painter = egui::Painter::new(ctx.clone(), egui::LayerId::background(), ctx.content_rect()); c.bench_function("Painter::rect", |b| { let rect = painter.clip_rect(); b.iter(|| { painter.rect( rect, 2.0, egui::Color32::RED, (1.0, egui::Color32::WHITE), egui::StrokeKind::Inside, ); }); }); // Don't call `end_pass` to not have to drain the huge paint list } { let pixels_per_point = 1.0; let wrap_width = 512.0; let font_id = egui::FontId::default(); let text_color = egui::Color32::WHITE; let mut fonts = egui::epaint::text::Fonts::new(Default::default(), egui::FontDefinitions::default()); { c.bench_function("text_layout_uncached", |b| { b.iter(|| { use egui::epaint::text::{LayoutJob, layout}; let job = LayoutJob::simple( LOREM_IPSUM_LONG.to_owned(), font_id.clone(), text_color, wrap_width, ); layout(&mut fonts.fonts, pixels_per_point, job.into()) }); }); } c.bench_function("text_layout_cached", |b| { b.iter(|| { fonts.with_pixels_per_point(pixels_per_point).layout( LOREM_IPSUM_LONG.to_owned(), font_id.clone(), text_color, wrap_width, ) }); }); c.bench_function("text_layout_cached_many_lines_modified", |b| { const NUM_LINES: usize = 2_000; let mut string = String::new(); for _ in 0..NUM_LINES { for i in 0..30_u8 { #[expect(clippy::unwrap_used)] write!(string, "{i:02X} ").unwrap(); } string.push('\n'); } let mut rng = rand::rng(); b.iter(|| { fonts.begin_pass(egui::epaint::TextOptions::default()); // Delete a random character, simulating a user making an edit in a long file: let mut new_string = string.clone(); let idx = rng.random_range(0..string.len()); new_string.remove(idx); fonts.with_pixels_per_point(pixels_per_point).layout( new_string, font_id.clone(), text_color, wrap_width, ); }); }); let galley = fonts.with_pixels_per_point(pixels_per_point).layout( LOREM_IPSUM_LONG.to_owned(), font_id, text_color, wrap_width, ); let font_image_size = fonts.font_image_size(); let prepared_discs = fonts.texture_atlas().prepared_discs(); let mut tessellator = egui::epaint::Tessellator::new( 1.0, Default::default(), font_image_size, prepared_discs, ); let mut mesh = egui::epaint::Mesh::default(); let text_shape = TextShape::new(egui::Pos2::ZERO, galley, text_color); c.bench_function("tessellate_text", |b| { b.iter(|| { tessellator.tessellate_text(&text_shape, &mut mesh); mesh.clear(); }); }); } } criterion_group!(benches, criterion_benchmark); 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/epaint_default_fonts/src/lib.rs
crates/epaint_default_fonts/src/lib.rs
//! A library containing built-in fonts for `epaint`, embedded as bytes. //! //! This is intended to be consumed through the `epaint` crate. /// A typeface designed for source code. /// /// Hack is designed to be a workhorse typeface for source code. It has deep /// roots in the free, open source typeface community and expands upon the /// contributions of the [Bitstream Vera](https://www.gnome.org/fonts/) and /// [DejaVu](https://dejavu-fonts.github.io/) projects. The large x-height + /// wide aperture + low contrast design make it legible at commonly used source /// code text sizes with a sweet spot that runs in the 8 - 14 range. /// /// See [the Hack repository](https://github.com/source-foundry/Hack) for more /// information. pub const HACK_REGULAR: &[u8] = include_bytes!("../fonts/Hack-Regular.ttf"); /// A typeface containing emoji characters as designed for the Noto font family. /// /// Noto is a collection of high-quality fonts with multiple weights and widths /// in sans, serif, mono, and other styles, in more than 1,000 languages and /// over 150 writing systems. Noto Emoji contains black-and-white emoji /// characters that match Google's emoji designs. /// /// See [Google Fonts](https://fonts.google.com/noto/specimen/Noto+Emoji) for /// more information. pub const NOTO_EMOJI_REGULAR: &[u8] = include_bytes!("../fonts/NotoEmoji-Regular.ttf"); /// A typeface designed for use by Ubuntu. /// /// The Ubuntu typeface has been specially created to complement the Ubuntu tone /// of voice. It has a contemporary style and contains characteristics unique to /// the Ubuntu brand that convey a precise, reliable and free attitude. /// /// See [Ubuntu design](https://design.ubuntu.com/font) for more information. pub const UBUNTU_LIGHT: &[u8] = include_bytes!("../fonts/Ubuntu-Light.ttf"); /// An experimental typeface that uses standardized /// [UNICODE planes](http://en.wikipedia.org/wiki/Plane_(Unicode)) /// for icon fonts. /// /// The icons in this font are designed to be styled with minimal effort. Each /// icon is solid, which is useful for changing icon colors. /// /// See [the `emoji-icon-font` repository](https://github.com/jslegers/emoji-icon-font) /// for more information. pub const EMOJI_ICON: &[u8] = include_bytes!("../fonts/emoji-icon-font.ttf");
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/epaint/src/stroke.rs
crates/epaint/src/stroke.rs
use std::{fmt::Debug, sync::Arc}; use emath::GuiRounding as _; use super::{Color32, ColorMode, Pos2, Rect, emath}; /// Describes the width and color of a line. /// /// The default stroke is the same as [`Stroke::NONE`]. #[derive(Clone, Copy, Debug, Default, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct Stroke { pub width: f32, pub color: Color32, } impl Stroke { /// Same as [`Stroke::default`]. pub const NONE: Self = Self { width: 0.0, color: Color32::TRANSPARENT, }; #[inline] pub fn new(width: impl Into<f32>, color: impl Into<Color32>) -> Self { Self { width: width.into(), color: color.into(), } } /// True if width is zero or color is transparent #[inline] pub fn is_empty(&self) -> bool { self.width <= 0.0 || self.color == Color32::TRANSPARENT } /// For vertical or horizontal lines: /// round the stroke center to produce a sharp, pixel-aligned line. pub fn round_center_to_pixel(&self, pixels_per_point: f32, coord: &mut f32) { // If the stroke is an odd number of pixels wide, // we want to round the center of it to the center of a pixel. // // If however it is an even number of pixels wide, // we want to round the center to be between two pixels. // // We also want to treat strokes that are _almost_ odd as it it was odd, // to make it symmetric. Same for strokes that are _almost_ even. // // For strokes less than a pixel wide we also round to the center, // because it will rendered as a single row of pixels by the tessellator. let pixel_size = 1.0 / pixels_per_point; if self.width <= pixel_size || is_nearest_integer_odd(pixels_per_point * self.width) { *coord = coord.round_to_pixel_center(pixels_per_point); } else { *coord = coord.round_to_pixels(pixels_per_point); } } pub(crate) fn round_rect_to_pixel(&self, pixels_per_point: f32, rect: &mut Rect) { // We put odd-width strokes in the center of pixels. // To understand why, see `fn round_center_to_pixel`. let pixel_size = 1.0 / pixels_per_point; let width = self.width; if width <= 0.0 { *rect = rect.round_to_pixels(pixels_per_point); } else if width <= pixel_size || is_nearest_integer_odd(pixels_per_point * width) { *rect = rect.round_to_pixel_center(pixels_per_point); } else { *rect = rect.round_to_pixels(pixels_per_point); } } } impl<Color> From<(f32, Color)> for Stroke where Color: Into<Color32>, { #[inline(always)] fn from((width, color): (f32, Color)) -> Self { Self::new(width, color) } } impl std::hash::Hash for Stroke { #[inline(always)] fn hash<H: std::hash::Hasher>(&self, state: &mut H) { let Self { width, color } = *self; emath::OrderedFloat(width).hash(state); color.hash(state); } } /// Describes how the stroke of a shape should be painted. #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub enum StrokeKind { /// The stroke should be painted entirely inside of the shape Inside, /// The stroke should be painted right on the edge of the shape, half inside and half outside. Middle, /// The stroke should be painted entirely outside of the shape Outside, } /// Describes the width and color of paths. The color can either be solid or provided by a callback. For more information, see [`ColorMode`] /// /// The default stroke is the same as [`Stroke::NONE`]. #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct PathStroke { pub width: f32, pub color: ColorMode, pub kind: StrokeKind, } impl Default for PathStroke { #[inline] fn default() -> Self { Self::NONE } } impl PathStroke { /// Same as [`PathStroke::default`]. pub const NONE: Self = Self { width: 0.0, color: ColorMode::TRANSPARENT, kind: StrokeKind::Middle, }; #[inline] pub fn new(width: impl Into<f32>, color: impl Into<Color32>) -> Self { Self { width: width.into(), color: ColorMode::Solid(color.into()), kind: StrokeKind::Middle, } } /// Create a new `PathStroke` with a UV function /// /// The bounding box passed to the callback will have a margin of [`TessellationOptions::feathering_size_in_pixels`](`crate::tessellator::TessellationOptions::feathering_size_in_pixels`) #[inline] pub fn new_uv( width: impl Into<f32>, callback: impl Fn(Rect, Pos2) -> Color32 + Send + Sync + 'static, ) -> Self { Self { width: width.into(), color: ColorMode::UV(Arc::new(callback)), kind: StrokeKind::Middle, } } #[inline] pub fn with_kind(self, kind: StrokeKind) -> Self { Self { kind, ..self } } /// Set the stroke to be painted right on the edge of the shape, half inside and half outside. #[inline] pub fn middle(self) -> Self { Self { kind: StrokeKind::Middle, ..self } } /// Set the stroke to be painted entirely outside of the shape #[inline] pub fn outside(self) -> Self { Self { kind: StrokeKind::Outside, ..self } } /// Set the stroke to be painted entirely inside of the shape #[inline] pub fn inside(self) -> Self { Self { kind: StrokeKind::Inside, ..self } } /// True if width is zero or color is solid and transparent #[inline] pub fn is_empty(&self) -> bool { self.width <= 0.0 || self.color == ColorMode::TRANSPARENT } } impl<Color> From<(f32, Color)> for PathStroke where Color: Into<Color32>, { #[inline(always)] fn from((width, color): (f32, Color)) -> Self { Self::new(width, color) } } impl From<Stroke> for PathStroke { fn from(value: Stroke) -> Self { if value.is_empty() { // Important, since we use the stroke color when doing feathering of the fill! Self::NONE } else { Self { width: value.width, color: ColorMode::Solid(value.color), kind: StrokeKind::Middle, } } } } /// Returns true if the nearest integer is odd. fn is_nearest_integer_odd(x: f32) -> bool { (x * 0.5 + 0.25).fract() > 0.5 } #[test] fn test_is_nearest_integer_odd() { assert!(is_nearest_integer_odd(0.6)); assert!(is_nearest_integer_odd(1.0)); assert!(is_nearest_integer_odd(1.4)); assert!(!is_nearest_integer_odd(1.6)); assert!(!is_nearest_integer_odd(2.0)); assert!(!is_nearest_integer_odd(2.4)); assert!(is_nearest_integer_odd(2.6)); assert!(is_nearest_integer_odd(3.0)); assert!(is_nearest_integer_odd(3.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/shadow.rs
crates/epaint/src/shadow.rs
use crate::{Color32, CornerRadius, MarginF32, Rect, RectShape, Vec2}; /// The color and fuzziness of a fuzzy shape. /// /// Can be used for a rectangular shadow with a soft penumbra. /// /// Very similar to a box-shadow in CSS. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct Shadow { /// Move the shadow by this much. /// /// For instance, a value of `[1.0, 2.0]` will move the shadow 1 point to the right and 2 points down, /// causing a drop-shadow effect. pub offset: [i8; 2], /// The width of the blur, i.e. the width of the fuzzy penumbra. /// /// A value of 0 means a sharp shadow. pub blur: u8, /// Expand the shadow in all directions by this much. pub spread: u8, /// Color of the opaque center of the shadow. pub color: Color32, } #[test] fn shadow_size() { assert_eq!( std::mem::size_of::<Shadow>(), 8, "Shadow changed size! If it shrank - good! Update this test. If it grew - bad! Try to find a way to avoid it." ); } impl Shadow { /// No shadow at all. pub const NONE: Self = Self { offset: [0, 0], blur: 0, spread: 0, color: Color32::TRANSPARENT, }; /// The argument is the rectangle of the shadow caster. pub fn as_shape(&self, rect: Rect, corner_radius: impl Into<CornerRadius>) -> RectShape { // tessellator.clip_rect = clip_rect; // TODO(emilk): culling let Self { offset, blur, spread, color, } = *self; let [offset_x, offset_y] = offset; let rect = rect .translate(Vec2::new(offset_x as _, offset_y as _)) .expand(spread as _); let corner_radius = corner_radius.into() + CornerRadius::from(spread); RectShape::filled(rect, corner_radius, color).with_blur_width(blur as _) } /// How much larger than the parent rect are we in each direction? pub fn margin(&self) -> MarginF32 { let Self { offset, blur, spread, color: _, } = *self; let spread = spread as f32; let blur = blur as f32; let [offset_x, offset_y] = offset; MarginF32 { left: spread + 0.5 * blur - offset_x as f32, right: spread + 0.5 * blur + offset_x as f32, top: spread + 0.5 * blur - offset_y as f32, bottom: spread + 0.5 * blur + offset_y as f32, } } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/epaint/src/viewport.rs
crates/epaint/src/viewport.rs
use crate::Rect; /// Size of the viewport in whole, physical pixels. pub struct ViewportInPixels { /// Physical pixel offset for left side of the viewport. pub left_px: i32, /// Physical pixel offset for top side of the viewport. pub top_px: i32, /// Physical pixel offset for bottom side of the viewport. /// /// This is what `glViewport`, `glScissor` etc expects for the y axis. pub from_bottom_px: i32, /// Viewport width in physical pixels. pub width_px: i32, /// Viewport height in physical pixels. pub height_px: i32, } impl ViewportInPixels { /// Convert from ui points. pub fn from_points(rect: &Rect, pixels_per_point: f32, screen_size_px: [u32; 2]) -> Self { // Fractional pixel values for viewports are generally valid, but may cause sampling issues // and rounding errors might cause us to get out of bounds. // Round: let left_px = (pixels_per_point * rect.min.x).round() as i32; // inclusive let top_px = (pixels_per_point * rect.min.y).round() as i32; // inclusive let right_px = (pixels_per_point * rect.max.x).round() as i32; // exclusive let bottom_px = (pixels_per_point * rect.max.y).round() as i32; // exclusive // Clamp to screen: let screen_width = screen_size_px[0] as i32; let screen_height = screen_size_px[1] as i32; let left_px = left_px.clamp(0, screen_width); let right_px = right_px.clamp(left_px, screen_width); let top_px = top_px.clamp(0, screen_height); let bottom_px = bottom_px.clamp(top_px, screen_height); let width_px = right_px - left_px; let height_px = bottom_px - top_px; Self { left_px, top_px, from_bottom_px: screen_height - height_px - top_px, width_px, height_px, } } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/epaint/src/stats.rs
crates/epaint/src/stats.rs
//! Collect statistics about what is being painted. use crate::{ClippedShape, Galley, Mesh, Primitive, Shape}; /// Size of the elements in a vector/array. #[derive(Clone, Copy, Default, PartialEq)] enum ElementSize { #[default] Unknown, Homogeneous(usize), Heterogenous, } /// Aggregate information about a bunch of allocations. #[derive(Clone, Copy, Default, PartialEq)] pub struct AllocInfo { element_size: ElementSize, num_allocs: usize, num_elements: usize, num_bytes: usize, } impl<T> From<&[T]> for AllocInfo { fn from(slice: &[T]) -> Self { Self::from_slice(slice) } } impl std::ops::Add for AllocInfo { type Output = Self; fn add(self, rhs: Self) -> Self { use ElementSize::{Heterogenous, Homogeneous, Unknown}; let element_size = match (self.element_size, rhs.element_size) { (Heterogenous, _) | (_, Heterogenous) => Heterogenous, (Unknown, other) | (other, Unknown) => other, (Homogeneous(lhs), Homogeneous(rhs)) if lhs == rhs => Homogeneous(lhs), _ => Heterogenous, }; Self { element_size, num_allocs: self.num_allocs + rhs.num_allocs, num_elements: self.num_elements + rhs.num_elements, num_bytes: self.num_bytes + rhs.num_bytes, } } } impl std::ops::AddAssign for AllocInfo { fn add_assign(&mut self, rhs: Self) { *self = *self + rhs; } } impl std::iter::Sum for AllocInfo { fn sum<I>(iter: I) -> Self where I: Iterator<Item = Self>, { let mut sum = Self::default(); for value in iter { sum += value; } sum } } impl AllocInfo { // pub fn from_shape(shape: &Shape) -> Self { // match shape { // Shape::Noop // Shape::Vec(shapes) => Self::from_shapes(shapes) // | Shape::Circle { .. } // | Shape::LineSegment { .. } // | Shape::Rect { .. } => Self::default(), // Shape::Path { points, .. } => Self::from_slice(points), // Shape::Text { galley, .. } => Self::from_galley(galley), // Shape::Mesh(mesh) => Self::from_mesh(mesh), // } // } pub fn from_galley(galley: &Galley) -> Self { Self::from_slice(galley.text().as_bytes()) + Self::from_slice(&galley.rows) + galley.rows.iter().map(Self::from_galley_row).sum() } fn from_galley_row(row: &crate::text::PlacedRow) -> Self { Self::from_mesh(&row.visuals.mesh) + Self::from_slice(&row.glyphs) } pub fn from_mesh(mesh: &Mesh) -> Self { Self::from_slice(&mesh.indices) + Self::from_slice(&mesh.vertices) } pub fn from_slice<T>(slice: &[T]) -> Self { use std::mem::size_of; let element_size = size_of::<T>(); Self { element_size: ElementSize::Homogeneous(element_size), num_allocs: 1, num_elements: slice.len(), num_bytes: std::mem::size_of_val(slice), } } pub fn num_elements(&self) -> usize { assert!( self.element_size != ElementSize::Heterogenous, "Heterogenous element size" ); self.num_elements } pub fn num_allocs(&self) -> usize { self.num_allocs } pub fn num_bytes(&self) -> usize { self.num_bytes } pub fn megabytes(&self) -> String { megabytes(self.num_bytes()) } pub fn format(&self, what: &str) -> String { if self.num_allocs() == 0 { format!("{:6} {:16}", 0, what) } else if self.num_allocs() == 1 { format!( "{:6} {:16} {} 1 allocation", self.num_elements, what, self.megabytes() ) } else if self.element_size != ElementSize::Heterogenous { format!( "{:6} {:16} {} {:3} allocations", self.num_elements(), what, self.megabytes(), self.num_allocs() ) } else { format!( "{:6} {:16} {} {:3} allocations", "", what, self.megabytes(), self.num_allocs() ) } } } /// Collected allocation statistics for shapes and meshes. #[derive(Clone, Copy, Default)] pub struct PaintStats { pub shapes: AllocInfo, pub shape_text: AllocInfo, pub shape_path: AllocInfo, pub shape_mesh: AllocInfo, pub shape_vec: AllocInfo, pub num_callbacks: usize, pub text_shape_vertices: AllocInfo, pub text_shape_indices: AllocInfo, /// Number of separate clip rectangles pub clipped_primitives: AllocInfo, pub vertices: AllocInfo, pub indices: AllocInfo, } impl PaintStats { pub fn from_shapes(shapes: &[ClippedShape]) -> Self { let mut stats = Self::default(); stats.shape_path.element_size = ElementSize::Heterogenous; // nicer display later stats.shape_vec.element_size = ElementSize::Heterogenous; // nicer display later stats.shapes = AllocInfo::from_slice(shapes); for ClippedShape { shape, .. } in shapes { stats.add(shape); } stats } fn add(&mut self, shape: &Shape) { match shape { Shape::Vec(shapes) => { // self += PaintStats::from_shapes(&shapes); // TODO(emilk) self.shapes += AllocInfo::from_slice(shapes); self.shape_vec += AllocInfo::from_slice(shapes); for shape in shapes { self.add(shape); } } Shape::Noop | Shape::Circle { .. } | Shape::Ellipse { .. } | Shape::LineSegment { .. } | Shape::Rect { .. } | Shape::CubicBezier(_) | Shape::QuadraticBezier(_) => {} Shape::Path(path_shape) => { self.shape_path += AllocInfo::from_slice(&path_shape.points); } Shape::Text(text_shape) => { self.shape_text += AllocInfo::from_galley(&text_shape.galley); for row in &text_shape.galley.rows { self.text_shape_indices += AllocInfo::from_slice(&row.visuals.mesh.indices); self.text_shape_vertices += AllocInfo::from_slice(&row.visuals.mesh.vertices); } } Shape::Mesh(mesh) => { self.shape_mesh += AllocInfo::from_mesh(mesh); } Shape::Callback(_) => { self.num_callbacks += 1; } } } pub fn with_clipped_primitives( mut self, clipped_primitives: &[crate::ClippedPrimitive], ) -> Self { self.clipped_primitives += AllocInfo::from_slice(clipped_primitives); for clipped_primitive in clipped_primitives { if let Primitive::Mesh(mesh) = &clipped_primitive.primitive { self.vertices += AllocInfo::from_slice(&mesh.vertices); self.indices += AllocInfo::from_slice(&mesh.indices); } } self } } fn megabytes(size: usize) -> String { format!("{:.2} MB", size as f64 / 1e6) }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/epaint/src/lib.rs
crates/epaint/src/lib.rs
//! A simple 2D graphics library for turning simple 2D shapes and text into textured triangles. //! //! Made for [`egui`](https://github.com/emilk/egui/). //! //! Create some [`Shape`]:s and pass them to [`Tessellator::tessellate_shapes`] to generate [`Mesh`]:es //! that you can then paint using some graphics API of your choice (e.g. OpenGL). //! //! ## Coordinate system //! The left-top corner of the screen is `(0.0, 0.0)`, //! with X increasing to the right and Y increasing downwards. //! //! `epaint` 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. //! //! ## Feature flags #![cfg_attr(feature = "document-features", doc = document_features::document_features!())] //! #![expect(clippy::float_cmp)] #![expect(clippy::manual_range_contains)] mod brush; pub mod color; mod corner_radius; mod corner_radius_f32; pub mod image; mod margin; mod margin_f32; mod mesh; pub mod mutex; mod shadow; pub mod shape_transform; mod shapes; pub mod stats; mod stroke; pub mod tessellator; pub mod text; mod texture_atlas; mod texture_handle; pub mod textures; pub mod util; mod viewport; pub use self::{ brush::Brush, color::ColorMode, corner_radius::CornerRadius, corner_radius_f32::CornerRadiusF32, image::{AlphaFromCoverage, ColorImage, ImageData, ImageDelta}, margin::Margin, margin_f32::*, mesh::{Mesh, Mesh16, Vertex}, shadow::Shadow, shapes::{ CircleShape, CubicBezierShape, EllipseShape, PaintCallback, PaintCallbackInfo, PathShape, QuadraticBezierShape, RectShape, Shape, TextShape, }, stats::PaintStats, stroke::{PathStroke, Stroke, StrokeKind}, tessellator::{TessellationOptions, Tessellator}, text::{FontFamily, FontId, Fonts, FontsView, Galley, TextOptions}, texture_atlas::TextureAtlas, texture_handle::TextureHandle, textures::TextureManager, viewport::ViewportInPixels, }; #[deprecated = "Renamed to CornerRadius"] pub type Rounding = CornerRadius; pub use ecolor::{Color32, Hsva, HsvaGamma, Rgba}; pub use emath::{Pos2, Rect, Vec2, pos2, vec2}; #[deprecated = "Use the ahash crate directly."] pub use ahash; pub use ecolor; pub use emath; #[cfg(feature = "color-hex")] pub use ecolor::hex_color; /// The UV coordinate of a white region of the texture mesh. /// /// The default egui texture has the top-left corner pixel fully white. /// You need need use a clamping texture sampler for this to work /// (so it doesn't do bilinear blending with bottom right corner). pub const WHITE_UV: emath::Pos2 = emath::pos2(0.0, 0.0); /// What texture to use in a [`Mesh`] mesh. /// /// If you don't want to use a texture, use `TextureId::Managed(0)` and the [`WHITE_UV`] for uv-coord. #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub enum TextureId { /// Textures allocated using [`TextureManager`]. /// /// The first texture (`TextureId::Managed(0)`) is used for the font data. Managed(u64), /// Your own texture, defined in any which way you want. /// The backend renderer will presumably use this to look up what texture to use. User(u64), } impl Default for TextureId { /// The epaint font texture. fn default() -> Self { Self::Managed(0) } } /// A [`Shape`] within a clip rectangle. /// /// Everything is using logical points. #[derive(Clone, Debug, PartialEq)] pub struct ClippedShape { /// Clip / scissor rectangle. /// Only show the part of the [`Shape`] that falls within this. pub clip_rect: emath::Rect, /// The shape pub shape: Shape, } impl ClippedShape { /// 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: emath::TSTransform) { let Self { clip_rect, shape } = self; *clip_rect = transform * *clip_rect; shape.transform(transform); } } /// A [`Mesh`] or [`PaintCallback`] within a clip rectangle. /// /// Everything is using logical points. #[derive(Clone, Debug)] pub struct ClippedPrimitive { /// Clip / scissor rectangle. /// Only show the part of the [`Mesh`] that falls within this. pub clip_rect: emath::Rect, /// What to paint - either a [`Mesh`] or a [`PaintCallback`]. pub primitive: Primitive, } /// A rendering primitive - either a [`Mesh`] or a [`PaintCallback`]. #[derive(Clone, Debug)] pub enum Primitive { Mesh(Mesh), Callback(PaintCallback), } // --------------------------------------------------------------------------- /// Was epaint compiled with the `rayon` feature? pub const HAS_RAYON: bool = cfg!(feature = "rayon");
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/epaint/src/image.rs
crates/epaint/src/image.rs
use emath::Vec2; use crate::{Color32, textures::TextureOptions}; use std::sync::Arc; /// An image stored in RAM. /// /// To load an image file, see [`ColorImage::from_rgba_unmultiplied`]. /// /// This is currently an enum with only one variant, but more image types may be added in the future. /// /// See also: [`ColorImage`]. #[derive(Clone, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub enum ImageData { /// RGBA image. Color(Arc<ColorImage>), } impl ImageData { pub fn size(&self) -> [usize; 2] { match self { Self::Color(image) => image.size, } } pub fn width(&self) -> usize { self.size()[0] } pub fn height(&self) -> usize { self.size()[1] } pub fn bytes_per_pixel(&self) -> usize { match self { Self::Color(_) => 4, } } } // ---------------------------------------------------------------------------- /// A 2D RGBA color image in RAM. #[derive(Clone, Default, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct ColorImage { /// width, height in texels. pub size: [usize; 2], /// Size of the original SVG image (if any), or just the texel size of the image. pub source_size: Vec2, /// The pixels, row by row, from top to bottom. pub pixels: Vec<Color32>, } impl ColorImage { /// Create an image filled with the given color. pub fn new(size: [usize; 2], pixels: Vec<Color32>) -> Self { debug_assert!( size[0] * size[1] == pixels.len(), "size: {size:?}, pixels.len(): {}", pixels.len() ); Self { size, source_size: Vec2::new(size[0] as f32, size[1] as f32), pixels, } } /// Create an image filled with the given color. pub fn filled(size: [usize; 2], color: Color32) -> Self { Self { size, source_size: Vec2::new(size[0] as f32, size[1] as f32), pixels: vec![color; size[0] * size[1]], } } /// Create a [`ColorImage`] from flat un-multiplied RGBA data. /// /// This is usually what you want to use after having loaded an image file. /// /// Panics if `size[0] * size[1] * 4 != rgba.len()`. /// /// ## Example using the [`image`](crates.io/crates/image) crate: /// ``` ignore /// fn load_image_from_path(path: &std::path::Path) -> Result<egui::ColorImage, image::ImageError> { /// let image = image::io::Reader::open(path)?.decode()?; /// let size = [image.width() as _, image.height() as _]; /// let image_buffer = image.to_rgba8(); /// let pixels = image_buffer.as_flat_samples(); /// Ok(egui::ColorImage::from_rgba_unmultiplied( /// size, /// pixels.as_slice(), /// )) /// } /// /// fn load_image_from_memory(image_data: &[u8]) -> Result<ColorImage, image::ImageError> { /// let image = image::load_from_memory(image_data)?; /// let size = [image.width() as _, image.height() as _]; /// let image_buffer = image.to_rgba8(); /// let pixels = image_buffer.as_flat_samples(); /// Ok(ColorImage::from_rgba_unmultiplied( /// size, /// pixels.as_slice(), /// )) /// } /// ``` pub fn from_rgba_unmultiplied(size: [usize; 2], rgba: &[u8]) -> Self { assert_eq!( size[0] * size[1] * 4, rgba.len(), "size: {:?}, rgba.len(): {}", size, rgba.len() ); let pixels = rgba .chunks_exact(4) .map(|p| Color32::from_rgba_unmultiplied(p[0], p[1], p[2], p[3])) .collect(); Self::new(size, pixels) } pub fn from_rgba_premultiplied(size: [usize; 2], rgba: &[u8]) -> Self { assert_eq!( size[0] * size[1] * 4, rgba.len(), "size: {:?}, rgba.len(): {}", size, rgba.len() ); let pixels = rgba .chunks_exact(4) .map(|p| Color32::from_rgba_premultiplied(p[0], p[1], p[2], p[3])) .collect(); Self::new(size, pixels) } /// Create a [`ColorImage`] from flat opaque gray data. /// /// Panics if `size[0] * size[1] != gray.len()`. pub fn from_gray(size: [usize; 2], gray: &[u8]) -> Self { assert_eq!( size[0] * size[1], gray.len(), "size: {:?}, gray.len(): {}", size, gray.len() ); let pixels = gray.iter().map(|p| Color32::from_gray(*p)).collect(); Self::new(size, pixels) } /// Alternative method to `from_gray`. /// Create a [`ColorImage`] from iterator over flat opaque gray data. /// /// Panics if `size[0] * size[1] != gray_iter.len()`. #[doc(alias = "from_grey_iter")] pub fn from_gray_iter(size: [usize; 2], gray_iter: impl Iterator<Item = u8>) -> Self { let pixels: Vec<_> = gray_iter.map(Color32::from_gray).collect(); assert_eq!( size[0] * size[1], pixels.len(), "size: {:?}, pixels.len(): {}", size, pixels.len() ); Self::new(size, pixels) } /// A view of the underlying data as `&[u8]` #[cfg(feature = "bytemuck")] pub fn as_raw(&self) -> &[u8] { bytemuck::cast_slice(&self.pixels) } /// A view of the underlying data as `&mut [u8]` #[cfg(feature = "bytemuck")] pub fn as_raw_mut(&mut self) -> &mut [u8] { bytemuck::cast_slice_mut(&mut self.pixels) } /// Create a [`ColorImage`] from flat RGB data. /// /// This is what you want to use after having loaded an image file (and if /// you are ignoring the alpha channel - considering it to always be 0xff) /// /// Panics if `size[0] * size[1] * 3 != rgb.len()`. pub fn from_rgb(size: [usize; 2], rgb: &[u8]) -> Self { assert_eq!( size[0] * size[1] * 3, rgb.len(), "size: {:?}, rgb.len(): {}", size, rgb.len() ); let pixels = rgb .chunks_exact(3) .map(|p| Color32::from_rgb(p[0], p[1], p[2])) .collect(); Self::new(size, pixels) } /// An example color image, useful for tests. pub fn example() -> Self { let width = 128; let height = 64; let mut img = Self::filled([width, height], Color32::TRANSPARENT); for y in 0..height { for x in 0..width { let h = x as f32 / width as f32; let s = 1.0; let v = 1.0; let a = y as f32 / height as f32; img[(x, y)] = crate::Hsva { h, s, v, a }.into(); } } img } /// Set the source size of e.g. the original SVG image. #[inline] pub fn with_source_size(mut self, source_size: Vec2) -> Self { self.source_size = source_size; self } #[inline] pub fn width(&self) -> usize { self.size[0] } #[inline] pub fn height(&self) -> usize { self.size[1] } /// Create a new image from a patch of the current image. /// /// This method is especially convenient for screenshotting a part of the app /// since `region` can be interpreted as screen coordinates of the entire screenshot if `pixels_per_point` is provided for the native application. /// The floats of [`emath::Rect`] are cast to usize, rounding them down in order to interpret them as indices to the image data. /// /// Panics if `region.min.x > region.max.x || region.min.y > region.max.y`, or if a region larger than the image is passed. pub fn region(&self, region: &emath::Rect, pixels_per_point: Option<f32>) -> Self { let pixels_per_point = pixels_per_point.unwrap_or(1.0); let min_x = (region.min.x * pixels_per_point) as usize; let max_x = (region.max.x * pixels_per_point) as usize; let min_y = (region.min.y * pixels_per_point) as usize; let max_y = (region.max.y * pixels_per_point) as usize; assert!( min_x <= max_x && min_y <= max_y, "Screenshot region is invalid: {region:?}" ); let width = max_x - min_x; let height = max_y - min_y; let mut output = Vec::with_capacity(width * height); let row_stride = self.size[0]; for row in min_y..max_y { output.extend_from_slice( &self.pixels[row * row_stride + min_x..row * row_stride + max_x], ); } Self::new([width, height], output) } /// Clone a sub-region as a new image. pub fn region_by_pixels(&self, [x, y]: [usize; 2], [w, h]: [usize; 2]) -> Self { assert!( x + w <= self.width(), "x + w should be <= self.width(), but x: {}, w: {}, width: {}", x, w, self.width() ); assert!( y + h <= self.height(), "y + h should be <= self.height(), but y: {}, h: {}, height: {}", y, h, self.height() ); let mut pixels = Vec::with_capacity(w * h); for y in y..y + h { let offset = y * self.width() + x; pixels.extend(&self.pixels[offset..(offset + w)]); } assert_eq!( pixels.len(), w * h, "pixels.len should be w * h, but got {}", pixels.len() ); Self::new([w, h], pixels) } } impl std::ops::Index<(usize, usize)> for ColorImage { type Output = Color32; #[inline] fn index(&self, (x, y): (usize, usize)) -> &Color32 { let [w, h] = self.size; assert!(x < w && y < h, "x: {x}, y: {y}, w: {w}, h: {h}"); &self.pixels[y * w + x] } } impl std::ops::IndexMut<(usize, usize)> for ColorImage { #[inline] fn index_mut(&mut self, (x, y): (usize, usize)) -> &mut Color32 { let [w, h] = self.size; assert!(x < w && y < h, "x: {x}, y: {y}, w: {w}, h: {h}"); &mut self.pixels[y * w + x] } } impl From<ColorImage> for ImageData { #[inline(always)] fn from(image: ColorImage) -> Self { Self::Color(Arc::new(image)) } } impl From<Arc<ColorImage>> for ImageData { #[inline] fn from(image: Arc<ColorImage>) -> Self { Self::Color(image) } } impl std::fmt::Debug for ColorImage { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("ColorImage") .field("size", &self.size) .field("pixel-count", &self.pixels.len()) .finish_non_exhaustive() } } // ---------------------------------------------------------------------------- /// How to convert font coverage values into alpha and color values. // // This whole thing is less than rigorous. // Ideally we should do this in a shader instead, and use different computations // for different text colors. // See https://hikogui.org/2022/10/24/the-trouble-with-anti-aliasing.html for an in-depth analysis. #[derive(Clone, Copy, Debug, Default, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub enum AlphaFromCoverage { /// `alpha = coverage`. /// /// Looks good for black-on-white text, i.e. light mode. /// /// Same as [`Self::Gamma`]`(1.0)`, but more efficient. Linear, /// `alpha = coverage^gamma`. Gamma(f32), /// `alpha = 2 * coverage - coverage^2` /// /// This looks good for white-on-black text, i.e. dark mode. /// /// Very similar to a gamma of 0.5, but produces sharper text. /// See <https://www.desmos.com/calculator/w0ndf5blmn> for a comparison to gamma=0.5. #[default] TwoCoverageMinusCoverageSq, } impl AlphaFromCoverage { /// A good-looking default for light mode (black-on-white text). pub const LIGHT_MODE_DEFAULT: Self = Self::Linear; /// A good-looking default for dark mode (white-on-black text). pub const DARK_MODE_DEFAULT: Self = Self::TwoCoverageMinusCoverageSq; /// Convert coverage to alpha. #[inline(always)] pub fn alpha_from_coverage(&self, coverage: f32) -> f32 { let coverage = coverage.clamp(0.0, 1.0); match self { Self::Linear => coverage, Self::Gamma(gamma) => coverage.powf(*gamma), Self::TwoCoverageMinusCoverageSq => 2.0 * coverage - coverage * coverage, } } #[inline(always)] pub fn color_from_coverage(&self, coverage: f32) -> Color32 { let alpha = self.alpha_from_coverage(coverage); Color32::from_white_alpha(ecolor::linear_u8_from_linear_f32(alpha)) } } // ---------------------------------------------------------------------------- /// A change to an image. /// /// Either a whole new image, or an update to a rectangular region of it. #[derive(Clone, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[must_use = "The painter must take care of this"] pub struct ImageDelta { /// What to set the texture to. /// /// If [`Self::pos`] is `None`, this describes the whole texture. /// /// If [`Self::pos`] is `Some`, this describes a patch of the whole image starting at [`Self::pos`]. pub image: ImageData, pub options: TextureOptions, /// If `None`, set the whole texture to [`Self::image`]. /// /// If `Some(pos)`, update a sub-region of an already allocated texture with the patch in [`Self::image`]. pub pos: Option<[usize; 2]>, } impl ImageDelta { /// Update the whole texture. pub fn full(image: impl Into<ImageData>, options: TextureOptions) -> Self { Self { image: image.into(), options, pos: None, } } /// Update a sub-region of an existing texture. pub fn partial(pos: [usize; 2], image: impl Into<ImageData>, options: TextureOptions) -> Self { Self { image: image.into(), options, pos: Some(pos), } } /// Is this affecting the whole texture? /// If `false`, this is a partial (sub-region) update. pub fn is_whole(&self) -> bool { self.pos.is_none() } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/epaint/src/mutex.rs
crates/epaint/src/mutex.rs
//! Wrappers around `parking_lot` locks, with a simple deadlock detection mechanism. // ---------------------------------------------------------------------------- const DEADLOCK_DURATION: std::time::Duration = std::time::Duration::from_secs(10); /// Provides interior mutability. /// /// It's tailored for internal use in egui should only be used for short locks (as a guideline, /// locks should never be held longer than a single frame). In debug builds, when a lock can't /// be acquired within 10 seconds, we assume a deadlock and will panic. /// /// This is a thin wrapper around [`parking_lot::Mutex`]. #[derive(Default)] pub struct Mutex<T>(parking_lot::Mutex<T>); /// The lock you get from [`Mutex`]. pub use parking_lot::MutexGuard; impl<T> Mutex<T> { #[inline(always)] pub fn new(val: T) -> Self { Self(parking_lot::Mutex::new(val)) } /// Try to acquire the lock. /// /// ## Panics /// Will panic in debug builds if the lock can't be acquired within 10 seconds. #[inline(always)] #[cfg_attr(debug_assertions, track_caller)] pub fn lock(&self) -> MutexGuard<'_, T> { if cfg!(debug_assertions) { self.0.try_lock_for(DEADLOCK_DURATION).unwrap_or_else(|| { panic!( "DEBUG PANIC: Failed to acquire Mutex after {}s. Deadlock?", DEADLOCK_DURATION.as_secs() ) }) } else { self.0.lock() } } } // ---------------------------------------------------------------------------- /// The lock you get from [`RwLock::read`]. pub use parking_lot::MappedRwLockReadGuard as RwLockReadGuard; /// The lock you get from [`RwLock::write`]. pub use parking_lot::MappedRwLockWriteGuard as RwLockWriteGuard; /// Provides interior mutability. /// /// It's tailored for internal use in egui should only be used for short locks (as a guideline, /// locks should never be held longer than a single frame). In debug builds, when a lock can't /// be acquired within 10 seconds, we assume a deadlock and will panic. /// /// This is a thin wrapper around [`parking_lot::RwLock`]. #[derive(Default)] pub struct RwLock<T: ?Sized>(parking_lot::RwLock<T>); impl<T> RwLock<T> { #[inline(always)] pub fn new(val: T) -> Self { Self(parking_lot::RwLock::new(val)) } } impl<T: ?Sized> RwLock<T> { /// Try to acquire read-access to the lock. /// /// ## Panics /// Will panic in debug builds if the lock can't be acquired within 10 seconds. #[inline(always)] #[cfg_attr(debug_assertions, track_caller)] pub fn read(&self) -> RwLockReadGuard<'_, T> { let guard = if cfg!(debug_assertions) { self.0.try_read_for(DEADLOCK_DURATION).unwrap_or_else(|| { panic!( "DEBUG PANIC: Failed to acquire RwLock read after {}s. Deadlock?", DEADLOCK_DURATION.as_secs() ) }) } else { self.0.read() }; parking_lot::RwLockReadGuard::map(guard, |v| v) } /// Try to acquire write-access to the lock. /// /// ## Panics /// Will panic in debug builds if the lock can't be acquired within 10 seconds. #[inline(always)] #[cfg_attr(debug_assertions, track_caller)] pub fn write(&self) -> RwLockWriteGuard<'_, T> { let guard = if cfg!(debug_assertions) { self.0.try_write_for(DEADLOCK_DURATION).unwrap_or_else(|| { panic!( "DEBUG PANIC: Failed to acquire RwLock write after {}s. Deadlock?", DEADLOCK_DURATION.as_secs() ) }) } else { self.0.write() }; parking_lot::RwLockWriteGuard::map(guard, |v| v) } } // ---------------------------------------------------------------------------- impl<T> Clone for Mutex<T> where T: Clone, { fn clone(&self) -> Self { Self::new(self.lock().clone()) } } // ---------------------------------------------------------------------------- #[cfg(test)] mod tests { #![expect(clippy::disallowed_methods)] // Ok for tests use crate::mutex::Mutex; use std::time::Duration; #[test] fn lock_two_different_mutexes_single_thread() { let one = Mutex::new(()); let two = Mutex::new(()); let _a = one.lock(); let _b = two.lock(); } #[test] fn lock_multiple_threads() { use std::sync::Arc; let one = Arc::new(Mutex::new(())); let our_lock = one.lock(); let other_thread = { let one = Arc::clone(&one); std::thread::spawn(move || { let _lock = one.lock(); }) }; std::thread::sleep(Duration::from_millis(200)); drop(our_lock); other_thread.join().unwrap(); } } #[cfg(not(target_arch = "wasm32"))] #[cfg(test)] mod tests_rwlock { #![expect(clippy::disallowed_methods)] // Ok for tests use crate::mutex::RwLock; use std::time::Duration; #[test] fn lock_two_different_rwlocks_single_thread() { let one = RwLock::new(()); let two = RwLock::new(()); let _a = one.write(); let _b = two.write(); } #[test] fn rwlock_multiple_threads() { use std::sync::Arc; let one = Arc::new(RwLock::new(())); let our_lock = one.write(); let other_thread1 = { let one = Arc::clone(&one); std::thread::spawn(move || { let _ = one.write(); }) }; let other_thread2 = { let one = Arc::clone(&one); std::thread::spawn(move || { let _ = one.read(); }) }; std::thread::sleep(Duration::from_millis(200)); drop(our_lock); other_thread1.join().unwrap(); other_thread2.join().unwrap(); } #[test] #[should_panic] fn rwlock_write_write_reentrancy() { let one = RwLock::new(()); let _a1 = one.write(); let _a2 = one.write(); // panics } #[test] #[should_panic] fn rwlock_write_read_reentrancy() { let one = RwLock::new(()); let _a1 = one.write(); let _a2 = one.read(); // panics } #[test] #[should_panic] fn rwlock_read_write_reentrancy() { let one = RwLock::new(()); let _a1 = one.read(); let _a2 = one.write(); // panics } #[test] fn rwlock_read_read_reentrancy() { let one = RwLock::new(()); let _a1 = one.read(); // This is legal: this test suite specifically targets native, which relies // on parking_lot's rw-locks, which are reentrant. let _a2 = one.read(); } #[test] fn rwlock_short_read_foreign_read_write_reentrancy() { use std::sync::Arc; let lock = Arc::new(RwLock::new(())); // Thread #0 grabs a read lock let t0r0 = lock.read(); // Thread #1 grabs the same read lock let other_thread = { let lock = Arc::clone(&lock); std::thread::spawn(move || { let _t1r0 = lock.read(); }) }; other_thread.join().unwrap(); // Thread #0 releases its read lock drop(t0r0); // Thread #0 now grabs a write lock, which is legal let _t0w0 = lock.write(); } #[test] #[should_panic] fn rwlock_read_foreign_read_write_reentrancy() { use std::sync::Arc; let lock = Arc::new(RwLock::new(())); // Thread #0 grabs a read lock let _t0r0 = lock.read(); // Thread #1 grabs the same read lock let other_thread = { let lock = Arc::clone(&lock); std::thread::spawn(move || { let _t1r0 = lock.read(); }) }; other_thread.join().unwrap(); // Thread #0 now grabs a write lock, which should panic (read-write) let _t0w0 = lock.write(); // panics } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/epaint/src/margin.rs
crates/epaint/src/margin.rs
use emath::{Rect, Vec2, vec2}; /// A value for all four sides of a rectangle, /// often used to express padding or spacing. /// /// Can be added and subtracted to/from [`Rect`]s. /// /// Negative margins are possible, but may produce weird behavior. /// Use with care. /// /// All values are stored as [`i8`] to keep the size of [`Margin`] small. /// If you want floats, use [`crate::MarginF32`] instead. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct Margin { pub left: i8, pub right: i8, pub top: i8, pub bottom: i8, } impl Margin { pub const ZERO: Self = Self { left: 0, right: 0, top: 0, bottom: 0, }; /// The same margin on every side. #[doc(alias = "symmetric")] #[inline] pub const fn same(margin: i8) -> Self { Self { left: margin, right: margin, top: margin, bottom: margin, } } /// Margins with the same size on opposing sides #[inline] pub const fn symmetric(x: i8, y: i8) -> Self { Self { left: x, right: x, top: y, bottom: y, } } /// Left margin, as `f32` #[inline] pub const fn leftf(self) -> f32 { self.left as _ } /// Right margin, as `f32` #[inline] pub const fn rightf(self) -> f32 { self.right as _ } /// Top margin, as `f32` #[inline] pub const fn topf(self) -> f32 { self.top as _ } /// Bottom margin, as `f32` #[inline] pub const fn bottomf(self) -> f32 { self.bottom as _ } /// Total margins on both sides #[inline] pub fn sum(self) -> Vec2 { vec2(self.leftf() + self.rightf(), self.topf() + self.bottomf()) } #[inline] pub const fn left_top(self) -> Vec2 { vec2(self.leftf(), self.topf()) } #[inline] pub const fn right_bottom(self) -> Vec2 { vec2(self.rightf(), self.bottomf()) } /// Are the margin on every side the same? #[doc(alias = "symmetric")] #[inline] pub const fn is_same(self) -> bool { self.left == self.right && self.left == self.top && self.left == self.bottom } } impl From<i8> for Margin { #[inline] fn from(v: i8) -> Self { Self::same(v) } } impl From<f32> for Margin { #[inline] fn from(v: f32) -> Self { Self::same(v.round() as _) } } impl From<Vec2> for Margin { #[inline] fn from(v: Vec2) -> Self { Self::symmetric(v.x.round() as _, v.y.round() as _) } } /// `Margin + Margin` impl std::ops::Add for Margin { type Output = Self; #[inline] fn add(self, other: Self) -> Self { Self { left: self.left.saturating_add(other.left), right: self.right.saturating_add(other.right), top: self.top.saturating_add(other.top), bottom: self.bottom.saturating_add(other.bottom), } } } /// `Margin + i8` impl std::ops::Add<i8> for Margin { type Output = Self; #[inline] fn add(self, v: i8) -> Self { Self { left: self.left.saturating_add(v), right: self.right.saturating_add(v), top: self.top.saturating_add(v), bottom: self.bottom.saturating_add(v), } } } /// `Margin += i8` impl std::ops::AddAssign<i8> for Margin { #[inline] fn add_assign(&mut self, v: i8) { *self = *self + v; } } /// `Margin * f32` impl std::ops::Mul<f32> for Margin { type Output = Self; #[inline] fn mul(self, v: f32) -> Self { Self { left: (self.leftf() * v).round() as _, right: (self.rightf() * v).round() as _, top: (self.topf() * v).round() as _, bottom: (self.bottomf() * v).round() as _, } } } /// `Margin *= f32` impl std::ops::MulAssign<f32> for Margin { #[inline] fn mul_assign(&mut self, v: f32) { *self = *self * v; } } /// `Margin / f32` impl std::ops::Div<f32> for Margin { type Output = Self; #[inline] fn div(self, v: f32) -> Self { #![expect(clippy::suspicious_arithmetic_impl)] self * v.recip() } } /// `Margin /= f32` impl std::ops::DivAssign<f32> for Margin { #[inline] fn div_assign(&mut self, v: f32) { *self = *self / v; } } /// `Margin - Margin` impl std::ops::Sub for Margin { type Output = Self; #[inline] fn sub(self, other: Self) -> Self { Self { left: self.left.saturating_sub(other.left), right: self.right.saturating_sub(other.right), top: self.top.saturating_sub(other.top), bottom: self.bottom.saturating_sub(other.bottom), } } } /// `Margin - i8` impl std::ops::Sub<i8> for Margin { type Output = Self; #[inline] fn sub(self, v: i8) -> Self { Self { left: self.left.saturating_sub(v), right: self.right.saturating_sub(v), top: self.top.saturating_sub(v), bottom: self.bottom.saturating_sub(v), } } } /// `Margin -= i8` impl std::ops::SubAssign<i8> for Margin { #[inline] fn sub_assign(&mut self, v: i8) { *self = *self - v; } } /// `Rect + Margin` impl std::ops::Add<Margin> for Rect { type Output = Self; #[inline] fn add(self, margin: Margin) -> Self { Self::from_min_max( self.min - margin.left_top(), self.max + margin.right_bottom(), ) } } /// `Rect += Margin` impl std::ops::AddAssign<Margin> for Rect { #[inline] fn add_assign(&mut self, margin: Margin) { *self = *self + margin; } } /// `Rect - Margin` impl std::ops::Sub<Margin> for Rect { type Output = Self; #[inline] fn sub(self, margin: Margin) -> Self { Self::from_min_max( self.min + margin.left_top(), self.max - margin.right_bottom(), ) } } /// `Rect -= Margin` impl std::ops::SubAssign<Margin> for Rect { #[inline] fn sub_assign(&mut self, margin: Margin) { *self = *self - margin; } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/epaint/src/margin_f32.rs
crates/epaint/src/margin_f32.rs
use emath::{Rect, Vec2, vec2}; use crate::Margin; /// A value for all four sides of a rectangle, /// often used to express padding or spacing. /// /// Can be added and subtracted to/from [`Rect`]s. /// /// For storage, use [`crate::Margin`] instead. #[derive(Clone, Copy, Debug, Default, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct MarginF32 { pub left: f32, pub right: f32, pub top: f32, pub bottom: f32, } #[deprecated = "Renamed to MarginF32"] pub type Marginf = MarginF32; impl From<Margin> for MarginF32 { #[inline] fn from(margin: Margin) -> Self { Self { left: margin.left as _, right: margin.right as _, top: margin.top as _, bottom: margin.bottom as _, } } } impl From<MarginF32> for Margin { #[inline] fn from(marginf: MarginF32) -> Self { Self { left: marginf.left as _, right: marginf.right as _, top: marginf.top as _, bottom: marginf.bottom as _, } } } impl MarginF32 { pub const ZERO: Self = Self { left: 0.0, right: 0.0, top: 0.0, bottom: 0.0, }; /// The same margin on every side. #[doc(alias = "symmetric")] #[inline] pub const fn same(margin: f32) -> Self { Self { left: margin, right: margin, top: margin, bottom: margin, } } /// Margins with the same size on opposing sides #[inline] pub const fn symmetric(x: f32, y: f32) -> Self { Self { left: x, right: x, top: y, bottom: y, } } /// Total margins on both sides #[inline] pub fn sum(&self) -> Vec2 { vec2(self.left + self.right, self.top + self.bottom) } #[inline] pub const fn left_top(&self) -> Vec2 { vec2(self.left, self.top) } #[inline] pub const fn right_bottom(&self) -> Vec2 { vec2(self.right, self.bottom) } /// Are the margin on every side the same? #[doc(alias = "symmetric")] #[inline] pub fn is_same(&self) -> bool { self.left == self.right && self.left == self.top && self.left == self.bottom } #[deprecated = "Use `rect + margin` instead"] #[inline] pub fn expand_rect(&self, rect: Rect) -> Rect { Rect::from_min_max(rect.min - self.left_top(), rect.max + self.right_bottom()) } #[deprecated = "Use `rect - margin` instead"] #[inline] pub fn shrink_rect(&self, rect: Rect) -> Rect { Rect::from_min_max(rect.min + self.left_top(), rect.max - self.right_bottom()) } } impl From<f32> for MarginF32 { #[inline] fn from(v: f32) -> Self { Self::same(v) } } impl From<Vec2> for MarginF32 { #[inline] fn from(v: Vec2) -> Self { Self::symmetric(v.x, v.y) } } /// `MarginF32 + MarginF32` impl std::ops::Add for MarginF32 { type Output = Self; #[inline] fn add(self, other: Self) -> Self { Self { left: self.left + other.left, right: self.right + other.right, top: self.top + other.top, bottom: self.bottom + other.bottom, } } } /// `MarginF32 + f32` impl std::ops::Add<f32> for MarginF32 { type Output = Self; #[inline] fn add(self, v: f32) -> Self { Self { left: self.left + v, right: self.right + v, top: self.top + v, bottom: self.bottom + v, } } } /// `Margind += f32` impl std::ops::AddAssign<f32> for MarginF32 { #[inline] fn add_assign(&mut self, v: f32) { self.left += v; self.right += v; self.top += v; self.bottom += v; } } /// `MarginF32 * f32` impl std::ops::Mul<f32> for MarginF32 { type Output = Self; #[inline] fn mul(self, v: f32) -> Self { Self { left: self.left * v, right: self.right * v, top: self.top * v, bottom: self.bottom * v, } } } /// `MarginF32 *= f32` impl std::ops::MulAssign<f32> for MarginF32 { #[inline] fn mul_assign(&mut self, v: f32) { self.left *= v; self.right *= v; self.top *= v; self.bottom *= v; } } /// `MarginF32 / f32` impl std::ops::Div<f32> for MarginF32 { type Output = Self; #[inline] fn div(self, v: f32) -> Self { Self { left: self.left / v, right: self.right / v, top: self.top / v, bottom: self.bottom / v, } } } /// `MarginF32 /= f32` impl std::ops::DivAssign<f32> for MarginF32 { #[inline] fn div_assign(&mut self, v: f32) { self.left /= v; self.right /= v; self.top /= v; self.bottom /= v; } } /// `MarginF32 - MarginF32` impl std::ops::Sub for MarginF32 { type Output = Self; #[inline] fn sub(self, other: Self) -> Self { Self { left: self.left - other.left, right: self.right - other.right, top: self.top - other.top, bottom: self.bottom - other.bottom, } } } /// `MarginF32 - f32` impl std::ops::Sub<f32> for MarginF32 { type Output = Self; #[inline] fn sub(self, v: f32) -> Self { Self { left: self.left - v, right: self.right - v, top: self.top - v, bottom: self.bottom - v, } } } /// `MarginF32 -= f32` impl std::ops::SubAssign<f32> for MarginF32 { #[inline] fn sub_assign(&mut self, v: f32) { self.left -= v; self.right -= v; self.top -= v; self.bottom -= v; } } /// `Rect + MarginF32` impl std::ops::Add<MarginF32> for Rect { type Output = Self; #[inline] fn add(self, margin: MarginF32) -> Self { Self::from_min_max( self.min - margin.left_top(), self.max + margin.right_bottom(), ) } } /// `Rect += MarginF32` impl std::ops::AddAssign<MarginF32> for Rect { #[inline] fn add_assign(&mut self, margin: MarginF32) { *self = *self + margin; } } /// `Rect - MarginF32` impl std::ops::Sub<MarginF32> for Rect { type Output = Self; #[inline] fn sub(self, margin: MarginF32) -> Self { Self::from_min_max( self.min + margin.left_top(), self.max - margin.right_bottom(), ) } } /// `Rect -= MarginF32` impl std::ops::SubAssign<MarginF32> for Rect { #[inline] fn sub_assign(&mut self, margin: MarginF32) { *self = *self - margin; } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/epaint/src/tessellator.rs
crates/epaint/src/tessellator.rs
//! Converts graphics primitives into textured triangles. //! //! This module converts lines, circles, text and more represented by [`Shape`] //! into textured triangles represented by [`Mesh`]. #![expect(clippy::identity_op)] use emath::{GuiRounding as _, NumExt as _, Pos2, Rect, Rot2, Vec2, pos2, remap, vec2}; use crate::{ CircleShape, ClippedPrimitive, ClippedShape, Color32, CornerRadiusF32, CubicBezierShape, EllipseShape, Mesh, PathShape, Primitive, QuadraticBezierShape, RectShape, Shape, Stroke, StrokeKind, TextShape, TextureId, Vertex, WHITE_UV, color::ColorMode, emath, stroke::PathStroke, texture_atlas::PreparedDisc, }; // ---------------------------------------------------------------------------- #[expect(clippy::approx_constant)] mod precomputed_vertices { // fn main() { // let n = 64; // println!("pub const CIRCLE_{}: [Vec2; {}] = [", n, n+1); // for i in 0..=n { // let a = std::f64::consts::TAU * i as f64 / n as f64; // println!(" vec2({:.06}, {:.06}),", a.cos(), a.sin()); // } // println!("];") // } use emath::{Vec2, vec2}; pub const CIRCLE_8: [Vec2; 9] = [ vec2(1.000000, 0.000000), vec2(0.707107, 0.707107), vec2(0.000000, 1.000000), vec2(-0.707107, 0.707107), vec2(-1.000000, 0.000000), vec2(-0.707107, -0.707107), vec2(0.000000, -1.000000), vec2(0.707107, -0.707107), vec2(1.000000, 0.000000), ]; pub const CIRCLE_16: [Vec2; 17] = [ vec2(1.000000, 0.000000), vec2(0.923880, 0.382683), vec2(0.707107, 0.707107), vec2(0.382683, 0.923880), vec2(0.000000, 1.000000), vec2(-0.382684, 0.923880), vec2(-0.707107, 0.707107), vec2(-0.923880, 0.382683), vec2(-1.000000, 0.000000), vec2(-0.923880, -0.382683), vec2(-0.707107, -0.707107), vec2(-0.382684, -0.923880), vec2(0.000000, -1.000000), vec2(0.382684, -0.923879), vec2(0.707107, -0.707107), vec2(0.923880, -0.382683), vec2(1.000000, 0.000000), ]; pub const CIRCLE_32: [Vec2; 33] = [ vec2(1.000000, 0.000000), vec2(0.980785, 0.195090), vec2(0.923880, 0.382683), vec2(0.831470, 0.555570), vec2(0.707107, 0.707107), vec2(0.555570, 0.831470), vec2(0.382683, 0.923880), vec2(0.195090, 0.980785), vec2(0.000000, 1.000000), vec2(-0.195090, 0.980785), vec2(-0.382683, 0.923880), vec2(-0.555570, 0.831470), vec2(-0.707107, 0.707107), vec2(-0.831470, 0.555570), vec2(-0.923880, 0.382683), vec2(-0.980785, 0.195090), vec2(-1.000000, 0.000000), vec2(-0.980785, -0.195090), vec2(-0.923880, -0.382683), vec2(-0.831470, -0.555570), vec2(-0.707107, -0.707107), vec2(-0.555570, -0.831470), vec2(-0.382683, -0.923880), vec2(-0.195090, -0.980785), vec2(-0.000000, -1.000000), vec2(0.195090, -0.980785), vec2(0.382683, -0.923880), vec2(0.555570, -0.831470), vec2(0.707107, -0.707107), vec2(0.831470, -0.555570), vec2(0.923880, -0.382683), vec2(0.980785, -0.195090), vec2(1.000000, -0.000000), ]; pub const CIRCLE_64: [Vec2; 65] = [ vec2(1.000000, 0.000000), vec2(0.995185, 0.098017), vec2(0.980785, 0.195090), vec2(0.956940, 0.290285), vec2(0.923880, 0.382683), vec2(0.881921, 0.471397), vec2(0.831470, 0.555570), vec2(0.773010, 0.634393), vec2(0.707107, 0.707107), vec2(0.634393, 0.773010), vec2(0.555570, 0.831470), vec2(0.471397, 0.881921), vec2(0.382683, 0.923880), vec2(0.290285, 0.956940), vec2(0.195090, 0.980785), vec2(0.098017, 0.995185), vec2(0.000000, 1.000000), vec2(-0.098017, 0.995185), vec2(-0.195090, 0.980785), vec2(-0.290285, 0.956940), vec2(-0.382683, 0.923880), vec2(-0.471397, 0.881921), vec2(-0.555570, 0.831470), vec2(-0.634393, 0.773010), vec2(-0.707107, 0.707107), vec2(-0.773010, 0.634393), vec2(-0.831470, 0.555570), vec2(-0.881921, 0.471397), vec2(-0.923880, 0.382683), vec2(-0.956940, 0.290285), vec2(-0.980785, 0.195090), vec2(-0.995185, 0.098017), vec2(-1.000000, 0.000000), vec2(-0.995185, -0.098017), vec2(-0.980785, -0.195090), vec2(-0.956940, -0.290285), vec2(-0.923880, -0.382683), vec2(-0.881921, -0.471397), vec2(-0.831470, -0.555570), vec2(-0.773010, -0.634393), vec2(-0.707107, -0.707107), vec2(-0.634393, -0.773010), vec2(-0.555570, -0.831470), vec2(-0.471397, -0.881921), vec2(-0.382683, -0.923880), vec2(-0.290285, -0.956940), vec2(-0.195090, -0.980785), vec2(-0.098017, -0.995185), vec2(-0.000000, -1.000000), vec2(0.098017, -0.995185), vec2(0.195090, -0.980785), vec2(0.290285, -0.956940), vec2(0.382683, -0.923880), vec2(0.471397, -0.881921), vec2(0.555570, -0.831470), vec2(0.634393, -0.773010), vec2(0.707107, -0.707107), vec2(0.773010, -0.634393), vec2(0.831470, -0.555570), vec2(0.881921, -0.471397), vec2(0.923880, -0.382683), vec2(0.956940, -0.290285), vec2(0.980785, -0.195090), vec2(0.995185, -0.098017), vec2(1.000000, -0.000000), ]; pub const CIRCLE_128: [Vec2; 129] = [ vec2(1.000000, 0.000000), vec2(0.998795, 0.049068), vec2(0.995185, 0.098017), vec2(0.989177, 0.146730), vec2(0.980785, 0.195090), vec2(0.970031, 0.242980), vec2(0.956940, 0.290285), vec2(0.941544, 0.336890), vec2(0.923880, 0.382683), vec2(0.903989, 0.427555), vec2(0.881921, 0.471397), vec2(0.857729, 0.514103), vec2(0.831470, 0.555570), vec2(0.803208, 0.595699), vec2(0.773010, 0.634393), vec2(0.740951, 0.671559), vec2(0.707107, 0.707107), vec2(0.671559, 0.740951), vec2(0.634393, 0.773010), vec2(0.595699, 0.803208), vec2(0.555570, 0.831470), vec2(0.514103, 0.857729), vec2(0.471397, 0.881921), vec2(0.427555, 0.903989), vec2(0.382683, 0.923880), vec2(0.336890, 0.941544), vec2(0.290285, 0.956940), vec2(0.242980, 0.970031), vec2(0.195090, 0.980785), vec2(0.146730, 0.989177), vec2(0.098017, 0.995185), vec2(0.049068, 0.998795), vec2(0.000000, 1.000000), vec2(-0.049068, 0.998795), vec2(-0.098017, 0.995185), vec2(-0.146730, 0.989177), vec2(-0.195090, 0.980785), vec2(-0.242980, 0.970031), vec2(-0.290285, 0.956940), vec2(-0.336890, 0.941544), vec2(-0.382683, 0.923880), vec2(-0.427555, 0.903989), vec2(-0.471397, 0.881921), vec2(-0.514103, 0.857729), vec2(-0.555570, 0.831470), vec2(-0.595699, 0.803208), vec2(-0.634393, 0.773010), vec2(-0.671559, 0.740951), vec2(-0.707107, 0.707107), vec2(-0.740951, 0.671559), vec2(-0.773010, 0.634393), vec2(-0.803208, 0.595699), vec2(-0.831470, 0.555570), vec2(-0.857729, 0.514103), vec2(-0.881921, 0.471397), vec2(-0.903989, 0.427555), vec2(-0.923880, 0.382683), vec2(-0.941544, 0.336890), vec2(-0.956940, 0.290285), vec2(-0.970031, 0.242980), vec2(-0.980785, 0.195090), vec2(-0.989177, 0.146730), vec2(-0.995185, 0.098017), vec2(-0.998795, 0.049068), vec2(-1.000000, 0.000000), vec2(-0.998795, -0.049068), vec2(-0.995185, -0.098017), vec2(-0.989177, -0.146730), vec2(-0.980785, -0.195090), vec2(-0.970031, -0.242980), vec2(-0.956940, -0.290285), vec2(-0.941544, -0.336890), vec2(-0.923880, -0.382683), vec2(-0.903989, -0.427555), vec2(-0.881921, -0.471397), vec2(-0.857729, -0.514103), vec2(-0.831470, -0.555570), vec2(-0.803208, -0.595699), vec2(-0.773010, -0.634393), vec2(-0.740951, -0.671559), vec2(-0.707107, -0.707107), vec2(-0.671559, -0.740951), vec2(-0.634393, -0.773010), vec2(-0.595699, -0.803208), vec2(-0.555570, -0.831470), vec2(-0.514103, -0.857729), vec2(-0.471397, -0.881921), vec2(-0.427555, -0.903989), vec2(-0.382683, -0.923880), vec2(-0.336890, -0.941544), vec2(-0.290285, -0.956940), vec2(-0.242980, -0.970031), vec2(-0.195090, -0.980785), vec2(-0.146730, -0.989177), vec2(-0.098017, -0.995185), vec2(-0.049068, -0.998795), vec2(-0.000000, -1.000000), vec2(0.049068, -0.998795), vec2(0.098017, -0.995185), vec2(0.146730, -0.989177), vec2(0.195090, -0.980785), vec2(0.242980, -0.970031), vec2(0.290285, -0.956940), vec2(0.336890, -0.941544), vec2(0.382683, -0.923880), vec2(0.427555, -0.903989), vec2(0.471397, -0.881921), vec2(0.514103, -0.857729), vec2(0.555570, -0.831470), vec2(0.595699, -0.803208), vec2(0.634393, -0.773010), vec2(0.671559, -0.740951), vec2(0.707107, -0.707107), vec2(0.740951, -0.671559), vec2(0.773010, -0.634393), vec2(0.803208, -0.595699), vec2(0.831470, -0.555570), vec2(0.857729, -0.514103), vec2(0.881921, -0.471397), vec2(0.903989, -0.427555), vec2(0.923880, -0.382683), vec2(0.941544, -0.336890), vec2(0.956940, -0.290285), vec2(0.970031, -0.242980), vec2(0.980785, -0.195090), vec2(0.989177, -0.146730), vec2(0.995185, -0.098017), vec2(0.998795, -0.049068), vec2(1.000000, -0.000000), ]; } // ---------------------------------------------------------------------------- #[derive(Clone, Copy, Debug, Default, PartialEq)] struct PathPoint { pos: Pos2, /// For filled paths the normal is used for anti-aliasing (both strokes and filled areas). /// /// For strokes the normal is also used for giving thickness to the path /// (i.e. in what direction to expand). /// /// The normal could be estimated by differences between successive points, /// but that would be less accurate (and in some cases slower). /// /// Normals are normally unit-length. normal: Vec2, } /// A connected line (without thickness or gaps) which can be tessellated /// to either to a stroke (with thickness) or a filled convex area. /// Used as a scratch-pad during tessellation. #[derive(Clone, Debug, Default)] pub struct Path(Vec<PathPoint>); impl Path { #[inline(always)] pub fn clear(&mut self) { self.0.clear(); } #[inline(always)] pub fn reserve(&mut self, additional: usize) { self.0.reserve(additional); } #[inline(always)] pub fn add_point(&mut self, pos: Pos2, normal: Vec2) { self.0.push(PathPoint { pos, normal }); } pub fn add_circle(&mut self, center: Pos2, radius: f32) { use precomputed_vertices::{CIRCLE_8, CIRCLE_16, CIRCLE_32, CIRCLE_64, CIRCLE_128}; // These cutoffs are based on a high-dpi display. TODO(emilk): use pixels_per_point here? // same cutoffs as in add_circle_quadrant if radius <= 2.0 { self.0.extend(CIRCLE_8.iter().map(|&n| PathPoint { pos: center + radius * n, normal: n, })); } else if radius <= 5.0 { self.0.extend(CIRCLE_16.iter().map(|&n| PathPoint { pos: center + radius * n, normal: n, })); } else if radius < 18.0 { self.0.extend(CIRCLE_32.iter().map(|&n| PathPoint { pos: center + radius * n, normal: n, })); } else if radius < 50.0 { self.0.extend(CIRCLE_64.iter().map(|&n| PathPoint { pos: center + radius * n, normal: n, })); } else { self.0.extend(CIRCLE_128.iter().map(|&n| PathPoint { pos: center + radius * n, normal: n, })); } } pub fn add_line_segment(&mut self, points: [Pos2; 2]) { self.reserve(2); let normal = (points[1] - points[0]).normalized().rot90(); self.add_point(points[0], normal); self.add_point(points[1], normal); } pub fn add_open_points(&mut self, points: &[Pos2]) { let n = points.len(); assert!(n >= 2, "A path needs at least two points, but got {n}"); if n == 2 { // Common case optimization: self.add_line_segment([points[0], points[1]]); } else { self.reserve(n); self.add_point(points[0], (points[1] - points[0]).normalized().rot90()); let mut n0 = (points[1] - points[0]).normalized().rot90(); for i in 1..n - 1 { let mut n1 = (points[i + 1] - points[i]).normalized().rot90(); // Handle duplicated points (but not triplicated…): if n0 == Vec2::ZERO { n0 = n1; } else if n1 == Vec2::ZERO { n1 = n0; } let normal = (n0 + n1) / 2.0; let length_sq = normal.length_sq(); let right_angle_length_sq = 0.5; let sharper_than_a_right_angle = length_sq < right_angle_length_sq; if sharper_than_a_right_angle { // cut off the sharp corner let center_normal = normal.normalized(); let n0c = (n0 + center_normal) / 2.0; let n1c = (n1 + center_normal) / 2.0; self.add_point(points[i], n0c / n0c.length_sq()); self.add_point(points[i], n1c / n1c.length_sq()); } else { // miter join self.add_point(points[i], normal / length_sq); } n0 = n1; } self.add_point( points[n - 1], (points[n - 1] - points[n - 2]).normalized().rot90(), ); } } pub fn add_line_loop(&mut self, points: &[Pos2]) { let n = points.len(); assert!(n >= 2, "A path needs at least two points, but got {n}"); self.reserve(n); let mut n0 = (points[0] - points[n - 1]).normalized().rot90(); for i in 0..n { let next_i = if i + 1 == n { 0 } else { i + 1 }; let mut n1 = (points[next_i] - points[i]).normalized().rot90(); // Handle duplicated points (but not triplicated…): if n0 == Vec2::ZERO { n0 = n1; } else if n1 == Vec2::ZERO { n1 = n0; } let normal = (n0 + n1) / 2.0; let length_sq = normal.length_sq(); // We can't just cut off corners for filled shapes like this, // because the feather will both expand and contract the corner along the provided normals // to make sure it doesn't grow, and the shrinking will make the inner points cross each other. // // A better approach is to shrink the vertices in by half the feather-width here // and then only expand during feathering. // // See https://github.com/emilk/egui/issues/1226 const CUT_OFF_SHARP_CORNERS: bool = false; let right_angle_length_sq = 0.5; let sharper_than_a_right_angle = length_sq < right_angle_length_sq; if CUT_OFF_SHARP_CORNERS && sharper_than_a_right_angle { // cut off the sharp corner let center_normal = normal.normalized(); let n0c = (n0 + center_normal) / 2.0; let n1c = (n1 + center_normal) / 2.0; self.add_point(points[i], n0c / n0c.length_sq()); self.add_point(points[i], n1c / n1c.length_sq()); } else { // miter join self.add_point(points[i], normal / length_sq); } n0 = n1; } } /// The path is taken to be closed (i.e. returning to the start again). /// /// Calling this may reverse the vertices in the path if they are wrong winding order. /// The preferred winding order is clockwise. pub fn fill_and_stroke( &mut self, feathering: f32, fill: Color32, stroke: &PathStroke, out: &mut Mesh, ) { stroke_and_fill_path(feathering, &mut self.0, PathType::Closed, stroke, fill, out); } /// Open-ended. pub fn stroke_open(&mut self, feathering: f32, stroke: &PathStroke, out: &mut Mesh) { stroke_path(feathering, &mut self.0, PathType::Open, stroke, out); } /// A closed path (returning to the first point). pub fn stroke_closed(&mut self, feathering: f32, stroke: &PathStroke, out: &mut Mesh) { stroke_path(feathering, &mut self.0, PathType::Closed, stroke, out); } pub fn stroke( &mut self, feathering: f32, path_type: PathType, stroke: &PathStroke, out: &mut Mesh, ) { stroke_path(feathering, &mut self.0, path_type, stroke, out); } /// The path is taken to be closed (i.e. returning to the start again). /// /// Calling this may reverse the vertices in the path if they are wrong winding order. /// The preferred winding order is clockwise. pub fn fill(&mut self, feathering: f32, color: Color32, out: &mut Mesh) { fill_closed_path(feathering, &mut self.0, color, out); } /// Like [`Self::fill`] but with texturing. /// /// The `uv_from_pos` is called for each vertex position. pub fn fill_with_uv( &mut self, feathering: f32, color: Color32, texture_id: TextureId, uv_from_pos: impl Fn(Pos2) -> Pos2, out: &mut Mesh, ) { fill_closed_path_with_uv(feathering, &mut self.0, color, texture_id, uv_from_pos, out); } } pub mod path { //! Helpers for constructing paths use crate::CornerRadiusF32; use emath::{Pos2, Rect, pos2}; /// overwrites existing points pub fn rounded_rectangle(path: &mut Vec<Pos2>, rect: Rect, cr: CornerRadiusF32) { path.clear(); let min = rect.min; let max = rect.max; let cr = clamp_corner_radius(cr, rect); if cr == CornerRadiusF32::ZERO { path.reserve(4); path.push(pos2(min.x, min.y)); // left top path.push(pos2(max.x, min.y)); // right top path.push(pos2(max.x, max.y)); // right bottom path.push(pos2(min.x, max.y)); // left bottom } else { // We need to avoid duplicated vertices, because that leads to visual artifacts later. // Duplicated vertices can happen when one side is all rounding, with no straight edge between. let eps = f32::EPSILON * rect.size().max_elem(); add_circle_quadrant(path, pos2(max.x - cr.se, max.y - cr.se), cr.se, 0.0); // south east if rect.width() <= cr.se + cr.sw + eps { path.pop(); // avoid duplicated vertex } add_circle_quadrant(path, pos2(min.x + cr.sw, max.y - cr.sw), cr.sw, 1.0); // south west if rect.height() <= cr.sw + cr.nw + eps { path.pop(); // avoid duplicated vertex } add_circle_quadrant(path, pos2(min.x + cr.nw, min.y + cr.nw), cr.nw, 2.0); // north west if rect.width() <= cr.nw + cr.ne + eps { path.pop(); // avoid duplicated vertex } add_circle_quadrant(path, pos2(max.x - cr.ne, min.y + cr.ne), cr.ne, 3.0); // north east if rect.height() <= cr.ne + cr.se + eps { path.pop(); // avoid duplicated vertex } } } /// Add one quadrant of a circle /// /// * quadrant 0: right bottom /// * quadrant 1: left bottom /// * quadrant 2: left top /// * quadrant 3: right top // // Derivation: // // * angle 0 * TAU / 4 = right // - quadrant 0: right bottom // * angle 1 * TAU / 4 = bottom // - quadrant 1: left bottom // * angle 2 * TAU / 4 = left // - quadrant 2: left top // * angle 3 * TAU / 4 = top // - quadrant 3: right top // * angle 4 * TAU / 4 = right pub fn add_circle_quadrant(path: &mut Vec<Pos2>, center: Pos2, radius: f32, quadrant: f32) { use super::precomputed_vertices::{CIRCLE_8, CIRCLE_16, CIRCLE_32, CIRCLE_64, CIRCLE_128}; // These cutoffs are based on a high-dpi display. TODO(emilk): use pixels_per_point here? // same cutoffs as in add_circle if radius <= 0.0 { path.push(center); } else if radius <= 2.0 { let offset = quadrant as usize * 2; let quadrant_vertices = &CIRCLE_8[offset..=offset + 2]; path.extend(quadrant_vertices.iter().map(|&n| center + radius * n)); } else if radius <= 5.0 { let offset = quadrant as usize * 4; let quadrant_vertices = &CIRCLE_16[offset..=offset + 4]; path.extend(quadrant_vertices.iter().map(|&n| center + radius * n)); } else if radius < 18.0 { let offset = quadrant as usize * 8; let quadrant_vertices = &CIRCLE_32[offset..=offset + 8]; path.extend(quadrant_vertices.iter().map(|&n| center + radius * n)); } else if radius < 50.0 { let offset = quadrant as usize * 16; let quadrant_vertices = &CIRCLE_64[offset..=offset + 16]; path.extend(quadrant_vertices.iter().map(|&n| center + radius * n)); } else { let offset = quadrant as usize * 32; let quadrant_vertices = &CIRCLE_128[offset..=offset + 32]; path.extend(quadrant_vertices.iter().map(|&n| center + radius * n)); } } // Ensures the radius of each corner is within a valid range fn clamp_corner_radius(cr: CornerRadiusF32, rect: Rect) -> CornerRadiusF32 { let half_width = rect.width() * 0.5; let half_height = rect.height() * 0.5; let max_cr = half_width.min(half_height); cr.at_most(max_cr).at_least(0.0) } } // ---------------------------------------------------------------------------- #[derive(Clone, Copy, PartialEq, Eq)] pub enum PathType { Open, Closed, } /// Tessellation quality options #[derive(Clone, Copy, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] pub struct TessellationOptions { /// Use "feathering" to smooth out the edges of shapes as a form of anti-aliasing. /// /// Feathering works by making each edge into a thin gradient into transparency. /// The size of this edge is controlled by [`Self::feathering_size_in_pixels`]. /// /// This makes shapes appear smoother, but requires more triangles and is therefore slower. /// /// This setting does not affect text. /// /// Default: `true`. pub feathering: bool, /// The size of the feathering, in physical pixels. /// /// The default, and suggested, value for this is `1.0`. /// If you use a larger value, edges will appear blurry. pub feathering_size_in_pixels: f32, /// If `true` (default) cull certain primitives before tessellating them. /// This likely makes pub coarse_tessellation_culling: bool, /// If `true`, small filled circled will be optimized by using pre-rasterized circled /// from the font atlas. pub prerasterized_discs: bool, /// If `true` (default) align text to the physical pixel grid. /// This makes the text sharper on most platforms. pub round_text_to_pixels: bool, /// If `true` (default), align right-angled line segments to the physical pixel grid. /// /// This makes the line segments appear crisp on any display. pub round_line_segments_to_pixels: bool, /// If `true` (default), align rectangles to the physical pixel grid. /// /// This makes the rectangle strokes more crisp, /// and makes filled rectangles tile perfectly (without feathering). /// /// You can override this with [`crate::RectShape::round_to_pixels`]. pub round_rects_to_pixels: bool, /// Output the clip rectangles to be painted. pub debug_paint_clip_rects: bool, /// Output the text-containing rectangles. pub debug_paint_text_rects: bool, /// If true, no clipping will be done. pub debug_ignore_clip_rects: bool, /// The maximum distance between the original curve and the flattened curve. pub bezier_tolerance: f32, /// The default value will be 1.0e-5, it will be used during float compare. pub epsilon: f32, /// If `rayon` feature is activated, should we parallelize tessellation? pub parallel_tessellation: bool, /// If `true`, invalid meshes will be silently ignored. /// If `false`, invalid meshes will cause a panic. /// /// The default is `false` to save performance. pub validate_meshes: bool, } impl Default for TessellationOptions { fn default() -> Self { Self { feathering: true, feathering_size_in_pixels: 1.0, coarse_tessellation_culling: true, prerasterized_discs: true, round_text_to_pixels: true, round_line_segments_to_pixels: true, round_rects_to_pixels: true, debug_paint_text_rects: false, debug_paint_clip_rects: false, debug_ignore_clip_rects: false, bezier_tolerance: 0.1, epsilon: 1.0e-5, parallel_tessellation: true, validate_meshes: false, } } } fn cw_signed_area(path: &[PathPoint]) -> f64 { if let Some(last) = path.last() { let mut previous = last.pos; let mut area = 0.0; for p in path { area += (previous.x * p.pos.y - p.pos.x * previous.y) as f64; previous = p.pos; } area } else { 0.0 } } /// Tessellate the given convex area into a polygon. /// /// Calling this may reverse the vertices in the path if they are wrong winding order. /// /// The preferred winding order is clockwise. fn fill_closed_path(feathering: f32, path: &mut [PathPoint], fill_color: Color32, out: &mut Mesh) { if fill_color == Color32::TRANSPARENT { return; } let n = path.len() as u32; if n < 3 { return; } if 0.0 < feathering { if cw_signed_area(path) < 0.0 { // Wrong winding order - fix: path.reverse(); for point in &mut *path { point.normal = -point.normal; } } out.reserve_triangles(3 * n as usize); out.reserve_vertices(2 * n as usize); let idx_inner = out.vertices.len() as u32; let idx_outer = idx_inner + 1; // The fill: for i in 2..n { out.add_triangle(idx_inner + 2 * (i - 1), idx_inner, idx_inner + 2 * i); } // The feathering: let mut i0 = n - 1; for i1 in 0..n { let p1 = &path[i1 as usize]; let dm = 0.5 * feathering * p1.normal; let pos_inner = p1.pos - dm; let pos_outer = p1.pos + dm; out.colored_vertex(pos_inner, fill_color); out.colored_vertex(pos_outer, Color32::TRANSPARENT); out.add_triangle(idx_inner + i1 * 2, idx_inner + i0 * 2, idx_outer + 2 * i0); out.add_triangle(idx_outer + i0 * 2, idx_outer + i1 * 2, idx_inner + 2 * i1); i0 = i1; } } else { out.reserve_triangles(n as usize); let idx = out.vertices.len() as u32; out.vertices.extend(path.iter().map(|p| Vertex { pos: p.pos, uv: WHITE_UV, color: fill_color, })); for i in 2..n { out.add_triangle(idx, idx + i - 1, idx + i); } } } /// Like [`fill_closed_path`] but with texturing. /// /// The `uv_from_pos` is called for each vertex position. fn fill_closed_path_with_uv( feathering: f32, path: &mut [PathPoint], color: Color32, texture_id: TextureId, uv_from_pos: impl Fn(Pos2) -> Pos2, out: &mut Mesh, ) { if color == Color32::TRANSPARENT { return; } if out.is_empty() { out.texture_id = texture_id; } else { assert_eq!( out.texture_id, texture_id, "Mixing different `texture_id` in the same " ); } let n = path.len() as u32; if 0.0 < feathering { if cw_signed_area(path) < 0.0 { // Wrong winding order - fix: path.reverse(); for point in &mut *path { point.normal = -point.normal; } } out.reserve_triangles(3 * n as usize); out.reserve_vertices(2 * n as usize); let color_outer = Color32::TRANSPARENT; let idx_inner = out.vertices.len() as u32; let idx_outer = idx_inner + 1; // The fill: for i in 2..n { out.add_triangle(idx_inner + 2 * (i - 1), idx_inner, idx_inner + 2 * i); } // The feathering: let mut i0 = n - 1; for i1 in 0..n { let p1 = &path[i1 as usize]; let dm = 0.5 * feathering * p1.normal; let pos = p1.pos - dm; out.vertices.push(Vertex { pos, uv: uv_from_pos(pos), color, }); let pos = p1.pos + dm; out.vertices.push(Vertex { pos, uv: uv_from_pos(pos), color: color_outer, }); out.add_triangle(idx_inner + i1 * 2, idx_inner + i0 * 2, idx_outer + 2 * i0); out.add_triangle(idx_outer + i0 * 2, idx_outer + i1 * 2, idx_inner + 2 * i1); i0 = i1; } } else { out.reserve_triangles(n as usize); let idx = out.vertices.len() as u32; out.vertices.extend(path.iter().map(|p| Vertex { pos: p.pos, uv: uv_from_pos(p.pos), color, })); for i in 2..n { out.add_triangle(idx, idx + i - 1, idx + i); } } } /// Tessellate the given path as a stroke with thickness. fn stroke_path( feathering: f32, path: &mut [PathPoint], path_type: PathType, stroke: &PathStroke, out: &mut Mesh, ) { let fill = Color32::TRANSPARENT; stroke_and_fill_path(feathering, path, path_type, stroke, fill, out); } /// Tessellate the given path as a stroke with thickness, with optional fill color. /// /// Calling this may reverse the vertices in the path if they are wrong winding order. /// /// The preferred winding order is clockwise. fn stroke_and_fill_path( feathering: f32, path: &mut [PathPoint], path_type: PathType, stroke: &PathStroke, color_fill: Color32, out: &mut Mesh, ) { let n = path.len() as u32; if n < 2 { return; } if stroke.width == 0.0 { // Skip the stroke, just fill. return fill_closed_path(feathering, path, color_fill, out); } if color_fill != Color32::TRANSPARENT && cw_signed_area(path) < 0.0 { // Wrong winding order - fix: path.reverse(); for point in &mut *path { point.normal = -point.normal; } } if stroke.color == ColorMode::TRANSPARENT { // Skip the stroke, just fill. But subtract the width from the path: match stroke.kind { StrokeKind::Inside => { for point in &mut *path { point.pos -= stroke.width * point.normal; } } StrokeKind::Middle => { for point in &mut *path { point.pos -= 0.5 * stroke.width * point.normal; } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
true
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/epaint/src/corner_radius.rs
crates/epaint/src/corner_radius.rs
/// How rounded the corners of things should be. /// /// This specific the _corner radius_ of the underlying geometric shape (e.g. rectangle). /// If there is a stroke, then the stroke will have an inner and outer corner radius /// which will depends on its width and [`crate::StrokeKind`]. /// /// The rounding uses `u8` to save space, /// so the amount of rounding is limited to integers in the range `[0, 255]`. /// /// For calculations, you may want to use [`crate::CornerRadiusF32`] instead, which uses `f32`. #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct CornerRadius { /// Radius of the rounding of the North-West (left top) corner. pub nw: u8, /// Radius of the rounding of the North-East (right top) corner. pub ne: u8, /// Radius of the rounding of the South-West (left bottom) corner. pub sw: u8, /// Radius of the rounding of the South-East (right bottom) corner. pub se: u8, } impl Default for CornerRadius { #[inline] fn default() -> Self { Self::ZERO } } impl From<u8> for CornerRadius { #[inline] fn from(radius: u8) -> Self { Self::same(radius) } } impl From<f32> for CornerRadius { #[inline] fn from(radius: f32) -> Self { Self::same(radius.round() as u8) } } impl CornerRadius { /// No rounding on any corner. pub const ZERO: Self = Self { nw: 0, ne: 0, sw: 0, se: 0, }; /// Same rounding on all four corners. #[inline] pub const fn same(radius: u8) -> 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: u8) -> 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: u8) -> Self { Self { nw: self.nw.min(max), ne: self.ne.min(max), sw: self.sw.min(max), se: self.se.min(max), } } /// Average rounding of the corners. pub fn average(&self) -> f32 { (self.nw as f32 + self.ne as f32 + self.sw as f32 + self.se as f32) / 4.0 } } impl std::ops::Add for CornerRadius { type Output = Self; #[inline] fn add(self, rhs: Self) -> Self { Self { nw: self.nw.saturating_add(rhs.nw), ne: self.ne.saturating_add(rhs.ne), sw: self.sw.saturating_add(rhs.sw), se: self.se.saturating_add(rhs.se), } } } impl std::ops::Add<u8> for CornerRadius { type Output = Self; #[inline] fn add(self, rhs: u8) -> Self { Self { nw: self.nw.saturating_add(rhs), ne: self.ne.saturating_add(rhs), sw: self.sw.saturating_add(rhs), se: self.se.saturating_add(rhs), } } } impl std::ops::AddAssign for CornerRadius { #[inline] fn add_assign(&mut self, rhs: Self) { *self = Self { nw: self.nw.saturating_add(rhs.nw), ne: self.ne.saturating_add(rhs.ne), sw: self.sw.saturating_add(rhs.sw), se: self.se.saturating_add(rhs.se), }; } } impl std::ops::AddAssign<u8> for CornerRadius { #[inline] fn add_assign(&mut self, rhs: u8) { *self = Self { nw: self.nw.saturating_add(rhs), ne: self.ne.saturating_add(rhs), sw: self.sw.saturating_add(rhs), se: self.se.saturating_add(rhs), }; } } impl std::ops::Sub for CornerRadius { type Output = Self; #[inline] fn sub(self, rhs: Self) -> Self { Self { nw: self.nw.saturating_sub(rhs.nw), ne: self.ne.saturating_sub(rhs.ne), sw: self.sw.saturating_sub(rhs.sw), se: self.se.saturating_sub(rhs.se), } } } impl std::ops::Sub<u8> for CornerRadius { type Output = Self; #[inline] fn sub(self, rhs: u8) -> Self { Self { nw: self.nw.saturating_sub(rhs), ne: self.ne.saturating_sub(rhs), sw: self.sw.saturating_sub(rhs), se: self.se.saturating_sub(rhs), } } } impl std::ops::SubAssign for CornerRadius { #[inline] fn sub_assign(&mut self, rhs: Self) { *self = Self { nw: self.nw.saturating_sub(rhs.nw), ne: self.ne.saturating_sub(rhs.ne), sw: self.sw.saturating_sub(rhs.sw), se: self.se.saturating_sub(rhs.se), }; } } impl std::ops::SubAssign<u8> for CornerRadius { #[inline] fn sub_assign(&mut self, rhs: u8) { *self = Self { nw: self.nw.saturating_sub(rhs), ne: self.ne.saturating_sub(rhs), sw: self.sw.saturating_sub(rhs), se: self.se.saturating_sub(rhs), }; } } impl std::ops::Div<f32> for CornerRadius { type Output = Self; #[inline] fn div(self, rhs: f32) -> Self { Self { nw: (self.nw as f32 / rhs) as u8, ne: (self.ne as f32 / rhs) as u8, sw: (self.sw as f32 / rhs) as u8, se: (self.se as f32 / rhs) as u8, } } } impl std::ops::DivAssign<f32> for CornerRadius { #[inline] fn div_assign(&mut self, rhs: f32) { *self = Self { nw: (self.nw as f32 / rhs) as u8, ne: (self.ne as f32 / rhs) as u8, sw: (self.sw as f32 / rhs) as u8, se: (self.se as f32 / rhs) as u8, }; } } impl std::ops::Mul<f32> for CornerRadius { type Output = Self; #[inline] fn mul(self, rhs: f32) -> Self { Self { nw: (self.nw as f32 * rhs) as u8, ne: (self.ne as f32 * rhs) as u8, sw: (self.sw as f32 * rhs) as u8, se: (self.se as f32 * rhs) as u8, } } } impl std::ops::MulAssign<f32> for CornerRadius { #[inline] fn mul_assign(&mut self, rhs: f32) { *self = Self { nw: (self.nw as f32 * rhs) as u8, ne: (self.ne as f32 * rhs) as u8, sw: (self.sw as f32 * rhs) as u8, se: (self.se as f32 * rhs) as u8, }; } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/epaint/src/mesh.rs
crates/epaint/src/mesh.rs
use crate::{Color32, TextureId, WHITE_UV, emath}; use emath::{Pos2, Rect, Rot2, TSTransform, Vec2}; /// The 2D vertex type. /// /// Should be friendly to send to GPU as is. #[repr(C)] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] #[cfg(any(not(feature = "unity"), feature = "_override_unity"))] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "bytemuck", derive(bytemuck::Pod, bytemuck::Zeroable))] pub struct Vertex { /// Logical pixel coordinates (points). /// (0,0) is the top left corner of the screen. pub pos: Pos2, // 64 bit /// Normalized texture coordinates. /// (0, 0) is the top left corner of the texture. /// (1, 1) is the bottom right corner of the texture. pub uv: Pos2, // 64 bit /// sRGBA with premultiplied alpha pub color: Color32, // 32 bit } #[repr(C)] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] #[cfg(all(feature = "unity", not(feature = "_override_unity")))] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "bytemuck", derive(bytemuck::Pod, bytemuck::Zeroable))] pub struct Vertex { /// Logical pixel coordinates (points). /// (0,0) is the top left corner of the screen. pub pos: Pos2, // 64 bit /// sRGBA with premultiplied alpha pub color: Color32, // 32 bit /// Normalized texture coordinates. /// (0, 0) is the top left corner of the texture. /// (1, 1) is the bottom right corner of the texture. pub uv: Pos2, // 64 bit } /// Textured triangles in two dimensions. #[derive(Clone, Debug, Default, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct Mesh { /// Draw as triangles (i.e. the length is always multiple of three). /// /// If you only support 16-bit indices you can use [`Mesh::split_to_u16`]. /// /// egui is NOT consistent with what winding order it uses, so turn off backface culling. pub indices: Vec<u32>, /// The vertex data indexed by `indices`. pub vertices: Vec<Vertex>, /// The texture to use when drawing these triangles. pub texture_id: TextureId, // TODO(emilk): bounding rectangle } impl Mesh { pub fn with_texture(texture_id: TextureId) -> Self { Self { texture_id, ..Default::default() } } /// Restore to default state, but without freeing memory. pub fn clear(&mut self) { self.indices.clear(); self.vertices.clear(); self.vertices = Default::default(); } /// Returns the amount of memory used by the vertices and indices. pub fn bytes_used(&self) -> usize { std::mem::size_of::<Self>() + self.vertices.len() * std::mem::size_of::<Vertex>() + self.indices.len() * std::mem::size_of::<u32>() } /// Are all indices within the bounds of the contained vertices? pub fn is_valid(&self) -> bool { profiling::function_scope!(); if let Ok(n) = u32::try_from(self.vertices.len()) { self.indices.iter().all(|&i| i < n) } else { false } } pub fn is_empty(&self) -> bool { self.indices.is_empty() && self.vertices.is_empty() } /// Iterate over the triangles of this mesh, returning vertex indices. pub fn triangles(&self) -> impl Iterator<Item = [u32; 3]> + '_ { self.indices .chunks_exact(3) .map(|chunk| [chunk[0], chunk[1], chunk[2]]) } /// Calculate a bounding rectangle. pub fn calc_bounds(&self) -> Rect { let mut bounds = Rect::NOTHING; for v in &self.vertices { bounds.extend_with(v.pos); } bounds } /// Append all the indices and vertices of `other` to `self`. /// /// Panics when `other` mesh has a different texture. pub fn append(&mut self, other: Self) { profiling::function_scope!(); debug_assert!(other.is_valid(), "Other mesh is invalid"); if self.is_empty() { *self = other; } else { self.append_ref(&other); } } /// Append all the indices and vertices of `other` to `self` without /// taking ownership. /// /// Panics when `other` mesh has a different texture. pub fn append_ref(&mut self, other: &Self) { debug_assert!(other.is_valid(), "Other mesh is invalid"); if self.is_empty() { self.texture_id = other.texture_id; } else { assert_eq!( self.texture_id, other.texture_id, "Can't merge Mesh using different textures" ); } let index_offset = self.vertices.len() as u32; self.indices .extend(other.indices.iter().map(|index| index + index_offset)); self.vertices.extend(other.vertices.iter()); } /// Add a colored vertex. /// /// Panics when the mesh has assigned a texture. #[inline(always)] pub fn colored_vertex(&mut self, pos: Pos2, color: Color32) { debug_assert!( self.texture_id == TextureId::default(), "Mesh has an assigned texture" ); self.vertices.push(Vertex { pos, uv: WHITE_UV, color, }); } /// Add a triangle. #[inline(always)] pub fn add_triangle(&mut self, a: u32, b: u32, c: u32) { self.indices.extend_from_slice(&[a, b, c]); } /// Make room for this many additional triangles (will reserve 3x as many indices). /// See also `reserve_vertices`. #[inline(always)] pub fn reserve_triangles(&mut self, additional_triangles: usize) { self.indices.reserve(3 * additional_triangles); } /// Make room for this many additional vertices. /// See also `reserve_triangles`. #[inline(always)] pub fn reserve_vertices(&mut self, additional: usize) { self.vertices.reserve(additional); } /// Rectangle with a texture and color. #[inline(always)] pub fn add_rect_with_uv(&mut self, rect: Rect, uv: Rect, color: Color32) { #![expect(clippy::identity_op)] let idx = self.vertices.len() as u32; self.indices .extend_from_slice(&[idx + 0, idx + 1, idx + 2, idx + 2, idx + 1, idx + 3]); self.vertices.extend_from_slice(&[ Vertex { pos: rect.left_top(), uv: uv.left_top(), color, }, Vertex { pos: rect.right_top(), uv: uv.right_top(), color, }, Vertex { pos: rect.left_bottom(), uv: uv.left_bottom(), color, }, Vertex { pos: rect.right_bottom(), uv: uv.right_bottom(), color, }, ]); } /// Uniformly colored rectangle. #[inline(always)] pub fn add_colored_rect(&mut self, rect: Rect, color: Color32) { debug_assert!( self.texture_id == TextureId::default(), "Mesh has an assigned texture" ); self.add_rect_with_uv(rect, [WHITE_UV, WHITE_UV].into(), color); } /// This is for platforms that only support 16-bit index buffers. /// /// Splits this mesh into many smaller meshes (if needed) /// where the smaller meshes have 16-bit indices. pub fn split_to_u16(self) -> Vec<Mesh16> { debug_assert!(self.is_valid(), "Mesh is invalid"); const MAX_SIZE: u32 = u16::MAX as u32; if self.vertices.len() <= MAX_SIZE as usize { // Common-case optimization: return vec![Mesh16 { indices: self.indices.iter().map(|&i| i as u16).collect(), vertices: self.vertices, texture_id: self.texture_id, }]; } let mut output = vec![]; let mut index_cursor = 0; while index_cursor < self.indices.len() { let span_start = index_cursor; let mut min_vindex = self.indices[index_cursor]; let mut max_vindex = self.indices[index_cursor]; while index_cursor < self.indices.len() { let (mut new_min, mut new_max) = (min_vindex, max_vindex); for i in 0..3 { let idx = self.indices[index_cursor + i]; new_min = new_min.min(idx); new_max = new_max.max(idx); } let new_span_size = new_max - new_min + 1; // plus one, because it is an inclusive range if new_span_size <= MAX_SIZE { // Triangle fits min_vindex = new_min; max_vindex = new_max; index_cursor += 3; } else { break; } } assert!( index_cursor > span_start, "One triangle spanned more than {MAX_SIZE} vertices" ); let mesh = Mesh16 { indices: self.indices[span_start..index_cursor] .iter() .map(|vi| { #[expect(clippy::unwrap_used)] { u16::try_from(vi - min_vindex).unwrap() } }) .collect(), vertices: self.vertices[(min_vindex as usize)..=(max_vindex as usize)].to_vec(), texture_id: self.texture_id, }; debug_assert!(mesh.is_valid(), "Mesh is invalid"); output.push(mesh); } output } /// Translate location by this much, in-place pub fn translate(&mut self, delta: Vec2) { for v in &mut self.vertices { v.pos += delta; } } /// Transform the mesh in-place with the given transform. pub fn transform(&mut self, transform: TSTransform) { for v in &mut self.vertices { v.pos = transform * v.pos; } } /// Rotate by some angle about an origin, in-place. /// /// Origin is a position in screen space. pub fn rotate(&mut self, rot: Rot2, origin: Pos2) { for v in &mut self.vertices { v.pos = origin + rot * (v.pos - origin); } } } // ---------------------------------------------------------------------------- /// A version of [`Mesh`] that uses 16-bit indices. /// /// This is produced by [`Mesh::split_to_u16`] and is meant to be used for legacy render backends. pub struct Mesh16 { /// Draw as triangles (i.e. the length is always multiple of three). /// /// egui is NOT consistent with what winding order it uses, so turn off backface culling. pub indices: Vec<u16>, /// The vertex data indexed by `indices`. pub vertices: Vec<Vertex>, /// The texture to use when drawing these triangles. pub texture_id: TextureId, } impl Mesh16 { /// Are all indices within the bounds of the contained vertices? pub fn is_valid(&self) -> bool { if let Ok(n) = u16::try_from(self.vertices.len()) { self.indices.iter().all(|&i| i < n) } else { false } } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false