8000 Rework interal Modal drawing to better use the the provided Area, allowing for draggable Modals. by mkalte666 · Pull Request #6749 · emilk/egui · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Rework interal Modal drawing to better use the the provided Area, allowing for draggable Modals. #6749

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 58 additions & 23 deletions crates/egui/src/containers/modal.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::{
Area, Color32, Context, Frame, Id, InnerResponse, Order, Response, Sense, Ui, UiBuilder, UiKind,
Area, Color32, Context, Frame, Id, InnerResponse, Order, Response, Sense, Ui, UiKind,
WidgetRect,
};
use emath::{Align2, Vec2};

Expand Down Expand Up @@ -33,18 +34,37 @@ impl Modal {
/// Returns an area customized for a modal.
///
/// Makes these changes to the default area:
/// - sense: hover
/// - sense: click + drag
/// - anchor: center
/// - order: foreground
///
/// Consider the notes at [`Modal::area`] for more information.
pub fn default_area(id: Id) -> Area {
Area::new(id)
.kind(UiKind::Modal)
.sense(Sense::hover())
.sense(Sense::click_and_drag())
.anchor(Align2::CENTER_CENTER, Vec2::ZERO)
.order(Order::Foreground)
.interactable(true)
}

/// Returns an area customized to make a modal draggable.
///
/// Makes these changes to the default area:
/// - sense: click + drag
/// - pivot: center
/// - order: foreground
///
/// Consider the notes at [`Modal::area`] for more information.
pub fn draggable_area(id: Id) -> Area {
Area::new(id)
.kind(UiKind::Modal)
.sense(Sense::click_and_drag())
.pivot(Align2::CENTER_CENTER)
.order(Order::Foreground)
.interactable(true)
}

/// Set the frame of the modal.
///
/// Default is [`Frame::popup`].
Expand All @@ -66,6 +86,14 @@ impl Modal {
/// Set the area of the modal.
///
/// Default is [`Modal::default_area`].
///
/// If the modal should be draggable, consider using [`Modal::draggable_area`] instead.
///
/// If you want to provide a custom area, make sure it senses [`Sense::CLICK`] and [`Sense::DRAG`].
/// Otherwise the background backdrop might catch events meant for the content of the modal.
///
/// Also, if the Area satisfies [`Area::is_movable`], the Modal will ignore the stored position and re-center it on modal re-open.
/// This is affected by [`Area::pivot`], which [`Modal::draggable_area`] sets to [`Align2::CENTER_CENTER`].
#[inline]
pub fn area(mut self, area: Area) -> Self {
self.area = area;
Expand All @@ -75,7 +103,7 @@ impl Modal {
/// Show the modal.
pub fn show<T>(self, ctx: &Context, content: impl FnOnce(&mut Ui) -> T) -> ModalResponse<T> {
let Self {
area,
mut area,
backdrop_color,
frame,
} = self;
Expand All @@ -87,28 +115,35 @@ impl Modal {
mem.any_popup_open(),
)
});
let InnerResponse {
inner: (inner, backdrop_response),
response,
} = area.show(ctx, |ui| {
let bg_rect = ui.ctx().screen_rect();
let bg_sense = Sense::CLICK | Sense::DRAG;
let mut backdrop = ui.new_child(UiBuilder::new().sense(bg_sense).max_rect(bg_rect));
backdrop.set_min_size(bg_rect.size());
ui.painter().rect_filled(bg_rect, 0.0, backdrop_color);
let backdrop_response = backdrop.response();

let frame = frame.unwrap_or_else(|| Frame::popup(ui.style()));
// The backdrop response is responsible for checking for click through etc.
// It needs to be drawn before everything else, so we can use it to block clicks.
// Thus, we manually add the widget.
let bg_rect = ctx.screen_rect();
let bg_sense = Sense::CLICK | Sense::DRAG;
let backdrop_response = ctx.create_widget(
WidgetRect {
id: area.id.with("background rect"),
layer_id: area.layer(),
rect: bg_rect,
interact_rect: bg_rect,
sense: bg_sense,
enabled: true,
},
true,
);

// Should the area be movable, and we are (re-)opening it, try to center it.
if area.is_movable() && !ctx.memory(|mem| mem.areas().visible_last_frame(&area.layer())) {
area = area.current_pos(ctx.screen_rect().center());
}
Comment on lines +136 to +139
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this 8000 would fail if someone creates a movable modal with a default pos that isn't center. Can we read the position from the Area struct? Or maybe move this to Area with a configurable bool like reset_position_on_open?

Copy link
Contributor Author
@mkalte666 mkalte666 Apr 15, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We cannot, as far as i can see. We can get last frames position from the memory state IIRC, but that is only marginally helpful.

Some things come to mind in area:
Area currently positions itself like this, if i understand this correctly:

  • If there is an anchor, fix the area on the anchor. Sets movable to false. Setting moveable to true manually, you get an area that always snaps back to the anchor every time you touch it
  • If there is no anchor, but a fixed_pos, use the fixed_pos and it gets the same snappy movement if you force movable to true
  • If there is neither, and current_pos was set, set position to that, otherwise either use the last frames position, or if that is not available, default_pos.

AFAICS this is not documented well, though using Area directly also is kind of non-standard, so shrug.

I'd like to suggest doing the following: Change the way area positions to an AreaPositioning enum. Something Like

pub enum AreaPosition {
   Anchored {anchor: Align2, offset: Vec2},
   Fixed {pos: Pos2},
   Movable { 
       override_pos: Option<Pos2>,
       initial_position: InitialAreaPosition,
       reset_on_open: bool,
   }
}

pub enum InitialAreaPosition {
    Automatic,
    Center,
    DefaultPos(Pos2), // Or OpenAt or just Position... naming is hard. 
}

This would make the builder pattern for Area a bit less nice to use, but it would more or less represent the internal state as it is right now. And you cannot set conflicting properties.

What do you think? I might be able to throw a commit together with this later today.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm I think it would be nice to change the Area to hold an enum like this, but we should also definitely keep the current builder methods.


// We need the extra scope with the sense since frame can't have a sense and since we
// need to prevent the clicks from passing through to the backdrop.
let inner = ui
.scope_builder(UiBuilder::new().sense(Sense::CLICK | Sense::DRAG), |ui| {
frame.show(ui, content).inner
})
.inner;
let InnerResponse { inner, response } = area.show(ctx, |ui| {
// The backdrop still needs painting.
ui.painter().rect_filled(bg_rect, 0.0, backdrop_color);

(inner, backdrop_response)
let frame = frame.unwrap_or_else(|| Frame::popup(ui.style()));
frame.show(ui, content).inner
});

ModalResponse {
Expand Down
90 changes: 89 additions & 1 deletion crates/egui_demo_lib/src/demo/modals.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ pub struct Modals {
user_modal_open: bool,
save_modal_open: bool,
save_progress: Option<f32>,
drag_modal_open: bool,

role: &'static str,
name: String,
Expand All @@ -16,6 +17,7 @@ impl Default for Modals {
Self {
user_modal_open: false,
save_modal_open: false,
drag_modal_open: false,
save_progress: None,
role: Self::ROLES[0],
name: "John Doe".to_owned(),
Expand Down Expand Up @@ -48,6 +50,7 @@ impl crate::View for Modals {
user_modal_open,
save_modal_open,
save_progress,
drag_modal_open,
role,
name,
} = self;
Expand All @@ -60,6 +63,10 @@ impl crate::View for Modals {
if ui.button("Open Save Modal").clicked() {
*save_modal_open = true;
}

if ui.button("Draggable Modal").clicked() {
*drag_modal_open = true;
}
});

ui.label("Click one of the buttons to open a modal.");
Expand Down Expand Up @@ -154,6 +161,34 @@ impl crate::View for Modals {
});
}

if *drag_modal_open {
let id = Id::new("Modal D");

// It is tempting to do this:
// let area = Modal::default_area(id).movable(true);
// However the default area sets anchors, and thus movable will not work.
// Instead, use Modal::draggable_area instead.
let modal = Modal::new(id)
.area(Modal::draggable_area(id))
.show(ui.ctx(), |ui| {
egui::Resize::default()
.with_stroke(false)
.min_size([125.0, 225.0])
.max_size(ui.ctx().screen_rect().size())
.show(ui, |ui| {
ui.vertical_centered(|ui| {
ui.add_space(25.0);
ui.heading("You should be able to drag me around!");
ui.add_space(125.0);
});
});
});

if modal.should_close() {
*drag_modal_open = false;
}
}

ui.vertical_centered(|ui| {
ui.add(crate::egui_github_link_file!());
});
Expand All @@ -165,7 +200,7 @@ mod tests {
use crate::demo::modals::Modals;
use crate::Demo;
use egui::accesskit::Role;
use egui::Key;
use egui::{Event, Key, PointerButton, Vec2};
use egui_kittest::kittest::Queryable;
use egui_kittest::{Harness, SnapshotResults};

Expand Down Expand Up @@ -249,6 +284,59 @@ mod tests {
results.add(harness.try_snapshot("modals_3"));
}

#[test]
fn draggable_should_drag_and_close() {
let initial_state = Modals {
drag_modal_open: true,
..Modals::default()
};

let mut harness = Harness::new_state(
|ctx, modals| {
modals.show(ctx, &mut true);
},
initial_state,
);

let mut results = SnapshotResults::new();

harness.run();
results.add(harness.try_snapshot("modals_drag_1"));

let center = harness.ctx.screen_rect().center();
let delta = Vec2::new(150.0, 25.0);
let pos_after = center + delta;

harness.input_mut().events.push(Event::PointerButton {
pos: center,
button: PointerButton::Primary,
pressed: true,
modifiers: Default::default(),
});
harness.step();

harness
.input_mut()
.events
.push(Event::PointerMoved(pos_after));
harness.step();

harness.input_mut().events.push(Event::PointerButton {
pos: pos_after,
button: PointerButton::Primary,
pressed: false,
modifiers: Default::default(),
});
harness.step();

results.add(harness.try_snapshot("modals_drag_2"));

harness.press_key(Key::Escape);
harness.run();

results.add(harness.try_snapshot("modals_drag_3"));
}

// This tests whether the backdrop actually prevents interaction with lower layers.
#[test]
fn backdrop_should_prevent_focusing_lower_area() {
Expand Down
4 changes: 2 additions & 2 deletions crates/egui_demo_lib/tests/snapshots/demos/Modals.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 2 additions & 2 deletions crates/egui_demo_lib/tests/snapshots/modals_1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 2 additions & 2 deletions crates/egui_demo_lib/tests/snapshots/modals_2.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 2 additions & 2 deletions crates/egui_demo_lib/tests/snapshots/modals_3.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
3 changes: 3 additions & 0 deletions crates/egui_demo_lib/tests/snapshots/modals_drag_1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
3 changes: 3 additions & 0 deletions crates/egui_demo_lib/tests/snapshots/modals_drag_2.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
3 changes: 3 additions & 0 deletions crates/egui_demo_lib/tests/snapshots/modals_drag_3.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
0