Avoid deadlocks by using lambdas for context lock (#2625)

ctx.input().key_pressed(Key::A) -> ctx.input(|i| i.key_pressed(Key::A))
This commit is contained in:
Emil Ernerfeldt 2023-01-25 10:24:23 +01:00 committed by GitHub
parent eee4cf6a82
commit 8ce0e1c520
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
77 changed files with 1445 additions and 1123 deletions

3
.gitignore vendored
View File

@ -1,6 +1,7 @@
.DS_Store
**/target **/target
**/target_ra **/target_ra
**/target_wasm
/.*.json /.*.json
/.vscode /.vscode
/media/* /media/*
.DS_Store

View File

@ -5,6 +5,10 @@ NOTE: [`epaint`](crates/epaint/CHANGELOG.md), [`eframe`](crates/eframe/CHANGELOG
## Unreleased ## Unreleased
* ⚠️ BREAKING: `egui::Context` now use closures for locking ([#2625](https://github.com/emilk/egui/pull/2625)):
* `ctx.input().key_pressed(Key::A)` -> `ctx.input(|i| i.key_pressed(Key::A))`
* `ui.memory().toggle_popup(popup_id)` -> `ui.memory_mut(|mem| mem.toggle_popup(popup_id))`
### Added ⭐ ### Added ⭐
* Add `Response::drag_started_by` and `Response::drag_released_by` for convenience, similar to `dragged` and `dragged_by` ([#2507](https://github.com/emilk/egui/pull/2507)). * Add `Response::drag_started_by` and `Response::drag_released_by` for convenience, similar to `dragged` and `dragged_by` ([#2507](https://github.com/emilk/egui/pull/2507)).
* Add `PointerState::*_pressed` to check if the given button was pressed in this frame ([#2507](https://github.com/emilk/egui/pull/2507)). * Add `PointerState::*_pressed` to check if the given button was pressed in this frame ([#2507](https://github.com/emilk/egui/pull/2507)).
@ -18,6 +22,7 @@ NOTE: [`epaint`](crates/epaint/CHANGELOG.md), [`eframe`](crates/eframe/CHANGELOG
* Add `ProgressBar::fill` if you want to set the fill color manually. ([#2618](https://github.com/emilk/egui/pull/2618)). * Add `ProgressBar::fill` if you want to set the fill color manually. ([#2618](https://github.com/emilk/egui/pull/2618)).
* Add `Button::rounding` to enable round buttons ([#2616](https://github.com/emilk/egui/pull/2616)). * Add `Button::rounding` to enable round buttons ([#2616](https://github.com/emilk/egui/pull/2616)).
* Add `WidgetVisuals::optional_bg_color` - set it to `Color32::TRANSPARENT` to hide button backgrounds ([#2621](https://github.com/emilk/egui/pull/2621)). * Add `WidgetVisuals::optional_bg_color` - set it to `Color32::TRANSPARENT` to hide button backgrounds ([#2621](https://github.com/emilk/egui/pull/2621)).
* Add `Context::screen_rect` and `Context::set_cursor_icon` ([#2625](https://github.com/emilk/egui/pull/2625)).
### Changed 🔧 ### Changed 🔧
* Improved plot grid appearance ([#2412](https://github.com/emilk/egui/pull/2412)). * Improved plot grid appearance ([#2412](https://github.com/emilk/egui/pull/2412)).

7
Cargo.lock generated
View File

@ -2171,6 +2171,13 @@ dependencies = [
"tracing-subscriber", "tracing-subscriber",
] ]
[[package]]
name = "hello_world_par"
version = "0.1.0"
dependencies = [
"eframe",
]
[[package]] [[package]]
name = "hermit-abi" name = "hermit-abi"
version = "0.1.19" version = "0.1.19"

View File

@ -371,6 +371,8 @@ egui uses the builder pattern for construction widgets. For instance: `ui.add(La
Instead of using matching `begin/end` style function calls (which can be error prone) egui prefers to use `FnOnce` closures passed to a wrapping function. Lambdas are a bit ugly though, so I'd like to find a nicer solution to this. More discussion of this at <https://github.com/emilk/egui/issues/1004#issuecomment-1001650754>. Instead of using matching `begin/end` style function calls (which can be error prone) egui prefers to use `FnOnce` closures passed to a wrapping function. Lambdas are a bit ugly though, so I'd like to find a nicer solution to this. More discussion of this at <https://github.com/emilk/egui/issues/1004#issuecomment-1001650754>.
egui uses a single `RwLock` for short-time locks on each access of `Context` data. This is to leave implementation simple and transactional and allow users to run their UI logic in parallel. Instead of creating mutex guards, egui uses closures passed to a wrapping function, e.g. `ctx.input(|i| i.key_down(Key::A))`. This is to make it less likely that a user would accidentally double-lock the `Context`, which would lead to a deadlock.
### Inspiration ### Inspiration
The one and only [Dear ImGui](https://github.com/ocornut/imgui) is a great Immediate Mode GUI for C++ which works with many backends. That library revolutionized how I think about GUI code and turned GUI programming from something I hated to do to something I now enjoy. The one and only [Dear ImGui](https://github.com/ocornut/imgui) is a great Immediate Mode GUI for C++ which works with many backends. That library revolutionized how I think about GUI code and turned GUI programming from something I hated to do to something I now enjoy.
@ -396,6 +398,7 @@ Notable contributions by:
* [@mankinskin](https://github.com/mankinskin): [Context menus](https://github.com/emilk/egui/pull/543). * [@mankinskin](https://github.com/mankinskin): [Context menus](https://github.com/emilk/egui/pull/543).
* [@t18b219k](https://github.com/t18b219k): [Port glow painter to web](https://github.com/emilk/egui/pull/868). * [@t18b219k](https://github.com/t18b219k): [Port glow painter to web](https://github.com/emilk/egui/pull/868).
* [@danielkeller](https://github.com/danielkeller): [`Context` refactor](https://github.com/emilk/egui/pull/1050). * [@danielkeller](https://github.com/danielkeller): [`Context` refactor](https://github.com/emilk/egui/pull/1050).
* [@MaximOsipenko](https://github.com/MaximOsipenko): [`Context` lock refactor](https://github.com/emilk/egui/pull/2625).
* And [many more](https://github.com/emilk/egui/graphs/contributors?type=a). * And [many more](https://github.com/emilk/egui/graphs/contributors?type=a).
egui is licensed under [MIT](LICENSE-MIT) OR [Apache-2.0](LICENSE-APACHE). egui is licensed under [MIT](LICENSE-MIT) OR [Apache-2.0](LICENSE-APACHE).

View File

@ -55,7 +55,7 @@ persistence = [
## `eframe` will call `puffin::GlobalProfiler::lock().new_frame()` for you ## `eframe` will call `puffin::GlobalProfiler::lock().new_frame()` for you
puffin = ["dep:puffin", "egui_glow?/puffin", "egui-wgpu?/puffin"] puffin = ["dep:puffin", "egui_glow?/puffin", "egui-wgpu?/puffin"]
## Enable screen reader support (requires `ctx.options().screen_reader = true;`) ## Enable screen reader support (requires `ctx.options_mut(|o| o.screen_reader = true);`)
screen_reader = ["egui-winit/screen_reader", "tts"] screen_reader = ["egui-winit/screen_reader", "tts"]
## If set, eframe will look for the env-var `EFRAME_SCREENSHOT_TO` and write a screenshot to that location, and then quit. ## If set, eframe will look for the env-var `EFRAME_SCREENSHOT_TO` and write a screenshot to that location, and then quit.

View File

@ -173,7 +173,7 @@ pub trait App {
} }
/// If `true` a warm-up call to [`Self::update`] will be issued where /// If `true` a warm-up call to [`Self::update`] will be issued where
/// `ctx.memory().everything_is_visible()` will be set to `true`. /// `ctx.memory(|mem| mem.everything_is_visible())` will be set to `true`.
/// ///
/// This can help pre-caching resources loaded by different parts of the UI, preventing stutter later on. /// This can help pre-caching resources loaded by different parts of the UI, preventing stutter later on.
/// ///

View File

@ -257,7 +257,8 @@ impl EpiIntegration {
) -> Self { ) -> Self {
let egui_ctx = egui::Context::default(); let egui_ctx = egui::Context::default();
*egui_ctx.memory() = load_egui_memory(storage.as_deref()).unwrap_or_default(); let memory = load_egui_memory(storage.as_deref()).unwrap_or_default();
egui_ctx.memory_mut(|mem| *mem = memory);
let native_pixels_per_point = window.scale_factor() as f32; let native_pixels_per_point = window.scale_factor() as f32;
@ -315,11 +316,12 @@ impl EpiIntegration {
pub fn warm_up(&mut self, app: &mut dyn epi::App, window: &winit::window::Window) { pub fn warm_up(&mut self, app: &mut dyn epi::App, window: &winit::window::Window) {
crate::profile_function!(); crate::profile_function!();
let saved_memory: egui::Memory = self.egui_ctx.memory().clone(); let saved_memory: egui::Memory = self.egui_ctx.memory(|mem| mem.clone());
self.egui_ctx.memory().set_everything_is_visible(true); self.egui_ctx
.memory_mut(|mem| mem.set_everything_is_visible(true));
let full_output = self.update(app, window); let full_output = self.update(app, window);
self.pending_full_output.append(full_output); // Handle it next frame self.pending_full_output.append(full_output); // Handle it next frame
*self.egui_ctx.memory() = saved_memory; // We don't want to remember that windows were huge. self.egui_ctx.memory_mut(|mem| *mem = saved_memory); // We don't want to remember that windows were huge.
self.egui_ctx.clear_animations(); self.egui_ctx.clear_animations();
} }
@ -446,7 +448,8 @@ impl EpiIntegration {
} }
if _app.persist_egui_memory() { if _app.persist_egui_memory() {
crate::profile_scope!("egui_memory"); crate::profile_scope!("egui_memory");
epi::set_value(storage, STORAGE_EGUI_MEMORY_KEY, &*self.egui_ctx.memory()); self.egui_ctx
.memory(|mem| epi::set_value(storage, STORAGE_EGUI_MEMORY_KEY, mem));
} }
{ {
crate::profile_scope!("App::save"); crate::profile_scope!("App::save");

View File

@ -313,10 +313,11 @@ impl AppRunner {
pub fn warm_up(&mut self) -> Result<(), JsValue> { pub fn warm_up(&mut self) -> Result<(), JsValue> {
if self.app.warm_up_enabled() { if self.app.warm_up_enabled() {
let saved_memory: egui::Memory = self.egui_ctx.memory().clone(); let saved_memory: egui::Memory = self.egui_ctx.memory(|m| m.clone());
self.egui_ctx.memory().set_everything_is_visible(true); self.egui_ctx
.memory_mut(|m| m.set_everything_is_visible(true));
self.logic()?; self.logic()?;
*self.egui_ctx.memory() = saved_memory; // We don't want to remember that windows were huge. self.egui_ctx.memory_mut(|m| *m = saved_memory); // We don't want to remember that windows were huge.
self.egui_ctx.clear_animations(); self.egui_ctx.clear_animations();
} }
Ok(()) Ok(())
@ -388,7 +389,7 @@ impl AppRunner {
} }
fn handle_platform_output(&mut self, platform_output: egui::PlatformOutput) { fn handle_platform_output(&mut self, platform_output: egui::PlatformOutput) {
if self.egui_ctx.options().screen_reader { if self.egui_ctx.options(|o| o.screen_reader) {
self.screen_reader self.screen_reader
.speak(&platform_output.events_description()); .speak(&platform_output.events_description());
} }

View File

@ -15,7 +15,7 @@ pub fn load_memory(ctx: &egui::Context) {
if let Some(memory_string) = local_storage_get("egui_memory_ron") { if let Some(memory_string) = local_storage_get("egui_memory_ron") {
match ron::from_str(&memory_string) { match ron::from_str(&memory_string) {
Ok(memory) => { Ok(memory) => {
*ctx.memory() = memory; ctx.memory_mut(|m| *m = memory);
} }
Err(err) => { Err(err) => {
tracing::error!("Failed to parse memory RON: {}", err); tracing::error!("Failed to parse memory RON: {}", err);
@ -29,7 +29,7 @@ pub fn load_memory(_: &egui::Context) {}
#[cfg(feature = "persistence")] #[cfg(feature = "persistence")]
pub fn save_memory(ctx: &egui::Context) { pub fn save_memory(ctx: &egui::Context) {
match ron::to_string(&*ctx.memory()) { match ctx.memory(|mem| ron::to_string(mem)) {
Ok(ron) => { Ok(ron) => {
local_storage_set("egui_memory_ron", &ron); local_storage_set("egui_memory_ron", &ron);
} }

View File

@ -615,7 +615,7 @@ impl State {
egui_ctx: &egui::Context, egui_ctx: &egui::Context,
platform_output: egui::PlatformOutput, platform_output: egui::PlatformOutput,
) { ) {
if egui_ctx.options().screen_reader { if egui_ctx.options(|o| o.screen_reader) {
self.screen_reader self.screen_reader
.speak(&platform_output.events_description()); .speak(&platform_output.events_description());
} }

View File

@ -5,7 +5,7 @@
use crate::*; use crate::*;
/// State that is persisted between frames. /// State that is persisted between frames.
// TODO(emilk): this is not currently stored in `memory().data`, but maybe it should be? // TODO(emilk): this is not currently stored in `Memory::data`, but maybe it should be?
#[derive(Clone, Copy, Debug)] #[derive(Clone, Copy, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub(crate) struct State { pub(crate) struct State {
@ -231,7 +231,7 @@ impl Area {
let layer_id = LayerId::new(order, id); let layer_id = LayerId::new(order, id);
let state = ctx.memory().areas.get(id).copied(); let state = ctx.memory(|mem| mem.areas.get(id).copied());
let is_new = state.is_none(); let is_new = state.is_none();
if is_new { if is_new {
ctx.request_repaint(); // if we don't know the previous size we are likely drawing the area in the wrong place ctx.request_repaint(); // if we don't know the previous size we are likely drawing the area in the wrong place
@ -278,7 +278,7 @@ impl Area {
// Important check - don't try to move e.g. a combobox popup! // Important check - don't try to move e.g. a combobox popup!
if movable { if movable {
if move_response.dragged() { if move_response.dragged() {
state.pos += ctx.input().pointer.delta(); state.pos += ctx.input(|i| i.pointer.delta());
} }
state.pos = ctx state.pos = ctx
@ -288,9 +288,9 @@ impl Area {
if (move_response.dragged() || move_response.clicked()) if (move_response.dragged() || move_response.clicked())
|| pointer_pressed_on_area(ctx, layer_id) || pointer_pressed_on_area(ctx, layer_id)
|| !ctx.memory().areas.visible_last_frame(&layer_id) || !ctx.memory(|m| m.areas.visible_last_frame(&layer_id))
{ {
ctx.memory().areas.move_to_top(layer_id); ctx.memory_mut(|m| m.areas.move_to_top(layer_id));
ctx.request_repaint(); ctx.request_repaint();
} }
@ -329,7 +329,7 @@ impl Area {
} }
let layer_id = LayerId::new(self.order, self.id); let layer_id = LayerId::new(self.order, self.id);
let area_rect = ctx.memory().areas.get(self.id).map(|area| area.rect()); let area_rect = ctx.memory(|mem| mem.areas.get(self.id).map(|area| area.rect()));
if let Some(area_rect) = area_rect { if let Some(area_rect) = area_rect {
let clip_rect = ctx.available_rect(); let clip_rect = ctx.available_rect();
let painter = Painter::new(ctx.clone(), layer_id, clip_rect); let painter = Painter::new(ctx.clone(), layer_id, clip_rect);
@ -358,7 +358,7 @@ impl Prepared {
} }
pub(crate) fn content_ui(&self, ctx: &Context) -> Ui { pub(crate) fn content_ui(&self, ctx: &Context) -> Ui {
let screen_rect = ctx.input().screen_rect(); let screen_rect = ctx.screen_rect();
let bounds = if let Some(bounds) = self.drag_bounds { let bounds = if let Some(bounds) = self.drag_bounds {
bounds.intersect(screen_rect) // protect against infinite bounds bounds.intersect(screen_rect) // protect against infinite bounds
@ -410,7 +410,7 @@ impl Prepared {
state.size = content_ui.min_rect().size(); state.size = content_ui.min_rect().size();
ctx.memory().areas.set_state(layer_id, state); ctx.memory_mut(|m| m.areas.set_state(layer_id, state));
move_response move_response
} }
@ -418,7 +418,7 @@ impl Prepared {
fn pointer_pressed_on_area(ctx: &Context, layer_id: LayerId) -> bool { fn pointer_pressed_on_area(ctx: &Context, layer_id: LayerId) -> bool {
if let Some(pointer_pos) = ctx.pointer_interact_pos() { if let Some(pointer_pos) = ctx.pointer_interact_pos() {
let any_pressed = ctx.input().pointer.any_pressed(); let any_pressed = ctx.input(|i| i.pointer.any_pressed());
any_pressed && ctx.layer_id_at(pointer_pos) == Some(layer_id) any_pressed && ctx.layer_id_at(pointer_pos) == Some(layer_id)
} else { } else {
false false
@ -426,13 +426,13 @@ fn pointer_pressed_on_area(ctx: &Context, layer_id: LayerId) -> bool {
} }
fn automatic_area_position(ctx: &Context) -> Pos2 { fn automatic_area_position(ctx: &Context) -> Pos2 {
let mut existing: Vec<Rect> = ctx let mut existing: Vec<Rect> = ctx.memory(|mem| {
.memory() mem.areas
.areas .visible_windows()
.visible_windows() .into_iter()
.into_iter() .map(State::rect)
.map(State::rect) .collect()
.collect(); });
existing.sort_by_key(|r| r.left().round() as i32); existing.sort_by_key(|r| r.left().round() as i32);
let available_rect = ctx.available_rect(); let available_rect = ctx.available_rect();

View File

@ -26,13 +26,14 @@ pub struct CollapsingState {
impl CollapsingState { impl CollapsingState {
pub fn load(ctx: &Context, id: Id) -> Option<Self> { pub fn load(ctx: &Context, id: Id) -> Option<Self> {
ctx.data() ctx.data_mut(|d| {
.get_persisted::<InnerState>(id) d.get_persisted::<InnerState>(id)
.map(|state| Self { id, state }) .map(|state| Self { id, state })
})
} }
pub fn store(&self, ctx: &Context) { pub fn store(&self, ctx: &Context) {
ctx.data().insert_persisted(self.id, self.state); ctx.data_mut(|d| d.insert_persisted(self.id, self.state));
} }
pub fn id(&self) -> Id { pub fn id(&self) -> Id {
@ -64,7 +65,7 @@ impl CollapsingState {
/// 0 for closed, 1 for open, with tweening /// 0 for closed, 1 for open, with tweening
pub fn openness(&self, ctx: &Context) -> f32 { pub fn openness(&self, ctx: &Context) -> f32 {
if ctx.memory().everything_is_visible() { if ctx.memory(|mem| mem.everything_is_visible()) {
1.0 1.0
} else { } else {
ctx.animate_bool(self.id, self.state.open) ctx.animate_bool(self.id, self.state.open)

View File

@ -242,18 +242,13 @@ fn combo_box_dyn<'c, R>(
) -> InnerResponse<Option<R>> { ) -> InnerResponse<Option<R>> {
let popup_id = button_id.with("popup"); let popup_id = button_id.with("popup");
let is_popup_open = ui.memory().is_popup_open(popup_id); let is_popup_open = ui.memory(|m| m.is_popup_open(popup_id));
let popup_height = ui let popup_height = ui.memory(|m| m.areas.get(popup_id).map_or(100.0, |state| state.size.y));
.ctx()
.memory()
.areas
.get(popup_id)
.map_or(100.0, |state| state.size.y);
let above_or_below = let above_or_below =
if ui.next_widget_position().y + ui.spacing().interact_size.y + popup_height if ui.next_widget_position().y + ui.spacing().interact_size.y + popup_height
< ui.ctx().input().screen_rect().bottom() < ui.ctx().screen_rect().bottom()
{ {
AboveOrBelow::Below AboveOrBelow::Below
} else { } else {
@ -334,7 +329,7 @@ fn combo_box_dyn<'c, R>(
}); });
if button_response.clicked() { if button_response.clicked() {
ui.memory().toggle_popup(popup_id); ui.memory_mut(|mem| mem.toggle_popup(popup_id));
} }
let inner = crate::popup::popup_above_or_below_widget( let inner = crate::popup::popup_above_or_below_widget(
ui, ui,

View File

@ -28,7 +28,7 @@ pub struct PanelState {
impl PanelState { impl PanelState {
pub fn load(ctx: &Context, bar_id: Id) -> Option<Self> { pub fn load(ctx: &Context, bar_id: Id) -> Option<Self> {
ctx.data().get_persisted(bar_id) ctx.data_mut(|d| d.get_persisted(bar_id))
} }
/// The size of the panel (from previous frame). /// The size of the panel (from previous frame).
@ -37,7 +37,7 @@ impl PanelState {
} }
fn store(self, ctx: &Context, bar_id: Id) { fn store(self, ctx: &Context, bar_id: Id) {
ctx.data().insert_persisted(bar_id, self); ctx.data_mut(|d| d.insert_persisted(bar_id, self));
} }
} }
@ -245,11 +245,12 @@ impl SidePanel {
&& (resize_x - pointer.x).abs() && (resize_x - pointer.x).abs()
<= ui.style().interaction.resize_grab_radius_side; <= ui.style().interaction.resize_grab_radius_side;
let any_pressed = ui.input().pointer.any_pressed(); // avoid deadlocks if ui.input(|i| i.pointer.any_pressed() && i.pointer.any_down())
if any_pressed && ui.input().pointer.any_down() && mouse_over_resize_line { && mouse_over_resize_line
ui.memory().set_dragged_id(resize_id); {
ui.memory_mut(|mem| mem.set_dragged_id(resize_id));
} }
is_resizing = ui.memory().is_being_dragged(resize_id); is_resizing = ui.memory(|mem| mem.is_being_dragged(resize_id));
if is_resizing { if is_resizing {
let width = (pointer.x - side.side_x(panel_rect)).abs(); let width = (pointer.x - side.side_x(panel_rect)).abs();
let width = let width =
@ -257,12 +258,12 @@ impl SidePanel {
side.set_rect_width(&mut panel_rect, width); side.set_rect_width(&mut panel_rect, width);
} }
let any_down = ui.input().pointer.any_down(); // avoid deadlocks let dragging_something_else =
let dragging_something_else = any_down || ui.input().pointer.any_pressed(); ui.input(|i| i.pointer.any_down() || i.pointer.any_pressed());
resize_hover = mouse_over_resize_line && !dragging_something_else; resize_hover = mouse_over_resize_line && !dragging_something_else;
if resize_hover || is_resizing { if resize_hover || is_resizing {
ui.output().cursor_icon = CursorIcon::ResizeHorizontal; ui.ctx().set_cursor_icon(CursorIcon::ResizeHorizontal);
} }
} }
} }
@ -334,19 +335,19 @@ impl SidePanel {
let layer_id = LayerId::background(); let layer_id = LayerId::background();
let side = self.side; let side = self.side;
let available_rect = ctx.available_rect(); let available_rect = ctx.available_rect();
let clip_rect = ctx.input().screen_rect(); let clip_rect = ctx.screen_rect();
let mut panel_ui = Ui::new(ctx.clone(), layer_id, self.id, available_rect, clip_rect); let mut panel_ui = Ui::new(ctx.clone(), layer_id, self.id, available_rect, clip_rect);
let inner_response = self.show_inside_dyn(&mut panel_ui, add_contents); let inner_response = self.show_inside_dyn(&mut panel_ui, add_contents);
let rect = inner_response.response.rect; let rect = inner_response.response.rect;
match side { match side {
Side::Left => ctx Side::Left => ctx.frame_state_mut(|state| {
.frame_state() state.allocate_left_panel(Rect::from_min_max(available_rect.min, rect.max));
.allocate_left_panel(Rect::from_min_max(available_rect.min, rect.max)), }),
Side::Right => ctx Side::Right => ctx.frame_state_mut(|state| {
.frame_state() state.allocate_right_panel(Rect::from_min_max(rect.min, available_rect.max));
.allocate_right_panel(Rect::from_min_max(rect.min, available_rect.max)), }),
} }
inner_response inner_response
} }
@ -682,7 +683,7 @@ impl TopBottomPanel {
let mut is_resizing = false; let mut is_resizing = false;
if resizable { if resizable {
let resize_id = id.with("__resize"); let resize_id = id.with("__resize");
let latest_pos = ui.input().pointer.latest_pos(); let latest_pos = ui.input(|i| i.pointer.latest_pos());
if let Some(pointer) = latest_pos { if let Some(pointer) = latest_pos {
let we_are_on_top = ui let we_are_on_top = ui
.ctx() .ctx()
@ -695,13 +696,12 @@ impl TopBottomPanel {
&& (resize_y - pointer.y).abs() && (resize_y - pointer.y).abs()
<= ui.style().interaction.resize_grab_radius_side; <= ui.style().interaction.resize_grab_radius_side;
if ui.input().pointer.any_pressed() if ui.input(|i| i.pointer.any_pressed() && i.pointer.any_down())
&& ui.input().pointer.any_down()
&& mouse_over_resize_line && mouse_over_resize_line
{ {
ui.memory().interaction.drag_id = Some(resize_id); ui.memory_mut(|mem| mem.interaction.drag_id = Some(resize_id));
} }
is_resizing = ui.memory().interaction.drag_id == Some(resize_id); is_resizing = ui.memory(|mem| mem.interaction.drag_id == Some(resize_id));
if is_resizing { if is_resizing {
let height = (pointer.y - side.side_y(panel_rect)).abs(); let height = (pointer.y - side.side_y(panel_rect)).abs();
let height = clamp_to_range(height, height_range.clone()) let height = clamp_to_range(height, height_range.clone())
@ -709,12 +709,12 @@ impl TopBottomPanel {
side.set_rect_height(&mut panel_rect, height); side.set_rect_height(&mut panel_rect, height);
} }
let any_down = ui.input().pointer.any_down(); // avoid deadlocks let dragging_something_else =
let dragging_something_else = any_down || ui.input().pointer.any_pressed(); ui.input(|i| i.pointer.any_down() || i.pointer.any_pressed());
resize_hover = mouse_over_resize_line && !dragging_something_else; resize_hover = mouse_over_resize_line && !dragging_something_else;
if resize_hover || is_resizing { if resize_hover || is_resizing {
ui.output().cursor_icon = CursorIcon::ResizeVertical; ui.ctx().set_cursor_icon(CursorIcon::ResizeVertical);
} }
} }
} }
@ -787,7 +787,7 @@ impl TopBottomPanel {
let available_rect = ctx.available_rect(); let available_rect = ctx.available_rect();
let side = self.side; let side = self.side;
let clip_rect = ctx.input().screen_rect(); let clip_rect = ctx.screen_rect();
let mut panel_ui = Ui::new(ctx.clone(), layer_id, self.id, available_rect, clip_rect); let mut panel_ui = Ui::new(ctx.clone(), layer_id, self.id, available_rect, clip_rect);
let inner_response = self.show_inside_dyn(&mut panel_ui, add_contents); let inner_response = self.show_inside_dyn(&mut panel_ui, add_contents);
@ -795,12 +795,14 @@ impl TopBottomPanel {
match side { match side {
TopBottomSide::Top => { TopBottomSide::Top => {
ctx.frame_state() ctx.frame_state_mut(|state| {
.allocate_top_panel(Rect::from_min_max(available_rect.min, rect.max)); state.allocate_top_panel(Rect::from_min_max(available_rect.min, rect.max));
});
} }
TopBottomSide::Bottom => { TopBottomSide::Bottom => {
ctx.frame_state() ctx.frame_state_mut(|state| {
.allocate_bottom_panel(Rect::from_min_max(rect.min, available_rect.max)); state.allocate_bottom_panel(Rect::from_min_max(rect.min, available_rect.max));
});
} }
} }
@ -1042,14 +1044,13 @@ impl CentralPanel {
let layer_id = LayerId::background(); let layer_id = LayerId::background();
let id = Id::new("central_panel"); let id = Id::new("central_panel");
let clip_rect = ctx.input().screen_rect(); let clip_rect = ctx.screen_rect();
let mut panel_ui = Ui::new(ctx.clone(), layer_id, id, available_rect, clip_rect); let mut panel_ui = Ui::new(ctx.clone(), layer_id, id, available_rect, clip_rect);
let inner_response = self.show_inside_dyn(&mut panel_ui, add_contents); let inner_response = self.show_inside_dyn(&mut panel_ui, add_contents);
// Only inform ctx about what we actually used, so we can shrink the native window to fit. // Only inform ctx about what we actually used, so we can shrink the native window to fit.
ctx.frame_state() ctx.frame_state_mut(|state| state.allocate_central_panel(inner_response.response.rect));
.allocate_central_panel(inner_response.response.rect);
inner_response inner_response
} }

View File

@ -13,11 +13,11 @@ pub(crate) struct TooltipState {
impl TooltipState { impl TooltipState {
pub fn load(ctx: &Context) -> Option<Self> { pub fn load(ctx: &Context) -> Option<Self> {
ctx.data().get_temp(Id::null()) ctx.data_mut(|d| d.get_temp(Id::null()))
} }
fn store(self, ctx: &Context) { fn store(self, ctx: &Context) {
ctx.data().insert_temp(Id::null(), self); ctx.data_mut(|d| d.insert_temp(Id::null(), self));
} }
fn individual_tooltip_size(&self, common_id: Id, index: usize) -> Option<Vec2> { fn individual_tooltip_size(&self, common_id: Id, index: usize) -> Option<Vec2> {
@ -95,9 +95,7 @@ pub fn show_tooltip_at_pointer<R>(
add_contents: impl FnOnce(&mut Ui) -> R, add_contents: impl FnOnce(&mut Ui) -> R,
) -> Option<R> { ) -> Option<R> {
let suggested_pos = ctx let suggested_pos = ctx
.input() .input(|i| i.pointer.hover_pos())
.pointer
.hover_pos()
.map(|pointer_pos| pointer_pos + vec2(16.0, 16.0)); .map(|pointer_pos| pointer_pos + vec2(16.0, 16.0));
show_tooltip_at(ctx, id, suggested_pos, add_contents) show_tooltip_at(ctx, id, suggested_pos, add_contents)
} }
@ -112,7 +110,7 @@ pub fn show_tooltip_for<R>(
add_contents: impl FnOnce(&mut Ui) -> R, add_contents: impl FnOnce(&mut Ui) -> R,
) -> Option<R> { ) -> Option<R> {
let expanded_rect = rect.expand2(vec2(2.0, 4.0)); let expanded_rect = rect.expand2(vec2(2.0, 4.0));
let (above, position) = if ctx.input().any_touches() { let (above, position) = if ctx.input(|i| i.any_touches()) {
(true, expanded_rect.left_top()) (true, expanded_rect.left_top())
} else { } else {
(false, expanded_rect.left_bottom()) (false, expanded_rect.left_bottom())
@ -159,8 +157,7 @@ fn show_tooltip_at_avoid_dyn<'c, R>(
// if there are multiple tooltips open they should use the same common_id for the `tooltip_size` caching to work. // if there are multiple tooltips open they should use the same common_id for the `tooltip_size` caching to work.
let mut frame_state = let mut frame_state =
ctx.frame_state() ctx.frame_state(|fs| fs.tooltip_state)
.tooltip_state
.unwrap_or(crate::frame_state::TooltipFrameState { .unwrap_or(crate::frame_state::TooltipFrameState {
common_id: individual_id, common_id: individual_id,
rect: Rect::NOTHING, rect: Rect::NOTHING,
@ -176,7 +173,7 @@ fn show_tooltip_at_avoid_dyn<'c, R>(
} }
} else if let Some(position) = suggested_position { } else if let Some(position) = suggested_position {
position position
} else if ctx.memory().everything_is_visible() { } else if ctx.memory(|mem| mem.everything_is_visible()) {
Pos2::ZERO Pos2::ZERO
} else { } else {
return None; // No good place for a tooltip :( return None; // No good place for a tooltip :(
@ -191,7 +188,7 @@ fn show_tooltip_at_avoid_dyn<'c, R>(
position.y -= expected_size.y; position.y -= expected_size.y;
} }
position = position.at_most(ctx.input().screen_rect().max - expected_size); position = position.at_most(ctx.screen_rect().max - expected_size);
// check if we intersect the avoid_rect // check if we intersect the avoid_rect
{ {
@ -209,7 +206,7 @@ fn show_tooltip_at_avoid_dyn<'c, R>(
} }
} }
let position = position.at_least(ctx.input().screen_rect().min); let position = position.at_least(ctx.screen_rect().min);
let area_id = frame_state.common_id.with(frame_state.count); let area_id = frame_state.common_id.with(frame_state.count);
@ -226,7 +223,7 @@ fn show_tooltip_at_avoid_dyn<'c, R>(
frame_state.count += 1; frame_state.count += 1;
frame_state.rect = frame_state.rect.union(response.rect); frame_state.rect = frame_state.rect.union(response.rect);
ctx.frame_state().tooltip_state = Some(frame_state); ctx.frame_state_mut(|fs| fs.tooltip_state = Some(frame_state));
Some(inner) Some(inner)
} }
@ -283,7 +280,7 @@ pub fn was_tooltip_open_last_frame(ctx: &Context, tooltip_id: Id) -> bool {
if *individual_id == tooltip_id { if *individual_id == tooltip_id {
let area_id = common_id.with(count); let area_id = common_id.with(count);
let layer_id = LayerId::new(Order::Tooltip, area_id); let layer_id = LayerId::new(Order::Tooltip, area_id);
if ctx.memory().areas.visible_last_frame(&layer_id) { if ctx.memory(|mem| mem.areas.visible_last_frame(&layer_id)) {
return true; return true;
} }
} }
@ -325,7 +322,7 @@ pub fn popup_below_widget<R>(
/// let response = ui.button("Open popup"); /// let response = ui.button("Open popup");
/// let popup_id = ui.make_persistent_id("my_unique_id"); /// let popup_id = ui.make_persistent_id("my_unique_id");
/// if response.clicked() { /// if response.clicked() {
/// ui.memory().toggle_popup(popup_id); /// ui.memory_mut(|mem| mem.toggle_popup(popup_id));
/// } /// }
/// let below = egui::AboveOrBelow::Below; /// let below = egui::AboveOrBelow::Below;
/// egui::popup::popup_above_or_below_widget(ui, popup_id, &response, below, |ui| { /// egui::popup::popup_above_or_below_widget(ui, popup_id, &response, below, |ui| {
@ -342,7 +339,7 @@ pub fn popup_above_or_below_widget<R>(
above_or_below: AboveOrBelow, above_or_below: AboveOrBelow,
add_contents: impl FnOnce(&mut Ui) -> R, add_contents: impl FnOnce(&mut Ui) -> R,
) -> Option<R> { ) -> Option<R> {
if ui.memory().is_popup_open(popup_id) { if ui.memory(|mem| mem.is_popup_open(popup_id)) {
let (pos, pivot) = match above_or_below { let (pos, pivot) = match above_or_below {
AboveOrBelow::Above => (widget_response.rect.left_top(), Align2::LEFT_BOTTOM), AboveOrBelow::Above => (widget_response.rect.left_top(), Align2::LEFT_BOTTOM),
AboveOrBelow::Below => (widget_response.rect.left_bottom(), Align2::LEFT_TOP), AboveOrBelow::Below => (widget_response.rect.left_bottom(), Align2::LEFT_TOP),
@ -370,8 +367,8 @@ pub fn popup_above_or_below_widget<R>(
}) })
.inner; .inner;
if ui.input().key_pressed(Key::Escape) || widget_response.clicked_elsewhere() { if ui.input(|i| i.key_pressed(Key::Escape)) || widget_response.clicked_elsewhere() {
ui.memory().close_popup(); ui.memory_mut(|mem| mem.close_popup());
} }
Some(inner) Some(inner)
} else { } else {

View File

@ -18,11 +18,11 @@ pub(crate) struct State {
impl State { impl State {
pub fn load(ctx: &Context, id: Id) -> Option<Self> { pub fn load(ctx: &Context, id: Id) -> Option<Self> {
ctx.data().get_persisted(id) ctx.data_mut(|d| d.get_persisted(id))
} }
pub fn store(self, ctx: &Context, id: Id) { pub fn store(self, ctx: &Context, id: Id) {
ctx.data().insert_persisted(id, self); ctx.data_mut(|d| d.insert_persisted(id, self));
} }
} }
@ -180,7 +180,7 @@ impl Resize {
.at_least(self.min_size) .at_least(self.min_size)
.at_most(self.max_size) .at_most(self.max_size)
.at_most( .at_most(
ui.input().screen_rect().size() - ui.spacing().window_margin.sum(), // hack for windows ui.ctx().screen_rect().size() - ui.spacing().window_margin.sum(), // hack for windows
); );
State { State {
@ -305,7 +305,7 @@ impl Resize {
paint_resize_corner(ui, &corner_response); paint_resize_corner(ui, &corner_response);
if corner_response.hovered() || corner_response.dragged() { if corner_response.hovered() || corner_response.dragged() {
ui.ctx().output().cursor_icon = CursorIcon::ResizeNwSe; ui.ctx().set_cursor_icon(CursorIcon::ResizeNwSe);
} }
} }

View File

@ -48,11 +48,11 @@ impl Default for State {
impl State { impl State {
pub fn load(ctx: &Context, id: Id) -> Option<Self> { pub fn load(ctx: &Context, id: Id) -> Option<Self> {
ctx.data().get_persisted(id) ctx.data_mut(|d| d.get_persisted(id))
} }
pub fn store(self, ctx: &Context, id: Id) { pub fn store(self, ctx: &Context, id: Id) {
ctx.data().insert_persisted(id, self); ctx.data_mut(|d| d.insert_persisted(id, self));
} }
} }
@ -449,8 +449,10 @@ impl ScrollArea {
if content_response.dragged() { if content_response.dragged() {
for d in 0..2 { for d in 0..2 {
if has_bar[d] { if has_bar[d] {
state.offset[d] -= ui.input().pointer.delta()[d]; ui.input(|input| {
state.vel[d] = ui.input().pointer.velocity()[d]; state.offset[d] -= input.pointer.delta()[d];
state.vel[d] = input.pointer.velocity()[d];
});
state.scroll_stuck_to_end[d] = false; state.scroll_stuck_to_end[d] = false;
} else { } else {
state.vel[d] = 0.0; state.vel[d] = 0.0;
@ -459,7 +461,7 @@ impl ScrollArea {
} else { } else {
let stop_speed = 20.0; // Pixels per second. let stop_speed = 20.0; // Pixels per second.
let friction_coeff = 1000.0; // Pixels per second squared. let friction_coeff = 1000.0; // Pixels per second squared.
let dt = ui.input().unstable_dt; let dt = ui.input(|i| i.unstable_dt);
let friction = friction_coeff * dt; let friction = friction_coeff * dt;
if friction > state.vel.length() || state.vel.length() < stop_speed { if friction > state.vel.length() || state.vel.length() < stop_speed {
@ -603,7 +605,9 @@ impl Prepared {
for d in 0..2 { for d in 0..2 {
if has_bar[d] { if has_bar[d] {
// We take the scroll target so only this ScrollArea will use it: // We take the scroll target so only this ScrollArea will use it:
let scroll_target = content_ui.ctx().frame_state().scroll_target[d].take(); let scroll_target = content_ui
.ctx()
.frame_state_mut(|state| state.scroll_target[d].take());
if let Some((scroll, align)) = scroll_target { if let Some((scroll, align)) = scroll_target {
let min = content_ui.min_rect().min[d]; let min = content_ui.min_rect().min[d];
let clip_rect = content_ui.clip_rect(); let clip_rect = content_ui.clip_rect();
@ -668,8 +672,7 @@ impl Prepared {
if scrolling_enabled && ui.rect_contains_pointer(outer_rect) { if scrolling_enabled && ui.rect_contains_pointer(outer_rect) {
for d in 0..2 { for d in 0..2 {
if has_bar[d] { if has_bar[d] {
let mut frame_state = ui.ctx().frame_state(); let scroll_delta = ui.ctx().frame_state(|fs| fs.scroll_delta);
let scroll_delta = frame_state.scroll_delta;
let scrolling_up = state.offset[d] > 0.0 && scroll_delta[d] > 0.0; let scrolling_up = state.offset[d] > 0.0 && scroll_delta[d] > 0.0;
let scrolling_down = state.offset[d] < max_offset[d] && scroll_delta[d] < 0.0; let scrolling_down = state.offset[d] < max_offset[d] && scroll_delta[d] < 0.0;
@ -677,7 +680,7 @@ impl Prepared {
if scrolling_up || scrolling_down { if scrolling_up || scrolling_down {
state.offset[d] -= scroll_delta[d]; state.offset[d] -= scroll_delta[d];
// Clear scroll delta so no parent scroll will use it. // Clear scroll delta so no parent scroll will use it.
frame_state.scroll_delta[d] = 0.0; ui.ctx().frame_state_mut(|fs| fs.scroll_delta[d] = 0.0);
state.scroll_stuck_to_end[d] = false; state.scroll_stuck_to_end[d] = false;
} }
} }

View File

@ -301,7 +301,8 @@ impl<'open> Window<'open> {
let frame = frame.unwrap_or_else(|| Frame::window(&ctx.style())); let frame = frame.unwrap_or_else(|| Frame::window(&ctx.style()));
let is_open = !matches!(open, Some(false)) || ctx.memory().everything_is_visible(); let is_explicitly_closed = matches!(open, Some(false));
let is_open = !is_explicitly_closed || ctx.memory(|mem| mem.everything_is_visible());
area.show_open_close_animation(ctx, &frame, is_open); area.show_open_close_animation(ctx, &frame, is_open);
if !is_open { if !is_open {
@ -339,7 +340,7 @@ impl<'open> Window<'open> {
// Calculate roughly how much larger the window size is compared to the inner rect // Calculate roughly how much larger the window size is compared to the inner rect
let title_bar_height = if with_title_bar { let title_bar_height = if with_title_bar {
let style = ctx.style(); let style = ctx.style();
title.font_height(&ctx.fonts(), &style) + title_content_spacing ctx.fonts(|f| title.font_height(f, &style)) + title_content_spacing
} else { } else {
0.0 0.0
}; };
@ -425,7 +426,7 @@ impl<'open> Window<'open> {
ctx.style().visuals.widgets.active, ctx.style().visuals.widgets.active,
); );
} else if let Some(hover_interaction) = hover_interaction { } else if let Some(hover_interaction) = hover_interaction {
if ctx.input().pointer.has_pointer() { if ctx.input(|i| i.pointer.has_pointer()) {
paint_frame_interaction( paint_frame_interaction(
&mut area_content_ui, &mut area_content_ui,
outer_rect, outer_rect,
@ -520,13 +521,13 @@ pub(crate) struct WindowInteraction {
impl WindowInteraction { impl WindowInteraction {
pub fn set_cursor(&self, ctx: &Context) { pub fn set_cursor(&self, ctx: &Context) {
if (self.left && self.top) || (self.right && self.bottom) { if (self.left && self.top) || (self.right && self.bottom) {
ctx.output().cursor_icon = CursorIcon::ResizeNwSe; ctx.set_cursor_icon(CursorIcon::ResizeNwSe);
} else if (self.right && self.top) || (self.left && self.bottom) { } else if (self.right && self.top) || (self.left && self.bottom) {
ctx.output().cursor_icon = CursorIcon::ResizeNeSw; ctx.set_cursor_icon(CursorIcon::ResizeNeSw);
} else if self.left || self.right { } else if self.left || self.right {
ctx.output().cursor_icon = CursorIcon::ResizeHorizontal; ctx.set_cursor_icon(CursorIcon::ResizeHorizontal);
} else if self.bottom || self.top { } else if self.bottom || self.top {
ctx.output().cursor_icon = CursorIcon::ResizeVertical; ctx.set_cursor_icon(CursorIcon::ResizeVertical);
} }
} }
@ -558,7 +559,7 @@ fn interact(
} }
} }
ctx.memory().areas.move_to_top(area_layer_id); ctx.memory_mut(|mem| mem.areas.move_to_top(area_layer_id));
Some(window_interaction) Some(window_interaction)
} }
@ -566,11 +567,11 @@ fn move_and_resize_window(ctx: &Context, window_interaction: &WindowInteraction)
window_interaction.set_cursor(ctx); window_interaction.set_cursor(ctx);
// Only move/resize windows with primary mouse button: // Only move/resize windows with primary mouse button:
if !ctx.input().pointer.primary_down() { if !ctx.input(|i| i.pointer.primary_down()) {
return None; return None;
} }
let pointer_pos = ctx.input().pointer.interact_pos()?; let pointer_pos = ctx.input(|i| i.pointer.interact_pos())?;
let mut rect = window_interaction.start_rect; // prevent drift let mut rect = window_interaction.start_rect; // prevent drift
if window_interaction.is_resize() { if window_interaction.is_resize() {
@ -592,8 +593,8 @@ fn move_and_resize_window(ctx: &Context, window_interaction: &WindowInteraction)
// but we want anything interactive in the window (e.g. slider) to steal // but we want anything interactive in the window (e.g. slider) to steal
// the drag from us. It is therefor important not to move the window the first frame, // the drag from us. It is therefor important not to move the window the first frame,
// but instead let other widgets to the steal. HACK. // but instead let other widgets to the steal. HACK.
if !ctx.input().pointer.any_pressed() { if !ctx.input(|i| i.pointer.any_pressed()) {
let press_origin = ctx.input().pointer.press_origin()?; let press_origin = ctx.input(|i| i.pointer.press_origin())?;
let delta = pointer_pos - press_origin; let delta = pointer_pos - press_origin;
rect = rect.translate(delta); rect = rect.translate(delta);
} }
@ -611,30 +612,31 @@ fn window_interaction(
rect: Rect, rect: Rect,
) -> Option<WindowInteraction> { ) -> Option<WindowInteraction> {
{ {
let drag_id = ctx.memory().interaction.drag_id; let drag_id = ctx.memory(|mem| mem.interaction.drag_id);
if drag_id.is_some() && drag_id != Some(id) { if drag_id.is_some() && drag_id != Some(id) {
return None; return None;
} }
} }
let mut window_interaction = { ctx.memory().window_interaction }; let mut window_interaction = ctx.memory(|mem| mem.window_interaction);
if window_interaction.is_none() { if window_interaction.is_none() {
if let Some(hover_window_interaction) = resize_hover(ctx, possible, area_layer_id, rect) { if let Some(hover_window_interaction) = resize_hover(ctx, possible, area_layer_id, rect) {
hover_window_interaction.set_cursor(ctx); hover_window_interaction.set_cursor(ctx);
let any_pressed = ctx.input().pointer.any_pressed(); // avoid deadlocks if ctx.input(|i| i.pointer.any_pressed() && i.pointer.primary_down()) {
if any_pressed && ctx.input().pointer.primary_down() { ctx.memory_mut(|mem| {
ctx.memory().interaction.drag_id = Some(id); mem.interaction.drag_id = Some(id);
ctx.memory().interaction.drag_is_window = true; mem.interaction.drag_is_window = true;
window_interaction = Some(hover_window_interaction); window_interaction = Some(hover_window_interaction);
ctx.memory().window_interaction = window_interaction; mem.window_interaction = window_interaction;
});
} }
} }
} }
if let Some(window_interaction) = window_interaction { if let Some(window_interaction) = window_interaction {
let is_active = ctx.memory().interaction.drag_id == Some(id); let is_active = ctx.memory_mut(|mem| mem.interaction.drag_id == Some(id));
if is_active && window_interaction.area_layer_id == area_layer_id { if is_active && window_interaction.area_layer_id == area_layer_id {
return Some(window_interaction); return Some(window_interaction);
@ -650,10 +652,9 @@ fn resize_hover(
area_layer_id: LayerId, area_layer_id: LayerId,
rect: Rect, rect: Rect,
) -> Option<WindowInteraction> { ) -> Option<WindowInteraction> {
let pointer = ctx.input().pointer.interact_pos()?; let pointer = ctx.input(|i| i.pointer.interact_pos())?;
let any_down = ctx.input().pointer.any_down(); // avoid deadlocks if ctx.input(|i| i.pointer.any_down() && !i.pointer.any_pressed()) {
if any_down && !ctx.input().pointer.any_pressed() {
return None; // already dragging (something) return None; // already dragging (something)
} }
@ -663,7 +664,7 @@ fn resize_hover(
} }
} }
if ctx.memory().interaction.drag_interest { if ctx.memory(|mem| mem.interaction.drag_interest) {
// Another widget will become active if we drag here // Another widget will become active if we drag here
return None; return None;
} }
@ -825,8 +826,8 @@ fn show_title_bar(
collapsible: bool, collapsible: bool,
) -> TitleBar { ) -> TitleBar {
let inner_response = ui.horizontal(|ui| { let inner_response = ui.horizontal(|ui| {
let height = title let height = ui
.font_height(&ui.fonts(), ui.style()) .fonts(|fonts| title.font_height(fonts, ui.style()))
.max(ui.spacing().interact_size.y); .max(ui.spacing().interact_size.y);
ui.set_min_height(height); ui.set_min_height(height);

File diff suppressed because it is too large Load Diff

View File

@ -70,7 +70,7 @@ pub struct PlatformOutput {
/// ``` /// ```
/// # egui::__run_test_ui(|ui| { /// # egui::__run_test_ui(|ui| {
/// if ui.button("📋").clicked() { /// if ui.button("📋").clicked() {
/// ui.output().copied_text = "some_text".to_string(); /// ui.output_mut(|o| o.copied_text = "some_text".to_string());
/// } /// }
/// # }); /// # });
/// ``` /// ```

View File

@ -8,14 +8,14 @@ pub(crate) struct State {
impl State { impl State {
pub fn load(ctx: &Context, id: Id) -> Option<Self> { pub fn load(ctx: &Context, id: Id) -> Option<Self> {
ctx.data().get_temp(id) ctx.data_mut(|d| d.get_temp(id))
} }
pub fn store(self, ctx: &Context, id: Id) { pub fn store(self, ctx: &Context, id: Id) {
// We don't persist Grids, because // We don't persist Grids, because
// A) there are potentially a lot of them, using up a lot of space (and therefore serialization time) // A) there are potentially a lot of them, using up a lot of space (and therefore serialization time)
// B) if the code changes, the grid _should_ change, and not remember old sizes // B) if the code changes, the grid _should_ change, and not remember old sizes
ctx.data().insert_temp(id, self); ctx.data_mut(|d| d.insert_temp(id, self));
} }
fn set_min_col_width(&mut self, col: usize, width: f32) { fn set_min_col_width(&mut self, col: usize, width: f32) {

View File

@ -26,15 +26,15 @@ pub mod kb_shortcuts {
/// } /// }
/// ``` /// ```
pub fn zoom_with_keyboard_shortcuts(ctx: &Context, native_pixels_per_point: Option<f32>) { pub fn zoom_with_keyboard_shortcuts(ctx: &Context, native_pixels_per_point: Option<f32>) {
if ctx.input_mut().consume_shortcut(&kb_shortcuts::ZOOM_RESET) { if ctx.input_mut(|i| i.consume_shortcut(&kb_shortcuts::ZOOM_RESET)) {
if let Some(native_pixels_per_point) = native_pixels_per_point { if let Some(native_pixels_per_point) = native_pixels_per_point {
ctx.set_pixels_per_point(native_pixels_per_point); ctx.set_pixels_per_point(native_pixels_per_point);
} }
} else { } else {
if ctx.input_mut().consume_shortcut(&kb_shortcuts::ZOOM_IN) { if ctx.input_mut(|i| i.consume_shortcut(&kb_shortcuts::ZOOM_IN)) {
zoom_in(ctx); zoom_in(ctx);
} }
if ctx.input_mut().consume_shortcut(&kb_shortcuts::ZOOM_OUT) { if ctx.input_mut(|i| i.consume_shortcut(&kb_shortcuts::ZOOM_OUT)) {
zoom_out(ctx); zoom_out(ctx);
} }
} }

View File

@ -368,7 +368,7 @@ impl InputState {
/// # egui::__run_test_ui(|ui| { /// # egui::__run_test_ui(|ui| {
/// let mut zoom = 1.0; // no zoom /// let mut zoom = 1.0; // no zoom
/// let mut rotation = 0.0; // no rotation /// let mut rotation = 0.0; // no rotation
/// let multi_touch = ui.input().multi_touch(); /// let multi_touch = ui.input(|i| i.multi_touch());
/// if let Some(multi_touch) = multi_touch { /// if let Some(multi_touch) = multi_touch {
/// zoom *= multi_touch.zoom_delta; /// zoom *= multi_touch.zoom_delta;
/// rotation += multi_touch.rotation_delta; /// rotation += multi_touch.rotation_delta;

View File

@ -2,7 +2,7 @@
use crate::*; use crate::*;
pub fn font_family_ui(ui: &mut Ui, font_family: &mut FontFamily) { pub fn font_family_ui(ui: &mut Ui, font_family: &mut FontFamily) {
let families = ui.fonts().families(); let families = ui.fonts(|f| f.families());
ui.horizontal(|ui| { ui.horizontal(|ui| {
for alternative in families { for alternative in families {
let text = alternative.to_string(); let text = alternative.to_string();
@ -12,7 +12,7 @@ pub fn font_family_ui(ui: &mut Ui, font_family: &mut FontFamily) {
} }
pub fn font_id_ui(ui: &mut Ui, font_id: &mut FontId) { pub fn font_id_ui(ui: &mut Ui, font_id: &mut FontId) {
let families = ui.fonts().families(); let families = ui.fonts(|f| f.families());
ui.horizontal(|ui| { ui.horizontal(|ui| {
ui.add(Slider::new(&mut font_id.size, 4.0..=40.0).max_decimals(1)); ui.add(Slider::new(&mut font_id.size, 4.0..=40.0).max_decimals(1));
for alternative in families { for alternative in families {

View File

@ -363,7 +363,7 @@ pub use {
input_state::{InputState, MultiTouchInfo, PointerState}, input_state::{InputState, MultiTouchInfo, PointerState},
layers::{LayerId, Order}, layers::{LayerId, Order},
layout::*, layout::*,
memory::Memory, memory::{Memory, Options},
painter::Painter, painter::Painter,
response::{InnerResponse, Response}, response::{InnerResponse, Response},
sense::Sense, sense::Sense,

View File

@ -52,9 +52,10 @@ pub struct Memory {
/// type CharCountCache<'a> = FrameCache<usize, CharCounter>; /// type CharCountCache<'a> = FrameCache<usize, CharCounter>;
/// ///
/// # let mut ctx = egui::Context::default(); /// # let mut ctx = egui::Context::default();
/// let mut memory = ctx.memory(); /// ctx.memory_mut(|mem| {
/// let cache = memory.caches.cache::<CharCountCache<'_>>(); /// let cache = mem.caches.cache::<CharCountCache<'_>>();
/// assert_eq!(cache.get("hello"), 5); /// assert_eq!(cache.get("hello"), 5);
/// });
/// ``` /// ```
#[cfg_attr(feature = "persistence", serde(skip))] #[cfg_attr(feature = "persistence", serde(skip))]
pub caches: crate::util::cache::CacheStorage, pub caches: crate::util::cache::CacheStorage,
@ -405,7 +406,7 @@ impl Memory {
} }
/// Is the keyboard focus locked on this widget? If so the focus won't move even if the user presses the tab key. /// Is the keyboard focus locked on this widget? If so the focus won't move even if the user presses the tab key.
pub fn has_lock_focus(&mut self, id: Id) -> bool { pub fn has_lock_focus(&self, id: Id) -> bool {
if self.had_focus_last_frame(id) && self.has_focus(id) { if self.had_focus_last_frame(id) && self.has_focus(id) {
self.interaction.focus.is_focus_locked self.interaction.focus.is_focus_locked
} else { } else {

View File

@ -31,11 +31,11 @@ pub(crate) struct BarState {
impl BarState { impl BarState {
fn load(ctx: &Context, bar_id: Id) -> Self { fn load(ctx: &Context, bar_id: Id) -> Self {
ctx.data().get_temp::<Self>(bar_id).unwrap_or_default() ctx.data_mut(|d| d.get_temp::<Self>(bar_id).unwrap_or_default())
} }
fn store(self, ctx: &Context, bar_id: Id) { fn store(self, ctx: &Context, bar_id: Id) {
ctx.data().insert_temp(bar_id, self); ctx.data_mut(|d| d.insert_temp(bar_id, self));
} }
/// Show a menu at pointer if primary-clicked response. /// Show a menu at pointer if primary-clicked response.
@ -310,10 +310,9 @@ impl MenuRoot {
root: &mut MenuRootManager, root: &mut MenuRootManager,
id: Id, id: Id,
) -> MenuResponse { ) -> MenuResponse {
// Lock the input once for the whole function call (see https://github.com/emilk/egui/pull/1380). if (response.clicked() && root.is_menu_open(id))
let input = response.ctx.input(); || response.ctx.input(|i| i.key_pressed(Key::Escape))
{
if (response.clicked() && root.is_menu_open(id)) || input.key_pressed(Key::Escape) {
// menu open and button clicked or esc pressed // menu open and button clicked or esc pressed
return MenuResponse::Close; return MenuResponse::Close;
} else if (response.clicked() && !root.is_menu_open(id)) } else if (response.clicked() && !root.is_menu_open(id))
@ -321,12 +320,10 @@ impl MenuRoot {
{ {
// menu not open and button clicked // menu not open and button clicked
// or button hovered while other menu is open // or button hovered while other menu is open
drop(input);
let mut pos = response.rect.left_bottom(); let mut pos = response.rect.left_bottom();
if let Some(root) = root.inner.as_mut() { if let Some(root) = root.inner.as_mut() {
let menu_rect = root.menu_state.read().rect; let menu_rect = root.menu_state.read().rect;
let screen_rect = response.ctx.input().screen_rect; let screen_rect = response.ctx.input(|i| i.screen_rect);
if pos.y + menu_rect.height() > screen_rect.max.y { if pos.y + menu_rect.height() > screen_rect.max.y {
pos.y = screen_rect.max.y - menu_rect.height() - response.rect.height(); pos.y = screen_rect.max.y - menu_rect.height() - response.rect.height();
@ -338,8 +335,11 @@ impl MenuRoot {
} }
return MenuResponse::Create(pos, id); return MenuResponse::Create(pos, id);
} else if input.pointer.any_pressed() && input.pointer.primary_down() { } else if response
if let Some(pos) = input.pointer.interact_pos() { .ctx
.input(|i| i.pointer.any_pressed() && i.pointer.primary_down())
{
if let Some(pos) = response.ctx.input(|i| i.pointer.interact_pos()) {
if let Some(root) = root.inner.as_mut() { if let Some(root) = root.inner.as_mut() {
if root.id == id { if root.id == id {
// pressed somewhere while this menu is open // pressed somewhere while this menu is open
@ -362,26 +362,28 @@ impl MenuRoot {
id: Id, id: Id,
) -> MenuResponse { ) -> MenuResponse {
let response = response.interact(Sense::click()); let response = response.interact(Sense::click());
let pointer = &response.ctx.input().pointer; response.ctx.input(|input| {
if pointer.any_pressed() { let pointer = &input.pointer;
if let Some(pos) = pointer.interact_pos() { if pointer.any_pressed() {
let mut destroy = false; if let Some(pos) = pointer.interact_pos() {
let mut in_old_menu = false; let mut destroy = false;
if let Some(root) = root { let mut in_old_menu = false;
let menu_state = root.menu_state.read(); if let Some(root) = root {
in_old_menu = menu_state.area_contains(pos); let menu_state = root.menu_state.read();
destroy = root.id == response.id; in_old_menu = menu_state.area_contains(pos);
} destroy = root.id == response.id;
if !in_old_menu { }
if response.hovered() && pointer.secondary_down() { if !in_old_menu {
return MenuResponse::Create(pos, id); if response.hovered() && pointer.secondary_down() {
} else if (response.hovered() && pointer.primary_down()) || destroy { return MenuResponse::Create(pos, id);
return MenuResponse::Close; } else if (response.hovered() && pointer.primary_down()) || destroy {
return MenuResponse::Close;
}
} }
} }
} }
} MenuResponse::Stay
MenuResponse::Stay })
} }
fn handle_menu_response(root: &mut MenuRootManager, menu_response: MenuResponse) { fn handle_menu_response(root: &mut MenuRootManager, menu_response: MenuResponse) {
@ -605,15 +607,15 @@ impl MenuState {
/// Sense button interaction opening and closing submenu. /// Sense button interaction opening and closing submenu.
fn submenu_button_interaction(&mut self, ui: &mut Ui, sub_id: Id, button: &Response) { fn submenu_button_interaction(&mut self, ui: &mut Ui, sub_id: Id, button: &Response) {
let pointer = &ui.input().pointer.clone(); let pointer = ui.input(|i| i.pointer.clone());
let open = self.is_open(sub_id); let open = self.is_open(sub_id);
if self.moving_towards_current_submenu(pointer) { if self.moving_towards_current_submenu(&pointer) {
// ensure to repaint once even when pointer is not moving // ensure to repaint once even when pointer is not moving
ui.ctx().request_repaint(); ui.ctx().request_repaint();
} else if !open && button.hovered() { } else if !open && button.hovered() {
let pos = button.rect.right_top(); let pos = button.rect.right_top();
self.open_submenu(sub_id, pos); self.open_submenu(sub_id, pos);
} else if open && !button.hovered() && !self.hovering_current_submenu(pointer) { } else if open && !button.hovered() && !self.hovering_current_submenu(&pointer) {
self.close_submenu(); self.close_submenu();
} }
} }

View File

@ -7,7 +7,6 @@ use crate::{
Color32, Context, FontId, Color32, Context, FontId,
}; };
use epaint::{ use epaint::{
mutex::{RwLockReadGuard, RwLockWriteGuard},
text::{Fonts, Galley}, text::{Fonts, Galley},
CircleShape, RectShape, Rounding, Shape, Stroke, CircleShape, RectShape, Rounding, Shape, Stroke,
}; };
@ -105,10 +104,12 @@ impl Painter {
&self.ctx &self.ctx
} }
/// Available fonts. /// Read-only access to the shared [`Fonts`].
///
/// See [`Context`] documentation for how locks work.
#[inline(always)] #[inline(always)]
pub fn fonts(&self) -> RwLockReadGuard<'_, Fonts> { pub fn fonts<R>(&self, reader: impl FnOnce(&Fonts) -> R) -> R {
self.ctx.fonts() self.ctx.fonts(reader)
} }
/// Where we paint /// Where we paint
@ -152,8 +153,9 @@ impl Painter {
/// ## Low level /// ## Low level
impl Painter { impl Painter {
fn paint_list(&self) -> RwLockWriteGuard<'_, PaintList> { #[inline]
RwLockWriteGuard::map(self.ctx.graphics(), |g| g.list(self.layer_id)) fn paint_list<R>(&self, writer: impl FnOnce(&mut PaintList) -> R) -> R {
self.ctx.graphics_mut(|g| writer(g.list(self.layer_id)))
} }
fn transform_shape(&self, shape: &mut Shape) { fn transform_shape(&self, shape: &mut Shape) {
@ -167,11 +169,11 @@ impl Painter {
/// NOTE: all coordinates are screen coordinates! /// NOTE: all coordinates are screen coordinates!
pub fn add(&self, shape: impl Into<Shape>) -> ShapeIdx { pub fn add(&self, shape: impl Into<Shape>) -> ShapeIdx {
if self.fade_to_color == Some(Color32::TRANSPARENT) { if self.fade_to_color == Some(Color32::TRANSPARENT) {
self.paint_list().add(self.clip_rect, Shape::Noop) self.paint_list(|l| l.add(self.clip_rect, Shape::Noop))
} else { } else {
let mut shape = shape.into(); let mut shape = shape.into();
self.transform_shape(&mut shape); self.transform_shape(&mut shape);
self.paint_list().add(self.clip_rect, shape) self.paint_list(|l| l.add(self.clip_rect, shape))
} }
} }
@ -187,9 +189,9 @@ impl Painter {
self.transform_shape(&mut shape); self.transform_shape(&mut shape);
shape shape
}); });
self.paint_list().extend(self.clip_rect, shapes); self.paint_list(|l| l.extend(self.clip_rect, shapes));
} else { } else {
self.paint_list().extend(self.clip_rect, shapes); self.paint_list(|l| l.extend(self.clip_rect, shapes));
}; };
} }
@ -200,7 +202,7 @@ impl Painter {
} }
let mut shape = shape.into(); let mut shape = shape.into();
self.transform_shape(&mut shape); self.transform_shape(&mut shape);
self.paint_list().set(idx, self.clip_rect, shape); self.paint_list(|l| l.set(idx, self.clip_rect, shape));
} }
} }
@ -405,7 +407,7 @@ impl Painter {
color: crate::Color32, color: crate::Color32,
wrap_width: f32, wrap_width: f32,
) -> Arc<Galley> { ) -> Arc<Galley> {
self.fonts().layout(text, font_id, color, wrap_width) self.fonts(|f| f.layout(text, font_id, color, wrap_width))
} }
/// Will line break at `\n`. /// Will line break at `\n`.
@ -418,7 +420,7 @@ impl Painter {
font_id: FontId, font_id: FontId,
color: crate::Color32, color: crate::Color32,
) -> Arc<Galley> { ) -> Arc<Galley> {
self.fonts().layout(text, font_id, color, f32::INFINITY) self.fonts(|f| f.layout(text, font_id, color, f32::INFINITY))
} }
/// Paint text that has already been layed out in a [`Galley`]. /// Paint text that has already been layed out in a [`Galley`].

View File

@ -173,23 +173,25 @@ impl Response {
// We do not use self.clicked(), because we want to catch all clicks within our frame, // We do not use self.clicked(), because we want to catch all clicks within our frame,
// even if we aren't clickable (or even enabled). // even if we aren't clickable (or even enabled).
// This is important for windows and such that should close then the user clicks elsewhere. // This is important for windows and such that should close then the user clicks elsewhere.
let pointer = &self.ctx.input().pointer; self.ctx.input(|i| {
let pointer = &i.pointer;
if pointer.any_click() { if pointer.any_click() {
// We detect clicks/hover on a "interact_rect" that is slightly larger than // We detect clicks/hover on a "interact_rect" that is slightly larger than
// self.rect. See Context::interact. // self.rect. See Context::interact.
// This means we can be hovered and clicked even though `!self.rect.contains(pos)` is true, // This means we can be hovered and clicked even though `!self.rect.contains(pos)` is true,
// hence the extra complexity here. // hence the extra complexity here.
if self.hovered() { if self.hovered() {
false false
} else if let Some(pos) = pointer.interact_pos() { } else if let Some(pos) = pointer.interact_pos() {
!self.rect.contains(pos) !self.rect.contains(pos)
} else {
false // clicked without a pointer, weird
}
} else { } else {
false // clicked without a pointer, weird false
} }
} else { })
false
}
} }
/// Was the widget enabled? /// Was the widget enabled?
@ -217,14 +219,12 @@ impl Response {
/// also has the keyboard focus. That makes this function suitable /// also has the keyboard focus. That makes this function suitable
/// for style choices, e.g. a thicker border around focused widgets. /// for style choices, e.g. a thicker border around focused widgets.
pub fn has_focus(&self) -> bool { pub fn has_focus(&self) -> bool {
// Access input and memory in separate statements to prevent deadlock. self.ctx.input(|i| i.raw.has_focus) && self.ctx.memory(|mem| mem.has_focus(self.id))
let has_global_focus = self.ctx.input().raw.has_focus;
has_global_focus && self.ctx.memory().has_focus(self.id)
} }
/// True if this widget has keyboard focus this frame, but didn't last frame. /// True if this widget has keyboard focus this frame, but didn't last frame.
pub fn gained_focus(&self) -> bool { pub fn gained_focus(&self) -> bool {
self.ctx.memory().gained_focus(self.id) self.ctx.memory(|mem| mem.gained_focus(self.id))
} }
/// The widget had keyboard focus and lost it, /// The widget had keyboard focus and lost it,
@ -236,29 +236,29 @@ impl Response {
/// # let mut my_text = String::new(); /// # let mut my_text = String::new();
/// # fn do_request(_: &str) {} /// # fn do_request(_: &str) {}
/// let response = ui.text_edit_singleline(&mut my_text); /// let response = ui.text_edit_singleline(&mut my_text);
/// if response.lost_focus() && ui.input().key_pressed(egui::Key::Enter) { /// if response.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) {
/// do_request(&my_text); /// do_request(&my_text);
/// } /// }
/// # }); /// # });
/// ``` /// ```
pub fn lost_focus(&self) -> bool { pub fn lost_focus(&self) -> bool {
self.ctx.memory().lost_focus(self.id) self.ctx.memory(|mem| mem.lost_focus(self.id))
} }
/// Request that this widget get keyboard focus. /// Request that this widget get keyboard focus.
pub fn request_focus(&self) { pub fn request_focus(&self) {
self.ctx.memory().request_focus(self.id); self.ctx.memory_mut(|mem| mem.request_focus(self.id));
} }
/// Surrender keyboard focus for this widget. /// Surrender keyboard focus for this widget.
pub fn surrender_focus(&self) { pub fn surrender_focus(&self) {
self.ctx.memory().surrender_focus(self.id); self.ctx.memory_mut(|mem| mem.surrender_focus(self.id));
} }
/// The widgets is being dragged. /// The widgets is being dragged.
/// ///
/// To find out which button(s), query [`crate::PointerState::button_down`] /// To find out which button(s), query [`crate::PointerState::button_down`]
/// (`ui.input().pointer.button_down(…)`). /// (`ui.input(|i| i.pointer.button_down(…))`).
/// ///
/// Note that the widget must be sensing drags with [`Sense::drag`]. /// Note that the widget must be sensing drags with [`Sense::drag`].
/// [`crate::DragValue`] senses drags; [`crate::Label`] does not (unless you call [`crate::Label::sense`]). /// [`crate::DragValue`] senses drags; [`crate::Label`] does not (unless you call [`crate::Label::sense`]).
@ -270,17 +270,17 @@ impl Response {
} }
pub fn dragged_by(&self, button: PointerButton) -> bool { pub fn dragged_by(&self, button: PointerButton) -> bool {
self.dragged() && self.ctx.input().pointer.button_down(button) self.dragged() && self.ctx.input(|i| i.pointer.button_down(button))
} }
/// Did a drag on this widgets begin this frame? /// Did a drag on this widgets begin this frame?
pub fn drag_started(&self) -> bool { pub fn drag_started(&self) -> bool {
self.dragged && self.ctx.input().pointer.any_pressed() self.dragged && self.ctx.input(|i| i.pointer.any_pressed())
} }
/// Did a drag on this widgets by the button begin this frame? /// Did a drag on this widgets by the button begin this frame?
pub fn drag_started_by(&self, button: PointerButton) -> bool { pub fn drag_started_by(&self, button: PointerButton) -> bool {
self.drag_started() && self.ctx.input().pointer.button_pressed(button) self.drag_started() && self.ctx.input(|i| i.pointer.button_pressed(button))
} }
/// The widget was being dragged, but now it has been released. /// The widget was being dragged, but now it has been released.
@ -290,13 +290,13 @@ impl Response {
/// The widget was being dragged by the button, but now it has been released. /// The widget was being dragged by the button, but now it has been released.
pub fn drag_released_by(&self, button: PointerButton) -> bool { pub fn drag_released_by(&self, button: PointerButton) -> bool {
self.drag_released() && self.ctx.input().pointer.button_released(button) self.drag_released() && self.ctx.input(|i| i.pointer.button_released(button))
} }
/// If dragged, how many points were we dragged and in what direction? /// If dragged, how many points were we dragged and in what direction?
pub fn drag_delta(&self) -> Vec2 { pub fn drag_delta(&self) -> Vec2 {
if self.dragged() { if self.dragged() {
self.ctx.input().pointer.delta() self.ctx.input(|i| i.pointer.delta())
} else { } else {
Vec2::ZERO Vec2::ZERO
} }
@ -312,7 +312,7 @@ impl Response {
/// None if the pointer is outside the response area. /// None if the pointer is outside the response area.
pub fn hover_pos(&self) -> Option<Pos2> { pub fn hover_pos(&self) -> Option<Pos2> {
if self.hovered() { if self.hovered() {
self.ctx.input().pointer.hover_pos() self.ctx.input(|i| i.pointer.hover_pos())
} else { } else {
None None
} }
@ -402,11 +402,11 @@ impl Response {
} }
fn should_show_hover_ui(&self) -> bool { fn should_show_hover_ui(&self) -> bool {
if self.ctx.memory().everything_is_visible() { if self.ctx.memory(|mem| mem.everything_is_visible()) {
return true; return true;
} }
if !self.hovered || !self.ctx.input().pointer.has_pointer() { if !self.hovered || !self.ctx.input(|i| i.pointer.has_pointer()) {
return false; return false;
} }
@ -414,8 +414,7 @@ impl Response {
// We only show the tooltip when the mouse pointer is still, // We only show the tooltip when the mouse pointer is still,
// but once shown we keep showing it until the mouse leaves the parent. // but once shown we keep showing it until the mouse leaves the parent.
let is_pointer_still = self.ctx.input().pointer.is_still(); if !self.ctx.input(|i| i.pointer.is_still()) && !self.is_tooltip_open() {
if !is_pointer_still && !self.is_tooltip_open() {
// wait for mouse to stop // wait for mouse to stop
self.ctx.request_repaint(); self.ctx.request_repaint();
return false; return false;
@ -424,8 +423,9 @@ impl Response {
// We don't want tooltips of things while we are dragging them, // We don't want tooltips of things while we are dragging them,
// but we do want tooltips while holding down on an item on a touch screen. // but we do want tooltips while holding down on an item on a touch screen.
if self.ctx.input().pointer.any_down() if self
&& self.ctx.input().pointer.has_moved_too_much_for_a_click .ctx
.input(|i| i.pointer.any_down() && i.pointer.has_moved_too_much_for_a_click)
{ {
return false; return false;
} }
@ -464,7 +464,7 @@ impl Response {
/// When hovered, use this icon for the mouse cursor. /// When hovered, use this icon for the mouse cursor.
pub fn on_hover_cursor(self, cursor: CursorIcon) -> Self { pub fn on_hover_cursor(self, cursor: CursorIcon) -> Self {
if self.hovered() { if self.hovered() {
self.ctx.output().cursor_icon = cursor; self.ctx.set_cursor_icon(cursor);
} }
self self
} }
@ -472,7 +472,7 @@ impl Response {
/// When hovered or dragged, use this icon for the mouse cursor. /// When hovered or dragged, use this icon for the mouse cursor.
pub fn on_hover_and_drag_cursor(self, cursor: CursorIcon) -> Self { pub fn on_hover_and_drag_cursor(self, cursor: CursorIcon) -> Self {
if self.hovered() || self.dragged() { if self.hovered() || self.dragged() {
self.ctx.output().cursor_icon = cursor; self.ctx.set_cursor_icon(cursor);
} }
self self
} }
@ -521,8 +521,10 @@ impl Response {
/// # }); /// # });
/// ``` /// ```
pub fn scroll_to_me(&self, align: Option<Align>) { pub fn scroll_to_me(&self, align: Option<Align>) {
self.ctx.frame_state().scroll_target[0] = Some((self.rect.x_range(), align)); self.ctx.frame_state_mut(|state| {
self.ctx.frame_state().scroll_target[1] = Some((self.rect.y_range(), align)); state.scroll_target[0] = Some((self.rect.x_range(), align));
state.scroll_target[1] = Some((self.rect.y_range(), align));
});
} }
/// For accessibility. /// For accessibility.
@ -547,18 +549,18 @@ impl Response {
self.output_event(event); self.output_event(event);
} else { } else {
#[cfg(feature = "accesskit")] #[cfg(feature = "accesskit")]
if let Some(mut node) = self.ctx.accesskit_node(self.id) { self.ctx.accesskit_node(self.id, |node| {
self.fill_accesskit_node_from_widget_info(&mut node, make_info()); self.fill_accesskit_node_from_widget_info(node, make_info());
} });
} }
} }
pub fn output_event(&self, event: crate::output::OutputEvent) { pub fn output_event(&self, event: crate::output::OutputEvent) {
#[cfg(feature = "accesskit")] #[cfg(feature = "accesskit")]
if let Some(mut node) = self.ctx.accesskit_node(self.id) { self.ctx.accesskit_node(self.id, |node| {
self.fill_accesskit_node_from_widget_info(&mut node, event.widget_info().clone()); self.fill_accesskit_node_from_widget_info(node, event.widget_info().clone());
} });
self.ctx.output().events.push(event); self.ctx.output_mut(|o| o.events.push(event));
} }
#[cfg(feature = "accesskit")] #[cfg(feature = "accesskit")]
@ -636,9 +638,8 @@ impl Response {
/// ``` /// ```
pub fn labelled_by(self, id: Id) -> Self { pub fn labelled_by(self, id: Id) -> Self {
#[cfg(feature = "accesskit")] #[cfg(feature = "accesskit")]
if let Some(mut node) = self.ctx.accesskit_node(self.id) { self.ctx
node.labelled_by.push(id.accesskit_id()); .accesskit_node(self.id, |node| node.labelled_by.push(id.accesskit_id()));
}
#[cfg(not(feature = "accesskit"))] #[cfg(not(feature = "accesskit"))]
{ {
let _ = id; let _ = id;

View File

@ -3,11 +3,11 @@
use std::hash::Hash; use std::hash::Hash;
use std::sync::Arc; use std::sync::Arc;
use epaint::mutex::{RwLock, RwLockReadGuard, RwLockWriteGuard}; use epaint::mutex::RwLock;
use crate::{ use crate::{
containers::*, ecolor::*, epaint::text::Fonts, layout::*, menu::MenuState, placer::Placer, containers::*, ecolor::*, epaint::text::Fonts, layout::*, menu::MenuState, placer::Placer,
widgets::*, *, util::IdTypeMap, widgets::*, *,
}; };
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
@ -314,84 +314,9 @@ impl Ui {
self.painter().layer_id() self.painter().layer_id()
} }
/// The [`InputState`] of the [`Context`] associated with this [`Ui`].
/// Equivalent to `.ctx().input()`.
///
/// Note that this locks the [`Context`], so be careful with if-let bindings:
///
/// ```
/// # egui::__run_test_ui(|ui| {
/// if let Some(pos) = { ui.input().pointer.hover_pos() } {
/// // This is fine!
/// }
///
/// let pos = ui.input().pointer.hover_pos();
/// if let Some(pos) = pos {
/// // This is also fine!
/// }
///
/// if let Some(pos) = ui.input().pointer.hover_pos() {
/// // ⚠️ Using `ui` again here will lead to a dead-lock!
/// }
/// # });
/// ```
#[inline]
pub fn input(&self) -> RwLockReadGuard<'_, InputState> {
self.ctx().input()
}
/// The [`InputState`] of the [`Context`] associated with this [`Ui`].
/// Equivalent to `.ctx().input_mut()`.
///
/// Note that this locks the [`Context`], so be careful with if-let bindings
/// like for [`Self::input()`].
/// ```
/// # egui::__run_test_ui(|ui| {
/// ui.input_mut().consume_key(egui::Modifiers::default(), egui::Key::Enter);
/// # });
/// ```
#[inline]
pub fn input_mut(&self) -> RwLockWriteGuard<'_, InputState> {
self.ctx().input_mut()
}
/// The [`Memory`] of the [`Context`] associated with this ui.
/// Equivalent to `.ctx().memory()`.
#[inline]
pub fn memory(&self) -> RwLockWriteGuard<'_, Memory> {
self.ctx().memory()
}
/// Stores superficial widget state.
#[inline]
pub fn data(&self) -> RwLockWriteGuard<'_, crate::util::IdTypeMap> {
self.ctx().data()
}
/// The [`PlatformOutput`] of the [`Context`] associated with this ui.
/// Equivalent to `.ctx().output()`.
///
/// ```
/// # egui::__run_test_ui(|ui| {
/// if ui.button("📋").clicked() {
/// ui.output().copied_text = "some_text".to_string();
/// }
/// # });
#[inline]
pub fn output(&self) -> RwLockWriteGuard<'_, PlatformOutput> {
self.ctx().output()
}
/// The [`Fonts`] of the [`Context`] associated with this ui.
/// Equivalent to `.ctx().fonts()`.
#[inline]
pub fn fonts(&self) -> RwLockReadGuard<'_, Fonts> {
self.ctx().fonts()
}
/// The height of text of this text style /// The height of text of this text style
pub fn text_style_height(&self, style: &TextStyle) -> f32 { pub fn text_style_height(&self, style: &TextStyle) -> f32 {
self.fonts().row_height(&style.resolve(self.style())) self.fonts(|f| f.row_height(&style.resolve(self.style())))
} }
/// Screen-space rectangle for clipping what we paint in this ui. /// Screen-space rectangle for clipping what we paint in this ui.
@ -413,6 +338,87 @@ impl Ui {
} }
} }
/// # Helpers for accessing the underlying [`Context`].
/// These functions all lock the [`Context`] owned by this [`Ui`].
/// Please see the documentation of [`Context`] for how locking works!
impl Ui {
/// Read-only access to the shared [`InputState`].
///
/// ```
/// # egui::__run_test_ui(|ui| {
/// if ui.input(|i| i.key_pressed(egui::Key::A)) {
/// // …
/// }
/// # });
/// ```
#[inline]
pub fn input<R>(&self, reader: impl FnOnce(&InputState) -> R) -> R {
self.ctx().input(reader)
}
/// Read-write access to the shared [`InputState`].
#[inline]
pub fn input_mut<R>(&self, writer: impl FnOnce(&mut InputState) -> R) -> R {
self.ctx().input_mut(writer)
}
/// Read-only access to the shared [`Memory`].
#[inline]
pub fn memory<R>(&self, reader: impl FnOnce(&Memory) -> R) -> R {
self.ctx().memory(reader)
}
/// Read-write access to the shared [`Memory`].
#[inline]
pub fn memory_mut<R>(&self, writer: impl FnOnce(&mut Memory) -> R) -> R {
self.ctx().memory_mut(writer)
}
/// Read-only access to the shared [`IdTypeMap`], which stores superficial widget state.
#[inline]
pub fn data<R>(&self, reader: impl FnOnce(&IdTypeMap) -> R) -> R {
self.ctx().data(reader)
}
/// Read-write access to the shared [`IdTypeMap`], which stores superficial widget state.
#[inline]
pub fn data_mut<R>(&self, writer: impl FnOnce(&mut IdTypeMap) -> R) -> R {
self.ctx().data_mut(writer)
}
/// Read-only access to the shared [`PlatformOutput`].
///
/// This is what egui outputs each frame.
///
/// ```
/// # let mut ctx = egui::Context::default();
/// ctx.output_mut(|o| o.cursor_icon = egui::CursorIcon::Progress);
/// ```
#[inline]
pub fn output<R>(&self, reader: impl FnOnce(&PlatformOutput) -> R) -> R {
self.ctx().output(reader)
}
/// Read-write access to the shared [`PlatformOutput`].
///
/// This is what egui outputs each frame.
///
/// ```
/// # let mut ctx = egui::Context::default();
/// ctx.output_mut(|o| o.cursor_icon = egui::CursorIcon::Progress);
/// ```
#[inline]
pub fn output_mut<R>(&self, writer: impl FnOnce(&mut PlatformOutput) -> R) -> R {
self.ctx().output_mut(writer)
}
/// Read-only access to [`Fonts`].
#[inline]
pub fn fonts<R>(&self, reader: impl FnOnce(&Fonts) -> R) -> R {
self.ctx().fonts(reader)
}
}
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
/// # Sizes etc /// # Sizes etc
@ -961,7 +967,8 @@ impl Ui {
pub fn scroll_to_rect(&self, rect: Rect, align: Option<Align>) { pub fn scroll_to_rect(&self, rect: Rect, align: Option<Align>) {
for d in 0..2 { for d in 0..2 {
let range = rect.min[d]..=rect.max[d]; let range = rect.min[d]..=rect.max[d];
self.ctx().frame_state().scroll_target[d] = Some((range, align)); self.ctx()
.frame_state_mut(|state| state.scroll_target[d] = Some((range, align)));
} }
} }
@ -990,7 +997,8 @@ impl Ui {
let target = self.next_widget_position(); let target = self.next_widget_position();
for d in 0..2 { for d in 0..2 {
let target = target[d]; let target = target[d];
self.ctx().frame_state().scroll_target[d] = Some((target..=target, align)); self.ctx()
.frame_state_mut(|state| state.scroll_target[d] = Some((target..=target, align)));
} }
} }
@ -1022,7 +1030,8 @@ impl Ui {
/// # }); /// # });
/// ``` /// ```
pub fn scroll_with_delta(&self, delta: Vec2) { pub fn scroll_with_delta(&self, delta: Vec2) {
self.ctx().frame_state().scroll_delta += delta; self.ctx()
.frame_state_mut(|state| state.scroll_delta += delta);
} }
} }

View File

@ -460,18 +460,18 @@ impl IdTypeMap {
} }
#[inline] #[inline]
pub fn is_empty(&mut self) -> bool { pub fn is_empty(&self) -> bool {
self.0.is_empty() self.0.is_empty()
} }
#[inline] #[inline]
pub fn len(&mut self) -> usize { pub fn len(&self) -> usize {
self.0.len() self.0.len()
} }
/// Count how many values are stored but not yet deserialized. /// Count how many values are stored but not yet deserialized.
#[inline] #[inline]
pub fn count_serialized(&mut self) -> usize { pub fn count_serialized(&self) -> usize {
self.0 self.0
.values() .values()
.filter(|e| matches!(e, Element::Serialized { .. })) .filter(|e| matches!(e, Element::Serialized { .. }))
@ -479,7 +479,7 @@ impl IdTypeMap {
} }
/// Count the number of values are stored with the given type. /// Count the number of values are stored with the given type.
pub fn count<T: 'static>(&mut self) -> usize { pub fn count<T: 'static>(&self) -> usize {
let key = TypeId::of::<T>(); let key = TypeId::of::<T>();
self.0 self.0
.iter() .iter()

View File

@ -573,14 +573,14 @@ impl WidgetText {
let mut text_job = text.into_text_job(ui.style(), fallback_font.into(), valign); let mut text_job = text.into_text_job(ui.style(), fallback_font.into(), valign);
text_job.job.wrap.max_width = wrap_width; text_job.job.wrap.max_width = wrap_width;
WidgetTextGalley { WidgetTextGalley {
galley: ui.fonts().layout_job(text_job.job), galley: ui.fonts(|f| f.layout_job(text_job.job)),
galley_has_color: text_job.job_has_color, galley_has_color: text_job.job_has_color,
} }
} }
Self::LayoutJob(mut job) => { Self::LayoutJob(mut job) => {
job.wrap.max_width = wrap_width; job.wrap.max_width = wrap_width;
WidgetTextGalley { WidgetTextGalley {
galley: ui.fonts().layout_job(job), galley: ui.fonts(|f| f.layout_job(job)),
galley_has_color: true, galley_has_color: true,
} }
} }

View File

@ -228,9 +228,9 @@ fn color_text_ui(ui: &mut Ui, color: impl Into<Color32>, alpha: Alpha) {
if ui.button("📋").on_hover_text("Click to copy").clicked() { if ui.button("📋").on_hover_text("Click to copy").clicked() {
if alpha == Alpha::Opaque { if alpha == Alpha::Opaque {
ui.output().copied_text = format!("{}, {}, {}", r, g, b); ui.output_mut(|o| o.copied_text = format!("{}, {}, {}", r, g, b));
} else { } else {
ui.output().copied_text = format!("{}, {}, {}, {}", r, g, b, a); ui.output_mut(|o| o.copied_text = format!("{}, {}, {}, {}", r, g, b, a));
} }
} }
@ -341,20 +341,20 @@ pub fn color_picker_color32(ui: &mut Ui, srgba: &mut Color32, alpha: Alpha) -> b
pub fn color_edit_button_hsva(ui: &mut Ui, hsva: &mut Hsva, alpha: Alpha) -> Response { pub fn color_edit_button_hsva(ui: &mut Ui, hsva: &mut Hsva, alpha: Alpha) -> Response {
let popup_id = ui.auto_id_with("popup"); let popup_id = ui.auto_id_with("popup");
let open = ui.memory().is_popup_open(popup_id); let open = ui.memory(|mem| mem.is_popup_open(popup_id));
let mut button_response = color_button(ui, (*hsva).into(), open); let mut button_response = color_button(ui, (*hsva).into(), open);
if ui.style().explanation_tooltips { if ui.style().explanation_tooltips {
button_response = button_response.on_hover_text("Click to edit color"); button_response = button_response.on_hover_text("Click to edit color");
} }
if button_response.clicked() { if button_response.clicked() {
ui.memory().toggle_popup(popup_id); ui.memory_mut(|mem| mem.toggle_popup(popup_id));
} }
const COLOR_SLIDER_WIDTH: f32 = 210.0; const COLOR_SLIDER_WIDTH: f32 = 210.0;
// TODO(emilk): make it easier to show a temporary popup that closes when you click outside it // TODO(emilk): make it easier to show a temporary popup that closes when you click outside it
if ui.memory().is_popup_open(popup_id) { if ui.memory(|mem| mem.is_popup_open(popup_id)) {
let area_response = Area::new(popup_id) let area_response = Area::new(popup_id)
.order(Order::Foreground) .order(Order::Foreground)
.fixed_pos(button_response.rect.max) .fixed_pos(button_response.rect.max)
@ -370,9 +370,9 @@ pub fn color_edit_button_hsva(ui: &mut Ui, hsva: &mut Hsva, alpha: Alpha) -> Res
.response; .response;
if !button_response.clicked() if !button_response.clicked()
&& (ui.input().key_pressed(Key::Escape) || area_response.clicked_elsewhere()) && (ui.input(|i| i.key_pressed(Key::Escape)) || area_response.clicked_elsewhere())
{ {
ui.memory().close_popup(); ui.memory_mut(|mem| mem.close_popup());
} }
} }
@ -436,5 +436,5 @@ fn color_cache_set(ctx: &Context, rgba: impl Into<Rgba>, hsva: Hsva) {
// To ensure we keep hue slider when `srgba` is gray we store the full [`Hsva`] in a cache: // To ensure we keep hue slider when `srgba` is gray we store the full [`Hsva`] in a cache:
fn use_color_cache<R>(ctx: &Context, f: impl FnOnce(&mut FixedCache<Rgba, Hsva>) -> R) -> R { fn use_color_cache<R>(ctx: &Context, f: impl FnOnce(&mut FixedCache<Rgba, Hsva>) -> R) -> R {
f(ctx.data().get_temp_mut_or_default(Id::null())) ctx.data_mut(|d| f(d.get_temp_mut_or_default(Id::null())))
} }

View File

@ -368,33 +368,35 @@ impl<'a> Widget for DragValue<'a> {
custom_parser, custom_parser,
} = self; } = self;
let shift = ui.input().modifiers.shift_only(); let shift = ui.input(|i| i.modifiers.shift_only());
// The widget has the same ID whether it's in edit or button mode. // The widget has the same ID whether it's in edit or button mode.
let id = ui.next_auto_id(); let id = ui.next_auto_id();
let is_slow_speed = shift && ui.memory().is_being_dragged(id); let is_slow_speed = shift && ui.memory(|mem| mem.is_being_dragged(id));
// The following call ensures that when a `DragValue` receives focus, // The following ensures that when a `DragValue` receives focus,
// it is immediately rendered in edit mode, rather than being rendered // it is immediately rendered in edit mode, rather than being rendered
// in button mode for just one frame. This is important for // in button mode for just one frame. This is important for
// screen readers. // screen readers.
ui.memory().interested_in_focus(id); let is_kb_editing = ui.memory_mut(|mem| {
let is_kb_editing = ui.memory().has_focus(id); mem.interested_in_focus(id);
if ui.memory().gained_focus(id) { let is_kb_editing = mem.has_focus(id);
ui.memory().drag_value.edit_string = None; if mem.gained_focus(id) {
} mem.drag_value.edit_string = None;
}
is_kb_editing
});
let old_value = get(&mut get_set_value); let old_value = get(&mut get_set_value);
let mut value = old_value; let mut value = old_value;
let aim_rad = ui.input().aim_radius() as f64; let aim_rad = ui.input(|i| i.aim_radius() as f64);
let auto_decimals = (aim_rad / speed.abs()).log10().ceil().clamp(0.0, 15.0) as usize; let auto_decimals = (aim_rad / speed.abs()).log10().ceil().clamp(0.0, 15.0) as usize;
let auto_decimals = auto_decimals + is_slow_speed as usize; let auto_decimals = auto_decimals + is_slow_speed as usize;
let max_decimals = max_decimals.unwrap_or(auto_decimals + 2); let max_decimals = max_decimals.unwrap_or(auto_decimals + 2);
let auto_decimals = auto_decimals.clamp(min_decimals, max_decimals); let auto_decimals = auto_decimals.clamp(min_decimals, max_decimals);
let change = { let change = ui.input_mut(|input| {
let mut change = 0.0; let mut change = 0.0;
let mut input = ui.input_mut();
if is_kb_editing { if is_kb_editing {
// This deliberately doesn't listen for left and right arrow keys, // This deliberately doesn't listen for left and right arrow keys,
@ -418,16 +420,18 @@ impl<'a> Widget for DragValue<'a> {
} }
change change
}; });
#[cfg(feature = "accesskit")] #[cfg(feature = "accesskit")]
{ {
use accesskit::{Action, ActionData}; use accesskit::{Action, ActionData};
for request in ui.input().accesskit_action_requests(id, Action::SetValue) { ui.input(|input| {
if let Some(ActionData::NumericValue(new_value)) = request.data { for request in input.accesskit_action_requests(id, Action::SetValue) {
value = new_value; if let Some(ActionData::NumericValue(new_value)) = request.data {
value = new_value;
}
} }
} });
} }
if change != 0.0 { if change != 0.0 {
@ -438,7 +442,7 @@ impl<'a> Widget for DragValue<'a> {
value = clamp_to_range(value, clamp_range.clone()); value = clamp_to_range(value, clamp_range.clone());
if old_value != value { if old_value != value {
set(&mut get_set_value, value); set(&mut get_set_value, value);
ui.memory().drag_value.edit_string = None; ui.memory_mut(|mem| mem.drag_value.edit_string = None);
} }
let value_text = match custom_formatter { let value_text = match custom_formatter {
@ -457,10 +461,7 @@ impl<'a> Widget for DragValue<'a> {
let mut response = if is_kb_editing { let mut response = if is_kb_editing {
let button_width = ui.spacing().interact_size.x; let button_width = ui.spacing().interact_size.x;
let mut value_text = ui let mut value_text = ui
.memory() .memory_mut(|mem| mem.drag_value.edit_string.take())
.drag_value
.edit_string
.take()
.unwrap_or_else(|| value_text.clone()); .unwrap_or_else(|| value_text.clone());
let response = ui.add( let response = ui.add(
TextEdit::singleline(&mut value_text) TextEdit::singleline(&mut value_text)
@ -476,7 +477,7 @@ impl<'a> Widget for DragValue<'a> {
let parsed_value = clamp_to_range(parsed_value, clamp_range.clone()); let parsed_value = clamp_to_range(parsed_value, clamp_range.clone());
set(&mut get_set_value, parsed_value); set(&mut get_set_value, parsed_value);
} }
ui.memory().drag_value.edit_string = Some(value_text); ui.memory_mut(|mem| mem.drag_value.edit_string = Some(value_text));
response response
} else { } else {
let button = Button::new( let button = Button::new(
@ -499,10 +500,12 @@ impl<'a> Widget for DragValue<'a> {
} }
if response.clicked() { if response.clicked() {
ui.memory().drag_value.edit_string = None; ui.memory_mut(|mem| {
ui.memory().request_focus(id); mem.drag_value.edit_string = None;
mem.request_focus(id);
});
} else if response.dragged() { } else if response.dragged() {
ui.output().cursor_icon = CursorIcon::ResizeHorizontal; ui.ctx().set_cursor_icon(CursorIcon::ResizeHorizontal);
let mdelta = response.drag_delta(); let mdelta = response.drag_delta();
let delta_points = mdelta.x - mdelta.y; // Increase to the right and up let delta_points = mdelta.x - mdelta.y; // Increase to the right and up
@ -512,7 +515,7 @@ impl<'a> Widget for DragValue<'a> {
let delta_value = delta_points as f64 * speed; let delta_value = delta_points as f64 * speed;
if delta_value != 0.0 { if delta_value != 0.0 {
let mut drag_state = std::mem::take(&mut ui.memory().drag_value); let mut drag_state = ui.memory_mut(|mem| std::mem::take(&mut mem.drag_value));
// Since we round the value being dragged, we need to store the full precision value in memory: // Since we round the value being dragged, we need to store the full precision value in memory:
let stored_value = (drag_state.last_dragged_id == Some(response.id)) let stored_value = (drag_state.last_dragged_id == Some(response.id))
@ -533,7 +536,7 @@ impl<'a> Widget for DragValue<'a> {
drag_state.last_dragged_id = Some(response.id); drag_state.last_dragged_id = Some(response.id);
drag_state.last_dragged_value = Some(stored_value); drag_state.last_dragged_value = Some(stored_value);
ui.memory().drag_value = drag_state; ui.memory_mut(|mem| mem.drag_value = drag_state);
} }
} }
@ -545,7 +548,7 @@ impl<'a> Widget for DragValue<'a> {
response.widget_info(|| WidgetInfo::drag_value(value)); response.widget_info(|| WidgetInfo::drag_value(value));
#[cfg(feature = "accesskit")] #[cfg(feature = "accesskit")]
if let Some(mut node) = ui.ctx().accesskit_node(response.id) { ui.ctx().accesskit_node(response.id, |node| {
use accesskit::Action; use accesskit::Action;
// If either end of the range is unbounded, it's better // If either end of the range is unbounded, it's better
// to leave the corresponding AccessKit field set to None, // to leave the corresponding AccessKit field set to None,
@ -589,7 +592,7 @@ impl<'a> Widget for DragValue<'a> {
let value_text = format!("{}{}{}", prefix, value_text, suffix); let value_text = format!("{}{}{}", prefix, value_text, suffix);
node.value = Some(value_text.into()); node.value = Some(value_text.into());
} }
} });
response response
} }

View File

@ -38,7 +38,7 @@ impl Widget for Link {
response.widget_info(|| WidgetInfo::labeled(WidgetType::Link, text_galley.text())); response.widget_info(|| WidgetInfo::labeled(WidgetType::Link, text_galley.text()));
if response.hovered() { if response.hovered() {
ui.ctx().output().cursor_icon = CursorIcon::PointingHand; ui.ctx().set_cursor_icon(CursorIcon::PointingHand);
} }
if ui.is_rect_visible(response.rect) { if ui.is_rect_visible(response.rect) {
@ -110,16 +110,20 @@ impl Widget for Hyperlink {
let response = ui.add(Link::new(text)); let response = ui.add(Link::new(text));
if response.clicked() { if response.clicked() {
let modifiers = ui.ctx().input().modifiers; let modifiers = ui.ctx().input(|i| i.modifiers);
ui.ctx().output().open_url = Some(crate::output::OpenUrl { ui.ctx().output_mut(|o| {
url: url.clone(), o.open_url = Some(crate::output::OpenUrl {
new_tab: modifiers.any(), url: url.clone(),
new_tab: modifiers.any(),
});
}); });
} }
if response.middle_clicked() { if response.middle_clicked() {
ui.ctx().output().open_url = Some(crate::output::OpenUrl { ui.ctx().output_mut(|o| {
url: url.clone(), o.open_url = Some(crate::output::OpenUrl {
new_tab: true, url: url.clone(),
new_tab: true,
});
}); });
} }
response.on_hover_text(url) response.on_hover_text(url)

View File

@ -72,7 +72,7 @@ impl Label {
pub fn layout_in_ui(self, ui: &mut Ui) -> (Pos2, WidgetTextGalley, Response) { pub fn layout_in_ui(self, ui: &mut Ui) -> (Pos2, WidgetTextGalley, Response) {
let sense = self.sense.unwrap_or_else(|| { let sense = self.sense.unwrap_or_else(|| {
// We only want to focus labels if the screen reader is on. // We only want to focus labels if the screen reader is on.
if ui.memory().options.screen_reader { if ui.memory(|mem| mem.options.screen_reader) {
Sense::focusable_noninteractive() Sense::focusable_noninteractive()
} else { } else {
Sense::hover() Sense::hover()
@ -120,7 +120,7 @@ impl Label {
if let Some(first_section) = text_job.job.sections.first_mut() { if let Some(first_section) = text_job.job.sections.first_mut() {
first_section.leading_space = first_row_indentation; first_section.leading_space = first_row_indentation;
} }
let text_galley = text_job.into_galley(&ui.fonts()); let text_galley = ui.fonts(|f| text_job.into_galley(f));
let pos = pos2(ui.max_rect().left(), ui.cursor().top()); let pos = pos2(ui.max_rect().left(), ui.cursor().top());
assert!( assert!(
@ -153,7 +153,7 @@ impl Label {
text_job.job.justify = ui.layout().horizontal_justify(); text_job.job.justify = ui.layout().horizontal_justify();
}; };
let text_galley = text_job.into_galley(&ui.fonts()); let text_galley = ui.fonts(|f| text_job.into_galley(f));
let (rect, response) = ui.allocate_exact_size(text_galley.size(), sense); let (rect, response) = ui.allocate_exact_size(text_galley.size(), sense);
let pos = match text_galley.galley.job.halign { let pos = match text_galley.galley.job.halign {
Align::LEFT => rect.left_top(), Align::LEFT => rect.left_top(),

View File

@ -1658,14 +1658,16 @@ fn add_rulers_and_text(
let font_id = TextStyle::Body.resolve(plot.ui.style()); let font_id = TextStyle::Body.resolve(plot.ui.style());
let corner_value = elem.corner_value(); let corner_value = elem.corner_value();
shapes.push(Shape::text( plot.ui.fonts(|f| {
&plot.ui.fonts(), shapes.push(Shape::text(
plot.transform.position_from_point(&corner_value) + vec2(3.0, -2.0), f,
Align2::LEFT_BOTTOM, plot.transform.position_from_point(&corner_value) + vec2(3.0, -2.0),
text, Align2::LEFT_BOTTOM,
font_id, text,
plot.ui.visuals().text_color(), font_id,
)); plot.ui.visuals().text_color(),
));
});
} }
/// Draws a cross of horizontal and vertical ruler at the `pointer` position. /// Draws a cross of horizontal and vertical ruler at the `pointer` position.
@ -1714,15 +1716,16 @@ pub(super) fn rulers_at_value(
}; };
let font_id = TextStyle::Body.resolve(plot.ui.style()); let font_id = TextStyle::Body.resolve(plot.ui.style());
plot.ui.fonts(|f| {
shapes.push(Shape::text( shapes.push(Shape::text(
&plot.ui.fonts(), f,
pointer + vec2(3.0, -2.0), pointer + vec2(3.0, -2.0),
Align2::LEFT_BOTTOM, Align2::LEFT_BOTTOM,
text, text,
font_id, font_id,
plot.ui.visuals().text_color(), plot.ui.visuals().text_color(),
)); ));
});
} }
fn find_closest_rect<'a, T>( fn find_closest_rect<'a, T>(

View File

@ -89,9 +89,7 @@ impl LegendEntry {
let font_id = text_style.resolve(ui.style()); let font_id = text_style.resolve(ui.style());
let galley = ui let galley = ui.fonts(|f| f.layout_delayed_color(text, font_id, f32::INFINITY));
.fonts()
.layout_delayed_color(text, font_id, f32::INFINITY);
let icon_size = galley.size().y; let icon_size = galley.size().y;
let icon_spacing = icon_size / 5.0; let icon_spacing = icon_size / 5.0;

View File

@ -108,11 +108,11 @@ struct PlotMemory {
impl PlotMemory { impl PlotMemory {
pub fn load(ctx: &Context, id: Id) -> Option<Self> { pub fn load(ctx: &Context, id: Id) -> Option<Self> {
ctx.data().get_persisted(id) ctx.data_mut(|d| d.get_persisted(id))
} }
pub fn store(self, ctx: &Context, id: Id) { pub fn store(self, ctx: &Context, id: Id) {
ctx.data().insert_persisted(id, self); ctx.data_mut(|d| d.insert_persisted(id, self));
} }
} }
@ -953,9 +953,9 @@ impl Plot {
if let Some(hover_pos) = response.hover_pos() { if let Some(hover_pos) = response.hover_pos() {
if allow_zoom { if allow_zoom {
let zoom_factor = if data_aspect.is_some() { let zoom_factor = if data_aspect.is_some() {
Vec2::splat(ui.input().zoom_delta()) Vec2::splat(ui.input(|i| i.zoom_delta()))
} else { } else {
ui.input().zoom_delta_2d() ui.input(|i| i.zoom_delta_2d())
}; };
if zoom_factor != Vec2::splat(1.0) { if zoom_factor != Vec2::splat(1.0) {
transform.zoom(zoom_factor, hover_pos); transform.zoom(zoom_factor, hover_pos);
@ -963,7 +963,7 @@ impl Plot {
} }
} }
if allow_scroll { if allow_scroll {
let scroll_delta = ui.input().scroll_delta; let scroll_delta = ui.input(|i| i.scroll_delta);
if scroll_delta != Vec2::ZERO { if scroll_delta != Vec2::ZERO {
transform.translate_bounds(-scroll_delta); transform.translate_bounds(-scroll_delta);
bounds_modified = true.into(); bounds_modified = true.into();
@ -1094,7 +1094,7 @@ impl PlotUi {
/// The pointer position in plot coordinates. Independent of whether the pointer is in the plot area. /// The pointer position in plot coordinates. Independent of whether the pointer is in the plot area.
pub fn pointer_coordinate(&self) -> Option<PlotPoint> { pub fn pointer_coordinate(&self) -> Option<PlotPoint> {
// We need to subtract the drag delta to keep in sync with the frame-delayed screen transform: // We need to subtract the drag delta to keep in sync with the frame-delayed screen transform:
let last_pos = self.ctx().input().pointer.latest_pos()? - self.response.drag_delta(); let last_pos = self.ctx().input(|i| i.pointer.latest_pos())? - self.response.drag_delta();
let value = self.plot_from_screen(last_pos); let value = self.plot_from_screen(last_pos);
Some(value) Some(value)
} }

View File

@ -99,7 +99,8 @@ impl Widget for ProgressBar {
let (dark, bright) = (0.7, 1.0); let (dark, bright) = (0.7, 1.0);
let color_factor = if animate { let color_factor = if animate {
lerp(dark..=bright, ui.input().time.cos().abs()) let time = ui.input(|i| i.time);
lerp(dark..=bright, time.cos().abs())
} else { } else {
bright bright
}; };
@ -115,8 +116,9 @@ impl Widget for ProgressBar {
if animate { if animate {
let n_points = 20; let n_points = 20;
let start_angle = ui.input().time * std::f64::consts::TAU; let time = ui.input(|i| i.time);
let end_angle = start_angle + 240f64.to_radians() * ui.input().time.sin(); let start_angle = time * std::f64::consts::TAU;
let end_angle = start_angle + 240f64.to_radians() * time.sin();
let circle_radius = rounding - 2.0; let circle_radius = rounding - 2.0;
let points: Vec<Pos2> = (0..n_points) let points: Vec<Pos2> = (0..n_points)
.map(|i| { .map(|i| {

View File

@ -540,7 +540,7 @@ impl<'a> Slider<'a> {
if let Some(pointer_position_2d) = response.interact_pointer_pos() { if let Some(pointer_position_2d) = response.interact_pointer_pos() {
let position = self.pointer_position(pointer_position_2d); let position = self.pointer_position(pointer_position_2d);
let new_value = if self.smart_aim { let new_value = if self.smart_aim {
let aim_radius = ui.input().aim_radius(); let aim_radius = ui.input(|i| i.aim_radius());
emath::smart_aim::best_in_range_f64( emath::smart_aim::best_in_range_f64(
self.value_from_position(position - aim_radius, position_range.clone()), self.value_from_position(position - aim_radius, position_range.clone()),
self.value_from_position(position + aim_radius, position_range.clone()), self.value_from_position(position + aim_radius, position_range.clone()),
@ -562,19 +562,19 @@ impl<'a> Slider<'a> {
SliderOrientation::Vertical => (Key::ArrowUp, Key::ArrowDown), SliderOrientation::Vertical => (Key::ArrowUp, Key::ArrowDown),
}; };
decrement += ui.input().num_presses(dec_key); ui.input(|input| {
increment += ui.input().num_presses(inc_key); decrement += input.num_presses(dec_key);
increment += input.num_presses(inc_key);
});
} }
#[cfg(feature = "accesskit")] #[cfg(feature = "accesskit")]
{ {
use accesskit::Action; use accesskit::Action;
decrement += ui ui.input(|input| {
.input() decrement += input.num_accesskit_action_requests(response.id, Action::Decrement);
.num_accesskit_action_requests(response.id, Action::Decrement); increment += input.num_accesskit_action_requests(response.id, Action::Increment);
increment += ui });
.input()
.num_accesskit_action_requests(response.id, Action::Increment);
} }
let kb_step = increment as f32 - decrement as f32; let kb_step = increment as f32 - decrement as f32;
@ -586,7 +586,7 @@ impl<'a> Slider<'a> {
let new_value = match self.step { let new_value = match self.step {
Some(step) => prev_value + (kb_step as f64 * step), Some(step) => prev_value + (kb_step as f64 * step),
None if self.smart_aim => { None if self.smart_aim => {
let aim_radius = ui.input().aim_radius(); let aim_radius = ui.input(|i| i.aim_radius());
emath::smart_aim::best_in_range_f64( emath::smart_aim::best_in_range_f64(
self.value_from_position(new_position - aim_radius, position_range.clone()), self.value_from_position(new_position - aim_radius, position_range.clone()),
self.value_from_position(new_position + aim_radius, position_range.clone()), self.value_from_position(new_position + aim_radius, position_range.clone()),
@ -600,14 +600,13 @@ impl<'a> Slider<'a> {
#[cfg(feature = "accesskit")] #[cfg(feature = "accesskit")]
{ {
use accesskit::{Action, ActionData}; use accesskit::{Action, ActionData};
for request in ui ui.input(|input| {
.input() for request in input.accesskit_action_requests(response.id, Action::SetValue) {
.accesskit_action_requests(response.id, Action::SetValue) if let Some(ActionData::NumericValue(new_value)) = request.data {
{ self.set_value(new_value);
if let Some(ActionData::NumericValue(new_value)) = request.data { }
self.set_value(new_value);
} }
} });
} }
// Paint it: // Paint it:
@ -693,14 +692,12 @@ impl<'a> Slider<'a> {
} }
fn value_ui(&mut self, ui: &mut Ui, position_range: RangeInclusive<f32>) -> Response { fn value_ui(&mut self, ui: &mut Ui, position_range: RangeInclusive<f32>) -> Response {
let change = { // If [`DragValue`] is controlled from the keyboard and `step` is defined, set speed to `step`
// Hold one lock rather than 4 (see https://github.com/emilk/egui/pull/1380). let change = ui.input(|input| {
let input = ui.input();
input.num_presses(Key::ArrowUp) as i32 + input.num_presses(Key::ArrowRight) as i32 input.num_presses(Key::ArrowUp) as i32 + input.num_presses(Key::ArrowRight) as i32
- input.num_presses(Key::ArrowDown) as i32 - input.num_presses(Key::ArrowDown) as i32
- input.num_presses(Key::ArrowLeft) as i32 - input.num_presses(Key::ArrowLeft) as i32
}; });
let any_change = change != 0; let any_change = change != 0;
let speed = if let (Some(step), true) = (self.step, any_change) { let speed = if let (Some(step), true) = (self.step, any_change) {
@ -760,7 +757,7 @@ impl<'a> Slider<'a> {
response.widget_info(|| WidgetInfo::slider(value, self.text.text())); response.widget_info(|| WidgetInfo::slider(value, self.text.text()));
#[cfg(feature = "accesskit")] #[cfg(feature = "accesskit")]
if let Some(mut node) = ui.ctx().accesskit_node(response.id) { ui.ctx().accesskit_node(response.id, |node| {
use accesskit::Action; use accesskit::Action;
node.min_numeric_value = Some(*self.range.start()); node.min_numeric_value = Some(*self.range.start());
node.max_numeric_value = Some(*self.range.end()); node.max_numeric_value = Some(*self.range.end());
@ -773,7 +770,7 @@ impl<'a> Slider<'a> {
if value > *clamp_range.start() { if value > *clamp_range.start() {
node.actions |= Action::Decrement; node.actions |= Action::Decrement;
} }
} });
let slider_response = response.clone(); let slider_response = response.clone();

View File

@ -48,8 +48,9 @@ impl Widget for Spinner {
let radius = (rect.height() / 2.0) - 2.0; let radius = (rect.height() / 2.0) - 2.0;
let n_points = 20; let n_points = 20;
let start_angle = ui.input().time * std::f64::consts::TAU; let time = ui.input(|i| i.time);
let end_angle = start_angle + 240f64.to_radians() * ui.input().time.sin(); let start_angle = time * std::f64::consts::TAU;
let end_angle = start_angle + 240f64.to_radians() * time.sin();
let points: Vec<Pos2> = (0..n_points) let points: Vec<Pos2> = (0..n_points)
.map(|i| { .map(|i| {
let angle = lerp(start_angle..=end_angle, i as f64 / n_points as f64); let angle = lerp(start_angle..=end_angle, i as f64 / n_points as f64);

View File

@ -19,7 +19,7 @@ use super::{CCursorRange, CursorRange, TextEditOutput, TextEditState};
/// if response.changed() { /// if response.changed() {
/// // … /// // …
/// } /// }
/// if response.lost_focus() && ui.input().key_pressed(egui::Key::Enter) { /// if response.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) {
/// // … /// // …
/// } /// }
/// # }); /// # });
@ -206,7 +206,7 @@ impl<'t> TextEdit<'t> {
/// let mut layouter = |ui: &egui::Ui, string: &str, wrap_width: f32| { /// let mut layouter = |ui: &egui::Ui, string: &str, wrap_width: f32| {
/// let mut layout_job: egui::text::LayoutJob = my_memoized_highlighter(string); /// let mut layout_job: egui::text::LayoutJob = my_memoized_highlighter(string);
/// layout_job.wrap.max_width = wrap_width; /// layout_job.wrap.max_width = wrap_width;
/// ui.fonts().layout_job(layout_job) /// ui.fonts(|f| f.layout_job(layout_job))
/// }; /// };
/// ui.add(egui::TextEdit::multiline(&mut my_code).layouter(&mut layouter)); /// ui.add(egui::TextEdit::multiline(&mut my_code).layouter(&mut layouter));
/// # }); /// # });
@ -312,7 +312,7 @@ impl<'t> TextEdit<'t> {
output.response |= ui.interact(frame_rect, id, Sense::click()); output.response |= ui.interact(frame_rect, id, Sense::click());
} }
if output.response.clicked() && !output.response.lost_focus() { if output.response.clicked() && !output.response.lost_focus() {
ui.memory().request_focus(output.response.id); ui.memory_mut(|mem| mem.request_focus(output.response.id));
} }
if frame { if frame {
@ -381,7 +381,7 @@ impl<'t> TextEdit<'t> {
let prev_text = text.as_str().to_owned(); let prev_text = text.as_str().to_owned();
let font_id = font_selection.resolve(ui.style()); let font_id = font_selection.resolve(ui.style());
let row_height = ui.fonts().row_height(&font_id); let row_height = ui.fonts(|f| f.row_height(&font_id));
const MIN_WIDTH: f32 = 24.0; // Never make a [`TextEdit`] more narrow than this. const MIN_WIDTH: f32 = 24.0; // Never make a [`TextEdit`] more narrow than this.
let available_width = ui.available_width().at_least(MIN_WIDTH); let available_width = ui.available_width().at_least(MIN_WIDTH);
let desired_width = desired_width.unwrap_or_else(|| ui.spacing().text_edit_width); let desired_width = desired_width.unwrap_or_else(|| ui.spacing().text_edit_width);
@ -394,11 +394,12 @@ impl<'t> TextEdit<'t> {
let font_id_clone = font_id.clone(); let font_id_clone = font_id.clone();
let mut default_layouter = move |ui: &Ui, text: &str, wrap_width: f32| { let mut default_layouter = move |ui: &Ui, text: &str, wrap_width: f32| {
let text = mask_if_password(password, text); let text = mask_if_password(password, text);
ui.fonts().layout_job(if multiline { let layout_job = if multiline {
LayoutJob::simple(text, font_id_clone.clone(), text_color, wrap_width) LayoutJob::simple(text, font_id_clone.clone(), text_color, wrap_width)
} else { } else {
LayoutJob::simple_singleline(text, font_id_clone.clone(), text_color) LayoutJob::simple_singleline(text, font_id_clone.clone(), text_color)
}) };
ui.fonts(|f| f.layout_job(layout_job))
}; };
let layouter = layouter.unwrap_or(&mut default_layouter); let layouter = layouter.unwrap_or(&mut default_layouter);
@ -428,8 +429,8 @@ impl<'t> TextEdit<'t> {
// dragging select text, or scroll the enclosing [`ScrollArea`] (if any)? // dragging select text, or scroll the enclosing [`ScrollArea`] (if any)?
// Since currently copying selected text in not supported on `eframe` web, // Since currently copying selected text in not supported on `eframe` web,
// we prioritize touch-scrolling: // we prioritize touch-scrolling:
let any_touches = ui.input().any_touches(); // separate line to avoid double-locking the same mutex let allow_drag_to_select =
let allow_drag_to_select = !any_touches || ui.memory().has_focus(id); ui.input(|i| !i.any_touches()) || ui.memory(|mem| mem.has_focus(id));
let sense = if interactive { let sense = if interactive {
if allow_drag_to_select { if allow_drag_to_select {
@ -447,7 +448,7 @@ impl<'t> TextEdit<'t> {
if interactive { if interactive {
if let Some(pointer_pos) = ui.ctx().pointer_interact_pos() { if let Some(pointer_pos) = ui.ctx().pointer_interact_pos() {
if response.hovered() && text.is_mutable() { if response.hovered() && text.is_mutable() {
ui.output().mutable_text_under_cursor = true; ui.output_mut(|o| o.mutable_text_under_cursor = true);
} }
// TODO(emilk): drag selected text to either move or clone (ctrl on windows, alt on mac) // TODO(emilk): drag selected text to either move or clone (ctrl on windows, alt on mac)
@ -457,7 +458,7 @@ impl<'t> TextEdit<'t> {
if ui.visuals().text_cursor_preview if ui.visuals().text_cursor_preview
&& response.hovered() && response.hovered()
&& ui.input().pointer.is_moving() && ui.input(|i| i.pointer.is_moving())
{ {
// preview: // preview:
paint_cursor_end( paint_cursor_end(
@ -487,9 +488,9 @@ impl<'t> TextEdit<'t> {
secondary: galley.from_ccursor(ccursor_range.secondary), secondary: galley.from_ccursor(ccursor_range.secondary),
})); }));
} else if allow_drag_to_select { } else if allow_drag_to_select {
if response.hovered() && ui.input().pointer.any_pressed() { if response.hovered() && ui.input(|i| i.pointer.any_pressed()) {
ui.memory().request_focus(id); ui.memory_mut(|mem| mem.request_focus(id));
if ui.input().modifiers.shift { if ui.input(|i| i.modifiers.shift) {
if let Some(mut cursor_range) = state.cursor_range(&galley) { if let Some(mut cursor_range) = state.cursor_range(&galley) {
cursor_range.primary = cursor_at_pointer; cursor_range.primary = cursor_at_pointer;
state.set_cursor_range(Some(cursor_range)); state.set_cursor_range(Some(cursor_range));
@ -499,7 +500,8 @@ impl<'t> TextEdit<'t> {
} else { } else {
state.set_cursor_range(Some(CursorRange::one(cursor_at_pointer))); state.set_cursor_range(Some(CursorRange::one(cursor_at_pointer)));
} }
} else if ui.input().pointer.any_down() && response.is_pointer_button_down_on() } else if ui.input(|i| i.pointer.any_down())
&& response.is_pointer_button_down_on()
{ {
// drag to select text: // drag to select text:
if let Some(mut cursor_range) = state.cursor_range(&galley) { if let Some(mut cursor_range) = state.cursor_range(&galley) {
@ -511,14 +513,14 @@ impl<'t> TextEdit<'t> {
} }
} }
if response.hovered() && interactive { if interactive && response.hovered() {
ui.output().cursor_icon = CursorIcon::Text; ui.ctx().set_cursor_icon(CursorIcon::Text);
} }
let mut cursor_range = None; let mut cursor_range = None;
let prev_cursor_range = state.cursor_range(&galley); let prev_cursor_range = state.cursor_range(&galley);
if ui.memory().has_focus(id) && interactive { if interactive && ui.memory(|mem| mem.has_focus(id)) {
ui.memory().lock_focus(id, lock_focus); ui.memory_mut(|mem| mem.lock_focus(id, lock_focus));
let default_cursor_range = if cursor_at_end { let default_cursor_range = if cursor_at_end {
CursorRange::one(galley.end()) CursorRange::one(galley.end())
@ -549,7 +551,7 @@ impl<'t> TextEdit<'t> {
// Visual clipping for singleline text editor with text larger than width // Visual clipping for singleline text editor with text larger than width
if !multiline { if !multiline {
let cursor_pos = match (cursor_range, ui.memory().has_focus(id)) { let cursor_pos = match (cursor_range, ui.memory(|mem| mem.has_focus(id))) {
(Some(cursor_range), true) => galley.pos_from_cursor(&cursor_range.primary).min.x, (Some(cursor_range), true) => galley.pos_from_cursor(&cursor_range.primary).min.x,
_ => 0.0, _ => 0.0,
}; };
@ -594,7 +596,7 @@ impl<'t> TextEdit<'t> {
galley.paint_with_fallback_color(&painter, response.rect.min, hint_text_color); galley.paint_with_fallback_color(&painter, response.rect.min, hint_text_color);
} }
if ui.memory().has_focus(id) { if ui.memory(|mem| mem.has_focus(id)) {
if let Some(cursor_range) = state.cursor_range(&galley) { if let Some(cursor_range) = state.cursor_range(&galley) {
// We paint the cursor on top of the text, in case // We paint the cursor on top of the text, in case
// the text galley has backgrounds (as e.g. `code` snippets in markup do). // the text galley has backgrounds (as e.g. `code` snippets in markup do).
@ -621,9 +623,13 @@ impl<'t> TextEdit<'t> {
// But `winit` and `egui_web` differs in how to set the // But `winit` and `egui_web` differs in how to set the
// position of IME. // position of IME.
if cfg!(target_arch = "wasm32") { if cfg!(target_arch = "wasm32") {
ui.ctx().output().text_cursor_pos = Some(cursor_pos.left_top()); ui.ctx().output_mut(|o| {
o.text_cursor_pos = Some(cursor_pos.left_top());
});
} else { } else {
ui.ctx().output().text_cursor_pos = Some(cursor_pos.left_bottom()); ui.ctx().output_mut(|o| {
o.text_cursor_pos = Some(cursor_pos.left_bottom());
});
} }
} }
} }
@ -659,89 +665,98 @@ impl<'t> TextEdit<'t> {
} }
#[cfg(feature = "accesskit")] #[cfg(feature = "accesskit")]
if let Some(mut node) = ui.ctx().accesskit_node(response.id) { {
use accesskit::{Role, TextDirection, TextPosition, TextSelection}; let parent_id = ui.ctx().accesskit_node(response.id, |node| {
use accesskit::{TextPosition, TextSelection};
let parent_id = response.id; let parent_id = response.id;
if let Some(cursor_range) = &cursor_range { if let Some(cursor_range) = &cursor_range {
let anchor = &cursor_range.secondary.rcursor; let anchor = &cursor_range.secondary.rcursor;
let focus = &cursor_range.primary.rcursor; let focus = &cursor_range.primary.rcursor;
node.text_selection = Some(TextSelection { node.text_selection = Some(TextSelection {
anchor: TextPosition { anchor: TextPosition {
node: parent_id.with(anchor.row).accesskit_id(), node: parent_id.with(anchor.row).accesskit_id(),
character_index: anchor.column, character_index: anchor.column,
}, },
focus: TextPosition { focus: TextPosition {
node: parent_id.with(focus.row).accesskit_id(), node: parent_id.with(focus.row).accesskit_id(),
character_index: focus.column, character_index: focus.column,
}, },
});
}
node.default_action_verb = Some(accesskit::DefaultActionVerb::Focus);
node.multiline = self.multiline;
parent_id
});
if let Some(parent_id) = parent_id {
// drop ctx lock before further processing
use accesskit::{Role, TextDirection};
ui.ctx().with_accessibility_parent(parent_id, || {
for (i, row) in galley.rows.iter().enumerate() {
let id = parent_id.with(i);
ui.ctx().accesskit_node(id, |node| {
node.role = Role::InlineTextBox;
let rect = row.rect.translate(text_draw_pos.to_vec2());
node.bounds = Some(accesskit::kurbo::Rect {
x0: rect.min.x.into(),
y0: rect.min.y.into(),
x1: rect.max.x.into(),
y1: rect.max.y.into(),
});
node.text_direction = Some(TextDirection::LeftToRight);
// TODO(mwcampbell): Set more node fields for the row
// once AccessKit adapters expose text formatting info.
let glyph_count = row.glyphs.len();
let mut value = String::new();
value.reserve(glyph_count);
let mut character_lengths = Vec::<u8>::new();
character_lengths.reserve(glyph_count);
let mut character_positions = Vec::<f32>::new();
character_positions.reserve(glyph_count);
let mut character_widths = Vec::<f32>::new();
character_widths.reserve(glyph_count);
let mut word_lengths = Vec::<u8>::new();
let mut was_at_word_end = false;
let mut last_word_start = 0usize;
for glyph in &row.glyphs {
let is_word_char = is_word_char(glyph.chr);
if is_word_char && was_at_word_end {
word_lengths
.push((character_lengths.len() - last_word_start) as _);
last_word_start = character_lengths.len();
}
was_at_word_end = !is_word_char;
let old_len = value.len();
value.push(glyph.chr);
character_lengths.push((value.len() - old_len) as _);
character_positions.push(glyph.pos.x - row.rect.min.x);
character_widths.push(glyph.size.x);
}
if row.ends_with_newline {
value.push('\n');
character_lengths.push(1);
character_positions.push(row.rect.max.x - row.rect.min.x);
character_widths.push(0.0);
}
word_lengths.push((character_lengths.len() - last_word_start) as _);
node.value = Some(value.into());
node.character_lengths = character_lengths.into();
node.character_positions = Some(character_positions.into());
node.character_widths = Some(character_widths.into());
node.word_lengths = word_lengths.into();
});
}
}); });
} }
node.default_action_verb = Some(accesskit::DefaultActionVerb::Focus);
node.multiline = self.multiline;
drop(node);
ui.ctx().with_accessibility_parent(parent_id, || {
for (i, row) in galley.rows.iter().enumerate() {
let id = parent_id.with(i);
let mut node = ui.ctx().accesskit_node(id).unwrap();
node.role = Role::InlineTextBox;
let rect = row.rect.translate(text_draw_pos.to_vec2());
node.bounds = Some(accesskit::kurbo::Rect {
x0: rect.min.x.into(),
y0: rect.min.y.into(),
x1: rect.max.x.into(),
y1: rect.max.y.into(),
});
node.text_direction = Some(TextDirection::LeftToRight);
// TODO(mwcampbell): Set more node fields for the row
// once AccessKit adapters expose text formatting info.
let glyph_count = row.glyphs.len();
let mut value = String::new();
value.reserve(glyph_count);
let mut character_lengths = Vec::<u8>::new();
character_lengths.reserve(glyph_count);
let mut character_positions = Vec::<f32>::new();
character_positions.reserve(glyph_count);
let mut character_widths = Vec::<f32>::new();
character_widths.reserve(glyph_count);
let mut word_lengths = Vec::<u8>::new();
let mut was_at_word_end = false;
let mut last_word_start = 0usize;
for glyph in &row.glyphs {
let is_word_char = is_word_char(glyph.chr);
if is_word_char && was_at_word_end {
word_lengths.push((character_lengths.len() - last_word_start) as _);
last_word_start = character_lengths.len();
}
was_at_word_end = !is_word_char;
let old_len = value.len();
value.push(glyph.chr);
character_lengths.push((value.len() - old_len) as _);
character_positions.push(glyph.pos.x - row.rect.min.x);
character_widths.push(glyph.size.x);
}
if row.ends_with_newline {
value.push('\n');
character_lengths.push(1);
character_positions.push(row.rect.max.x - row.rect.min.x);
character_widths.push(0.0);
}
word_lengths.push((character_lengths.len() - last_word_start) as _);
node.value = Some(value.into());
node.character_lengths = character_lengths.into();
node.character_positions = Some(character_positions.into());
node.character_widths = Some(character_widths.into());
node.word_lengths = word_lengths.into();
}
});
} }
TextEditOutput { TextEditOutput {
@ -812,19 +827,19 @@ fn events(
// We feed state to the undoer both before and after handling input // We feed state to the undoer both before and after handling input
// so that the undoer creates automatic saves even when there are no events for a while. // so that the undoer creates automatic saves even when there are no events for a while.
state.undoer.lock().feed_state( state.undoer.lock().feed_state(
ui.input().time, ui.input(|i| i.time),
&(cursor_range.as_ccursor_range(), text.as_str().to_owned()), &(cursor_range.as_ccursor_range(), text.as_str().to_owned()),
); );
let copy_if_not_password = |ui: &Ui, text: String| { let copy_if_not_password = |ui: &Ui, text: String| {
if !password { if !password {
ui.ctx().output().copied_text = text; ui.ctx().output_mut(|o| o.copied_text = text);
} }
}; };
let mut any_change = false; let mut any_change = false;
let events = ui.input().events.clone(); // avoid dead-lock by cloning. TODO(emilk): optimize let events = ui.input(|i| i.events.clone()); // avoid dead-lock by cloning. TODO(emilk): optimize
for event in &events { for event in &events {
let did_mutate_text = match event { let did_mutate_text = match event {
Event::Copy => { Event::Copy => {
@ -869,7 +884,7 @@ fn events(
modifiers, modifiers,
.. ..
} => { } => {
if multiline && ui.memory().has_lock_focus(id) { if multiline && ui.memory(|mem| mem.has_lock_focus(id)) {
let mut ccursor = delete_selected(text, &cursor_range); let mut ccursor = delete_selected(text, &cursor_range);
if modifiers.shift { if modifiers.shift {
// TODO(emilk): support removing indentation over a selection? // TODO(emilk): support removing indentation over a selection?
@ -893,7 +908,7 @@ fn events(
// TODO(emilk): if code editor, auto-indent by same leading tabs, + one if the lines end on an opening bracket // TODO(emilk): if code editor, auto-indent by same leading tabs, + one if the lines end on an opening bracket
Some(CCursorRange::one(ccursor)) Some(CCursorRange::one(ccursor))
} else { } else {
ui.memory().surrender_focus(id); // End input with enter ui.memory_mut(|mem| mem.surrender_focus(id)); // End input with enter
break; break;
} }
} }
@ -997,7 +1012,7 @@ fn events(
state.set_cursor_range(Some(cursor_range)); state.set_cursor_range(Some(cursor_range));
state.undoer.lock().feed_state( state.undoer.lock().feed_state(
ui.input().time, ui.input(|i| i.time),
&(cursor_range.as_ccursor_range(), text.as_str().to_owned()), &(cursor_range.as_ccursor_range(), text.as_str().to_owned()),
); );

View File

@ -34,11 +34,11 @@ pub struct TextEditState {
impl TextEditState { impl TextEditState {
pub fn load(ctx: &Context, id: Id) -> Option<Self> { pub fn load(ctx: &Context, id: Id) -> Option<Self> {
ctx.data().get_persisted(id) ctx.data_mut(|d| d.get_persisted(id))
} }
pub fn store(self, ctx: &Context, id: Id) { pub fn store(self, ctx: &Context, id: Id) {
ctx.data().insert_persisted(id, self); ctx.data_mut(|d| d.insert_persisted(id, self));
} }
/// The the currently selected range of characters. /// The the currently selected range of characters.

View File

@ -35,7 +35,7 @@ impl Default for FractalClock {
impl FractalClock { impl FractalClock {
pub fn ui(&mut self, ui: &mut Ui, seconds_since_midnight: Option<f64>) { pub fn ui(&mut self, ui: &mut Ui, seconds_since_midnight: Option<f64>) {
if !self.paused { if !self.paused {
self.time = seconds_since_midnight.unwrap_or_else(|| ui.input().time); self.time = seconds_since_midnight.unwrap_or_else(|| ui.input(|i| i.time));
ui.ctx().request_repaint(); ui.ctx().request_repaint();
} }

View File

@ -131,7 +131,7 @@ fn ui_url(ui: &mut egui::Ui, frame: &mut eframe::Frame, url: &mut String) -> boo
trigger_fetch = true; trigger_fetch = true;
} }
if ui.button("Random image").clicked() { if ui.button("Random image").clicked() {
let seed = ui.input().time; let seed = ui.input(|i| i.time);
let side = 640; let side = 640;
*url = format!("https://picsum.photos/seed/{}/{}", seed, side); *url = format!("https://picsum.photos/seed/{}/{}", seed, side);
trigger_fetch = true; trigger_fetch = true;
@ -187,7 +187,7 @@ fn ui_resource(ui: &mut egui::Ui, resource: &Resource) {
if let Some(text) = &text { if let Some(text) = &text {
let tooltip = "Click to copy the response body"; let tooltip = "Click to copy the response body";
if ui.button("📋").on_hover_text(tooltip).clicked() { if ui.button("📋").on_hover_text(tooltip).clicked() {
ui.output().copied_text = text.clone(); ui.output_mut(|o| o.copied_text = text.clone());
} }
ui.separator(); ui.separator();
} }
@ -245,7 +245,7 @@ impl ColoredText {
let mut layouter = |ui: &egui::Ui, _string: &str, wrap_width: f32| { let mut layouter = |ui: &egui::Ui, _string: &str, wrap_width: f32| {
let mut layout_job = self.0.clone(); let mut layout_job = self.0.clone();
layout_job.wrap.max_width = wrap_width; layout_job.wrap.max_width = wrap_width;
ui.fonts().layout_job(layout_job) ui.fonts(|f| f.layout_job(layout_job))
}; };
let mut text = self.0.text.as_str(); let mut text = self.0.text.as_str();
@ -258,7 +258,7 @@ impl ColoredText {
} else { } else {
let mut job = self.0.clone(); let mut job = self.0.clone();
job.wrap.max_width = ui.available_width(); job.wrap.max_width = ui.available_width();
let galley = ui.fonts().layout_job(job); let galley = ui.fonts(|f| f.layout_job(job));
let (response, painter) = ui.allocate_painter(galley.size(), egui::Sense::hover()); let (response, painter) = ui.allocate_painter(galley.size(), egui::Sense::hover());
painter.add(egui::Shape::galley(response.rect.min, galley)); painter.add(egui::Shape::galley(response.rect.min, galley));
} }

View File

@ -81,7 +81,7 @@ impl Default for BackendPanel {
impl BackendPanel { impl BackendPanel {
pub fn update(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) { pub fn update(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) {
self.frame_history self.frame_history
.on_new_frame(ctx.input().time, frame.info().cpu_usage); .on_new_frame(ctx.input(|i| i.time), frame.info().cpu_usage);
match self.run_mode { match self.run_mode {
RunMode::Continuous => { RunMode::Continuous => {
@ -131,9 +131,9 @@ impl BackendPanel {
ui.separator(); ui.separator();
{ {
let mut screen_reader = ui.ctx().options().screen_reader; let mut screen_reader = ui.ctx().options(|o| o.screen_reader);
ui.checkbox(&mut screen_reader, "🔈 Screen reader").on_hover_text("Experimental feature: checking this will turn on the screen reader on supported platforms"); ui.checkbox(&mut screen_reader, "🔈 Screen reader").on_hover_text("Experimental feature: checking this will turn on the screen reader on supported platforms");
ui.ctx().options().screen_reader = screen_reader; ui.ctx().options_mut(|o| o.screen_reader = screen_reader);
} }
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
@ -339,9 +339,11 @@ impl EguiWindows {
output_event_history, output_event_history,
} = self; } = self;
for event in &ctx.output().events { ctx.output(|o| {
output_event_history.push_back(event.clone()); for event in &o.events {
} output_event_history.push_back(event.clone());
}
});
while output_event_history.len() > 1000 { while output_event_history.len() > 1000 {
output_event_history.pop_front(); output_event_history.pop_front();
} }

View File

@ -95,19 +95,21 @@ impl FrameHistory {
)); ));
let cpu_usage = to_screen.inverse().transform_pos(pointer_pos).y; let cpu_usage = to_screen.inverse().transform_pos(pointer_pos).y;
let text = format!("{:.1} ms", 1e3 * cpu_usage); let text = format!("{:.1} ms", 1e3 * cpu_usage);
shapes.push(Shape::text( shapes.push(ui.fonts(|f| {
&ui.fonts(), Shape::text(
pos2(rect.left(), y), f,
egui::Align2::LEFT_BOTTOM, pos2(rect.left(), y),
text, egui::Align2::LEFT_BOTTOM,
TextStyle::Monospace.resolve(ui.style()), text,
color, TextStyle::Monospace.resolve(ui.style()),
)); color,
)
}));
} }
let circle_color = color; let circle_color = color;
let radius = 2.0; let radius = 2.0;
let right_side_time = ui.input().time; // Time at right side of screen let right_side_time = ui.input(|i| i.time); // Time at right side of screen
for (time, cpu_usage) in history.iter() { for (time, cpu_usage) in history.iter() {
let age = (right_side_time - time) as f32; let age = (right_side_time - time) as f32;

View File

@ -191,10 +191,7 @@ impl eframe::App for WrapApp {
} }
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
if ctx if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::F11)) {
.input_mut()
.consume_key(egui::Modifiers::NONE, egui::Key::F11)
{
frame.set_fullscreen(!frame.info().window_info.fullscreen); frame.set_fullscreen(!frame.info().window_info.fullscreen);
} }
@ -241,7 +238,8 @@ impl WrapApp {
fn backend_panel(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) { fn backend_panel(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) {
// The backend-panel can be toggled on/off. // The backend-panel can be toggled on/off.
// We show a little animation when the user switches it. // We show a little animation when the user switches it.
let is_open = self.state.backend_panel.open || ctx.memory().everything_is_visible(); let is_open =
self.state.backend_panel.open || ctx.memory(|mem| mem.everything_is_visible());
egui::SidePanel::left("backend_panel") egui::SidePanel::left("backend_panel")
.resizable(false) .resizable(false)
@ -266,13 +264,13 @@ impl WrapApp {
.on_hover_text("Forget scroll, positions, sizes etc") .on_hover_text("Forget scroll, positions, sizes etc")
.clicked() .clicked()
{ {
*ui.ctx().memory() = Default::default(); ui.ctx().memory_mut(|mem| *mem = Default::default());
ui.close_menu(); ui.close_menu();
} }
if ui.button("Reset everything").clicked() { if ui.button("Reset everything").clicked() {
self.state = Default::default(); self.state = Default::default();
*ui.ctx().memory() = Default::default(); ui.ctx().memory_mut(|mem| *mem = Default::default());
ui.close_menu(); ui.close_menu();
} }
}); });
@ -282,7 +280,7 @@ impl WrapApp {
let mut found_anchor = false; let mut found_anchor = false;
let selected_anchor = self.state.selected_anchor.clone(); let selected_anchor = self.state.selected_anchor.clone();
for (_name, anchor, app) in self.apps_iter_mut() { for (_name, anchor, app) in self.apps_iter_mut() {
if anchor == selected_anchor || ctx.memory().everything_is_visible() { if anchor == selected_anchor || ctx.memory(|mem| mem.everything_is_visible()) {
app.update(ctx, frame); app.update(ctx, frame);
found_anchor = true; found_anchor = true;
} }
@ -316,7 +314,7 @@ impl WrapApp {
{ {
selected_anchor = anchor.to_owned(); selected_anchor = anchor.to_owned();
if frame.is_web() { if frame.is_web() {
ui.output().open_url(format!("#{}", anchor)); ui.output_mut(|o| o.open_url(format!("#{}", anchor)));
} }
} }
} }
@ -328,7 +326,7 @@ impl WrapApp {
if clock_button(ui, crate::seconds_since_midnight()).clicked() { if clock_button(ui, crate::seconds_since_midnight()).clicked() {
self.state.selected_anchor = "clock".to_owned(); self.state.selected_anchor = "clock".to_owned();
if frame.is_web() { if frame.is_web() {
ui.output().open_url("#clock"); ui.output_mut(|o| o.open_url("#clock"));
} }
} }
} }
@ -342,22 +340,25 @@ impl WrapApp {
use std::fmt::Write as _; use std::fmt::Write as _;
// Preview hovering files: // Preview hovering files:
if !ctx.input().raw.hovered_files.is_empty() { if !ctx.input(|i| i.raw.hovered_files.is_empty()) {
let mut text = "Dropping files:\n".to_owned(); let text = ctx.input(|i| {
for file in &ctx.input().raw.hovered_files { let mut text = "Dropping files:\n".to_owned();
if let Some(path) = &file.path { for file in &i.raw.hovered_files {
write!(text, "\n{}", path.display()).ok(); if let Some(path) = &file.path {
} else if !file.mime.is_empty() { write!(text, "\n{}", path.display()).ok();
write!(text, "\n{}", file.mime).ok(); } else if !file.mime.is_empty() {
} else { write!(text, "\n{}", file.mime).ok();
text += "\n???"; } else {
text += "\n???";
}
} }
} text
});
let painter = let painter =
ctx.layer_painter(LayerId::new(Order::Foreground, Id::new("file_drop_target"))); ctx.layer_painter(LayerId::new(Order::Foreground, Id::new("file_drop_target")));
let screen_rect = ctx.input().screen_rect(); let screen_rect = ctx.screen_rect();
painter.rect_filled(screen_rect, 0.0, Color32::from_black_alpha(192)); painter.rect_filled(screen_rect, 0.0, Color32::from_black_alpha(192));
painter.text( painter.text(
screen_rect.center(), screen_rect.center(),
@ -369,9 +370,11 @@ impl WrapApp {
} }
// Collect dropped files: // Collect dropped files:
if !ctx.input().raw.dropped_files.is_empty() { ctx.input(|i| {
self.dropped_files = ctx.input().raw.dropped_files.clone(); if !i.raw.dropped_files.is_empty() {
} self.dropped_files = i.raw.dropped_files.clone();
}
});
// Show dropped files (if any): // Show dropped files (if any):
if !self.dropped_files.is_empty() { if !self.dropped_files.is_empty() {

View File

@ -38,7 +38,7 @@ pub fn criterion_benchmark(c: &mut Criterion) {
if false { if false {
let ctx = egui::Context::default(); let ctx = egui::Context::default();
ctx.memory().set_everything_is_visible(true); // give us everything ctx.memory_mut(|m| m.set_everything_is_visible(true)); // give us everything
let mut demo_windows = egui_demo_lib::DemoWindows::default(); let mut demo_windows = egui_demo_lib::DemoWindows::default();
c.bench_function("demo_full_no_tessellate", |b| { c.bench_function("demo_full_no_tessellate", |b| {
b.iter(|| { b.iter(|| {

View File

@ -79,7 +79,7 @@ impl super::View for CodeEditor {
let mut layout_job = let mut layout_job =
crate::syntax_highlighting::highlight(ui.ctx(), &theme, string, language); crate::syntax_highlighting::highlight(ui.ctx(), &theme, string, language);
layout_job.wrap.max_width = wrap_width; layout_job.wrap.max_width = wrap_width;
ui.fonts().layout_job(layout_job) ui.fonts(|f| f.layout_job(layout_job))
}; };
egui::ScrollArea::vertical().show(ui, |ui| { egui::ScrollArea::vertical().show(ui, |ui| {

View File

@ -103,7 +103,7 @@ impl CodeExample {
ui.horizontal(|ui| { ui.horizontal(|ui| {
let font_id = egui::TextStyle::Monospace.resolve(ui.style()); let font_id = egui::TextStyle::Monospace.resolve(ui.style());
let indentation = 8.0 * ui.fonts().glyph_width(&font_id, ' '); let indentation = 8.0 * ui.fonts(|f| f.glyph_width(&font_id, ' '));
let item_spacing = ui.spacing_mut().item_spacing; let item_spacing = ui.spacing_mut().item_spacing;
ui.add_space(indentation - item_spacing.x); ui.add_space(indentation - item_spacing.x);

View File

@ -30,7 +30,7 @@ impl super::View for DancingStrings {
Frame::canvas(ui.style()).show(ui, |ui| { Frame::canvas(ui.style()).show(ui, |ui| {
ui.ctx().request_repaint(); ui.ctx().request_repaint();
let time = ui.input().time; let time = ui.input(|i| i.time);
let desired_size = ui.available_width() * vec2(1.0, 0.35); let desired_size = ui.available_width() * vec2(1.0, 0.35);
let (_id, rect) = ui.allocate_space(desired_size); let (_id, rect) = ui.allocate_space(desired_size);

View File

@ -177,7 +177,7 @@ impl DemoWindows {
fn mobile_ui(&mut self, ctx: &Context) { fn mobile_ui(&mut self, ctx: &Context) {
if self.about_is_open { if self.about_is_open {
let screen_size = ctx.input().screen_rect.size(); let screen_size = ctx.input(|i| i.screen_rect.size());
let default_width = (screen_size.x - 20.0).min(400.0); let default_width = (screen_size.x - 20.0).min(400.0);
let mut close = false; let mut close = false;
@ -216,7 +216,7 @@ impl DemoWindows {
ui.menu_button(egui::RichText::new("⏷ demos").size(font_size), |ui| { ui.menu_button(egui::RichText::new("⏷ demos").size(font_size), |ui| {
ui.set_style(ui.ctx().style()); // ignore the "menu" style set by `menu_button`. ui.set_style(ui.ctx().style()); // ignore the "menu" style set by `menu_button`.
self.demo_list_ui(ui); self.demo_list_ui(ui);
if ui.ui_contains_pointer() && ui.input().pointer.any_click() { if ui.ui_contains_pointer() && ui.input(|i| i.pointer.any_click()) {
ui.close_menu(); ui.close_menu();
} }
}); });
@ -291,7 +291,7 @@ impl DemoWindows {
ui.separator(); ui.separator();
if ui.button("Organize windows").clicked() { if ui.button("Organize windows").clicked() {
ui.ctx().memory().reset_areas(); ui.ctx().memory_mut(|mem| mem.reset_areas());
} }
}); });
}); });
@ -309,12 +309,12 @@ fn file_menu_button(ui: &mut Ui) {
// NOTE: we must check the shortcuts OUTSIDE of the actual "File" menu, // 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! // or else they would only be checked if the "File" menu was actually open!
if ui.input_mut().consume_shortcut(&organize_shortcut) { if ui.input_mut(|i| i.consume_shortcut(&organize_shortcut)) {
ui.ctx().memory().reset_areas(); ui.ctx().memory_mut(|mem| mem.reset_areas());
} }
if ui.input_mut().consume_shortcut(&reset_shortcut) { if ui.input_mut(|i| i.consume_shortcut(&reset_shortcut)) {
*ui.ctx().memory() = Default::default(); ui.ctx().memory_mut(|mem| *mem = Default::default());
} }
ui.menu_button("File", |ui| { ui.menu_button("File", |ui| {
@ -335,7 +335,7 @@ fn file_menu_button(ui: &mut Ui) {
) )
.clicked() .clicked()
{ {
ui.ctx().memory().reset_areas(); ui.ctx().memory_mut(|mem| mem.reset_areas());
ui.close_menu(); ui.close_menu();
} }
@ -347,7 +347,7 @@ fn file_menu_button(ui: &mut Ui) {
.on_hover_text("Forget scroll, positions, sizes etc") .on_hover_text("Forget scroll, positions, sizes etc")
.clicked() .clicked()
{ {
*ui.ctx().memory() = Default::default(); ui.ctx().memory_mut(|mem| *mem = Default::default());
ui.close_menu(); ui.close_menu();
} }
}); });

View File

@ -1,7 +1,7 @@
use egui::*; use egui::*;
pub fn drag_source(ui: &mut Ui, id: Id, body: impl FnOnce(&mut Ui)) { pub fn drag_source(ui: &mut Ui, id: Id, body: impl FnOnce(&mut Ui)) {
let is_being_dragged = ui.memory().is_being_dragged(id); let is_being_dragged = ui.memory(|mem| mem.is_being_dragged(id));
if !is_being_dragged { if !is_being_dragged {
let response = ui.scope(body).response; let response = ui.scope(body).response;
@ -9,10 +9,10 @@ pub fn drag_source(ui: &mut Ui, id: Id, body: impl FnOnce(&mut Ui)) {
// Check for drags: // Check for drags:
let response = ui.interact(response.rect, id, Sense::drag()); let response = ui.interact(response.rect, id, Sense::drag());
if response.hovered() { if response.hovered() {
ui.output().cursor_icon = CursorIcon::Grab; ui.ctx().set_cursor_icon(CursorIcon::Grab);
} }
} else { } else {
ui.output().cursor_icon = CursorIcon::Grabbing; ui.ctx().set_cursor_icon(CursorIcon::Grabbing);
// Paint the body to a new layer: // Paint the body to a new layer:
let layer_id = LayerId::new(Order::Tooltip, id); let layer_id = LayerId::new(Order::Tooltip, id);
@ -37,7 +37,7 @@ pub fn drop_target<R>(
can_accept_what_is_being_dragged: bool, can_accept_what_is_being_dragged: bool,
body: impl FnOnce(&mut Ui) -> R, body: impl FnOnce(&mut Ui) -> R,
) -> InnerResponse<R> { ) -> InnerResponse<R> {
let is_being_dragged = ui.memory().is_anything_being_dragged(); let is_being_dragged = ui.memory(|mem| mem.is_anything_being_dragged());
let margin = Vec2::splat(4.0); let margin = Vec2::splat(4.0);
@ -139,7 +139,7 @@ impl super::View for DragAndDropDemo {
}); });
}); });
if ui.memory().is_being_dragged(item_id) { if ui.memory(|mem| mem.is_being_dragged(item_id)) {
source_col_row = Some((col_idx, row_idx)); source_col_row = Some((col_idx, row_idx));
} }
} }
@ -153,7 +153,7 @@ impl super::View for DragAndDropDemo {
} }
}); });
let is_being_dragged = ui.memory().is_anything_being_dragged(); let is_being_dragged = ui.memory(|mem| mem.is_anything_being_dragged());
if is_being_dragged && can_accept_what_is_being_dragged && response.hovered() { if is_being_dragged && can_accept_what_is_being_dragged && response.hovered() {
drop_col = Some(col_idx); drop_col = Some(col_idx);
} }
@ -162,7 +162,7 @@ impl super::View for DragAndDropDemo {
if let Some((source_col, source_row)) = source_col_row { if let Some((source_col, source_row)) = source_col_row {
if let Some(drop_col) = drop_col { if let Some(drop_col) = drop_col {
if ui.input().pointer.any_released() { if ui.input(|i| i.pointer.any_released()) {
// do the drop: // do the drop:
let item = self.columns[source_col].remove(source_row); let item = self.columns[source_col].remove(source_row);
self.columns[drop_col].push(item); self.columns[drop_col].push(item);

View File

@ -93,7 +93,7 @@ impl super::View for FontBook {
}; };
if ui.add(button).on_hover_ui(tooltip_ui).clicked() { if ui.add(button).on_hover_ui(tooltip_ui).clicked() {
ui.output().copied_text = chr.to_string(); ui.output_mut(|o| o.copied_text = chr.to_string());
} }
} }
} }
@ -103,15 +103,16 @@ impl super::View for FontBook {
} }
fn available_characters(ui: &egui::Ui, family: egui::FontFamily) -> BTreeMap<char, String> { fn available_characters(ui: &egui::Ui, family: egui::FontFamily) -> BTreeMap<char, String> {
ui.fonts() ui.fonts(|f| {
.lock() f.lock()
.fonts .fonts
.font(&egui::FontId::new(10.0, family)) // size is arbitrary for getting the characters .font(&egui::FontId::new(10.0, family)) // size is arbitrary for getting the characters
.characters() .characters()
.iter() .iter()
.filter(|chr| !chr.is_whitespace() && !chr.is_ascii_control()) .filter(|chr| !chr.is_whitespace() && !chr.is_ascii_control())
.map(|&chr| (chr, char_name(chr))) .map(|&chr| (chr, char_name(chr)))
.collect() .collect()
})
} }
fn char_name(chr: char) -> String { fn char_name(chr: char) -> String {

View File

@ -202,7 +202,7 @@ impl Widgets {
ui.horizontal_wrapped(|ui| { ui.horizontal_wrapped(|ui| {
// Trick so we don't have to add spaces in the text below: // Trick so we don't have to add spaces in the text below:
let width = ui.fonts().glyph_width(&TextStyle::Body.resolve(ui.style()), ' '); let width = ui.fonts(|f|f.glyph_width(&TextStyle::Body.resolve(ui.style()), ' '));
ui.spacing_mut().item_spacing.x = width; ui.spacing_mut().item_spacing.x = width;
ui.label(RichText::new("Text can have").color(Color32::from_rgb(110, 255, 110))); ui.label(RichText::new("Text can have").color(Color32::from_rgb(110, 255, 110)));

View File

@ -49,7 +49,7 @@ impl super::View for MultiTouch {
ui.separator(); ui.separator();
ui.label("Try touch gestures Pinch/Stretch, Rotation, and Pressure with 2+ fingers."); ui.label("Try touch gestures Pinch/Stretch, Rotation, and Pressure with 2+ fingers.");
let num_touches = ui.input().multi_touch().map_or(0, |mt| mt.num_touches); let num_touches = ui.input(|i| i.multi_touch().map_or(0, |mt| mt.num_touches));
ui.label(format!("Current touches: {}", num_touches)); ui.label(format!("Current touches: {}", num_touches));
let color = if ui.visuals().dark_mode { let color = if ui.visuals().dark_mode {
@ -93,7 +93,7 @@ impl super::View for MultiTouch {
// touch pressure will make the arrow thicker (not all touch devices support this): // touch pressure will make the arrow thicker (not all touch devices support this):
stroke_width += 10. * multi_touch.force; stroke_width += 10. * multi_touch.force;
self.last_touch_time = ui.input().time; self.last_touch_time = ui.input(|i| i.time);
} else { } else {
self.slowly_reset(ui); self.slowly_reset(ui);
} }
@ -118,7 +118,7 @@ impl MultiTouch {
// This has nothing to do with the touch gesture. It just smoothly brings the // 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: // painted arrow back into its original position, for a nice visual effect:
let time_since_last_touch = (ui.input().time - self.last_touch_time) as f32; let time_since_last_touch = (ui.input(|i| i.time) - self.last_touch_time) as f32;
let delay = 0.5; let delay = 0.5;
if time_since_last_touch < delay { if time_since_last_touch < delay {
@ -133,7 +133,7 @@ impl MultiTouch {
self.rotation = 0.0; self.rotation = 0.0;
self.translation = Vec2::ZERO; self.translation = Vec2::ZERO;
} else { } else {
let dt = ui.input().unstable_dt; let dt = ui.input(|i| i.unstable_dt);
let half_life_factor = (-(2_f32.ln()) / half_life * dt).exp(); let half_life_factor = (-(2_f32.ln()) / half_life * dt).exp();
self.zoom = 1. + ((self.zoom - 1.) * half_life_factor); self.zoom = 1. + ((self.zoom - 1.) * half_life_factor);
self.rotation *= half_life_factor; self.rotation *= half_life_factor;

View File

@ -53,11 +53,10 @@ impl PaintBezier {
}); });
ui.collapsing("Global tessellation options", |ui| { ui.collapsing("Global tessellation options", |ui| {
let mut tessellation_options = *(ui.ctx().tessellation_options()); let mut tessellation_options = ui.ctx().tessellation_options(|to| *to);
let tessellation_options = &mut tessellation_options;
tessellation_options.ui(ui); tessellation_options.ui(ui);
let mut new_tessellation_options = ui.ctx().tessellation_options(); ui.ctx()
*new_tessellation_options = *tessellation_options; .tessellation_options_mut(|to| *to = tessellation_options);
}); });
ui.radio_value(&mut self.degree, 3, "Quadratic Bézier"); ui.radio_value(&mut self.degree, 3, "Quadratic Bézier");

View File

@ -20,7 +20,7 @@ pub fn password_ui(ui: &mut egui::Ui, password: &mut String) -> egui::Response {
// Get state for this widget. // Get state for this widget.
// You should get state by value, not by reference to avoid borrowing of [`Memory`]. // You should get state by value, not by reference to avoid borrowing of [`Memory`].
let mut show_plaintext = ui.data().get_temp::<bool>(state_id).unwrap_or(false); 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 // 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 // We want TextEdit to fill entire space, and have button after that, so in that case we can
@ -43,7 +43,7 @@ pub fn password_ui(ui: &mut egui::Ui, password: &mut String) -> egui::Response {
}); });
// Store the (possibly changed) state: // Store the (possibly changed) state:
ui.data().insert_temp(state_id, show_plaintext); ui.data_mut(|d| d.insert_temp(state_id, show_plaintext));
// All done! Return the interaction response so the user can check what happened // All done! Return the interaction response so the user can check what happened
// (hovered, clicked, …) and maybe show a tooltip: // (hovered, clicked, …) and maybe show a tooltip:

View File

@ -270,7 +270,7 @@ impl LineDemo {
self.options_ui(ui); self.options_ui(ui);
if self.animate { if self.animate {
ui.ctx().request_repaint(); ui.ctx().request_repaint();
self.time += ui.input().unstable_dt.at_most(1.0 / 30.0) as f64; self.time += ui.input(|i| i.unstable_dt).at_most(1.0 / 30.0) as f64;
}; };
let mut plot = Plot::new("lines_demo").legend(Legend::default()); let mut plot = Plot::new("lines_demo").legend(Legend::default());
if self.square { if self.square {

View File

@ -112,7 +112,7 @@ fn huge_content_painter(ui: &mut egui::Ui) {
ui.add_space(4.0); ui.add_space(4.0);
let font_id = TextStyle::Body.resolve(ui.style()); let font_id = TextStyle::Body.resolve(ui.style());
let row_height = ui.fonts().row_height(&font_id) + ui.spacing().item_spacing.y; let row_height = ui.fonts(|f| f.row_height(&font_id)) + ui.spacing().item_spacing.y;
let num_rows = 10_000; let num_rows = 10_000;
ScrollArea::vertical() ScrollArea::vertical()

View File

@ -65,10 +65,7 @@ impl super::View for TextEdit {
egui::Label::new("Press ctrl+Y to toggle the case of selected text (cmd+Y on Mac)"), egui::Label::new("Press ctrl+Y to toggle the case of selected text (cmd+Y on Mac)"),
); );
if ui if ui.input_mut(|i| i.consume_key(egui::Modifiers::COMMAND, egui::Key::Y)) {
.input_mut()
.consume_key(egui::Modifiers::COMMAND, egui::Key::Y)
{
if let Some(text_cursor_range) = output.cursor_range { if let Some(text_cursor_range) = output.cursor_range {
use egui::TextBuffer as _; use egui::TextBuffer as _;
let selected_chars = text_cursor_range.as_sorted_char_range(); let selected_chars = text_cursor_range.as_sorted_char_range();
@ -93,7 +90,7 @@ impl super::View for TextEdit {
let ccursor = egui::text::CCursor::new(0); let ccursor = egui::text::CCursor::new(0);
state.set_ccursor_range(Some(egui::text::CCursorRange::one(ccursor))); state.set_ccursor_range(Some(egui::text::CCursorRange::one(ccursor)));
state.store(ui.ctx(), text_edit_id); state.store(ui.ctx(), text_edit_id);
ui.ctx().memory().request_focus(text_edit_id); // give focus back to the [`TextEdit`]. ui.ctx().memory_mut(|mem| mem.request_focus(text_edit_id)); // give focus back to the [`TextEdit`].
} }
} }
@ -103,7 +100,7 @@ impl super::View for TextEdit {
let ccursor = egui::text::CCursor::new(text.chars().count()); let ccursor = egui::text::CCursor::new(text.chars().count());
state.set_ccursor_range(Some(egui::text::CCursorRange::one(ccursor))); state.set_ccursor_range(Some(egui::text::CCursorRange::one(ccursor)));
state.store(ui.ctx(), text_edit_id); state.store(ui.ctx(), text_edit_id);
ui.ctx().memory().request_focus(text_edit_id); // give focus back to the [`TextEdit`]. ui.ctx().memory_mut(|mem| mem.request_focus(text_edit_id)); // give focus back to the [`TextEdit`].
} }
} }
}); });

View File

@ -50,7 +50,7 @@ impl super::Demo for WindowOptions {
anchor_offset, anchor_offset,
} = self.clone(); } = self.clone();
let enabled = ctx.input().time - disabled_time > 2.0; let enabled = ctx.input(|i| i.time) - disabled_time > 2.0;
if !enabled { if !enabled {
ctx.request_repaint(); ctx.request_repaint();
} }
@ -132,7 +132,7 @@ impl super::View for WindowOptions {
ui.horizontal(|ui| { ui.horizontal(|ui| {
if ui.button("Disable for 2 seconds").clicked() { if ui.button("Disable for 2 seconds").clicked() {
self.disabled_time = ui.input().time; self.disabled_time = ui.input(|i| i.time);
} }
egui::reset_button(ui, self); egui::reset_button(ui, self);
ui.add(crate::egui_github_link_file!()); ui.add(crate::egui_github_link_file!());

View File

@ -81,7 +81,7 @@ impl EasyMarkEditor {
let mut layouter = |ui: &egui::Ui, easymark: &str, wrap_width: f32| { let mut layouter = |ui: &egui::Ui, easymark: &str, wrap_width: f32| {
let mut layout_job = highlighter.highlight(ui.style(), easymark); let mut layout_job = highlighter.highlight(ui.style(), easymark);
layout_job.wrap.max_width = wrap_width; layout_job.wrap.max_width = wrap_width;
ui.fonts().layout_job(layout_job) ui.fonts(|f| f.layout_job(layout_job))
}; };
ui.add( ui.add(
@ -141,7 +141,7 @@ fn nested_hotkeys_ui(ui: &mut egui::Ui) {
fn shortcuts(ui: &Ui, code: &mut dyn TextBuffer, ccursor_range: &mut CCursorRange) -> bool { fn shortcuts(ui: &Ui, code: &mut dyn TextBuffer, ccursor_range: &mut CCursorRange) -> bool {
let mut any_change = false; let mut any_change = false;
if ui.input_mut().consume_shortcut(&SHORTCUT_INDENT) { if ui.input_mut(|i| i.consume_shortcut(&SHORTCUT_INDENT)) {
// This is a placeholder till we can indent the active line // This is a placeholder till we can indent the active line
any_change = true; any_change = true;
let [primary, _secondary] = ccursor_range.sorted(); let [primary, _secondary] = ccursor_range.sorted();
@ -160,7 +160,7 @@ fn shortcuts(ui: &Ui, code: &mut dyn TextBuffer, ccursor_range: &mut CCursorRang
(SHORTCUT_STRIKETHROUGH, "~"), (SHORTCUT_STRIKETHROUGH, "~"),
(SHORTCUT_UNDERLINE, "_"), (SHORTCUT_UNDERLINE, "_"),
] { ] {
if ui.input_mut().consume_shortcut(&shortcut) { if ui.input_mut(|i| i.consume_shortcut(&shortcut)) {
any_change = true; any_change = true;
toggle_surrounding(code, ccursor_range, surrounding); toggle_surrounding(code, ccursor_range, surrounding);
}; };

View File

@ -144,7 +144,7 @@ fn bullet_point(ui: &mut Ui, width: f32) -> Response {
fn numbered_point(ui: &mut Ui, width: f32, number: &str) -> Response { fn numbered_point(ui: &mut Ui, width: f32, number: &str) -> Response {
let font_id = TextStyle::Body.resolve(ui.style()); let font_id = TextStyle::Body.resolve(ui.style());
let row_height = ui.fonts().row_height(&font_id); let row_height = ui.fonts(|f| f.row_height(&font_id));
let (rect, response) = ui.allocate_exact_size(vec2(width, row_height), Sense::hover()); let (rect, response) = ui.allocate_exact_size(vec2(width, row_height), Sense::hover());
let text = format!("{}.", number); let text = format!("{}.", number);
let text_color = ui.visuals().strong_text_color(); let text_color = ui.visuals().strong_text_color();

View File

@ -102,6 +102,6 @@ fn test_egui_zero_window_size() {
/// Detect narrow screens. This is used to show a simpler UI on mobile devices, /// Detect narrow screens. This is used to show a simpler UI on mobile devices,
/// especially for the web demo at <https://egui.rs>. /// especially for the web demo at <https://egui.rs>.
pub fn is_mobile(ctx: &egui::Context) -> bool { pub fn is_mobile(ctx: &egui::Context) -> bool {
let screen_size = ctx.input().screen_rect().size(); let screen_size = ctx.screen_rect().size();
screen_size.x < 550.0 screen_size.x < 550.0
} }

View File

@ -8,7 +8,7 @@ pub fn code_view_ui(ui: &mut egui::Ui, mut code: &str) {
let mut layouter = |ui: &egui::Ui, string: &str, _wrap_width: f32| { let mut layouter = |ui: &egui::Ui, string: &str, _wrap_width: f32| {
let layout_job = highlight(ui.ctx(), &theme, string, language); let layout_job = highlight(ui.ctx(), &theme, string, language);
// layout_job.wrap.max_width = wrap_width; // no wrapping // layout_job.wrap.max_width = wrap_width; // no wrapping
ui.fonts().layout_job(layout_job) ui.fonts(|f| f.layout_job(layout_job))
}; };
ui.add( ui.add(
@ -31,9 +31,11 @@ pub fn highlight(ctx: &egui::Context, theme: &CodeTheme, code: &str, language: &
type HighlightCache = egui::util::cache::FrameCache<LayoutJob, Highlighter>; type HighlightCache = egui::util::cache::FrameCache<LayoutJob, Highlighter>;
let mut memory = ctx.memory(); ctx.memory_mut(|mem| {
let highlight_cache = memory.caches.cache::<HighlightCache>(); mem.caches
highlight_cache.get((theme, code, language)) .cache::<HighlightCache>()
.get((theme, code, language))
})
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
@ -146,21 +148,23 @@ impl CodeTheme {
pub fn from_memory(ctx: &egui::Context) -> Self { pub fn from_memory(ctx: &egui::Context) -> Self {
if ctx.style().visuals.dark_mode { if ctx.style().visuals.dark_mode {
ctx.data() ctx.data_mut(|d| {
.get_persisted(egui::Id::new("dark")) d.get_persisted(egui::Id::new("dark"))
.unwrap_or_else(CodeTheme::dark) .unwrap_or_else(CodeTheme::dark)
})
} else { } else {
ctx.data() ctx.data_mut(|d| {
.get_persisted(egui::Id::new("light")) d.get_persisted(egui::Id::new("light"))
.unwrap_or_else(CodeTheme::light) .unwrap_or_else(CodeTheme::light)
})
} }
} }
pub fn store_in_memory(self, ctx: &egui::Context) { pub fn store_in_memory(self, ctx: &egui::Context) {
if self.dark_mode { if self.dark_mode {
ctx.data().insert_persisted(egui::Id::new("dark"), self); ctx.data_mut(|d| d.insert_persisted(egui::Id::new("dark"), self));
} else { } else {
ctx.data().insert_persisted(egui::Id::new("light"), self); ctx.data_mut(|d| d.insert_persisted(egui::Id::new("light"), self));
} }
} }
} }
@ -230,9 +234,8 @@ impl CodeTheme {
pub fn ui(&mut self, ui: &mut egui::Ui) { pub fn ui(&mut self, ui: &mut egui::Ui) {
ui.horizontal_top(|ui| { ui.horizontal_top(|ui| {
let selected_id = egui::Id::null(); let selected_id = egui::Id::null();
let mut selected_tt: TokenType = *ui let mut selected_tt: TokenType =
.data() ui.data_mut(|d| *d.get_persisted_mut_or(selected_id, TokenType::Comment));
.get_persisted_mut_or(selected_id, TokenType::Comment);
ui.vertical(|ui| { ui.vertical(|ui| {
ui.set_width(150.0); ui.set_width(150.0);
@ -274,7 +277,7 @@ impl CodeTheme {
ui.add_space(16.0); ui.add_space(16.0);
ui.data().insert_persisted(selected_id, selected_tt); ui.data_mut(|d| d.insert_persisted(selected_id, selected_tt));
egui::Frame::group(ui.style()) egui::Frame::group(ui.style())
.inner_margin(egui::Vec2::splat(2.0)) .inner_margin(egui::Vec2::splat(2.0))

View File

@ -64,9 +64,7 @@ impl<'a> Widget for DatePickerButton<'a> {
fn ui(self, ui: &mut Ui) -> egui::Response { fn ui(self, ui: &mut Ui) -> egui::Response {
let id = ui.make_persistent_id(self.id_source); let id = ui.make_persistent_id(self.id_source);
let mut button_state = ui let mut button_state = ui
.memory() .memory_mut(|mem| mem.data.get_persisted::<DatePickerButtonState>(id))
.data
.get_persisted::<DatePickerButtonState>(id)
.unwrap_or_default(); .unwrap_or_default();
let mut text = RichText::new(format!("{} 📆", self.selection.format("%Y-%m-%d"))); let mut text = RichText::new(format!("{} 📆", self.selection.format("%Y-%m-%d")));
@ -81,7 +79,7 @@ impl<'a> Widget for DatePickerButton<'a> {
let mut button_response = ui.add(button); let mut button_response = ui.add(button);
if button_response.clicked() { if button_response.clicked() {
button_state.picker_visible = true; button_state.picker_visible = true;
ui.memory().data.insert_persisted(id, button_state.clone()); ui.memory_mut(|mem| mem.data.insert_persisted(id, button_state.clone()));
} }
if button_state.picker_visible { if button_state.picker_visible {
@ -131,10 +129,10 @@ impl<'a> Widget for DatePickerButton<'a> {
} }
if !button_response.clicked() if !button_response.clicked()
&& (ui.input().key_pressed(Key::Escape) || area_response.clicked_elsewhere()) && (ui.input(|i| i.key_pressed(Key::Escape)) || area_response.clicked_elsewhere())
{ {
button_state.picker_visible = false; button_state.picker_visible = false;
ui.memory().data.insert_persisted(id, button_state); ui.memory_mut(|mem| mem.data.insert_persisted(id, button_state));
} }
} }

View File

@ -41,16 +41,14 @@ impl<'a> DatePickerPopup<'a> {
let id = ui.make_persistent_id("date_picker"); let id = ui.make_persistent_id("date_picker");
let today = chrono::offset::Utc::now().date_naive(); let today = chrono::offset::Utc::now().date_naive();
let mut popup_state = ui let mut popup_state = ui
.memory() .memory_mut(|mem| mem.data.get_persisted::<DatePickerPopupState>(id))
.data
.get_persisted::<DatePickerPopupState>(id)
.unwrap_or_default(); .unwrap_or_default();
if !popup_state.setup { if !popup_state.setup {
popup_state.year = self.selection.year(); popup_state.year = self.selection.year();
popup_state.month = self.selection.month(); popup_state.month = self.selection.month();
popup_state.day = self.selection.day(); popup_state.day = self.selection.day();
popup_state.setup = true; popup_state.setup = true;
ui.memory().data.insert_persisted(id, popup_state.clone()); ui.memory_mut(|mem| mem.data.insert_persisted(id, popup_state.clone()));
} }
let weeks = month_data(popup_state.year, popup_state.month); let weeks = month_data(popup_state.year, popup_state.month);
@ -93,9 +91,10 @@ impl<'a> DatePickerPopup<'a> {
popup_state.day = popup_state popup_state.day = popup_state
.day .day
.min(popup_state.last_day_of_month()); .min(popup_state.last_day_of_month());
ui.memory() ui.memory_mut(|mem| {
.data mem.data
.insert_persisted(id, popup_state.clone()); .insert_persisted(id, popup_state.clone());
});
} }
} }
}); });
@ -116,9 +115,10 @@ impl<'a> DatePickerPopup<'a> {
popup_state.day = popup_state popup_state.day = popup_state
.day .day
.min(popup_state.last_day_of_month()); .min(popup_state.last_day_of_month());
ui.memory() ui.memory_mut(|mem| {
.data mem.data
.insert_persisted(id, popup_state.clone()); .insert_persisted(id, popup_state.clone());
});
} }
} }
}); });
@ -136,9 +136,10 @@ impl<'a> DatePickerPopup<'a> {
) )
.changed() .changed()
{ {
ui.memory() ui.memory_mut(|mem| {
.data mem.data
.insert_persisted(id, popup_state.clone()); .insert_persisted(id, popup_state.clone());
});
} }
} }
}); });
@ -160,7 +161,9 @@ impl<'a> DatePickerPopup<'a> {
popup_state.year -= 1; popup_state.year -= 1;
popup_state.day = popup_state.day =
popup_state.day.min(popup_state.last_day_of_month()); popup_state.day.min(popup_state.last_day_of_month());
ui.memory().data.insert_persisted(id, popup_state.clone()); ui.memory_mut(|mem| {
mem.data.insert_persisted(id, popup_state.clone());
});
} }
}); });
}); });
@ -178,7 +181,9 @@ impl<'a> DatePickerPopup<'a> {
} }
popup_state.day = popup_state.day =
popup_state.day.min(popup_state.last_day_of_month()); popup_state.day.min(popup_state.last_day_of_month());
ui.memory().data.insert_persisted(id, popup_state.clone()); ui.memory_mut(|mem| {
mem.data.insert_persisted(id, popup_state.clone());
});
} }
}); });
}); });
@ -194,7 +199,9 @@ impl<'a> DatePickerPopup<'a> {
} }
popup_state.day = popup_state.last_day_of_month(); popup_state.day = popup_state.last_day_of_month();
} }
ui.memory().data.insert_persisted(id, popup_state.clone()); ui.memory_mut(|mem| {
mem.data.insert_persisted(id, popup_state.clone());
});
} }
}); });
}); });
@ -210,7 +217,9 @@ impl<'a> DatePickerPopup<'a> {
popup_state.year += 1; popup_state.year += 1;
} }
} }
ui.memory().data.insert_persisted(id, popup_state.clone()); ui.memory_mut(|mem| {
mem.data.insert_persisted(id, popup_state.clone());
});
} }
}); });
}); });
@ -224,7 +233,9 @@ impl<'a> DatePickerPopup<'a> {
} }
popup_state.day = popup_state.day =
popup_state.day.min(popup_state.last_day_of_month()); popup_state.day.min(popup_state.last_day_of_month());
ui.memory().data.insert_persisted(id, popup_state.clone()); ui.memory_mut(|mem| {
mem.data.insert_persisted(id, popup_state.clone());
});
} }
}); });
}); });
@ -234,7 +245,9 @@ impl<'a> DatePickerPopup<'a> {
popup_state.year += 1; popup_state.year += 1;
popup_state.day = popup_state.day =
popup_state.day.min(popup_state.last_day_of_month()); popup_state.day.min(popup_state.last_day_of_month());
ui.memory().data.insert_persisted(id, popup_state.clone()); ui.memory_mut(|mem| {
mem.data.insert_persisted(id, popup_state.clone());
});
} }
}); });
}); });
@ -342,10 +355,12 @@ impl<'a> DatePickerPopup<'a> {
popup_state.year = day.year(); popup_state.year = day.year();
popup_state.month = day.month(); popup_state.month = day.month();
popup_state.day = day.day(); popup_state.day = day.day();
ui.memory().data.insert_persisted( ui.memory_mut(|mem| {
id, mem.data.insert_persisted(
popup_state.clone(), id,
); popup_state.clone(),
);
});
} }
}, },
); );
@ -387,12 +402,12 @@ impl<'a> DatePickerPopup<'a> {
if close { if close {
popup_state.setup = false; popup_state.setup = false;
ui.memory().data.insert_persisted(id, popup_state); ui.memory_mut(|mem| {
mem.data.insert_persisted(id, popup_state);
ui.memory() mem.data
.data .get_persisted_mut_or_default::<DatePickerButtonState>(self.button_id)
.get_persisted_mut_or_default::<DatePickerButtonState>(self.button_id) .picker_visible = false;
.picker_visible = false; });
} }
saved && close saved && close

View File

@ -479,7 +479,7 @@ impl TableState {
let rect = Rect::from_min_size(ui.available_rect_before_wrap().min, Vec2::ZERO); let rect = Rect::from_min_size(ui.available_rect_before_wrap().min, Vec2::ZERO);
ui.ctx().check_for_id_clash(state_id, rect, "Table"); ui.ctx().check_for_id_clash(state_id, rect, "Table");
if let Some(state) = ui.data().get_persisted::<Self>(state_id) { if let Some(state) = ui.data_mut(|d| d.get_persisted::<Self>(state_id)) {
// make sure that the stored widths aren't out-dated // make sure that the stored widths aren't out-dated
if state.column_widths.len() == default_widths.len() { if state.column_widths.len() == default_widths.len() {
return (true, state); return (true, state);
@ -495,7 +495,7 @@ impl TableState {
} }
fn store(self, ui: &egui::Ui, state_id: egui::Id) { fn store(self, ui: &egui::Ui, state_id: egui::Id) {
ui.data().insert_persisted(state_id, self); ui.data_mut(|d| d.insert_persisted(state_id, self));
} }
} }
@ -680,14 +680,12 @@ impl<'a> Table<'a> {
} }
} }
let dragging_something_else = { let dragging_something_else =
let pointer = &ui.input().pointer; ui.input(|i| i.pointer.any_down() || i.pointer.any_pressed());
pointer.any_down() || pointer.any_pressed()
};
let resize_hover = resize_response.hovered() && !dragging_something_else; let resize_hover = resize_response.hovered() && !dragging_something_else;
if resize_hover || resize_response.dragged() { if resize_hover || resize_response.dragged() {
ui.output().cursor_icon = egui::CursorIcon::ResizeColumn; ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeColumn);
} }
let stroke = if resize_response.dragged() { let stroke = if resize_response.dragged() {

View File

@ -65,9 +65,11 @@ impl eframe::App for MyApp {
preview_files_being_dropped(ctx); preview_files_being_dropped(ctx);
// Collect dropped files: // Collect dropped files:
if !ctx.input().raw.dropped_files.is_empty() { ctx.input(|i| {
self.dropped_files = ctx.input().raw.dropped_files.clone(); if !i.raw.dropped_files.is_empty() {
} self.dropped_files = i.raw.dropped_files.clone();
}
});
} }
} }
@ -76,22 +78,25 @@ fn preview_files_being_dropped(ctx: &egui::Context) {
use egui::*; use egui::*;
use std::fmt::Write as _; use std::fmt::Write as _;
if !ctx.input().raw.hovered_files.is_empty() { if !ctx.input(|i| i.raw.hovered_files.is_empty()) {
let mut text = "Dropping files:\n".to_owned(); let text = ctx.input(|i| {
for file in &ctx.input().raw.hovered_files { let mut text = "Dropping files:\n".to_owned();
if let Some(path) = &file.path { for file in &i.raw.hovered_files {
write!(text, "\n{}", path.display()).ok(); if let Some(path) = &file.path {
} else if !file.mime.is_empty() { write!(text, "\n{}", path.display()).ok();
write!(text, "\n{}", file.mime).ok(); } else if !file.mime.is_empty() {
} else { write!(text, "\n{}", file.mime).ok();
text += "\n???"; } else {
text += "\n???";
}
} }
} text
});
let painter = let painter =
ctx.layer_painter(LayerId::new(Order::Foreground, Id::new("file_drop_target"))); ctx.layer_painter(LayerId::new(Order::Foreground, Id::new("file_drop_target")));
let screen_rect = ctx.input().screen_rect(); let screen_rect = ctx.screen_rect();
painter.rect_filled(screen_rect, 0.0, Color32::from_black_alpha(192)); painter.rect_filled(screen_rect, 0.0, Color32::from_black_alpha(192));
painter.text( painter.text(
screen_rect.center(), screen_rect.center(),

View File

@ -0,0 +1,16 @@
[package]
name = "hello_world_par"
version = "0.1.0"
authors = ["Maxim Osipenko <maxim1999max@gmail.com>"]
license = "MIT OR Apache-2.0"
edition = "2021"
rust-version = "1.65"
publish = false
[dependencies]
eframe = { path = "../../crates/eframe", default-features = false, features = [
# accesskit struggles with threading
"default_fonts",
"wgpu",
] }

View File

@ -0,0 +1,5 @@
This example shows that you can use egui in parallel from multiple threads.
```sh
cargo run -p hello_world_par
```

View File

@ -0,0 +1,132 @@
//! This example shows that you can use egui in parallel from multiple threads.
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] // hide console window on Windows in release
use std::sync::mpsc;
use std::thread::JoinHandle;
use eframe::egui;
fn main() -> Result<(), eframe::Error> {
let options = eframe::NativeOptions {
initial_window_size: Some(egui::vec2(1024.0, 768.0)),
..Default::default()
};
eframe::run_native(
"My parallel egui App",
options,
Box::new(|_cc| Box::new(MyApp::new())),
)
}
/// State per thread.
struct ThreadState {
thread_nr: usize,
title: String,
name: String,
age: u32,
}
impl ThreadState {
fn new(thread_nr: usize) -> Self {
let title = format!("Background thread {thread_nr}");
Self {
thread_nr,
title,
name: "Arthur".into(),
age: 12 + thread_nr as u32 * 10,
}
}
fn show(&mut self, ctx: &egui::Context) {
let pos = egui::pos2(16.0, 128.0 * (self.thread_nr as f32 + 1.0));
egui::Window::new(&self.title)
.default_pos(pos)
.show(ctx, |ui| {
ui.horizontal(|ui| {
ui.label("Your name: ");
ui.text_edit_singleline(&mut self.name);
});
ui.add(egui::Slider::new(&mut self.age, 0..=120).text("age"));
if ui.button("Click each year").clicked() {
self.age += 1;
}
ui.label(format!("Hello '{}', age {}", self.name, self.age));
});
}
}
fn new_worker(
thread_nr: usize,
on_done_tx: mpsc::SyncSender<()>,
) -> (JoinHandle<()>, mpsc::SyncSender<egui::Context>) {
let (show_tx, show_rc) = mpsc::sync_channel(0);
let handle = std::thread::Builder::new()
.name(format!("EguiPanelWorker {}", thread_nr))
.spawn(move || {
let mut state = ThreadState::new(thread_nr);
while let Ok(ctx) = show_rc.recv() {
state.show(&ctx);
let _ = on_done_tx.send(());
}
})
.expect("failed to spawn thread");
(handle, show_tx)
}
struct MyApp {
threads: Vec<(JoinHandle<()>, mpsc::SyncSender<egui::Context>)>,
on_done_tx: mpsc::SyncSender<()>,
on_done_rc: mpsc::Receiver<()>,
}
impl MyApp {
fn new() -> Self {
let threads = Vec::with_capacity(3);
let (on_done_tx, on_done_rc) = mpsc::sync_channel(0);
let mut slf = Self {
threads,
on_done_tx,
on_done_rc,
};
slf.spawn_thread();
slf.spawn_thread();
slf
}
fn spawn_thread(&mut self) {
let thread_nr = self.threads.len();
self.threads
.push(new_worker(thread_nr, self.on_done_tx.clone()));
}
}
impl std::ops::Drop for MyApp {
fn drop(&mut self) {
for (handle, show_tx) in self.threads.drain(..) {
std::mem::drop(show_tx);
handle.join().unwrap();
}
}
}
impl eframe::App for MyApp {
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
egui::Window::new("Main thread").show(ctx, |ui| {
if ui.button("Spawn another thread").clicked() {
self.spawn_thread();
}
});
for (_handle, show_tx) in &self.threads {
let _ = show_tx.send(ctx.clone());
}
for _ in 0..self.threads.len() {
let _ = self.on_done_rc.recv();
}
}
}

View File

@ -33,14 +33,14 @@ impl eframe::App for Content {
ui.label(&self.text); ui.label(&self.text);
}); });
if ctx.input().key_pressed(Key::A) { if ctx.input(|i| i.key_pressed(Key::A)) {
self.text.push_str("\nPressed"); self.text.push_str("\nPressed");
} }
if ctx.input().key_down(Key::A) { if ctx.input(|i| i.key_down(Key::A)) {
self.text.push_str("\nHeld"); self.text.push_str("\nHeld");
ui.ctx().request_repaint(); // make sure we note the holding. ui.ctx().request_repaint(); // make sure we note the holding.
} }
if ctx.input().key_released(Key::A) { if ctx.input(|i| i.key_released(Key::A)) {
self.text.push_str("\nReleased"); self.text.push_str("\nReleased");
} }
}); });

View File

@ -28,7 +28,7 @@ impl eframe::App for MyApp {
ui.horizontal(|ui| { ui.horizontal(|ui| {
ui.monospace(cmd); ui.monospace(cmd);
if ui.small_button("📋").clicked() { if ui.small_button("📋").clicked() {
ui.output().copied_text = cmd.into(); ui.output_mut(|o| o.copied_text = cmd.into());
} }
}); });