Move all crates into a crates directory (#1940)

This commit is contained in:
Emil Ernerfeldt
2022-08-20 10:41:49 +02:00
committed by GitHub
parent 5c63648c02
commit 041f2e64ba
260 changed files with 59 additions and 57 deletions
+71
View File
@@ -0,0 +1,71 @@
[package]
name = "egui"
version = "0.18.1"
authors = ["Emil Ernerfeldt <emil.ernerfeldt@gmail.com>"]
description = "An easy-to-use immediate mode GUI that runs on both web and native"
edition = "2021"
rust-version = "1.61"
homepage = "https://github.com/emilk/egui"
license = "MIT OR Apache-2.0"
readme = "../README.md"
repository = "https://github.com/emilk/egui"
categories = ["gui", "game-development"]
keywords = ["gui", "imgui", "immediate", "portable", "gamedev"]
include = ["../LICENSE-APACHE", "../LICENSE-MIT", "**/*.rs", "Cargo.toml"]
[package.metadata.docs.rs]
all-features = true
[lib]
[features]
default = ["default_fonts"]
## [`bytemuck`](https://docs.rs/bytemuck) enables you to cast [`epaint::Vertex`], [`emath::Vec2`] etc to `&[u8]`.
bytemuck = ["epaint/bytemuck"]
## [`cint`](https://docs.rs/cint) enables interopability with other color libraries.
cint = ["epaint/cint"]
## Enable the [`hex_color`] macro.
color-hex = ["epaint/color-hex"]
## This will automatically detect deadlocks due to double-locking on the same thread.
## If your app freezes, you may want to enable this!
## Only affects [`epaint::mutex::RwLock`] (which egui uses a lot).
deadlock_detection = ["epaint/deadlock_detection"]
## If set, egui will use `include_bytes!` to bundle some fonts.
## If you plan on specifying your own fonts you may disable this feature.
default_fonts = ["epaint/default_fonts"]
## Enable additional checks if debug assertions are enabled (debug builds).
extra_debug_asserts = ["epaint/extra_debug_asserts"]
## Always enable additional checks.
extra_asserts = ["epaint/extra_asserts"]
## [`mint`](https://docs.rs/mint) enables interopability with other math libraries such as [`glam`](https://docs.rs/glam) and [`nalgebra`](https://docs.rs/nalgebra).
mint = ["epaint/mint"]
## Enable persistence of memory (window positions etc).
persistence = ["serde", "epaint/serde", "ron"]
## Allow serialization using [`serde`](https://docs.rs/serde).
serde = ["dep:serde", "epaint/serde"]
[dependencies]
epaint = { version = "0.18.1", path = "../epaint", default-features = false }
ahash = "0.8"
nohash-hasher = "0.2"
#! ### Optional dependencies
## Enable this when generating docs.
document-features = { version = "0.2", optional = true }
ron = { version = "0.8", optional = true }
serde = { version = "1", optional = true, features = ["derive", "rc"] }
# egui doesn't log much, but when it does, it uses [`tracing`](https://docs.rs/tracing).
tracing = { version = "0.1", optional = true, default-features = false, features = ["std"] }
+2
View File
@@ -0,0 +1,2 @@
# GUI implementation
This is the core library crate egui. It is fully platform independent without any backend. You give the egui library input each frame (mouse pos etc), and it outputs a triangle mesh for you to paint.
+7
View File
@@ -0,0 +1,7 @@
There are no stand-alone egui examples, because egui is not stand-alone!
See the top-level [examples](https://github.com/emilk/egui/tree/master/examples/) folder instead.
There are also plenty of examples in [the online demo](https://www.egui.rs/#demo). You can find the source code for it at <https://github.com/emilk/egui/tree/master/egui_demo_lib>.
To learn how to set up `eframe` for web and native, go to <https://github.com/emilk/eframe_template/> and follow the instructions there!
+111
View File
@@ -0,0 +1,111 @@
use crate::{emath::remap_clamp, Id, IdMap, InputState};
#[derive(Clone, Default)]
pub(crate) struct AnimationManager {
bools: IdMap<BoolAnim>,
values: IdMap<ValueAnim>,
}
#[derive(Clone, Debug)]
struct BoolAnim {
value: bool,
/// when did `value` last toggle?
toggle_time: f64,
}
#[derive(Clone, Debug)]
struct ValueAnim {
from_value: f32,
to_value: f32,
/// when did `value` last toggle?
toggle_time: f64,
}
impl AnimationManager {
/// See `Context::animate_bool` for documentation
pub fn animate_bool(
&mut self,
input: &InputState,
animation_time: f32,
id: Id,
value: bool,
) -> f32 {
match self.bools.get_mut(&id) {
None => {
self.bools.insert(
id,
BoolAnim {
value,
toggle_time: -f64::INFINITY, // long time ago
},
);
if value {
1.0
} else {
0.0
}
}
Some(anim) => {
if anim.value != value {
anim.value = value;
anim.toggle_time = input.time;
}
let time_since_toggle = (input.time - anim.toggle_time) as f32;
// On the frame we toggle we don't want to return the old value,
// so we extrapolate forwards:
let time_since_toggle = time_since_toggle + input.predicted_dt;
if value {
remap_clamp(time_since_toggle, 0.0..=animation_time, 0.0..=1.0)
} else {
remap_clamp(time_since_toggle, 0.0..=animation_time, 1.0..=0.0)
}
}
}
}
pub fn animate_value(
&mut self,
input: &InputState,
animation_time: f32,
id: Id,
value: f32,
) -> f32 {
match self.values.get_mut(&id) {
None => {
self.values.insert(
id,
ValueAnim {
from_value: value,
to_value: value,
toggle_time: -f64::INFINITY, // long time ago
},
);
value
}
Some(anim) => {
let time_since_toggle = (input.time - anim.toggle_time) as f32;
// On the frame we toggle we don't want to return the old value,
// so we extrapolate forwards:
let time_since_toggle = time_since_toggle + input.predicted_dt;
let current_value = remap_clamp(
time_since_toggle,
0.0..=animation_time,
anim.from_value..=anim.to_value,
);
if anim.to_value != value {
anim.from_value = current_value; //start new animation from current position of playing animation
anim.to_value = value;
anim.toggle_time = input.time;
}
if animation_time == 0.0 {
anim.from_value = value;
anim.to_value = value;
}
current_value
}
}
}
}
+459
View File
@@ -0,0 +1,459 @@
//! Area is a [`Ui`] that has no parent, it floats on the background.
//! It has no frame or own size. It is potentially movable.
//! It is the foundation for windows and popups.
use std::{fmt::Debug, hash::Hash};
use crate::*;
/// State that is persisted between frames.
// TODO(emilk): this is not currently stored in `memory().data`, but maybe it should be?
#[derive(Clone, Copy, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub(crate) struct State {
/// Last known pos
pub pos: Pos2,
/// Last know size. Used for catching clicks.
pub size: Vec2,
/// If false, clicks goes straight through to what is behind us.
/// Good for tooltips etc.
pub interactable: bool,
}
impl State {
pub fn rect(&self) -> Rect {
Rect::from_min_size(self.pos, self.size)
}
}
/// An area on the screen that can be moved by dragging.
///
/// This forms the base of the [`Window`] container.
///
/// ```
/// # egui::__run_test_ctx(|ctx| {
/// egui::Area::new("my_area")
/// .fixed_pos(egui::pos2(32.0, 32.0))
/// .show(ctx, |ui| {
/// ui.label("Floating text!");
/// });
/// # });
/// ```
#[must_use = "You should call .show()"]
#[derive(Clone, Copy, Debug)]
pub struct Area {
pub(crate) id: Id,
movable: bool,
interactable: bool,
enabled: bool,
order: Order,
default_pos: Option<Pos2>,
anchor: Option<(Align2, Vec2)>,
new_pos: Option<Pos2>,
drag_bounds: Option<Rect>,
}
impl Area {
pub fn new(id_source: impl Hash) -> Self {
Self {
id: Id::new(id_source),
movable: true,
interactable: true,
enabled: true,
order: Order::Middle,
default_pos: None,
new_pos: None,
anchor: None,
drag_bounds: None,
}
}
pub fn id(mut self, id: Id) -> Self {
self.id = id;
self
}
pub fn layer(&self) -> LayerId {
LayerId::new(self.order, self.id)
}
/// If false, no content responds to click
/// and widgets will be shown grayed out.
/// You won't be able to move the window.
/// Default: `true`.
pub fn enabled(mut self, enabled: bool) -> Self {
self.enabled = enabled;
self
}
/// moveable by dragging the area?
pub fn movable(mut self, movable: bool) -> Self {
self.movable = movable;
self.interactable |= movable;
self
}
pub fn is_enabled(&self) -> bool {
self.enabled
}
pub fn is_movable(&self) -> bool {
self.movable && self.enabled
}
/// If false, clicks goes straight through to what is behind us.
/// Good for tooltips etc.
pub fn interactable(mut self, interactable: bool) -> Self {
self.interactable = interactable;
self.movable &= interactable;
self
}
/// `order(Order::Foreground)` for an Area that should always be on top
pub fn order(mut self, order: Order) -> Self {
self.order = order;
self
}
pub fn default_pos(mut self, default_pos: impl Into<Pos2>) -> Self {
self.default_pos = Some(default_pos.into());
self
}
/// Positions the window and prevents it from being moved
pub fn fixed_pos(mut self, fixed_pos: impl Into<Pos2>) -> Self {
self.new_pos = Some(fixed_pos.into());
self.movable = false;
self
}
/// Positions the window but you can still move it.
pub fn current_pos(mut self, current_pos: impl Into<Pos2>) -> Self {
self.new_pos = Some(current_pos.into());
self
}
/// Set anchor and distance.
///
/// An anchor of `Align2::RIGHT_TOP` means "put the right-top corner of the window
/// in the right-top corner of the screen".
///
/// The offset is added to the position, so e.g. an offset of `[-5.0, 5.0]`
/// would move the window left and down from the given anchor.
///
/// Anchoring also makes the window immovable.
///
/// It is an error to set both an anchor and a position.
pub fn anchor(mut self, align: Align2, offset: impl Into<Vec2>) -> Self {
self.anchor = Some((align, offset.into()));
self.movable(false)
}
/// Constrain the area up to which the window can be dragged.
pub fn drag_bounds(mut self, bounds: Rect) -> Self {
self.drag_bounds = Some(bounds);
self
}
pub(crate) fn get_pivot(&self) -> Align2 {
if let Some((pivot, _)) = self.anchor {
pivot
} else {
Align2::LEFT_TOP
}
}
}
pub(crate) struct Prepared {
layer_id: LayerId,
state: State,
pub(crate) movable: bool,
enabled: bool,
drag_bounds: Option<Rect>,
/// Set the first frame of new windows with anchors.
///
/// This is so that we use the first frame to calculate the window size,
/// and then can correctly position the window the next frame,
/// without having one frame where the window is positioned in the wrong place.
temporarily_invisible: bool,
}
impl Area {
pub fn show<R>(
self,
ctx: &Context,
add_contents: impl FnOnce(&mut Ui) -> R,
) -> InnerResponse<R> {
let prepared = self.begin(ctx);
let mut content_ui = prepared.content_ui(ctx);
let inner = add_contents(&mut content_ui);
let response = prepared.end(ctx, content_ui);
InnerResponse { inner, response }
}
pub(crate) fn begin(self, ctx: &Context) -> Prepared {
let Area {
id,
movable,
order,
interactable,
enabled,
default_pos,
new_pos,
anchor,
drag_bounds,
} = self;
let layer_id = LayerId::new(order, id);
let state = ctx.memory().areas.get(id).cloned();
let is_new = state.is_none();
if is_new {
ctx.request_repaint(); // if we don't know the previous size we are likely drawing the area in the wrong place
}
let mut state = state.unwrap_or_else(|| State {
pos: default_pos.unwrap_or_else(|| automatic_area_position(ctx)),
size: Vec2::ZERO,
interactable,
});
state.pos = new_pos.unwrap_or(state.pos);
state.interactable = interactable;
let mut temporarily_invisible = false;
if let Some((anchor, offset)) = anchor {
if is_new {
temporarily_invisible = true;
} else {
let screen = ctx.available_rect();
state.pos = anchor.align_size_within_rect(state.size, screen).min + offset;
}
}
state.pos = ctx.round_pos_to_pixels(state.pos);
Prepared {
layer_id,
state,
movable,
enabled,
drag_bounds,
temporarily_invisible,
}
}
pub fn show_open_close_animation(&self, ctx: &Context, frame: &Frame, is_open: bool) {
// must be called first so animation managers know the latest state
let visibility_factor = ctx.animate_bool(self.id.with("close_animation"), is_open);
if is_open {
// we actually only show close animations.
// when opening a window we show it right away.
return;
}
if visibility_factor <= 0.0 {
return;
}
let layer_id = LayerId::new(self.order, self.id);
let area_rect = ctx.memory().areas.get(self.id).map(|area| area.rect());
if let Some(area_rect) = area_rect {
let clip_rect = ctx.available_rect();
let painter = Painter::new(ctx.clone(), layer_id, clip_rect);
// shrinkage: looks kinda a bad on its own
// let area_rect =
// Rect::from_center_size(area_rect.center(), visibility_factor * area_rect.size());
let frame = frame.multiply_with_opacity(visibility_factor);
painter.add(frame.paint(area_rect));
}
}
}
impl Prepared {
pub(crate) fn state(&self) -> &State {
&self.state
}
pub(crate) fn state_mut(&mut self) -> &mut State {
&mut self.state
}
pub(crate) fn drag_bounds(&self) -> Option<Rect> {
self.drag_bounds
}
pub(crate) fn content_ui(&self, ctx: &Context) -> Ui {
let screen_rect = ctx.input().screen_rect();
let bounds = if let Some(bounds) = self.drag_bounds {
bounds.intersect(screen_rect) // protect against infinite bounds
} else {
let central_area = ctx.available_rect();
let is_within_central_area = central_area.contains_rect(self.state.rect().shrink(1.0));
if is_within_central_area {
central_area // let's try to not cover side panels
} else {
screen_rect
}
};
let max_rect = Rect::from_min_max(
self.state.pos,
bounds.max.at_least(self.state.pos + Vec2::splat(32.0)),
);
let shadow_radius = ctx.style().visuals.window_shadow.extrusion; // hacky
let clip_rect_margin = ctx.style().visuals.clip_rect_margin.max(shadow_radius);
let clip_rect = Rect::from_min_max(self.state.pos, bounds.max)
.expand(clip_rect_margin)
.intersect(bounds);
let mut ui = Ui::new(
ctx.clone(),
self.layer_id,
self.layer_id.id,
max_rect,
clip_rect,
);
ui.set_enabled(self.enabled);
ui.set_visible(!self.temporarily_invisible);
ui
}
#[allow(clippy::needless_pass_by_value)] // intentional to swallow up `content_ui`.
pub(crate) fn end(self, ctx: &Context, content_ui: Ui) -> Response {
let Prepared {
layer_id,
mut state,
movable,
enabled,
drag_bounds,
temporarily_invisible: _,
} = self;
state.size = content_ui.min_rect().size();
let interact_id = layer_id.id.with("move");
let sense = if movable {
Sense::click_and_drag()
} else {
Sense::click() // allow clicks to bring to front
};
let move_response = ctx.interact(
Rect::EVERYTHING,
ctx.style().spacing.item_spacing,
layer_id,
interact_id,
state.rect(),
sense,
enabled,
);
if move_response.dragged() && movable {
state.pos += ctx.input().pointer.delta();
}
// Important check - don't try to move e.g. a combobox popup!
if movable {
state.pos = ctx
.constrain_window_rect_to_area(state.rect(), drag_bounds)
.min;
}
if (move_response.dragged() || move_response.clicked())
|| pointer_pressed_on_area(ctx, layer_id)
|| !ctx.memory().areas.visible_last_frame(&layer_id)
{
ctx.memory().areas.move_to_top(layer_id);
ctx.request_repaint();
}
ctx.memory().areas.set_state(layer_id, state);
move_response
}
}
fn pointer_pressed_on_area(ctx: &Context, layer_id: LayerId) -> bool {
if let Some(pointer_pos) = ctx.pointer_interact_pos() {
let any_pressed = ctx.input().pointer.any_pressed();
any_pressed && ctx.layer_id_at(pointer_pos) == Some(layer_id)
} else {
false
}
}
fn automatic_area_position(ctx: &Context) -> Pos2 {
let mut existing: Vec<Rect> = ctx
.memory()
.areas
.visible_windows()
.into_iter()
.map(State::rect)
.collect();
existing.sort_by_key(|r| r.left().round() as i32);
let available_rect = ctx.available_rect();
let spacing = 16.0;
let left = available_rect.left() + spacing;
let top = available_rect.top() + spacing;
if existing.is_empty() {
return pos2(left, top);
}
// Separate existing rectangles into columns:
let mut column_bbs = vec![existing[0]];
for &rect in &existing {
let current_column_bb = column_bbs.last_mut().unwrap();
if rect.left() < current_column_bb.right() {
// same column
*current_column_bb = current_column_bb.union(rect);
} else {
// new column
column_bbs.push(rect);
}
}
{
// Look for large spaces between columns (empty columns):
let mut x = left;
for col_bb in &column_bbs {
let available = col_bb.left() - x;
if available >= 300.0 {
return pos2(x, top);
}
x = col_bb.right() + spacing;
}
}
// Find first column with some available space at the bottom of it:
for col_bb in &column_bbs {
if col_bb.bottom() < available_rect.center().y {
return pos2(col_bb.left(), col_bb.bottom() + spacing);
}
}
// Maybe we can fit a new column?
let rightmost = column_bbs.last().unwrap().right();
if rightmost + 200.0 < available_rect.right() {
return pos2(rightmost + spacing, top);
}
// Ok, just put us in the column with the most space at the bottom:
let mut best_pos = pos2(left, column_bbs[0].bottom() + spacing);
for col_bb in &column_bbs {
let col_pos = pos2(col_bb.left(), col_bb.bottom() + spacing);
if col_pos.y < best_pos.y {
best_pos = col_pos;
}
}
best_pos
}
@@ -0,0 +1,668 @@
use std::hash::Hash;
use crate::*;
use epaint::Shape;
#[derive(Clone, Copy, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub(crate) struct InnerState {
open: bool,
/// Height of the region when open. Used for animations
#[cfg_attr(feature = "serde", serde(default))]
open_height: Option<f32>,
}
/// This is a a building block for building collapsing regions.
///
/// It is used by [`CollapsingHeader`] and [`Window`], but can also be used on its own.
///
/// See [`CollapsingState::show_header`] for how to show a collapsing header with a custom header.
#[derive(Clone, Debug)]
pub struct CollapsingState {
id: Id,
state: InnerState,
}
impl CollapsingState {
pub fn load(ctx: &Context, id: Id) -> Option<Self> {
ctx.data()
.get_persisted::<InnerState>(id)
.map(|state| Self { id, state })
}
pub fn store(&self, ctx: &Context) {
ctx.data().insert_persisted(self.id, self.state);
}
pub fn id(&self) -> Id {
self.id
}
pub fn load_with_default_open(ctx: &Context, id: Id, default_open: bool) -> Self {
Self::load(ctx, id).unwrap_or(CollapsingState {
id,
state: InnerState {
open: default_open,
open_height: None,
},
})
}
pub fn is_open(&self) -> bool {
self.state.open
}
pub fn set_open(&mut self, open: bool) {
self.state.open = open;
}
pub fn toggle(&mut self, ui: &Ui) {
self.state.open = !self.state.open;
ui.ctx().request_repaint();
}
/// 0 for closed, 1 for open, with tweening
pub fn openness(&self, ctx: &Context) -> f32 {
if ctx.memory().everything_is_visible() {
1.0
} else {
ctx.animate_bool(self.id, self.state.open)
}
}
/// Will toggle when clicked, etc.
pub(crate) fn show_default_button_with_size(
&mut self,
ui: &mut Ui,
button_size: Vec2,
) -> Response {
let (_id, rect) = ui.allocate_space(button_size);
let response = ui.interact(rect, self.id, Sense::click());
if response.clicked() {
self.toggle(ui);
}
let openness = self.openness(ui.ctx());
paint_default_icon(ui, openness, &response);
response
}
/// Will toggle when clicked, etc.
fn show_default_button_indented(&mut self, ui: &mut Ui) -> Response {
self.show_button_indented(ui, paint_default_icon)
}
/// Will toggle when clicked, etc.
fn show_button_indented(
&mut self,
ui: &mut Ui,
icon_fn: impl FnOnce(&mut Ui, f32, &Response) + 'static,
) -> Response {
let size = vec2(ui.spacing().indent, ui.spacing().icon_width);
let (_id, rect) = ui.allocate_space(size);
let response = ui.interact(rect, self.id, Sense::click());
if response.clicked() {
self.toggle(ui);
}
let (mut icon_rect, _) = ui.spacing().icon_rectangles(response.rect);
icon_rect.set_center(pos2(
response.rect.left() + ui.spacing().indent / 2.0,
response.rect.center().y,
));
let openness = self.openness(ui.ctx());
let small_icon_response = Response {
rect: icon_rect,
..response.clone()
};
icon_fn(ui, openness, &small_icon_response);
response
}
/// Shows header and body (if expanded).
///
/// The header will start with the default button in a horizontal layout, followed by whatever you add.
///
/// Will also store the state.
///
/// Returns the response of the collapsing button, the custom header, and the custom body.
///
/// ```
/// # egui::__run_test_ui(|ui| {
/// let id = ui.make_persistent_id("my_collapsing_header");
/// egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, false)
/// .show_header(ui, |ui| {
/// ui.label("Header"); // you can put checkboxes or whatever here
/// })
/// .body(|ui| ui.label("Body"));
/// # });
/// ```
pub fn show_header<HeaderRet>(
mut self,
ui: &mut Ui,
add_header: impl FnOnce(&mut Ui) -> HeaderRet,
) -> HeaderResponse<'_, HeaderRet> {
let header_response = ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 0.0; // the toggler button uses the full indent width
let collapser = self.show_default_button_indented(ui);
ui.spacing_mut().item_spacing.x = ui.spacing_mut().icon_spacing; // Restore spacing
(collapser, add_header(ui))
});
HeaderResponse {
state: self,
ui,
toggle_button_response: header_response.inner.0,
header_response: InnerResponse {
response: header_response.response,
inner: header_response.inner.1,
},
}
}
/// Show body if we are open, with a nice animation between closed and open.
/// Indent the body to show it belongs to the header.
///
/// Will also store the state.
pub fn show_body_indented<R>(
&mut self,
header_response: &Response,
ui: &mut Ui,
add_body: impl FnOnce(&mut Ui) -> R,
) -> Option<InnerResponse<R>> {
let id = self.id;
self.show_body_unindented(ui, |ui| {
ui.indent(id, |ui| {
// make as wide as the header:
ui.expand_to_include_x(header_response.rect.right());
add_body(ui)
})
.inner
})
}
/// Show body if we are open, with a nice animation between closed and open.
/// Will also store the state.
pub fn show_body_unindented<R>(
&mut self,
ui: &mut Ui,
add_body: impl FnOnce(&mut Ui) -> R,
) -> Option<InnerResponse<R>> {
let openness = self.openness(ui.ctx());
if openness <= 0.0 {
self.store(ui.ctx()); // we store any earlier toggling as promised in the docstring
None
} else if openness < 1.0 {
Some(ui.scope(|child_ui| {
let max_height = if self.state.open && self.state.open_height.is_none() {
// First frame of expansion.
// We don't know full height yet, but we will next frame.
// Just use a placeholder value that shows some movement:
10.0
} else {
let full_height = self.state.open_height.unwrap_or_default();
remap_clamp(openness, 0.0..=1.0, 0.0..=full_height)
};
let mut clip_rect = child_ui.clip_rect();
clip_rect.max.y = clip_rect.max.y.min(child_ui.max_rect().top() + max_height);
child_ui.set_clip_rect(clip_rect);
let ret = add_body(child_ui);
let mut min_rect = child_ui.min_rect();
self.state.open_height = Some(min_rect.height());
self.store(child_ui.ctx()); // remember the height
// Pretend children took up at most `max_height` space:
min_rect.max.y = min_rect.max.y.at_most(min_rect.top() + max_height);
child_ui.force_set_min_rect(min_rect);
ret
}))
} else {
let ret_response = ui.scope(add_body);
let full_size = ret_response.response.rect.size();
self.state.open_height = Some(full_size.y);
self.store(ui.ctx()); // remember the height
Some(ret_response)
}
}
/// Paint this [CollapsingState](CollapsingState)'s toggle button. Takes an [IconPainter](IconPainter) as the icon.
/// ```
/// # egui::__run_test_ui(|ui| {
/// fn circle_icon(ui: &mut egui::Ui, openness: f32, response: &egui::Response) {
/// let stroke = ui.style().interact(&response).fg_stroke;
/// let radius = egui::lerp(2.0..=3.0, openness);
/// ui.painter().circle_filled(response.rect.center(), radius, stroke.color);
/// }
///
/// let mut state = egui::collapsing_header::CollapsingState::load_with_default_open(
/// ui.ctx(),
/// ui.make_persistent_id("my_collapsing_state"),
/// false,
/// );
///
/// let header_res = ui.horizontal(|ui| {
/// ui.label("Header");
/// state.show_toggle_button(ui, circle_icon);
/// });
///
/// state.show_body_indented(&header_res.response, ui, |ui| ui.label("Body"));
/// # });
/// ```
pub fn show_toggle_button(
&mut self,
ui: &mut Ui,
icon_fn: impl FnOnce(&mut Ui, f32, &Response) + 'static,
) -> Response {
self.show_button_indented(ui, icon_fn)
}
}
/// From [`CollapsingState::show_header`].
#[must_use = "Remember to show the body"]
pub struct HeaderResponse<'ui, HeaderRet> {
state: CollapsingState,
ui: &'ui mut Ui,
toggle_button_response: Response,
header_response: InnerResponse<HeaderRet>,
}
impl<'ui, HeaderRet> HeaderResponse<'ui, HeaderRet> {
/// Returns the response of the collapsing button, the custom header, and the custom body.
pub fn body<BodyRet>(
mut self,
add_body: impl FnOnce(&mut Ui) -> BodyRet,
) -> (
Response,
InnerResponse<HeaderRet>,
Option<InnerResponse<BodyRet>>,
) {
let body_response =
self.state
.show_body_indented(&self.header_response.response, self.ui, add_body);
(
self.toggle_button_response,
self.header_response,
body_response,
)
}
/// Returns the response of the collapsing button, the custom header, and the custom body, without indentation.
pub fn body_unindented<BodyRet>(
mut self,
add_body: impl FnOnce(&mut Ui) -> BodyRet,
) -> (
Response,
InnerResponse<HeaderRet>,
Option<InnerResponse<BodyRet>>,
) {
let body_response = self.state.show_body_unindented(self.ui, add_body);
(
self.toggle_button_response,
self.header_response,
body_response,
)
}
}
// ----------------------------------------------------------------------------
/// Paint the arrow icon that indicated if the region is open or not
pub fn paint_default_icon(ui: &mut Ui, openness: f32, response: &Response) {
let visuals = ui.style().interact(response);
let stroke = visuals.fg_stroke;
let rect = response.rect;
// Draw a pointy triangle arrow:
let rect = Rect::from_center_size(rect.center(), vec2(rect.width(), rect.height()) * 0.75);
let rect = rect.expand(visuals.expansion);
let mut points = vec![rect.left_top(), rect.right_top(), rect.center_bottom()];
use std::f32::consts::TAU;
let rotation = emath::Rot2::from_angle(remap(openness, 0.0..=1.0, -TAU / 4.0..=0.0));
for p in &mut points {
*p = rect.center() + rotation * (*p - rect.center());
}
ui.painter().add(Shape::closed_line(points, stroke));
}
/// A function that paints an icon indicating if the region is open or not
pub type IconPainter = Box<dyn FnOnce(&mut Ui, f32, &Response)>;
/// A header which can be collapsed/expanded, revealing a contained [`Ui`] region.
///
/// ```
/// # egui::__run_test_ui(|ui| {
/// egui::CollapsingHeader::new("Heading")
/// .show(ui, |ui| {
/// ui.label("Body");
/// });
///
/// // Short version:
/// ui.collapsing("Heading", |ui| { ui.label("Body"); });
/// # });
/// ```
///
/// If you want to customize the header contents, see [`CollapsingState::show_header`].
#[must_use = "You should call .show()"]
pub struct CollapsingHeader {
text: WidgetText,
default_open: bool,
open: Option<bool>,
id_source: Id,
enabled: bool,
selectable: bool,
selected: bool,
show_background: bool,
icon: Option<IconPainter>,
}
impl CollapsingHeader {
/// The [`CollapsingHeader`] starts out collapsed unless you call `default_open`.
///
/// The label is used as an [`Id`] source.
/// If the label is unique and static this is fine,
/// but if it changes or there are several [`CollapsingHeader`] with the same title
/// you need to provide a unique id source with [`Self::id_source`].
pub fn new(text: impl Into<WidgetText>) -> Self {
let text = text.into();
let id_source = Id::new(text.text());
Self {
text,
default_open: false,
open: None,
id_source,
enabled: true,
selectable: false,
selected: false,
show_background: false,
icon: None,
}
}
/// By default, the [`CollapsingHeader`] is collapsed.
/// Call `.default_open(true)` to change this.
pub fn default_open(mut self, open: bool) -> Self {
self.default_open = open;
self
}
/// Calling `.open(Some(true))` will make the collapsing header open this frame (or stay open).
///
/// Calling `.open(Some(false))` will make the collapsing header close this frame (or stay closed).
///
/// Calling `.open(None)` has no effect (default).
pub fn open(mut self, open: Option<bool>) -> Self {
self.open = open;
self
}
/// Explicitly set the source of the [`Id`] of this widget, instead of using title label.
/// This is useful if the title label is dynamic or not unique.
pub fn id_source(mut self, id_source: impl Hash) -> Self {
self.id_source = Id::new(id_source);
self
}
/// If you set this to `false`, the [`CollapsingHeader`] will be grayed out and un-clickable.
///
/// This is a convenience for [`Ui::set_enabled`].
pub fn enabled(mut self, enabled: bool) -> Self {
self.enabled = enabled;
self
}
/// Can the [`CollapsingHeader`] be selected by clicking it? Default: `false`.
#[deprecated = "Use the more powerful egui::collapsing_header::CollapsingState::show_header"] // Deprecated in 2022-04-28, before egui 0.18
pub fn selectable(mut self, selectable: bool) -> Self {
self.selectable = selectable;
self
}
/// If you set this to 'true', the [`CollapsingHeader`] will be shown as selected.
///
/// Example:
/// ```
/// # egui::__run_test_ui(|ui| {
/// let mut selected = false;
/// let response = egui::CollapsingHeader::new("Select and open me")
/// .selectable(true)
/// .selected(selected)
/// .show(ui, |ui| ui.label("Body"));
/// if response.header_response.clicked() {
/// selected = true;
/// }
/// # });
/// ```
#[deprecated = "Use the more powerful egui::collapsing_header::CollapsingState::show_header"] // Deprecated in 2022-04-28, before egui 0.18
pub fn selected(mut self, selected: bool) -> Self {
self.selected = selected;
self
}
/// Should the [`CollapsingHeader`] show a background behind it? Default: `false`.
///
/// To show it behind all [`CollapsingHeader`] you can just use:
/// ```
/// # egui::__run_test_ui(|ui| {
/// ui.visuals_mut().collapsing_header_frame = true;
/// # });
/// ```
pub fn show_background(mut self, show_background: bool) -> Self {
self.show_background = show_background;
self
}
/// Use the provided function to render a different [`CollapsingHeader`] icon.
/// Defaults to a triangle that animates as the [`CollapsingHeader`] opens and closes.
///
/// For example:
/// ```
/// # egui::__run_test_ui(|ui| {
/// fn circle_icon(ui: &mut egui::Ui, openness: f32, response: &egui::Response) {
/// let stroke = ui.style().interact(&response).fg_stroke;
/// let radius = egui::lerp(2.0..=3.0, openness);
/// ui.painter().circle_filled(response.rect.center(), radius, stroke.color);
/// }
///
/// egui::CollapsingHeader::new("Circles")
/// .icon(circle_icon)
/// .show(ui, |ui| { ui.label("Hi!"); });
/// # });
/// ```
pub fn icon(mut self, icon_fn: impl FnOnce(&mut Ui, f32, &Response) + 'static) -> Self {
self.icon = Some(Box::new(icon_fn));
self
}
}
struct Prepared {
header_response: Response,
state: CollapsingState,
openness: f32,
}
impl CollapsingHeader {
fn begin(self, ui: &mut Ui) -> Prepared {
assert!(
ui.layout().main_dir().is_vertical(),
"Horizontal collapsing is unimplemented"
);
let Self {
icon,
text,
default_open,
open,
id_source,
enabled: _,
selectable,
selected,
show_background,
} = self;
// TODO(emilk): horizontal layout, with icon and text as labels. Insert background behind using Frame.
let id = ui.make_persistent_id(id_source);
let button_padding = ui.spacing().button_padding;
let available = ui.available_rect_before_wrap();
let text_pos = available.min + vec2(ui.spacing().indent, 0.0);
let wrap_width = available.right() - text_pos.x;
let wrap = Some(false);
let text = text.into_galley(ui, wrap, wrap_width, TextStyle::Button);
let text_max_x = text_pos.x + text.size().x;
let mut desired_width = text_max_x + button_padding.x - available.left();
if ui.visuals().collapsing_header_frame {
desired_width = desired_width.max(available.width()); // fill full width
}
let mut desired_size = vec2(desired_width, text.size().y + 2.0 * button_padding.y);
desired_size = desired_size.at_least(ui.spacing().interact_size);
let (_, rect) = ui.allocate_space(desired_size);
let mut header_response = ui.interact(rect, id, Sense::click());
let text_pos = pos2(
text_pos.x,
header_response.rect.center().y - text.size().y / 2.0,
);
let mut state = CollapsingState::load_with_default_open(ui.ctx(), id, default_open);
if let Some(open) = open {
if open != state.is_open() {
state.toggle(ui);
header_response.mark_changed();
}
} else if header_response.clicked() {
state.toggle(ui);
header_response.mark_changed();
}
header_response
.widget_info(|| WidgetInfo::labeled(WidgetType::CollapsingHeader, text.text()));
let openness = state.openness(ui.ctx());
if ui.is_rect_visible(rect) {
let visuals = ui.style().interact_selectable(&header_response, selected);
if ui.visuals().collapsing_header_frame || show_background {
ui.painter().add(epaint::RectShape {
rect: header_response.rect.expand(visuals.expansion),
rounding: visuals.rounding,
fill: visuals.bg_fill,
stroke: visuals.bg_stroke,
// stroke: Default::default(),
});
}
if selected || selectable && (header_response.hovered() || header_response.has_focus())
{
let rect = rect.expand(visuals.expansion);
ui.painter()
.rect(rect, visuals.rounding, visuals.bg_fill, visuals.bg_stroke);
}
{
let (mut icon_rect, _) = ui.spacing().icon_rectangles(header_response.rect);
icon_rect.set_center(pos2(
header_response.rect.left() + ui.spacing().indent / 2.0,
header_response.rect.center().y,
));
let icon_response = Response {
rect: icon_rect,
..header_response.clone()
};
if let Some(icon) = icon {
icon(ui, openness, &icon_response);
} else {
paint_default_icon(ui, openness, &icon_response);
}
}
text.paint_with_visuals(ui.painter(), text_pos, &visuals);
}
Prepared {
header_response,
state,
openness,
}
}
#[inline]
pub fn show<R>(
self,
ui: &mut Ui,
add_body: impl FnOnce(&mut Ui) -> R,
) -> CollapsingResponse<R> {
self.show_dyn(ui, Box::new(add_body))
}
fn show_dyn<'c, R>(
self,
ui: &mut Ui,
add_body: Box<dyn FnOnce(&mut Ui) -> R + 'c>,
) -> CollapsingResponse<R> {
// Make sure body is bellow header,
// and make sure it is one unit (necessary for putting a [`CollapsingHeader`] in a grid).
ui.vertical(|ui| {
ui.set_enabled(self.enabled);
let Prepared {
header_response,
mut state,
openness,
} = self.begin(ui); // show the header
let ret_response = state.show_body_indented(&header_response, ui, add_body);
if let Some(ret_response) = ret_response {
CollapsingResponse {
header_response,
body_response: Some(ret_response.response),
body_returned: Some(ret_response.inner),
openness,
}
} else {
CollapsingResponse {
header_response,
body_response: None,
body_returned: None,
openness,
}
}
})
.inner
}
}
/// The response from showing a [`CollapsingHeader`].
pub struct CollapsingResponse<R> {
/// Response of the actual clickable header.
pub header_response: Response,
/// None iff collapsed.
pub body_response: Option<Response>,
/// None iff collapsed.
pub body_returned: Option<R>,
/// 0.0 if fully closed, 1.0 if fully open, and something in-between while animating.
pub openness: f32,
}
impl<R> CollapsingResponse<R> {
/// Was the [`CollapsingHeader`] fully closed (and not being animated)?
pub fn fully_closed(&self) -> bool {
self.openness <= 0.0
}
/// Was the [`CollapsingHeader`] fully open (and not being animated)?
pub fn fully_open(&self) -> bool {
self.openness >= 1.0
}
}
+328
View File
@@ -0,0 +1,328 @@
use crate::{style::WidgetVisuals, *};
use epaint::Shape;
/// A function that paints the [`ComboBox`] icon
pub type IconPainter = Box<dyn FnOnce(&Ui, Rect, &WidgetVisuals, bool)>;
/// A drop-down selection menu with a descriptive label.
///
/// ```
/// # #[derive(Debug, PartialEq)]
/// # enum Enum { First, Second, Third }
/// # let mut selected = Enum::First;
/// # egui::__run_test_ui(|ui| {
/// egui::ComboBox::from_label("Select one!")
/// .selected_text(format!("{:?}", selected))
/// .show_ui(ui, |ui| {
/// ui.selectable_value(&mut selected, Enum::First, "First");
/// ui.selectable_value(&mut selected, Enum::Second, "Second");
/// ui.selectable_value(&mut selected, Enum::Third, "Third");
/// }
/// );
/// # });
/// ```
#[must_use = "You should call .show*"]
pub struct ComboBox {
id_source: Id,
label: Option<WidgetText>,
selected_text: WidgetText,
width: Option<f32>,
icon: Option<IconPainter>,
}
impl ComboBox {
/// Create new [`ComboBox`] with id and label
pub fn new(id_source: impl std::hash::Hash, label: impl Into<WidgetText>) -> Self {
Self {
id_source: Id::new(id_source),
label: Some(label.into()),
selected_text: Default::default(),
width: None,
icon: None,
}
}
/// Label shown next to the combo box
pub fn from_label(label: impl Into<WidgetText>) -> Self {
let label = label.into();
Self {
id_source: Id::new(label.text()),
label: Some(label),
selected_text: Default::default(),
width: None,
icon: None,
}
}
/// Without label.
pub fn from_id_source(id_source: impl std::hash::Hash) -> Self {
Self {
id_source: Id::new(id_source),
label: Default::default(),
selected_text: Default::default(),
width: None,
icon: None,
}
}
/// Set the width of the button and menu
pub fn width(mut self, width: f32) -> Self {
self.width = Some(width);
self
}
/// What we show as the currently selected value
pub fn selected_text(mut self, selected_text: impl Into<WidgetText>) -> Self {
self.selected_text = selected_text.into();
self
}
/// Use the provided function to render a different [`ComboBox`] icon.
/// Defaults to a triangle that expands when the cursor is hovering over the [`ComboBox`].
///
/// For example:
/// ```
/// # egui::__run_test_ui(|ui| {
/// # let text = "Selected text";
/// pub fn filled_triangle(
/// ui: &egui::Ui,
/// rect: egui::Rect,
/// visuals: &egui::style::WidgetVisuals,
/// _is_open: bool,
/// ) {
/// let rect = egui::Rect::from_center_size(
/// rect.center(),
/// egui::vec2(rect.width() * 0.6, rect.height() * 0.4),
/// );
/// ui.painter().add(egui::Shape::convex_polygon(
/// vec![rect.left_top(), rect.right_top(), rect.center_bottom()],
/// visuals.fg_stroke.color,
/// visuals.fg_stroke,
/// ));
/// }
///
/// egui::ComboBox::from_id_source("my-combobox")
/// .selected_text(text)
/// .icon(filled_triangle)
/// .show_ui(ui, |_ui| {});
/// # });
/// ```
pub fn icon(mut self, icon_fn: impl FnOnce(&Ui, Rect, &WidgetVisuals, bool) + 'static) -> Self {
self.icon = Some(Box::new(icon_fn));
self
}
/// Show the combo box, with the given ui code for the menu contents.
///
/// Returns `InnerResponse { inner: None }` if the combo box is closed.
pub fn show_ui<R>(
self,
ui: &mut Ui,
menu_contents: impl FnOnce(&mut Ui) -> R,
) -> InnerResponse<Option<R>> {
self.show_ui_dyn(ui, Box::new(menu_contents))
}
fn show_ui_dyn<'c, R>(
self,
ui: &mut Ui,
menu_contents: Box<dyn FnOnce(&mut Ui) -> R + 'c>,
) -> InnerResponse<Option<R>> {
let Self {
id_source,
label,
selected_text,
width,
icon,
} = self;
let button_id = ui.make_persistent_id(id_source);
ui.horizontal(|ui| {
if let Some(width) = width {
ui.spacing_mut().slider_width = width; // yes, this is ugly. Will remove later.
}
let mut ir = combo_box_dyn(ui, button_id, selected_text, menu_contents, icon);
if let Some(label) = label {
ir.response
.widget_info(|| WidgetInfo::labeled(WidgetType::ComboBox, label.text()));
ir.response |= ui.label(label);
} else {
ir.response
.widget_info(|| WidgetInfo::labeled(WidgetType::ComboBox, ""));
}
ir
})
.inner
}
/// Show a list of items with the given selected index.
///
///
/// ```
/// # #[derive(Debug, PartialEq)]
/// # enum Enum { First, Second, Third }
/// # let mut selected = Enum::First;
/// # egui::__run_test_ui(|ui| {
/// let alternatives = ["a", "b", "c", "d"];
/// let mut selected = 2;
/// egui::ComboBox::from_label("Select one!").show_index(
/// ui,
/// &mut selected,
/// alternatives.len(),
/// |i| alternatives[i].to_owned()
/// );
/// # });
/// ```
pub fn show_index(
self,
ui: &mut Ui,
selected: &mut usize,
len: usize,
get: impl Fn(usize) -> String,
) -> Response {
let slf = self.selected_text(get(*selected));
let mut changed = false;
let mut response = slf
.show_ui(ui, |ui| {
for i in 0..len {
if ui.selectable_label(i == *selected, get(i)).clicked() {
*selected = i;
changed = true;
}
}
})
.response;
if changed {
response.mark_changed();
}
response
}
}
fn combo_box_dyn<'c, R>(
ui: &mut Ui,
button_id: Id,
selected_text: WidgetText,
menu_contents: Box<dyn FnOnce(&mut Ui) -> R + 'c>,
icon: Option<IconPainter>,
) -> InnerResponse<Option<R>> {
let popup_id = button_id.with("popup");
let is_popup_open = ui.memory().is_popup_open(popup_id);
let button_response = button_frame(ui, button_id, is_popup_open, Sense::click(), |ui| {
// We don't want to change width when user selects something new
let full_minimum_width = ui.spacing().slider_width;
let icon_size = Vec2::splat(ui.spacing().icon_width);
let galley = selected_text.into_galley(ui, Some(false), f32::INFINITY, TextStyle::Button);
let width = galley.size().x + ui.spacing().item_spacing.x + icon_size.x;
let width = width.at_least(full_minimum_width);
let height = galley.size().y.max(icon_size.y);
let (_, rect) = ui.allocate_space(Vec2::new(width, height));
let button_rect = ui.min_rect().expand2(ui.spacing().button_padding);
let response = ui.interact(button_rect, button_id, Sense::click());
// response.active |= is_popup_open;
if ui.is_rect_visible(rect) {
let icon_rect = Align2::RIGHT_CENTER.align_size_within_rect(icon_size, rect);
let visuals = if is_popup_open {
&ui.visuals().widgets.open
} else {
ui.style().interact(&response)
};
if let Some(icon) = icon {
icon(
ui,
icon_rect.expand(visuals.expansion),
visuals,
is_popup_open,
);
} else {
paint_default_icon(ui.painter(), icon_rect.expand(visuals.expansion), visuals);
}
let text_rect = Align2::LEFT_CENTER.align_size_within_rect(galley.size(), rect);
galley.paint_with_visuals(ui.painter(), text_rect.min, visuals);
}
});
if button_response.clicked() {
ui.memory().toggle_popup(popup_id);
}
let inner = crate::popup::popup_below_widget(ui, popup_id, &button_response, |ui| {
ScrollArea::vertical()
.max_height(ui.spacing().combo_height)
.show(ui, menu_contents)
.inner
});
InnerResponse {
inner,
response: button_response,
}
}
fn button_frame(
ui: &mut Ui,
id: Id,
is_popup_open: bool,
sense: Sense,
add_contents: impl FnOnce(&mut Ui),
) -> Response {
let where_to_put_background = ui.painter().add(Shape::Noop);
let margin = ui.spacing().button_padding;
let interact_size = ui.spacing().interact_size;
let mut outer_rect = ui.available_rect_before_wrap();
outer_rect.set_height(outer_rect.height().at_least(interact_size.y));
let inner_rect = outer_rect.shrink2(margin);
let mut content_ui = ui.child_ui(inner_rect, *ui.layout());
add_contents(&mut content_ui);
let mut outer_rect = content_ui.min_rect().expand2(margin);
outer_rect.set_height(outer_rect.height().at_least(interact_size.y));
let response = ui.interact(outer_rect, id, sense);
if ui.is_rect_visible(outer_rect) {
let visuals = if is_popup_open {
&ui.visuals().widgets.open
} else {
ui.style().interact(&response)
};
ui.painter().set(
where_to_put_background,
epaint::RectShape {
rect: outer_rect.expand(visuals.expansion),
rounding: visuals.rounding,
fill: visuals.bg_fill,
stroke: visuals.bg_stroke,
},
);
}
ui.advance_cursor_after_rect(outer_rect);
response
}
fn paint_default_icon(painter: &Painter, rect: Rect, visuals: &WidgetVisuals) {
let rect = Rect::from_center_size(
rect.center(),
vec2(rect.width() * 0.7, rect.height() * 0.45),
);
painter.add(Shape::closed_line(
vec![rect.left_top(), rect.right_top(), rect.center_bottom()],
visuals.fg_stroke,
));
}
+263
View File
@@ -0,0 +1,263 @@
//! Frame container
use crate::{layers::ShapeIdx, style::Margin, *};
use epaint::*;
/// Add a background, frame and/or margin to a rectangular background of a [`Ui`].
///
/// ```
/// # egui::__run_test_ui(|ui| {
/// egui::Frame::none()
/// .fill(egui::Color32::RED)
/// .show(ui, |ui| {
/// ui.label("Label with red background");
/// });
/// # });
/// ```
#[derive(Clone, Copy, Debug, Default, PartialEq)]
#[must_use = "You should call .show()"]
pub struct Frame {
/// Margin within the painted frame.
pub inner_margin: Margin,
/// Margin outside the painted frame.
pub outer_margin: Margin,
pub rounding: Rounding,
pub shadow: Shadow,
pub fill: Color32,
pub stroke: Stroke,
}
impl Frame {
pub fn none() -> Self {
Self::default()
}
/// For when you want to group a few widgets together within a frame.
pub fn group(style: &Style) -> Self {
Self {
inner_margin: Margin::same(6.0), // same and symmetric looks best in corners when nesting groups
rounding: style.visuals.widgets.noninteractive.rounding,
stroke: style.visuals.widgets.noninteractive.bg_stroke,
..Default::default()
}
}
pub(crate) fn side_top_panel(style: &Style) -> Self {
Self {
inner_margin: Margin::symmetric(8.0, 2.0),
rounding: Rounding::none(),
fill: style.visuals.window_fill(),
stroke: style.visuals.window_stroke(),
..Default::default()
}
}
pub(crate) fn central_panel(style: &Style) -> Self {
Self {
inner_margin: Margin::same(8.0),
rounding: Rounding::none(),
fill: style.visuals.window_fill(),
stroke: Default::default(),
..Default::default()
}
}
pub fn window(style: &Style) -> Self {
Self {
inner_margin: style.spacing.window_margin,
rounding: style.visuals.window_rounding,
shadow: style.visuals.window_shadow,
fill: style.visuals.window_fill(),
stroke: style.visuals.window_stroke(),
..Default::default()
}
}
pub fn menu(style: &Style) -> Self {
Self {
inner_margin: Margin::same(1.0),
rounding: style.visuals.widgets.noninteractive.rounding,
shadow: style.visuals.popup_shadow,
fill: style.visuals.window_fill(),
stroke: style.visuals.window_stroke(),
..Default::default()
}
}
pub fn popup(style: &Style) -> Self {
Self {
inner_margin: style.spacing.window_margin,
rounding: style.visuals.widgets.noninteractive.rounding,
shadow: style.visuals.popup_shadow,
fill: style.visuals.window_fill(),
stroke: style.visuals.window_stroke(),
..Default::default()
}
}
/// A canvas to draw on.
///
/// In bright mode this will be very bright,
/// and in dark mode this will be very dark.
pub fn canvas(style: &Style) -> Self {
Self {
inner_margin: Margin::same(2.0),
rounding: style.visuals.widgets.noninteractive.rounding,
fill: style.visuals.extreme_bg_color,
stroke: style.visuals.window_stroke(),
..Default::default()
}
}
/// A dark canvas to draw on.
pub fn dark_canvas(style: &Style) -> Self {
Self {
fill: Color32::from_black_alpha(250),
..Self::canvas(style)
}
}
}
impl Frame {
pub fn fill(mut self, fill: Color32) -> Self {
self.fill = fill;
self
}
pub fn stroke(mut self, stroke: Stroke) -> Self {
self.stroke = stroke;
self
}
pub fn rounding(mut self, rounding: impl Into<Rounding>) -> Self {
self.rounding = rounding.into();
self
}
/// Margin within the painted frame.
pub fn inner_margin(mut self, inner_margin: impl Into<Margin>) -> Self {
self.inner_margin = inner_margin.into();
self
}
/// Margin outside the painted frame.
pub fn outer_margin(mut self, outer_margin: impl Into<Margin>) -> Self {
self.outer_margin = outer_margin.into();
self
}
#[deprecated = "Renamed inner_margin in egui 0.18"]
pub fn margin(self, margin: impl Into<Margin>) -> Self {
self.inner_margin(margin)
}
pub fn shadow(mut self, shadow: Shadow) -> Self {
self.shadow = shadow;
self
}
pub fn multiply_with_opacity(mut self, opacity: f32) -> Self {
self.fill = self.fill.linear_multiply(opacity);
self.stroke.color = self.stroke.color.linear_multiply(opacity);
self.shadow.color = self.shadow.color.linear_multiply(opacity);
self
}
}
pub struct Prepared {
pub frame: Frame,
where_to_put_background: ShapeIdx,
pub content_ui: Ui,
}
impl Frame {
pub fn begin(self, ui: &mut Ui) -> Prepared {
let where_to_put_background = ui.painter().add(Shape::Noop);
let outer_rect_bounds = ui.available_rect_before_wrap();
let mut inner_rect = outer_rect_bounds;
inner_rect.min += self.outer_margin.left_top() + self.inner_margin.left_top();
inner_rect.max -= self.outer_margin.right_bottom() + self.inner_margin.right_bottom();
// Make sure we don't shrink to the negative:
inner_rect.max.x = inner_rect.max.x.max(inner_rect.min.x);
inner_rect.max.y = inner_rect.max.y.max(inner_rect.min.y);
let content_ui = ui.child_ui(inner_rect, *ui.layout());
// content_ui.set_clip_rect(outer_rect_bounds.shrink(self.stroke.width * 0.5)); // Can't do this since we don't know final size yet
Prepared {
frame: self,
where_to_put_background,
content_ui,
}
}
pub fn show<R>(self, ui: &mut Ui, add_contents: impl FnOnce(&mut Ui) -> R) -> InnerResponse<R> {
self.show_dyn(ui, Box::new(add_contents))
}
fn show_dyn<'c, R>(
self,
ui: &mut Ui,
add_contents: Box<dyn FnOnce(&mut Ui) -> R + 'c>,
) -> InnerResponse<R> {
let mut prepared = self.begin(ui);
let ret = add_contents(&mut prepared.content_ui);
let response = prepared.end(ui);
InnerResponse::new(ret, response)
}
pub fn paint(&self, outer_rect: Rect) -> Shape {
let Self {
inner_margin: _,
outer_margin: _,
rounding,
shadow,
fill,
stroke,
} = *self;
let frame_shape = Shape::Rect(epaint::RectShape {
rect: outer_rect,
rounding,
fill,
stroke,
});
if shadow == Default::default() {
frame_shape
} else {
let shadow = shadow.tessellate(outer_rect, rounding);
let shadow = Shape::Mesh(shadow);
Shape::Vec(vec![shadow, frame_shape])
}
}
}
impl Prepared {
fn paint_rect(&self) -> Rect {
let mut rect = self.content_ui.min_rect();
rect.min -= self.frame.inner_margin.left_top();
rect.max += self.frame.inner_margin.right_bottom();
rect
}
pub fn end(self, ui: &mut Ui) -> Response {
let paint_rect = self.paint_rect();
let Prepared {
frame,
where_to_put_background,
..
} = self;
if ui.is_rect_visible(paint_rect) {
let shape = frame.paint(paint_rect);
ui.painter().set(where_to_put_background, shape);
}
ui.allocate_rect(paint_rect, Sense::hover())
}
}
+25
View File
@@ -0,0 +1,25 @@
//! Containers are pieces of the UI which wraps other pieces of UI. Examples: [`Window`], [`ScrollArea`], [`Resize`], [`SidePanel`], etc.
//!
//! For instance, a [`Frame`] adds a frame and background to some contained UI.
pub(crate) mod area;
pub mod collapsing_header;
mod combo_box;
pub(crate) mod frame;
pub mod panel;
pub mod popup;
pub(crate) mod resize;
pub(crate) mod scroll_area;
pub(crate) mod window;
pub use {
area::Area,
collapsing_header::{CollapsingHeader, CollapsingResponse},
combo_box::*,
frame::Frame,
panel::{CentralPanel, SidePanel, TopBottomPanel},
popup::*,
resize::Resize,
scroll_area::ScrollArea,
window::Window,
};
+716
View File
@@ -0,0 +1,716 @@
//! Panels are [`Ui`] regions taking up e.g. the left side of a [`Ui`] or screen.
//!
//! Panels can either be a child of a [`Ui`] (taking up a portion of the parent)
//! or be top-level (taking up a portion of the whole screen).
//!
//! Together with [`Window`] and [`Area`]:s, top-level panels are
//! the only places where you can put you widgets.
//!
//! The order in which you add panels matter!
//! The first panel you add will always be the outermost, and the last you add will always be the innermost.
//!
//! You must never open one top-level panel from within another panel. Add one panel, then the next.
//!
//! ⚠ Always add any [`CentralPanel`] last.
//!
//! Add your [`Window`]:s after any top-level panels.
use std::ops::RangeInclusive;
use crate::*;
#[derive(Clone, Copy, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
struct PanelState {
rect: Rect,
}
impl PanelState {
fn load(ctx: &Context, bar_id: Id) -> Option<Self> {
ctx.data().get_persisted(bar_id)
}
fn store(self, ctx: &Context, bar_id: Id) {
ctx.data().insert_persisted(bar_id, self);
}
}
// ----------------------------------------------------------------------------
/// [`Left`](Side::Left) or [`Right`](Side::Right)
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Side {
Left,
Right,
}
impl Side {
fn opposite(self) -> Self {
match self {
Side::Left => Self::Right,
Side::Right => Self::Left,
}
}
fn set_rect_width(self, rect: &mut Rect, width: f32) {
match self {
Side::Left => rect.max.x = rect.min.x + width,
Side::Right => rect.min.x = rect.max.x - width,
}
}
fn side_x(self, rect: Rect) -> f32 {
match self {
Side::Left => rect.left(),
Side::Right => rect.right(),
}
}
}
/// A panel that covers the entire left or right side of a [`Ui`] or screen.
///
/// The order in which you add panels matter!
/// The first panel you add will always be the outermost, and the last you add will always be the innermost.
///
/// ⚠ Always add any [`CentralPanel`] last.
///
/// See the [module level docs](crate::containers::panel) for more details.
///
/// ```
/// # egui::__run_test_ctx(|ctx| {
/// egui::SidePanel::left("my_left_panel").show(ctx, |ui| {
/// ui.label("Hello World!");
/// });
/// # });
/// ```
///
/// See also [`TopBottomPanel`].
#[must_use = "You should call .show()"]
pub struct SidePanel {
side: Side,
id: Id,
frame: Option<Frame>,
resizable: bool,
default_width: f32,
width_range: RangeInclusive<f32>,
}
impl SidePanel {
/// `id_source`: Something unique, e.g. `"my_left_panel"`.
pub fn left(id_source: impl std::hash::Hash) -> Self {
Self::new(Side::Left, id_source)
}
/// `id_source`: Something unique, e.g. `"my_right_panel"`.
pub fn right(id_source: impl std::hash::Hash) -> Self {
Self::new(Side::Right, id_source)
}
/// `id_source`: Something unique, e.g. `"my_panel"`.
pub fn new(side: Side, id_source: impl std::hash::Hash) -> Self {
Self {
side,
id: Id::new(id_source),
frame: None,
resizable: true,
default_width: 200.0,
width_range: 96.0..=f32::INFINITY,
}
}
/// Can panel be resized by dragging the edge of it?
///
/// Default is `true`.
///
/// If you want your panel to be resizable you also need a widget in it that
/// takes up more space as you resize it, such as:
/// * Wrapping text ([`Ui::horizontal_wrapped`]).
/// * A [`ScrollArea`].
/// * A [`Separator`].
/// * A [`TextEdit`].
/// * …
pub fn resizable(mut self, resizable: bool) -> Self {
self.resizable = resizable;
self
}
/// The initial wrapping width of the [`SidePanel`].
pub fn default_width(mut self, default_width: f32) -> Self {
self.default_width = default_width;
self
}
pub fn min_width(mut self, min_width: f32) -> Self {
self.width_range = min_width..=(*self.width_range.end());
self
}
pub fn max_width(mut self, max_width: f32) -> Self {
self.width_range = (*self.width_range.start())..=max_width;
self
}
/// The allowable width range for resizable panels.
pub fn width_range(mut self, width_range: RangeInclusive<f32>) -> Self {
self.width_range = width_range;
self
}
/// Change the background color, margins, etc.
pub fn frame(mut self, frame: Frame) -> Self {
self.frame = Some(frame);
self
}
}
impl SidePanel {
/// Show the panel inside a [`Ui`].
pub fn show_inside<R>(
self,
ui: &mut Ui,
add_contents: impl FnOnce(&mut Ui) -> R,
) -> InnerResponse<R> {
self.show_inside_dyn(ui, Box::new(add_contents))
}
/// Show the panel inside a [`Ui`].
fn show_inside_dyn<'c, R>(
self,
ui: &mut Ui,
add_contents: Box<dyn FnOnce(&mut Ui) -> R + 'c>,
) -> InnerResponse<R> {
let Self {
side,
id,
frame,
resizable,
default_width,
width_range,
} = self;
let available_rect = ui.available_rect_before_wrap();
let mut panel_rect = available_rect;
{
let mut width = default_width;
if let Some(state) = PanelState::load(ui.ctx(), id) {
width = state.rect.width();
}
width = clamp_to_range(width, width_range.clone()).at_most(available_rect.width());
side.set_rect_width(&mut panel_rect, width);
}
let mut resize_hover = false;
let mut is_resizing = false;
if resizable {
let resize_id = id.with("__resize");
if let Some(pointer) = ui.ctx().pointer_latest_pos() {
let we_are_on_top = ui
.ctx()
.layer_id_at(pointer)
.map_or(true, |top_layer_id| top_layer_id == ui.layer_id());
let resize_x = side.opposite().side_x(panel_rect);
let mouse_over_resize_line = we_are_on_top
&& panel_rect.y_range().contains(&pointer.y)
&& (resize_x - pointer.x).abs()
<= ui.style().interaction.resize_grab_radius_side;
if ui.input().pointer.any_pressed()
&& ui.input().pointer.any_down()
&& mouse_over_resize_line
{
ui.memory().set_dragged_id(resize_id);
}
is_resizing = ui.memory().is_being_dragged(resize_id);
if is_resizing {
let width = (pointer.x - side.side_x(panel_rect)).abs();
let width =
clamp_to_range(width, width_range.clone()).at_most(available_rect.width());
side.set_rect_width(&mut panel_rect, width);
}
let dragging_something_else =
ui.input().pointer.any_down() || ui.input().pointer.any_pressed();
resize_hover = mouse_over_resize_line && !dragging_something_else;
if resize_hover || is_resizing {
ui.output().cursor_icon = CursorIcon::ResizeHorizontal;
}
}
}
let mut panel_ui = ui.child_ui_with_id_source(panel_rect, Layout::top_down(Align::Min), id);
panel_ui.expand_to_include_rect(panel_rect);
let frame = frame.unwrap_or_else(|| Frame::side_top_panel(ui.style()));
let inner_response = frame.show(&mut panel_ui, |ui| {
ui.set_min_height(ui.max_rect().height()); // Make sure the frame fills the full height
ui.set_min_width(*width_range.start());
add_contents(ui)
});
let rect = inner_response.response.rect;
{
let mut cursor = ui.cursor();
match side {
Side::Left => {
cursor.min.x = rect.max.x + ui.spacing().item_spacing.x;
}
Side::Right => {
cursor.max.x = rect.min.x - ui.spacing().item_spacing.x;
}
}
ui.set_cursor(cursor);
}
ui.expand_to_include_rect(rect);
PanelState { rect }.store(ui.ctx(), id);
if resize_hover || is_resizing {
let stroke = if is_resizing {
ui.style().visuals.widgets.active.bg_stroke
} else {
ui.style().visuals.widgets.hovered.bg_stroke
};
// draw on top of ALL panels so that the resize line won't be covered by subsequent panels
let resize_layer = LayerId::new(Order::Foreground, Id::new("panel_resize"));
let resize_x = side.opposite().side_x(rect);
ui.ctx()
.layer_painter(resize_layer)
.vline(resize_x, rect.y_range(), stroke);
}
inner_response
}
/// Show the panel at the top level.
pub fn show<R>(
self,
ctx: &Context,
add_contents: impl FnOnce(&mut Ui) -> R,
) -> InnerResponse<R> {
self.show_dyn(ctx, Box::new(add_contents))
}
/// Show the panel at the top level.
fn show_dyn<'c, R>(
self,
ctx: &Context,
add_contents: Box<dyn FnOnce(&mut Ui) -> R + 'c>,
) -> InnerResponse<R> {
let layer_id = LayerId::background();
let side = self.side;
let available_rect = ctx.available_rect();
let clip_rect = ctx.input().screen_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 rect = inner_response.response.rect;
match side {
Side::Left => ctx
.frame_state()
.allocate_left_panel(Rect::from_min_max(available_rect.min, rect.max)),
Side::Right => ctx
.frame_state()
.allocate_right_panel(Rect::from_min_max(rect.min, available_rect.max)),
}
inner_response
}
}
// ----------------------------------------------------------------------------
/// [`Top`](TopBottomSide::Top) or [`Bottom`](TopBottomSide::Bottom)
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TopBottomSide {
Top,
Bottom,
}
impl TopBottomSide {
fn opposite(self) -> Self {
match self {
TopBottomSide::Top => Self::Bottom,
TopBottomSide::Bottom => Self::Top,
}
}
fn set_rect_height(self, rect: &mut Rect, height: f32) {
match self {
TopBottomSide::Top => rect.max.y = rect.min.y + height,
TopBottomSide::Bottom => rect.min.y = rect.max.y - height,
}
}
fn side_y(self, rect: Rect) -> f32 {
match self {
TopBottomSide::Top => rect.top(),
TopBottomSide::Bottom => rect.bottom(),
}
}
}
/// A panel that covers the entire top or bottom of a [`Ui`] or screen.
///
/// The order in which you add panels matter!
/// The first panel you add will always be the outermost, and the last you add will always be the innermost.
///
/// ⚠ Always add any [`CentralPanel`] last.
///
/// See the [module level docs](crate::containers::panel) for more details.
///
/// ```
/// # egui::__run_test_ctx(|ctx| {
/// egui::TopBottomPanel::top("my_panel").show(ctx, |ui| {
/// ui.label("Hello World!");
/// });
/// # });
/// ```
///
/// See also [`SidePanel`].
#[must_use = "You should call .show()"]
pub struct TopBottomPanel {
side: TopBottomSide,
id: Id,
frame: Option<Frame>,
resizable: bool,
default_height: Option<f32>,
height_range: RangeInclusive<f32>,
}
impl TopBottomPanel {
/// `id_source`: Something unique, e.g. `"my_top_panel"`.
pub fn top(id_source: impl std::hash::Hash) -> Self {
Self::new(TopBottomSide::Top, id_source)
}
/// `id_source`: Something unique, e.g. `"my_bottom_panel"`.
pub fn bottom(id_source: impl std::hash::Hash) -> Self {
Self::new(TopBottomSide::Bottom, id_source)
}
/// `id_source`: Something unique, e.g. `"my_panel"`.
pub fn new(side: TopBottomSide, id_source: impl std::hash::Hash) -> Self {
Self {
side,
id: Id::new(id_source),
frame: None,
resizable: false,
default_height: None,
height_range: 20.0..=f32::INFINITY,
}
}
/// Can panel be resized by dragging the edge of it?
///
/// Default is `false`.
///
/// If you want your panel to be resizable you also need a widget in it that
/// takes up more space as you resize it, such as:
/// * Wrapping text ([`Ui::horizontal_wrapped`]).
/// * A [`ScrollArea`].
/// * A [`Separator`].
/// * A [`TextEdit`].
/// * …
pub fn resizable(mut self, resizable: bool) -> Self {
self.resizable = resizable;
self
}
/// The initial height of the [`SidePanel`].
/// Defaults to [`style::Spacing::interact_size`].y.
pub fn default_height(mut self, default_height: f32) -> Self {
self.default_height = Some(default_height);
self
}
pub fn min_height(mut self, min_height: f32) -> Self {
self.height_range = min_height..=(*self.height_range.end());
self
}
pub fn max_height(mut self, max_height: f32) -> Self {
self.height_range = (*self.height_range.start())..=max_height;
self
}
/// The allowable height range for resizable panels.
pub fn height_range(mut self, height_range: RangeInclusive<f32>) -> Self {
self.height_range = height_range;
self
}
/// Change the background color, margins, etc.
pub fn frame(mut self, frame: Frame) -> Self {
self.frame = Some(frame);
self
}
}
impl TopBottomPanel {
/// Show the panel inside a [`Ui`].
pub fn show_inside<R>(
self,
ui: &mut Ui,
add_contents: impl FnOnce(&mut Ui) -> R,
) -> InnerResponse<R> {
self.show_inside_dyn(ui, Box::new(add_contents))
}
/// Show the panel inside a [`Ui`].
fn show_inside_dyn<'c, R>(
self,
ui: &mut Ui,
add_contents: Box<dyn FnOnce(&mut Ui) -> R + 'c>,
) -> InnerResponse<R> {
let Self {
side,
id,
frame,
resizable,
default_height,
height_range,
} = self;
let available_rect = ui.available_rect_before_wrap();
let mut panel_rect = available_rect;
{
let mut height = if let Some(state) = PanelState::load(ui.ctx(), id) {
state.rect.height()
} else {
default_height.unwrap_or_else(|| ui.style().spacing.interact_size.y)
};
height = clamp_to_range(height, height_range.clone()).at_most(available_rect.height());
side.set_rect_height(&mut panel_rect, height);
}
let mut resize_hover = false;
let mut is_resizing = false;
if resizable {
let resize_id = id.with("__resize");
let latest_pos = ui.input().pointer.latest_pos();
if let Some(pointer) = latest_pos {
let we_are_on_top = ui
.ctx()
.layer_id_at(pointer)
.map_or(true, |top_layer_id| top_layer_id == ui.layer_id());
let resize_y = side.opposite().side_y(panel_rect);
let mouse_over_resize_line = we_are_on_top
&& panel_rect.x_range().contains(&pointer.x)
&& (resize_y - pointer.y).abs()
<= ui.style().interaction.resize_grab_radius_side;
if ui.input().pointer.any_pressed()
&& ui.input().pointer.any_down()
&& mouse_over_resize_line
{
ui.memory().interaction.drag_id = Some(resize_id);
}
is_resizing = ui.memory().interaction.drag_id == Some(resize_id);
if is_resizing {
let height = (pointer.y - side.side_y(panel_rect)).abs();
let height = clamp_to_range(height, height_range.clone())
.at_most(available_rect.height());
side.set_rect_height(&mut panel_rect, height);
}
let dragging_something_else =
ui.input().pointer.any_down() || ui.input().pointer.any_pressed();
resize_hover = mouse_over_resize_line && !dragging_something_else;
if resize_hover || is_resizing {
ui.output().cursor_icon = CursorIcon::ResizeVertical;
}
}
}
let mut panel_ui = ui.child_ui_with_id_source(panel_rect, Layout::top_down(Align::Min), id);
panel_ui.expand_to_include_rect(panel_rect);
let frame = frame.unwrap_or_else(|| Frame::side_top_panel(ui.style()));
let inner_response = frame.show(&mut panel_ui, |ui| {
ui.set_min_width(ui.max_rect().width()); // Make the frame fill full width
ui.set_min_height(*height_range.start());
add_contents(ui)
});
let rect = inner_response.response.rect;
{
let mut cursor = ui.cursor();
match side {
TopBottomSide::Top => {
cursor.min.y = rect.max.y + ui.spacing().item_spacing.y;
}
TopBottomSide::Bottom => {
cursor.max.y = rect.min.y - ui.spacing().item_spacing.y;
}
}
ui.set_cursor(cursor);
}
ui.expand_to_include_rect(rect);
PanelState { rect }.store(ui.ctx(), id);
if resize_hover || is_resizing {
let stroke = if is_resizing {
ui.style().visuals.widgets.active.bg_stroke
} else {
ui.style().visuals.widgets.hovered.bg_stroke
};
// draw on top of ALL panels so that the resize line won't be covered by subsequent panels
let resize_layer = LayerId::new(Order::Foreground, Id::new("panel_resize"));
let resize_y = side.opposite().side_y(rect);
ui.ctx()
.layer_painter(resize_layer)
.hline(rect.x_range(), resize_y, stroke);
}
inner_response
}
/// Show the panel at the top level.
pub fn show<R>(
self,
ctx: &Context,
add_contents: impl FnOnce(&mut Ui) -> R,
) -> InnerResponse<R> {
self.show_dyn(ctx, Box::new(add_contents))
}
/// Show the panel at the top level.
fn show_dyn<'c, R>(
self,
ctx: &Context,
add_contents: Box<dyn FnOnce(&mut Ui) -> R + 'c>,
) -> InnerResponse<R> {
let layer_id = LayerId::background();
let available_rect = ctx.available_rect();
let side = self.side;
let clip_rect = ctx.input().screen_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 rect = inner_response.response.rect;
match side {
TopBottomSide::Top => {
ctx.frame_state()
.allocate_top_panel(Rect::from_min_max(available_rect.min, rect.max));
}
TopBottomSide::Bottom => {
ctx.frame_state()
.allocate_bottom_panel(Rect::from_min_max(rect.min, available_rect.max));
}
}
inner_response
}
}
// ----------------------------------------------------------------------------
/// A panel that covers the remainder of the screen,
/// i.e. whatever area is left after adding other panels.
///
/// The order in which you add panels matter!
/// The first panel you add will always be the outermost, and the last you add will always be the innermost.
///
/// ⚠ [`CentralPanel`] must be added after all other panels!
///
/// NOTE: Any [`Window`]s and [`Area`]s will cover the top-level [`CentralPanel`].
///
/// See the [module level docs](crate::containers::panel) for more details.
///
/// ```
/// # egui::__run_test_ctx(|ctx| {
/// egui::TopBottomPanel::top("my_panel").show(ctx, |ui| {
/// ui.label("Hello World! From `TopBottomPanel`, that must be before `CentralPanel`!");
/// });
/// egui::CentralPanel::default().show(ctx, |ui| {
/// ui.label("Hello World!");
/// });
/// # });
/// ```
#[must_use = "You should call .show()"]
#[derive(Default)]
pub struct CentralPanel {
frame: Option<Frame>,
}
impl CentralPanel {
/// Change the background color, margins, etc.
pub fn frame(mut self, frame: Frame) -> Self {
self.frame = Some(frame);
self
}
}
impl CentralPanel {
/// Show the panel inside a [`Ui`].
pub fn show_inside<R>(
self,
ui: &mut Ui,
add_contents: impl FnOnce(&mut Ui) -> R,
) -> InnerResponse<R> {
self.show_inside_dyn(ui, Box::new(add_contents))
}
/// Show the panel inside a [`Ui`].
fn show_inside_dyn<'c, R>(
self,
ui: &mut Ui,
add_contents: Box<dyn FnOnce(&mut Ui) -> R + 'c>,
) -> InnerResponse<R> {
let Self { frame } = self;
let panel_rect = ui.available_rect_before_wrap();
let mut panel_ui = ui.child_ui(panel_rect, Layout::top_down(Align::Min));
let frame = frame.unwrap_or_else(|| Frame::central_panel(ui.style()));
frame.show(&mut panel_ui, |ui| {
ui.expand_to_include_rect(ui.max_rect()); // Expand frame to include it all
add_contents(ui)
})
}
/// Show the panel at the top level.
pub fn show<R>(
self,
ctx: &Context,
add_contents: impl FnOnce(&mut Ui) -> R,
) -> InnerResponse<R> {
self.show_dyn(ctx, Box::new(add_contents))
}
/// Show the panel at the top level.
fn show_dyn<'c, R>(
self,
ctx: &Context,
add_contents: Box<dyn FnOnce(&mut Ui) -> R + 'c>,
) -> InnerResponse<R> {
let available_rect = ctx.available_rect();
let layer_id = LayerId::background();
let id = Id::new("central_panel");
let clip_rect = ctx.input().screen_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);
// Only inform ctx about what we actually used, so we can shrink the native window to fit.
ctx.frame_state()
.allocate_central_panel(inner_response.response.rect);
inner_response
}
}
fn clamp_to_range(x: f32, range: RangeInclusive<f32>) -> f32 {
x.clamp(
range.start().min(*range.end()),
range.start().max(*range.end()),
)
}
+325
View File
@@ -0,0 +1,325 @@
//! Show popup windows, tooltips, context menus etc.
use crate::*;
// ----------------------------------------------------------------------------
/// Same state for all tooltips.
#[derive(Clone, Debug, Default)]
pub(crate) struct MonoState {
last_id: Option<Id>,
last_size: Vec<Vec2>,
}
impl MonoState {
fn load(ctx: &Context) -> Option<Self> {
ctx.data().get_temp(Id::null())
}
fn store(self, ctx: &Context) {
ctx.data().insert_temp(Id::null(), self);
}
fn tooltip_size(&self, id: Id, index: usize) -> Option<Vec2> {
if self.last_id == Some(id) {
self.last_size.get(index).cloned()
} else {
None
}
}
fn set_tooltip_size(&mut self, id: Id, index: usize, size: Vec2) {
if self.last_id == Some(id) {
if let Some(stored_size) = self.last_size.get_mut(index) {
*stored_size = size;
} else {
self.last_size
.extend((0..index - self.last_size.len()).map(|_| Vec2::ZERO));
self.last_size.push(size);
}
return;
}
self.last_id = Some(id);
self.last_size.clear();
self.last_size.extend((0..index).map(|_| Vec2::ZERO));
self.last_size.push(size);
}
}
// ----------------------------------------------------------------------------
/// Show a tooltip at the current pointer position (if any).
///
/// Most of the time it is easier to use [`Response::on_hover_ui`].
///
/// See also [`show_tooltip_text`].
///
/// Returns `None` if the tooltip could not be placed.
///
/// ```
/// # egui::__run_test_ui(|ui| {
/// if ui.ui_contains_pointer() {
/// egui::show_tooltip(ui.ctx(), egui::Id::new("my_tooltip"), |ui| {
/// ui.label("Helpful text");
/// });
/// }
/// # });
/// ```
pub fn show_tooltip<R>(
ctx: &Context,
id: Id,
add_contents: impl FnOnce(&mut Ui) -> R,
) -> Option<R> {
show_tooltip_at_pointer(ctx, id, add_contents)
}
/// Show a tooltip at the current pointer position (if any).
///
/// Most of the time it is easier to use [`Response::on_hover_ui`].
///
/// See also [`show_tooltip_text`].
///
/// Returns `None` if the tooltip could not be placed.
///
/// ```
/// # egui::__run_test_ui(|ui| {
/// if ui.ui_contains_pointer() {
/// egui::show_tooltip_at_pointer(ui.ctx(), egui::Id::new("my_tooltip"), |ui| {
/// ui.label("Helpful text");
/// });
/// }
/// # });
/// ```
pub fn show_tooltip_at_pointer<R>(
ctx: &Context,
id: Id,
add_contents: impl FnOnce(&mut Ui) -> R,
) -> Option<R> {
let suggested_pos = ctx
.input()
.pointer
.hover_pos()
.map(|pointer_pos| pointer_pos + vec2(16.0, 16.0));
show_tooltip_at(ctx, id, suggested_pos, add_contents)
}
/// Show a tooltip under the given area.
///
/// If the tooltip does not fit under the area, it tries to place it above it instead.
pub fn show_tooltip_for<R>(
ctx: &Context,
id: Id,
rect: &Rect,
add_contents: impl FnOnce(&mut Ui) -> R,
) -> Option<R> {
let expanded_rect = rect.expand2(vec2(2.0, 4.0));
let (above, position) = if ctx.input().any_touches() {
(true, expanded_rect.left_top())
} else {
(false, expanded_rect.left_bottom())
};
show_tooltip_at_avoid_dyn(
ctx,
id,
Some(position),
above,
expanded_rect,
Box::new(add_contents),
)
}
/// Show a tooltip at the given position.
///
/// Returns `None` if the tooltip could not be placed.
pub fn show_tooltip_at<R>(
ctx: &Context,
id: Id,
suggested_position: Option<Pos2>,
add_contents: impl FnOnce(&mut Ui) -> R,
) -> Option<R> {
let above = false;
show_tooltip_at_avoid_dyn(
ctx,
id,
suggested_position,
above,
Rect::NOTHING,
Box::new(add_contents),
)
}
fn show_tooltip_at_avoid_dyn<'c, R>(
ctx: &Context,
mut id: Id,
suggested_position: Option<Pos2>,
above: bool,
mut avoid_rect: Rect,
add_contents: Box<dyn FnOnce(&mut Ui) -> R + 'c>,
) -> Option<R> {
let mut tooltip_rect = Rect::NOTHING;
let mut count = 0;
let stored = ctx.frame_state().tooltip_rect;
let mut position = if let Some(stored) = stored {
// if there are multiple tooltips open they should use the same id for the `tooltip_size` caching to work.
id = stored.id;
tooltip_rect = stored.rect;
count = stored.count;
avoid_rect = avoid_rect.union(tooltip_rect);
if above {
tooltip_rect.left_top()
} else {
tooltip_rect.left_bottom()
}
} else if let Some(position) = suggested_position {
position
} else if ctx.memory().everything_is_visible() {
Pos2::ZERO
} else {
return None; // No good place for a tooltip :(
};
let mut state = MonoState::load(ctx).unwrap_or_default();
let expected_size = state.tooltip_size(id, count);
let expected_size = expected_size.unwrap_or_else(|| vec2(64.0, 32.0));
if above {
position.y -= expected_size.y;
}
position = position.at_most(ctx.input().screen_rect().max - expected_size);
// check if we intersect the avoid_rect
{
let new_rect = Rect::from_min_size(position, expected_size);
// Note: We do not use Rect::intersects() since it returns true even if the rects only touch.
if new_rect.shrink(1.0).intersects(avoid_rect) {
if above {
// place below instead:
position = avoid_rect.left_bottom();
} else {
// place above instead:
position = Pos2::new(position.x, avoid_rect.min.y - expected_size.y);
}
}
}
let position = position.at_least(ctx.input().screen_rect().min);
let InnerResponse { inner, response } = show_tooltip_area_dyn(ctx, id, position, add_contents);
state.set_tooltip_size(id, count, response.rect.size());
state.store(ctx);
ctx.frame_state().tooltip_rect = Some(crate::frame_state::TooltipRect {
id,
rect: tooltip_rect.union(response.rect),
count: count + 1,
});
Some(inner)
}
/// Show some text at the current pointer position (if any).
///
/// Most of the time it is easier to use [`Response::on_hover_text`].
///
/// See also [`show_tooltip`].
///
/// Returns `None` if the tooltip could not be placed.
///
/// ```
/// # egui::__run_test_ui(|ui| {
/// if ui.ui_contains_pointer() {
/// egui::show_tooltip_text(ui.ctx(), egui::Id::new("my_tooltip"), "Helpful text");
/// }
/// # });
/// ```
pub fn show_tooltip_text(ctx: &Context, id: Id, text: impl Into<WidgetText>) -> Option<()> {
show_tooltip(ctx, id, |ui| {
crate::widgets::Label::new(text).ui(ui);
})
}
/// Show a pop-over window.
fn show_tooltip_area_dyn<'c, R>(
ctx: &Context,
id: Id,
window_pos: Pos2,
add_contents: Box<dyn FnOnce(&mut Ui) -> R + 'c>,
) -> InnerResponse<R> {
use containers::*;
Area::new(id)
.order(Order::Tooltip)
.fixed_pos(window_pos)
.interactable(false)
.drag_bounds(Rect::EVERYTHING) // disable clip rect
.show(ctx, |ui| {
Frame::popup(&ctx.style())
.show(ui, |ui| {
ui.set_max_width(ui.spacing().tooltip_width);
add_contents(ui)
})
.inner
})
}
/// Shows a popup below another widget.
///
/// Useful for drop-down menus (combo boxes) or suggestion menus under text fields.
///
/// You must open the popup with [`Memory::open_popup`] or [`Memory::toggle_popup`].
///
/// Returns `None` if the popup is not open.
///
/// ```
/// # egui::__run_test_ui(|ui| {
/// let response = ui.button("Open popup");
/// let popup_id = ui.make_persistent_id("my_unique_id");
/// if response.clicked() {
/// ui.memory().toggle_popup(popup_id);
/// }
/// egui::popup::popup_below_widget(ui, popup_id, &response, |ui| {
/// ui.set_min_width(200.0); // if you want to control the size
/// ui.label("Some more info, or things you can select:");
/// ui.label("…");
/// });
/// # });
/// ```
pub fn popup_below_widget<R>(
ui: &Ui,
popup_id: Id,
widget_response: &Response,
add_contents: impl FnOnce(&mut Ui) -> R,
) -> Option<R> {
if ui.memory().is_popup_open(popup_id) {
let inner = Area::new(popup_id)
.order(Order::Foreground)
.fixed_pos(widget_response.rect.left_bottom())
.show(ui.ctx(), |ui| {
// Note: we use a separate clip-rect for this area, so the popup can be outside the parent.
// See https://github.com/emilk/egui/issues/825
let frame = Frame::popup(ui.style());
let frame_margin = frame.inner_margin + frame.outer_margin;
frame
.show(ui, |ui| {
ui.with_layout(Layout::top_down_justified(Align::LEFT), |ui| {
ui.set_width(widget_response.rect.width() - frame_margin.sum().x);
add_contents(ui)
})
.inner
})
.inner
})
.inner;
if ui.input().key_pressed(Key::Escape) || widget_response.clicked_elsewhere() {
ui.memory().close_popup();
}
Some(inner)
} else {
None
}
}
+351
View File
@@ -0,0 +1,351 @@
use crate::*;
#[derive(Clone, Copy, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub(crate) struct State {
/// This is the size that the user has picked by dragging the resize handles.
/// This may be smaller and/or larger than the actual size.
/// For instance, the user may have tried to shrink too much (not fitting the contents).
/// Or the user requested a large area, but the content don't need that much space.
pub(crate) desired_size: Vec2,
/// Actual size of content last frame
last_content_size: Vec2,
/// Externally requested size (e.g. by Window) for the next frame
pub(crate) requested_size: Option<Vec2>,
}
impl State {
pub fn load(ctx: &Context, id: Id) -> Option<Self> {
ctx.data().get_persisted(id)
}
pub fn store(self, ctx: &Context, id: Id) {
ctx.data().insert_persisted(id, self);
}
}
/// A region that can be resized by dragging the bottom right corner.
#[derive(Clone, Copy, Debug)]
#[must_use = "You should call .show()"]
pub struct Resize {
id: Option<Id>,
id_source: Option<Id>,
/// If false, we are no enabled
resizable: bool,
pub(crate) min_size: Vec2,
pub(crate) max_size: Vec2,
default_size: Vec2,
with_stroke: bool,
}
impl Default for Resize {
fn default() -> Self {
Self {
id: None,
id_source: None,
resizable: true,
min_size: Vec2::splat(16.0),
max_size: Vec2::splat(f32::INFINITY),
default_size: vec2(320.0, 128.0), // TODO(emilk): preferred size of [`Resize`] area.
with_stroke: true,
}
}
}
impl Resize {
/// Assign an explicit and globally unique id.
pub fn id(mut self, id: Id) -> Self {
self.id = Some(id);
self
}
/// A source for the unique [`Id`], e.g. `.id_source("second_resize_area")` or `.id_source(loop_index)`.
pub fn id_source(mut self, id_source: impl std::hash::Hash) -> Self {
self.id_source = Some(Id::new(id_source));
self
}
/// Preferred / suggested width. Actual width will depend on contents.
///
/// Examples:
/// * if the contents is text, this will decide where we break long lines.
/// * if the contents is a canvas, this decides the width of it,
/// * if the contents is some buttons, this is ignored and we will auto-size.
pub fn default_width(mut self, width: f32) -> Self {
self.default_size.x = width;
self
}
/// Preferred / suggested height. Actual height will depend on contents.
///
/// Examples:
/// * if the contents is a [`ScrollArea`] then this decides the maximum size.
/// * if the contents is a canvas, this decides the height of it,
/// * if the contents is text and buttons, then the `default_height` is ignored
/// and the height is picked automatically..
pub fn default_height(mut self, height: f32) -> Self {
self.default_size.y = height;
self
}
pub fn default_size(mut self, default_size: impl Into<Vec2>) -> Self {
self.default_size = default_size.into();
self
}
/// Won't shrink to smaller than this
pub fn min_size(mut self, min_size: impl Into<Vec2>) -> Self {
self.min_size = min_size.into();
self
}
/// Won't shrink to smaller than this
pub fn min_width(mut self, min_width: f32) -> Self {
self.min_size.x = min_width;
self
}
/// Won't shrink to smaller than this
pub fn min_height(mut self, min_height: f32) -> Self {
self.min_size.y = min_height;
self
}
/// Won't expand to larger than this
pub fn max_size(mut self, max_size: impl Into<Vec2>) -> Self {
self.max_size = max_size.into();
self
}
/// Can you resize it with the mouse?
/// Note that a window can still auto-resize
pub fn resizable(mut self, resizable: bool) -> Self {
self.resizable = resizable;
self
}
pub fn is_resizable(&self) -> bool {
self.resizable
}
/// Not manually resizable, just takes the size of its contents.
/// Text will not wrap, but will instead make your window width expand.
pub fn auto_sized(self) -> Self {
self.min_size(Vec2::ZERO)
.default_size(Vec2::splat(f32::INFINITY))
.resizable(false)
}
pub fn fixed_size(mut self, size: impl Into<Vec2>) -> Self {
let size = size.into();
self.default_size = size;
self.min_size = size;
self.max_size = size;
self.resizable = false;
self
}
pub fn with_stroke(mut self, with_stroke: bool) -> Self {
self.with_stroke = with_stroke;
self
}
}
struct Prepared {
id: Id,
state: State,
corner_response: Option<Response>,
content_ui: Ui,
}
impl Resize {
fn begin(&mut self, ui: &mut Ui) -> Prepared {
let position = ui.available_rect_before_wrap().min;
let id = self.id.unwrap_or_else(|| {
let id_source = self.id_source.unwrap_or_else(|| Id::new("resize"));
ui.make_persistent_id(id_source)
});
let mut state = State::load(ui.ctx(), id).unwrap_or_else(|| {
ui.ctx().request_repaint(); // counter frame delay
let default_size = self
.default_size
.at_least(self.min_size)
.at_most(self.max_size)
.at_most(
ui.input().screen_rect().size() - ui.spacing().window_margin.sum(), // hack for windows
);
State {
desired_size: default_size,
last_content_size: vec2(0.0, 0.0),
requested_size: None,
}
});
state.desired_size = state
.desired_size
.at_least(self.min_size)
.at_most(self.max_size);
let mut user_requested_size = state.requested_size.take();
let corner_response = if self.resizable {
// Resize-corner:
let corner_size = Vec2::splat(ui.visuals().resize_corner_size);
let corner_rect =
Rect::from_min_size(position + state.desired_size - corner_size, corner_size);
let corner_response = ui.interact(corner_rect, id.with("corner"), Sense::drag());
if let Some(pointer_pos) = corner_response.interact_pointer_pos() {
user_requested_size =
Some(pointer_pos - position + 0.5 * corner_response.rect.size());
}
Some(corner_response)
} else {
None
};
if let Some(user_requested_size) = user_requested_size {
state.desired_size = user_requested_size;
} else {
// We are not being actively resized, so auto-expand to include size of last frame.
// This prevents auto-shrinking if the contents contain width-filling widgets (separators etc)
// but it makes a lot of interactions with [`Window`]s nicer.
state.desired_size = state.desired_size.max(state.last_content_size);
}
state.desired_size = state
.desired_size
.at_least(self.min_size)
.at_most(self.max_size);
// ------------------------------
let inner_rect = Rect::from_min_size(position, state.desired_size);
let mut content_clip_rect = inner_rect.expand(ui.visuals().clip_rect_margin);
// If we pull the resize handle to shrink, we want to TRY to shrink it.
// After laying out the contents, we might be much bigger.
// In those cases we don't want the clip_rect to be smaller, because
// then we will clip the contents of the region even thought the result gets larger. This is simply ugly!
// So we use the memory of last_content_size to make the clip rect large enough.
content_clip_rect.max = content_clip_rect.max.max(
inner_rect.min + state.last_content_size + Vec2::splat(ui.visuals().clip_rect_margin),
);
content_clip_rect = content_clip_rect.intersect(ui.clip_rect()); // Respect parent region
let mut content_ui = ui.child_ui(inner_rect, *ui.layout());
content_ui.set_clip_rect(content_clip_rect);
Prepared {
id,
state,
corner_response,
content_ui,
}
}
pub fn show<R>(mut self, ui: &mut Ui, add_contents: impl FnOnce(&mut Ui) -> R) -> R {
let mut prepared = self.begin(ui);
let ret = add_contents(&mut prepared.content_ui);
self.end(ui, prepared);
ret
}
fn end(self, ui: &mut Ui, prepared: Prepared) {
let Prepared {
id,
mut state,
corner_response,
content_ui,
} = prepared;
state.last_content_size = content_ui.min_size();
// ------------------------------
let size = if self.with_stroke || self.resizable {
// We show how large we are,
// so we must follow the contents:
state.desired_size = state.desired_size.max(state.last_content_size);
// We are as large as we look
state.desired_size
} else {
// Probably a window.
state.last_content_size
};
ui.advance_cursor_after_rect(Rect::from_min_size(content_ui.min_rect().min, size));
// ------------------------------
if self.with_stroke && corner_response.is_some() {
let rect = Rect::from_min_size(content_ui.min_rect().left_top(), state.desired_size);
let rect = rect.expand(2.0); // breathing room for content
ui.painter().add(Shape::rect_stroke(
rect,
3.0,
ui.visuals().widgets.noninteractive.bg_stroke,
));
}
if let Some(corner_response) = corner_response {
paint_resize_corner(ui, &corner_response);
if corner_response.hovered() || corner_response.dragged() {
ui.ctx().output().cursor_icon = CursorIcon::ResizeNwSe;
}
}
state.store(ui.ctx(), id);
if ui.ctx().style().debug.show_resize {
ui.ctx().debug_painter().debug_rect(
Rect::from_min_size(content_ui.min_rect().left_top(), state.desired_size),
Color32::GREEN,
"desired_size",
);
ui.ctx().debug_painter().debug_rect(
Rect::from_min_size(content_ui.min_rect().left_top(), state.last_content_size),
Color32::LIGHT_BLUE,
"last_content_size",
);
}
}
}
use epaint::Stroke;
pub fn paint_resize_corner(ui: &mut Ui, response: &Response) {
let stroke = ui.style().interact(response).fg_stroke;
paint_resize_corner_with_style(ui, &response.rect, stroke, Align2::RIGHT_BOTTOM);
}
pub fn paint_resize_corner_with_style(ui: &mut Ui, rect: &Rect, stroke: Stroke, corner: Align2) {
let painter = ui.painter();
let cp = painter.round_pos_to_pixels(corner.pos_in_rect(rect));
let mut w = 2.0;
while w <= rect.width() && w <= rect.height() {
painter.line_segment(
[
pos2(cp.x - w * corner.x().to_sign(), cp.y),
pos2(cp.x, cp.y - w * corner.y().to_sign()),
],
stroke,
);
w += 4.0;
}
}
+850
View File
@@ -0,0 +1,850 @@
//! Coordinate system names:
//! * content: size of contents (generally large; that's why we want scroll bars)
//! * outer: size of scroll area including scroll bar(s)
//! * inner: excluding scroll bar(s). The area we clip the contents to.
#![allow(clippy::needless_range_loop)]
use crate::*;
#[derive(Clone, Copy, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(feature = "serde", serde(default))]
pub struct State {
/// Positive offset means scrolling down/right
pub offset: Vec2,
show_scroll: [bool; 2],
/// Momentum, used for kinetic scrolling
#[cfg_attr(feature = "serde", serde(skip))]
pub vel: Vec2,
/// Mouse offset relative to the top of the handle when started moving the handle.
scroll_start_offset_from_top_left: [Option<f32>; 2],
/// Is the scroll sticky. This is true while scroll handle is in the end position
/// and remains that way until the user moves the scroll_handle. Once unstuck (false)
/// it remains false until the scroll touches the end position, which reenables stickiness.
scroll_stuck_to_end: [bool; 2],
}
impl Default for State {
fn default() -> Self {
Self {
offset: Vec2::ZERO,
show_scroll: [false; 2],
vel: Vec2::ZERO,
scroll_start_offset_from_top_left: [None; 2],
scroll_stuck_to_end: [true; 2],
}
}
}
impl State {
pub fn load(ctx: &Context, id: Id) -> Option<Self> {
ctx.data().get_persisted(id)
}
pub fn store(self, ctx: &Context, id: Id) {
ctx.data().insert_persisted(id, self);
}
}
pub struct ScrollAreaOutput<R> {
/// What the user closure returned.
pub inner: R,
/// [`Id`] of the [`ScrollArea`].
pub id: Id,
/// The current state of the scroll area.
pub state: State,
/// Where on the screen the content is (excludes scroll bars).
pub inner_rect: Rect,
}
/// Add vertical and/or horizontal scrolling to a contained [`Ui`].
///
/// ```
/// # egui::__run_test_ui(|ui| {
/// egui::ScrollArea::vertical().show(ui, |ui| {
/// // Add a lot of widgets here.
/// });
/// # });
/// ```
///
/// You can scroll to an element using [`Response::scroll_to_me`], [`Ui::scroll_to_cursor`] and [`Ui::scroll_to_rect`].
#[derive(Clone, Debug)]
#[must_use = "You should call .show()"]
pub struct ScrollArea {
/// Do we have horizontal/vertical scrolling?
has_bar: [bool; 2],
auto_shrink: [bool; 2],
max_size: Vec2,
min_scrolled_size: Vec2,
always_show_scroll: bool,
id_source: Option<Id>,
offset_x: Option<f32>,
offset_y: Option<f32>,
/// If false, we ignore scroll events.
scrolling_enabled: bool,
/// If true for vertical or horizontal the scroll wheel will stick to the
/// end position until user manually changes position. It will become true
/// again once scroll handle makes contact with end.
stick_to_end: [bool; 2],
}
impl ScrollArea {
/// Create a horizontal scroll area.
pub fn horizontal() -> Self {
Self::new([true, false])
}
/// Create a vertical scroll area.
pub fn vertical() -> Self {
Self::new([false, true])
}
/// Create a bi-directional (horizontal and vertical) scroll area.
pub fn both() -> Self {
Self::new([true, true])
}
/// Create a scroll area where both direction of scrolling is disabled.
/// It's unclear why you would want to do this.
pub fn neither() -> Self {
Self::new([false, false])
}
/// Create a scroll area where you decide which axis has scrolling enabled.
/// For instance, `ScrollAre::new([true, false])` enable horizontal scrolling.
pub fn new(has_bar: [bool; 2]) -> Self {
Self {
has_bar,
auto_shrink: [true; 2],
max_size: Vec2::INFINITY,
min_scrolled_size: Vec2::splat(64.0),
always_show_scroll: false,
id_source: None,
offset_x: None,
offset_y: None,
scrolling_enabled: true,
stick_to_end: [false; 2],
}
}
/// The maximum width of the outer frame of the scroll area.
///
/// Use `f32::INFINITY` if you want the scroll area to expand to fit the surrounding [`Ui`] (default).
///
/// See also [`Self::auto_shrink`].
pub fn max_width(mut self, max_width: f32) -> Self {
self.max_size.x = max_width;
self
}
/// The maximum height of the outer frame of the scroll area.
///
/// Use `f32::INFINITY` if you want the scroll area to expand to fit the surrounding [`Ui`] (default).
///
/// See also [`Self::auto_shrink`].
pub fn max_height(mut self, max_height: f32) -> Self {
self.max_size.y = max_height;
self
}
/// The minimum width of a horizontal scroll area which requires scroll bars.
///
/// The [`ScrollArea`] will only become smaller than this if the content is smaller than this
/// (and so we don't require scroll bars).
///
/// Default: `64.0`.
pub fn min_scrolled_width(mut self, min_scrolled_width: f32) -> Self {
self.min_scrolled_size.x = min_scrolled_width;
self
}
/// The minimum height of a vertical scroll area which requires scroll bars.
///
/// The [`ScrollArea`] will only become smaller than this if the content is smaller than this
/// (and so we don't require scroll bars).
///
/// Default: `64.0`.
pub fn min_scrolled_height(mut self, min_scrolled_height: f32) -> Self {
self.min_scrolled_size.y = min_scrolled_height;
self
}
/// If `false` (default), the scroll bar will be hidden when not needed/
/// If `true`, the scroll bar will always be displayed even if not needed.
pub fn always_show_scroll(mut self, always_show_scroll: bool) -> Self {
self.always_show_scroll = always_show_scroll;
self
}
/// A source for the unique [`Id`], e.g. `.id_source("second_scroll_area")` or `.id_source(loop_index)`.
pub fn id_source(mut self, id_source: impl std::hash::Hash) -> Self {
self.id_source = Some(Id::new(id_source));
self
}
/// Set the horizontal and vertical scroll offset position.
///
/// See also: [`Self::vertical_scroll_offset`], [`Self::horizontal_scroll_offset`],
/// [`Ui::scroll_to_cursor`](crate::ui::Ui::scroll_to_cursor) and
/// [`Response::scroll_to_me`](crate::Response::scroll_to_me)
pub fn scroll_offset(mut self, offset: Vec2) -> Self {
self.offset_x = Some(offset.x);
self.offset_y = Some(offset.y);
self
}
/// Set the vertical scroll offset position.
///
/// See also: [`Self::scroll_offset`], [`Ui::scroll_to_cursor`](crate::ui::Ui::scroll_to_cursor) and
/// [`Response::scroll_to_me`](crate::Response::scroll_to_me)
pub fn vertical_scroll_offset(mut self, offset: f32) -> Self {
self.offset_y = Some(offset);
self
}
/// Set the horizontal scroll offset position.
///
/// See also: [`Self::scroll_offset`], [`Ui::scroll_to_cursor`](crate::ui::Ui::scroll_to_cursor) and
/// [`Response::scroll_to_me`](crate::Response::scroll_to_me)
pub fn horizontal_scroll_offset(mut self, offset: f32) -> Self {
self.offset_x = Some(offset);
self
}
/// Turn on/off scrolling on the horizontal axis.
pub fn hscroll(mut self, hscroll: bool) -> Self {
self.has_bar[0] = hscroll;
self
}
/// Turn on/off scrolling on the vertical axis.
pub fn vscroll(mut self, vscroll: bool) -> Self {
self.has_bar[1] = vscroll;
self
}
/// Turn on/off scrolling on the horizontal/vertical axes.
pub fn scroll2(mut self, has_bar: [bool; 2]) -> Self {
self.has_bar = has_bar;
self
}
/// Control the scrolling behavior
/// If `true` (default), the scroll area will respond to user scrolling
/// If `false`, the scroll area will not respond to user scrolling
///
/// This can be used, for example, to optionally freeze scrolling while the user
/// is inputing text in a [`TextEdit`] widget contained within the scroll area.
///
/// This controls both scrolling directions.
pub fn enable_scrolling(mut self, enable: bool) -> Self {
self.scrolling_enabled = enable;
self
}
/// For each axis, should the containing area shrink if the content is small?
///
/// If true, egui will add blank space outside the scroll area.
/// If false, egui will add blank space inside the scroll area.
///
/// Default: `[true; 2]`.
pub fn auto_shrink(mut self, auto_shrink: [bool; 2]) -> Self {
self.auto_shrink = auto_shrink;
self
}
pub(crate) fn has_any_bar(&self) -> bool {
self.has_bar[0] || self.has_bar[1]
}
/// The scroll handle will stick to the rightmost position even while the content size
/// changes dynamically. This can be useful to simulate text scrollers coming in from right
/// hand side. The scroll handle remains stuck until user manually changes position. Once "unstuck"
/// it will remain focused on whatever content viewport the user left it on. If the scroll
/// handle is dragged all the way to the right it will again become stuck and remain there
/// until manually pulled from the end position.
pub fn stick_to_right(mut self, stick: bool) -> Self {
self.stick_to_end[0] = stick;
self
}
/// The scroll handle will stick to the bottom position even while the content size
/// changes dynamically. This can be useful to simulate terminal UIs or log/info scrollers.
/// The scroll handle remains stuck until user manually changes position. Once "unstuck"
/// it will remain focused on whatever content viewport the user left it on. If the scroll
/// handle is dragged to the bottom it will again become stuck and remain there until manually
/// pulled from the end position.
pub fn stick_to_bottom(mut self, stick: bool) -> Self {
self.stick_to_end[1] = stick;
self
}
}
struct Prepared {
id: Id,
state: State,
has_bar: [bool; 2],
auto_shrink: [bool; 2],
/// How much horizontal and vertical space are used up by the
/// width of the vertical bar, and the height of the horizontal bar?
current_bar_use: Vec2,
always_show_scroll: bool,
/// Where on the screen the content is (excludes scroll bars).
inner_rect: Rect,
content_ui: Ui,
/// Relative coordinates: the offset and size of the view of the inner UI.
/// `viewport.min == ZERO` means we scrolled to the top.
viewport: Rect,
scrolling_enabled: bool,
stick_to_end: [bool; 2],
}
impl ScrollArea {
fn begin(self, ui: &mut Ui) -> Prepared {
let Self {
has_bar,
auto_shrink,
max_size,
min_scrolled_size,
always_show_scroll,
id_source,
offset_x,
offset_y,
scrolling_enabled,
stick_to_end,
} = self;
let ctx = ui.ctx().clone();
let id_source = id_source.unwrap_or_else(|| Id::new("scroll_area"));
let id = ui.make_persistent_id(id_source);
ui.ctx().check_for_id_clash(
id,
Rect::from_min_size(ui.available_rect_before_wrap().min, Vec2::ZERO),
"ScrollArea",
);
let mut state = State::load(&ctx, id).unwrap_or_default();
state.offset.x = offset_x.unwrap_or(state.offset.x);
state.offset.y = offset_y.unwrap_or(state.offset.y);
let max_scroll_bar_width = max_scroll_bar_width_with_margin(ui);
let current_hscroll_bar_height = if !has_bar[0] {
0.0
} else if always_show_scroll {
max_scroll_bar_width
} else {
max_scroll_bar_width * ui.ctx().animate_bool(id.with("h"), state.show_scroll[0])
};
let current_vscroll_bar_width = if !has_bar[1] {
0.0
} else if always_show_scroll {
max_scroll_bar_width
} else {
max_scroll_bar_width * ui.ctx().animate_bool(id.with("v"), state.show_scroll[1])
};
let current_bar_use = vec2(current_vscroll_bar_width, current_hscroll_bar_height);
let available_outer = ui.available_rect_before_wrap();
let outer_size = available_outer.size().at_most(max_size);
let inner_size = {
let mut inner_size = outer_size - current_bar_use;
// Don't go so far that we shrink to zero.
// In particular, if we put a [`ScrollArea`] inside of a [`ScrollArea`], the inner
// one shouldn't collapse into nothingness.
// See https://github.com/emilk/egui/issues/1097
for d in 0..2 {
if has_bar[d] {
inner_size[d] = inner_size[d].max(min_scrolled_size[d]);
}
}
inner_size
};
let inner_rect = Rect::from_min_size(available_outer.min, inner_size);
let mut content_max_size = inner_size;
if true {
// Tell the inner Ui to *try* to fit the content without needing to scroll,
// i.e. better to wrap text and shrink images than showing a horizontal scrollbar!
} else {
// Tell the inner Ui to use as much space as possible, we can scroll to see it!
for d in 0..2 {
if has_bar[d] {
content_max_size[d] = f32::INFINITY;
}
}
}
let content_max_rect = Rect::from_min_size(inner_rect.min - state.offset, content_max_size);
let mut content_ui = ui.child_ui(content_max_rect, *ui.layout());
let mut content_clip_rect = inner_rect.expand(ui.visuals().clip_rect_margin);
content_clip_rect = content_clip_rect.intersect(ui.clip_rect());
// Nice handling of forced resizing beyond the possible:
for d in 0..2 {
if !has_bar[d] {
content_clip_rect.max[d] = ui.clip_rect().max[d] - current_bar_use[d];
}
}
content_ui.set_clip_rect(content_clip_rect);
let viewport = Rect::from_min_size(Pos2::ZERO + state.offset, inner_size);
Prepared {
id,
state,
has_bar,
auto_shrink,
current_bar_use,
always_show_scroll,
inner_rect,
content_ui,
viewport,
scrolling_enabled,
stick_to_end,
}
}
/// Show the [`ScrollArea`], and add the contents to the viewport.
///
/// If the inner area can be very long, consider using [`Self::show_rows`] instead.
pub fn show<R>(
self,
ui: &mut Ui,
add_contents: impl FnOnce(&mut Ui) -> R,
) -> ScrollAreaOutput<R> {
self.show_viewport_dyn(ui, Box::new(|ui, _viewport| add_contents(ui)))
}
/// Efficiently show only the visible part of a large number of rows.
///
/// ```
/// # egui::__run_test_ui(|ui| {
/// let text_style = egui::TextStyle::Body;
/// let row_height = ui.text_style_height(&text_style);
/// // let row_height = ui.spacing().interact_size.y; // if you are adding buttons instead of labels.
/// let total_rows = 10_000;
/// egui::ScrollArea::vertical().show_rows(ui, row_height, total_rows, |ui, row_range| {
/// for row in row_range {
/// let text = format!("Row {}/{}", row + 1, total_rows);
/// ui.label(text);
/// }
/// });
/// # });
/// ```
pub fn show_rows<R>(
self,
ui: &mut Ui,
row_height_sans_spacing: f32,
total_rows: usize,
add_contents: impl FnOnce(&mut Ui, std::ops::Range<usize>) -> R,
) -> ScrollAreaOutput<R> {
let spacing = ui.spacing().item_spacing;
let row_height_with_spacing = row_height_sans_spacing + spacing.y;
self.show_viewport(ui, |ui, viewport| {
ui.set_height((row_height_with_spacing * total_rows as f32 - spacing.y).at_least(0.0));
let min_row = (viewport.min.y / row_height_with_spacing).floor() as usize;
let max_row = (viewport.max.y / row_height_with_spacing).ceil() as usize + 1;
let max_row = max_row.at_most(total_rows);
let y_min = ui.max_rect().top() + min_row as f32 * row_height_with_spacing;
let y_max = ui.max_rect().top() + max_row as f32 * row_height_with_spacing;
let rect = Rect::from_x_y_ranges(ui.max_rect().x_range(), y_min..=y_max);
ui.allocate_ui_at_rect(rect, |viewport_ui| {
viewport_ui.skip_ahead_auto_ids(min_row); // Make sure we get consistent IDs.
add_contents(viewport_ui, min_row..max_row)
})
.inner
})
}
/// This can be used to only paint the visible part of the contents.
///
/// `add_contents` is past the viewport, which is the relative view of the content.
/// So if the passed rect has min = zero, then show the top left content (the user has not scrolled).
pub fn show_viewport<R>(
self,
ui: &mut Ui,
add_contents: impl FnOnce(&mut Ui, Rect) -> R,
) -> ScrollAreaOutput<R> {
self.show_viewport_dyn(ui, Box::new(add_contents))
}
fn show_viewport_dyn<'c, R>(
self,
ui: &mut Ui,
add_contents: Box<dyn FnOnce(&mut Ui, Rect) -> R + 'c>,
) -> ScrollAreaOutput<R> {
let mut prepared = self.begin(ui);
let id = prepared.id;
let inner_rect = prepared.inner_rect;
let inner = add_contents(&mut prepared.content_ui, prepared.viewport);
let state = prepared.end(ui);
ScrollAreaOutput {
inner,
id,
state,
inner_rect,
}
}
}
impl Prepared {
fn end(self, ui: &mut Ui) -> State {
let Prepared {
id,
mut state,
inner_rect,
has_bar,
auto_shrink,
mut current_bar_use,
always_show_scroll,
content_ui,
viewport: _,
scrolling_enabled,
stick_to_end,
} = self;
let content_size = content_ui.min_size();
for d in 0..2 {
if has_bar[d] {
// We take the scroll target so only this ScrollArea will use it:
let scroll_target = content_ui.ctx().frame_state().scroll_target[d].take();
if let Some((scroll, align)) = scroll_target {
let min = content_ui.min_rect().min[d];
let clip_rect = content_ui.clip_rect();
let visible_range = min..=min + clip_rect.size()[d];
let start = *scroll.start();
let end = *scroll.end();
let clip_start = clip_rect.min[d];
let clip_end = clip_rect.max[d];
let mut spacing = ui.spacing().item_spacing[d];
let delta = if let Some(align) = align {
let center_factor = align.to_factor();
let offset =
lerp(scroll, center_factor) - lerp(visible_range, center_factor);
// Depending on the alignment we need to add or subtract the spacing
spacing *= remap(center_factor, 0.0..=1.0, -1.0..=1.0);
offset + spacing - state.offset[d]
} else if start < clip_start && end < clip_end {
-(clip_start - start + spacing).min(clip_end - end - spacing)
} else if end > clip_end && start > clip_start {
(end - clip_end + spacing).min(start - clip_start - spacing)
} else {
// Ui is already in view, no need to adjust scroll.
0.0
};
if delta != 0.0 {
state.offset[d] += delta;
ui.ctx().request_repaint();
}
}
}
}
let inner_rect = {
// At this point this is the available size for the inner rect.
let mut inner_size = inner_rect.size();
for d in 0..2 {
inner_size[d] = match (has_bar[d], auto_shrink[d]) {
(true, true) => inner_size[d].min(content_size[d]), // shrink scroll area if content is small
(true, false) => inner_size[d], // let scroll area be larger than content; fill with blank space
(false, true) => content_size[d], // Follow the content (expand/contract to fit it).
(false, false) => inner_size[d].max(content_size[d]), // Expand to fit content
};
}
let mut inner_rect = Rect::from_min_size(inner_rect.min, inner_size);
// The window that egui sits in can't be expanded by egui, so we need to respect it:
for d in 0..2 {
if !has_bar[d] {
// HACK for when we have a vertical-only scroll area in a top level panel,
// and that panel is not wide enough for the contents.
// This code ensures we still see the scroll bar!
let max = ui.input().screen_rect().max[d]
- current_bar_use[d]
- ui.spacing().item_spacing[d];
inner_rect.max[d] = inner_rect.max[d].at_most(max);
// TODO(emilk): maybe auto-enable horizontal/vertical scrolling if this limit is reached
}
}
inner_rect
};
let outer_rect = Rect::from_min_size(inner_rect.min, inner_rect.size() + current_bar_use);
let content_is_too_large = [
content_size.x > inner_rect.width(),
content_size.y > inner_rect.height(),
];
if content_is_too_large[0] || content_is_too_large[1] {
// Drag contents to scroll (for touch screens mostly):
let sense = if self.scrolling_enabled {
Sense::drag()
} else {
Sense::hover()
};
let content_response = ui.interact(inner_rect, id.with("area"), sense);
if content_response.dragged() {
for d in 0..2 {
if has_bar[d] {
state.offset[d] -= ui.input().pointer.delta()[d];
state.vel[d] = ui.input().pointer.velocity()[d];
state.scroll_stuck_to_end[d] = false;
} else {
state.vel[d] = 0.0;
}
}
} else {
let stop_speed = 20.0; // Pixels per second.
let friction_coeff = 1000.0; // Pixels per second squared.
let dt = ui.input().unstable_dt;
let friction = friction_coeff * dt;
if friction > state.vel.length() || state.vel.length() < stop_speed {
state.vel = Vec2::ZERO;
} else {
state.vel -= friction * state.vel.normalized();
// Offset has an inverted coordinate system compared to
// the velocity, so we subtract it instead of adding it
state.offset -= state.vel * dt;
ui.ctx().request_repaint();
}
}
}
let max_offset = content_size - inner_rect.size();
if scrolling_enabled && ui.rect_contains_pointer(outer_rect) {
for d in 0..2 {
if has_bar[d] {
let mut frame_state = ui.ctx().frame_state();
let scroll_delta = frame_state.scroll_delta;
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;
if scrolling_up || scrolling_down {
state.offset[d] -= scroll_delta[d];
// Clear scroll delta so no parent scroll will use it.
frame_state.scroll_delta[d] = 0.0;
state.scroll_stuck_to_end[d] = false;
}
}
}
}
let show_scroll_this_frame = [
content_is_too_large[0] || always_show_scroll,
content_is_too_large[1] || always_show_scroll,
];
let max_scroll_bar_width = max_scroll_bar_width_with_margin(ui);
// Avoid frame delay; start showing scroll bar right away:
if show_scroll_this_frame[0] && current_bar_use.y <= 0.0 {
current_bar_use.y = max_scroll_bar_width * ui.ctx().animate_bool(id.with("h"), true);
}
if show_scroll_this_frame[1] && current_bar_use.x <= 0.0 {
current_bar_use.x = max_scroll_bar_width * ui.ctx().animate_bool(id.with("v"), true);
}
for d in 0..2 {
let animation_t = current_bar_use[1 - d] / max_scroll_bar_width;
if animation_t == 0.0 {
continue;
}
// margin between contents and scroll bar
let margin = animation_t * ui.spacing().item_spacing.x;
let min_cross = inner_rect.max[1 - d] + margin; // left of vertical scroll (d == 1)
let max_cross = outer_rect.max[1 - d]; // right of vertical scroll (d == 1)
let min_main = inner_rect.min[d]; // top of vertical scroll (d == 1)
let max_main = inner_rect.max[d]; // bottom of vertical scroll (d == 1)
let outer_scroll_rect = if d == 0 {
Rect::from_min_max(
pos2(inner_rect.left(), min_cross),
pos2(inner_rect.right(), max_cross),
)
} else {
Rect::from_min_max(
pos2(min_cross, inner_rect.top()),
pos2(max_cross, inner_rect.bottom()),
)
};
// maybe force increase in offset to keep scroll stuck to end position
if stick_to_end[d] && state.scroll_stuck_to_end[d] {
state.offset[d] = content_size[d] - inner_rect.size()[d];
}
let from_content =
|content| remap_clamp(content, 0.0..=content_size[d], min_main..=max_main);
let handle_rect = if d == 0 {
Rect::from_min_max(
pos2(from_content(state.offset.x), min_cross),
pos2(from_content(state.offset.x + inner_rect.width()), max_cross),
)
} else {
Rect::from_min_max(
pos2(min_cross, from_content(state.offset.y)),
pos2(
max_cross,
from_content(state.offset.y + inner_rect.height()),
),
)
};
let interact_id = id.with(d);
let sense = if self.scrolling_enabled {
Sense::click_and_drag()
} else {
Sense::hover()
};
let response = ui.interact(outer_scroll_rect, interact_id, sense);
if let Some(pointer_pos) = response.interact_pointer_pos() {
let scroll_start_offset_from_top_left = state.scroll_start_offset_from_top_left[d]
.get_or_insert_with(|| {
if handle_rect.contains(pointer_pos) {
pointer_pos[d] - handle_rect.min[d]
} else {
let handle_top_pos_at_bottom = max_main - handle_rect.size()[d];
// Calculate the new handle top position, centering the handle on the mouse.
let new_handle_top_pos = (pointer_pos[d] - handle_rect.size()[d] / 2.0)
.clamp(min_main, handle_top_pos_at_bottom);
pointer_pos[d] - new_handle_top_pos
}
});
let new_handle_top = pointer_pos[d] - *scroll_start_offset_from_top_left;
state.offset[d] = remap(new_handle_top, min_main..=max_main, 0.0..=content_size[d]);
// some manual action taken, scroll not stuck
state.scroll_stuck_to_end[d] = false;
} else {
state.scroll_start_offset_from_top_left[d] = None;
}
let unbounded_offset = state.offset[d];
state.offset[d] = state.offset[d].max(0.0);
state.offset[d] = state.offset[d].min(max_offset[d]);
if state.offset[d] != unbounded_offset {
state.vel[d] = 0.0;
}
if ui.is_rect_visible(outer_scroll_rect) {
// Avoid frame-delay by calculating a new handle rect:
let mut handle_rect = if d == 0 {
Rect::from_min_max(
pos2(from_content(state.offset.x), min_cross),
pos2(from_content(state.offset.x + inner_rect.width()), max_cross),
)
} else {
Rect::from_min_max(
pos2(min_cross, from_content(state.offset.y)),
pos2(
max_cross,
from_content(state.offset.y + inner_rect.height()),
),
)
};
let min_handle_size = ui.spacing().scroll_bar_width;
if handle_rect.size()[d] < min_handle_size {
handle_rect = Rect::from_center_size(
handle_rect.center(),
if d == 0 {
vec2(min_handle_size, handle_rect.size().y)
} else {
vec2(handle_rect.size().x, min_handle_size)
},
);
}
let visuals = if scrolling_enabled {
ui.style().interact(&response)
} else {
&ui.style().visuals.widgets.inactive
};
ui.painter().add(epaint::Shape::rect_filled(
outer_scroll_rect,
visuals.rounding,
ui.visuals().extreme_bg_color,
));
ui.painter().add(epaint::Shape::rect_filled(
handle_rect,
visuals.rounding,
visuals.bg_fill,
));
}
}
ui.advance_cursor_after_rect(outer_rect);
if show_scroll_this_frame != state.show_scroll {
ui.ctx().request_repaint();
}
let available_offset = content_size - inner_rect.size();
state.offset = state.offset.min(available_offset);
state.offset = state.offset.max(Vec2::ZERO);
// Is scroll handle at end of content, or is there no scrollbar
// yet (not enough content), but sticking is requested? If so, enter sticky mode.
// Only has an effect if stick_to_end is enabled but we save in
// state anyway so that entering sticky mode at an arbitrary time
// has appropriate effect.
state.scroll_stuck_to_end = [
(state.offset[0] == available_offset[0])
|| (self.stick_to_end[0] && available_offset[0] < 0.),
(state.offset[1] == available_offset[1])
|| (self.stick_to_end[1] && available_offset[1] < 0.),
];
state.show_scroll = show_scroll_this_frame;
state.store(ui.ctx(), id);
state
}
}
/// Width of a vertical scrollbar, or height of a horizontal scroll bar
fn max_scroll_bar_width_with_margin(ui: &Ui) -> f32 {
ui.spacing().item_spacing.x + ui.spacing().scroll_bar_width
}
+934
View File
@@ -0,0 +1,934 @@
// WARNING: the code in here is horrible. It is a behemoth that needs breaking up into simpler parts.
use crate::collapsing_header::CollapsingState;
use crate::{widget_text::WidgetTextGalley, *};
use epaint::*;
use super::*;
/// Builder for a floating window which can be dragged, closed, collapsed, resized and scrolled (off by default).
///
/// You can customize:
/// * title
/// * default, minimum, maximum and/or fixed size
/// * if the window has a scroll area (off by default)
/// * if the window can be collapsed (minimized) to just the title bar (yes, by default)
/// * if there should be a close button (none by default)
///
/// ```
/// # egui::__run_test_ctx(|ctx| {
/// egui::Window::new("My Window").show(ctx, |ui| {
/// ui.label("Hello World!");
/// });
/// # });
#[must_use = "You should call .show()"]
pub struct Window<'open> {
title: WidgetText,
open: Option<&'open mut bool>,
area: Area,
frame: Option<Frame>,
resize: Resize,
scroll: ScrollArea,
collapsible: bool,
with_title_bar: bool,
}
impl<'open> Window<'open> {
/// The window title is used as a unique [`Id`] and must be unique, and should not change.
/// This is true even if you disable the title bar with `.title_bar(false)`.
/// If you need a changing title, you must call `window.id(…)` with a fixed id.
pub fn new(title: impl Into<WidgetText>) -> Self {
let title = title.into().fallback_text_style(TextStyle::Heading);
let area = Area::new(title.text());
Self {
title,
open: None,
area,
frame: None,
resize: Resize::default()
.with_stroke(false)
.min_size([96.0, 32.0])
.default_size([340.0, 420.0]), // Default inner size of a window
scroll: ScrollArea::neither(),
collapsible: true,
with_title_bar: true,
}
}
/// Assign a unique id to the Window. Required if the title changes, or is shared with another window.
pub fn id(mut self, id: Id) -> Self {
self.area = self.area.id(id);
self
}
/// Call this to add a close-button to the window title bar.
///
/// * If `*open == false`, the window will not be visible.
/// * If `*open == true`, the window will have a close button.
/// * If the close button is pressed, `*open` will be set to `false`.
pub fn open(mut self, open: &'open mut bool) -> Self {
self.open = Some(open);
self
}
/// If `false` the window will be grayed out and non-interactive.
pub fn enabled(mut self, enabled: bool) -> Self {
self.area = self.area.enabled(enabled);
self
}
/// Usage: `Window::new(…).mutate(|w| w.resize = w.resize.auto_expand_width(true))`
/// Not sure this is a good interface for this.
pub fn mutate(mut self, mutate: impl Fn(&mut Self)) -> Self {
mutate(&mut self);
self
}
/// Usage: `Window::new(…).resize(|r| r.auto_expand_width(true))`
/// Not sure this is a good interface for this.
pub fn resize(mut self, mutate: impl Fn(Resize) -> Resize) -> Self {
self.resize = mutate(self.resize);
self
}
/// Change the background color, margins, etc.
pub fn frame(mut self, frame: Frame) -> Self {
self.frame = Some(frame);
self
}
/// Set minimum width of the window.
pub fn min_width(mut self, min_width: f32) -> Self {
self.resize = self.resize.min_width(min_width);
self
}
/// Set minimum height of the window.
pub fn min_height(mut self, min_height: f32) -> Self {
self.resize = self.resize.min_height(min_height);
self
}
/// Set current position of the window.
/// If the window is movable it is up to you to keep track of where it moved to!
pub fn current_pos(mut self, current_pos: impl Into<Pos2>) -> Self {
self.area = self.area.current_pos(current_pos);
self
}
/// Set initial position of the window.
pub fn default_pos(mut self, default_pos: impl Into<Pos2>) -> Self {
self.area = self.area.default_pos(default_pos);
self
}
/// Set anchor and distance.
///
/// An anchor of `Align2::RIGHT_TOP` means "put the right-top corner of the window
/// in the right-top corner of the screen".
///
/// The offset is added to the position, so e.g. an offset of `[-5.0, 5.0]`
/// would move the window left and down from the given anchor.
///
/// Anchoring also makes the window immovable.
///
/// It is an error to set both an anchor and a position.
pub fn anchor(mut self, align: Align2, offset: impl Into<Vec2>) -> Self {
self.area = self.area.anchor(align, offset);
self
}
/// Set initial size of the window.
pub fn default_size(mut self, default_size: impl Into<Vec2>) -> Self {
self.resize = self.resize.default_size(default_size);
self
}
/// Set initial width of the window.
pub fn default_width(mut self, default_width: f32) -> Self {
self.resize = self.resize.default_width(default_width);
self
}
/// Set initial height of the window.
pub fn default_height(mut self, default_height: f32) -> Self {
self.resize = self.resize.default_height(default_height);
self
}
/// Set initial position and size of the window.
pub fn default_rect(self, rect: Rect) -> Self {
self.default_pos(rect.min).default_size(rect.size())
}
/// Sets the window position and prevents it from being dragged around.
pub fn fixed_pos(mut self, pos: impl Into<Pos2>) -> Self {
self.area = self.area.fixed_pos(pos);
self
}
/// Sets the window size and prevents it from being resized by dragging its edges.
pub fn fixed_size(mut self, size: impl Into<Vec2>) -> Self {
self.resize = self.resize.fixed_size(size);
self
}
/// Sets the window pos and size and prevents it from being moved and resized by dragging its edges.
pub fn fixed_rect(self, rect: Rect) -> Self {
self.fixed_pos(rect.min).fixed_size(rect.size())
}
/// Can the user resize the window by dragging its edges?
/// Note that even if you set this to `false` the window may still auto-resize.
pub fn resizable(mut self, resizable: bool) -> Self {
self.resize = self.resize.resizable(resizable);
self
}
/// Can the window be collapsed by clicking on its title?
pub fn collapsible(mut self, collapsible: bool) -> Self {
self.collapsible = collapsible;
self
}
/// Show title bar on top of the window?
/// If `false`, the window will not be collapsible nor have a close-button.
pub fn title_bar(mut self, title_bar: bool) -> Self {
self.with_title_bar = title_bar;
self
}
/// Not resizable, just takes the size of its contents.
/// Also disabled scrolling.
/// Text will not wrap, but will instead make your window width expand.
pub fn auto_sized(mut self) -> Self {
self.resize = self.resize.auto_sized();
self.scroll = ScrollArea::neither();
self
}
/// Enable/disable horizontal/vertical scrolling. `false` by default.
pub fn scroll2(mut self, scroll: [bool; 2]) -> Self {
self.scroll = self.scroll.scroll2(scroll);
self
}
/// Enable/disable horizontal scrolling. `false` by default.
pub fn hscroll(mut self, hscroll: bool) -> Self {
self.scroll = self.scroll.hscroll(hscroll);
self
}
/// Enable/disable vertical scrolling. `false` by default.
pub fn vscroll(mut self, vscroll: bool) -> Self {
self.scroll = self.scroll.vscroll(vscroll);
self
}
/// Constrain the area up to which the window can be dragged.
pub fn drag_bounds(mut self, bounds: Rect) -> Self {
self.area = self.area.drag_bounds(bounds);
self
}
}
impl<'open> Window<'open> {
/// Returns `None` if the window is not open (if [`Window::open`] was called with `&mut false`).
/// Returns `Some(InnerResponse { inner: None })` if the window is collapsed.
#[inline]
pub fn show<R>(
self,
ctx: &Context,
add_contents: impl FnOnce(&mut Ui) -> R,
) -> Option<InnerResponse<Option<R>>> {
self.show_dyn(ctx, Box::new(add_contents))
}
fn show_dyn<'c, R>(
self,
ctx: &Context,
add_contents: Box<dyn FnOnce(&mut Ui) -> R + 'c>,
) -> Option<InnerResponse<Option<R>>> {
let Window {
title,
open,
area,
frame,
resize,
scroll,
collapsible,
with_title_bar,
} = self;
let frame = frame.unwrap_or_else(|| Frame::window(&ctx.style()));
let is_open = !matches!(open, Some(false)) || ctx.memory().everything_is_visible();
area.show_open_close_animation(ctx, &frame, is_open);
if !is_open {
return None;
}
let area_id = area.id;
let area_layer_id = area.layer();
let resize_id = area_id.with("resize");
let mut collapsing =
CollapsingState::load_with_default_open(ctx, area_id.with("collapsing"), true);
let is_collapsed = with_title_bar && !collapsing.is_open();
let possible = PossibleInteractions::new(&area, &resize, is_collapsed);
let area = area.movable(false); // We move it manually, or the area will move the window when we want to resize it
let resize = resize.resizable(false); // We move it manually
let mut resize = resize.id(resize_id);
let mut area = area.begin(ctx);
let title_content_spacing = 2.0 * ctx.style().spacing.item_spacing.y;
// First interact (move etc) to avoid frame delay:
let last_frame_outer_rect = area.state().rect();
let interaction = if possible.movable || possible.resizable() {
window_interaction(
ctx,
possible,
area_layer_id,
area_id.with("frame_resize"),
last_frame_outer_rect,
)
.and_then(|window_interaction| {
// Calculate roughly how much larger the window size is compared to the inner rect
let title_bar_height = if with_title_bar {
let style = ctx.style();
title.font_height(&ctx.fonts(), &style) + title_content_spacing
} else {
0.0
};
let margins = frame.outer_margin.sum()
+ frame.inner_margin.sum()
+ vec2(0.0, title_bar_height);
interact(
window_interaction,
ctx,
margins,
area_layer_id,
&mut area,
resize_id,
)
})
} else {
None
};
let hover_interaction = resize_hover(ctx, possible, area_layer_id, last_frame_outer_rect);
let mut area_content_ui = area.content_ui(ctx);
let content_inner = {
// BEGIN FRAME --------------------------------
let frame_stroke = frame.stroke;
let mut frame = frame.begin(&mut area_content_ui);
let show_close_button = open.is_some();
let title_bar = if with_title_bar {
let title_bar = show_title_bar(
&mut frame.content_ui,
title,
show_close_button,
&mut collapsing,
collapsible,
);
resize.min_size.x = resize.min_size.x.at_least(title_bar.rect.width()); // Prevent making window smaller than title bar width
Some(title_bar)
} else {
None
};
let (content_inner, content_response) = collapsing
.show_body_unindented(&mut frame.content_ui, |ui| {
resize.show(ui, |ui| {
if title_bar.is_some() {
ui.add_space(title_content_spacing);
}
if scroll.has_any_bar() {
scroll.show(ui, add_contents).inner
} else {
add_contents(ui)
}
})
})
.map_or((None, None), |ir| (Some(ir.inner), Some(ir.response)));
let outer_rect = frame.end(&mut area_content_ui).rect;
paint_resize_corner(&mut area_content_ui, &possible, outer_rect, frame_stroke);
// END FRAME --------------------------------
if let Some(title_bar) = title_bar {
title_bar.ui(
&mut area_content_ui,
outer_rect,
&content_response,
open,
&mut collapsing,
collapsible,
);
}
collapsing.store(ctx);
if let Some(interaction) = interaction {
paint_frame_interaction(
&mut area_content_ui,
outer_rect,
interaction,
ctx.style().visuals.widgets.active,
);
} else if let Some(hover_interaction) = hover_interaction {
if ctx.input().pointer.has_pointer() {
paint_frame_interaction(
&mut area_content_ui,
outer_rect,
hover_interaction,
ctx.style().visuals.widgets.hovered,
);
}
}
content_inner
};
area.state_mut().pos = ctx
.constrain_window_rect_to_area(area.state().rect(), area.drag_bounds())
.min;
let full_response = area.end(ctx, area_content_ui);
let inner_response = InnerResponse {
inner: content_inner,
response: full_response,
};
Some(inner_response)
}
}
fn paint_resize_corner(
ui: &mut Ui,
possible: &PossibleInteractions,
outer_rect: Rect,
stroke: Stroke,
) {
let corner = if possible.resize_right && possible.resize_bottom {
Align2::RIGHT_BOTTOM
} else if possible.resize_left && possible.resize_bottom {
Align2::LEFT_BOTTOM
} else if possible.resize_left && possible.resize_top {
Align2::LEFT_TOP
} else if possible.resize_right && possible.resize_top {
Align2::RIGHT_TOP
} else {
return;
};
let corner_size = Vec2::splat(ui.visuals().resize_corner_size);
let corner_rect = corner.align_size_within_rect(corner_size, outer_rect);
let corner_rect = corner_rect.translate(-2.0 * corner.to_sign()); // move away from corner
crate::resize::paint_resize_corner_with_style(ui, &corner_rect, stroke, corner);
}
// ----------------------------------------------------------------------------
#[derive(Clone, Copy, Debug)]
struct PossibleInteractions {
movable: bool,
// Which sides can we drag to resize?
resize_left: bool,
resize_right: bool,
resize_top: bool,
resize_bottom: bool,
}
impl PossibleInteractions {
fn new(area: &Area, resize: &Resize, is_collapsed: bool) -> Self {
let movable = area.is_enabled() && area.is_movable();
let resizable = area.is_enabled() && resize.is_resizable() && !is_collapsed;
let pivot = area.get_pivot();
Self {
movable,
resize_left: resizable && (movable || pivot.x() != Align::LEFT),
resize_right: resizable && (movable || pivot.x() != Align::RIGHT),
resize_top: resizable && (movable || pivot.y() != Align::TOP),
resize_bottom: resizable && (movable || pivot.y() != Align::BOTTOM),
}
}
pub fn resizable(&self) -> bool {
self.resize_left || self.resize_right || self.resize_top || self.resize_bottom
}
}
/// Either a move or resize
#[derive(Clone, Copy, Debug)]
pub(crate) struct WindowInteraction {
pub(crate) area_layer_id: LayerId,
pub(crate) start_rect: Rect,
pub(crate) left: bool,
pub(crate) right: bool,
pub(crate) top: bool,
pub(crate) bottom: bool,
}
impl WindowInteraction {
pub fn set_cursor(&self, ctx: &Context) {
if (self.left && self.top) || (self.right && self.bottom) {
ctx.output().cursor_icon = CursorIcon::ResizeNwSe;
} else if (self.right && self.top) || (self.left && self.bottom) {
ctx.output().cursor_icon = CursorIcon::ResizeNeSw;
} else if self.left || self.right {
ctx.output().cursor_icon = CursorIcon::ResizeHorizontal;
} else if self.bottom || self.top {
ctx.output().cursor_icon = CursorIcon::ResizeVertical;
}
}
pub fn is_resize(&self) -> bool {
self.left || self.right || self.top || self.bottom
}
}
fn interact(
window_interaction: WindowInteraction,
ctx: &Context,
margins: Vec2,
area_layer_id: LayerId,
area: &mut area::Prepared,
resize_id: Id,
) -> Option<WindowInteraction> {
let new_rect = move_and_resize_window(ctx, &window_interaction)?;
let new_rect = ctx.round_rect_to_pixels(new_rect);
let new_rect = ctx.constrain_window_rect_to_area(new_rect, area.drag_bounds());
// TODO(emilk): add this to a Window state instead as a command "move here next frame"
area.state_mut().pos = new_rect.min;
if window_interaction.is_resize() {
if let Some(mut state) = resize::State::load(ctx, resize_id) {
state.requested_size = Some(new_rect.size() - margins);
state.store(ctx, resize_id);
}
}
ctx.memory().areas.move_to_top(area_layer_id);
Some(window_interaction)
}
fn move_and_resize_window(ctx: &Context, window_interaction: &WindowInteraction) -> Option<Rect> {
window_interaction.set_cursor(ctx);
// Only move/resize windows with primary mouse button:
if !ctx.input().pointer.primary_down() {
return None;
}
let pointer_pos = ctx.input().pointer.interact_pos()?;
let mut rect = window_interaction.start_rect; // prevent drift
if window_interaction.is_resize() {
if window_interaction.left {
rect.min.x = ctx.round_to_pixel(pointer_pos.x);
} else if window_interaction.right {
rect.max.x = ctx.round_to_pixel(pointer_pos.x);
}
if window_interaction.top {
rect.min.y = ctx.round_to_pixel(pointer_pos.y);
} else if window_interaction.bottom {
rect.max.y = ctx.round_to_pixel(pointer_pos.y);
}
} else {
// Movement.
// We do window interaction first (to avoid frame delay),
// 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,
// but instead let other widgets to the steal. HACK.
if !ctx.input().pointer.any_pressed() {
let press_origin = ctx.input().pointer.press_origin()?;
let delta = pointer_pos - press_origin;
rect = rect.translate(delta);
}
}
Some(rect)
}
/// Returns `Some` if there is a move or resize
fn window_interaction(
ctx: &Context,
possible: PossibleInteractions,
area_layer_id: LayerId,
id: Id,
rect: Rect,
) -> Option<WindowInteraction> {
{
let drag_id = ctx.memory().interaction.drag_id;
if drag_id.is_some() && drag_id != Some(id) {
return None;
}
}
let mut window_interaction = { ctx.memory().window_interaction };
if window_interaction.is_none() {
if let Some(hover_window_interaction) = resize_hover(ctx, possible, area_layer_id, rect) {
hover_window_interaction.set_cursor(ctx);
if ctx.input().pointer.any_pressed() && ctx.input().pointer.primary_down() {
ctx.memory().interaction.drag_id = Some(id);
ctx.memory().interaction.drag_is_window = true;
window_interaction = Some(hover_window_interaction);
ctx.memory().window_interaction = window_interaction;
}
}
}
if let Some(window_interaction) = window_interaction {
let is_active = ctx.memory().interaction.drag_id == Some(id);
if is_active && window_interaction.area_layer_id == area_layer_id {
return Some(window_interaction);
}
}
None
}
fn resize_hover(
ctx: &Context,
possible: PossibleInteractions,
area_layer_id: LayerId,
rect: Rect,
) -> Option<WindowInteraction> {
let pointer = ctx.input().pointer.interact_pos()?;
if ctx.input().pointer.any_down() && !ctx.input().pointer.any_pressed() {
return None; // already dragging (something)
}
if let Some(top_layer_id) = ctx.layer_id_at(pointer) {
if top_layer_id != area_layer_id && top_layer_id.order != Order::Background {
return None; // Another window is on top here
}
}
if ctx.memory().interaction.drag_interest {
// Another widget will become active if we drag here
return None;
}
let side_grab_radius = ctx.style().interaction.resize_grab_radius_side;
let corner_grab_radius = ctx.style().interaction.resize_grab_radius_corner;
if !rect.expand(side_grab_radius).contains(pointer) {
return None;
}
let mut left = possible.resize_left && (rect.left() - pointer.x).abs() <= side_grab_radius;
let mut right = possible.resize_right && (rect.right() - pointer.x).abs() <= side_grab_radius;
let mut top = possible.resize_top && (rect.top() - pointer.y).abs() <= side_grab_radius;
let mut bottom =
possible.resize_bottom && (rect.bottom() - pointer.y).abs() <= side_grab_radius;
if possible.resize_right
&& possible.resize_bottom
&& rect.right_bottom().distance(pointer) < corner_grab_radius
{
right = true;
bottom = true;
}
if possible.resize_right
&& possible.resize_top
&& rect.right_top().distance(pointer) < corner_grab_radius
{
right = true;
top = true;
}
if possible.resize_left
&& possible.resize_top
&& rect.left_top().distance(pointer) < corner_grab_radius
{
left = true;
top = true;
}
if possible.resize_left
&& possible.resize_bottom
&& rect.left_bottom().distance(pointer) < corner_grab_radius
{
left = true;
bottom = true;
}
let any_resize = left || right || top || bottom;
if !any_resize && !possible.movable {
return None;
}
if any_resize || possible.movable {
Some(WindowInteraction {
area_layer_id,
start_rect: rect,
left,
right,
top,
bottom,
})
} else {
None
}
}
/// Fill in parts of the window frame when we resize by dragging that part
fn paint_frame_interaction(
ui: &mut Ui,
rect: Rect,
interaction: WindowInteraction,
visuals: style::WidgetVisuals,
) {
use epaint::tessellator::path::add_circle_quadrant;
let rounding = ui.visuals().window_rounding;
let Rect { min, max } = rect;
let mut points = Vec::new();
if interaction.right && !interaction.bottom && !interaction.top {
points.push(pos2(max.x, min.y + rounding.ne));
points.push(pos2(max.x, max.y - rounding.se));
}
if interaction.right && interaction.bottom {
points.push(pos2(max.x, min.y + rounding.ne));
points.push(pos2(max.x, max.y - rounding.se));
add_circle_quadrant(
&mut points,
pos2(max.x - rounding.se, max.y - rounding.se),
rounding.se,
0.0,
);
}
if interaction.bottom {
points.push(pos2(max.x - rounding.se, max.y));
points.push(pos2(min.x + rounding.sw, max.y));
}
if interaction.left && interaction.bottom {
add_circle_quadrant(
&mut points,
pos2(min.x + rounding.sw, max.y - rounding.sw),
rounding.sw,
1.0,
);
}
if interaction.left {
points.push(pos2(min.x, max.y - rounding.sw));
points.push(pos2(min.x, min.y + rounding.nw));
}
if interaction.left && interaction.top {
add_circle_quadrant(
&mut points,
pos2(min.x + rounding.nw, min.y + rounding.nw),
rounding.nw,
2.0,
);
}
if interaction.top {
points.push(pos2(min.x + rounding.nw, min.y));
points.push(pos2(max.x - rounding.ne, min.y));
}
if interaction.right && interaction.top {
add_circle_quadrant(
&mut points,
pos2(max.x - rounding.ne, min.y + rounding.ne),
rounding.ne,
3.0,
);
points.push(pos2(max.x, min.y + rounding.ne));
points.push(pos2(max.x, max.y - rounding.se));
}
ui.painter().add(Shape::line(points, visuals.bg_stroke));
}
// ----------------------------------------------------------------------------
struct TitleBar {
/// A title Id used for dragging windows
id: Id,
/// Prepared text in the title
title_galley: WidgetTextGalley,
/// Size of the title bar in a collapsed state (if window is collapsible),
/// which includes all necessary space for showing the expand button, the
/// title and the close button.
min_rect: Rect,
/// Size of the title bar in an expanded state. This size become known only
/// after expanding window and painting its content
rect: Rect,
}
fn show_title_bar(
ui: &mut Ui,
title: WidgetText,
show_close_button: bool,
collapsing: &mut CollapsingState,
collapsible: bool,
) -> TitleBar {
let inner_response = ui.horizontal(|ui| {
let height = title
.font_height(&ui.fonts(), ui.style())
.max(ui.spacing().interact_size.y);
ui.set_min_height(height);
let item_spacing = ui.spacing().item_spacing;
let button_size = Vec2::splat(ui.spacing().icon_width);
let pad = (height - button_size.y) / 2.0; // calculated so that the icon is on the diagonal (if window padding is symmetrical)
if collapsible {
ui.add_space(pad);
collapsing.show_default_button_with_size(ui, button_size);
}
let title_galley = title.into_galley(ui, Some(false), f32::INFINITY, TextStyle::Heading);
let minimum_width = if collapsible || show_close_button {
// If at least one button is shown we make room for both buttons (since title is centered):
2.0 * (pad + button_size.x + item_spacing.x) + title_galley.size().x
} else {
pad + title_galley.size().x + pad
};
let min_rect = Rect::from_min_size(ui.min_rect().min, vec2(minimum_width, height));
let id = ui.advance_cursor_after_rect(min_rect);
TitleBar {
id,
title_galley,
min_rect,
rect: Rect::NAN, // Will be filled in later
}
});
let title_bar = inner_response.inner;
let rect = inner_response.response.rect;
TitleBar { rect, ..title_bar }
}
impl TitleBar {
/// Finishes painting of the title bar when the window content size already known.
///
/// # Parameters
///
/// - `ui`:
/// - `outer_rect`:
/// - `content_response`: if `None`, window is collapsed at this frame, otherwise contains
/// a result of rendering the window content
/// - `open`: if `None`, no "Close" button will be rendered, otherwise renders and processes
/// the "Close" button and writes a `false` if window was closed
/// - `collapsing`: holds the current expanding state. Can be changed by double click on the
/// title if `collapsible` is `true`
/// - `collapsible`: if `true`, double click on the title bar will be handled for a change
/// of `collapsing` state
fn ui(
mut self,
ui: &mut Ui,
outer_rect: Rect,
content_response: &Option<Response>,
open: Option<&mut bool>,
collapsing: &mut CollapsingState,
collapsible: bool,
) {
if let Some(content_response) = &content_response {
// Now we know how large we got to be:
self.rect.max.x = self.rect.max.x.max(content_response.rect.max.x);
}
if let Some(open) = open {
// Add close button now that we know our full width:
if self.close_button_ui(ui).clicked() {
*open = false;
}
}
let full_top_rect = Rect::from_x_y_ranges(self.rect.x_range(), self.min_rect.y_range());
let text_pos =
emath::align::center_size_in_rect(self.title_galley.size(), full_top_rect).left_top();
let text_pos = text_pos - self.title_galley.galley().rect.min.to_vec2();
let text_pos = text_pos - 1.5 * Vec2::Y; // HACK: center on x-height of text (looks better)
self.title_galley.paint_with_fallback_color(
ui.painter(),
text_pos,
ui.visuals().text_color(),
);
if let Some(content_response) = &content_response {
// paint separator between title and content:
let y = content_response.rect.top() + ui.spacing().item_spacing.y * 0.5;
// let y = lerp(self.rect.bottom()..=content_response.rect.top(), 0.5);
let stroke = ui.visuals().widgets.noninteractive.bg_stroke;
ui.painter().hline(outer_rect.x_range(), y, stroke);
}
if ui
.interact(self.rect, self.id, Sense::click())
.double_clicked()
&& collapsible
{
collapsing.toggle(ui);
}
}
/// Paints the "Close" button at the right side of the title bar
/// and processes clicks on it.
///
/// The button is square and its size is determined by the
/// [`crate::style::Spacing::icon_width`] setting.
fn close_button_ui(&self, ui: &mut Ui) -> Response {
let button_size = Vec2::splat(ui.spacing().icon_width);
let pad = (self.rect.height() - button_size.y) / 2.0; // calculated so that the icon is on the diagonal (if window padding is symmetrical)
let button_rect = Rect::from_min_size(
pos2(
self.rect.right() - pad - button_size.x,
self.rect.center().y - 0.5 * button_size.y,
),
button_size,
);
close_button(ui, button_rect)
}
}
/// Paints the "Close" button of the window and processes clicks on it.
///
/// The close button is just an `X` symbol painted by a current stroke
/// for foreground elements (such as a label text).
///
/// # Parameters
/// - `ui`:
/// - `rect`: The rectangular area to fit the button in
///
/// Returns the result of a click on a button if it was pressed
fn close_button(ui: &mut Ui, rect: Rect) -> Response {
let close_id = ui.auto_id_with("window_close_button");
let response = ui.interact(rect, close_id, Sense::click());
ui.expand_to_include_rect(response.rect);
let visuals = ui.style().interact(&response);
let rect = rect.shrink(2.0).expand(visuals.expansion);
let stroke = visuals.fg_stroke;
ui.painter() // paints \
.line_segment([rect.left_top(), rect.right_bottom()], stroke);
ui.painter() // paints /
.line_segment([rect.right_top(), rect.left_bottom()], stroke);
response
}
File diff suppressed because it is too large Load Diff
+654
View File
@@ -0,0 +1,654 @@
//! The input needed by egui.
use crate::emath::*;
/// What the integrations provides to egui at the start of each frame.
///
/// Set the values that make sense, leave the rest at their `Default::default()`.
///
/// You can check if `egui` is using the inputs using
/// [`crate::Context::wants_pointer_input`] and [`crate::Context::wants_keyboard_input`].
///
/// All coordinates are in points (logical pixels) with origin (0, 0) in the top left corner.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct RawInput {
/// Position and size of the area that egui should use.
/// Usually you would set this to
///
/// `Some(Rect::from_pos_size(Default::default(), screen_size))`.
///
/// but you could also constrain egui to some smaller portion of your window if you like.
///
/// `None` will be treated as "same as last frame", with the default being a very big area.
pub screen_rect: Option<Rect>,
/// Also known as device pixel ratio, > 1 for high resolution screens.
/// If text looks blurry you probably forgot to set this.
/// Set this the first frame, whenever it changes, or just on every frame.
pub pixels_per_point: Option<f32>,
/// Maximum size of one side of the font texture.
///
/// Ask your graphics drivers about this. This corresponds to `GL_MAX_TEXTURE_SIZE`.
///
/// The default is a very small (but very portable) 2048.
pub max_texture_side: Option<usize>,
/// Monotonically increasing time, in seconds. Relative to whatever. Used for animations.
/// If `None` is provided, egui will assume a time delta of `predicted_dt` (default 1/60 seconds).
pub time: Option<f64>,
/// Should be set to the expected time between frames when painting at vsync speeds.
/// The default for this is 1/60.
/// Can safely be left at its default value.
pub predicted_dt: f32,
/// Which modifier keys are down at the start of the frame?
pub modifiers: Modifiers,
/// In-order events received this frame.
///
/// There is currently no way to know if egui handles a particular event,
/// but you can check if egui is using the keyboard with [`crate::Context::wants_keyboard_input`]
/// and/or the pointer (mouse/touch) with [`crate::Context::is_using_pointer`].
pub events: Vec<Event>,
/// Dragged files hovering over egui.
pub hovered_files: Vec<HoveredFile>,
/// Dragged files dropped into egui.
///
/// Note: when using `eframe` on Windows you need to enable
/// drag-and-drop support using `eframe::NativeOptions`.
pub dropped_files: Vec<DroppedFile>,
/// The window has the keyboard focus (i.e. is receiving key presses).
pub has_focus: bool,
}
impl Default for RawInput {
fn default() -> Self {
Self {
screen_rect: None,
pixels_per_point: None,
max_texture_side: None,
time: None,
predicted_dt: 1.0 / 60.0,
modifiers: Modifiers::default(),
events: vec![],
hovered_files: Default::default(),
dropped_files: Default::default(),
has_focus: true, // integrations opt into global focus tracking
}
}
}
impl RawInput {
/// Helper: move volatile (deltas and events), clone the rest.
///
/// * [`Self::hovered_files`] is cloned.
/// * [`Self::dropped_files`] is moved.
pub fn take(&mut self) -> RawInput {
RawInput {
screen_rect: self.screen_rect.take(),
pixels_per_point: self.pixels_per_point.take(),
max_texture_side: self.max_texture_side.take(),
time: self.time.take(),
predicted_dt: self.predicted_dt,
modifiers: self.modifiers,
events: std::mem::take(&mut self.events),
hovered_files: self.hovered_files.clone(),
dropped_files: std::mem::take(&mut self.dropped_files),
has_focus: self.has_focus,
}
}
/// Add on new input.
pub fn append(&mut self, newer: Self) {
let Self {
screen_rect,
pixels_per_point,
max_texture_side,
time,
predicted_dt,
modifiers,
mut events,
mut hovered_files,
mut dropped_files,
has_focus,
} = newer;
self.screen_rect = screen_rect.or(self.screen_rect);
self.pixels_per_point = pixels_per_point.or(self.pixels_per_point);
self.max_texture_side = max_texture_side.or(self.max_texture_side);
self.time = time; // use latest time
self.predicted_dt = predicted_dt; // use latest dt
self.modifiers = modifiers; // use latest
self.events.append(&mut events);
self.hovered_files.append(&mut hovered_files);
self.dropped_files.append(&mut dropped_files);
self.has_focus = has_focus;
}
}
/// A file about to be dropped into egui.
#[derive(Clone, Debug, Default, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct HoveredFile {
/// Set by the `egui-winit` backend.
pub path: Option<std::path::PathBuf>,
/// With the `eframe` web backend, this is set to the mime-type of the file (if available).
pub mime: String,
}
/// A file dropped into egui.
#[derive(Clone, Debug, Default, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct DroppedFile {
/// Set by the `egui-winit` backend.
pub path: Option<std::path::PathBuf>,
/// Name of the file. Set by the `eframe` web backend.
pub name: String,
/// Set by the `eframe` web backend.
pub last_modified: Option<std::time::SystemTime>,
/// Set by the `eframe` web backend.
pub bytes: Option<std::sync::Arc<[u8]>>,
}
/// An input event generated by the integration.
///
/// This only covers events that egui cares about.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum Event {
/// The integration detected a "copy" event (e.g. Cmd+C).
Copy,
/// The integration detected a "cut" event (e.g. Cmd+X).
Cut,
/// The integration detected a "paste" event (e.g. Cmd+V).
Paste(String),
/// Text input, e.g. via keyboard.
///
/// When the user presses enter/return, do not send a [`Text`](Event::Text) (just [`Key::Enter`]).
Text(String),
/// A key was pressed or released.
Key {
key: Key,
/// Was it pressed or released?
pressed: bool,
/// The state of the modifier keys at the time of the event.
modifiers: Modifiers,
},
/// The mouse or touch moved to a new place.
PointerMoved(Pos2),
/// A mouse button was pressed or released (or a touch started or stopped).
PointerButton {
/// Where is the pointer?
pos: Pos2,
/// What mouse button? For touches, use [`PointerButton::Primary`].
button: PointerButton,
/// Was it the button/touch pressed this frame, or released?
pressed: bool,
/// The state of the modifier keys at the time of the event.
modifiers: Modifiers,
},
/// The mouse left the screen, or the last/primary touch input disappeared.
///
/// This means there is no longer a cursor on the screen for hovering etc.
///
/// On touch-up first send `PointerButton{pressed: false, …}` followed by `PointerLeft`.
PointerGone,
/// How many points (logical pixels) the user scrolled.
///
/// The direction of the vector indicates how to move the _content_ that is being viewed.
/// So if you get positive values, the content being viewed should move to the right and down,
/// revealing new things to the left and up.
///
/// A positive X-value indicates the content is being moved right,
/// as when swiping right on a touch-screen or track-pad with natural scrolling.
///
/// A positive Y-value indicates the content is being moved down,
/// as when swiping down on a touch-screen or track-pad with natural scrolling.
///
/// Shift-scroll should result in horizontal scrolling (it is up to the integrations to do this).
Scroll(Vec2),
/// Zoom scale factor this frame (e.g. from ctrl-scroll or pinch gesture).
/// * `zoom = 1`: no change.
/// * `zoom < 1`: pinch together
/// * `zoom > 1`: pinch spread
Zoom(f32),
/// IME composition start.
CompositionStart,
/// A new IME candidate is being suggested.
CompositionUpdate(String),
/// IME composition ended with this final result.
CompositionEnd(String),
/// On touch screens, report this *in addition to*
/// [`Self::PointerMoved`], [`Self::PointerButton`], [`Self::PointerGone`]
Touch {
/// Hashed device identifier (if available; may be zero).
/// Can be used to separate touches from different devices.
device_id: TouchDeviceId,
/// Unique identifier of a finger/pen. Value is stable from touch down
/// to lift-up
id: TouchId,
/// One of: start move end cancel.
phase: TouchPhase,
/// Position of the touch (or where the touch was last detected)
pos: Pos2,
/// Describes how hard the touch device was pressed. May always be `0` if the platform does
/// not support pressure sensitivity.
/// The value is in the range from 0.0 (no pressure) to 1.0 (maximum pressure).
force: f32,
},
}
/// Mouse button (or similar for touch input)
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum PointerButton {
/// The primary mouse button is usually the left one.
Primary = 0,
/// The secondary mouse button is usually the right one,
/// and most often used for context menus or other optional things.
Secondary = 1,
/// The tertiary mouse button is usually the middle mouse button (e.g. clicking the scroll wheel).
Middle = 2,
/// The first extra mouse button on some mice. In web typically corresponds to the Browser back button.
Extra1 = 3,
/// The second extra mouse button on some mice. In web typically corresponds to the Browser forward button.
Extra2 = 4,
}
/// Number of pointer buttons supported by egui, i.e. the number of possible states of [`PointerButton`].
pub const NUM_POINTER_BUTTONS: usize = 5;
/// State of the modifier keys. These must be fed to egui.
///
/// The best way to compare [`Modifiers`] is by using [`Modifiers::matches`].
#[derive(Clone, Copy, Debug, Default, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct Modifiers {
/// Either of the alt keys are down (option ⌥ on Mac).
pub alt: bool,
/// Either of the control keys are down.
/// When checking for keyboard shortcuts, consider using [`Self::command`] instead.
pub ctrl: bool,
/// Either of the shift keys are down.
pub shift: bool,
/// The Mac ⌘ Command key. Should always be set to `false` on other platforms.
pub mac_cmd: bool,
/// On Windows and Linux, set this to the same value as `ctrl`.
/// On Mac, this should be set whenever one of the ⌘ Command keys are down (same as `mac_cmd`).
/// This is so that egui can, for instance, select all text by checking for `command + A`
/// and it will work on both Mac and Windows.
pub command: bool,
}
impl Modifiers {
pub fn new() -> Self {
Default::default()
}
pub const NONE: Self = Self {
alt: false,
ctrl: false,
shift: false,
mac_cmd: false,
command: false,
};
pub const ALT: Self = Self {
alt: true,
ctrl: false,
shift: false,
mac_cmd: false,
command: false,
};
pub const CTRL: Self = Self {
alt: false,
ctrl: true,
shift: false,
mac_cmd: false,
command: false,
};
pub const SHIFT: Self = Self {
alt: false,
ctrl: false,
shift: true,
mac_cmd: false,
command: false,
};
pub const ALT_SHIFT: Self = Self {
alt: true,
ctrl: false,
shift: true,
mac_cmd: false,
command: false,
};
/// The Mac ⌘ Command key
pub const MAC_CMD: Self = Self {
alt: false,
ctrl: false,
shift: false,
mac_cmd: true,
command: false,
};
/// On Mac: ⌘ Command key, elsewhere: Ctrl key
pub const COMMAND: Self = Self {
alt: false,
ctrl: false,
shift: false,
mac_cmd: false,
command: true,
};
#[inline(always)]
pub fn is_none(&self) -> bool {
self == &Self::default()
}
#[inline(always)]
pub fn any(&self) -> bool {
!self.is_none()
}
/// Is shift the only pressed button?
#[inline(always)]
pub fn shift_only(&self) -> bool {
self.shift && !(self.alt || self.command)
}
/// true if only [`Self::ctrl`] or only [`Self::mac_cmd`] is pressed.
#[inline(always)]
pub fn command_only(&self) -> bool {
!self.alt && !self.shift && self.command
}
/// Check for equality but with proper handling of [`Self::command`].
///
/// ```
/// # use egui::Modifiers;
/// assert!(Modifiers::CTRL.matches(Modifiers::CTRL));
/// assert!(!Modifiers::CTRL.matches(Modifiers::CTRL | Modifiers::SHIFT));
/// assert!(!(Modifiers::CTRL | Modifiers::SHIFT).matches(Modifiers::CTRL));
/// assert!((Modifiers::CTRL | Modifiers::COMMAND).matches(Modifiers::CTRL));
/// assert!((Modifiers::CTRL | Modifiers::COMMAND).matches(Modifiers::COMMAND));
/// assert!((Modifiers::MAC_CMD | Modifiers::COMMAND).matches(Modifiers::COMMAND));
/// assert!(!Modifiers::COMMAND.matches(Modifiers::MAC_CMD));
/// ```
pub fn matches(&self, pattern: Modifiers) -> bool {
// alt and shift must always match the pattern:
if pattern.alt != self.alt || pattern.shift != self.shift {
return false;
}
if pattern.mac_cmd {
// Mac-specific match:
if !self.mac_cmd {
return false;
}
if pattern.ctrl != self.ctrl {
return false;
}
return true;
}
if !pattern.ctrl && !pattern.command {
// the pattern explicitly doesn't want any ctrl/command:
return !self.ctrl && !self.command;
}
// if the pattern is looking for command, then `ctrl` may or may not be set depending on platform.
// if the pattern is looking for `ctrl`, then `command` may or may not be set depending on platform.
if pattern.ctrl && !self.ctrl {
return false;
}
if pattern.command && !self.command {
return false;
}
true
}
}
impl std::ops::BitOr for Modifiers {
type Output = Self;
fn bitor(self, rhs: Self) -> Self {
Self {
alt: self.alt | rhs.alt,
ctrl: self.ctrl | rhs.ctrl,
shift: self.shift | rhs.shift,
mac_cmd: self.mac_cmd | rhs.mac_cmd,
command: self.command | rhs.command,
}
}
}
/// Keyboard keys.
///
/// Includes all keys egui is interested in (such as `Home` and `End`)
/// plus a few that are useful for detecting keyboard shortcuts.
///
/// Many keys are omitted because they are not always physical keys (depending on keyboard language), e.g. `;` and `§`,
/// and are therefore unsuitable as keyboard shortcuts if you want your app to be portable.
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum Key {
ArrowDown,
ArrowLeft,
ArrowRight,
ArrowUp,
Escape,
Tab,
Backspace,
Enter,
Space,
Insert,
Delete,
Home,
End,
PageUp,
PageDown,
/// Either from the main row or from the numpad.
Num0,
/// Either from the main row or from the numpad.
Num1,
/// Either from the main row or from the numpad.
Num2,
/// Either from the main row or from the numpad.
Num3,
/// Either from the main row or from the numpad.
Num4,
/// Either from the main row or from the numpad.
Num5,
/// Either from the main row or from the numpad.
Num6,
/// Either from the main row or from the numpad.
Num7,
/// Either from the main row or from the numpad.
Num8,
/// Either from the main row or from the numpad.
Num9,
A, // Used for cmd+A (select All)
B,
C, // |CMD COPY|
D, // |CMD BOOKMARK|
E, // |CMD SEARCH|
F, // |CMD FIND firefox & chrome|
G, // |CMD FIND chrome|
H, // |CMD History|
I, // italics
J, // |CMD SEARCH firefox/DOWNLOAD chrome|
K, // Used for ctrl+K (delete text after cursor)
L,
M,
N,
O, // |CMD OPEN|
P, // |CMD PRINT|
Q,
R, // |CMD REFRESH|
S, // |CMD SAVE|
T, // |CMD TAB|
U, // Used for ctrl+U (delete text before cursor)
V, // |CMD PASTE|
W, // Used for ctrl+W (delete previous word)
X, // |CMD CUT|
Y,
Z, // |CMD UNDO|
// The function keys:
F1,
F2,
F3,
F4,
F5, // |CMD REFRESH|
F6,
F7,
F8,
F9,
F10,
F11,
F12,
F13,
F14,
F15,
F16,
F17,
F18,
F19,
F20,
}
impl RawInput {
pub fn ui(&self, ui: &mut crate::Ui) {
let Self {
screen_rect,
pixels_per_point,
max_texture_side,
time,
predicted_dt,
modifiers,
events,
hovered_files,
dropped_files,
has_focus,
} = self;
ui.label(format!("screen_rect: {:?} points", screen_rect));
ui.label(format!("pixels_per_point: {:?}", pixels_per_point))
.on_hover_text(
"Also called HDPI factor.\nNumber of physical pixels per each logical pixel.",
);
ui.label(format!("max_texture_side: {:?}", max_texture_side));
if let Some(time) = time {
ui.label(format!("time: {:.3} s", time));
} else {
ui.label("time: None");
}
ui.label(format!("predicted_dt: {:.1} ms", 1e3 * predicted_dt));
ui.label(format!("modifiers: {:#?}", modifiers));
ui.label(format!("hovered_files: {}", hovered_files.len()));
ui.label(format!("dropped_files: {}", dropped_files.len()));
ui.label(format!("has_focus: {}", has_focus));
ui.scope(|ui| {
ui.set_min_height(150.0);
ui.label(format!("events: {:#?}", events))
.on_hover_text("key presses etc");
});
}
}
/// this is a `u64` as values of this kind can always be obtained by hashing
#[derive(Clone, Copy, Debug, Eq, PartialEq, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct TouchDeviceId(pub u64);
/// Unique identification of a touch occurrence (finger or pen or …).
/// A Touch ID is valid until the finger is lifted.
/// A new ID is used for the next touch.
#[derive(Clone, Copy, Debug, Eq, PartialEq, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct TouchId(pub u64);
/// In what phase a touch event is in.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum TouchPhase {
/// User just placed a touch point on the touch surface
Start,
/// User moves a touch point along the surface. This event is also sent when
/// any attributes (position, force, …) of the touch point change.
Move,
/// User lifted the finger or pen from the surface, or slid off the edge of
/// the surface
End,
/// Touch operation has been disrupted by something (various reasons are possible,
/// maybe a pop-up alert or any other kind of interruption which may not have
/// been intended by the user)
Cancel,
}
impl From<u64> for TouchId {
fn from(id: u64) -> Self {
Self(id)
}
}
impl From<i32> for TouchId {
fn from(id: i32) -> Self {
Self(id as u64)
}
}
impl From<u32> for TouchId {
fn from(id: u32) -> Self {
Self(id as u64)
}
}
+4
View File
@@ -0,0 +1,4 @@
//! All the data sent between egui and the backend
pub mod input;
pub mod output;
+604
View File
@@ -0,0 +1,604 @@
//! All the data egui returns to the backend at the end of each frame.
use crate::WidgetType;
/// What egui emits each frame from [`crate::Context::run`].
///
/// The backend should use this.
#[derive(Clone, Default, PartialEq)]
pub struct FullOutput {
/// Non-rendering related output.
pub platform_output: PlatformOutput,
/// If `Duration::is_zero()`, egui is requesting immediate repaint (i.e. on the next frame).
///
/// This happens for instance when there is an animation, or if a user has called `Context::request_repaint()`.
///
/// If `Duration` is greater than zero, egui wants to be repainted at or before the specified
/// duration elapses. when in reactive mode, egui spends forever waiting for input and only then,
/// will it repaint itself. this can be used to make sure that backend will only wait for a
/// specified amount of time, and repaint egui without any new input.
pub repaint_after: std::time::Duration,
/// Texture changes since last frame (including the font texture).
///
/// The backend needs to apply [`crate::TexturesDelta::set`] _before_ painting,
/// and free any texture in [`crate::TexturesDelta::free`] _after_ painting.
pub textures_delta: epaint::textures::TexturesDelta,
/// What to paint.
///
/// You can use [`crate::Context::tessellate`] to turn this into triangles.
pub shapes: Vec<epaint::ClippedShape>,
}
impl FullOutput {
/// Add on new output.
pub fn append(&mut self, newer: Self) {
let Self {
platform_output,
repaint_after,
textures_delta,
shapes,
} = newer;
self.platform_output.append(platform_output);
self.repaint_after = repaint_after; // if the last frame doesn't need a repaint, then we don't need to repaint
self.textures_delta.append(textures_delta);
self.shapes = shapes; // Only paint the latest
}
}
/// The non-rendering part of what egui emits each frame.
///
/// You can access (and modify) this with [`crate::Context::output`].
///
/// The backend should use this.
#[derive(Default, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct PlatformOutput {
/// Set the cursor to this icon.
pub cursor_icon: CursorIcon,
/// If set, open this url.
pub open_url: Option<OpenUrl>,
/// If set, put this text in the system clipboard. Ignore if empty.
///
/// This is often a response to [`crate::Event::Copy`] or [`crate::Event::Cut`].
///
/// ```
/// # egui::__run_test_ui(|ui| {
/// if ui.button("📋").clicked() {
/// ui.output().copied_text = "some_text".to_string();
/// }
/// # });
/// ```
pub copied_text: String,
/// Events that may be useful to e.g. a screen reader.
pub events: Vec<OutputEvent>,
/// Is there a mutable [`TextEdit`](crate::TextEdit) under the cursor?
/// Use by `eframe` web to show/hide mobile keyboard and IME agent.
pub mutable_text_under_cursor: bool,
/// Screen-space position of text edit cursor (used for IME).
pub text_cursor_pos: Option<crate::Pos2>,
}
impl PlatformOutput {
/// Open the given url in a web browser.
/// If egui is running in a browser, the same tab will be reused.
pub fn open_url(&mut self, url: impl ToString) {
self.open_url = Some(OpenUrl::same_tab(url));
}
/// This can be used by a text-to-speech system to describe the events (if any).
pub fn events_description(&self) -> String {
// only describe last event:
if let Some(event) = self.events.iter().rev().next() {
match event {
OutputEvent::Clicked(widget_info)
| OutputEvent::DoubleClicked(widget_info)
| OutputEvent::TripleClicked(widget_info)
| OutputEvent::FocusGained(widget_info)
| OutputEvent::TextSelectionChanged(widget_info)
| OutputEvent::ValueChanged(widget_info) => {
return widget_info.description();
}
}
}
Default::default()
}
/// Add on new output.
pub fn append(&mut self, newer: Self) {
let Self {
cursor_icon,
open_url,
copied_text,
mut events,
mutable_text_under_cursor,
text_cursor_pos,
} = newer;
self.cursor_icon = cursor_icon;
if open_url.is_some() {
self.open_url = open_url;
}
if !copied_text.is_empty() {
self.copied_text = copied_text;
}
self.events.append(&mut events);
self.mutable_text_under_cursor = mutable_text_under_cursor;
self.text_cursor_pos = text_cursor_pos.or(self.text_cursor_pos);
}
/// Take everything ephemeral (everything except `cursor_icon` currently)
pub fn take(&mut self) -> Self {
let taken = std::mem::take(self);
self.cursor_icon = taken.cursor_icon; // eveything else is ephemeral
taken
}
}
/// What URL to open, and how.
#[derive(Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct OpenUrl {
pub url: String,
/// If `true`, open the url in a new tab.
/// If `false` open it in the same tab.
/// Only matters when in a web browser.
pub new_tab: bool,
}
impl OpenUrl {
#[allow(clippy::needless_pass_by_value)]
pub fn same_tab(url: impl ToString) -> Self {
Self {
url: url.to_string(),
new_tab: false,
}
}
#[allow(clippy::needless_pass_by_value)]
pub fn new_tab(url: impl ToString) -> Self {
Self {
url: url.to_string(),
new_tab: true,
}
}
}
/// A mouse cursor icon.
///
/// egui emits a [`CursorIcon`] in [`PlatformOutput`] each frame as a request to the integration.
///
/// Loosely based on <https://developer.mozilla.org/en-US/docs/Web/CSS/cursor>.
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum CursorIcon {
/// Normal cursor icon, whatever that is.
Default,
/// Show no cursor
None,
// ------------------------------------
// Links and status:
/// A context menu is available
ContextMenu,
/// Question mark
Help,
/// Pointing hand, used for e.g. web links
PointingHand,
/// Shows that processing is being done, but that the program is still interactive.
Progress,
/// Not yet ready, try later.
Wait,
// ------------------------------------
// Selection:
/// Hover a cell in a table
Cell,
/// For precision work
Crosshair,
/// Text caret, e.g. "Click here to edit text"
Text,
/// Vertical text caret, e.g. "Click here to edit vertical text"
VerticalText,
// ------------------------------------
// Drag-and-drop:
/// Indicated an alias, e.g. a shortcut
Alias,
/// Indicate that a copy will be made
Copy,
/// Omnidirectional move icon (e.g. arrows in all cardinal directions)
Move,
/// Can't drop here
NoDrop,
/// Forbidden
NotAllowed,
/// The thing you are hovering can be grabbed
Grab,
/// You are grabbing the thing you are hovering
Grabbing,
// ------------------------------------
/// Something can be scrolled in any direction (panned).
AllScroll,
// ------------------------------------
// Resizing in two directions:
/// Horizontal resize `-` to make something wider or more narrow (left to/from right)
ResizeHorizontal,
/// Diagonal resize `/` (right-up to/from left-down)
ResizeNeSw,
/// Diagonal resize `\` (left-up to/from right-down)
ResizeNwSe,
/// Vertical resize `|` (up-down or down-up)
ResizeVertical,
// ------------------------------------
// Resizing in one direction:
/// Resize something rightwards (e.g. when dragging the right-most edge of something)
ResizeEast,
/// Resize something down and right (e.g. when dragging the bottom-right corner of something)
ResizeSouthEast,
/// Resize something downwards (e.g. when dragging the bottom edge of something)
ResizeSouth,
/// Resize something down and left (e.g. when dragging the bottom-left corner of something)
ResizeSouthWest,
/// Resize something leftwards (e.g. when dragging the left edge of something)
ResizeWest,
/// Resize something up and left (e.g. when dragging the top-left corner of something)
ResizeNorthWest,
/// Resize something up (e.g. when dragging the top edge of something)
ResizeNorth,
/// Resize something up and right (e.g. when dragging the top-right corner of something)
ResizeNorthEast,
// ------------------------------------
/// Resize a column
ResizeColumn,
/// Resize a row
ResizeRow,
// ------------------------------------
// Zooming:
/// Enhance!
ZoomIn,
/// Let's get a better overview
ZoomOut,
}
impl CursorIcon {
pub const ALL: [CursorIcon; 35] = [
CursorIcon::Default,
CursorIcon::None,
CursorIcon::ContextMenu,
CursorIcon::Help,
CursorIcon::PointingHand,
CursorIcon::Progress,
CursorIcon::Wait,
CursorIcon::Cell,
CursorIcon::Crosshair,
CursorIcon::Text,
CursorIcon::VerticalText,
CursorIcon::Alias,
CursorIcon::Copy,
CursorIcon::Move,
CursorIcon::NoDrop,
CursorIcon::NotAllowed,
CursorIcon::Grab,
CursorIcon::Grabbing,
CursorIcon::AllScroll,
CursorIcon::ResizeHorizontal,
CursorIcon::ResizeNeSw,
CursorIcon::ResizeNwSe,
CursorIcon::ResizeVertical,
CursorIcon::ResizeEast,
CursorIcon::ResizeSouthEast,
CursorIcon::ResizeSouth,
CursorIcon::ResizeSouthWest,
CursorIcon::ResizeWest,
CursorIcon::ResizeNorthWest,
CursorIcon::ResizeNorth,
CursorIcon::ResizeNorthEast,
CursorIcon::ResizeColumn,
CursorIcon::ResizeRow,
CursorIcon::ZoomIn,
CursorIcon::ZoomOut,
];
}
impl Default for CursorIcon {
fn default() -> Self {
Self::Default
}
}
/// Things that happened during this frame that the integration may be interested in.
///
/// In particular, these events may be useful for accessability, i.e. for screen readers.
#[derive(Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum OutputEvent {
/// A widget was clicked.
Clicked(WidgetInfo),
/// A widget was double-clicked.
DoubleClicked(WidgetInfo),
/// A widget was triple-clicked.
TripleClicked(WidgetInfo),
/// A widget gained keyboard focus (by tab key).
FocusGained(WidgetInfo),
/// Text selection was updated.
TextSelectionChanged(WidgetInfo),
/// A widget's value changed.
ValueChanged(WidgetInfo),
}
impl std::fmt::Debug for OutputEvent {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Clicked(wi) => write!(f, "Clicked({:?})", wi),
Self::DoubleClicked(wi) => write!(f, "DoubleClicked({:?})", wi),
Self::TripleClicked(wi) => write!(f, "TripleClicked({:?})", wi),
Self::FocusGained(wi) => write!(f, "FocusGained({:?})", wi),
Self::TextSelectionChanged(wi) => write!(f, "TextSelectionChanged({:?})", wi),
Self::ValueChanged(wi) => write!(f, "ValueChanged({:?})", wi),
}
}
}
/// Describes a widget such as a [`crate::Button`] or a [`crate::TextEdit`].
#[derive(Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct WidgetInfo {
/// The type of widget this is.
pub typ: WidgetType,
/// Whether the widget is enabled.
pub enabled: bool,
/// The text on labels, buttons, checkboxes etc.
pub label: Option<String>,
/// The contents of some editable text (for [`TextEdit`](crate::TextEdit) fields).
pub current_text_value: Option<String>,
/// The previous text value.
pub prev_text_value: Option<String>,
/// The current value of checkboxes and radio buttons.
pub selected: Option<bool>,
/// The current value of sliders etc.
pub value: Option<f64>,
/// Selected range of characters in [`Self::current_text_value`].
pub text_selection: Option<std::ops::RangeInclusive<usize>>,
}
impl std::fmt::Debug for WidgetInfo {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let Self {
typ,
enabled,
label,
current_text_value: text_value,
prev_text_value,
selected,
value,
text_selection,
} = self;
let mut s = f.debug_struct("WidgetInfo");
s.field("typ", typ);
s.field("enabled", enabled);
if let Some(label) = label {
s.field("label", label);
}
if let Some(text_value) = text_value {
s.field("text_value", text_value);
}
if let Some(prev_text_value) = prev_text_value {
s.field("prev_text_value", prev_text_value);
}
if let Some(selected) = selected {
s.field("selected", selected);
}
if let Some(value) = value {
s.field("value", value);
}
if let Some(text_selection) = text_selection {
s.field("text_selection", text_selection);
}
s.finish()
}
}
impl WidgetInfo {
pub fn new(typ: WidgetType) -> Self {
Self {
typ,
enabled: true,
label: None,
current_text_value: None,
prev_text_value: None,
selected: None,
value: None,
text_selection: None,
}
}
#[allow(clippy::needless_pass_by_value)]
pub fn labeled(typ: WidgetType, label: impl ToString) -> Self {
Self {
label: Some(label.to_string()),
..Self::new(typ)
}
}
/// checkboxes, radio-buttons etc
#[allow(clippy::needless_pass_by_value)]
pub fn selected(typ: WidgetType, selected: bool, label: impl ToString) -> Self {
Self {
label: Some(label.to_string()),
selected: Some(selected),
..Self::new(typ)
}
}
pub fn drag_value(value: f64) -> Self {
Self {
value: Some(value),
..Self::new(WidgetType::DragValue)
}
}
#[allow(clippy::needless_pass_by_value)]
pub fn slider(value: f64, label: impl ToString) -> Self {
let label = label.to_string();
Self {
label: if label.is_empty() { None } else { Some(label) },
value: Some(value),
..Self::new(WidgetType::Slider)
}
}
#[allow(clippy::needless_pass_by_value)]
pub fn text_edit(prev_text_value: impl ToString, text_value: impl ToString) -> Self {
let text_value = text_value.to_string();
let prev_text_value = prev_text_value.to_string();
let prev_text_value = if text_value == prev_text_value {
None
} else {
Some(prev_text_value)
};
Self {
current_text_value: Some(text_value),
prev_text_value,
..Self::new(WidgetType::TextEdit)
}
}
#[allow(clippy::needless_pass_by_value)]
pub fn text_selection_changed(
text_selection: std::ops::RangeInclusive<usize>,
current_text_value: impl ToString,
) -> Self {
Self {
text_selection: Some(text_selection),
current_text_value: Some(current_text_value.to_string()),
..Self::new(WidgetType::TextEdit)
}
}
/// This can be used by a text-to-speech system to describe the widget.
pub fn description(&self) -> String {
let Self {
typ,
enabled,
label,
current_text_value: text_value,
prev_text_value: _,
selected,
value,
text_selection: _,
} = self;
// TODO(emilk): localization
let widget_type = match typ {
WidgetType::Link => "link",
WidgetType::TextEdit => "text edit",
WidgetType::Button => "button",
WidgetType::Checkbox => "checkbox",
WidgetType::RadioButton => "radio",
WidgetType::SelectableLabel => "selectable",
WidgetType::ComboBox => "combo",
WidgetType::Slider => "slider",
WidgetType::DragValue => "drag value",
WidgetType::ColorButton => "color button",
WidgetType::ImageButton => "image button",
WidgetType::CollapsingHeader => "collapsing header",
WidgetType::Label | WidgetType::Other => "",
};
let mut description = widget_type.to_owned();
if let Some(selected) = selected {
if *typ == WidgetType::Checkbox {
let state = if *selected { "checked" } else { "unchecked" };
description = format!("{} {}", state, description);
} else {
description += if *selected { "selected" } else { "" };
};
}
if let Some(label) = label {
description = format!("{}: {}", label, description);
}
if typ == &WidgetType::TextEdit {
let text;
if let Some(text_value) = text_value {
if text_value.is_empty() {
text = "blank".into();
} else {
text = text_value.to_string();
}
} else {
text = "blank".into();
}
description = format!("{}: {}", text, description);
}
if let Some(value) = value {
description += " ";
description += &value.to_string();
}
if !enabled {
description += ": disabled";
}
description.trim().to_owned()
}
}
+142
View File
@@ -0,0 +1,142 @@
use std::ops::RangeInclusive;
use crate::*;
#[derive(Clone, Copy, Debug)]
pub(crate) struct TooltipRect {
pub id: Id,
pub rect: Rect,
pub count: usize,
}
/// State that is collected during a frame and then cleared.
/// Short-term (single frame) memory.
#[derive(Clone)]
pub(crate) struct FrameState {
/// All [`Id`]s that were used this frame.
/// Used to debug [`Id`] clashes of widgets.
pub(crate) used_ids: IdMap<Rect>,
/// Starts off as the screen_rect, shrinks as panels are added.
/// The [`CentralPanel`] does not change this.
/// This is the area available to Window's.
pub(crate) available_rect: Rect,
/// Starts off as the screen_rect, shrinks as panels are added.
/// The [`CentralPanel`] retracts from this.
pub(crate) unused_rect: Rect,
/// How much space is used by panels.
pub(crate) used_by_panels: Rect,
/// If a tooltip has been shown this frame, where was it?
/// This is used to prevent multiple tooltips to cover each other.
/// Initialized to `None` at the start of each frame.
pub(crate) tooltip_rect: Option<TooltipRect>,
/// Set to [`InputState::scroll_delta`] on the start of each frame.
///
/// Cleared by the first [`ScrollArea`] that makes use of it.
pub(crate) scroll_delta: Vec2, // TODO(emilk): move to `InputState` ?
/// horizontal, vertical
pub(crate) scroll_target: [Option<(RangeInclusive<f32>, Option<Align>)>; 2],
}
impl Default for FrameState {
fn default() -> Self {
Self {
used_ids: Default::default(),
available_rect: Rect::NAN,
unused_rect: Rect::NAN,
used_by_panels: Rect::NAN,
tooltip_rect: None,
scroll_delta: Vec2::ZERO,
scroll_target: [None, None],
}
}
}
impl FrameState {
pub(crate) fn begin_frame(&mut self, input: &InputState) {
let Self {
used_ids,
available_rect,
unused_rect,
used_by_panels,
tooltip_rect,
scroll_delta,
scroll_target,
} = self;
used_ids.clear();
*available_rect = input.screen_rect();
*unused_rect = input.screen_rect();
*used_by_panels = Rect::NOTHING;
*tooltip_rect = None;
*scroll_delta = input.scroll_delta;
*scroll_target = [None, None];
}
/// How much space is still available after panels has been added.
/// This is the "background" area, what egui doesn't cover with panels (but may cover with windows).
/// This is also the area to which windows are constrained.
pub(crate) fn available_rect(&self) -> Rect {
crate::egui_assert!(
self.available_rect.is_finite(),
"Called `available_rect()` before `Context::run()`"
);
self.available_rect
}
/// Shrink `available_rect`.
pub(crate) fn allocate_left_panel(&mut self, panel_rect: Rect) {
crate::egui_assert!(
panel_rect.min.distance(self.available_rect.min) < 0.1,
"Mismatching left panel. You must not create a panel from within another panel."
);
self.available_rect.min.x = panel_rect.max.x;
self.unused_rect.min.x = panel_rect.max.x;
self.used_by_panels = self.used_by_panels.union(panel_rect);
}
/// Shrink `available_rect`.
pub(crate) fn allocate_right_panel(&mut self, panel_rect: Rect) {
crate::egui_assert!(
panel_rect.max.distance(self.available_rect.max) < 0.1,
"Mismatching right panel. You must not create a panel from within another panel."
);
self.available_rect.max.x = panel_rect.min.x;
self.unused_rect.max.x = panel_rect.min.x;
self.used_by_panels = self.used_by_panels.union(panel_rect);
}
/// Shrink `available_rect`.
pub(crate) fn allocate_top_panel(&mut self, panel_rect: Rect) {
crate::egui_assert!(
panel_rect.min.distance(self.available_rect.min) < 0.1,
"Mismatching top panel. You must not create a panel from within another panel."
);
self.available_rect.min.y = panel_rect.max.y;
self.unused_rect.min.y = panel_rect.max.y;
self.used_by_panels = self.used_by_panels.union(panel_rect);
}
/// Shrink `available_rect`.
pub(crate) fn allocate_bottom_panel(&mut self, panel_rect: Rect) {
crate::egui_assert!(
panel_rect.max.distance(self.available_rect.max) < 0.1,
"Mismatching bottom panel. You must not create a panel from within another panel."
);
self.available_rect.max.y = panel_rect.min.y;
self.unused_rect.max.y = panel_rect.min.y;
self.used_by_panels = self.used_by_panels.union(panel_rect);
}
pub(crate) fn allocate_central_panel(&mut self, panel_rect: Rect) {
// Note: we do not shrink `available_rect`, because
// we allow windows to cover the CentralPanel.
self.unused_rect = Rect::NOTHING; // Nothing left unused after this
self.used_by_panels = self.used_by_panels.union(panel_rect);
}
}
+390
View File
@@ -0,0 +1,390 @@
use crate::*;
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct State {
col_widths: Vec<f32>,
row_heights: Vec<f32>,
}
impl State {
pub fn load(ctx: &Context, id: Id) -> Option<Self> {
ctx.data().get_temp(id)
}
pub fn store(self, ctx: &Context, id: Id) {
// We don't persist Grids, because
// 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
ctx.data().insert_temp(id, self);
}
fn set_min_col_width(&mut self, col: usize, width: f32) {
self.col_widths
.resize(self.col_widths.len().max(col + 1), 0.0);
self.col_widths[col] = self.col_widths[col].max(width);
}
fn set_min_row_height(&mut self, row: usize, height: f32) {
self.row_heights
.resize(self.row_heights.len().max(row + 1), 0.0);
self.row_heights[row] = self.row_heights[row].max(height);
}
fn col_width(&self, col: usize) -> Option<f32> {
self.col_widths.get(col).copied()
}
fn row_height(&self, row: usize) -> Option<f32> {
self.row_heights.get(row).copied()
}
fn full_width(&self, x_spacing: f32) -> f32 {
self.col_widths.iter().sum::<f32>()
+ (self.col_widths.len().at_least(1) - 1) as f32 * x_spacing
}
}
// ----------------------------------------------------------------------------
pub(crate) struct GridLayout {
ctx: Context,
style: std::sync::Arc<Style>,
id: Id,
/// State previous frame (if any).
/// This can be used to predict future sizes of cells.
prev_state: State,
/// State accumulated during the current frame.
curr_state: State,
initial_available: Rect,
// Options:
num_columns: Option<usize>,
spacing: Vec2,
min_cell_size: Vec2,
max_cell_size: Vec2,
striped: bool,
// Cursor:
col: usize,
row: usize,
}
impl GridLayout {
pub(crate) fn new(ui: &Ui, id: Id) -> Self {
let prev_state = State::load(ui.ctx(), id).unwrap_or_default();
// TODO(emilk): respect current layout
let initial_available = ui.placer().max_rect().intersect(ui.cursor());
crate::egui_assert!(
initial_available.min.x.is_finite(),
"Grid not yet available for right-to-left layouts"
);
ui.ctx().check_for_id_clash(id, initial_available, "Grid");
Self {
ctx: ui.ctx().clone(),
style: ui.style().clone(),
id,
prev_state,
curr_state: State::default(),
initial_available,
num_columns: None,
spacing: ui.spacing().item_spacing,
min_cell_size: ui.spacing().interact_size,
max_cell_size: Vec2::INFINITY,
striped: false,
col: 0,
row: 0,
}
}
}
impl GridLayout {
fn prev_col_width(&self, col: usize) -> f32 {
self.prev_state
.col_width(col)
.unwrap_or(self.min_cell_size.x)
}
fn prev_row_height(&self, row: usize) -> f32 {
self.prev_state
.row_height(row)
.unwrap_or(self.min_cell_size.y)
}
pub(crate) fn wrap_text(&self) -> bool {
self.max_cell_size.x.is_finite()
}
pub(crate) fn available_rect(&self, region: &Region) -> Rect {
let is_last_column = Some(self.col + 1) == self.num_columns;
let width = if is_last_column {
(self.initial_available.right() - region.cursor.left()).at_most(self.max_cell_size.x)
} else if self.max_cell_size.x.is_finite() {
// TODO(emilk): should probably heed `prev_state` here too
self.max_cell_size.x
} else {
// If we want to allow width-filling widgets like [`Separator`] in one of the first cells
// then we need to make sure they don't spill out of the first cell:
self.prev_state
.col_width(self.col)
.or_else(|| self.curr_state.col_width(self.col))
.unwrap_or(self.min_cell_size.x)
};
// If something above was wider, we can be wider:
let width = width.max(self.curr_state.col_width(self.col).unwrap_or(0.0));
let available = region.max_rect.intersect(region.cursor);
let height = region.max_rect.max.y - available.top();
let height = height
.at_least(self.min_cell_size.y)
.at_most(self.max_cell_size.y);
Rect::from_min_size(available.min, vec2(width, height))
}
pub(crate) fn next_cell(&self, cursor: Rect, child_size: Vec2) -> Rect {
let width = self.prev_state.col_width(self.col).unwrap_or(0.0);
let height = self.prev_row_height(self.row);
let size = child_size.max(vec2(width, height));
Rect::from_min_size(cursor.min, size)
}
#[allow(clippy::unused_self)]
pub(crate) fn align_size_within_rect(&self, size: Vec2, frame: Rect) -> Rect {
// TODO(emilk): allow this alignment to be customized
Align2::LEFT_CENTER.align_size_within_rect(size, frame)
}
pub(crate) fn justify_and_align(&self, frame: Rect, size: Vec2) -> Rect {
self.align_size_within_rect(size, frame)
}
pub(crate) fn advance(&mut self, cursor: &mut Rect, _frame_rect: Rect, widget_rect: Rect) {
let debug_expand_width = self.style.debug.show_expand_width;
let debug_expand_height = self.style.debug.show_expand_height;
if debug_expand_width || debug_expand_height {
let rect = widget_rect;
let too_wide = rect.width() > self.prev_col_width(self.col);
let too_high = rect.height() > self.prev_row_height(self.row);
if (debug_expand_width && too_wide) || (debug_expand_height && too_high) {
let painter = self.ctx.debug_painter();
painter.rect_stroke(rect, 0.0, (1.0, Color32::LIGHT_BLUE));
let stroke = Stroke::new(2.5, Color32::from_rgb(200, 0, 0));
let paint_line_seg = |a, b| painter.line_segment([a, b], stroke);
if debug_expand_width && too_wide {
paint_line_seg(rect.left_top(), rect.left_bottom());
paint_line_seg(rect.left_center(), rect.right_center());
paint_line_seg(rect.right_top(), rect.right_bottom());
}
}
}
self.curr_state
.set_min_col_width(self.col, widget_rect.width().max(self.min_cell_size.x));
self.curr_state
.set_min_row_height(self.row, widget_rect.height().max(self.min_cell_size.y));
cursor.min.x += self.prev_col_width(self.col) + self.spacing.x;
self.col += 1;
}
pub(crate) fn end_row(&mut self, cursor: &mut Rect, painter: &Painter) {
cursor.min.x = self.initial_available.min.x;
cursor.min.y += self.spacing.y;
cursor.min.y += self
.curr_state
.row_height(self.row)
.unwrap_or(self.min_cell_size.y);
self.col = 0;
self.row += 1;
if self.striped && self.row % 2 == 1 {
if let Some(height) = self.prev_state.row_height(self.row) {
// Paint background for coming row:
let size = Vec2::new(self.prev_state.full_width(self.spacing.x), height);
let rect = Rect::from_min_size(cursor.min, size);
let rect = rect.expand2(0.5 * self.spacing.y * Vec2::Y);
let rect = rect.expand2(2.0 * Vec2::X); // HACK: just looks better with some spacing on the sides
painter.rect_filled(rect, 2.0, self.style.visuals.faint_bg_color);
}
}
}
pub(crate) fn save(&self) {
if self.curr_state != self.prev_state {
self.curr_state.clone().store(&self.ctx, self.id);
self.ctx.request_repaint();
}
}
}
// ----------------------------------------------------------------------------
/// A simple grid layout.
///
/// The cells are always layed out left to right, top-down.
/// The contents of each cell will be aligned to the left and center.
///
/// If you want to add multiple widgets to a cell you need to group them with
/// [`Ui::horizontal`], [`Ui::vertical`] etc.
///
/// ```
/// # egui::__run_test_ui(|ui| {
/// egui::Grid::new("some_unique_id").show(ui, |ui| {
/// ui.label("First row, first column");
/// ui.label("First row, second column");
/// ui.end_row();
///
/// ui.label("Second row, first column");
/// ui.label("Second row, second column");
/// ui.label("Second row, third column");
/// ui.end_row();
///
/// ui.horizontal(|ui| { ui.label("Same"); ui.label("cell"); });
/// ui.label("Third row, second column");
/// ui.end_row();
/// });
/// # });
/// ```
#[must_use = "You should call .show()"]
pub struct Grid {
id_source: Id,
num_columns: Option<usize>,
striped: bool,
min_col_width: Option<f32>,
min_row_height: Option<f32>,
max_cell_size: Vec2,
spacing: Option<Vec2>,
start_row: usize,
}
impl Grid {
/// Create a new [`Grid`] with a locally unique identifier.
pub fn new(id_source: impl std::hash::Hash) -> Self {
Self {
id_source: Id::new(id_source),
num_columns: None,
striped: false,
min_col_width: None,
min_row_height: None,
max_cell_size: Vec2::INFINITY,
spacing: None,
start_row: 0,
}
}
/// Setting this will allow the last column to expand to take up the rest of the space of the parent [`Ui`].
pub fn num_columns(mut self, num_columns: usize) -> Self {
self.num_columns = Some(num_columns);
self
}
/// If `true`, add a subtle background color to every other row.
///
/// This can make a table easier to read.
/// Default: `false`.
pub fn striped(mut self, striped: bool) -> Self {
self.striped = striped;
self
}
/// Set minimum width of each column.
/// Default: [`crate::style::Spacing::interact_size`]`.x`.
pub fn min_col_width(mut self, min_col_width: f32) -> Self {
self.min_col_width = Some(min_col_width);
self
}
/// Set minimum height of each row.
/// Default: [`crate::style::Spacing::interact_size`]`.y`.
pub fn min_row_height(mut self, min_row_height: f32) -> Self {
self.min_row_height = Some(min_row_height);
self
}
/// Set soft maximum width (wrapping width) of each column.
pub fn max_col_width(mut self, max_col_width: f32) -> Self {
self.max_cell_size.x = max_col_width;
self
}
/// Set spacing between columns/rows.
/// Default: [`crate::style::Spacing::item_spacing`].
pub fn spacing(mut self, spacing: impl Into<Vec2>) -> Self {
self.spacing = Some(spacing.into());
self
}
/// Change which row number the grid starts on.
/// This can be useful when you have a large [`Grid`] inside of [`ScrollArea::show_rows`].
pub fn start_row(mut self, start_row: usize) -> Self {
self.start_row = start_row;
self
}
}
impl Grid {
pub fn show<R>(self, ui: &mut Ui, add_contents: impl FnOnce(&mut Ui) -> R) -> InnerResponse<R> {
self.show_dyn(ui, Box::new(add_contents))
}
fn show_dyn<'c, R>(
self,
ui: &mut Ui,
add_contents: Box<dyn FnOnce(&mut Ui) -> R + 'c>,
) -> InnerResponse<R> {
let Self {
id_source,
num_columns,
striped,
min_col_width,
min_row_height,
max_cell_size,
spacing,
start_row,
} = self;
let min_col_width = min_col_width.unwrap_or_else(|| ui.spacing().interact_size.x);
let min_row_height = min_row_height.unwrap_or_else(|| ui.spacing().interact_size.y);
let spacing = spacing.unwrap_or_else(|| ui.spacing().item_spacing);
// Each grid cell is aligned LEFT_CENTER.
// If somebody wants to wrap more things inside a cell,
// then we should pick a default layout that matches that alignment,
// which we do here:
let max_rect = ui.cursor().intersect(ui.max_rect());
ui.allocate_ui_at_rect(max_rect, |ui| {
ui.horizontal(|ui| {
let id = ui.make_persistent_id(id_source);
let grid = GridLayout {
num_columns,
striped,
min_cell_size: vec2(min_col_width, min_row_height),
max_cell_size,
spacing,
row: start_row,
..GridLayout::new(ui, id)
};
ui.set_grid(grid);
let r = add_contents(ui);
ui.save_grid();
r
})
.inner
})
}
}
+152
View File
@@ -0,0 +1,152 @@
// TODO(emilk): have separate types `PositionId` and `UniqueId`. ?
/// egui tracks widgets frame-to-frame using [`Id`]s.
///
/// For instance, if you start dragging a slider one frame, egui stores
/// the sliders [`Id`] as the current active id so that next frame when
/// you move the mouse the same slider changes, even if the mouse has
/// moved outside the slider.
///
/// For some widgets [`Id`]s are also used to persist some state about the
/// widgets, such as Window position or whether not a collapsing header region is open.
///
/// This implies that the [`Id`]s must be unique.
///
/// For simple things like sliders and buttons that don't have any memory and
/// doesn't move we can use the location of the widget as a source of identity.
/// For instance, a slider only needs a unique and persistent ID while you are
/// dragging the slider. As long as it is still while moving, that is fine.
///
/// For things that need to persist state even after moving (windows, collapsing headers)
/// the location of the widgets is obviously not good enough. For instance,
/// a collapsing region needs to remember whether or not it is open even
/// if the layout next frame is different and the collapsing is not lower down
/// on the screen.
///
/// Then there are widgets that need no identifiers at all, like labels,
/// because they have no state nor are interacted with.
#[derive(Clone, Copy, Hash, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct Id(u64);
impl Id {
/// A special [`Id`], in particular as a key to [`crate::Memory::data`]
/// for when there is no particular widget to attach the data.
///
/// The null [`Id`] is still a valid id to use in all circumstances,
/// though obviously it will lead to a lot of collisions if you do use it!
pub fn null() -> Self {
Self(0)
}
pub(crate) fn background() -> Self {
Self(1)
}
/// Generate a new [`Id`] by hashing some source (e.g. a string or integer).
pub fn new(source: impl std::hash::Hash) -> Id {
use std::hash::Hasher;
let mut hasher = epaint::ahash::AHasher::default();
source.hash(&mut hasher);
Id(hasher.finish())
}
/// Generate a new [`Id`] by hashing the parent [`Id`] and the given argument.
pub fn with(self, child: impl std::hash::Hash) -> Id {
use std::hash::Hasher;
let mut hasher = epaint::ahash::AHasher::default();
hasher.write_u64(self.0);
child.hash(&mut hasher);
Id(hasher.finish())
}
/// Short and readable summary
pub fn short_debug_format(&self) -> String {
format!("{:04X}", self.0 as u16)
}
#[inline(always)]
pub(crate) fn value(&self) -> u64 {
self.0
}
}
impl std::fmt::Debug for Id {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:016X}", self.0)
}
}
// ----------------------------------------------------------------------------
// Idea taken from the `nohash_hasher` crate.
#[derive(Default)]
pub struct IdHasher(u64);
impl std::hash::Hasher for IdHasher {
fn write(&mut self, _: &[u8]) {
unreachable!("Invalid use of IdHasher");
}
fn write_u8(&mut self, _n: u8) {
unreachable!("Invalid use of IdHasher");
}
fn write_u16(&mut self, _n: u16) {
unreachable!("Invalid use of IdHasher");
}
fn write_u32(&mut self, _n: u32) {
unreachable!("Invalid use of IdHasher");
}
#[inline(always)]
fn write_u64(&mut self, n: u64) {
self.0 = n;
}
fn write_usize(&mut self, _n: usize) {
unreachable!("Invalid use of IdHasher");
}
fn write_i8(&mut self, _n: i8) {
unreachable!("Invalid use of IdHasher");
}
fn write_i16(&mut self, _n: i16) {
unreachable!("Invalid use of IdHasher");
}
fn write_i32(&mut self, _n: i32) {
unreachable!("Invalid use of IdHasher");
}
fn write_i64(&mut self, _n: i64) {
unreachable!("Invalid use of IdHasher");
}
fn write_isize(&mut self, _n: isize) {
unreachable!("Invalid use of IdHasher");
}
#[inline(always)]
fn finish(&self) -> u64 {
self.0
}
}
#[derive(Copy, Clone, Debug, Default)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct BuilIdHasher {}
impl std::hash::BuildHasher for BuilIdHasher {
type Hasher = IdHasher;
#[inline(always)]
fn build_hasher(&self) -> IdHasher {
IdHasher::default()
}
}
/// `IdMap<V>` is a `HashMap<Id, V>` optimized by knowing that [`Id`] has good entropy, and doesn't need more hashing.
pub type IdMap<V> = std::collections::HashMap<Id, V, BuilIdHasher>;
+938
View File
@@ -0,0 +1,938 @@
mod touch_state;
use crate::data::input::*;
use crate::{emath::*, util::History};
use std::collections::{BTreeMap, HashSet};
pub use crate::data::input::Key;
pub use touch_state::MultiTouchInfo;
use touch_state::TouchState;
/// If the pointer moves more than this, it won't become a click (but it is still a drag)
const MAX_CLICK_DIST: f32 = 6.0; // TODO(emilk): move to settings
/// If the pointer is down for longer than this, it won't become a click (but it is still a drag)
const MAX_CLICK_DURATION: f64 = 0.6; // TODO(emilk): move to settings
/// The new pointer press must come within this many seconds from previous pointer release
const MAX_DOUBLE_CLICK_DELAY: f64 = 0.3; // TODO(emilk): move to settings
/// Input state that egui updates each frame.
///
/// You can check if `egui` is using the inputs using
/// [`crate::Context::wants_pointer_input`] and [`crate::Context::wants_keyboard_input`].
#[derive(Clone, Debug)]
pub struct InputState {
/// The raw input we got this frame from the backend.
pub raw: RawInput,
/// State of the mouse or simple touch gestures which can be mapped to mouse operations.
pub pointer: PointerState,
/// State of touches, except those covered by PointerState (like clicks and drags).
/// (We keep a separate [`TouchState`] for each encountered touch device.)
touch_states: BTreeMap<TouchDeviceId, TouchState>,
/// How many points the user scrolled.
///
/// The delta dictates how the _content_ should move.
///
/// A positive X-value indicates the content is being moved right,
/// as when swiping right on a touch-screen or track-pad with natural scrolling.
///
/// A positive Y-value indicates the content is being moved down,
/// as when swiping down on a touch-screen or track-pad with natural scrolling.
pub scroll_delta: Vec2,
/// Zoom scale factor this frame (e.g. from ctrl-scroll or pinch gesture).
///
/// * `zoom = 1`: no change.
/// * `zoom < 1`: pinch together
/// * `zoom > 1`: pinch spread
zoom_factor_delta: f32,
/// Position and size of the egui area.
pub screen_rect: Rect,
/// Also known as device pixel ratio, > 1 for high resolution screens.
pub pixels_per_point: f32,
/// Maximum size of one side of a texture.
///
/// This depends on the backend.
pub max_texture_side: usize,
/// Time in seconds. Relative to whatever. Used for animation.
pub time: f64,
/// Time since last frame, in seconds.
///
/// This can be very unstable in reactive mode (when we don't paint each frame).
/// For animations it is therefore better to use [`Self::stable_dt`].
pub unstable_dt: f32,
/// Estimated time until next frame (provided we repaint right away).
///
/// Used for animations to get instant feedback (avoid frame delay).
/// Should be set to the expected time between frames when painting at vsync speeds.
///
/// On most integrations this has a fixed value of `1.0 / 60.0`, so it is not a very accurate estimate.
pub predicted_dt: f32,
/// Time since last frame (in seconds), but gracefully handles the first frame after sleeping in reactive mode.
///
/// In reactive mode (available in e.g. `eframe`), `egui` only updates when there is new input
/// or something is animating.
/// This can lead to large gaps of time (sleep), leading to large [`Self::unstable_dt`].
///
/// If `egui` requested a repaint the previous frame, then `egui` will use
/// `stable_dt = unstable_dt;`, but if `egui` did not not request a repaint last frame,
/// then `egui` will assume `unstable_dt` is too large, and will use
/// `stable_dt = predicted_dt;`.
///
/// This means that for the first frame after a sleep,
/// `stable_dt` will be a prediction of the delta-time until the next frame,
/// and in all other situations this will be an accurate measurement of time passed
/// since the previous frame.
///
/// Note that a frame can still stall for various reasons, so `stable_dt` can
/// still be unusually large in some situations.
///
/// When animating something, it is recommended that you use something like
/// `stable_dt.min(0.1)` - this will give you smooth animations when the framerate is good
/// (even in reactive mode), but will avoid large jumps when framerate is bad,
/// and will effectively slow down the animation when FPS drops below 10.
pub stable_dt: f32,
/// Which modifier keys are down at the start of the frame?
pub modifiers: Modifiers,
// The keys that are currently being held down.
pub keys_down: HashSet<Key>,
/// In-order events received this frame
pub events: Vec<Event>,
}
impl Default for InputState {
fn default() -> Self {
Self {
raw: Default::default(),
pointer: Default::default(),
touch_states: Default::default(),
scroll_delta: Vec2::ZERO,
zoom_factor_delta: 1.0,
screen_rect: Rect::from_min_size(Default::default(), vec2(10_000.0, 10_000.0)),
pixels_per_point: 1.0,
max_texture_side: 2048,
time: 0.0,
unstable_dt: 1.0 / 60.0,
predicted_dt: 1.0 / 60.0,
stable_dt: 1.0 / 60.0,
modifiers: Default::default(),
keys_down: Default::default(),
events: Default::default(),
}
}
}
impl InputState {
#[must_use]
pub fn begin_frame(mut self, new: RawInput, requested_repaint_last_frame: bool) -> InputState {
let time = new.time.unwrap_or(self.time + new.predicted_dt as f64);
let unstable_dt = (time - self.time) as f32;
let stable_dt = if requested_repaint_last_frame {
// we should have had a repaint straight away,
// so this should be trustable.
unstable_dt
} else {
new.predicted_dt
};
let screen_rect = new.screen_rect.unwrap_or(self.screen_rect);
self.create_touch_states_for_new_devices(&new.events);
for touch_state in self.touch_states.values_mut() {
touch_state.begin_frame(time, &new, self.pointer.interact_pos);
}
let pointer = self.pointer.begin_frame(time, &new);
let mut keys_down = self.keys_down;
let mut scroll_delta = Vec2::ZERO;
let mut zoom_factor_delta = 1.0;
for event in &new.events {
match event {
Event::Key { key, pressed, .. } => {
if *pressed {
keys_down.insert(*key);
} else {
keys_down.remove(key);
}
}
Event::Scroll(delta) => {
scroll_delta += *delta;
}
Event::Zoom(factor) => {
zoom_factor_delta *= *factor;
}
_ => {}
}
}
InputState {
pointer,
touch_states: self.touch_states,
scroll_delta,
zoom_factor_delta,
screen_rect,
pixels_per_point: new.pixels_per_point.unwrap_or(self.pixels_per_point),
max_texture_side: new.max_texture_side.unwrap_or(self.max_texture_side),
time,
unstable_dt,
predicted_dt: new.predicted_dt,
stable_dt,
modifiers: new.modifiers,
keys_down,
events: new.events.clone(), // TODO(emilk): remove clone() and use raw.events
raw: new,
}
}
#[inline(always)]
pub fn screen_rect(&self) -> Rect {
self.screen_rect
}
/// Zoom scale factor this frame (e.g. from ctrl-scroll or pinch gesture).
/// * `zoom = 1`: no change
/// * `zoom < 1`: pinch together
/// * `zoom > 1`: pinch spread
#[inline(always)]
pub fn zoom_delta(&self) -> f32 {
// If a multi touch gesture is detected, it measures the exact and linear proportions of
// the distances of the finger tips. It is therefore potentially more accurate than
// `zoom_factor_delta` which is based on the `ctrl-scroll` event which, in turn, may be
// synthesized from an original touch gesture.
self.multi_touch()
.map_or(self.zoom_factor_delta, |touch| touch.zoom_delta)
}
/// 2D non-proportional zoom scale factor this frame (e.g. from ctrl-scroll or pinch gesture).
///
/// For multitouch devices the user can do a horizontal or vertical pinch gesture.
/// In these cases a non-proportional zoom factor is a available.
/// In other cases, this reverts to `Vec2::splat(self.zoom_delta())`.
///
/// For horizontal pinches, this will return `[z, 1]`,
/// for vertical pinches this will return `[1, z]`,
/// and otherwise this will return `[z, z]`,
/// where `z` is the zoom factor:
/// * `zoom = 1`: no change
/// * `zoom < 1`: pinch together
/// * `zoom > 1`: pinch spread
#[inline(always)]
pub fn zoom_delta_2d(&self) -> Vec2 {
// If a multi touch gesture is detected, it measures the exact and linear proportions of
// the distances of the finger tips. It is therefore potentially more accurate than
// `zoom_factor_delta` which is based on the `ctrl-scroll` event which, in turn, may be
// synthesized from an original touch gesture.
self.multi_touch().map_or_else(
|| Vec2::splat(self.zoom_factor_delta),
|touch| touch.zoom_delta_2d,
)
}
pub fn wants_repaint(&self) -> bool {
self.pointer.wants_repaint() || self.scroll_delta != Vec2::ZERO || !self.events.is_empty()
}
/// Check for a key press. If found, `true` is returned and the key pressed is consumed, so that this will only return `true` once.
pub fn consume_key(&mut self, modifiers: Modifiers, key: Key) -> bool {
let mut match_found = false;
self.events.retain(|event| {
let is_match = matches!(
event,
Event::Key {
key: ev_key,
modifiers: ev_mods,
pressed: true
} if *ev_key == key && ev_mods.matches(modifiers)
);
match_found |= is_match;
!is_match
});
match_found
}
/// Was the given key pressed this frame?
pub fn key_pressed(&self, desired_key: Key) -> bool {
self.num_presses(desired_key) > 0
}
/// How many times were the given key pressed this frame?
pub fn num_presses(&self, desired_key: Key) -> usize {
self.events
.iter()
.filter(|event| {
matches!(
event,
Event::Key {
key,
pressed: true,
..
} if *key == desired_key
)
})
.count()
}
/// Is the given key currently held down?
pub fn key_down(&self, desired_key: Key) -> bool {
self.keys_down.contains(&desired_key)
}
/// Was the given key released this frame?
pub fn key_released(&self, desired_key: Key) -> bool {
self.events.iter().any(|event| {
matches!(
event,
Event::Key {
key,
pressed: false,
..
} if *key == desired_key
)
})
}
/// Also known as device pixel ratio, > 1 for high resolution screens.
#[inline(always)]
pub fn pixels_per_point(&self) -> f32 {
self.pixels_per_point
}
/// Size of a physical pixel in logical gui coordinates (points).
#[inline(always)]
pub fn physical_pixel_size(&self) -> f32 {
1.0 / self.pixels_per_point()
}
/// How imprecise do we expect the mouse/touch input to be?
/// Returns imprecision in points.
#[inline(always)]
pub fn aim_radius(&self) -> f32 {
// TODO(emilk): multiply by ~3 for touch inputs because fingers are fat
self.physical_pixel_size()
}
/// Returns details about the currently ongoing multi-touch gesture, if any. Note that this
/// method returns `None` for single-touch gestures (click, drag, …).
///
/// ```
/// # use egui::emath::Rot2;
/// # egui::__run_test_ui(|ui| {
/// let mut zoom = 1.0; // no zoom
/// let mut rotation = 0.0; // no rotation
/// let multi_touch = ui.input().multi_touch();
/// if let Some(multi_touch) = multi_touch {
/// zoom *= multi_touch.zoom_delta;
/// rotation += multi_touch.rotation_delta;
/// }
/// let transform = zoom * Rot2::from_angle(rotation);
/// # });
/// ```
///
/// By far not all touch devices are supported, and the details depend on the `egui`
/// integration backend you are using. `eframe` web supports multi touch for most mobile
/// devices, but not for a `Trackpad` on `MacOS`, for example. The backend has to be able to
/// capture native touch events, but many browsers seem to pass such events only for touch
/// _screens_, but not touch _pads._
///
/// Refer to [`MultiTouchInfo`] for details about the touch information available.
///
/// Consider using `zoom_delta()` instead of `MultiTouchInfo::zoom_delta` as the former
/// delivers a synthetic zoom factor based on ctrl-scroll events, as a fallback.
pub fn multi_touch(&self) -> Option<MultiTouchInfo> {
// In case of multiple touch devices simply pick the touch_state of the first active device
if let Some(touch_state) = self.touch_states.values().find(|t| t.is_active()) {
touch_state.info()
} else {
None
}
}
/// True if there currently are any fingers touching egui.
pub fn any_touches(&self) -> bool {
!self.touch_states.is_empty()
}
/// Scans `events` for device IDs of touch devices we have not seen before,
/// and creates a new [`TouchState`] for each such device.
fn create_touch_states_for_new_devices(&mut self, events: &[Event]) {
for event in events {
if let Event::Touch { device_id, .. } = event {
self.touch_states
.entry(*device_id)
.or_insert_with(|| TouchState::new(*device_id));
}
}
}
}
// ----------------------------------------------------------------------------
/// A pointer (mouse or touch) click.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct Click {
pub pos: Pos2,
pub button: PointerButton,
/// 1 or 2 (double-click) or 3 (triple-click)
pub count: u32,
/// Allows you to check for e.g. shift-click
pub modifiers: Modifiers,
}
impl Click {
pub fn is_double(&self) -> bool {
self.count == 2
}
pub fn is_triple(&self) -> bool {
self.count == 3
}
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum PointerEvent {
Moved(Pos2),
Pressed {
position: Pos2,
button: PointerButton,
},
Released(Option<Click>),
}
impl PointerEvent {
pub fn is_press(&self) -> bool {
matches!(self, PointerEvent::Pressed { .. })
}
pub fn is_release(&self) -> bool {
matches!(self, PointerEvent::Released(_))
}
pub fn is_click(&self) -> bool {
matches!(self, PointerEvent::Released(Some(_click)))
}
}
/// Mouse or touch state.
#[derive(Clone, Debug)]
pub struct PointerState {
/// Latest known time
time: f64,
// Consider a finger tapping a touch screen.
// What position should we report?
// The location of the touch, or `None`, because the finger is gone?
//
// For some cases we want the first: e.g. to check for interaction.
// For showing tooltips, we want the latter (no tooltips, since there are no fingers).
/// Latest reported pointer position.
/// When tapping a touch screen, this will be `None`.
latest_pos: Option<Pos2>,
/// Latest position of the mouse, but ignoring any [`Event::PointerGone`]
/// if there were interactions this frame.
/// When tapping a touch screen, this will be the location of the touch.
interact_pos: Option<Pos2>,
/// How much the pointer moved compared to last frame, in points.
delta: Vec2,
/// Current velocity of pointer.
velocity: Vec2,
/// Recent movement of the pointer.
/// Used for calculating velocity of pointer.
pos_history: History<Pos2>,
down: [bool; NUM_POINTER_BUTTONS],
/// Where did the current click/drag originate?
/// `None` if no mouse button is down.
press_origin: Option<Pos2>,
/// When did the current click/drag originate?
/// `None` if no mouse button is down.
press_start_time: Option<f64>,
/// Set to `true` if the pointer has moved too much (since being pressed)
/// for it to be registered as a click.
pub(crate) has_moved_too_much_for_a_click: bool,
/// When did the pointer get click last?
/// Used to check for double-clicks.
last_click_time: f64,
/// When did the pointer get click two clicks ago?
/// Used to check for triple-clicks.
last_last_click_time: f64,
/// All button events that occurred this frame
pub(crate) pointer_events: Vec<PointerEvent>,
}
impl Default for PointerState {
fn default() -> Self {
Self {
time: -f64::INFINITY,
latest_pos: None,
interact_pos: None,
delta: Vec2::ZERO,
velocity: Vec2::ZERO,
pos_history: History::new(0..1000, 0.1),
down: Default::default(),
press_origin: None,
press_start_time: None,
has_moved_too_much_for_a_click: false,
last_click_time: std::f64::NEG_INFINITY,
last_last_click_time: std::f64::NEG_INFINITY,
pointer_events: vec![],
}
}
}
impl PointerState {
#[must_use]
pub(crate) fn begin_frame(mut self, time: f64, new: &RawInput) -> PointerState {
self.time = time;
self.pointer_events.clear();
let old_pos = self.latest_pos;
self.interact_pos = self.latest_pos;
for event in &new.events {
match event {
Event::PointerMoved(pos) => {
let pos = *pos;
self.latest_pos = Some(pos);
self.interact_pos = Some(pos);
if let Some(press_origin) = self.press_origin {
self.has_moved_too_much_for_a_click |=
press_origin.distance(pos) > MAX_CLICK_DIST;
}
self.pointer_events.push(PointerEvent::Moved(pos));
}
Event::PointerButton {
pos,
button,
pressed,
modifiers,
} => {
let pos = *pos;
let button = *button;
let pressed = *pressed;
let modifiers = *modifiers;
self.latest_pos = Some(pos);
self.interact_pos = Some(pos);
if pressed {
// Start of a drag: we want to track the velocity for during the drag
// and ignore any incoming movement
self.pos_history.clear();
}
if pressed {
self.press_origin = Some(pos);
self.press_start_time = Some(time);
self.has_moved_too_much_for_a_click = false;
self.pointer_events.push(PointerEvent::Pressed {
position: pos,
button,
});
} else {
let clicked = self.could_any_button_be_click();
let click = if clicked {
let double_click =
(time - self.last_click_time) < MAX_DOUBLE_CLICK_DELAY;
let triple_click =
(time - self.last_last_click_time) < (MAX_DOUBLE_CLICK_DELAY * 2.0);
let count = if triple_click {
3
} else if double_click {
2
} else {
1
};
self.last_last_click_time = self.last_click_time;
self.last_click_time = time;
Some(Click {
pos,
button,
count,
modifiers,
})
} else {
None
};
self.pointer_events.push(PointerEvent::Released(click));
self.press_origin = None;
self.press_start_time = None;
}
self.down[button as usize] = pressed; // must be done after the above call to `could_any_button_be_click`
}
Event::PointerGone => {
self.latest_pos = None;
// NOTE: we do NOT clear `self.interact_pos` here. It will be cleared next frame.
}
_ => {}
}
}
self.delta = if let (Some(old_pos), Some(new_pos)) = (old_pos, self.latest_pos) {
new_pos - old_pos
} else {
Vec2::ZERO
};
if let Some(pos) = self.latest_pos {
self.pos_history.add(time, pos);
} else {
// we do not clear the `pos_history` here, because it is exactly when a finger has
// released from the touch screen that we may want to assign a velocity to whatever
// the user tried to throw.
}
self.pos_history.flush(time);
self.velocity = if self.pos_history.len() >= 3 && self.pos_history.duration() > 0.01 {
self.pos_history.velocity().unwrap_or_default()
} else {
Vec2::default()
};
self
}
fn wants_repaint(&self) -> bool {
!self.pointer_events.is_empty() || self.delta != Vec2::ZERO
}
/// How much the pointer moved compared to last frame, in points.
#[inline(always)]
pub fn delta(&self) -> Vec2 {
self.delta
}
/// Current velocity of pointer.
#[inline(always)]
pub fn velocity(&self) -> Vec2 {
self.velocity
}
/// Where did the current click/drag originate?
/// `None` if no mouse button is down.
#[inline(always)]
pub fn press_origin(&self) -> Option<Pos2> {
self.press_origin
}
/// When did the current click/drag originate?
/// `None` if no mouse button is down.
#[inline(always)]
pub fn press_start_time(&self) -> Option<f64> {
self.press_start_time
}
/// Latest reported pointer position.
/// When tapping a touch screen, this will be `None`.
#[inline(always)]
pub(crate) fn latest_pos(&self) -> Option<Pos2> {
self.latest_pos
}
/// If it is a good idea to show a tooltip, where is pointer?
#[inline(always)]
pub fn hover_pos(&self) -> Option<Pos2> {
self.latest_pos
}
/// If you detect a click or drag and wants to know where it happened, use this.
///
/// Latest position of the mouse, but ignoring any [`Event::PointerGone`]
/// if there were interactions this frame.
/// When tapping a touch screen, this will be the location of the touch.
#[inline(always)]
pub fn interact_pos(&self) -> Option<Pos2> {
self.interact_pos
}
/// Do we have a pointer?
///
/// `false` if the mouse is not over the egui area, or if no touches are down on touch screens.
#[inline(always)]
pub fn has_pointer(&self) -> bool {
self.latest_pos.is_some()
}
/// Is the pointer currently still?
/// This is smoothed so a few frames of stillness is required before this returns `true`.
#[inline(always)]
pub fn is_still(&self) -> bool {
self.velocity == Vec2::ZERO
}
/// Is the pointer currently moving?
/// This is smoothed so a few frames of stillness is required before this returns `false`.
#[inline]
pub fn is_moving(&self) -> bool {
self.velocity != Vec2::ZERO
}
/// Was any pointer button pressed (`!down -> down`) this frame?
/// This can sometimes return `true` even if `any_down() == false`
/// because a press can be shorted than one frame.
pub fn any_pressed(&self) -> bool {
self.pointer_events.iter().any(|event| event.is_press())
}
/// Was any pointer button released (`down -> !down`) this frame?
pub fn any_released(&self) -> bool {
self.pointer_events.iter().any(|event| event.is_release())
}
/// Was the button given released this frame?
pub fn button_released(&self, button: PointerButton) -> bool {
self.pointer_events
.iter()
.any(|event| matches!(event, &PointerEvent::Released(Some(Click{button: b, ..})) if button == b))
}
/// Was the primary button released this frame?
pub fn primary_released(&self) -> bool {
self.button_released(PointerButton::Primary)
}
/// Was the secondary button released this frame?
pub fn secondary_released(&self) -> bool {
self.button_released(PointerButton::Secondary)
}
/// Is any pointer button currently down?
pub fn any_down(&self) -> bool {
self.down.iter().any(|&down| down)
}
/// Were there any type of click this frame?
pub fn any_click(&self) -> bool {
self.pointer_events.iter().any(|event| event.is_click())
}
/// Was the button given clicked this frame?
pub fn button_clicked(&self, button: PointerButton) -> bool {
self.pointer_events
.iter()
.any(|event| matches!(event, &PointerEvent::Pressed { button: b, .. } if button == b))
}
/// Was the button given double clicked this frame?
pub fn button_double_clicked(&self, button: PointerButton) -> bool {
self.pointer_events
.iter()
.any(|event| matches!(&event, PointerEvent::Released(Some(click)) if click.button == button && click.is_double()))
}
/// Was the button given triple clicked this frame?
pub fn button_triple_clicked(&self, button: PointerButton) -> bool {
self.pointer_events
.iter()
.any(|event| matches!(&event, PointerEvent::Released(Some(click)) if click.button == button && click.is_triple()))
}
/// Was the primary button clicked this frame?
pub fn primary_clicked(&self) -> bool {
self.button_clicked(PointerButton::Primary)
}
/// Was the secondary button clicked this frame?
pub fn secondary_clicked(&self) -> bool {
self.button_clicked(PointerButton::Secondary)
}
// /// Was this button pressed (`!down -> down`) this frame?
// /// This can sometimes return `true` even if `any_down() == false`
// /// because a press can be shorted than one frame.
// pub fn button_pressed(&self, button: PointerButton) -> bool {
// self.pointer_events.iter().any(|event| event.is_press())
// }
// /// Was this button released (`down -> !down`) this frame?
// pub fn button_released(&self, button: PointerButton) -> bool {
// self.pointer_events.iter().any(|event| event.is_release())
// }
/// Is this button currently down?
#[inline(always)]
pub fn button_down(&self, button: PointerButton) -> bool {
self.down[button as usize]
}
/// If the pointer button is down, will it register as a click when released?
#[inline(always)]
pub(crate) fn could_any_button_be_click(&self) -> bool {
if !self.any_down() {
return false;
}
if self.has_moved_too_much_for_a_click {
return false;
}
if let Some(press_start_time) = self.press_start_time {
if self.time - press_start_time > MAX_CLICK_DURATION {
return false;
}
}
true
}
/// Is the primary button currently down?
#[inline(always)]
pub fn primary_down(&self) -> bool {
self.button_down(PointerButton::Primary)
}
/// Is the secondary button currently down?
#[inline(always)]
pub fn secondary_down(&self) -> bool {
self.button_down(PointerButton::Secondary)
}
/// Is the middle button currently down?
#[inline(always)]
pub fn middle_down(&self) -> bool {
self.button_down(PointerButton::Middle)
}
}
impl InputState {
pub fn ui(&self, ui: &mut crate::Ui) {
let Self {
raw,
pointer,
touch_states,
scroll_delta,
zoom_factor_delta,
screen_rect,
pixels_per_point,
max_texture_side,
time,
unstable_dt,
predicted_dt,
stable_dt,
modifiers,
keys_down,
events,
} = self;
ui.style_mut()
.text_styles
.get_mut(&crate::TextStyle::Body)
.unwrap()
.family = crate::FontFamily::Monospace;
ui.collapsing("Raw Input", |ui| raw.ui(ui));
crate::containers::CollapsingHeader::new("🖱 Pointer")
.default_open(true)
.show(ui, |ui| {
pointer.ui(ui);
});
for (device_id, touch_state) in touch_states {
ui.collapsing(format!("Touch State [device {}]", device_id.0), |ui| {
touch_state.ui(ui);
});
}
ui.label(format!("scroll_delta: {:?} points", scroll_delta));
ui.label(format!("zoom_factor_delta: {:4.2}x", zoom_factor_delta));
ui.label(format!("screen_rect: {:?} points", screen_rect));
ui.label(format!(
"{} physical pixels for each logical point",
pixels_per_point
));
ui.label(format!(
"max texture size (on each side): {}",
max_texture_side
));
ui.label(format!("time: {:.3} s", time));
ui.label(format!(
"time since previous frame: {:.1} ms",
1e3 * unstable_dt
));
ui.label(format!("predicted_dt: {:.1} ms", 1e3 * predicted_dt));
ui.label(format!("stable_dt: {:.1} ms", 1e3 * stable_dt));
ui.label(format!("modifiers: {:#?}", modifiers));
ui.label(format!("keys_down: {:?}", keys_down));
ui.scope(|ui| {
ui.set_min_height(150.0);
ui.label(format!("events: {:#?}", events))
.on_hover_text("key presses etc");
});
}
}
impl PointerState {
pub fn ui(&self, ui: &mut crate::Ui) {
let Self {
time: _,
latest_pos,
interact_pos,
delta,
velocity,
pos_history: _,
down,
press_origin,
press_start_time,
has_moved_too_much_for_a_click,
last_click_time,
last_last_click_time,
pointer_events,
} = self;
ui.label(format!("latest_pos: {:?}", latest_pos));
ui.label(format!("interact_pos: {:?}", interact_pos));
ui.label(format!("delta: {:?}", delta));
ui.label(format!(
"velocity: [{:3.0} {:3.0}] points/sec",
velocity.x, velocity.y
));
ui.label(format!("down: {:#?}", down));
ui.label(format!("press_origin: {:?}", press_origin));
ui.label(format!("press_start_time: {:?} s", press_start_time));
ui.label(format!(
"has_moved_too_much_for_a_click: {}",
has_moved_too_much_for_a_click
));
ui.label(format!("last_click_time: {:#?}", last_click_time));
ui.label(format!("last_last_click_time: {:#?}", last_last_click_time));
ui.label(format!("pointer_events: {:?}", pointer_events));
}
}
+335
View File
@@ -0,0 +1,335 @@
use std::{collections::BTreeMap, fmt::Debug};
use crate::{
data::input::TouchDeviceId,
emath::{normalized_angle, Pos2, Vec2},
Event, RawInput, TouchId, TouchPhase,
};
/// All you probably need to know about a multi-touch gesture.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MultiTouchInfo {
/// Point in time when the gesture started.
pub start_time: f64,
/// Position of the pointer at the time the gesture started.
pub start_pos: Pos2,
/// Number of touches (fingers) on the surface. Value is ≥ 2 since for a single touch no
/// [`MultiTouchInfo`] is created.
pub num_touches: usize,
/// Proportional zoom factor (pinch gesture).
/// * `zoom = 1`: no change
/// * `zoom < 1`: pinch together
/// * `zoom > 1`: pinch spread
pub zoom_delta: f32,
/// 2D non-proportional zoom factor (pinch gesture).
///
/// For horizontal pinches, this will return `[z, 1]`,
/// for vertical pinches this will return `[1, z]`,
/// and otherwise this will return `[z, z]`,
/// where `z` is the zoom factor:
/// * `zoom = 1`: no change
/// * `zoom < 1`: pinch together
/// * `zoom > 1`: pinch spread
pub zoom_delta_2d: Vec2,
/// Rotation in radians. Moving fingers around each other will change this value. This is a
/// relative value, comparing the orientation of fingers in the current frame with the previous
/// frame. If all fingers are resting, this value is `0.0`.
pub rotation_delta: f32,
/// Relative movement (comparing previous frame and current frame) of the average position of
/// all touch points. Without movement this value is `Vec2::ZERO`.
///
/// Note that this may not necessarily be measured in screen points (although it _will_ be for
/// most mobile devices). In general (depending on the touch device), touch coordinates cannot
/// be directly mapped to the screen. A touch always is considered to start at the position of
/// the pointer, but touch movement is always measured in the units delivered by the device,
/// and may depend on hardware and system settings.
pub translation_delta: Vec2,
/// Current force of the touch (average of the forces of the individual fingers). This is a
/// value in the interval `[0.0 .. =1.0]`.
///
/// Note 1: A value of `0.0` either indicates a very light touch, or it means that the device
/// is not capable of measuring the touch force at all.
///
/// Note 2: Just increasing the physical pressure without actually moving the finger may not
/// necessarily lead to a change of this value.
pub force: f32,
}
/// The current state (for a specific touch device) of touch events and gestures.
#[derive(Clone)]
pub(crate) struct TouchState {
/// Technical identifier of the touch device. This is used to identify relevant touch events
/// for this [`TouchState`] instance.
device_id: TouchDeviceId,
/// Active touches, if any.
///
/// TouchId is the unique identifier of the touch. It is valid as long as the finger/pen touches the surface. The
/// next touch will receive a new unique ID.
///
/// Refer to [`ActiveTouch`].
active_touches: BTreeMap<TouchId, ActiveTouch>,
/// If a gesture has been recognized (i.e. when exactly two fingers touch the surface), this
/// holds state information
gesture_state: Option<GestureState>,
}
#[derive(Clone, Debug)]
struct GestureState {
start_time: f64,
start_pointer_pos: Pos2,
pinch_type: PinchType,
previous: Option<DynGestureState>,
current: DynGestureState,
}
/// Gesture data that can change over time
#[derive(Clone, Copy, Debug)]
struct DynGestureState {
/// used for proportional zooming
avg_distance: f32,
/// used for non-proportional zooming
avg_abs_distance2: Vec2,
avg_pos: Pos2,
avg_force: f32,
heading: f32,
}
/// Describes an individual touch (finger or digitizer) on the touch surface. Instances exist as
/// long as the finger/pen touches the surface.
#[derive(Clone, Copy, Debug)]
struct ActiveTouch {
/// Current position of this touch, in device coordinates (not necessarily screen position)
pos: Pos2,
/// Current force of the touch. A value in the interval [0.0 .. 1.0]
///
/// Note that a value of 0.0 either indicates a very light touch, or it means that the device
/// is not capable of measuring the touch force.
force: f32,
}
impl TouchState {
pub fn new(device_id: TouchDeviceId) -> Self {
Self {
device_id,
active_touches: Default::default(),
gesture_state: None,
}
}
pub fn begin_frame(&mut self, time: f64, new: &RawInput, pointer_pos: Option<Pos2>) {
let mut added_or_removed_touches = false;
for event in &new.events {
match *event {
Event::Touch {
device_id,
id,
phase,
pos,
force,
} if device_id == self.device_id => match phase {
TouchPhase::Start => {
self.active_touches.insert(id, ActiveTouch { pos, force });
added_or_removed_touches = true;
}
TouchPhase::Move => {
if let Some(touch) = self.active_touches.get_mut(&id) {
touch.pos = pos;
touch.force = force;
}
}
TouchPhase::End | TouchPhase::Cancel => {
self.active_touches.remove(&id);
added_or_removed_touches = true;
}
},
_ => (),
}
}
// This needs to be called each frame, even if there are no new touch events.
// Otherwise, we would send the same old delta information multiple times:
self.update_gesture(time, pointer_pos);
if added_or_removed_touches {
// Adding or removing fingers makes the average values "jump". We better forget
// about the previous values, and don't create delta information for this frame:
if let Some(ref mut state) = &mut self.gesture_state {
state.previous = None;
}
}
}
pub fn is_active(&self) -> bool {
self.gesture_state.is_some()
}
pub fn info(&self) -> Option<MultiTouchInfo> {
self.gesture_state.as_ref().map(|state| {
// state.previous can be `None` when the number of simultaneous touches has just
// changed. In this case, we take `current` as `previous`, pretending that there
// was no change for the current frame.
let state_previous = state.previous.unwrap_or(state.current);
let zoom_delta = state.current.avg_distance / state_previous.avg_distance;
let zoom_delta2 = match state.pinch_type {
PinchType::Horizontal => Vec2::new(
state.current.avg_abs_distance2.x / state_previous.avg_abs_distance2.x,
1.0,
),
PinchType::Vertical => Vec2::new(
1.0,
state.current.avg_abs_distance2.y / state_previous.avg_abs_distance2.y,
),
PinchType::Proportional => Vec2::splat(zoom_delta),
};
MultiTouchInfo {
start_time: state.start_time,
start_pos: state.start_pointer_pos,
num_touches: self.active_touches.len(),
zoom_delta,
zoom_delta_2d: zoom_delta2,
rotation_delta: normalized_angle(state.current.heading - state_previous.heading),
translation_delta: state.current.avg_pos - state_previous.avg_pos,
force: state.current.avg_force,
}
})
}
fn update_gesture(&mut self, time: f64, pointer_pos: Option<Pos2>) {
if let Some(dyn_state) = self.calc_dynamic_state() {
if let Some(ref mut state) = &mut self.gesture_state {
// updating an ongoing gesture
state.previous = Some(state.current);
state.current = dyn_state;
} else if let Some(pointer_pos) = pointer_pos {
// starting a new gesture
self.gesture_state = Some(GestureState {
start_time: time,
start_pointer_pos: pointer_pos,
pinch_type: PinchType::classify(&self.active_touches),
previous: None,
current: dyn_state,
});
}
} else {
// the end of a gesture (if there is any)
self.gesture_state = None;
}
}
/// `None` if less than two fingers
fn calc_dynamic_state(&self) -> Option<DynGestureState> {
let num_touches = self.active_touches.len();
if num_touches < 2 {
None
} else {
let mut state = DynGestureState {
avg_distance: 0.0,
avg_abs_distance2: Vec2::ZERO,
avg_pos: Pos2::ZERO,
avg_force: 0.0,
heading: 0.0,
};
let num_touches_recip = 1. / num_touches as f32;
// first pass: calculate force and center of touch positions:
for touch in self.active_touches.values() {
state.avg_force += touch.force;
state.avg_pos.x += touch.pos.x;
state.avg_pos.y += touch.pos.y;
}
state.avg_force *= num_touches_recip;
state.avg_pos.x *= num_touches_recip;
state.avg_pos.y *= num_touches_recip;
// second pass: calculate distances from center:
for touch in self.active_touches.values() {
state.avg_distance += state.avg_pos.distance(touch.pos);
state.avg_abs_distance2.x += (state.avg_pos.x - touch.pos.x).abs();
state.avg_abs_distance2.y += (state.avg_pos.y - touch.pos.y).abs();
}
state.avg_distance *= num_touches_recip;
state.avg_abs_distance2 *= num_touches_recip;
// Calculate the direction from the first touch to the center position.
// This is not the perfect way of calculating the direction if more than two fingers
// are involved, but as long as all fingers rotate more or less at the same angular
// velocity, the shortcomings of this method will not be noticed. One can see the
// issues though, when touching with three or more fingers, and moving only one of them
// (it takes two hands to do this in a controlled manner). A better technique would be
// to store the current and previous directions (with reference to the center) for each
// touch individually, and then calculate the average of all individual changes in
// direction. But this approach cannot be implemented locally in this method, making
// everything a bit more complicated.
let first_touch = self.active_touches.values().next().unwrap();
state.heading = (state.avg_pos - first_touch.pos).angle();
Some(state)
}
}
}
impl TouchState {
pub fn ui(&self, ui: &mut crate::Ui) {
ui.label(format!("{:?}", self));
}
}
impl Debug for TouchState {
// This outputs less clutter than `#[derive(Debug)]`:
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for (id, touch) in &self.active_touches {
f.write_fmt(format_args!("#{:?}: {:#?}\n", id, touch))?;
}
f.write_fmt(format_args!("gesture: {:#?}\n", self.gesture_state))?;
Ok(())
}
}
#[derive(Clone, Debug)]
enum PinchType {
Horizontal,
Vertical,
Proportional,
}
impl PinchType {
fn classify(touches: &BTreeMap<TouchId, ActiveTouch>) -> Self {
// For non-proportional 2d zooming:
// If the user is pinching with two fingers that have roughly the same Y coord,
// then the Y zoom is unstable and should be 1.
// Similarly, if the fingers are directly above/below each other,
// we should only zoom on the Y axis.
// If the fingers are roughly on a diagonal, we revert to the proportional zooming.
if touches.len() == 2 {
let mut touches = touches.values();
let t0 = touches.next().unwrap().pos;
let t1 = touches.next().unwrap().pos;
let dx = (t0.x - t1.x).abs();
let dy = (t0.y - t1.y).abs();
if dx > 3.0 * dy {
Self::Horizontal
} else if dy > 3.0 * dx {
Self::Vertical
} else {
Self::Proportional
}
} else {
Self::Proportional
}
}
}
+198
View File
@@ -0,0 +1,198 @@
//! Showing UI:s for egui/epaint types.
use crate::*;
pub fn font_family_ui(ui: &mut Ui, font_family: &mut FontFamily) {
let families = ui.fonts().families();
ui.horizontal(|ui| {
for alternative in families {
let text = alternative.to_string();
ui.radio_value(font_family, alternative, text);
}
});
}
pub fn font_id_ui(ui: &mut Ui, font_id: &mut FontId) {
let families = ui.fonts().families();
ui.horizontal(|ui| {
ui.add(Slider::new(&mut font_id.size, 4.0..=40.0).max_decimals(0));
for alternative in families {
let text = alternative.to_string();
ui.radio_value(&mut font_id.family, alternative, text);
}
});
}
// Show font texture in demo Ui
pub(crate) fn font_texture_ui(ui: &mut Ui, [width, height]: [usize; 2]) -> Response {
ui.vertical(|ui| {
let color = if ui.visuals().dark_mode {
Color32::WHITE
} else {
Color32::BLACK
};
ui.label(format!(
"Texture size: {} x {} (hover to zoom)",
width, height
));
if width <= 1 || height <= 1 {
return;
}
let mut size = vec2(width as f32, height as f32);
if size.x > ui.available_width() {
size *= ui.available_width() / size.x;
}
let (rect, response) = ui.allocate_at_least(size, Sense::hover());
let mut mesh = Mesh::default();
mesh.add_rect_with_uv(rect, [pos2(0.0, 0.0), pos2(1.0, 1.0)].into(), color);
ui.painter().add(Shape::mesh(mesh));
let (tex_w, tex_h) = (width as f32, height as f32);
response
.on_hover_cursor(CursorIcon::ZoomIn)
.on_hover_ui_at_pointer(|ui| {
if let Some(pos) = ui.ctx().pointer_latest_pos() {
let (_id, zoom_rect) = ui.allocate_space(vec2(128.0, 128.0));
let u = remap_clamp(pos.x, rect.x_range(), 0.0..=tex_w);
let v = remap_clamp(pos.y, rect.y_range(), 0.0..=tex_h);
let texel_radius = 32.0;
let u = u.at_least(texel_radius).at_most(tex_w - texel_radius);
let v = v.at_least(texel_radius).at_most(tex_h - texel_radius);
let uv_rect = Rect::from_min_max(
pos2((u - texel_radius) / tex_w, (v - texel_radius) / tex_h),
pos2((u + texel_radius) / tex_w, (v + texel_radius) / tex_h),
);
let mut mesh = Mesh::default();
mesh.add_rect_with_uv(zoom_rect, uv_rect, color);
ui.painter().add(Shape::mesh(mesh));
}
});
})
.response
}
impl Widget for &epaint::stats::PaintStats {
fn ui(self, ui: &mut Ui) -> Response {
ui.vertical(|ui| {
ui.label(
"egui generates intermediate level shapes like circles and text. \
These are later tessellated into triangles.",
);
ui.add_space(10.0);
ui.style_mut().override_text_style = Some(TextStyle::Monospace);
let epaint::stats::PaintStats {
shapes,
shape_text,
shape_path,
shape_mesh,
shape_vec,
num_callbacks,
text_shape_vertices,
text_shape_indices,
clipped_primitives,
vertices,
indices,
} = self;
ui.label("Intermediate:");
label(ui, shapes, "shapes").on_hover_text("Boxes, circles, etc");
ui.horizontal(|ui| {
label(ui, shape_text, "text");
ui.small("(mostly cached)");
});
label(ui, shape_path, "paths");
label(ui, shape_mesh, "nested meshes");
label(ui, shape_vec, "nested shapes");
ui.label(format!("{:6} callbacks", num_callbacks));
ui.add_space(10.0);
ui.label("Text shapes:");
label(ui, text_shape_vertices, "vertices");
label(ui, text_shape_indices, "indices")
.on_hover_text("Three 32-bit indices per triangles");
ui.add_space(10.0);
ui.label("Tessellated (and culled):");
label(ui, clipped_primitives, "primitives lists")
.on_hover_text("Number of separate clip rectangles");
label(ui, vertices, "vertices");
label(ui, indices, "indices").on_hover_text("Three 32-bit indices per triangles");
ui.add_space(10.0);
// ui.label("Total:");
// ui.label(self.total().format(""));
})
.response
}
}
fn label(ui: &mut Ui, alloc_info: &epaint::stats::AllocInfo, what: &str) -> Response {
ui.add(Label::new(alloc_info.format(what)).wrap(false))
}
impl Widget for &mut epaint::TessellationOptions {
fn ui(self, ui: &mut Ui) -> Response {
ui.vertical(|ui| {
let epaint::TessellationOptions {
feathering,
feathering_size_in_pixels,
coarse_tessellation_culling,
prerasterized_discs,
round_text_to_pixels,
debug_paint_clip_rects,
debug_paint_text_rects,
debug_ignore_clip_rects,
bezier_tolerance,
epsilon: _,
} = self;
ui.checkbox(feathering, "Feathering (antialias)")
.on_hover_text("Apply feathering to smooth out the edges of shapes. Turn off for small performance gain.");
let feathering_slider = crate::Slider::new(feathering_size_in_pixels, 0.0..=10.0)
.smallest_positive(0.1)
.logarithmic(true)
.text("Feathering size in pixels");
ui.add_enabled(*feathering, feathering_slider);
ui.checkbox(prerasterized_discs, "Speed up filled circles with pre-rasterization");
ui.add(
crate::widgets::Slider::new(bezier_tolerance, 0.0001..=10.0)
.logarithmic(true)
.show_value(true)
.text("Spline Tolerance"),
);
ui.collapsing("debug", |ui| {
ui.checkbox(
coarse_tessellation_culling,
"Do coarse culling in the tessellator",
);
ui.checkbox(round_text_to_pixels, "Align text positions to pixel grid")
.on_hover_text("Most text already is, so don't expect to see a large change.");
ui.checkbox(debug_ignore_clip_rects, "Ignore clip rectangles");
ui.checkbox(debug_paint_clip_rects, "Paint clip rectangles");
ui.checkbox(debug_paint_text_rects, "Paint text bounds");
});
})
.response
}
}
impl Widget for &memory::Interaction {
fn ui(self, ui: &mut Ui) -> Response {
ui.vertical(|ui| {
ui.label(format!("click_id: {:?}", self.click_id));
ui.label(format!("drag_id: {:?}", self.drag_id));
ui.label(format!("drag_is_window: {:?}", self.drag_is_window));
ui.label(format!("click_interest: {:?}", self.click_interest));
ui.label(format!("drag_interest: {:?}", self.drag_interest));
})
.response
}
}
+197
View File
@@ -0,0 +1,197 @@
//! Handles paint layers, i.e. how things
//! are sometimes painted behind or in front of other things.
use crate::{Id, *};
use epaint::{ClippedShape, Shape};
/// Different layer categories
#[derive(Clone, Copy, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum Order {
/// Painted behind all floating windows
Background,
/// Special layer between panels and windows
PanelResizeLine,
/// Normal moveable windows that you reorder by click
Middle,
/// Popups, menus etc that should always be painted on top of windows
/// Foreground objects can also have tooltips
Foreground,
/// Things floating on top of everything else, like tooltips.
/// You cannot interact with these.
Tooltip,
/// Debug layer, always painted last / on top
Debug,
}
impl Order {
const COUNT: usize = 6;
const ALL: [Order; Self::COUNT] = [
Self::Background,
Self::PanelResizeLine,
Self::Middle,
Self::Foreground,
Self::Tooltip,
Self::Debug,
];
#[inline(always)]
pub fn allow_interaction(&self) -> bool {
match self {
Self::Background
| Self::PanelResizeLine
| Self::Middle
| Self::Foreground
| Self::Debug => true,
Self::Tooltip => false,
}
}
/// Short and readable summary
pub fn short_debug_format(&self) -> &'static str {
match self {
Self::Background => "backg",
Self::PanelResizeLine => "panel",
Self::Middle => "middl",
Self::Foreground => "foreg",
Self::Tooltip => "toolt",
Self::Debug => "debug",
}
}
}
/// An identifier for a paint layer.
/// Also acts as an identifier for [`Area`]:s.
#[derive(Clone, Copy, Debug, Hash, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct LayerId {
pub order: Order,
pub id: Id,
}
impl LayerId {
pub fn new(order: Order, id: Id) -> Self {
Self { order, id }
}
pub fn debug() -> Self {
Self {
order: Order::Debug,
id: Id::new("debug"),
}
}
pub fn background() -> Self {
Self {
order: Order::Background,
id: Id::background(),
}
}
#[inline(always)]
pub fn allow_interaction(&self) -> bool {
self.order.allow_interaction()
}
/// Short and readable summary
pub fn short_debug_format(&self) -> String {
format!(
"{} {}",
self.order.short_debug_format(),
self.id.short_debug_format()
)
}
}
/// A unique identifier of a specific [`Shape`] in a [`PaintList`].
#[derive(Clone, Copy, PartialEq)]
pub struct ShapeIdx(usize);
/// A list of [`Shape`]s paired with a clip rectangle.
#[derive(Clone, Default)]
pub struct PaintList(Vec<ClippedShape>);
impl PaintList {
#[inline(always)]
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// Returns the index of the new [`Shape`] that can be used with `PaintList::set`.
#[inline(always)]
pub fn add(&mut self, clip_rect: Rect, shape: Shape) -> ShapeIdx {
let idx = ShapeIdx(self.0.len());
self.0.push(ClippedShape(clip_rect, shape));
idx
}
pub fn extend(&mut self, clip_rect: Rect, mut shapes: Vec<Shape>) {
self.0
.extend(shapes.drain(..).map(|shape| ClippedShape(clip_rect, shape)));
}
/// Modify an existing [`Shape`].
///
/// Sometimes you want to paint a frame behind some contents, but don't know how large the frame needs to be
/// until the contents have been added, and therefor also painted to the [`PaintList`].
///
/// The solution is to allocate a [`Shape`] using `let idx = paint_list.add(cr, Shape::Noop);`
/// and then later setting it using `paint_list.set(idx, cr, frame);`.
#[inline(always)]
pub fn set(&mut self, idx: ShapeIdx, clip_rect: Rect, shape: Shape) {
self.0[idx.0] = ClippedShape(clip_rect, shape);
}
/// Translate each [`Shape`] and clip rectangle by this much, in-place
pub fn translate(&mut self, delta: Vec2) {
for ClippedShape(clip_rect, shape) in &mut self.0 {
*clip_rect = clip_rect.translate(delta);
shape.translate(delta);
}
}
}
#[derive(Clone, Default)]
pub(crate) struct GraphicLayers([IdMap<PaintList>; Order::COUNT]);
impl GraphicLayers {
pub fn list(&mut self, layer_id: LayerId) -> &mut PaintList {
self.0[layer_id.order as usize]
.entry(layer_id.id)
.or_default()
}
pub fn drain(&mut self, area_order: &[LayerId]) -> impl ExactSizeIterator<Item = ClippedShape> {
let mut all_shapes: Vec<_> = Default::default();
for &order in &Order::ALL {
let order_map = &mut self.0[order as usize];
// If a layer is empty at the start of the frame
// then nobody has added to it, and it is old and defunct.
// Free it to save memory:
order_map.retain(|_, list| !list.is_empty());
// First do the layers part of area_order:
for layer_id in area_order {
if layer_id.order == order {
if let Some(list) = order_map.get_mut(&layer_id.id) {
all_shapes.append(&mut list.0);
}
}
}
// Also draw areas that are missing in `area_order`:
for shapes in order_map.values_mut() {
all_shapes.append(&mut shapes.0);
}
}
all_shapes.into_iter()
}
}
+839
View File
@@ -0,0 +1,839 @@
use crate::{egui_assert, emath::*, Align};
use std::f32::INFINITY;
// ----------------------------------------------------------------------------
/// This describes the bounds and existing contents of an [`Ui`][`crate::Ui`].
/// It is what is used and updated by [`Layout`] when adding new widgets.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Region {
/// This is the minimal size of the [`Ui`](crate::Ui).
/// When adding new widgets, this will generally expand.
///
/// Always finite.
///
/// The bounding box of all child widgets, but not necessarily a tight bounding box
/// since [`Ui`](crate::Ui) can start with a non-zero min_rect size.
pub min_rect: Rect,
/// The maximum size of this [`Ui`](crate::Ui). This is a *soft max*
/// meaning new widgets will *try* not to expand beyond it,
/// but if they have to, they will.
///
/// Text will wrap at `max_rect.right()`.
/// Some widgets (like separator lines) will try to fill the full `max_rect` width of the ui.
///
/// `max_rect` will always be at least the size of `min_rect`.
///
/// If the `max_rect` size is zero, it is a signal that child widgets should be as small as possible.
/// If the `max_rect` size is infinite, it is a signal that child widgets should take up as much room as they want.
pub max_rect: Rect,
/// Where the next widget will be put.
///
/// One side of this will always be infinite: the direction in which new widgets will be added.
/// The opposing side is what is incremented.
/// The crossing sides are initialized to `max_rect`.
///
/// So one can think of `cursor` as a constraint on the available region.
///
/// If something has already been added, this will point to `style.spacing.item_spacing` beyond the latest child.
/// The cursor can thus be `style.spacing.item_spacing` pixels outside of the min_rect.
pub(crate) cursor: Rect,
}
impl Region {
/// Expand the `min_rect` and `max_rect` of this ui to include a child at the given rect.
pub fn expand_to_include_rect(&mut self, rect: Rect) {
self.min_rect = self.min_rect.union(rect);
self.max_rect = self.max_rect.union(rect);
}
/// Ensure we are big enough to contain the given X-coordinate.
/// This is sometimes useful to expand an ui to stretch to a certain place.
pub fn expand_to_include_x(&mut self, x: f32) {
self.min_rect.extend_with_x(x);
self.max_rect.extend_with_x(x);
self.cursor.extend_with_x(x);
}
/// Ensure we are big enough to contain the given Y-coordinate.
/// This is sometimes useful to expand an ui to stretch to a certain place.
pub fn expand_to_include_y(&mut self, y: f32) {
self.min_rect.extend_with_y(y);
self.max_rect.extend_with_y(y);
self.cursor.extend_with_y(y);
}
pub fn sanity_check(&self) {
egui_assert!(!self.min_rect.any_nan());
egui_assert!(!self.max_rect.any_nan());
egui_assert!(!self.cursor.any_nan());
}
}
// ----------------------------------------------------------------------------
/// Layout direction, one of [`LeftToRight`](Direction::LeftToRight), [`RightToLeft`](Direction::RightToLeft), [`TopDown`](Direction::TopDown), [`BottomUp`](Direction::BottomUp).
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum Direction {
LeftToRight,
RightToLeft,
TopDown,
BottomUp,
}
impl Direction {
#[inline(always)]
pub fn is_horizontal(self) -> bool {
match self {
Direction::LeftToRight | Direction::RightToLeft => true,
Direction::TopDown | Direction::BottomUp => false,
}
}
#[inline(always)]
pub fn is_vertical(self) -> bool {
match self {
Direction::LeftToRight | Direction::RightToLeft => false,
Direction::TopDown | Direction::BottomUp => true,
}
}
}
// ----------------------------------------------------------------------------
/// The layout of a [`Ui`][`crate::Ui`], e.g. "vertical & centered".
///
/// ```
/// # egui::__run_test_ui(|ui| {
/// ui.with_layout(egui::Layout::right_to_left(egui::Align::TOP), |ui| {
/// ui.label("world!");
/// ui.label("Hello");
/// });
/// # });
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
// #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct Layout {
/// Main axis direction
main_dir: Direction,
/// If true, wrap around when reading the end of the main direction.
/// For instance, for `main_dir == Direction::LeftToRight` this will
/// wrap to a new row when we reach the right side of the `max_rect`.
main_wrap: bool,
/// How to align things on the main axis.
main_align: Align,
/// Justify the main axis?
main_justify: bool,
/// How to align things on the cross axis.
/// For vertical layouts: put things to left, center or right?
/// For horizontal layouts: put things to top, center or bottom?
cross_align: Align,
/// Justify the cross axis?
/// For vertical layouts justify mean all widgets get maximum width.
/// For horizontal layouts justify mean all widgets get maximum height.
cross_justify: bool,
}
impl Default for Layout {
fn default() -> Self {
// TODO(emilk): Get from `Style` instead.
Self::top_down(Align::LEFT) // This is a very euro-centric default.
}
}
/// ## Constructors
impl Layout {
/// Place elements horizontally, left to right.
///
/// The `valign` parameter controls how to align elements vertically.
#[inline(always)]
pub fn left_to_right(valign: Align) -> Self {
Self {
main_dir: Direction::LeftToRight,
main_wrap: false,
main_align: Align::Center, // looks best to e.g. center text within a button
main_justify: false,
cross_align: valign,
cross_justify: false,
}
}
/// Place elements horizontally, right to left.
///
/// The `valign` parameter controls how to align elements vertically.
#[inline(always)]
pub fn right_to_left(valign: Align) -> Self {
Self {
main_dir: Direction::RightToLeft,
main_wrap: false,
main_align: Align::Center, // looks best to e.g. center text within a button
main_justify: false,
cross_align: valign,
cross_justify: false,
}
}
/// Place elements vertically, top to bottom.
///
/// Use the provided horizontal alignmen.
#[inline(always)]
pub fn top_down(halign: Align) -> Self {
Self {
main_dir: Direction::TopDown,
main_wrap: false,
main_align: Align::Center, // looks best to e.g. center text within a button
main_justify: false,
cross_align: halign,
cross_justify: false,
}
}
/// Top-down layout justifed so that buttons etc fill the full available width.
#[inline(always)]
pub fn top_down_justified(halign: Align) -> Self {
Self::top_down(halign).with_cross_justify(true)
}
/// Place elements vertically, bottom up.
///
/// Use the provided horizontal alignmen.
#[inline(always)]
pub fn bottom_up(halign: Align) -> Self {
Self {
main_dir: Direction::BottomUp,
main_wrap: false,
main_align: Align::Center, // looks best to e.g. center text within a button
main_justify: false,
cross_align: halign,
cross_justify: false,
}
}
#[inline(always)]
pub fn from_main_dir_and_cross_align(main_dir: Direction, cross_align: Align) -> Self {
Self {
main_dir,
main_wrap: false,
main_align: Align::Center, // looks best to e.g. center text within a button
main_justify: false,
cross_align,
cross_justify: false,
}
}
/// For when you want to add a single widget to a layout, and that widget
/// should use up all available space.
#[inline(always)]
pub fn centered_and_justified(main_dir: Direction) -> Self {
Self {
main_dir,
main_wrap: false,
main_align: Align::Center,
main_justify: true,
cross_align: Align::Center,
cross_justify: true,
}
}
/// Wrap widgets when we overflow the main axis?
///
/// For instance, for left-to-right layouts, setting this to `true` will
/// put widgets on a new row if we would overflow the right side of [`crate::Ui::max_rect`].
#[inline(always)]
pub fn with_main_wrap(self, main_wrap: bool) -> Self {
Self { main_wrap, ..self }
}
/// The alignment to use on the main axis.
#[inline(always)]
pub fn with_main_align(self, main_align: Align) -> Self {
Self { main_align, ..self }
}
/// The alignment to use on the cross axis.
///
/// The "cross" axis is the one orthogonal to the main axis.
/// For instance: in left-to-right layout, the main axis is horizontal and the cross axis is vertical.
#[inline(always)]
pub fn with_cross_align(self, cross_align: Align) -> Self {
Self {
cross_align,
..self
}
}
/// Justify widgets on the main axis?
///
/// Justify here means "take up all available space".
#[inline(always)]
pub fn with_main_justify(self, main_justify: bool) -> Self {
Self {
main_justify,
..self
}
}
/// Justify widgets along the cross axis?
///
/// Justify here means "take up all available space".
///
/// The "cross" axis is the one orthogonal to the main axis.
/// For instance: in left-to-right layout, the main axis is horizontal and the cross axis is vertical.
#[inline(always)]
pub fn with_cross_justify(self, cross_justify: bool) -> Self {
Self {
cross_justify,
..self
}
}
}
/// ## Inspectors
impl Layout {
#[inline(always)]
pub fn main_dir(&self) -> Direction {
self.main_dir
}
#[inline(always)]
pub fn main_wrap(&self) -> bool {
self.main_wrap
}
#[inline(always)]
pub fn cross_align(&self) -> Align {
self.cross_align
}
#[inline(always)]
pub fn cross_justify(&self) -> bool {
self.cross_justify
}
#[inline(always)]
pub fn is_horizontal(&self) -> bool {
self.main_dir().is_horizontal()
}
#[inline(always)]
pub fn is_vertical(&self) -> bool {
self.main_dir().is_vertical()
}
pub fn prefer_right_to_left(&self) -> bool {
self.main_dir == Direction::RightToLeft
|| self.main_dir.is_vertical() && self.cross_align == Align::Max
}
/// e.g. for adjusting the placement of something.
/// * in horizontal layout: left or right?
/// * in vertical layout: same as [`Self::horizontal_align`].
pub fn horizontal_placement(&self) -> Align {
match self.main_dir {
Direction::LeftToRight => Align::LEFT,
Direction::RightToLeft => Align::RIGHT,
Direction::TopDown | Direction::BottomUp => self.cross_align,
}
}
/// e.g. for when aligning text within a button.
pub fn horizontal_align(&self) -> Align {
if self.is_horizontal() {
self.main_align
} else {
self.cross_align
}
}
/// e.g. for when aligning text within a button.
pub fn vertical_align(&self) -> Align {
if self.is_vertical() {
self.main_align
} else {
self.cross_align
}
}
/// e.g. for when aligning text within a button.
fn align2(&self) -> Align2 {
Align2([self.horizontal_align(), self.vertical_align()])
}
pub fn horizontal_justify(&self) -> bool {
if self.is_horizontal() {
self.main_justify
} else {
self.cross_justify
}
}
pub fn vertical_justify(&self) -> bool {
if self.is_vertical() {
self.main_justify
} else {
self.cross_justify
}
}
}
/// ## Doing layout
impl Layout {
pub fn align_size_within_rect(&self, size: Vec2, outer: Rect) -> Rect {
egui_assert!(size.x >= 0.0 && size.y >= 0.0);
egui_assert!(!outer.is_negative());
self.align2().align_size_within_rect(size, outer)
}
fn initial_cursor(&self, max_rect: Rect) -> Rect {
let mut cursor = max_rect;
match self.main_dir {
Direction::LeftToRight => {
cursor.max.x = INFINITY;
}
Direction::RightToLeft => {
cursor.min.x = -INFINITY;
}
Direction::TopDown => {
cursor.max.y = INFINITY;
}
Direction::BottomUp => {
cursor.min.y = -INFINITY;
}
}
cursor
}
pub(crate) fn region_from_max_rect(&self, max_rect: Rect) -> Region {
egui_assert!(!max_rect.any_nan());
egui_assert!(max_rect.is_finite());
let mut region = Region {
min_rect: Rect::NOTHING, // temporary
max_rect,
cursor: self.initial_cursor(max_rect),
};
let seed = self.next_widget_position(&region);
region.min_rect = Rect::from_center_size(seed, Vec2::ZERO);
region
}
pub(crate) fn available_rect_before_wrap(&self, region: &Region) -> Rect {
self.available_from_cursor_max_rect(region.cursor, region.max_rect)
}
/// Amount of space available for a widget.
/// For wrapping layouts, this is the maximum (after wrap).
pub(crate) fn available_size(&self, r: &Region) -> Vec2 {
if self.main_wrap {
if self.main_dir.is_horizontal() {
vec2(r.max_rect.width(), r.cursor.height())
} else {
vec2(r.cursor.width(), r.max_rect.height())
}
} else {
self.available_from_cursor_max_rect(r.cursor, r.max_rect)
.size()
}
}
/// Given the cursor in the region, how much space is available
/// for the next widget?
fn available_from_cursor_max_rect(&self, cursor: Rect, max_rect: Rect) -> Rect {
egui_assert!(!cursor.any_nan());
egui_assert!(!max_rect.any_nan());
egui_assert!(max_rect.is_finite());
// NOTE: in normal top-down layout the cursor has moved below the current max_rect,
// but the available shouldn't be negative.
// ALSO: with wrapping layouts, cursor jumps to new row before expanding max_rect.
let mut avail = max_rect;
match self.main_dir {
Direction::LeftToRight => {
avail.min.x = cursor.min.x;
avail.max.x = avail.max.x.max(cursor.min.x);
avail.max.x = avail.max.x.max(avail.min.x);
avail.max.y = avail.max.y.max(avail.min.y);
}
Direction::RightToLeft => {
avail.max.x = cursor.max.x;
avail.min.x = avail.min.x.min(cursor.max.x);
avail.min.x = avail.min.x.min(avail.max.x);
avail.max.y = avail.max.y.max(avail.min.y);
}
Direction::TopDown => {
avail.min.y = cursor.min.y;
avail.max.y = avail.max.y.max(cursor.min.y);
avail.max.x = avail.max.x.max(avail.min.x);
avail.max.y = avail.max.y.max(avail.min.y);
}
Direction::BottomUp => {
avail.max.y = cursor.max.y;
avail.min.y = avail.min.y.min(cursor.max.y);
avail.max.x = avail.max.x.max(avail.min.x);
avail.min.y = avail.min.y.min(avail.max.y);
}
}
// We can use the cursor to restrict the available region.
// For instance, we use this to restrict the available space of a parent Ui
// after adding a panel to it.
// We also use it for wrapping layouts.
avail = avail.intersect(cursor);
// Make sure it isn't negative:
if avail.max.x < avail.min.x {
let x = 0.5 * (avail.min.x + avail.max.x);
avail.min.x = x;
avail.max.x = x;
}
if avail.max.y < avail.min.y {
let y = 0.5 * (avail.min.y + avail.max.y);
avail.min.y = y;
avail.max.y = y;
}
egui_assert!(!avail.any_nan());
avail
}
/// Returns where to put the next widget that is of the given size.
/// The returned `frame_rect` [`Rect`] will always be justified along the cross axis.
/// This is what you then pass to `advance_after_rects`.
/// Use `justify_and_align` to get the inner `widget_rect`.
pub(crate) fn next_frame(&self, region: &Region, child_size: Vec2, spacing: Vec2) -> Rect {
region.sanity_check();
egui_assert!(child_size.x >= 0.0 && child_size.y >= 0.0);
if self.main_wrap {
let available_size = self.available_rect_before_wrap(region).size();
let Region {
mut cursor,
mut max_rect,
min_rect,
} = *region;
match self.main_dir {
Direction::LeftToRight => {
if available_size.x < child_size.x && max_rect.left() < cursor.left() {
// New row
let new_row_height = cursor.height().max(child_size.y);
// let new_top = cursor.bottom() + spacing.y;
let new_top = min_rect.bottom() + spacing.y; // tighter packing
cursor = Rect::from_min_max(
pos2(max_rect.left(), new_top),
pos2(INFINITY, new_top + new_row_height),
);
max_rect.max.y = max_rect.max.y.max(cursor.max.y);
}
}
Direction::RightToLeft => {
if available_size.x < child_size.x && cursor.right() < max_rect.right() {
// New row
let new_row_height = cursor.height().max(child_size.y);
// let new_top = cursor.bottom() + spacing.y;
let new_top = min_rect.bottom() + spacing.y; // tighter packing
cursor = Rect::from_min_max(
pos2(-INFINITY, new_top),
pos2(max_rect.right(), new_top + new_row_height),
);
max_rect.max.y = max_rect.max.y.max(cursor.max.y);
}
}
Direction::TopDown => {
if available_size.y < child_size.y && max_rect.top() < cursor.top() {
// New column
let new_col_width = cursor.width().max(child_size.x);
cursor = Rect::from_min_max(
pos2(cursor.right() + spacing.x, max_rect.top()),
pos2(cursor.right() + spacing.x + new_col_width, INFINITY),
);
max_rect.max.x = max_rect.max.x.max(cursor.max.x);
}
}
Direction::BottomUp => {
if available_size.y < child_size.y && cursor.bottom() < max_rect.bottom() {
// New column
let new_col_width = cursor.width().max(child_size.x);
cursor = Rect::from_min_max(
pos2(cursor.right() + spacing.x, -INFINITY),
pos2(
cursor.right() + spacing.x + new_col_width,
max_rect.bottom(),
),
);
max_rect.max.x = max_rect.max.x.max(cursor.max.x);
}
}
}
// Use the new cursor:
let region = Region {
min_rect,
max_rect,
cursor,
};
self.next_frame_ignore_wrap(&region, child_size)
} else {
self.next_frame_ignore_wrap(region, child_size)
}
}
fn next_frame_ignore_wrap(&self, region: &Region, child_size: Vec2) -> Rect {
region.sanity_check();
egui_assert!(child_size.x >= 0.0 && child_size.y >= 0.0);
let available_rect = self.available_rect_before_wrap(region);
let mut frame_size = child_size;
if (self.is_vertical() && self.horizontal_align() == Align::Center)
|| self.horizontal_justify()
{
frame_size.x = frame_size.x.max(available_rect.width()); // fill full width
}
if (self.is_horizontal() && self.vertical_align() == Align::Center)
|| self.vertical_justify()
{
frame_size.y = frame_size.y.max(available_rect.height()); // fill full height
}
let align2 = match self.main_dir {
Direction::LeftToRight => Align2([Align::LEFT, self.vertical_align()]),
Direction::RightToLeft => Align2([Align::RIGHT, self.vertical_align()]),
Direction::TopDown => Align2([self.horizontal_align(), Align::TOP]),
Direction::BottomUp => Align2([self.horizontal_align(), Align::BOTTOM]),
};
let mut frame_rect = align2.align_size_within_rect(frame_size, available_rect);
if self.is_horizontal() && frame_rect.top() < region.cursor.top() {
// for horizontal layouts we always want to expand down,
// or we will overlap the row above.
// This is a bit hacky. Maybe we should do it for vertical layouts too.
frame_rect = frame_rect.translate(Vec2::Y * (region.cursor.top() - frame_rect.top()));
}
egui_assert!(!frame_rect.any_nan());
egui_assert!(!frame_rect.is_negative());
frame_rect
}
/// Apply justify (fill width/height) and/or alignment after calling `next_space`.
pub(crate) fn justify_and_align(&self, frame: Rect, mut child_size: Vec2) -> Rect {
egui_assert!(child_size.x >= 0.0 && child_size.y >= 0.0);
egui_assert!(!frame.is_negative());
if self.horizontal_justify() {
child_size.x = child_size.x.at_least(frame.width()); // fill full width
}
if self.vertical_justify() {
child_size.y = child_size.y.at_least(frame.height()); // fill full height
}
self.align_size_within_rect(child_size, frame)
}
pub(crate) fn next_widget_space_ignore_wrap_justify(
&self,
region: &Region,
size: Vec2,
) -> Rect {
let frame = self.next_frame_ignore_wrap(region, size);
let rect = self.align_size_within_rect(size, frame);
egui_assert!(!rect.any_nan());
egui_assert!(!rect.is_negative());
egui_assert!((rect.width() - size.x).abs() < 1.0 || size.x == f32::INFINITY);
egui_assert!((rect.height() - size.y).abs() < 1.0 || size.y == f32::INFINITY);
rect
}
/// Where would the next tiny widget be centered?
pub(crate) fn next_widget_position(&self, region: &Region) -> Pos2 {
self.next_widget_space_ignore_wrap_justify(region, Vec2::ZERO)
.center()
}
/// Advance the cursor by this many points, and allocate in region.
pub(crate) fn advance_cursor(&self, region: &mut Region, amount: f32) {
match self.main_dir {
Direction::LeftToRight => {
region.cursor.min.x += amount;
region.expand_to_include_x(region.cursor.min.x);
}
Direction::RightToLeft => {
region.cursor.max.x -= amount;
region.expand_to_include_x(region.cursor.max.x);
}
Direction::TopDown => {
region.cursor.min.y += amount;
region.expand_to_include_y(region.cursor.min.y);
}
Direction::BottomUp => {
region.cursor.max.y -= amount;
region.expand_to_include_y(region.cursor.max.y);
}
}
}
/// Advance cursor after a widget was added to a specific rectangle.
///
/// * `frame_rect`: the frame inside which a widget was e.g. centered
/// * `widget_rect`: the actual rect used by the widget
pub(crate) fn advance_after_rects(
&self,
cursor: &mut Rect,
frame_rect: Rect,
widget_rect: Rect,
item_spacing: Vec2,
) {
egui_assert!(!cursor.any_nan());
if self.main_wrap {
if cursor.intersects(frame_rect.shrink(1.0)) {
// make row/column larger if necessary
*cursor = cursor.union(frame_rect);
} else {
// this is a new row or column. We temporarily use NAN for what will be filled in later.
match self.main_dir {
Direction::LeftToRight => {
*cursor = Rect::from_min_max(
pos2(f32::NAN, frame_rect.min.y),
pos2(INFINITY, frame_rect.max.y),
);
}
Direction::RightToLeft => {
*cursor = Rect::from_min_max(
pos2(-INFINITY, frame_rect.min.y),
pos2(f32::NAN, frame_rect.max.y),
);
}
Direction::TopDown => {
*cursor = Rect::from_min_max(
pos2(frame_rect.min.x, f32::NAN),
pos2(frame_rect.max.x, INFINITY),
);
}
Direction::BottomUp => {
*cursor = Rect::from_min_max(
pos2(frame_rect.min.x, -INFINITY),
pos2(frame_rect.max.x, f32::NAN),
);
}
};
}
} else {
// Make sure we also expand where we consider adding things (the cursor):
if self.is_horizontal() {
cursor.min.y = cursor.min.y.min(frame_rect.min.y);
cursor.max.y = cursor.max.y.max(frame_rect.max.y);
} else {
cursor.min.x = cursor.min.x.min(frame_rect.min.x);
cursor.max.x = cursor.max.x.max(frame_rect.max.x);
}
}
match self.main_dir {
Direction::LeftToRight => {
cursor.min.x = widget_rect.max.x + item_spacing.x;
}
Direction::RightToLeft => {
cursor.max.x = widget_rect.min.x - item_spacing.x;
}
Direction::TopDown => {
cursor.min.y = widget_rect.max.y + item_spacing.y;
}
Direction::BottomUp => {
cursor.max.y = widget_rect.min.y - item_spacing.y;
}
};
}
/// Move to the next row in a wrapping layout.
/// Otherwise does nothing.
pub(crate) fn end_row(&mut self, region: &mut Region, spacing: Vec2) {
if self.main_wrap {
match self.main_dir {
Direction::LeftToRight => {
let new_top = region.cursor.bottom() + spacing.y;
region.cursor = Rect::from_min_max(
pos2(region.max_rect.left(), new_top),
pos2(INFINITY, new_top + region.cursor.height()),
);
}
Direction::RightToLeft => {
let new_top = region.cursor.bottom() + spacing.y;
region.cursor = Rect::from_min_max(
pos2(-INFINITY, new_top),
pos2(region.max_rect.right(), new_top + region.cursor.height()),
);
}
Direction::TopDown | Direction::BottomUp => {}
}
}
}
/// Set row height in horizontal wrapping layout.
pub(crate) fn set_row_height(&mut self, region: &mut Region, height: f32) {
if self.main_wrap && self.is_horizontal() {
region.cursor.max.y = region.cursor.min.y + height;
}
}
}
// ----------------------------------------------------------------------------
/// ## Debug stuff
impl Layout {
/// Shows where the next widget is going to be placed
pub(crate) fn paint_text_at_cursor(
&self,
painter: &crate::Painter,
region: &Region,
stroke: epaint::Stroke,
text: impl ToString,
) {
let cursor = region.cursor;
let next_pos = self.next_widget_position(region);
let l = 64.0;
let align = match self.main_dir {
Direction::LeftToRight => {
painter.line_segment([cursor.left_top(), cursor.left_bottom()], stroke);
painter.arrow(next_pos, vec2(l, 0.0), stroke);
Align2([Align::LEFT, self.vertical_align()])
}
Direction::RightToLeft => {
painter.line_segment([cursor.right_top(), cursor.right_bottom()], stroke);
painter.arrow(next_pos, vec2(-l, 0.0), stroke);
Align2([Align::RIGHT, self.vertical_align()])
}
Direction::TopDown => {
painter.line_segment([cursor.left_top(), cursor.right_top()], stroke);
painter.arrow(next_pos, vec2(0.0, l), stroke);
Align2([self.horizontal_align(), Align::TOP])
}
Direction::BottomUp => {
painter.line_segment([cursor.left_bottom(), cursor.right_bottom()], stroke);
painter.arrow(next_pos, vec2(0.0, -l), stroke);
Align2([self.horizontal_align(), Align::BOTTOM])
}
};
painter.debug_text(next_pos, align, stroke.color, text);
}
}
+549
View File
@@ -0,0 +1,549 @@
//! `egui`: an easy-to-use GUI in pure Rust!
//!
//! Try the live web demo: <https://www.egui.rs/#demo>. Read more about egui at <https://github.com/emilk/egui>.
//!
//! `egui` is in heavy development, with each new version having breaking changes.
//! You need to have rust 1.61.0 or later to use `egui`.
//!
//! To quickly get started with egui, you can take a look at [`eframe_template`](https://github.com/emilk/eframe_template)
//! which uses [`eframe`](https://docs.rs/eframe).
//!
//! To create a GUI using egui you first need a [`Context`] (by convention referred to by `ctx`).
//! Then you add a [`Window`] or a [`SidePanel`] to get a [`Ui`], which is what you'll be using to add all the buttons and labels that you need.
//!
//!
//! # Using egui
//!
//! To see what is possible to build with egui you can check out the online demo at <https://www.egui.rs/#demo>.
//!
//! If you like the "learning by doing" approach, clone <https://github.com/emilk/eframe_template> and get started using egui right away.
//!
//! ### A simple example
//!
//! Here is a simple counter that can be incremented and decremented using two buttons:
//! ```
//! fn ui_counter(ui: &mut egui::Ui, counter: &mut i32) {
//! // Put the buttons and label on the same row:
//! ui.horizontal(|ui| {
//! if ui.button("-").clicked() {
//! *counter -= 1;
//! }
//! ui.label(counter.to_string());
//! if ui.button("+").clicked() {
//! *counter += 1;
//! }
//! });
//! }
//! ```
//!
//! In some GUI frameworks this would require defining multiple types and functions with callbacks or message handlers,
//! but thanks to `egui` being immediate mode everything is one self-contained function!
//!
//! ### Getting a [`Ui`]
//!
//! Use one of [`SidePanel`], [`TopBottomPanel`], [`CentralPanel`], [`Window`] or [`Area`] to
//! get access to an [`Ui`] where you can put widgets. For example:
//!
//! ```
//! # egui::__run_test_ctx(|ctx| {
//! egui::CentralPanel::default().show(&ctx, |ui| {
//! ui.add(egui::Label::new("Hello World!"));
//! ui.label("A shorter and more convenient way to add a label.");
//! if ui.button("Click me").clicked() {
//! // take some action here
//! }
//! });
//! # });
//! ```
//!
//! ### Quick start
//!
//! ```
//! # egui::__run_test_ui(|ui| {
//! # let mut my_string = String::new();
//! # let mut my_boolean = true;
//! # let mut my_f32 = 42.0;
//! ui.label("This is a label");
//! ui.hyperlink("https://github.com/emilk/egui");
//! ui.text_edit_singleline(&mut my_string);
//! if ui.button("Click me").clicked() { }
//! ui.add(egui::Slider::new(&mut my_f32, 0.0..=100.0));
//! ui.add(egui::DragValue::new(&mut my_f32));
//!
//! ui.checkbox(&mut my_boolean, "Checkbox");
//!
//! #[derive(PartialEq)]
//! enum Enum { First, Second, Third }
//! # let mut my_enum = Enum::First;
//! ui.horizontal(|ui| {
//! ui.radio_value(&mut my_enum, Enum::First, "First");
//! ui.radio_value(&mut my_enum, Enum::Second, "Second");
//! ui.radio_value(&mut my_enum, Enum::Third, "Third");
//! });
//!
//! ui.separator();
//!
//! # let my_image = egui::TextureId::default();
//! ui.image(my_image, [640.0, 480.0]);
//!
//! ui.collapsing("Click to see what is hidden!", |ui| {
//! ui.label("Not much, as it turns out");
//! });
//! # });
//! ```
//!
//! ## Conventions
//!
//! Conventions unless otherwise specified:
//!
//! * angles are in radians
//! * `Vec2::X` is right and `Vec2::Y` is down.
//! * `Pos2::ZERO` is left top.
//! * Positions and sizes are measured in _points_. Each point may consist of many physical pixels.
//!
//! # Integrating with egui
//!
//! Most likely you are using an existing `egui` backend/integration such as [`eframe`](https://docs.rs/eframe), [`bevy_egui`](https://docs.rs/bevy_egui),
//! or [`egui-miniquad`](https://github.com/not-fl3/egui-miniquad),
//! but if you want to integrate `egui` into a new game engine, this is the section for you.
//!
//! To write your own integration for egui you need to do this:
//!
//! ``` no_run
//! # fn handle_platform_output(_: egui::PlatformOutput) {}
//! # fn gather_input() -> egui::RawInput { egui::RawInput::default() }
//! # fn paint(textures_detla: egui::TexturesDelta, _: Vec<egui::ClippedPrimitive>) {}
//! let mut ctx = egui::Context::default();
//!
//! // Game loop:
//! loop {
//! let raw_input: egui::RawInput = gather_input();
//!
//! let full_output = ctx.run(raw_input, |ctx| {
//! egui::CentralPanel::default().show(&ctx, |ui| {
//! ui.label("Hello world!");
//! if ui.button("Click me").clicked() {
//! // take some action here
//! }
//! });
//! });
//! handle_platform_output(full_output.platform_output);
//! let clipped_primitives = ctx.tessellate(full_output.shapes); // create triangles to paint
//! paint(full_output.textures_delta, clipped_primitives);
//! }
//! ```
//!
//!
//! # Understanding immediate mode
//!
//! `egui` is an immediate mode GUI library. It is useful to fully grok what "immediate mode" implies.
//!
//! Here is an example to illustrate it:
//!
//! ```
//! # egui::__run_test_ui(|ui| {
//! if ui.button("click me").clicked() {
//! take_action()
//! }
//! # });
//! # fn take_action() {}
//! ```
//!
//! This code is being executed each frame at maybe 60 frames per second.
//! Each frame egui does these things:
//!
//! * lays out the letters `click me` in order to figure out the size of the button
//! * decides where on screen to place the button
//! * check if the mouse is hovering or clicking that location
//! * chose button colors based on if it is being hovered or clicked
//! * add a [`Shape::Rect`] and [`Shape::Text`] to the list of shapes to be painted later this frame
//! * return a [`Response`] with the [`clicked`](`Response::clicked`) member so the user can check for interactions
//!
//! There is no button being created and stored somewhere.
//! The only output of this call is some colored shapes, and a [`Response`].
//!
//! Similarly, consider this code:
//!
//! ```
//! # egui::__run_test_ui(|ui| {
//! # let mut value: f32 = 0.0;
//! ui.add(egui::Slider::new(&mut value, 0.0..=100.0).text("My value"));
//! # });
//! ```
//!
//! Here egui will read `value` to display the slider, then look if the mouse is dragging the slider and if so change the `value`.
//! Note that `egui` does not store the slider value for you - it only displays the current value, and changes it
//! by how much the slider has been dragged in the previous few milliseconds.
//! This means it is responsibility of the egui user to store the state (`value`) so that it persists between frames.
//!
//! It can be useful to read the code for the toggle switch example widget to get a better understanding
//! of how egui works: <https://github.com/emilk/egui/blob/master/egui_demo_lib/src/demo/toggle_switch.rs>.
//!
//! Read more about the pros and cons of immediate mode at <https://github.com/emilk/egui#why-immediate-mode>.
//!
//! # Misc
//!
//! ## How widgets works
//!
//! ```
//! # egui::__run_test_ui(|ui| {
//! if ui.button("click me").clicked() { take_action() }
//! # });
//! # fn take_action() {}
//! ```
//!
//! is short for
//!
//! ```
//! # egui::__run_test_ui(|ui| {
//! let button = egui::Button::new("click me");
//! if ui.add(button).clicked() { take_action() }
//! # });
//! # fn take_action() {}
//! ```
//!
//! which is short for
//!
//! ```
//! # use egui::Widget;
//! # egui::__run_test_ui(|ui| {
//! let button = egui::Button::new("click me");
//! let response = button.ui(ui);
//! if response.clicked() { take_action() }
//! # });
//! # fn take_action() {}
//! ```
//!
//! [`Button`] uses the builder pattern to create the data required to show it. The [`Button`] is then discarded.
//!
//! [`Button`] implements `trait` [`Widget`], which looks like this:
//! ```
//! # use egui::*;
//! pub trait Widget {
//! /// Allocate space, interact, paint, and return a [`Response`].
//! fn ui(self, ui: &mut Ui) -> Response;
//! }
//! ```
//!
//! ## Auto-sizing panels and windows
//! In egui, all panels and windows auto-shrink to fit the content.
//! If the window or panel is also resizable, this can lead to a weird behavior
//! where you can drag the edge of the panel/window to make it larger, and
//! when you release the panel/window shrinks again.
//! This is an artifact of immediate mode, and here are some alternatives on how to avoid it:
//!
//! 1. Turn off resizing with [`Window::resizable`], [`SidePanel::resizable`], [`TopBottomPanel::resizable`].
//! 2. Wrap your panel contents in a [`ScrollArea`], or use [`Window::vscroll`] and [`Window::hscroll`].
//! 3. Use a justified layout:
//!
//! ```
//! # egui::__run_test_ui(|ui| {
//! ui.with_layout(egui::Layout::top_down_justified(egui::Align::Center), |ui| {
//! ui.button("I am becoming wider as needed");
//! });
//! # });
//! ```
//!
//! 4. Fill in extra space with emptiness:
//!
//! ```
//! # egui::__run_test_ui(|ui| {
//! ui.allocate_space(ui.available_size()); // put this LAST in your panel/window code
//! # });
//! ```
//!
//! ## Sizes
//! You can control the size of widgets using [`Ui::add_sized`].
//!
//! ```
//! # egui::__run_test_ui(|ui| {
//! # let mut my_value = 0.0_f32;
//! ui.add_sized([40.0, 20.0], egui::DragValue::new(&mut my_value));
//! # });
//! ```
//!
//! ## Code snippets
//!
//! ```
//! # egui::__run_test_ui(|ui| {
//! # let mut some_bool = true;
//! // Miscellaneous tips and tricks
//!
//! ui.horizontal_wrapped(|ui| {
//! ui.spacing_mut().item_spacing.x = 0.0; // remove spacing between widgets
//! // `radio_value` also works for enums, integers, and more.
//! ui.radio_value(&mut some_bool, false, "Off");
//! ui.radio_value(&mut some_bool, true, "On");
//! });
//!
//! ui.group(|ui| {
//! ui.label("Within a frame");
//! ui.set_min_height(200.0);
//! });
//!
//! // A `scope` creates a temporary [`Ui`] in which you can change settings:
//! ui.scope(|ui| {
//! ui.visuals_mut().override_text_color = Some(egui::Color32::RED);
//! ui.style_mut().override_text_style = Some(egui::TextStyle::Monospace);
//! ui.style_mut().wrap = Some(false);
//!
//! ui.label("This text will be red, monospace, and won't wrap to a new line");
//! }); // the temporary settings are reverted here
//! # });
//! ```
//!
//! ## Feature flags
#![cfg_attr(feature = "document-features", doc = document_features::document_features!())]
//!
#![allow(clippy::float_cmp)]
#![allow(clippy::manual_range_contains)]
mod animation_manager;
pub mod containers;
mod context;
mod data;
mod frame_state;
pub(crate) mod grid;
mod id;
mod input_state;
pub mod introspection;
pub mod layers;
mod layout;
mod memory;
pub mod menu;
mod painter;
pub(crate) mod placer;
mod response;
mod sense;
pub mod style;
mod ui;
pub mod util;
pub mod widget_text;
pub mod widgets;
pub use epaint;
pub use epaint::emath;
pub use emath::{lerp, pos2, remap, remap_clamp, vec2, Align, Align2, NumExt, Pos2, Rect, Vec2};
#[cfg(feature = "color-hex")]
pub use epaint::hex_color;
pub use epaint::{
color, mutex,
text::{FontData, FontDefinitions, FontFamily, FontId, FontTweak},
textures::{TextureFilter, TexturesDelta},
ClippedPrimitive, Color32, ColorImage, FontImage, ImageData, Mesh, PaintCallback,
PaintCallbackInfo, Rgba, Rounding, Shape, Stroke, TextureHandle, TextureId,
};
pub mod text {
pub use crate::text_edit::CCursorRange;
pub use epaint::text::{
cursor::CCursor, FontData, FontDefinitions, FontFamily, Fonts, Galley, LayoutJob,
LayoutSection, TextFormat, TAB_SIZE,
};
}
pub use {
containers::*,
context::Context,
data::{
input::*,
output::{self, CursorIcon, FullOutput, PlatformOutput, WidgetInfo},
},
grid::Grid,
id::{Id, IdMap},
input_state::{InputState, MultiTouchInfo, PointerState},
layers::{LayerId, Order},
layout::*,
memory::Memory,
painter::Painter,
response::{InnerResponse, Response},
sense::Sense,
style::{FontSelection, Style, TextStyle, Visuals},
text::{Galley, TextFormat},
ui::Ui,
widget_text::{RichText, WidgetText},
widgets::*,
};
// ----------------------------------------------------------------------------
/// Helper function that adds a label when compiling with debug assertions enabled.
pub fn warn_if_debug_build(ui: &mut crate::Ui) {
if cfg!(debug_assertions) {
ui.label(
RichText::new("‼ Debug build ‼")
.small()
.color(ui.visuals().warn_fg_color),
)
.on_hover_text("egui was compiled with debug assertions enabled.");
}
}
// ----------------------------------------------------------------------------
/// Create a [`Hyperlink`](crate::Hyperlink) to the current [`file!()`] (and line) on Github
///
/// ```
/// # egui::__run_test_ui(|ui| {
/// ui.add(egui::github_link_file_line!("https://github.com/YOUR/PROJECT/blob/master/", "(source code)"));
/// # });
/// ```
#[macro_export]
macro_rules! github_link_file_line {
($github_url: expr, $label: expr) => {{
let url = format!("{}{}#L{}", $github_url, file!(), line!());
$crate::Hyperlink::from_label_and_url($label, url)
}};
}
/// Create a [`Hyperlink`](crate::Hyperlink) to the current [`file!()`] on github.
///
/// ```
/// # egui::__run_test_ui(|ui| {
/// ui.add(egui::github_link_file!("https://github.com/YOUR/PROJECT/blob/master/", "(source code)"));
/// # });
/// ```
#[macro_export]
macro_rules! github_link_file {
($github_url: expr, $label: expr) => {{
let url = format!("{}{}", $github_url, file!());
$crate::Hyperlink::from_label_and_url($label, url)
}};
}
// ----------------------------------------------------------------------------
/// Show debug info on hover when [`Context::set_debug_on_hover`] has been turned on.
///
/// ```
/// # egui::__run_test_ui(|ui| {
/// // Turn on tracing of widgets
/// ui.ctx().set_debug_on_hover(true);
///
/// /// Show [`std::file`], [`std::line`] and argument on hover
/// egui::trace!(ui, "MyWindow");
///
/// /// Show [`std::file`] and [`std::line`] on hover
/// egui::trace!(ui);
/// # });
/// ```
#[macro_export]
macro_rules! trace {
($ui: expr) => {{
$ui.trace_location(format!("{}:{}", file!(), line!()))
}};
($ui: expr, $label: expr) => {{
$ui.trace_location(format!("{} - {}:{}", $label, file!(), line!()))
}};
}
// ----------------------------------------------------------------------------
/// An assert that is only active when `egui` is compiled with the `extra_asserts` feature
/// or with the `extra_debug_asserts` feature in debug builds.
#[macro_export]
macro_rules! egui_assert {
($($arg: tt)*) => {
if cfg!(any(
feature = "extra_asserts",
all(feature = "extra_debug_asserts", debug_assertions),
)) {
assert!($($arg)*);
}
}
}
// ----------------------------------------------------------------------------
/// The default egui fonts supports around 1216 emojis in total.
/// Here are some of the most useful:
/// ∞⊗⎗⎘⎙⏏⏴⏵⏶⏷
/// ⏩⏪⏭⏮⏸⏹⏺■▶📾🔀🔁🔃
/// ☀☁★☆☐☑☜☝☞☟⛃⛶✔
/// ↺↻⟲⟳⬅➡⬆⬇⬈⬉⬊⬋⬌⬍⮨⮩⮪⮫
/// ♡
/// 📅📆
/// 📈📉📊
/// 📋📌📎📤📥🔆
/// 🔈🔉🔊🔍🔎🔗🔘
/// 🕓🖧🖩🖮🖱🖴🖵🖼🗀🗁🗋🗐🗑🗙🚫❓
///
/// NOTE: In egui all emojis are monochrome!
///
/// You can explore them all in the Font Book in [the online demo](https://www.egui.rs/#demo).
///
/// In addition, egui supports a few special emojis that are not part of the unicode standard.
/// This module contains some of them:
pub mod special_emojis {
/// Tux, the Linux penguin.
pub const OS_LINUX: char = '🐧';
/// The Windows logo.
pub const OS_WINDOWS: char = '';
/// The Android logo.
pub const OS_ANDROID: char = '';
/// The Apple logo.
pub const OS_APPLE: char = '';
/// The Github logo.
pub const GITHUB: char = '';
/// The Twitter bird.
pub const TWITTER: char = '';
/// The word `git`.
pub const GIT: char = '';
// I really would like to have ferris here.
}
/// The different types of built-in widgets in egui
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum WidgetType {
Label, // TODO(emilk): emit Label events
/// e.g. a hyperlink
Link,
TextEdit,
Button,
Checkbox,
RadioButton,
SelectableLabel,
ComboBox,
Slider,
DragValue,
ColorButton,
ImageButton,
CollapsingHeader,
/// If you cannot fit any of the above slots.
///
/// If this is something you think should be added, file an issue.
Other,
}
// ----------------------------------------------------------------------------
/// For use in tests; especially doctests.
pub fn __run_test_ctx(mut run_ui: impl FnMut(&Context)) {
let ctx = Context::default();
ctx.set_fonts(FontDefinitions::empty()); // prevent fonts from being loaded (save CPU time)
let _ = ctx.run(Default::default(), |ctx| {
run_ui(ctx);
});
}
/// For use in tests; especially doctests.
pub fn __run_test_ui(mut add_contents: impl FnMut(&mut Ui)) {
let ctx = Context::default();
ctx.set_fonts(FontDefinitions::empty()); // prevent fonts from being loaded (save CPU time)
let _ = ctx.run(Default::default(), |ctx| {
crate::CentralPanel::default().show(ctx, |ui| {
add_contents(ui);
});
});
}
+598
View File
@@ -0,0 +1,598 @@
use crate::{area, window, Id, IdMap, InputState, LayerId, Pos2, Rect, Style};
// ----------------------------------------------------------------------------
/// The data that egui persists between frames.
///
/// This includes window positions and sizes,
/// how far the user has scrolled in a [`ScrollArea`](crate::ScrollArea) etc.
///
/// If you want this to persist when closing your app you should serialize [`Memory`] and store it.
/// For this you need to enable the `persistence`.
///
/// If you want to store data for your widgets, you should look at [`Memory::data`]
#[derive(Clone, Debug, Default)]
#[cfg_attr(feature = "persistence", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(feature = "persistence", serde(default))]
pub struct Memory {
pub options: Options,
/// This map stores some superficial state for all widgets with custom [`Id`]s.
///
/// This includes storing if a [`crate::CollapsingHeader`] is open, how far scrolled a
/// [`crate::ScrollArea`] is, where the cursor in a [`crate::TextEdit`] is, etc.
///
/// This is NOT meant to store any important data. Store that in your own structures!
///
/// Each read clones the data, so keep your values cheap to clone.
/// If you want to store a lot of data you should wrap it in `Arc<Mutex<…>>` so it is cheap to clone.
///
/// This will be saved between different program runs if you use the `persistence` feature.
///
/// To store a state common for all your widgets (a singleton), use [`Id::null`] as the key.
pub data: crate::util::IdTypeMap,
// ------------------------------------------
/// Can be used to cache computations from one frame to another.
///
/// This is for saving CPU when you have something that may take 1-100ms to compute.
/// Things that are very slow (>100ms) should instead be done async (i.e. in another thread)
/// so as not to lock the UI thread.
///
/// ```
/// use egui::util::cache::{ComputerMut, FrameCache};
///
/// #[derive(Default)]
/// struct CharCounter {}
/// impl ComputerMut<&str, usize> for CharCounter {
/// fn compute(&mut self, s: &str) -> usize {
/// s.chars().count() // you probably want to cache something more expensive than this
/// }
/// }
/// type CharCountCache<'a> = FrameCache<usize, CharCounter>;
///
/// # let mut ctx = egui::Context::default();
/// let mut memory = ctx.memory();
/// let cache = memory.caches.cache::<CharCountCache<'_>>();
/// assert_eq!(cache.get("hello"), 5);
/// ```
#[cfg_attr(feature = "persistence", serde(skip))]
pub caches: crate::util::cache::CacheStorage,
// ------------------------------------------
/// new scale that will be applied at the start of the next frame
#[cfg_attr(feature = "persistence", serde(skip))]
pub(crate) new_pixels_per_point: Option<f32>,
/// new fonts that will be applied at the start of the next frame
#[cfg_attr(feature = "persistence", serde(skip))]
pub(crate) new_font_definitions: Option<epaint::text::FontDefinitions>,
#[cfg_attr(feature = "persistence", serde(skip))]
pub(crate) interaction: Interaction,
#[cfg_attr(feature = "persistence", serde(skip))]
pub(crate) window_interaction: Option<window::WindowInteraction>,
#[cfg_attr(feature = "persistence", serde(skip))]
pub(crate) drag_value: crate::widgets::drag_value::MonoState,
pub(crate) areas: Areas,
/// Which popup-window is open (if any)?
/// Could be a combo box, color picker, menu etc.
#[cfg_attr(feature = "persistence", serde(skip))]
popup: Option<Id>,
#[cfg_attr(feature = "persistence", serde(skip))]
everything_is_visible: bool,
}
// ----------------------------------------------------------------------------
/// Some global options that you can read and write.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(feature = "serde", serde(default))]
pub struct Options {
/// The default style for new [`Ui`](crate::Ui):s.
#[cfg_attr(feature = "serde", serde(skip))]
pub(crate) style: std::sync::Arc<Style>,
/// Controls the tessellator.
pub tessellation_options: epaint::TessellationOptions,
/// This does not at all change the behavior of egui,
/// but is a signal to any backend that we want the [`crate::PlatformOutput::events`] read out loud.
/// Screen readers is an experimental feature of egui, and not supported on all platforms.
pub screen_reader: bool,
/// If true, the most common glyphs (ASCII) are pre-rendered to the texture atlas.
///
/// Only the fonts in [`Style::text_styles`] will be pre-cached.
///
/// This can lead to fewer texture operations, but may use up the texture atlas quicker
/// if you are changing [`Style::text_styles`], of have a lot of text styles.
pub preload_font_glyphs: bool,
}
impl Default for Options {
fn default() -> Self {
Self {
style: Default::default(),
tessellation_options: Default::default(),
screen_reader: false,
preload_font_glyphs: true,
}
}
}
// ----------------------------------------------------------------------------
/// Say there is a button in a scroll area.
/// If the user clicks the button, the button should click.
/// If the user drags the button we should scroll the scroll area.
/// So what we do is that when the mouse is pressed we register both the button
/// and the scroll area (as `click_id`/`drag_id`).
/// If the user releases the button without moving the mouse we register it as a click on `click_id`.
/// If the cursor moves too much we clear the `click_id` and start passing move events to `drag_id`.
#[derive(Clone, Debug, Default)]
pub(crate) struct Interaction {
/// A widget interested in clicks that has a mouse press on it.
pub click_id: Option<Id>,
/// A widget interested in drags that has a mouse press on it.
pub drag_id: Option<Id>,
pub focus: Focus,
/// HACK: windows have low priority on dragging.
/// This is so that if you drag a slider in a window,
/// the slider will steal the drag away from the window.
/// This is needed because we do window interaction first (to prevent frame delay),
/// and then do content layout.
pub drag_is_window: bool,
/// Any interest in catching clicks this frame?
/// Cleared to false at start of each frame.
pub click_interest: bool,
/// Any interest in catching clicks this frame?
/// Cleared to false at start of each frame.
pub drag_interest: bool,
}
/// Keeps tracks of what widget has keyboard focus
#[derive(Clone, Debug, Default)]
pub(crate) struct Focus {
/// The widget with keyboard focus (i.e. a text input field).
id: Option<Id>,
/// What had keyboard focus previous frame?
id_previous_frame: Option<Id>,
/// Give focus to this widget next frame
id_next_frame: Option<Id>,
/// If set, the next widget that is interested in focus will automatically get it.
/// Probably because the user pressed Tab.
give_to_next: bool,
/// The last widget interested in focus.
last_interested: Option<Id>,
/// If `true`, pressing tab will NOT move focus away from the current widget.
is_focus_locked: bool,
/// Set at the beginning of the frame, set to `false` when "used".
pressed_tab: bool,
/// Set at the beginning of the frame, set to `false` when "used".
pressed_shift_tab: bool,
}
impl Interaction {
/// Are we currently clicking or dragging an egui widget?
pub fn is_using_pointer(&self) -> bool {
self.click_id.is_some() || self.drag_id.is_some()
}
fn begin_frame(
&mut self,
prev_input: &crate::input_state::InputState,
new_input: &crate::data::input::RawInput,
) {
self.click_interest = false;
self.drag_interest = false;
if !prev_input.pointer.could_any_button_be_click() {
self.click_id = None;
}
if !prev_input.pointer.any_down() || prev_input.pointer.latest_pos().is_none() {
// pointer button was not down last frame
self.click_id = None;
self.drag_id = None;
}
self.focus.begin_frame(new_input);
}
}
impl Focus {
/// Which widget currently has keyboard focus?
pub fn focused(&self) -> Option<Id> {
self.id
}
fn begin_frame(&mut self, new_input: &crate::data::input::RawInput) {
self.id_previous_frame = self.id;
if let Some(id) = self.id_next_frame.take() {
self.id = Some(id);
}
self.pressed_tab = false;
self.pressed_shift_tab = false;
for event in &new_input.events {
if matches!(
event,
crate::Event::Key {
key: crate::Key::Escape,
pressed: true,
modifiers: _,
}
) {
self.id = None;
self.is_focus_locked = false;
break;
}
if let crate::Event::Key {
key: crate::Key::Tab,
pressed: true,
modifiers,
} = event
{
if !self.is_focus_locked {
if modifiers.shift {
self.pressed_shift_tab = true;
} else {
self.pressed_tab = true;
}
}
}
}
}
pub(crate) fn end_frame(&mut self, used_ids: &IdMap<Rect>) {
if let Some(id) = self.id {
// Allow calling `request_focus` one frame and not using it until next frame
let recently_gained_focus = self.id_previous_frame != Some(id);
if !recently_gained_focus && !used_ids.contains_key(&id) {
// Dead-mans-switch: the widget with focus has disappeared!
self.id = None;
}
}
}
pub(crate) fn had_focus_last_frame(&self, id: Id) -> bool {
self.id_previous_frame == Some(id)
}
fn interested_in_focus(&mut self, id: Id) {
if self.give_to_next && !self.had_focus_last_frame(id) {
self.id = Some(id);
self.give_to_next = false;
} else if self.id == Some(id) {
if self.pressed_tab && !self.is_focus_locked {
self.id = None;
self.give_to_next = true;
self.pressed_tab = false;
} else if self.pressed_shift_tab && !self.is_focus_locked {
self.id_next_frame = self.last_interested; // frame-delay so gained_focus works
self.pressed_shift_tab = false;
}
} else if self.pressed_tab && self.id == None && !self.give_to_next {
// nothing has focus and the user pressed tab - give focus to the first widgets that wants it:
self.id = Some(id);
self.pressed_tab = false;
}
self.last_interested = Some(id);
}
}
impl Memory {
pub(crate) fn begin_frame(
&mut self,
prev_input: &crate::input_state::InputState,
new_input: &crate::data::input::RawInput,
) {
self.interaction.begin_frame(prev_input, new_input);
if !prev_input.pointer.any_down() {
self.window_interaction = None;
}
}
pub(crate) fn end_frame(&mut self, input: &InputState, used_ids: &IdMap<Rect>) {
self.caches.update();
self.areas.end_frame();
self.interaction.focus.end_frame(used_ids);
self.drag_value.end_frame(input);
}
/// Top-most layer at the given position.
pub fn layer_id_at(&self, pos: Pos2, resize_interact_radius_side: f32) -> Option<LayerId> {
self.areas.layer_id_at(pos, resize_interact_radius_side)
}
/// An iterator over all layers. Back-to-front. Top is last.
pub fn layer_ids(&self) -> impl ExactSizeIterator<Item = LayerId> + '_ {
self.areas.order().iter().copied()
}
pub(crate) fn had_focus_last_frame(&self, id: Id) -> bool {
self.interaction.focus.id_previous_frame == Some(id)
}
/// True if the given widget had keyboard focus last frame, but not this one.
pub(crate) fn lost_focus(&self, id: Id) -> bool {
self.had_focus_last_frame(id) && !self.has_focus(id)
}
/// True if the given widget has keyboard focus this frame, but didn't last frame.
pub(crate) fn gained_focus(&self, id: Id) -> bool {
!self.had_focus_last_frame(id) && self.has_focus(id)
}
/// Does this widget have keyboard focus?
///
/// This function does not consider whether the UI as a whole (e.g. window)
/// has the keyboard focus. That makes this function suitable for deciding
/// widget state that should not be disrupted if the user moves away
/// from the window and back.
#[inline(always)]
pub fn has_focus(&self, id: Id) -> bool {
self.interaction.focus.id == Some(id)
}
/// Which widget has keyboard focus?
pub fn focus(&self) -> Option<Id> {
self.interaction.focus.id
}
/// Prevent keyboard focus from moving away from this widget even if users presses the tab key.
/// You must first give focus to the widget before calling this.
pub fn lock_focus(&mut self, id: Id, lock_focus: bool) {
if self.had_focus_last_frame(id) && self.has_focus(id) {
self.interaction.focus.is_focus_locked = lock_focus;
}
}
/// 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 {
if self.had_focus_last_frame(id) && self.has_focus(id) {
self.interaction.focus.is_focus_locked
} else {
false
}
}
/// Give keyboard focus to a specific widget.
/// See also [`crate::Response::request_focus`].
#[inline(always)]
pub fn request_focus(&mut self, id: Id) {
self.interaction.focus.id = Some(id);
self.interaction.focus.is_focus_locked = false;
}
/// Surrender keyboard focus for a specific widget.
/// See also [`crate::Response::surrender_focus`].
#[inline(always)]
pub fn surrender_focus(&mut self, id: Id) {
if self.interaction.focus.id == Some(id) {
self.interaction.focus.id = None;
self.interaction.focus.is_focus_locked = false;
}
}
/// Register this widget as being interested in getting keyboard focus.
/// This will allow the user to select it with tab and shift-tab.
#[inline(always)]
pub(crate) fn interested_in_focus(&mut self, id: Id) {
self.interaction.focus.interested_in_focus(id);
}
/// Stop editing of active [`TextEdit`](crate::TextEdit) (if any).
#[inline(always)]
pub fn stop_text_input(&mut self) {
self.interaction.focus.id = None;
}
#[inline(always)]
pub fn is_anything_being_dragged(&self) -> bool {
self.interaction.drag_id.is_some()
}
#[inline(always)]
pub fn is_being_dragged(&self, id: Id) -> bool {
self.interaction.drag_id == Some(id)
}
#[inline(always)]
pub fn set_dragged_id(&mut self, id: Id) {
self.interaction.drag_id = Some(id);
}
/// Forget window positions, sizes etc.
/// Can be used to auto-layout windows.
pub fn reset_areas(&mut self) {
self.areas = Default::default();
}
}
/// ## Popups
/// Popups are things like combo-boxes, color pickers, menus etc.
/// Only one can be be open at a time.
impl Memory {
pub fn is_popup_open(&self, popup_id: Id) -> bool {
self.popup == Some(popup_id) || self.everything_is_visible()
}
pub fn open_popup(&mut self, popup_id: Id) {
self.popup = Some(popup_id);
}
pub fn close_popup(&mut self) {
self.popup = None;
}
pub fn toggle_popup(&mut self, popup_id: Id) {
if self.is_popup_open(popup_id) {
self.close_popup();
} else {
self.open_popup(popup_id);
}
}
/// If true, all windows, menus, tooltips etc are to be visible at once.
///
/// This is useful for testing, benchmarking, pre-caching, etc.
///
/// Experimental feature!
#[inline(always)]
pub fn everything_is_visible(&self) -> bool {
self.everything_is_visible
}
/// If true, all windows, menus, tooltips etc are to be visible at once.
///
/// This is useful for testing, benchmarking, pre-caching, etc.
///
/// Experimental feature!
pub fn set_everything_is_visible(&mut self, value: bool) {
self.everything_is_visible = value;
}
}
// ----------------------------------------------------------------------------
/// Keeps track of [`Area`](crate::containers::area::Area)s, which are free-floating [`Ui`](crate::Ui)s.
/// These [`Area`](crate::containers::area::Area)s can be in any [`Order`](crate::Order).
#[derive(Clone, Debug, Default)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(feature = "serde", serde(default))]
pub struct Areas {
areas: IdMap<area::State>,
/// Back-to-front. Top is last.
order: Vec<LayerId>,
visible_last_frame: ahash::HashSet<LayerId>,
visible_current_frame: ahash::HashSet<LayerId>,
/// When an area want to be on top, it is put in here.
/// At the end of the frame, this is used to reorder the layers.
/// This means if several layers want to be on top, they will keep their relative order.
/// So if you close three windows and then reopen them all in one frame,
/// they will all be sent to the top, but keep their previous internal order.
wants_to_be_on_top: ahash::HashSet<LayerId>,
}
impl Areas {
pub(crate) fn count(&self) -> usize {
self.areas.len()
}
pub(crate) fn get(&self, id: Id) -> Option<&area::State> {
self.areas.get(&id)
}
/// Back-to-front. Top is last.
pub(crate) fn order(&self) -> &[LayerId] {
&self.order
}
pub(crate) fn set_state(&mut self, layer_id: LayerId, state: area::State) {
self.visible_current_frame.insert(layer_id);
self.areas.insert(layer_id.id, state);
if !self.order.iter().any(|x| *x == layer_id) {
self.order.push(layer_id);
}
}
/// Top-most layer at the given position.
pub fn layer_id_at(&self, pos: Pos2, resize_interact_radius_side: f32) -> Option<LayerId> {
for layer in self.order.iter().rev() {
if self.is_visible(layer) {
if let Some(state) = self.areas.get(&layer.id) {
let mut rect = state.rect();
if state.interactable {
// Allow us to resize by dragging just outside the window:
rect = rect.expand(resize_interact_radius_side);
if rect.contains(pos) {
return Some(*layer);
}
}
}
}
}
None
}
pub fn visible_last_frame(&self, layer_id: &LayerId) -> bool {
self.visible_last_frame.contains(layer_id)
}
pub fn is_visible(&self, layer_id: &LayerId) -> bool {
self.visible_last_frame.contains(layer_id) || self.visible_current_frame.contains(layer_id)
}
pub fn visible_layer_ids(&self) -> ahash::HashSet<LayerId> {
self.visible_last_frame
.iter()
.cloned()
.chain(self.visible_current_frame.iter().cloned())
.collect()
}
pub(crate) fn visible_windows(&self) -> Vec<&area::State> {
self.visible_layer_ids()
.iter()
.filter(|layer| layer.order == crate::Order::Middle)
.filter_map(|layer| self.get(layer.id))
.collect()
}
pub fn move_to_top(&mut self, layer_id: LayerId) {
self.visible_current_frame.insert(layer_id);
self.wants_to_be_on_top.insert(layer_id);
if !self.order.iter().any(|x| *x == layer_id) {
self.order.push(layer_id);
}
}
pub(crate) fn end_frame(&mut self) {
let Self {
visible_last_frame,
visible_current_frame,
order,
wants_to_be_on_top,
..
} = self;
std::mem::swap(visible_last_frame, visible_current_frame);
visible_current_frame.clear();
order.sort_by_key(|layer| (layer.order, wants_to_be_on_top.contains(layer)));
wants_to_be_on_top.clear();
}
}
// ----------------------------------------------------------------------------
#[test]
fn memory_impl_send_sync() {
fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<Memory>();
}
+638
View File
@@ -0,0 +1,638 @@
//! Menu bar functionality (very basic so far).
//!
//! Usage:
//! ```
//! fn show_menu(ui: &mut egui::Ui) {
//! use egui::{menu, Button};
//!
//! menu::bar(ui, |ui| {
//! ui.menu_button("File", |ui| {
//! if ui.button("Open").clicked() {
//! // …
//! }
//! });
//! });
//! }
//! ```
use super::{
style::WidgetVisuals, Align, Context, Id, InnerResponse, PointerState, Pos2, Rect, Response,
Sense, TextStyle, Ui, Vec2,
};
use crate::{widgets::*, *};
use epaint::mutex::RwLock;
use std::sync::Arc;
/// What is saved between frames.
#[derive(Clone, Default)]
pub(crate) struct BarState {
open_menu: MenuRootManager,
}
impl BarState {
fn load(ctx: &Context, bar_id: Id) -> Self {
ctx.data().get_temp::<Self>(bar_id).unwrap_or_default()
}
fn store(self, ctx: &Context, bar_id: Id) {
ctx.data().insert_temp(bar_id, self);
}
/// Show a menu at pointer if primary-clicked response.
/// Should be called from [`Context`] on a [`Response`]
pub fn bar_menu<R>(
&mut self,
response: &Response,
add_contents: impl FnOnce(&mut Ui) -> R,
) -> Option<InnerResponse<R>> {
MenuRoot::stationary_click_interaction(response, &mut self.open_menu, response.id);
self.open_menu.show(response, add_contents)
}
}
impl std::ops::Deref for BarState {
type Target = MenuRootManager;
fn deref(&self) -> &Self::Target {
&self.open_menu
}
}
impl std::ops::DerefMut for BarState {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.open_menu
}
}
fn set_menu_style(style: &mut Style) {
style.spacing.button_padding = vec2(2.0, 0.0);
style.visuals.widgets.active.bg_stroke = Stroke::none();
style.visuals.widgets.hovered.bg_stroke = Stroke::none();
style.visuals.widgets.inactive.bg_fill = Color32::TRANSPARENT;
style.visuals.widgets.inactive.bg_stroke = Stroke::none();
}
/// The menu bar goes well in a [`TopBottomPanel::top`],
/// but can also be placed in a [`Window`].
/// In the latter case you may want to wrap it in [`Frame`].
pub fn bar<R>(ui: &mut Ui, add_contents: impl FnOnce(&mut Ui) -> R) -> InnerResponse<R> {
ui.horizontal(|ui| {
set_menu_style(ui.style_mut());
// Take full width and fixed height:
let height = ui.spacing().interact_size.y;
ui.set_min_size(vec2(ui.available_width(), height));
add_contents(ui)
})
}
/// Construct a top level menu in a menu bar. This would be e.g. "File", "Edit" etc.
///
/// Responds to primary clicks.
///
/// Returns `None` if the menu is not open.
pub fn menu_button<R>(
ui: &mut Ui,
title: impl Into<WidgetText>,
add_contents: impl FnOnce(&mut Ui) -> R,
) -> InnerResponse<Option<R>> {
stationary_menu_impl(ui, title, Box::new(add_contents))
}
/// Construct a nested sub menu in another menu.
///
/// Opens on hover.
///
/// Returns `None` if the menu is not open.
pub(crate) fn submenu_button<R>(
ui: &mut Ui,
parent_state: Arc<RwLock<MenuState>>,
title: impl Into<WidgetText>,
add_contents: impl FnOnce(&mut Ui) -> R,
) -> InnerResponse<Option<R>> {
SubMenu::new(parent_state, title).show(ui, add_contents)
}
/// wrapper for the contents of every menu.
pub(crate) fn menu_ui<'c, R>(
ctx: &Context,
menu_id: impl std::hash::Hash,
menu_state_arc: &Arc<RwLock<MenuState>>,
add_contents: impl FnOnce(&mut Ui) -> R + 'c,
) -> InnerResponse<R> {
let pos = {
let mut menu_state = menu_state_arc.write();
menu_state.entry_count = 0;
menu_state.rect.min
};
let area = Area::new(menu_id)
.order(Order::Foreground)
.fixed_pos(pos)
.interactable(true)
.drag_bounds(Rect::EVERYTHING);
let inner_response = area.show(ctx, |ui| {
set_menu_style(ui.style_mut());
Frame::menu(ui.style())
.show(ui, |ui| {
const DEFAULT_MENU_WIDTH: f32 = 150.0; // TODO(emilk): add to ui.spacing
ui.set_max_width(DEFAULT_MENU_WIDTH);
ui.set_menu_state(Some(menu_state_arc.clone()));
ui.with_layout(Layout::top_down_justified(Align::LEFT), add_contents)
.inner
})
.inner
});
menu_state_arc.write().rect = inner_response.response.rect;
inner_response
}
/// Build a top level menu with a button.
///
/// Responds to primary clicks.
fn stationary_menu_impl<'c, R>(
ui: &mut Ui,
title: impl Into<WidgetText>,
add_contents: Box<dyn FnOnce(&mut Ui) -> R + 'c>,
) -> InnerResponse<Option<R>> {
let title = title.into();
let bar_id = ui.id();
let menu_id = bar_id.with(title.text());
let mut bar_state = BarState::load(ui.ctx(), bar_id);
let mut button = Button::new(title);
if bar_state.open_menu.is_menu_open(menu_id) {
button = button.fill(ui.visuals().widgets.open.bg_fill);
button = button.stroke(ui.visuals().widgets.open.bg_stroke);
}
let button_response = ui.add(button);
let inner = bar_state.bar_menu(&button_response, add_contents);
bar_state.store(ui.ctx(), bar_id);
InnerResponse::new(inner.map(|r| r.inner), button_response)
}
/// Response to secondary clicks (right-clicks) by showing the given menu.
pub(crate) fn context_menu(
response: &Response,
add_contents: impl FnOnce(&mut Ui),
) -> Option<InnerResponse<()>> {
let menu_id = Id::new("__egui::context_menu");
let mut bar_state = BarState::load(&response.ctx, menu_id);
MenuRoot::context_click_interaction(response, &mut bar_state, response.id);
let inner_response = bar_state.show(response, add_contents);
bar_state.store(&response.ctx, menu_id);
inner_response
}
/// Stores the state for the context menu.
#[derive(Clone, Default)]
pub(crate) struct MenuRootManager {
inner: Option<MenuRoot>,
}
impl MenuRootManager {
/// Show a menu at pointer if right-clicked response.
/// Should be called from [`Context`] on a [`Response`]
pub fn show<R>(
&mut self,
response: &Response,
add_contents: impl FnOnce(&mut Ui) -> R,
) -> Option<InnerResponse<R>> {
if let Some(root) = self.inner.as_mut() {
let (menu_response, inner_response) = root.show(response, add_contents);
if MenuResponse::Close == menu_response {
self.inner = None;
}
inner_response
} else {
None
}
}
fn is_menu_open(&self, id: Id) -> bool {
self.inner.as_ref().map(|m| m.id) == Some(id)
}
}
impl std::ops::Deref for MenuRootManager {
type Target = Option<MenuRoot>;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl std::ops::DerefMut for MenuRootManager {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.inner
}
}
/// Menu root associated with an Id from a Response
#[derive(Clone)]
pub(crate) struct MenuRoot {
pub menu_state: Arc<RwLock<MenuState>>,
pub id: Id,
}
impl MenuRoot {
pub fn new(position: Pos2, id: Id) -> Self {
Self {
menu_state: Arc::new(RwLock::new(MenuState::new(position))),
id,
}
}
pub fn show<R>(
&mut self,
response: &Response,
add_contents: impl FnOnce(&mut Ui) -> R,
) -> (MenuResponse, Option<InnerResponse<R>>) {
if self.id == response.id {
let inner_response =
MenuState::show(&response.ctx, &self.menu_state, self.id, add_contents);
let mut menu_state = self.menu_state.write();
menu_state.rect = inner_response.response.rect;
if menu_state.response.is_close() {
return (MenuResponse::Close, Some(inner_response));
}
}
(MenuResponse::Stay, None)
}
/// Interaction with a stationary menu, i.e. fixed in another Ui.
///
/// Responds to primary clicks.
fn stationary_interaction(
response: &Response,
root: &mut MenuRootManager,
id: Id,
) -> MenuResponse {
// Lock the input once for the whole function call (see https://github.com/emilk/egui/pull/1380).
let input = response.ctx.input();
if (response.clicked() && root.is_menu_open(id)) || input.key_pressed(Key::Escape) {
// menu open and button clicked or esc pressed
return MenuResponse::Close;
} else if (response.clicked() && !root.is_menu_open(id))
|| (response.hovered() && root.is_some())
{
// menu not open and button clicked
// or button hovered while other menu is open
let pos = response.rect.left_bottom();
return MenuResponse::Create(pos, id);
} else if input.pointer.any_pressed() && input.pointer.primary_down() {
if let Some(pos) = input.pointer.interact_pos() {
if let Some(root) = root.inner.as_mut() {
if root.id == id {
// pressed somewhere while this menu is open
let menu_state = root.menu_state.read();
let in_menu = menu_state.area_contains(pos);
if !in_menu {
return MenuResponse::Close;
}
}
}
}
}
MenuResponse::Stay
}
/// Interaction with a context menu (secondary clicks).
fn context_interaction(
response: &Response,
root: &mut Option<MenuRoot>,
id: Id,
) -> MenuResponse {
let response = response.interact(Sense::click());
let pointer = &response.ctx.input().pointer;
if pointer.any_pressed() {
if let Some(pos) = pointer.interact_pos() {
let mut destroy = false;
let mut in_old_menu = false;
if let Some(root) = root {
let menu_state = root.menu_state.read();
in_old_menu = menu_state.area_contains(pos);
destroy = root.id == response.id;
}
if !in_old_menu {
if response.hovered() && pointer.secondary_down() {
return MenuResponse::Create(pos, id);
} else if (response.hovered() && pointer.primary_down()) || destroy {
return MenuResponse::Close;
}
}
}
}
MenuResponse::Stay
}
fn handle_menu_response(root: &mut MenuRootManager, menu_response: MenuResponse) {
match menu_response {
MenuResponse::Create(pos, id) => {
root.inner = Some(MenuRoot::new(pos, id));
}
MenuResponse::Close => root.inner = None,
MenuResponse::Stay => {}
}
}
/// Respond to secondary (right) clicks.
pub fn context_click_interaction(response: &Response, root: &mut MenuRootManager, id: Id) {
let menu_response = Self::context_interaction(response, root, id);
Self::handle_menu_response(root, menu_response);
}
// Responds to primary clicks.
pub fn stationary_click_interaction(response: &Response, root: &mut MenuRootManager, id: Id) {
let menu_response = Self::stationary_interaction(response, root, id);
Self::handle_menu_response(root, menu_response);
}
}
#[derive(Copy, Clone, PartialEq)]
pub(crate) enum MenuResponse {
Close,
Stay,
Create(Pos2, Id),
}
impl MenuResponse {
pub fn is_close(&self) -> bool {
*self == Self::Close
}
}
pub struct SubMenuButton {
text: WidgetText,
icon: WidgetText,
index: usize,
}
impl SubMenuButton {
/// The `icon` can be an emoji (e.g. `⏵` right arrow), shown right of the label
fn new(text: impl Into<WidgetText>, icon: impl Into<WidgetText>, index: usize) -> Self {
Self {
text: text.into(),
icon: icon.into(),
index,
}
}
fn visuals<'a>(
ui: &'a Ui,
response: &'_ Response,
menu_state: &'_ MenuState,
sub_id: Id,
) -> &'a WidgetVisuals {
if menu_state.is_open(sub_id) {
&ui.style().visuals.widgets.hovered
} else {
ui.style().interact(response)
}
}
pub fn icon(mut self, icon: impl Into<WidgetText>) -> Self {
self.icon = icon.into();
self
}
pub(crate) fn show(self, ui: &mut Ui, menu_state: &MenuState, sub_id: Id) -> Response {
let SubMenuButton { text, icon, .. } = self;
let text_style = TextStyle::Button;
let sense = Sense::click();
let button_padding = ui.spacing().button_padding;
let total_extra = button_padding + button_padding;
let text_available_width = ui.available_width() - total_extra.x;
let text_galley =
text.into_galley(ui, Some(true), text_available_width, text_style.clone());
let icon_available_width = text_available_width - text_galley.size().x;
let icon_galley = icon.into_galley(ui, Some(true), icon_available_width, text_style);
let text_and_icon_size = Vec2::new(
text_galley.size().x + icon_galley.size().x,
text_galley.size().y.max(icon_galley.size().y),
);
let desired_size = text_and_icon_size + 2.0 * button_padding;
let (rect, response) = ui.allocate_at_least(desired_size, sense);
response.widget_info(|| {
crate::WidgetInfo::labeled(crate::WidgetType::Button, &text_galley.text())
});
if ui.is_rect_visible(rect) {
let visuals = Self::visuals(ui, &response, menu_state, sub_id);
let text_pos = Align2::LEFT_CENTER
.align_size_within_rect(text_galley.size(), rect.shrink2(button_padding))
.min;
let icon_pos = Align2::RIGHT_CENTER
.align_size_within_rect(icon_galley.size(), rect.shrink2(button_padding))
.min;
if ui.visuals().button_frame {
ui.painter().rect_filled(
rect.expand(visuals.expansion),
visuals.rounding,
visuals.bg_fill,
);
}
let text_color = visuals.text_color();
text_galley.paint_with_fallback_color(ui.painter(), text_pos, text_color);
icon_galley.paint_with_fallback_color(ui.painter(), icon_pos, text_color);
}
response
}
}
pub struct SubMenu {
button: SubMenuButton,
parent_state: Arc<RwLock<MenuState>>,
}
impl SubMenu {
fn new(parent_state: Arc<RwLock<MenuState>>, text: impl Into<WidgetText>) -> Self {
let index = parent_state.write().next_entry_index();
Self {
button: SubMenuButton::new(text, "⏵", index),
parent_state,
}
}
pub fn show<R>(
self,
ui: &mut Ui,
add_contents: impl FnOnce(&mut Ui) -> R,
) -> InnerResponse<Option<R>> {
let sub_id = ui.id().with(self.button.index);
let button = self.button.show(ui, &*self.parent_state.read(), sub_id);
self.parent_state
.write()
.submenu_button_interaction(ui, sub_id, &button);
let inner = self
.parent_state
.write()
.show_submenu(ui.ctx(), sub_id, add_contents);
InnerResponse::new(inner, button)
}
}
pub(crate) struct MenuState {
/// The opened sub-menu and its [`Id`]
sub_menu: Option<(Id, Arc<RwLock<MenuState>>)>,
/// Bounding box of this menu (without the sub-menu)
pub rect: Rect,
/// Used to check if any menu in the tree wants to close
pub response: MenuResponse,
/// Used to hash different [`Id`]s for sub-menus
entry_count: usize,
}
impl MenuState {
pub fn new(position: Pos2) -> Self {
Self {
rect: Rect::from_min_size(position, Vec2::ZERO),
sub_menu: None,
response: MenuResponse::Stay,
entry_count: 0,
}
}
/// Close menu hierarchy.
pub fn close(&mut self) {
self.response = MenuResponse::Close;
}
pub fn show<R>(
ctx: &Context,
menu_state: &Arc<RwLock<Self>>,
id: Id,
add_contents: impl FnOnce(&mut Ui) -> R,
) -> InnerResponse<R> {
crate::menu::menu_ui(ctx, id, menu_state, add_contents)
}
fn show_submenu<R>(
&mut self,
ctx: &Context,
id: Id,
add_contents: impl FnOnce(&mut Ui) -> R,
) -> Option<R> {
let (sub_response, response) = self.submenu(id).map(|sub| {
let inner_response = Self::show(ctx, sub, id, add_contents);
(sub.read().response, inner_response.inner)
})?;
self.cascade_close_response(sub_response);
Some(response)
}
/// Check if position is in the menu hierarchy's area.
pub fn area_contains(&self, pos: Pos2) -> bool {
self.rect.contains(pos)
|| self
.sub_menu
.as_ref()
.map_or(false, |(_, sub)| sub.read().area_contains(pos))
}
fn next_entry_index(&mut self) -> usize {
self.entry_count += 1;
self.entry_count - 1
}
/// Sense button interaction opening and closing submenu.
fn submenu_button_interaction(&mut self, ui: &mut Ui, sub_id: Id, button: &Response) {
let pointer = &ui.input().pointer.clone();
let open = self.is_open(sub_id);
if self.moving_towards_current_submenu(pointer) {
// ensure to repaint once even when pointer is not moving
ui.ctx().request_repaint();
} else if !open && button.hovered() {
let pos = button.rect.right_top();
self.open_submenu(sub_id, pos);
} else if open && !button.hovered() && !self.hovering_current_submenu(pointer) {
self.close_submenu();
}
}
/// Check if `dir` points from `pos` towards left side of `rect`.
fn points_at_left_of_rect(pos: Pos2, dir: Vec2, rect: Rect) -> bool {
let vel_a = dir.angle();
let top_a = (rect.left_top() - pos).angle();
let bottom_a = (rect.left_bottom() - pos).angle();
bottom_a - vel_a >= 0.0 && top_a - vel_a <= 0.0
}
/// Check if pointer is moving towards current submenu.
fn moving_towards_current_submenu(&self, pointer: &PointerState) -> bool {
if pointer.is_still() {
return false;
}
if let Some(sub_menu) = self.current_submenu() {
if let Some(pos) = pointer.hover_pos() {
return Self::points_at_left_of_rect(pos, pointer.velocity(), sub_menu.read().rect);
}
}
false
}
/// Check if pointer is hovering current submenu.
fn hovering_current_submenu(&self, pointer: &PointerState) -> bool {
if let Some(sub_menu) = self.current_submenu() {
if let Some(pos) = pointer.hover_pos() {
return sub_menu.read().area_contains(pos);
}
}
false
}
/// Cascade close response to menu root.
fn cascade_close_response(&mut self, response: MenuResponse) {
if response.is_close() {
self.response = response;
}
}
fn is_open(&self, id: Id) -> bool {
self.sub_id() == Some(id)
}
fn sub_id(&self) -> Option<Id> {
self.sub_menu.as_ref().map(|(id, _)| *id)
}
fn current_submenu(&self) -> Option<&Arc<RwLock<MenuState>>> {
self.sub_menu.as_ref().map(|(_, sub)| sub)
}
fn submenu(&mut self, id: Id) -> Option<&Arc<RwLock<MenuState>>> {
self.sub_menu
.as_ref()
.and_then(|(k, sub)| if id == *k { Some(sub) } else { None })
}
/// Open submenu at position, if not already open.
fn open_submenu(&mut self, id: Id, pos: Pos2) {
if !self.is_open(id) {
self.sub_menu = Some((id, Arc::new(RwLock::new(MenuState::new(pos)))));
}
}
fn close_submenu(&mut self) {
self.sub_menu = None;
}
}
+438
View File
@@ -0,0 +1,438 @@
use std::ops::RangeInclusive;
use std::sync::Arc;
use crate::{
emath::{Align2, Pos2, Rect, Vec2},
layers::{LayerId, PaintList, ShapeIdx},
Color32, Context, FontId,
};
use epaint::{
mutex::{RwLockReadGuard, RwLockWriteGuard},
text::{Fonts, Galley},
CircleShape, RectShape, Rounding, Shape, Stroke,
};
/// Helper to paint shapes and text to a specific region on a specific layer.
///
/// All coordinates are screen coordinates in the unit points (one point can consist of many physical pixels).
#[derive(Clone)]
pub struct Painter {
/// Source of fonts and destination of shapes
ctx: Context,
/// Where we paint
layer_id: LayerId,
/// Everything painted in this [`Painter`] will be clipped against this.
/// This means nothing outside of this rectangle will be visible on screen.
clip_rect: Rect,
/// If set, all shapes will have their colors modified to be closer to this.
/// This is used to implement grayed out interfaces.
fade_to_color: Option<Color32>,
}
impl Painter {
/// Create a painter to a specific layer within a certain clip rectangle.
pub fn new(ctx: Context, layer_id: LayerId, clip_rect: Rect) -> Self {
Self {
ctx,
layer_id,
clip_rect,
fade_to_color: None,
}
}
/// Redirect where you are painting.
#[must_use]
pub fn with_layer_id(self, layer_id: LayerId) -> Self {
Self {
ctx: self.ctx,
layer_id,
clip_rect: self.clip_rect,
fade_to_color: None,
}
}
/// Create a painter for a sub-region of this [`Painter`].
///
/// The clip-rect of the returned [`Painter`] will be the intersection
/// of the given rectangle and the `clip_rect()` of the parent [`Painter`].
pub fn with_clip_rect(&self, rect: Rect) -> Self {
Self {
ctx: self.ctx.clone(),
layer_id: self.layer_id,
clip_rect: rect.intersect(self.clip_rect),
fade_to_color: self.fade_to_color,
}
}
/// Redirect where you are painting.
pub fn set_layer_id(&mut self, layer_id: LayerId) {
self.layer_id = layer_id;
}
/// If set, colors will be modified to look like this
pub(crate) fn set_fade_to_color(&mut self, fade_to_color: Option<Color32>) {
self.fade_to_color = fade_to_color;
}
pub(crate) fn is_visible(&self) -> bool {
self.fade_to_color != Some(Color32::TRANSPARENT)
}
/// If `false`, nothing added to the painter will be visible
pub(crate) fn set_invisible(&mut self) {
self.fade_to_color = Some(Color32::TRANSPARENT);
}
#[deprecated = "Use Painter::with_clip_rect"] // Deprecated in 2022-04-18, before egui 0.18
pub fn sub_region(&self, rect: Rect) -> Self {
Self {
ctx: self.ctx.clone(),
layer_id: self.layer_id,
clip_rect: rect.intersect(self.clip_rect),
fade_to_color: self.fade_to_color,
}
}
}
/// ## Accessors etc
impl Painter {
/// Get a reference to the parent [`Context`].
#[inline(always)]
pub fn ctx(&self) -> &Context {
&self.ctx
}
/// Available fonts.
#[inline(always)]
pub fn fonts(&self) -> RwLockReadGuard<'_, Fonts> {
self.ctx.fonts()
}
/// Where we paint
#[inline(always)]
pub fn layer_id(&self) -> LayerId {
self.layer_id
}
/// Everything painted in this [`Painter`] will be clipped against this.
/// This means nothing outside of this rectangle will be visible on screen.
#[inline(always)]
pub fn clip_rect(&self) -> Rect {
self.clip_rect
}
/// Everything painted in this [`Painter`] will be clipped against this.
/// This means nothing outside of this rectangle will be visible on screen.
#[inline(always)]
pub fn set_clip_rect(&mut self, clip_rect: Rect) {
self.clip_rect = clip_rect;
}
/// Useful for pixel-perfect rendering.
#[inline(always)]
pub fn round_to_pixel(&self, point: f32) -> f32 {
self.ctx().round_to_pixel(point)
}
/// Useful for pixel-perfect rendering.
#[inline(always)]
pub fn round_vec_to_pixels(&self, vec: Vec2) -> Vec2 {
self.ctx().round_vec_to_pixels(vec)
}
/// Useful for pixel-perfect rendering.
#[inline(always)]
pub fn round_pos_to_pixels(&self, pos: Pos2) -> Pos2 {
self.ctx().round_pos_to_pixels(pos)
}
}
/// ## Low level
impl Painter {
fn paint_list(&self) -> RwLockWriteGuard<'_, PaintList> {
RwLockWriteGuard::map(self.ctx.graphics(), |g| g.list(self.layer_id))
}
fn transform_shape(&self, shape: &mut Shape) {
if let Some(fade_to_color) = self.fade_to_color {
tint_shape_towards(shape, fade_to_color);
}
}
/// It is up to the caller to make sure there is room for this.
/// Can be used for free painting.
/// NOTE: all coordinates are screen coordinates!
pub fn add(&self, shape: impl Into<Shape>) -> ShapeIdx {
if self.fade_to_color == Some(Color32::TRANSPARENT) {
self.paint_list().add(self.clip_rect, Shape::Noop)
} else {
let mut shape = shape.into();
self.transform_shape(&mut shape);
self.paint_list().add(self.clip_rect, shape)
}
}
/// Add many shapes at once.
///
/// Calling this once is generally faster than calling [`Self::add`] multiple times.
pub fn extend(&self, mut shapes: Vec<Shape>) {
if self.fade_to_color == Some(Color32::TRANSPARENT) {
return;
}
if !shapes.is_empty() {
if self.fade_to_color.is_some() {
for shape in &mut shapes {
self.transform_shape(shape);
}
}
self.paint_list().extend(self.clip_rect, shapes);
}
}
/// Modify an existing [`Shape`].
pub fn set(&self, idx: ShapeIdx, shape: impl Into<Shape>) {
if self.fade_to_color == Some(Color32::TRANSPARENT) {
return;
}
let mut shape = shape.into();
self.transform_shape(&mut shape);
self.paint_list().set(idx, self.clip_rect, shape);
}
}
/// ## Debug painting
impl Painter {
#[allow(clippy::needless_pass_by_value)]
pub fn debug_rect(&self, rect: Rect, color: Color32, text: impl ToString) {
self.rect_stroke(rect, 0.0, (1.0, color));
self.text(
rect.min,
Align2::LEFT_TOP,
text.to_string(),
FontId::monospace(14.0),
color,
);
}
pub fn error(&self, pos: Pos2, text: impl std::fmt::Display) -> Rect {
let color = self.ctx.style().visuals.error_fg_color;
self.debug_text(pos, Align2::LEFT_TOP, color, format!("🔥 {}", text))
}
/// text with a background
#[allow(clippy::needless_pass_by_value)]
pub fn debug_text(
&self,
pos: Pos2,
anchor: Align2,
color: Color32,
text: impl ToString,
) -> Rect {
let galley = self.layout_no_wrap(text.to_string(), FontId::monospace(14.0), color);
let rect = anchor.anchor_rect(Rect::from_min_size(pos, galley.size()));
let frame_rect = rect.expand(2.0);
self.add(Shape::rect_filled(
frame_rect,
0.0,
Color32::from_black_alpha(240),
));
self.galley(rect.min, galley);
frame_rect
}
}
/// # Paint different primitives
impl Painter {
/// Paints a line from the first point to the second.
pub fn line_segment(&self, points: [Pos2; 2], stroke: impl Into<Stroke>) {
self.add(Shape::LineSegment {
points,
stroke: stroke.into(),
});
}
/// Paints a horizontal line.
pub fn hline(&self, x: RangeInclusive<f32>, y: f32, stroke: impl Into<Stroke>) {
self.add(Shape::hline(x, y, stroke));
}
/// Paints a vertical line.
pub fn vline(&self, x: f32, y: RangeInclusive<f32>, stroke: impl Into<Stroke>) {
self.add(Shape::vline(x, y, stroke));
}
pub fn circle(
&self,
center: Pos2,
radius: f32,
fill_color: impl Into<Color32>,
stroke: impl Into<Stroke>,
) {
self.add(CircleShape {
center,
radius,
fill: fill_color.into(),
stroke: stroke.into(),
});
}
pub fn circle_filled(&self, center: Pos2, radius: f32, fill_color: impl Into<Color32>) {
self.add(CircleShape {
center,
radius,
fill: fill_color.into(),
stroke: Default::default(),
});
}
pub fn circle_stroke(&self, center: Pos2, radius: f32, stroke: impl Into<Stroke>) {
self.add(CircleShape {
center,
radius,
fill: Default::default(),
stroke: stroke.into(),
});
}
pub fn rect(
&self,
rect: Rect,
rounding: impl Into<Rounding>,
fill_color: impl Into<Color32>,
stroke: impl Into<Stroke>,
) {
self.add(RectShape {
rect,
rounding: rounding.into(),
fill: fill_color.into(),
stroke: stroke.into(),
});
}
pub fn rect_filled(
&self,
rect: Rect,
rounding: impl Into<Rounding>,
fill_color: impl Into<Color32>,
) {
self.add(RectShape {
rect,
rounding: rounding.into(),
fill: fill_color.into(),
stroke: Default::default(),
});
}
pub fn rect_stroke(
&self,
rect: Rect,
rounding: impl Into<Rounding>,
stroke: impl Into<Stroke>,
) {
self.add(RectShape {
rect,
rounding: rounding.into(),
fill: Default::default(),
stroke: stroke.into(),
});
}
/// Show an arrow starting at `origin` and going in the direction of `vec`, with the length `vec.length()`.
pub fn arrow(&self, origin: Pos2, vec: Vec2, stroke: Stroke) {
use crate::emath::*;
let rot = Rot2::from_angle(std::f32::consts::TAU / 10.0);
let tip_length = vec.length() / 4.0;
let tip = origin + vec;
let dir = vec.normalized();
self.line_segment([origin, tip], stroke);
self.line_segment([tip, tip - tip_length * (rot * dir)], stroke);
self.line_segment([tip, tip - tip_length * (rot.inverse() * dir)], stroke);
}
}
/// ## Text
impl Painter {
/// Lay out and paint some text.
///
/// To center the text at the given position, use `Align2::CENTER_CENTER`.
///
/// To find out the size of text before painting it, use
/// [`Self::layout`] or [`Self::layout_no_wrap`].
///
/// Returns where the text ended up.
#[allow(clippy::needless_pass_by_value)]
pub fn text(
&self,
pos: Pos2,
anchor: Align2,
text: impl ToString,
font_id: FontId,
text_color: Color32,
) -> Rect {
let galley = self.layout_no_wrap(text.to_string(), font_id, text_color);
let rect = anchor.anchor_rect(Rect::from_min_size(pos, galley.size()));
self.galley(rect.min, galley);
rect
}
/// Will wrap text at the given width and line break at `\n`.
///
/// Paint the results with [`Self::galley`].
#[inline(always)]
pub fn layout(
&self,
text: String,
font_id: FontId,
color: crate::Color32,
wrap_width: f32,
) -> Arc<Galley> {
self.fonts().layout(text, font_id, color, wrap_width)
}
/// Will line break at `\n`.
///
/// Paint the results with [`Self::galley`].
#[inline(always)]
pub fn layout_no_wrap(
&self,
text: String,
font_id: FontId,
color: crate::Color32,
) -> Arc<Galley> {
self.fonts().layout(text, font_id, color, f32::INFINITY)
}
/// Paint text that has already been layed out in a [`Galley`].
///
/// You can create the [`Galley`] with [`Self::layout`].
///
/// If you want to change the color of the text, use [`Self::galley_with_color`].
#[inline(always)]
pub fn galley(&self, pos: Pos2, galley: Arc<Galley>) {
if !galley.is_empty() {
self.add(Shape::galley(pos, galley));
}
}
/// Paint text that has already been layed out in a [`Galley`].
///
/// You can create the [`Galley`] with [`Self::layout`].
///
/// The text color in the [`Galley`] will be replaced with the given color.
#[inline(always)]
pub fn galley_with_color(&self, pos: Pos2, galley: Arc<Galley>, text_color: Color32) {
if !galley.is_empty() {
self.add(Shape::galley_with_color(pos, galley, text_color));
}
}
}
fn tint_shape_towards(shape: &mut Shape, target: Color32) {
epaint::shape_transform::adjust_colors(shape, &|color| {
*color = crate::color::tint_color_towards(*color, target);
});
}
+279
View File
@@ -0,0 +1,279 @@
use crate::*;
pub(crate) struct Placer {
/// If set this will take precedence over [`layout`].
grid: Option<grid::GridLayout>,
layout: Layout,
region: Region,
}
impl Placer {
pub(crate) fn new(max_rect: Rect, layout: Layout) -> Self {
let region = layout.region_from_max_rect(max_rect);
Self {
grid: None,
layout,
region,
}
}
#[inline(always)]
pub(crate) fn set_grid(&mut self, grid: grid::GridLayout) {
self.grid = Some(grid);
}
pub(crate) fn save_grid(&mut self) {
if let Some(grid) = &mut self.grid {
grid.save();
}
}
#[inline(always)]
pub(crate) fn grid(&self) -> Option<&grid::GridLayout> {
self.grid.as_ref()
}
#[inline(always)]
pub(crate) fn is_grid(&self) -> bool {
self.grid.is_some()
}
#[inline(always)]
pub(crate) fn layout(&self) -> &Layout {
&self.layout
}
#[inline(always)]
pub(crate) fn prefer_right_to_left(&self) -> bool {
self.layout.prefer_right_to_left()
}
#[inline(always)]
pub(crate) fn min_rect(&self) -> Rect {
self.region.min_rect
}
#[inline(always)]
pub(crate) fn max_rect(&self) -> Rect {
self.region.max_rect
}
#[inline(always)]
pub(crate) fn force_set_min_rect(&mut self, min_rect: Rect) {
self.region.min_rect = min_rect;
}
#[inline(always)]
pub(crate) fn cursor(&self) -> Rect {
self.region.cursor
}
#[inline(always)]
pub(crate) fn set_cursor(&mut self, cursor: Rect) {
self.region.cursor = cursor;
}
}
impl Placer {
pub(crate) fn align_size_within_rect(&self, size: Vec2, outer: Rect) -> Rect {
if let Some(grid) = &self.grid {
grid.align_size_within_rect(size, outer)
} else {
self.layout.align_size_within_rect(size, outer)
}
}
pub(crate) fn available_rect_before_wrap(&self) -> Rect {
if let Some(grid) = &self.grid {
grid.available_rect(&self.region)
} else {
self.layout.available_rect_before_wrap(&self.region)
}
}
/// Amount of space available for a widget.
/// For wrapping layouts, this is the maximum (after wrap).
pub(crate) fn available_size(&self) -> Vec2 {
if let Some(grid) = &self.grid {
grid.available_rect(&self.region).size()
} else {
self.layout.available_size(&self.region)
}
}
/// Returns where to put the next widget that is of the given size.
/// The returned `frame_rect` will always be justified along the cross axis.
/// This is what you then pass to `advance_after_rects`.
/// Use `justify_and_align` to get the inner `widget_rect`.
pub(crate) fn next_space(&self, child_size: Vec2, item_spacing: Vec2) -> Rect {
egui_assert!(child_size.is_finite() && child_size.x >= 0.0 && child_size.y >= 0.0);
self.region.sanity_check();
if let Some(grid) = &self.grid {
grid.next_cell(self.region.cursor, child_size)
} else {
self.layout
.next_frame(&self.region, child_size, item_spacing)
}
}
/// Where do we expect a zero-sized widget to be placed?
pub(crate) fn next_widget_position(&self) -> Pos2 {
if let Some(grid) = &self.grid {
grid.next_cell(self.region.cursor, Vec2::ZERO).center()
} else {
self.layout.next_widget_position(&self.region)
}
}
/// Apply justify or alignment after calling `next_space`.
pub(crate) fn justify_and_align(&self, rect: Rect, child_size: Vec2) -> Rect {
crate::egui_assert!(!rect.any_nan());
crate::egui_assert!(!child_size.any_nan());
if let Some(grid) = &self.grid {
grid.justify_and_align(rect, child_size)
} else {
self.layout.justify_and_align(rect, child_size)
}
}
/// Advance the cursor by this many points.
/// [`Self::min_rect`] will expand to contain the cursor.
pub(crate) fn advance_cursor(&mut self, amount: f32) {
crate::egui_assert!(
self.grid.is_none(),
"You cannot advance the cursor when in a grid layout"
);
self.layout.advance_cursor(&mut self.region, amount);
}
/// Advance cursor after a widget was added to a specific rectangle
/// and expand the region `min_rect`.
///
/// * `frame_rect`: the frame inside which a widget was e.g. centered
/// * `widget_rect`: the actual rect used by the widget
pub(crate) fn advance_after_rects(
&mut self,
frame_rect: Rect,
widget_rect: Rect,
item_spacing: Vec2,
) {
egui_assert!(!frame_rect.any_nan());
egui_assert!(!widget_rect.any_nan());
self.region.sanity_check();
if let Some(grid) = &mut self.grid {
grid.advance(&mut self.region.cursor, frame_rect, widget_rect);
} else {
self.layout.advance_after_rects(
&mut self.region.cursor,
frame_rect,
widget_rect,
item_spacing,
);
}
self.expand_to_include_rect(frame_rect); // e.g. for centered layouts: pretend we used whole frame
self.region.sanity_check();
}
/// Move to the next row in a grid layout or wrapping layout.
/// Otherwise does nothing.
pub(crate) fn end_row(&mut self, item_spacing: Vec2, painter: &Painter) {
if let Some(grid) = &mut self.grid {
grid.end_row(&mut self.region.cursor, painter);
} else {
self.layout.end_row(&mut self.region, item_spacing);
}
}
/// Set row height in horizontal wrapping layout.
pub(crate) fn set_row_height(&mut self, height: f32) {
self.layout.set_row_height(&mut self.region, height);
}
}
impl Placer {
/// Expand the `min_rect` and `max_rect` of this ui to include a child at the given rect.
pub(crate) fn expand_to_include_rect(&mut self, rect: Rect) {
self.region.expand_to_include_rect(rect);
}
/// Expand the `min_rect` and `max_rect` of this ui to include a child at the given x-coordinate.
pub(crate) fn expand_to_include_x(&mut self, x: f32) {
self.region.expand_to_include_x(x);
}
/// Expand the `min_rect` and `max_rect` of this ui to include a child at the given y-coordinate.
pub(crate) fn expand_to_include_y(&mut self, y: f32) {
self.region.expand_to_include_y(y);
}
fn next_widget_space_ignore_wrap_justify(&self, size: Vec2) -> Rect {
self.layout
.next_widget_space_ignore_wrap_justify(&self.region, size)
}
/// Set the maximum width of the ui.
/// You won't be able to shrink it below the current minimum size.
pub(crate) fn set_max_width(&mut self, width: f32) {
let rect = self.next_widget_space_ignore_wrap_justify(vec2(width, 0.0));
let region = &mut self.region;
region.max_rect.min.x = rect.min.x;
region.max_rect.max.x = rect.max.x;
region.max_rect = region.max_rect.union(region.min_rect); // make sure we didn't shrink too much
region.cursor.min.x = region.max_rect.min.x;
region.cursor.max.x = region.max_rect.max.x;
region.sanity_check();
}
/// Set the maximum height of the ui.
/// You won't be able to shrink it below the current minimum size.
pub(crate) fn set_max_height(&mut self, height: f32) {
let rect = self.next_widget_space_ignore_wrap_justify(vec2(0.0, height));
let region = &mut self.region;
region.max_rect.min.y = rect.min.y;
region.max_rect.max.y = rect.max.y;
region.max_rect = region.max_rect.union(region.min_rect); // make sure we didn't shrink too much
region.cursor.min.y = region.max_rect.min.y;
region.cursor.max.y = region.max_rect.max.y;
region.sanity_check();
}
/// Set the minimum width of the ui.
/// This can't shrink the ui, only make it larger.
pub(crate) fn set_min_width(&mut self, width: f32) {
let rect = self.next_widget_space_ignore_wrap_justify(vec2(width, 0.0));
self.region.expand_to_include_x(rect.min.x);
self.region.expand_to_include_x(rect.max.x);
}
/// Set the minimum height of the ui.
/// This can't shrink the ui, only make it larger.
pub(crate) fn set_min_height(&mut self, height: f32) {
let rect = self.next_widget_space_ignore_wrap_justify(vec2(0.0, height));
self.region.expand_to_include_y(rect.min.y);
self.region.expand_to_include_y(rect.max.y);
}
}
impl Placer {
pub(crate) fn debug_paint_cursor(&self, painter: &crate::Painter, text: impl ToString) {
let stroke = Stroke::new(1.0, Color32::DEBUG_COLOR);
if let Some(grid) = &self.grid {
let rect = grid.next_cell(self.cursor(), Vec2::splat(0.0));
painter.rect_stroke(rect, 1.0, stroke);
let align = Align2::CENTER_CENTER;
painter.debug_text(align.pos_in_rect(&rect), align, stroke.color, text);
} else {
self.layout
.paint_text_at_cursor(painter, &self.region, stroke, text);
}
}
}
+659
View File
@@ -0,0 +1,659 @@
use crate::{
emath::{Align, Pos2, Rect, Vec2},
menu, Context, CursorIcon, Id, LayerId, PointerButton, Sense, Ui, WidgetText,
NUM_POINTER_BUTTONS,
};
// ----------------------------------------------------------------------------
/// The result of adding a widget to a [`Ui`].
///
/// A [`Response`] lets you know whether or not a widget is being hovered, clicked or dragged.
/// It also lets you easily show a tooltip on hover.
///
/// Whenever something gets added to a [`Ui`], a [`Response`] object is returned.
/// [`ui.add`] returns a [`Response`], as does [`ui.button`], and all similar shortcuts.
#[derive(Clone)]
pub struct Response {
// CONTEXT:
/// Used for optionally showing a tooltip and checking for more interactions.
pub ctx: Context,
// IN:
/// Which layer the widget is part of.
pub layer_id: LayerId,
/// The [`Id`] of the widget/area this response pertains.
pub id: Id,
/// The area of the screen we are talking about.
pub rect: Rect,
/// The senses (click and/or drag) that the widget was interested in (if any).
pub sense: Sense,
/// Was the widget enabled?
/// If `false`, there was no interaction attempted (not even hover).
#[doc(hidden)]
pub enabled: bool,
// OUT:
/// The pointer is hovering above this widget or the widget was clicked/tapped this frame.
#[doc(hidden)]
pub hovered: bool,
/// The pointer clicked this thing this frame.
#[doc(hidden)]
pub clicked: [bool; NUM_POINTER_BUTTONS],
// TODO(emilk): `released` for sliders
/// The thing was double-clicked.
#[doc(hidden)]
pub double_clicked: [bool; NUM_POINTER_BUTTONS],
/// The thing was triple-clicked.
pub(crate) triple_clicked: [bool; NUM_POINTER_BUTTONS],
/// The widgets is being dragged
#[doc(hidden)]
pub dragged: bool,
/// The widget was being dragged, but now it has been released.
#[doc(hidden)]
pub drag_released: bool,
/// Is the pointer button currently down on this widget?
/// This is true if the pointer is pressing down or dragging a widget
#[doc(hidden)]
pub is_pointer_button_down_on: bool,
/// Where the pointer (mouse/touch) were when when this widget was clicked or dragged.
/// `None` if the widget is not being interacted with.
#[doc(hidden)]
pub interact_pointer_pos: Option<Pos2>,
/// What the underlying data changed?
///
/// e.g. the slider was dragged, text was entered in a [`TextEdit`](crate::TextEdit) etc.
/// Always `false` for something like a [`Button`](crate::Button).
#[doc(hidden)]
pub changed: bool,
}
impl std::fmt::Debug for Response {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let Self {
ctx: _,
layer_id,
id,
rect,
sense,
enabled,
hovered,
clicked,
double_clicked,
triple_clicked,
dragged,
drag_released,
is_pointer_button_down_on,
interact_pointer_pos,
changed,
} = self;
f.debug_struct("Response")
.field("layer_id", layer_id)
.field("id", id)
.field("rect", rect)
.field("sense", sense)
.field("enabled", enabled)
.field("hovered", hovered)
.field("clicked", clicked)
.field("double_clicked", double_clicked)
.field("triple_clicked", triple_clicked)
.field("dragged", dragged)
.field("drag_released", drag_released)
.field("is_pointer_button_down_on", is_pointer_button_down_on)
.field("interact_pointer_pos", interact_pointer_pos)
.field("changed", changed)
.finish()
}
}
impl Response {
/// Returns true if this widget was clicked this frame by the primary button.
///
/// A click is registered when the mouse or touch is released within
/// a certain amount of time and distance from when and where it was pressed.
///
/// Note that the widget must be sensing clicks with [`Sense::click`].
/// [`crate::Button`] senses clicks; [`crate::Label`] does not (unless you call [`crate::Label::sense`]).
///
/// You can use [`Self::interact`] to sense more things *after* adding a widget.
#[inline(always)]
pub fn clicked(&self) -> bool {
self.clicked[PointerButton::Primary as usize]
}
/// Returns true if this widget was clicked this frame by the given button.
pub fn clicked_by(&self, button: PointerButton) -> bool {
self.clicked[button as usize]
}
/// Returns true if this widget was clicked this frame by the secondary mouse button (e.g. the right mouse button).
pub fn secondary_clicked(&self) -> bool {
self.clicked[PointerButton::Secondary as usize]
}
/// Returns true if this widget was clicked this frame by the middle mouse button.
pub fn middle_clicked(&self) -> bool {
self.clicked[PointerButton::Middle as usize]
}
/// Returns true if this widget was double-clicked this frame by the primary button.
pub fn double_clicked(&self) -> bool {
self.double_clicked[PointerButton::Primary as usize]
}
/// Returns true if this widget was triple-clicked this frame by the primary button.
pub fn triple_clicked(&self) -> bool {
self.triple_clicked[PointerButton::Primary as usize]
}
/// Returns true if this widget was double-clicked this frame by the given button.
pub fn double_clicked_by(&self, button: PointerButton) -> bool {
self.double_clicked[button as usize]
}
/// Returns true if this widget was triple-clicked this frame by the given button.
pub fn triple_clicked_by(&self, button: PointerButton) -> bool {
self.triple_clicked[button as usize]
}
/// `true` if there was a click *outside* this widget this frame.
pub fn clicked_elsewhere(&self) -> bool {
// We do not use self.clicked(), because we want to catch all clicks within our frame,
// even if we aren't clickable (or even enabled).
// This is important for windows and such that should close then the user clicks elsewhere.
let pointer = &self.ctx.input().pointer;
if pointer.any_click() {
// We detect clicks/hover on a "interact_rect" that is slightly larger than
// self.rect. See Context::interact.
// This means we can be hovered and clicked even though `!self.rect.contains(pos)` is true,
// hence the extra complexity here.
if self.hovered() {
false
} else if let Some(pos) = pointer.interact_pos() {
!self.rect.contains(pos)
} else {
false // clicked without a pointer, weird
}
} else {
false
}
}
/// Was the widget enabled?
/// If false, there was no interaction attempted
/// and the widget should be drawn in a gray disabled look.
#[inline(always)]
pub fn enabled(&self) -> bool {
self.enabled
}
/// The pointer is hovering above this widget or the widget was clicked/tapped this frame.
///
/// Note that this is slightly different from checking `response.rect.contains(pointer_pos)`.
/// For one, the hover rectangle is slightly larger, by half of the current item spacing
/// (to make it easier to click things). But `hovered` also checks that no other area
/// is covering this response rectangle.
#[inline(always)]
pub fn hovered(&self) -> bool {
self.hovered
}
/// This widget has the keyboard focus (i.e. is receiving key presses).
///
/// This function only returns true if the UI as a whole (e.g. window)
/// also has the keyboard focus. That makes this function suitable
/// for style choices, e.g. a thicker border around focused widgets.
pub fn has_focus(&self) -> bool {
// Access input and memory in separate statements to prevent deadlock.
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.
pub fn gained_focus(&self) -> bool {
self.ctx.memory().gained_focus(self.id)
}
/// The widget had keyboard focus and lost it,
/// either because the user pressed tab or clicked somewhere else,
/// or (in case of a [`crate::TextEdit`]) because the user pressed enter.
///
/// ```
/// # egui::__run_test_ui(|ui| {
/// # let mut my_text = String::new();
/// # fn do_request(_: &str) {}
/// let response = ui.text_edit_singleline(&mut my_text);
/// if response.lost_focus() && ui.input().key_pressed(egui::Key::Enter) {
/// do_request(&my_text);
/// }
/// # });
/// ```
pub fn lost_focus(&self) -> bool {
self.ctx.memory().lost_focus(self.id)
}
/// Request that this widget get keyboard focus.
pub fn request_focus(&self) {
self.ctx.memory().request_focus(self.id);
}
/// Surrender keyboard focus for this widget.
pub fn surrender_focus(&self) {
self.ctx.memory().surrender_focus(self.id);
}
/// The widgets is being dragged.
///
/// To find out which button(s), query [`crate::PointerState::button_down`]
/// (`ui.input().pointer.button_down(…)`).
///
/// 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`]).
///
/// You can use [`Self::interact`] to sense more things *after* adding a widget.
#[inline(always)]
pub fn dragged(&self) -> bool {
self.dragged
}
pub fn dragged_by(&self, button: PointerButton) -> bool {
self.dragged() && self.ctx.input().pointer.button_down(button)
}
/// Did a drag on this widgets begin this frame?
pub fn drag_started(&self) -> bool {
self.dragged && self.ctx.input().pointer.any_pressed()
}
/// The widget was being dragged, but now it has been released.
pub fn drag_released(&self) -> bool {
self.drag_released
}
/// If dragged, how many points were we dragged and in what direction?
pub fn drag_delta(&self) -> Vec2 {
if self.dragged() {
self.ctx.input().pointer.delta()
} else {
Vec2::ZERO
}
}
/// Where the pointer (mouse/touch) were when when this widget was clicked or dragged.
/// `None` if the widget is not being interacted with.
pub fn interact_pointer_pos(&self) -> Option<Pos2> {
self.interact_pointer_pos
}
/// If it is a good idea to show a tooltip, where is pointer?
/// None if the pointer is outside the response area.
pub fn hover_pos(&self) -> Option<Pos2> {
if self.hovered() {
self.ctx.input().pointer.hover_pos()
} else {
None
}
}
/// Is the pointer button currently down on this widget?
/// This is true if the pointer is pressing down or dragging a widget
#[inline(always)]
pub fn is_pointer_button_down_on(&self) -> bool {
self.is_pointer_button_down_on
}
/// What the underlying data changed?
///
/// e.g. the slider was dragged, text was entered in a [`TextEdit`](crate::TextEdit) etc.
/// Always `false` for something like a [`Button`](crate::Button).
///
/// Can sometimes be `true` even though the data didn't changed
/// (e.g. if the user entered a character and erased it the same frame).
///
/// This is not set if the *view* of the data was changed.
/// For instance, moving the cursor in a [`TextEdit`](crate::TextEdit) does not set this to `true`.
#[inline(always)]
pub fn changed(&self) -> bool {
self.changed
}
/// Report the data shown by this widget changed.
///
/// This must be called by widgets that represent some mutable data,
/// e.g. checkboxes, sliders etc.
///
/// This should be called when the *content* changes, but not when the view does.
/// So we call this when the text of a [`crate::TextEdit`], but not when the cursors changes.
#[inline(always)]
pub fn mark_changed(&mut self) {
self.changed = true;
}
/// Show this UI if the widget was hovered (i.e. a tooltip).
///
/// The text will not be visible if the widget is not enabled.
/// For that, use [`Self::on_disabled_hover_ui`] instead.
///
/// If you call this multiple times the tooltips will stack underneath the previous ones.
#[doc(alias = "tooltip")]
pub fn on_hover_ui(self, add_contents: impl FnOnce(&mut Ui)) -> Self {
if self.should_show_hover_ui() {
crate::containers::show_tooltip_for(
&self.ctx,
self.id.with("__tooltip"),
&self.rect,
add_contents,
);
}
self
}
/// Show this UI when hovering if the widget is disabled.
pub fn on_disabled_hover_ui(self, add_contents: impl FnOnce(&mut Ui)) -> Self {
if !self.enabled && self.ctx.rect_contains_pointer(self.layer_id, self.rect) {
crate::containers::show_tooltip_for(
&self.ctx,
self.id.with("__tooltip"),
&self.rect,
add_contents,
);
}
self
}
/// Like `on_hover_ui`, but show the ui next to cursor.
pub fn on_hover_ui_at_pointer(self, add_contents: impl FnOnce(&mut Ui)) -> Self {
if self.should_show_hover_ui() {
crate::containers::show_tooltip_at_pointer(
&self.ctx,
self.id.with("__tooltip"),
add_contents,
);
}
self
}
fn should_show_hover_ui(&self) -> bool {
if self.ctx.memory().everything_is_visible() {
return true;
}
if !self.hovered || !self.ctx.input().pointer.has_pointer() {
return false;
}
if self.ctx.style().interaction.show_tooltips_only_when_still
&& !self.ctx.input().pointer.is_still()
{
// wait for mouse to stop
self.ctx.request_repaint();
return false;
}
// 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.
if self.ctx.input().pointer.any_down()
&& self.ctx.input().pointer.has_moved_too_much_for_a_click
{
return false;
}
true
}
/// Like `on_hover_text`, but show the text next to cursor.
#[doc(alias = "tooltip")]
pub fn on_hover_text_at_pointer(self, text: impl Into<WidgetText>) -> Self {
self.on_hover_ui_at_pointer(|ui| {
ui.add(crate::widgets::Label::new(text));
})
}
/// Show this text if the widget was hovered (i.e. a tooltip).
///
/// The text will not be visible if the widget is not enabled.
/// For that, use [`Self::on_disabled_hover_text`] instead.
///
/// If you call this multiple times the tooltips will stack underneath the previous ones.
#[doc(alias = "tooltip")]
pub fn on_hover_text(self, text: impl Into<WidgetText>) -> Self {
self.on_hover_ui(|ui| {
ui.add(crate::widgets::Label::new(text));
})
}
/// Show this text when hovering if the widget is disabled.
pub fn on_disabled_hover_text(self, text: impl Into<WidgetText>) -> Self {
self.on_disabled_hover_ui(|ui| {
ui.add(crate::widgets::Label::new(text));
})
}
/// When hovered, use this icon for the mouse cursor.
pub fn on_hover_cursor(self, cursor: CursorIcon) -> Self {
if self.hovered() {
self.ctx.output().cursor_icon = cursor;
}
self
}
/// Check for more interactions (e.g. sense clicks on a [`Response`] returned from a label).
///
/// Note that this call will not add any hover-effects to the widget, so when possible
/// it is better to give the widget a [`Sense`] instead, e.g. using [`crate::Label::sense`].
///
/// ```
/// # egui::__run_test_ui(|ui| {
/// let response = ui.label("hello");
/// assert!(!response.clicked()); // labels don't sense clicks by default
/// let response = response.interact(egui::Sense::click());
/// if response.clicked() { /* … */ }
/// # });
/// ```
#[must_use]
pub fn interact(&self, sense: Sense) -> Self {
self.ctx.interact_with_hovered(
self.layer_id,
self.id,
self.rect,
sense,
self.enabled,
self.hovered,
)
}
/// Adjust the scroll position until this UI becomes visible.
///
/// If `align` is `None`, it'll scroll enough to bring the UI into view.
///
/// See also: [`Ui::scroll_to_cursor`], [`Ui::scroll_to_rect`]. [`Ui::scroll_with_delta`].
///
/// ```
/// # egui::__run_test_ui(|ui| {
/// egui::ScrollArea::vertical().show(ui, |ui| {
/// for i in 0..1000 {
/// let response = ui.button("Scroll to me");
/// if response.clicked() {
/// response.scroll_to_me(Some(egui::Align::Center));
/// }
/// }
/// });
/// # });
/// ```
pub fn scroll_to_me(&self, align: Option<Align>) {
self.ctx.frame_state().scroll_target[0] = Some((self.rect.x_range(), align));
self.ctx.frame_state().scroll_target[1] = Some((self.rect.y_range(), align));
}
/// For accessibility.
///
/// Call after interacting and potential calls to [`Self::mark_changed`].
pub fn widget_info(&self, make_info: impl Fn() -> crate::WidgetInfo) {
use crate::output::OutputEvent;
let event = if self.clicked() {
Some(OutputEvent::Clicked(make_info()))
} else if self.double_clicked() {
Some(OutputEvent::DoubleClicked(make_info()))
} else if self.triple_clicked() {
Some(OutputEvent::TripleClicked(make_info()))
} else if self.gained_focus() {
Some(OutputEvent::FocusGained(make_info()))
} else if self.changed {
Some(OutputEvent::ValueChanged(make_info()))
} else {
None
};
if let Some(event) = event {
self.ctx.output().events.push(event);
}
}
/// Response to secondary clicks (right-clicks) by showing the given menu.
///
/// ```
/// # use egui::{Label, Sense};
/// # egui::__run_test_ui(|ui| {
/// let response = ui.add(Label::new("Right-click me!").sense(Sense::click()));
/// response.context_menu(|ui| {
/// if ui.button("Close the menu").clicked() {
/// ui.close_menu();
/// }
/// });
/// # });
/// ```
///
/// See also: [`Ui::menu_button`] and [`Ui::close_menu`].
pub fn context_menu(self, add_contents: impl FnOnce(&mut Ui)) -> Self {
menu::context_menu(&self, add_contents);
self
}
}
impl Response {
/// A logical "or" operation.
/// For instance `a.union(b).hovered` means "was either a or b hovered?".
///
/// The resulting [`Self::id`] will come from the first (`self`) argument.
pub fn union(&self, other: Self) -> Self {
assert!(self.ctx == other.ctx);
crate::egui_assert!(
self.layer_id == other.layer_id,
"It makes no sense to combine Responses from two different layers"
);
Self {
ctx: other.ctx,
layer_id: self.layer_id,
id: self.id,
rect: self.rect.union(other.rect),
sense: self.sense.union(other.sense),
enabled: self.enabled || other.enabled,
hovered: self.hovered || other.hovered,
clicked: [
self.clicked[0] || other.clicked[0],
self.clicked[1] || other.clicked[1],
self.clicked[2] || other.clicked[2],
self.clicked[3] || other.clicked[3],
self.clicked[4] || other.clicked[4],
],
double_clicked: [
self.double_clicked[0] || other.double_clicked[0],
self.double_clicked[1] || other.double_clicked[1],
self.double_clicked[2] || other.double_clicked[2],
self.double_clicked[3] || other.double_clicked[3],
self.double_clicked[4] || other.double_clicked[4],
],
triple_clicked: [
self.triple_clicked[0] || other.triple_clicked[0],
self.triple_clicked[1] || other.triple_clicked[1],
self.triple_clicked[2] || other.triple_clicked[2],
self.triple_clicked[3] || other.triple_clicked[3],
self.triple_clicked[4] || other.triple_clicked[4],
],
dragged: self.dragged || other.dragged,
drag_released: self.drag_released || other.drag_released,
is_pointer_button_down_on: self.is_pointer_button_down_on
|| other.is_pointer_button_down_on,
interact_pointer_pos: self.interact_pointer_pos.or(other.interact_pointer_pos),
changed: self.changed || other.changed,
}
}
}
/// To summarize the response from many widgets you can use this pattern:
///
/// ```
/// use egui::*;
/// fn draw_vec2(ui: &mut Ui, v: &mut Vec2) -> Response {
/// ui.add(DragValue::new(&mut v.x)) | ui.add(DragValue::new(&mut v.y))
/// }
/// ```
///
/// Now `draw_vec2(ui, foo).hovered` is true if either [`DragValue`](crate::DragValue) were hovered.
impl std::ops::BitOr for Response {
type Output = Self;
fn bitor(self, rhs: Self) -> Self {
self.union(rhs)
}
}
/// To summarize the response from many widgets you can use this pattern:
///
/// ```
/// # egui::__run_test_ui(|ui| {
/// # let (widget_a, widget_b, widget_c) = (egui::Label::new("a"), egui::Label::new("b"), egui::Label::new("c"));
/// let mut response = ui.add(widget_a);
/// response |= ui.add(widget_b);
/// response |= ui.add(widget_c);
/// if response.hovered() { ui.label("You hovered at least one of the widgets"); }
/// # });
/// ```
impl std::ops::BitOrAssign for Response {
fn bitor_assign(&mut self, rhs: Self) {
*self = self.union(rhs);
}
}
// ----------------------------------------------------------------------------
/// Returned when we wrap some ui-code and want to return both
/// the results of the inner function and the ui as a whole, e.g.:
///
/// ```
/// # egui::__run_test_ui(|ui| {
/// let inner_resp = ui.horizontal(|ui| {
/// ui.label("Blah blah");
/// 42
/// });
/// inner_resp.response.on_hover_text("You hovered the horizontal layout");
/// assert_eq!(inner_resp.inner, 42);
/// # });
/// ```
#[derive(Debug)]
pub struct InnerResponse<R> {
/// What the user closure returned.
pub inner: R,
/// The response of the area.
pub response: Response,
}
impl<R> InnerResponse<R> {
#[inline]
pub fn new(inner: R, response: Response) -> Self {
Self { inner, response }
}
}
+78
View File
@@ -0,0 +1,78 @@
/// What sort of interaction is a widget sensitive to?
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
// #[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct Sense {
/// buttons, sliders, windows, …
pub click: bool,
/// sliders, windows, scroll bars, scroll areas, …
pub drag: bool,
/// this widgets want focus.
/// Anything interactive + labels that can be focused
/// for the benefit of screen readers.
pub focusable: bool,
}
impl Sense {
/// Senses no clicks or drags. Only senses mouse hover.
pub fn hover() -> Self {
Self {
click: false,
drag: false,
focusable: false,
}
}
/// Senses no clicks or drags, but can be focused with the keyboard.
/// Used for labels that can be focused for the benefit of screen readers.
pub fn focusable_noninteractive() -> Self {
Self {
click: false,
drag: false,
focusable: true,
}
}
/// Sense clicks and hover, but not drags.
pub fn click() -> Self {
Self {
click: true,
drag: false,
focusable: true,
}
}
/// Sense drags and hover, but not clicks.
pub fn drag() -> Self {
Self {
click: false,
drag: true,
focusable: true,
}
}
/// Sense both clicks, drags and hover (e.g. a slider or window).
pub fn click_and_drag() -> Self {
Self {
click: true,
drag: true,
focusable: true,
}
}
/// The logical "or" of two [`Sense`]s.
#[must_use]
pub fn union(self, other: Self) -> Self {
Self {
click: self.click | other.click,
drag: self.drag | other.drag,
focusable: self.focusable | other.focusable,
}
}
/// Returns true if we sense either clicks or drags.
pub fn interactive(&self) -> bool {
self.click || self.drag
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+164
View File
@@ -0,0 +1,164 @@
//! Computing the same thing each frame can be expensive,
//! so often you want to save the result from the previous frame and reuse it.
//!
//! Enter [`FrameCache`]: it caches the results of a computation for one frame.
//! If it is still used next frame, it is not recomputed.
//! If it is not used next frame, it is evicted from the cache to save memory.
/// Something that does an expensive computation that we want to cache
/// to save us from recomputing it each frame.
pub trait ComputerMut<Key, Value>: 'static + Send + Sync {
fn compute(&mut self, key: Key) -> Value;
}
/// Caches the results of a computation for one frame.
/// If it is still used next frame, it is not recomputed.
/// If it is not used next frame, it is evicted from the cache to save memory.
pub struct FrameCache<Value, Computer> {
generation: u32,
computer: Computer,
cache: nohash_hasher::IntMap<u64, (u32, Value)>,
}
impl<Value, Computer> Default for FrameCache<Value, Computer>
where
Computer: Default,
{
fn default() -> Self {
Self::new(Computer::default())
}
}
impl<Value, Computer> FrameCache<Value, Computer> {
pub fn new(computer: Computer) -> Self {
Self {
generation: 0,
computer,
cache: Default::default(),
}
}
/// Must be called once per frame to clear the cache.
pub fn evice_cache(&mut self) {
let current_generation = self.generation;
self.cache.retain(|_key, cached| {
cached.0 == current_generation // only keep those that were used this frame
});
self.generation = self.generation.wrapping_add(1);
}
}
impl<Value, Computer> FrameCache<Value, Computer> {
/// Get from cache (if the same key was used last frame)
/// or recompute and store in the cache.
pub fn get<Key>(&mut self, key: Key) -> Value
where
Key: Copy + std::hash::Hash,
Value: Clone,
Computer: ComputerMut<Key, Value>,
{
let hash = crate::util::hash(key);
match self.cache.entry(hash) {
std::collections::hash_map::Entry::Occupied(entry) => {
let cached = entry.into_mut();
cached.0 = self.generation;
cached.1.clone()
}
std::collections::hash_map::Entry::Vacant(entry) => {
let value = self.computer.compute(key);
entry.insert((self.generation, value.clone()));
value
}
}
}
}
#[allow(clippy::len_without_is_empty)]
pub trait CacheTrait: 'static + Send + Sync {
/// Call once per frame to evict cache.
fn update(&mut self);
/// Number of values currently in the cache.
fn len(&self) -> usize;
fn as_any_mut(&mut self) -> &mut dyn std::any::Any;
}
impl<Value: 'static + Send + Sync, Computer: 'static + Send + Sync> CacheTrait
for FrameCache<Value, Computer>
{
fn update(&mut self) {
self.evice_cache();
}
fn len(&self) -> usize {
self.cache.len()
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
}
/// ```
/// use egui::util::cache::{CacheStorage, ComputerMut, FrameCache};
///
/// #[derive(Default)]
/// struct CharCounter {}
/// impl ComputerMut<&str, usize> for CharCounter {
/// fn compute(&mut self, s: &str) -> usize {
/// s.chars().count()
/// }
/// }
/// type CharCountCache<'a> = FrameCache<usize, CharCounter>;
///
/// # let mut cache_storage = CacheStorage::default();
/// let mut cache = cache_storage.cache::<CharCountCache<'_>>();
/// assert_eq!(cache.get("hello"), 5);
/// ```
#[derive(Default)]
pub struct CacheStorage {
caches: ahash::HashMap<std::any::TypeId, Box<dyn CacheTrait>>,
}
impl CacheStorage {
pub fn cache<FrameCache: CacheTrait + Default>(&mut self) -> &mut FrameCache {
self.caches
.entry(std::any::TypeId::of::<FrameCache>())
.or_insert_with(|| Box::new(FrameCache::default()))
.as_any_mut()
.downcast_mut::<FrameCache>()
.unwrap()
}
/// Total number of cached values
fn num_values(&self) -> usize {
self.caches.values().map(|cache| cache.len()).sum()
}
/// Call once per frame to evict cache.
pub fn update(&mut self) {
for cache in self.caches.values_mut() {
cache.update();
}
}
}
impl Clone for CacheStorage {
fn clone(&self) -> Self {
// We return an empty cache that can be filled in again.
Self::default()
}
}
impl std::fmt::Debug for CacheStorage {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"FrameCacheStorage[{} caches with {} elements]",
self.caches.len(),
self.num_values()
)
}
}
+41
View File
@@ -0,0 +1,41 @@
use epaint::util::hash;
const FIXED_CACHE_SIZE: usize = 1024; // must be small for web/WASM build (for unknown reason)
/// Very stupid/simple key-value cache. TODO(emilk): improve
#[derive(Clone)]
pub(crate) struct FixedCache<K, V>([Option<(K, V)>; FIXED_CACHE_SIZE]);
impl<K, V> Default for FixedCache<K, V>
where
K: Copy,
V: Copy,
{
fn default() -> Self {
Self([None; FIXED_CACHE_SIZE])
}
}
impl<K, V> std::fmt::Debug for FixedCache<K, V> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Cache")
}
}
impl<K, V> FixedCache<K, V>
where
K: std::hash::Hash + PartialEq,
{
pub fn get(&self, key: &K) -> Option<&V> {
let bucket = (hash(key) % (FIXED_CACHE_SIZE as u64)) as usize;
match &self.0[bucket] {
Some((k, v)) if k == key => Some(v),
_ => None,
}
}
pub fn set(&mut self, key: K, value: V) {
let bucket = (hash(&key) % (FIXED_CACHE_SIZE as u64)) as usize;
self.0[bucket] = Some((key, value));
}
}
+229
View File
@@ -0,0 +1,229 @@
use std::collections::VecDeque;
/// This struct tracks recent values of some time series.
///
/// It can be used as a smoothing filter for e.g. latency, fps etc,
/// or to show a log or graph of recent events.
///
/// It has a minimum and maximum length, as well as a maximum storage time.
/// * The minimum length is to ensure you have enough data for an estimate.
/// * The maximum length is to make sure the history doesn't take up too much space.
/// * The maximum age is to make sure the estimate isn't outdated.
///
/// Time difference between values can be zero, but never negative.
///
/// This can be used for things like smoothed averages (for e.g. FPS)
/// or for smoothed velocity (e.g. mouse pointer speed).
/// All times are in seconds.
#[derive(Clone, Debug)]
pub struct History<T> {
/// In elements, i.e. of `values.len()`.
/// The length is initially zero, but once past `min_len` will not shrink below it.
min_len: usize,
/// In elements, i.e. of `values.len()`.
max_len: usize,
/// In seconds.
max_age: f32,
/// Total number of elements seen ever
total_count: u64,
/// (time, value) pairs, oldest front, newest back.
/// Time difference between values can be zero, but never negative.
values: VecDeque<(f64, T)>,
}
impl<T> History<T>
where
T: Copy,
{
/// Example:
/// ```
/// # use egui::util::History;
/// # fn now() -> f64 { 0.0 }
/// // Drop events that are older than one second,
/// // as long we keep at least two events. Never keep more than a hundred events.
/// let mut history = History::new(2..100, 1.0);
/// assert_eq!(history.average(), None);
/// history.add(now(), 40.0_f32);
/// history.add(now(), 44.0_f32);
/// assert_eq!(history.average(), Some(42.0));
/// ```
pub fn new(length_range: std::ops::Range<usize>, max_age: f32) -> Self {
Self {
min_len: length_range.start,
max_len: length_range.end,
max_age,
total_count: 0,
values: Default::default(),
}
}
#[inline]
pub fn max_len(&self) -> usize {
self.max_len
}
#[inline]
pub fn max_age(&self) -> f32 {
self.max_age
}
#[inline]
pub fn is_empty(&self) -> bool {
self.values.is_empty()
}
/// Current number of values kept in history
#[inline]
pub fn len(&self) -> usize {
self.values.len()
}
/// Total number of values seen.
/// Includes those that have been discarded due to `max_len` or `max_age`.
#[inline]
pub fn total_count(&self) -> u64 {
self.total_count
}
pub fn latest(&self) -> Option<T> {
self.values.back().map(|(_, value)| *value)
}
pub fn latest_mut(&mut self) -> Option<&mut T> {
self.values.back_mut().map(|(_, value)| value)
}
/// Amount of time contained from start to end in this [`History`].
pub fn duration(&self) -> f32 {
if let (Some(front), Some(back)) = (self.values.front(), self.values.back()) {
(back.0 - front.0) as f32
} else {
0.0
}
}
/// `(time, value)` pairs
/// Time difference between values can be zero, but never negative.
// TODO(emilk): impl IntoIter
pub fn iter(&'_ self) -> impl ExactSizeIterator<Item = (f64, T)> + '_ {
self.values.iter().map(|(time, value)| (*time, *value))
}
pub fn values(&'_ self) -> impl ExactSizeIterator<Item = T> + '_ {
self.values.iter().map(|(_time, value)| *value)
}
#[inline]
pub fn clear(&mut self) {
self.values.clear();
}
/// Values must be added with a monotonically increasing time, or at least not decreasing.
pub fn add(&mut self, now: f64, value: T) {
if let Some((last_time, _)) = self.values.back() {
crate::egui_assert!(now >= *last_time, "Time shouldn't move backwards");
}
self.total_count += 1;
self.values.push_back((now, value));
self.flush(now);
}
/// Mean time difference between values in this [`History`].
pub fn mean_time_interval(&self) -> Option<f32> {
if let (Some(first), Some(last)) = (self.values.front(), self.values.back()) {
let n = self.len();
if n >= 2 {
Some((last.0 - first.0) as f32 / ((n - 1) as f32))
} else {
None
}
} else {
None
}
}
// Mean number of events per second.
pub fn rate(&self) -> Option<f32> {
self.mean_time_interval().map(|time| 1.0 / time)
}
/// Remove samples that are too old.
pub fn flush(&mut self, now: f64) {
while self.values.len() > self.max_len {
self.values.pop_front();
}
while self.values.len() > self.min_len {
if let Some((front_time, _)) = self.values.front() {
if *front_time < now - (self.max_age as f64) {
self.values.pop_front();
} else {
break;
}
} else {
break;
}
}
}
}
impl<T> History<T>
where
T: Copy,
T: std::iter::Sum,
T: std::ops::Div<f32, Output = T>,
{
#[inline]
pub fn sum(&self) -> T {
self.values().sum()
}
pub fn average(&self) -> Option<T> {
let num = self.len();
if num > 0 {
Some(self.sum() / (num as f32))
} else {
None
}
}
}
impl<T> History<T>
where
T: Copy,
T: std::iter::Sum,
T: std::ops::Div<f32, Output = T>,
T: std::ops::Mul<f32, Output = T>,
{
/// Average times rate.
/// If you are keeping track of individual sizes of things (e.g. bytes),
/// this will estimate the bandwidth (bytes per second).
pub fn bandwidth(&self) -> Option<T> {
Some(self.average()? * self.rate()?)
}
}
impl<T, Vel> History<T>
where
T: Copy,
T: std::ops::Sub<Output = Vel>,
Vel: std::ops::Div<f32, Output = Vel>,
{
/// Calculate a smooth velocity (per second) over the entire time span.
/// Calculated as the last value minus the first value over the elapsed time between them.
pub fn velocity(&self) -> Option<Vel> {
if let (Some(first), Some(last)) = (self.values.front(), self.values.back()) {
let dt = (last.0 - first.0) as f32;
if dt > 0.0 {
Some((last.1 - first.1) / dt)
} else {
None
}
} else {
None
}
}
}
+720
View File
@@ -0,0 +1,720 @@
// TODO(emilk): it is possible we can simplify `Element` further by
// assuming everything is possibly serializable, and by supplying serialize/deserialize functions for them.
// For non-serializable types, these simply return `None`.
// This will also allow users to pick their own serialization format per type.
use std::any::Any;
use std::sync::Arc;
// -----------------------------------------------------------------------------------------------
/// Like [`std::any::TypeId`], but can be serialized and deserialized.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
#[cfg_attr(feature = "persistence", derive(serde::Deserialize, serde::Serialize))]
pub struct TypeId(u64);
impl TypeId {
#[inline]
pub fn of<T: Any + 'static>() -> Self {
std::any::TypeId::of::<T>().into()
}
#[inline(always)]
pub(crate) fn value(&self) -> u64 {
self.0
}
}
impl From<std::any::TypeId> for TypeId {
#[inline]
fn from(id: std::any::TypeId) -> Self {
Self(epaint::util::hash(id))
}
}
// -----------------------------------------------------------------------------------------------
#[cfg(feature = "persistence")]
pub trait SerializableAny:
'static + Any + Clone + serde::Serialize + for<'a> serde::Deserialize<'a> + Send + Sync
{
}
#[cfg(feature = "persistence")]
impl<T> SerializableAny for T where
T: 'static + Any + Clone + serde::Serialize + for<'a> serde::Deserialize<'a> + Send + Sync
{
}
#[cfg(not(feature = "persistence"))]
pub trait SerializableAny: 'static + Any + Clone + for<'a> Send + Sync {}
#[cfg(not(feature = "persistence"))]
impl<T> SerializableAny for T where T: 'static + Any + Clone + for<'a> Send + Sync {}
// -----------------------------------------------------------------------------------------------
#[cfg(feature = "persistence")]
#[cfg_attr(feature = "persistence", derive(serde::Deserialize, serde::Serialize))]
struct SerializedElement {
type_id: TypeId,
ron: Arc<str>,
}
#[cfg(feature = "persistence")]
type Serializer = fn(&Box<dyn Any + 'static + Send + Sync>) -> Option<String>;
enum Element {
/// A value, maybe serializable.
Value {
/// The actual value.
value: Box<dyn Any + 'static + Send + Sync>,
/// How to clone the value.
clone_fn: fn(&Box<dyn Any + 'static + Send + Sync>) -> Box<dyn Any + 'static + Send + Sync>,
/// How to serialize the value.
/// None if non-serializable type.
#[cfg(feature = "persistence")]
serialize_fn: Option<Serializer>,
},
/// A serialized value
Serialized {
/// The type of value we are storing.
type_id: TypeId,
/// The ron data we can deserialize.
ron: Arc<str>,
},
}
impl Clone for Element {
fn clone(&self) -> Self {
match &self {
Self::Value {
value,
clone_fn,
#[cfg(feature = "persistence")]
serialize_fn,
} => Self::Value {
value: clone_fn(value),
clone_fn: *clone_fn,
#[cfg(feature = "persistence")]
serialize_fn: *serialize_fn,
},
Self::Serialized { type_id, ron } => Self::Serialized {
type_id: *type_id,
ron: ron.clone(),
},
}
}
}
impl std::fmt::Debug for Element {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self {
Self::Value { value, .. } => f
.debug_struct("MaybeSerializable::Value")
.field("type_id", &value.type_id())
.finish_non_exhaustive(),
Self::Serialized { type_id, ron } => f
.debug_struct("MaybeSerializable::Serialized")
.field("type_id", &type_id)
.field("ron", &ron)
.finish(),
}
}
}
impl Element {
/// Create a value that won't be persisted.
#[inline]
pub(crate) fn new_temp<T: 'static + Any + Clone + Send + Sync>(t: T) -> Self {
Self::Value {
value: Box::new(t),
clone_fn: |x| {
let x = x.downcast_ref::<T>().unwrap(); // This unwrap will never panic, because we always construct this type using this `new` function and because we return &mut reference only with this type `T`, so type cannot change.
Box::new(x.clone())
},
#[cfg(feature = "persistence")]
serialize_fn: None,
}
}
/// Create a value that will be persisted.
#[inline]
pub(crate) fn new_persisted<T: SerializableAny>(t: T) -> Self {
Self::Value {
value: Box::new(t),
clone_fn: |x| {
let x = x.downcast_ref::<T>().unwrap(); // This unwrap will never panic, because we always construct this type using this `new` function and because we return &mut reference only with this type `T`, so type cannot change.
Box::new(x.clone())
},
#[cfg(feature = "persistence")]
serialize_fn: Some(|x| {
let x = x.downcast_ref::<T>().unwrap(); // This will never panic too, for same reason.
ron::to_string(x).ok()
}),
}
}
/// The type of the stored value.
#[inline]
pub(crate) fn type_id(&self) -> TypeId {
match self {
Self::Value { value, .. } => (**value).type_id().into(),
Self::Serialized { type_id, .. } => *type_id,
}
}
#[inline]
pub(crate) fn get_mut_temp<T: 'static>(&mut self) -> Option<&mut T> {
match self {
Self::Value { value, .. } => value.downcast_mut(),
Self::Serialized { .. } => None,
}
}
#[inline]
pub(crate) fn get_temp_mut_or_insert_with<T: 'static + Any + Clone + Send + Sync>(
&mut self,
insert_with: impl FnOnce() -> T,
) -> &mut T {
match self {
Self::Value { value, .. } => {
if !value.is::<T>() {
*self = Self::new_temp(insert_with());
}
}
Self::Serialized { .. } => {
*self = Self::new_temp(insert_with());
}
}
match self {
Self::Value { value, .. } => value.downcast_mut().unwrap(), // This unwrap will never panic because we already converted object to required type
Self::Serialized { .. } => unreachable!(),
}
}
#[inline]
pub(crate) fn get_persisted_mut_or_insert_with<T: SerializableAny>(
&mut self,
insert_with: impl FnOnce() -> T,
) -> &mut T {
match self {
Self::Value { value, .. } => {
if !value.is::<T>() {
*self = Self::new_persisted(insert_with());
}
}
#[cfg(feature = "persistence")]
Self::Serialized { ron, .. } => {
*self = Self::new_persisted(from_ron_str::<T>(ron).unwrap_or_else(insert_with));
}
#[cfg(not(feature = "persistence"))]
Self::Serialized { .. } => {
*self = Self::new_persisted(insert_with());
}
}
match self {
Self::Value { value, .. } => value.downcast_mut().unwrap(), // This unwrap will never panic because we already converted object to required type
Self::Serialized { .. } => unreachable!(),
}
}
pub(crate) fn get_mut_persisted<T: SerializableAny>(&mut self) -> Option<&mut T> {
match self {
Self::Value { value, .. } => value.downcast_mut(),
#[cfg(feature = "persistence")]
Self::Serialized { ron, .. } => {
*self = Self::new_persisted(from_ron_str::<T>(ron)?);
match self {
Self::Value { value, .. } => value.downcast_mut(),
Self::Serialized { .. } => unreachable!(),
}
}
#[cfg(not(feature = "persistence"))]
Self::Serialized { .. } => None,
}
}
#[cfg(feature = "persistence")]
fn to_serialize(&self) -> Option<SerializedElement> {
match self {
Self::Value {
value,
serialize_fn,
..
} => {
if let Some(serialize_fn) = serialize_fn {
let ron = serialize_fn(value)?;
Some(SerializedElement {
type_id: (**value).type_id().into(),
ron: ron.into(),
})
} else {
None
}
}
Self::Serialized { type_id, ron } => Some(SerializedElement {
type_id: *type_id,
ron: ron.clone(),
}),
}
}
}
#[cfg(feature = "persistence")]
fn from_ron_str<T: serde::de::DeserializeOwned>(ron: &str) -> Option<T> {
match ron::from_str::<T>(ron) {
Ok(value) => Some(value),
Err(_err) => {
#[cfg(feature = "tracing")]
tracing::warn!(
"egui: Failed to deserialize {} from memory: {}, ron error: {:?}",
std::any::type_name::<T>(),
_err,
ron
);
None
}
}
}
// -----------------------------------------------------------------------------------------------
use crate::Id;
// TODO(emilk): make IdTypeMap generic over the key (`Id`), and make a library of IdTypeMap.
/// Stores values identified by an [`Id`] AND a the [`std::any::TypeId`] of the value.
///
/// In other words, it maps `(Id, TypeId)` to any value you want.
///
/// Values are cloned when read, so keep them small and light.
/// If you want to store something bigger, wrap them in `Arc<Mutex<…>>`.
///
/// Values can either be "persisted" (serializable) or "temporary" (cleared when egui is shut down).
///
/// You can store state using the key [`Id::null`]. The state will then only be identified by its type.
///
/// ```
/// # use egui::{Id, util::IdTypeMap};
/// let a = Id::new("a");
/// let b = Id::new("b");
/// let mut map: IdTypeMap = Default::default();
///
/// // `a` associated with an f64 and an i32
/// map.insert_persisted(a, 3.14);
/// map.insert_temp(a, 42);
///
/// // `b` associated with an f64 and a `&'static str`
/// map.insert_persisted(b, 13.37);
/// map.insert_temp(b, "Hello World".to_owned());
///
/// // we can retrieve all four values:
/// assert_eq!(map.get_temp::<f64>(a), Some(3.14));
/// assert_eq!(map.get_temp::<i32>(a), Some(42));
/// assert_eq!(map.get_temp::<f64>(b), Some(13.37));
/// assert_eq!(map.get_temp::<String>(b), Some("Hello World".to_owned()));
///
/// // we can retrieve them like so also:
/// assert_eq!(map.get_persisted::<f64>(a), Some(3.14));
/// assert_eq!(map.get_persisted::<i32>(a), Some(42));
/// assert_eq!(map.get_persisted::<f64>(b), Some(13.37));
/// assert_eq!(map.get_temp::<String>(b), Some("Hello World".to_owned()));
/// ```
#[derive(Clone, Debug, Default)]
// We store use `id XOR typeid` as a key, so we don't need to hash again!
pub struct IdTypeMap(nohash_hasher::IntMap<u64, Element>);
impl IdTypeMap {
/// Insert a value that will not be persisted.
#[inline]
pub fn insert_temp<T: 'static + Any + Clone + Send + Sync>(&mut self, id: Id, value: T) {
let hash = hash(TypeId::of::<T>(), id);
self.0.insert(hash, Element::new_temp(value));
}
/// Insert a value that will be persisted next time you start the app.
#[inline]
pub fn insert_persisted<T: SerializableAny>(&mut self, id: Id, value: T) {
let hash = hash(TypeId::of::<T>(), id);
self.0.insert(hash, Element::new_persisted(value));
}
/// Read a value without trying to deserialize a persisted value.
///
/// The call clones the value (if found), so make sure it is cheap to clone!
#[inline]
pub fn get_temp<T: 'static + Clone>(&mut self, id: Id) -> Option<T> {
let hash = hash(TypeId::of::<T>(), id);
self.0
.get_mut(&hash)
.and_then(|x| x.get_mut_temp())
.cloned()
}
/// Read a value, optionally deserializing it if available.
///
/// The call clones the value (if found), so make sure it is cheap to clone!
#[inline]
pub fn get_persisted<T: SerializableAny>(&mut self, id: Id) -> Option<T> {
let hash = hash(TypeId::of::<T>(), id);
self.0
.get_mut(&hash)
.and_then(|x| x.get_mut_persisted())
.cloned()
}
#[inline]
pub fn get_temp_mut_or<T: 'static + Any + Clone + Send + Sync>(
&mut self,
id: Id,
or_insert: T,
) -> &mut T {
self.get_temp_mut_or_insert_with(id, || or_insert)
}
#[inline]
pub fn get_persisted_mut_or<T: SerializableAny>(&mut self, id: Id, or_insert: T) -> &mut T {
self.get_persisted_mut_or_insert_with(id, || or_insert)
}
#[inline]
pub fn get_temp_mut_or_default<T: 'static + Any + Clone + Send + Sync + Default>(
&mut self,
id: Id,
) -> &mut T {
self.get_temp_mut_or_insert_with(id, Default::default)
}
#[inline]
pub fn get_persisted_mut_or_default<T: SerializableAny + Default>(&mut self, id: Id) -> &mut T {
self.get_persisted_mut_or_insert_with(id, Default::default)
}
pub fn get_temp_mut_or_insert_with<T: 'static + Any + Clone + Send + Sync>(
&mut self,
id: Id,
insert_with: impl FnOnce() -> T,
) -> &mut T {
let hash = hash(TypeId::of::<T>(), id);
use std::collections::hash_map::Entry;
match self.0.entry(hash) {
Entry::Vacant(vacant) => vacant
.insert(Element::new_temp(insert_with()))
.get_mut_temp()
.unwrap(), // this unwrap will never panic, because we insert correct type right now
Entry::Occupied(occupied) => {
occupied.into_mut().get_temp_mut_or_insert_with(insert_with)
}
}
}
pub fn get_persisted_mut_or_insert_with<T: SerializableAny>(
&mut self,
id: Id,
insert_with: impl FnOnce() -> T,
) -> &mut T {
let hash = hash(TypeId::of::<T>(), id);
use std::collections::hash_map::Entry;
match self.0.entry(hash) {
Entry::Vacant(vacant) => vacant
.insert(Element::new_persisted(insert_with()))
.get_mut_persisted()
.unwrap(), // this unwrap will never panic, because we insert correct type right now
Entry::Occupied(occupied) => occupied
.into_mut()
.get_persisted_mut_or_insert_with(insert_with),
}
}
/// Remove the state of this type an id.
#[inline]
pub fn remove<T: 'static>(&mut self, id: Id) {
let hash = hash(TypeId::of::<T>(), id);
self.0.remove(&hash);
}
/// Note all state of the given type.
pub fn remove_by_type<T: 'static>(&mut self) {
let key = TypeId::of::<T>();
self.0.retain(|_, e| {
let e: &Element = e;
e.type_id() != key
});
}
#[inline]
pub fn clear(&mut self) {
self.0.clear();
}
#[inline]
pub fn is_empty(&mut self) -> bool {
self.0.is_empty()
}
#[inline]
pub fn len(&mut self) -> usize {
self.0.len()
}
/// Count how many values are stored but not yet deserialized.
#[inline]
pub fn count_serialized(&mut self) -> usize {
self.0
.values()
.filter(|e| matches!(e, Element::Serialized { .. }))
.count()
}
/// Count the number of values are stored with the given type.
pub fn count<T: 'static>(&mut self) -> usize {
let key = TypeId::of::<T>();
self.0
.iter()
.filter(|(_, e)| {
let e: &Element = e;
e.type_id() == key
})
.count()
}
}
#[inline(always)]
fn hash(type_id: TypeId, id: Id) -> u64 {
type_id.value() ^ id.value()
}
// ----------------------------------------------------------------------------
/// How [`IdTypeMap`] is persisted.
#[cfg(feature = "persistence")]
#[cfg_attr(feature = "persistence", derive(serde::Deserialize, serde::Serialize))]
struct PersistedMap(Vec<(u64, SerializedElement)>);
#[cfg(feature = "persistence")]
impl PersistedMap {
fn from_map(map: &IdTypeMap) -> Self {
// filter out the elements which cannot be serialized:
Self(
map.0
.iter()
.filter_map(|(&hash, element)| Some((hash, element.to_serialize()?)))
.collect(),
)
}
fn into_map(self) -> IdTypeMap {
IdTypeMap(
self.0
.into_iter()
.map(|(hash, SerializedElement { type_id, ron })| {
(hash, Element::Serialized { type_id, ron })
})
.collect(),
)
}
}
#[cfg(feature = "persistence")]
impl serde::Serialize for IdTypeMap {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
PersistedMap::from_map(self).serialize(serializer)
}
}
#[cfg(feature = "persistence")]
impl<'de> serde::Deserialize<'de> for IdTypeMap {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
<PersistedMap>::deserialize(deserializer).map(PersistedMap::into_map)
}
}
// ----------------------------------------------------------------------------
#[test]
fn test_two_id_two_type() {
let a = Id::new("a");
let b = Id::new("b");
let mut map: IdTypeMap = Default::default();
map.insert_persisted(a, 13.37);
map.insert_temp(b, 42);
assert_eq!(map.get_persisted::<f64>(a), Some(13.37));
assert_eq!(map.get_persisted::<i32>(b), Some(42));
assert_eq!(map.get_temp::<f64>(a), Some(13.37));
assert_eq!(map.get_temp::<i32>(b), Some(42));
}
#[test]
fn test_two_id_x_two_types() {
#![allow(clippy::approx_constant)]
let a = Id::new("a");
let b = Id::new("b");
let mut map: IdTypeMap = Default::default();
// `a` associated with an f64 and an i32
map.insert_persisted(a, 3.14);
map.insert_temp(a, 42);
// `b` associated with an f64 and a `&'static str`
map.insert_persisted(b, 13.37);
map.insert_temp(b, "Hello World".to_owned());
// we can retrieve all four values:
assert_eq!(map.get_temp::<f64>(a), Some(3.14));
assert_eq!(map.get_temp::<i32>(a), Some(42));
assert_eq!(map.get_temp::<f64>(b), Some(13.37));
assert_eq!(map.get_temp::<String>(b), Some("Hello World".to_owned()));
// we can retrieve them like so also:
assert_eq!(map.get_persisted::<f64>(a), Some(3.14));
assert_eq!(map.get_persisted::<i32>(a), Some(42));
assert_eq!(map.get_persisted::<f64>(b), Some(13.37));
assert_eq!(map.get_temp::<String>(b), Some("Hello World".to_owned()));
}
#[test]
fn test_one_id_two_types() {
let id = Id::new("a");
let mut map: IdTypeMap = Default::default();
map.insert_persisted(id, 13.37);
map.insert_temp(id, 42);
assert_eq!(map.get_temp::<f64>(id), Some(13.37));
assert_eq!(map.get_persisted::<f64>(id), Some(13.37));
assert_eq!(map.get_temp::<i32>(id), Some(42));
// ------------
// Test removal:
// We can remove:
map.remove::<i32>(id);
assert_eq!(map.get_temp::<i32>(id), None);
// Other type is still there, even though it is the same if:
assert_eq!(map.get_temp::<f64>(id), Some(13.37));
assert_eq!(map.get_persisted::<f64>(id), Some(13.37));
// But we can still remove the last:
map.remove::<f64>(id);
assert_eq!(map.get_temp::<f64>(id), None);
assert_eq!(map.get_persisted::<f64>(id), None);
}
#[test]
fn test_mix() {
#[cfg_attr(feature = "persistence", derive(serde::Deserialize, serde::Serialize))]
#[derive(Clone, Debug, PartialEq)]
struct Foo(i32);
#[derive(Clone, Debug, PartialEq)]
struct Bar(f32);
let id = Id::new("a");
let mut map: IdTypeMap = Default::default();
map.insert_persisted(id, Foo(555));
map.insert_temp(id, Bar(1.0));
assert_eq!(map.get_temp::<Foo>(id), Some(Foo(555)));
assert_eq!(map.get_persisted::<Foo>(id), Some(Foo(555)));
assert_eq!(map.get_temp::<Bar>(id), Some(Bar(1.0)));
// ------------
// Test removal:
// We can remove:
map.remove::<Bar>(id);
assert_eq!(map.get_temp::<Bar>(id), None);
// Other type is still there, even though it is the same if:
assert_eq!(map.get_temp::<Foo>(id), Some(Foo(555)));
assert_eq!(map.get_persisted::<Foo>(id), Some(Foo(555)));
// But we can still remove the last:
map.remove::<Foo>(id);
assert_eq!(map.get_temp::<Foo>(id), None);
assert_eq!(map.get_persisted::<Foo>(id), None);
}
#[cfg(feature = "persistence")]
#[test]
fn test_mix_serialize() {
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
struct Serializable(i32);
#[derive(Clone, Debug, PartialEq)]
struct NonSerializable(f32);
let id = Id::new("a");
let mut map: IdTypeMap = Default::default();
map.insert_persisted(id, Serializable(555));
map.insert_temp(id, NonSerializable(1.0));
assert_eq!(map.get_temp::<Serializable>(id), Some(Serializable(555)));
assert_eq!(
map.get_persisted::<Serializable>(id),
Some(Serializable(555))
);
assert_eq!(
map.get_temp::<NonSerializable>(id),
Some(NonSerializable(1.0))
);
// -----------
let serialized = ron::to_string(&map).unwrap();
// ------------
// Test removal:
// We can remove:
map.remove::<NonSerializable>(id);
assert_eq!(map.get_temp::<NonSerializable>(id), None);
// Other type is still there, even though it is the same if:
assert_eq!(map.get_temp::<Serializable>(id), Some(Serializable(555)));
assert_eq!(
map.get_persisted::<Serializable>(id),
Some(Serializable(555))
);
// But we can still remove the last:
map.remove::<Serializable>(id);
assert_eq!(map.get_temp::<Serializable>(id), None);
assert_eq!(map.get_persisted::<Serializable>(id), None);
// --------------------
// Test deserialization:
let mut map: IdTypeMap = ron::from_str(&serialized).unwrap();
assert_eq!(map.get_temp::<Serializable>(id), None);
assert_eq!(
map.get_persisted::<Serializable>(id),
Some(Serializable(555))
);
assert_eq!(map.get_temp::<Serializable>(id), Some(Serializable(555)));
}
+12
View File
@@ -0,0 +1,12 @@
//! Miscellaneous tools used by the rest of egui.
pub mod cache;
pub(crate) mod fixed_cache;
mod history;
pub mod id_type_map;
pub mod undoer;
pub use history::History;
pub use id_type_map::IdTypeMap;
pub use epaint::util::{hash, hash_with};
+172
View File
@@ -0,0 +1,172 @@
use std::collections::VecDeque;
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct Settings {
/// Maximum number of undos.
/// If your state is resource intensive, you should keep this low.
///
/// Default: `100`
pub max_undos: usize,
/// When that state hasn't changed for this many seconds,
/// create a new undo point (if one is needed).
///
/// Default value: `1.0` seconds.
pub stable_time: f32,
/// If the state is changing so often that we never get to `stable_time`,
/// then still create a save point every `auto_save_interval` seconds,
/// so we have something to undo to.
///
/// Default value: `30` seconds.
pub auto_save_interval: f32,
}
impl Default for Settings {
fn default() -> Self {
Self {
max_undos: 100,
stable_time: 1.0,
auto_save_interval: 30.0,
}
}
}
/// Automatic undo system.
///
/// Every frame you feed it the most recent state.
/// The [`Undoer`] compares it with the latest undo point
/// and if there is a change it may create a new undo point.
///
/// [`Undoer`] follows two simple rules:
///
/// 1) If the state has changed since the latest undo point, but has
/// remained stable for `stable_time` seconds, an new undo point is created.
/// 2) If the state does not stabilize within `auto_save_interval` seconds, an undo point is created.
///
/// Rule 1) will make sure an undo point is not created until you _stop_ dragging that slider.
/// Rule 2) will make sure that you will get some undo points even if you are constantly changing the state.
#[derive(Clone, Default)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct Undoer<State> {
settings: Settings,
/// New undoes are added to the back.
/// Two adjacent undo points are never equal.
/// The latest undo point may (often) be the current state.
undos: VecDeque<State>,
#[cfg_attr(feature = "serde", serde(skip))]
flux: Option<Flux<State>>,
}
impl<State> std::fmt::Debug for Undoer<State> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let Self { undos, .. } = self;
f.debug_struct("Undoer")
.field("undo count", &undos.len())
.finish()
}
}
/// Represents how the current state is changing
#[derive(Clone)]
struct Flux<State> {
start_time: f64,
latest_change_time: f64,
latest_state: State,
}
impl<State> Undoer<State>
where
State: Clone + PartialEq,
{
/// Do we have an undo point different from the given state?
pub fn has_undo(&self, current_state: &State) -> bool {
match self.undos.len() {
0 => false,
1 => self.undos.back() != Some(current_state),
_ => true,
}
}
/// Return true if the state is currently changing
pub fn is_in_flux(&self) -> bool {
self.flux.is_some()
}
pub fn undo(&mut self, current_state: &State) -> Option<&State> {
if self.has_undo(current_state) {
self.flux = None;
if self.undos.back() == Some(current_state) {
self.undos.pop_back();
}
// Note: we keep the undo point intact.
self.undos.back()
} else {
None
}
}
/// Add an undo point if, and only if, there has been a change since the latest undo point.
///
/// * `time`: current time in seconds.
pub fn add_undo(&mut self, current_state: &State) {
if self.undos.back() != Some(current_state) {
self.undos.push_back(current_state.clone());
}
while self.undos.len() > self.settings.max_undos {
self.undos.pop_front();
}
self.flux = None;
}
/// Call this as often as you want (e.g. every frame)
/// and [`Undoer`] will determine if a new undo point should be created.
///
/// * `current_time`: current time in seconds.
pub fn feed_state(&mut self, current_time: f64, current_state: &State) {
match self.undos.back() {
None => {
// First time feed_state is called.
// always create an undo point:
self.add_undo(current_state);
}
Some(latest_undo) => {
if latest_undo == current_state {
self.flux = None;
} else {
match self.flux.as_mut() {
None => {
self.flux = Some(Flux {
start_time: current_time,
latest_change_time: current_time,
latest_state: current_state.clone(),
});
}
Some(flux) => {
if &flux.latest_state == current_state {
let time_since_latest_change =
(current_time - flux.latest_change_time) as f32;
if time_since_latest_change >= self.settings.stable_time {
self.add_undo(current_state);
}
} else {
let time_since_flux_start = (current_time - flux.start_time) as f32;
if time_since_flux_start >= self.settings.auto_save_interval {
self.add_undo(current_state);
} else {
flux.latest_change_time = current_time;
flux.latest_state = current_state.clone();
}
}
}
}
}
}
}
}
}
+725
View File
@@ -0,0 +1,725 @@
use std::borrow::Cow;
use std::sync::Arc;
use crate::{
style::WidgetVisuals, text::LayoutJob, Align, Color32, FontFamily, FontSelection, Galley, Pos2,
Style, TextStyle, Ui, Visuals,
};
/// Text and optional style choices for it.
///
/// The style choices (font, color) are applied to the entire text.
/// For more detailed control, use [`crate::text::LayoutJob`] instead.
///
/// A [`RichText`] can be used in most widgets and helper functions, e.g. [`Ui::label`] and [`Ui::button`].
///
/// ### Example
/// ```
/// use egui::{RichText, Color32};
///
/// RichText::new("Plain");
/// RichText::new("colored").color(Color32::RED);
/// RichText::new("Large and underlined").size(20.0).underline();
/// ```
#[derive(Clone, Default, PartialEq)]
pub struct RichText {
text: String,
size: Option<f32>,
family: Option<FontFamily>,
text_style: Option<TextStyle>,
background_color: Color32,
text_color: Option<Color32>,
code: bool,
strong: bool,
weak: bool,
strikethrough: bool,
underline: bool,
italics: bool,
raised: bool,
}
impl From<&str> for RichText {
#[inline]
fn from(text: &str) -> Self {
RichText::new(text)
}
}
impl From<&String> for RichText {
#[inline]
fn from(text: &String) -> Self {
RichText::new(text)
}
}
impl From<&mut String> for RichText {
#[inline]
fn from(text: &mut String) -> Self {
RichText::new(text.clone())
}
}
impl From<String> for RichText {
#[inline]
fn from(text: String) -> Self {
RichText::new(text)
}
}
impl From<Cow<'_, str>> for RichText {
#[inline]
fn from(text: Cow<'_, str>) -> Self {
Self::new(text)
}
}
impl RichText {
#[inline]
pub fn new(text: impl Into<String>) -> Self {
Self {
text: text.into(),
..Default::default()
}
}
#[inline]
pub fn is_empty(&self) -> bool {
self.text.is_empty()
}
#[inline]
pub fn text(&self) -> &str {
&self.text
}
/// Select the font size (in points).
/// This overrides the value from [`Self::text_style`].
#[inline]
pub fn size(mut self, size: f32) -> Self {
self.size = Some(size);
self
}
/// Select the font family.
///
/// This overrides the value from [`Self::text_style`].
///
/// Only the families available in [`crate::FontDefinitions::families`] may be used.
#[inline]
pub fn family(mut self, family: FontFamily) -> Self {
self.family = Some(family);
self
}
/// Select the font and size.
/// This overrides the value from [`Self::text_style`].
#[inline]
pub fn font(mut self, font_id: crate::FontId) -> Self {
let crate::FontId { size, family } = font_id;
self.size = Some(size);
self.family = Some(family);
self
}
/// Override the [`TextStyle`].
#[inline]
pub fn text_style(mut self, text_style: TextStyle) -> Self {
self.text_style = Some(text_style);
self
}
/// Set the [`TextStyle`] unless it has already been set
#[inline]
pub fn fallback_text_style(mut self, text_style: TextStyle) -> Self {
self.text_style.get_or_insert(text_style);
self
}
/// Use [`TextStyle::Heading`].
#[inline]
pub fn heading(self) -> Self {
self.text_style(TextStyle::Heading)
}
/// Use [`TextStyle::Monospace`].
#[inline]
pub fn monospace(self) -> Self {
self.text_style(TextStyle::Monospace)
}
/// Monospace label with different background color.
#[inline]
pub fn code(mut self) -> Self {
self.code = true;
self.text_style(TextStyle::Monospace)
}
/// Extra strong text (stronger color).
#[inline]
pub fn strong(mut self) -> Self {
self.strong = true;
self
}
/// Extra weak text (fainter color).
#[inline]
pub fn weak(mut self) -> Self {
self.weak = true;
self
}
/// Draw a line under the text.
///
/// If you want to control the line color, use [`LayoutJob`] instead.
#[inline]
pub fn underline(mut self) -> Self {
self.underline = true;
self
}
/// Draw a line through the text, crossing it out.
///
/// If you want to control the strikethrough line color, use [`LayoutJob`] instead.
#[inline]
pub fn strikethrough(mut self) -> Self {
self.strikethrough = true;
self
}
/// Tilt the characters to the right.
#[inline]
pub fn italics(mut self) -> Self {
self.italics = true;
self
}
/// Smaller text.
#[inline]
pub fn small(self) -> Self {
self.text_style(TextStyle::Small)
}
/// For e.g. exponents.
#[inline]
pub fn small_raised(self) -> Self {
self.text_style(TextStyle::Small).raised()
}
/// Align text to top. Only applicable together with [`Self::small()`].
#[inline]
pub fn raised(mut self) -> Self {
self.raised = true;
self
}
/// Fill-color behind the text.
#[inline]
pub fn background_color(mut self, background_color: impl Into<Color32>) -> Self {
self.background_color = background_color.into();
self
}
/// Override text color.
#[inline]
pub fn color(mut self, color: impl Into<Color32>) -> Self {
self.text_color = Some(color.into());
self
}
/// Read the font height of the selected text style.
pub fn font_height(&self, fonts: &epaint::Fonts, style: &Style) -> f32 {
let mut font_id = self.text_style.as_ref().map_or_else(
|| FontSelection::Default.resolve(style),
|text_style| text_style.resolve(style),
);
if let Some(size) = self.size {
font_id.size = size;
}
if let Some(family) = &self.family {
font_id.family = family.clone();
}
fonts.row_height(&font_id)
}
fn into_text_job(
self,
style: &Style,
fallback_font: FontSelection,
default_valign: Align,
) -> WidgetTextJob {
let text_color = self.get_text_color(&style.visuals);
let Self {
text,
size,
family,
text_style,
background_color,
text_color: _, // already used by `get_text_color`
code,
strong: _, // already used by `get_text_color`
weak: _, // already used by `get_text_color`
strikethrough,
underline,
italics,
raised,
} = self;
let job_has_color = text_color.is_some();
let line_color = text_color.unwrap_or_else(|| style.visuals.text_color());
let text_color = text_color.unwrap_or(crate::Color32::TEMPORARY_COLOR);
let font_id = {
let mut font_id = text_style
.or_else(|| style.override_text_style.clone())
.map_or_else(
|| fallback_font.resolve(style),
|text_style| text_style.resolve(style),
);
if let Some(size) = size {
font_id.size = size;
}
if let Some(family) = family {
font_id.family = family;
}
font_id
};
let mut background_color = background_color;
if code {
background_color = style.visuals.code_bg_color;
}
let underline = if underline {
crate::Stroke::new(1.0, line_color)
} else {
crate::Stroke::none()
};
let strikethrough = if strikethrough {
crate::Stroke::new(1.0, line_color)
} else {
crate::Stroke::none()
};
let valign = if raised {
crate::Align::TOP
} else {
default_valign
};
let text_format = crate::text::TextFormat {
font_id,
color: text_color,
background: background_color,
italics,
underline,
strikethrough,
valign,
};
let job = LayoutJob::single_section(text, text_format);
WidgetTextJob { job, job_has_color }
}
fn get_text_color(&self, visuals: &Visuals) -> Option<Color32> {
if let Some(text_color) = self.text_color {
Some(text_color)
} else if self.strong {
Some(visuals.strong_text_color())
} else if self.weak {
Some(visuals.weak_text_color())
} else {
visuals.override_text_color
}
}
}
// ----------------------------------------------------------------------------
/// This is how you specify text for a widget.
///
/// A lot of widgets use `impl Into<WidgetText>` as an argument,
/// allowing you to pass in [`String`], [`RichText`], [`LayoutJob`], and more.
///
/// Often a [`WidgetText`] is just a simple [`String`],
/// but it can be a [`RichText`] (text with color, style, etc),
/// a [`LayoutJob`] (for when you want full control of how the text looks)
/// or text that has already been layed out in a [`Galley`].
#[derive(Clone)]
pub enum WidgetText {
RichText(RichText),
/// Use this [`LayoutJob`] when laying out the text.
///
/// Only [`LayoutJob::text`] and [`LayoutJob::sections`] are guaranteed to be respected.
///
/// [`TextWrapping::max_width`](epaint::text::TextWrapping::max_width), [`LayoutJob::halign`], [`LayoutJob::justify`]
/// and [`LayoutJob::first_row_min_height`] will likely be determined by the [`crate::Layout`]
/// of the [`Ui`] the widget is placed in.
/// If you want all parts of the [`LayoutJob`] respected, then convert it to a
/// [`Galley`] and use [`Self::Galley`] instead.
LayoutJob(LayoutJob),
/// Use exactly this galley when painting the text.
Galley(Arc<Galley>),
}
impl Default for WidgetText {
fn default() -> Self {
Self::RichText(RichText::default())
}
}
impl WidgetText {
#[inline]
pub fn is_empty(&self) -> bool {
match self {
Self::RichText(text) => text.is_empty(),
Self::LayoutJob(job) => job.is_empty(),
Self::Galley(galley) => galley.is_empty(),
}
}
#[inline]
pub fn text(&self) -> &str {
match self {
Self::RichText(text) => text.text(),
Self::LayoutJob(job) => &job.text,
Self::Galley(galley) => galley.text(),
}
}
/// Override the [`TextStyle`] if, and only if, this is a [`RichText`].
///
/// Prefer using [`RichText`] directly!
#[inline]
pub fn text_style(self, text_style: TextStyle) -> Self {
match self {
Self::RichText(text) => Self::RichText(text.text_style(text_style)),
Self::LayoutJob(_) | Self::Galley(_) => self,
}
}
/// Set the [`TextStyle`] unless it has already been set
///
/// Prefer using [`RichText`] directly!
#[inline]
pub fn fallback_text_style(self, text_style: TextStyle) -> Self {
match self {
Self::RichText(text) => Self::RichText(text.fallback_text_style(text_style)),
Self::LayoutJob(_) | Self::Galley(_) => self,
}
}
/// Override text color if, and only if, this is a [`RichText`].
///
/// Prefer using [`RichText`] directly!
#[inline]
pub fn color(self, color: impl Into<Color32>) -> Self {
match self {
Self::RichText(text) => Self::RichText(text.color(color)),
Self::LayoutJob(_) | Self::Galley(_) => self,
}
}
/// Prefer using [`RichText`] directly!
pub fn heading(self) -> Self {
match self {
Self::RichText(text) => Self::RichText(text.heading()),
Self::LayoutJob(_) | Self::Galley(_) => self,
}
}
/// Prefer using [`RichText`] directly!
pub fn monospace(self) -> Self {
match self {
Self::RichText(text) => Self::RichText(text.monospace()),
Self::LayoutJob(_) | Self::Galley(_) => self,
}
}
/// Prefer using [`RichText`] directly!
pub fn code(self) -> Self {
match self {
Self::RichText(text) => Self::RichText(text.code()),
Self::LayoutJob(_) | Self::Galley(_) => self,
}
}
/// Prefer using [`RichText`] directly!
pub fn strong(self) -> Self {
match self {
Self::RichText(text) => Self::RichText(text.strong()),
Self::LayoutJob(_) | Self::Galley(_) => self,
}
}
/// Prefer using [`RichText`] directly!
pub fn weak(self) -> Self {
match self {
Self::RichText(text) => Self::RichText(text.weak()),
Self::LayoutJob(_) | Self::Galley(_) => self,
}
}
/// Prefer using [`RichText`] directly!
pub fn underline(self) -> Self {
match self {
Self::RichText(text) => Self::RichText(text.underline()),
Self::LayoutJob(_) | Self::Galley(_) => self,
}
}
/// Prefer using [`RichText`] directly!
pub fn strikethrough(self) -> Self {
match self {
Self::RichText(text) => Self::RichText(text.strikethrough()),
Self::LayoutJob(_) | Self::Galley(_) => self,
}
}
/// Prefer using [`RichText`] directly!
pub fn italics(self) -> Self {
match self {
Self::RichText(text) => Self::RichText(text.italics()),
Self::LayoutJob(_) | Self::Galley(_) => self,
}
}
/// Prefer using [`RichText`] directly!
pub fn small(self) -> Self {
match self {
Self::RichText(text) => Self::RichText(text.small()),
Self::LayoutJob(_) | Self::Galley(_) => self,
}
}
/// Prefer using [`RichText`] directly!
pub fn small_raised(self) -> Self {
match self {
Self::RichText(text) => Self::RichText(text.small_raised()),
Self::LayoutJob(_) | Self::Galley(_) => self,
}
}
/// Prefer using [`RichText`] directly!
pub fn raised(self) -> Self {
match self {
Self::RichText(text) => Self::RichText(text.raised()),
Self::LayoutJob(_) | Self::Galley(_) => self,
}
}
/// Prefer using [`RichText`] directly!
pub fn background_color(self, background_color: impl Into<Color32>) -> Self {
match self {
Self::RichText(text) => Self::RichText(text.background_color(background_color)),
Self::LayoutJob(_) | Self::Galley(_) => self,
}
}
pub(crate) fn font_height(&self, fonts: &epaint::Fonts, style: &Style) -> f32 {
match self {
Self::RichText(text) => text.font_height(fonts, style),
Self::LayoutJob(job) => job.font_height(fonts),
Self::Galley(galley) => {
if let Some(row) = galley.rows.first() {
row.height()
} else {
galley.size().y
}
}
}
}
pub fn into_text_job(
self,
style: &Style,
fallback_font: FontSelection,
default_valign: Align,
) -> WidgetTextJob {
match self {
Self::RichText(text) => text.into_text_job(style, fallback_font, default_valign),
Self::LayoutJob(job) => WidgetTextJob {
job,
job_has_color: true,
},
Self::Galley(galley) => {
let job: LayoutJob = (*galley.job).clone();
WidgetTextJob {
job,
job_has_color: true,
}
}
}
}
/// Layout with wrap mode based on the containing [`Ui`].
///
/// wrap: override for [`Ui::wrap_text`].
pub fn into_galley(
self,
ui: &Ui,
wrap: Option<bool>,
available_width: f32,
fallback_font: impl Into<FontSelection>,
) -> WidgetTextGalley {
let wrap = wrap.unwrap_or_else(|| ui.wrap_text());
let wrap_width = if wrap { available_width } else { f32::INFINITY };
match self {
Self::RichText(text) => {
let valign = ui.layout().vertical_align();
let mut text_job = text.into_text_job(ui.style(), fallback_font.into(), valign);
text_job.job.wrap.max_width = wrap_width;
WidgetTextGalley {
galley: ui.fonts().layout_job(text_job.job),
galley_has_color: text_job.job_has_color,
}
}
Self::LayoutJob(mut job) => {
job.wrap.max_width = wrap_width;
WidgetTextGalley {
galley: ui.fonts().layout_job(job),
galley_has_color: true,
}
}
Self::Galley(galley) => WidgetTextGalley {
galley,
galley_has_color: true,
},
}
}
}
impl From<&str> for WidgetText {
#[inline]
fn from(text: &str) -> Self {
Self::RichText(RichText::new(text))
}
}
impl From<&String> for WidgetText {
#[inline]
fn from(text: &String) -> Self {
Self::RichText(RichText::new(text))
}
}
impl From<String> for WidgetText {
#[inline]
fn from(text: String) -> Self {
Self::RichText(RichText::new(text))
}
}
impl From<Cow<'_, str>> for WidgetText {
#[inline]
fn from(text: Cow<'_, str>) -> Self {
Self::RichText(RichText::new(text))
}
}
impl From<RichText> for WidgetText {
#[inline]
fn from(rich_text: RichText) -> Self {
Self::RichText(rich_text)
}
}
impl From<LayoutJob> for WidgetText {
#[inline]
fn from(layout_job: LayoutJob) -> Self {
Self::LayoutJob(layout_job)
}
}
impl From<Arc<Galley>> for WidgetText {
#[inline]
fn from(galley: Arc<Galley>) -> Self {
Self::Galley(galley)
}
}
// ----------------------------------------------------------------------------
#[derive(Clone, PartialEq)]
pub struct WidgetTextJob {
pub job: LayoutJob,
pub job_has_color: bool,
}
impl WidgetTextJob {
pub fn into_galley(self, fonts: &crate::text::Fonts) -> WidgetTextGalley {
let Self { job, job_has_color } = self;
let galley = fonts.layout_job(job);
WidgetTextGalley {
galley,
galley_has_color: job_has_color,
}
}
}
// ----------------------------------------------------------------------------
/// Text that has been layed out and ready to be painted.
#[derive(Clone, PartialEq)]
pub struct WidgetTextGalley {
pub galley: Arc<Galley>,
pub galley_has_color: bool,
}
impl WidgetTextGalley {
/// Size of the layed out text.
#[inline]
pub fn size(&self) -> crate::Vec2 {
self.galley.size()
}
/// Size of the layed out text.
#[inline]
pub fn text(&self) -> &str {
self.galley.text()
}
#[inline]
pub fn galley(&self) -> &Arc<Galley> {
&self.galley
}
/// Use the colors in the original [`WidgetText`] if any,
/// else fall back to the one specified by the [`WidgetVisuals`].
pub fn paint_with_visuals(
self,
painter: &crate::Painter,
text_pos: Pos2,
visuals: &WidgetVisuals,
) {
self.paint_with_fallback_color(painter, text_pos, visuals.text_color());
}
/// Use the colors in the original [`WidgetText`] if any,
/// else fall back to the given color.
pub fn paint_with_fallback_color(
self,
painter: &crate::Painter,
text_pos: Pos2,
text_color: Color32,
) {
if self.galley_has_color {
painter.galley(text_pos, self.galley);
} else {
painter.galley_with_color(text_pos, self.galley, text_color);
}
}
/// Paint with this specific color.
pub fn paint_with_color_override(
self,
painter: &crate::Painter,
text_pos: Pos2,
text_color: Color32,
) {
painter.galley_with_color(text_pos, self.galley, text_color);
}
}
+527
View File
@@ -0,0 +1,527 @@
use crate::*;
/// Clickable button with text.
///
/// See also [`Ui::button`].
///
/// ```
/// # egui::__run_test_ui(|ui| {
/// # fn do_stuff() {}
///
/// if ui.add(egui::Button::new("Click me")).clicked() {
/// do_stuff();
/// }
///
/// // A greyed-out and non-interactive button:
/// if ui.add_enabled(false, egui::Button::new("Can't click this")).clicked() {
/// unreachable!();
/// }
/// # });
/// ```
#[must_use = "You should put this widget in an ui with `ui.add(widget);`"]
pub struct Button {
text: WidgetText,
wrap: Option<bool>,
/// None means default for interact
fill: Option<Color32>,
stroke: Option<Stroke>,
sense: Sense,
small: bool,
frame: Option<bool>,
min_size: Vec2,
image: Option<widgets::Image>,
}
impl Button {
pub fn new(text: impl Into<WidgetText>) -> Self {
Self {
text: text.into(),
wrap: None,
fill: None,
stroke: None,
sense: Sense::click(),
small: false,
frame: None,
min_size: Vec2::ZERO,
image: None,
}
}
/// Creates a button with an image to the left of the text. The size of the image as displayed is defined by the size Vec2 provided.
#[allow(clippy::needless_pass_by_value)]
pub fn image_and_text(
texture_id: TextureId,
size: impl Into<Vec2>,
text: impl Into<WidgetText>,
) -> Self {
Self {
text: text.into(),
fill: None,
stroke: None,
sense: Sense::click(),
small: false,
frame: None,
wrap: None,
min_size: Vec2::ZERO,
image: Some(widgets::Image::new(texture_id, size)),
}
}
/// If `true`, the text will wrap to stay within the max width of the [`Ui`].
///
/// By default [`Self::wrap`] will be true in vertical layouts
/// and horizontal layouts with wrapping,
/// and false on non-wrapping horizontal layouts.
///
/// Note that any `\n` in the text will always produce a new line.
#[inline]
pub fn wrap(mut self, wrap: bool) -> Self {
self.wrap = Some(wrap);
self
}
/// Override background fill color. Note that this will override any on-hover effects.
/// Calling this will also turn on the frame.
pub fn fill(mut self, fill: impl Into<Color32>) -> Self {
self.fill = Some(fill.into());
self.frame = Some(true);
self
}
/// Override button stroke. Note that this will override any on-hover effects.
/// Calling this will also turn on the frame.
pub fn stroke(mut self, stroke: impl Into<Stroke>) -> Self {
self.stroke = Some(stroke.into());
self.frame = Some(true);
self
}
/// Make this a small button, suitable for embedding into text.
pub fn small(mut self) -> Self {
self.text = self.text.text_style(TextStyle::Body);
self.small = true;
self
}
/// Turn off the frame
pub fn frame(mut self, frame: bool) -> Self {
self.frame = Some(frame);
self
}
/// By default, buttons senses clicks.
/// Change this to a drag-button with `Sense::drag()`.
pub fn sense(mut self, sense: Sense) -> Self {
self.sense = sense;
self
}
pub(crate) fn min_size(mut self, min_size: Vec2) -> Self {
self.min_size = min_size;
self
}
}
impl Widget for Button {
fn ui(self, ui: &mut Ui) -> Response {
let Button {
text,
wrap,
fill,
stroke,
sense,
small,
frame,
min_size,
image,
} = self;
let frame = frame.unwrap_or_else(|| ui.visuals().button_frame);
let mut button_padding = ui.spacing().button_padding;
if small {
button_padding.y = 0.0;
}
let total_extra = button_padding + button_padding;
let wrap_width = ui.available_width() - total_extra.x;
let text = text.into_galley(ui, wrap, wrap_width, TextStyle::Button);
let mut desired_size = text.size() + 2.0 * button_padding;
if !small {
desired_size.y = desired_size.y.at_least(ui.spacing().interact_size.y);
}
desired_size = desired_size.at_least(min_size);
if let Some(image) = image {
desired_size.x += image.size().x + ui.spacing().icon_spacing;
desired_size.y = desired_size.y.max(image.size().y + 2.0 * button_padding.y);
}
let (rect, response) = ui.allocate_at_least(desired_size, sense);
response.widget_info(|| WidgetInfo::labeled(WidgetType::Button, text.text()));
if ui.is_rect_visible(rect) {
let visuals = ui.style().interact(&response);
let text_pos = if let Some(image) = image {
let icon_spacing = ui.spacing().icon_spacing;
pos2(
rect.min.x + button_padding.x + image.size().x + icon_spacing,
rect.center().y - 0.5 * text.size().y,
)
} else {
ui.layout()
.align_size_within_rect(text.size(), rect.shrink2(button_padding))
.min
};
if frame {
let fill = fill.unwrap_or(visuals.bg_fill);
let stroke = stroke.unwrap_or(visuals.bg_stroke);
ui.painter().rect(
rect.expand(visuals.expansion),
visuals.rounding,
fill,
stroke,
);
}
text.paint_with_visuals(ui.painter(), text_pos, visuals);
}
if let Some(image) = image {
let image_rect = Rect::from_min_size(
pos2(rect.min.x, rect.center().y - 0.5 - (image.size().y / 2.0)),
image.size(),
);
image.paint_at(ui, image_rect);
}
response
}
}
// ----------------------------------------------------------------------------
// TODO(emilk): allow checkbox without a text label
/// Boolean on/off control with text label.
///
/// Usually you'd use [`Ui::checkbox`] instead.
///
/// ```
/// # egui::__run_test_ui(|ui| {
/// # let mut my_bool = true;
/// // These are equivalent:
/// ui.checkbox(&mut my_bool, "Checked");
/// ui.add(egui::Checkbox::new(&mut my_bool, "Checked"));
/// # });
/// ```
#[must_use = "You should put this widget in an ui with `ui.add(widget);`"]
pub struct Checkbox<'a> {
checked: &'a mut bool,
text: WidgetText,
}
impl<'a> Checkbox<'a> {
pub fn new(checked: &'a mut bool, text: impl Into<WidgetText>) -> Self {
Checkbox {
checked,
text: text.into(),
}
}
}
impl<'a> Widget for Checkbox<'a> {
fn ui(self, ui: &mut Ui) -> Response {
let Checkbox { checked, text } = self;
let spacing = &ui.spacing();
let icon_width = spacing.icon_width;
let icon_spacing = spacing.icon_spacing;
let (text, mut desired_size) = if text.is_empty() {
(None, vec2(icon_width, 0.0))
} else {
let total_extra = vec2(icon_width + icon_spacing, 0.0);
let wrap_width = ui.available_width() - total_extra.x;
let text = text.into_galley(ui, None, wrap_width, TextStyle::Button);
let mut desired_size = total_extra + text.size();
desired_size = desired_size.at_least(spacing.interact_size);
(Some(text), desired_size)
};
desired_size = desired_size.at_least(Vec2::splat(spacing.interact_size.y));
desired_size.y = desired_size.y.max(icon_width);
let (rect, mut response) = ui.allocate_exact_size(desired_size, Sense::click());
if response.clicked() {
*checked = !*checked;
response.mark_changed();
}
response.widget_info(|| {
WidgetInfo::selected(
WidgetType::Checkbox,
*checked,
text.as_ref().map_or("", |x| x.text()),
)
});
if ui.is_rect_visible(rect) {
// let visuals = ui.style().interact_selectable(&response, *checked); // too colorful
let visuals = ui.style().interact(&response);
let (small_icon_rect, big_icon_rect) = ui.spacing().icon_rectangles(rect);
ui.painter().add(epaint::RectShape {
rect: big_icon_rect.expand(visuals.expansion),
rounding: visuals.rounding,
fill: visuals.bg_fill,
stroke: visuals.bg_stroke,
});
if *checked {
// Check mark:
ui.painter().add(Shape::line(
vec![
pos2(small_icon_rect.left(), small_icon_rect.center().y),
pos2(small_icon_rect.center().x, small_icon_rect.bottom()),
pos2(small_icon_rect.right(), small_icon_rect.top()),
],
visuals.fg_stroke,
));
}
if let Some(text) = text {
let text_pos = pos2(
rect.min.x + icon_width + icon_spacing,
rect.center().y - 0.5 * text.size().y,
);
text.paint_with_visuals(ui.painter(), text_pos, visuals);
}
}
response
}
}
// ----------------------------------------------------------------------------
/// One out of several alternatives, either selected or not.
///
/// Usually you'd use [`Ui::radio_value`] or [`Ui::radio`] instead.
///
/// ```
/// # egui::__run_test_ui(|ui| {
/// #[derive(PartialEq)]
/// enum Enum { First, Second, Third }
/// let mut my_enum = Enum::First;
///
/// ui.radio_value(&mut my_enum, Enum::First, "First");
///
/// // is equivalent to:
///
/// if ui.add(egui::RadioButton::new(my_enum == Enum::First, "First")).clicked() {
/// my_enum = Enum::First
/// }
/// # });
/// ```
#[must_use = "You should put this widget in an ui with `ui.add(widget);`"]
pub struct RadioButton {
checked: bool,
text: WidgetText,
}
impl RadioButton {
pub fn new(checked: bool, text: impl Into<WidgetText>) -> Self {
Self {
checked,
text: text.into(),
}
}
}
impl Widget for RadioButton {
fn ui(self, ui: &mut Ui) -> Response {
let RadioButton { checked, text } = self;
let spacing = &ui.spacing();
let icon_width = spacing.icon_width;
let icon_spacing = spacing.icon_spacing;
let (text, mut desired_size) = if text.is_empty() {
(None, vec2(icon_width, 0.0))
} else {
let total_extra = vec2(icon_width + icon_spacing, 0.0);
let wrap_width = ui.available_width() - total_extra.x;
let text = text.into_galley(ui, None, wrap_width, TextStyle::Button);
let mut desired_size = total_extra + text.size();
desired_size = desired_size.at_least(spacing.interact_size);
(Some(text), desired_size)
};
desired_size = desired_size.at_least(Vec2::splat(spacing.interact_size.y));
desired_size.y = desired_size.y.max(icon_width);
let (rect, response) = ui.allocate_exact_size(desired_size, Sense::click());
response.widget_info(|| {
WidgetInfo::selected(
WidgetType::RadioButton,
checked,
text.as_ref().map_or("", |x| x.text()),
)
});
if ui.is_rect_visible(rect) {
// let visuals = ui.style().interact_selectable(&response, checked); // too colorful
let visuals = ui.style().interact(&response);
let (small_icon_rect, big_icon_rect) = ui.spacing().icon_rectangles(rect);
let painter = ui.painter();
painter.add(epaint::CircleShape {
center: big_icon_rect.center(),
radius: big_icon_rect.width() / 2.0 + visuals.expansion,
fill: visuals.bg_fill,
stroke: visuals.bg_stroke,
});
if checked {
painter.add(epaint::CircleShape {
center: small_icon_rect.center(),
radius: small_icon_rect.width() / 3.0,
fill: visuals.fg_stroke.color, // Intentional to use stroke and not fill
// fill: ui.visuals().selection.stroke.color, // too much color
stroke: Default::default(),
});
}
if let Some(text) = text {
let text_pos = pos2(
rect.min.x + icon_width + icon_spacing,
rect.center().y - 0.5 * text.size().y,
);
text.paint_with_visuals(ui.painter(), text_pos, visuals);
}
}
response
}
}
// ----------------------------------------------------------------------------
/// A clickable image within a frame.
#[must_use = "You should put this widget in an ui with `ui.add(widget);`"]
#[derive(Clone, Debug)]
pub struct ImageButton {
image: widgets::Image,
sense: Sense,
frame: bool,
selected: bool,
}
impl ImageButton {
pub fn new(texture_id: impl Into<TextureId>, size: impl Into<Vec2>) -> Self {
Self {
image: widgets::Image::new(texture_id, size),
sense: Sense::click(),
frame: true,
selected: false,
}
}
/// Select UV range. Default is (0,0) in top-left, (1,1) bottom right.
pub fn uv(mut self, uv: impl Into<Rect>) -> Self {
self.image = self.image.uv(uv);
self
}
/// Multiply image color with this. Default is WHITE (no tint).
pub fn tint(mut self, tint: impl Into<Color32>) -> Self {
self.image = self.image.tint(tint);
self
}
/// If `true`, mark this button as "selected".
pub fn selected(mut self, selected: bool) -> Self {
self.selected = selected;
self
}
/// Turn off the frame
pub fn frame(mut self, frame: bool) -> Self {
self.frame = frame;
self
}
/// By default, buttons senses clicks.
/// Change this to a drag-button with `Sense::drag()`.
pub fn sense(mut self, sense: Sense) -> Self {
self.sense = sense;
self
}
}
impl Widget for ImageButton {
fn ui(self, ui: &mut Ui) -> Response {
let Self {
image,
sense,
frame,
selected,
} = self;
let padding = if frame {
// so we can see that it is a button:
Vec2::splat(ui.spacing().button_padding.x)
} else {
Vec2::ZERO
};
let padded_size = image.size() + 2.0 * padding;
let (rect, response) = ui.allocate_exact_size(padded_size, sense);
response.widget_info(|| WidgetInfo::new(WidgetType::ImageButton));
if ui.is_rect_visible(rect) {
let (expansion, rounding, fill, stroke) = if selected {
let selection = ui.visuals().selection;
(
Vec2::ZERO,
Rounding::none(),
selection.bg_fill,
selection.stroke,
)
} else if frame {
let visuals = ui.style().interact(&response);
let expansion = Vec2::splat(visuals.expansion);
(
expansion,
visuals.rounding,
visuals.bg_fill,
visuals.bg_stroke,
)
} else {
Default::default()
};
// Draw frame background (for transparent images):
ui.painter()
.rect_filled(rect.expand2(expansion), rounding, fill);
let image_rect = ui
.layout()
.align_size_within_rect(image.size(), rect.shrink2(padding));
// let image_rect = image_rect.expand2(expansion); // can make it blurry, so let's not
image.paint_at(ui, image_rect);
// Draw frame outline:
ui.painter()
.rect_stroke(rect.expand2(expansion), rounding, stroke);
}
response
}
}
+436
View File
@@ -0,0 +1,436 @@
//! Color picker widgets.
use crate::util::fixed_cache::FixedCache;
use crate::*;
use epaint::{color::*, *};
fn contrast_color(color: impl Into<Rgba>) -> Color32 {
if color.into().intensity() < 0.5 {
Color32::WHITE
} else {
Color32::BLACK
}
}
/// Number of vertices per dimension in the color sliders.
/// We need at least 6 for hues, and more for smooth 2D areas.
/// Should always be a multiple of 6 to hit the peak hues in HSV/HSL (every 60°).
const N: u32 = 6 * 6;
fn background_checkers(painter: &Painter, rect: Rect) {
let rect = rect.shrink(0.5); // Small hack to avoid the checkers from peeking through the sides
if !rect.is_positive() {
return;
}
let dark_color = Color32::from_gray(32);
let bright_color = Color32::from_gray(128);
let checker_size = Vec2::splat(rect.height() / 2.0);
let n = (rect.width() / checker_size.x).round() as u32;
let mut mesh = Mesh::default();
mesh.add_colored_rect(rect, dark_color);
let mut top = true;
for i in 0..n {
let x = lerp(rect.left()..=rect.right(), i as f32 / (n as f32));
let small_rect = if top {
Rect::from_min_size(pos2(x, rect.top()), checker_size)
} else {
Rect::from_min_size(pos2(x, rect.center().y), checker_size)
};
mesh.add_colored_rect(small_rect, bright_color);
top = !top;
}
painter.add(Shape::mesh(mesh));
}
/// Show a color with background checkers to demonstrate transparency (if any).
pub fn show_color(ui: &mut Ui, color: impl Into<Color32>, desired_size: Vec2) -> Response {
show_color32(ui, color.into(), desired_size)
}
fn show_color32(ui: &mut Ui, color: Color32, desired_size: Vec2) -> Response {
let (rect, response) = ui.allocate_at_least(desired_size, Sense::hover());
if ui.is_rect_visible(rect) {
show_color_at(ui.painter(), color, rect);
}
response
}
/// Show a color with background checkers to demonstrate transparency (if any).
pub fn show_color_at(painter: &Painter, color: Color32, rect: Rect) {
if color.is_opaque() {
painter.rect_filled(rect, 0.0, color);
} else {
// Transparent: how both the transparent and opaque versions of the color
background_checkers(painter, rect);
if color == Color32::TRANSPARENT {
// There is no opaque version, so just show the background checkers
} else {
let left = Rect::from_min_max(rect.left_top(), rect.center_bottom());
let right = Rect::from_min_max(rect.center_top(), rect.right_bottom());
painter.rect_filled(left, 0.0, color);
painter.rect_filled(right, 0.0, color.to_opaque());
}
}
}
fn color_button(ui: &mut Ui, color: Color32, open: bool) -> Response {
let size = ui.spacing().interact_size;
let (rect, response) = ui.allocate_exact_size(size, Sense::click());
response.widget_info(|| WidgetInfo::new(WidgetType::ColorButton));
if ui.is_rect_visible(rect) {
let visuals = if open {
&ui.visuals().widgets.open
} else {
ui.style().interact(&response)
};
let rect = rect.expand(visuals.expansion);
show_color_at(ui.painter(), color, rect);
let rounding = visuals.rounding.at_most(2.0);
ui.painter()
.rect_stroke(rect, rounding, (2.0, visuals.bg_fill)); // fill is intentional, because default style has no border
}
response
}
fn color_slider_1d(ui: &mut Ui, value: &mut f32, color_at: impl Fn(f32) -> Color32) -> Response {
#![allow(clippy::identity_op)]
let desired_size = vec2(ui.spacing().slider_width, ui.spacing().interact_size.y);
let (rect, response) = ui.allocate_at_least(desired_size, Sense::click_and_drag());
if let Some(mpos) = response.interact_pointer_pos() {
*value = remap_clamp(mpos.x, rect.left()..=rect.right(), 0.0..=1.0);
}
if ui.is_rect_visible(rect) {
let visuals = ui.style().interact(&response);
background_checkers(ui.painter(), rect); // for alpha:
{
// fill color:
let mut mesh = Mesh::default();
for i in 0..=N {
let t = i as f32 / (N as f32);
let color = color_at(t);
let x = lerp(rect.left()..=rect.right(), t);
mesh.colored_vertex(pos2(x, rect.top()), color);
mesh.colored_vertex(pos2(x, rect.bottom()), color);
if i < N {
mesh.add_triangle(2 * i + 0, 2 * i + 1, 2 * i + 2);
mesh.add_triangle(2 * i + 1, 2 * i + 2, 2 * i + 3);
}
}
ui.painter().add(Shape::mesh(mesh));
}
ui.painter().rect_stroke(rect, 0.0, visuals.bg_stroke); // outline
{
// Show where the slider is at:
let x = lerp(rect.left()..=rect.right(), *value);
let r = rect.height() / 4.0;
let picked_color = color_at(*value);
ui.painter().add(Shape::convex_polygon(
vec![
pos2(x, rect.center().y), // tip
pos2(x + r, rect.bottom()), // right bottom
pos2(x - r, rect.bottom()), // left bottom
],
picked_color,
Stroke::new(visuals.fg_stroke.width, contrast_color(picked_color)),
));
}
}
response
}
fn color_slider_2d(
ui: &mut Ui,
x_value: &mut f32,
y_value: &mut f32,
color_at: impl Fn(f32, f32) -> Color32,
) -> Response {
let desired_size = Vec2::splat(ui.spacing().slider_width);
let (rect, response) = ui.allocate_at_least(desired_size, Sense::click_and_drag());
if let Some(mpos) = response.interact_pointer_pos() {
*x_value = remap_clamp(mpos.x, rect.left()..=rect.right(), 0.0..=1.0);
*y_value = remap_clamp(mpos.y, rect.bottom()..=rect.top(), 0.0..=1.0);
}
if ui.is_rect_visible(rect) {
let visuals = ui.style().interact(&response);
let mut mesh = Mesh::default();
for xi in 0..=N {
for yi in 0..=N {
let xt = xi as f32 / (N as f32);
let yt = yi as f32 / (N as f32);
let color = color_at(xt, yt);
let x = lerp(rect.left()..=rect.right(), xt);
let y = lerp(rect.bottom()..=rect.top(), yt);
mesh.colored_vertex(pos2(x, y), color);
if xi < N && yi < N {
let x_offset = 1;
let y_offset = N + 1;
let tl = yi * y_offset + xi;
mesh.add_triangle(tl, tl + x_offset, tl + y_offset);
mesh.add_triangle(tl + x_offset, tl + y_offset, tl + y_offset + x_offset);
}
}
}
ui.painter().add(Shape::mesh(mesh)); // fill
ui.painter().rect_stroke(rect, 0.0, visuals.bg_stroke); // outline
// Show where the slider is at:
let x = lerp(rect.left()..=rect.right(), *x_value);
let y = lerp(rect.bottom()..=rect.top(), *y_value);
let picked_color = color_at(*x_value, *y_value);
ui.painter().add(epaint::CircleShape {
center: pos2(x, y),
radius: rect.width() / 12.0,
fill: picked_color,
stroke: Stroke::new(visuals.fg_stroke.width, contrast_color(picked_color)),
});
}
response
}
/// What options to show for alpha
#[derive(Clone, Copy, PartialEq)]
pub enum Alpha {
// Set alpha to 1.0, and show no option for it.
Opaque,
// Only show normal blend options for it.
OnlyBlend,
// Show both blend and additive options.
BlendOrAdditive,
}
fn color_text_ui(ui: &mut Ui, color: impl Into<Color32>, alpha: Alpha) {
let color = color.into();
ui.horizontal(|ui| {
let [r, g, b, a] = color.to_array();
if ui.button("📋").on_hover_text("Click to copy").clicked() {
if alpha == Alpha::Opaque {
ui.output().copied_text = format!("{}, {}, {}", r, g, b);
} else {
ui.output().copied_text = format!("{}, {}, {}, {}", r, g, b, a);
}
}
if alpha == Alpha::Opaque {
ui.label(format!("rgb({}, {}, {})", r, g, b))
.on_hover_text("Red Green Blue");
} else {
ui.label(format!("rgba({}, {}, {}, {})", r, g, b, a))
.on_hover_text("Red Green Blue with premultiplied Alpha");
}
});
}
fn color_picker_hsvag_2d(ui: &mut Ui, hsva: &mut HsvaGamma, alpha: Alpha) {
let current_color_size = vec2(ui.spacing().slider_width, ui.spacing().interact_size.y);
show_color(ui, *hsva, current_color_size).on_hover_text("Selected color");
color_text_ui(ui, *hsva, alpha);
if alpha == Alpha::BlendOrAdditive {
// We signal additive blending by storing a negative alpha (a bit ironic).
let a = &mut hsva.a;
let mut additive = *a < 0.0;
ui.horizontal(|ui| {
ui.label("Blending:");
ui.radio_value(&mut additive, false, "Normal");
ui.radio_value(&mut additive, true, "Additive");
if additive {
*a = -a.abs();
}
if !additive {
*a = a.abs();
}
});
}
let additive = hsva.a < 0.0;
let opaque = HsvaGamma { a: 1.0, ..*hsva };
if alpha == Alpha::Opaque {
hsva.a = 1.0;
} else {
let a = &mut hsva.a;
if alpha == Alpha::OnlyBlend {
if *a < 0.0 {
*a = 0.5; // was additive, but isn't allowed to be
}
color_slider_1d(ui, a, |a| HsvaGamma { a, ..opaque }.into()).on_hover_text("Alpha");
} else if !additive {
color_slider_1d(ui, a, |a| HsvaGamma { a, ..opaque }.into()).on_hover_text("Alpha");
}
}
let HsvaGamma { h, s, v, a: _ } = hsva;
color_slider_1d(ui, h, |h| {
HsvaGamma {
h,
s: 1.0,
v: 1.0,
a: 1.0,
}
.into()
})
.on_hover_text("Hue");
if false {
color_slider_1d(ui, s, |s| HsvaGamma { s, ..opaque }.into()).on_hover_text("Saturation");
}
if false {
color_slider_1d(ui, v, |v| HsvaGamma { v, ..opaque }.into()).on_hover_text("Value");
}
color_slider_2d(ui, v, s, |v, s| HsvaGamma { s, v, ..opaque }.into());
}
//// Shows a color picker where the user can change the given [`Hsva`] color.
///
/// Returns `true` on change.
pub fn color_picker_hsva_2d(ui: &mut Ui, hsva: &mut Hsva, alpha: Alpha) -> bool {
let mut hsvag = HsvaGamma::from(*hsva);
ui.vertical(|ui| {
color_picker_hsvag_2d(ui, &mut hsvag, alpha);
});
let new_hasva = Hsva::from(hsvag);
if *hsva == new_hasva {
false
} else {
*hsva = new_hasva;
true
}
}
/// Shows a color picker where the user can change the given [`Color32`] color.
///
/// Returns `true` on change.
pub fn color_picker_color32(ui: &mut Ui, srgba: &mut Color32, alpha: Alpha) -> bool {
let mut hsva = color_cache_get(ui.ctx(), *srgba);
let changed = color_picker_hsva_2d(ui, &mut hsva, alpha);
*srgba = Color32::from(hsva);
color_cache_set(ui.ctx(), *srgba, hsva);
changed
}
pub fn color_edit_button_hsva(ui: &mut Ui, hsva: &mut Hsva, alpha: Alpha) -> Response {
let popup_id = ui.auto_id_with("popup");
let open = ui.memory().is_popup_open(popup_id);
let mut button_response = color_button(ui, (*hsva).into(), open);
if ui.style().explanation_tooltips {
button_response = button_response.on_hover_text("Click to edit color");
}
if button_response.clicked() {
ui.memory().toggle_popup(popup_id);
}
// 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) {
let area_response = Area::new(popup_id)
.order(Order::Foreground)
.current_pos(button_response.rect.max)
.show(ui.ctx(), |ui| {
ui.spacing_mut().slider_width = 210.0;
Frame::popup(ui.style()).show(ui, |ui| {
if color_picker_hsva_2d(ui, hsva, alpha) {
button_response.mark_changed();
}
});
})
.response;
if !button_response.clicked()
&& (ui.input().key_pressed(Key::Escape) || area_response.clicked_elsewhere())
{
ui.memory().close_popup();
}
}
button_response
}
/// Shows a button with the given color.
/// If the user clicks the button, a full color picker is shown.
pub fn color_edit_button_srgba(ui: &mut Ui, srgba: &mut Color32, alpha: Alpha) -> Response {
let mut hsva = color_cache_get(ui.ctx(), *srgba);
let response = color_edit_button_hsva(ui, &mut hsva, alpha);
*srgba = Color32::from(hsva);
color_cache_set(ui.ctx(), *srgba, hsva);
response
}
/// Shows a button with the given color.
/// If the user clicks the button, a full color picker is shown.
/// The given color is in `sRGB` space.
pub fn color_edit_button_srgb(ui: &mut Ui, srgb: &mut [u8; 3]) -> Response {
let mut srgba = Color32::from_rgb(srgb[0], srgb[1], srgb[2]);
let response = color_edit_button_srgba(ui, &mut srgba, Alpha::Opaque);
srgb[0] = srgba[0];
srgb[1] = srgba[1];
srgb[2] = srgba[2];
response
}
/// Shows a button with the given color.
/// If the user clicks the button, a full color picker is shown.
pub fn color_edit_button_rgba(ui: &mut Ui, rgba: &mut Rgba, alpha: Alpha) -> Response {
let mut hsva = color_cache_get(ui.ctx(), *rgba);
let response = color_edit_button_hsva(ui, &mut hsva, alpha);
*rgba = Rgba::from(hsva);
color_cache_set(ui.ctx(), *rgba, hsva);
response
}
/// Shows a button with the given color.
/// If the user clicks the button, a full color picker is shown.
pub fn color_edit_button_rgb(ui: &mut Ui, rgb: &mut [f32; 3]) -> Response {
let mut rgba = Rgba::from_rgb(rgb[0], rgb[1], rgb[2]);
let response = color_edit_button_rgba(ui, &mut rgba, Alpha::Opaque);
rgb[0] = rgba[0];
rgb[1] = rgba[1];
rgb[2] = rgba[2];
response
}
// To ensure we keep hue slider when `srgba` is gray we store the full [`Hsva`] in a cache:
fn color_cache_get(ctx: &Context, rgba: impl Into<Rgba>) -> Hsva {
let rgba = rgba.into();
use_color_cache(ctx, |cc| cc.get(&rgba).cloned()).unwrap_or_else(|| Hsva::from(rgba))
}
// To ensure we keep hue slider when `srgba` is gray we store the full [`Hsva`] in a cache:
fn color_cache_set(ctx: &Context, rgba: impl Into<Rgba>, hsva: Hsva) {
let rgba = rgba.into();
use_color_cache(ctx, |cc| cc.set(rgba, hsva));
}
// 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 {
f(ctx.data().get_temp_mut_or_default(Id::null()))
}
+328
View File
@@ -0,0 +1,328 @@
#![allow(clippy::needless_pass_by_value)] // False positives with `impl ToString`
use std::ops::RangeInclusive;
use crate::*;
// ----------------------------------------------------------------------------
/// Same state for all [`DragValue`]s.
#[derive(Clone, Debug, Default)]
pub(crate) struct MonoState {
last_dragged_id: Option<Id>,
last_dragged_value: Option<f64>,
/// For temporary edit of a [`DragValue`] value.
/// Couples with the current focus id.
edit_string: Option<String>,
}
impl MonoState {
pub(crate) fn end_frame(&mut self, input: &InputState) {
if input.pointer.any_pressed() || input.pointer.any_released() {
self.last_dragged_id = None;
self.last_dragged_value = None;
}
}
}
// ----------------------------------------------------------------------------
type NumFormatter<'a> = Box<dyn 'a + Fn(f64, RangeInclusive<usize>) -> String>;
// ----------------------------------------------------------------------------
/// Combined into one function (rather than two) to make it easier
/// for the borrow checker.
type GetSetValue<'a> = Box<dyn 'a + FnMut(Option<f64>) -> f64>;
fn get(get_set_value: &mut GetSetValue<'_>) -> f64 {
(get_set_value)(None)
}
fn set(get_set_value: &mut GetSetValue<'_>, value: f64) {
(get_set_value)(Some(value));
}
/// A numeric value that you can change by dragging the number. More compact than a [`Slider`].
///
/// ```
/// # egui::__run_test_ui(|ui| {
/// # let mut my_f32: f32 = 0.0;
/// ui.add(egui::DragValue::new(&mut my_f32).speed(0.1));
/// # });
/// ```
#[must_use = "You should put this widget in an ui with `ui.add(widget);`"]
pub struct DragValue<'a> {
get_set_value: GetSetValue<'a>,
speed: f64,
prefix: String,
suffix: String,
clamp_range: RangeInclusive<f64>,
min_decimals: usize,
max_decimals: Option<usize>,
custom_formatter: Option<NumFormatter<'a>>,
}
impl<'a> DragValue<'a> {
pub fn new<Num: emath::Numeric>(value: &'a mut Num) -> Self {
let slf = Self::from_get_set(move |v: Option<f64>| {
if let Some(v) = v {
*value = Num::from_f64(v);
}
value.to_f64()
});
if Num::INTEGRAL {
slf.max_decimals(0)
.clamp_range(Num::MIN..=Num::MAX)
.speed(0.25)
} else {
slf
}
}
pub fn from_get_set(get_set_value: impl 'a + FnMut(Option<f64>) -> f64) -> Self {
Self {
get_set_value: Box::new(get_set_value),
speed: 1.0,
prefix: Default::default(),
suffix: Default::default(),
clamp_range: f64::NEG_INFINITY..=f64::INFINITY,
min_decimals: 0,
max_decimals: None,
custom_formatter: None,
}
}
/// How much the value changes when dragged one point (logical pixel).
pub fn speed(mut self, speed: impl Into<f64>) -> Self {
self.speed = speed.into();
self
}
/// Clamp incoming and outgoing values to this range.
pub fn clamp_range<Num: emath::Numeric>(mut self, clamp_range: RangeInclusive<Num>) -> Self {
self.clamp_range = clamp_range.start().to_f64()..=clamp_range.end().to_f64();
self
}
/// Show a prefix before the number, e.g. "x: "
pub fn prefix(mut self, prefix: impl ToString) -> Self {
self.prefix = prefix.to_string();
self
}
/// Add a suffix to the number, this can be e.g. a unit ("°" or " m")
pub fn suffix(mut self, suffix: impl ToString) -> Self {
self.suffix = suffix.to_string();
self
}
// TODO(emilk): we should also have a "min precision".
/// Set a minimum number of decimals to display.
/// Normally you don't need to pick a precision, as the slider will intelligently pick a precision for you.
/// Regardless of precision the slider will use "smart aim" to help the user select nice, round values.
pub fn min_decimals(mut self, min_decimals: usize) -> Self {
self.min_decimals = min_decimals;
self
}
// TODO(emilk): we should also have a "max precision".
/// Set a maximum number of decimals to display.
/// Values will also be rounded to this number of decimals.
/// Normally you don't need to pick a precision, as the slider will intelligently pick a precision for you.
/// Regardless of precision the slider will use "smart aim" to help the user select nice, round values.
pub fn max_decimals(mut self, max_decimals: usize) -> Self {
self.max_decimals = Some(max_decimals);
self
}
pub fn max_decimals_opt(mut self, max_decimals: Option<usize>) -> Self {
self.max_decimals = max_decimals;
self
}
/// Set an exact number of decimals to display.
/// Values will also be rounded to this number of decimals.
/// Normally you don't need to pick a precision, as the slider will intelligently pick a precision for you.
/// Regardless of precision the slider will use "smart aim" to help the user select nice, round values.
pub fn fixed_decimals(mut self, num_decimals: usize) -> Self {
self.min_decimals = num_decimals;
self.max_decimals = Some(num_decimals);
self
}
/// Set custom formatter defining how numbers are converted into text.
///
/// A custom formatter takes a `f64` for the numeric value and a `RangeInclusive<usize>` representing
/// the decimal range i.e. minimum and maximum number of decimal places shown.
///
/// ```
/// # egui::__run_test_ui(|ui| {
/// # let mut my_i64: i64 = 0;
/// ui.add(egui::DragValue::new(&mut my_i64).custom_formatter(|n, _| format!("{:X}", n as i64)));
/// # });
/// ```
pub fn custom_formatter(
mut self,
formatter: impl 'a + Fn(f64, RangeInclusive<usize>) -> String,
) -> Self {
self.custom_formatter = Some(Box::new(formatter));
self
}
}
impl<'a> Widget for DragValue<'a> {
fn ui(self, ui: &mut Ui) -> Response {
let Self {
mut get_set_value,
speed,
clamp_range,
prefix,
suffix,
min_decimals,
max_decimals,
custom_formatter,
} = self;
let shift = ui.input().modifiers.shift_only();
let is_slow_speed = shift && ui.memory().is_being_dragged(ui.next_auto_id());
let old_value = get(&mut get_set_value);
let value = clamp_to_range(old_value, clamp_range.clone());
if old_value != value {
set(&mut get_set_value, value);
}
let aim_rad = ui.input().aim_radius() as f64;
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 max_decimals = max_decimals.unwrap_or(auto_decimals + 2);
let auto_decimals = auto_decimals.clamp(min_decimals, max_decimals);
let value_text = match custom_formatter {
Some(custom_formatter) => custom_formatter(value, auto_decimals..=max_decimals),
None => {
if value == 0.0 {
"0".to_owned()
} else {
emath::format_with_decimals_in_range(value, auto_decimals..=max_decimals)
}
}
};
let kb_edit_id = ui.next_auto_id();
let is_kb_editing = ui.memory().has_focus(kb_edit_id);
let mut response = if is_kb_editing {
let button_width = ui.spacing().interact_size.x;
let mut value_text = ui
.memory()
.drag_value
.edit_string
.take()
.unwrap_or(value_text);
let response = ui.add(
TextEdit::singleline(&mut value_text)
.id(kb_edit_id)
.desired_width(button_width)
.font(TextStyle::Monospace),
);
if let Ok(parsed_value) = value_text.parse() {
let parsed_value = clamp_to_range(parsed_value, clamp_range);
set(&mut get_set_value, parsed_value);
}
if ui.input().key_pressed(Key::Enter) {
ui.memory().surrender_focus(kb_edit_id);
ui.memory().drag_value.edit_string = None;
} else {
ui.memory().drag_value.edit_string = Some(value_text);
}
response
} else {
let button = Button::new(
RichText::new(format!("{}{}{}", prefix, value_text, suffix)).monospace(),
)
.wrap(false)
.sense(Sense::click_and_drag())
.min_size(ui.spacing().interact_size); // TODO(emilk): find some more generic solution to `min_size`
let response = ui.add(button);
let mut response = response.on_hover_cursor(CursorIcon::ResizeHorizontal);
if ui.style().explanation_tooltips {
response = response .on_hover_text(format!(
"{}{}{}\nDrag to edit or click to enter a value.\nPress 'Shift' while dragging for better control.",
prefix,
value as f32, // Show full precision value on-hover. TODO(emilk): figure out f64 vs f32
suffix
));
}
if response.clicked() {
ui.memory().request_focus(kb_edit_id);
ui.memory().drag_value.edit_string = None; // Filled in next frame
} else if response.dragged() {
ui.output().cursor_icon = CursorIcon::ResizeHorizontal;
let mdelta = response.drag_delta();
let delta_points = mdelta.x - mdelta.y; // Increase to the right and up
let speed = if is_slow_speed { speed / 10.0 } else { speed };
let delta_value = delta_points as f64 * speed;
if delta_value != 0.0 {
let mut drag_state = std::mem::take(&mut ui.memory().drag_value);
// 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))
.then(|| drag_state.last_dragged_value)
.flatten();
let stored_value = stored_value.unwrap_or(value);
let stored_value = stored_value + delta_value;
let aim_delta = aim_rad * speed;
let rounded_new_value = emath::smart_aim::best_in_range_f64(
stored_value - aim_delta,
stored_value + aim_delta,
);
let rounded_new_value =
emath::round_to_decimals(rounded_new_value, auto_decimals);
let rounded_new_value = clamp_to_range(rounded_new_value, clamp_range);
set(&mut get_set_value, rounded_new_value);
drag_state.last_dragged_id = Some(response.id);
drag_state.last_dragged_value = Some(stored_value);
ui.memory().drag_value = drag_state;
}
} else if response.has_focus() {
let change = ui.input().num_presses(Key::ArrowUp) as f64
+ ui.input().num_presses(Key::ArrowRight) as f64
- ui.input().num_presses(Key::ArrowDown) as f64
- ui.input().num_presses(Key::ArrowLeft) as f64;
if change != 0.0 {
let new_value = value + speed * change;
let new_value = emath::round_to_decimals(new_value, auto_decimals);
let new_value = clamp_to_range(new_value, clamp_range);
set(&mut get_set_value, new_value);
}
}
response
};
response.changed = get(&mut get_set_value) != old_value;
response.widget_info(|| WidgetInfo::drag_value(value));
response
}
}
fn clamp_to_range(x: f64, range: RangeInclusive<f64>) -> f64 {
x.clamp(
range.start().min(*range.end()),
range.start().max(*range.end()),
)
}
+127
View File
@@ -0,0 +1,127 @@
use crate::*;
/// Clickable text, that looks like a hyperlink.
///
/// To link to a web page, use [`Hyperlink`], [`Ui::hyperlink`] or [`Ui::hyperlink_to`].
///
/// See also [`Ui::link`].
///
/// ```
/// # egui::__run_test_ui(|ui| {
/// // These are equivalent:
/// if ui.link("Documentation").clicked() {
/// // …
/// }
///
/// if ui.add(egui::Link::new("Documentation")).clicked() {
/// // …
/// }
/// # });
/// ```
#[must_use = "You should put this widget in an ui with `ui.add(widget);`"]
pub struct Link {
text: WidgetText,
}
impl Link {
pub fn new(text: impl Into<WidgetText>) -> Self {
Self { text: text.into() }
}
}
impl Widget for Link {
fn ui(self, ui: &mut Ui) -> Response {
let Link { text } = self;
let label = Label::new(text).sense(Sense::click());
let (pos, text_galley, response) = label.layout_in_ui(ui);
response.widget_info(|| WidgetInfo::labeled(WidgetType::Link, text_galley.text()));
if response.hovered() {
ui.ctx().output().cursor_icon = CursorIcon::PointingHand;
}
if ui.is_rect_visible(response.rect) {
let color = ui.visuals().hyperlink_color;
let visuals = ui.style().interact(&response);
let underline = if response.hovered() || response.has_focus() {
Stroke::new(visuals.fg_stroke.width, color)
} else {
Stroke::none()
};
ui.painter().add(epaint::TextShape {
pos,
galley: text_galley.galley,
override_text_color: Some(color),
underline,
angle: 0.0,
});
}
response
}
}
/// A clickable hyperlink, e.g. to `"https://github.com/emilk/egui"`.
///
/// See also [`Ui::hyperlink`] and [`Ui::hyperlink_to`].
///
/// ```
/// # egui::__run_test_ui(|ui| {
/// // These are equivalent:
/// ui.hyperlink("https://github.com/emilk/egui");
/// ui.add(egui::Hyperlink::new("https://github.com/emilk/egui"));
///
/// // These are equivalent:
/// ui.hyperlink_to("My favorite repo", "https://github.com/emilk/egui");
/// ui.add(egui::Hyperlink::from_label_and_url("My favorite repo", "https://github.com/emilk/egui"));
/// # });
/// ```
#[must_use = "You should put this widget in an ui with `ui.add(widget);`"]
pub struct Hyperlink {
url: String,
text: WidgetText,
}
impl Hyperlink {
#[allow(clippy::needless_pass_by_value)]
pub fn new(url: impl ToString) -> Self {
let url = url.to_string();
Self {
url: url.clone(),
text: url.into(),
}
}
#[allow(clippy::needless_pass_by_value)]
pub fn from_label_and_url(text: impl Into<WidgetText>, url: impl ToString) -> Self {
Self {
url: url.to_string(),
text: text.into(),
}
}
}
impl Widget for Hyperlink {
fn ui(self, ui: &mut Ui) -> Response {
let Self { url, text } = self;
let response = ui.add(Link::new(text));
if response.clicked() {
let modifiers = ui.ctx().input().modifiers;
ui.ctx().output().open_url = Some(crate::output::OpenUrl {
url: url.clone(),
new_tab: modifiers.any(),
});
}
if response.middle_clicked() {
ui.ctx().output().open_url = Some(crate::output::OpenUrl {
url: url.clone(),
new_tab: true,
});
}
response.on_hover_text(url)
}
}
+141
View File
@@ -0,0 +1,141 @@
use crate::*;
use emath::Rot2;
/// An widget to show an image of a given size.
///
/// In order to display an image you must first acquire a [`TextureHandle`].
/// This is best done with [`egui_extras::RetainedImage`](https://docs.rs/egui_extras/latest/egui_extras/image/struct.RetainedImage.html) or [`Context::load_texture`].
///
/// ```
/// struct MyImage {
/// texture: Option<egui::TextureHandle>,
/// }
///
/// impl MyImage {
/// fn ui(&mut self, ui: &mut egui::Ui) {
/// let texture: &egui::TextureHandle = self.texture.get_or_insert_with(|| {
/// // Load the texture only once.
/// ui.ctx().load_texture(
/// "my-image",
/// egui::ColorImage::example(),
/// egui::TextureFilter::Linear
/// )
/// });
///
/// // Show the image:
/// ui.add(egui::Image::new(texture, texture.size_vec2()));
///
/// // Shorter version:
/// ui.image(texture, texture.size_vec2());
/// }
/// }
/// ```
///
/// Se also [`crate::Ui::image`] and [`crate::ImageButton`].
#[must_use = "You should put this widget in an ui with `ui.add(widget);`"]
#[derive(Clone, Copy, Debug)]
pub struct Image {
texture_id: TextureId,
uv: Rect,
size: Vec2,
bg_fill: Color32,
tint: Color32,
sense: Sense,
rotation: Option<(Rot2, Vec2)>,
}
impl Image {
pub fn new(texture_id: impl Into<TextureId>, size: impl Into<Vec2>) -> Self {
Self {
texture_id: texture_id.into(),
uv: Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)),
size: size.into(),
bg_fill: Default::default(),
tint: Color32::WHITE,
sense: Sense::hover(),
rotation: None,
}
}
/// Select UV range. Default is (0,0) in top-left, (1,1) bottom right.
pub fn uv(mut self, uv: impl Into<Rect>) -> Self {
self.uv = uv.into();
self
}
/// A solid color to put behind the image. Useful for transparent images.
pub fn bg_fill(mut self, bg_fill: impl Into<Color32>) -> Self {
self.bg_fill = bg_fill.into();
self
}
/// Multiply image color with this. Default is WHITE (no tint).
pub fn tint(mut self, tint: impl Into<Color32>) -> Self {
self.tint = tint.into();
self
}
/// Make the image respond to clicks and/or drags.
///
/// Consider using [`ImageButton`] instead, for an on-hover effect.
pub fn sense(mut self, sense: Sense) -> Self {
self.sense = sense;
self
}
/// Rotate the image about an origin by some angle
///
/// Positive angle is clockwise.
/// Origin is a vector in normalized UV space ((0,0) in top-left, (1,1) bottom right).
///
/// To rotate about the center you can pass `Vec2::splat(0.5)` as the origin.
pub fn rotate(mut self, angle: f32, origin: Vec2) -> Self {
self.rotation = Some((Rot2::from_angle(angle), origin));
self
}
}
impl Image {
pub fn size(&self) -> Vec2 {
self.size
}
pub fn paint_at(&self, ui: &mut Ui, rect: Rect) {
if ui.is_rect_visible(rect) {
use epaint::*;
let Self {
texture_id,
uv,
size,
bg_fill,
tint,
sense: _,
rotation,
} = self;
if *bg_fill != Default::default() {
let mut mesh = Mesh::default();
mesh.add_colored_rect(rect, *bg_fill);
ui.painter().add(Shape::mesh(mesh));
}
{
// TODO(emilk): builder pattern for Mesh
let mut mesh = Mesh::with_texture(*texture_id);
mesh.add_rect_with_uv(rect, *uv, *tint);
if let Some((rot, origin)) = rotation {
mesh.rotate(*rot, rect.min + *origin * *size);
}
ui.painter().add(Shape::mesh(mesh));
}
}
}
}
impl Widget for Image {
fn ui(self, ui: &mut Ui) -> Response {
let (rect, response) = ui.allocate_exact_size(self.size, self.sense);
self.paint_at(ui, rect);
response
}
}
+189
View File
@@ -0,0 +1,189 @@
use crate::{widget_text::WidgetTextGalley, *};
/// Static text.
///
/// Usually it is more convenient to use [`Ui::label`].
///
/// ```
/// # egui::__run_test_ui(|ui| {
/// ui.label("Equivalent");
/// ui.add(egui::Label::new("Equivalent"));
/// ui.add(egui::Label::new("With Options").wrap(false));
/// ui.label(egui::RichText::new("With formatting").underline());
/// # });
/// ```
#[must_use = "You should put this widget in an ui with `ui.add(widget);`"]
pub struct Label {
text: WidgetText,
wrap: Option<bool>,
sense: Sense,
}
impl Label {
pub fn new(text: impl Into<WidgetText>) -> Self {
Self {
text: text.into(),
wrap: None,
sense: Sense::focusable_noninteractive(),
}
}
pub fn text(&self) -> &str {
self.text.text()
}
/// If `true`, the text will wrap to stay within the max width of the [`Ui`].
///
/// By default [`Self::wrap`] will be true in vertical layouts
/// and horizontal layouts with wrapping,
/// and false on non-wrapping horizontal layouts.
///
/// Note that any `\n` in the text will always produce a new line.
#[inline]
pub fn wrap(mut self, wrap: bool) -> Self {
self.wrap = Some(wrap);
self
}
/// Make the label respond to clicks and/or drags.
///
/// By default, a label is inert and does not respond to click or drags.
/// By calling this you can turn the label into a button of sorts.
/// This will also give the label the hover-effect of a button, but without the frame.
///
/// ```
/// # use egui::{Label, Sense};
/// # egui::__run_test_ui(|ui| {
/// if ui.add(Label::new("click me").sense(Sense::click())).clicked() {
/// /* … */
/// }
/// # });
/// ```
pub fn sense(mut self, sense: Sense) -> Self {
self.sense = sense;
self
}
}
impl Label {
/// Do layout and position the galley in the ui, without painting it or adding widget info.
pub fn layout_in_ui(self, ui: &mut Ui) -> (Pos2, WidgetTextGalley, Response) {
if let WidgetText::Galley(galley) = self.text {
// If the user said "use this specific galley", then just use it:
let (rect, response) = ui.allocate_exact_size(galley.size(), self.sense);
let pos = match galley.job.halign {
Align::LEFT => rect.left_top(),
Align::Center => rect.center_top(),
Align::RIGHT => rect.right_top(),
};
let text_galley = WidgetTextGalley {
galley,
galley_has_color: true,
};
return (pos, text_galley, response);
}
let valign = ui.layout().vertical_align();
let mut text_job = self
.text
.into_text_job(ui.style(), FontSelection::Default, valign);
let should_wrap = self.wrap.unwrap_or_else(|| ui.wrap_text());
let available_width = ui.available_width();
if should_wrap
&& ui.layout().main_dir() == Direction::LeftToRight
&& ui.layout().main_wrap()
&& available_width.is_finite()
{
// On a wrapping horizontal layout we want text to start after the previous widget,
// then continue on the line below! This will take some extra work:
let cursor = ui.cursor();
let first_row_indentation = available_width - ui.available_size_before_wrap().x;
egui_assert!(first_row_indentation.is_finite());
text_job.job.wrap.max_width = available_width;
text_job.job.first_row_min_height = cursor.height();
text_job.job.halign = Align::Min;
text_job.job.justify = false;
if let Some(first_section) = text_job.job.sections.first_mut() {
first_section.leading_space = first_row_indentation;
}
let text_galley = text_job.into_galley(&*ui.fonts());
let pos = pos2(ui.max_rect().left(), ui.cursor().top());
assert!(
!text_galley.galley.rows.is_empty(),
"Galleys are never empty"
);
// collect a response from many rows:
let rect = text_galley.galley.rows[0]
.rect
.translate(vec2(pos.x, pos.y));
let mut response = ui.allocate_rect(rect, self.sense);
for row in text_galley.galley.rows.iter().skip(1) {
let rect = row.rect.translate(vec2(pos.x, pos.y));
response |= ui.allocate_rect(rect, self.sense);
}
(pos, text_galley, response)
} else {
if should_wrap {
text_job.job.wrap.max_width = available_width;
} else {
text_job.job.wrap.max_width = f32::INFINITY;
};
if ui.is_grid() {
// TODO(emilk): remove special Grid hacks like these
text_job.job.halign = Align::LEFT;
text_job.job.justify = false;
} else {
text_job.job.halign = ui.layout().horizontal_placement();
text_job.job.justify = ui.layout().horizontal_justify();
};
let text_galley = text_job.into_galley(&*ui.fonts());
let (rect, response) = ui.allocate_exact_size(text_galley.size(), self.sense);
let pos = match text_galley.galley.job.halign {
Align::LEFT => rect.left_top(),
Align::Center => rect.center_top(),
Align::RIGHT => rect.right_top(),
};
(pos, text_galley, response)
}
}
}
impl Widget for Label {
fn ui(self, ui: &mut Ui) -> Response {
let (pos, text_galley, response) = self.layout_in_ui(ui);
response.widget_info(|| WidgetInfo::labeled(WidgetType::Label, text_galley.text()));
if ui.is_rect_visible(response.rect) {
let response_color = ui.style().interact(&response).text_color();
let underline = if response.has_focus() {
Stroke::new(1.0, response_color)
} else {
Stroke::none()
};
let override_text_color = if text_galley.galley_has_color {
None
} else {
Some(response_color)
};
ui.painter().add(epaint::TextShape {
pos,
galley: text_galley.galley,
override_text_color,
underline,
angle: 0.0,
});
}
response
}
}
+155
View File
@@ -0,0 +1,155 @@
//! Widgets are pieces of GUI such as [`Label`], [`Button`], [`Slider`] etc.
//!
//! Example widget uses:
//! * `ui.add(Label::new("Text").text_color(color::red));`
//! * `if ui.add(Button::new("Click me")).clicked() { … }`
use crate::*;
mod button;
pub mod color_picker;
pub(crate) mod drag_value;
mod hyperlink;
mod image;
mod label;
pub mod plot;
mod progress_bar;
mod selected_label;
mod separator;
mod slider;
mod spinner;
pub mod text_edit;
pub use button::*;
pub use drag_value::DragValue;
pub use hyperlink::*;
pub use image::Image;
pub use label::*;
pub use progress_bar::ProgressBar;
pub use selected_label::SelectableLabel;
pub use separator::Separator;
pub use slider::*;
pub use spinner::*;
pub use text_edit::{TextBuffer, TextEdit};
// ----------------------------------------------------------------------------
/// Anything implementing Widget can be added to a [`Ui`] with [`Ui::add`].
///
/// [`Button`], [`Label`], [`Slider`], etc all implement the [`Widget`] trait.
///
/// Note that the widgets ([`Button`], [`TextEdit`] etc) are
/// [builders](https://doc.rust-lang.org/1.0.0/style/ownership/builders.html),
/// and not objects that hold state.
///
/// Tip: you can `impl Widget for &mut YourThing { }`.
///
/// `|ui: &mut Ui| -> Response { … }` also implements [`Widget`].
#[must_use = "You should put this widget in an ui with `ui.add(widget);`"]
pub trait Widget {
/// Allocate space, interact, paint, and return a [`Response`].
///
/// Note that this consumes `self`.
/// This is because most widgets ([`Button`], [`TextEdit`] etc) are
/// [builders](https://doc.rust-lang.org/1.0.0/style/ownership/builders.html)
///
/// Tip: you can `impl Widget for &mut YourObject { }`.
fn ui(self, ui: &mut Ui) -> Response;
}
/// This enables functions that return `impl Widget`, so that you can
/// create a widget by just returning a lambda from a function.
///
/// For instance: `ui.add(slider_vec2(&mut vec2));` with:
///
/// ```
/// pub fn slider_vec2(value: &mut egui::Vec2) -> impl egui::Widget + '_ {
/// move |ui: &mut egui::Ui| {
/// ui.horizontal(|ui| {
/// ui.add(egui::Slider::new(&mut value.x, 0.0..=1.0).text("x"));
/// ui.add(egui::Slider::new(&mut value.y, 0.0..=1.0).text("y"));
/// })
/// .response
/// }
/// }
/// ```
impl<F> Widget for F
where
F: FnOnce(&mut Ui) -> Response,
{
fn ui(self, ui: &mut Ui) -> Response {
self(ui)
}
}
/// Helper so that you can do `TextEdit::State::read…`
pub trait WidgetWithState {
type State;
}
// ----------------------------------------------------------------------------
/// Show a button to reset a value to its default.
/// The button is only enabled if the value does not already have its original value.
pub fn reset_button<T: Default + PartialEq>(ui: &mut Ui, value: &mut T) {
reset_button_with(ui, value, T::default());
}
/// Show a button to reset a value to its default.
/// The button is only enabled if the value does not already have its original value.
pub fn reset_button_with<T: PartialEq>(ui: &mut Ui, value: &mut T, reset_value: T) {
if ui
.add_enabled(*value != reset_value, Button::new("Reset"))
.clicked()
{
*value = reset_value;
}
}
// ----------------------------------------------------------------------------
pub fn stroke_ui(ui: &mut crate::Ui, stroke: &mut epaint::Stroke, text: &str) {
let epaint::Stroke { width, color } = stroke;
ui.horizontal(|ui| {
ui.add(DragValue::new(width).speed(0.1).clamp_range(0.0..=5.0))
.on_hover_text("Width");
ui.color_edit_button_srgba(color);
ui.label(text);
// stroke preview:
let (_id, stroke_rect) = ui.allocate_space(ui.spacing().interact_size);
let left = stroke_rect.left_center();
let right = stroke_rect.right_center();
ui.painter().line_segment([left, right], (*width, *color));
});
}
pub(crate) fn shadow_ui(ui: &mut Ui, shadow: &mut epaint::Shadow, text: &str) {
let epaint::Shadow { extrusion, color } = shadow;
ui.horizontal(|ui| {
ui.label(text);
ui.add(
DragValue::new(extrusion)
.speed(1.0)
.clamp_range(0.0..=100.0),
)
.on_hover_text("Extrusion");
ui.color_edit_button_srgba(color);
});
}
/// Show a small button to switch to/from dark/light mode (globally).
pub fn global_dark_light_mode_switch(ui: &mut Ui) {
let style: crate::Style = (*ui.ctx().style()).clone();
let new_visuals = style.visuals.light_dark_small_toggle_button(ui);
if let Some(visuals) = new_visuals {
ui.ctx().set_visuals(visuals);
}
}
/// Show larger buttons for switching between light and dark mode (globally).
pub fn global_dark_light_mode_buttons(ui: &mut Ui) {
let mut visuals = ui.ctx().style().visuals.clone();
visuals.light_dark_radio_buttons(ui);
ui.ctx().set_visuals(visuals);
}
+190
View File
@@ -0,0 +1,190 @@
use crate::emath::NumExt;
use crate::epaint::{Color32, RectShape, Rounding, Shape, Stroke};
use super::{add_rulers_and_text, highlighted_color, Orientation, PlotConfig, RectElement};
use crate::plot::{BarChart, PlotPoint, ScreenTransform};
/// One bar in a [`BarChart`]. Potentially floating, allowing stacked bar charts.
/// Width can be changed to allow variable-width histograms.
#[derive(Clone, Debug, PartialEq)]
pub struct Bar {
/// Name of plot element in the diagram (annotated by default formatter)
pub name: String,
/// Which direction the bar faces in the diagram
pub orientation: Orientation,
/// Position on the argument (input) axis -- X if vertical, Y if horizontal
pub argument: f64,
/// Position on the value (output) axis -- Y if vertical, X if horizontal
pub value: f64,
/// For stacked bars, this denotes where the bar starts. None if base axis
pub base_offset: Option<f64>,
/// Thickness of the bar
pub bar_width: f64,
/// Line width and color
pub stroke: Stroke,
/// Fill color
pub fill: Color32,
}
impl Bar {
/// Create a bar. Its `orientation` is set by its [`BarChart`] parent.
///
/// - `argument`: Position on the argument axis (X if vertical, Y if horizontal).
/// - `value`: Height of the bar (if vertical).
///
/// By default the bar is vertical and its base is at zero.
pub fn new(argument: f64, height: f64) -> Bar {
Bar {
argument,
value: height,
orientation: Orientation::default(),
name: Default::default(),
base_offset: None,
bar_width: 0.5,
stroke: Stroke::new(1.0, Color32::TRANSPARENT),
fill: Color32::TRANSPARENT,
}
}
/// Name of this bar chart element.
#[allow(clippy::needless_pass_by_value)]
pub fn name(mut self, name: impl ToString) -> Self {
self.name = name.to_string();
self
}
/// Add a custom stroke.
pub fn stroke(mut self, stroke: impl Into<Stroke>) -> Self {
self.stroke = stroke.into();
self
}
/// Add a custom fill color.
pub fn fill(mut self, color: impl Into<Color32>) -> Self {
self.fill = color.into();
self
}
/// Offset the base of the bar.
/// This offset is on the Y axis for a vertical bar
/// and on the X axis for a horizontal bar.
pub fn base_offset(mut self, offset: f64) -> Self {
self.base_offset = Some(offset);
self
}
/// Set the bar width.
pub fn width(mut self, width: f64) -> Self {
self.bar_width = width;
self
}
/// Set orientation of the element as vertical. Argument axis is X.
pub fn vertical(mut self) -> Self {
self.orientation = Orientation::Vertical;
self
}
/// Set orientation of the element as horizontal. Argument axis is Y.
pub fn horizontal(mut self) -> Self {
self.orientation = Orientation::Horizontal;
self
}
pub(super) fn lower(&self) -> f64 {
if self.value.is_sign_positive() {
self.base_offset.unwrap_or(0.0)
} else {
self.base_offset.map_or(self.value, |o| o + self.value)
}
}
pub(super) fn upper(&self) -> f64 {
if self.value.is_sign_positive() {
self.base_offset.map_or(self.value, |o| o + self.value)
} else {
self.base_offset.unwrap_or(0.0)
}
}
pub(super) fn add_shapes(
&self,
transform: &ScreenTransform,
highlighted: bool,
shapes: &mut Vec<Shape>,
) {
let (stroke, fill) = if highlighted {
highlighted_color(self.stroke, self.fill)
} else {
(self.stroke, self.fill)
};
let rect = transform.rect_from_values(&self.bounds_min(), &self.bounds_max());
let rect = Shape::Rect(RectShape {
rect,
rounding: Rounding::none(),
fill,
stroke,
});
shapes.push(rect);
}
pub(super) fn add_rulers_and_text(
&self,
parent: &BarChart,
plot: &PlotConfig<'_>,
shapes: &mut Vec<Shape>,
) {
let text: Option<String> = parent
.element_formatter
.as_ref()
.map(|fmt| fmt(self, parent));
add_rulers_and_text(self, plot, text, shapes);
}
}
impl RectElement for Bar {
fn name(&self) -> &str {
self.name.as_str()
}
fn bounds_min(&self) -> PlotPoint {
self.point_at(self.argument - self.bar_width / 2.0, self.lower())
}
fn bounds_max(&self) -> PlotPoint {
self.point_at(self.argument + self.bar_width / 2.0, self.upper())
}
fn values_with_ruler(&self) -> Vec<PlotPoint> {
let base = self.base_offset.unwrap_or(0.0);
let value_center = self.point_at(self.argument, base + self.value);
let mut ruler_positions = vec![value_center];
if let Some(offset) = self.base_offset {
ruler_positions.push(self.point_at(self.argument, offset));
}
ruler_positions
}
fn orientation(&self) -> Orientation {
self.orientation
}
fn default_values_format(&self, transform: &ScreenTransform) -> String {
let scale = transform.dvalue_dpos();
let y_decimals = ((-scale[1].abs().log10()).ceil().at_least(0.0) as usize).at_most(6);
format!("\n{:.*}", y_decimals, self.value)
}
}
@@ -0,0 +1,286 @@
use crate::emath::NumExt;
use crate::epaint::{Color32, RectShape, Rounding, Shape, Stroke};
use super::{add_rulers_and_text, highlighted_color, Orientation, PlotConfig, RectElement};
use crate::plot::{BoxPlot, PlotPoint, ScreenTransform};
/// Contains the values of a single box in a box plot.
#[derive(Clone, Debug, PartialEq)]
pub struct BoxSpread {
/// Value of lower whisker (typically minimum).
///
/// The whisker is not drawn if `lower_whisker >= quartile1`.
pub lower_whisker: f64,
/// Value of lower box threshold (typically 25% quartile)
pub quartile1: f64,
/// Value of middle line in box (typically median)
pub median: f64,
/// Value of upper box threshold (typically 75% quartile)
pub quartile3: f64,
/// Value of upper whisker (typically maximum)
///
/// The whisker is not drawn if `upper_whisker <= quartile3`.
pub upper_whisker: f64,
}
impl BoxSpread {
pub fn new(
lower_whisker: f64,
quartile1: f64,
median: f64,
quartile3: f64,
upper_whisker: f64,
) -> Self {
Self {
lower_whisker,
quartile1,
median,
quartile3,
upper_whisker,
}
}
}
/// A box in a [`BoxPlot`] diagram. This is a low level graphical element; it will not compute quartiles and whiskers,
/// letting one use their preferred formula. Use [`Points`][`super::Points`] to draw the outliers.
#[derive(Clone, Debug, PartialEq)]
pub struct BoxElem {
/// Name of plot element in the diagram (annotated by default formatter).
pub name: String,
/// Which direction the box faces in the diagram.
pub orientation: Orientation,
/// Position on the argument (input) axis -- X if vertical, Y if horizontal.
pub argument: f64,
/// Values of the box
pub spread: BoxSpread,
/// Thickness of the box
pub box_width: f64,
/// Width of the whisker at minimum/maximum
pub whisker_width: f64,
/// Line width and color
pub stroke: Stroke,
/// Fill color
pub fill: Color32,
}
impl BoxElem {
/// Create a box element. Its `orientation` is set by its [`BoxPlot`] parent.
///
/// Check [`BoxElem`] fields for detailed description.
pub fn new(argument: f64, spread: BoxSpread) -> Self {
Self {
argument,
orientation: Orientation::default(),
name: String::default(),
spread,
box_width: 0.25,
whisker_width: 0.15,
stroke: Stroke::new(1.0, Color32::TRANSPARENT),
fill: Color32::TRANSPARENT,
}
}
/// Name of this box element.
#[allow(clippy::needless_pass_by_value)]
pub fn name(mut self, name: impl ToString) -> Self {
self.name = name.to_string();
self
}
/// Add a custom stroke.
pub fn stroke(mut self, stroke: impl Into<Stroke>) -> Self {
self.stroke = stroke.into();
self
}
/// Add a custom fill color.
pub fn fill(mut self, color: impl Into<Color32>) -> Self {
self.fill = color.into();
self
}
/// Set the box width.
pub fn box_width(mut self, width: f64) -> Self {
self.box_width = width;
self
}
/// Set the whisker width.
pub fn whisker_width(mut self, width: f64) -> Self {
self.whisker_width = width;
self
}
/// Set orientation of the element as vertical. Argument axis is X.
pub fn vertical(mut self) -> Self {
self.orientation = Orientation::Vertical;
self
}
/// Set orientation of the element as horizontal. Argument axis is Y.
pub fn horizontal(mut self) -> Self {
self.orientation = Orientation::Horizontal;
self
}
pub(super) fn add_shapes(
&self,
transform: &ScreenTransform,
highlighted: bool,
shapes: &mut Vec<Shape>,
) {
let (stroke, fill) = if highlighted {
highlighted_color(self.stroke, self.fill)
} else {
(self.stroke, self.fill)
};
let rect = transform.rect_from_values(
&self.point_at(self.argument - self.box_width / 2.0, self.spread.quartile1),
&self.point_at(self.argument + self.box_width / 2.0, self.spread.quartile3),
);
let rect = Shape::Rect(RectShape {
rect,
rounding: Rounding::none(),
fill,
stroke,
});
shapes.push(rect);
let line_between = |v1, v2| {
Shape::line_segment(
[
transform.position_from_point(&v1),
transform.position_from_point(&v2),
],
stroke,
)
};
let median = line_between(
self.point_at(self.argument - self.box_width / 2.0, self.spread.median),
self.point_at(self.argument + self.box_width / 2.0, self.spread.median),
);
shapes.push(median);
if self.spread.upper_whisker > self.spread.quartile3 {
let high_whisker = line_between(
self.point_at(self.argument, self.spread.quartile3),
self.point_at(self.argument, self.spread.upper_whisker),
);
shapes.push(high_whisker);
if self.box_width > 0.0 {
let high_whisker_end = line_between(
self.point_at(
self.argument - self.whisker_width / 2.0,
self.spread.upper_whisker,
),
self.point_at(
self.argument + self.whisker_width / 2.0,
self.spread.upper_whisker,
),
);
shapes.push(high_whisker_end);
}
}
if self.spread.lower_whisker < self.spread.quartile1 {
let low_whisker = line_between(
self.point_at(self.argument, self.spread.quartile1),
self.point_at(self.argument, self.spread.lower_whisker),
);
shapes.push(low_whisker);
if self.box_width > 0.0 {
let low_whisker_end = line_between(
self.point_at(
self.argument - self.whisker_width / 2.0,
self.spread.lower_whisker,
),
self.point_at(
self.argument + self.whisker_width / 2.0,
self.spread.lower_whisker,
),
);
shapes.push(low_whisker_end);
}
}
}
pub(super) fn add_rulers_and_text(
&self,
parent: &BoxPlot,
plot: &PlotConfig<'_>,
shapes: &mut Vec<Shape>,
) {
let text: Option<String> = parent
.element_formatter
.as_ref()
.map(|fmt| fmt(self, parent));
add_rulers_and_text(self, plot, text, shapes);
}
}
impl RectElement for BoxElem {
fn name(&self) -> &str {
self.name.as_str()
}
fn bounds_min(&self) -> PlotPoint {
let argument = self.argument - self.box_width.max(self.whisker_width) / 2.0;
let value = self.spread.lower_whisker;
self.point_at(argument, value)
}
fn bounds_max(&self) -> PlotPoint {
let argument = self.argument + self.box_width.max(self.whisker_width) / 2.0;
let value = self.spread.upper_whisker;
self.point_at(argument, value)
}
fn values_with_ruler(&self) -> Vec<PlotPoint> {
let median = self.point_at(self.argument, self.spread.median);
let q1 = self.point_at(self.argument, self.spread.quartile1);
let q3 = self.point_at(self.argument, self.spread.quartile3);
let upper = self.point_at(self.argument, self.spread.upper_whisker);
let lower = self.point_at(self.argument, self.spread.lower_whisker);
vec![median, q1, q3, upper, lower]
}
fn orientation(&self) -> Orientation {
self.orientation
}
fn corner_value(&self) -> PlotPoint {
self.point_at(self.argument, self.spread.upper_whisker)
}
fn default_values_format(&self, transform: &ScreenTransform) -> String {
let scale = transform.dvalue_dpos();
let y_decimals = ((-scale[1].abs().log10()).ceil().at_least(0.0) as usize).at_most(6);
format!(
"\nMax = {max:.decimals$}\
\nQuartile 3 = {q3:.decimals$}\
\nMedian = {med:.decimals$}\
\nQuartile 1 = {q1:.decimals$}\
\nMin = {min:.decimals$}",
max = self.spread.upper_whisker,
q3 = self.spread.quartile3,
med = self.spread.median,
q1 = self.spread.quartile1,
min = self.spread.lower_whisker,
decimals = y_decimals
)
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,63 @@
use super::{Orientation, PlotPoint};
use crate::plot::transform::{PlotBounds, ScreenTransform};
use epaint::emath::NumExt;
use epaint::{Color32, Rgba, Stroke};
/// Trait that abstracts from rectangular 'Value'-like elements, such as bars or boxes
pub(super) trait RectElement {
fn name(&self) -> &str;
fn bounds_min(&self) -> PlotPoint;
fn bounds_max(&self) -> PlotPoint;
fn bounds(&self) -> PlotBounds {
let mut bounds = PlotBounds::NOTHING;
bounds.extend_with(&self.bounds_min());
bounds.extend_with(&self.bounds_max());
bounds
}
/// At which argument (input; usually X) there is a ruler (usually vertical)
fn arguments_with_ruler(&self) -> Vec<PlotPoint> {
// Default: one at center
vec![self.bounds().center()]
}
/// At which value (output; usually Y) there is a ruler (usually horizontal)
fn values_with_ruler(&self) -> Vec<PlotPoint>;
/// The diagram's orientation (vertical/horizontal)
fn orientation(&self) -> Orientation;
/// Get X/Y-value for (argument, value) pair, taking into account orientation
fn point_at(&self, argument: f64, value: f64) -> PlotPoint {
match self.orientation() {
Orientation::Horizontal => PlotPoint::new(value, argument),
Orientation::Vertical => PlotPoint::new(argument, value),
}
}
/// Right top of the rectangle (position of text)
fn corner_value(&self) -> PlotPoint {
//self.point_at(self.position + self.width / 2.0, value)
PlotPoint {
x: self.bounds_max().x,
y: self.bounds_max().y,
}
}
/// Debug formatting for hovered-over value, if none is specified by the user
fn default_values_format(&self, transform: &ScreenTransform) -> String;
}
// ----------------------------------------------------------------------------
// Helper functions
pub(super) fn highlighted_color(mut stroke: Stroke, fill: Color32) -> (Stroke, Color32) {
stroke.width *= 2.0;
let fill = Rgba::from(fill);
let fill_alpha = (2.0 * fill.a()).at_most(1.0);
let fill = fill.to_opaque().multiply(fill_alpha);
(stroke, fill.into())
}
@@ -0,0 +1,432 @@
use epaint::{Pos2, Shape, Stroke, Vec2};
use std::ops::{Bound, RangeBounds, RangeInclusive};
use crate::plot::transform::PlotBounds;
/// A point coordinate in the plot.
///
/// Uses f64 for improved accuracy to enable plotting
/// large values (e.g. unix time on x axis).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PlotPoint {
/// This is often something monotonically increasing, such as time, but doesn't have to be.
/// Goes from left to right.
pub x: f64,
/// Goes from bottom to top (inverse of everything else in egui!).
pub y: f64,
}
impl From<[f64; 2]> for PlotPoint {
#[inline]
fn from([x, y]: [f64; 2]) -> Self {
Self { x, y }
}
}
impl PlotPoint {
#[inline(always)]
pub fn new(x: impl Into<f64>, y: impl Into<f64>) -> Self {
Self {
x: x.into(),
y: y.into(),
}
}
#[inline(always)]
pub fn to_pos2(self) -> Pos2 {
Pos2::new(self.x as f32, self.y as f32)
}
#[inline(always)]
pub fn to_vec2(self) -> Vec2 {
Vec2::new(self.x as f32, self.y as f32)
}
}
// ----------------------------------------------------------------------------
#[derive(Debug, PartialEq, Clone, Copy)]
pub enum LineStyle {
Solid,
Dotted { spacing: f32 },
Dashed { length: f32 },
}
impl LineStyle {
pub fn dashed_loose() -> Self {
Self::Dashed { length: 10.0 }
}
pub fn dashed_dense() -> Self {
Self::Dashed { length: 5.0 }
}
pub fn dotted_loose() -> Self {
Self::Dotted { spacing: 10.0 }
}
pub fn dotted_dense() -> Self {
Self::Dotted { spacing: 5.0 }
}
pub(super) fn style_line(
&self,
line: Vec<Pos2>,
mut stroke: Stroke,
highlight: bool,
shapes: &mut Vec<Shape>,
) {
match line.len() {
0 => {}
1 => {
let mut radius = stroke.width / 2.0;
if highlight {
radius *= 2f32.sqrt();
}
shapes.push(Shape::circle_filled(line[0], radius, stroke.color));
}
_ => {
match self {
LineStyle::Solid => {
if highlight {
stroke.width *= 2.0;
}
shapes.push(Shape::line(line, stroke));
}
LineStyle::Dotted { spacing } => {
// Take the stroke width for the radius even though it's not "correct", otherwise
// the dots would become too small.
let mut radius = stroke.width;
if highlight {
radius *= 2f32.sqrt();
}
shapes.extend(Shape::dotted_line(&line, stroke.color, *spacing, radius));
}
LineStyle::Dashed { length } => {
if highlight {
stroke.width *= 2.0;
}
let golden_ratio = (5.0_f32.sqrt() - 1.0) / 2.0; // 0.61803398875
shapes.extend(Shape::dashed_line(
&line,
stroke,
*length,
length * golden_ratio,
));
}
}
}
}
}
}
impl ToString for LineStyle {
fn to_string(&self) -> String {
match self {
LineStyle::Solid => "Solid".into(),
LineStyle::Dotted { spacing } => format!("Dotted{}Px", spacing),
LineStyle::Dashed { length } => format!("Dashed{}Px", length),
}
}
}
// ----------------------------------------------------------------------------
/// Determines whether a plot element is vertically or horizontally oriented.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum Orientation {
Horizontal,
Vertical,
}
impl Default for Orientation {
fn default() -> Self {
Self::Vertical
}
}
// ----------------------------------------------------------------------------
/// Represents many [`PlotPoint`]s.
///
/// These can be an owned `Vec` or generated with a function.
pub enum PlotPoints {
Owned(Vec<PlotPoint>),
Generator(ExplicitGenerator),
// Borrowed(&[PlotPoint]), // TODO: Lifetimes are tricky in this case.
}
impl Default for PlotPoints {
fn default() -> Self {
Self::Owned(Vec::new())
}
}
impl From<[f64; 2]> for PlotPoints {
fn from(coordinate: [f64; 2]) -> Self {
Self::new(vec![coordinate])
}
}
impl From<Vec<[f64; 2]>> for PlotPoints {
fn from(coordinates: Vec<[f64; 2]>) -> Self {
Self::new(coordinates)
}
}
impl FromIterator<[f64; 2]> for PlotPoints {
fn from_iter<T: IntoIterator<Item = [f64; 2]>>(iter: T) -> Self {
Self::Owned(iter.into_iter().map(|point| point.into()).collect())
}
}
impl PlotPoints {
pub fn new(points: Vec<[f64; 2]>) -> Self {
Self::from_iter(points)
}
pub fn points(&self) -> &[PlotPoint] {
match self {
PlotPoints::Owned(points) => points.as_slice(),
PlotPoints::Generator(_) => &[],
}
}
/// Draw a line based on a function `y=f(x)`, a range (which can be infinite) for x and the number of points.
pub fn from_explicit_callback(
function: impl Fn(f64) -> f64 + 'static,
x_range: impl RangeBounds<f64>,
points: usize,
) -> Self {
let start = match x_range.start_bound() {
Bound::Included(x) | Bound::Excluded(x) => *x,
Bound::Unbounded => f64::NEG_INFINITY,
};
let end = match x_range.end_bound() {
Bound::Included(x) | Bound::Excluded(x) => *x,
Bound::Unbounded => f64::INFINITY,
};
let x_range = start..=end;
let generator = ExplicitGenerator {
function: Box::new(function),
x_range,
points,
};
Self::Generator(generator)
}
/// Draw a line based on a function `(x,y)=f(t)`, a range for t and the number of points.
/// The range may be specified as start..end or as start..=end.
pub fn from_parametric_callback(
function: impl Fn(f64) -> (f64, f64),
t_range: impl RangeBounds<f64>,
points: usize,
) -> Self {
let start = match t_range.start_bound() {
Bound::Included(x) => x,
Bound::Excluded(_) => unreachable!(),
Bound::Unbounded => panic!("The range for parametric functions must be bounded!"),
};
let end = match t_range.end_bound() {
Bound::Included(x) | Bound::Excluded(x) => x,
Bound::Unbounded => panic!("The range for parametric functions must be bounded!"),
};
let last_point_included = matches!(t_range.end_bound(), Bound::Included(_));
let increment = if last_point_included {
(end - start) / (points - 1) as f64
} else {
(end - start) / points as f64
};
(0..points)
.map(|i| {
let t = start + i as f64 * increment;
let (x, y) = function(t);
[x, y]
})
.collect()
}
/// From a series of y-values.
/// The x-values will be the indices of these values
pub fn from_ys_f32(ys: &[f32]) -> Self {
ys.iter()
.enumerate()
.map(|(i, &y)| [i as f64, y as f64])
.collect()
}
/// From a series of y-values.
/// The x-values will be the indices of these values
pub fn from_ys_f64(ys: &[f64]) -> Self {
ys.iter().enumerate().map(|(i, &y)| [i as f64, y]).collect()
}
/// Returns true if there are no data points available and there is no function to generate any.
pub(crate) fn is_empty(&self) -> bool {
match self {
PlotPoints::Owned(points) => points.is_empty(),
PlotPoints::Generator(_) => false,
}
}
/// If initialized with a generator function, this will generate `n` evenly spaced points in the
/// given range.
pub(super) fn generate_points(&mut self, x_range: RangeInclusive<f64>) {
if let Self::Generator(generator) = self {
*self = Self::range_intersection(&x_range, &generator.x_range)
.map(|intersection| {
let increment =
(intersection.end() - intersection.start()) / (generator.points - 1) as f64;
(0..generator.points)
.map(|i| {
let x = intersection.start() + i as f64 * increment;
let y = (generator.function)(x);
[x, y]
})
.collect()
})
.unwrap_or_default();
}
}
/// Returns the intersection of two ranges if they intersect.
fn range_intersection(
range1: &RangeInclusive<f64>,
range2: &RangeInclusive<f64>,
) -> Option<RangeInclusive<f64>> {
let start = range1.start().max(*range2.start());
let end = range1.end().min(*range2.end());
(start < end).then(|| start..=end)
}
pub(super) fn bounds(&self) -> PlotBounds {
match self {
PlotPoints::Owned(points) => {
let mut bounds = PlotBounds::NOTHING;
for point in points {
bounds.extend_with(point);
}
bounds
}
PlotPoints::Generator(generator) => generator.estimate_bounds(),
}
}
}
// ----------------------------------------------------------------------------
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum MarkerShape {
Circle,
Diamond,
Square,
Cross,
Plus,
Up,
Down,
Left,
Right,
Asterisk,
}
impl MarkerShape {
/// Get a vector containing all marker shapes.
pub fn all() -> impl ExactSizeIterator<Item = MarkerShape> {
[
Self::Circle,
Self::Diamond,
Self::Square,
Self::Cross,
Self::Plus,
Self::Up,
Self::Down,
Self::Left,
Self::Right,
Self::Asterisk,
]
.iter()
.copied()
}
}
// ----------------------------------------------------------------------------
/// Query the points of the plot, for geometric relations like closest checks
pub(crate) enum PlotGeometry<'a> {
/// No geometry based on single elements (examples: text, image, horizontal/vertical line)
None,
/// Point values (X-Y graphs)
Points(&'a [PlotPoint]),
/// Rectangles (examples: boxes or bars)
// Has currently no data, as it would require copying rects or iterating a list of pointers.
// Instead, geometry-based functions are directly implemented in the respective PlotItem impl.
Rects,
}
// ----------------------------------------------------------------------------
/// Describes a function y = f(x) with an optional range for x and a number of points.
pub struct ExplicitGenerator {
function: Box<dyn Fn(f64) -> f64>,
x_range: RangeInclusive<f64>,
points: usize,
}
impl ExplicitGenerator {
fn estimate_bounds(&self) -> PlotBounds {
let mut bounds = PlotBounds::NOTHING;
let mut add_x = |x: f64| {
// avoid infinities, as we cannot auto-bound on them!
if x.is_finite() {
bounds.extend_with_x(x);
}
let y = (self.function)(x);
if y.is_finite() {
bounds.extend_with_y(y);
}
};
let min_x = *self.x_range.start();
let max_x = *self.x_range.end();
add_x(min_x);
add_x(max_x);
if min_x.is_finite() && max_x.is_finite() {
// Sample some points in the interval:
const N: u32 = 8;
for i in 1..N {
let t = i as f64 / (N - 1) as f64;
let x = crate::lerp(min_x..=max_x, t);
add_x(x);
}
} else {
// Try adding some points anyway:
for x in [-1, 0, 1] {
let x = x as f64;
if min_x <= x && x <= max_x {
add_x(x);
}
}
}
bounds
}
}
// ----------------------------------------------------------------------------
/// Result of [`super::PlotItem::find_closest()`] search, identifies an element inside the item for immediate use
pub(crate) struct ClosestElem {
/// Position of hovered-over value (or bar/box-plot/...) in PlotItem
pub index: usize,
/// Squared distance from the mouse cursor (needed to compare against other PlotItems, which might be nearer)
pub dist_sq: f32,
}
+260
View File
@@ -0,0 +1,260 @@
use std::{collections::BTreeMap, string::String};
use crate::*;
use super::items::PlotItem;
/// Where to place the plot legend.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Corner {
LeftTop,
RightTop,
LeftBottom,
RightBottom,
}
impl Corner {
pub fn all() -> impl Iterator<Item = Corner> {
[
Corner::LeftTop,
Corner::RightTop,
Corner::LeftBottom,
Corner::RightBottom,
]
.iter()
.copied()
}
}
/// The configuration for a plot legend.
#[derive(Clone, PartialEq)]
pub struct Legend {
pub text_style: TextStyle,
pub background_alpha: f32,
pub position: Corner,
}
impl Default for Legend {
fn default() -> Self {
Self {
text_style: TextStyle::Body,
background_alpha: 0.75,
position: Corner::RightTop,
}
}
}
impl Legend {
/// Which text style to use for the legend. Default: `TextStyle::Body`.
pub fn text_style(mut self, style: TextStyle) -> Self {
self.text_style = style;
self
}
/// The alpha of the legend background. Default: `0.75`.
pub fn background_alpha(mut self, alpha: f32) -> Self {
self.background_alpha = alpha;
self
}
/// In which corner to place the legend. Default: `Corner::RightTop`.
pub fn position(mut self, corner: Corner) -> Self {
self.position = corner;
self
}
}
#[derive(Clone)]
struct LegendEntry {
color: Color32,
checked: bool,
hovered: bool,
}
impl LegendEntry {
fn new(color: Color32, checked: bool) -> Self {
Self {
color,
checked,
hovered: false,
}
}
fn ui(&mut self, ui: &mut Ui, text: String, text_style: &TextStyle) -> Response {
let Self {
color,
checked,
hovered,
} = self;
let font_id = text_style.resolve(ui.style());
let galley = ui
.fonts()
.layout_delayed_color(text, font_id, f32::INFINITY);
let icon_size = galley.size().y;
let icon_spacing = icon_size / 5.0;
let total_extra = vec2(icon_size + icon_spacing, 0.0);
let desired_size = total_extra + galley.size();
let (rect, response) = ui.allocate_exact_size(desired_size, Sense::click());
response
.widget_info(|| WidgetInfo::selected(WidgetType::Checkbox, *checked, galley.text()));
let visuals = ui.style().interact(&response);
let label_on_the_left = ui.layout().horizontal_placement() == Align::RIGHT;
let icon_position_x = if label_on_the_left {
rect.right() - icon_size / 2.0
} else {
rect.left() + icon_size / 2.0
};
let icon_position = pos2(icon_position_x, rect.center().y);
let icon_rect = Rect::from_center_size(icon_position, vec2(icon_size, icon_size));
let painter = ui.painter();
painter.add(epaint::CircleShape {
center: icon_rect.center(),
radius: icon_size * 0.5,
fill: visuals.bg_fill,
stroke: visuals.bg_stroke,
});
if *checked {
let fill = if *color == Color32::TRANSPARENT {
ui.visuals().noninteractive().fg_stroke.color
} else {
*color
};
painter.add(epaint::Shape::circle_filled(
icon_rect.center(),
icon_size * 0.4,
fill,
));
}
let text_position_x = if label_on_the_left {
rect.right() - icon_size - icon_spacing - galley.size().x
} else {
rect.left() + icon_size + icon_spacing
};
let text_position = pos2(text_position_x, rect.center().y - 0.5 * galley.size().y);
painter.galley_with_color(text_position, galley, visuals.text_color());
*checked ^= response.clicked_by(PointerButton::Primary);
*hovered = response.hovered();
response
}
}
#[derive(Clone)]
pub(super) struct LegendWidget {
rect: Rect,
entries: BTreeMap<String, LegendEntry>,
config: Legend,
}
impl LegendWidget {
/// Create a new legend from items, the names of items that are hidden and the style of the
/// text. Returns `None` if the legend has no entries.
pub(super) fn try_new(
rect: Rect,
config: Legend,
items: &[Box<dyn PlotItem>],
hidden_items: &ahash::HashSet<String>,
) -> Option<Self> {
// Collect the legend entries. If multiple items have the same name, they share a
// checkbox. If their colors don't match, we pick a neutral color for the checkbox.
let mut entries: BTreeMap<String, LegendEntry> = BTreeMap::new();
items
.iter()
.filter(|item| !item.name().is_empty())
.for_each(|item| {
entries
.entry(item.name().to_owned())
.and_modify(|entry| {
if entry.color != item.color() {
// Multiple items with different colors
entry.color = Color32::TRANSPARENT;
}
})
.or_insert_with(|| {
let color = item.color();
let checked = !hidden_items.contains(item.name());
LegendEntry::new(color, checked)
});
});
(!entries.is_empty()).then(|| Self {
rect,
entries,
config,
})
}
// Get the names of the hidden items.
pub fn hidden_items(&self) -> ahash::HashSet<String> {
self.entries
.iter()
.filter(|(_, entry)| !entry.checked)
.map(|(name, _)| name.clone())
.collect()
}
// Get the name of the hovered items.
pub fn hovered_entry_name(&self) -> Option<String> {
self.entries
.iter()
.find(|(_, entry)| entry.hovered)
.map(|(name, _)| name.to_string())
}
}
impl Widget for &mut LegendWidget {
fn ui(self, ui: &mut Ui) -> Response {
let LegendWidget {
rect,
entries,
config,
} = self;
let main_dir = match config.position {
Corner::LeftTop | Corner::RightTop => Direction::TopDown,
Corner::LeftBottom | Corner::RightBottom => Direction::BottomUp,
};
let cross_align = match config.position {
Corner::LeftTop | Corner::LeftBottom => Align::LEFT,
Corner::RightTop | Corner::RightBottom => Align::RIGHT,
};
let layout = Layout::from_main_dir_and_cross_align(main_dir, cross_align);
let legend_pad = 4.0;
let legend_rect = rect.shrink(legend_pad);
let mut legend_ui = ui.child_ui(legend_rect, layout);
legend_ui
.scope(|ui| {
let background_frame = Frame {
inner_margin: vec2(8.0, 4.0).into(),
rounding: ui.style().visuals.window_rounding,
shadow: epaint::Shadow::default(),
fill: ui.style().visuals.extreme_bg_color,
stroke: ui.style().visuals.window_stroke(),
..Default::default()
}
.multiply_with_opacity(config.background_alpha);
background_frame
.show(ui, |ui| {
entries
.iter_mut()
.map(|(name, entry)| entry.ui(ui, name.clone(), &config.text_style))
.reduce(|r1, r2| r1.union(r2))
.unwrap()
})
.inner
})
.inner
}
}
File diff suppressed because it is too large Load Diff
+350
View File
@@ -0,0 +1,350 @@
use std::ops::RangeInclusive;
use super::PlotPoint;
use crate::*;
/// 2D bounding box of f64 precision.
/// The range of data values we show.
#[derive(Clone, Copy, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct PlotBounds {
pub(crate) min: [f64; 2],
pub(crate) max: [f64; 2],
}
impl PlotBounds {
pub const NOTHING: Self = Self {
min: [f64::INFINITY; 2],
max: [-f64::INFINITY; 2],
};
pub fn min(&self) -> [f64; 2] {
self.min
}
pub fn max(&self) -> [f64; 2] {
self.max
}
pub(crate) fn new_symmetrical(half_extent: f64) -> Self {
Self {
min: [-half_extent; 2],
max: [half_extent; 2],
}
}
pub fn is_finite(&self) -> bool {
self.min[0].is_finite()
&& self.min[1].is_finite()
&& self.max[0].is_finite()
&& self.max[1].is_finite()
}
pub fn is_valid(&self) -> bool {
self.is_finite() && self.width() > 0.0 && self.height() > 0.0
}
pub fn width(&self) -> f64 {
self.max[0] - self.min[0]
}
pub fn height(&self) -> f64 {
self.max[1] - self.min[1]
}
pub fn center(&self) -> PlotPoint {
[
(self.min[0] + self.max[0]) / 2.0,
(self.min[1] + self.max[1]) / 2.0,
]
.into()
}
/// Expand to include the given (x,y) value
pub(crate) fn extend_with(&mut self, value: &PlotPoint) {
self.extend_with_x(value.x);
self.extend_with_y(value.y);
}
/// Expand to include the given x coordinate
pub(crate) fn extend_with_x(&mut self, x: f64) {
self.min[0] = self.min[0].min(x);
self.max[0] = self.max[0].max(x);
}
/// Expand to include the given y coordinate
pub(crate) fn extend_with_y(&mut self, y: f64) {
self.min[1] = self.min[1].min(y);
self.max[1] = self.max[1].max(y);
}
pub(crate) fn expand_x(&mut self, pad: f64) {
self.min[0] -= pad;
self.max[0] += pad;
}
pub(crate) fn expand_y(&mut self, pad: f64) {
self.min[1] -= pad;
self.max[1] += pad;
}
pub(crate) fn merge_x(&mut self, other: &PlotBounds) {
self.min[0] = self.min[0].min(other.min[0]);
self.max[0] = self.max[0].max(other.max[0]);
}
pub(crate) fn merge_y(&mut self, other: &PlotBounds) {
self.min[1] = self.min[1].min(other.min[1]);
self.max[1] = self.max[1].max(other.max[1]);
}
pub(crate) fn set_x(&mut self, other: &PlotBounds) {
self.min[0] = other.min[0];
self.max[0] = other.max[0];
}
pub(crate) fn set_y(&mut self, other: &PlotBounds) {
self.min[1] = other.min[1];
self.max[1] = other.max[1];
}
pub(crate) fn merge(&mut self, other: &PlotBounds) {
self.min[0] = self.min[0].min(other.min[0]);
self.min[1] = self.min[1].min(other.min[1]);
self.max[0] = self.max[0].max(other.max[0]);
self.max[1] = self.max[1].max(other.max[1]);
}
pub(crate) fn translate_x(&mut self, delta: f64) {
self.min[0] += delta;
self.max[0] += delta;
}
pub(crate) fn translate_y(&mut self, delta: f64) {
self.min[1] += delta;
self.max[1] += delta;
}
pub(crate) fn translate(&mut self, delta: Vec2) {
self.translate_x(delta.x as f64);
self.translate_y(delta.y as f64);
}
pub(crate) fn add_relative_margin_x(&mut self, margin_fraction: Vec2) {
let width = self.width().max(0.0);
self.expand_x(margin_fraction.x as f64 * width);
}
pub(crate) fn add_relative_margin_y(&mut self, margin_fraction: Vec2) {
let height = self.height().max(0.0);
self.expand_y(margin_fraction.y as f64 * height);
}
pub(crate) fn range_x(&self) -> RangeInclusive<f64> {
self.min[0]..=self.max[0]
}
pub(crate) fn range_y(&self) -> RangeInclusive<f64> {
self.min[1]..=self.max[1]
}
pub(crate) fn make_x_symmetrical(&mut self) {
let x_abs = self.min[0].abs().max(self.max[0].abs());
self.min[0] = -x_abs;
self.max[0] = x_abs;
}
pub(crate) fn make_y_symmetrical(&mut self) {
let y_abs = self.min[1].abs().max(self.max[1].abs());
self.min[1] = -y_abs;
self.max[1] = y_abs;
}
}
/// Contains the screen rectangle and the plot bounds and provides methods to transform them.
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[derive(Clone)]
pub(crate) struct ScreenTransform {
/// The screen rectangle.
frame: Rect,
/// The plot bounds.
bounds: PlotBounds,
/// Whether to always center the x-range of the bounds.
x_centered: bool,
/// Whether to always center the y-range of the bounds.
y_centered: bool,
}
impl ScreenTransform {
pub fn new(frame: Rect, mut bounds: PlotBounds, x_centered: bool, y_centered: bool) -> Self {
// Make sure they are not empty.
if !bounds.is_valid() {
bounds = PlotBounds::new_symmetrical(1.0);
}
// Scale axes so that the origin is in the center.
if x_centered {
bounds.make_x_symmetrical();
};
if y_centered {
bounds.make_y_symmetrical();
};
Self {
frame,
bounds,
x_centered,
y_centered,
}
}
pub fn frame(&self) -> &Rect {
&self.frame
}
pub fn bounds(&self) -> &PlotBounds {
&self.bounds
}
pub fn set_bounds(&mut self, bounds: PlotBounds) {
self.bounds = bounds;
}
pub fn translate_bounds(&mut self, mut delta_pos: Vec2) {
if self.x_centered {
delta_pos.x = 0.;
}
if self.y_centered {
delta_pos.y = 0.;
}
delta_pos.x *= self.dvalue_dpos()[0] as f32;
delta_pos.y *= self.dvalue_dpos()[1] as f32;
self.bounds.translate(delta_pos);
}
/// Zoom by a relative factor with the given screen position as center.
pub fn zoom(&mut self, zoom_factor: Vec2, center: Pos2) {
let center = self.value_from_position(center);
let mut new_bounds = self.bounds;
new_bounds.min[0] = center.x + (new_bounds.min[0] - center.x) / (zoom_factor.x as f64);
new_bounds.max[0] = center.x + (new_bounds.max[0] - center.x) / (zoom_factor.x as f64);
new_bounds.min[1] = center.y + (new_bounds.min[1] - center.y) / (zoom_factor.y as f64);
new_bounds.max[1] = center.y + (new_bounds.max[1] - center.y) / (zoom_factor.y as f64);
if new_bounds.is_valid() {
self.bounds = new_bounds;
}
}
pub fn position_from_point(&self, value: &PlotPoint) -> Pos2 {
let x = remap(
value.x,
self.bounds.min[0]..=self.bounds.max[0],
(self.frame.left() as f64)..=(self.frame.right() as f64),
);
let y = remap(
value.y,
self.bounds.min[1]..=self.bounds.max[1],
(self.frame.bottom() as f64)..=(self.frame.top() as f64), // negated y axis!
);
pos2(x as f32, y as f32)
}
pub fn value_from_position(&self, pos: Pos2) -> PlotPoint {
let x = remap(
pos.x as f64,
(self.frame.left() as f64)..=(self.frame.right() as f64),
self.bounds.min[0]..=self.bounds.max[0],
);
let y = remap(
pos.y as f64,
(self.frame.bottom() as f64)..=(self.frame.top() as f64), // negated y axis!
self.bounds.min[1]..=self.bounds.max[1],
);
PlotPoint::new(x, y)
}
/// Transform a rectangle of plot values to a screen-coordinate rectangle.
///
/// This typically means that the rect is mirrored vertically (top becomes bottom and vice versa),
/// since the plot's coordinate system has +Y up, while egui has +Y down.
pub fn rect_from_values(&self, value1: &PlotPoint, value2: &PlotPoint) -> Rect {
let pos1 = self.position_from_point(value1);
let pos2 = self.position_from_point(value2);
let mut rect = Rect::NOTHING;
rect.extend_with(pos1);
rect.extend_with(pos2);
rect
}
/// delta position / delta value
pub fn dpos_dvalue_x(&self) -> f64 {
self.frame.width() as f64 / self.bounds.width()
}
/// delta position / delta value
pub fn dpos_dvalue_y(&self) -> f64 {
-self.frame.height() as f64 / self.bounds.height() // negated y axis!
}
/// delta position / delta value
pub fn dpos_dvalue(&self) -> [f64; 2] {
[self.dpos_dvalue_x(), self.dpos_dvalue_y()]
}
/// delta value / delta position
pub fn dvalue_dpos(&self) -> [f64; 2] {
[1.0 / self.dpos_dvalue_x(), 1.0 / self.dpos_dvalue_y()]
}
fn aspect(&self) -> f64 {
let rw = self.frame.width() as f64;
let rh = self.frame.height() as f64;
(self.bounds.width() / rw) / (self.bounds.height() / rh)
}
/// Sets the aspect ratio by expanding the x- or y-axis.
///
/// This never contracts, so we don't miss out on any data.
pub fn set_aspect_by_expanding(&mut self, aspect: f64) {
let current_aspect = self.aspect();
let epsilon = 1e-5;
if (current_aspect - aspect).abs() < epsilon {
// Don't make any changes when the aspect is already almost correct.
return;
}
if current_aspect < aspect {
self.bounds
.expand_x((aspect / current_aspect - 1.0) * self.bounds.width() * 0.5);
} else {
self.bounds
.expand_y((current_aspect / aspect - 1.0) * self.bounds.height() * 0.5);
}
}
/// Sets the aspect ratio by changing either the X or Y axis (callers choice).
pub fn set_aspect_by_changing_axis(&mut self, aspect: f64, change_x: bool) {
let current_aspect = self.aspect();
let epsilon = 1e-5;
if (current_aspect - aspect).abs() < epsilon {
// Don't make any changes when the aspect is already almost correct.
return;
}
if change_x {
self.bounds
.expand_x((aspect / current_aspect - 1.0) * self.bounds.width() * 0.5);
} else {
self.bounds
.expand_y((current_aspect / aspect - 1.0) * self.bounds.height() * 0.5);
}
}
}
+152
View File
@@ -0,0 +1,152 @@
use crate::*;
enum ProgressBarText {
Custom(WidgetText),
Percentage,
}
/// A simple progress bar.
///
/// See also: [`crate::Spinner`].
#[must_use = "You should put this widget in an ui with `ui.add(widget);`"]
pub struct ProgressBar {
progress: f32,
desired_width: Option<f32>,
text: Option<ProgressBarText>,
animate: bool,
}
impl ProgressBar {
/// Progress in the `[0, 1]` range, where `1` means "completed".
pub fn new(progress: f32) -> Self {
Self {
progress: progress.clamp(0.0, 1.0),
desired_width: None,
text: None,
animate: false,
}
}
/// The desired width of the bar. Will use all horizontal space if not set.
pub fn desired_width(mut self, desired_width: f32) -> Self {
self.desired_width = Some(desired_width);
self
}
/// A custom text to display on the progress bar.
pub fn text(mut self, text: impl Into<WidgetText>) -> Self {
self.text = Some(ProgressBarText::Custom(text.into()));
self
}
/// Show the progress in percent on the progress bar.
pub fn show_percentage(mut self) -> Self {
self.text = Some(ProgressBarText::Percentage);
self
}
/// Whether to display a loading animation when progress `< 1`.
/// Note that this will cause the UI to be redrawn.
/// Defaults to `false`.
pub fn animate(mut self, animate: bool) -> Self {
self.animate = animate;
self
}
}
impl Widget for ProgressBar {
fn ui(self, ui: &mut Ui) -> Response {
let ProgressBar {
progress,
desired_width,
text,
animate,
} = self;
let animate = animate && progress < 1.0;
let desired_width =
desired_width.unwrap_or_else(|| ui.available_size_before_wrap().x.at_least(96.0));
let height = ui.spacing().interact_size.y;
let (outer_rect, response) =
ui.allocate_exact_size(vec2(desired_width, height), Sense::hover());
if ui.is_rect_visible(response.rect) {
if animate {
ui.ctx().request_repaint();
}
let visuals = ui.style().visuals.clone();
let rounding = outer_rect.height() / 2.0;
ui.painter().rect(
outer_rect,
rounding,
visuals.extreme_bg_color,
Stroke::none(),
);
let inner_rect = Rect::from_min_size(
outer_rect.min,
vec2(
(outer_rect.width() * progress).at_least(outer_rect.height()),
outer_rect.height(),
),
);
let (dark, bright) = (0.7, 1.0);
let color_factor = if animate {
lerp(dark..=bright, ui.input().time.cos().abs())
} else {
bright
};
ui.painter().rect(
inner_rect,
rounding,
Color32::from(Rgba::from(visuals.selection.bg_fill) * color_factor as f32),
Stroke::none(),
);
if animate {
let n_points = 20;
let start_angle = ui.input().time * std::f64::consts::TAU;
let end_angle = start_angle + 240f64.to_radians() * ui.input().time.sin();
let circle_radius = rounding - 2.0;
let points: Vec<Pos2> = (0..n_points)
.map(|i| {
let angle = lerp(start_angle..=end_angle, i as f64 / n_points as f64);
let (sin, cos) = angle.sin_cos();
inner_rect.right_center()
+ circle_radius * vec2(cos as f32, sin as f32)
+ vec2(-rounding, 0.0)
})
.collect();
ui.painter().add(Shape::line(
points,
Stroke::new(2.0, visuals.faint_bg_color),
));
}
if let Some(text_kind) = text {
let text = match text_kind {
ProgressBarText::Custom(text) => text,
ProgressBarText::Percentage => {
format!("{}%", (progress * 100.0) as usize).into()
}
};
let galley = text.into_galley(ui, Some(false), f32::INFINITY, TextStyle::Button);
let text_pos = outer_rect.left_center() - Vec2::new(0.0, galley.size().y / 2.0)
+ vec2(ui.spacing().item_spacing.x, 0.0);
let text_color = visuals
.override_text_color
.unwrap_or(visuals.selection.stroke.color);
galley.paint_with_fallback_color(
&ui.painter().with_clip_rect(outer_rect),
text_pos,
text_color,
);
}
}
response
}
}
+76
View File
@@ -0,0 +1,76 @@
use crate::*;
/// One out of several alternatives, either selected or not.
/// Will mark selected items with a different background color.
/// An alternative to [`RadioButton`] and [`Checkbox`].
///
/// Usually you'd use [`Ui::selectable_value`] or [`Ui::selectable_label`] instead.
///
/// ```
/// # egui::__run_test_ui(|ui| {
/// #[derive(PartialEq)]
/// enum Enum { First, Second, Third }
/// let mut my_enum = Enum::First;
///
/// ui.selectable_value(&mut my_enum, Enum::First, "First");
///
/// // is equivalent to:
///
/// if ui.add(egui::SelectableLabel::new(my_enum == Enum::First, "First")).clicked() {
/// my_enum = Enum::First
/// }
/// # });
/// ```
#[must_use = "You should put this widget in an ui with `ui.add(widget);`"]
pub struct SelectableLabel {
selected: bool,
text: WidgetText,
}
impl SelectableLabel {
pub fn new(selected: bool, text: impl Into<WidgetText>) -> Self {
Self {
selected,
text: text.into(),
}
}
}
impl Widget for SelectableLabel {
fn ui(self, ui: &mut Ui) -> Response {
let Self { selected, text } = self;
let button_padding = ui.spacing().button_padding;
let total_extra = button_padding + button_padding;
let wrap_width = ui.available_width() - total_extra.x;
let text = text.into_galley(ui, None, wrap_width, TextStyle::Button);
let mut desired_size = total_extra + text.size();
desired_size.y = desired_size.y.at_least(ui.spacing().interact_size.y);
let (rect, response) = ui.allocate_at_least(desired_size, Sense::click());
response.widget_info(|| {
WidgetInfo::selected(WidgetType::SelectableLabel, selected, text.text())
});
if ui.is_rect_visible(response.rect) {
let text_pos = ui
.layout()
.align_size_within_rect(text.size(), rect.shrink2(button_padding))
.min;
let visuals = ui.style().interact_selectable(&response, selected);
if selected || response.hovered() || response.has_focus() {
let rect = rect.expand(visuals.expansion);
ui.painter()
.rect(rect, visuals.rounding, visuals.bg_fill, visuals.bg_stroke);
}
text.paint_with_visuals(ui.painter(), text_pos, &visuals);
}
response
}
}
+84
View File
@@ -0,0 +1,84 @@
use crate::*;
/// A visual separator. A horizontal or vertical line (depending on [`Layout`]).
///
/// Usually you'd use the shorter version [`Ui::separator`].
///
/// ```
/// # egui::__run_test_ui(|ui| {
/// // These are equivalent:
/// ui.separator();
/// ui.add(egui::Separator::default());
/// # });
/// ```
#[must_use = "You should put this widget in an ui with `ui.add(widget);`"]
pub struct Separator {
spacing: f32,
is_horizontal_line: Option<bool>,
}
impl Default for Separator {
fn default() -> Self {
Self {
spacing: 6.0,
is_horizontal_line: None,
}
}
}
impl Separator {
/// How much space we take up. The line is painted in the middle of this.
pub fn spacing(mut self, spacing: f32) -> Self {
self.spacing = spacing;
self
}
/// Explicitly ask for a horizontal line.
/// By default you will get a horizontal line in vertical layouts,
/// and a vertical line in horizontal layouts.
pub fn horizontal(mut self) -> Self {
self.is_horizontal_line = Some(true);
self
}
/// Explicitly ask for a vertical line.
/// By default you will get a horizontal line in vertical layouts,
/// and a vertical line in horizontal layouts.
pub fn vertical(mut self) -> Self {
self.is_horizontal_line = Some(false);
self
}
}
impl Widget for Separator {
fn ui(self, ui: &mut Ui) -> Response {
let Separator {
spacing,
is_horizontal_line,
} = self;
let is_horizontal_line = is_horizontal_line
.unwrap_or_else(|| ui.is_grid() || !ui.layout().main_dir().is_horizontal());
let available_space = ui.available_size_before_wrap();
let size = if is_horizontal_line {
vec2(available_space.x, spacing)
} else {
vec2(spacing, available_space.y)
};
let (rect, response) = ui.allocate_at_least(size, Sense::hover());
if ui.is_rect_visible(response.rect) {
let stroke = ui.visuals().widgets.noninteractive.bg_stroke;
if is_horizontal_line {
ui.painter().hline(rect.x_range(), rect.center().y, stroke);
} else {
ui.painter().vline(rect.center().x, rect.y_range(), stroke);
}
}
response
}
}
+728
View File
@@ -0,0 +1,728 @@
#![allow(clippy::needless_pass_by_value)] // False positives with `impl ToString`
use std::ops::RangeInclusive;
use crate::*;
// ----------------------------------------------------------------------------
type NumFormatter<'a> = Box<dyn 'a + Fn(f64, RangeInclusive<usize>) -> String>;
// ----------------------------------------------------------------------------
/// Combined into one function (rather than two) to make it easier
/// for the borrow checker.
type GetSetValue<'a> = Box<dyn 'a + FnMut(Option<f64>) -> f64>;
fn get(get_set_value: &mut GetSetValue<'_>) -> f64 {
(get_set_value)(None)
}
fn set(get_set_value: &mut GetSetValue<'_>, value: f64) {
(get_set_value)(Some(value));
}
// ----------------------------------------------------------------------------
#[derive(Clone)]
struct SliderSpec {
logarithmic: bool,
/// For logarithmic sliders, the smallest positive value we are interested in.
/// 1 for integer sliders, maybe 1e-6 for others.
smallest_positive: f64,
/// For logarithmic sliders, the largest positive value we are interested in
/// before the slider switches to `INFINITY`, if that is the higher end.
/// Default: INFINITY.
largest_finite: f64,
}
/// Specifies the orientation of a [`Slider`].
pub enum SliderOrientation {
Horizontal,
Vertical,
}
/// Control a number with a slider.
///
/// The slider range defines the values you get when pulling the slider to the far edges.
/// By default, the slider can still show values outside this range,
/// and still allows users to enter values outside the range by clicking the slider value and editing it.
/// If you want to clamp incoming and outgoing values, use [`Slider::clamp_to_range`].
///
/// The range can include any numbers, and go from low-to-high or from high-to-low.
///
/// The slider consists of three parts: a slider, a value display, and an optional text.
/// The user can click the value display to edit its value. It can be turned off with `.show_value(false)`.
///
/// ```
/// # egui::__run_test_ui(|ui| {
/// # let mut my_f32: f32 = 0.0;
/// ui.add(egui::Slider::new(&mut my_f32, 0.0..=100.0).text("My value"));
/// # });
/// ```
///
/// The default [`Slider`] size is set by [`crate::style::Spacing::slider_width`].
#[must_use = "You should put this widget in an ui with `ui.add(widget);`"]
pub struct Slider<'a> {
get_set_value: GetSetValue<'a>,
range: RangeInclusive<f64>,
spec: SliderSpec,
clamp_to_range: bool,
smart_aim: bool,
show_value: bool,
orientation: SliderOrientation,
prefix: String,
suffix: String,
text: String,
text_color: Option<Color32>,
/// Sets the minimal step of the widget value
step: Option<f64>,
min_decimals: usize,
max_decimals: Option<usize>,
custom_formatter: Option<NumFormatter<'a>>,
}
impl<'a> Slider<'a> {
/// Creates a new horizontal slider.
pub fn new<Num: emath::Numeric>(value: &'a mut Num, range: RangeInclusive<Num>) -> Self {
let range_f64 = range.start().to_f64()..=range.end().to_f64();
let slf = Self::from_get_set(range_f64, move |v: Option<f64>| {
if let Some(v) = v {
*value = Num::from_f64(v);
}
value.to_f64()
});
if Num::INTEGRAL {
slf.integer()
} else {
slf
}
}
pub fn from_get_set(
range: RangeInclusive<f64>,
get_set_value: impl 'a + FnMut(Option<f64>) -> f64,
) -> Self {
Self {
get_set_value: Box::new(get_set_value),
range,
spec: SliderSpec {
logarithmic: false,
smallest_positive: 1e-6,
largest_finite: f64::INFINITY,
},
clamp_to_range: true,
smart_aim: true,
show_value: true,
orientation: SliderOrientation::Horizontal,
prefix: Default::default(),
suffix: Default::default(),
text: Default::default(),
text_color: None,
step: None,
min_decimals: 0,
max_decimals: None,
custom_formatter: None,
}
}
/// Control whether or not the slider shows the current value.
/// Default: `true`.
pub fn show_value(mut self, show_value: bool) -> Self {
self.show_value = show_value;
self
}
/// Show a prefix before the number, e.g. "x: "
pub fn prefix(mut self, prefix: impl ToString) -> Self {
self.prefix = prefix.to_string();
self
}
/// Add a suffix to the number, this can be e.g. a unit ("°" or " m")
pub fn suffix(mut self, suffix: impl ToString) -> Self {
self.suffix = suffix.to_string();
self
}
/// Show a text next to the slider (e.g. explaining what the slider controls).
pub fn text(mut self, text: impl ToString) -> Self {
self.text = text.to_string();
self
}
pub fn text_color(mut self, text_color: Color32) -> Self {
self.text_color = Some(text_color);
self
}
/// Vertical or horizontal slider? The default is horizontal.
pub fn orientation(mut self, orientation: SliderOrientation) -> Self {
self.orientation = orientation;
self
}
/// Make this a vertical slider.
pub fn vertical(mut self) -> Self {
self.orientation = SliderOrientation::Vertical;
self
}
/// Make this a logarithmic slider.
/// This is great for when the slider spans a huge range,
/// e.g. from one to a million.
/// The default is OFF.
pub fn logarithmic(mut self, logarithmic: bool) -> Self {
self.spec.logarithmic = logarithmic;
self
}
/// For logarithmic sliders that includes zero:
/// what is the smallest positive value you want to be able to select?
/// The default is `1` for integer sliders and `1e-6` for real sliders.
pub fn smallest_positive(mut self, smallest_positive: f64) -> Self {
self.spec.smallest_positive = smallest_positive;
self
}
/// For logarithmic sliders, the largest positive value we are interested in
/// before the slider switches to `INFINITY`, if that is the higher end.
/// Default: INFINITY.
pub fn largest_finite(mut self, largest_finite: f64) -> Self {
self.spec.largest_finite = largest_finite;
self
}
/// If set to `true`, all incoming and outgoing values will be clamped to the slider range.
/// Default: `true`.
pub fn clamp_to_range(mut self, clamp_to_range: bool) -> Self {
self.clamp_to_range = clamp_to_range;
self
}
/// Turn smart aim on/off. Default is ON.
/// There is almost no point in turning this off.
pub fn smart_aim(mut self, smart_aim: bool) -> Self {
self.smart_aim = smart_aim;
self
}
/// Sets the minimal change of the value.
/// Value `0.0` effectively disables the feature. If the new value is out of range
/// and `clamp_to_range` is enabled, you would not have the ability to change the value.
///
/// Default: `0.0` (disabled).
pub fn step_by(mut self, step: f64) -> Self {
self.step = if step != 0.0 { Some(step) } else { None };
self
}
// TODO(emilk): we should also have a "min precision".
/// Set a minimum number of decimals to display.
/// Normally you don't need to pick a precision, as the slider will intelligently pick a precision for you.
/// Regardless of precision the slider will use "smart aim" to help the user select nice, round values.
pub fn min_decimals(mut self, min_decimals: usize) -> Self {
self.min_decimals = min_decimals;
self
}
// TODO(emilk): we should also have a "max precision".
/// Set a maximum number of decimals to display.
/// Values will also be rounded to this number of decimals.
/// Normally you don't need to pick a precision, as the slider will intelligently pick a precision for you.
/// Regardless of precision the slider will use "smart aim" to help the user select nice, round values.
pub fn max_decimals(mut self, max_decimals: usize) -> Self {
self.max_decimals = Some(max_decimals);
self
}
/// Set an exact number of decimals to display.
/// Values will also be rounded to this number of decimals.
/// Normally you don't need to pick a precision, as the slider will intelligently pick a precision for you.
/// Regardless of precision the slider will use "smart aim" to help the user select nice, round values.
pub fn fixed_decimals(mut self, num_decimals: usize) -> Self {
self.min_decimals = num_decimals;
self.max_decimals = Some(num_decimals);
self
}
/// Set custom formatter defining how numbers are converted into text.
///
/// A custom formatter takes a `f64` for the numeric value and a `RangeInclusive<usize>` representing
/// the decimal range i.e. minimum and maximum number of decimal places shown.
///
/// ```
/// # egui::__run_test_ui(|ui| {
/// # let mut my_i64: i64 = 0;
/// ui.add(egui::Slider::new(&mut my_i64, 0..=100).custom_formatter(|n, _| format!("{:X}", n as i64)));
/// # });
/// ```
pub fn custom_formatter(
mut self,
formatter: impl 'a + Fn(f64, RangeInclusive<usize>) -> String,
) -> Self {
self.custom_formatter = Some(Box::new(formatter));
self
}
/// Helper: equivalent to `self.precision(0).smallest_positive(1.0)`.
/// If you use one of the integer constructors (e.g. `Slider::i32`) this is called for you,
/// but if you want to have a slider for picking integer values in an `Slider::f64`, use this.
pub fn integer(self) -> Self {
self.fixed_decimals(0).smallest_positive(1.0)
}
fn get_value(&mut self) -> f64 {
let value = get(&mut self.get_set_value);
if self.clamp_to_range {
let start = *self.range.start();
let end = *self.range.end();
value.clamp(start.min(end), start.max(end))
} else {
value
}
}
fn set_value(&mut self, mut value: f64) {
if self.clamp_to_range {
let start = *self.range.start();
let end = *self.range.end();
value = value.clamp(start.min(end), start.max(end));
}
if let Some(max_decimals) = self.max_decimals {
value = emath::round_to_decimals(value, max_decimals);
}
if let Some(step) = self.step {
value = (value / step).round() * step;
}
set(&mut self.get_set_value, value);
}
fn clamp_range(&self) -> RangeInclusive<f64> {
if self.clamp_to_range {
self.range()
} else {
f64::NEG_INFINITY..=f64::INFINITY
}
}
fn range(&self) -> RangeInclusive<f64> {
self.range.clone()
}
/// For instance, `position` is the mouse position and `position_range` is the physical location of the slider on the screen.
fn value_from_position(&self, position: f32, position_range: RangeInclusive<f32>) -> f64 {
let normalized = remap_clamp(position, position_range, 0.0..=1.0) as f64;
value_from_normalized(normalized, self.range(), &self.spec)
}
fn position_from_value(&self, value: f64, position_range: RangeInclusive<f32>) -> f32 {
let normalized = normalized_from_value(value, self.range(), &self.spec);
lerp(position_range, normalized as f32)
}
}
impl<'a> Slider<'a> {
/// Just the slider, no text
fn allocate_slider_space(&self, ui: &mut Ui, thickness: f32) -> Response {
let desired_size = match self.orientation {
SliderOrientation::Horizontal => vec2(ui.spacing().slider_width, thickness),
SliderOrientation::Vertical => vec2(thickness, ui.spacing().slider_width),
};
ui.allocate_response(desired_size, Sense::click_and_drag())
}
/// Just the slider, no text
fn slider_ui(&mut self, ui: &mut Ui, response: &Response) {
let rect = &response.rect;
let position_range = self.position_range(rect);
if let Some(pointer_position_2d) = response.interact_pointer_pos() {
let position = self.pointer_position(pointer_position_2d);
let new_value = if self.smart_aim {
let aim_radius = ui.input().aim_radius();
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()),
)
} else {
self.value_from_position(position, position_range.clone())
};
self.set_value(new_value);
}
if response.has_focus() {
let (dec_key, inc_key) = match self.orientation {
SliderOrientation::Horizontal => (Key::ArrowLeft, Key::ArrowRight),
// Note that this is for moving the slider position,
// so up = decrement y coordinate:
SliderOrientation::Vertical => (Key::ArrowUp, Key::ArrowDown),
};
let decrement = ui.input().num_presses(dec_key);
let increment = ui.input().num_presses(inc_key);
let kb_step = increment as f32 - decrement as f32;
if kb_step != 0.0 {
let prev_value = self.get_value();
let prev_position = self.position_from_value(prev_value, position_range.clone());
let new_position = prev_position + kb_step;
let new_value = match self.step {
Some(step) => prev_value + (kb_step as f64 * step),
None if self.smart_aim => {
let aim_radius = ui.input().aim_radius();
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, position_range.clone()),
};
self.set_value(new_value);
}
}
// Paint it:
if ui.is_rect_visible(response.rect) {
let value = self.get_value();
let rail_radius = ui.painter().round_to_pixel(self.rail_radius_limit(rect));
let rail_rect = self.rail_rect(rect, rail_radius);
let position_1d = self.position_from_value(value, position_range);
let visuals = ui.style().interact(response);
ui.painter().add(epaint::RectShape {
rect: rail_rect,
rounding: ui.visuals().widgets.inactive.rounding,
fill: ui.visuals().widgets.inactive.bg_fill,
// fill: visuals.bg_fill,
// fill: ui.visuals().extreme_bg_color,
stroke: Default::default(),
// stroke: visuals.bg_stroke,
// stroke: ui.visuals().widgets.inactive.bg_stroke,
});
let center = self.marker_center(position_1d, &rail_rect);
ui.painter().add(epaint::CircleShape {
center,
radius: self.handle_radius(rect) + visuals.expansion,
fill: visuals.bg_fill,
stroke: visuals.fg_stroke,
});
}
}
fn marker_center(&self, position_1d: f32, rail_rect: &Rect) -> Pos2 {
match self.orientation {
SliderOrientation::Horizontal => pos2(position_1d, rail_rect.center().y),
SliderOrientation::Vertical => pos2(rail_rect.center().x, position_1d),
}
}
fn pointer_position(&self, pointer_position_2d: Pos2) -> f32 {
match self.orientation {
SliderOrientation::Horizontal => pointer_position_2d.x,
SliderOrientation::Vertical => pointer_position_2d.y,
}
}
fn position_range(&self, rect: &Rect) -> RangeInclusive<f32> {
let handle_radius = self.handle_radius(rect);
match self.orientation {
SliderOrientation::Horizontal => {
(rect.left() + handle_radius)..=(rect.right() - handle_radius)
}
SliderOrientation::Vertical => {
(rect.bottom() - handle_radius)..=(rect.top() + handle_radius)
}
}
}
fn rail_rect(&self, rect: &Rect, radius: f32) -> Rect {
match self.orientation {
SliderOrientation::Horizontal => Rect::from_min_max(
pos2(rect.left(), rect.center().y - radius),
pos2(rect.right(), rect.center().y + radius),
),
SliderOrientation::Vertical => Rect::from_min_max(
pos2(rect.center().x - radius, rect.top()),
pos2(rect.center().x + radius, rect.bottom()),
),
}
}
fn handle_radius(&self, rect: &Rect) -> f32 {
let limit = match self.orientation {
SliderOrientation::Horizontal => rect.height(),
SliderOrientation::Vertical => rect.width(),
};
limit / 2.5
}
fn rail_radius_limit(&self, rect: &Rect) -> f32 {
match self.orientation {
SliderOrientation::Horizontal => (rect.height() / 4.0).at_least(2.0),
SliderOrientation::Vertical => (rect.width() / 4.0).at_least(2.0),
}
}
fn value_ui(&mut self, ui: &mut Ui, position_range: RangeInclusive<f32>) -> Response {
// If [`DragValue`] is controlled from the keyboard and `step` is defined, set speed to `step`
let change = {
// Hold one lock rather than 4 (see https://github.com/emilk/egui/pull/1380).
let input = ui.input();
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::ArrowLeft) as i32
};
let speed = match self.step {
Some(step) if change != 0 => step,
_ => self.current_gradient(&position_range),
};
let mut value = self.get_value();
let response = ui.add({
let dv = DragValue::new(&mut value)
.speed(speed)
.clamp_range(self.clamp_range())
.min_decimals(self.min_decimals)
.max_decimals_opt(self.max_decimals)
.suffix(self.suffix.clone())
.prefix(self.prefix.clone());
match &self.custom_formatter {
Some(fmt) => dv.custom_formatter(fmt),
None => dv,
}
});
if value != self.get_value() {
self.set_value(value);
}
response
}
/// delta(value) / delta(points)
fn current_gradient(&mut self, position_range: &RangeInclusive<f32>) -> f64 {
// TODO(emilk): handle clamping
let value = self.get_value();
let value_from_pos =
|position: f32| self.value_from_position(position, position_range.clone());
let pos_from_value = |value: f64| self.position_from_value(value, position_range.clone());
let left_value = value_from_pos(pos_from_value(value) - 0.5);
let right_value = value_from_pos(pos_from_value(value) + 0.5);
right_value - left_value
}
fn add_contents(&mut self, ui: &mut Ui) -> Response {
let thickness = ui
.text_style_height(&TextStyle::Body)
.at_least(ui.spacing().interact_size.y);
let mut response = self.allocate_slider_space(ui, thickness);
self.slider_ui(ui, &response);
if self.show_value {
let position_range = self.position_range(&response.rect);
let value_response = self.value_ui(ui, position_range);
if value_response.gained_focus()
|| value_response.has_focus()
|| value_response.lost_focus()
{
// Use the [`DragValue`] id as the id of the whole widget,
// so that the focus events work as expected.
response = value_response.union(response);
} else {
// Use the slider id as the id for the whole widget
response = response.union(value_response);
}
}
if !self.text.is_empty() {
let text_color = self.text_color.unwrap_or_else(|| ui.visuals().text_color());
let text = RichText::new(&self.text).color(text_color);
ui.add(Label::new(text).wrap(false));
}
response
}
}
impl<'a> Widget for Slider<'a> {
fn ui(mut self, ui: &mut Ui) -> Response {
let old_value = self.get_value();
let inner_response = match self.orientation {
SliderOrientation::Horizontal => ui.horizontal(|ui| self.add_contents(ui)),
SliderOrientation::Vertical => ui.vertical(|ui| self.add_contents(ui)),
};
let mut response = inner_response.inner | inner_response.response;
let value = self.get_value();
response.changed = value != old_value;
response.widget_info(|| WidgetInfo::slider(value, &self.text));
response
}
}
// ----------------------------------------------------------------------------
// Helpers for converting slider range to/from normalized [0-1] range.
// Always clamps.
// Logarithmic sliders are allowed to include zero and infinity,
// even though mathematically it doesn't make sense.
use std::f64::INFINITY;
/// When the user asks for an infinitely large range (e.g. logarithmic from zero),
/// give a scale that this many orders of magnitude in size.
const INF_RANGE_MAGNITUDE: f64 = 10.0;
fn value_from_normalized(normalized: f64, range: RangeInclusive<f64>, spec: &SliderSpec) -> f64 {
let (min, max) = (*range.start(), *range.end());
if min.is_nan() || max.is_nan() {
f64::NAN
} else if min == max {
min
} else if min > max {
value_from_normalized(1.0 - normalized, max..=min, spec)
} else if normalized <= 0.0 {
min
} else if normalized >= 1.0 {
max
} else if spec.logarithmic {
if max <= 0.0 {
// non-positive range
-value_from_normalized(normalized, -min..=-max, spec)
} else if 0.0 <= min {
let (min_log, max_log) = range_log10(min, max, spec);
let log = lerp(min_log..=max_log, normalized);
10.0_f64.powf(log)
} else {
assert!(min < 0.0 && 0.0 < max);
let zero_cutoff = logaritmic_zero_cutoff(min, max);
if normalized < zero_cutoff {
// negative
value_from_normalized(
remap(normalized, 0.0..=zero_cutoff, 0.0..=1.0),
min..=0.0,
spec,
)
} else {
// positive
value_from_normalized(
remap(normalized, zero_cutoff..=1.0, 0.0..=1.0),
0.0..=max,
spec,
)
}
}
} else {
crate::egui_assert!(
min.is_finite() && max.is_finite(),
"You should use a logarithmic range"
);
lerp(range, normalized.clamp(0.0, 1.0))
}
}
fn normalized_from_value(value: f64, range: RangeInclusive<f64>, spec: &SliderSpec) -> f64 {
let (min, max) = (*range.start(), *range.end());
if min.is_nan() || max.is_nan() {
f64::NAN
} else if min == max {
0.5 // empty range, show center of slider
} else if min > max {
1.0 - normalized_from_value(value, max..=min, spec)
} else if value <= min {
0.0
} else if value >= max {
1.0
} else if spec.logarithmic {
if max <= 0.0 {
// non-positive range
normalized_from_value(-value, -min..=-max, spec)
} else if 0.0 <= min {
let (min_log, max_log) = range_log10(min, max, spec);
let value_log = value.log10();
remap_clamp(value_log, min_log..=max_log, 0.0..=1.0)
} else {
assert!(min < 0.0 && 0.0 < max);
let zero_cutoff = logaritmic_zero_cutoff(min, max);
if value < 0.0 {
// negative
remap(
normalized_from_value(value, min..=0.0, spec),
0.0..=1.0,
0.0..=zero_cutoff,
)
} else {
// positive side
remap(
normalized_from_value(value, 0.0..=max, spec),
0.0..=1.0,
zero_cutoff..=1.0,
)
}
}
} else {
crate::egui_assert!(
min.is_finite() && max.is_finite(),
"You should use a logarithmic range"
);
remap_clamp(value, range, 0.0..=1.0)
}
}
fn range_log10(min: f64, max: f64, spec: &SliderSpec) -> (f64, f64) {
assert!(spec.logarithmic);
assert!(min <= max);
if min == 0.0 && max == INFINITY {
(spec.smallest_positive.log10(), INF_RANGE_MAGNITUDE)
} else if min == 0.0 {
if spec.smallest_positive < max {
(spec.smallest_positive.log10(), max.log10())
} else {
(max.log10() - INF_RANGE_MAGNITUDE, max.log10())
}
} else if max == INFINITY {
if min < spec.largest_finite {
(min.log10(), spec.largest_finite.log10())
} else {
(min.log10(), min.log10() + INF_RANGE_MAGNITUDE)
}
} else {
(min.log10(), max.log10())
}
}
/// where to put the zero cutoff for logarithmic sliders
/// that crosses zero ?
fn logaritmic_zero_cutoff(min: f64, max: f64) -> f64 {
assert!(min < 0.0 && 0.0 < max);
let min_magnitude = if min == -INFINITY {
INF_RANGE_MAGNITUDE
} else {
min.abs().log10().abs()
};
let max_magnitude = if max == INFINITY {
INF_RANGE_MAGNITUDE
} else {
max.log10().abs()
};
let cutoff = min_magnitude / (min_magnitude + max_magnitude);
crate::egui_assert!(0.0 <= cutoff && cutoff <= 1.0);
cutoff
}
+58
View File
@@ -0,0 +1,58 @@
use epaint::{emath::lerp, vec2, Pos2, Shape, Stroke};
use crate::{Response, Sense, Ui, Widget};
/// A spinner widget used to indicate loading.
///
/// See also: [`crate::ProgressBar`].
#[must_use = "You should put this widget in an ui with `ui.add(widget);`"]
#[derive(Default)]
pub struct Spinner {
/// Uses the style's `interact_size` if `None`.
size: Option<f32>,
}
impl Spinner {
/// Create a new spinner that uses the style's `interact_size` unless changed.
pub fn new() -> Self {
Self::default()
}
/// Sets the spinner's size. The size sets both the height and width, as the spinner is always
/// square. If the size isn't set explicitly, the active style's `interact_size` is used.
pub fn size(mut self, size: f32) -> Self {
self.size = Some(size);
self
}
}
impl Widget for Spinner {
fn ui(self, ui: &mut Ui) -> Response {
let size = self
.size
.unwrap_or_else(|| ui.style().spacing.interact_size.y);
let (rect, response) = ui.allocate_exact_size(vec2(size, size), Sense::hover());
if ui.is_rect_visible(rect) {
ui.ctx().request_repaint();
let radius = (rect.height() / 2.0) - 2.0;
let n_points = 20;
let start_angle = ui.input().time * std::f64::consts::TAU;
let end_angle = start_angle + 240f64.to_radians() * ui.input().time.sin();
let points: Vec<Pos2> = (0..n_points)
.map(|i| {
let angle = lerp(start_angle..=end_angle, i as f64 / n_points as f64);
let (sin, cos) = angle.sin_cos();
rect.center() + radius * vec2(cos as f32, sin as f32)
})
.collect();
ui.painter().add(Shape::line(
points,
Stroke::new(3.0, ui.visuals().strong_text_color()),
));
}
response
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,150 @@
use epaint::text::cursor::*;
/// A selected text range (could be a range of length zero).
#[derive(Clone, Copy, Debug, Default)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct CursorRange {
/// When selecting with a mouse, this is where the mouse was released.
/// When moving with e.g. shift+arrows, this is what moves.
/// Note that the two ends can come in any order, and also be equal (no selection).
pub primary: Cursor,
/// When selecting with a mouse, this is where the mouse was first pressed.
/// This part of the cursor does not move when shift is down.
pub secondary: Cursor,
}
impl CursorRange {
/// The empty range.
pub fn one(cursor: Cursor) -> Self {
Self {
primary: cursor,
secondary: cursor,
}
}
pub fn two(min: Cursor, max: Cursor) -> Self {
Self {
primary: max,
secondary: min,
}
}
pub fn as_ccursor_range(&self) -> CCursorRange {
CCursorRange {
primary: self.primary.ccursor,
secondary: self.secondary.ccursor,
}
}
/// The range of selected character indices.
pub fn as_sorted_char_range(&self) -> std::ops::Range<usize> {
let [start, end] = self.sorted_cursors();
std::ops::Range {
start: start.ccursor.index,
end: end.ccursor.index,
}
}
/// True if the selected range contains no characters.
pub fn is_empty(&self) -> bool {
self.primary.ccursor == self.secondary.ccursor
}
/// If there is a selection, None is returned.
/// If the two ends is the same, that is returned.
pub fn single(&self) -> Option<Cursor> {
if self.is_empty() {
Some(self.primary)
} else {
None
}
}
pub fn is_sorted(&self) -> bool {
let p = self.primary.ccursor;
let s = self.secondary.ccursor;
(p.index, p.prefer_next_row) <= (s.index, s.prefer_next_row)
}
pub fn sorted(self) -> Self {
if self.is_sorted() {
self
} else {
Self {
primary: self.secondary,
secondary: self.primary,
}
}
}
/// returns the two ends ordered
pub fn sorted_cursors(&self) -> [Cursor; 2] {
if self.is_sorted() {
[self.primary, self.secondary]
} else {
[self.secondary, self.primary]
}
}
}
/// A selected text range (could be a range of length zero).
///
/// The selection is based on character count (NOT byte count!).
#[derive(Clone, Copy, Debug, Default, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct CCursorRange {
/// When selecting with a mouse, this is where the mouse was released.
/// When moving with e.g. shift+arrows, this is what moves.
/// Note that the two ends can come in any order, and also be equal (no selection).
pub primary: CCursor,
/// When selecting with a mouse, this is where the mouse was first pressed.
/// This part of the cursor does not move when shift is down.
pub secondary: CCursor,
}
impl CCursorRange {
/// The empty range.
pub fn one(ccursor: CCursor) -> Self {
Self {
primary: ccursor,
secondary: ccursor,
}
}
pub fn two(min: CCursor, max: CCursor) -> Self {
Self {
primary: max,
secondary: min,
}
}
pub fn is_sorted(&self) -> bool {
let p = self.primary;
let s = self.secondary;
(p.index, p.prefer_next_row) <= (s.index, s.prefer_next_row)
}
/// returns the two ends ordered
pub fn sorted(&self) -> [CCursor; 2] {
if self.is_sorted() {
[self.primary, self.secondary]
} else {
[self.secondary, self.primary]
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct PCursorRange {
/// When selecting with a mouse, this is where the mouse was released.
/// When moving with e.g. shift+arrows, this is what moves.
/// Note that the two ends can come in any order, and also be equal (no selection).
pub primary: PCursor,
/// When selecting with a mouse, this is where the mouse was first pressed.
/// This part of the cursor does not move when shift is down.
pub secondary: PCursor,
}
+10
View File
@@ -0,0 +1,10 @@
mod builder;
mod cursor_range;
mod output;
mod state;
mod text_buffer;
pub use {
builder::TextEdit, cursor_range::*, output::TextEditOutput, state::TextEditState,
text_buffer::TextBuffer,
};
@@ -0,0 +1,24 @@
use std::sync::Arc;
/// The output from a [`TextEdit`](crate::TextEdit).
pub struct TextEditOutput {
/// The interaction response.
pub response: crate::Response,
/// How the text was displayed.
pub galley: Arc<crate::Galley>,
/// Where the text in [`Self::galley`] ended up on the screen.
pub text_draw_pos: crate::Pos2,
/// The text was clipped to this rectangle when painted.
pub text_clip_rect: crate::Rect,
/// The state we stored after the run.
pub state: super::TextEditState,
/// Where the text cursor is.
pub cursor_range: Option<super::CursorRange>,
}
// TODO(emilk): add `output.paint` and `output.store` and split out that code from `TextEdit::show`.
@@ -0,0 +1,85 @@
use std::sync::Arc;
use crate::mutex::Mutex;
use crate::*;
use super::{CCursorRange, CursorRange};
type Undoer = crate::util::undoer::Undoer<(CCursorRange, String)>;
/// The text edit state stored between frames.
#[derive(Clone, Default)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(feature = "serde", serde(default))]
pub struct TextEditState {
cursor_range: Option<CursorRange>,
/// This is what is easiest to work with when editing text,
/// so users are more likely to read/write this.
ccursor_range: Option<CCursorRange>,
/// Wrapped in Arc for cheaper clones.
#[cfg_attr(feature = "serde", serde(skip))]
pub(crate) undoer: Arc<Mutex<Undoer>>,
// If IME candidate window is shown on this text edit.
#[cfg_attr(feature = "serde", serde(skip))]
pub(crate) has_ime: bool,
// Visual offset when editing singleline text bigger than the width.
#[cfg_attr(feature = "serde", serde(skip))]
pub(crate) singleline_offset: f32,
}
impl TextEditState {
pub fn load(ctx: &Context, id: Id) -> Option<Self> {
ctx.data().get_persisted(id)
}
pub fn store(self, ctx: &Context, id: Id) {
ctx.data().insert_persisted(id, self);
}
/// The the currently selected range of characters.
pub fn ccursor_range(&self) -> Option<CCursorRange> {
self.ccursor_range.or_else(|| {
self.cursor_range
.map(|cursor_range| cursor_range.as_ccursor_range())
})
}
/// Sets the currently selected range of characters.
pub fn set_ccursor_range(&mut self, ccursor_range: Option<CCursorRange>) {
self.cursor_range = None;
self.ccursor_range = ccursor_range;
}
pub fn set_cursor_range(&mut self, cursor_range: Option<CursorRange>) {
self.cursor_range = cursor_range;
self.ccursor_range = None;
}
pub fn cursor_range(&mut self, galley: &Galley) -> Option<CursorRange> {
self.cursor_range
.map(|cursor_range| {
// We only use the PCursor (paragraph number, and character offset within that paragraph).
// This is so that if we resize the [`TextEdit`] region, and text wrapping changes,
// we keep the same byte character offset from the beginning of the text,
// even though the number of rows changes
// (each paragraph can be several rows, due to word wrapping).
// The column (character offset) should be able to extend beyond the last word so that we can
// go down and still end up on the same column when we return.
CursorRange {
primary: galley.from_pcursor(cursor_range.primary.pcursor),
secondary: galley.from_pcursor(cursor_range.secondary.pcursor),
}
})
.or_else(|| {
self.ccursor_range.map(|ccursor_range| CursorRange {
primary: galley.from_ccursor(ccursor_range.primary),
secondary: galley.from_ccursor(ccursor_range.secondary),
})
})
}
}
@@ -0,0 +1,127 @@
use std::ops::Range;
/// Trait constraining what types [`crate::TextEdit`] may use as
/// an underlying buffer.
///
/// Most likely you will use a [`String`] which implements [`TextBuffer`].
pub trait TextBuffer {
/// Can this text be edited?
fn is_mutable(&self) -> bool;
/// Returns this buffer as a `str`.
fn as_str(&self) -> &str;
/// Reads the given character range.
fn char_range(&self, char_range: Range<usize>) -> &str {
assert!(char_range.start <= char_range.end);
let start_byte = self.byte_index_from_char_index(char_range.start);
let end_byte = self.byte_index_from_char_index(char_range.end);
&self.as_str()[start_byte..end_byte]
}
fn byte_index_from_char_index(&self, char_index: usize) -> usize {
byte_index_from_char_index(self.as_str(), char_index)
}
/// Inserts text `text` into this buffer at character index `char_index`.
///
/// # Notes
/// `char_index` is a *character index*, not a byte index.
///
/// # Return
/// Returns how many *characters* were successfully inserted
fn insert_text(&mut self, text: &str, char_index: usize) -> usize;
/// Deletes a range of text `char_range` from this buffer.
///
/// # Notes
/// `char_range` is a *character range*, not a byte range.
fn delete_char_range(&mut self, char_range: Range<usize>);
/// Clears all characters in this buffer
fn clear(&mut self) {
self.delete_char_range(0..self.as_str().len());
}
/// Replaces all contents of this string with `text`
fn replace(&mut self, text: &str) {
self.clear();
self.insert_text(text, 0);
}
/// Clears all characters in this buffer and returns a string of the contents.
fn take(&mut self) -> String {
let s = self.as_str().to_owned();
self.clear();
s
}
}
impl TextBuffer for String {
fn is_mutable(&self) -> bool {
true
}
fn as_str(&self) -> &str {
self.as_ref()
}
fn insert_text(&mut self, text: &str, char_index: usize) -> usize {
// Get the byte index from the character index
let byte_idx = self.byte_index_from_char_index(char_index);
// Then insert the string
self.insert_str(byte_idx, text);
text.chars().count()
}
fn delete_char_range(&mut self, char_range: Range<usize>) {
assert!(char_range.start <= char_range.end);
// Get both byte indices
let byte_start = self.byte_index_from_char_index(char_range.start);
let byte_end = self.byte_index_from_char_index(char_range.end);
// Then drain all characters within this range
self.drain(byte_start..byte_end);
}
fn clear(&mut self) {
self.clear();
}
fn replace(&mut self, text: &str) {
*self = text.to_owned();
}
fn take(&mut self) -> String {
std::mem::take(self)
}
}
/// Immutable view of a `&str`!
impl<'a> TextBuffer for &'a str {
fn is_mutable(&self) -> bool {
false
}
fn as_str(&self) -> &str {
self
}
fn insert_text(&mut self, _text: &str, _ch_idx: usize) -> usize {
0
}
fn delete_char_range(&mut self, _ch_range: Range<usize>) {}
}
fn byte_index_from_char_index(s: &str, char_index: usize) -> usize {
for (ci, (bi, _)) in s.char_indices().enumerate() {
if ci == char_index {
return bi;
}
}
s.len()
}