egui/emigui/src/layout.rs

538 lines
16 KiB
Rust
Raw Normal View History

2019-01-07 07:54:37 +00:00
use std::{
collections::HashSet,
hash::Hash,
sync::{Arc, Mutex},
};
2018-12-27 18:08:43 +00:00
use crate::{
2019-01-12 23:55:56 +00:00
font::TextFragment,
fonts::{Fonts, TextStyle},
math::*,
types::*,
widgets::{label, Widget},
};
2018-12-26 09:46:23 +00:00
2018-12-26 22:08:50 +00:00
// ----------------------------------------------------------------------------
2018-12-26 09:46:23 +00:00
2018-12-26 22:08:50 +00:00
#[derive(Clone, Copy, Debug, Serialize)]
pub struct LayoutOptions {
2018-12-28 22:29:24 +00:00
/// Horizontal and vertical padding within a window frame.
pub window_padding: Vec2,
2019-01-14 13:26:02 +00:00
/// Button size is text size plus this on each side
pub button_padding: Vec2,
2018-12-28 22:29:24 +00:00
/// Horizontal and vertical spacing between widgets
2018-12-26 22:08:50 +00:00
pub item_spacing: Vec2,
2018-12-27 18:08:43 +00:00
/// Indent foldable regions etc by this much.
pub indent: f32,
2019-01-14 13:26:02 +00:00
/// Anything clickable is (at least) this wide.
pub clickable_diameter: f32,
2018-12-26 22:08:50 +00:00
2018-12-27 22:55:16 +00:00
/// Checkboxed, radio button and foldables have an icon at the start.
/// The text starts after this many pixels.
pub start_icon_width: f32,
2018-12-26 22:08:50 +00:00
}
impl Default for LayoutOptions {
fn default() -> Self {
LayoutOptions {
2018-12-28 22:29:24 +00:00
window_padding: vec2(6.0, 6.0),
2018-12-27 22:55:16 +00:00
button_padding: vec2(5.0, 3.0),
2019-01-14 13:26:02 +00:00
item_spacing: vec2(8.0, 4.0),
indent: 21.0,
clickable_diameter: 10.0,
2018-12-27 22:55:16 +00:00
start_icon_width: 20.0,
2018-12-26 22:08:50 +00:00
}
}
}
// ----------------------------------------------------------------------------
2018-12-26 09:46:23 +00:00
2018-12-28 22:53:15 +00:00
// TODO: rename
2019-01-07 07:54:37 +00:00
pub struct GuiResponse {
2018-12-28 22:53:15 +00:00
/// The mouse is hovering above this
pub hovered: bool,
/// The mouse went got pressed on this thing this frame
pub clicked: bool,
/// The mouse is interacting with this thing (e.g. dragging it)
pub active: bool,
2019-01-14 13:26:02 +00:00
/// The region of the screen we are talking about
pub rect: Rect,
2019-01-06 15:34:01 +00:00
/// Used for showing a popup (if any)
2019-01-07 07:54:37 +00:00
data: Arc<Data>,
2018-12-28 22:53:15 +00:00
}
2019-01-07 07:54:37 +00:00
impl GuiResponse {
2018-12-28 22:53:15 +00:00
/// Show some stuff if the item was hovered
2019-01-06 15:34:01 +00:00
pub fn tooltip<F>(&mut self, add_contents: F) -> &mut Self
2018-12-28 22:53:15 +00:00
where
2019-01-06 15:34:01 +00:00
F: FnOnce(&mut Region),
2018-12-28 22:53:15 +00:00
{
if self.hovered {
2019-01-06 15:34:01 +00:00
let window_pos = self.data.input().mouse_pos + vec2(16.0, 16.0);
2019-01-07 07:54:37 +00:00
show_popup(&self.data, window_pos, add_contents);
2018-12-28 22:53:15 +00:00
}
self
}
/// Show this text if the item was hovered
2019-01-06 15:34:01 +00:00
pub fn tooltip_text<S: Into<String>>(&mut self, text: S) -> &mut Self {
2018-12-28 22:53:15 +00:00
self.tooltip(|popup| {
popup.add(label(text));
2018-12-28 22:53:15 +00:00
})
}
}
// ----------------------------------------------------------------------------
2018-12-27 18:08:43 +00:00
#[derive(Clone, Debug, Default)]
2019-01-06 15:34:01 +00:00
pub struct Memory {
2018-12-26 14:28:38 +00:00
/// The widget being interacted with (e.g. dragged, in case of a slider).
2018-12-28 09:39:08 +00:00
active_id: Option<Id>,
2018-12-27 18:08:43 +00:00
/// Which foldable regions are open.
open_foldables: HashSet<Id>,
2018-12-26 09:46:23 +00:00
}
2018-12-26 22:08:50 +00:00
// ----------------------------------------------------------------------------
2018-12-28 09:39:08 +00:00
#[derive(Clone, Copy, Debug, PartialEq)]
2019-01-06 15:34:01 +00:00
pub enum Direction {
2018-12-28 09:39:08 +00:00
Horizontal,
Vertical,
}
impl Default for Direction {
fn default() -> Direction {
Direction::Vertical
}
}
// ----------------------------------------------------------------------------
pub type Id = u64;
pub fn make_id<H: Hash>(source: &H) -> Id {
use std::hash::Hasher;
let mut hasher = std::collections::hash_map::DefaultHasher::new();
source.hash(&mut hasher);
hasher.finish()
}
2018-12-26 22:08:50 +00:00
2019-01-07 07:54:37 +00:00
// ----------------------------------------------------------------------------
/// TODO: improve this
#[derive(Clone, Default)]
pub struct GraphicLayers {
pub(crate) graphics: Vec<GuiCmd>,
pub(crate) hovering_graphics: Vec<GuiCmd>,
}
impl GraphicLayers {
pub fn drain(&mut self) -> impl ExactSizeIterator<Item = GuiCmd> {
// TODO: there must be a nicer way to do this?
let mut all_commands: Vec<_> = self.graphics.drain(..).collect();
all_commands.extend(self.hovering_graphics.drain(..));
all_commands.into_iter()
}
}
// ----------------------------------------------------------------------------
2019-01-06 15:34:01 +00:00
// TODO: give a better name.
/// Contains the input, options and output of all GUI commands.
pub struct Data {
/// The default options for new regions
pub(crate) options: Mutex<LayoutOptions>,
2019-01-12 23:55:56 +00:00
pub(crate) fonts: Arc<Fonts>,
2019-01-06 15:34:01 +00:00
pub(crate) input: GuiInput,
2019-01-07 07:54:37 +00:00
pub(crate) memory: Mutex<Memory>,
pub(crate) graphics: Mutex<GraphicLayers>,
}
impl Clone for Data {
fn clone(&self) -> Self {
Data {
options: Mutex::new(self.options()),
2019-01-12 23:55:56 +00:00
fonts: self.fonts.clone(),
2019-01-07 07:54:37 +00:00
input: self.input.clone(),
memory: Mutex::new(self.memory.lock().unwrap().clone()),
graphics: Mutex::new(self.graphics.lock().unwrap().clone()),
}
}
2018-12-26 14:28:38 +00:00
}
2018-12-26 09:46:23 +00:00
2019-01-06 15:34:01 +00:00
impl Data {
2019-01-12 23:55:56 +00:00
pub fn new() -> Data {
2019-01-06 15:34:01 +00:00
Data {
2019-01-05 14:28:07 +00:00
options: Default::default(),
2019-01-12 23:55:56 +00:00
fonts: Arc::new(Fonts::new()),
2019-01-05 14:28:07 +00:00
input: Default::default(),
memory: Default::default(),
graphics: Default::default(),
}
}
2018-12-26 09:46:23 +00:00
pub fn input(&self) -> &GuiInput {
&self.input
}
pub fn options(&self) -> LayoutOptions {
*self.options.lock().unwrap()
2018-12-28 22:29:24 +00:00
}
pub fn set_options(&self, options: LayoutOptions) {
*self.options.lock().unwrap() = options;
2018-12-26 09:46:23 +00:00
}
2018-12-28 09:39:08 +00:00
// TODO: move
2018-12-28 22:29:24 +00:00
pub fn new_frame(&mut self, gui_input: GuiInput) {
2018-12-28 09:39:08 +00:00
self.input = gui_input;
if !gui_input.mouse_down {
2019-01-07 07:54:37 +00:00
self.memory.lock().unwrap().active_id = None;
2018-12-28 09:39:08 +00:00
}
}
2019-01-07 07:54:37 +00:00
}
2018-12-28 09:39:08 +00:00
2019-01-07 07:54:37 +00:00
/// Show a pop-over window
pub fn show_popup<F>(data: &Arc<Data>, window_pos: Vec2, add_contents: F)
where
F: FnOnce(&mut Region),
{
// TODO: nicer way to do layering!
let num_graphics_before = data.graphics.lock().unwrap().graphics.len();
let options = data.options();
let window_padding = options.window_padding;
2019-01-07 07:54:37 +00:00
let mut popup_region = Region {
data: data.clone(),
options,
2019-01-07 07:54:37 +00:00
id: Default::default(),
dir: Direction::Vertical,
cursor: window_pos + window_padding,
bounding_size: vec2(0.0, 0.0),
available_space: vec2(400.0, std::f32::INFINITY), // TODO: popup/tooltip width
2019-01-07 07:54:37 +00:00
};
add_contents(&mut popup_region);
// TODO: handle the last item_spacing in a nicer way
let inner_size = popup_region.bounding_size - options.item_spacing;
2019-01-07 07:54:37 +00:00
let outer_size = inner_size + 2.0 * window_padding;
let rect = Rect::from_min_size(window_pos, outer_size);
let mut graphics = data.graphics.lock().unwrap();
let popup_graphics = graphics.graphics.split_off(num_graphics_before);
graphics.hovering_graphics.push(GuiCmd::Window { rect });
graphics.hovering_graphics.extend(popup_graphics);
2019-01-06 15:34:01 +00:00
}
// ----------------------------------------------------------------------------
/// Represents a region of the screen
/// with a type of layout (horizontal or vertical).
/// TODO: make Region a trait so we can have type-safe HorizontalRegion etc?
2019-01-07 07:54:37 +00:00
pub struct Region {
pub(crate) data: Arc<Data>,
2019-01-06 15:34:01 +00:00
pub(crate) options: LayoutOptions,
2019-01-06 15:34:01 +00:00
/// Unique ID of this region.
pub(crate) id: Id,
/// Doesn't change.
pub(crate) dir: Direction,
/// Changes only along self.dir
pub(crate) cursor: Vec2,
/// Bounding box children.
2019-01-06 15:34:01 +00:00
/// We keep track of our max-size along the orthogonal to self.dir
pub(crate) bounding_size: Vec2,
/// This how much space we can take up without overflowing our parent.
/// Shrinks as cursor increments.
pub(crate) available_space: Vec2,
2019-01-06 15:34:01 +00:00
}
2019-01-07 07:54:37 +00:00
impl Region {
2019-01-06 15:34:01 +00:00
/// 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_graphic(&mut self, gui_cmd: GuiCmd) {
2019-01-07 07:54:37 +00:00
self.data.graphics.lock().unwrap().graphics.push(gui_cmd)
2019-01-06 15:34:01 +00:00
}
/// Options for this region, and any child regions we may spawn.
2019-01-06 15:34:01 +00:00
pub fn options(&self) -> &LayoutOptions {
&self.options
2019-01-06 15:34:01 +00:00
}
pub fn input(&self) -> &GuiInput {
self.data.input()
}
2018-12-26 09:46:23 +00:00
pub fn cursor(&self) -> Vec2 {
self.cursor
}
2019-01-12 23:55:56 +00:00
pub fn fonts(&self) -> &Fonts {
&*self.data.fonts
}
pub fn width(&self) -> f32 {
self.available_space.x
}
2019-01-13 18:15:11 +00:00
pub fn direction(&self) -> Direction {
self.dir
}
2018-12-27 18:08:43 +00:00
// ------------------------------------------------------------------------
// Sub-regions:
2018-12-27 18:08:43 +00:00
2018-12-28 22:53:15 +00:00
pub fn foldable<S, F>(&mut self, text: S, add_contents: F) -> GuiResponse
2018-12-27 18:08:43 +00:00
where
S: Into<String>,
2019-01-06 15:34:01 +00:00
F: FnOnce(&mut Region),
2018-12-27 18:08:43 +00:00
{
2018-12-28 09:39:08 +00:00
assert!(
2019-01-06 15:34:01 +00:00
self.dir == Direction::Vertical,
2018-12-28 09:39:08 +00:00
"Horizontal foldable is unimplemented"
);
2018-12-27 22:26:05 +00:00
let text: String = text.into();
2019-01-07 07:54:37 +00:00
let id = self.make_child_id(&text);
2019-01-12 23:55:56 +00:00
let text_style = TextStyle::Heading;
let font = &self.fonts()[text_style];
let (text, text_size) = font.layout_multiline(&text, self.width());
2019-01-06 15:34:01 +00:00
let text_cursor = self.cursor + self.options().button_padding;
2019-01-14 13:26:02 +00:00
let interact = self.reserve_space(
2018-12-27 22:26:05 +00:00
vec2(
self.available_space.x,
2019-01-06 15:34:01 +00:00
text_size.y + 2.0 * self.options().button_padding.y,
2018-12-27 22:26:05 +00:00
),
2018-12-28 22:53:15 +00:00
Some(id),
2018-12-27 18:35:02 +00:00
);
2018-12-27 18:08:43 +00:00
2019-01-07 07:54:37 +00:00
let open = {
let mut memory = self.data.memory.lock().unwrap();
if interact.clicked {
if memory.open_foldables.contains(&id) {
memory.open_foldables.remove(&id);
} else {
memory.open_foldables.insert(id);
}
2018-12-27 18:08:43 +00:00
}
2019-01-07 07:54:37 +00:00
memory.open_foldables.contains(&id)
};
2018-12-27 18:08:43 +00:00
2019-01-14 13:26:02 +00:00
self.add_graphic(GuiCmd::FoldableHeader { interact, open });
2019-01-06 15:34:01 +00:00
self.add_text(
text_cursor + vec2(self.options().start_icon_width, 0.0),
2019-01-12 23:55:56 +00:00
text_style,
2019-01-06 15:34:01 +00:00
text,
);
2018-12-27 18:08:43 +00:00
if open {
2018-12-27 22:26:05 +00:00
let old_id = self.id;
self.id = id;
self.indent(add_contents);
2018-12-27 22:26:05 +00:00
self.id = old_id;
2018-12-27 18:08:43 +00:00
}
2018-12-28 22:53:15 +00:00
self.response(interact)
2018-12-27 18:08:43 +00:00
}
/// Create a child region which is indented to the right
pub fn indent<F>(&mut self, add_contents: F)
where
F: FnOnce(&mut Region),
{
let indent = vec2(self.options().indent, 0.0);
let mut child_region = Region {
2019-01-07 07:54:37 +00:00
data: self.data.clone(),
options: self.options,
id: self.id,
dir: self.dir,
cursor: self.cursor + indent,
bounding_size: vec2(0.0, 0.0),
available_space: self.available_space - indent,
};
add_contents(&mut child_region);
let size = child_region.bounding_size;
2019-01-14 13:26:02 +00:00
self.reserve_space_without_padding(indent + size);
}
/// A horizontally centered region of the given width.
pub fn centered_column(&mut self, width: f32) -> Region {
Region {
2019-01-07 07:54:37 +00:00
data: self.data.clone(),
options: self.options,
id: self.id,
dir: self.dir,
cursor: vec2((self.available_space.x - width) / 2.0, self.cursor.y),
bounding_size: vec2(0.0, 0.0),
available_space: vec2(width, self.available_space.y),
}
}
2018-12-28 09:39:08 +00:00
/// Start a region with horizontal layout
pub fn horizontal<F>(&mut self, add_contents: F)
where
2019-01-06 15:34:01 +00:00
F: FnOnce(&mut Region),
2018-12-28 22:53:15 +00:00
{
let mut child_region = Region {
2019-01-07 07:54:37 +00:00
data: self.data.clone(),
options: self.options,
2018-12-28 22:29:24 +00:00
id: self.id,
2019-01-06 15:34:01 +00:00
dir: Direction::Horizontal,
cursor: self.cursor,
bounding_size: vec2(0.0, 0.0),
available_space: self.available_space,
2018-12-28 22:29:24 +00:00
};
add_contents(&mut child_region);
let size = child_region.bounding_size;
2019-01-14 13:26:02 +00:00
self.reserve_space_without_padding(size);
2018-12-28 22:29:24 +00:00
}
/// Temporarily split split a vertical layout into several columns.
2019-01-07 07:54:37 +00:00
///
/// gui.columns(2, |columns| {
/// columns[0].add(label("First column"));
/// columns[1].add(label("Second column"));
2019-01-07 07:54:37 +00:00
/// });
pub fn columns<F, R>(&mut self, num_columns: usize, add_contents: F) -> R
where
F: FnOnce(&mut [Region]) -> R,
{
// TODO: ensure there is space
let padding = self.options().item_spacing.x;
let total_padding = padding * (num_columns as f32 - 1.0);
let column_width = (self.available_space.x - total_padding) / (num_columns as f32);
let mut columns: Vec<Region> = (0..num_columns)
.map(|col_idx| Region {
data: self.data.clone(),
options: self.options,
2019-01-07 07:54:37 +00:00
id: self.make_child_id(&("column", col_idx)),
dir: Direction::Vertical,
cursor: self.cursor + vec2((col_idx as f32) * (column_width + padding), 0.0),
bounding_size: vec2(0.0, 0.0),
available_space: vec2(column_width, self.available_space.y),
})
.collect();
let result = add_contents(&mut columns[..]);
let mut max_height = 0.0;
for region in columns {
let size = region.bounding_size;
max_height = size.y.max(max_height);
}
2019-01-14 13:26:02 +00:00
self.reserve_space_without_padding(vec2(self.available_space.x, max_height));
2019-01-07 07:54:37 +00:00
result
}
2018-12-26 09:46:23 +00:00
// ------------------------------------------------------------------------
2018-12-26 14:28:38 +00:00
pub fn add<W: Widget>(&mut self, widget: W) -> GuiResponse {
widget.add_to(self)
}
// ------------------------------------------------------------------------
2019-01-14 13:26:02 +00:00
pub fn reserve_space(&mut self, size: Vec2, interaction_id: Option<Id>) -> InteractInfo {
2018-12-27 18:35:02 +00:00
let rect = Rect {
2019-01-06 15:34:01 +00:00
pos: self.cursor,
2018-12-27 18:35:02 +00:00
size,
};
2019-01-14 13:26:02 +00:00
self.reserve_space_without_padding(size + self.options().item_spacing);
2019-01-06 15:34:01 +00:00
let hovered = rect.contains(self.input().mouse_pos);
let clicked = hovered && self.input().mouse_clicked;
2018-12-28 22:53:15 +00:00
let active = if interaction_id.is_some() {
2019-01-07 07:54:37 +00:00
let mut memory = self.data.memory.lock().unwrap();
2018-12-28 22:53:15 +00:00
if clicked {
2019-01-07 07:54:37 +00:00
memory.active_id = interaction_id;
2018-12-28 22:53:15 +00:00
}
2019-01-07 07:54:37 +00:00
memory.active_id == interaction_id
2018-12-28 22:53:15 +00:00
} else {
false
};
2018-12-26 16:01:46 +00:00
2019-01-14 13:26:02 +00:00
InteractInfo {
rect,
2018-12-26 16:01:46 +00:00
hovered,
clicked,
active,
2019-01-14 13:26:02 +00:00
}
2018-12-26 16:01:46 +00:00
}
// TODO: Return a Rect
2019-01-06 15:34:01 +00:00
/// Reserve this much space and move the cursor.
2019-01-14 13:26:02 +00:00
pub fn reserve_space_without_padding(&mut self, size: Vec2) {
2019-01-06 15:34:01 +00:00
if self.dir == Direction::Horizontal {
self.cursor.x += size.x;
self.available_space.x -= size.x;
self.bounding_size.x += size.x;
self.bounding_size.y = self.bounding_size.y.max(size.y);
2019-01-06 15:34:01 +00:00
} else {
self.cursor.y += size.y;
self.available_space.y -= size.x;
self.bounding_size.y += size.y;
self.bounding_size.x = self.bounding_size.x.max(size.x);
2019-01-06 15:34:01 +00:00
}
}
pub fn make_child_id<H: Hash>(&self, child_id: &H) -> Id {
2018-12-26 14:28:38 +00:00
use std::hash::Hasher;
let mut hasher = std::collections::hash_map::DefaultHasher::new();
2018-12-27 22:26:05 +00:00
hasher.write_u64(self.id);
2019-01-07 07:54:37 +00:00
child_id.hash(&mut hasher);
2018-12-26 14:28:38 +00:00
hasher.finish()
}
pub fn combined_id(&self, child_id: Option<Id>) -> Option<Id> {
child_id.map(|child_id| {
use std::hash::Hasher;
let mut hasher = std::collections::hash_map::DefaultHasher::new();
hasher.write_u64(self.id);
child_id.hash(&mut hasher);
hasher.finish()
})
}
2019-01-12 23:55:56 +00:00
pub fn add_text(&mut self, pos: Vec2, text_style: TextStyle, text: Vec<TextFragment>) {
2018-12-27 22:26:05 +00:00
for fragment in text {
2019-01-06 15:34:01 +00:00
self.add_graphic(GuiCmd::Text {
2019-01-05 14:28:07 +00:00
pos: pos + vec2(0.0, fragment.y_offset),
2019-01-12 23:55:56 +00:00
text_style,
2018-12-27 22:26:05 +00:00
text: fragment.text,
2019-01-05 14:28:07 +00:00
x_offsets: fragment.x_offsets,
2018-12-27 22:26:05 +00:00
});
}
2018-12-26 14:28:38 +00:00
}
2018-12-28 22:53:15 +00:00
pub fn response(&mut self, interact: InteractInfo) -> GuiResponse {
2019-01-14 13:26:02 +00:00
// TODO: unify GuiResponse and InteractInfo. They are the same thing!
2018-12-28 22:53:15 +00:00
GuiResponse {
hovered: interact.hovered,
clicked: interact.clicked,
active: interact.active,
2019-01-14 13:26:02 +00:00
rect: interact.rect,
2019-01-07 07:54:37 +00:00
data: self.data.clone(),
2018-12-28 22:53:15 +00:00
}
}
2018-12-26 09:46:23 +00:00
}