Merge branch 'zed2' into zed2-workspace
This commit is contained in:
@@ -4,7 +4,7 @@ use collections::{HashMap, HashSet};
|
||||
use serde::Deserialize;
|
||||
use std::any::{type_name, Any};
|
||||
|
||||
pub trait Action: Any + Send + Sync {
|
||||
pub trait Action: Any + Send {
|
||||
fn qualified_name() -> SharedString
|
||||
where
|
||||
Self: Sized;
|
||||
@@ -19,7 +19,7 @@ pub trait Action: Any + Send + Sync {
|
||||
|
||||
impl<A> Action for A
|
||||
where
|
||||
A: for<'a> Deserialize<'a> + PartialEq + Any + Send + Sync + Clone + Default,
|
||||
A: for<'a> Deserialize<'a> + PartialEq + Any + Send + Clone + Default,
|
||||
{
|
||||
fn qualified_name() -> SharedString {
|
||||
type_name::<A>().into()
|
||||
|
||||
+103
-32
@@ -23,7 +23,7 @@ use crate::{
|
||||
use anyhow::{anyhow, Result};
|
||||
use collections::{HashMap, HashSet, VecDeque};
|
||||
use futures::{future::BoxFuture, Future};
|
||||
use parking_lot::{Mutex, RwLock};
|
||||
use parking_lot::Mutex;
|
||||
use slotmap::SlotMap;
|
||||
use std::{
|
||||
any::{type_name, Any, TypeId},
|
||||
@@ -39,7 +39,10 @@ use util::http::{self, HttpClient};
|
||||
|
||||
pub struct App(Arc<Mutex<AppContext>>);
|
||||
|
||||
/// Represents an application before it is fully launched. Once your app is
|
||||
/// configured, you'll start the app with `App::run`.
|
||||
impl App {
|
||||
/// Builds an app with the given asset source.
|
||||
pub fn production(asset_source: Arc<dyn AssetSource>) -> Self {
|
||||
Self(AppContext::new(
|
||||
current_platform(),
|
||||
@@ -48,6 +51,8 @@ impl App {
|
||||
))
|
||||
}
|
||||
|
||||
/// Start the application. The provided callback will be called once the
|
||||
/// app is fully launched.
|
||||
pub fn run<F>(self, on_finish_launching: F)
|
||||
where
|
||||
F: 'static + FnOnce(&mut MainThread<AppContext>),
|
||||
@@ -61,6 +66,8 @@ impl App {
|
||||
}));
|
||||
}
|
||||
|
||||
/// Register a handler to be invoked when the platform instructs the application
|
||||
/// to open one or more URLs.
|
||||
pub fn on_open_urls<F>(&self, mut callback: F) -> &Self
|
||||
where
|
||||
F: 'static + FnMut(Vec<String>, &mut AppContext),
|
||||
@@ -110,11 +117,10 @@ impl App {
|
||||
|
||||
type ActionBuilder = fn(json: Option<serde_json::Value>) -> anyhow::Result<Box<dyn Action>>;
|
||||
type FrameCallback = Box<dyn FnOnce(&mut WindowContext) + Send>;
|
||||
type Handler = Box<dyn FnMut(&mut AppContext) -> bool + Send + Sync + 'static>;
|
||||
type Listener = Box<dyn FnMut(&dyn Any, &mut AppContext) -> bool + Send + Sync + 'static>;
|
||||
type QuitHandler =
|
||||
Box<dyn FnMut(&mut AppContext) -> BoxFuture<'static, ()> + Send + Sync + 'static>;
|
||||
type ReleaseListener = Box<dyn FnMut(&mut dyn Any, &mut AppContext) + Send + Sync + 'static>;
|
||||
type Handler = Box<dyn FnMut(&mut AppContext) -> bool + Send + 'static>;
|
||||
type Listener = Box<dyn FnMut(&dyn Any, &mut AppContext) -> bool + Send + 'static>;
|
||||
type QuitHandler = Box<dyn FnMut(&mut AppContext) -> BoxFuture<'static, ()> + Send + 'static>;
|
||||
type ReleaseListener = Box<dyn FnMut(&mut dyn Any, &mut AppContext) + Send + 'static>;
|
||||
|
||||
pub struct AppContext {
|
||||
this: Weak<Mutex<AppContext>>,
|
||||
@@ -131,12 +137,11 @@ pub struct AppContext {
|
||||
pub(crate) image_cache: ImageCache,
|
||||
pub(crate) text_style_stack: Vec<TextStyleRefinement>,
|
||||
pub(crate) globals_by_type: HashMap<TypeId, AnyBox>,
|
||||
pub(crate) unit_entity: Handle<()>,
|
||||
pub(crate) entities: EntityMap,
|
||||
pub(crate) windows: SlotMap<WindowId, Option<Window>>,
|
||||
pub(crate) keymap: Arc<RwLock<Keymap>>,
|
||||
pub(crate) keymap: Arc<Mutex<Keymap>>,
|
||||
pub(crate) global_action_listeners:
|
||||
HashMap<TypeId, Vec<Box<dyn Fn(&dyn Action, DispatchPhase, &mut Self) + Send + Sync>>>,
|
||||
HashMap<TypeId, Vec<Box<dyn Fn(&dyn Action, DispatchPhase, &mut Self) + Send>>>,
|
||||
action_builders: HashMap<SharedString, ActionBuilder>,
|
||||
pending_effects: VecDeque<Effect>,
|
||||
pub(crate) pending_notifications: HashSet<EntityId>,
|
||||
@@ -163,8 +168,8 @@ impl AppContext {
|
||||
);
|
||||
|
||||
let text_system = Arc::new(TextSystem::new(platform.text_system()));
|
||||
let mut entities = EntityMap::new();
|
||||
let unit_entity = entities.insert(entities.reserve(), ());
|
||||
let entities = EntityMap::new();
|
||||
|
||||
let app_metadata = AppMetadata {
|
||||
os_name: platform.os_name(),
|
||||
os_version: platform.os_version().ok(),
|
||||
@@ -186,10 +191,9 @@ impl AppContext {
|
||||
image_cache: ImageCache::new(http_client),
|
||||
text_style_stack: Vec::new(),
|
||||
globals_by_type: HashMap::default(),
|
||||
unit_entity,
|
||||
entities,
|
||||
windows: SlotMap::with_key(),
|
||||
keymap: Arc::new(RwLock::new(Keymap::default())),
|
||||
keymap: Arc::new(Mutex::new(Keymap::default())),
|
||||
global_action_listeners: HashMap::default(),
|
||||
action_builders: HashMap::default(),
|
||||
pending_effects: VecDeque::new(),
|
||||
@@ -207,6 +211,8 @@ impl AppContext {
|
||||
})
|
||||
}
|
||||
|
||||
/// Quit the application gracefully. Handlers registered with `ModelContext::on_app_quit`
|
||||
/// will be given 100ms to complete before exiting.
|
||||
pub fn quit(&mut self) {
|
||||
let mut futures = Vec::new();
|
||||
|
||||
@@ -234,6 +240,8 @@ impl AppContext {
|
||||
self.app_metadata.clone()
|
||||
}
|
||||
|
||||
/// Schedules all windows in the application to be redrawn. This can be called
|
||||
/// multiple times in an update cycle and still result in a single redraw.
|
||||
pub fn refresh(&mut self) {
|
||||
self.pending_effects.push_back(Effect::Refresh);
|
||||
}
|
||||
@@ -313,6 +321,9 @@ impl AppContext {
|
||||
self.pending_effects.push_back(effect);
|
||||
}
|
||||
|
||||
/// Called at the end of AppContext::update to complete any side effects
|
||||
/// such as notifying observers, emitting events, etc. Effects can themselves
|
||||
/// cause effects, so we continue looping until all effects are processed.
|
||||
fn flush_effects(&mut self) {
|
||||
loop {
|
||||
self.release_dropped_entities();
|
||||
@@ -363,6 +374,9 @@ impl AppContext {
|
||||
}
|
||||
}
|
||||
|
||||
/// Repeatedly called during `flush_effects` to release any entities whose
|
||||
/// reference count has become zero. We invoke any release observers before dropping
|
||||
/// each entity.
|
||||
fn release_dropped_entities(&mut self) {
|
||||
loop {
|
||||
let dropped = self.entities.take_dropped();
|
||||
@@ -380,6 +394,9 @@ impl AppContext {
|
||||
}
|
||||
}
|
||||
|
||||
/// Repeatedly called during `flush_effects` to handle a focused handle being dropped.
|
||||
/// For now, we simply blur the window if this happens, but we may want to support invoking
|
||||
/// a window blur handler to restore focus to some logical element.
|
||||
fn release_dropped_focus_handles(&mut self) {
|
||||
for window_handle in self.windows() {
|
||||
self.update_window(window_handle, |cx| {
|
||||
@@ -414,7 +431,7 @@ impl AppContext {
|
||||
fn apply_emit_effect(&mut self, emitter: EntityId, event: Box<dyn Any>) {
|
||||
self.event_listeners
|
||||
.clone()
|
||||
.retain(&emitter, |handler| handler(&event, self));
|
||||
.retain(&emitter, |handler| handler(event.as_ref(), self));
|
||||
}
|
||||
|
||||
fn apply_focus_changed_effect(
|
||||
@@ -462,10 +479,12 @@ impl AppContext {
|
||||
.retain(&type_id, |observer| observer(self));
|
||||
}
|
||||
|
||||
fn apply_defer_effect(&mut self, callback: Box<dyn FnOnce(&mut Self) + Send + Sync + 'static>) {
|
||||
fn apply_defer_effect(&mut self, callback: Box<dyn FnOnce(&mut Self) + Send + 'static>) {
|
||||
callback(self);
|
||||
}
|
||||
|
||||
/// Creates an `AsyncAppContext`, which can be cloned and has a static lifetime
|
||||
/// so it can be held across `await` points.
|
||||
pub fn to_async(&self) -> AsyncAppContext {
|
||||
AsyncAppContext {
|
||||
app: unsafe { mem::transmute(self.this.clone()) },
|
||||
@@ -473,10 +492,14 @@ impl AppContext {
|
||||
}
|
||||
}
|
||||
|
||||
/// Obtains a reference to the executor, which can be used to spawn futures.
|
||||
pub fn executor(&self) -> &Executor {
|
||||
&self.executor
|
||||
}
|
||||
|
||||
/// Runs the given closure on the main thread, where interaction with the platform
|
||||
/// is possible. The given closure will be invoked with a `MainThread<AppContext>`, which
|
||||
/// has platform-specific methods that aren't present on `AppContext`.
|
||||
pub fn run_on_main<R>(
|
||||
&mut self,
|
||||
f: impl FnOnce(&mut MainThread<AppContext>) -> R + Send + 'static,
|
||||
@@ -497,6 +520,11 @@ impl AppContext {
|
||||
}
|
||||
}
|
||||
|
||||
/// Spawns the future returned by the given function on the main thread, where interaction with
|
||||
/// the platform is possible. The given closure will be invoked with a `MainThread<AsyncAppContext>`,
|
||||
/// which has platform-specific methods that aren't present on `AsyncAppContext`. The future will be
|
||||
/// polled exclusively on the main thread.
|
||||
// todo!("I think we need somehow to prevent the MainThread<AsyncAppContext> from implementing Send")
|
||||
pub fn spawn_on_main<F, R>(
|
||||
&self,
|
||||
f: impl FnOnce(MainThread<AsyncAppContext>) -> F + Send + 'static,
|
||||
@@ -509,6 +537,8 @@ impl AppContext {
|
||||
self.executor.spawn_on_main(move || f(MainThread(cx)))
|
||||
}
|
||||
|
||||
/// Spawns the future returned by the given function on the thread pool. The closure will be invoked
|
||||
/// with AsyncAppContext, which allows the application state to be accessed across await points.
|
||||
pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncAppContext) -> Fut + Send + 'static) -> Task<R>
|
||||
where
|
||||
Fut: Future<Output = R> + Send + 'static,
|
||||
@@ -521,20 +551,25 @@ impl AppContext {
|
||||
})
|
||||
}
|
||||
|
||||
pub fn defer(&mut self, f: impl FnOnce(&mut AppContext) + 'static + Send + Sync) {
|
||||
/// Schedules the given function to be run at the end of the current effect cycle, allowing entities
|
||||
/// that are currently on the stack to be returned to the app.
|
||||
pub fn defer(&mut self, f: impl FnOnce(&mut AppContext) + 'static + Send) {
|
||||
self.push_effect(Effect::Defer {
|
||||
callback: Box::new(f),
|
||||
});
|
||||
}
|
||||
|
||||
/// Accessor for the application's asset source, which is provided when constructing the `App`.
|
||||
pub fn asset_source(&self) -> &Arc<dyn AssetSource> {
|
||||
&self.asset_source
|
||||
}
|
||||
|
||||
/// Accessor for the text system.
|
||||
pub fn text_system(&self) -> &Arc<TextSystem> {
|
||||
&self.text_system
|
||||
}
|
||||
|
||||
/// The current text style. Which is composed of all the style refinements provided to `with_text_style`.
|
||||
pub fn text_style(&self) -> TextStyle {
|
||||
let mut style = TextStyle::default();
|
||||
for refinement in &self.text_style_stack {
|
||||
@@ -543,10 +578,12 @@ impl AppContext {
|
||||
style
|
||||
}
|
||||
|
||||
/// Check whether a global of the given type has been assigned.
|
||||
pub fn has_global<G: 'static>(&self) -> bool {
|
||||
self.globals_by_type.contains_key(&TypeId::of::<G>())
|
||||
}
|
||||
|
||||
/// Access the global of the given type. Panics if a global for that type has not been assigned.
|
||||
pub fn global<G: 'static>(&self) -> &G {
|
||||
self.globals_by_type
|
||||
.get(&TypeId::of::<G>())
|
||||
@@ -555,12 +592,14 @@ impl AppContext {
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// Access the global of the given type if a value has been assigned.
|
||||
pub fn try_global<G: 'static>(&self) -> Option<&G> {
|
||||
self.globals_by_type
|
||||
.get(&TypeId::of::<G>())
|
||||
.map(|any_state| any_state.downcast_ref::<G>().unwrap())
|
||||
}
|
||||
|
||||
/// Access the global of the given type mutably. Panics if a global for that type has not been assigned.
|
||||
pub fn global_mut<G: 'static>(&mut self) -> &mut G {
|
||||
let global_type = TypeId::of::<G>();
|
||||
self.push_effect(Effect::NotifyGlobalObservers { global_type });
|
||||
@@ -571,7 +610,9 @@ impl AppContext {
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
pub fn default_global<G: 'static + Default + Sync + Send>(&mut self) -> &mut G {
|
||||
/// Access the global of the given type mutably. A default value is assigned if a global of this type has not
|
||||
/// yet been assigned.
|
||||
pub fn default_global<G: 'static + Default + Send>(&mut self) -> &mut G {
|
||||
let global_type = TypeId::of::<G>();
|
||||
self.push_effect(Effect::NotifyGlobalObservers { global_type });
|
||||
self.globals_by_type
|
||||
@@ -581,12 +622,15 @@ impl AppContext {
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
pub fn set_global<G: Any + Send + Sync>(&mut self, global: G) {
|
||||
/// Set the value of the global of the given type.
|
||||
pub fn set_global<G: Any + Send>(&mut self, global: G) {
|
||||
let global_type = TypeId::of::<G>();
|
||||
self.push_effect(Effect::NotifyGlobalObservers { global_type });
|
||||
self.globals_by_type.insert(global_type, Box::new(global));
|
||||
}
|
||||
|
||||
/// Update the global of the given type with a closure. Unlike `global_mut`, this method provides
|
||||
/// your closure with mutable access to the `AppContext` and the global simultaneously.
|
||||
pub fn update_global<G: 'static, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R {
|
||||
let mut global = self.lease_global::<G>();
|
||||
let result = f(&mut global, self);
|
||||
@@ -594,9 +638,10 @@ impl AppContext {
|
||||
result
|
||||
}
|
||||
|
||||
/// Register a callback to be invoked when a global of the given type is updated.
|
||||
pub fn observe_global<G: 'static>(
|
||||
&mut self,
|
||||
mut f: impl FnMut(&mut Self) + Send + Sync + 'static,
|
||||
mut f: impl FnMut(&mut Self) + Send + 'static,
|
||||
) -> Subscription {
|
||||
self.global_observers.insert(
|
||||
TypeId::of::<G>(),
|
||||
@@ -607,6 +652,7 @@ impl AppContext {
|
||||
)
|
||||
}
|
||||
|
||||
/// Move the global of the given type to the stack.
|
||||
pub(crate) fn lease_global<G: 'static>(&mut self) -> GlobalLease<G> {
|
||||
GlobalLease::new(
|
||||
self.globals_by_type
|
||||
@@ -616,6 +662,7 @@ impl AppContext {
|
||||
)
|
||||
}
|
||||
|
||||
/// Restore the global of the given type after it is moved to the stack.
|
||||
pub(crate) fn end_global_lease<G: 'static>(&mut self, lease: GlobalLease<G>) {
|
||||
let global_type = TypeId::of::<G>();
|
||||
self.push_effect(Effect::NotifyGlobalObservers { global_type });
|
||||
@@ -625,7 +672,7 @@ impl AppContext {
|
||||
pub fn observe_release<E: 'static>(
|
||||
&mut self,
|
||||
handle: &Handle<E>,
|
||||
mut on_release: impl FnMut(&mut E, &mut AppContext) + Send + Sync + 'static,
|
||||
mut on_release: impl FnMut(&mut E, &mut AppContext) + Send + 'static,
|
||||
) -> Subscription {
|
||||
self.release_listeners.insert(
|
||||
handle.entity_id,
|
||||
@@ -644,15 +691,14 @@ impl AppContext {
|
||||
self.text_style_stack.pop();
|
||||
}
|
||||
|
||||
/// Register key bindings.
|
||||
pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
|
||||
self.keymap.write().add_bindings(bindings);
|
||||
self.keymap.lock().add_bindings(bindings);
|
||||
self.pending_effects.push_back(Effect::Refresh);
|
||||
}
|
||||
|
||||
pub fn on_action<A: Action>(
|
||||
&mut self,
|
||||
listener: impl Fn(&A, &mut Self) + Send + Sync + 'static,
|
||||
) {
|
||||
/// Register a global listener for actions invoked via the keyboard.
|
||||
pub fn on_action<A: Action>(&mut self, listener: impl Fn(&A, &mut Self) + Send + 'static) {
|
||||
self.global_action_listeners
|
||||
.entry(TypeId::of::<A>())
|
||||
.or_default()
|
||||
@@ -664,10 +710,12 @@ impl AppContext {
|
||||
}));
|
||||
}
|
||||
|
||||
/// Register an action type to allow it to be referenced in keymaps.
|
||||
pub fn register_action_type<A: Action>(&mut self) {
|
||||
self.action_builders.insert(A::qualified_name(), A::build);
|
||||
}
|
||||
|
||||
/// Construct an action based on its name and parameters.
|
||||
pub fn build_action(
|
||||
&mut self,
|
||||
name: &str,
|
||||
@@ -680,18 +728,23 @@ impl AppContext {
|
||||
(build)(params)
|
||||
}
|
||||
|
||||
/// Halt propagation of a mouse event, keyboard event, or action. This prevents listeners
|
||||
/// that have not yet been invoked from receiving the event.
|
||||
pub fn stop_propagation(&mut self) {
|
||||
self.propagate_event = false;
|
||||
}
|
||||
}
|
||||
|
||||
impl Context for AppContext {
|
||||
type EntityContext<'a, 'w, T> = ModelContext<'a, T>;
|
||||
type EntityContext<'a, T> = ModelContext<'a, T>;
|
||||
type Result<T> = T;
|
||||
|
||||
fn entity<T: Any + Send + Sync>(
|
||||
/// Build an entity that is owned by the application. The given function will be invoked with
|
||||
/// a `ModelContext` and must return an object representing the entity. A `Handle` will be returned
|
||||
/// which can be used to access the entity in a context.
|
||||
fn entity<T: 'static + Send>(
|
||||
&mut self,
|
||||
build_entity: impl FnOnce(&mut Self::EntityContext<'_, '_, T>) -> T,
|
||||
build_entity: impl FnOnce(&mut Self::EntityContext<'_, T>) -> T,
|
||||
) -> Handle<T> {
|
||||
self.update(|cx| {
|
||||
let slot = cx.entities.reserve();
|
||||
@@ -700,10 +753,12 @@ impl Context for AppContext {
|
||||
})
|
||||
}
|
||||
|
||||
/// Update the entity referenced by the given handle. The function is passed a mutable reference to the
|
||||
/// entity along with a `ModelContext` for the entity.
|
||||
fn update_entity<T: 'static, R>(
|
||||
&mut self,
|
||||
handle: &Handle<T>,
|
||||
update: impl FnOnce(&mut T, &mut Self::EntityContext<'_, '_, T>) -> R,
|
||||
update: impl FnOnce(&mut T, &mut Self::EntityContext<'_, T>) -> R,
|
||||
) -> R {
|
||||
self.update(|cx| {
|
||||
let mut entity = cx.entities.lease(handle);
|
||||
@@ -725,30 +780,37 @@ where
|
||||
self.0.borrow().platform.borrow_on_main_thread()
|
||||
}
|
||||
|
||||
/// Instructs the platform to activate the application by bringing it to the foreground.
|
||||
pub fn activate(&self, ignoring_other_apps: bool) {
|
||||
self.platform().activate(ignoring_other_apps);
|
||||
}
|
||||
|
||||
/// Writes data to the platform clipboard.
|
||||
pub fn write_to_clipboard(&self, item: ClipboardItem) {
|
||||
self.platform().write_to_clipboard(item)
|
||||
}
|
||||
|
||||
/// Reads data from the platform clipboard.
|
||||
pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
|
||||
self.platform().read_from_clipboard()
|
||||
}
|
||||
|
||||
/// Writes credentials to the platform keychain.
|
||||
pub fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Result<()> {
|
||||
self.platform().write_credentials(url, username, password)
|
||||
}
|
||||
|
||||
/// Reads credentials from the platform keychain.
|
||||
pub fn read_credentials(&self, url: &str) -> Result<Option<(String, Vec<u8>)>> {
|
||||
self.platform().read_credentials(url)
|
||||
}
|
||||
|
||||
/// Deletes credentials from the platform keychain.
|
||||
pub fn delete_credentials(&self, url: &str) -> Result<()> {
|
||||
self.platform().delete_credentials(url)
|
||||
}
|
||||
|
||||
/// Directs the platform's default browser to open the given URL.
|
||||
pub fn open_url(&self, url: &str) {
|
||||
self.platform().open_url(url);
|
||||
}
|
||||
@@ -779,6 +841,9 @@ impl MainThread<AppContext> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Opens a new window with the given option and the root view returned by the given function.
|
||||
/// The function is invoked with a `WindowContext`, which can be used to interact with window-specific
|
||||
/// functionality.
|
||||
pub fn open_window<V: 'static>(
|
||||
&mut self,
|
||||
options: crate::WindowOptions,
|
||||
@@ -795,7 +860,9 @@ impl MainThread<AppContext> {
|
||||
})
|
||||
}
|
||||
|
||||
pub fn update_global<G: 'static + Send + Sync, R>(
|
||||
/// Update the global of the given type with a closure. Unlike `global_mut`, this method provides
|
||||
/// your closure with mutable access to the `MainThread<AppContext>` and the global simultaneously.
|
||||
pub fn update_global<G: 'static + Send, R>(
|
||||
&mut self,
|
||||
update: impl FnOnce(&mut G, &mut MainThread<AppContext>) -> R,
|
||||
) -> R {
|
||||
@@ -806,13 +873,14 @@ impl MainThread<AppContext> {
|
||||
}
|
||||
}
|
||||
|
||||
/// These effects are processed at the end of each application update cycle.
|
||||
pub(crate) enum Effect {
|
||||
Notify {
|
||||
emitter: EntityId,
|
||||
},
|
||||
Emit {
|
||||
emitter: EntityId,
|
||||
event: Box<dyn Any + Send + Sync + 'static>,
|
||||
event: Box<dyn Any + Send + 'static>,
|
||||
},
|
||||
FocusChanged {
|
||||
window_handle: AnyWindowHandle,
|
||||
@@ -823,10 +891,11 @@ pub(crate) enum Effect {
|
||||
global_type: TypeId,
|
||||
},
|
||||
Defer {
|
||||
callback: Box<dyn FnOnce(&mut AppContext) + Send + Sync + 'static>,
|
||||
callback: Box<dyn FnOnce(&mut AppContext) + Send + 'static>,
|
||||
},
|
||||
}
|
||||
|
||||
/// Wraps a global variable value during `update_global` while the value has been moved to the stack.
|
||||
pub(crate) struct GlobalLease<G: 'static> {
|
||||
global: AnyBox,
|
||||
global_type: PhantomData<G>,
|
||||
@@ -855,6 +924,8 @@ impl<G: 'static> DerefMut for GlobalLease<G> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Contains state associated with an active drag operation, started by dragging an element
|
||||
/// within the window or by dragging into the app from the underlying platform.
|
||||
pub(crate) struct AnyDrag {
|
||||
pub drag_handle_view: Option<AnyView>,
|
||||
pub cursor_offset: Point<Pixels>,
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
use crate::{
|
||||
AnyWindowHandle, AppContext, Context, Executor, Handle, MainThread, ModelContext, Result, Task,
|
||||
ViewContext, WindowContext,
|
||||
WindowContext,
|
||||
};
|
||||
use anyhow::Context as _;
|
||||
use derive_more::{Deref, DerefMut};
|
||||
use parking_lot::Mutex;
|
||||
use std::{any::Any, future::Future, sync::Weak};
|
||||
use std::{future::Future, sync::Weak};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AsyncAppContext {
|
||||
@@ -14,15 +14,15 @@ pub struct AsyncAppContext {
|
||||
}
|
||||
|
||||
impl Context for AsyncAppContext {
|
||||
type EntityContext<'a, 'w, T> = ModelContext<'a, T>;
|
||||
type EntityContext<'a, T> = ModelContext<'a, T>;
|
||||
type Result<T> = Result<T>;
|
||||
|
||||
fn entity<T: 'static>(
|
||||
&mut self,
|
||||
build_entity: impl FnOnce(&mut Self::EntityContext<'_, '_, T>) -> T,
|
||||
build_entity: impl FnOnce(&mut Self::EntityContext<'_, T>) -> T,
|
||||
) -> Self::Result<Handle<T>>
|
||||
where
|
||||
T: Any + Send + Sync,
|
||||
T: 'static + Send,
|
||||
{
|
||||
let app = self.app.upgrade().context("app was released")?;
|
||||
let mut lock = app.lock(); // Need this to compile
|
||||
@@ -32,7 +32,7 @@ impl Context for AsyncAppContext {
|
||||
fn update_entity<T: 'static, R>(
|
||||
&mut self,
|
||||
handle: &Handle<T>,
|
||||
update: impl FnOnce(&mut T, &mut Self::EntityContext<'_, '_, T>) -> R,
|
||||
update: impl FnOnce(&mut T, &mut Self::EntityContext<'_, T>) -> R,
|
||||
) -> Self::Result<R> {
|
||||
let app = self.app.upgrade().context("app was released")?;
|
||||
let mut lock = app.lock(); // Need this to compile
|
||||
@@ -221,15 +221,15 @@ impl AsyncWindowContext {
|
||||
}
|
||||
|
||||
impl Context for AsyncWindowContext {
|
||||
type EntityContext<'a, 'w, T> = ViewContext<'a, 'w, T>;
|
||||
type EntityContext<'a, T> = ModelContext<'a, T>;
|
||||
type Result<T> = Result<T>;
|
||||
|
||||
fn entity<T>(
|
||||
&mut self,
|
||||
build_entity: impl FnOnce(&mut Self::EntityContext<'_, '_, T>) -> T,
|
||||
build_entity: impl FnOnce(&mut Self::EntityContext<'_, T>) -> T,
|
||||
) -> Result<Handle<T>>
|
||||
where
|
||||
T: Any + Send + Sync,
|
||||
T: 'static + Send,
|
||||
{
|
||||
self.app
|
||||
.update_window(self.window, |cx| cx.entity(build_entity))
|
||||
@@ -238,7 +238,7 @@ impl Context for AsyncWindowContext {
|
||||
fn update_entity<T: 'static, R>(
|
||||
&mut self,
|
||||
handle: &Handle<T>,
|
||||
update: impl FnOnce(&mut T, &mut Self::EntityContext<'_, '_, T>) -> R,
|
||||
update: impl FnOnce(&mut T, &mut Self::EntityContext<'_, T>) -> R,
|
||||
) -> Result<R> {
|
||||
self.app
|
||||
.update_window(self.window, |cx| cx.update_entity(handle, update))
|
||||
|
||||
@@ -4,7 +4,7 @@ use derive_more::{Deref, DerefMut};
|
||||
use parking_lot::{RwLock, RwLockUpgradableReadGuard};
|
||||
use slotmap::{SecondaryMap, SlotMap};
|
||||
use std::{
|
||||
any::{type_name, Any, TypeId},
|
||||
any::{type_name, TypeId},
|
||||
fmt::{self, Display},
|
||||
hash::{Hash, Hasher},
|
||||
marker::PhantomData,
|
||||
@@ -59,7 +59,7 @@ impl EntityMap {
|
||||
/// Insert an entity into a slot obtained by calling `reserve`.
|
||||
pub fn insert<T>(&mut self, slot: Slot<T>, entity: T) -> Handle<T>
|
||||
where
|
||||
T: Any + Send + Sync,
|
||||
T: 'static + Send,
|
||||
{
|
||||
let handle = slot.0;
|
||||
self.entities.insert(handle.entity_id, Box::new(entity));
|
||||
@@ -100,10 +100,15 @@ impl EntityMap {
|
||||
}
|
||||
|
||||
pub fn take_dropped(&mut self) -> Vec<(EntityId, AnyBox)> {
|
||||
let dropped_entity_ids = mem::take(&mut self.ref_counts.write().dropped_entity_ids);
|
||||
let mut ref_counts = self.ref_counts.write();
|
||||
let dropped_entity_ids = mem::take(&mut ref_counts.dropped_entity_ids);
|
||||
|
||||
dropped_entity_ids
|
||||
.into_iter()
|
||||
.map(|entity_id| (entity_id, self.entities.remove(entity_id).unwrap()))
|
||||
.map(|entity_id| {
|
||||
ref_counts.counts.remove(entity_id);
|
||||
(entity_id, self.entities.remove(entity_id).unwrap())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
@@ -212,7 +217,6 @@ impl Drop for AnyHandle {
|
||||
if prev_count == 1 {
|
||||
// We were the last reference to this entity, so we can remove it.
|
||||
let mut entity_map = RwLockUpgradableReadGuard::upgrade(entity_map);
|
||||
entity_map.counts.remove(self.entity_id);
|
||||
entity_map.dropped_entity_ids.push(self.entity_id);
|
||||
}
|
||||
}
|
||||
@@ -280,7 +284,7 @@ impl<T: 'static> Handle<T> {
|
||||
pub fn update<C, R>(
|
||||
&self,
|
||||
cx: &mut C,
|
||||
update: impl FnOnce(&mut T, &mut C::EntityContext<'_, '_, T>) -> R,
|
||||
update: impl FnOnce(&mut T, &mut C::EntityContext<'_, T>) -> R,
|
||||
) -> C::Result<R>
|
||||
where
|
||||
C: Context,
|
||||
@@ -423,7 +427,7 @@ impl<T: 'static> WeakHandle<T> {
|
||||
pub fn update<C, R>(
|
||||
&self,
|
||||
cx: &mut C,
|
||||
update: impl FnOnce(&mut T, &mut C::EntityContext<'_, '_, T>) -> R,
|
||||
update: impl FnOnce(&mut T, &mut C::EntityContext<'_, T>) -> R,
|
||||
) -> Result<R>
|
||||
where
|
||||
C: Context,
|
||||
|
||||
@@ -43,10 +43,10 @@ impl<'a, T: 'static> ModelContext<'a, T> {
|
||||
pub fn observe<T2: 'static>(
|
||||
&mut self,
|
||||
handle: &Handle<T2>,
|
||||
mut on_notify: impl FnMut(&mut T, Handle<T2>, &mut ModelContext<'_, T>) + Send + Sync + 'static,
|
||||
mut on_notify: impl FnMut(&mut T, Handle<T2>, &mut ModelContext<'_, T>) + Send + 'static,
|
||||
) -> Subscription
|
||||
where
|
||||
T: Any + Send + Sync,
|
||||
T: 'static + Send,
|
||||
{
|
||||
let this = self.weak_handle();
|
||||
let handle = handle.downgrade();
|
||||
@@ -68,18 +68,17 @@ impl<'a, T: 'static> ModelContext<'a, T> {
|
||||
handle: &Handle<E>,
|
||||
mut on_event: impl FnMut(&mut T, Handle<E>, &E::Event, &mut ModelContext<'_, T>)
|
||||
+ Send
|
||||
+ Sync
|
||||
+ 'static,
|
||||
) -> Subscription
|
||||
where
|
||||
T: Any + Send + Sync,
|
||||
T: 'static + Send,
|
||||
{
|
||||
let this = self.weak_handle();
|
||||
let handle = handle.downgrade();
|
||||
self.app.event_listeners.insert(
|
||||
handle.entity_id,
|
||||
Box::new(move |event, cx| {
|
||||
let event = event.downcast_ref().expect("invalid event type");
|
||||
let event: &E::Event = event.downcast_ref().expect("invalid event type");
|
||||
if let Some((this, handle)) = this.upgrade().zip(handle.upgrade()) {
|
||||
this.update(cx, |this, cx| on_event(this, handle, event, cx));
|
||||
true
|
||||
@@ -92,7 +91,7 @@ impl<'a, T: 'static> ModelContext<'a, T> {
|
||||
|
||||
pub fn on_release(
|
||||
&mut self,
|
||||
mut on_release: impl FnMut(&mut T, &mut AppContext) + Send + Sync + 'static,
|
||||
mut on_release: impl FnMut(&mut T, &mut AppContext) + Send + 'static,
|
||||
) -> Subscription
|
||||
where
|
||||
T: 'static,
|
||||
@@ -109,10 +108,10 @@ impl<'a, T: 'static> ModelContext<'a, T> {
|
||||
pub fn observe_release<E: 'static>(
|
||||
&mut self,
|
||||
handle: &Handle<E>,
|
||||
mut on_release: impl FnMut(&mut T, &mut E, &mut ModelContext<'_, T>) + Send + Sync + 'static,
|
||||
mut on_release: impl FnMut(&mut T, &mut E, &mut ModelContext<'_, T>) + Send + 'static,
|
||||
) -> Subscription
|
||||
where
|
||||
T: Any + Send + Sync,
|
||||
T: Any + Send,
|
||||
{
|
||||
let this = self.weak_handle();
|
||||
self.app.observe_release(handle, move |entity, cx| {
|
||||
@@ -124,10 +123,10 @@ impl<'a, T: 'static> ModelContext<'a, T> {
|
||||
|
||||
pub fn observe_global<G: 'static>(
|
||||
&mut self,
|
||||
mut f: impl FnMut(&mut T, &mut ModelContext<'_, T>) + Send + Sync + 'static,
|
||||
mut f: impl FnMut(&mut T, &mut ModelContext<'_, T>) + Send + 'static,
|
||||
) -> Subscription
|
||||
where
|
||||
T: Any + Send + Sync,
|
||||
T: 'static + Send,
|
||||
{
|
||||
let handle = self.weak_handle();
|
||||
self.global_observers.insert(
|
||||
@@ -138,11 +137,11 @@ impl<'a, T: 'static> ModelContext<'a, T> {
|
||||
|
||||
pub fn on_app_quit<Fut>(
|
||||
&mut self,
|
||||
mut on_quit: impl FnMut(&mut T, &mut ModelContext<T>) -> Fut + Send + Sync + 'static,
|
||||
mut on_quit: impl FnMut(&mut T, &mut ModelContext<T>) -> Fut + Send + 'static,
|
||||
) -> Subscription
|
||||
where
|
||||
Fut: 'static + Future<Output = ()> + Send,
|
||||
T: Any + Send + Sync,
|
||||
T: 'static + Send,
|
||||
{
|
||||
let handle = self.weak_handle();
|
||||
self.app.quit_observers.insert(
|
||||
@@ -173,7 +172,7 @@ impl<'a, T: 'static> ModelContext<'a, T> {
|
||||
|
||||
pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
|
||||
where
|
||||
G: 'static + Send + Sync,
|
||||
G: 'static + Send,
|
||||
{
|
||||
let mut global = self.app.lease_global::<G>();
|
||||
let result = f(&mut global, self);
|
||||
@@ -210,7 +209,7 @@ impl<'a, T: 'static> ModelContext<'a, T> {
|
||||
impl<'a, T> ModelContext<'a, T>
|
||||
where
|
||||
T: EventEmitter,
|
||||
T::Event: Send + Sync,
|
||||
T::Event: Send,
|
||||
{
|
||||
pub fn emit(&mut self, event: T::Event) {
|
||||
self.app.pending_effects.push_back(Effect::Emit {
|
||||
@@ -221,15 +220,15 @@ where
|
||||
}
|
||||
|
||||
impl<'a, T> Context for ModelContext<'a, T> {
|
||||
type EntityContext<'b, 'c, U> = ModelContext<'b, U>;
|
||||
type EntityContext<'b, U> = ModelContext<'b, U>;
|
||||
type Result<U> = U;
|
||||
|
||||
fn entity<U>(
|
||||
&mut self,
|
||||
build_entity: impl FnOnce(&mut Self::EntityContext<'_, '_, U>) -> U,
|
||||
build_entity: impl FnOnce(&mut Self::EntityContext<'_, U>) -> U,
|
||||
) -> Handle<U>
|
||||
where
|
||||
U: 'static + Send + Sync,
|
||||
U: 'static + Send,
|
||||
{
|
||||
self.app.entity(build_entity)
|
||||
}
|
||||
@@ -237,7 +236,7 @@ impl<'a, T> Context for ModelContext<'a, T> {
|
||||
fn update_entity<U: 'static, R>(
|
||||
&mut self,
|
||||
handle: &Handle<U>,
|
||||
update: impl FnOnce(&mut U, &mut Self::EntityContext<'_, '_, U>) -> R,
|
||||
update: impl FnOnce(&mut U, &mut Self::EntityContext<'_, U>) -> R,
|
||||
) -> R {
|
||||
self.app.update_entity(handle, update)
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ use crate::{
|
||||
ModelContext, Result, Task, TestDispatcher, TestPlatform, WindowContext,
|
||||
};
|
||||
use parking_lot::Mutex;
|
||||
use std::{any::Any, future::Future, sync::Arc};
|
||||
use std::{future::Future, sync::Arc};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct TestAppContext {
|
||||
@@ -12,15 +12,15 @@ pub struct TestAppContext {
|
||||
}
|
||||
|
||||
impl Context for TestAppContext {
|
||||
type EntityContext<'a, 'w, T> = ModelContext<'a, T>;
|
||||
type EntityContext<'a, T> = ModelContext<'a, T>;
|
||||
type Result<T> = T;
|
||||
|
||||
fn entity<T: 'static>(
|
||||
&mut self,
|
||||
build_entity: impl FnOnce(&mut Self::EntityContext<'_, '_, T>) -> T,
|
||||
build_entity: impl FnOnce(&mut Self::EntityContext<'_, T>) -> T,
|
||||
) -> Self::Result<Handle<T>>
|
||||
where
|
||||
T: Any + Send + Sync,
|
||||
T: 'static + Send,
|
||||
{
|
||||
let mut lock = self.app.lock();
|
||||
lock.entity(build_entity)
|
||||
@@ -29,7 +29,7 @@ impl Context for TestAppContext {
|
||||
fn update_entity<T: 'static, R>(
|
||||
&mut self,
|
||||
handle: &Handle<T>,
|
||||
update: impl FnOnce(&mut T, &mut Self::EntityContext<'_, '_, T>) -> R,
|
||||
update: impl FnOnce(&mut T, &mut Self::EntityContext<'_, T>) -> R,
|
||||
) -> Self::Result<R> {
|
||||
let mut lock = self.app.lock();
|
||||
lock.update_entity(handle, update)
|
||||
|
||||
+10
-20
@@ -16,8 +16,6 @@ pub trait Element<V: 'static> {
|
||||
element_state: Option<Self::ElementState>,
|
||||
cx: &mut ViewContext<V>,
|
||||
) -> Self::ElementState;
|
||||
// where
|
||||
// V: Any + Send + Sync;
|
||||
|
||||
fn layout(
|
||||
&mut self,
|
||||
@@ -25,8 +23,6 @@ pub trait Element<V: 'static> {
|
||||
element_state: &mut Self::ElementState,
|
||||
cx: &mut ViewContext<V>,
|
||||
) -> LayoutId;
|
||||
// where
|
||||
// V: Any + Send + Sync;
|
||||
|
||||
fn paint(
|
||||
&mut self,
|
||||
@@ -35,9 +31,6 @@ pub trait Element<V: 'static> {
|
||||
element_state: &mut Self::ElementState,
|
||||
cx: &mut ViewContext<V>,
|
||||
);
|
||||
|
||||
// where
|
||||
// Self::ViewState: Any + Send + Sync;
|
||||
}
|
||||
|
||||
#[derive(Deref, DerefMut, Default, Clone, Debug, Eq, PartialEq, Hash)]
|
||||
@@ -104,8 +97,7 @@ impl<V, E: Element<V>> RenderedElement<V, E> {
|
||||
impl<V, E> ElementObject<V> for RenderedElement<V, E>
|
||||
where
|
||||
E: Element<V>,
|
||||
// E::ViewState: Any + Send + Sync,
|
||||
E::ElementState: Any + Send + Sync,
|
||||
E::ElementState: 'static + Send,
|
||||
{
|
||||
fn initialize(&mut self, view_state: &mut V, cx: &mut ViewContext<V>) {
|
||||
let frame_state = if let Some(id) = self.element.id() {
|
||||
@@ -178,18 +170,16 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
pub struct AnyElement<V>(Box<dyn ElementObject<V> + Send + Sync>);
|
||||
pub struct AnyElement<V>(Box<dyn ElementObject<V> + Send>);
|
||||
|
||||
unsafe impl<V> Send for AnyElement<V> {}
|
||||
unsafe impl<V> Sync for AnyElement<V> {}
|
||||
|
||||
impl<V> AnyElement<V> {
|
||||
pub fn new<E>(element: E) -> Self
|
||||
where
|
||||
V: 'static,
|
||||
E: 'static + Send + Sync,
|
||||
E: Element<V>,
|
||||
E::ElementState: Any + Send + Sync,
|
||||
E: 'static + Element<V> + Send,
|
||||
E::ElementState: Any + Send,
|
||||
{
|
||||
AnyElement(Box::new(RenderedElement::new(element)))
|
||||
}
|
||||
@@ -230,8 +220,8 @@ impl<V> Component<V> for AnyElement<V> {
|
||||
impl<V, E, F> Element<V> for Option<F>
|
||||
where
|
||||
V: 'static,
|
||||
E: 'static + Component<V> + Send + Sync,
|
||||
F: FnOnce(&mut V, &mut ViewContext<'_, '_, V>) -> E + Send + Sync + 'static,
|
||||
E: 'static + Component<V> + Send,
|
||||
F: FnOnce(&mut V, &mut ViewContext<'_, '_, V>) -> E + Send + 'static,
|
||||
{
|
||||
type ElementState = AnyElement<V>;
|
||||
|
||||
@@ -274,8 +264,8 @@ where
|
||||
impl<V, E, F> Component<V> for Option<F>
|
||||
where
|
||||
V: 'static,
|
||||
E: 'static + Component<V> + Send + Sync,
|
||||
F: FnOnce(&mut V, &mut ViewContext<'_, '_, V>) -> E + Send + Sync + 'static,
|
||||
E: 'static + Component<V> + Send,
|
||||
F: FnOnce(&mut V, &mut ViewContext<'_, '_, V>) -> E + Send + 'static,
|
||||
{
|
||||
fn render(self) -> AnyElement<V> {
|
||||
AnyElement::new(self)
|
||||
@@ -285,8 +275,8 @@ where
|
||||
impl<V, E, F> Component<V> for F
|
||||
where
|
||||
V: 'static,
|
||||
E: 'static + Component<V> + Send + Sync,
|
||||
F: FnOnce(&mut V, &mut ViewContext<'_, '_, V>) -> E + Send + Sync + 'static,
|
||||
E: 'static + Component<V> + Send,
|
||||
F: FnOnce(&mut V, &mut ViewContext<'_, '_, V>) -> E + Send + 'static,
|
||||
{
|
||||
fn render(self) -> AnyElement<V> {
|
||||
AnyElement::new(Some(self))
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::{AppContext, PlatformDispatcher};
|
||||
use futures::{channel::mpsc, pin_mut};
|
||||
use futures::{channel::mpsc, pin_mut, FutureExt};
|
||||
use smol::prelude::*;
|
||||
use std::{
|
||||
fmt::Debug,
|
||||
@@ -162,16 +162,16 @@ impl Executor {
|
||||
duration: Duration,
|
||||
future: impl Future<Output = R>,
|
||||
) -> Result<R, impl Future<Output = R>> {
|
||||
let mut future = Box::pin(future);
|
||||
let timeout = {
|
||||
let future = &mut future;
|
||||
async {
|
||||
let timer = async {
|
||||
self.timer(duration).await;
|
||||
Err(())
|
||||
};
|
||||
let future = async move { Ok(future.await) };
|
||||
timer.race(future).await
|
||||
let mut future = Box::pin(future.fuse());
|
||||
if duration.is_zero() {
|
||||
return Err(future);
|
||||
}
|
||||
|
||||
let mut timer = self.timer(duration).fuse();
|
||||
let timeout = async {
|
||||
futures::select_biased! {
|
||||
value = future => Ok(value),
|
||||
_ = timer => Err(()),
|
||||
}
|
||||
};
|
||||
match self.block(timeout) {
|
||||
@@ -216,7 +216,7 @@ impl Executor {
|
||||
|
||||
#[cfg(any(test, feature = "test-support"))]
|
||||
pub fn simulate_random_delay(&self) -> impl Future<Output = ()> {
|
||||
self.dispatcher.as_test().unwrap().simulate_random_delay()
|
||||
self.spawn(self.dispatcher.as_test().unwrap().simulate_random_delay())
|
||||
}
|
||||
|
||||
#[cfg(any(test, feature = "test-support"))]
|
||||
|
||||
@@ -4,12 +4,11 @@ use crate::{
|
||||
};
|
||||
use refineable::Refineable;
|
||||
use smallvec::SmallVec;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub type FocusListeners<V> = SmallVec<[FocusListener<V>; 2]>;
|
||||
|
||||
pub type FocusListener<V> =
|
||||
Arc<dyn Fn(&mut V, &FocusHandle, &FocusEvent, &mut ViewContext<V>) + Send + Sync + 'static>;
|
||||
Box<dyn Fn(&mut V, &FocusHandle, &FocusEvent, &mut ViewContext<V>) + Send + 'static>;
|
||||
|
||||
pub trait Focusable<V: 'static>: Element<V> {
|
||||
fn focus_listeners(&mut self) -> &mut FocusListeners<V>;
|
||||
@@ -43,13 +42,13 @@ pub trait Focusable<V: 'static>: Element<V> {
|
||||
|
||||
fn on_focus(
|
||||
mut self,
|
||||
listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + Send + Sync + 'static,
|
||||
listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + Send + 'static,
|
||||
) -> Self
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
self.focus_listeners()
|
||||
.push(Arc::new(move |view, focus_handle, event, cx| {
|
||||
.push(Box::new(move |view, focus_handle, event, cx| {
|
||||
if event.focused.as_ref() == Some(focus_handle) {
|
||||
listener(view, event, cx)
|
||||
}
|
||||
@@ -59,13 +58,13 @@ pub trait Focusable<V: 'static>: Element<V> {
|
||||
|
||||
fn on_blur(
|
||||
mut self,
|
||||
listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + Send + Sync + 'static,
|
||||
listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + Send + 'static,
|
||||
) -> Self
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
self.focus_listeners()
|
||||
.push(Arc::new(move |view, focus_handle, event, cx| {
|
||||
.push(Box::new(move |view, focus_handle, event, cx| {
|
||||
if event.blurred.as_ref() == Some(focus_handle) {
|
||||
listener(view, event, cx)
|
||||
}
|
||||
@@ -75,13 +74,13 @@ pub trait Focusable<V: 'static>: Element<V> {
|
||||
|
||||
fn on_focus_in(
|
||||
mut self,
|
||||
listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + Send + Sync + 'static,
|
||||
listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + Send + 'static,
|
||||
) -> Self
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
self.focus_listeners()
|
||||
.push(Arc::new(move |view, focus_handle, event, cx| {
|
||||
.push(Box::new(move |view, focus_handle, event, cx| {
|
||||
let descendant_blurred = event
|
||||
.blurred
|
||||
.as_ref()
|
||||
@@ -100,13 +99,13 @@ pub trait Focusable<V: 'static>: Element<V> {
|
||||
|
||||
fn on_focus_out(
|
||||
mut self,
|
||||
listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + Send + Sync + 'static,
|
||||
listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + Send + 'static,
|
||||
) -> Self
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
self.focus_listeners()
|
||||
.push(Arc::new(move |view, focus_handle, event, cx| {
|
||||
.push(Box::new(move |view, focus_handle, event, cx| {
|
||||
let descendant_blurred = event
|
||||
.blurred
|
||||
.as_ref()
|
||||
@@ -123,7 +122,7 @@ pub trait Focusable<V: 'static>: Element<V> {
|
||||
}
|
||||
}
|
||||
|
||||
pub trait ElementFocus<V: 'static>: 'static + Send + Sync {
|
||||
pub trait ElementFocus<V: 'static>: 'static + Send {
|
||||
fn as_focusable(&self) -> Option<&FocusEnabled<V>>;
|
||||
fn as_focusable_mut(&mut self) -> Option<&mut FocusEnabled<V>>;
|
||||
|
||||
@@ -138,7 +137,7 @@ pub trait ElementFocus<V: 'static>: 'static + Send + Sync {
|
||||
.focus_handle
|
||||
.get_or_insert_with(|| focus_handle.unwrap_or_else(|| cx.focus_handle()))
|
||||
.clone();
|
||||
for listener in focusable.focus_listeners.iter().cloned() {
|
||||
for listener in focusable.focus_listeners.drain(..) {
|
||||
let focus_handle = focus_handle.clone();
|
||||
cx.on_focus_changed(move |view, event, cx| {
|
||||
listener(view, &focus_handle, event, cx)
|
||||
|
||||
+77
-15
@@ -67,23 +67,42 @@ use std::{
|
||||
};
|
||||
use taffy::TaffyLayoutEngine;
|
||||
|
||||
type AnyBox = Box<dyn Any + Send + Sync>;
|
||||
type AnyBox = Box<dyn Any + Send>;
|
||||
|
||||
pub trait Context {
|
||||
type EntityContext<'a, 'w, T>;
|
||||
type EntityContext<'a, T>;
|
||||
type Result<T>;
|
||||
|
||||
fn entity<T>(
|
||||
&mut self,
|
||||
build_entity: impl FnOnce(&mut Self::EntityContext<'_, '_, T>) -> T,
|
||||
build_entity: impl FnOnce(&mut Self::EntityContext<'_, T>) -> T,
|
||||
) -> Self::Result<Handle<T>>
|
||||
where
|
||||
T: 'static + Send + Sync;
|
||||
T: 'static + Send;
|
||||
|
||||
fn update_entity<T: 'static, R>(
|
||||
&mut self,
|
||||
handle: &Handle<T>,
|
||||
update: impl FnOnce(&mut T, &mut Self::EntityContext<'_, '_, T>) -> R,
|
||||
update: impl FnOnce(&mut T, &mut Self::EntityContext<'_, T>) -> R,
|
||||
) -> Self::Result<R>;
|
||||
}
|
||||
|
||||
pub trait VisualContext: Context {
|
||||
type ViewContext<'a, 'w, V>;
|
||||
|
||||
fn build_view<E, V>(
|
||||
&mut self,
|
||||
build_entity: impl FnOnce(&mut Self::ViewContext<'_, '_, V>) -> V,
|
||||
render: impl Fn(&mut V, &mut ViewContext<'_, '_, V>) -> E + Send + 'static,
|
||||
) -> Self::Result<View<V>>
|
||||
where
|
||||
E: Component<V>,
|
||||
V: 'static + Send;
|
||||
|
||||
fn update_view<V: 'static, R>(
|
||||
&mut self,
|
||||
view: &View<V>,
|
||||
update: impl FnOnce(&mut V, &mut Self::ViewContext<'_, '_, V>) -> R,
|
||||
) -> Self::Result<R>;
|
||||
}
|
||||
|
||||
@@ -111,21 +130,21 @@ impl<T> DerefMut for MainThread<T> {
|
||||
}
|
||||
|
||||
impl<C: Context> Context for MainThread<C> {
|
||||
type EntityContext<'a, 'w, T> = MainThread<C::EntityContext<'a, 'w, T>>;
|
||||
type EntityContext<'a, T> = MainThread<C::EntityContext<'a, T>>;
|
||||
type Result<T> = C::Result<T>;
|
||||
|
||||
fn entity<T>(
|
||||
&mut self,
|
||||
build_entity: impl FnOnce(&mut Self::EntityContext<'_, '_, T>) -> T,
|
||||
build_entity: impl FnOnce(&mut Self::EntityContext<'_, T>) -> T,
|
||||
) -> Self::Result<Handle<T>>
|
||||
where
|
||||
T: Any + Send + Sync,
|
||||
T: 'static + Send,
|
||||
{
|
||||
self.0.entity(|cx| {
|
||||
let cx = unsafe {
|
||||
mem::transmute::<
|
||||
&mut C::EntityContext<'_, '_, T>,
|
||||
&mut MainThread<C::EntityContext<'_, '_, T>>,
|
||||
&mut C::EntityContext<'_, T>,
|
||||
&mut MainThread<C::EntityContext<'_, T>>,
|
||||
>(cx)
|
||||
};
|
||||
build_entity(cx)
|
||||
@@ -135,13 +154,13 @@ impl<C: Context> Context for MainThread<C> {
|
||||
fn update_entity<T: 'static, R>(
|
||||
&mut self,
|
||||
handle: &Handle<T>,
|
||||
update: impl FnOnce(&mut T, &mut Self::EntityContext<'_, '_, T>) -> R,
|
||||
update: impl FnOnce(&mut T, &mut Self::EntityContext<'_, T>) -> R,
|
||||
) -> Self::Result<R> {
|
||||
self.0.update_entity(handle, |entity, cx| {
|
||||
let cx = unsafe {
|
||||
mem::transmute::<
|
||||
&mut C::EntityContext<'_, '_, T>,
|
||||
&mut MainThread<C::EntityContext<'_, '_, T>>,
|
||||
&mut C::EntityContext<'_, T>,
|
||||
&mut MainThread<C::EntityContext<'_, T>>,
|
||||
>(cx)
|
||||
};
|
||||
update(entity, cx)
|
||||
@@ -149,12 +168,55 @@ impl<C: Context> Context for MainThread<C> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<C: VisualContext> VisualContext for MainThread<C> {
|
||||
type ViewContext<'a, 'w, V> = MainThread<C::ViewContext<'a, 'w, V>>;
|
||||
|
||||
fn build_view<E, V>(
|
||||
&mut self,
|
||||
build_entity: impl FnOnce(&mut Self::ViewContext<'_, '_, V>) -> V,
|
||||
render: impl Fn(&mut V, &mut ViewContext<'_, '_, V>) -> E + Send + 'static,
|
||||
) -> Self::Result<View<V>>
|
||||
where
|
||||
E: Component<V>,
|
||||
V: 'static + Send,
|
||||
{
|
||||
self.0.build_view(
|
||||
|cx| {
|
||||
let cx = unsafe {
|
||||
mem::transmute::<
|
||||
&mut C::ViewContext<'_, '_, V>,
|
||||
&mut MainThread<C::ViewContext<'_, '_, V>>,
|
||||
>(cx)
|
||||
};
|
||||
build_entity(cx)
|
||||
},
|
||||
render,
|
||||
)
|
||||
}
|
||||
|
||||
fn update_view<V: 'static, R>(
|
||||
&mut self,
|
||||
view: &View<V>,
|
||||
update: impl FnOnce(&mut V, &mut Self::ViewContext<'_, '_, V>) -> R,
|
||||
) -> Self::Result<R> {
|
||||
self.0.update_view(view, |view_state, cx| {
|
||||
let cx = unsafe {
|
||||
mem::transmute::<
|
||||
&mut C::ViewContext<'_, '_, V>,
|
||||
&mut MainThread<C::ViewContext<'_, '_, V>>,
|
||||
>(cx)
|
||||
};
|
||||
update(view_state, cx)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub trait BorrowAppContext {
|
||||
fn with_text_style<F, R>(&mut self, style: TextStyleRefinement, f: F) -> R
|
||||
where
|
||||
F: FnOnce(&mut Self) -> R;
|
||||
|
||||
fn set_global<T: Send + Sync + 'static>(&mut self, global: T);
|
||||
fn set_global<T: Send + 'static>(&mut self, global: T);
|
||||
}
|
||||
|
||||
impl<C> BorrowAppContext for C
|
||||
@@ -171,7 +233,7 @@ where
|
||||
result
|
||||
}
|
||||
|
||||
fn set_global<G: 'static + Send + Sync>(&mut self, global: G) {
|
||||
fn set_global<G: 'static + Send>(&mut self, global: G) {
|
||||
self.borrow_mut().set_global(global)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
use crate::{
|
||||
point, px, view, Action, AnyBox, AnyDrag, AppContext, BorrowWindow, Bounds, Component,
|
||||
point, px, Action, AnyBox, AnyDrag, AppContext, BorrowWindow, Bounds, Component,
|
||||
DispatchContext, DispatchPhase, Element, ElementId, FocusHandle, KeyMatch, Keystroke,
|
||||
Modifiers, Overflow, Pixels, Point, SharedString, Size, Style, StyleRefinement, ViewContext,
|
||||
Modifiers, Overflow, Pixels, Point, SharedString, Size, Style, StyleRefinement, View,
|
||||
ViewContext,
|
||||
};
|
||||
use collections::HashMap;
|
||||
use derive_more::{Deref, DerefMut};
|
||||
@@ -12,6 +13,7 @@ use std::{
|
||||
any::{Any, TypeId},
|
||||
fmt::Debug,
|
||||
marker::PhantomData,
|
||||
mem,
|
||||
ops::Deref,
|
||||
path::PathBuf,
|
||||
sync::Arc,
|
||||
@@ -48,14 +50,14 @@ pub trait StatelessInteractive<V: 'static>: Element<V> {
|
||||
fn on_mouse_down(
|
||||
mut self,
|
||||
button: MouseButton,
|
||||
handler: impl Fn(&mut V, &MouseDownEvent, &mut ViewContext<V>) + Send + Sync + 'static,
|
||||
handler: impl Fn(&mut V, &MouseDownEvent, &mut ViewContext<V>) + Send + 'static,
|
||||
) -> Self
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
self.stateless_interaction()
|
||||
.mouse_down_listeners
|
||||
.push(Arc::new(move |view, event, bounds, phase, cx| {
|
||||
.push(Box::new(move |view, event, bounds, phase, cx| {
|
||||
if phase == DispatchPhase::Bubble
|
||||
&& event.button == button
|
||||
&& bounds.contains_point(&event.position)
|
||||
@@ -69,14 +71,14 @@ pub trait StatelessInteractive<V: 'static>: Element<V> {
|
||||
fn on_mouse_up(
|
||||
mut self,
|
||||
button: MouseButton,
|
||||
handler: impl Fn(&mut V, &MouseUpEvent, &mut ViewContext<V>) + Send + Sync + 'static,
|
||||
handler: impl Fn(&mut V, &MouseUpEvent, &mut ViewContext<V>) + Send + 'static,
|
||||
) -> Self
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
self.stateless_interaction()
|
||||
.mouse_up_listeners
|
||||
.push(Arc::new(move |view, event, bounds, phase, cx| {
|
||||
.push(Box::new(move |view, event, bounds, phase, cx| {
|
||||
if phase == DispatchPhase::Bubble
|
||||
&& event.button == button
|
||||
&& bounds.contains_point(&event.position)
|
||||
@@ -90,14 +92,14 @@ pub trait StatelessInteractive<V: 'static>: Element<V> {
|
||||
fn on_mouse_down_out(
|
||||
mut self,
|
||||
button: MouseButton,
|
||||
handler: impl Fn(&mut V, &MouseDownEvent, &mut ViewContext<V>) + Send + Sync + 'static,
|
||||
handler: impl Fn(&mut V, &MouseDownEvent, &mut ViewContext<V>) + Send + 'static,
|
||||
) -> Self
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
self.stateless_interaction()
|
||||
.mouse_down_listeners
|
||||
.push(Arc::new(move |view, event, bounds, phase, cx| {
|
||||
.push(Box::new(move |view, event, bounds, phase, cx| {
|
||||
if phase == DispatchPhase::Capture
|
||||
&& event.button == button
|
||||
&& !bounds.contains_point(&event.position)
|
||||
@@ -111,14 +113,14 @@ pub trait StatelessInteractive<V: 'static>: Element<V> {
|
||||
fn on_mouse_up_out(
|
||||
mut self,
|
||||
button: MouseButton,
|
||||
handler: impl Fn(&mut V, &MouseUpEvent, &mut ViewContext<V>) + Send + Sync + 'static,
|
||||
handler: impl Fn(&mut V, &MouseUpEvent, &mut ViewContext<V>) + Send + 'static,
|
||||
) -> Self
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
self.stateless_interaction()
|
||||
.mouse_up_listeners
|
||||
.push(Arc::new(move |view, event, bounds, phase, cx| {
|
||||
.push(Box::new(move |view, event, bounds, phase, cx| {
|
||||
if phase == DispatchPhase::Capture
|
||||
&& event.button == button
|
||||
&& !bounds.contains_point(&event.position)
|
||||
@@ -131,14 +133,14 @@ pub trait StatelessInteractive<V: 'static>: Element<V> {
|
||||
|
||||
fn on_mouse_move(
|
||||
mut self,
|
||||
handler: impl Fn(&mut V, &MouseMoveEvent, &mut ViewContext<V>) + Send + Sync + 'static,
|
||||
handler: impl Fn(&mut V, &MouseMoveEvent, &mut ViewContext<V>) + Send + 'static,
|
||||
) -> Self
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
self.stateless_interaction()
|
||||
.mouse_move_listeners
|
||||
.push(Arc::new(move |view, event, bounds, phase, cx| {
|
||||
.push(Box::new(move |view, event, bounds, phase, cx| {
|
||||
if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position) {
|
||||
handler(view, event, cx);
|
||||
}
|
||||
@@ -148,14 +150,14 @@ pub trait StatelessInteractive<V: 'static>: Element<V> {
|
||||
|
||||
fn on_scroll_wheel(
|
||||
mut self,
|
||||
handler: impl Fn(&mut V, &ScrollWheelEvent, &mut ViewContext<V>) + Send + Sync + 'static,
|
||||
handler: impl Fn(&mut V, &ScrollWheelEvent, &mut ViewContext<V>) + Send + 'static,
|
||||
) -> Self
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
self.stateless_interaction()
|
||||
.scroll_wheel_listeners
|
||||
.push(Arc::new(move |view, event, bounds, phase, cx| {
|
||||
.push(Box::new(move |view, event, bounds, phase, cx| {
|
||||
if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position) {
|
||||
handler(view, event, cx);
|
||||
}
|
||||
@@ -176,14 +178,14 @@ pub trait StatelessInteractive<V: 'static>: Element<V> {
|
||||
|
||||
fn on_action<A: 'static>(
|
||||
mut self,
|
||||
listener: impl Fn(&mut V, &A, DispatchPhase, &mut ViewContext<V>) + Send + Sync + 'static,
|
||||
listener: impl Fn(&mut V, &A, DispatchPhase, &mut ViewContext<V>) + Send + 'static,
|
||||
) -> Self
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
self.stateless_interaction().key_listeners.push((
|
||||
TypeId::of::<A>(),
|
||||
Arc::new(move |view, event, _, phase, cx| {
|
||||
Box::new(move |view, event, _, phase, cx| {
|
||||
let event = event.downcast_ref().unwrap();
|
||||
listener(view, event, phase, cx);
|
||||
None
|
||||
@@ -194,17 +196,14 @@ pub trait StatelessInteractive<V: 'static>: Element<V> {
|
||||
|
||||
fn on_key_down(
|
||||
mut self,
|
||||
listener: impl Fn(&mut V, &KeyDownEvent, DispatchPhase, &mut ViewContext<V>)
|
||||
+ Send
|
||||
+ Sync
|
||||
+ 'static,
|
||||
listener: impl Fn(&mut V, &KeyDownEvent, DispatchPhase, &mut ViewContext<V>) + Send + 'static,
|
||||
) -> Self
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
self.stateless_interaction().key_listeners.push((
|
||||
TypeId::of::<KeyDownEvent>(),
|
||||
Arc::new(move |view, event, _, phase, cx| {
|
||||
Box::new(move |view, event, _, phase, cx| {
|
||||
let event = event.downcast_ref().unwrap();
|
||||
listener(view, event, phase, cx);
|
||||
None
|
||||
@@ -215,17 +214,14 @@ pub trait StatelessInteractive<V: 'static>: Element<V> {
|
||||
|
||||
fn on_key_up(
|
||||
mut self,
|
||||
listener: impl Fn(&mut V, &KeyUpEvent, DispatchPhase, &mut ViewContext<V>)
|
||||
+ Send
|
||||
+ Sync
|
||||
+ 'static,
|
||||
listener: impl Fn(&mut V, &KeyUpEvent, DispatchPhase, &mut ViewContext<V>) + Send + 'static,
|
||||
) -> Self
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
self.stateless_interaction().key_listeners.push((
|
||||
TypeId::of::<KeyUpEvent>(),
|
||||
Arc::new(move |view, event, _, phase, cx| {
|
||||
Box::new(move |view, event, _, phase, cx| {
|
||||
let event = event.downcast_ref().unwrap();
|
||||
listener(view, event, phase, cx);
|
||||
None
|
||||
@@ -264,14 +260,14 @@ pub trait StatelessInteractive<V: 'static>: Element<V> {
|
||||
|
||||
fn on_drop<S: 'static>(
|
||||
mut self,
|
||||
listener: impl Fn(&mut V, S, &mut ViewContext<V>) + Send + Sync + 'static,
|
||||
listener: impl Fn(&mut V, S, &mut ViewContext<V>) + Send + 'static,
|
||||
) -> Self
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
self.stateless_interaction().drop_listeners.push((
|
||||
TypeId::of::<S>(),
|
||||
Arc::new(move |view, drag_state, cx| {
|
||||
Box::new(move |view, drag_state, cx| {
|
||||
listener(view, *drag_state.downcast().unwrap(), cx);
|
||||
}),
|
||||
));
|
||||
@@ -307,26 +303,26 @@ pub trait StatefulInteractive<V: 'static>: StatelessInteractive<V> {
|
||||
|
||||
fn on_click(
|
||||
mut self,
|
||||
listener: impl Fn(&mut V, &ClickEvent, &mut ViewContext<V>) + Send + Sync + 'static,
|
||||
listener: impl Fn(&mut V, &ClickEvent, &mut ViewContext<V>) + Send + 'static,
|
||||
) -> Self
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
self.stateful_interaction()
|
||||
.click_listeners
|
||||
.push(Arc::new(move |view, event, cx| listener(view, event, cx)));
|
||||
.push(Box::new(move |view, event, cx| listener(view, event, cx)));
|
||||
self
|
||||
}
|
||||
|
||||
fn on_drag<S, R, E>(
|
||||
mut self,
|
||||
listener: impl Fn(&mut V, &mut ViewContext<V>) -> Drag<S, R, V, E> + Send + Sync + 'static,
|
||||
listener: impl Fn(&mut V, &mut ViewContext<V>) -> Drag<S, R, V, E> + Send + 'static,
|
||||
) -> Self
|
||||
where
|
||||
Self: Sized,
|
||||
S: Any + Send + Sync,
|
||||
S: Any + Send,
|
||||
R: Fn(&mut V, &mut ViewContext<V>) -> E,
|
||||
R: 'static + Send + Sync,
|
||||
R: 'static + Send,
|
||||
E: Component<V>,
|
||||
{
|
||||
debug_assert!(
|
||||
@@ -334,11 +330,10 @@ pub trait StatefulInteractive<V: 'static>: StatelessInteractive<V> {
|
||||
"calling on_drag more than once on the same element is not supported"
|
||||
);
|
||||
self.stateful_interaction().drag_listener =
|
||||
Some(Arc::new(move |view_state, cursor_offset, cx| {
|
||||
Some(Box::new(move |view_state, cursor_offset, cx| {
|
||||
let drag = listener(view_state, cx);
|
||||
let view_handle = cx.handle().upgrade().unwrap();
|
||||
let drag_handle_view = Some(
|
||||
view(view_handle, move |view_state, cx| {
|
||||
View::for_handle(cx.handle().upgrade().unwrap(), move |view_state, cx| {
|
||||
(drag.render_drag_handle)(view_state, cx)
|
||||
})
|
||||
.into_any(),
|
||||
@@ -354,7 +349,7 @@ pub trait StatefulInteractive<V: 'static>: StatelessInteractive<V> {
|
||||
}
|
||||
}
|
||||
|
||||
pub trait ElementInteraction<V: 'static>: 'static + Send + Sync {
|
||||
pub trait ElementInteraction<V: 'static>: 'static + Send {
|
||||
fn as_stateless(&self) -> &StatelessInteraction<V>;
|
||||
fn as_stateless_mut(&mut self) -> &mut StatelessInteraction<V>;
|
||||
fn as_stateful(&self) -> Option<&StatefulInteraction<V>>;
|
||||
@@ -369,7 +364,7 @@ pub trait ElementInteraction<V: 'static>: 'static + Send + Sync {
|
||||
cx.with_element_id(stateful.id.clone(), |global_id, cx| {
|
||||
stateful.key_listeners.push((
|
||||
TypeId::of::<KeyDownEvent>(),
|
||||
Arc::new(move |_, key_down, context, phase, cx| {
|
||||
Box::new(move |_, key_down, context, phase, cx| {
|
||||
if phase == DispatchPhase::Bubble {
|
||||
let key_down = key_down.downcast_ref::<KeyDownEvent>().unwrap();
|
||||
if let KeyMatch::Some(action) =
|
||||
@@ -387,9 +382,9 @@ pub trait ElementInteraction<V: 'static>: 'static + Send + Sync {
|
||||
result
|
||||
})
|
||||
} else {
|
||||
let stateless = self.as_stateless();
|
||||
let stateless = self.as_stateless_mut();
|
||||
cx.with_key_dispatch_context(stateless.dispatch_context.clone(), |cx| {
|
||||
cx.with_key_listeners(&stateless.key_listeners, f)
|
||||
cx.with_key_listeners(mem::take(&mut stateless.key_listeners), f)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -455,26 +450,26 @@ pub trait ElementInteraction<V: 'static>: 'static + Send + Sync {
|
||||
element_state: &mut InteractiveElementState,
|
||||
cx: &mut ViewContext<V>,
|
||||
) {
|
||||
let stateless = self.as_stateless();
|
||||
for listener in stateless.mouse_down_listeners.iter().cloned() {
|
||||
let stateless = self.as_stateless_mut();
|
||||
for listener in stateless.mouse_down_listeners.drain(..) {
|
||||
cx.on_mouse_event(move |state, event: &MouseDownEvent, phase, cx| {
|
||||
listener(state, event, &bounds, phase, cx);
|
||||
})
|
||||
}
|
||||
|
||||
for listener in stateless.mouse_up_listeners.iter().cloned() {
|
||||
for listener in stateless.mouse_up_listeners.drain(..) {
|
||||
cx.on_mouse_event(move |state, event: &MouseUpEvent, phase, cx| {
|
||||
listener(state, event, &bounds, phase, cx);
|
||||
})
|
||||
}
|
||||
|
||||
for listener in stateless.mouse_move_listeners.iter().cloned() {
|
||||
for listener in stateless.mouse_move_listeners.drain(..) {
|
||||
cx.on_mouse_event(move |state, event: &MouseMoveEvent, phase, cx| {
|
||||
listener(state, event, &bounds, phase, cx);
|
||||
})
|
||||
}
|
||||
|
||||
for listener in stateless.scroll_wheel_listeners.iter().cloned() {
|
||||
for listener in stateless.scroll_wheel_listeners.drain(..) {
|
||||
cx.on_mouse_event(move |state, event: &ScrollWheelEvent, phase, cx| {
|
||||
listener(state, event, &bounds, phase, cx);
|
||||
})
|
||||
@@ -510,7 +505,7 @@ pub trait ElementInteraction<V: 'static>: 'static + Send + Sync {
|
||||
}
|
||||
|
||||
if cx.active_drag.is_some() {
|
||||
let drop_listeners = stateless.drop_listeners.clone();
|
||||
let drop_listeners = mem::take(&mut stateless.drop_listeners);
|
||||
cx.on_mouse_event(move |view, event: &MouseUpEvent, phase, cx| {
|
||||
if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position) {
|
||||
if let Some(drag_state_type) =
|
||||
@@ -532,9 +527,9 @@ pub trait ElementInteraction<V: 'static>: 'static + Send + Sync {
|
||||
});
|
||||
}
|
||||
|
||||
if let Some(stateful) = self.as_stateful() {
|
||||
let click_listeners = stateful.click_listeners.clone();
|
||||
let drag_listener = stateful.drag_listener.clone();
|
||||
if let Some(stateful) = self.as_stateful_mut() {
|
||||
let click_listeners = mem::take(&mut stateful.click_listeners);
|
||||
let drag_listener = mem::take(&mut stateful.drag_listener);
|
||||
|
||||
if !click_listeners.is_empty() || drag_listener.is_some() {
|
||||
let pending_mouse_down = element_state.pending_mouse_down.clone();
|
||||
@@ -690,7 +685,7 @@ impl<V> From<ElementId> for StatefulInteraction<V> {
|
||||
}
|
||||
}
|
||||
|
||||
type DropListener<V> = dyn Fn(&mut V, AnyBox, &mut ViewContext<V>) + 'static + Send + Sync;
|
||||
type DropListener<V> = dyn Fn(&mut V, AnyBox, &mut ViewContext<V>) + 'static + Send;
|
||||
|
||||
pub struct StatelessInteraction<V> {
|
||||
pub dispatch_context: DispatchContext,
|
||||
@@ -703,7 +698,7 @@ pub struct StatelessInteraction<V> {
|
||||
pub group_hover_style: Option<GroupStyle>,
|
||||
drag_over_styles: SmallVec<[(TypeId, StyleRefinement); 2]>,
|
||||
group_drag_over_styles: SmallVec<[(TypeId, GroupStyle); 2]>,
|
||||
drop_listeners: SmallVec<[(TypeId, Arc<DropListener<V>>); 2]>,
|
||||
drop_listeners: SmallVec<[(TypeId, Box<DropListener<V>>); 2]>,
|
||||
}
|
||||
|
||||
impl<V> StatelessInteraction<V> {
|
||||
@@ -1082,40 +1077,35 @@ pub struct FocusEvent {
|
||||
pub focused: Option<FocusHandle>,
|
||||
}
|
||||
|
||||
pub type MouseDownListener<V> = Arc<
|
||||
pub type MouseDownListener<V> = Box<
|
||||
dyn Fn(&mut V, &MouseDownEvent, &Bounds<Pixels>, DispatchPhase, &mut ViewContext<V>)
|
||||
+ Send
|
||||
+ Sync
|
||||
+ 'static,
|
||||
>;
|
||||
pub type MouseUpListener<V> = Arc<
|
||||
pub type MouseUpListener<V> = Box<
|
||||
dyn Fn(&mut V, &MouseUpEvent, &Bounds<Pixels>, DispatchPhase, &mut ViewContext<V>)
|
||||
+ Send
|
||||
+ Sync
|
||||
+ 'static,
|
||||
>;
|
||||
|
||||
pub type MouseMoveListener<V> = Arc<
|
||||
pub type MouseMoveListener<V> = Box<
|
||||
dyn Fn(&mut V, &MouseMoveEvent, &Bounds<Pixels>, DispatchPhase, &mut ViewContext<V>)
|
||||
+ Send
|
||||
+ Sync
|
||||
+ 'static,
|
||||
>;
|
||||
|
||||
pub type ScrollWheelListener<V> = Arc<
|
||||
pub type ScrollWheelListener<V> = Box<
|
||||
dyn Fn(&mut V, &ScrollWheelEvent, &Bounds<Pixels>, DispatchPhase, &mut ViewContext<V>)
|
||||
+ Send
|
||||
+ Sync
|
||||
+ 'static,
|
||||
>;
|
||||
|
||||
pub type ClickListener<V> =
|
||||
Arc<dyn Fn(&mut V, &ClickEvent, &mut ViewContext<V>) + Send + Sync + 'static>;
|
||||
pub type ClickListener<V> = Box<dyn Fn(&mut V, &ClickEvent, &mut ViewContext<V>) + Send + 'static>;
|
||||
|
||||
pub(crate) type DragListener<V> =
|
||||
Arc<dyn Fn(&mut V, Point<Pixels>, &mut ViewContext<V>) -> AnyDrag + Send + Sync + 'static>;
|
||||
Box<dyn Fn(&mut V, Point<Pixels>, &mut ViewContext<V>) -> AnyDrag + Send + 'static>;
|
||||
|
||||
pub type KeyListener<V> = Arc<
|
||||
pub type KeyListener<V> = Box<
|
||||
dyn Fn(
|
||||
&mut V,
|
||||
&dyn Any,
|
||||
@@ -1124,6 +1114,5 @@ pub type KeyListener<V> = Arc<
|
||||
&mut ViewContext<V>,
|
||||
) -> Option<Box<dyn Action>>
|
||||
+ Send
|
||||
+ Sync
|
||||
+ 'static,
|
||||
>;
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
use crate::{Action, DispatchContext, Keymap, KeymapVersion, Keystroke};
|
||||
use parking_lot::RwLock;
|
||||
use parking_lot::Mutex;
|
||||
use smallvec::SmallVec;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub struct KeyMatcher {
|
||||
pending_keystrokes: Vec<Keystroke>,
|
||||
keymap: Arc<RwLock<Keymap>>,
|
||||
keymap: Arc<Mutex<Keymap>>,
|
||||
keymap_version: KeymapVersion,
|
||||
}
|
||||
|
||||
impl KeyMatcher {
|
||||
pub fn new(keymap: Arc<RwLock<Keymap>>) -> Self {
|
||||
let keymap_version = keymap.read().version();
|
||||
pub fn new(keymap: Arc<Mutex<Keymap>>) -> Self {
|
||||
let keymap_version = keymap.lock().version();
|
||||
Self {
|
||||
pending_keystrokes: Vec::new(),
|
||||
keymap_version,
|
||||
@@ -21,7 +21,7 @@ impl KeyMatcher {
|
||||
|
||||
// todo!("replace with a function that calls an FnMut for every binding matching the action")
|
||||
// pub fn bindings_for_action(&self, action_id: TypeId) -> impl Iterator<Item = &Binding> {
|
||||
// self.keymap.read().bindings_for_action(action_id)
|
||||
// self.keymap.lock().bindings_for_action(action_id)
|
||||
// }
|
||||
|
||||
pub fn clear_pending(&mut self) {
|
||||
@@ -46,7 +46,7 @@ impl KeyMatcher {
|
||||
keystroke: &Keystroke,
|
||||
context_stack: &[&DispatchContext],
|
||||
) -> KeyMatch {
|
||||
let keymap = self.keymap.read();
|
||||
let keymap = self.keymap.lock();
|
||||
// Clear pending keystrokes if the keymap has changed since the last matched keystroke.
|
||||
if keymap.version() != self.keymap_version {
|
||||
self.keymap_version = keymap.version();
|
||||
@@ -89,7 +89,7 @@ impl KeyMatcher {
|
||||
contexts: &[&DispatchContext],
|
||||
) -> Option<SmallVec<[Keystroke; 2]>> {
|
||||
self.keymap
|
||||
.read()
|
||||
.lock()
|
||||
.bindings()
|
||||
.iter()
|
||||
.rev()
|
||||
|
||||
@@ -185,8 +185,7 @@ impl MacPlatform {
|
||||
}))
|
||||
}
|
||||
|
||||
unsafe fn read_from_pasteboard(&self, kind: id) -> Option<&[u8]> {
|
||||
let pasteboard = self.0.lock().pasteboard;
|
||||
unsafe fn read_from_pasteboard(&self, pasteboard: *mut Object, kind: id) -> Option<&[u8]> {
|
||||
let data = pasteboard.dataForType(kind);
|
||||
if data == nil {
|
||||
None
|
||||
@@ -787,14 +786,16 @@ impl Platform for MacPlatform {
|
||||
fn read_from_clipboard(&self) -> Option<ClipboardItem> {
|
||||
let state = self.0.lock();
|
||||
unsafe {
|
||||
if let Some(text_bytes) = self.read_from_pasteboard(NSPasteboardTypeString) {
|
||||
if let Some(text_bytes) =
|
||||
self.read_from_pasteboard(state.pasteboard, NSPasteboardTypeString)
|
||||
{
|
||||
let text = String::from_utf8_lossy(text_bytes).to_string();
|
||||
let hash_bytes = self
|
||||
.read_from_pasteboard(state.text_hash_pasteboard_type)
|
||||
.read_from_pasteboard(state.pasteboard, state.text_hash_pasteboard_type)
|
||||
.and_then(|bytes| bytes.try_into().ok())
|
||||
.map(u64::from_be_bytes);
|
||||
let metadata_bytes = self
|
||||
.read_from_pasteboard(state.metadata_pasteboard_type)
|
||||
.read_from_pasteboard(state.pasteboard, state.metadata_pasteboard_type)
|
||||
.and_then(|bytes| String::from_utf8(bytes.to_vec()).ok());
|
||||
|
||||
if let Some((hash, metadata)) = hash_bytes.zip(metadata_bytes) {
|
||||
|
||||
+46
-46
@@ -775,55 +775,55 @@ impl Bounds<ScaledPixels> {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::{point, size};
|
||||
// #[cfg(test)]
|
||||
// mod tests {
|
||||
// use crate::{point, size};
|
||||
|
||||
use super::*;
|
||||
use smallvec::smallvec;
|
||||
// use super::*;
|
||||
// use smallvec::smallvec;
|
||||
|
||||
#[test]
|
||||
fn test_scene() {
|
||||
let mut scene = SceneBuilder::new();
|
||||
assert_eq!(scene.layers_by_order.len(), 0);
|
||||
// #[test]
|
||||
// fn test_scene() {
|
||||
// let mut scene = SceneBuilder::new();
|
||||
// assert_eq!(scene.layers_by_order.len(), 0);
|
||||
|
||||
scene.insert(&smallvec![1].into(), quad());
|
||||
scene.insert(&smallvec![2].into(), shadow());
|
||||
scene.insert(&smallvec![3].into(), quad());
|
||||
// scene.insert(&smallvec![1].into(), quad());
|
||||
// scene.insert(&smallvec![2].into(), shadow());
|
||||
// scene.insert(&smallvec![3].into(), quad());
|
||||
|
||||
let mut batches_count = 0;
|
||||
for _ in scene.build().batches() {
|
||||
batches_count += 1;
|
||||
}
|
||||
assert_eq!(batches_count, 3);
|
||||
}
|
||||
// let mut batches_count = 0;
|
||||
// for _ in scene.build().batches() {
|
||||
// batches_count += 1;
|
||||
// }
|
||||
// assert_eq!(batches_count, 3);
|
||||
// }
|
||||
|
||||
fn quad() -> Quad {
|
||||
Quad {
|
||||
order: 0,
|
||||
bounds: Bounds {
|
||||
origin: point(ScaledPixels(0.), ScaledPixels(0.)),
|
||||
size: size(ScaledPixels(100.), ScaledPixels(100.)),
|
||||
},
|
||||
content_mask: Default::default(),
|
||||
background: Default::default(),
|
||||
border_color: Default::default(),
|
||||
corner_radii: Default::default(),
|
||||
border_widths: Default::default(),
|
||||
}
|
||||
}
|
||||
// fn quad() -> Quad {
|
||||
// Quad {
|
||||
// order: 0,
|
||||
// bounds: Bounds {
|
||||
// origin: point(ScaledPixels(0.), ScaledPixels(0.)),
|
||||
// size: size(ScaledPixels(100.), ScaledPixels(100.)),
|
||||
// },
|
||||
// content_mask: Default::default(),
|
||||
// background: Default::default(),
|
||||
// border_color: Default::default(),
|
||||
// corner_radii: Default::default(),
|
||||
// border_widths: Default::default(),
|
||||
// }
|
||||
// }
|
||||
|
||||
fn shadow() -> Shadow {
|
||||
Shadow {
|
||||
order: Default::default(),
|
||||
bounds: Bounds {
|
||||
origin: point(ScaledPixels(0.), ScaledPixels(0.)),
|
||||
size: size(ScaledPixels(100.), ScaledPixels(100.)),
|
||||
},
|
||||
corner_radii: Default::default(),
|
||||
content_mask: Default::default(),
|
||||
color: Default::default(),
|
||||
blur_radius: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
// fn shadow() -> Shadow {
|
||||
// Shadow {
|
||||
// order: Default::default(),
|
||||
// bounds: Bounds {
|
||||
// origin: point(ScaledPixels(0.), ScaledPixels(0.)),
|
||||
// size: size(ScaledPixels(100.), ScaledPixels(100.)),
|
||||
// },
|
||||
// corner_radii: Default::default(),
|
||||
// content_mask: Default::default(),
|
||||
// color: Default::default(),
|
||||
// blur_radius: Default::default(),
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use crate::{
|
||||
black, phi, point, rems, AbsoluteLength, BorrowAppContext, BorrowWindow, Bounds, ContentMask,
|
||||
Corners, CornersRefinement, DefiniteLength, Edges, EdgesRefinement, Font, FontFeatures,
|
||||
FontStyle, FontWeight, Hsla, Length, Pixels, Point, PointRefinement, Rems, Result,
|
||||
FontStyle, FontWeight, Hsla, Length, Pixels, Point, PointRefinement, Rems, Result, Rgba,
|
||||
SharedString, Size, SizeRefinement, Styled, TextRun, ViewContext, WindowContext,
|
||||
};
|
||||
use refineable::{Cascade, Refineable};
|
||||
@@ -417,3 +417,12 @@ impl From<Hsla> for HighlightStyle {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Rgba> for HighlightStyle {
|
||||
fn from(color: Rgba) -> Self {
|
||||
Self {
|
||||
color: Some(color.into()),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,8 +21,8 @@ struct SubscriberSetState<EmitterKey, Callback> {
|
||||
|
||||
impl<EmitterKey, Callback> SubscriberSet<EmitterKey, Callback>
|
||||
where
|
||||
EmitterKey: 'static + Send + Sync + Ord + Clone + Debug,
|
||||
Callback: 'static + Send + Sync,
|
||||
EmitterKey: 'static + Send + Ord + Clone + Debug,
|
||||
Callback: 'static + Send,
|
||||
{
|
||||
pub fn new() -> Self {
|
||||
Self(Arc::new(Mutex::new(SubscriberSetState {
|
||||
@@ -96,7 +96,7 @@ where
|
||||
|
||||
#[must_use]
|
||||
pub struct Subscription {
|
||||
unsubscribe: Option<Box<dyn FnOnce() + Send + Sync + 'static>>,
|
||||
unsubscribe: Option<Box<dyn FnOnce() + Send + 'static>>,
|
||||
}
|
||||
|
||||
impl Subscription {
|
||||
|
||||
@@ -179,7 +179,7 @@ struct Measureable<F>(F);
|
||||
|
||||
impl<F> taffy::tree::Measurable for Measureable<F>
|
||||
where
|
||||
F: Send + Sync + Fn(Size<Option<Pixels>>, Size<AvailableSpace>) -> Size<Pixels>,
|
||||
F: Fn(Size<Option<Pixels>>, Size<AvailableSpace>) -> Size<Pixels> + Send + Sync,
|
||||
{
|
||||
fn measure(
|
||||
&self,
|
||||
|
||||
@@ -8,7 +8,7 @@ use std::{
|
||||
pub fn run_test(
|
||||
mut num_iterations: u64,
|
||||
max_retries: usize,
|
||||
test_fn: &mut (dyn RefUnwindSafe + Fn(TestDispatcher)),
|
||||
test_fn: &mut (dyn RefUnwindSafe + Fn(TestDispatcher, u64)),
|
||||
on_fail_fn: Option<fn()>,
|
||||
_fn_name: String, // todo!("re-enable fn_name")
|
||||
) {
|
||||
@@ -28,7 +28,7 @@ pub fn run_test(
|
||||
}
|
||||
let result = panic::catch_unwind(|| {
|
||||
let dispatcher = TestDispatcher::new(StdRng::seed_from_u64(seed));
|
||||
test_fn(dispatcher);
|
||||
test_fn(dispatcher, seed);
|
||||
});
|
||||
|
||||
match result {
|
||||
|
||||
+117
-65
@@ -1,24 +1,63 @@
|
||||
use parking_lot::Mutex;
|
||||
|
||||
use crate::{
|
||||
AnyBox, AnyElement, AnyHandle, BorrowWindow, Bounds, Component, Element, ElementId, Handle,
|
||||
LayoutId, Pixels, ViewContext, WindowContext,
|
||||
AnyBox, AnyElement, AvailableSpace, BorrowWindow, Bounds, Component, Element, ElementId,
|
||||
EntityId, Handle, LayoutId, Pixels, Size, ViewContext, VisualContext, WeakHandle,
|
||||
WindowContext,
|
||||
};
|
||||
use anyhow::{Context, Result};
|
||||
use parking_lot::Mutex;
|
||||
use std::{
|
||||
marker::PhantomData,
|
||||
sync::{Arc, Weak},
|
||||
};
|
||||
use std::{marker::PhantomData, sync::Arc};
|
||||
|
||||
pub struct View<V> {
|
||||
state: Handle<V>,
|
||||
render: Arc<dyn Fn(&mut V, &mut ViewContext<V>) -> AnyElement<V> + Send + Sync + 'static>,
|
||||
pub(crate) state: Handle<V>,
|
||||
render: Arc<Mutex<dyn Fn(&mut V, &mut ViewContext<V>) -> AnyElement<V> + Send + 'static>>,
|
||||
}
|
||||
|
||||
impl<V: 'static> View<V> {
|
||||
pub fn for_handle<E>(
|
||||
state: Handle<V>,
|
||||
render: impl Fn(&mut V, &mut ViewContext<'_, '_, V>) -> E + Send + 'static,
|
||||
) -> View<V>
|
||||
where
|
||||
E: Component<V>,
|
||||
{
|
||||
View {
|
||||
state,
|
||||
render: Arc::new(Mutex::new(
|
||||
move |state: &mut V, cx: &mut ViewContext<'_, '_, V>| render(state, cx).render(),
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<V: 'static> View<V> {
|
||||
pub fn into_any(self) -> AnyView {
|
||||
AnyView {
|
||||
view: Arc::new(Mutex::new(self)),
|
||||
AnyView(Arc::new(self))
|
||||
}
|
||||
|
||||
pub fn downgrade(&self) -> WeakView<V> {
|
||||
WeakView {
|
||||
state: self.state.downgrade(),
|
||||
render: Arc::downgrade(&self.render),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<V: 'static> View<V> {
|
||||
pub fn update<C, R>(
|
||||
&self,
|
||||
cx: &mut C,
|
||||
f: impl FnOnce(&mut V, &mut C::ViewContext<'_, '_, V>) -> R,
|
||||
) -> C::Result<R>
|
||||
where
|
||||
C: VisualContext,
|
||||
{
|
||||
cx.update_view(self, f)
|
||||
}
|
||||
}
|
||||
|
||||
impl<V> Clone for View<V> {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
@@ -28,19 +67,6 @@ impl<V> Clone for View<V> {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn view<V, E>(
|
||||
state: Handle<V>,
|
||||
render: impl Fn(&mut V, &mut ViewContext<V>) -> E + Send + Sync + 'static,
|
||||
) -> View<V>
|
||||
where
|
||||
E: Component<V>,
|
||||
{
|
||||
View {
|
||||
state,
|
||||
render: Arc::new(move |state, cx| render(state, cx).render()),
|
||||
}
|
||||
}
|
||||
|
||||
impl<V: 'static, ParentViewState: 'static> Component<ParentViewState> for View<V> {
|
||||
fn render(self) -> AnyElement<ParentViewState> {
|
||||
AnyElement::new(EraseViewState {
|
||||
@@ -63,8 +89,8 @@ impl<V: 'static> Element<()> for View<V> {
|
||||
_: Option<Self::ElementState>,
|
||||
cx: &mut ViewContext<()>,
|
||||
) -> Self::ElementState {
|
||||
self.state.update(cx, |state, cx| {
|
||||
let mut any_element = (self.render)(state, cx);
|
||||
self.update(cx, |state, cx| {
|
||||
let mut any_element = (self.render.lock())(state, cx);
|
||||
any_element.initialize(state, cx);
|
||||
any_element
|
||||
})
|
||||
@@ -76,7 +102,7 @@ impl<V: 'static> Element<()> for View<V> {
|
||||
element: &mut Self::ElementState,
|
||||
cx: &mut ViewContext<()>,
|
||||
) -> LayoutId {
|
||||
self.state.update(cx, |state, cx| element.layout(state, cx))
|
||||
self.update(cx, |state, cx| element.layout(state, cx))
|
||||
}
|
||||
|
||||
fn paint(
|
||||
@@ -86,7 +112,38 @@ impl<V: 'static> Element<()> for View<V> {
|
||||
element: &mut Self::ElementState,
|
||||
cx: &mut ViewContext<()>,
|
||||
) {
|
||||
self.state.update(cx, |state, cx| element.paint(state, cx))
|
||||
self.update(cx, |state, cx| element.paint(state, cx))
|
||||
}
|
||||
}
|
||||
|
||||
pub struct WeakView<V> {
|
||||
pub(crate) state: WeakHandle<V>,
|
||||
render: Weak<Mutex<dyn Fn(&mut V, &mut ViewContext<V>) -> AnyElement<V> + Send + 'static>>,
|
||||
}
|
||||
|
||||
impl<V: 'static> WeakView<V> {
|
||||
pub fn upgrade(&self) -> Option<View<V>> {
|
||||
let state = self.state.upgrade()?;
|
||||
let render = self.render.upgrade()?;
|
||||
Some(View { state, render })
|
||||
}
|
||||
|
||||
pub fn update<R>(
|
||||
&self,
|
||||
cx: &mut WindowContext,
|
||||
f: impl FnOnce(&mut V, &mut ViewContext<V>) -> R,
|
||||
) -> Result<R> {
|
||||
let view = self.upgrade().context("error upgrading view")?;
|
||||
Ok(view.update(cx, f))
|
||||
}
|
||||
}
|
||||
|
||||
impl<V> Clone for WeakView<V> {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
state: self.state.clone(),
|
||||
render: self.render.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -96,7 +153,6 @@ struct EraseViewState<V, ParentV> {
|
||||
}
|
||||
|
||||
unsafe impl<V, ParentV> Send for EraseViewState<V, ParentV> {}
|
||||
unsafe impl<V, ParentV> Sync for EraseViewState<V, ParentV> {}
|
||||
|
||||
impl<V: 'static, ParentV: 'static> Component<ParentV> for EraseViewState<V, ParentV> {
|
||||
fn render(self) -> AnyElement<ParentV> {
|
||||
@@ -141,39 +197,39 @@ impl<V: 'static, ParentV: 'static> Element<ParentV> for EraseViewState<V, Parent
|
||||
}
|
||||
|
||||
trait ViewObject: Send + Sync {
|
||||
fn entity_handle(&self) -> &AnyHandle;
|
||||
fn initialize(&mut self, cx: &mut WindowContext) -> AnyBox;
|
||||
fn layout(&mut self, element: &mut AnyBox, cx: &mut WindowContext) -> LayoutId;
|
||||
fn paint(&mut self, bounds: Bounds<Pixels>, element: &mut AnyBox, cx: &mut WindowContext);
|
||||
fn entity_id(&self) -> EntityId;
|
||||
fn initialize(&self, cx: &mut WindowContext) -> AnyBox;
|
||||
fn layout(&self, element: &mut AnyBox, cx: &mut WindowContext) -> LayoutId;
|
||||
fn paint(&self, bounds: Bounds<Pixels>, element: &mut AnyBox, cx: &mut WindowContext);
|
||||
}
|
||||
|
||||
impl<V: 'static> ViewObject for View<V> {
|
||||
fn entity_handle(&self) -> &AnyHandle {
|
||||
&self.state
|
||||
fn entity_id(&self) -> EntityId {
|
||||
self.state.entity_id()
|
||||
}
|
||||
|
||||
fn initialize(&mut self, cx: &mut WindowContext) -> AnyBox {
|
||||
cx.with_element_id(self.state.entity_id, |_global_id, cx| {
|
||||
self.state.update(cx, |state, cx| {
|
||||
let mut any_element = Box::new((self.render)(state, cx));
|
||||
fn initialize(&self, cx: &mut WindowContext) -> AnyBox {
|
||||
cx.with_element_id(self.entity_id(), |_global_id, cx| {
|
||||
self.update(cx, |state, cx| {
|
||||
let mut any_element = Box::new((self.render.lock())(state, cx));
|
||||
any_element.initialize(state, cx);
|
||||
any_element as AnyBox
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn layout(&mut self, element: &mut AnyBox, cx: &mut WindowContext) -> LayoutId {
|
||||
cx.with_element_id(self.state.entity_id, |_global_id, cx| {
|
||||
self.state.update(cx, |state, cx| {
|
||||
fn layout(&self, element: &mut AnyBox, cx: &mut WindowContext) -> LayoutId {
|
||||
cx.with_element_id(self.entity_id(), |_global_id, cx| {
|
||||
self.update(cx, |state, cx| {
|
||||
let element = element.downcast_mut::<AnyElement<V>>().unwrap();
|
||||
element.layout(state, cx)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn paint(&mut self, _: Bounds<Pixels>, element: &mut AnyBox, cx: &mut WindowContext) {
|
||||
cx.with_element_id(self.state.entity_id, |_global_id, cx| {
|
||||
self.state.update(cx, |state, cx| {
|
||||
fn paint(&self, _: Bounds<Pixels>, element: &mut AnyBox, cx: &mut WindowContext) {
|
||||
cx.with_element_id(self.entity_id(), |_global_id, cx| {
|
||||
self.update(cx, |state, cx| {
|
||||
let element = element.downcast_mut::<AnyElement<V>>().unwrap();
|
||||
element.paint(state, cx);
|
||||
});
|
||||
@@ -181,13 +237,18 @@ impl<V: 'static> ViewObject for View<V> {
|
||||
}
|
||||
}
|
||||
|
||||
pub struct AnyView {
|
||||
view: Arc<Mutex<dyn ViewObject>>,
|
||||
}
|
||||
#[derive(Clone)]
|
||||
pub struct AnyView(Arc<dyn ViewObject>);
|
||||
|
||||
impl AnyView {
|
||||
pub fn entity_handle(&self) -> AnyHandle {
|
||||
self.view.lock().entity_handle().clone()
|
||||
pub(crate) fn draw(&self, available_space: Size<AvailableSpace>, cx: &mut WindowContext) {
|
||||
let mut rendered_element = self.0.initialize(cx);
|
||||
let layout_id = self.0.layout(&mut rendered_element, cx);
|
||||
cx.window
|
||||
.layout_engine
|
||||
.compute_layout(layout_id, available_space);
|
||||
let bounds = cx.window.layout_engine.layout_bounds(layout_id);
|
||||
self.0.paint(bounds, &mut rendered_element, cx);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -203,8 +264,8 @@ impl<ParentV: 'static> Component<ParentV> for AnyView {
|
||||
impl Element<()> for AnyView {
|
||||
type ElementState = AnyBox;
|
||||
|
||||
fn id(&self) -> Option<ElementId> {
|
||||
Some(ElementId::View(self.view.lock().entity_handle().entity_id))
|
||||
fn id(&self) -> Option<crate::ElementId> {
|
||||
Some(ElementId::View(self.0.entity_id()))
|
||||
}
|
||||
|
||||
fn initialize(
|
||||
@@ -213,7 +274,7 @@ impl Element<()> for AnyView {
|
||||
_: Option<Self::ElementState>,
|
||||
cx: &mut ViewContext<()>,
|
||||
) -> Self::ElementState {
|
||||
self.view.lock().initialize(cx)
|
||||
self.0.initialize(cx)
|
||||
}
|
||||
|
||||
fn layout(
|
||||
@@ -222,7 +283,7 @@ impl Element<()> for AnyView {
|
||||
element: &mut Self::ElementState,
|
||||
cx: &mut ViewContext<()>,
|
||||
) -> LayoutId {
|
||||
self.view.lock().layout(element, cx)
|
||||
self.0.layout(element, cx)
|
||||
}
|
||||
|
||||
fn paint(
|
||||
@@ -232,7 +293,7 @@ impl Element<()> for AnyView {
|
||||
element: &mut AnyBox,
|
||||
cx: &mut ViewContext<()>,
|
||||
) {
|
||||
self.view.lock().paint(bounds, element, cx)
|
||||
self.0.paint(bounds, element, cx)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -242,7 +303,6 @@ struct EraseAnyViewState<ParentViewState> {
|
||||
}
|
||||
|
||||
unsafe impl<ParentV> Send for EraseAnyViewState<ParentV> {}
|
||||
unsafe impl<ParentV> Sync for EraseAnyViewState<ParentV> {}
|
||||
|
||||
impl<ParentV: 'static> Component<ParentV> for EraseAnyViewState<ParentV> {
|
||||
fn render(self) -> AnyElement<ParentV> {
|
||||
@@ -263,7 +323,7 @@ impl<ParentV: 'static> Element<ParentV> for EraseAnyViewState<ParentV> {
|
||||
_: Option<Self::ElementState>,
|
||||
cx: &mut ViewContext<ParentV>,
|
||||
) -> Self::ElementState {
|
||||
self.view.view.lock().initialize(cx)
|
||||
self.view.0.initialize(cx)
|
||||
}
|
||||
|
||||
fn layout(
|
||||
@@ -272,7 +332,7 @@ impl<ParentV: 'static> Element<ParentV> for EraseAnyViewState<ParentV> {
|
||||
element: &mut Self::ElementState,
|
||||
cx: &mut ViewContext<ParentV>,
|
||||
) -> LayoutId {
|
||||
self.view.view.lock().layout(element, cx)
|
||||
self.view.0.layout(element, cx)
|
||||
}
|
||||
|
||||
fn paint(
|
||||
@@ -282,14 +342,6 @@ impl<ParentV: 'static> Element<ParentV> for EraseAnyViewState<ParentV> {
|
||||
element: &mut Self::ElementState,
|
||||
cx: &mut ViewContext<ParentV>,
|
||||
) {
|
||||
self.view.view.lock().paint(bounds, element, cx)
|
||||
}
|
||||
}
|
||||
|
||||
impl Clone for AnyView {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
view: self.view.clone(),
|
||||
}
|
||||
self.view.0.paint(bounds, element, cx)
|
||||
}
|
||||
}
|
||||
|
||||
+294
-143
@@ -1,13 +1,13 @@
|
||||
use crate::{
|
||||
px, size, Action, AnyBox, AnyDrag, AnyHandle, AnyView, AppContext, AsyncWindowContext,
|
||||
AvailableSpace, Bounds, BoxShadow, Context, Corners, DevicePixels, DispatchContext, DisplayId,
|
||||
Edges, Effect, Element, EntityId, EventEmitter, ExternalPaths, FileDropEvent, FocusEvent,
|
||||
FontId, GlobalElementId, GlyphId, Handle, Hsla, ImageData, InputEvent, IsZero, KeyListener,
|
||||
KeyMatch, KeyMatcher, Keystroke, LayoutId, MainThread, MainThreadOnly, Modifiers,
|
||||
MonochromeSprite, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, Path, Pixels,
|
||||
PlatformAtlas, PlatformWindow, Point, PolychromeSprite, Quad, Reference, RenderGlyphParams,
|
||||
RenderImageParams, RenderSvgParams, ScaledPixels, SceneBuilder, Shadow, SharedString, Size,
|
||||
Style, Subscription, TaffyLayoutEngine, Task, Underline, UnderlineStyle, WeakHandle,
|
||||
px, size, Action, AnyBox, AnyDrag, AnyView, AppContext, AsyncWindowContext, AvailableSpace,
|
||||
Bounds, BoxShadow, Context, Corners, DevicePixels, DispatchContext, DisplayId, Edges, Effect,
|
||||
EntityId, EventEmitter, ExternalPaths, FileDropEvent, FocusEvent, FontId, GlobalElementId,
|
||||
GlyphId, Handle, Hsla, ImageData, InputEvent, IsZero, KeyListener, KeyMatch, KeyMatcher,
|
||||
Keystroke, LayoutId, MainThread, MainThreadOnly, ModelContext, Modifiers, MonochromeSprite,
|
||||
MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, Path, Pixels, PlatformAtlas,
|
||||
PlatformWindow, Point, PolychromeSprite, Quad, Reference, RenderGlyphParams, RenderImageParams,
|
||||
RenderSvgParams, ScaledPixels, SceneBuilder, Shadow, SharedString, Size, Style, Subscription,
|
||||
TaffyLayoutEngine, Task, Underline, UnderlineStyle, View, VisualContext, WeakHandle, WeakView,
|
||||
WindowOptions, SUBPIXEL_VARIANTS,
|
||||
};
|
||||
use anyhow::Result;
|
||||
@@ -30,24 +30,30 @@ use std::{
|
||||
};
|
||||
use util::ResultExt;
|
||||
|
||||
/// A global stacking order, which is created by stacking successive z-index values.
|
||||
/// Each z-index will always be interpreted in the context of its parent z-index.
|
||||
#[derive(Deref, DerefMut, Ord, PartialOrd, Eq, PartialEq, Clone, Default)]
|
||||
pub struct StackingOrder(pub(crate) SmallVec<[u32; 16]>);
|
||||
pub(crate) struct StackingOrder(pub(crate) SmallVec<[u32; 16]>);
|
||||
|
||||
/// Represents the two different phases when dispatching events.
|
||||
#[derive(Default, Copy, Clone, Debug, Eq, PartialEq)]
|
||||
pub enum DispatchPhase {
|
||||
/// After the capture phase comes the bubble phase, in which event handlers are
|
||||
/// invoked front to back. This is the phase you'll usually want to use for event handlers.
|
||||
/// After the capture phase comes the bubble phase, in which mouse event listeners are
|
||||
/// invoked front to back and keyboard event listeners are invoked from the focused element
|
||||
/// to the root of the element tree. This is the phase you'll most commonly want to use when
|
||||
/// registering event listeners.
|
||||
#[default]
|
||||
Bubble,
|
||||
/// During the initial capture phase, event handlers are invoked back to front. This phase
|
||||
/// During the initial capture phase, mouse event listeners are invoked back to front, and keyboard
|
||||
/// listeners are invoked from the root of the tree downward toward the focused element. This phase
|
||||
/// is used for special purposes such as clearing the "pressed" state for click events. If
|
||||
/// you stop event propagation during this phase, you need to know what you're doing. Handlers
|
||||
/// outside of the immediate region may rely on detecting non-local events during this phase.
|
||||
Capture,
|
||||
}
|
||||
|
||||
type AnyListener = Arc<dyn Fn(&dyn Any, DispatchPhase, &mut WindowContext) + Send + Sync + 'static>;
|
||||
type AnyKeyListener = Arc<
|
||||
type AnyListener = Box<dyn Fn(&dyn Any, DispatchPhase, &mut WindowContext) + Send + 'static>;
|
||||
type AnyKeyListener = Box<
|
||||
dyn Fn(
|
||||
&dyn Any,
|
||||
&[&DispatchContext],
|
||||
@@ -55,13 +61,13 @@ type AnyKeyListener = Arc<
|
||||
&mut WindowContext,
|
||||
) -> Option<Box<dyn Action>>
|
||||
+ Send
|
||||
+ Sync
|
||||
+ 'static,
|
||||
>;
|
||||
type AnyFocusListener = Arc<dyn Fn(&FocusEvent, &mut WindowContext) + Send + Sync + 'static>;
|
||||
type AnyFocusListener = Box<dyn Fn(&FocusEvent, &mut WindowContext) + Send + 'static>;
|
||||
|
||||
slotmap::new_key_type! { pub struct FocusId; }
|
||||
|
||||
/// A handle which can be used to track and manipulate the focused element in a window.
|
||||
pub struct FocusHandle {
|
||||
pub(crate) id: FocusId,
|
||||
handles: Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
|
||||
@@ -93,20 +99,26 @@ impl FocusHandle {
|
||||
}
|
||||
}
|
||||
|
||||
/// Obtains whether the element associated with this handle is currently focused.
|
||||
pub fn is_focused(&self, cx: &WindowContext) -> bool {
|
||||
cx.window.focus == Some(self.id)
|
||||
}
|
||||
|
||||
/// Obtains whether the element associated with this handle contains the focused
|
||||
/// element or is itself focused.
|
||||
pub fn contains_focused(&self, cx: &WindowContext) -> bool {
|
||||
cx.focused()
|
||||
.map_or(false, |focused| self.contains(&focused, cx))
|
||||
}
|
||||
|
||||
/// Obtains whether the element associated with this handle is contained within the
|
||||
/// focused element or is itself focused.
|
||||
pub fn within_focused(&self, cx: &WindowContext) -> bool {
|
||||
let focused = cx.focused();
|
||||
focused.map_or(false, |focused| focused.contains(self, cx))
|
||||
}
|
||||
|
||||
/// Obtains whether this handle contains the given handle in the most recently rendered frame.
|
||||
pub(crate) fn contains(&self, other: &Self, cx: &WindowContext) -> bool {
|
||||
let mut ancestor = Some(other.id);
|
||||
while let Some(ancestor_id) = ancestor {
|
||||
@@ -144,6 +156,7 @@ impl Drop for FocusHandle {
|
||||
}
|
||||
}
|
||||
|
||||
// Holds the state for a specific window.
|
||||
pub struct Window {
|
||||
pub(crate) handle: AnyWindowHandle,
|
||||
platform_window: MainThreadOnly<Box<dyn PlatformWindow>>,
|
||||
@@ -151,7 +164,7 @@ pub struct Window {
|
||||
sprite_atlas: Arc<dyn PlatformAtlas>,
|
||||
rem_size: Pixels,
|
||||
content_size: Size<Pixels>,
|
||||
layout_engine: TaffyLayoutEngine,
|
||||
pub(crate) layout_engine: TaffyLayoutEngine,
|
||||
pub(crate) root_view: Option<AnyView>,
|
||||
pub(crate) element_id_stack: GlobalElementId,
|
||||
prev_frame_element_states: HashMap<GlobalElementId, AnyBox>,
|
||||
@@ -254,6 +267,9 @@ impl Window {
|
||||
}
|
||||
}
|
||||
|
||||
/// When constructing the element tree, we maintain a stack of key dispatch frames until we
|
||||
/// find the focused element. We interleave key listeners with dispatch contexts so we can use the
|
||||
/// contexts when matching key events against the keymap.
|
||||
enum KeyDispatchStackFrame {
|
||||
Listener {
|
||||
event_type: TypeId,
|
||||
@@ -262,6 +278,9 @@ enum KeyDispatchStackFrame {
|
||||
Context(DispatchContext),
|
||||
}
|
||||
|
||||
/// Indicates which region of the window is visible. Content falling outside of this mask will not be
|
||||
/// rendered. Currently, only rectangular content masks are supported, but we give the mask its own type
|
||||
/// to leave room to support more complex shapes in the future.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
#[repr(C)]
|
||||
pub struct ContentMask<P: Clone + Default + Debug> {
|
||||
@@ -269,20 +288,25 @@ pub struct ContentMask<P: Clone + Default + Debug> {
|
||||
}
|
||||
|
||||
impl ContentMask<Pixels> {
|
||||
/// Scale the content mask's pixel units by the given scaling factor.
|
||||
pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
|
||||
ContentMask {
|
||||
bounds: self.bounds.scale(factor),
|
||||
}
|
||||
}
|
||||
|
||||
/// Intersect the content mask with the given content mask.
|
||||
pub fn intersect(&self, other: &Self) -> Self {
|
||||
let bounds = self.bounds.intersect(&other.bounds);
|
||||
ContentMask { bounds }
|
||||
}
|
||||
}
|
||||
|
||||
/// Provides access to application state in the context of a single window. Derefs
|
||||
/// to an `AppContext`, so you can also pass a `WindowContext` to any method that takes
|
||||
/// an `AppContext` and call any `AppContext` methods.
|
||||
pub struct WindowContext<'a, 'w> {
|
||||
app: Reference<'a, AppContext>,
|
||||
pub(crate) app: Reference<'a, AppContext>,
|
||||
pub(crate) window: Reference<'w, Window>,
|
||||
}
|
||||
|
||||
@@ -301,28 +325,30 @@ impl<'a, 'w> WindowContext<'a, 'w> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Obtain a handle to the window that belongs to this context.
|
||||
pub fn window_handle(&self) -> AnyWindowHandle {
|
||||
self.window.handle
|
||||
}
|
||||
|
||||
pub fn root_view(&self) -> Option<AnyHandle> {
|
||||
Some(self.window.root_view.as_ref()?.entity_handle())
|
||||
}
|
||||
|
||||
/// Mark the window as dirty, scheduling it to be redrawn on the next frame.
|
||||
pub fn notify(&mut self) {
|
||||
self.window.dirty = true;
|
||||
}
|
||||
|
||||
/// Obtain a new `FocusHandle`, which allows you to track and manipulate the keyboard focus
|
||||
/// for elements rendered within this window.
|
||||
pub fn focus_handle(&mut self) -> FocusHandle {
|
||||
FocusHandle::new(&self.window.focus_handles)
|
||||
}
|
||||
|
||||
/// Obtain the currently focused `FocusHandle`. If no elements are focused, returns `None`.
|
||||
pub fn focused(&self) -> Option<FocusHandle> {
|
||||
self.window
|
||||
.focus
|
||||
.and_then(|id| FocusHandle::for_id(id, &self.window.focus_handles))
|
||||
}
|
||||
|
||||
/// Move focus to the element associated with the given `FocusHandle`.
|
||||
pub fn focus(&mut self, handle: &FocusHandle) {
|
||||
if self.window.last_blur.is_none() {
|
||||
self.window.last_blur = Some(self.window.focus);
|
||||
@@ -336,6 +362,7 @@ impl<'a, 'w> WindowContext<'a, 'w> {
|
||||
self.notify();
|
||||
}
|
||||
|
||||
/// Remove focus from all elements within this context's window.
|
||||
pub fn blur(&mut self) {
|
||||
if self.window.last_blur.is_none() {
|
||||
self.window.last_blur = Some(self.window.focus);
|
||||
@@ -349,6 +376,9 @@ impl<'a, 'w> WindowContext<'a, 'w> {
|
||||
self.notify();
|
||||
}
|
||||
|
||||
/// Schedule the given closure to be run on the main thread. It will be invoked with
|
||||
/// a `MainThread<WindowContext>`, which provides access to platform-specific functionality
|
||||
/// of the window.
|
||||
pub fn run_on_main<R>(
|
||||
&mut self,
|
||||
f: impl FnOnce(&mut MainThread<WindowContext<'_, '_>>) -> R + Send + 'static,
|
||||
@@ -366,10 +396,13 @@ impl<'a, 'w> WindowContext<'a, 'w> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Create an `AsyncWindowContext`, which has a static lifetime and can be held across
|
||||
/// await points in async code.
|
||||
pub fn to_async(&self) -> AsyncWindowContext {
|
||||
AsyncWindowContext::new(self.app.to_async(), self.window.handle)
|
||||
}
|
||||
|
||||
/// Schedule the given closure to be run directly after the current frame is rendered.
|
||||
pub fn on_next_frame(&mut self, f: impl FnOnce(&mut WindowContext) + Send + 'static) {
|
||||
let f = Box::new(f);
|
||||
let display_id = self.window.display_id;
|
||||
@@ -413,6 +446,9 @@ impl<'a, 'w> WindowContext<'a, 'w> {
|
||||
.detach();
|
||||
}
|
||||
|
||||
/// Spawn the future returned by the given closure on the application thread pool.
|
||||
/// The closure is provided a handle to the current window and an `AsyncWindowContext` for
|
||||
/// use within your future.
|
||||
pub fn spawn<Fut, R>(
|
||||
&mut self,
|
||||
f: impl FnOnce(AnyWindowHandle, AsyncWindowContext) -> Fut + Send + 'static,
|
||||
@@ -429,6 +465,8 @@ impl<'a, 'w> WindowContext<'a, 'w> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Update the global of the given type. The given closure is given simultaneous mutable
|
||||
/// access both to the global and the context.
|
||||
pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
|
||||
where
|
||||
G: 'static,
|
||||
@@ -439,6 +477,9 @@ impl<'a, 'w> WindowContext<'a, 'w> {
|
||||
result
|
||||
}
|
||||
|
||||
/// Add a node to the layout tree for the current frame. Takes the `Style` of the element for which
|
||||
/// layout is being requested, along with the layout ids of any children. This method is called during
|
||||
/// calls to the `Element::layout` trait method and enables any element to participate in layout.
|
||||
pub fn request_layout(
|
||||
&mut self,
|
||||
style: &Style,
|
||||
@@ -453,6 +494,12 @@ impl<'a, 'w> WindowContext<'a, 'w> {
|
||||
.request_layout(style, rem_size, &self.app.layout_id_buffer)
|
||||
}
|
||||
|
||||
/// Add a node to the layout tree for the current frame. Instead of taking a `Style` and children,
|
||||
/// this variant takes a function that is invoked during layout so you can use arbitrary logic to
|
||||
/// determine the element's size. One place this is used internally is when measuring text.
|
||||
///
|
||||
/// The given closure is invoked at layout time with the known dimensions and available space and
|
||||
/// returns a `Size`.
|
||||
pub fn request_measured_layout<
|
||||
F: Fn(Size<Option<Pixels>>, Size<AvailableSpace>) -> Size<Pixels> + Send + Sync + 'static,
|
||||
>(
|
||||
@@ -466,6 +513,9 @@ impl<'a, 'w> WindowContext<'a, 'w> {
|
||||
.request_measured_layout(style, rem_size, measure)
|
||||
}
|
||||
|
||||
/// Obtain the bounds computed for the given LayoutId relative to the window. This method should not
|
||||
/// be invoked until the paint phase begins, and will usually be invoked by GPUI itself automatically
|
||||
/// in order to pass your element its `Bounds` automatically.
|
||||
pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
|
||||
let mut bounds = self
|
||||
.window
|
||||
@@ -476,14 +526,20 @@ impl<'a, 'w> WindowContext<'a, 'w> {
|
||||
bounds
|
||||
}
|
||||
|
||||
/// The scale factor of the display associated with the window. For example, it could
|
||||
/// return 2.0 for a "retina" display, indicating that each logical pixel should actually
|
||||
/// be rendered as two pixels on screen.
|
||||
pub fn scale_factor(&self) -> f32 {
|
||||
self.window.scale_factor
|
||||
}
|
||||
|
||||
/// The size of an em for the base font of the application. Adjusting this value allows the
|
||||
/// UI to scale, just like zooming a web page.
|
||||
pub fn rem_size(&self) -> Pixels {
|
||||
self.window.rem_size
|
||||
}
|
||||
|
||||
/// The line height associated with the current text style.
|
||||
pub fn line_height(&self) -> Pixels {
|
||||
let rem_size = self.rem_size();
|
||||
let text_style = self.text_style();
|
||||
@@ -492,17 +548,26 @@ impl<'a, 'w> WindowContext<'a, 'w> {
|
||||
.to_pixels(text_style.font_size.into(), rem_size)
|
||||
}
|
||||
|
||||
/// Call to prevent the default action of an event. Currently only used to prevent
|
||||
/// parent elements from becoming focused on mouse down.
|
||||
pub fn prevent_default(&mut self) {
|
||||
self.window.default_prevented = true;
|
||||
}
|
||||
|
||||
/// Obtain whether default has been prevented for the event currently being dispatched.
|
||||
pub fn default_prevented(&self) -> bool {
|
||||
self.window.default_prevented
|
||||
}
|
||||
|
||||
/// Register a mouse event listener on the window for the current frame. The type of event
|
||||
/// is determined by the first parameter of the given listener. When the next frame is rendered
|
||||
/// the listener will be cleared.
|
||||
///
|
||||
/// This is a fairly low-level method, so prefer using event handlers on elements unless you have
|
||||
/// a specific need to register a global listener.
|
||||
pub fn on_mouse_event<Event: 'static>(
|
||||
&mut self,
|
||||
handler: impl Fn(&Event, DispatchPhase, &mut WindowContext) + Send + Sync + 'static,
|
||||
handler: impl Fn(&Event, DispatchPhase, &mut WindowContext) + Send + 'static,
|
||||
) {
|
||||
let order = self.window.z_index_stack.clone();
|
||||
self.window
|
||||
@@ -511,23 +576,27 @@ impl<'a, 'w> WindowContext<'a, 'w> {
|
||||
.or_default()
|
||||
.push((
|
||||
order,
|
||||
Arc::new(move |event: &dyn Any, phase, cx| {
|
||||
Box::new(move |event: &dyn Any, phase, cx| {
|
||||
handler(event.downcast_ref().unwrap(), phase, cx)
|
||||
}),
|
||||
))
|
||||
}
|
||||
|
||||
/// The position of the mouse relative to the window.
|
||||
pub fn mouse_position(&self) -> Point<Pixels> {
|
||||
self.window.mouse_position
|
||||
}
|
||||
|
||||
pub fn stack<R>(&mut self, order: u32, f: impl FnOnce(&mut Self) -> R) -> R {
|
||||
self.window.z_index_stack.push(order);
|
||||
/// Called during painting to invoke the given closure in a new stacking context. The given
|
||||
/// z-index is interpreted relative to the previous call to `stack`.
|
||||
pub fn stack<R>(&mut self, z_index: u32, f: impl FnOnce(&mut Self) -> R) -> R {
|
||||
self.window.z_index_stack.push(z_index);
|
||||
let result = f(self);
|
||||
self.window.z_index_stack.pop();
|
||||
result
|
||||
}
|
||||
|
||||
/// Paint one or more drop shadows into the scene for the current frame at the current z-index.
|
||||
pub fn paint_shadows(
|
||||
&mut self,
|
||||
bounds: Bounds<Pixels>,
|
||||
@@ -555,6 +624,8 @@ impl<'a, 'w> WindowContext<'a, 'w> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Paint one or more quads into the scene for the current frame at the current stacking context.
|
||||
/// Quads are colored rectangular regions with an optional background, border, and corner radius.
|
||||
pub fn paint_quad(
|
||||
&mut self,
|
||||
bounds: Bounds<Pixels>,
|
||||
@@ -581,6 +652,7 @@ impl<'a, 'w> WindowContext<'a, 'w> {
|
||||
);
|
||||
}
|
||||
|
||||
/// Paint the given `Path` into the scene for the current frame at the current z-index.
|
||||
pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Hsla>) {
|
||||
let scale_factor = self.scale_factor();
|
||||
let content_mask = self.content_mask();
|
||||
@@ -592,6 +664,7 @@ impl<'a, 'w> WindowContext<'a, 'w> {
|
||||
.insert(&window.z_index_stack, path.scale(scale_factor));
|
||||
}
|
||||
|
||||
/// Paint an underline into the scene for the current frame at the current z-index.
|
||||
pub fn paint_underline(
|
||||
&mut self,
|
||||
origin: Point<Pixels>,
|
||||
@@ -624,6 +697,7 @@ impl<'a, 'w> WindowContext<'a, 'w> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Paint a monochrome (non-emoji) glyph into the scene for the current frame at the current z-index.
|
||||
pub fn paint_glyph(
|
||||
&mut self,
|
||||
origin: Point<Pixels>,
|
||||
@@ -676,6 +750,7 @@ impl<'a, 'w> WindowContext<'a, 'w> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Paint an emoji glyph into the scene for the current frame at the current z-index.
|
||||
pub fn paint_emoji(
|
||||
&mut self,
|
||||
origin: Point<Pixels>,
|
||||
@@ -726,6 +801,7 @@ impl<'a, 'w> WindowContext<'a, 'w> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Paint a monochrome SVG into the scene for the current frame at the current stacking context.
|
||||
pub fn paint_svg(
|
||||
&mut self,
|
||||
bounds: Bounds<Pixels>,
|
||||
@@ -766,6 +842,7 @@ impl<'a, 'w> WindowContext<'a, 'w> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Paint an image into the scene for the current frame at the current z-index.
|
||||
pub fn paint_image(
|
||||
&mut self,
|
||||
bounds: Bounds<Pixels>,
|
||||
@@ -801,61 +878,42 @@ impl<'a, 'w> WindowContext<'a, 'w> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Draw pixels to the display for this window based on the contents of its scene.
|
||||
pub(crate) fn draw(&mut self) {
|
||||
let unit_entity = self.unit_entity.clone();
|
||||
self.update_entity(&unit_entity, |view, cx| {
|
||||
cx.start_frame();
|
||||
let root_view = self.window.root_view.take().unwrap();
|
||||
|
||||
let mut root_view = cx.window.root_view.take().unwrap();
|
||||
self.start_frame();
|
||||
|
||||
cx.stack(0, |cx| {
|
||||
let available_space = cx.window.content_size.map(Into::into);
|
||||
draw_any_view(&mut root_view, available_space, cx);
|
||||
});
|
||||
|
||||
if let Some(mut active_drag) = cx.active_drag.take() {
|
||||
cx.stack(1, |cx| {
|
||||
let offset = cx.mouse_position() - active_drag.cursor_offset;
|
||||
cx.with_element_offset(Some(offset), |cx| {
|
||||
let available_space =
|
||||
size(AvailableSpace::MinContent, AvailableSpace::MinContent);
|
||||
if let Some(drag_handle_view) = &mut active_drag.drag_handle_view {
|
||||
draw_any_view(drag_handle_view, available_space, cx);
|
||||
}
|
||||
cx.active_drag = Some(active_drag);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
cx.window.root_view = Some(root_view);
|
||||
let scene = cx.window.scene_builder.build();
|
||||
|
||||
cx.run_on_main(view, |_, cx| {
|
||||
cx.window
|
||||
.platform_window
|
||||
.borrow_on_main_thread()
|
||||
.draw(scene);
|
||||
cx.window.dirty = false;
|
||||
})
|
||||
.detach();
|
||||
self.stack(0, |cx| {
|
||||
let available_space = cx.window.content_size.map(Into::into);
|
||||
root_view.draw(available_space, cx);
|
||||
});
|
||||
|
||||
fn draw_any_view(
|
||||
view: &mut AnyView,
|
||||
available_space: Size<AvailableSpace>,
|
||||
cx: &mut ViewContext<()>,
|
||||
) {
|
||||
cx.with_optional_element_state(view.id(), |element_state, cx| {
|
||||
let mut element_state = view.initialize(&mut (), element_state, cx);
|
||||
let layout_id = view.layout(&mut (), &mut element_state, cx);
|
||||
cx.window
|
||||
.layout_engine
|
||||
.compute_layout(layout_id, available_space);
|
||||
let bounds = cx.window.layout_engine.layout_bounds(layout_id);
|
||||
view.paint(bounds, &mut (), &mut element_state, cx);
|
||||
((), element_state)
|
||||
if let Some(mut active_drag) = self.app.active_drag.take() {
|
||||
self.stack(1, |cx| {
|
||||
let offset = cx.mouse_position() - active_drag.cursor_offset;
|
||||
cx.with_element_offset(Some(offset), |cx| {
|
||||
let available_space =
|
||||
size(AvailableSpace::MinContent, AvailableSpace::MinContent);
|
||||
if let Some(drag_handle_view) = &mut active_drag.drag_handle_view {
|
||||
drag_handle_view.draw(available_space, cx);
|
||||
}
|
||||
cx.active_drag = Some(active_drag);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
self.window.root_view = Some(root_view);
|
||||
let scene = self.window.scene_builder.build();
|
||||
|
||||
self.run_on_main(|cx| {
|
||||
cx.window
|
||||
.platform_window
|
||||
.borrow_on_main_thread()
|
||||
.draw(scene);
|
||||
cx.window.dirty = false;
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
|
||||
fn start_frame(&mut self) {
|
||||
@@ -893,12 +951,17 @@ impl<'a, 'w> WindowContext<'a, 'w> {
|
||||
window.freeze_key_dispatch_stack = false;
|
||||
}
|
||||
|
||||
/// Dispatch a mouse or keyboard event on the window.
|
||||
fn dispatch_event(&mut self, event: InputEvent) -> bool {
|
||||
let event = match event {
|
||||
// Track the mouse position with our own state, since accessing the platform
|
||||
// API for the mouse position can only occur on the main thread.
|
||||
InputEvent::MouseMove(mouse_move) => {
|
||||
self.window.mouse_position = mouse_move.position;
|
||||
InputEvent::MouseMove(mouse_move)
|
||||
}
|
||||
// Translate dragging and dropping of external files from the operating system
|
||||
// to internal drag and drop events.
|
||||
InputEvent::FileDrop(file_drop) => match file_drop {
|
||||
FileDropEvent::Entered { position, files } => {
|
||||
self.window.mouse_position = position;
|
||||
@@ -1059,6 +1122,7 @@ impl<'a, 'w> WindowContext<'a, 'w> {
|
||||
true
|
||||
}
|
||||
|
||||
/// Attempt to map a keystroke to an action based on the keymap.
|
||||
pub fn match_keystroke(
|
||||
&mut self,
|
||||
element_id: &GlobalElementId,
|
||||
@@ -1081,9 +1145,11 @@ impl<'a, 'w> WindowContext<'a, 'w> {
|
||||
key_match
|
||||
}
|
||||
|
||||
/// Register the given handler to be invoked whenever the global of the given type
|
||||
/// is updated.
|
||||
pub fn observe_global<G: 'static>(
|
||||
&mut self,
|
||||
f: impl Fn(&mut WindowContext<'_, '_>) + Send + Sync + 'static,
|
||||
f: impl Fn(&mut WindowContext<'_, '_>) + Send + 'static,
|
||||
) -> Subscription {
|
||||
let window_handle = self.window.handle;
|
||||
self.global_observers.insert(
|
||||
@@ -1182,40 +1248,74 @@ impl<'a, 'w> MainThread<WindowContext<'a, 'w>> {
|
||||
}
|
||||
|
||||
impl Context for WindowContext<'_, '_> {
|
||||
type EntityContext<'a, 'w, T> = ViewContext<'a, 'w, T>;
|
||||
type EntityContext<'a, T> = ModelContext<'a, T>;
|
||||
type Result<T> = T;
|
||||
|
||||
fn entity<T>(
|
||||
&mut self,
|
||||
build_entity: impl FnOnce(&mut Self::EntityContext<'_, '_, T>) -> T,
|
||||
build_entity: impl FnOnce(&mut Self::EntityContext<'_, T>) -> T,
|
||||
) -> Handle<T>
|
||||
where
|
||||
T: Any + Send + Sync,
|
||||
T: 'static + Send,
|
||||
{
|
||||
let slot = self.app.entities.reserve();
|
||||
let entity = build_entity(&mut ViewContext::mutable(
|
||||
&mut *self.app,
|
||||
&mut self.window,
|
||||
slot.downgrade(),
|
||||
));
|
||||
let entity = build_entity(&mut ModelContext::mutable(&mut *self.app, slot.downgrade()));
|
||||
self.entities.insert(slot, entity)
|
||||
}
|
||||
|
||||
fn update_entity<T: 'static, R>(
|
||||
&mut self,
|
||||
handle: &Handle<T>,
|
||||
update: impl FnOnce(&mut T, &mut Self::EntityContext<'_, '_, T>) -> R,
|
||||
update: impl FnOnce(&mut T, &mut Self::EntityContext<'_, T>) -> R,
|
||||
) -> R {
|
||||
let mut entity = self.entities.lease(handle);
|
||||
let result = update(
|
||||
&mut *entity,
|
||||
&mut ViewContext::mutable(&mut *self.app, &mut *self.window, handle.downgrade()),
|
||||
&mut ModelContext::mutable(&mut *self.app, handle.downgrade()),
|
||||
);
|
||||
self.entities.end_lease(entity);
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
impl VisualContext for WindowContext<'_, '_> {
|
||||
type ViewContext<'a, 'w, V> = ViewContext<'a, 'w, V>;
|
||||
|
||||
/// Builds a new view in the current window. The first argument is a function that builds
|
||||
/// an entity representing the view's state. It is invoked with a `ViewContext` that provides
|
||||
/// entity-specific access to the window and application state during construction. The second
|
||||
/// argument is a render function that returns a component based on the view's state.
|
||||
fn build_view<E, V>(
|
||||
&mut self,
|
||||
build_view_state: impl FnOnce(&mut Self::ViewContext<'_, '_, V>) -> V,
|
||||
render: impl Fn(&mut V, &mut ViewContext<'_, '_, V>) -> E + Send + 'static,
|
||||
) -> Self::Result<View<V>>
|
||||
where
|
||||
E: crate::Component<V>,
|
||||
V: 'static + Send,
|
||||
{
|
||||
let slot = self.app.entities.reserve();
|
||||
let view = View::for_handle(slot.clone(), render);
|
||||
let mut cx = ViewContext::mutable(&mut *self.app, &mut *self.window, view.downgrade());
|
||||
let entity = build_view_state(&mut cx);
|
||||
self.entities.insert(slot, entity);
|
||||
view
|
||||
}
|
||||
|
||||
/// Update the given view. Prefer calling `View::update` instead, which calls this method.
|
||||
fn update_view<T: 'static, R>(
|
||||
&mut self,
|
||||
view: &View<T>,
|
||||
update: impl FnOnce(&mut T, &mut Self::ViewContext<'_, '_, T>) -> R,
|
||||
) -> Self::Result<R> {
|
||||
let mut lease = self.app.entities.lease(&view.state);
|
||||
let mut cx = ViewContext::mutable(&mut *self.app, &mut *self.window, view.downgrade());
|
||||
let result = update(&mut *lease, &mut cx);
|
||||
cx.app.entities.end_lease(lease);
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, 'w> std::ops::Deref for WindowContext<'a, 'w> {
|
||||
type Target = AppContext;
|
||||
|
||||
@@ -1255,6 +1355,10 @@ pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
|
||||
self.borrow_mut()
|
||||
}
|
||||
|
||||
/// Pushes the given element id onto the global stack and invokes the given closure
|
||||
/// with a `GlobalElementId`, which disambiguates the given id in the context of its ancestor
|
||||
/// ids. Because elements are discarded and recreated on each frame, the `GlobalElementId` is
|
||||
/// used to associate state with identified elements across separate frames.
|
||||
fn with_element_id<R>(
|
||||
&mut self,
|
||||
id: impl Into<ElementId>,
|
||||
@@ -1281,6 +1385,8 @@ pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
|
||||
result
|
||||
}
|
||||
|
||||
/// Invoke the given function with the given content mask after intersecting it
|
||||
/// with the current mask.
|
||||
fn with_content_mask<R>(
|
||||
&mut self,
|
||||
mask: ContentMask<Pixels>,
|
||||
@@ -1293,6 +1399,8 @@ pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
|
||||
result
|
||||
}
|
||||
|
||||
/// Update the global element offset based on the given offset. This is used to implement
|
||||
/// scrolling and position drag handles.
|
||||
fn with_element_offset<R>(
|
||||
&mut self,
|
||||
offset: Option<Point<Pixels>>,
|
||||
@@ -1309,6 +1417,7 @@ pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
|
||||
result
|
||||
}
|
||||
|
||||
/// Obtain the current element offset.
|
||||
fn element_offset(&self) -> Point<Pixels> {
|
||||
self.window()
|
||||
.element_offset_stack
|
||||
@@ -1317,13 +1426,17 @@ pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Update or intialize state for an element with the given id that lives across multiple
|
||||
/// frames. If an element with this id existed in the previous frame, its state will be passed
|
||||
/// to the given closure. The state returned by the closure will be stored so it can be referenced
|
||||
/// when drawing the next frame.
|
||||
fn with_element_state<S, R>(
|
||||
&mut self,
|
||||
id: ElementId,
|
||||
f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
|
||||
) -> R
|
||||
where
|
||||
S: Any + Send + Sync,
|
||||
S: 'static + Send,
|
||||
{
|
||||
self.with_element_id(id, |global_id, cx| {
|
||||
if let Some(any) = cx
|
||||
@@ -1353,13 +1466,15 @@ pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Like `with_element_state`, but for situations where the element_id is optional. If the
|
||||
/// id is `None`, no state will be retrieved or stored.
|
||||
fn with_optional_element_state<S, R>(
|
||||
&mut self,
|
||||
element_id: Option<ElementId>,
|
||||
f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
|
||||
) -> R
|
||||
where
|
||||
S: Any + Send + Sync,
|
||||
S: 'static + Send,
|
||||
{
|
||||
if let Some(element_id) = element_id {
|
||||
self.with_element_state(element_id, f)
|
||||
@@ -1368,6 +1483,7 @@ pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Obtain the current content mask.
|
||||
fn content_mask(&self) -> ContentMask<Pixels> {
|
||||
self.window()
|
||||
.content_mask_stack
|
||||
@@ -1381,6 +1497,8 @@ pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
|
||||
})
|
||||
}
|
||||
|
||||
/// The size of an em for the base font of the application. Adjusting this value allows the
|
||||
/// UI to scale, just like zooming a web page.
|
||||
fn rem_size(&self) -> Pixels {
|
||||
self.window().rem_size
|
||||
}
|
||||
@@ -1402,7 +1520,7 @@ impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}
|
||||
|
||||
pub struct ViewContext<'a, 'w, V> {
|
||||
window_cx: WindowContext<'a, 'w>,
|
||||
view_state: WeakHandle<V>,
|
||||
view: WeakView<V>,
|
||||
}
|
||||
|
||||
impl<V> Borrow<AppContext> for ViewContext<'_, '_, V> {
|
||||
@@ -1430,15 +1548,23 @@ impl<V> BorrowMut<Window> for ViewContext<'_, '_, V> {
|
||||
}
|
||||
|
||||
impl<'a, 'w, V: 'static> ViewContext<'a, 'w, V> {
|
||||
fn mutable(app: &'a mut AppContext, window: &'w mut Window, view_state: WeakHandle<V>) -> Self {
|
||||
pub(crate) fn mutable(
|
||||
app: &'a mut AppContext,
|
||||
window: &'w mut Window,
|
||||
view: WeakView<V>,
|
||||
) -> Self {
|
||||
Self {
|
||||
window_cx: WindowContext::mutable(app, window),
|
||||
view_state,
|
||||
view,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn view(&self) -> WeakView<V> {
|
||||
self.view.clone()
|
||||
}
|
||||
|
||||
pub fn handle(&self) -> WeakHandle<V> {
|
||||
self.view_state.clone()
|
||||
self.view.state.clone()
|
||||
}
|
||||
|
||||
pub fn stack<R>(&mut self, order: u32, f: impl FnOnce(&mut Self) -> R) -> R {
|
||||
@@ -1450,27 +1576,22 @@ impl<'a, 'w, V: 'static> ViewContext<'a, 'w, V> {
|
||||
|
||||
pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + Send + 'static)
|
||||
where
|
||||
V: Any + Send + Sync,
|
||||
V: Any + Send,
|
||||
{
|
||||
let entity = self.handle();
|
||||
self.window_cx.on_next_frame(move |cx| {
|
||||
entity.update(cx, f).ok();
|
||||
});
|
||||
let view = self.view().upgrade().unwrap();
|
||||
self.window_cx.on_next_frame(move |cx| view.update(cx, f));
|
||||
}
|
||||
|
||||
pub fn observe<E>(
|
||||
&mut self,
|
||||
handle: &Handle<E>,
|
||||
mut on_notify: impl FnMut(&mut V, Handle<E>, &mut ViewContext<'_, '_, V>)
|
||||
+ Send
|
||||
+ Sync
|
||||
+ 'static,
|
||||
mut on_notify: impl FnMut(&mut V, Handle<E>, &mut ViewContext<'_, '_, V>) + Send + 'static,
|
||||
) -> Subscription
|
||||
where
|
||||
E: 'static,
|
||||
V: Any + Send + Sync,
|
||||
V: Any + Send,
|
||||
{
|
||||
let this = self.handle();
|
||||
let view = self.view();
|
||||
let handle = handle.downgrade();
|
||||
let window_handle = self.window.handle;
|
||||
self.app.observers.insert(
|
||||
@@ -1478,7 +1599,7 @@ impl<'a, 'w, V: 'static> ViewContext<'a, 'w, V> {
|
||||
Box::new(move |cx| {
|
||||
cx.update_window(window_handle, |cx| {
|
||||
if let Some(handle) = handle.upgrade() {
|
||||
this.update(cx, |this, cx| on_notify(this, handle, cx))
|
||||
view.update(cx, |this, cx| on_notify(this, handle, cx))
|
||||
.is_ok()
|
||||
} else {
|
||||
false
|
||||
@@ -1494,10 +1615,9 @@ impl<'a, 'w, V: 'static> ViewContext<'a, 'w, V> {
|
||||
handle: &Handle<E>,
|
||||
mut on_event: impl FnMut(&mut V, Handle<E>, &E::Event, &mut ViewContext<'_, '_, V>)
|
||||
+ Send
|
||||
+ Sync
|
||||
+ 'static,
|
||||
) -> Subscription {
|
||||
let this = self.handle();
|
||||
let view = self.view();
|
||||
let handle = handle.downgrade();
|
||||
let window_handle = self.window.handle;
|
||||
self.app.event_listeners.insert(
|
||||
@@ -1506,7 +1626,7 @@ impl<'a, 'w, V: 'static> ViewContext<'a, 'w, V> {
|
||||
cx.update_window(window_handle, |cx| {
|
||||
if let Some(handle) = handle.upgrade() {
|
||||
let event = event.downcast_ref().expect("invalid event type");
|
||||
this.update(cx, |this, cx| on_event(this, handle, event, cx))
|
||||
view.update(cx, |this, cx| on_event(this, handle, event, cx))
|
||||
.is_ok()
|
||||
} else {
|
||||
false
|
||||
@@ -1519,11 +1639,11 @@ impl<'a, 'w, V: 'static> ViewContext<'a, 'w, V> {
|
||||
|
||||
pub fn on_release(
|
||||
&mut self,
|
||||
mut on_release: impl FnMut(&mut V, &mut WindowContext) + Send + Sync + 'static,
|
||||
mut on_release: impl FnMut(&mut V, &mut WindowContext) + Send + 'static,
|
||||
) -> Subscription {
|
||||
let window_handle = self.window.handle;
|
||||
self.app.release_listeners.insert(
|
||||
self.view_state.entity_id,
|
||||
self.view.state.entity_id,
|
||||
Box::new(move |this, cx| {
|
||||
let this = this.downcast_mut().expect("invalid entity type");
|
||||
// todo!("are we okay with silently swallowing the error?")
|
||||
@@ -1535,30 +1655,37 @@ impl<'a, 'w, V: 'static> ViewContext<'a, 'w, V> {
|
||||
pub fn observe_release<T: 'static>(
|
||||
&mut self,
|
||||
handle: &Handle<T>,
|
||||
mut on_release: impl FnMut(&mut V, &mut T, &mut ViewContext<'_, '_, V>) + Send + Sync + 'static,
|
||||
) -> Subscription {
|
||||
let this = self.handle();
|
||||
mut on_release: impl FnMut(&mut V, &mut T, &mut ViewContext<'_, '_, V>) + Send + 'static,
|
||||
) -> Subscription
|
||||
where
|
||||
V: Any + Send,
|
||||
{
|
||||
let view = self.view();
|
||||
let window_handle = self.window.handle;
|
||||
self.app.observe_release(handle, move |entity, cx| {
|
||||
let _ = cx.update_window(window_handle, |cx| {
|
||||
this.update(cx, |this, cx| on_release(this, entity, cx))
|
||||
});
|
||||
})
|
||||
self.app.release_listeners.insert(
|
||||
handle.entity_id,
|
||||
Box::new(move |entity, cx| {
|
||||
let entity = entity.downcast_mut().expect("invalid entity type");
|
||||
let _ = cx.update_window(window_handle, |cx| {
|
||||
view.update(cx, |this, cx| on_release(this, entity, cx))
|
||||
});
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn notify(&mut self) {
|
||||
self.window_cx.notify();
|
||||
self.window_cx.app.push_effect(Effect::Notify {
|
||||
emitter: self.view_state.entity_id,
|
||||
emitter: self.view.state.entity_id,
|
||||
});
|
||||
}
|
||||
|
||||
pub fn on_focus_changed(
|
||||
&mut self,
|
||||
listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + Send + Sync + 'static,
|
||||
listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + Send + 'static,
|
||||
) {
|
||||
let handle = self.handle();
|
||||
self.window.focus_listeners.push(Arc::new(move |event, cx| {
|
||||
let handle = self.view();
|
||||
self.window.focus_listeners.push(Box::new(move |event, cx| {
|
||||
handle
|
||||
.update(cx, |view, cx| listener(view, event, cx))
|
||||
.log_err();
|
||||
@@ -1567,13 +1694,14 @@ impl<'a, 'w, V: 'static> ViewContext<'a, 'w, V> {
|
||||
|
||||
pub fn with_key_listeners<R>(
|
||||
&mut self,
|
||||
key_listeners: &[(TypeId, KeyListener<V>)],
|
||||
key_listeners: impl IntoIterator<Item = (TypeId, KeyListener<V>)>,
|
||||
f: impl FnOnce(&mut Self) -> R,
|
||||
) -> R {
|
||||
let old_stack_len = self.window.key_dispatch_stack.len();
|
||||
if !self.window.freeze_key_dispatch_stack {
|
||||
for (event_type, listener) in key_listeners.iter().cloned() {
|
||||
let handle = self.handle();
|
||||
let listener = Arc::new(
|
||||
for (event_type, listener) in key_listeners {
|
||||
let handle = self.view();
|
||||
let listener = Box::new(
|
||||
move |event: &dyn Any,
|
||||
context_stack: &[&DispatchContext],
|
||||
phase: DispatchPhase,
|
||||
@@ -1598,8 +1726,7 @@ impl<'a, 'w, V: 'static> ViewContext<'a, 'w, V> {
|
||||
let result = f(self);
|
||||
|
||||
if !self.window.freeze_key_dispatch_stack {
|
||||
let prev_len = self.window.key_dispatch_stack.len() - key_listeners.len();
|
||||
self.window.key_dispatch_stack.truncate(prev_len);
|
||||
self.window.key_dispatch_stack.truncate(old_stack_len);
|
||||
}
|
||||
|
||||
result
|
||||
@@ -1663,29 +1790,29 @@ impl<'a, 'w, V: 'static> ViewContext<'a, 'w, V> {
|
||||
let cx = unsafe { mem::transmute::<&mut Self, &mut MainThread<Self>>(self) };
|
||||
Task::ready(Ok(f(view, cx)))
|
||||
} else {
|
||||
let handle = self.handle().upgrade().unwrap();
|
||||
self.window_cx.run_on_main(move |cx| handle.update(cx, f))
|
||||
let view = self.view().upgrade().unwrap();
|
||||
self.window_cx.run_on_main(move |cx| view.update(cx, f))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn spawn<Fut, R>(
|
||||
&mut self,
|
||||
f: impl FnOnce(WeakHandle<V>, AsyncWindowContext) -> Fut + Send + 'static,
|
||||
f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut + Send + 'static,
|
||||
) -> Task<R>
|
||||
where
|
||||
R: Send + 'static,
|
||||
Fut: Future<Output = R> + Send + 'static,
|
||||
{
|
||||
let handle = self.handle();
|
||||
let view = self.view();
|
||||
self.window_cx.spawn(move |_, cx| {
|
||||
let result = f(handle, cx);
|
||||
let result = f(view, cx);
|
||||
async move { result.await }
|
||||
})
|
||||
}
|
||||
|
||||
pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
|
||||
where
|
||||
G: 'static + Send + Sync,
|
||||
G: 'static + Send,
|
||||
{
|
||||
let mut global = self.app.lease_global::<G>();
|
||||
let result = f(&mut global, self);
|
||||
@@ -1695,10 +1822,10 @@ impl<'a, 'w, V: 'static> ViewContext<'a, 'w, V> {
|
||||
|
||||
pub fn observe_global<G: 'static>(
|
||||
&mut self,
|
||||
f: impl Fn(&mut V, &mut ViewContext<'_, '_, V>) + Send + Sync + 'static,
|
||||
f: impl Fn(&mut V, &mut ViewContext<'_, '_, V>) + Send + 'static,
|
||||
) -> Subscription {
|
||||
let window_handle = self.window.handle;
|
||||
let handle = self.handle();
|
||||
let handle = self.view();
|
||||
self.global_observers.insert(
|
||||
TypeId::of::<G>(),
|
||||
Box::new(move |cx| {
|
||||
@@ -1712,9 +1839,9 @@ impl<'a, 'w, V: 'static> ViewContext<'a, 'w, V> {
|
||||
|
||||
pub fn on_mouse_event<Event: 'static>(
|
||||
&mut self,
|
||||
handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + Send + Sync + 'static,
|
||||
handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + Send + 'static,
|
||||
) {
|
||||
let handle = self.handle().upgrade().unwrap();
|
||||
let handle = self.view().upgrade().unwrap();
|
||||
self.window_cx.on_mouse_event(move |event, phase, cx| {
|
||||
handle.update(cx, |view, cx| {
|
||||
handler(view, event, phase, cx);
|
||||
@@ -1726,10 +1853,10 @@ impl<'a, 'w, V: 'static> ViewContext<'a, 'w, V> {
|
||||
impl<'a, 'w, V> ViewContext<'a, 'w, V>
|
||||
where
|
||||
V: EventEmitter,
|
||||
V::Event: Any + Send + Sync,
|
||||
V::Event: Any + Send,
|
||||
{
|
||||
pub fn emit(&mut self, event: V::Event) {
|
||||
let emitter = self.view_state.entity_id;
|
||||
let emitter = self.view.state.entity_id;
|
||||
self.app.push_effect(Effect::Emit {
|
||||
emitter,
|
||||
event: Box::new(event),
|
||||
@@ -1738,15 +1865,15 @@ where
|
||||
}
|
||||
|
||||
impl<'a, 'w, V> Context for ViewContext<'a, 'w, V> {
|
||||
type EntityContext<'b, 'c, U> = ViewContext<'b, 'c, U>;
|
||||
type EntityContext<'b, U> = ModelContext<'b, U>;
|
||||
type Result<U> = U;
|
||||
|
||||
fn entity<T>(
|
||||
&mut self,
|
||||
build_entity: impl FnOnce(&mut Self::EntityContext<'_, '_, T>) -> T,
|
||||
build_entity: impl FnOnce(&mut Self::EntityContext<'_, T>) -> T,
|
||||
) -> Handle<T>
|
||||
where
|
||||
T: 'static + Send + Sync,
|
||||
T: 'static + Send,
|
||||
{
|
||||
self.window_cx.entity(build_entity)
|
||||
}
|
||||
@@ -1754,12 +1881,36 @@ impl<'a, 'w, V> Context for ViewContext<'a, 'w, V> {
|
||||
fn update_entity<T: 'static, R>(
|
||||
&mut self,
|
||||
handle: &Handle<T>,
|
||||
update: impl FnOnce(&mut T, &mut Self::EntityContext<'_, '_, T>) -> R,
|
||||
update: impl FnOnce(&mut T, &mut Self::EntityContext<'_, T>) -> R,
|
||||
) -> R {
|
||||
self.window_cx.update_entity(handle, update)
|
||||
}
|
||||
}
|
||||
|
||||
impl<V: 'static> VisualContext for ViewContext<'_, '_, V> {
|
||||
type ViewContext<'a, 'w, V2> = ViewContext<'a, 'w, V2>;
|
||||
|
||||
fn build_view<E, V2>(
|
||||
&mut self,
|
||||
build_entity: impl FnOnce(&mut Self::ViewContext<'_, '_, V2>) -> V2,
|
||||
render: impl Fn(&mut V2, &mut ViewContext<'_, '_, V2>) -> E + Send + 'static,
|
||||
) -> Self::Result<View<V2>>
|
||||
where
|
||||
E: crate::Component<V2>,
|
||||
V2: 'static + Send,
|
||||
{
|
||||
self.window_cx.build_view(build_entity, render)
|
||||
}
|
||||
|
||||
fn update_view<V2: 'static, R>(
|
||||
&mut self,
|
||||
view: &View<V2>,
|
||||
update: impl FnOnce(&mut V2, &mut Self::ViewContext<'_, '_, V2>) -> R,
|
||||
) -> Self::Result<R> {
|
||||
self.window_cx.update_view(view, update)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, 'w, V> std::ops::Deref for ViewContext<'a, 'w, V> {
|
||||
type Target = WindowContext<'a, 'w>;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user