diff --git a/Cargo.lock b/Cargo.lock index 522abc99..1f650f2c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -756,7 +756,9 @@ name = "egui" version = "0.11.0" dependencies = [ "epaint", + "ron", "serde", + "serde_json", ] [[package]] diff --git a/egui/Cargo.toml b/egui/Cargo.toml index cd2bfecf..88784c9f 100644 --- a/egui/Cargo.toml +++ b/egui/Cargo.toml @@ -22,6 +22,7 @@ include = [ [dependencies] epaint = { version = "0.11.0", path = "../epaint", default-features = false } serde = { version = "1", features = ["derive", "rc"], optional = true } +ron = { version = "0.6.4", optional = true } [features] default = ["default_fonts", "single_threaded"] @@ -30,8 +31,11 @@ default = ["default_fonts", "single_threaded"] # If you plan on specifying your own fonts you may disable this feature. default_fonts = ["epaint/default_fonts"] -persistence = ["serde", "epaint/persistence"] +persistence = ["serde", "epaint/persistence", "ron"] # Only needed if you plan to use the same egui::Context from multiple threads. single_threaded = ["epaint/single_threaded"] multi_threaded = ["epaint/multi_threaded"] + +[dev-dependencies] +serde_json = "1" \ No newline at end of file diff --git a/egui/src/any/any_map.rs b/egui/src/any/any_map.rs new file mode 100644 index 00000000..106c4842 --- /dev/null +++ b/egui/src/any/any_map.rs @@ -0,0 +1,205 @@ +use crate::any::element::{AnyMapElement, AnyMapTrait}; +use std::any::TypeId; +use std::collections::HashMap; +use std::hash::Hash; + +/// Stores any object by `Key`. +#[derive(Clone, Debug)] +pub struct AnyMap(HashMap); + +impl Default for AnyMap { + fn default() -> Self { + AnyMap(HashMap::new()) + } +} + +// ---------------------------------------------------------------------------- + +impl AnyMap { + pub fn get(&mut self, key: &Key) -> Option<&T> { + self.get_mut(key).map(|x| &*x) + } + + pub fn get_mut(&mut self, key: &Key) -> Option<&mut T> { + self.0.get_mut(key)?.get_mut() + } +} + +impl AnyMap { + pub fn get_or_insert_with( + &mut self, + key: Key, + or_insert_with: impl FnOnce() -> T, + ) -> &T { + &*self.get_mut_or_insert_with(key, or_insert_with) + } + + pub fn get_or_default(&mut self, key: Key) -> &T { + self.get_or_insert_with(key, Default::default) + } + + pub fn get_mut_or_insert_with( + &mut self, + key: Key, + or_insert_with: impl FnOnce() -> T, + ) -> &mut T { + use std::collections::hash_map::Entry; + match self.0.entry(key) { + Entry::Vacant(vacant) => vacant + .insert(AnyMapElement::new(or_insert_with())) + .get_mut() + .unwrap(), // this unwrap will never panic, because we insert correct type right now + Entry::Occupied(occupied) => occupied.into_mut().get_mut_or_set_with(or_insert_with), + } + } + + pub fn get_mut_or_default(&mut self, key: Key) -> &mut T { + self.get_mut_or_insert_with(key, Default::default) + } +} + +impl AnyMap { + pub fn insert(&mut self, key: Key, element: T) { + self.0.insert(key, AnyMapElement::new(element)); + } + + pub fn remove(&mut self, key: &Key) { + self.0.remove(key); + } + + pub fn remove_by_type(&mut self) { + let key = TypeId::of::(); + self.0.retain(|_, v| v.type_id() != key); + } + + pub fn clear(&mut self) { + self.0.clear(); + } +} + +impl AnyMap { + /// You could use this function to find is there some leak or misusage. + pub fn count(&mut self) -> usize { + let key = TypeId::of::(); + self.0.iter().filter(|(_, v)| v.type_id() == key).count() + } + + pub fn count_all(&mut self) -> usize { + self.0.len() + } +} + +// ---------------------------------------------------------------------------- + +#[cfg(test)] +#[test] +fn basic_usage() { + #[derive(Debug, Clone, Eq, PartialEq, Default)] + struct State { + a: i32, + } + + let mut map: AnyMap = Default::default(); + + assert!(map.get::(&0).is_none()); + map.insert(0, State { a: 42 }); + + assert_eq!(*map.get::(&0).unwrap(), State { a: 42 }); + assert!(map.get::(&1).is_none()); + map.get_mut::(&0).unwrap().a = 43; + assert_eq!(*map.get::(&0).unwrap(), State { a: 43 }); + + map.remove(&0); + assert!(map.get::(&0).is_none()); + + assert_eq!( + *map.get_or_insert_with(0, || State { a: 55 }), + State { a: 55 } + ); + map.remove(&0); + assert_eq!( + *map.get_mut_or_insert_with(0, || State { a: 56 }), + State { a: 56 } + ); + map.remove(&0); + assert_eq!(*map.get_or_default::(0), State { a: 0 }); + map.remove(&0); + assert_eq!(*map.get_mut_or_default::(0), State { a: 0 }); +} + +#[cfg(test)] +#[test] +fn different_type_same_id() { + #[derive(Debug, Clone, Eq, PartialEq, Default)] + struct State { + a: i32, + } + + let mut map: AnyMap = Default::default(); + + map.insert(0, State { a: 42 }); + + assert_eq!(*map.get::(&0).unwrap(), State { a: 42 }); + assert!(map.get::(&0).is_none()); + + map.insert(0, 255i32); + + assert_eq!(*map.get::(&0).unwrap(), 255); + assert!(map.get::(&0).is_none()); +} + +#[cfg(test)] +#[test] +fn cloning() { + #[derive(Debug, Clone, Eq, PartialEq, Default)] + struct State { + a: i32, + } + + let mut map: AnyMap = Default::default(); + + map.insert(0, State::default()); + map.insert(10, 10i32); + map.insert(11, 11i32); + + let mut cloned_map = map.clone(); + + map.insert(12, 12i32); + map.insert(1, State { a: 10 }); + + assert_eq!(*cloned_map.get::(&0).unwrap(), State { a: 0 }); + assert!(cloned_map.get::(&1).is_none()); + assert_eq!(*cloned_map.get::(&10).unwrap(), 10i32); + assert_eq!(*cloned_map.get::(&11).unwrap(), 11i32); + assert!(cloned_map.get::(&12).is_none()); +} + +#[cfg(test)] +#[test] +fn counting() { + #[derive(Debug, Clone, Eq, PartialEq, Default)] + struct State { + a: i32, + } + + let mut map: AnyMap = Default::default(); + + map.insert(0, State::default()); + map.insert(1, State { a: 10 }); + map.insert(10, 10i32); + map.insert(11, 11i32); + map.insert(12, 12i32); + + assert_eq!(map.count::(), 2); + assert_eq!(map.count::(), 3); + + map.remove_by_type::(); + + assert_eq!(map.count::(), 0); + assert_eq!(map.count::(), 3); + + map.clear(); + + assert_eq!(map.count::(), 0); + assert_eq!(map.count::(), 0); +} diff --git a/egui/src/any/element.rs b/egui/src/any/element.rs new file mode 100644 index 00000000..9e41f715 --- /dev/null +++ b/egui/src/any/element.rs @@ -0,0 +1,61 @@ +use std::any::{Any, TypeId}; +use std::fmt; + +/// Like [`std::any::Any`], but also implements `Clone`. +pub(crate) struct AnyMapElement { + value: Box, + clone_fn: fn(&Box) -> Box, +} + +impl fmt::Debug for AnyMapElement { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("AnyMapElement") + .field("value_type_id", &self.type_id()) + .finish() + } +} + +impl Clone for AnyMapElement { + fn clone(&self) -> Self { + AnyMapElement { + value: (self.clone_fn)(&self.value), + clone_fn: self.clone_fn, + } + } +} + +pub trait AnyMapTrait: 'static + Any + Clone {} + +impl AnyMapTrait for T {} + +impl AnyMapElement { + pub(crate) fn new(t: T) -> Self { + AnyMapElement { + value: Box::new(t), + clone_fn: |x| { + let x = x.downcast_ref::().unwrap(); // This unwrap will never panic, because we always construct this type using this `new` function and because we return &mut reference only with type `T`, so type cannot change. + Box::new(x.clone()) + }, + } + } + + pub(crate) fn type_id(&self) -> TypeId { + (*self.value).type_id() + } + + pub(crate) fn get_mut(&mut self) -> Option<&mut T> { + self.value.downcast_mut() + } + + pub(crate) fn get_mut_or_set_with( + &mut self, + set_with: impl FnOnce() -> T, + ) -> &mut T { + if !self.value.is::() { + *self = Self::new(set_with()); + // TODO: log this error, because it can occurs when user used same Id or same type for different widgets + } + + self.value.downcast_mut().unwrap() // This unwrap will never panic because we already converted object to required type + } +} diff --git a/egui/src/any/mod.rs b/egui/src/any/mod.rs new file mode 100644 index 00000000..1a98246f --- /dev/null +++ b/egui/src/any/mod.rs @@ -0,0 +1,61 @@ +//! Any-type storages for [`Memory`]. +//! +//! This module contains structs to store arbitrary types using [`Any`] trait. Also, they can be cloned, and structs in [`serializable`] can be de/serialized. +//! +//! All this is just `HashMap>` and `HashMap>`, but with helper functions and hacks for cloning and de/serialization. +//! +//! # Trait requirements +//! +//! If you want to store your type here, it must implement `Clone` and `Any` and be `'static`, which means it must not contain references. If you want to store your data in serializable storage, it must implement `serde::Serialize` and `serde::Deserialize` under the `persistent` feature. +//! +//! # [`TypeMap`] +//! +//! It stores everything by just type. You should use this map for your widget when all instances of your widgets can have only one state. E.g. for popup windows, for color picker. +//! +//! To not have intersections, you should create newtype for anything you try to store here, like: +//! ```rust +//! struct MyEditBool(pub bool); +//! ``` +//! +//! # [`AnyMap`] +//! +//! In [`Memory`] `Key` = [`Id`]. +//! +//! [`TypeMap`] and [`AnyMap`] has a quite similar interface, except for [`AnyMap`] you should pass `Key` to get and insert things. +//! +//! It stores everything by `Key`, this should be used when your widget can have different data for different instances of the widget. +//! +//! # `serializable` +//! +//! [`TypeMap`] and [`serializable::TypeMap`] has exactly the same interface, but [`serializable::TypeMap`] only requires serde traits for stored object under `persistent` feature. Same thing for [`AnyMap`] and [`serializable::AnyMap`]. +//! +//! # What could break +//! +//! Things here could break only when you trying to load this from file. +//! +//! First, serialized `TypeId` in [`serializable::TypeMap`] could broke if you updated the version of the Rust compiler between runs. +//! +//! Second, count and reset all instances of a type in [`serializable::AnyMap`] could return an incorrect value for the same reason. +//! +//! Deserialization errors of loaded elements of these storages can be determined only when you call `get_...` functions, they not logged and not provided to a user, on this errors value is just replaced with `or_insert()`/default value. +//! +//! # When not to use this +//! +//! This is not for important widget data. Some errors are just ignored and the correct value of type is inserted when you call. This is done to more simple interface. +//! +//! You shouldn't use any map here when you need very reliable state storage with rich error-handling. For this purpose you should create your own `Memory` struct and pass it everywhere you need it. Then, you should de/serialize it by yourself, handling all serialization or other errors as you wish. +//! +//! [`Id`]: crate::Id +//! [`Memory`]: crate::Memory +//! [`Any`]: std::any::Any +//! [`AnyMap`]: crate::any::AnyMap + +mod any_map; +mod element; +mod type_map; + +/// Same structs and traits, but also can be de/serialized under `persistence` feature. +#[cfg(feature = "persistence")] +pub mod serializable; + +pub use self::{any_map::AnyMap, element::AnyMapTrait, type_map::TypeMap}; diff --git a/egui/src/any/serializable/any_map.rs b/egui/src/any/serializable/any_map.rs new file mode 100644 index 00000000..5b11d116 --- /dev/null +++ b/egui/src/any/serializable/any_map.rs @@ -0,0 +1,263 @@ +use crate::any::serializable::element::{AnyMapElement, AnyMapTrait}; +use crate::any::serializable::type_id::TypeId; +use serde::{Deserialize, Serialize}; +use std::collections::HashMap; +use std::hash::Hash; + +/// Stores any object by `Key`, and can be de/serialized. +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct AnyMap(HashMap); + +impl Default for AnyMap { + fn default() -> Self { + AnyMap(HashMap::new()) + } +} + +// ---------------------------------------------------------------------------- + +impl AnyMap { + pub fn get(&mut self, key: &Key) -> Option<&T> { + self.get_mut(key).map(|x| &*x) + } + + pub fn get_mut(&mut self, key: &Key) -> Option<&mut T> { + self.0.get_mut(key)?.get_mut() + } +} + +impl AnyMap { + pub fn get_or_insert_with( + &mut self, + key: Key, + or_insert_with: impl FnOnce() -> T, + ) -> &T { + &*self.get_mut_or_insert_with(key, or_insert_with) + } + + pub fn get_or_default(&mut self, key: Key) -> &T { + self.get_or_insert_with(key, Default::default) + } + + pub fn get_mut_or_insert_with( + &mut self, + key: Key, + or_insert_with: impl FnOnce() -> T, + ) -> &mut T { + use std::collections::hash_map::Entry; + match self.0.entry(key) { + Entry::Vacant(vacant) => vacant + .insert(AnyMapElement::new(or_insert_with())) + .get_mut() + .unwrap(), // this unwrap will never panic, because we insert correct type right now + Entry::Occupied(occupied) => occupied.into_mut().get_mut_or_set_with(or_insert_with), + } + } + + pub fn get_mut_or_default(&mut self, key: Key) -> &mut T { + self.get_mut_or_insert_with(key, Default::default) + } +} + +impl AnyMap { + pub fn insert(&mut self, key: Key, element: T) { + self.0.insert(key, AnyMapElement::new(element)); + } + + pub fn remove(&mut self, key: &Key) { + self.0.remove(key); + } + + /// Note that this function could not remove all needed types between runs because if you upgraded the Rust version or for other reasons. + pub fn remove_by_type(&mut self) { + let key = TypeId::of::(); + self.0.retain(|_, v| v.type_id() != key); + } + + pub fn clear(&mut self) { + self.0.clear(); + } +} + +impl AnyMap { + /// You could use this function to find is there some leak or misusage. Note, that result of this function could break between runs, if you upgraded the Rust version or for other reasons. + pub fn count(&mut self) -> usize { + let key = TypeId::of::(); + self.0.iter().filter(|(_, v)| v.type_id() == key).count() + } + + pub fn count_all(&mut self) -> usize { + self.0.len() + } +} + +// ---------------------------------------------------------------------------- + +#[test] +fn discard_different_struct() { + use serde::{Deserialize, Serialize}; + + #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] + struct State1 { + a: i32, + } + + #[derive(Clone, Debug, Serialize, Deserialize)] + struct State2 { + b: String, + } + + let file_string = { + let mut map: AnyMap = Default::default(); + map.insert(1, State1 { a: 42 }); + serde_json::to_string(&map).unwrap() + }; + + let mut map: AnyMap = serde_json::from_str(&file_string).unwrap(); + assert!(map.get::(&1).is_none()); + assert_eq!(map.get::(&1), Some(&State1 { a: 42 })); +} + +#[test] +fn new_field_between_runs() { + use serde::{Deserialize, Serialize}; + + #[derive(Clone, Debug, Serialize, Deserialize)] + struct State { + a: i32, + } + + #[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)] + struct StateNew { + a: i32, + + #[serde(default)] + b: String, + } + + let file_string = { + let mut map: AnyMap = Default::default(); + map.insert(1, State { a: 42 }); + serde_json::to_string(&map).unwrap() + }; + + let mut map: AnyMap = serde_json::from_str(&file_string).unwrap(); + assert_eq!( + map.get::(&1), + Some(&StateNew { + a: 42, + b: String::default() + }) + ); +} + +// ---------------------------------------------------------------------------- + +#[test] +fn basic_usage() { + #[derive(Debug, Clone, Eq, PartialEq, Default, Deserialize, Serialize)] + struct State { + a: i32, + } + + let mut map: AnyMap = Default::default(); + + assert!(map.get::(&0).is_none()); + map.insert(0, State { a: 42 }); + + assert_eq!(*map.get::(&0).unwrap(), State { a: 42 }); + assert!(map.get::(&1).is_none()); + map.get_mut::(&0).unwrap().a = 43; + assert_eq!(*map.get::(&0).unwrap(), State { a: 43 }); + + map.remove(&0); + assert!(map.get::(&0).is_none()); + + assert_eq!( + *map.get_or_insert_with(0, || State { a: 55 }), + State { a: 55 } + ); + map.remove(&0); + assert_eq!( + *map.get_mut_or_insert_with(0, || State { a: 56 }), + State { a: 56 } + ); + map.remove(&0); + assert_eq!(*map.get_or_default::(0), State { a: 0 }); + map.remove(&0); + assert_eq!(*map.get_mut_or_default::(0), State { a: 0 }); +} + +#[test] +fn different_type_same_id() { + #[derive(Debug, Clone, Eq, PartialEq, Default, Deserialize, Serialize)] + struct State { + a: i32, + } + + let mut map: AnyMap = Default::default(); + + map.insert(0, State { a: 42 }); + + assert_eq!(*map.get::(&0).unwrap(), State { a: 42 }); + assert!(map.get::(&0).is_none()); + + map.insert(0, 255i32); + + assert_eq!(*map.get::(&0).unwrap(), 255); + assert!(map.get::(&0).is_none()); +} + +#[test] +fn cloning() { + #[derive(Debug, Clone, Eq, PartialEq, Default, Deserialize, Serialize)] + struct State { + a: i32, + } + + let mut map: AnyMap = Default::default(); + + map.insert(0, State::default()); + map.insert(10, 10i32); + map.insert(11, 11i32); + + let mut cloned_map = map.clone(); + + map.insert(12, 12i32); + map.insert(1, State { a: 10 }); + + assert_eq!(*cloned_map.get::(&0).unwrap(), State { a: 0 }); + assert!(cloned_map.get::(&1).is_none()); + assert_eq!(*cloned_map.get::(&10).unwrap(), 10i32); + assert_eq!(*cloned_map.get::(&11).unwrap(), 11i32); + assert!(cloned_map.get::(&12).is_none()); +} + +#[test] +fn counting() { + #[derive(Debug, Clone, Eq, PartialEq, Default, Deserialize, Serialize)] + struct State { + a: i32, + } + + let mut map: AnyMap = Default::default(); + + map.insert(0, State::default()); + map.insert(1, State { a: 10 }); + map.insert(10, 10i32); + map.insert(11, 11i32); + map.insert(12, 12i32); + + assert_eq!(map.count::(), 2); + assert_eq!(map.count::(), 3); + + map.remove_by_type::(); + + assert_eq!(map.count::(), 0); + assert_eq!(map.count::(), 3); + + map.clear(); + + assert_eq!(map.count::(), 0); + assert_eq!(map.count::(), 0); +} diff --git a/egui/src/any/serializable/element.rs b/egui/src/any/serializable/element.rs new file mode 100644 index 00000000..eb980c25 --- /dev/null +++ b/egui/src/any/serializable/element.rs @@ -0,0 +1,149 @@ +use crate::any::serializable::type_id::TypeId; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; +use std::any::Any; +use std::fmt; +use AnyMapElementInner::{Deserialized, Serialized}; + +pub(crate) struct AnyMapElement(AnyMapElementInner); + +enum AnyMapElementInner { + Deserialized { + value: Box, + clone_fn: fn(&Box) -> Box, + + serialize_fn: fn(&Box) -> Result, + }, + Serialized(String, TypeId), +} + +#[derive(Deserialize, Serialize)] +struct AnyMapElementInnerSer(String, TypeId); + +impl Serialize for AnyMapElement { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let inner = match &self.0 { + Deserialized { + value, + serialize_fn, + .. + } => { + let s = serialize_fn(value).map_err(serde::ser::Error::custom)?; + AnyMapElementInnerSer(s, self.type_id()) + } + Serialized(s, id) => AnyMapElementInnerSer(s.clone(), *id), + }; + + inner.serialize(serializer) + } +} + +impl<'de> Deserialize<'de> for AnyMapElement { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let AnyMapElementInnerSer(s, id) = AnyMapElementInnerSer::deserialize(deserializer)?; + + Ok(AnyMapElement(Serialized(s, id))) + } +} + +impl fmt::Debug for AnyMapElement { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match &self.0 { + Deserialized { value, .. } => f + .debug_struct("AnyMapElement_Deserialized") + .field("value_type_id", &value.type_id()) + .finish(), + Serialized(s, id) => f + .debug_tuple("AnyMapElement_Serialized") + .field(&s) + .field(&id) + .finish(), + } + } +} + +impl Clone for AnyMapElement { + fn clone(&self) -> Self { + match &self.0 { + Deserialized { + value, + clone_fn, + serialize_fn, + } => AnyMapElement(Deserialized { + value: clone_fn(value), + clone_fn: *clone_fn, + serialize_fn: *serialize_fn, + }), + Serialized(s, id) => AnyMapElement(Serialized(s.clone(), *id)), + } + } +} + +pub trait AnyMapTrait: 'static + Any + Clone + Serialize + for<'a> Deserialize<'a> {} +impl Deserialize<'a>> AnyMapTrait for T {} + +impl AnyMapElement { + pub(crate) fn new(t: T) -> Self { + AnyMapElement(Deserialized { + value: Box::new(t), + clone_fn: |x| { + let x = x.downcast_ref::().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()) + }, + + serialize_fn: |x| { + let x = x.downcast_ref::().unwrap(); // This will never panic too, for same reason. + ron::to_string(x) + }, + }) + } + + pub(crate) fn type_id(&self) -> TypeId { + match self { + AnyMapElement(Deserialized { value, .. }) => (**value).type_id().into(), + AnyMapElement(Serialized(_, id)) => *id, + } + } + + pub(crate) fn get_mut(&mut self) -> Option<&mut T> { + match self { + AnyMapElement(Deserialized { value, .. }) => value.downcast_mut(), + AnyMapElement(Serialized(s, _)) => { + *self = Self::new(ron::from_str::(s).ok()?); + + match self { + AnyMapElement(Deserialized { value, .. }) => value.downcast_mut(), + AnyMapElement(Serialized(_, _)) => unreachable!(), + } + } + } + } + + pub(crate) fn get_mut_or_set_with( + &mut self, + set_with: impl FnOnce() -> T, + ) -> &mut T { + match &mut self.0 { + Deserialized { value, .. } => { + if !value.is::() { + *self = Self::new(set_with()); + // TODO: log this error, because it can occurs when user used same Id or same type for different widgets + } + } + Serialized(s, _) => { + *self = Self::new(ron::from_str::(s).unwrap_or_else(|_| set_with())); + // TODO: log deserialization error + } + } + + match &mut self.0 { + Deserialized { value, .. } => value.downcast_mut().unwrap(), // This unwrap will never panic because we already converted object to required type + Serialized(_, _) => unreachable!(), + } + } +} diff --git a/egui/src/any/serializable/mod.rs b/egui/src/any/serializable/mod.rs new file mode 100644 index 00000000..958f6a84 --- /dev/null +++ b/egui/src/any/serializable/mod.rs @@ -0,0 +1,6 @@ +mod any_map; +mod element; +mod type_id; +mod type_map; + +pub use self::{any_map::AnyMap, element::AnyMapTrait, type_map::TypeMap}; diff --git a/egui/src/any/serializable/type_id.rs b/egui/src/any/serializable/type_id.rs new file mode 100644 index 00000000..320e726e --- /dev/null +++ b/egui/src/any/serializable/type_id.rs @@ -0,0 +1,23 @@ +use std::any::Any; + +/// We need this because `TypeId` can't be deserialized or serialized directly, but this can be done using hashing. However, there is a small possibility that different types will have intersection by hashes of their type ids. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)] +#[cfg_attr(feature = "persistence", derive(serde::Deserialize, serde::Serialize))] +pub struct TypeId(u64); + +impl TypeId { + pub fn of() -> Self { + std::any::TypeId::of::().into() + } +} + +impl From for TypeId { + fn from(id: std::any::TypeId) -> Self { + use std::collections::hash_map::DefaultHasher; + use std::hash::{Hash, Hasher}; + + let mut hasher = DefaultHasher::new(); + id.hash(&mut hasher); + Self(hasher.finish()) + } +} diff --git a/egui/src/any/serializable/type_map.rs b/egui/src/any/serializable/type_map.rs new file mode 100644 index 00000000..b4d019d2 --- /dev/null +++ b/egui/src/any/serializable/type_map.rs @@ -0,0 +1,203 @@ +use crate::any::serializable::element::{AnyMapElement, AnyMapTrait}; +use crate::any::serializable::type_id::TypeId; +use serde::{Deserialize, Serialize}; +use std::collections::HashMap; + +/// Maps types to a single instance of that type. +/// +/// Used to store state per widget type. In effect a sort of singleton storage. +/// Similar to [the `typemap` crate](https://docs.rs/typemap/0.3.3/typemap/) but allows serialization. +#[derive(Clone, Debug, Default, Deserialize, Serialize)] +pub struct TypeMap(HashMap); + +// ---------------------------------------------------------------------------- + +impl TypeMap { + pub fn get(&mut self) -> Option<&T> { + self.get_mut().map(|x| &*x) + } + + pub fn get_mut(&mut self) -> Option<&mut T> { + self.0.get_mut(&TypeId::of::())?.get_mut() + } +} + +impl TypeMap { + pub fn get_or_insert_with(&mut self, or_insert_with: impl FnOnce() -> T) -> &T { + &*self.get_mut_or_insert_with(or_insert_with) + } + + pub fn get_or_default(&mut self) -> &T { + self.get_or_insert_with(Default::default) + } + + pub fn get_mut_or_insert_with( + &mut self, + or_insert_with: impl FnOnce() -> T, + ) -> &mut T { + use std::collections::hash_map::Entry; + match self.0.entry(TypeId::of::()) { + Entry::Vacant(vacant) => vacant + .insert(AnyMapElement::new(or_insert_with())) + .get_mut() + .unwrap(), // this unwrap will never panic, because we insert correct type right now + Entry::Occupied(occupied) => occupied.into_mut().get_mut_or_set_with(or_insert_with), + } + } + + pub fn get_mut_or_default(&mut self) -> &mut T { + self.get_mut_or_insert_with(Default::default) + } +} + +impl TypeMap { + pub fn insert(&mut self, element: T) { + self.0 + .insert(TypeId::of::(), AnyMapElement::new(element)); + } + + pub fn remove(&mut self) { + self.0.remove(&TypeId::of::()); + } + + pub fn clear(&mut self) { + self.0.clear(); + } +} + +// ---------------------------------------------------------------------------- + +#[test] +fn discard_different_struct() { + #[derive(Clone, Debug, Serialize, Deserialize)] + struct State1 { + a: i32, + } + + #[derive(Clone, Debug, Serialize, Deserialize)] + struct State2 { + a: String, + } + + let file_string = { + let mut map: TypeMap = Default::default(); + map.insert(State1 { a: 42 }); + serde_json::to_string(&map).unwrap() + }; + + let mut map: TypeMap = serde_json::from_str(&file_string).unwrap(); + assert!(map.get::().is_none()); +} + +#[test] +fn new_field_between_runs() { + #[derive(Clone, Debug, Serialize, Deserialize)] + struct State { + a: i32, + } + + #[derive(Clone, Debug, Serialize, Deserialize)] + struct StateNew { + a: i32, + + #[serde(default)] + b: i32, + } + + let file_string = { + let mut map: TypeMap = Default::default(); + map.insert(State { a: 42 }); + serde_json::to_string(&map).unwrap() + }; + + let mut map: TypeMap = serde_json::from_str(&file_string).unwrap(); + assert!(map.get::().is_none()); +} + +// ---------------------------------------------------------------------------- + +#[cfg(test)] +#[test] +fn basic_usage() { + #[derive(Debug, Clone, Eq, PartialEq, Default, Serialize, Deserialize)] + struct State { + a: i32, + } + + let mut map = TypeMap::default(); + + assert!(map.get::().is_none()); + map.insert(State { a: 42 }); + map.insert(5i32); + map.insert((6.0f32, -1i16)); + + assert_eq!(*map.get::().unwrap(), State { a: 42 }); + map.get_mut::().unwrap().a = 43; + assert_eq!(*map.get::().unwrap(), State { a: 43 }); + + map.remove::(); + assert!(map.get::().is_none()); + + assert_eq!(*map.get_or_insert_with(|| State { a: 55 }), State { a: 55 }); + map.remove::(); + assert_eq!( + *map.get_mut_or_insert_with(|| State { a: 56 }), + State { a: 56 } + ); + map.remove::(); + assert_eq!(*map.get_or_default::(), State { a: 0 }); + map.remove::(); + assert_eq!(*map.get_mut_or_default::(), State { a: 0 }); +} + +#[cfg(test)] +#[test] +fn cloning() { + #[derive(Debug, Clone, Eq, PartialEq, Default, Serialize, Deserialize)] + struct State { + a: i32, + } + + let mut map: TypeMap = Default::default(); + + map.insert(State::default()); + map.insert(10i32); + + let mut cloned_map = map.clone(); + + map.insert(11.5f32); + map.insert("aoeu".to_string()); + + assert_eq!(*cloned_map.get::().unwrap(), State { a: 0 }); + assert_eq!(*cloned_map.get::().unwrap(), 10i32); + assert!(cloned_map.get::().is_none()); + assert!(cloned_map.get::().is_none()); +} + +#[cfg(test)] +#[test] +fn removing() { + #[derive(Debug, Clone, Eq, PartialEq, Default, Serialize, Deserialize)] + struct State { + a: i32, + } + + let mut map: TypeMap = Default::default(); + + map.insert(State::default()); + map.insert(10i32); + map.insert(11.5f32); + map.insert("aoeu".to_string()); + + map.remove::(); + assert!(map.get::().is_none()); + assert!(map.get::().is_some()); + assert!(map.get::().is_some()); + assert!(map.get::().is_some()); + + map.clear(); + assert!(map.get::().is_none()); + assert!(map.get::().is_none()); + assert!(map.get::().is_none()); + assert!(map.get::().is_none()); +} diff --git a/egui/src/any/type_map.rs b/egui/src/any/type_map.rs new file mode 100644 index 00000000..6ac8cbd6 --- /dev/null +++ b/egui/src/any/type_map.rs @@ -0,0 +1,153 @@ +use crate::any::element::{AnyMapElement, AnyMapTrait}; +use std::any::TypeId; +use std::collections::HashMap; + +/// Maps types to a single instance of that type. +/// +/// Used to store state per widget type. In effect a sort of singleton storage. +/// Similar to [the `typemap` crate](https://docs.rs/typemap/0.3.3/typemap/). +#[derive(Clone, Debug, Default)] +pub struct TypeMap(HashMap); + +// ---------------------------------------------------------------------------- + +impl TypeMap { + pub fn get(&mut self) -> Option<&T> { + self.get_mut().map(|x| &*x) + } + + pub fn get_mut(&mut self) -> Option<&mut T> { + self.0.get_mut(&TypeId::of::())?.get_mut() + } +} + +impl TypeMap { + pub fn get_or_insert_with(&mut self, or_insert_with: impl FnOnce() -> T) -> &T { + &*self.get_mut_or_insert_with(or_insert_with) + } + + pub fn get_or_default(&mut self) -> &T { + self.get_or_insert_with(Default::default) + } + + pub fn get_mut_or_insert_with( + &mut self, + or_insert_with: impl FnOnce() -> T, + ) -> &mut T { + use std::collections::hash_map::Entry; + match self.0.entry(TypeId::of::()) { + Entry::Vacant(vacant) => vacant + .insert(AnyMapElement::new(or_insert_with())) + .get_mut() + .unwrap(), // this unwrap will never panic, because we insert correct type right now + Entry::Occupied(occupied) => occupied.into_mut().get_mut_or_set_with(or_insert_with), + } + } + + pub fn get_mut_or_default(&mut self) -> &mut T { + self.get_mut_or_insert_with(Default::default) + } +} + +impl TypeMap { + pub fn insert(&mut self, element: T) { + self.0 + .insert(TypeId::of::(), AnyMapElement::new(element)); + } + + pub fn remove(&mut self) { + self.0.remove(&TypeId::of::()); + } + + pub fn clear(&mut self) { + self.0.clear(); + } +} + +// ---------------------------------------------------------------------------- + +#[cfg(test)] +#[test] +fn basic_usage() { + #[derive(Debug, Clone, Eq, PartialEq, Default)] + struct State { + a: i32, + } + + let mut map = TypeMap::default(); + + assert!(map.get::().is_none()); + map.insert(State { a: 42 }); + map.insert(5i32); + map.insert((6.0f32, -1i16)); + + assert_eq!(*map.get::().unwrap(), State { a: 42 }); + map.get_mut::().unwrap().a = 43; + assert_eq!(*map.get::().unwrap(), State { a: 43 }); + + map.remove::(); + assert!(map.get::().is_none()); + + assert_eq!(*map.get_or_insert_with(|| State { a: 55 }), State { a: 55 }); + map.remove::(); + assert_eq!( + *map.get_mut_or_insert_with(|| State { a: 56 }), + State { a: 56 } + ); + map.remove::(); + assert_eq!(*map.get_or_default::(), State { a: 0 }); + map.remove::(); + assert_eq!(*map.get_mut_or_default::(), State { a: 0 }); +} + +#[cfg(test)] +#[test] +fn cloning() { + #[derive(Debug, Clone, Eq, PartialEq, Default)] + struct State { + a: i32, + } + + let mut map: TypeMap = Default::default(); + + map.insert(State::default()); + map.insert(10i32); + + let mut cloned_map = map.clone(); + + map.insert(11.5f32); + map.insert("aoeu"); + + assert_eq!(*cloned_map.get::().unwrap(), State { a: 0 }); + assert_eq!(*cloned_map.get::().unwrap(), 10i32); + assert!(cloned_map.get::().is_none()); + assert!(cloned_map.get::<&'static str>().is_none()); +} + +#[cfg(test)] +#[test] +fn removing() { + #[derive(Debug, Clone, Eq, PartialEq, Default)] + struct State { + a: i32, + } + + let mut map: TypeMap = Default::default(); + + map.insert(State::default()); + map.insert(10i32); + map.insert(11.5f32); + map.insert("aoeu"); + + map.remove::(); + assert!(map.get::().is_none()); + assert!(map.get::().is_some()); + assert!(map.get::().is_some()); + assert!(map.get::<&'static str>().is_some()); + + map.clear(); + assert!(map.get::().is_none()); + assert!(map.get::().is_none()); + assert!(map.get::().is_none()); + assert!(map.get::<&'static str>().is_none()); +} diff --git a/egui/src/containers/collapsing_header.rs b/egui/src/containers/collapsing_header.rs index b5b68169..c05ef57a 100644 --- a/egui/src/containers/collapsing_header.rs +++ b/egui/src/containers/collapsing_header.rs @@ -24,7 +24,7 @@ impl Default for State { impl State { pub fn from_memory_with_default_open(ctx: &Context, id: Id, default_open: bool) -> Self { - *ctx.memory().collapsing_headers.entry(id).or_insert(State { + *ctx.memory().id_data.get_or_insert_with(id, || State { open: default_open, ..Default::default() }) @@ -36,8 +36,8 @@ impl State { Some(true) } else { ctx.memory() - .collapsing_headers - .get(&id) + .id_data + .get::(&id) .map(|state| state.open) } } @@ -295,7 +295,7 @@ impl CollapsingHeader { }) .inner }); - ui.memory().collapsing_headers.insert(id, state); + ui.memory().id_data.insert(id, state); if let Some(ret_response) = ret_response { CollapsingResponse { diff --git a/egui/src/containers/popup.rs b/egui/src/containers/popup.rs index 96c46a0f..8daf77c2 100644 --- a/egui/src/containers/popup.rs +++ b/egui/src/containers/popup.rs @@ -92,14 +92,19 @@ pub fn show_tooltip_at( return; // No good place for a tooltip :( }; - let expected_size = ctx.memory().tooltip.tooltip_size(id); + let expected_size = ctx + .memory() + .data_temp + .get_or_default::() + .tooltip_size(id); let expected_size = expected_size.unwrap_or_else(|| vec2(64.0, 32.0)); let position = position.min(ctx.input().screen_rect().right_bottom() - expected_size); let position = position.max(ctx.input().screen_rect().left_top()); let response = show_tooltip_area(ctx, id, position, add_contents); ctx.memory() - .tooltip + .data_temp + .get_mut_or_default::() .set_tooltip_size(id, response.rect.size()); ctx.frame_state().tooltip_rect = Some((id, tooltip_rect.union(response.rect))); diff --git a/egui/src/containers/resize.rs b/egui/src/containers/resize.rs index 22d64f60..11b8054c 100644 --- a/egui/src/containers/resize.rs +++ b/egui/src/containers/resize.rs @@ -159,7 +159,7 @@ impl Resize { ui.make_persistent_id(id_source) }); - let mut state = ui.memory().resize.get(&id).cloned().unwrap_or_else(|| { + let mut state = *ui.memory().id_data.get_or_insert_with(id, || { ui.ctx().request_repaint(); // counter frame delay let default_size = self @@ -297,7 +297,7 @@ impl Resize { } } - ui.memory().resize.insert(id, state); + ui.memory().id_data.insert(id, state); if ui.ctx().style().debug.show_resize { ui.ctx().debug_painter().debug_rect( diff --git a/egui/src/containers/scroll_area.rs b/egui/src/containers/scroll_area.rs index 1ed40941..e3fac236 100644 --- a/egui/src/containers/scroll_area.rs +++ b/egui/src/containers/scroll_area.rs @@ -98,12 +98,7 @@ impl ScrollArea { let id_source = id_source.unwrap_or_else(|| Id::new("scroll_area")); let id = ui.make_persistent_id(id_source); - let mut state = ctx - .memory() - .scroll_areas - .get(&id) - .cloned() - .unwrap_or_default(); + let mut state = *ctx.memory().id_data.get_or_default::(id); if let Some(offset) = offset { state.offset = offset; @@ -357,7 +352,7 @@ impl Prepared { state.offset.y = state.offset.y.max(0.0); state.show_scroll = show_scroll_this_frame; - ui.memory().scroll_areas.insert(id, state); + ui.memory().id_data.insert(id, state); } } diff --git a/egui/src/containers/window.rs b/egui/src/containers/window.rs index 117f8154..3d5b31ab 100644 --- a/egui/src/containers/window.rs +++ b/egui/src/containers/window.rs @@ -364,7 +364,7 @@ impl<'open> Window<'open> { area_content_ui .memory() - .collapsing_headers + .id_data .insert(collapsing_id, collapsing); if let Some(interaction) = interaction { @@ -458,9 +458,11 @@ fn interact( area_state.pos = new_rect.min; if window_interaction.is_resize() { - let mut resize_state = ctx.memory().resize.get(&resize_id).cloned().unwrap(); - resize_state.requested_size = Some(new_rect.size() - margins); - ctx.memory().resize.insert(resize_id, resize_state); + ctx.memory() + .id_data + .get_mut::(&resize_id) + .unwrap() + .requested_size = Some(new_rect.size() - margins); } ctx.memory().areas.move_to_top(area_layer_id); diff --git a/egui/src/context.rs b/egui/src/context.rs index cd37e9eb..bca7891e 100644 --- a/egui/src/context.rs +++ b/egui/src/context.rs @@ -856,31 +856,46 @@ impl Context { ui.horizontal(|ui| { ui.label(format!( "{} collapsing headers", - self.memory().collapsing_headers.len() + self.memory() + .id_data + .count::() )); if ui.button("Reset").clicked() { - self.memory().collapsing_headers = Default::default(); + self.memory() + .id_data + .remove_by_type::(); } }); ui.horizontal(|ui| { - ui.label(format!("{} menu bars", self.memory().menu_bar.len())); + ui.label(format!( + "{} menu bars", + self.memory().id_data_temp.count::() + )); if ui.button("Reset").clicked() { - self.memory().menu_bar = Default::default(); + self.memory() + .id_data_temp + .remove_by_type::(); } }); ui.horizontal(|ui| { - ui.label(format!("{} scroll areas", self.memory().scroll_areas.len())); + ui.label(format!( + "{} scroll areas", + self.memory().id_data.count::() + )); if ui.button("Reset").clicked() { - self.memory().scroll_areas = Default::default(); + self.memory().id_data.remove_by_type::(); } }); ui.horizontal(|ui| { - ui.label(format!("{} resize areas", self.memory().resize.len())); + ui.label(format!( + "{} resize areas", + self.memory().id_data.count::() + )); if ui.button("Reset").clicked() { - self.memory().resize = Default::default(); + self.memory().id_data.remove_by_type::(); } }); diff --git a/egui/src/grid.rs b/egui/src/grid.rs index e65aab91..b2c519e6 100644 --- a/egui/src/grid.rs +++ b/egui/src/grid.rs @@ -59,7 +59,7 @@ pub(crate) struct GridLayout { impl GridLayout { pub(crate) fn new(ui: &Ui, id: Id) -> Self { - let prev_state = ui.memory().grid.get(&id).cloned().unwrap_or_default(); + let prev_state = ui.memory().id_data.get_or_default::(id).clone(); // TODO: respect current layout @@ -212,7 +212,7 @@ impl GridLayout { if self.curr_state != self.prev_state { self.ctx .memory() - .grid + .id_data .insert(self.id, self.curr_state.clone()); self.ctx.request_repaint(); } diff --git a/egui/src/lib.rs b/egui/src/lib.rs index f89b5c5c..f1b2bd8a 100644 --- a/egui/src/lib.rs +++ b/egui/src/lib.rs @@ -289,6 +289,7 @@ #![allow(clippy::manual_range_contains)] mod animation_manager; +pub mod any; pub mod containers; mod context; mod data; diff --git a/egui/src/memory.rs b/egui/src/memory.rs index fd8698f6..b3f8dead 100644 --- a/egui/src/memory.rs +++ b/egui/src/memory.rs @@ -1,10 +1,6 @@ use std::collections::{HashMap, HashSet}; -use crate::{ - area, collapsing_header, menu, resize, scroll_area, util::Cache, widgets::text_edit, window, - Id, InputState, LayerId, Pos2, Rect, Style, -}; -use epaint::color::{Color32, Hsva}; +use crate::{any, area, window, Id, InputState, LayerId, Pos2, Rect, Style}; // ---------------------------------------------------------------------------- @@ -14,12 +10,38 @@ use epaint::color::{Color32, Hsva}; /// how far the user has scrolled in a `ScrollArea` etc. /// /// If you want this to persist when closing your app you should serialize `Memory` and store it. +/// +/// If you want to store data for your widgets, you should look at `data`/`data_temp` and `id_data`/`id_data_temp` fields, and read the documentation of [`any`] module. #[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 current states for widgets that don't require `Id`. This will be saved between different program runs if you use the `persistence` feature. + #[cfg(feature = "persistence")] + pub data: any::serializable::TypeMap, + + /// This map stores current states for widgets that don't require `Id`. This will be saved between different program runs if you use the `persistence` feature. + #[cfg(not(feature = "persistence"))] + pub data: any::TypeMap, + + /// Same as `data`, but this data will not be saved between runs. + #[cfg_attr(feature = "persistence", serde(skip))] + pub data_temp: any::TypeMap, + + /// This map stores current states for all widgets with custom `Id`s. This will be saved between different program runs if you use the `persistence` feature. + #[cfg(feature = "persistence")] + pub id_data: any::serializable::AnyMap, + + /// This map stores current states for all widgets with custom `Id`s. This will be saved between different program runs if you use the `persistence` feature. + #[cfg(not(feature = "persistence"))] + pub id_data: any::AnyMap, + + /// Same as `id_data`, but this data will not be saved between runs. + #[cfg_attr(feature = "persistence", serde(skip))] + pub id_data_temp: any::AnyMap, + /// new scale that will be applied at the start of the next frame pub(crate) new_pixels_per_point: Option, @@ -29,30 +51,14 @@ pub struct Memory { #[cfg_attr(feature = "persistence", serde(skip))] pub(crate) interaction: Interaction, - // states of various types of widgets - pub(crate) collapsing_headers: HashMap, - pub(crate) grid: HashMap, - #[cfg_attr(feature = "persistence", serde(skip))] - pub(crate) menu_bar: HashMap, - pub(crate) resize: HashMap, - pub(crate) scroll_areas: HashMap, - pub(crate) text_edit: HashMap, - #[cfg_attr(feature = "persistence", serde(skip))] pub(crate) window_interaction: Option, #[cfg_attr(feature = "persistence", serde(skip))] pub(crate) drag_value: crate::widgets::drag_value::MonoState, - #[cfg_attr(feature = "persistence", serde(skip))] - pub(crate) tooltip: crate::containers::popup::MonoState, - pub(crate) areas: Areas, - /// Used by color picker - #[cfg_attr(feature = "persistence", serde(skip))] - pub(crate) color_cache: Cache, - /// Which popup-window is open (if any)? /// Could be a combo box, color picker, menu etc. #[cfg_attr(feature = "persistence", serde(skip))] diff --git a/egui/src/menu.rs b/egui/src/menu.rs index 5b5bbecc..05e997f2 100644 --- a/egui/src/menu.rs +++ b/egui/src/menu.rs @@ -20,21 +20,19 @@ use epaint::Stroke; /// What is saved between frames. #[derive(Clone, Copy, Debug, Default)] +#[cfg_attr(feature = "persistence", derive(serde::Deserialize, serde::Serialize))] +#[cfg_attr(feature = "persistence", serde(default))] pub(crate) struct BarState { open_menu: Option, } impl BarState { fn load(ctx: &Context, bar_id: &Id) -> Self { - ctx.memory() - .menu_bar - .get(bar_id) - .cloned() - .unwrap_or_default() + *ctx.memory().id_data_temp.get_or_default(*bar_id) } fn save(self, ctx: &Context, bar_id: Id) { - ctx.memory().menu_bar.insert(bar_id, self); + ctx.memory().id_data_temp.insert(bar_id, self); } } diff --git a/egui/src/widgets/color_picker.rs b/egui/src/widgets/color_picker.rs index 9796cabc..a99be840 100644 --- a/egui/src/widgets/color_picker.rs +++ b/egui/src/widgets/color_picker.rs @@ -1,5 +1,6 @@ //! Color picker widgets. +use crate::util::Cache; use crate::*; use epaint::{color::*, *}; @@ -369,7 +370,8 @@ pub fn color_edit_button_srgba(ui: &mut Ui, srgba: &mut Color32, alpha: Alpha) - let mut hsva = ui .ctx() .memory() - .color_cache + .data_temp + .get_or_default::>() .get(srgba) .cloned() .unwrap_or_else(|| Hsva::from(*srgba)); @@ -378,7 +380,11 @@ pub fn color_edit_button_srgba(ui: &mut Ui, srgba: &mut Color32, alpha: Alpha) - *srgba = Color32::from(hsva); - ui.ctx().memory().color_cache.set(*srgba, hsva); + ui.ctx() + .memory() + .data_temp + .get_mut_or_default::>() + .set(*srgba, hsva); response } diff --git a/egui/src/widgets/text_edit.rs b/egui/src/widgets/text_edit.rs index 5d322578..ed83debb 100644 --- a/egui/src/widgets/text_edit.rs +++ b/egui/src/widgets/text_edit.rs @@ -144,8 +144,8 @@ pub struct TextEdit<'t> { impl<'t> TextEdit<'t> { pub fn cursor(ui: &Ui, id: Id) -> Option { ui.memory() - .text_edit - .get(&id) + .id_data + .get::(&id) .and_then(|state| state.cursorp) } } @@ -356,7 +356,7 @@ impl<'t> TextEdit<'t> { auto_id // Since we are only storing the cursor a persistent Id is not super important } }); - let mut state = ui.memory().text_edit.get(&id).cloned().unwrap_or_default(); + let mut state = ui.memory().id_data.get_or_default::(id).clone(); let sense = if enabled { Sense::click_and_drag() @@ -600,7 +600,7 @@ impl<'t> TextEdit<'t> { .galley(response.rect.min, galley, hint_text_color); } - ui.memory().text_edit.insert(id, state); + ui.memory().id_data.insert(id, state); response.widget_info(|| WidgetInfo::text_edit(&*text)); response