Eliminate GPUI View, ViewContext, and WindowContext types (#22632)
There's still a bit more work to do on this, but this PR is compiling (with warnings) after eliminating the key types. When the tasks below are complete, this will be the new narrative for GPUI: - `Entity<T>` - This replaces `View<T>`/`Model<T>`. It represents a unit of state, and if `T` implements `Render`, then `Entity<T>` implements `Element`. - `&mut App` This replaces `AppContext` and represents the app. - `&mut Context<T>` This replaces `ModelContext` and derefs to `App`. It is provided by the framework when updating an entity. - `&mut Window` Broken out of `&mut WindowContext` which no longer exists. Every method that once took `&mut WindowContext` now takes `&mut Window, &mut App` and every method that took `&mut ViewContext<T>` now takes `&mut Window, &mut Context<T>` Not pictured here are the two other failed attempts. It's been quite a month! Tasks: - [x] Remove `View`, `ViewContext`, `WindowContext` and thread through `Window` - [x] [@cole-miller @mikayla-maki] Redraw window when entities change - [x] [@cole-miller @mikayla-maki] Get examples and Zed running - [x] [@cole-miller @mikayla-maki] Fix Zed rendering - [x] [@mikayla-maki] Fix todo! macros and comments - [x] Fix a bug where the editor would not be redrawn because of view caching - [x] remove publicness window.notify() and replace with `AppContext::notify` - [x] remove `observe_new_window_models`, replace with `observe_new_models` with an optional window - [x] Fix a bug where the project panel would not be redrawn because of the wrong refresh() call being used - [x] Fix the tests - [x] Fix warnings by eliminating `Window` params or using `_` - [x] Fix conflicts - [x] Simplify generic code where possible - [x] Rename types - [ ] Update docs ### issues post merge - [x] Issues switching between normal and insert mode - [x] Assistant re-rendering failure - [x] Vim test failures - [x] Mac build issue Release Notes: - N/A --------- Co-authored-by: Antonio Scandurra <me@as-cii.com> Co-authored-by: Cole Miller <cole@zed.dev> Co-authored-by: Mikayla <mikayla@zed.dev> Co-authored-by: Joseph <joseph@zed.dev> Co-authored-by: max <max@zed.dev> Co-authored-by: Michael Sloan <michael@zed.dev> Co-authored-by: Mikayla Maki <mikaylamaki@Mikaylas-MacBook-Pro.local> Co-authored-by: Mikayla <mikayla.c.maki@gmail.com> Co-authored-by: joão <joao@zed.dev>
This commit is contained in:
co-authored by
Antonio Scandurra
Cole Miller
Mikayla
Joseph
max
Michael Sloan
Mikayla Maki
Mikayla
joão
parent
21b4a0d50e
commit
6fca1d2b0b
+310
-178
@@ -2,13 +2,11 @@ use std::{
|
||||
any::{type_name, TypeId},
|
||||
cell::{Ref, RefCell, RefMut},
|
||||
marker::PhantomData,
|
||||
mem,
|
||||
ops::{Deref, DerefMut},
|
||||
path::{Path, PathBuf},
|
||||
rc::{Rc, Weak},
|
||||
sync::{
|
||||
atomic::{AtomicUsize, Ordering::SeqCst},
|
||||
Arc,
|
||||
},
|
||||
sync::{atomic::Ordering::SeqCst, Arc},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
@@ -33,13 +31,13 @@ use util::ResultExt;
|
||||
|
||||
use crate::{
|
||||
current_platform, hash, init_app_menus, Action, ActionBuildError, ActionRegistry, Any, AnyView,
|
||||
AnyWindowHandle, Asset, AssetSource, BackgroundExecutor, Bounds, ClipboardItem, Context,
|
||||
DispatchPhase, DisplayId, Entity, EventEmitter, FocusHandle, FocusId, ForegroundExecutor,
|
||||
Global, KeyBinding, Keymap, Keystroke, LayoutId, Menu, MenuItem, OwnedMenu, PathPromptOptions,
|
||||
Pixels, Platform, PlatformDisplay, Point, PromptBuilder, PromptHandle, PromptLevel, Render,
|
||||
AnyWindowHandle, AppContext, Asset, AssetSource, BackgroundExecutor, Bounds, ClipboardItem,
|
||||
DispatchPhase, DisplayId, EventEmitter, FocusHandle, FocusMap, ForegroundExecutor, Global,
|
||||
KeyBinding, Keymap, Keystroke, LayoutId, Menu, MenuItem, OwnedMenu, PathPromptOptions, Pixels,
|
||||
Platform, PlatformDisplay, Point, PromptBuilder, PromptHandle, PromptLevel, Render,
|
||||
RenderablePromptHandle, Reservation, ScreenCaptureSource, SharedString, SubscriberSet,
|
||||
Subscription, SvgRenderer, Task, TextSystem, View, ViewContext, Window, WindowAppearance,
|
||||
WindowContext, WindowHandle, WindowId,
|
||||
Subscription, SvgRenderer, Task, TextSystem, Window, WindowAppearance, WindowHandle, WindowId,
|
||||
WindowInvalidator,
|
||||
};
|
||||
|
||||
mod async_context;
|
||||
@@ -55,7 +53,7 @@ pub const SHUTDOWN_TIMEOUT: Duration = Duration::from_millis(100);
|
||||
/// Strongly consider removing after stabilization.
|
||||
#[doc(hidden)]
|
||||
pub struct AppCell {
|
||||
app: RefCell<AppContext>,
|
||||
app: RefCell<App>,
|
||||
}
|
||||
|
||||
impl AppCell {
|
||||
@@ -82,7 +80,7 @@ impl AppCell {
|
||||
|
||||
#[doc(hidden)]
|
||||
#[derive(Deref, DerefMut)]
|
||||
pub struct AppRef<'a>(Ref<'a, AppContext>);
|
||||
pub struct AppRef<'a>(Ref<'a, App>);
|
||||
|
||||
impl<'a> Drop for AppRef<'a> {
|
||||
fn drop(&mut self) {
|
||||
@@ -95,7 +93,7 @@ impl<'a> Drop for AppRef<'a> {
|
||||
|
||||
#[doc(hidden)]
|
||||
#[derive(Deref, DerefMut)]
|
||||
pub struct AppRefMut<'a>(RefMut<'a, AppContext>);
|
||||
pub struct AppRefMut<'a>(RefMut<'a, App>);
|
||||
|
||||
impl<'a> Drop for AppRefMut<'a> {
|
||||
fn drop(&mut self) {
|
||||
@@ -108,18 +106,18 @@ impl<'a> Drop for AppRefMut<'a> {
|
||||
|
||||
/// A reference to a GPUI application, typically constructed in the `main` function of your app.
|
||||
/// You won't interact with this type much outside of initial configuration and startup.
|
||||
pub struct App(Rc<AppCell>);
|
||||
pub struct Application(Rc<AppCell>);
|
||||
|
||||
/// Represents an application before it is fully launched. Once your app is
|
||||
/// configured, you'll start the app with `App::run`.
|
||||
impl App {
|
||||
impl Application {
|
||||
/// Builds an app with the given asset source.
|
||||
#[allow(clippy::new_without_default)]
|
||||
pub fn new() -> Self {
|
||||
#[cfg(any(test, feature = "test-support"))]
|
||||
log::info!("GPUI was compiled in test mode");
|
||||
|
||||
Self(AppContext::new(
|
||||
Self(App::new_app(
|
||||
current_platform(false),
|
||||
Arc::new(()),
|
||||
Arc::new(NullHttpClient),
|
||||
@@ -130,7 +128,7 @@ impl App {
|
||||
/// but makes it possible to run an application in an context like
|
||||
/// SSH, where GUI applications are not allowed.
|
||||
pub fn headless() -> Self {
|
||||
Self(AppContext::new(
|
||||
Self(App::new_app(
|
||||
current_platform(true),
|
||||
Arc::new(()),
|
||||
Arc::new(NullHttpClient),
|
||||
@@ -159,7 +157,7 @@ impl App {
|
||||
/// app is fully launched.
|
||||
pub fn run<F>(self, on_finish_launching: F)
|
||||
where
|
||||
F: 'static + FnOnce(&mut AppContext),
|
||||
F: 'static + FnOnce(&mut App),
|
||||
{
|
||||
let this = self.0.clone();
|
||||
let platform = self.0.borrow().platform.clone();
|
||||
@@ -183,7 +181,7 @@ impl App {
|
||||
/// On macOS, this can occur when the application icon is double-clicked or the app is launched via the dock.
|
||||
pub fn on_reopen<F>(&self, mut callback: F) -> &Self
|
||||
where
|
||||
F: 'static + FnMut(&mut AppContext),
|
||||
F: 'static + FnMut(&mut App),
|
||||
{
|
||||
let this = Rc::downgrade(&self.0);
|
||||
self.0.borrow_mut().platform.on_reopen(Box::new(move || {
|
||||
@@ -215,19 +213,18 @@ impl App {
|
||||
}
|
||||
}
|
||||
|
||||
type Handler = Box<dyn FnMut(&mut AppContext) -> bool + 'static>;
|
||||
type Listener = Box<dyn FnMut(&dyn Any, &mut AppContext) -> bool + 'static>;
|
||||
type Handler = Box<dyn FnMut(&mut App) -> bool + 'static>;
|
||||
type Listener = Box<dyn FnMut(&dyn Any, &mut App) -> bool + 'static>;
|
||||
pub(crate) type KeystrokeObserver =
|
||||
Box<dyn FnMut(&KeystrokeEvent, &mut WindowContext) -> bool + 'static>;
|
||||
type QuitHandler = Box<dyn FnOnce(&mut AppContext) -> LocalBoxFuture<'static, ()> + 'static>;
|
||||
type ReleaseListener = Box<dyn FnOnce(&mut dyn Any, &mut AppContext) + 'static>;
|
||||
type NewViewListener = Box<dyn FnMut(AnyView, &mut WindowContext) + 'static>;
|
||||
type NewModelListener = Box<dyn FnMut(AnyModel, &mut AppContext) + 'static>;
|
||||
Box<dyn FnMut(&KeystrokeEvent, &mut Window, &mut App) -> bool + 'static>;
|
||||
type QuitHandler = Box<dyn FnOnce(&mut App) -> LocalBoxFuture<'static, ()> + 'static>;
|
||||
type ReleaseListener = Box<dyn FnOnce(&mut dyn Any, &mut App) + 'static>;
|
||||
type NewModelListener = Box<dyn FnMut(AnyEntity, &mut Option<&mut Window>, &mut App) + 'static>;
|
||||
|
||||
/// Contains the state of the full application, and passed as a reference to a variety of callbacks.
|
||||
/// Other contexts such as [ModelContext], [WindowContext], and [ViewContext] deref to this type, making it the most general context type.
|
||||
/// You need a reference to an `AppContext` to access the state of a [Model].
|
||||
pub struct AppContext {
|
||||
pub struct App {
|
||||
pub(crate) this: Weak<AppCell>,
|
||||
pub(crate) platform: Rc<dyn Platform>,
|
||||
text_system: Arc<TextSystem>,
|
||||
@@ -243,11 +240,11 @@ pub struct AppContext {
|
||||
http_client: Arc<dyn HttpClient>,
|
||||
pub(crate) globals_by_type: FxHashMap<TypeId, Box<dyn Any>>,
|
||||
pub(crate) entities: EntityMap,
|
||||
pub(crate) window_update_stack: Vec<WindowId>,
|
||||
pub(crate) new_model_observers: SubscriberSet<TypeId, NewModelListener>,
|
||||
pub(crate) new_view_observers: SubscriberSet<TypeId, NewViewListener>,
|
||||
pub(crate) windows: SlotMap<WindowId, Option<Window>>,
|
||||
pub(crate) window_handles: FxHashMap<WindowId, AnyWindowHandle>,
|
||||
pub(crate) focus_handles: Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
|
||||
pub(crate) focus_handles: Arc<FocusMap>,
|
||||
pub(crate) keymap: Rc<RefCell<Keymap>>,
|
||||
pub(crate) keyboard_layout: SharedString,
|
||||
pub(crate) global_action_listeners:
|
||||
@@ -266,14 +263,16 @@ pub struct AppContext {
|
||||
pub(crate) layout_id_buffer: Vec<LayoutId>, // We recycle this memory across layout requests.
|
||||
pub(crate) propagate_event: bool,
|
||||
pub(crate) prompt_builder: Option<PromptBuilder>,
|
||||
|
||||
pub(crate) window_invalidators_by_entity:
|
||||
FxHashMap<EntityId, FxHashMap<WindowId, WindowInvalidator>>,
|
||||
pub(crate) tracked_entities: FxHashMap<WindowId, FxHashSet<EntityId>>,
|
||||
#[cfg(any(test, feature = "test-support", debug_assertions))]
|
||||
pub(crate) name: Option<&'static str>,
|
||||
}
|
||||
|
||||
impl AppContext {
|
||||
impl App {
|
||||
#[allow(clippy::new_ret_no_self)]
|
||||
pub(crate) fn new(
|
||||
pub(crate) fn new_app(
|
||||
platform: Rc<dyn Platform>,
|
||||
asset_source: Arc<dyn AssetSource>,
|
||||
http_client: Arc<dyn HttpClient>,
|
||||
@@ -290,7 +289,7 @@ impl AppContext {
|
||||
let keyboard_layout = SharedString::from(platform.keyboard_layout());
|
||||
|
||||
let app = Rc::new_cyclic(|this| AppCell {
|
||||
app: RefCell::new(AppContext {
|
||||
app: RefCell::new(App {
|
||||
this: this.clone(),
|
||||
platform: platform.clone(),
|
||||
text_system,
|
||||
@@ -306,9 +305,9 @@ impl AppContext {
|
||||
http_client,
|
||||
globals_by_type: FxHashMap::default(),
|
||||
entities,
|
||||
new_view_observers: SubscriberSet::new(),
|
||||
new_model_observers: SubscriberSet::new(),
|
||||
windows: SlotMap::with_key(),
|
||||
window_update_stack: Vec::new(),
|
||||
window_handles: FxHashMap::default(),
|
||||
focus_handles: Arc::new(RwLock::new(SlotMap::with_key())),
|
||||
keymap: Rc::new(RefCell::new(Keymap::default())),
|
||||
@@ -318,6 +317,8 @@ impl AppContext {
|
||||
pending_notifications: FxHashSet::default(),
|
||||
pending_global_notifications: FxHashSet::default(),
|
||||
observers: SubscriberSet::new(),
|
||||
tracked_entities: FxHashMap::default(),
|
||||
window_invalidators_by_entity: FxHashMap::default(),
|
||||
event_listeners: SubscriberSet::new(),
|
||||
release_listeners: SubscriberSet::new(),
|
||||
keystroke_observers: SubscriberSet::new(),
|
||||
@@ -389,7 +390,7 @@ impl AppContext {
|
||||
/// Invokes a handler when the current keyboard layout changes
|
||||
pub fn on_keyboard_layout_change<F>(&self, mut callback: F) -> Subscription
|
||||
where
|
||||
F: 'static + FnMut(&mut AppContext),
|
||||
F: 'static + FnMut(&mut App),
|
||||
{
|
||||
let (subscription, activate) = self.keyboard_layout_observers.insert(
|
||||
(),
|
||||
@@ -409,8 +410,8 @@ impl AppContext {
|
||||
|
||||
/// 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);
|
||||
pub fn refresh_windows(&mut self) {
|
||||
self.pending_effects.push_back(Effect::RefreshWindows);
|
||||
}
|
||||
|
||||
pub(crate) fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
|
||||
@@ -426,14 +427,13 @@ impl AppContext {
|
||||
}
|
||||
|
||||
/// Arrange a callback to be invoked when the given model or view calls `notify` on its respective context.
|
||||
pub fn observe<W, E>(
|
||||
pub fn observe<W>(
|
||||
&mut self,
|
||||
entity: &E,
|
||||
mut on_notify: impl FnMut(E, &mut AppContext) + 'static,
|
||||
entity: &Entity<W>,
|
||||
mut on_notify: impl FnMut(Entity<W>, &mut App) + 'static,
|
||||
) -> Subscription
|
||||
where
|
||||
W: 'static,
|
||||
E: Entity<W>,
|
||||
{
|
||||
self.observe_internal(entity, move |e, cx| {
|
||||
on_notify(e, cx);
|
||||
@@ -441,27 +441,67 @@ impl AppContext {
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn detect_accessed_entities<R>(
|
||||
&mut self,
|
||||
callback: impl FnOnce(&mut App) -> R,
|
||||
) -> (R, FxHashSet<EntityId>) {
|
||||
let accessed_entities_start = self.entities.accessed_entities.borrow().clone();
|
||||
let result = callback(self);
|
||||
let accessed_entities_end = self.entities.accessed_entities.borrow().clone();
|
||||
let entities_accessed_in_callback = accessed_entities_end
|
||||
.difference(&accessed_entities_start)
|
||||
.copied()
|
||||
.collect::<FxHashSet<EntityId>>();
|
||||
(result, entities_accessed_in_callback)
|
||||
}
|
||||
|
||||
pub(crate) fn record_entities_accessed(
|
||||
&mut self,
|
||||
window_handle: AnyWindowHandle,
|
||||
invalidator: WindowInvalidator,
|
||||
entities: &FxHashSet<EntityId>,
|
||||
) {
|
||||
let mut tracked_entities =
|
||||
std::mem::take(self.tracked_entities.entry(window_handle.id).or_default());
|
||||
for entity in tracked_entities.iter() {
|
||||
self.window_invalidators_by_entity
|
||||
.entry(*entity)
|
||||
.and_modify(|windows| {
|
||||
windows.remove(&window_handle.id);
|
||||
});
|
||||
}
|
||||
for entity in entities.iter() {
|
||||
self.window_invalidators_by_entity
|
||||
.entry(*entity)
|
||||
.or_default()
|
||||
.insert(window_handle.id, invalidator.clone());
|
||||
}
|
||||
tracked_entities.clear();
|
||||
tracked_entities.extend(entities.iter().copied());
|
||||
self.tracked_entities
|
||||
.insert(window_handle.id, tracked_entities);
|
||||
}
|
||||
|
||||
pub(crate) fn new_observer(&mut self, key: EntityId, value: Handler) -> Subscription {
|
||||
let (subscription, activate) = self.observers.insert(key, value);
|
||||
self.defer(move |_| activate());
|
||||
subscription
|
||||
}
|
||||
|
||||
pub(crate) fn observe_internal<W, E>(
|
||||
pub(crate) fn observe_internal<W>(
|
||||
&mut self,
|
||||
entity: &E,
|
||||
mut on_notify: impl FnMut(E, &mut AppContext) -> bool + 'static,
|
||||
entity: &Entity<W>,
|
||||
mut on_notify: impl FnMut(Entity<W>, &mut App) -> bool + 'static,
|
||||
) -> Subscription
|
||||
where
|
||||
W: 'static,
|
||||
E: Entity<W>,
|
||||
{
|
||||
let entity_id = entity.entity_id();
|
||||
let handle = entity.downgrade();
|
||||
self.new_observer(
|
||||
entity_id,
|
||||
Box::new(move |cx| {
|
||||
if let Some(handle) = E::upgrade_from(&handle) {
|
||||
if let Some(handle) = Entity::<W>::upgrade_from(&handle) {
|
||||
on_notify(handle, cx)
|
||||
} else {
|
||||
false
|
||||
@@ -472,14 +512,13 @@ impl AppContext {
|
||||
|
||||
/// Arrange for the given callback to be invoked whenever the given model or view emits an event of a given type.
|
||||
/// The callback is provided a handle to the emitting entity and a reference to the emitted event.
|
||||
pub fn subscribe<T, E, Event>(
|
||||
pub fn subscribe<T, Event>(
|
||||
&mut self,
|
||||
entity: &E,
|
||||
mut on_event: impl FnMut(E, &Event, &mut AppContext) + 'static,
|
||||
entity: &Entity<T>,
|
||||
mut on_event: impl FnMut(Entity<T>, &Event, &mut App) + 'static,
|
||||
) -> Subscription
|
||||
where
|
||||
T: 'static + EventEmitter<Event>,
|
||||
E: Entity<T>,
|
||||
Event: 'static,
|
||||
{
|
||||
self.subscribe_internal(entity, move |entity, event, cx| {
|
||||
@@ -497,14 +536,13 @@ impl AppContext {
|
||||
self.defer(move |_| activate());
|
||||
subscription
|
||||
}
|
||||
pub(crate) fn subscribe_internal<T, E, Evt>(
|
||||
pub(crate) fn subscribe_internal<T, Evt>(
|
||||
&mut self,
|
||||
entity: &E,
|
||||
mut on_event: impl FnMut(E, &Evt, &mut AppContext) -> bool + 'static,
|
||||
entity: &Entity<T>,
|
||||
mut on_event: impl FnMut(Entity<T>, &Evt, &mut App) -> bool + 'static,
|
||||
) -> Subscription
|
||||
where
|
||||
T: 'static + EventEmitter<Evt>,
|
||||
E: Entity<T>,
|
||||
Evt: 'static,
|
||||
{
|
||||
let entity_id = entity.entity_id();
|
||||
@@ -515,7 +553,7 @@ impl AppContext {
|
||||
TypeId::of::<Evt>(),
|
||||
Box::new(move |event, cx| {
|
||||
let event: &Evt = event.downcast_ref().expect("invalid event type");
|
||||
if let Some(handle) = E::upgrade_from(&entity) {
|
||||
if let Some(handle) = Entity::<T>::upgrade_from(&entity) {
|
||||
on_event(handle, event, cx)
|
||||
} else {
|
||||
false
|
||||
@@ -555,16 +593,18 @@ impl AppContext {
|
||||
pub fn open_window<V: 'static + Render>(
|
||||
&mut self,
|
||||
options: crate::WindowOptions,
|
||||
build_root_view: impl FnOnce(&mut WindowContext) -> View<V>,
|
||||
build_root_view: impl FnOnce(&mut Window, &mut App) -> Entity<V>,
|
||||
) -> anyhow::Result<WindowHandle<V>> {
|
||||
self.update(|cx| {
|
||||
let id = cx.windows.insert(None);
|
||||
let handle = WindowHandle::new(id);
|
||||
match Window::new(handle.into(), options, cx) {
|
||||
Ok(mut window) => {
|
||||
let root_view = build_root_view(&mut WindowContext::new(cx, &mut window));
|
||||
window.root_view.replace(root_view.into());
|
||||
WindowContext::new(cx, &mut window).defer(|cx| cx.appearance_changed());
|
||||
cx.window_update_stack.push(id);
|
||||
let root_view = build_root_view(&mut window, cx);
|
||||
cx.window_update_stack.pop();
|
||||
window.root_model.replace(root_view.into());
|
||||
window.defer(cx, |window: &mut Window, cx| window.appearance_changed(cx));
|
||||
cx.window_handles.insert(id, window.handle);
|
||||
cx.windows.get_mut(id).unwrap().replace(window);
|
||||
Ok(handle)
|
||||
@@ -577,12 +617,6 @@ impl AppContext {
|
||||
})
|
||||
}
|
||||
|
||||
/// Obtain a new [`FocusHandle`], which allows you to track and manipulate the keyboard focus
|
||||
/// for elements rendered within this window.
|
||||
pub fn focus_handle(&self) -> FocusHandle {
|
||||
FocusHandle::new(&self.focus_handles)
|
||||
}
|
||||
|
||||
/// 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);
|
||||
@@ -809,7 +843,7 @@ impl AppContext {
|
||||
event,
|
||||
} => self.apply_emit_effect(emitter, event_type, event),
|
||||
|
||||
Effect::Refresh => {
|
||||
Effect::RefreshWindows => {
|
||||
self.apply_refresh_effect();
|
||||
}
|
||||
|
||||
@@ -820,6 +854,13 @@ impl AppContext {
|
||||
Effect::Defer { callback } => {
|
||||
self.apply_defer_effect(callback);
|
||||
}
|
||||
Effect::ModelCreated {
|
||||
entity,
|
||||
tid,
|
||||
window,
|
||||
} => {
|
||||
self.apply_model_created_effect(entity, tid, window);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
#[cfg(any(test, feature = "test-support"))]
|
||||
@@ -828,11 +869,12 @@ impl AppContext {
|
||||
.values()
|
||||
.filter_map(|window| {
|
||||
let window = window.as_ref()?;
|
||||
window.dirty.get().then_some(window.handle)
|
||||
window.invalidator.is_dirty().then_some(window.handle)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
{
|
||||
self.update_window(window, |_, cx| cx.draw()).unwrap();
|
||||
self.update_window(window, |_, window, cx| window.draw(cx))
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
if self.pending_effects.is_empty() {
|
||||
@@ -871,9 +913,9 @@ impl AppContext {
|
||||
if count.load(SeqCst) == 0 {
|
||||
for window_handle in self.windows() {
|
||||
window_handle
|
||||
.update(self, |_, cx| {
|
||||
if cx.window.focus == Some(handle_id) {
|
||||
cx.blur();
|
||||
.update(self, |_, window, _| {
|
||||
if window.focus == Some(handle_id) {
|
||||
window.blur();
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
@@ -908,7 +950,8 @@ impl AppContext {
|
||||
fn apply_refresh_effect(&mut self) {
|
||||
for window in self.windows.values_mut() {
|
||||
if let Some(window) = window.as_mut() {
|
||||
window.dirty.set(true);
|
||||
window.refreshing = true;
|
||||
window.invalidator.set_dirty(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -924,6 +967,57 @@ impl AppContext {
|
||||
callback(self);
|
||||
}
|
||||
|
||||
fn apply_model_created_effect(
|
||||
&mut self,
|
||||
entity: AnyEntity,
|
||||
tid: TypeId,
|
||||
window: Option<WindowId>,
|
||||
) {
|
||||
self.new_model_observers.clone().retain(&tid, |observer| {
|
||||
if let Some(id) = window {
|
||||
self.update_window_id(id, {
|
||||
let entity = entity.clone();
|
||||
|_, window, cx| (observer)(entity, &mut Some(window), cx)
|
||||
})
|
||||
.expect("All windows should be off the stack when flushing effects");
|
||||
} else {
|
||||
(observer)(entity.clone(), &mut None, self)
|
||||
}
|
||||
true
|
||||
});
|
||||
}
|
||||
|
||||
fn update_window_id<T, F>(&mut self, id: WindowId, update: F) -> Result<T>
|
||||
where
|
||||
F: FnOnce(AnyView, &mut Window, &mut App) -> T,
|
||||
{
|
||||
self.update(|cx| {
|
||||
let mut window = cx
|
||||
.windows
|
||||
.get_mut(id)
|
||||
.ok_or_else(|| anyhow!("window not found"))?
|
||||
.take()
|
||||
.ok_or_else(|| anyhow!("window not found"))?;
|
||||
|
||||
let root_view = window.root_model.clone().unwrap();
|
||||
|
||||
cx.window_update_stack.push(window.handle.id);
|
||||
let result = update(root_view, &mut window, cx);
|
||||
cx.window_update_stack.pop();
|
||||
|
||||
if window.removed {
|
||||
cx.window_handles.remove(&id);
|
||||
cx.windows.remove(id);
|
||||
} else {
|
||||
cx.windows
|
||||
.get_mut(id)
|
||||
.ok_or_else(|| anyhow!("window not found"))?
|
||||
.replace(window);
|
||||
}
|
||||
|
||||
Ok(result)
|
||||
})
|
||||
}
|
||||
/// 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 {
|
||||
@@ -956,7 +1050,7 @@ impl AppContext {
|
||||
|
||||
/// 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) {
|
||||
pub fn defer(&mut self, f: impl FnOnce(&mut App) + 'static) {
|
||||
self.push_effect(Effect::Defer {
|
||||
callback: Box::new(f),
|
||||
});
|
||||
@@ -1073,35 +1167,11 @@ impl AppContext {
|
||||
/// Restore the global of the given type after it is moved to the stack.
|
||||
pub(crate) fn end_global_lease<G: Global>(&mut self, lease: GlobalLease<G>) {
|
||||
let global_type = TypeId::of::<G>();
|
||||
|
||||
self.push_effect(Effect::NotifyGlobalObservers { global_type });
|
||||
self.globals_by_type.insert(global_type, lease.global);
|
||||
}
|
||||
|
||||
pub(crate) fn new_view_observer(&self, key: TypeId, value: NewViewListener) -> Subscription {
|
||||
let (subscription, activate) = self.new_view_observers.insert(key, value);
|
||||
activate();
|
||||
subscription
|
||||
}
|
||||
|
||||
/// Arrange for the given function to be invoked whenever a view of the specified type is created.
|
||||
/// The function will be passed a mutable reference to the view along with an appropriate context.
|
||||
pub fn observe_new_views<V: 'static>(
|
||||
&self,
|
||||
on_new: impl 'static + Fn(&mut V, &mut ViewContext<V>),
|
||||
) -> Subscription {
|
||||
self.new_view_observer(
|
||||
TypeId::of::<V>(),
|
||||
Box::new(move |any_view: AnyView, cx: &mut WindowContext| {
|
||||
any_view
|
||||
.downcast::<V>()
|
||||
.unwrap()
|
||||
.update(cx, |view_state, cx| {
|
||||
on_new(view_state, cx);
|
||||
})
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn new_model_observer(&self, key: TypeId, value: NewModelListener) -> Subscription {
|
||||
let (subscription, activate) = self.new_model_observers.insert(key, value);
|
||||
activate();
|
||||
@@ -1110,32 +1180,37 @@ impl AppContext {
|
||||
|
||||
/// Arrange for the given function to be invoked whenever a view of the specified type is created.
|
||||
/// The function will be passed a mutable reference to the view along with an appropriate context.
|
||||
pub fn observe_new_models<T: 'static>(
|
||||
pub fn observe_new<T: 'static>(
|
||||
&self,
|
||||
on_new: impl 'static + Fn(&mut T, &mut ModelContext<T>),
|
||||
on_new: impl 'static + Fn(&mut T, Option<&mut Window>, &mut Context<T>),
|
||||
) -> Subscription {
|
||||
self.new_model_observer(
|
||||
TypeId::of::<T>(),
|
||||
Box::new(move |any_model: AnyModel, cx: &mut AppContext| {
|
||||
any_model
|
||||
.downcast::<T>()
|
||||
.unwrap()
|
||||
.update(cx, |model_state, cx| {
|
||||
on_new(model_state, cx);
|
||||
})
|
||||
}),
|
||||
Box::new(
|
||||
move |any_model: AnyEntity, window: &mut Option<&mut Window>, cx: &mut App| {
|
||||
any_model
|
||||
.downcast::<T>()
|
||||
.unwrap()
|
||||
.update(cx, |model_state, cx| {
|
||||
if let Some(window) = window {
|
||||
on_new(model_state, Some(window), cx);
|
||||
} else {
|
||||
on_new(model_state, None, cx);
|
||||
}
|
||||
})
|
||||
},
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
/// Observe the release of a model or view. The callback is invoked after the model or view
|
||||
/// has no more strong references but before it has been dropped.
|
||||
pub fn observe_release<E, T>(
|
||||
pub fn observe_release<T>(
|
||||
&self,
|
||||
handle: &E,
|
||||
on_release: impl FnOnce(&mut T, &mut AppContext) + 'static,
|
||||
handle: &Entity<T>,
|
||||
on_release: impl FnOnce(&mut T, &mut App) + 'static,
|
||||
) -> Subscription
|
||||
where
|
||||
E: Entity<T>,
|
||||
T: 'static,
|
||||
{
|
||||
let (subscription, activate) = self.release_listeners.insert(
|
||||
@@ -1149,12 +1224,35 @@ impl AppContext {
|
||||
subscription
|
||||
}
|
||||
|
||||
/// Observe the release of a model or view. The callback is invoked after the model or view
|
||||
/// has no more strong references but before it has been dropped.
|
||||
pub fn observe_release_in<T>(
|
||||
&self,
|
||||
handle: &Entity<T>,
|
||||
window: &Window,
|
||||
on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
|
||||
) -> Subscription
|
||||
where
|
||||
T: 'static,
|
||||
{
|
||||
let window_handle = window.handle;
|
||||
let (subscription, activate) = self.release_listeners.insert(
|
||||
handle.entity_id(),
|
||||
Box::new(move |entity, cx| {
|
||||
let entity = entity.downcast_mut().expect("invalid entity type");
|
||||
let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
|
||||
}),
|
||||
);
|
||||
activate();
|
||||
subscription
|
||||
}
|
||||
|
||||
/// Register a callback to be invoked when a keystroke is received by the application
|
||||
/// in any window. Note that this fires after all other action and event mechanisms have resolved
|
||||
/// and that this API will not be invoked if the event's propagation is stopped.
|
||||
pub fn observe_keystrokes(
|
||||
&mut self,
|
||||
mut f: impl FnMut(&KeystrokeEvent, &mut WindowContext) + 'static,
|
||||
mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
|
||||
) -> Subscription {
|
||||
fn inner(
|
||||
keystroke_observers: &SubscriberSet<(), KeystrokeObserver>,
|
||||
@@ -1167,8 +1265,8 @@ impl AppContext {
|
||||
|
||||
inner(
|
||||
&mut self.keystroke_observers,
|
||||
Box::new(move |event, cx| {
|
||||
f(event, cx);
|
||||
Box::new(move |event, window, cx| {
|
||||
f(event, window, cx);
|
||||
true
|
||||
}),
|
||||
)
|
||||
@@ -1177,13 +1275,13 @@ impl AppContext {
|
||||
/// Register key bindings.
|
||||
pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
|
||||
self.keymap.borrow_mut().add_bindings(bindings);
|
||||
self.pending_effects.push_back(Effect::Refresh);
|
||||
self.pending_effects.push_back(Effect::RefreshWindows);
|
||||
}
|
||||
|
||||
/// Clear all key bindings in the app.
|
||||
pub fn clear_key_bindings(&mut self) {
|
||||
self.keymap.borrow_mut().clear();
|
||||
self.pending_effects.push_back(Effect::Refresh);
|
||||
self.pending_effects.push_back(Effect::RefreshWindows);
|
||||
}
|
||||
|
||||
/// Register a global listener for actions invoked via the keyboard.
|
||||
@@ -1230,6 +1328,13 @@ impl AppContext {
|
||||
self.actions.all_action_names()
|
||||
}
|
||||
|
||||
/// Returns key bindings that invoke the given action on the currently focused element, without
|
||||
/// checking context. Bindings are returned in the order they were added. For display, the last
|
||||
/// binding should take precedence.
|
||||
pub fn all_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
|
||||
RefCell::borrow(&self.keymap).all_bindings_for_input(input)
|
||||
}
|
||||
|
||||
/// Get all non-internal actions that have been registered, along with their schemas.
|
||||
pub fn action_schemas(
|
||||
&self,
|
||||
@@ -1247,7 +1352,7 @@ impl AppContext {
|
||||
/// It is not possible to cancel the quit event at this point.
|
||||
pub fn on_app_quit<Fut>(
|
||||
&self,
|
||||
mut on_quit: impl FnMut(&mut AppContext) -> Fut + 'static,
|
||||
mut on_quit: impl FnMut(&mut App) -> Fut + 'static,
|
||||
) -> Subscription
|
||||
where
|
||||
Fut: 'static + Future<Output = ()>,
|
||||
@@ -1266,8 +1371,8 @@ impl AppContext {
|
||||
pub(crate) fn clear_pending_keystrokes(&mut self) {
|
||||
for window in self.windows() {
|
||||
window
|
||||
.update(self, |_, cx| {
|
||||
cx.clear_pending_keystrokes();
|
||||
.update(self, |_, window, _| {
|
||||
window.clear_pending_keystrokes();
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
@@ -1279,7 +1384,7 @@ impl AppContext {
|
||||
let mut action_available = false;
|
||||
if let Some(window) = self.active_window() {
|
||||
if let Ok(window_action_available) =
|
||||
window.update(self, |_, cx| cx.is_action_available(action))
|
||||
window.update(self, |_, window, cx| window.is_action_available(action, cx))
|
||||
{
|
||||
action_available = window_action_available;
|
||||
}
|
||||
@@ -1319,7 +1424,9 @@ impl AppContext {
|
||||
pub fn dispatch_action(&mut self, action: &dyn Action) {
|
||||
if let Some(active_window) = self.active_window() {
|
||||
active_window
|
||||
.update(self, |_, cx| cx.dispatch_action(action.boxed_clone()))
|
||||
.update(self, |_, window, cx| {
|
||||
window.dispatch_action(action.boxed_clone(), cx)
|
||||
})
|
||||
.log_err();
|
||||
} else {
|
||||
self.dispatch_global_action(action);
|
||||
@@ -1389,7 +1496,8 @@ impl AppContext {
|
||||
Option<&str>,
|
||||
&[&str],
|
||||
PromptHandle,
|
||||
&mut WindowContext,
|
||||
&mut Window,
|
||||
&mut App,
|
||||
) -> RenderablePromptHandle
|
||||
+ 'static,
|
||||
) {
|
||||
@@ -1425,6 +1533,36 @@ impl AppContext {
|
||||
(task, is_first)
|
||||
}
|
||||
|
||||
/// Obtain a new [`FocusHandle`], which allows you to track and manipulate the keyboard focus
|
||||
/// for elements rendered within this window.
|
||||
#[track_caller]
|
||||
pub fn focus_handle(&self) -> FocusHandle {
|
||||
FocusHandle::new(&self.focus_handles)
|
||||
}
|
||||
|
||||
/// Tell GPUI that an entity has changed and observers of it should be notified.
|
||||
pub fn notify(&mut self, entity_id: EntityId) {
|
||||
let window_invalidators = mem::take(
|
||||
self.window_invalidators_by_entity
|
||||
.entry(entity_id)
|
||||
.or_default(),
|
||||
);
|
||||
|
||||
if window_invalidators.is_empty() {
|
||||
if self.pending_notifications.insert(entity_id) {
|
||||
self.pending_effects
|
||||
.push_back(Effect::Notify { emitter: entity_id });
|
||||
}
|
||||
} else {
|
||||
for invalidator in window_invalidators.values() {
|
||||
invalidator.invalidate_view(entity_id, self);
|
||||
}
|
||||
}
|
||||
|
||||
self.window_invalidators_by_entity
|
||||
.insert(entity_id, window_invalidators);
|
||||
}
|
||||
|
||||
/// Get the name for this App.
|
||||
#[cfg(any(test, feature = "test-support", debug_assertions))]
|
||||
pub fn get_name(&self) -> &'static str {
|
||||
@@ -1437,32 +1575,25 @@ impl AppContext {
|
||||
}
|
||||
}
|
||||
|
||||
impl Context for AppContext {
|
||||
impl AppContext for App {
|
||||
type Result<T> = T;
|
||||
|
||||
/// 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 `Model` handle will be returned,
|
||||
/// which can be used to access the entity in a context.
|
||||
fn new_model<T: 'static>(
|
||||
&mut self,
|
||||
build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
|
||||
) -> Model<T> {
|
||||
fn new<T: 'static>(&mut self, build_model: impl FnOnce(&mut Context<'_, T>) -> T) -> Entity<T> {
|
||||
self.update(|cx| {
|
||||
let slot = cx.entities.reserve();
|
||||
let model = slot.clone();
|
||||
let entity = build_model(&mut ModelContext::new(cx, slot.downgrade()));
|
||||
let entity = build_model(&mut Context::new_context(cx, slot.downgrade()));
|
||||
|
||||
cx.push_effect(Effect::ModelCreated {
|
||||
entity: model.clone().into_any(),
|
||||
tid: TypeId::of::<T>(),
|
||||
window: cx.window_update_stack.last().cloned(),
|
||||
});
|
||||
|
||||
cx.entities.insert(slot, entity);
|
||||
|
||||
// Non-generic part to avoid leaking SubscriberSet to invokers of `new_view`.
|
||||
fn notify_observers(cx: &mut AppContext, tid: TypeId, model: AnyModel) {
|
||||
cx.new_model_observers.clone().retain(&tid, |observer| {
|
||||
let any_model = model.clone();
|
||||
(observer)(any_model, cx);
|
||||
true
|
||||
});
|
||||
}
|
||||
notify_observers(cx, TypeId::of::<T>(), AnyModel::from(model.clone()));
|
||||
|
||||
model
|
||||
})
|
||||
}
|
||||
@@ -1474,11 +1605,11 @@ impl Context for AppContext {
|
||||
fn insert_model<T: 'static>(
|
||||
&mut self,
|
||||
reservation: Reservation<T>,
|
||||
build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
|
||||
) -> Self::Result<Model<T>> {
|
||||
build_model: impl FnOnce(&mut Context<'_, T>) -> T,
|
||||
) -> Self::Result<Entity<T>> {
|
||||
self.update(|cx| {
|
||||
let slot = reservation.0;
|
||||
let entity = build_model(&mut ModelContext::new(cx, slot.downgrade()));
|
||||
let entity = build_model(&mut Context::new_context(cx, slot.downgrade()));
|
||||
cx.entities.insert(slot, entity)
|
||||
})
|
||||
}
|
||||
@@ -1487,12 +1618,15 @@ impl Context for AppContext {
|
||||
/// entity along with a `ModelContext` for the entity.
|
||||
fn update_model<T: 'static, R>(
|
||||
&mut self,
|
||||
model: &Model<T>,
|
||||
update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
|
||||
model: &Entity<T>,
|
||||
update: impl FnOnce(&mut T, &mut Context<'_, T>) -> R,
|
||||
) -> R {
|
||||
self.update(|cx| {
|
||||
let mut entity = cx.entities.lease(model);
|
||||
let result = update(&mut entity, &mut ModelContext::new(cx, model.downgrade()));
|
||||
let result = update(
|
||||
&mut entity,
|
||||
&mut Context::new_context(cx, model.downgrade()),
|
||||
);
|
||||
cx.entities.end_lease(entity);
|
||||
result
|
||||
})
|
||||
@@ -1500,8 +1634,8 @@ impl Context for AppContext {
|
||||
|
||||
fn read_model<T, R>(
|
||||
&self,
|
||||
handle: &Model<T>,
|
||||
read: impl FnOnce(&T, &AppContext) -> R,
|
||||
handle: &Entity<T>,
|
||||
read: impl FnOnce(&T, &App) -> R,
|
||||
) -> Self::Result<R>
|
||||
where
|
||||
T: 'static,
|
||||
@@ -1512,37 +1646,15 @@ impl Context for AppContext {
|
||||
|
||||
fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>
|
||||
where
|
||||
F: FnOnce(AnyView, &mut WindowContext) -> T,
|
||||
F: FnOnce(AnyView, &mut Window, &mut App) -> T,
|
||||
{
|
||||
self.update(|cx| {
|
||||
let mut window = cx
|
||||
.windows
|
||||
.get_mut(handle.id)
|
||||
.ok_or_else(|| anyhow!("window not found"))?
|
||||
.take()
|
||||
.ok_or_else(|| anyhow!("window not found"))?;
|
||||
|
||||
let root_view = window.root_view.clone().unwrap();
|
||||
let result = update(root_view, &mut WindowContext::new(cx, &mut window));
|
||||
|
||||
if window.removed {
|
||||
cx.window_handles.remove(&handle.id);
|
||||
cx.windows.remove(handle.id);
|
||||
} else {
|
||||
cx.windows
|
||||
.get_mut(handle.id)
|
||||
.ok_or_else(|| anyhow!("window not found"))?
|
||||
.replace(window);
|
||||
}
|
||||
|
||||
Ok(result)
|
||||
})
|
||||
self.update_window_id(handle.id, update)
|
||||
}
|
||||
|
||||
fn read_window<T, R>(
|
||||
&self,
|
||||
window: &WindowHandle<T>,
|
||||
read: impl FnOnce(View<T>, &AppContext) -> R,
|
||||
read: impl FnOnce(Entity<T>, &App) -> R,
|
||||
) -> Result<R>
|
||||
where
|
||||
T: 'static,
|
||||
@@ -1552,9 +1664,9 @@ impl Context for AppContext {
|
||||
.get(window.id)
|
||||
.ok_or_else(|| anyhow!("window not found"))?
|
||||
.as_ref()
|
||||
.unwrap();
|
||||
.expect("attempted to read a window that is already on the stack");
|
||||
|
||||
let root_view = window.root_view.clone().unwrap();
|
||||
let root_view = window.root_model.clone().unwrap();
|
||||
let view = root_view
|
||||
.downcast::<T>()
|
||||
.map_err(|_| anyhow!("root view's type has changed"))?;
|
||||
@@ -1573,13 +1685,33 @@ pub(crate) enum Effect {
|
||||
event_type: TypeId,
|
||||
event: Box<dyn Any>,
|
||||
},
|
||||
Refresh,
|
||||
RefreshWindows,
|
||||
NotifyGlobalObservers {
|
||||
global_type: TypeId,
|
||||
},
|
||||
Defer {
|
||||
callback: Box<dyn FnOnce(&mut AppContext) + 'static>,
|
||||
callback: Box<dyn FnOnce(&mut App) + 'static>,
|
||||
},
|
||||
ModelCreated {
|
||||
entity: AnyEntity,
|
||||
tid: TypeId,
|
||||
window: Option<WindowId>,
|
||||
},
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Effect {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Effect::Notify { emitter } => write!(f, "Notify({})", emitter),
|
||||
Effect::Emit { emitter, .. } => write!(f, "Emit({:?})", emitter),
|
||||
Effect::RefreshWindows => write!(f, "RefreshWindows"),
|
||||
Effect::NotifyGlobalObservers { global_type } => {
|
||||
write!(f, "NotifyGlobalObservers({:?})", global_type)
|
||||
}
|
||||
Effect::Defer { .. } => write!(f, "Defer(..)"),
|
||||
Effect::ModelCreated { entity, .. } => write!(f, "ModelCreated({:?})", entity),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Wraps a global variable value during `update_global` while the value has been moved to the stack.
|
||||
@@ -1638,7 +1770,7 @@ pub struct AnyTooltip {
|
||||
/// Given the bounds of the tooltip, checks whether the tooltip should still be visible and
|
||||
/// updates its state accordingly. This is needed atop the hovered element's mouse move handler
|
||||
/// to handle the case where the element is not painted (e.g. via use of `visible_on_hover`).
|
||||
pub check_visible_and_update: Rc<dyn Fn(Bounds<Pixels>, &mut WindowContext) -> bool>,
|
||||
pub check_visible_and_update: Rc<dyn Fn(Bounds<Pixels>, &mut Window, &mut App) -> bool>,
|
||||
}
|
||||
|
||||
/// A keystroke event, and potentially the associated action
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
use crate::{
|
||||
AnyView, AnyWindowHandle, AppCell, AppContext, BackgroundExecutor, BorrowAppContext, Context,
|
||||
DismissEvent, FocusableView, ForegroundExecutor, Global, Model, ModelContext, PromptLevel,
|
||||
Render, Reservation, Result, Task, View, ViewContext, VisualContext, WindowContext,
|
||||
WindowHandle,
|
||||
AnyView, AnyWindowHandle, App, AppCell, AppContext, BackgroundExecutor, BorrowAppContext,
|
||||
Entity, Focusable, ForegroundExecutor, Global, PromptLevel, Render, Reservation, Result, Task,
|
||||
VisualContext, Window, WindowHandle,
|
||||
};
|
||||
use anyhow::{anyhow, Context as _};
|
||||
use derive_more::{Deref, DerefMut};
|
||||
use futures::channel::oneshot;
|
||||
use std::{future::Future, rc::Weak};
|
||||
|
||||
use super::Context;
|
||||
|
||||
/// An async-friendly version of [AppContext] with a static lifetime so it can be held across `await` points in async code.
|
||||
/// You're provided with an instance when calling [AppContext::spawn], and you can also create one with [AppContext::to_async].
|
||||
/// Internally, this holds a weak reference to an `AppContext`, so its methods are fallible to protect against cases where the [AppContext] is dropped.
|
||||
@@ -19,19 +20,19 @@ pub struct AsyncAppContext {
|
||||
pub(crate) foreground_executor: ForegroundExecutor,
|
||||
}
|
||||
|
||||
impl Context for AsyncAppContext {
|
||||
impl AppContext for AsyncAppContext {
|
||||
type Result<T> = Result<T>;
|
||||
|
||||
fn new_model<T: 'static>(
|
||||
fn new<T: 'static>(
|
||||
&mut self,
|
||||
build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
|
||||
) -> Self::Result<Model<T>> {
|
||||
build_model: impl FnOnce(&mut Context<'_, T>) -> T,
|
||||
) -> Self::Result<Entity<T>> {
|
||||
let app = self
|
||||
.app
|
||||
.upgrade()
|
||||
.ok_or_else(|| anyhow!("app was released"))?;
|
||||
let mut app = app.borrow_mut();
|
||||
Ok(app.new_model(build_model))
|
||||
Ok(app.new(build_model))
|
||||
}
|
||||
|
||||
fn reserve_model<T: 'static>(&mut self) -> Result<Reservation<T>> {
|
||||
@@ -46,8 +47,8 @@ impl Context for AsyncAppContext {
|
||||
fn insert_model<T: 'static>(
|
||||
&mut self,
|
||||
reservation: Reservation<T>,
|
||||
build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
|
||||
) -> Result<Model<T>> {
|
||||
build_model: impl FnOnce(&mut Context<'_, T>) -> T,
|
||||
) -> Result<Entity<T>> {
|
||||
let app = self
|
||||
.app
|
||||
.upgrade()
|
||||
@@ -58,8 +59,8 @@ impl Context for AsyncAppContext {
|
||||
|
||||
fn update_model<T: 'static, R>(
|
||||
&mut self,
|
||||
handle: &Model<T>,
|
||||
update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
|
||||
handle: &Entity<T>,
|
||||
update: impl FnOnce(&mut T, &mut Context<'_, T>) -> R,
|
||||
) -> Self::Result<R> {
|
||||
let app = self
|
||||
.app
|
||||
@@ -71,8 +72,8 @@ impl Context for AsyncAppContext {
|
||||
|
||||
fn read_model<T, R>(
|
||||
&self,
|
||||
handle: &Model<T>,
|
||||
callback: impl FnOnce(&T, &AppContext) -> R,
|
||||
handle: &Entity<T>,
|
||||
callback: impl FnOnce(&T, &App) -> R,
|
||||
) -> Self::Result<R>
|
||||
where
|
||||
T: 'static,
|
||||
@@ -84,7 +85,7 @@ impl Context for AsyncAppContext {
|
||||
|
||||
fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
|
||||
where
|
||||
F: FnOnce(AnyView, &mut WindowContext) -> T,
|
||||
F: FnOnce(AnyView, &mut Window, &mut App) -> T,
|
||||
{
|
||||
let app = self.app.upgrade().context("app was released")?;
|
||||
let mut lock = app.borrow_mut();
|
||||
@@ -94,7 +95,7 @@ impl Context for AsyncAppContext {
|
||||
fn read_window<T, R>(
|
||||
&self,
|
||||
window: &WindowHandle<T>,
|
||||
read: impl FnOnce(View<T>, &AppContext) -> R,
|
||||
read: impl FnOnce(Entity<T>, &App) -> R,
|
||||
) -> Result<R>
|
||||
where
|
||||
T: 'static,
|
||||
@@ -113,7 +114,7 @@ impl AsyncAppContext {
|
||||
.upgrade()
|
||||
.ok_or_else(|| anyhow!("app was released"))?;
|
||||
let mut lock = app.borrow_mut();
|
||||
lock.refresh();
|
||||
lock.refresh_windows();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -128,7 +129,7 @@ impl AsyncAppContext {
|
||||
}
|
||||
|
||||
/// Invoke the given function in the context of the app, then flush any effects produced during its invocation.
|
||||
pub fn update<R>(&self, f: impl FnOnce(&mut AppContext) -> R) -> Result<R> {
|
||||
pub fn update<R>(&self, f: impl FnOnce(&mut App) -> R) -> Result<R> {
|
||||
let app = self
|
||||
.app
|
||||
.upgrade()
|
||||
@@ -141,7 +142,7 @@ impl AsyncAppContext {
|
||||
pub fn open_window<V>(
|
||||
&self,
|
||||
options: crate::WindowOptions,
|
||||
build_root_view: impl FnOnce(&mut WindowContext) -> View<V>,
|
||||
build_root_view: impl FnOnce(&mut Window, &mut App) -> Entity<V>,
|
||||
) -> Result<WindowHandle<V>>
|
||||
where
|
||||
V: 'static + Render,
|
||||
@@ -178,7 +179,7 @@ impl AsyncAppContext {
|
||||
///
|
||||
/// Panics if no global state of the specified type has been assigned.
|
||||
/// Returns an error if the `AppContext` has been dropped.
|
||||
pub fn read_global<G: Global, R>(&self, read: impl FnOnce(&G, &AppContext) -> R) -> Result<R> {
|
||||
pub fn read_global<G: Global, R>(&self, read: impl FnOnce(&G, &App) -> R) -> Result<R> {
|
||||
let app = self
|
||||
.app
|
||||
.upgrade()
|
||||
@@ -193,10 +194,7 @@ impl AsyncAppContext {
|
||||
/// if no state of the specified type has been assigned.
|
||||
///
|
||||
/// Returns an error if no state of the specified type has been assigned the `AppContext` has been dropped.
|
||||
pub fn try_read_global<G: Global, R>(
|
||||
&self,
|
||||
read: impl FnOnce(&G, &AppContext) -> R,
|
||||
) -> Option<R> {
|
||||
pub fn try_read_global<G: Global, R>(&self, read: impl FnOnce(&G, &App) -> R) -> Option<R> {
|
||||
let app = self.app.upgrade()?;
|
||||
let app = app.borrow_mut();
|
||||
Some(read(app.try_global()?, &app))
|
||||
@@ -206,7 +204,7 @@ impl AsyncAppContext {
|
||||
/// for updating the global state of the specified type.
|
||||
pub fn update_global<G: Global, R>(
|
||||
&self,
|
||||
update: impl FnOnce(&mut G, &mut AppContext) -> R,
|
||||
update: impl FnOnce(&mut G, &mut App) -> R,
|
||||
) -> Result<R> {
|
||||
let app = self
|
||||
.app
|
||||
@@ -228,7 +226,7 @@ pub struct AsyncWindowContext {
|
||||
}
|
||||
|
||||
impl AsyncWindowContext {
|
||||
pub(crate) fn new(app: AsyncAppContext, window: AnyWindowHandle) -> Self {
|
||||
pub(crate) fn new_context(app: AsyncAppContext, window: AnyWindowHandle) -> Self {
|
||||
Self { app, window }
|
||||
}
|
||||
|
||||
@@ -238,41 +236,47 @@ impl AsyncWindowContext {
|
||||
}
|
||||
|
||||
/// A convenience method for [`AppContext::update_window`].
|
||||
pub fn update<R>(&mut self, update: impl FnOnce(&mut WindowContext) -> R) -> Result<R> {
|
||||
self.app.update_window(self.window, |_, cx| update(cx))
|
||||
pub fn update<R>(&mut self, update: impl FnOnce(&mut Window, &mut App) -> R) -> Result<R> {
|
||||
self.app
|
||||
.update_window(self.window, |_, window, cx| update(window, cx))
|
||||
}
|
||||
|
||||
/// A convenience method for [`AppContext::update_window`].
|
||||
pub fn update_root<R>(
|
||||
&mut self,
|
||||
update: impl FnOnce(AnyView, &mut WindowContext) -> R,
|
||||
update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
|
||||
) -> Result<R> {
|
||||
self.app.update_window(self.window, update)
|
||||
}
|
||||
|
||||
/// A convenience method for [`WindowContext::on_next_frame`].
|
||||
pub fn on_next_frame(&mut self, f: impl FnOnce(&mut WindowContext) + 'static) {
|
||||
self.window.update(self, |_, cx| cx.on_next_frame(f)).ok();
|
||||
/// A convenience method for [`Window::on_next_frame`].
|
||||
pub fn on_next_frame(&mut self, f: impl FnOnce(&mut Window, &mut App) + 'static) {
|
||||
self.window
|
||||
.update(self, |_, window, _| window.on_next_frame(f))
|
||||
.ok();
|
||||
}
|
||||
|
||||
/// A convenience method for [`AppContext::global`].
|
||||
pub fn read_global<G: Global, R>(
|
||||
&mut self,
|
||||
read: impl FnOnce(&G, &WindowContext) -> R,
|
||||
read: impl FnOnce(&G, &Window, &App) -> R,
|
||||
) -> Result<R> {
|
||||
self.window.update(self, |_, cx| read(cx.global(), cx))
|
||||
self.window
|
||||
.update(self, |_, window, cx| read(cx.global(), window, cx))
|
||||
}
|
||||
|
||||
/// A convenience method for [`AppContext::update_global`].
|
||||
/// for updating the global state of the specified type.
|
||||
pub fn update_global<G, R>(
|
||||
&mut self,
|
||||
update: impl FnOnce(&mut G, &mut WindowContext) -> R,
|
||||
update: impl FnOnce(&mut G, &mut Window, &mut App) -> R,
|
||||
) -> Result<R>
|
||||
where
|
||||
G: Global,
|
||||
{
|
||||
self.window.update(self, |_, cx| cx.update_global(update))
|
||||
self.window.update(self, |_, window, cx| {
|
||||
cx.update_global(|global, cx| update(global, window, cx))
|
||||
})
|
||||
}
|
||||
|
||||
/// Schedule a future to be executed on the main thread. This is used for collecting
|
||||
@@ -296,50 +300,49 @@ impl AsyncWindowContext {
|
||||
answers: &[&str],
|
||||
) -> oneshot::Receiver<usize> {
|
||||
self.window
|
||||
.update(self, |_, cx| cx.prompt(level, message, detail, answers))
|
||||
.update(self, |_, window, cx| {
|
||||
window.prompt(level, message, detail, answers, cx)
|
||||
})
|
||||
.unwrap_or_else(|_| oneshot::channel().1)
|
||||
}
|
||||
}
|
||||
|
||||
impl Context for AsyncWindowContext {
|
||||
impl AppContext for AsyncWindowContext {
|
||||
type Result<T> = Result<T>;
|
||||
|
||||
fn new_model<T>(
|
||||
&mut self,
|
||||
build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
|
||||
) -> Result<Model<T>>
|
||||
fn new<T>(&mut self, build_model: impl FnOnce(&mut Context<'_, T>) -> T) -> Result<Entity<T>>
|
||||
where
|
||||
T: 'static,
|
||||
{
|
||||
self.window.update(self, |_, cx| cx.new_model(build_model))
|
||||
self.window.update(self, |_, _, cx| cx.new(build_model))
|
||||
}
|
||||
|
||||
fn reserve_model<T: 'static>(&mut self) -> Result<Reservation<T>> {
|
||||
self.window.update(self, |_, cx| cx.reserve_model())
|
||||
self.window.update(self, |_, _, cx| cx.reserve_model())
|
||||
}
|
||||
|
||||
fn insert_model<T: 'static>(
|
||||
&mut self,
|
||||
reservation: Reservation<T>,
|
||||
build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
|
||||
) -> Self::Result<Model<T>> {
|
||||
build_model: impl FnOnce(&mut Context<'_, T>) -> T,
|
||||
) -> Self::Result<Entity<T>> {
|
||||
self.window
|
||||
.update(self, |_, cx| cx.insert_model(reservation, build_model))
|
||||
.update(self, |_, _, cx| cx.insert_model(reservation, build_model))
|
||||
}
|
||||
|
||||
fn update_model<T: 'static, R>(
|
||||
&mut self,
|
||||
handle: &Model<T>,
|
||||
update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
|
||||
handle: &Entity<T>,
|
||||
update: impl FnOnce(&mut T, &mut Context<'_, T>) -> R,
|
||||
) -> Result<R> {
|
||||
self.window
|
||||
.update(self, |_, cx| cx.update_model(handle, update))
|
||||
.update(self, |_, _, cx| cx.update_model(handle, update))
|
||||
}
|
||||
|
||||
fn read_model<T, R>(
|
||||
&self,
|
||||
handle: &Model<T>,
|
||||
read: impl FnOnce(&T, &AppContext) -> R,
|
||||
handle: &Entity<T>,
|
||||
read: impl FnOnce(&T, &App) -> R,
|
||||
) -> Self::Result<R>
|
||||
where
|
||||
T: 'static,
|
||||
@@ -349,7 +352,7 @@ impl Context for AsyncWindowContext {
|
||||
|
||||
fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
|
||||
where
|
||||
F: FnOnce(AnyView, &mut WindowContext) -> T,
|
||||
F: FnOnce(AnyView, &mut Window, &mut App) -> T,
|
||||
{
|
||||
self.app.update_window(window, update)
|
||||
}
|
||||
@@ -357,7 +360,7 @@ impl Context for AsyncWindowContext {
|
||||
fn read_window<T, R>(
|
||||
&self,
|
||||
window: &WindowHandle<T>,
|
||||
read: impl FnOnce(View<T>, &AppContext) -> R,
|
||||
read: impl FnOnce(Entity<T>, &App) -> R,
|
||||
) -> Result<R>
|
||||
where
|
||||
T: 'static,
|
||||
@@ -367,51 +370,46 @@ impl Context for AsyncWindowContext {
|
||||
}
|
||||
|
||||
impl VisualContext for AsyncWindowContext {
|
||||
fn new_view<V>(
|
||||
&mut self,
|
||||
build_view_state: impl FnOnce(&mut ViewContext<V>) -> V,
|
||||
) -> Self::Result<View<V>>
|
||||
where
|
||||
V: 'static + Render,
|
||||
{
|
||||
fn window_handle(&self) -> AnyWindowHandle {
|
||||
self.window
|
||||
.update(self, |_, cx| cx.new_view(build_view_state))
|
||||
}
|
||||
|
||||
fn update_view<V: 'static, R>(
|
||||
fn new_window_model<T: 'static>(
|
||||
&mut self,
|
||||
view: &View<V>,
|
||||
update: impl FnOnce(&mut V, &mut ViewContext<V>) -> R,
|
||||
) -> Self::Result<R> {
|
||||
build_model: impl FnOnce(&mut Window, &mut Context<T>) -> T,
|
||||
) -> Self::Result<Entity<T>> {
|
||||
self.window
|
||||
.update(self, |_, cx| cx.update_view(view, update))
|
||||
.update(self, |_, window, cx| cx.new(|cx| build_model(window, cx)))
|
||||
}
|
||||
|
||||
fn update_window_model<T: 'static, R>(
|
||||
&mut self,
|
||||
view: &Entity<T>,
|
||||
update: impl FnOnce(&mut T, &mut Window, &mut Context<T>) -> R,
|
||||
) -> Self::Result<R> {
|
||||
self.window.update(self, |_, window, cx| {
|
||||
view.update(cx, |model, cx| update(model, window, cx))
|
||||
})
|
||||
}
|
||||
|
||||
fn replace_root_view<V>(
|
||||
&mut self,
|
||||
build_view: impl FnOnce(&mut ViewContext<V>) -> V,
|
||||
) -> Self::Result<View<V>>
|
||||
build_view: impl FnOnce(&mut Window, &mut Context<V>) -> V,
|
||||
) -> Self::Result<Entity<V>>
|
||||
where
|
||||
V: 'static + Render,
|
||||
{
|
||||
self.window
|
||||
.update(self, |_, cx| cx.replace_root_view(build_view))
|
||||
}
|
||||
|
||||
fn focus_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
|
||||
where
|
||||
V: FocusableView,
|
||||
{
|
||||
self.window.update(self, |_, cx| {
|
||||
view.read(cx).focus_handle(cx).clone().focus(cx);
|
||||
self.window.update(self, |_, window, cx| {
|
||||
window.replace_root_model(cx, build_view)
|
||||
})
|
||||
}
|
||||
|
||||
fn dismiss_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
|
||||
fn focus<V>(&mut self, view: &Entity<V>) -> Self::Result<()>
|
||||
where
|
||||
V: crate::ManagedView,
|
||||
V: Focusable,
|
||||
{
|
||||
self.window
|
||||
.update(self, |_, cx| view.update(cx, |_, cx| cx.emit(DismissEvent)))
|
||||
self.window.update(self, |_, window, cx| {
|
||||
view.read(cx).focus_handle(cx).clone().focus(window);
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
+172
-120
@@ -1,10 +1,12 @@
|
||||
use crate::{seal::Sealed, AppContext, Context, Entity, ModelContext};
|
||||
use crate::{seal::Sealed, App, AppContext, VisualContext, Window};
|
||||
use anyhow::{anyhow, Result};
|
||||
use collections::FxHashSet;
|
||||
use derive_more::{Deref, DerefMut};
|
||||
use parking_lot::{RwLock, RwLockUpgradableReadGuard};
|
||||
use slotmap::{KeyData, SecondaryMap, SlotMap};
|
||||
use std::{
|
||||
any::{type_name, Any, TypeId},
|
||||
cell::RefCell,
|
||||
fmt::{self, Display},
|
||||
hash::{Hash, Hasher},
|
||||
marker::PhantomData,
|
||||
@@ -20,6 +22,8 @@ use std::{
|
||||
#[cfg(any(test, feature = "test-support"))]
|
||||
use collections::HashMap;
|
||||
|
||||
use super::Context;
|
||||
|
||||
slotmap::new_key_type! {
|
||||
/// A unique identifier for a model or view across the application.
|
||||
pub struct EntityId;
|
||||
@@ -51,6 +55,7 @@ impl Display for EntityId {
|
||||
|
||||
pub(crate) struct EntityMap {
|
||||
entities: SecondaryMap<EntityId, Box<dyn Any>>,
|
||||
pub accessed_entities: RefCell<FxHashSet<EntityId>>,
|
||||
ref_counts: Arc<RwLock<EntityRefCounts>>,
|
||||
}
|
||||
|
||||
@@ -65,6 +70,7 @@ impl EntityMap {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
entities: SecondaryMap::new(),
|
||||
accessed_entities: RefCell::new(FxHashSet::default()),
|
||||
ref_counts: Arc::new(RwLock::new(EntityRefCounts {
|
||||
counts: SlotMap::with_key(),
|
||||
dropped_entity_ids: Vec::new(),
|
||||
@@ -80,14 +86,17 @@ impl EntityMap {
|
||||
/// Reserve a slot for an entity, which you can subsequently use with `insert`.
|
||||
pub fn reserve<T: 'static>(&self) -> Slot<T> {
|
||||
let id = self.ref_counts.write().counts.insert(1.into());
|
||||
Slot(Model::new(id, Arc::downgrade(&self.ref_counts)))
|
||||
Slot(Entity::new(id, Arc::downgrade(&self.ref_counts)))
|
||||
}
|
||||
|
||||
/// Insert an entity into a slot obtained by calling `reserve`.
|
||||
pub fn insert<T>(&mut self, slot: Slot<T>, entity: T) -> Model<T>
|
||||
pub fn insert<T>(&mut self, slot: Slot<T>, entity: T) -> Entity<T>
|
||||
where
|
||||
T: 'static,
|
||||
{
|
||||
let mut accessed_entities = self.accessed_entities.borrow_mut();
|
||||
accessed_entities.insert(slot.entity_id);
|
||||
|
||||
let model = slot.0;
|
||||
self.entities.insert(model.entity_id, Box::new(entity));
|
||||
model
|
||||
@@ -95,16 +104,19 @@ impl EntityMap {
|
||||
|
||||
/// Move an entity to the stack.
|
||||
#[track_caller]
|
||||
pub fn lease<'a, T>(&mut self, model: &'a Model<T>) -> Lease<'a, T> {
|
||||
self.assert_valid_context(model);
|
||||
pub fn lease<'a, T>(&mut self, pointer: &'a Entity<T>) -> Lease<'a, T> {
|
||||
self.assert_valid_context(pointer);
|
||||
let mut accessed_entities = self.accessed_entities.borrow_mut();
|
||||
accessed_entities.insert(pointer.entity_id);
|
||||
|
||||
let entity = Some(
|
||||
self.entities
|
||||
.remove(model.entity_id)
|
||||
.remove(pointer.entity_id)
|
||||
.unwrap_or_else(|| double_lease_panic::<T>("update")),
|
||||
);
|
||||
Lease {
|
||||
model,
|
||||
entity,
|
||||
pointer,
|
||||
entity_type: PhantomData,
|
||||
}
|
||||
}
|
||||
@@ -112,27 +124,41 @@ impl EntityMap {
|
||||
/// Returns an entity after moving it to the stack.
|
||||
pub fn end_lease<T>(&mut self, mut lease: Lease<T>) {
|
||||
self.entities
|
||||
.insert(lease.model.entity_id, lease.entity.take().unwrap());
|
||||
.insert(lease.pointer.entity_id, lease.entity.take().unwrap());
|
||||
}
|
||||
|
||||
pub fn read<T: 'static>(&self, model: &Model<T>) -> &T {
|
||||
pub fn read<T: 'static>(&self, model: &Entity<T>) -> &T {
|
||||
self.assert_valid_context(model);
|
||||
let mut accessed_entities = self.accessed_entities.borrow_mut();
|
||||
accessed_entities.insert(model.entity_id);
|
||||
|
||||
self.entities
|
||||
.get(model.entity_id)
|
||||
.and_then(|entity| entity.downcast_ref())
|
||||
.unwrap_or_else(|| double_lease_panic::<T>("read"))
|
||||
}
|
||||
|
||||
fn assert_valid_context(&self, model: &AnyModel) {
|
||||
fn assert_valid_context(&self, model: &AnyEntity) {
|
||||
debug_assert!(
|
||||
Weak::ptr_eq(&model.entity_map, &Arc::downgrade(&self.ref_counts)),
|
||||
"used a model with the wrong context"
|
||||
);
|
||||
}
|
||||
|
||||
pub fn extend_accessed(&mut self, entities: &FxHashSet<EntityId>) {
|
||||
self.accessed_entities
|
||||
.borrow_mut()
|
||||
.extend(entities.iter().copied());
|
||||
}
|
||||
|
||||
pub fn clear_accessed(&mut self) {
|
||||
self.accessed_entities.borrow_mut().clear();
|
||||
}
|
||||
|
||||
pub fn take_dropped(&mut self) -> Vec<(EntityId, Box<dyn Any>)> {
|
||||
let mut ref_counts = self.ref_counts.write();
|
||||
let dropped_entity_ids = mem::take(&mut ref_counts.dropped_entity_ids);
|
||||
let mut accessed_entities = self.accessed_entities.borrow_mut();
|
||||
|
||||
dropped_entity_ids
|
||||
.into_iter()
|
||||
@@ -143,6 +169,7 @@ impl EntityMap {
|
||||
0,
|
||||
"dropped an entity that was referenced"
|
||||
);
|
||||
accessed_entities.remove(&entity_id);
|
||||
// If the EntityId was allocated with `Context::reserve`,
|
||||
// the entity may not have been inserted.
|
||||
Some((entity_id, self.entities.remove(entity_id)?))
|
||||
@@ -160,7 +187,7 @@ fn double_lease_panic<T>(operation: &str) -> ! {
|
||||
|
||||
pub(crate) struct Lease<'a, T> {
|
||||
entity: Option<Box<dyn Any>>,
|
||||
pub model: &'a Model<T>,
|
||||
pub pointer: &'a Entity<T>,
|
||||
entity_type: PhantomData<T>,
|
||||
}
|
||||
|
||||
@@ -187,10 +214,10 @@ impl<'a, T> Drop for Lease<'a, T> {
|
||||
}
|
||||
|
||||
#[derive(Deref, DerefMut)]
|
||||
pub(crate) struct Slot<T>(Model<T>);
|
||||
pub(crate) struct Slot<T>(Entity<T>);
|
||||
|
||||
/// A dynamically typed reference to a model, which can be downcast into a `Model<T>`.
|
||||
pub struct AnyModel {
|
||||
pub struct AnyEntity {
|
||||
pub(crate) entity_id: EntityId,
|
||||
pub(crate) entity_type: TypeId,
|
||||
entity_map: Weak<RwLock<EntityRefCounts>>,
|
||||
@@ -198,7 +225,7 @@ pub struct AnyModel {
|
||||
handle_id: HandleId,
|
||||
}
|
||||
|
||||
impl AnyModel {
|
||||
impl AnyEntity {
|
||||
fn new(id: EntityId, entity_type: TypeId, entity_map: Weak<RwLock<EntityRefCounts>>) -> Self {
|
||||
Self {
|
||||
entity_id: id,
|
||||
@@ -225,8 +252,8 @@ impl AnyModel {
|
||||
}
|
||||
|
||||
/// Converts this model handle into a weak variant, which does not prevent it from being released.
|
||||
pub fn downgrade(&self) -> AnyWeakModel {
|
||||
AnyWeakModel {
|
||||
pub fn downgrade(&self) -> AnyWeakEntity {
|
||||
AnyWeakEntity {
|
||||
entity_id: self.entity_id,
|
||||
entity_type: self.entity_type,
|
||||
entity_ref_counts: self.entity_map.clone(),
|
||||
@@ -235,10 +262,10 @@ impl AnyModel {
|
||||
|
||||
/// Converts this model handle into a strongly-typed model handle of the given type.
|
||||
/// If this model handle is not of the specified type, returns itself as an error variant.
|
||||
pub fn downcast<T: 'static>(self) -> Result<Model<T>, AnyModel> {
|
||||
pub fn downcast<T: 'static>(self) -> Result<Entity<T>, AnyEntity> {
|
||||
if TypeId::of::<T>() == self.entity_type {
|
||||
Ok(Model {
|
||||
any_model: self,
|
||||
Ok(Entity {
|
||||
any_entity: self,
|
||||
entity_type: PhantomData,
|
||||
})
|
||||
} else {
|
||||
@@ -247,7 +274,7 @@ impl AnyModel {
|
||||
}
|
||||
}
|
||||
|
||||
impl Clone for AnyModel {
|
||||
impl Clone for AnyEntity {
|
||||
fn clone(&self) -> Self {
|
||||
if let Some(entity_map) = self.entity_map.upgrade() {
|
||||
let entity_map = entity_map.read();
|
||||
@@ -275,7 +302,7 @@ impl Clone for AnyModel {
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for AnyModel {
|
||||
impl Drop for AnyEntity {
|
||||
fn drop(&mut self) {
|
||||
if let Some(entity_map) = self.entity_map.upgrade() {
|
||||
let entity_map = entity_map.upgradable_read();
|
||||
@@ -302,27 +329,27 @@ impl Drop for AnyModel {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> From<Model<T>> for AnyModel {
|
||||
fn from(model: Model<T>) -> Self {
|
||||
model.any_model
|
||||
impl<T> From<Entity<T>> for AnyEntity {
|
||||
fn from(model: Entity<T>) -> Self {
|
||||
model.any_entity
|
||||
}
|
||||
}
|
||||
|
||||
impl Hash for AnyModel {
|
||||
impl Hash for AnyEntity {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
self.entity_id.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for AnyModel {
|
||||
impl PartialEq for AnyEntity {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.entity_id == other.entity_id
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for AnyModel {}
|
||||
impl Eq for AnyEntity {}
|
||||
|
||||
impl std::fmt::Debug for AnyModel {
|
||||
impl std::fmt::Debug for AnyEntity {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("AnyModel")
|
||||
.field("entity_id", &self.entity_id.as_u64())
|
||||
@@ -333,76 +360,67 @@ impl std::fmt::Debug for AnyModel {
|
||||
/// A strong, well typed reference to a struct which is managed
|
||||
/// by GPUI
|
||||
#[derive(Deref, DerefMut)]
|
||||
pub struct Model<T> {
|
||||
pub struct Entity<T> {
|
||||
#[deref]
|
||||
#[deref_mut]
|
||||
pub(crate) any_model: AnyModel,
|
||||
pub(crate) any_entity: AnyEntity,
|
||||
pub(crate) entity_type: PhantomData<T>,
|
||||
}
|
||||
|
||||
unsafe impl<T> Send for Model<T> {}
|
||||
unsafe impl<T> Sync for Model<T> {}
|
||||
impl<T> Sealed for Model<T> {}
|
||||
unsafe impl<T> Send for Entity<T> {}
|
||||
unsafe impl<T> Sync for Entity<T> {}
|
||||
impl<T> Sealed for Entity<T> {}
|
||||
|
||||
impl<T: 'static> Entity<T> for Model<T> {
|
||||
type Weak = WeakModel<T>;
|
||||
|
||||
fn entity_id(&self) -> EntityId {
|
||||
self.any_model.entity_id
|
||||
}
|
||||
|
||||
fn downgrade(&self) -> Self::Weak {
|
||||
WeakModel {
|
||||
any_model: self.any_model.downgrade(),
|
||||
entity_type: self.entity_type,
|
||||
}
|
||||
}
|
||||
|
||||
fn upgrade_from(weak: &Self::Weak) -> Option<Self>
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
Some(Model {
|
||||
any_model: weak.any_model.upgrade()?,
|
||||
entity_type: weak.entity_type,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: 'static> Model<T> {
|
||||
impl<T: 'static> Entity<T> {
|
||||
fn new(id: EntityId, entity_map: Weak<RwLock<EntityRefCounts>>) -> Self
|
||||
where
|
||||
T: 'static,
|
||||
{
|
||||
Self {
|
||||
any_model: AnyModel::new(id, TypeId::of::<T>(), entity_map),
|
||||
any_entity: AnyEntity::new(id, TypeId::of::<T>(), entity_map),
|
||||
entity_type: PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
/// Downgrade the this to a weak model reference
|
||||
pub fn downgrade(&self) -> WeakModel<T> {
|
||||
// Delegate to the trait implementation to keep behavior in one place.
|
||||
// This method was included to improve method resolution in the presence of
|
||||
// the Model's deref
|
||||
Entity::downgrade(self)
|
||||
/// Get the entity ID associated with this entity
|
||||
pub fn entity_id(&self) -> EntityId {
|
||||
self.any_entity.entity_id
|
||||
}
|
||||
|
||||
/// Downgrade this entity pointer to a non-retaining weak pointer
|
||||
pub fn downgrade(&self) -> WeakEntity<T> {
|
||||
WeakEntity {
|
||||
any_entity: self.any_entity.downgrade(),
|
||||
entity_type: self.entity_type,
|
||||
}
|
||||
}
|
||||
|
||||
/// Upgrade the given weak pointer to a retaining pointer, if it still exists
|
||||
pub fn upgrade_from(weak: &WeakEntity<T>) -> Option<Self>
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
Some(Entity {
|
||||
any_entity: weak.any_entity.upgrade()?,
|
||||
entity_type: weak.entity_type,
|
||||
})
|
||||
}
|
||||
|
||||
/// Convert this into a dynamically typed model.
|
||||
pub fn into_any(self) -> AnyModel {
|
||||
self.any_model
|
||||
pub fn into_any(self) -> AnyEntity {
|
||||
self.any_entity
|
||||
}
|
||||
|
||||
/// Grab a reference to this entity from the context.
|
||||
pub fn read<'a>(&self, cx: &'a AppContext) -> &'a T {
|
||||
pub fn read<'a>(&self, cx: &'a App) -> &'a T {
|
||||
cx.entities.read(self)
|
||||
}
|
||||
|
||||
/// Read the entity referenced by this model with the given function.
|
||||
pub fn read_with<R, C: Context>(
|
||||
pub fn read_with<R, C: AppContext>(
|
||||
&self,
|
||||
cx: &C,
|
||||
f: impl FnOnce(&T, &AppContext) -> R,
|
||||
f: impl FnOnce(&T, &App) -> R,
|
||||
) -> C::Result<R> {
|
||||
cx.read_model(self, f)
|
||||
}
|
||||
@@ -415,62 +433,76 @@ impl<T: 'static> Model<T> {
|
||||
pub fn update<C, R>(
|
||||
&self,
|
||||
cx: &mut C,
|
||||
update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
|
||||
update: impl FnOnce(&mut T, &mut Context<'_, T>) -> R,
|
||||
) -> C::Result<R>
|
||||
where
|
||||
C: Context,
|
||||
C: AppContext,
|
||||
{
|
||||
cx.update_model(self, update)
|
||||
}
|
||||
|
||||
/// Updates the entity referenced by this model with the given function if
|
||||
/// the referenced entity still exists, within a visual context that has a window.
|
||||
/// Returns an error if the entity has been released.
|
||||
pub fn update_in<C, R>(
|
||||
&self,
|
||||
cx: &mut C,
|
||||
update: impl FnOnce(&mut T, &mut Window, &mut Context<'_, T>) -> R,
|
||||
) -> C::Result<R>
|
||||
where
|
||||
C: VisualContext,
|
||||
{
|
||||
cx.update_window_model(self, update)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Clone for Model<T> {
|
||||
impl<T> Clone for Entity<T> {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
any_model: self.any_model.clone(),
|
||||
any_entity: self.any_entity.clone(),
|
||||
entity_type: self.entity_type,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> std::fmt::Debug for Model<T> {
|
||||
impl<T> std::fmt::Debug for Entity<T> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("Model")
|
||||
.field("entity_id", &self.any_model.entity_id)
|
||||
.field("entity_id", &self.any_entity.entity_id)
|
||||
.field("entity_type", &type_name::<T>())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Hash for Model<T> {
|
||||
impl<T> Hash for Entity<T> {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
self.any_model.hash(state);
|
||||
self.any_entity.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> PartialEq for Model<T> {
|
||||
impl<T> PartialEq for Entity<T> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.any_model == other.any_model
|
||||
self.any_entity == other.any_entity
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Eq for Model<T> {}
|
||||
impl<T> Eq for Entity<T> {}
|
||||
|
||||
impl<T> PartialEq<WeakModel<T>> for Model<T> {
|
||||
fn eq(&self, other: &WeakModel<T>) -> bool {
|
||||
self.any_model.entity_id() == other.entity_id()
|
||||
impl<T> PartialEq<WeakEntity<T>> for Entity<T> {
|
||||
fn eq(&self, other: &WeakEntity<T>) -> bool {
|
||||
self.any_entity.entity_id() == other.entity_id()
|
||||
}
|
||||
}
|
||||
|
||||
/// A type erased, weak reference to a model.
|
||||
#[derive(Clone)]
|
||||
pub struct AnyWeakModel {
|
||||
pub struct AnyWeakEntity {
|
||||
pub(crate) entity_id: EntityId,
|
||||
entity_type: TypeId,
|
||||
entity_ref_counts: Weak<RwLock<EntityRefCounts>>,
|
||||
}
|
||||
|
||||
impl AnyWeakModel {
|
||||
impl AnyWeakEntity {
|
||||
/// Get the entity ID associated with this weak reference.
|
||||
pub fn entity_id(&self) -> EntityId {
|
||||
self.entity_id
|
||||
@@ -487,7 +519,7 @@ impl AnyWeakModel {
|
||||
}
|
||||
|
||||
/// Upgrade this weak model reference to a strong reference.
|
||||
pub fn upgrade(&self) -> Option<AnyModel> {
|
||||
pub fn upgrade(&self) -> Option<AnyEntity> {
|
||||
let ref_counts = &self.entity_ref_counts.upgrade()?;
|
||||
let ref_counts = ref_counts.read();
|
||||
let ref_count = ref_counts.counts.get(self.entity_id)?;
|
||||
@@ -499,7 +531,7 @@ impl AnyWeakModel {
|
||||
ref_count.fetch_add(1, SeqCst);
|
||||
drop(ref_counts);
|
||||
|
||||
Some(AnyModel {
|
||||
Some(AnyEntity {
|
||||
entity_id: self.entity_id,
|
||||
entity_type: self.entity_type,
|
||||
entity_map: self.entity_ref_counts.clone(),
|
||||
@@ -537,7 +569,7 @@ impl AnyWeakModel {
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for AnyWeakModel {
|
||||
impl std::fmt::Debug for AnyWeakEntity {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct(type_name::<Self>())
|
||||
.field("entity_id", &self.entity_id)
|
||||
@@ -546,61 +578,61 @@ impl std::fmt::Debug for AnyWeakModel {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> From<WeakModel<T>> for AnyWeakModel {
|
||||
fn from(model: WeakModel<T>) -> Self {
|
||||
model.any_model
|
||||
impl<T> From<WeakEntity<T>> for AnyWeakEntity {
|
||||
fn from(model: WeakEntity<T>) -> Self {
|
||||
model.any_entity
|
||||
}
|
||||
}
|
||||
|
||||
impl Hash for AnyWeakModel {
|
||||
impl Hash for AnyWeakEntity {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
self.entity_id.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for AnyWeakModel {
|
||||
impl PartialEq for AnyWeakEntity {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.entity_id == other.entity_id
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for AnyWeakModel {}
|
||||
impl Eq for AnyWeakEntity {}
|
||||
|
||||
/// A weak reference to a model of the given type.
|
||||
#[derive(Deref, DerefMut)]
|
||||
pub struct WeakModel<T> {
|
||||
pub struct WeakEntity<T> {
|
||||
#[deref]
|
||||
#[deref_mut]
|
||||
any_model: AnyWeakModel,
|
||||
any_entity: AnyWeakEntity,
|
||||
entity_type: PhantomData<T>,
|
||||
}
|
||||
|
||||
impl<T> std::fmt::Debug for WeakModel<T> {
|
||||
impl<T> std::fmt::Debug for WeakEntity<T> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct(&type_name::<Self>())
|
||||
.field("entity_id", &self.any_model.entity_id)
|
||||
.field("entity_id", &self.any_entity.entity_id)
|
||||
.field("entity_type", &type_name::<T>())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
unsafe impl<T> Send for WeakModel<T> {}
|
||||
unsafe impl<T> Sync for WeakModel<T> {}
|
||||
unsafe impl<T> Send for WeakEntity<T> {}
|
||||
unsafe impl<T> Sync for WeakEntity<T> {}
|
||||
|
||||
impl<T> Clone for WeakModel<T> {
|
||||
impl<T> Clone for WeakEntity<T> {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
any_model: self.any_model.clone(),
|
||||
any_entity: self.any_entity.clone(),
|
||||
entity_type: self.entity_type,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: 'static> WeakModel<T> {
|
||||
impl<T: 'static> WeakEntity<T> {
|
||||
/// Upgrade this weak model reference into a strong model reference
|
||||
pub fn upgrade(&self) -> Option<Model<T>> {
|
||||
pub fn upgrade(&self) -> Option<Entity<T>> {
|
||||
// Delegate to the trait implementation to keep behavior in one place.
|
||||
Model::upgrade_from(self)
|
||||
Entity::upgrade_from(self)
|
||||
}
|
||||
|
||||
/// Updates the entity referenced by this model with the given function if
|
||||
@@ -609,25 +641,45 @@ impl<T: 'static> WeakModel<T> {
|
||||
pub fn update<C, R>(
|
||||
&self,
|
||||
cx: &mut C,
|
||||
update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
|
||||
update: impl FnOnce(&mut T, &mut Context<'_, T>) -> R,
|
||||
) -> Result<R>
|
||||
where
|
||||
C: Context,
|
||||
C: AppContext,
|
||||
Result<C::Result<R>>: crate::Flatten<R>,
|
||||
{
|
||||
crate::Flatten::flatten(
|
||||
self.upgrade()
|
||||
.ok_or_else(|| anyhow!("entity release"))
|
||||
.ok_or_else(|| anyhow!("entity released"))
|
||||
.map(|this| cx.update_model(&this, update)),
|
||||
)
|
||||
}
|
||||
|
||||
/// Updates the entity referenced by this model with the given function if
|
||||
/// the referenced entity still exists, within a visual context that has a window.
|
||||
/// Returns an error if the entity has been released.
|
||||
pub fn update_in<C, R>(
|
||||
&self,
|
||||
cx: &mut C,
|
||||
update: impl FnOnce(&mut T, &mut Window, &mut Context<'_, T>) -> R,
|
||||
) -> Result<R>
|
||||
where
|
||||
C: VisualContext,
|
||||
Result<C::Result<R>>: crate::Flatten<R>,
|
||||
{
|
||||
let window = cx.window_handle();
|
||||
let this = self.upgrade().ok_or_else(|| anyhow!("entity released"))?;
|
||||
|
||||
crate::Flatten::flatten(window.update(cx, |_, window, cx| {
|
||||
this.update(cx, |model, cx| update(model, window, cx))
|
||||
}))
|
||||
}
|
||||
|
||||
/// Reads the entity referenced by this model with the given function if
|
||||
/// the referenced entity still exists. Returns an error if the entity has
|
||||
/// been released.
|
||||
pub fn read_with<C, R>(&self, cx: &C, read: impl FnOnce(&T, &AppContext) -> R) -> Result<R>
|
||||
pub fn read_with<C, R>(&self, cx: &C, read: impl FnOnce(&T, &App) -> R) -> Result<R>
|
||||
where
|
||||
C: Context,
|
||||
C: AppContext,
|
||||
Result<C::Result<R>>: crate::Flatten<R>,
|
||||
{
|
||||
crate::Flatten::flatten(
|
||||
@@ -638,23 +690,23 @@ impl<T: 'static> WeakModel<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Hash for WeakModel<T> {
|
||||
impl<T> Hash for WeakEntity<T> {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
self.any_model.hash(state);
|
||||
self.any_entity.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> PartialEq for WeakModel<T> {
|
||||
impl<T> PartialEq for WeakEntity<T> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.any_model == other.any_model
|
||||
self.any_entity == other.any_entity
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Eq for WeakModel<T> {}
|
||||
impl<T> Eq for WeakEntity<T> {}
|
||||
|
||||
impl<T> PartialEq<Model<T>> for WeakModel<T> {
|
||||
fn eq(&self, other: &Model<T>) -> bool {
|
||||
self.entity_id() == other.any_model.entity_id()
|
||||
impl<T> PartialEq<Entity<T>> for WeakEntity<T> {
|
||||
fn eq(&self, other: &Entity<T>) -> bool {
|
||||
self.entity_id() == other.any_entity.entity_id()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use crate::{
|
||||
AnyView, AnyWindowHandle, AppContext, AsyncAppContext, Context, Effect, Entity, EntityId,
|
||||
EventEmitter, Model, Reservation, Subscription, Task, View, WeakModel, WindowContext,
|
||||
WindowHandle,
|
||||
AnyView, AnyWindowHandle, App, AppContext, AsyncAppContext, DispatchPhase, Effect, EntityId,
|
||||
EventEmitter, FocusHandle, FocusOutEvent, Focusable, Global, KeystrokeObserver, Reservation,
|
||||
SubscriberSet, Subscription, Task, WeakEntity, WeakFocusHandle, Window, WindowHandle,
|
||||
};
|
||||
use anyhow::Result;
|
||||
use derive_more::{Deref, DerefMut};
|
||||
@@ -10,19 +10,22 @@ use std::{
|
||||
any::{Any, TypeId},
|
||||
borrow::{Borrow, BorrowMut},
|
||||
future::Future,
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use super::{AsyncWindowContext, Entity, KeystrokeEvent};
|
||||
|
||||
/// The app context, with specialized behavior for the given model.
|
||||
#[derive(Deref, DerefMut)]
|
||||
pub struct ModelContext<'a, T> {
|
||||
pub struct Context<'a, T> {
|
||||
#[deref]
|
||||
#[deref_mut]
|
||||
app: &'a mut AppContext,
|
||||
model_state: WeakModel<T>,
|
||||
app: &'a mut App,
|
||||
model_state: WeakEntity<T>,
|
||||
}
|
||||
|
||||
impl<'a, T: 'static> ModelContext<'a, T> {
|
||||
pub(crate) fn new(app: &'a mut AppContext, model_state: WeakModel<T>) -> Self {
|
||||
impl<'a, T: 'static> Context<'a, T> {
|
||||
pub(crate) fn new_context(app: &'a mut App, model_state: WeakEntity<T>) -> Self {
|
||||
Self { app, model_state }
|
||||
}
|
||||
|
||||
@@ -32,28 +35,27 @@ impl<'a, T: 'static> ModelContext<'a, T> {
|
||||
}
|
||||
|
||||
/// Returns a handle to the model belonging to this context.
|
||||
pub fn handle(&self) -> Model<T> {
|
||||
pub fn model(&self) -> Entity<T> {
|
||||
self.weak_model()
|
||||
.upgrade()
|
||||
.expect("The entity must be alive if we have a model context")
|
||||
}
|
||||
|
||||
/// Returns a weak handle to the model belonging to this context.
|
||||
pub fn weak_model(&self) -> WeakModel<T> {
|
||||
pub fn weak_model(&self) -> WeakEntity<T> {
|
||||
self.model_state.clone()
|
||||
}
|
||||
|
||||
/// Arranges for the given function to be called whenever [`ModelContext::notify`] or
|
||||
/// [`ViewContext::notify`](crate::ViewContext::notify) is called with the given model or view.
|
||||
pub fn observe<W, E>(
|
||||
pub fn observe<W>(
|
||||
&mut self,
|
||||
entity: &E,
|
||||
mut on_notify: impl FnMut(&mut T, E, &mut ModelContext<'_, T>) + 'static,
|
||||
entity: &Entity<W>,
|
||||
mut on_notify: impl FnMut(&mut T, Entity<W>, &mut Context<'_, T>) + 'static,
|
||||
) -> Subscription
|
||||
where
|
||||
T: 'static,
|
||||
W: 'static,
|
||||
E: Entity<W>,
|
||||
{
|
||||
let this = self.weak_model();
|
||||
self.app.observe_internal(entity, move |e, cx| {
|
||||
@@ -67,15 +69,14 @@ impl<'a, T: 'static> ModelContext<'a, T> {
|
||||
}
|
||||
|
||||
/// Subscribe to an event type from another model or view
|
||||
pub fn subscribe<T2, E, Evt>(
|
||||
pub fn subscribe<T2, Evt>(
|
||||
&mut self,
|
||||
entity: &E,
|
||||
mut on_event: impl FnMut(&mut T, E, &Evt, &mut ModelContext<'_, T>) + 'static,
|
||||
entity: &Entity<T2>,
|
||||
mut on_event: impl FnMut(&mut T, Entity<T2>, &Evt, &mut Context<'_, T>) + 'static,
|
||||
) -> Subscription
|
||||
where
|
||||
T: 'static,
|
||||
T2: 'static + EventEmitter<Evt>,
|
||||
E: Entity<T2>,
|
||||
Evt: 'static,
|
||||
{
|
||||
let this = self.weak_model();
|
||||
@@ -90,10 +91,7 @@ impl<'a, T: 'static> ModelContext<'a, T> {
|
||||
}
|
||||
|
||||
/// Register a callback to be invoked when GPUI releases this model.
|
||||
pub fn on_release(
|
||||
&self,
|
||||
on_release: impl FnOnce(&mut T, &mut AppContext) + 'static,
|
||||
) -> Subscription
|
||||
pub fn on_release(&self, on_release: impl FnOnce(&mut T, &mut App) + 'static) -> Subscription
|
||||
where
|
||||
T: 'static,
|
||||
{
|
||||
@@ -109,15 +107,14 @@ impl<'a, T: 'static> ModelContext<'a, T> {
|
||||
}
|
||||
|
||||
/// Register a callback to be run on the release of another model or view
|
||||
pub fn observe_release<T2, E>(
|
||||
pub fn observe_release<T2>(
|
||||
&self,
|
||||
entity: &E,
|
||||
on_release: impl FnOnce(&mut T, &mut T2, &mut ModelContext<'_, T>) + 'static,
|
||||
entity: &Entity<T2>,
|
||||
on_release: impl FnOnce(&mut T, &mut T2, &mut Context<'_, T>) + 'static,
|
||||
) -> Subscription
|
||||
where
|
||||
T: Any,
|
||||
T2: 'static,
|
||||
E: Entity<T2>,
|
||||
{
|
||||
let entity_id = entity.entity_id();
|
||||
let this = self.weak_model();
|
||||
@@ -137,7 +134,7 @@ impl<'a, T: 'static> ModelContext<'a, T> {
|
||||
/// Register a callback to for updates to the given global
|
||||
pub fn observe_global<G: 'static>(
|
||||
&mut self,
|
||||
mut f: impl FnMut(&mut T, &mut ModelContext<'_, T>) + 'static,
|
||||
mut f: impl FnMut(&mut T, &mut Context<'_, T>) + 'static,
|
||||
) -> Subscription
|
||||
where
|
||||
T: 'static,
|
||||
@@ -155,7 +152,7 @@ impl<'a, T: 'static> ModelContext<'a, T> {
|
||||
/// The future returned from this callback will be polled for up to [crate::SHUTDOWN_TIMEOUT] until the app fully quits.
|
||||
pub fn on_app_quit<Fut>(
|
||||
&self,
|
||||
mut on_quit: impl FnMut(&mut T, &mut ModelContext<T>) -> Fut + 'static,
|
||||
mut on_quit: impl FnMut(&mut T, &mut Context<T>) -> Fut + 'static,
|
||||
) -> Subscription
|
||||
where
|
||||
Fut: 'static + Future<Output = ()>,
|
||||
@@ -180,21 +177,13 @@ impl<'a, T: 'static> ModelContext<'a, T> {
|
||||
|
||||
/// Tell GPUI that this model has changed and observers of it should be notified.
|
||||
pub fn notify(&mut self) {
|
||||
if self
|
||||
.app
|
||||
.pending_notifications
|
||||
.insert(self.model_state.entity_id)
|
||||
{
|
||||
self.app.pending_effects.push_back(Effect::Notify {
|
||||
emitter: self.model_state.entity_id,
|
||||
});
|
||||
}
|
||||
self.app.notify(self.model_state.entity_id);
|
||||
}
|
||||
|
||||
/// Spawn the future returned by the given function.
|
||||
/// The function is provided a weak handle to the model owned by this context and a context that can be held across await points.
|
||||
/// The returned task must be held or detached.
|
||||
pub fn spawn<Fut, R>(&self, f: impl FnOnce(WeakModel<T>, AsyncAppContext) -> Fut) -> Task<R>
|
||||
pub fn spawn<Fut, R>(&self, f: impl FnOnce(WeakEntity<T>, AsyncAppContext) -> Fut) -> Task<R>
|
||||
where
|
||||
T: 'static,
|
||||
Fut: Future<Output = R> + 'static,
|
||||
@@ -203,9 +192,476 @@ impl<'a, T: 'static> ModelContext<'a, T> {
|
||||
let this = self.weak_model();
|
||||
self.app.spawn(|cx| f(this, cx))
|
||||
}
|
||||
|
||||
/// Convenience method for accessing view state in an event callback.
|
||||
///
|
||||
/// Many GPUI callbacks take the form of `Fn(&E, &mut Window, &mut AppContext)`,
|
||||
/// but it's often useful to be able to access view state in these
|
||||
/// callbacks. This method provides a convenient way to do so.
|
||||
pub fn listener<E: ?Sized>(
|
||||
&self,
|
||||
f: impl Fn(&mut T, &E, &mut Window, &mut Context<T>) + 'static,
|
||||
) -> impl Fn(&E, &mut Window, &mut App) + 'static {
|
||||
let view = self.model().downgrade();
|
||||
move |e: &E, window: &mut Window, cx: &mut App| {
|
||||
view.update(cx, |view, cx| f(view, e, window, cx)).ok();
|
||||
}
|
||||
}
|
||||
|
||||
/// Focus the given view in the given window. View type is required to implement Focusable.
|
||||
pub fn focus_view<W: Focusable>(&mut self, view: &Entity<W>, window: &mut Window) {
|
||||
window.focus(&view.focus_handle(self));
|
||||
}
|
||||
|
||||
/// Sets a given callback to be run on the next frame.
|
||||
pub fn on_next_frame(
|
||||
&self,
|
||||
window: &mut Window,
|
||||
f: impl FnOnce(&mut T, &mut Window, &mut Context<T>) + 'static,
|
||||
) where
|
||||
T: 'static,
|
||||
{
|
||||
let view = self.model();
|
||||
window.on_next_frame(move |window, cx| view.update(cx, |view, cx| f(view, window, cx)));
|
||||
}
|
||||
|
||||
/// 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_in(
|
||||
&mut self,
|
||||
window: &Window,
|
||||
f: impl FnOnce(&mut T, &mut Window, &mut Context<T>) + 'static,
|
||||
) {
|
||||
let view = self.model();
|
||||
window.defer(self, move |window, cx| {
|
||||
view.update(cx, |view, cx| f(view, window, cx))
|
||||
});
|
||||
}
|
||||
|
||||
/// Observe another model or view for changes to its state, as tracked by [`ModelContext::notify`].
|
||||
pub fn observe_in<V2>(
|
||||
&mut self,
|
||||
observed: &Entity<V2>,
|
||||
window: &mut Window,
|
||||
mut on_notify: impl FnMut(&mut T, Entity<V2>, &mut Window, &mut Context<'_, T>) + 'static,
|
||||
) -> Subscription
|
||||
where
|
||||
V2: 'static,
|
||||
T: 'static,
|
||||
{
|
||||
let observed_id = observed.entity_id();
|
||||
let observed = observed.downgrade();
|
||||
let window_handle = window.handle;
|
||||
let observer = self.weak_model();
|
||||
self.new_observer(
|
||||
observed_id,
|
||||
Box::new(move |cx| {
|
||||
window_handle
|
||||
.update(cx, |_, window, cx| {
|
||||
if let Some((observer, observed)) =
|
||||
observer.upgrade().zip(observed.upgrade())
|
||||
{
|
||||
observer.update(cx, |observer, cx| {
|
||||
on_notify(observer, observed, window, cx);
|
||||
});
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
})
|
||||
.unwrap_or(false)
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/// Subscribe to events emitted by another model or view.
|
||||
/// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
|
||||
/// The callback will be invoked with a reference to the current view, a handle to the emitting entity (either a [`View`] or [`Model`]), the event, and a view context for the current view.
|
||||
pub fn subscribe_in<Emitter, Evt>(
|
||||
&mut self,
|
||||
emitter: &Entity<Emitter>,
|
||||
window: &Window,
|
||||
mut on_event: impl FnMut(&mut T, &Entity<Emitter>, &Evt, &mut Window, &mut Context<'_, T>)
|
||||
+ 'static,
|
||||
) -> Subscription
|
||||
where
|
||||
Emitter: EventEmitter<Evt>,
|
||||
Evt: 'static,
|
||||
{
|
||||
let emitter = emitter.downgrade();
|
||||
let window_handle = window.handle;
|
||||
let subscriber = self.weak_model();
|
||||
self.new_subscription(
|
||||
emitter.entity_id(),
|
||||
(
|
||||
TypeId::of::<Evt>(),
|
||||
Box::new(move |event, cx| {
|
||||
window_handle
|
||||
.update(cx, |_, window, cx| {
|
||||
if let Some((subscriber, emitter)) =
|
||||
subscriber.upgrade().zip(emitter.upgrade())
|
||||
{
|
||||
let event = event.downcast_ref().expect("invalid event type");
|
||||
subscriber.update(cx, |subscriber, cx| {
|
||||
on_event(subscriber, &emitter, event, window, cx);
|
||||
});
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
})
|
||||
.unwrap_or(false)
|
||||
}),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
/// Register a callback to be invoked when the view is released.
|
||||
///
|
||||
/// The callback receives a handle to the view's window. This handle may be
|
||||
/// invalid, if the window was closed before the view was released.
|
||||
pub fn on_release_in(
|
||||
&mut self,
|
||||
window: &Window,
|
||||
on_release: impl FnOnce(&mut T, AnyWindowHandle, &mut App) + 'static,
|
||||
) -> Subscription {
|
||||
let window_handle = window.handle;
|
||||
let (subscription, activate) = self.release_listeners.insert(
|
||||
self.entity_id(),
|
||||
Box::new(move |this, cx| {
|
||||
let this = this.downcast_mut().expect("invalid entity type");
|
||||
on_release(this, window_handle, cx)
|
||||
}),
|
||||
);
|
||||
activate();
|
||||
subscription
|
||||
}
|
||||
|
||||
/// Register a callback to be invoked when the given Model or View is released.
|
||||
pub fn observe_release_in<V2>(
|
||||
&self,
|
||||
observed: &Entity<V2>,
|
||||
window: &Window,
|
||||
mut on_release: impl FnMut(&mut T, &mut V2, &mut Window, &mut Context<'_, T>) + 'static,
|
||||
) -> Subscription
|
||||
where
|
||||
T: 'static,
|
||||
V2: 'static,
|
||||
{
|
||||
let observer = self.weak_model();
|
||||
let window_handle = window.handle;
|
||||
let (subscription, activate) = self.release_listeners.insert(
|
||||
observed.entity_id(),
|
||||
Box::new(move |observed, cx| {
|
||||
let observed = observed
|
||||
.downcast_mut()
|
||||
.expect("invalid observed entity type");
|
||||
let _ = window_handle.update(cx, |_, window, cx| {
|
||||
observer.update(cx, |this, cx| on_release(this, observed, window, cx))
|
||||
});
|
||||
}),
|
||||
);
|
||||
activate();
|
||||
subscription
|
||||
}
|
||||
|
||||
/// Register a callback to be invoked when the window is resized.
|
||||
pub fn observe_window_bounds(
|
||||
&self,
|
||||
window: &mut Window,
|
||||
mut callback: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
|
||||
) -> Subscription {
|
||||
let view = self.weak_model();
|
||||
let (subscription, activate) = window.bounds_observers.insert(
|
||||
(),
|
||||
Box::new(move |window, cx| {
|
||||
view.update(cx, |view, cx| callback(view, window, cx))
|
||||
.is_ok()
|
||||
}),
|
||||
);
|
||||
activate();
|
||||
subscription
|
||||
}
|
||||
|
||||
/// Register a callback to be invoked when the window is activated or deactivated.
|
||||
pub fn observe_window_activation(
|
||||
&self,
|
||||
window: &mut Window,
|
||||
mut callback: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
|
||||
) -> Subscription {
|
||||
let view = self.weak_model();
|
||||
let (subscription, activate) = window.activation_observers.insert(
|
||||
(),
|
||||
Box::new(move |window, cx| {
|
||||
view.update(cx, |view, cx| callback(view, window, cx))
|
||||
.is_ok()
|
||||
}),
|
||||
);
|
||||
activate();
|
||||
subscription
|
||||
}
|
||||
|
||||
/// Registers a callback to be invoked when the window appearance changes.
|
||||
pub fn observe_window_appearance(
|
||||
&self,
|
||||
window: &mut Window,
|
||||
mut callback: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
|
||||
) -> Subscription {
|
||||
let view = self.weak_model();
|
||||
let (subscription, activate) = window.appearance_observers.insert(
|
||||
(),
|
||||
Box::new(move |window, cx| {
|
||||
view.update(cx, |view, cx| callback(view, window, cx))
|
||||
.is_ok()
|
||||
}),
|
||||
);
|
||||
activate();
|
||||
subscription
|
||||
}
|
||||
|
||||
/// Register a callback to be invoked when a keystroke is received by the application
|
||||
/// in any window. Note that this fires after all other action and event mechanisms have resolved
|
||||
/// and that this API will not be invoked if the event's propagation is stopped.
|
||||
pub fn observe_keystrokes(
|
||||
&mut self,
|
||||
mut f: impl FnMut(&mut T, &KeystrokeEvent, &mut Window, &mut Context<T>) + 'static,
|
||||
) -> Subscription {
|
||||
fn inner(
|
||||
keystroke_observers: &SubscriberSet<(), KeystrokeObserver>,
|
||||
handler: KeystrokeObserver,
|
||||
) -> Subscription {
|
||||
let (subscription, activate) = keystroke_observers.insert((), handler);
|
||||
activate();
|
||||
subscription
|
||||
}
|
||||
|
||||
let view = self.weak_model();
|
||||
inner(
|
||||
&mut self.keystroke_observers,
|
||||
Box::new(move |event, window, cx| {
|
||||
if let Some(view) = view.upgrade() {
|
||||
view.update(cx, |view, cx| f(view, event, window, cx));
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/// Register a callback to be invoked when the window's pending input changes.
|
||||
pub fn observe_pending_input(
|
||||
&self,
|
||||
window: &mut Window,
|
||||
mut callback: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
|
||||
) -> Subscription {
|
||||
let view = self.weak_model();
|
||||
let (subscription, activate) = window.pending_input_observers.insert(
|
||||
(),
|
||||
Box::new(move |window, cx| {
|
||||
view.update(cx, |view, cx| callback(view, window, cx))
|
||||
.is_ok()
|
||||
}),
|
||||
);
|
||||
activate();
|
||||
subscription
|
||||
}
|
||||
|
||||
/// Register a listener to be called when the given focus handle receives focus.
|
||||
/// Returns a subscription and persists until the subscription is dropped.
|
||||
pub fn on_focus(
|
||||
&mut self,
|
||||
handle: &FocusHandle,
|
||||
window: &mut Window,
|
||||
mut listener: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
|
||||
) -> Subscription {
|
||||
let view = self.weak_model();
|
||||
let focus_id = handle.id;
|
||||
let (subscription, activate) =
|
||||
window.new_focus_listener(Box::new(move |event, window, cx| {
|
||||
view.update(cx, |view, cx| {
|
||||
if event.previous_focus_path.last() != Some(&focus_id)
|
||||
&& event.current_focus_path.last() == Some(&focus_id)
|
||||
{
|
||||
listener(view, window, cx)
|
||||
}
|
||||
})
|
||||
.is_ok()
|
||||
}));
|
||||
self.defer(|_| activate());
|
||||
subscription
|
||||
}
|
||||
|
||||
/// Register a listener to be called when the given focus handle or one of its descendants receives focus.
|
||||
/// This does not fire if the given focus handle - or one of its descendants - was previously focused.
|
||||
/// Returns a subscription and persists until the subscription is dropped.
|
||||
pub fn on_focus_in(
|
||||
&mut self,
|
||||
handle: &FocusHandle,
|
||||
window: &mut Window,
|
||||
mut listener: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
|
||||
) -> Subscription {
|
||||
let view = self.weak_model();
|
||||
let focus_id = handle.id;
|
||||
let (subscription, activate) =
|
||||
window.new_focus_listener(Box::new(move |event, window, cx| {
|
||||
view.update(cx, |view, cx| {
|
||||
if event.is_focus_in(focus_id) {
|
||||
listener(view, window, cx)
|
||||
}
|
||||
})
|
||||
.is_ok()
|
||||
}));
|
||||
self.defer(|_| activate());
|
||||
subscription
|
||||
}
|
||||
|
||||
/// Register a listener to be called when the given focus handle loses focus.
|
||||
/// Returns a subscription and persists until the subscription is dropped.
|
||||
pub fn on_blur(
|
||||
&mut self,
|
||||
handle: &FocusHandle,
|
||||
window: &mut Window,
|
||||
mut listener: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
|
||||
) -> Subscription {
|
||||
let view = self.weak_model();
|
||||
let focus_id = handle.id;
|
||||
let (subscription, activate) =
|
||||
window.new_focus_listener(Box::new(move |event, window, cx| {
|
||||
view.update(cx, |view, cx| {
|
||||
if event.previous_focus_path.last() == Some(&focus_id)
|
||||
&& event.current_focus_path.last() != Some(&focus_id)
|
||||
{
|
||||
listener(view, window, cx)
|
||||
}
|
||||
})
|
||||
.is_ok()
|
||||
}));
|
||||
self.defer(|_| activate());
|
||||
subscription
|
||||
}
|
||||
|
||||
/// Register a listener to be called when nothing in the window has focus.
|
||||
/// This typically happens when the node that was focused is removed from the tree,
|
||||
/// and this callback lets you chose a default place to restore the users focus.
|
||||
/// Returns a subscription and persists until the subscription is dropped.
|
||||
pub fn on_focus_lost(
|
||||
&mut self,
|
||||
window: &mut Window,
|
||||
mut listener: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
|
||||
) -> Subscription {
|
||||
let view = self.weak_model();
|
||||
let (subscription, activate) = window.focus_lost_listeners.insert(
|
||||
(),
|
||||
Box::new(move |window, cx| {
|
||||
view.update(cx, |view, cx| listener(view, window, cx))
|
||||
.is_ok()
|
||||
}),
|
||||
);
|
||||
self.defer(|_| activate());
|
||||
subscription
|
||||
}
|
||||
|
||||
/// Register a listener to be called when the given focus handle or one of its descendants loses focus.
|
||||
/// Returns a subscription and persists until the subscription is dropped.
|
||||
pub fn on_focus_out(
|
||||
&mut self,
|
||||
handle: &FocusHandle,
|
||||
window: &mut Window,
|
||||
mut listener: impl FnMut(&mut T, FocusOutEvent, &mut Window, &mut Context<T>) + 'static,
|
||||
) -> Subscription {
|
||||
let view = self.weak_model();
|
||||
let focus_id = handle.id;
|
||||
let (subscription, activate) =
|
||||
window.new_focus_listener(Box::new(move |event, window, cx| {
|
||||
view.update(cx, |view, cx| {
|
||||
if let Some(blurred_id) = event.previous_focus_path.last().copied() {
|
||||
if event.is_focus_out(focus_id) {
|
||||
let event = FocusOutEvent {
|
||||
blurred: WeakFocusHandle {
|
||||
id: blurred_id,
|
||||
handles: Arc::downgrade(&cx.focus_handles),
|
||||
},
|
||||
};
|
||||
listener(view, event, window, cx)
|
||||
}
|
||||
}
|
||||
})
|
||||
.is_ok()
|
||||
}));
|
||||
self.defer(|_| activate());
|
||||
subscription
|
||||
}
|
||||
|
||||
/// Schedule a future to be run asynchronously.
|
||||
/// The given callback is invoked with a [`WeakModel<V>`] to avoid leaking the view for a long-running process.
|
||||
/// It's also given an [`AsyncWindowContext`], which can be used to access the state of the view across await points.
|
||||
/// The returned future will be polled on the main thread.
|
||||
pub fn spawn_in<Fut, R>(
|
||||
&self,
|
||||
window: &Window,
|
||||
f: impl FnOnce(WeakEntity<T>, AsyncWindowContext) -> Fut,
|
||||
) -> Task<R>
|
||||
where
|
||||
R: 'static,
|
||||
Fut: Future<Output = R> + 'static,
|
||||
{
|
||||
let view = self.weak_model();
|
||||
window.spawn(self, |mut cx| f(view, cx))
|
||||
}
|
||||
|
||||
/// Register a callback to be invoked when the given global state changes.
|
||||
pub fn observe_global_in<G: Global>(
|
||||
&mut self,
|
||||
window: &Window,
|
||||
mut f: impl FnMut(&mut T, &mut Window, &mut Context<'_, T>) + 'static,
|
||||
) -> Subscription {
|
||||
let window_handle = window.handle;
|
||||
let view = self.weak_model();
|
||||
let (subscription, activate) = self.global_observers.insert(
|
||||
TypeId::of::<G>(),
|
||||
Box::new(move |cx| {
|
||||
window_handle
|
||||
.update(cx, |_, window, cx| {
|
||||
view.update(cx, |view, cx| f(view, window, cx)).is_ok()
|
||||
})
|
||||
.unwrap_or(false)
|
||||
}),
|
||||
);
|
||||
self.defer(move |_| activate());
|
||||
subscription
|
||||
}
|
||||
|
||||
/// Register a callback to be invoked when the given Action type is dispatched to the window.
|
||||
pub fn on_action(
|
||||
&mut self,
|
||||
action_type: TypeId,
|
||||
window: &mut Window,
|
||||
listener: impl Fn(&mut T, &dyn Any, DispatchPhase, &mut Window, &mut Context<T>) + 'static,
|
||||
) {
|
||||
let handle = self.weak_model();
|
||||
window.on_action(action_type, move |action, phase, window, cx| {
|
||||
handle
|
||||
.update(cx, |view, cx| {
|
||||
listener(view, action, phase, window, cx);
|
||||
})
|
||||
.ok();
|
||||
});
|
||||
}
|
||||
|
||||
/// Move focus to the current view, assuming it implements [`Focusable`].
|
||||
pub fn focus_self(&mut self, window: &mut Window)
|
||||
where
|
||||
T: Focusable,
|
||||
{
|
||||
let view = self.model();
|
||||
window.defer(self, move |window, cx| {
|
||||
view.read(cx).focus_handle(cx).focus(window)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T> ModelContext<'a, T> {
|
||||
impl<'a, T> Context<'a, T> {
|
||||
/// Emit an event of the specified type, which can be handled by other entities that have subscribed via `subscribe` methods on their respective contexts.
|
||||
pub fn emit<Evt>(&mut self, event: Evt)
|
||||
where
|
||||
@@ -220,14 +676,11 @@ impl<'a, T> ModelContext<'a, T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T> Context for ModelContext<'a, T> {
|
||||
impl<'a, T> AppContext for Context<'a, T> {
|
||||
type Result<U> = U;
|
||||
|
||||
fn new_model<U: 'static>(
|
||||
&mut self,
|
||||
build_model: impl FnOnce(&mut ModelContext<'_, U>) -> U,
|
||||
) -> Model<U> {
|
||||
self.app.new_model(build_model)
|
||||
fn new<U: 'static>(&mut self, build_model: impl FnOnce(&mut Context<'_, U>) -> U) -> Entity<U> {
|
||||
self.app.new(build_model)
|
||||
}
|
||||
|
||||
fn reserve_model<U: 'static>(&mut self) -> Reservation<U> {
|
||||
@@ -237,23 +690,23 @@ impl<'a, T> Context for ModelContext<'a, T> {
|
||||
fn insert_model<U: 'static>(
|
||||
&mut self,
|
||||
reservation: Reservation<U>,
|
||||
build_model: impl FnOnce(&mut ModelContext<'_, U>) -> U,
|
||||
) -> Self::Result<Model<U>> {
|
||||
build_model: impl FnOnce(&mut Context<'_, U>) -> U,
|
||||
) -> Self::Result<Entity<U>> {
|
||||
self.app.insert_model(reservation, build_model)
|
||||
}
|
||||
|
||||
fn update_model<U: 'static, R>(
|
||||
&mut self,
|
||||
handle: &Model<U>,
|
||||
update: impl FnOnce(&mut U, &mut ModelContext<'_, U>) -> R,
|
||||
handle: &Entity<U>,
|
||||
update: impl FnOnce(&mut U, &mut Context<'_, U>) -> R,
|
||||
) -> R {
|
||||
self.app.update_model(handle, update)
|
||||
}
|
||||
|
||||
fn read_model<U, R>(
|
||||
&self,
|
||||
handle: &Model<U>,
|
||||
read: impl FnOnce(&U, &AppContext) -> R,
|
||||
handle: &Entity<U>,
|
||||
read: impl FnOnce(&U, &App) -> R,
|
||||
) -> Self::Result<R>
|
||||
where
|
||||
U: 'static,
|
||||
@@ -263,7 +716,7 @@ impl<'a, T> Context for ModelContext<'a, T> {
|
||||
|
||||
fn update_window<R, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<R>
|
||||
where
|
||||
F: FnOnce(AnyView, &mut WindowContext) -> R,
|
||||
F: FnOnce(AnyView, &mut Window, &mut App) -> R,
|
||||
{
|
||||
self.app.update_window(window, update)
|
||||
}
|
||||
@@ -271,7 +724,7 @@ impl<'a, T> Context for ModelContext<'a, T> {
|
||||
fn read_window<U, R>(
|
||||
&self,
|
||||
window: &WindowHandle<U>,
|
||||
read: impl FnOnce(View<U>, &AppContext) -> R,
|
||||
read: impl FnOnce(Entity<U>, &App) -> R,
|
||||
) -> Result<R>
|
||||
where
|
||||
U: 'static,
|
||||
@@ -280,14 +733,14 @@ impl<'a, T> Context for ModelContext<'a, T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Borrow<AppContext> for ModelContext<'_, T> {
|
||||
fn borrow(&self) -> &AppContext {
|
||||
impl<T> Borrow<App> for Context<'_, T> {
|
||||
fn borrow(&self) -> &App {
|
||||
self.app
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> BorrowMut<AppContext> for ModelContext<'_, T> {
|
||||
fn borrow_mut(&mut self) -> &mut AppContext {
|
||||
impl<T> BorrowMut<App> for Context<'_, T> {
|
||||
fn borrow_mut(&mut self) -> &mut App {
|
||||
self.app
|
||||
}
|
||||
}
|
||||
|
||||
+119
-146
@@ -1,11 +1,11 @@
|
||||
use crate::{
|
||||
Action, AnyView, AnyWindowHandle, AppCell, AppContext, AsyncAppContext, AvailableSpace,
|
||||
BackgroundExecutor, BorrowAppContext, Bounds, ClipboardItem, Context, DrawPhase, Drawable,
|
||||
Element, Empty, Entity, EventEmitter, ForegroundExecutor, Global, InputEvent, Keystroke, Model,
|
||||
ModelContext, Modifiers, ModifiersChangedEvent, MouseButton, MouseDownEvent, MouseMoveEvent,
|
||||
MouseUpEvent, Pixels, Platform, Point, Render, Result, Size, Task, TestDispatcher,
|
||||
TestPlatform, TestScreenCaptureSource, TestWindow, TextSystem, View, ViewContext,
|
||||
VisualContext, WindowBounds, WindowContext, WindowHandle, WindowOptions,
|
||||
Action, AnyView, AnyWindowHandle, App, AppCell, AppContext, AsyncAppContext, AvailableSpace,
|
||||
BackgroundExecutor, BorrowAppContext, Bounds, ClipboardItem, DrawPhase, Drawable, Element,
|
||||
Empty, EventEmitter, ForegroundExecutor, Global, InputEvent, Keystroke, Modifiers,
|
||||
ModifiersChangedEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels,
|
||||
Platform, Point, Render, Result, Size, Task, TestDispatcher, TestPlatform,
|
||||
TestScreenCaptureSource, TestWindow, TextSystem, VisualContext, Window, WindowBounds,
|
||||
WindowHandle, WindowOptions,
|
||||
};
|
||||
use anyhow::{anyhow, bail};
|
||||
use futures::{channel::oneshot, Stream, StreamExt};
|
||||
@@ -29,15 +29,15 @@ pub struct TestAppContext {
|
||||
on_quit: Rc<RefCell<Vec<Box<dyn FnOnce() + 'static>>>>,
|
||||
}
|
||||
|
||||
impl Context for TestAppContext {
|
||||
impl AppContext for TestAppContext {
|
||||
type Result<T> = T;
|
||||
|
||||
fn new_model<T: 'static>(
|
||||
fn new<T: 'static>(
|
||||
&mut self,
|
||||
build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
|
||||
) -> Self::Result<Model<T>> {
|
||||
build_model: impl FnOnce(&mut Context<'_, T>) -> T,
|
||||
) -> Self::Result<Entity<T>> {
|
||||
let mut app = self.app.borrow_mut();
|
||||
app.new_model(build_model)
|
||||
app.new(build_model)
|
||||
}
|
||||
|
||||
fn reserve_model<T: 'static>(&mut self) -> Self::Result<crate::Reservation<T>> {
|
||||
@@ -48,16 +48,16 @@ impl Context for TestAppContext {
|
||||
fn insert_model<T: 'static>(
|
||||
&mut self,
|
||||
reservation: crate::Reservation<T>,
|
||||
build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
|
||||
) -> Self::Result<Model<T>> {
|
||||
build_model: impl FnOnce(&mut Context<'_, T>) -> T,
|
||||
) -> Self::Result<Entity<T>> {
|
||||
let mut app = self.app.borrow_mut();
|
||||
app.insert_model(reservation, build_model)
|
||||
}
|
||||
|
||||
fn update_model<T: 'static, R>(
|
||||
&mut self,
|
||||
handle: &Model<T>,
|
||||
update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
|
||||
handle: &Entity<T>,
|
||||
update: impl FnOnce(&mut T, &mut Context<'_, T>) -> R,
|
||||
) -> Self::Result<R> {
|
||||
let mut app = self.app.borrow_mut();
|
||||
app.update_model(handle, update)
|
||||
@@ -65,8 +65,8 @@ impl Context for TestAppContext {
|
||||
|
||||
fn read_model<T, R>(
|
||||
&self,
|
||||
handle: &Model<T>,
|
||||
read: impl FnOnce(&T, &AppContext) -> R,
|
||||
handle: &Entity<T>,
|
||||
read: impl FnOnce(&T, &App) -> R,
|
||||
) -> Self::Result<R>
|
||||
where
|
||||
T: 'static,
|
||||
@@ -77,7 +77,7 @@ impl Context for TestAppContext {
|
||||
|
||||
fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
|
||||
where
|
||||
F: FnOnce(AnyView, &mut WindowContext) -> T,
|
||||
F: FnOnce(AnyView, &mut Window, &mut App) -> T,
|
||||
{
|
||||
let mut lock = self.app.borrow_mut();
|
||||
lock.update_window(window, f)
|
||||
@@ -86,7 +86,7 @@ impl Context for TestAppContext {
|
||||
fn read_window<T, R>(
|
||||
&self,
|
||||
window: &WindowHandle<T>,
|
||||
read: impl FnOnce(View<T>, &AppContext) -> R,
|
||||
read: impl FnOnce(Entity<T>, &App) -> R,
|
||||
) -> Result<R>
|
||||
where
|
||||
T: 'static,
|
||||
@@ -108,7 +108,7 @@ impl TestAppContext {
|
||||
let text_system = Arc::new(TextSystem::new(platform.text_system()));
|
||||
|
||||
Self {
|
||||
app: AppContext::new(platform.clone(), asset_source, http_client),
|
||||
app: App::new_app(platform.clone(), asset_source, http_client),
|
||||
background_executor,
|
||||
foreground_executor,
|
||||
dispatcher: dispatcher.clone(),
|
||||
@@ -149,7 +149,7 @@ impl TestAppContext {
|
||||
/// Schedules all windows to be redrawn on the next effect cycle.
|
||||
pub fn refresh(&mut self) -> Result<()> {
|
||||
let mut app = self.app.borrow_mut();
|
||||
app.refresh();
|
||||
app.refresh_windows();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -164,13 +164,13 @@ impl TestAppContext {
|
||||
}
|
||||
|
||||
/// Gives you an `&mut AppContext` for the duration of the closure
|
||||
pub fn update<R>(&self, f: impl FnOnce(&mut AppContext) -> R) -> R {
|
||||
pub fn update<R>(&self, f: impl FnOnce(&mut App) -> R) -> R {
|
||||
let mut cx = self.app.borrow_mut();
|
||||
cx.update(f)
|
||||
}
|
||||
|
||||
/// Gives you an `&AppContext` for the duration of the closure
|
||||
pub fn read<R>(&self, f: impl FnOnce(&AppContext) -> R) -> R {
|
||||
pub fn read<R>(&self, f: impl FnOnce(&App) -> R) -> R {
|
||||
let cx = self.app.borrow();
|
||||
f(&cx)
|
||||
}
|
||||
@@ -179,7 +179,7 @@ impl TestAppContext {
|
||||
/// can be retrieved with `self.test_window(handle)`
|
||||
pub fn add_window<F, V>(&mut self, build_window: F) -> WindowHandle<V>
|
||||
where
|
||||
F: FnOnce(&mut ViewContext<V>) -> V,
|
||||
F: FnOnce(&mut Window, &mut Context<V>) -> V,
|
||||
V: 'static + Render,
|
||||
{
|
||||
let mut cx = self.app.borrow_mut();
|
||||
@@ -191,7 +191,7 @@ impl TestAppContext {
|
||||
window_bounds: Some(WindowBounds::Windowed(bounds)),
|
||||
..Default::default()
|
||||
},
|
||||
|cx| cx.new_view(build_window),
|
||||
|window, cx| cx.new(|cx| build_window(window, cx)),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
@@ -206,7 +206,7 @@ impl TestAppContext {
|
||||
window_bounds: Some(WindowBounds::Windowed(bounds)),
|
||||
..Default::default()
|
||||
},
|
||||
|cx| cx.new_view(|_| Empty),
|
||||
|_, cx| cx.new(|_| Empty),
|
||||
)
|
||||
.unwrap();
|
||||
drop(cx);
|
||||
@@ -218,9 +218,12 @@ impl TestAppContext {
|
||||
/// Adds a new window, and returns its root view and a `VisualTestContext` which can be used
|
||||
/// as a `WindowContext` for the rest of the test. Typically you would shadow this context with
|
||||
/// the returned one. `let (view, cx) = cx.add_window_view(...);`
|
||||
pub fn add_window_view<F, V>(&mut self, build_root_view: F) -> (View<V>, &mut VisualTestContext)
|
||||
pub fn add_window_view<F, V>(
|
||||
&mut self,
|
||||
build_root_view: F,
|
||||
) -> (Entity<V>, &mut VisualTestContext)
|
||||
where
|
||||
F: FnOnce(&mut ViewContext<V>) -> V,
|
||||
F: FnOnce(&mut Window, &mut Context<V>) -> V,
|
||||
V: 'static + Render,
|
||||
{
|
||||
let mut cx = self.app.borrow_mut();
|
||||
@@ -231,11 +234,11 @@ impl TestAppContext {
|
||||
window_bounds: Some(WindowBounds::Windowed(bounds)),
|
||||
..Default::default()
|
||||
},
|
||||
|cx| cx.new_view(build_root_view),
|
||||
|window, cx| cx.new(|cx| build_root_view(window, cx)),
|
||||
)
|
||||
.unwrap();
|
||||
drop(cx);
|
||||
let view = window.root_view(self).unwrap();
|
||||
let view = window.root_model(self).unwrap();
|
||||
let cx = VisualTestContext::from_window(*window.deref(), self).as_mut();
|
||||
cx.run_until_parked();
|
||||
|
||||
@@ -315,16 +318,13 @@ impl TestAppContext {
|
||||
|
||||
/// runs the given closure with a reference to the global
|
||||
/// panics if `has_global` would return false.
|
||||
pub fn read_global<G: Global, R>(&self, read: impl FnOnce(&G, &AppContext) -> R) -> R {
|
||||
pub fn read_global<G: Global, R>(&self, read: impl FnOnce(&G, &App) -> R) -> R {
|
||||
let app = self.app.borrow();
|
||||
read(app.global(), &app)
|
||||
}
|
||||
|
||||
/// runs the given closure with a reference to the global (if set)
|
||||
pub fn try_read_global<G: Global, R>(
|
||||
&self,
|
||||
read: impl FnOnce(&G, &AppContext) -> R,
|
||||
) -> Option<R> {
|
||||
pub fn try_read_global<G: Global, R>(&self, read: impl FnOnce(&G, &App) -> R) -> Option<R> {
|
||||
let lock = self.app.borrow();
|
||||
Some(read(lock.try_global()?, &lock))
|
||||
}
|
||||
@@ -336,10 +336,7 @@ impl TestAppContext {
|
||||
}
|
||||
|
||||
/// updates the global in this context. (panics if `has_global` would return false)
|
||||
pub fn update_global<G: Global, R>(
|
||||
&mut self,
|
||||
update: impl FnOnce(&mut G, &mut AppContext) -> R,
|
||||
) -> R {
|
||||
pub fn update_global<G: Global, R>(&mut self, update: impl FnOnce(&mut G, &mut App) -> R) -> R {
|
||||
let mut lock = self.app.borrow_mut();
|
||||
lock.update(|cx| cx.update_global(update))
|
||||
}
|
||||
@@ -365,7 +362,9 @@ impl TestAppContext {
|
||||
A: Action,
|
||||
{
|
||||
window
|
||||
.update(self, |_, cx| cx.dispatch_action(action.boxed_clone()))
|
||||
.update(self, |_, window, cx| {
|
||||
window.dispatch_action(action.boxed_clone(), cx)
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
self.background_executor.run_until_parked()
|
||||
@@ -401,8 +400,10 @@ impl TestAppContext {
|
||||
|
||||
/// dispatches a single Keystroke (see also `simulate_keystrokes` and `simulate_input`)
|
||||
pub fn dispatch_keystroke(&mut self, window: AnyWindowHandle, keystroke: Keystroke) {
|
||||
self.update_window(window, |_, cx| cx.dispatch_keystroke(keystroke))
|
||||
.unwrap();
|
||||
self.update_window(window, |_, window, cx| {
|
||||
window.dispatch_keystroke(keystroke, cx)
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// Returns the `TestWindow` backing the given handle.
|
||||
@@ -421,7 +422,7 @@ impl TestAppContext {
|
||||
}
|
||||
|
||||
/// Returns a stream of notifications whenever the View or Model is updated.
|
||||
pub fn notifications<T: 'static>(&mut self, entity: &impl Entity<T>) -> impl Stream<Item = ()> {
|
||||
pub fn notifications<T: 'static>(&mut self, entity: &Entity<T>) -> impl Stream<Item = ()> {
|
||||
let (tx, rx) = futures::channel::mpsc::unbounded();
|
||||
self.update(|cx| {
|
||||
cx.observe(entity, {
|
||||
@@ -440,14 +441,14 @@ impl TestAppContext {
|
||||
/// Returns a stream of events emitted by the given Model.
|
||||
pub fn events<Evt, T: 'static + EventEmitter<Evt>>(
|
||||
&mut self,
|
||||
entity: &Model<T>,
|
||||
entity: &Entity<T>,
|
||||
) -> futures::channel::mpsc::UnboundedReceiver<Evt>
|
||||
where
|
||||
Evt: 'static + Clone,
|
||||
{
|
||||
let (tx, rx) = futures::channel::mpsc::unbounded();
|
||||
entity
|
||||
.update(self, |_, cx: &mut ModelContext<T>| {
|
||||
.update(self, |_, cx: &mut Context<T>| {
|
||||
cx.subscribe(entity, move |_model, _handle, event, _cx| {
|
||||
let _ = tx.unbounded_send(event.clone());
|
||||
})
|
||||
@@ -460,8 +461,8 @@ impl TestAppContext {
|
||||
/// don't need to jump in at a specific time).
|
||||
pub async fn condition<T: 'static>(
|
||||
&mut self,
|
||||
model: &Model<T>,
|
||||
mut predicate: impl FnMut(&mut T, &mut ModelContext<T>) -> bool,
|
||||
model: &Entity<T>,
|
||||
mut predicate: impl FnMut(&mut T, &mut Context<T>) -> bool,
|
||||
) {
|
||||
let timer = self.executor().timer(Duration::from_secs(3));
|
||||
let mut notifications = self.notifications(model);
|
||||
@@ -492,7 +493,7 @@ impl TestAppContext {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: 'static> Model<T> {
|
||||
impl<T: 'static> Entity<T> {
|
||||
/// Block until the next event is emitted by the model, then return it.
|
||||
pub fn next_event<Event>(&self, cx: &mut TestAppContext) -> impl Future<Output = Event>
|
||||
where
|
||||
@@ -515,34 +516,9 @@ impl<T: 'static> Model<T> {
|
||||
event
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a future that resolves when the model notifies.
|
||||
pub fn next_notification(&self, cx: &TestAppContext) -> impl Future<Output = ()> {
|
||||
use postage::prelude::{Sink as _, Stream as _};
|
||||
|
||||
let (mut tx, mut rx) = postage::mpsc::channel(1);
|
||||
let mut cx = cx.app.app.borrow_mut();
|
||||
let subscription = cx.observe(self, move |_, _| {
|
||||
tx.try_send(()).ok();
|
||||
});
|
||||
|
||||
let duration = if std::env::var("CI").is_ok() {
|
||||
Duration::from_secs(5)
|
||||
} else {
|
||||
Duration::from_secs(1)
|
||||
};
|
||||
|
||||
async move {
|
||||
let notification = crate::util::timeout(duration, rx.recv())
|
||||
.await
|
||||
.expect("next notification timed out");
|
||||
drop(subscription);
|
||||
notification.expect("model dropped while test was waiting for its next notification")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<V: 'static> View<V> {
|
||||
impl<V: 'static> Entity<V> {
|
||||
/// Returns a future that resolves when the view is next updated.
|
||||
pub fn next_notification(
|
||||
&self,
|
||||
@@ -552,7 +528,7 @@ impl<V: 'static> View<V> {
|
||||
use postage::prelude::{Sink as _, Stream as _};
|
||||
|
||||
let (mut tx, mut rx) = postage::mpsc::channel(1);
|
||||
let subscription = cx.app.app.borrow_mut().observe(self, move |_, _| {
|
||||
let subscription = cx.app.borrow_mut().observe(self, move |_, _| {
|
||||
tx.try_send(()).ok();
|
||||
});
|
||||
|
||||
@@ -574,12 +550,12 @@ impl<V: 'static> View<V> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<V> View<V> {
|
||||
impl<V> Entity<V> {
|
||||
/// Returns a future that resolves when the condition becomes true.
|
||||
pub fn condition<Evt>(
|
||||
&self,
|
||||
cx: &TestAppContext,
|
||||
mut predicate: impl FnMut(&V, &AppContext) -> bool,
|
||||
mut predicate: impl FnMut(&V, &App) -> bool,
|
||||
) -> impl Future<Output = ()>
|
||||
where
|
||||
Evt: 'static,
|
||||
@@ -645,6 +621,8 @@ impl<V> View<V> {
|
||||
}
|
||||
|
||||
use derive_more::{Deref, DerefMut};
|
||||
|
||||
use super::{Context, Entity};
|
||||
#[derive(Deref, DerefMut, Clone)]
|
||||
/// A VisualTestContext is the test-equivalent of a `WindowContext`. It allows you to
|
||||
/// run window-specific test code.
|
||||
@@ -657,14 +635,11 @@ pub struct VisualTestContext {
|
||||
}
|
||||
|
||||
impl VisualTestContext {
|
||||
/// Get the underlying window handle underlying this context.
|
||||
pub fn handle(&self) -> AnyWindowHandle {
|
||||
self.window
|
||||
}
|
||||
|
||||
/// Provides the `WindowContext` for the duration of the closure.
|
||||
pub fn update<R>(&mut self, f: impl FnOnce(&mut WindowContext) -> R) -> R {
|
||||
self.cx.update_window(self.window, |_, cx| f(cx)).unwrap()
|
||||
pub fn update<R>(&mut self, f: impl FnOnce(&mut Window, &mut App) -> R) -> R {
|
||||
self.cx
|
||||
.update_window(self.window, |_, window, cx| f(window, cx))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// Creates a new VisualTestContext. You would typically shadow the passed in
|
||||
@@ -781,7 +756,7 @@ impl VisualTestContext {
|
||||
|
||||
/// debug_bounds returns the bounds of the element with the given selector.
|
||||
pub fn debug_bounds(&mut self, selector: &'static str) -> Option<Bounds<Pixels>> {
|
||||
self.update(|cx| cx.window.rendered_frame.debug_bounds.get(selector).copied())
|
||||
self.update(|window, _| window.rendered_frame.debug_bounds.get(selector).copied())
|
||||
}
|
||||
|
||||
/// Draw an element to the window. Useful for simulating events or actions
|
||||
@@ -789,22 +764,22 @@ impl VisualTestContext {
|
||||
&mut self,
|
||||
origin: Point<Pixels>,
|
||||
space: impl Into<Size<AvailableSpace>>,
|
||||
f: impl FnOnce(&mut WindowContext) -> E,
|
||||
f: impl FnOnce(&mut Window, &mut App) -> E,
|
||||
) -> (E::RequestLayoutState, E::PrepaintState)
|
||||
where
|
||||
E: Element,
|
||||
{
|
||||
self.update(|cx| {
|
||||
cx.window.draw_phase = DrawPhase::Prepaint;
|
||||
let mut element = Drawable::new(f(cx));
|
||||
element.layout_as_root(space.into(), cx);
|
||||
cx.with_absolute_element_offset(origin, |cx| element.prepaint(cx));
|
||||
self.update(|window, cx| {
|
||||
window.invalidator.set_phase(DrawPhase::Prepaint);
|
||||
let mut element = Drawable::new(f(window, cx));
|
||||
element.layout_as_root(space.into(), window, cx);
|
||||
window.with_absolute_element_offset(origin, |window| element.prepaint(window, cx));
|
||||
|
||||
cx.window.draw_phase = DrawPhase::Paint;
|
||||
let (request_layout_state, prepaint_state) = element.paint(cx);
|
||||
window.invalidator.set_phase(DrawPhase::Paint);
|
||||
let (request_layout_state, prepaint_state) = element.paint(window, cx);
|
||||
|
||||
cx.window.draw_phase = DrawPhase::None;
|
||||
cx.refresh();
|
||||
window.invalidator.set_phase(DrawPhase::None);
|
||||
window.refresh();
|
||||
|
||||
(request_layout_state, prepaint_state)
|
||||
})
|
||||
@@ -831,8 +806,8 @@ impl VisualTestContext {
|
||||
pub fn simulate_close(&mut self) -> bool {
|
||||
let handler = self
|
||||
.cx
|
||||
.update_window(self.window, |_, cx| {
|
||||
cx.window
|
||||
.update_window(self.window, |_, window, _| {
|
||||
window
|
||||
.platform_window
|
||||
.as_test()
|
||||
.unwrap()
|
||||
@@ -845,8 +820,8 @@ impl VisualTestContext {
|
||||
if let Some(mut handler) = handler {
|
||||
let should_close = handler();
|
||||
self.cx
|
||||
.update_window(self.window, |_, cx| {
|
||||
cx.window.platform_window.on_should_close(handler);
|
||||
.update_window(self.window, |_, window, _| {
|
||||
window.platform_window.on_should_close(handler);
|
||||
})
|
||||
.unwrap();
|
||||
should_close
|
||||
@@ -870,14 +845,14 @@ impl VisualTestContext {
|
||||
}
|
||||
}
|
||||
|
||||
impl Context for VisualTestContext {
|
||||
type Result<T> = <TestAppContext as Context>::Result<T>;
|
||||
impl AppContext for VisualTestContext {
|
||||
type Result<T> = <TestAppContext as AppContext>::Result<T>;
|
||||
|
||||
fn new_model<T: 'static>(
|
||||
fn new<T: 'static>(
|
||||
&mut self,
|
||||
build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
|
||||
) -> Self::Result<Model<T>> {
|
||||
self.cx.new_model(build_model)
|
||||
build_model: impl FnOnce(&mut Context<'_, T>) -> T,
|
||||
) -> Self::Result<Entity<T>> {
|
||||
self.cx.new(build_model)
|
||||
}
|
||||
|
||||
fn reserve_model<T: 'static>(&mut self) -> Self::Result<crate::Reservation<T>> {
|
||||
@@ -887,15 +862,15 @@ impl Context for VisualTestContext {
|
||||
fn insert_model<T: 'static>(
|
||||
&mut self,
|
||||
reservation: crate::Reservation<T>,
|
||||
build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
|
||||
) -> Self::Result<Model<T>> {
|
||||
build_model: impl FnOnce(&mut Context<'_, T>) -> T,
|
||||
) -> Self::Result<Entity<T>> {
|
||||
self.cx.insert_model(reservation, build_model)
|
||||
}
|
||||
|
||||
fn update_model<T, R>(
|
||||
&mut self,
|
||||
handle: &Model<T>,
|
||||
update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
|
||||
handle: &Entity<T>,
|
||||
update: impl FnOnce(&mut T, &mut Context<'_, T>) -> R,
|
||||
) -> Self::Result<R>
|
||||
where
|
||||
T: 'static,
|
||||
@@ -905,8 +880,8 @@ impl Context for VisualTestContext {
|
||||
|
||||
fn read_model<T, R>(
|
||||
&self,
|
||||
handle: &Model<T>,
|
||||
read: impl FnOnce(&T, &AppContext) -> R,
|
||||
handle: &Entity<T>,
|
||||
read: impl FnOnce(&T, &App) -> R,
|
||||
) -> Self::Result<R>
|
||||
where
|
||||
T: 'static,
|
||||
@@ -916,7 +891,7 @@ impl Context for VisualTestContext {
|
||||
|
||||
fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
|
||||
where
|
||||
F: FnOnce(AnyView, &mut WindowContext) -> T,
|
||||
F: FnOnce(AnyView, &mut Window, &mut App) -> T,
|
||||
{
|
||||
self.cx.update_window(window, f)
|
||||
}
|
||||
@@ -924,7 +899,7 @@ impl Context for VisualTestContext {
|
||||
fn read_window<T, R>(
|
||||
&self,
|
||||
window: &WindowHandle<T>,
|
||||
read: impl FnOnce(View<T>, &AppContext) -> R,
|
||||
read: impl FnOnce(Entity<T>, &App) -> R,
|
||||
) -> Result<R>
|
||||
where
|
||||
T: 'static,
|
||||
@@ -934,55 +909,52 @@ impl Context for VisualTestContext {
|
||||
}
|
||||
|
||||
impl VisualContext for VisualTestContext {
|
||||
fn new_view<V>(
|
||||
&mut self,
|
||||
build_view: impl FnOnce(&mut ViewContext<V>) -> V,
|
||||
) -> Self::Result<View<V>>
|
||||
where
|
||||
V: 'static + Render,
|
||||
{
|
||||
/// Get the underlying window handle underlying this context.
|
||||
fn window_handle(&self) -> AnyWindowHandle {
|
||||
self.window
|
||||
.update(&mut self.cx, |_, cx| cx.new_view(build_view))
|
||||
}
|
||||
|
||||
fn new_window_model<T: 'static>(
|
||||
&mut self,
|
||||
build_model: impl FnOnce(&mut Window, &mut Context<'_, T>) -> T,
|
||||
) -> Self::Result<Entity<T>> {
|
||||
self.window
|
||||
.update(&mut self.cx, |_, window, cx| {
|
||||
cx.new(|cx| build_model(window, cx))
|
||||
})
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn update_view<V: 'static, R>(
|
||||
fn update_window_model<V: 'static, R>(
|
||||
&mut self,
|
||||
view: &View<V>,
|
||||
update: impl FnOnce(&mut V, &mut ViewContext<V>) -> R,
|
||||
view: &Entity<V>,
|
||||
update: impl FnOnce(&mut V, &mut Window, &mut Context<V>) -> R,
|
||||
) -> Self::Result<R> {
|
||||
self.window
|
||||
.update(&mut self.cx, |_, cx| cx.update_view(view, update))
|
||||
.update(&mut self.cx, |_, window, cx| {
|
||||
view.update(cx, |v, cx| update(v, window, cx))
|
||||
})
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn replace_root_view<V>(
|
||||
&mut self,
|
||||
build_view: impl FnOnce(&mut ViewContext<V>) -> V,
|
||||
) -> Self::Result<View<V>>
|
||||
build_view: impl FnOnce(&mut Window, &mut Context<V>) -> V,
|
||||
) -> Self::Result<Entity<V>>
|
||||
where
|
||||
V: 'static + Render,
|
||||
{
|
||||
self.window
|
||||
.update(&mut self.cx, |_, cx| cx.replace_root_view(build_view))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn focus_view<V: crate::FocusableView>(&mut self, view: &View<V>) -> Self::Result<()> {
|
||||
self.window
|
||||
.update(&mut self.cx, |_, cx| {
|
||||
view.read(cx).focus_handle(cx).clone().focus(cx)
|
||||
.update(&mut self.cx, |_, window, cx| {
|
||||
window.replace_root_model(cx, build_view)
|
||||
})
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn dismiss_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
|
||||
where
|
||||
V: crate::ManagedView,
|
||||
{
|
||||
fn focus<V: crate::Focusable>(&mut self, view: &Entity<V>) -> Self::Result<()> {
|
||||
self.window
|
||||
.update(&mut self.cx, |_, cx| {
|
||||
view.update(cx, |_, cx| cx.emit(crate::DismissEvent))
|
||||
.update(&mut self.cx, |_, window, cx| {
|
||||
view.read(cx).focus_handle(cx).clone().focus(window)
|
||||
})
|
||||
.unwrap()
|
||||
}
|
||||
@@ -990,11 +962,12 @@ impl VisualContext for VisualTestContext {
|
||||
|
||||
impl AnyWindowHandle {
|
||||
/// Creates the given view in this window.
|
||||
pub fn build_view<V: Render + 'static>(
|
||||
pub fn build_model<V: Render + 'static>(
|
||||
&self,
|
||||
cx: &mut TestAppContext,
|
||||
build_view: impl FnOnce(&mut ViewContext<V>) -> V,
|
||||
) -> View<V> {
|
||||
self.update(cx, |_, cx| cx.new_view(build_view)).unwrap()
|
||||
build_view: impl FnOnce(&mut Window, &mut Context<V>) -> V,
|
||||
) -> Entity<V> {
|
||||
self.update(cx, |_, window, cx| cx.new(|cx| build_view(window, cx)))
|
||||
.unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::{AppContext, SharedString, SharedUri};
|
||||
use crate::{App, SharedString, SharedUri};
|
||||
use futures::Future;
|
||||
|
||||
use std::fmt::Debug;
|
||||
@@ -47,7 +47,7 @@ pub trait Asset: 'static {
|
||||
/// Load the asset asynchronously
|
||||
fn load(
|
||||
source: Self::Source,
|
||||
cx: &mut AppContext,
|
||||
cx: &mut App,
|
||||
) -> impl Future<Output = Self::Output> + Send + 'static;
|
||||
}
|
||||
|
||||
@@ -66,7 +66,7 @@ impl<R: Clone + Send, E: Clone + Send + std::error::Error, T: Asset<Output = Res
|
||||
|
||||
fn load(
|
||||
source: Self::Source,
|
||||
cx: &mut AppContext,
|
||||
cx: &mut App,
|
||||
) -> impl Future<Output = Self::Output> + Send + 'static {
|
||||
let load = T::load(source, cx);
|
||||
async {
|
||||
|
||||
+101
-77
@@ -32,8 +32,8 @@
|
||||
//! your own custom layout algorithm or rendering a code editor.
|
||||
|
||||
use crate::{
|
||||
util::FluentBuilder, ArenaBox, AvailableSpace, Bounds, DispatchNodeId, ElementId, FocusHandle,
|
||||
LayoutId, Pixels, Point, Size, Style, ViewContext, WindowContext, ELEMENT_ARENA,
|
||||
util::FluentBuilder, App, ArenaBox, AvailableSpace, Bounds, Context, DispatchNodeId, ElementId,
|
||||
FocusHandle, LayoutId, Pixels, Point, Size, Style, Window, ELEMENT_ARENA,
|
||||
};
|
||||
use derive_more::{Deref, DerefMut};
|
||||
pub(crate) use smallvec::SmallVec;
|
||||
@@ -64,7 +64,8 @@ pub trait Element: 'static + IntoElement {
|
||||
fn request_layout(
|
||||
&mut self,
|
||||
id: Option<&GlobalElementId>,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> (LayoutId, Self::RequestLayoutState);
|
||||
|
||||
/// After laying out an element, we need to commit its bounds to the current frame for hitbox
|
||||
@@ -74,7 +75,8 @@ pub trait Element: 'static + IntoElement {
|
||||
id: Option<&GlobalElementId>,
|
||||
bounds: Bounds<Pixels>,
|
||||
request_layout: &mut Self::RequestLayoutState,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> Self::PrepaintState;
|
||||
|
||||
/// Once layout has been completed, this method will be called to paint the element to the screen.
|
||||
@@ -85,7 +87,8 @@ pub trait Element: 'static + IntoElement {
|
||||
bounds: Bounds<Pixels>,
|
||||
request_layout: &mut Self::RequestLayoutState,
|
||||
prepaint: &mut Self::PrepaintState,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
);
|
||||
|
||||
/// Convert this element into a dynamically-typed [`AnyElement`].
|
||||
@@ -115,11 +118,11 @@ impl<T: IntoElement> FluentBuilder for T {}
|
||||
/// models. Views are drawn to the screen and care about the current window's state, models are not and do not.
|
||||
pub trait Render: 'static + Sized {
|
||||
/// Render this view into an element tree.
|
||||
fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement;
|
||||
fn render(&mut self, window: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement;
|
||||
}
|
||||
|
||||
impl Render for Empty {
|
||||
fn render(&mut self, _cx: &mut ViewContext<Self>) -> impl IntoElement {
|
||||
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
|
||||
Empty
|
||||
}
|
||||
}
|
||||
@@ -133,7 +136,7 @@ pub trait RenderOnce: 'static {
|
||||
/// Render this component into an element tree. Note that this method
|
||||
/// takes ownership of self, as compared to [`Render::render()`] method
|
||||
/// which takes a mutable reference.
|
||||
fn render(self, cx: &mut WindowContext) -> impl IntoElement;
|
||||
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement;
|
||||
}
|
||||
|
||||
/// This is a helper trait to provide a uniform interface for constructing elements that
|
||||
@@ -184,10 +187,11 @@ impl<C: RenderOnce> Element for Component<C> {
|
||||
fn request_layout(
|
||||
&mut self,
|
||||
_id: Option<&GlobalElementId>,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> (LayoutId, Self::RequestLayoutState) {
|
||||
let mut element = self.0.take().unwrap().render(cx).into_any_element();
|
||||
let layout_id = element.request_layout(cx);
|
||||
let mut element = self.0.take().unwrap().render(window, cx).into_any_element();
|
||||
let layout_id = element.request_layout(window, cx);
|
||||
(layout_id, element)
|
||||
}
|
||||
|
||||
@@ -196,9 +200,10 @@ impl<C: RenderOnce> Element for Component<C> {
|
||||
_id: Option<&GlobalElementId>,
|
||||
_: Bounds<Pixels>,
|
||||
element: &mut AnyElement,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) {
|
||||
element.prepaint(cx);
|
||||
element.prepaint(window, cx);
|
||||
}
|
||||
|
||||
fn paint(
|
||||
@@ -207,9 +212,10 @@ impl<C: RenderOnce> Element for Component<C> {
|
||||
_: Bounds<Pixels>,
|
||||
element: &mut Self::RequestLayoutState,
|
||||
_: &mut Self::PrepaintState,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) {
|
||||
element.paint(cx);
|
||||
element.paint(window, cx);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -228,16 +234,17 @@ pub struct GlobalElementId(pub(crate) SmallVec<[ElementId; 32]>);
|
||||
trait ElementObject {
|
||||
fn inner_element(&mut self) -> &mut dyn Any;
|
||||
|
||||
fn request_layout(&mut self, cx: &mut WindowContext) -> LayoutId;
|
||||
fn request_layout(&mut self, window: &mut Window, cx: &mut App) -> LayoutId;
|
||||
|
||||
fn prepaint(&mut self, cx: &mut WindowContext);
|
||||
fn prepaint(&mut self, window: &mut Window, cx: &mut App);
|
||||
|
||||
fn paint(&mut self, cx: &mut WindowContext);
|
||||
fn paint(&mut self, window: &mut Window, cx: &mut App);
|
||||
|
||||
fn layout_as_root(
|
||||
&mut self,
|
||||
available_space: Size<AvailableSpace>,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> Size<Pixels>;
|
||||
}
|
||||
|
||||
@@ -282,19 +289,19 @@ impl<E: Element> Drawable<E> {
|
||||
}
|
||||
}
|
||||
|
||||
fn request_layout(&mut self, cx: &mut WindowContext) -> LayoutId {
|
||||
fn request_layout(&mut self, window: &mut Window, cx: &mut App) -> LayoutId {
|
||||
match mem::take(&mut self.phase) {
|
||||
ElementDrawPhase::Start => {
|
||||
let global_id = self.element.id().map(|element_id| {
|
||||
cx.window.element_id_stack.push(element_id);
|
||||
GlobalElementId(cx.window.element_id_stack.clone())
|
||||
window.element_id_stack.push(element_id);
|
||||
GlobalElementId(window.element_id_stack.clone())
|
||||
});
|
||||
|
||||
let (layout_id, request_layout) =
|
||||
self.element.request_layout(global_id.as_ref(), cx);
|
||||
self.element.request_layout(global_id.as_ref(), window, cx);
|
||||
|
||||
if global_id.is_some() {
|
||||
cx.window.element_id_stack.pop();
|
||||
window.element_id_stack.pop();
|
||||
}
|
||||
|
||||
self.phase = ElementDrawPhase::RequestLayout {
|
||||
@@ -308,7 +315,7 @@ impl<E: Element> Drawable<E> {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn prepaint(&mut self, cx: &mut WindowContext) {
|
||||
pub(crate) fn prepaint(&mut self, window: &mut Window, cx: &mut App) {
|
||||
match mem::take(&mut self.phase) {
|
||||
ElementDrawPhase::RequestLayout {
|
||||
layout_id,
|
||||
@@ -322,19 +329,23 @@ impl<E: Element> Drawable<E> {
|
||||
..
|
||||
} => {
|
||||
if let Some(element_id) = self.element.id() {
|
||||
cx.window.element_id_stack.push(element_id);
|
||||
debug_assert_eq!(global_id.as_ref().unwrap().0, cx.window.element_id_stack);
|
||||
window.element_id_stack.push(element_id);
|
||||
debug_assert_eq!(global_id.as_ref().unwrap().0, window.element_id_stack);
|
||||
}
|
||||
|
||||
let bounds = cx.layout_bounds(layout_id);
|
||||
let node_id = cx.window.next_frame.dispatch_tree.push_node();
|
||||
let prepaint =
|
||||
self.element
|
||||
.prepaint(global_id.as_ref(), bounds, &mut request_layout, cx);
|
||||
cx.window.next_frame.dispatch_tree.pop_node();
|
||||
let bounds = window.layout_bounds(layout_id);
|
||||
let node_id = window.next_frame.dispatch_tree.push_node();
|
||||
let prepaint = self.element.prepaint(
|
||||
global_id.as_ref(),
|
||||
bounds,
|
||||
&mut request_layout,
|
||||
window,
|
||||
cx,
|
||||
);
|
||||
window.next_frame.dispatch_tree.pop_node();
|
||||
|
||||
if global_id.is_some() {
|
||||
cx.window.element_id_stack.pop();
|
||||
window.element_id_stack.pop();
|
||||
}
|
||||
|
||||
self.phase = ElementDrawPhase::Prepaint {
|
||||
@@ -351,7 +362,8 @@ impl<E: Element> Drawable<E> {
|
||||
|
||||
pub(crate) fn paint(
|
||||
&mut self,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> (E::RequestLayoutState, E::PrepaintState) {
|
||||
match mem::take(&mut self.phase) {
|
||||
ElementDrawPhase::Prepaint {
|
||||
@@ -363,21 +375,22 @@ impl<E: Element> Drawable<E> {
|
||||
..
|
||||
} => {
|
||||
if let Some(element_id) = self.element.id() {
|
||||
cx.window.element_id_stack.push(element_id);
|
||||
debug_assert_eq!(global_id.as_ref().unwrap().0, cx.window.element_id_stack);
|
||||
window.element_id_stack.push(element_id);
|
||||
debug_assert_eq!(global_id.as_ref().unwrap().0, window.element_id_stack);
|
||||
}
|
||||
|
||||
cx.window.next_frame.dispatch_tree.set_active_node(node_id);
|
||||
window.next_frame.dispatch_tree.set_active_node(node_id);
|
||||
self.element.paint(
|
||||
global_id.as_ref(),
|
||||
bounds,
|
||||
&mut request_layout,
|
||||
&mut prepaint,
|
||||
window,
|
||||
cx,
|
||||
);
|
||||
|
||||
if global_id.is_some() {
|
||||
cx.window.element_id_stack.pop();
|
||||
window.element_id_stack.pop();
|
||||
}
|
||||
|
||||
self.phase = ElementDrawPhase::Painted;
|
||||
@@ -390,10 +403,11 @@ impl<E: Element> Drawable<E> {
|
||||
pub(crate) fn layout_as_root(
|
||||
&mut self,
|
||||
available_space: Size<AvailableSpace>,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> Size<Pixels> {
|
||||
if matches!(&self.phase, ElementDrawPhase::Start) {
|
||||
self.request_layout(cx);
|
||||
self.request_layout(window, cx);
|
||||
}
|
||||
|
||||
let layout_id = match mem::take(&mut self.phase) {
|
||||
@@ -402,7 +416,7 @@ impl<E: Element> Drawable<E> {
|
||||
global_id,
|
||||
request_layout,
|
||||
} => {
|
||||
cx.compute_layout(layout_id, available_space);
|
||||
window.compute_layout(layout_id, available_space, cx);
|
||||
self.phase = ElementDrawPhase::LayoutComputed {
|
||||
layout_id,
|
||||
global_id,
|
||||
@@ -418,7 +432,7 @@ impl<E: Element> Drawable<E> {
|
||||
request_layout,
|
||||
} => {
|
||||
if available_space != prev_available_space {
|
||||
cx.compute_layout(layout_id, available_space);
|
||||
window.compute_layout(layout_id, available_space, cx);
|
||||
}
|
||||
self.phase = ElementDrawPhase::LayoutComputed {
|
||||
layout_id,
|
||||
@@ -431,7 +445,7 @@ impl<E: Element> Drawable<E> {
|
||||
_ => panic!("cannot measure after painting"),
|
||||
};
|
||||
|
||||
cx.layout_bounds(layout_id).size
|
||||
window.layout_bounds(layout_id).size
|
||||
}
|
||||
}
|
||||
|
||||
@@ -444,24 +458,25 @@ where
|
||||
&mut self.element
|
||||
}
|
||||
|
||||
fn request_layout(&mut self, cx: &mut WindowContext) -> LayoutId {
|
||||
Drawable::request_layout(self, cx)
|
||||
fn request_layout(&mut self, window: &mut Window, cx: &mut App) -> LayoutId {
|
||||
Drawable::request_layout(self, window, cx)
|
||||
}
|
||||
|
||||
fn prepaint(&mut self, cx: &mut WindowContext) {
|
||||
Drawable::prepaint(self, cx);
|
||||
fn prepaint(&mut self, window: &mut Window, cx: &mut App) {
|
||||
Drawable::prepaint(self, window, cx);
|
||||
}
|
||||
|
||||
fn paint(&mut self, cx: &mut WindowContext) {
|
||||
Drawable::paint(self, cx);
|
||||
fn paint(&mut self, window: &mut Window, cx: &mut App) {
|
||||
Drawable::paint(self, window, cx);
|
||||
}
|
||||
|
||||
fn layout_as_root(
|
||||
&mut self,
|
||||
available_space: Size<AvailableSpace>,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> Size<Pixels> {
|
||||
Drawable::layout_as_root(self, available_space, cx)
|
||||
Drawable::layout_as_root(self, available_space, window, cx)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -487,19 +502,19 @@ impl AnyElement {
|
||||
|
||||
/// Request the layout ID of the element stored in this `AnyElement`.
|
||||
/// Used for laying out child elements in a parent element.
|
||||
pub fn request_layout(&mut self, cx: &mut WindowContext) -> LayoutId {
|
||||
self.0.request_layout(cx)
|
||||
pub fn request_layout(&mut self, window: &mut Window, cx: &mut App) -> LayoutId {
|
||||
self.0.request_layout(window, cx)
|
||||
}
|
||||
|
||||
/// Prepares the element to be painted by storing its bounds, giving it a chance to draw hitboxes and
|
||||
/// request autoscroll before the final paint pass is confirmed.
|
||||
pub fn prepaint(&mut self, cx: &mut WindowContext) -> Option<FocusHandle> {
|
||||
let focus_assigned = cx.window.next_frame.focus.is_some();
|
||||
pub fn prepaint(&mut self, window: &mut Window, cx: &mut App) -> Option<FocusHandle> {
|
||||
let focus_assigned = window.next_frame.focus.is_some();
|
||||
|
||||
self.0.prepaint(cx);
|
||||
self.0.prepaint(window, cx);
|
||||
|
||||
if !focus_assigned {
|
||||
if let Some(focus_id) = cx.window.next_frame.focus {
|
||||
if let Some(focus_id) = window.next_frame.focus {
|
||||
return FocusHandle::for_id(focus_id, &cx.focus_handles);
|
||||
}
|
||||
}
|
||||
@@ -508,17 +523,18 @@ impl AnyElement {
|
||||
}
|
||||
|
||||
/// Paints the element stored in this `AnyElement`.
|
||||
pub fn paint(&mut self, cx: &mut WindowContext) {
|
||||
self.0.paint(cx);
|
||||
pub fn paint(&mut self, window: &mut Window, cx: &mut App) {
|
||||
self.0.paint(window, cx);
|
||||
}
|
||||
|
||||
/// Performs layout for this element within the given available space and returns its size.
|
||||
pub fn layout_as_root(
|
||||
&mut self,
|
||||
available_space: Size<AvailableSpace>,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> Size<Pixels> {
|
||||
self.0.layout_as_root(available_space, cx)
|
||||
self.0.layout_as_root(available_space, window, cx)
|
||||
}
|
||||
|
||||
/// Prepaints this element at the given absolute origin.
|
||||
@@ -526,9 +542,10 @@ impl AnyElement {
|
||||
pub fn prepaint_at(
|
||||
&mut self,
|
||||
origin: Point<Pixels>,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> Option<FocusHandle> {
|
||||
cx.with_absolute_element_offset(origin, |cx| self.prepaint(cx))
|
||||
window.with_absolute_element_offset(origin, |window| self.prepaint(window, cx))
|
||||
}
|
||||
|
||||
/// Performs layout on this element in the available space, then prepaints it at the given absolute origin.
|
||||
@@ -537,10 +554,11 @@ impl AnyElement {
|
||||
&mut self,
|
||||
origin: Point<Pixels>,
|
||||
available_space: Size<AvailableSpace>,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> Option<FocusHandle> {
|
||||
self.layout_as_root(available_space, cx);
|
||||
cx.with_absolute_element_offset(origin, |cx| self.prepaint(cx))
|
||||
self.layout_as_root(available_space, window, cx);
|
||||
window.with_absolute_element_offset(origin, |window| self.prepaint(window, cx))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -555,9 +573,10 @@ impl Element for AnyElement {
|
||||
fn request_layout(
|
||||
&mut self,
|
||||
_: Option<&GlobalElementId>,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> (LayoutId, Self::RequestLayoutState) {
|
||||
let layout_id = self.request_layout(cx);
|
||||
let layout_id = self.request_layout(window, cx);
|
||||
(layout_id, ())
|
||||
}
|
||||
|
||||
@@ -566,9 +585,10 @@ impl Element for AnyElement {
|
||||
_: Option<&GlobalElementId>,
|
||||
_: Bounds<Pixels>,
|
||||
_: &mut Self::RequestLayoutState,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) {
|
||||
self.prepaint(cx);
|
||||
self.prepaint(window, cx);
|
||||
}
|
||||
|
||||
fn paint(
|
||||
@@ -577,9 +597,10 @@ impl Element for AnyElement {
|
||||
_: Bounds<Pixels>,
|
||||
_: &mut Self::RequestLayoutState,
|
||||
_: &mut Self::PrepaintState,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) {
|
||||
self.paint(cx);
|
||||
self.paint(window, cx);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -617,9 +638,10 @@ impl Element for Empty {
|
||||
fn request_layout(
|
||||
&mut self,
|
||||
_id: Option<&GlobalElementId>,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> (LayoutId, Self::RequestLayoutState) {
|
||||
(cx.request_layout(Style::default(), None), ())
|
||||
(window.request_layout(Style::default(), None, cx), ())
|
||||
}
|
||||
|
||||
fn prepaint(
|
||||
@@ -627,7 +649,8 @@ impl Element for Empty {
|
||||
_id: Option<&GlobalElementId>,
|
||||
_bounds: Bounds<Pixels>,
|
||||
_state: &mut Self::RequestLayoutState,
|
||||
_cx: &mut WindowContext,
|
||||
_window: &mut Window,
|
||||
_cx: &mut App,
|
||||
) {
|
||||
}
|
||||
|
||||
@@ -637,7 +660,8 @@ impl Element for Empty {
|
||||
_bounds: Bounds<Pixels>,
|
||||
_request_layout: &mut Self::RequestLayoutState,
|
||||
_prepaint: &mut Self::PrepaintState,
|
||||
_cx: &mut WindowContext,
|
||||
_window: &mut Window,
|
||||
_cx: &mut App,
|
||||
) {
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,8 +2,8 @@ use smallvec::SmallVec;
|
||||
use taffy::style::{Display, Position};
|
||||
|
||||
use crate::{
|
||||
point, AnyElement, Axis, Bounds, Corner, Edges, Element, GlobalElementId, IntoElement,
|
||||
LayoutId, ParentElement, Pixels, Point, Size, Style, WindowContext,
|
||||
point, AnyElement, App, Axis, Bounds, Corner, Edges, Element, GlobalElementId, IntoElement,
|
||||
LayoutId, ParentElement, Pixels, Point, Size, Style, Window,
|
||||
};
|
||||
|
||||
/// The state that the anchored element element uses to track its children.
|
||||
@@ -94,12 +94,13 @@ impl Element for Anchored {
|
||||
fn request_layout(
|
||||
&mut self,
|
||||
_id: Option<&GlobalElementId>,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> (crate::LayoutId, Self::RequestLayoutState) {
|
||||
let child_layout_ids = self
|
||||
.children
|
||||
.iter_mut()
|
||||
.map(|child| child.request_layout(cx))
|
||||
.map(|child| child.request_layout(window, cx))
|
||||
.collect::<SmallVec<_>>();
|
||||
|
||||
let anchored_style = Style {
|
||||
@@ -108,7 +109,7 @@ impl Element for Anchored {
|
||||
..Style::default()
|
||||
};
|
||||
|
||||
let layout_id = cx.request_layout(anchored_style, child_layout_ids.iter().copied());
|
||||
let layout_id = window.request_layout(anchored_style, child_layout_ids.iter().copied(), cx);
|
||||
|
||||
(layout_id, AnchoredState { child_layout_ids })
|
||||
}
|
||||
@@ -118,7 +119,8 @@ impl Element for Anchored {
|
||||
_id: Option<&GlobalElementId>,
|
||||
bounds: Bounds<Pixels>,
|
||||
request_layout: &mut Self::RequestLayoutState,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) {
|
||||
if request_layout.child_layout_ids.is_empty() {
|
||||
return;
|
||||
@@ -127,7 +129,7 @@ impl Element for Anchored {
|
||||
let mut child_min = point(Pixels::MAX, Pixels::MAX);
|
||||
let mut child_max = Point::default();
|
||||
for child_layout_id in &request_layout.child_layout_ids {
|
||||
let child_bounds = cx.layout_bounds(*child_layout_id);
|
||||
let child_bounds = window.layout_bounds(*child_layout_id);
|
||||
child_min = child_min.min(&child_bounds.origin);
|
||||
child_max = child_max.max(&child_bounds.bottom_right());
|
||||
}
|
||||
@@ -143,7 +145,7 @@ impl Element for Anchored {
|
||||
|
||||
let limits = Bounds {
|
||||
origin: Point::default(),
|
||||
size: cx.viewport_size(),
|
||||
size: window.viewport_size(),
|
||||
};
|
||||
|
||||
if self.fit_mode == AnchoredFitMode::SwitchAnchor {
|
||||
@@ -199,9 +201,9 @@ impl Element for Anchored {
|
||||
let offset = desired.origin - bounds.origin;
|
||||
let offset = point(offset.x.round(), offset.y.round());
|
||||
|
||||
cx.with_element_offset(offset, |cx| {
|
||||
window.with_element_offset(offset, |window| {
|
||||
for child in &mut self.children {
|
||||
child.prepaint(cx);
|
||||
child.prepaint(window, cx);
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -212,10 +214,11 @@ impl Element for Anchored {
|
||||
_bounds: crate::Bounds<crate::Pixels>,
|
||||
_request_layout: &mut Self::RequestLayoutState,
|
||||
_prepaint: &mut Self::PrepaintState,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) {
|
||||
for child in &mut self.children {
|
||||
child.paint(cx);
|
||||
child.paint(window, cx);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use crate::{AnyElement, Element, ElementId, GlobalElementId, IntoElement, WindowContext};
|
||||
use crate::{AnyElement, App, Element, ElementId, GlobalElementId, IntoElement, Window};
|
||||
|
||||
pub use easing::*;
|
||||
|
||||
@@ -104,9 +104,10 @@ impl<E: IntoElement + 'static> Element for AnimationElement<E> {
|
||||
fn request_layout(
|
||||
&mut self,
|
||||
global_id: Option<&GlobalElementId>,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> (crate::LayoutId, Self::RequestLayoutState) {
|
||||
cx.with_element_state(global_id.unwrap(), |state, cx| {
|
||||
window.with_element_state(global_id.unwrap(), |state, window| {
|
||||
let state = state.unwrap_or_else(|| AnimationState {
|
||||
start: Instant::now(),
|
||||
});
|
||||
@@ -133,10 +134,10 @@ impl<E: IntoElement + 'static> Element for AnimationElement<E> {
|
||||
let mut element = (self.animator)(element, delta).into_any_element();
|
||||
|
||||
if !done {
|
||||
cx.request_animation_frame();
|
||||
window.request_animation_frame();
|
||||
}
|
||||
|
||||
((element.request_layout(cx), element), state)
|
||||
((element.request_layout(window, cx), element), state)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -145,9 +146,10 @@ impl<E: IntoElement + 'static> Element for AnimationElement<E> {
|
||||
_id: Option<&GlobalElementId>,
|
||||
_bounds: crate::Bounds<crate::Pixels>,
|
||||
element: &mut Self::RequestLayoutState,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> Self::PrepaintState {
|
||||
element.prepaint(cx);
|
||||
element.prepaint(window, cx);
|
||||
}
|
||||
|
||||
fn paint(
|
||||
@@ -156,9 +158,10 @@ impl<E: IntoElement + 'static> Element for AnimationElement<E> {
|
||||
_bounds: crate::Bounds<crate::Pixels>,
|
||||
element: &mut Self::RequestLayoutState,
|
||||
_: &mut Self::PrepaintState,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) {
|
||||
element.paint(cx);
|
||||
element.paint(window, cx);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
use refineable::Refineable as _;
|
||||
|
||||
use crate::{
|
||||
Bounds, Element, ElementId, GlobalElementId, IntoElement, Pixels, Style, StyleRefinement,
|
||||
Styled, WindowContext,
|
||||
App, Bounds, Element, ElementId, GlobalElementId, IntoElement, Pixels, Style, StyleRefinement,
|
||||
Styled, Window,
|
||||
};
|
||||
|
||||
/// Construct a canvas element with the given paint callback.
|
||||
/// Useful for adding short term custom drawing to a view.
|
||||
pub fn canvas<T>(
|
||||
prepaint: impl 'static + FnOnce(Bounds<Pixels>, &mut WindowContext) -> T,
|
||||
paint: impl 'static + FnOnce(Bounds<Pixels>, T, &mut WindowContext),
|
||||
prepaint: impl 'static + FnOnce(Bounds<Pixels>, &mut Window, &mut App) -> T,
|
||||
paint: impl 'static + FnOnce(Bounds<Pixels>, T, &mut Window, &mut App),
|
||||
) -> Canvas<T> {
|
||||
Canvas {
|
||||
prepaint: Some(Box::new(prepaint)),
|
||||
@@ -21,8 +21,8 @@ pub fn canvas<T>(
|
||||
/// A canvas element, meant for accessing the low level paint API without defining a whole
|
||||
/// custom element
|
||||
pub struct Canvas<T> {
|
||||
prepaint: Option<Box<dyn FnOnce(Bounds<Pixels>, &mut WindowContext) -> T>>,
|
||||
paint: Option<Box<dyn FnOnce(Bounds<Pixels>, T, &mut WindowContext)>>,
|
||||
prepaint: Option<Box<dyn FnOnce(Bounds<Pixels>, &mut Window, &mut App) -> T>>,
|
||||
paint: Option<Box<dyn FnOnce(Bounds<Pixels>, T, &mut Window, &mut App)>>,
|
||||
style: StyleRefinement,
|
||||
}
|
||||
|
||||
@@ -45,11 +45,12 @@ impl<T: 'static> Element for Canvas<T> {
|
||||
fn request_layout(
|
||||
&mut self,
|
||||
_id: Option<&GlobalElementId>,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> (crate::LayoutId, Self::RequestLayoutState) {
|
||||
let mut style = Style::default();
|
||||
style.refine(&self.style);
|
||||
let layout_id = cx.request_layout(style.clone(), []);
|
||||
let layout_id = window.request_layout(style.clone(), [], cx);
|
||||
(layout_id, style)
|
||||
}
|
||||
|
||||
@@ -58,9 +59,10 @@ impl<T: 'static> Element for Canvas<T> {
|
||||
_id: Option<&GlobalElementId>,
|
||||
bounds: Bounds<Pixels>,
|
||||
_request_layout: &mut Style,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> Option<T> {
|
||||
Some(self.prepaint.take().unwrap()(bounds, cx))
|
||||
Some(self.prepaint.take().unwrap()(bounds, window, cx))
|
||||
}
|
||||
|
||||
fn paint(
|
||||
@@ -69,11 +71,12 @@ impl<T: 'static> Element for Canvas<T> {
|
||||
bounds: Bounds<Pixels>,
|
||||
style: &mut Style,
|
||||
prepaint: &mut Self::PrepaintState,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) {
|
||||
let prepaint = prepaint.take().unwrap();
|
||||
style.paint(bounds, cx, |cx| {
|
||||
(self.paint.take().unwrap())(bounds, prepaint, cx)
|
||||
style.paint(bounds, window, cx, |window, cx| {
|
||||
(self.paint.take().unwrap())(bounds, prepaint, window, cx)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::{
|
||||
AnyElement, Bounds, Element, GlobalElementId, IntoElement, LayoutId, Pixels, WindowContext,
|
||||
AnyElement, App, Bounds, Element, GlobalElementId, IntoElement, LayoutId, Pixels, Window,
|
||||
};
|
||||
|
||||
/// Builds a `Deferred` element, which delays the layout and paint of its child.
|
||||
@@ -38,9 +38,10 @@ impl Element for Deferred {
|
||||
fn request_layout(
|
||||
&mut self,
|
||||
_id: Option<&GlobalElementId>,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> (LayoutId, ()) {
|
||||
let layout_id = self.child.as_mut().unwrap().request_layout(cx);
|
||||
let layout_id = self.child.as_mut().unwrap().request_layout(window, cx);
|
||||
(layout_id, ())
|
||||
}
|
||||
|
||||
@@ -49,11 +50,12 @@ impl Element for Deferred {
|
||||
_id: Option<&GlobalElementId>,
|
||||
_bounds: Bounds<Pixels>,
|
||||
_request_layout: &mut Self::RequestLayoutState,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
_cx: &mut App,
|
||||
) {
|
||||
let child = self.child.take().unwrap();
|
||||
let element_offset = cx.element_offset();
|
||||
cx.defer_draw(child, element_offset, self.priority)
|
||||
let element_offset = window.element_offset();
|
||||
window.defer_draw(child, element_offset, self.priority)
|
||||
}
|
||||
|
||||
fn paint(
|
||||
@@ -62,7 +64,8 @@ impl Element for Deferred {
|
||||
_bounds: Bounds<Pixels>,
|
||||
_request_layout: &mut Self::RequestLayoutState,
|
||||
_prepaint: &mut Self::PrepaintState,
|
||||
_cx: &mut WindowContext,
|
||||
_window: &mut Window,
|
||||
_cx: &mut App,
|
||||
) {
|
||||
}
|
||||
}
|
||||
|
||||
+471
-396
File diff suppressed because it is too large
Load Diff
@@ -1,8 +1,8 @@
|
||||
use crate::{
|
||||
px, swap_rgba_pa_to_bgra, AbsoluteLength, AnyElement, AppContext, Asset, AssetLogger, Bounds,
|
||||
px, swap_rgba_pa_to_bgra, AbsoluteLength, AnyElement, App, Asset, AssetLogger, Bounds,
|
||||
DefiniteLength, Element, ElementId, GlobalElementId, Hitbox, Image, InteractiveElement,
|
||||
Interactivity, IntoElement, LayoutId, Length, ObjectFit, Pixels, RenderImage, Resource,
|
||||
SharedString, SharedUri, StyleRefinement, Styled, SvgSize, Task, WindowContext,
|
||||
SharedString, SharedUri, StyleRefinement, Styled, SvgSize, Task, Window,
|
||||
};
|
||||
use anyhow::{anyhow, Result};
|
||||
|
||||
@@ -45,7 +45,7 @@ pub enum ImageSource {
|
||||
/// Cached image data
|
||||
Image(Arc<Image>),
|
||||
/// A custom loading function to use
|
||||
Custom(Arc<dyn Fn(&mut WindowContext) -> Option<Result<Arc<RenderImage>, ImageCacheError>>>),
|
||||
Custom(Arc<dyn Fn(&mut Window, &mut App) -> Option<Result<Arc<RenderImage>, ImageCacheError>>>),
|
||||
}
|
||||
|
||||
fn is_uri(uri: &str) -> bool {
|
||||
@@ -114,8 +114,9 @@ impl From<Arc<Image>> for ImageSource {
|
||||
}
|
||||
}
|
||||
|
||||
impl<F: Fn(&mut WindowContext) -> Option<Result<Arc<RenderImage>, ImageCacheError>> + 'static>
|
||||
From<F> for ImageSource
|
||||
impl<
|
||||
F: Fn(&mut Window, &mut App) -> Option<Result<Arc<RenderImage>, ImageCacheError>> + 'static,
|
||||
> From<F> for ImageSource
|
||||
{
|
||||
fn from(value: F) -> Self {
|
||||
Self::Custom(Arc::new(value))
|
||||
@@ -248,14 +249,15 @@ impl Element for Img {
|
||||
fn request_layout(
|
||||
&mut self,
|
||||
global_id: Option<&GlobalElementId>,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> (LayoutId, Self::RequestLayoutState) {
|
||||
let mut layout_state = ImgLayoutState {
|
||||
frame_index: 0,
|
||||
replacement: None,
|
||||
};
|
||||
|
||||
cx.with_optional_element_state(global_id, |state, cx| {
|
||||
window.with_optional_element_state(global_id, |state, window| {
|
||||
let mut state = state.map(|state| {
|
||||
state.unwrap_or(ImgState {
|
||||
frame_index: 0,
|
||||
@@ -266,12 +268,14 @@ impl Element for Img {
|
||||
|
||||
let frame_index = state.as_ref().map(|state| state.frame_index).unwrap_or(0);
|
||||
|
||||
let layout_id = self
|
||||
.interactivity
|
||||
.request_layout(global_id, cx, |mut style, cx| {
|
||||
let layout_id = self.interactivity.request_layout(
|
||||
global_id,
|
||||
window,
|
||||
cx,
|
||||
|mut style, window, cx| {
|
||||
let mut replacement_id = None;
|
||||
|
||||
match self.source.use_data(cx) {
|
||||
match self.source.use_data(window, cx) {
|
||||
Some(Ok(data)) => {
|
||||
if let Some(state) = &mut state {
|
||||
let frame_count = data.frame_count();
|
||||
@@ -324,13 +328,13 @@ impl Element for Img {
|
||||
}
|
||||
|
||||
if global_id.is_some() && data.frame_count() > 1 {
|
||||
cx.request_animation_frame();
|
||||
window.request_animation_frame();
|
||||
}
|
||||
}
|
||||
Some(_err) => {
|
||||
if let Some(fallback) = self.style.fallback.as_ref() {
|
||||
let mut element = fallback();
|
||||
replacement_id = Some(element.request_layout(cx));
|
||||
replacement_id = Some(element.request_layout(window, cx));
|
||||
layout_state.replacement = Some(element);
|
||||
}
|
||||
if let Some(state) = &mut state {
|
||||
@@ -343,15 +347,16 @@ impl Element for Img {
|
||||
if started_loading.elapsed() > LOADING_DELAY {
|
||||
if let Some(loading) = self.style.loading.as_ref() {
|
||||
let mut element = loading();
|
||||
replacement_id = Some(element.request_layout(cx));
|
||||
replacement_id =
|
||||
Some(element.request_layout(window, cx));
|
||||
layout_state.replacement = Some(element);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let parent_view_id = cx.parent_view_id();
|
||||
let task = cx.spawn(|mut cx| async move {
|
||||
let parent_view_id = window.parent_view_id().unwrap();
|
||||
let task = window.spawn(cx, |mut cx| async move {
|
||||
cx.background_executor().timer(LOADING_DELAY).await;
|
||||
cx.update(|cx| {
|
||||
cx.update(move |_, cx| {
|
||||
cx.notify(parent_view_id);
|
||||
})
|
||||
.ok();
|
||||
@@ -362,8 +367,9 @@ impl Element for Img {
|
||||
}
|
||||
}
|
||||
|
||||
cx.request_layout(style, replacement_id)
|
||||
});
|
||||
window.request_layout(style, replacement_id, cx)
|
||||
},
|
||||
);
|
||||
|
||||
layout_state.frame_index = frame_index;
|
||||
|
||||
@@ -376,16 +382,23 @@ impl Element for Img {
|
||||
global_id: Option<&GlobalElementId>,
|
||||
bounds: Bounds<Pixels>,
|
||||
request_layout: &mut Self::RequestLayoutState,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> Self::PrepaintState {
|
||||
self.interactivity
|
||||
.prepaint(global_id, bounds, bounds.size, cx, |_, _, hitbox, cx| {
|
||||
self.interactivity.prepaint(
|
||||
global_id,
|
||||
bounds,
|
||||
bounds.size,
|
||||
window,
|
||||
cx,
|
||||
|_, _, hitbox, window, cx| {
|
||||
if let Some(replacement) = &mut request_layout.replacement {
|
||||
replacement.prepaint(cx);
|
||||
replacement.prepaint(window, cx);
|
||||
}
|
||||
|
||||
hitbox
|
||||
})
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn paint(
|
||||
@@ -394,30 +407,38 @@ impl Element for Img {
|
||||
bounds: Bounds<Pixels>,
|
||||
layout_state: &mut Self::RequestLayoutState,
|
||||
hitbox: &mut Self::PrepaintState,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) {
|
||||
let source = self.source.clone();
|
||||
self.interactivity
|
||||
.paint(global_id, bounds, hitbox.as_ref(), cx, |style, cx| {
|
||||
let corner_radii = style.corner_radii.to_pixels(bounds.size, cx.rem_size());
|
||||
self.interactivity.paint(
|
||||
global_id,
|
||||
bounds,
|
||||
hitbox.as_ref(),
|
||||
window,
|
||||
cx,
|
||||
|style, window, cx| {
|
||||
let corner_radii = style.corner_radii.to_pixels(bounds.size, window.rem_size());
|
||||
|
||||
if let Some(Ok(data)) = source.use_data(cx) {
|
||||
if let Some(Ok(data)) = source.use_data(window, cx) {
|
||||
let new_bounds = self
|
||||
.style
|
||||
.object_fit
|
||||
.get_bounds(bounds, data.size(layout_state.frame_index));
|
||||
cx.paint_image(
|
||||
new_bounds,
|
||||
corner_radii,
|
||||
data.clone(),
|
||||
layout_state.frame_index,
|
||||
self.style.grayscale,
|
||||
)
|
||||
.log_err();
|
||||
window
|
||||
.paint_image(
|
||||
new_bounds,
|
||||
corner_radii,
|
||||
data.clone(),
|
||||
layout_state.frame_index,
|
||||
self.style.grayscale,
|
||||
)
|
||||
.log_err();
|
||||
} else if let Some(replacement) = &mut layout_state.replacement {
|
||||
replacement.paint(cx);
|
||||
replacement.paint(window, cx);
|
||||
}
|
||||
})
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -448,13 +469,14 @@ impl StatefulInteractiveElement for Img {}
|
||||
impl ImageSource {
|
||||
pub(crate) fn use_data(
|
||||
&self,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> Option<Result<Arc<RenderImage>, ImageCacheError>> {
|
||||
match self {
|
||||
ImageSource::Resource(resource) => cx.use_asset::<ImgResourceLoader>(&resource),
|
||||
ImageSource::Custom(loading_fn) => loading_fn(cx),
|
||||
ImageSource::Resource(resource) => window.use_asset::<ImgResourceLoader>(&resource, cx),
|
||||
ImageSource::Custom(loading_fn) => loading_fn(window, cx),
|
||||
ImageSource::Render(data) => Some(Ok(data.to_owned())),
|
||||
ImageSource::Image(data) => cx.use_asset::<AssetLogger<ImageDecoder>>(data),
|
||||
ImageSource::Image(data) => window.use_asset::<AssetLogger<ImageDecoder>>(data, cx),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -468,7 +490,7 @@ impl Asset for ImageDecoder {
|
||||
|
||||
fn load(
|
||||
source: Self::Source,
|
||||
cx: &mut AppContext,
|
||||
cx: &mut App,
|
||||
) -> impl Future<Output = Self::Output> + Send + 'static {
|
||||
let renderer = cx.svg_renderer();
|
||||
async move { source.to_image_data(renderer).map_err(Into::into) }
|
||||
@@ -485,7 +507,7 @@ impl Asset for ImageAssetLoader {
|
||||
|
||||
fn load(
|
||||
source: Self::Source,
|
||||
cx: &mut AppContext,
|
||||
cx: &mut App,
|
||||
) -> impl Future<Output = Self::Output> + Send + 'static {
|
||||
let client = cx.http_client();
|
||||
// TODO: Can we make SVGs always rescale?
|
||||
|
||||
@@ -8,9 +8,9 @@
|
||||
//! If all of your elements are the same height, see [`UniformList`] for a simpler API
|
||||
|
||||
use crate::{
|
||||
point, px, size, AnyElement, AvailableSpace, Bounds, ContentMask, DispatchPhase, Edges,
|
||||
point, px, size, AnyElement, App, AvailableSpace, Bounds, ContentMask, DispatchPhase, Edges,
|
||||
Element, FocusHandle, GlobalElementId, Hitbox, IntoElement, Pixels, Point, ScrollWheelEvent,
|
||||
Size, Style, StyleRefinement, Styled, WindowContext,
|
||||
Size, Style, StyleRefinement, Styled, Window,
|
||||
};
|
||||
use collections::VecDeque;
|
||||
use refineable::Refineable as _;
|
||||
@@ -49,14 +49,14 @@ pub struct ListState(Rc<RefCell<StateInner>>);
|
||||
struct StateInner {
|
||||
last_layout_bounds: Option<Bounds<Pixels>>,
|
||||
last_padding: Option<Edges<Pixels>>,
|
||||
render_item: Box<dyn FnMut(usize, &mut WindowContext) -> AnyElement>,
|
||||
render_item: Box<dyn FnMut(usize, &mut Window, &mut App) -> AnyElement>,
|
||||
items: SumTree<ListItem>,
|
||||
logical_scroll_top: Option<ListOffset>,
|
||||
alignment: ListAlignment,
|
||||
overdraw: Pixels,
|
||||
reset: bool,
|
||||
#[allow(clippy::type_complexity)]
|
||||
scroll_handler: Option<Box<dyn FnMut(&ListScrollEvent, &mut WindowContext)>>,
|
||||
scroll_handler: Option<Box<dyn FnMut(&ListScrollEvent, &mut Window, &mut App)>>,
|
||||
}
|
||||
|
||||
/// Whether the list is scrolling from top to bottom or bottom to top.
|
||||
@@ -146,12 +146,12 @@ impl ListItem {
|
||||
}
|
||||
}
|
||||
|
||||
fn contains_focused(&self, cx: &WindowContext) -> bool {
|
||||
fn contains_focused(&self, window: &Window, cx: &App) -> bool {
|
||||
match self {
|
||||
ListItem::Unmeasured { focus_handle } | ListItem::Measured { focus_handle, .. } => {
|
||||
focus_handle
|
||||
.as_ref()
|
||||
.is_some_and(|handle| handle.contains_focused(cx))
|
||||
.is_some_and(|handle| handle.contains_focused(window, cx))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -186,7 +186,7 @@ impl ListState {
|
||||
render_item: R,
|
||||
) -> Self
|
||||
where
|
||||
R: 'static + FnMut(usize, &mut WindowContext) -> AnyElement,
|
||||
R: 'static + FnMut(usize, &mut Window, &mut App) -> AnyElement,
|
||||
{
|
||||
let this = Self(Rc::new(RefCell::new(StateInner {
|
||||
last_layout_bounds: None,
|
||||
@@ -272,7 +272,7 @@ impl ListState {
|
||||
/// Set a handler that will be called when the list is scrolled.
|
||||
pub fn set_scroll_handler(
|
||||
&self,
|
||||
handler: impl FnMut(&ListScrollEvent, &mut WindowContext) + 'static,
|
||||
handler: impl FnMut(&ListScrollEvent, &mut Window, &mut App) + 'static,
|
||||
) {
|
||||
self.0.borrow_mut().scroll_handler = Some(Box::new(handler))
|
||||
}
|
||||
@@ -371,7 +371,8 @@ impl StateInner {
|
||||
scroll_top: &ListOffset,
|
||||
height: Pixels,
|
||||
delta: Point<Pixels>,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) {
|
||||
// Drop scroll events after a reset, since we can't calculate
|
||||
// the new logical scroll top without the item heights
|
||||
@@ -407,11 +408,12 @@ impl StateInner {
|
||||
count: self.items.summary().count,
|
||||
is_scrolled: self.logical_scroll_top.is_some(),
|
||||
},
|
||||
window,
|
||||
cx,
|
||||
);
|
||||
}
|
||||
|
||||
cx.refresh();
|
||||
window.refresh();
|
||||
}
|
||||
|
||||
fn logical_scroll_top(&self) -> ListOffset {
|
||||
@@ -439,7 +441,8 @@ impl StateInner {
|
||||
available_width: Option<Pixels>,
|
||||
available_height: Pixels,
|
||||
padding: &Edges<Pixels>,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> LayoutItemsResponse {
|
||||
let old_items = self.items.clone();
|
||||
let mut measured_items = VecDeque::new();
|
||||
@@ -472,8 +475,8 @@ impl StateInner {
|
||||
// If we're within the visible area or the height wasn't cached, render and measure the item's element
|
||||
if visible_height < available_height || size.is_none() {
|
||||
let item_index = scroll_top.item_ix + ix;
|
||||
let mut element = (self.render_item)(item_index, cx);
|
||||
let element_size = element.layout_as_root(available_item_space, cx);
|
||||
let mut element = (self.render_item)(item_index, window, cx);
|
||||
let element_size = element.layout_as_root(available_item_space, window, cx);
|
||||
size = Some(element_size);
|
||||
if visible_height < available_height {
|
||||
item_layouts.push_back(ItemLayout {
|
||||
@@ -481,7 +484,7 @@ impl StateInner {
|
||||
element,
|
||||
size: element_size,
|
||||
});
|
||||
if item.contains_focused(cx) {
|
||||
if item.contains_focused(window, cx) {
|
||||
rendered_focused_item = true;
|
||||
}
|
||||
}
|
||||
@@ -507,8 +510,8 @@ impl StateInner {
|
||||
cursor.prev(&());
|
||||
if let Some(item) = cursor.item() {
|
||||
let item_index = cursor.start().0;
|
||||
let mut element = (self.render_item)(item_index, cx);
|
||||
let element_size = element.layout_as_root(available_item_space, cx);
|
||||
let mut element = (self.render_item)(item_index, window, cx);
|
||||
let element_size = element.layout_as_root(available_item_space, window, cx);
|
||||
let focus_handle = item.focus_handle();
|
||||
rendered_height += element_size.height;
|
||||
measured_items.push_front(ListItem::Measured {
|
||||
@@ -520,7 +523,7 @@ impl StateInner {
|
||||
element,
|
||||
size: element_size,
|
||||
});
|
||||
if item.contains_focused(cx) {
|
||||
if item.contains_focused(window, cx) {
|
||||
rendered_focused_item = true;
|
||||
}
|
||||
} else {
|
||||
@@ -556,8 +559,8 @@ impl StateInner {
|
||||
let size = if let ListItem::Measured { size, .. } = item {
|
||||
*size
|
||||
} else {
|
||||
let mut element = (self.render_item)(cursor.start().0, cx);
|
||||
element.layout_as_root(available_item_space, cx)
|
||||
let mut element = (self.render_item)(cursor.start().0, window, cx);
|
||||
element.layout_as_root(available_item_space, window, cx)
|
||||
};
|
||||
|
||||
leading_overdraw += size.height;
|
||||
@@ -587,10 +590,10 @@ impl StateInner {
|
||||
.filter::<_, Count>(&(), |summary| summary.has_focus_handles);
|
||||
cursor.next(&());
|
||||
while let Some(item) = cursor.item() {
|
||||
if item.contains_focused(cx) {
|
||||
if item.contains_focused(window, cx) {
|
||||
let item_index = cursor.start().0;
|
||||
let mut element = (self.render_item)(cursor.start().0, cx);
|
||||
let size = element.layout_as_root(available_item_space, cx);
|
||||
let mut element = (self.render_item)(cursor.start().0, window, cx);
|
||||
let size = element.layout_as_root(available_item_space, window, cx);
|
||||
item_layouts.push_back(ItemLayout {
|
||||
index: item_index,
|
||||
element,
|
||||
@@ -614,25 +617,31 @@ impl StateInner {
|
||||
bounds: Bounds<Pixels>,
|
||||
padding: Edges<Pixels>,
|
||||
autoscroll: bool,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> Result<LayoutItemsResponse, ListOffset> {
|
||||
cx.transact(|cx| {
|
||||
let mut layout_response =
|
||||
self.layout_items(Some(bounds.size.width), bounds.size.height, &padding, cx);
|
||||
window.transact(|window| {
|
||||
let mut layout_response = self.layout_items(
|
||||
Some(bounds.size.width),
|
||||
bounds.size.height,
|
||||
&padding,
|
||||
window,
|
||||
cx,
|
||||
);
|
||||
|
||||
// Avoid honoring autoscroll requests from elements other than our children.
|
||||
cx.take_autoscroll();
|
||||
window.take_autoscroll();
|
||||
|
||||
// Only paint the visible items, if there is actually any space for them (taking padding into account)
|
||||
if bounds.size.height > padding.top + padding.bottom {
|
||||
let mut item_origin = bounds.origin + Point::new(px(0.), padding.top);
|
||||
item_origin.y -= layout_response.scroll_top.offset_in_item;
|
||||
for item in &mut layout_response.item_layouts {
|
||||
cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
|
||||
item.element.prepaint_at(item_origin, cx);
|
||||
window.with_content_mask(Some(ContentMask { bounds }), |window| {
|
||||
item.element.prepaint_at(item_origin, window, cx);
|
||||
});
|
||||
|
||||
if let Some(autoscroll_bounds) = cx.take_autoscroll() {
|
||||
if let Some(autoscroll_bounds) = window.take_autoscroll() {
|
||||
if autoscroll {
|
||||
if autoscroll_bounds.top() < bounds.top() {
|
||||
return Err(ListOffset {
|
||||
@@ -653,12 +662,13 @@ impl StateInner {
|
||||
let Some(item) = cursor.item() else { break };
|
||||
|
||||
let size = item.size().unwrap_or_else(|| {
|
||||
let mut item = (self.render_item)(cursor.start().0, cx);
|
||||
let mut item =
|
||||
(self.render_item)(cursor.start().0, window, cx);
|
||||
let item_available_size = size(
|
||||
bounds.size.width.into(),
|
||||
AvailableSpace::MinContent,
|
||||
);
|
||||
item.layout_as_root(item_available_size, cx)
|
||||
item.layout_as_root(item_available_size, window, cx)
|
||||
});
|
||||
height -= size.height;
|
||||
}
|
||||
@@ -716,14 +726,15 @@ impl Element for List {
|
||||
fn request_layout(
|
||||
&mut self,
|
||||
_id: Option<&GlobalElementId>,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> (crate::LayoutId, Self::RequestLayoutState) {
|
||||
let layout_id = match self.sizing_behavior {
|
||||
ListSizingBehavior::Infer => {
|
||||
let mut style = Style::default();
|
||||
style.overflow.y = Overflow::Scroll;
|
||||
style.refine(&self.style);
|
||||
cx.with_text_style(style.text_style().cloned(), |cx| {
|
||||
window.with_text_style(style.text_style().cloned(), |window| {
|
||||
let state = &mut *self.state.0.borrow_mut();
|
||||
|
||||
let available_height = if let Some(last_bounds) = state.last_layout_bounds {
|
||||
@@ -735,18 +746,19 @@ impl Element for List {
|
||||
};
|
||||
let padding = style.padding.to_pixels(
|
||||
state.last_layout_bounds.unwrap_or_default().size.into(),
|
||||
cx.rem_size(),
|
||||
window.rem_size(),
|
||||
);
|
||||
|
||||
let layout_response = state.layout_items(None, available_height, &padding, cx);
|
||||
let layout_response =
|
||||
state.layout_items(None, available_height, &padding, window, cx);
|
||||
let max_element_width = layout_response.max_item_width;
|
||||
|
||||
let summary = state.items.summary();
|
||||
let total_height = summary.height;
|
||||
|
||||
cx.request_measured_layout(
|
||||
window.request_measured_layout(
|
||||
style,
|
||||
move |known_dimensions, available_space, _cx| {
|
||||
move |known_dimensions, available_space, _window, _cx| {
|
||||
let width =
|
||||
known_dimensions
|
||||
.width
|
||||
@@ -770,8 +782,8 @@ impl Element for List {
|
||||
ListSizingBehavior::Auto => {
|
||||
let mut style = Style::default();
|
||||
style.refine(&self.style);
|
||||
cx.with_text_style(style.text_style().cloned(), |cx| {
|
||||
cx.request_layout(style, None)
|
||||
window.with_text_style(style.text_style().cloned(), |window| {
|
||||
window.request_layout(style, None, cx)
|
||||
})
|
||||
}
|
||||
};
|
||||
@@ -783,7 +795,8 @@ impl Element for List {
|
||||
_id: Option<&GlobalElementId>,
|
||||
bounds: Bounds<Pixels>,
|
||||
_: &mut Self::RequestLayoutState,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> ListPrepaintState {
|
||||
let state = &mut *self.state.0.borrow_mut();
|
||||
state.reset = false;
|
||||
@@ -791,7 +804,7 @@ impl Element for List {
|
||||
let mut style = Style::default();
|
||||
style.refine(&self.style);
|
||||
|
||||
let hitbox = cx.insert_hitbox(bounds, false);
|
||||
let hitbox = window.insert_hitbox(bounds, false);
|
||||
|
||||
// If the width of the list has changed, invalidate all cached item heights
|
||||
if state.last_layout_bounds.map_or(true, |last_bounds| {
|
||||
@@ -807,12 +820,16 @@ impl Element for List {
|
||||
state.items = new_items;
|
||||
}
|
||||
|
||||
let padding = style.padding.to_pixels(bounds.size.into(), cx.rem_size());
|
||||
let layout = match state.prepaint_items(bounds, padding, true, cx) {
|
||||
let padding = style
|
||||
.padding
|
||||
.to_pixels(bounds.size.into(), window.rem_size());
|
||||
let layout = match state.prepaint_items(bounds, padding, true, window, cx) {
|
||||
Ok(layout) => layout,
|
||||
Err(autoscroll_request) => {
|
||||
state.logical_scroll_top = Some(autoscroll_request);
|
||||
state.prepaint_items(bounds, padding, false, cx).unwrap()
|
||||
state
|
||||
.prepaint_items(bounds, padding, false, window, cx)
|
||||
.unwrap()
|
||||
}
|
||||
};
|
||||
|
||||
@@ -827,11 +844,12 @@ impl Element for List {
|
||||
bounds: Bounds<crate::Pixels>,
|
||||
_: &mut Self::RequestLayoutState,
|
||||
prepaint: &mut Self::PrepaintState,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) {
|
||||
cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
|
||||
window.with_content_mask(Some(ContentMask { bounds }), |window| {
|
||||
for item in &mut prepaint.layout.item_layouts {
|
||||
item.element.paint(cx);
|
||||
item.element.paint(window, cx);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -839,12 +857,13 @@ impl Element for List {
|
||||
let height = bounds.size.height;
|
||||
let scroll_top = prepaint.layout.scroll_top;
|
||||
let hitbox_id = prepaint.hitbox.id;
|
||||
cx.on_mouse_event(move |event: &ScrollWheelEvent, phase, cx| {
|
||||
if phase == DispatchPhase::Bubble && hitbox_id.is_hovered(cx) {
|
||||
window.on_mouse_event(move |event: &ScrollWheelEvent, phase, window, cx| {
|
||||
if phase == DispatchPhase::Bubble && hitbox_id.is_hovered(window) {
|
||||
list_state.0.borrow_mut().scroll(
|
||||
&scroll_top,
|
||||
height,
|
||||
event.delta.pixel_delta(px(20.)),
|
||||
window,
|
||||
cx,
|
||||
)
|
||||
}
|
||||
@@ -952,7 +971,7 @@ mod test {
|
||||
|
||||
let cx = cx.add_empty_window();
|
||||
|
||||
let state = ListState::new(5, crate::ListAlignment::Top, px(10.), |_, _| {
|
||||
let state = ListState::new(5, crate::ListAlignment::Top, px(10.), |_, _, _| {
|
||||
div().h(px(10.)).w_full().into_any()
|
||||
});
|
||||
|
||||
@@ -963,7 +982,7 @@ mod test {
|
||||
});
|
||||
|
||||
// Paint
|
||||
cx.draw(point(px(0.), px(0.)), size(px(100.), px(20.)), |_| {
|
||||
cx.draw(point(px(0.), px(0.)), size(px(100.), px(20.)), |_, _| {
|
||||
list(state.clone()).w_full().h_full()
|
||||
});
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::{
|
||||
Bounds, Element, ElementId, GlobalElementId, IntoElement, LayoutId, ObjectFit, Pixels, Style,
|
||||
StyleRefinement, Styled, WindowContext,
|
||||
App, Bounds, Element, ElementId, GlobalElementId, IntoElement, LayoutId, ObjectFit, Pixels,
|
||||
Style, StyleRefinement, Styled, Window,
|
||||
};
|
||||
#[cfg(target_os = "macos")]
|
||||
use media::core_video::CVImageBuffer;
|
||||
@@ -56,11 +56,12 @@ impl Element for Surface {
|
||||
fn request_layout(
|
||||
&mut self,
|
||||
_global_id: Option<&GlobalElementId>,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> (LayoutId, Self::RequestLayoutState) {
|
||||
let mut style = Style::default();
|
||||
style.refine(&self.style);
|
||||
let layout_id = cx.request_layout(style, []);
|
||||
let layout_id = window.request_layout(style, [], cx);
|
||||
(layout_id, ())
|
||||
}
|
||||
|
||||
@@ -69,7 +70,8 @@ impl Element for Surface {
|
||||
_global_id: Option<&GlobalElementId>,
|
||||
_bounds: Bounds<Pixels>,
|
||||
_request_layout: &mut Self::RequestLayoutState,
|
||||
_cx: &mut WindowContext,
|
||||
_window: &mut Window,
|
||||
_cx: &mut App,
|
||||
) -> Self::PrepaintState {
|
||||
}
|
||||
|
||||
@@ -79,7 +81,8 @@ impl Element for Surface {
|
||||
#[cfg_attr(not(target_os = "macos"), allow(unused_variables))] bounds: Bounds<Pixels>,
|
||||
_: &mut Self::RequestLayoutState,
|
||||
_: &mut Self::PrepaintState,
|
||||
#[cfg_attr(not(target_os = "macos"), allow(unused_variables))] cx: &mut WindowContext,
|
||||
#[cfg_attr(not(target_os = "macos"), allow(unused_variables))] window: &mut Window,
|
||||
_: &mut App,
|
||||
) {
|
||||
match &self.source {
|
||||
#[cfg(target_os = "macos")]
|
||||
@@ -87,7 +90,7 @@ impl Element for Surface {
|
||||
let size = crate::size(surface.width().into(), surface.height().into());
|
||||
let new_bounds = self.object_fit.get_bounds(bounds, size);
|
||||
// TODO: Add support for corner_radii
|
||||
cx.paint_surface(new_bounds, surface.clone());
|
||||
window.paint_surface(new_bounds, surface.clone());
|
||||
}
|
||||
#[allow(unreachable_patterns)]
|
||||
_ => {}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use crate::{
|
||||
geometry::Negate as _, point, px, radians, size, Bounds, Element, GlobalElementId, Hitbox,
|
||||
geometry::Negate as _, point, px, radians, size, App, Bounds, Element, GlobalElementId, Hitbox,
|
||||
InteractiveElement, Interactivity, IntoElement, LayoutId, Pixels, Point, Radians, SharedString,
|
||||
Size, StyleRefinement, Styled, TransformationMatrix, WindowContext,
|
||||
Size, StyleRefinement, Styled, TransformationMatrix, Window,
|
||||
};
|
||||
use util::ResultExt;
|
||||
|
||||
@@ -47,11 +47,14 @@ impl Element for Svg {
|
||||
fn request_layout(
|
||||
&mut self,
|
||||
global_id: Option<&GlobalElementId>,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> (LayoutId, Self::RequestLayoutState) {
|
||||
let layout_id = self
|
||||
.interactivity
|
||||
.request_layout(global_id, cx, |style, cx| cx.request_layout(style, None));
|
||||
let layout_id =
|
||||
self.interactivity
|
||||
.request_layout(global_id, window, cx, |style, window, cx| {
|
||||
window.request_layout(style, None, cx)
|
||||
});
|
||||
(layout_id, ())
|
||||
}
|
||||
|
||||
@@ -60,10 +63,17 @@ impl Element for Svg {
|
||||
global_id: Option<&GlobalElementId>,
|
||||
bounds: Bounds<Pixels>,
|
||||
_request_layout: &mut Self::RequestLayoutState,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> Option<Hitbox> {
|
||||
self.interactivity
|
||||
.prepaint(global_id, bounds, bounds.size, cx, |_, _, hitbox, _| hitbox)
|
||||
self.interactivity.prepaint(
|
||||
global_id,
|
||||
bounds,
|
||||
bounds.size,
|
||||
window,
|
||||
cx,
|
||||
|_, _, hitbox, _, _| hitbox,
|
||||
)
|
||||
}
|
||||
|
||||
fn paint(
|
||||
@@ -72,25 +82,33 @@ impl Element for Svg {
|
||||
bounds: Bounds<Pixels>,
|
||||
_request_layout: &mut Self::RequestLayoutState,
|
||||
hitbox: &mut Option<Hitbox>,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) where
|
||||
Self: Sized,
|
||||
{
|
||||
self.interactivity
|
||||
.paint(global_id, bounds, hitbox.as_ref(), cx, |style, cx| {
|
||||
self.interactivity.paint(
|
||||
global_id,
|
||||
bounds,
|
||||
hitbox.as_ref(),
|
||||
window,
|
||||
cx,
|
||||
|style, window, cx| {
|
||||
if let Some((path, color)) = self.path.as_ref().zip(style.text.color) {
|
||||
let transformation = self
|
||||
.transformation
|
||||
.as_ref()
|
||||
.map(|transformation| {
|
||||
transformation.into_matrix(bounds.center(), cx.scale_factor())
|
||||
transformation.into_matrix(bounds.center(), window.scale_factor())
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
cx.paint_svg(bounds, path.clone(), transformation, color)
|
||||
window
|
||||
.paint_svg(bounds, path.clone(), transformation, color, cx)
|
||||
.log_err();
|
||||
}
|
||||
})
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
use crate::{
|
||||
register_tooltip_mouse_handlers, set_tooltip_on_window, ActiveTooltip, AnyView, Bounds,
|
||||
register_tooltip_mouse_handlers, set_tooltip_on_window, ActiveTooltip, AnyView, App, Bounds,
|
||||
DispatchPhase, Element, ElementId, GlobalElementId, HighlightStyle, Hitbox, IntoElement,
|
||||
LayoutId, MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels, Point, SharedString, Size,
|
||||
TextRun, TextStyle, TooltipId, Truncate, WhiteSpace, WindowContext, WrappedLine,
|
||||
WrappedLineLayout,
|
||||
TextRun, TextStyle, TooltipId, Truncate, WhiteSpace, Window, WrappedLine, WrappedLineLayout,
|
||||
};
|
||||
use anyhow::anyhow;
|
||||
use parking_lot::{Mutex, MutexGuard};
|
||||
@@ -28,10 +27,11 @@ impl Element for &'static str {
|
||||
fn request_layout(
|
||||
&mut self,
|
||||
_id: Option<&GlobalElementId>,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> (LayoutId, Self::RequestLayoutState) {
|
||||
let mut state = TextLayout::default();
|
||||
let layout_id = state.layout(SharedString::from(*self), None, cx);
|
||||
let layout_id = state.layout(SharedString::from(*self), None, window, cx);
|
||||
(layout_id, state)
|
||||
}
|
||||
|
||||
@@ -40,7 +40,8 @@ impl Element for &'static str {
|
||||
_id: Option<&GlobalElementId>,
|
||||
bounds: Bounds<Pixels>,
|
||||
text_layout: &mut Self::RequestLayoutState,
|
||||
_cx: &mut WindowContext,
|
||||
_window: &mut Window,
|
||||
_cx: &mut App,
|
||||
) {
|
||||
text_layout.prepaint(bounds, self)
|
||||
}
|
||||
@@ -51,9 +52,10 @@ impl Element for &'static str {
|
||||
_bounds: Bounds<Pixels>,
|
||||
text_layout: &mut TextLayout,
|
||||
_: &mut (),
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) {
|
||||
text_layout.paint(self, cx)
|
||||
text_layout.paint(self, window, cx)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,10 +88,11 @@ impl Element for SharedString {
|
||||
|
||||
_id: Option<&GlobalElementId>,
|
||||
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> (LayoutId, Self::RequestLayoutState) {
|
||||
let mut state = TextLayout::default();
|
||||
let layout_id = state.layout(self.clone(), None, cx);
|
||||
let layout_id = state.layout(self.clone(), None, window, cx);
|
||||
(layout_id, state)
|
||||
}
|
||||
|
||||
@@ -98,7 +101,8 @@ impl Element for SharedString {
|
||||
_id: Option<&GlobalElementId>,
|
||||
bounds: Bounds<Pixels>,
|
||||
text_layout: &mut Self::RequestLayoutState,
|
||||
_cx: &mut WindowContext,
|
||||
_window: &mut Window,
|
||||
_cx: &mut App,
|
||||
) {
|
||||
text_layout.prepaint(bounds, self.as_ref())
|
||||
}
|
||||
@@ -109,9 +113,10 @@ impl Element for SharedString {
|
||||
_bounds: Bounds<Pixels>,
|
||||
text_layout: &mut Self::RequestLayoutState,
|
||||
_: &mut Self::PrepaintState,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) {
|
||||
text_layout.paint(self.as_ref(), cx)
|
||||
text_layout.paint(self.as_ref(), window, cx)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -197,9 +202,12 @@ impl Element for StyledText {
|
||||
|
||||
_id: Option<&GlobalElementId>,
|
||||
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> (LayoutId, Self::RequestLayoutState) {
|
||||
let layout_id = self.layout.layout(self.text.clone(), self.runs.take(), cx);
|
||||
let layout_id = self
|
||||
.layout
|
||||
.layout(self.text.clone(), self.runs.take(), window, cx);
|
||||
(layout_id, ())
|
||||
}
|
||||
|
||||
@@ -208,7 +216,8 @@ impl Element for StyledText {
|
||||
_id: Option<&GlobalElementId>,
|
||||
bounds: Bounds<Pixels>,
|
||||
_: &mut Self::RequestLayoutState,
|
||||
_cx: &mut WindowContext,
|
||||
_window: &mut Window,
|
||||
_cx: &mut App,
|
||||
) {
|
||||
self.layout.prepaint(bounds, &self.text)
|
||||
}
|
||||
@@ -219,9 +228,10 @@ impl Element for StyledText {
|
||||
_bounds: Bounds<Pixels>,
|
||||
_: &mut Self::RequestLayoutState,
|
||||
_: &mut Self::PrepaintState,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) {
|
||||
self.layout.paint(&self.text, cx)
|
||||
self.layout.paint(&self.text, window, cx)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -256,13 +266,14 @@ impl TextLayout {
|
||||
&self,
|
||||
text: SharedString,
|
||||
runs: Option<Vec<TextRun>>,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
_: &mut App,
|
||||
) -> LayoutId {
|
||||
let text_style = cx.text_style();
|
||||
let font_size = text_style.font_size.to_pixels(cx.rem_size());
|
||||
let text_style = window.text_style();
|
||||
let font_size = text_style.font_size.to_pixels(window.rem_size());
|
||||
let line_height = text_style
|
||||
.line_height
|
||||
.to_pixels(font_size.into(), cx.rem_size());
|
||||
.to_pixels(font_size.into(), window.rem_size());
|
||||
|
||||
let mut runs = if let Some(runs) = runs {
|
||||
runs
|
||||
@@ -270,10 +281,10 @@ impl TextLayout {
|
||||
vec![text_style.to_run(text.len())]
|
||||
};
|
||||
|
||||
let layout_id = cx.request_measured_layout(Default::default(), {
|
||||
let layout_id = window.request_measured_layout(Default::default(), {
|
||||
let element_state = self.clone();
|
||||
|
||||
move |known_dimensions, available_space, cx| {
|
||||
move |known_dimensions, available_space, window, cx| {
|
||||
let wrap_width = if text_style.white_space == WhiteSpace::Normal {
|
||||
known_dimensions.width.or(match available_space.width {
|
||||
crate::AvailableSpace::Definite(x) => Some(x),
|
||||
@@ -312,7 +323,7 @@ impl TextLayout {
|
||||
text.clone()
|
||||
};
|
||||
|
||||
let Some(lines) = cx
|
||||
let Some(lines) = window
|
||||
.text_system()
|
||||
.shape_text(
|
||||
text, font_size, &runs, wrap_width, // Wrap if we know the width.
|
||||
@@ -360,7 +371,7 @@ impl TextLayout {
|
||||
element_state.bounds = Some(bounds);
|
||||
}
|
||||
|
||||
fn paint(&self, text: &str, cx: &mut WindowContext) {
|
||||
fn paint(&self, text: &str, window: &mut Window, cx: &mut App) {
|
||||
let element_state = self.lock();
|
||||
let element_state = element_state
|
||||
.as_ref()
|
||||
@@ -374,7 +385,7 @@ impl TextLayout {
|
||||
let line_height = element_state.line_height;
|
||||
let mut line_origin = bounds.origin;
|
||||
for line in &element_state.lines {
|
||||
line.paint(line_origin, line_height, cx).log_err();
|
||||
line.paint(line_origin, line_height, window, cx).log_err();
|
||||
line_origin.y += line.size(line_height).height;
|
||||
}
|
||||
}
|
||||
@@ -503,9 +514,9 @@ pub struct InteractiveText {
|
||||
element_id: ElementId,
|
||||
text: StyledText,
|
||||
click_listener:
|
||||
Option<Box<dyn Fn(&[Range<usize>], InteractiveTextClickEvent, &mut WindowContext)>>,
|
||||
hover_listener: Option<Box<dyn Fn(Option<usize>, MouseMoveEvent, &mut WindowContext)>>,
|
||||
tooltip_builder: Option<Rc<dyn Fn(usize, &mut WindowContext) -> Option<AnyView>>>,
|
||||
Option<Box<dyn Fn(&[Range<usize>], InteractiveTextClickEvent, &mut Window, &mut App)>>,
|
||||
hover_listener: Option<Box<dyn Fn(Option<usize>, MouseMoveEvent, &mut Window, &mut App)>>,
|
||||
tooltip_builder: Option<Rc<dyn Fn(usize, &mut Window, &mut App) -> Option<AnyView>>>,
|
||||
tooltip_id: Option<TooltipId>,
|
||||
clickable_ranges: Vec<Range<usize>>,
|
||||
}
|
||||
@@ -543,13 +554,13 @@ impl InteractiveText {
|
||||
pub fn on_click(
|
||||
mut self,
|
||||
ranges: Vec<Range<usize>>,
|
||||
listener: impl Fn(usize, &mut WindowContext) + 'static,
|
||||
listener: impl Fn(usize, &mut Window, &mut App) + 'static,
|
||||
) -> Self {
|
||||
self.click_listener = Some(Box::new(move |ranges, event, cx| {
|
||||
self.click_listener = Some(Box::new(move |ranges, event, window, cx| {
|
||||
for (range_ix, range) in ranges.iter().enumerate() {
|
||||
if range.contains(&event.mouse_down_index) && range.contains(&event.mouse_up_index)
|
||||
{
|
||||
listener(range_ix, cx);
|
||||
listener(range_ix, window, cx);
|
||||
}
|
||||
}
|
||||
}));
|
||||
@@ -561,7 +572,7 @@ impl InteractiveText {
|
||||
/// index of the hovered character, or None if the mouse leaves the text.
|
||||
pub fn on_hover(
|
||||
mut self,
|
||||
listener: impl Fn(Option<usize>, MouseMoveEvent, &mut WindowContext) + 'static,
|
||||
listener: impl Fn(Option<usize>, MouseMoveEvent, &mut Window, &mut App) + 'static,
|
||||
) -> Self {
|
||||
self.hover_listener = Some(Box::new(listener));
|
||||
self
|
||||
@@ -570,7 +581,7 @@ impl InteractiveText {
|
||||
/// tooltip lets you specify a tooltip for a given character index in the string.
|
||||
pub fn tooltip(
|
||||
mut self,
|
||||
builder: impl Fn(usize, &mut WindowContext) -> Option<AnyView> + 'static,
|
||||
builder: impl Fn(usize, &mut Window, &mut App) -> Option<AnyView> + 'static,
|
||||
) -> Self {
|
||||
self.tooltip_builder = Some(Rc::new(builder));
|
||||
self
|
||||
@@ -588,9 +599,10 @@ impl Element for InteractiveText {
|
||||
fn request_layout(
|
||||
&mut self,
|
||||
_id: Option<&GlobalElementId>,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> (LayoutId, Self::RequestLayoutState) {
|
||||
self.text.request_layout(None, cx)
|
||||
self.text.request_layout(None, window, cx)
|
||||
}
|
||||
|
||||
fn prepaint(
|
||||
@@ -598,26 +610,27 @@ impl Element for InteractiveText {
|
||||
global_id: Option<&GlobalElementId>,
|
||||
bounds: Bounds<Pixels>,
|
||||
state: &mut Self::RequestLayoutState,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> Hitbox {
|
||||
cx.with_optional_element_state::<InteractiveTextState, _>(
|
||||
window.with_optional_element_state::<InteractiveTextState, _>(
|
||||
global_id,
|
||||
|interactive_state, cx| {
|
||||
|interactive_state, window| {
|
||||
let mut interactive_state = interactive_state
|
||||
.map(|interactive_state| interactive_state.unwrap_or_default());
|
||||
|
||||
if let Some(interactive_state) = interactive_state.as_mut() {
|
||||
if self.tooltip_builder.is_some() {
|
||||
self.tooltip_id =
|
||||
set_tooltip_on_window(&interactive_state.active_tooltip, cx);
|
||||
set_tooltip_on_window(&interactive_state.active_tooltip, window);
|
||||
} else {
|
||||
// If there is no longer a tooltip builder, remove the active tooltip.
|
||||
interactive_state.active_tooltip.take();
|
||||
}
|
||||
}
|
||||
|
||||
self.text.prepaint(None, bounds, state, cx);
|
||||
let hitbox = cx.insert_hitbox(bounds, false);
|
||||
self.text.prepaint(None, bounds, state, window, cx);
|
||||
let hitbox = window.insert_hitbox(bounds, false);
|
||||
(hitbox, interactive_state)
|
||||
},
|
||||
)
|
||||
@@ -629,22 +642,23 @@ impl Element for InteractiveText {
|
||||
bounds: Bounds<Pixels>,
|
||||
_: &mut Self::RequestLayoutState,
|
||||
hitbox: &mut Hitbox,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) {
|
||||
let text_layout = self.text.layout().clone();
|
||||
cx.with_element_state::<InteractiveTextState, _>(
|
||||
window.with_element_state::<InteractiveTextState, _>(
|
||||
global_id.unwrap(),
|
||||
|interactive_state, cx| {
|
||||
|interactive_state, window| {
|
||||
let mut interactive_state = interactive_state.unwrap_or_default();
|
||||
if let Some(click_listener) = self.click_listener.take() {
|
||||
let mouse_position = cx.mouse_position();
|
||||
let mouse_position = window.mouse_position();
|
||||
if let Ok(ix) = text_layout.index_for_position(mouse_position) {
|
||||
if self
|
||||
.clickable_ranges
|
||||
.iter()
|
||||
.any(|range| range.contains(&ix))
|
||||
{
|
||||
cx.set_cursor_style(crate::CursorStyle::PointingHand, hitbox)
|
||||
window.set_cursor_style(crate::CursorStyle::PointingHand, hitbox)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -653,55 +667,58 @@ impl Element for InteractiveText {
|
||||
if let Some(mouse_down_index) = mouse_down.get() {
|
||||
let hitbox = hitbox.clone();
|
||||
let clickable_ranges = mem::take(&mut self.clickable_ranges);
|
||||
cx.on_mouse_event(move |event: &MouseUpEvent, phase, cx| {
|
||||
if phase == DispatchPhase::Bubble && hitbox.is_hovered(cx) {
|
||||
if let Ok(mouse_up_index) =
|
||||
text_layout.index_for_position(event.position)
|
||||
{
|
||||
click_listener(
|
||||
&clickable_ranges,
|
||||
InteractiveTextClickEvent {
|
||||
mouse_down_index,
|
||||
mouse_up_index,
|
||||
},
|
||||
cx,
|
||||
)
|
||||
}
|
||||
window.on_mouse_event(
|
||||
move |event: &MouseUpEvent, phase, window: &mut Window, cx| {
|
||||
if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
|
||||
if let Ok(mouse_up_index) =
|
||||
text_layout.index_for_position(event.position)
|
||||
{
|
||||
click_listener(
|
||||
&clickable_ranges,
|
||||
InteractiveTextClickEvent {
|
||||
mouse_down_index,
|
||||
mouse_up_index,
|
||||
},
|
||||
window,
|
||||
cx,
|
||||
)
|
||||
}
|
||||
|
||||
mouse_down.take();
|
||||
cx.refresh();
|
||||
}
|
||||
});
|
||||
mouse_down.take();
|
||||
window.refresh();
|
||||
}
|
||||
},
|
||||
);
|
||||
} else {
|
||||
let hitbox = hitbox.clone();
|
||||
cx.on_mouse_event(move |event: &MouseDownEvent, phase, cx| {
|
||||
if phase == DispatchPhase::Bubble && hitbox.is_hovered(cx) {
|
||||
window.on_mouse_event(move |event: &MouseDownEvent, phase, window, _| {
|
||||
if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
|
||||
if let Ok(mouse_down_index) =
|
||||
text_layout.index_for_position(event.position)
|
||||
{
|
||||
mouse_down.set(Some(mouse_down_index));
|
||||
cx.refresh();
|
||||
window.refresh();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
cx.on_mouse_event({
|
||||
window.on_mouse_event({
|
||||
let mut hover_listener = self.hover_listener.take();
|
||||
let hitbox = hitbox.clone();
|
||||
let text_layout = text_layout.clone();
|
||||
let hovered_index = interactive_state.hovered_index.clone();
|
||||
move |event: &MouseMoveEvent, phase, cx| {
|
||||
if phase == DispatchPhase::Bubble && hitbox.is_hovered(cx) {
|
||||
move |event: &MouseMoveEvent, phase, window, cx| {
|
||||
if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
|
||||
let current = hovered_index.get();
|
||||
let updated = text_layout.index_for_position(event.position).ok();
|
||||
if current != updated {
|
||||
hovered_index.set(updated);
|
||||
if let Some(hover_listener) = hover_listener.as_ref() {
|
||||
hover_listener(updated, event.clone(), cx);
|
||||
hover_listener(updated, event.clone(), window, cx);
|
||||
}
|
||||
cx.refresh();
|
||||
window.refresh();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -713,11 +730,11 @@ impl Element for InteractiveText {
|
||||
let build_tooltip = Rc::new({
|
||||
let tooltip_is_hoverable = false;
|
||||
let text_layout = text_layout.clone();
|
||||
move |cx: &mut WindowContext| {
|
||||
move |window: &mut Window, cx: &mut App| {
|
||||
text_layout
|
||||
.index_for_position(cx.mouse_position())
|
||||
.index_for_position(window.mouse_position())
|
||||
.ok()
|
||||
.and_then(|position| tooltip_builder(position, cx))
|
||||
.and_then(|position| tooltip_builder(position, window, cx))
|
||||
.map(|view| (view, tooltip_is_hoverable))
|
||||
}
|
||||
});
|
||||
@@ -726,9 +743,11 @@ impl Element for InteractiveText {
|
||||
let source_bounds = hitbox.bounds;
|
||||
let check_is_hovered = Rc::new({
|
||||
let text_layout = text_layout.clone();
|
||||
move |cx: &WindowContext| {
|
||||
text_layout.index_for_position(cx.mouse_position()).is_ok()
|
||||
&& source_bounds.contains(&cx.mouse_position())
|
||||
move |window: &Window| {
|
||||
text_layout
|
||||
.index_for_position(window.mouse_position())
|
||||
.is_ok()
|
||||
&& source_bounds.contains(&window.mouse_position())
|
||||
&& pending_mouse_down.get().is_none()
|
||||
}
|
||||
});
|
||||
@@ -737,11 +756,11 @@ impl Element for InteractiveText {
|
||||
self.tooltip_id,
|
||||
build_tooltip,
|
||||
check_is_hovered,
|
||||
cx,
|
||||
window,
|
||||
);
|
||||
}
|
||||
|
||||
self.text.paint(None, bounds, &mut (), &mut (), cx);
|
||||
self.text.paint(None, bounds, &mut (), &mut (), window, cx);
|
||||
|
||||
((), interactive_state)
|
||||
},
|
||||
|
||||
@@ -5,10 +5,10 @@
|
||||
//! elements with uniform height.
|
||||
|
||||
use crate::{
|
||||
point, size, AnyElement, AvailableSpace, Bounds, ContentMask, Element, ElementId,
|
||||
GlobalElementId, Hitbox, InteractiveElement, Interactivity, IntoElement, IsZero, LayoutId,
|
||||
ListSizingBehavior, Pixels, Render, ScrollHandle, Size, StyleRefinement, Styled, View,
|
||||
ViewContext, WindowContext,
|
||||
point, size, AnyElement, App, AvailableSpace, Bounds, ContentMask, Context, Element, ElementId,
|
||||
Entity, GlobalElementId, Hitbox, InteractiveElement, Interactivity, IntoElement, IsZero,
|
||||
LayoutId, ListSizingBehavior, Pixels, Render, ScrollHandle, Size, StyleRefinement, Styled,
|
||||
Window,
|
||||
};
|
||||
use smallvec::SmallVec;
|
||||
use std::{cell::RefCell, cmp, ops::Range, rc::Rc};
|
||||
@@ -21,10 +21,10 @@ use super::ListHorizontalSizingBehavior;
|
||||
/// uniform_list will only render the visible subset of items.
|
||||
#[track_caller]
|
||||
pub fn uniform_list<I, R, V>(
|
||||
view: View<V>,
|
||||
view: Entity<V>,
|
||||
id: I,
|
||||
item_count: usize,
|
||||
f: impl 'static + Fn(&mut V, Range<usize>, &mut ViewContext<V>) -> Vec<R>,
|
||||
f: impl 'static + Fn(&mut V, Range<usize>, &mut Window, &mut Context<V>) -> Vec<R>,
|
||||
) -> UniformList
|
||||
where
|
||||
I: Into<ElementId>,
|
||||
@@ -35,9 +35,9 @@ where
|
||||
let mut base_style = StyleRefinement::default();
|
||||
base_style.overflow.y = Some(Overflow::Scroll);
|
||||
|
||||
let render_range = move |range, cx: &mut WindowContext| {
|
||||
let render_range = move |range, window: &mut Window, cx: &mut App| {
|
||||
view.update(cx, |this, cx| {
|
||||
f(this, range, cx)
|
||||
f(this, range, window, cx)
|
||||
.into_iter()
|
||||
.map(|component| component.into_any_element())
|
||||
.collect()
|
||||
@@ -68,8 +68,9 @@ where
|
||||
pub struct UniformList {
|
||||
item_count: usize,
|
||||
item_to_measure_index: usize,
|
||||
render_items:
|
||||
Box<dyn for<'a> Fn(Range<usize>, &'a mut WindowContext) -> SmallVec<[AnyElement; 64]>>,
|
||||
render_items: Box<
|
||||
dyn for<'a> Fn(Range<usize>, &'a mut Window, &'a mut App) -> SmallVec<[AnyElement; 64]>,
|
||||
>,
|
||||
decorations: Vec<Box<dyn UniformListDecoration>>,
|
||||
interactivity: Interactivity,
|
||||
scroll_handle: Option<UniformListScrollHandle>,
|
||||
@@ -168,18 +169,21 @@ impl Element for UniformList {
|
||||
fn request_layout(
|
||||
&mut self,
|
||||
global_id: Option<&GlobalElementId>,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> (LayoutId, Self::RequestLayoutState) {
|
||||
let max_items = self.item_count;
|
||||
let item_size = self.measure_item(None, cx);
|
||||
let layout_id = self
|
||||
.interactivity
|
||||
.request_layout(global_id, cx, |style, cx| match self.sizing_behavior {
|
||||
let item_size = self.measure_item(None, window, cx);
|
||||
let layout_id = self.interactivity.request_layout(
|
||||
global_id,
|
||||
window,
|
||||
cx,
|
||||
|style, window, cx| match self.sizing_behavior {
|
||||
ListSizingBehavior::Infer => {
|
||||
cx.with_text_style(style.text_style().cloned(), |cx| {
|
||||
cx.request_measured_layout(
|
||||
window.with_text_style(style.text_style().cloned(), |window| {
|
||||
window.request_measured_layout(
|
||||
style,
|
||||
move |known_dimensions, available_space, _cx| {
|
||||
move |known_dimensions, available_space, _window, _cx| {
|
||||
let desired_height = item_size.height * max_items;
|
||||
let width = known_dimensions.width.unwrap_or(match available_space
|
||||
.width
|
||||
@@ -200,10 +204,12 @@ impl Element for UniformList {
|
||||
)
|
||||
})
|
||||
}
|
||||
ListSizingBehavior::Auto => cx.with_text_style(style.text_style().cloned(), |cx| {
|
||||
cx.request_layout(style, None)
|
||||
}),
|
||||
});
|
||||
ListSizingBehavior::Auto => window
|
||||
.with_text_style(style.text_style().cloned(), |window| {
|
||||
window.request_layout(style, None, cx)
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
||||
(
|
||||
layout_id,
|
||||
@@ -219,11 +225,16 @@ impl Element for UniformList {
|
||||
global_id: Option<&GlobalElementId>,
|
||||
bounds: Bounds<Pixels>,
|
||||
frame_state: &mut Self::RequestLayoutState,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> Option<Hitbox> {
|
||||
let style = self.interactivity.compute_style(global_id, None, cx);
|
||||
let border = style.border_widths.to_pixels(cx.rem_size());
|
||||
let padding = style.padding.to_pixels(bounds.size.into(), cx.rem_size());
|
||||
let style = self
|
||||
.interactivity
|
||||
.compute_style(global_id, None, window, cx);
|
||||
let border = style.border_widths.to_pixels(window.rem_size());
|
||||
let padding = style
|
||||
.padding
|
||||
.to_pixels(bounds.size.into(), window.rem_size());
|
||||
|
||||
let padded_bounds = Bounds::from_corners(
|
||||
bounds.origin + point(border.left + padding.left, border.top + padding.top),
|
||||
@@ -236,7 +247,7 @@ impl Element for UniformList {
|
||||
ListHorizontalSizingBehavior::Unconstrained
|
||||
);
|
||||
|
||||
let longest_item_size = self.measure_item(None, cx);
|
||||
let longest_item_size = self.measure_item(None, window, cx);
|
||||
let content_width = if can_scroll_horizontally {
|
||||
padded_bounds.size.width.max(longest_item_size.width)
|
||||
} else {
|
||||
@@ -262,10 +273,13 @@ impl Element for UniformList {
|
||||
global_id,
|
||||
bounds,
|
||||
content_size,
|
||||
window,
|
||||
cx,
|
||||
|style, mut scroll_offset, hitbox, cx| {
|
||||
let border = style.border_widths.to_pixels(cx.rem_size());
|
||||
let padding = style.padding.to_pixels(bounds.size.into(), cx.rem_size());
|
||||
|style, mut scroll_offset, hitbox, window, cx| {
|
||||
let border = style.border_widths.to_pixels(window.rem_size());
|
||||
let padding = style
|
||||
.padding
|
||||
.to_pixels(bounds.size.into(), window.rem_size());
|
||||
|
||||
let padded_bounds = Bounds::from_corners(
|
||||
bounds.origin + point(border.left + padding.left, border.top),
|
||||
@@ -348,15 +362,15 @@ impl Element for UniformList {
|
||||
let items = if y_flipped {
|
||||
let flipped_range = self.item_count.saturating_sub(visible_range.end)
|
||||
..self.item_count.saturating_sub(visible_range.start);
|
||||
let mut items = (self.render_items)(flipped_range, cx);
|
||||
let mut items = (self.render_items)(flipped_range, window, cx);
|
||||
items.reverse();
|
||||
items
|
||||
} else {
|
||||
(self.render_items)(visible_range.clone(), cx)
|
||||
(self.render_items)(visible_range.clone(), window, cx)
|
||||
};
|
||||
|
||||
let content_mask = ContentMask { bounds };
|
||||
cx.with_content_mask(Some(content_mask), |cx| {
|
||||
window.with_content_mask(Some(content_mask), |window| {
|
||||
for (mut item, ix) in items.into_iter().zip(visible_range.clone()) {
|
||||
let item_origin = padded_bounds.origin
|
||||
+ point(
|
||||
@@ -376,8 +390,8 @@ impl Element for UniformList {
|
||||
AvailableSpace::Definite(available_width),
|
||||
AvailableSpace::Definite(item_height),
|
||||
);
|
||||
item.layout_as_root(available_space, cx);
|
||||
item.prepaint_at(item_origin, cx);
|
||||
item.layout_as_root(available_space, window, cx);
|
||||
item.prepaint_at(item_origin, window, cx);
|
||||
frame_state.items.push(item);
|
||||
}
|
||||
|
||||
@@ -399,14 +413,15 @@ impl Element for UniformList {
|
||||
bounds,
|
||||
item_height,
|
||||
self.item_count,
|
||||
window,
|
||||
cx,
|
||||
);
|
||||
let available_space = size(
|
||||
AvailableSpace::Definite(bounds.size.width),
|
||||
AvailableSpace::Definite(bounds.size.height),
|
||||
);
|
||||
decoration.layout_as_root(available_space, cx);
|
||||
decoration.prepaint_at(bounds.origin, cx);
|
||||
decoration.layout_as_root(available_space, window, cx);
|
||||
decoration.prepaint_at(bounds.origin, window, cx);
|
||||
frame_state.decorations.push(decoration);
|
||||
}
|
||||
});
|
||||
@@ -423,17 +438,24 @@ impl Element for UniformList {
|
||||
bounds: Bounds<crate::Pixels>,
|
||||
request_layout: &mut Self::RequestLayoutState,
|
||||
hitbox: &mut Option<Hitbox>,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) {
|
||||
self.interactivity
|
||||
.paint(global_id, bounds, hitbox.as_ref(), cx, |_, cx| {
|
||||
self.interactivity.paint(
|
||||
global_id,
|
||||
bounds,
|
||||
hitbox.as_ref(),
|
||||
window,
|
||||
cx,
|
||||
|_, window, cx| {
|
||||
for item in &mut request_layout.items {
|
||||
item.paint(cx);
|
||||
item.paint(window, cx);
|
||||
}
|
||||
for decoration in &mut request_layout.decorations {
|
||||
decoration.paint(cx);
|
||||
decoration.paint(window, cx);
|
||||
}
|
||||
})
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -456,7 +478,8 @@ pub trait UniformListDecoration {
|
||||
bounds: Bounds<Pixels>,
|
||||
item_height: Pixels,
|
||||
item_count: usize,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> AnyElement;
|
||||
}
|
||||
|
||||
@@ -498,13 +521,18 @@ impl UniformList {
|
||||
self
|
||||
}
|
||||
|
||||
fn measure_item(&self, list_width: Option<Pixels>, cx: &mut WindowContext) -> Size<Pixels> {
|
||||
fn measure_item(
|
||||
&self,
|
||||
list_width: Option<Pixels>,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> Size<Pixels> {
|
||||
if self.item_count == 0 {
|
||||
return Size::default();
|
||||
}
|
||||
|
||||
let item_ix = cmp::min(self.item_to_measure_index, self.item_count - 1);
|
||||
let mut items = (self.render_items)(item_ix..item_ix + 1, cx);
|
||||
let mut items = (self.render_items)(item_ix..item_ix + 1, window, cx);
|
||||
let Some(mut item_to_measure) = items.pop() else {
|
||||
return Size::default();
|
||||
};
|
||||
@@ -514,7 +542,7 @@ impl UniformList {
|
||||
}),
|
||||
AvailableSpace::MinContent,
|
||||
);
|
||||
item_to_measure.layout_as_root(available_space, cx)
|
||||
item_to_measure.layout_as_root(available_space, window, cx)
|
||||
}
|
||||
|
||||
/// Track and render scroll state of this list with reference to the given scroll handle.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::{AppContext, PlatformDispatcher};
|
||||
use crate::{App, PlatformDispatcher};
|
||||
use async_task::Runnable;
|
||||
use futures::channel::mpsc;
|
||||
use smol::prelude::*;
|
||||
@@ -84,7 +84,7 @@ where
|
||||
/// Run the task to completion in the background and log any
|
||||
/// errors that occur.
|
||||
#[track_caller]
|
||||
pub fn detach_and_log_err(self, cx: &AppContext) {
|
||||
pub fn detach_and_log_err(self, cx: &App) {
|
||||
let location = core::panic::Location::caller();
|
||||
cx.foreground_executor()
|
||||
.spawn(self.log_tracked_err(*location))
|
||||
|
||||
@@ -13,7 +13,7 @@ use std::{
|
||||
ops::{Add, Div, Mul, MulAssign, Neg, Sub},
|
||||
};
|
||||
|
||||
use crate::{AppContext, DisplayId};
|
||||
use crate::{App, DisplayId};
|
||||
|
||||
/// Axis in a 2D cartesian space.
|
||||
#[derive(Copy, Clone, PartialEq, Eq, Serialize, Deserialize, Debug)]
|
||||
@@ -725,7 +725,7 @@ pub fn bounds<T: Clone + Default + Debug>(origin: Point<T>, size: Size<T>) -> Bo
|
||||
|
||||
impl Bounds<Pixels> {
|
||||
/// Generate a centered bounds for the given display or primary display if none is provided
|
||||
pub fn centered(display_id: Option<DisplayId>, size: Size<Pixels>, cx: &AppContext) -> Self {
|
||||
pub fn centered(display_id: Option<DisplayId>, size: Size<Pixels>, cx: &App) -> Self {
|
||||
let display = display_id
|
||||
.and_then(|id| cx.find_display(id))
|
||||
.or_else(|| cx.primary_display());
|
||||
@@ -739,7 +739,7 @@ impl Bounds<Pixels> {
|
||||
}
|
||||
|
||||
/// Generate maximized bounds for the given display or primary display if none is provided
|
||||
pub fn maximized(display_id: Option<DisplayId>, cx: &AppContext) -> Self {
|
||||
pub fn maximized(display_id: Option<DisplayId>, cx: &App) -> Self {
|
||||
let display = display_id
|
||||
.and_then(|id| cx.find_display(id))
|
||||
.or_else(|| cx.primary_display());
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::{AppContext, BorrowAppContext};
|
||||
use crate::{App, BorrowAppContext};
|
||||
|
||||
/// A marker trait for types that can be stored in GPUI's global state.
|
||||
///
|
||||
@@ -31,11 +31,11 @@ pub trait ReadGlobal {
|
||||
/// Returns the global instance of the implementing type.
|
||||
///
|
||||
/// Panics if a global for that type has not been assigned.
|
||||
fn global(cx: &AppContext) -> &Self;
|
||||
fn global(cx: &App) -> &Self;
|
||||
}
|
||||
|
||||
impl<T: Global> ReadGlobal for T {
|
||||
fn global(cx: &AppContext) -> &Self {
|
||||
fn global(cx: &App) -> &Self {
|
||||
cx.global::<T>()
|
||||
}
|
||||
}
|
||||
|
||||
+30
-52
@@ -138,7 +138,6 @@ pub use keymap::*;
|
||||
pub use platform::*;
|
||||
pub use refineable::*;
|
||||
pub use scene::*;
|
||||
use seal::Sealed;
|
||||
pub use shared_string::*;
|
||||
pub use shared_uri::*;
|
||||
pub use smol::Timer;
|
||||
@@ -159,16 +158,16 @@ use taffy::TaffyLayoutEngine;
|
||||
|
||||
/// The context trait, allows the different contexts in GPUI to be used
|
||||
/// interchangeably for certain operations.
|
||||
pub trait Context {
|
||||
pub trait AppContext {
|
||||
/// The result type for this context, used for async contexts that
|
||||
/// can't hold a direct reference to the application context.
|
||||
type Result<T>;
|
||||
|
||||
/// Create a new model in the app context.
|
||||
fn new_model<T: 'static>(
|
||||
fn new<T: 'static>(
|
||||
&mut self,
|
||||
build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
|
||||
) -> Self::Result<Model<T>>;
|
||||
build_model: impl FnOnce(&mut Context<'_, T>) -> T,
|
||||
) -> Self::Result<Entity<T>>;
|
||||
|
||||
/// Reserve a slot for a model to be inserted later.
|
||||
/// The returned [Reservation] allows you to obtain the [EntityId] for the future model.
|
||||
@@ -180,14 +179,14 @@ pub trait Context {
|
||||
fn insert_model<T: 'static>(
|
||||
&mut self,
|
||||
reservation: Reservation<T>,
|
||||
build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
|
||||
) -> Self::Result<Model<T>>;
|
||||
build_model: impl FnOnce(&mut Context<'_, T>) -> T,
|
||||
) -> Self::Result<Entity<T>>;
|
||||
|
||||
/// Update a model in the app context.
|
||||
fn update_model<T, R>(
|
||||
&mut self,
|
||||
handle: &Model<T>,
|
||||
update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
|
||||
handle: &Entity<T>,
|
||||
update: impl FnOnce(&mut T, &mut Context<'_, T>) -> R,
|
||||
) -> Self::Result<R>
|
||||
where
|
||||
T: 'static;
|
||||
@@ -195,8 +194,8 @@ pub trait Context {
|
||||
/// Read a model from the app context.
|
||||
fn read_model<T, R>(
|
||||
&self,
|
||||
handle: &Model<T>,
|
||||
read: impl FnOnce(&T, &AppContext) -> R,
|
||||
handle: &Entity<T>,
|
||||
read: impl FnOnce(&T, &App) -> R,
|
||||
) -> Self::Result<R>
|
||||
where
|
||||
T: 'static;
|
||||
@@ -204,13 +203,13 @@ pub trait Context {
|
||||
/// Update a window for the given handle.
|
||||
fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
|
||||
where
|
||||
F: FnOnce(AnyView, &mut WindowContext) -> T;
|
||||
F: FnOnce(AnyView, &mut Window, &mut App) -> T;
|
||||
|
||||
/// Read a window off of the application context.
|
||||
fn read_window<T, R>(
|
||||
&self,
|
||||
window: &WindowHandle<T>,
|
||||
read: impl FnOnce(View<T>, &AppContext) -> R,
|
||||
read: impl FnOnce(Entity<T>, &App) -> R,
|
||||
) -> Result<R>
|
||||
where
|
||||
T: 'static;
|
||||
@@ -229,56 +228,35 @@ impl<T: 'static> Reservation<T> {
|
||||
|
||||
/// This trait is used for the different visual contexts in GPUI that
|
||||
/// require a window to be present.
|
||||
pub trait VisualContext: Context {
|
||||
/// Construct a new view in the window referenced by this context.
|
||||
fn new_view<V>(
|
||||
&mut self,
|
||||
build_view: impl FnOnce(&mut ViewContext<V>) -> V,
|
||||
) -> Self::Result<View<V>>
|
||||
where
|
||||
V: 'static + Render;
|
||||
pub trait VisualContext: AppContext {
|
||||
/// Returns the handle of the window associated with this context.
|
||||
fn window_handle(&self) -> AnyWindowHandle;
|
||||
|
||||
/// Update a view with the given callback
|
||||
fn update_view<V: 'static, R>(
|
||||
fn update_window_model<T: 'static, R>(
|
||||
&mut self,
|
||||
view: &View<V>,
|
||||
update: impl FnOnce(&mut V, &mut ViewContext<V>) -> R,
|
||||
model: &Entity<T>,
|
||||
update: impl FnOnce(&mut T, &mut Window, &mut Context<T>) -> R,
|
||||
) -> Self::Result<R>;
|
||||
|
||||
/// Update a view with the given callback
|
||||
fn new_window_model<T: 'static>(
|
||||
&mut self,
|
||||
build_model: impl FnOnce(&mut Window, &mut Context<'_, T>) -> T,
|
||||
) -> Self::Result<Entity<T>>;
|
||||
|
||||
/// Replace the root view of a window with a new view.
|
||||
fn replace_root_view<V>(
|
||||
&mut self,
|
||||
build_view: impl FnOnce(&mut ViewContext<V>) -> V,
|
||||
) -> Self::Result<View<V>>
|
||||
build_view: impl FnOnce(&mut Window, &mut Context<V>) -> V,
|
||||
) -> Self::Result<Entity<V>>
|
||||
where
|
||||
V: 'static + Render;
|
||||
|
||||
/// Focus a view in the window, if it implements the [`FocusableView`] trait.
|
||||
fn focus_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
|
||||
/// Focus a model in the window, if it implements the [`Focusable`] trait.
|
||||
fn focus<V>(&mut self, model: &Entity<V>) -> Self::Result<()>
|
||||
where
|
||||
V: FocusableView;
|
||||
|
||||
/// Dismiss a view in the window, if it implements the [`ManagedView`] trait.
|
||||
fn dismiss_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
|
||||
where
|
||||
V: ManagedView;
|
||||
}
|
||||
|
||||
/// A trait that allows models and views to be interchangeable in certain operations
|
||||
pub trait Entity<T>: Sealed {
|
||||
/// The weak reference type for this entity.
|
||||
type Weak: 'static;
|
||||
|
||||
/// The ID for this entity
|
||||
fn entity_id(&self) -> EntityId;
|
||||
|
||||
/// Downgrade this entity to a weak reference.
|
||||
fn downgrade(&self) -> Self::Weak;
|
||||
|
||||
/// Upgrade this entity from a weak reference.
|
||||
fn upgrade_from(weak: &Self::Weak) -> Option<Self>
|
||||
where
|
||||
Self: Sized;
|
||||
V: Focusable;
|
||||
}
|
||||
|
||||
/// A trait for tying together the types of a GPUI entity and the events it can
|
||||
@@ -302,7 +280,7 @@ pub trait BorrowAppContext {
|
||||
|
||||
impl<C> BorrowAppContext for C
|
||||
where
|
||||
C: BorrowMut<AppContext>,
|
||||
C: BorrowMut<App>,
|
||||
{
|
||||
fn set_global<G: Global>(&mut self, global: G) {
|
||||
self.borrow_mut().set_global(global)
|
||||
|
||||
+46
-24
@@ -1,4 +1,4 @@
|
||||
use crate::{Bounds, InputHandler, Pixels, UTF16Selection, View, ViewContext, WindowContext};
|
||||
use crate::{App, Bounds, Context, Entity, InputHandler, Pixels, UTF16Selection, Window};
|
||||
use std::ops::Range;
|
||||
|
||||
/// Implement this trait to allow views to handle textual input when implementing an editor, field, etc.
|
||||
@@ -13,28 +13,35 @@ pub trait ViewInputHandler: 'static + Sized {
|
||||
&mut self,
|
||||
range: Range<usize>,
|
||||
adjusted_range: &mut Option<Range<usize>>,
|
||||
cx: &mut ViewContext<Self>,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) -> Option<String>;
|
||||
|
||||
/// See [`InputHandler::selected_text_range`] for details
|
||||
fn selected_text_range(
|
||||
&mut self,
|
||||
ignore_disabled_input: bool,
|
||||
cx: &mut ViewContext<Self>,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) -> Option<UTF16Selection>;
|
||||
|
||||
/// See [`InputHandler::marked_text_range`] for details
|
||||
fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>>;
|
||||
fn marked_text_range(
|
||||
&self,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) -> Option<Range<usize>>;
|
||||
|
||||
/// See [`InputHandler::unmark_text`] for details
|
||||
fn unmark_text(&mut self, cx: &mut ViewContext<Self>);
|
||||
fn unmark_text(&mut self, window: &mut Window, cx: &mut Context<Self>);
|
||||
|
||||
/// See [`InputHandler::replace_text_in_range`] for details
|
||||
fn replace_text_in_range(
|
||||
&mut self,
|
||||
range: Option<Range<usize>>,
|
||||
text: &str,
|
||||
cx: &mut ViewContext<Self>,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
);
|
||||
|
||||
/// See [`InputHandler::replace_and_mark_text_in_range`] for details
|
||||
@@ -43,7 +50,8 @@ pub trait ViewInputHandler: 'static + Sized {
|
||||
range: Option<Range<usize>>,
|
||||
new_text: &str,
|
||||
new_selected_range: Option<Range<usize>>,
|
||||
cx: &mut ViewContext<Self>,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
);
|
||||
|
||||
/// See [`InputHandler::bounds_for_range`] for details
|
||||
@@ -51,14 +59,15 @@ pub trait ViewInputHandler: 'static + Sized {
|
||||
&mut self,
|
||||
range_utf16: Range<usize>,
|
||||
element_bounds: Bounds<Pixels>,
|
||||
cx: &mut ViewContext<Self>,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) -> Option<Bounds<Pixels>>;
|
||||
}
|
||||
|
||||
/// The canonical implementation of [`PlatformInputHandler`]. Call [`WindowContext::handle_input`]
|
||||
/// with an instance during your element's paint.
|
||||
pub struct ElementInputHandler<V> {
|
||||
view: View<V>,
|
||||
view: Entity<V>,
|
||||
element_bounds: Bounds<Pixels>,
|
||||
}
|
||||
|
||||
@@ -67,7 +76,7 @@ impl<V: 'static> ElementInputHandler<V> {
|
||||
/// containing view.
|
||||
///
|
||||
/// [element_paint]: crate::Element::paint
|
||||
pub fn new(element_bounds: Bounds<Pixels>, view: View<V>) -> Self {
|
||||
pub fn new(element_bounds: Bounds<Pixels>, view: Entity<V>) -> Self {
|
||||
ElementInputHandler {
|
||||
view,
|
||||
element_bounds,
|
||||
@@ -79,25 +88,28 @@ impl<V: ViewInputHandler> InputHandler for ElementInputHandler<V> {
|
||||
fn selected_text_range(
|
||||
&mut self,
|
||||
ignore_disabled_input: bool,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> Option<UTF16Selection> {
|
||||
self.view.update(cx, |view, cx| {
|
||||
view.selected_text_range(ignore_disabled_input, cx)
|
||||
view.selected_text_range(ignore_disabled_input, window, cx)
|
||||
})
|
||||
}
|
||||
|
||||
fn marked_text_range(&mut self, cx: &mut WindowContext) -> Option<Range<usize>> {
|
||||
self.view.update(cx, |view, cx| view.marked_text_range(cx))
|
||||
fn marked_text_range(&mut self, window: &mut Window, cx: &mut App) -> Option<Range<usize>> {
|
||||
self.view
|
||||
.update(cx, |view, cx| view.marked_text_range(window, cx))
|
||||
}
|
||||
|
||||
fn text_for_range(
|
||||
&mut self,
|
||||
range_utf16: Range<usize>,
|
||||
adjusted_range: &mut Option<Range<usize>>,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> Option<String> {
|
||||
self.view.update(cx, |view, cx| {
|
||||
view.text_for_range(range_utf16, adjusted_range, cx)
|
||||
view.text_for_range(range_utf16, adjusted_range, window, cx)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -105,10 +117,11 @@ impl<V: ViewInputHandler> InputHandler for ElementInputHandler<V> {
|
||||
&mut self,
|
||||
replacement_range: Option<Range<usize>>,
|
||||
text: &str,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) {
|
||||
self.view.update(cx, |view, cx| {
|
||||
view.replace_text_in_range(replacement_range, text, cx)
|
||||
view.replace_text_in_range(replacement_range, text, window, cx)
|
||||
});
|
||||
}
|
||||
|
||||
@@ -117,24 +130,33 @@ impl<V: ViewInputHandler> InputHandler for ElementInputHandler<V> {
|
||||
range_utf16: Option<Range<usize>>,
|
||||
new_text: &str,
|
||||
new_selected_range: Option<Range<usize>>,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) {
|
||||
self.view.update(cx, |view, cx| {
|
||||
view.replace_and_mark_text_in_range(range_utf16, new_text, new_selected_range, cx)
|
||||
view.replace_and_mark_text_in_range(
|
||||
range_utf16,
|
||||
new_text,
|
||||
new_selected_range,
|
||||
window,
|
||||
cx,
|
||||
)
|
||||
});
|
||||
}
|
||||
|
||||
fn unmark_text(&mut self, cx: &mut WindowContext) {
|
||||
self.view.update(cx, |view, cx| view.unmark_text(cx));
|
||||
fn unmark_text(&mut self, window: &mut Window, cx: &mut App) {
|
||||
self.view
|
||||
.update(cx, |view, cx| view.unmark_text(window, cx));
|
||||
}
|
||||
|
||||
fn bounds_for_range(
|
||||
&mut self,
|
||||
range_utf16: Range<usize>,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> Option<Bounds<Pixels>> {
|
||||
self.view.update(cx, |view, cx| {
|
||||
view.bounds_for_range(range_utf16, self.element_bounds, cx)
|
||||
view.bounds_for_range(range_utf16, self.element_bounds, window, cx)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::{
|
||||
point, seal::Sealed, Empty, IntoElement, Keystroke, Modifiers, Pixels, Point, Render,
|
||||
ViewContext,
|
||||
point, seal::Sealed, Context, Empty, IntoElement, Keystroke, Modifiers, Pixels, Point, Render,
|
||||
Window,
|
||||
};
|
||||
use smallvec::SmallVec;
|
||||
use std::{any::Any, fmt::Debug, ops::Deref, path::PathBuf};
|
||||
@@ -372,7 +372,7 @@ impl ExternalPaths {
|
||||
}
|
||||
|
||||
impl Render for ExternalPaths {
|
||||
fn render(&mut self, _: &mut ViewContext<Self>) -> impl IntoElement {
|
||||
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
|
||||
// the platform will render icons for the dragged files
|
||||
Empty
|
||||
}
|
||||
@@ -467,8 +467,8 @@ impl PlatformInput {
|
||||
mod test {
|
||||
|
||||
use crate::{
|
||||
self as gpui, div, FocusHandle, InteractiveElement, IntoElement, KeyBinding, Keystroke,
|
||||
ParentElement, Render, TestAppContext, ViewContext, VisualContext,
|
||||
self as gpui, div, AppContext as _, Context, FocusHandle, InteractiveElement, IntoElement,
|
||||
KeyBinding, Keystroke, ParentElement, Render, TestAppContext, Window,
|
||||
};
|
||||
|
||||
struct TestView {
|
||||
@@ -480,19 +480,17 @@ mod test {
|
||||
actions!(test, [TestAction]);
|
||||
|
||||
impl Render for TestView {
|
||||
fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
|
||||
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
div().id("testview").child(
|
||||
div()
|
||||
.key_context("parent")
|
||||
.on_key_down(cx.listener(|this, _, cx| {
|
||||
.on_key_down(cx.listener(|this, _, _, cx| {
|
||||
cx.stop_propagation();
|
||||
this.saw_key_down = true
|
||||
}))
|
||||
.on_action(
|
||||
cx.listener(|this: &mut TestView, _: &TestAction, _| {
|
||||
this.saw_action = true
|
||||
}),
|
||||
)
|
||||
.on_action(cx.listener(|this: &mut TestView, _: &TestAction, _, _| {
|
||||
this.saw_action = true
|
||||
}))
|
||||
.child(
|
||||
div()
|
||||
.key_context("nested")
|
||||
@@ -506,8 +504,8 @@ mod test {
|
||||
#[gpui::test]
|
||||
fn test_on_events(cx: &mut TestAppContext) {
|
||||
let window = cx.update(|cx| {
|
||||
cx.open_window(Default::default(), |cx| {
|
||||
cx.new_view(|cx| TestView {
|
||||
cx.open_window(Default::default(), |_, cx| {
|
||||
cx.new(|cx| TestView {
|
||||
saw_key_down: false,
|
||||
saw_action: false,
|
||||
focus_handle: cx.focus_handle(),
|
||||
@@ -521,14 +519,16 @@ mod test {
|
||||
});
|
||||
|
||||
window
|
||||
.update(cx, |test_view, cx| cx.focus(&test_view.focus_handle))
|
||||
.update(cx, |test_view, window, _cx| {
|
||||
window.focus(&test_view.focus_handle)
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
cx.dispatch_keystroke(*window, Keystroke::parse("a").unwrap());
|
||||
cx.dispatch_keystroke(*window, Keystroke::parse("ctrl-g").unwrap());
|
||||
|
||||
window
|
||||
.update(cx, |test_view, _| {
|
||||
.update(cx, |test_view, _, _| {
|
||||
assert!(test_view.saw_key_down || test_view.saw_action);
|
||||
assert!(test_view.saw_key_down);
|
||||
assert!(test_view.saw_action);
|
||||
|
||||
@@ -9,12 +9,12 @@
|
||||
/// actions!(editor,[Undo, Redo]);;
|
||||
///
|
||||
/// impl Editor {
|
||||
/// fn undo(&mut self, _: &Undo, _cx: &mut ViewContext<Self>) { ... }
|
||||
/// fn redo(&mut self, _: &Redo, _cx: &mut ViewContext<Self>) { ... }
|
||||
/// fn undo(&mut self, _: &Undo, _window: &mut Window, _cx: &mut ModelContext<Self>) { ... }
|
||||
/// fn redo(&mut self, _: &Redo, _window: &mut Window, _cx: &mut ModelContext<Self>) { ... }
|
||||
/// }
|
||||
///
|
||||
/// impl Render for Editor {
|
||||
/// fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
|
||||
/// fn render(&mut self, window: &mut Window, cx: &mut ModelContext<Self>) -> impl IntoElement {
|
||||
/// div()
|
||||
/// .track_focus(&self.focus_handle(cx))
|
||||
/// .keymap_context("Editor")
|
||||
@@ -50,8 +50,8 @@
|
||||
/// KeyBinding::new("cmd-k left", pane::SplitLeft, Some("Pane"))
|
||||
///
|
||||
use crate::{
|
||||
Action, ActionRegistry, DispatchPhase, EntityId, FocusId, KeyBinding, KeyContext, Keymap,
|
||||
Keystroke, ModifiersChangedEvent, WindowContext,
|
||||
Action, ActionRegistry, App, DispatchPhase, EntityId, FocusId, KeyBinding, KeyContext, Keymap,
|
||||
Keystroke, ModifiersChangedEvent, Window,
|
||||
};
|
||||
use collections::FxHashMap;
|
||||
use smallvec::SmallVec;
|
||||
@@ -123,13 +123,13 @@ pub(crate) struct DispatchResult {
|
||||
pub(crate) to_replay: SmallVec<[Replay; 1]>,
|
||||
}
|
||||
|
||||
type KeyListener = Rc<dyn Fn(&dyn Any, DispatchPhase, &mut WindowContext)>;
|
||||
type ModifiersChangedListener = Rc<dyn Fn(&ModifiersChangedEvent, &mut WindowContext)>;
|
||||
type KeyListener = Rc<dyn Fn(&dyn Any, DispatchPhase, &mut Window, &mut App)>;
|
||||
type ModifiersChangedListener = Rc<dyn Fn(&ModifiersChangedEvent, &mut Window, &mut App)>;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct DispatchActionListener {
|
||||
pub(crate) action_type: TypeId,
|
||||
pub(crate) listener: Rc<dyn Fn(&dyn Any, DispatchPhase, &mut WindowContext)>,
|
||||
pub(crate) listener: Rc<dyn Fn(&dyn Any, DispatchPhase, &mut Window, &mut App)>,
|
||||
}
|
||||
|
||||
impl DispatchTree {
|
||||
@@ -333,7 +333,7 @@ impl DispatchTree {
|
||||
pub fn on_action(
|
||||
&mut self,
|
||||
action_type: TypeId,
|
||||
listener: Rc<dyn Fn(&dyn Any, DispatchPhase, &mut WindowContext)>,
|
||||
listener: Rc<dyn Fn(&dyn Any, DispatchPhase, &mut Window, &mut App)>,
|
||||
) {
|
||||
self.active_node()
|
||||
.action_listeners
|
||||
|
||||
+45
-26
@@ -27,11 +27,11 @@ mod test;
|
||||
mod windows;
|
||||
|
||||
use crate::{
|
||||
point, Action, AnyWindowHandle, AsyncWindowContext, BackgroundExecutor, Bounds, DevicePixels,
|
||||
DispatchEventResult, Font, FontId, FontMetrics, FontRun, ForegroundExecutor, GlyphId, GpuSpecs,
|
||||
ImageSource, Keymap, LineLayout, Pixels, PlatformInput, Point, RenderGlyphParams, RenderImage,
|
||||
RenderImageParams, RenderSvgParams, ScaledPixels, Scene, SharedString, Size, SvgRenderer,
|
||||
SvgSize, Task, TaskLabel, WindowContext, DEFAULT_WINDOW_SIZE,
|
||||
point, Action, AnyWindowHandle, App, AsyncWindowContext, BackgroundExecutor, Bounds,
|
||||
DevicePixels, DispatchEventResult, Font, FontId, FontMetrics, FontRun, ForegroundExecutor,
|
||||
GlyphId, GpuSpecs, ImageSource, Keymap, LineLayout, Pixels, PlatformInput, Point,
|
||||
RenderGlyphParams, RenderImage, RenderImageParams, RenderSvgParams, ScaledPixels, Scene,
|
||||
SharedString, Size, SvgRenderer, SvgSize, Task, TaskLabel, Window, DEFAULT_WINDOW_SIZE,
|
||||
};
|
||||
use anyhow::{anyhow, Result};
|
||||
use async_task::Runnable;
|
||||
@@ -697,14 +697,17 @@ impl PlatformInputHandler {
|
||||
|
||||
fn selected_text_range(&mut self, ignore_disabled_input: bool) -> Option<UTF16Selection> {
|
||||
self.cx
|
||||
.update(|cx| self.handler.selected_text_range(ignore_disabled_input, cx))
|
||||
.update(|window, cx| {
|
||||
self.handler
|
||||
.selected_text_range(ignore_disabled_input, window, cx)
|
||||
})
|
||||
.ok()
|
||||
.flatten()
|
||||
}
|
||||
|
||||
fn marked_text_range(&mut self) -> Option<Range<usize>> {
|
||||
self.cx
|
||||
.update(|cx| self.handler.marked_text_range(cx))
|
||||
.update(|window, cx| self.handler.marked_text_range(window, cx))
|
||||
.ok()
|
||||
.flatten()
|
||||
}
|
||||
@@ -716,16 +719,19 @@ impl PlatformInputHandler {
|
||||
adjusted: &mut Option<Range<usize>>,
|
||||
) -> Option<String> {
|
||||
self.cx
|
||||
.update(|cx| self.handler.text_for_range(range_utf16, adjusted, cx))
|
||||
.update(|window, cx| {
|
||||
self.handler
|
||||
.text_for_range(range_utf16, adjusted, window, cx)
|
||||
})
|
||||
.ok()
|
||||
.flatten()
|
||||
}
|
||||
|
||||
fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str) {
|
||||
self.cx
|
||||
.update(|cx| {
|
||||
.update(|window, cx| {
|
||||
self.handler
|
||||
.replace_text_in_range(replacement_range, text, cx);
|
||||
.replace_text_in_range(replacement_range, text, window, cx);
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
@@ -737,11 +743,12 @@ impl PlatformInputHandler {
|
||||
new_selected_range: Option<Range<usize>>,
|
||||
) {
|
||||
self.cx
|
||||
.update(|cx| {
|
||||
.update(|window, cx| {
|
||||
self.handler.replace_and_mark_text_in_range(
|
||||
range_utf16,
|
||||
new_text,
|
||||
new_selected_range,
|
||||
window,
|
||||
cx,
|
||||
)
|
||||
})
|
||||
@@ -749,12 +756,14 @@ impl PlatformInputHandler {
|
||||
}
|
||||
|
||||
fn unmark_text(&mut self) {
|
||||
self.cx.update(|cx| self.handler.unmark_text(cx)).ok();
|
||||
self.cx
|
||||
.update(|window, cx| self.handler.unmark_text(window, cx))
|
||||
.ok();
|
||||
}
|
||||
|
||||
fn bounds_for_range(&mut self, range_utf16: Range<usize>) -> Option<Bounds<Pixels>> {
|
||||
self.cx
|
||||
.update(|cx| self.handler.bounds_for_range(range_utf16, cx))
|
||||
.update(|window, cx| self.handler.bounds_for_range(range_utf16, window, cx))
|
||||
.ok()
|
||||
.flatten()
|
||||
}
|
||||
@@ -764,18 +773,19 @@ impl PlatformInputHandler {
|
||||
self.handler.apple_press_and_hold_enabled()
|
||||
}
|
||||
|
||||
pub(crate) fn dispatch_input(&mut self, input: &str, cx: &mut WindowContext) {
|
||||
self.handler.replace_text_in_range(None, input, cx);
|
||||
pub(crate) fn dispatch_input(&mut self, input: &str, window: &mut Window, cx: &mut App) {
|
||||
self.handler.replace_text_in_range(None, input, window, cx);
|
||||
}
|
||||
|
||||
pub fn selected_bounds(&mut self, cx: &mut WindowContext) -> Option<Bounds<Pixels>> {
|
||||
let selection = self.handler.selected_text_range(true, cx)?;
|
||||
pub fn selected_bounds(&mut self, window: &mut Window, cx: &mut App) -> Option<Bounds<Pixels>> {
|
||||
let selection = self.handler.selected_text_range(true, window, cx)?;
|
||||
self.handler.bounds_for_range(
|
||||
if selection.reversed {
|
||||
selection.range.start..selection.range.start
|
||||
} else {
|
||||
selection.range.end..selection.range.end
|
||||
},
|
||||
window,
|
||||
cx,
|
||||
)
|
||||
}
|
||||
@@ -805,14 +815,15 @@ pub trait InputHandler: 'static {
|
||||
fn selected_text_range(
|
||||
&mut self,
|
||||
ignore_disabled_input: bool,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> Option<UTF16Selection>;
|
||||
|
||||
/// Get the range of the currently marked text, if any
|
||||
/// Corresponds to [markedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438250-markedrange)
|
||||
///
|
||||
/// Return value is in terms of UTF-16 characters, from 0 to the length of the document
|
||||
fn marked_text_range(&mut self, cx: &mut WindowContext) -> Option<Range<usize>>;
|
||||
fn marked_text_range(&mut self, window: &mut Window, cx: &mut App) -> Option<Range<usize>>;
|
||||
|
||||
/// Get the text for the given document range in UTF-16 characters
|
||||
/// Corresponds to [attributedSubstring(forProposedRange: actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438238-attributedsubstring)
|
||||
@@ -822,7 +833,8 @@ pub trait InputHandler: 'static {
|
||||
&mut self,
|
||||
range_utf16: Range<usize>,
|
||||
adjusted_range: &mut Option<Range<usize>>,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> Option<String>;
|
||||
|
||||
/// Replace the text in the given document range with the given text
|
||||
@@ -833,7 +845,8 @@ pub trait InputHandler: 'static {
|
||||
&mut self,
|
||||
replacement_range: Option<Range<usize>>,
|
||||
text: &str,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
);
|
||||
|
||||
/// Replace the text in the given document range with the given text,
|
||||
@@ -847,12 +860,13 @@ pub trait InputHandler: 'static {
|
||||
range_utf16: Option<Range<usize>>,
|
||||
new_text: &str,
|
||||
new_selected_range: Option<Range<usize>>,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
);
|
||||
|
||||
/// Remove the IME 'composing' state from the document
|
||||
/// Corresponds to [unmarkText()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438239-unmarktext)
|
||||
fn unmark_text(&mut self, cx: &mut WindowContext);
|
||||
fn unmark_text(&mut self, window: &mut Window, cx: &mut App);
|
||||
|
||||
/// Get the bounds of the given document range in screen coordinates
|
||||
/// Corresponds to [firstRect(forCharacterRange:actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438240-firstrect)
|
||||
@@ -861,7 +875,8 @@ pub trait InputHandler: 'static {
|
||||
fn bounds_for_range(
|
||||
&mut self,
|
||||
range_utf16: Range<usize>,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> Option<Bounds<Pixels>>;
|
||||
|
||||
/// Allows a given input context to opt into getting raw key repeats instead of
|
||||
@@ -1336,9 +1351,13 @@ impl Image {
|
||||
}
|
||||
|
||||
/// Use the GPUI `use_asset` API to make this image renderable
|
||||
pub fn use_render_image(self: Arc<Self>, cx: &mut WindowContext) -> Option<Arc<RenderImage>> {
|
||||
pub fn use_render_image(
|
||||
self: Arc<Self>,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> Option<Arc<RenderImage>> {
|
||||
ImageSource::Image(self)
|
||||
.use_data(cx)
|
||||
.use_data(window, cx)
|
||||
.and_then(|result| result.ok())
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::{Action, AppContext, Platform, SharedString};
|
||||
use crate::{Action, App, Platform, SharedString};
|
||||
use util::ResultExt;
|
||||
|
||||
/// A menu of the application, either a main menu or a submenu
|
||||
@@ -171,7 +171,7 @@ pub enum OsAction {
|
||||
Redo,
|
||||
}
|
||||
|
||||
pub(crate) fn init_app_menus(platform: &dyn Platform, cx: &AppContext) {
|
||||
pub(crate) fn init_app_menus(platform: &dyn Platform, cx: &App) {
|
||||
platform.on_will_open_app_menu(Box::new({
|
||||
let cx = cx.to_async();
|
||||
move || {
|
||||
|
||||
@@ -3,7 +3,7 @@ use crate::{
|
||||
FontWeight, GlyphId, LineLayout, Pixels, PlatformTextSystem, Point, RenderGlyphParams,
|
||||
ShapedGlyph, SharedString, Size, SUBPIXEL_VARIANTS,
|
||||
};
|
||||
use anyhow::{anyhow, Context, Ok, Result};
|
||||
use anyhow::{anyhow, Context as _, Ok, Result};
|
||||
use collections::HashMap;
|
||||
use cosmic_text::{
|
||||
Attrs, AttrsList, CacheKey, Family, Font as CosmicTextFont, FontSystem, ShapeBuffer, ShapeLine,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use anyhow::{anyhow, Context};
|
||||
use anyhow::{anyhow, Context as _};
|
||||
|
||||
use crate::platform::blade::{BladeContext, BladeRenderer, BladeSurfaceConfig};
|
||||
use crate::{
|
||||
|
||||
@@ -3,7 +3,7 @@ use std::{
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Context as _;
|
||||
use async_task::Runnable;
|
||||
use flume::Sender;
|
||||
use parking::Parker;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use std::rc::Rc;
|
||||
|
||||
use ::util::ResultExt;
|
||||
use anyhow::Context;
|
||||
use anyhow::Context as _;
|
||||
use windows::Win32::{
|
||||
Foundation::*,
|
||||
Graphics::Gdi::*,
|
||||
|
||||
@@ -7,7 +7,7 @@ use std::{
|
||||
};
|
||||
|
||||
use ::util::{paths::SanitizedPath, ResultExt};
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use anyhow::{anyhow, Context as _, Result};
|
||||
use async_task::Runnable;
|
||||
use futures::channel::oneshot::{self, Receiver};
|
||||
use itertools::Itertools;
|
||||
|
||||
@@ -11,7 +11,7 @@ use std::{
|
||||
};
|
||||
|
||||
use ::util::ResultExt;
|
||||
use anyhow::{Context, Result};
|
||||
use anyhow::{Context as _, Result};
|
||||
use async_task::Runnable;
|
||||
use futures::channel::oneshot::{self, Receiver};
|
||||
use itertools::Itertools;
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//! application to avoid having to import each trait individually.
|
||||
|
||||
pub use crate::{
|
||||
util::FluentBuilder, BorrowAppContext, BorrowWindow, Context as _, Element, FocusableElement,
|
||||
util::FluentBuilder, AppContext as _, BorrowAppContext, Context, Element, FocusableElement,
|
||||
InteractiveElement, IntoElement, ParentElement, Refineable, Render, RenderOnce,
|
||||
StatefulInteractiveElement, Styled, StyledImage, VisualContext,
|
||||
};
|
||||
|
||||
+21
-20
@@ -5,11 +5,11 @@ use std::{
|
||||
};
|
||||
|
||||
use crate::{
|
||||
black, phi, point, quad, rems, size, AbsoluteLength, Background, BackgroundTag, Bounds,
|
||||
black, phi, point, quad, rems, size, AbsoluteLength, App, Background, BackgroundTag, Bounds,
|
||||
ContentMask, Corners, CornersRefinement, CursorStyle, DefiniteLength, DevicePixels, Edges,
|
||||
EdgesRefinement, Font, FontFallbacks, FontFeatures, FontStyle, FontWeight, Hsla, Length,
|
||||
Pixels, Point, PointRefinement, Rgba, SharedString, Size, SizeRefinement, Styled, TextRun,
|
||||
WindowContext,
|
||||
Window,
|
||||
};
|
||||
use collections::HashSet;
|
||||
use refineable::Refineable;
|
||||
@@ -550,8 +550,9 @@ impl Style {
|
||||
pub fn paint(
|
||||
&self,
|
||||
bounds: Bounds<Pixels>,
|
||||
cx: &mut WindowContext,
|
||||
continuation: impl FnOnce(&mut WindowContext),
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
continuation: impl FnOnce(&mut Window, &mut App),
|
||||
) {
|
||||
#[cfg(debug_assertions)]
|
||||
if self.debug_below {
|
||||
@@ -560,12 +561,12 @@ impl Style {
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
if self.debug || cx.has_global::<DebugBelow>() {
|
||||
cx.paint_quad(crate::outline(bounds, crate::red()));
|
||||
window.paint_quad(crate::outline(bounds, crate::red()));
|
||||
}
|
||||
|
||||
let rem_size = cx.rem_size();
|
||||
let rem_size = window.rem_size();
|
||||
|
||||
cx.paint_shadows(
|
||||
window.paint_shadows(
|
||||
bounds,
|
||||
self.corner_radii.to_pixels(bounds.size, rem_size),
|
||||
&self.box_shadow,
|
||||
@@ -585,7 +586,7 @@ impl Style {
|
||||
None => Hsla::default(),
|
||||
};
|
||||
border_color.a = 0.;
|
||||
cx.paint_quad(quad(
|
||||
window.paint_quad(quad(
|
||||
bounds,
|
||||
self.corner_radii.to_pixels(bounds.size, rem_size),
|
||||
background_color.unwrap_or_default(),
|
||||
@@ -594,7 +595,7 @@ impl Style {
|
||||
));
|
||||
}
|
||||
|
||||
continuation(cx);
|
||||
continuation(window, cx);
|
||||
|
||||
if self.is_border_visible() {
|
||||
let corner_radii = self.corner_radii.to_pixels(bounds.size, rem_size);
|
||||
@@ -629,31 +630,31 @@ impl Style {
|
||||
self.border_color.unwrap_or_default(),
|
||||
);
|
||||
|
||||
cx.with_content_mask(Some(ContentMask { bounds: top_bounds }), |cx| {
|
||||
cx.paint_quad(quad.clone());
|
||||
window.with_content_mask(Some(ContentMask { bounds: top_bounds }), |window| {
|
||||
window.paint_quad(quad.clone());
|
||||
});
|
||||
cx.with_content_mask(
|
||||
window.with_content_mask(
|
||||
Some(ContentMask {
|
||||
bounds: right_bounds,
|
||||
}),
|
||||
|cx| {
|
||||
cx.paint_quad(quad.clone());
|
||||
|window| {
|
||||
window.paint_quad(quad.clone());
|
||||
},
|
||||
);
|
||||
cx.with_content_mask(
|
||||
window.with_content_mask(
|
||||
Some(ContentMask {
|
||||
bounds: bottom_bounds,
|
||||
}),
|
||||
|cx| {
|
||||
cx.paint_quad(quad.clone());
|
||||
|window| {
|
||||
window.paint_quad(quad.clone());
|
||||
},
|
||||
);
|
||||
cx.with_content_mask(
|
||||
window.with_content_mask(
|
||||
Some(ContentMask {
|
||||
bounds: left_bounds,
|
||||
}),
|
||||
|cx| {
|
||||
cx.paint_quad(quad);
|
||||
|window| {
|
||||
window.paint_quad(quad);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
use crate::{
|
||||
AbsoluteLength, Bounds, DefiniteLength, Edges, Length, Pixels, Point, Size, Style,
|
||||
WindowContext,
|
||||
AbsoluteLength, App, Bounds, DefiniteLength, Edges, Length, Pixels, Point, Size, Style, Window,
|
||||
};
|
||||
use collections::{FxHashMap, FxHashSet};
|
||||
use smallvec::SmallVec;
|
||||
@@ -12,8 +11,9 @@ use taffy::{
|
||||
TaffyTree, TraversePartialTree as _,
|
||||
};
|
||||
|
||||
type NodeMeasureFn =
|
||||
Box<dyn FnMut(Size<Option<Pixels>>, Size<AvailableSpace>, &mut WindowContext) -> Size<Pixels>>;
|
||||
type NodeMeasureFn = Box<
|
||||
dyn FnMut(Size<Option<Pixels>>, Size<AvailableSpace>, &mut Window, &mut App) -> Size<Pixels>,
|
||||
>;
|
||||
|
||||
struct NodeContext {
|
||||
measure: NodeMeasureFn,
|
||||
@@ -71,7 +71,7 @@ impl TaffyLayoutEngine {
|
||||
&mut self,
|
||||
style: Style,
|
||||
rem_size: Pixels,
|
||||
measure: impl FnMut(Size<Option<Pixels>>, Size<AvailableSpace>, &mut WindowContext) -> Size<Pixels>
|
||||
measure: impl FnMut(Size<Option<Pixels>>, Size<AvailableSpace>, &mut Window, &mut App) -> Size<Pixels>
|
||||
+ 'static,
|
||||
) -> LayoutId {
|
||||
let taffy_style = style.to_taffy(rem_size);
|
||||
@@ -140,7 +140,8 @@ impl TaffyLayoutEngine {
|
||||
&mut self,
|
||||
id: LayoutId,
|
||||
available_space: Size<AvailableSpace>,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) {
|
||||
// Leaving this here until we have a better instrumentation approach.
|
||||
// println!("Laying out {} children", self.count_all_children(id)?);
|
||||
@@ -184,7 +185,8 @@ impl TaffyLayoutEngine {
|
||||
height: known_dimensions.height.map(Pixels),
|
||||
};
|
||||
|
||||
(node_context.measure)(known_dimensions, available_space.into(), cx).into()
|
||||
(node_context.measure)(known_dimensions, available_space.into(), window, cx)
|
||||
.into()
|
||||
},
|
||||
)
|
||||
.expect(EXPECT_MESSAGE);
|
||||
|
||||
@@ -102,7 +102,7 @@ impl<T: 'static> futures::Stream for Observation<T> {
|
||||
}
|
||||
|
||||
/// observe returns a stream of the change events from the given `View` or `Model`
|
||||
pub fn observe<T: 'static>(entity: &impl Entity<T>, cx: &mut TestAppContext) -> Observation<()> {
|
||||
pub fn observe<T: 'static>(entity: &Entity<T>, cx: &mut TestAppContext) -> Observation<()> {
|
||||
let (tx, rx) = smol::channel::unbounded();
|
||||
let _subscription = cx.update(|cx| {
|
||||
cx.observe(entity, move |_, _| {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
use crate::{
|
||||
black, fill, point, px, size, Bounds, Half, Hsla, LineLayout, Pixels, Point, Result,
|
||||
SharedString, StrikethroughStyle, UnderlineStyle, WindowContext, WrapBoundary,
|
||||
WrappedLineLayout,
|
||||
black, fill, point, px, size, App, Bounds, Half, Hsla, LineLayout, Pixels, Point, Result,
|
||||
SharedString, StrikethroughStyle, UnderlineStyle, Window, WrapBoundary, WrappedLineLayout,
|
||||
};
|
||||
use derive_more::{Deref, DerefMut};
|
||||
use smallvec::SmallVec;
|
||||
@@ -64,7 +63,8 @@ impl ShapedLine {
|
||||
&self,
|
||||
origin: Point<Pixels>,
|
||||
line_height: Pixels,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> Result<()> {
|
||||
paint_line(
|
||||
origin,
|
||||
@@ -72,6 +72,7 @@ impl ShapedLine {
|
||||
line_height,
|
||||
&self.decoration_runs,
|
||||
&[],
|
||||
window,
|
||||
cx,
|
||||
)?;
|
||||
|
||||
@@ -102,7 +103,8 @@ impl WrappedLine {
|
||||
&self,
|
||||
origin: Point<Pixels>,
|
||||
line_height: Pixels,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> Result<()> {
|
||||
paint_line(
|
||||
origin,
|
||||
@@ -110,6 +112,7 @@ impl WrappedLine {
|
||||
line_height,
|
||||
&self.decoration_runs,
|
||||
&self.wrap_boundaries,
|
||||
window,
|
||||
cx,
|
||||
)?;
|
||||
|
||||
@@ -123,7 +126,8 @@ fn paint_line(
|
||||
line_height: Pixels,
|
||||
decoration_runs: &[DecorationRun],
|
||||
wrap_boundaries: &[WrapBoundary],
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> Result<()> {
|
||||
let line_bounds = Bounds::new(
|
||||
origin,
|
||||
@@ -132,7 +136,7 @@ fn paint_line(
|
||||
line_height * (wrap_boundaries.len() as f32 + 1.),
|
||||
),
|
||||
);
|
||||
cx.paint_layer(line_bounds, |cx| {
|
||||
window.paint_layer(line_bounds, |window| {
|
||||
let padding_top = (line_height - layout.ascent - layout.descent) / 2.;
|
||||
let baseline_offset = point(px(0.), padding_top + layout.ascent);
|
||||
let mut decoration_runs = decoration_runs.iter();
|
||||
@@ -159,7 +163,7 @@ fn paint_line(
|
||||
if glyph_origin.x == background_origin.x {
|
||||
background_origin.x -= max_glyph_size.width.half()
|
||||
}
|
||||
cx.paint_quad(fill(
|
||||
window.paint_quad(fill(
|
||||
Bounds {
|
||||
origin: *background_origin,
|
||||
size: size(glyph_origin.x - background_origin.x, line_height),
|
||||
@@ -173,7 +177,7 @@ fn paint_line(
|
||||
if glyph_origin.x == underline_origin.x {
|
||||
underline_origin.x -= max_glyph_size.width.half();
|
||||
};
|
||||
cx.paint_underline(
|
||||
window.paint_underline(
|
||||
*underline_origin,
|
||||
glyph_origin.x - underline_origin.x,
|
||||
underline_style,
|
||||
@@ -187,7 +191,7 @@ fn paint_line(
|
||||
if glyph_origin.x == strikethrough_origin.x {
|
||||
strikethrough_origin.x -= max_glyph_size.width.half();
|
||||
};
|
||||
cx.paint_strikethrough(
|
||||
window.paint_strikethrough(
|
||||
*strikethrough_origin,
|
||||
glyph_origin.x - strikethrough_origin.x,
|
||||
strikethrough_style,
|
||||
@@ -281,7 +285,7 @@ fn paint_line(
|
||||
if background_origin.x == glyph_origin.x {
|
||||
background_origin.x -= max_glyph_size.width.half();
|
||||
};
|
||||
cx.paint_quad(fill(
|
||||
window.paint_quad(fill(
|
||||
Bounds {
|
||||
origin: background_origin,
|
||||
size: size(width, line_height),
|
||||
@@ -294,7 +298,7 @@ fn paint_line(
|
||||
if underline_origin.x == glyph_origin.x {
|
||||
underline_origin.x -= max_glyph_size.width.half();
|
||||
};
|
||||
cx.paint_underline(
|
||||
window.paint_underline(
|
||||
underline_origin,
|
||||
glyph_origin.x - underline_origin.x,
|
||||
&underline_style,
|
||||
@@ -307,7 +311,7 @@ fn paint_line(
|
||||
if strikethrough_origin.x == glyph_origin.x {
|
||||
strikethrough_origin.x -= max_glyph_size.width.half();
|
||||
};
|
||||
cx.paint_strikethrough(
|
||||
window.paint_strikethrough(
|
||||
strikethrough_origin,
|
||||
glyph_origin.x - strikethrough_origin.x,
|
||||
&strikethrough_style,
|
||||
@@ -319,17 +323,17 @@ fn paint_line(
|
||||
size: max_glyph_size,
|
||||
};
|
||||
|
||||
let content_mask = cx.content_mask();
|
||||
let content_mask = window.content_mask();
|
||||
if max_glyph_bounds.intersects(&content_mask.bounds) {
|
||||
if glyph.is_emoji {
|
||||
cx.paint_emoji(
|
||||
window.paint_emoji(
|
||||
glyph_origin + baseline_offset,
|
||||
run.font_id,
|
||||
glyph.id,
|
||||
layout.font_size,
|
||||
)?;
|
||||
} else {
|
||||
cx.paint_glyph(
|
||||
window.paint_glyph(
|
||||
glyph_origin + baseline_offset,
|
||||
run.font_id,
|
||||
glyph.id,
|
||||
@@ -352,7 +356,7 @@ fn paint_line(
|
||||
if last_line_end_x == background_origin.x {
|
||||
background_origin.x -= max_glyph_size.width.half()
|
||||
};
|
||||
cx.paint_quad(fill(
|
||||
window.paint_quad(fill(
|
||||
Bounds {
|
||||
origin: background_origin,
|
||||
size: size(last_line_end_x - background_origin.x, line_height),
|
||||
@@ -365,7 +369,7 @@ fn paint_line(
|
||||
if last_line_end_x == underline_start.x {
|
||||
underline_start.x -= max_glyph_size.width.half()
|
||||
};
|
||||
cx.paint_underline(
|
||||
window.paint_underline(
|
||||
underline_start,
|
||||
last_line_end_x - underline_start.x,
|
||||
&underline_style,
|
||||
@@ -376,7 +380,7 @@ fn paint_line(
|
||||
if last_line_end_x == strikethrough_start.x {
|
||||
strikethrough_start.x -= max_glyph_size.width.half()
|
||||
};
|
||||
cx.paint_strikethrough(
|
||||
window.paint_strikethrough(
|
||||
strikethrough_start,
|
||||
last_line_end_x - strikethrough_start.x,
|
||||
&strikethrough_style,
|
||||
|
||||
+121
-258
@@ -1,33 +1,20 @@
|
||||
use crate::Empty;
|
||||
use crate::{
|
||||
seal::Sealed, AnyElement, AnyModel, AnyWeakModel, AppContext, Bounds, ContentMask, Element,
|
||||
ElementId, Entity, EntityId, Flatten, FocusHandle, FocusableView, GlobalElementId, IntoElement,
|
||||
LayoutId, Model, PaintIndex, Pixels, PrepaintStateIndex, Render, Style, StyleRefinement,
|
||||
TextStyle, ViewContext, VisualContext, WeakModel, WindowContext,
|
||||
AnyElement, AnyEntity, AnyWeakEntity, App, Bounds, ContentMask, Context, Element, ElementId,
|
||||
Entity, EntityId, GlobalElementId, IntoElement, LayoutId, PaintIndex, Pixels,
|
||||
PrepaintStateIndex, Render, Style, StyleRefinement, TextStyle, WeakEntity,
|
||||
};
|
||||
use anyhow::{Context, Result};
|
||||
use crate::{Empty, Window};
|
||||
use anyhow::Result;
|
||||
use collections::FxHashSet;
|
||||
use refineable::Refineable;
|
||||
use std::mem;
|
||||
use std::{
|
||||
any::{type_name, TypeId},
|
||||
fmt,
|
||||
hash::{Hash, Hasher},
|
||||
ops::Range,
|
||||
};
|
||||
|
||||
/// A view is a piece of state that can be presented on screen by implementing the [Render] trait.
|
||||
/// Views implement [Element] and can composed with other views, and every window is created with a root view.
|
||||
pub struct View<V> {
|
||||
/// A view is just a [Model] whose type implements `Render`, and the model is accessible via this field.
|
||||
pub model: Model<V>,
|
||||
}
|
||||
|
||||
impl<V> Sealed for View<V> {}
|
||||
use std::{any::TypeId, fmt, ops::Range};
|
||||
|
||||
struct AnyViewState {
|
||||
prepaint_range: Range<PrepaintStateIndex>,
|
||||
paint_range: Range<PaintIndex>,
|
||||
cache_key: ViewCacheKey,
|
||||
accessed_entities: FxHashSet<EntityId>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -37,61 +24,7 @@ struct ViewCacheKey {
|
||||
text_style: TextStyle,
|
||||
}
|
||||
|
||||
impl<V: 'static> Entity<V> for View<V> {
|
||||
type Weak = WeakView<V>;
|
||||
|
||||
fn entity_id(&self) -> EntityId {
|
||||
self.model.entity_id
|
||||
}
|
||||
|
||||
fn downgrade(&self) -> Self::Weak {
|
||||
WeakView {
|
||||
model: self.model.downgrade(),
|
||||
}
|
||||
}
|
||||
|
||||
fn upgrade_from(weak: &Self::Weak) -> Option<Self>
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
let model = weak.model.upgrade()?;
|
||||
Some(View { model })
|
||||
}
|
||||
}
|
||||
|
||||
impl<V: 'static> View<V> {
|
||||
/// Convert this strong view reference into a weak view reference.
|
||||
pub fn downgrade(&self) -> WeakView<V> {
|
||||
Entity::downgrade(self)
|
||||
}
|
||||
|
||||
/// Updates the view's state with the given function, which is passed a mutable reference and a context.
|
||||
pub fn update<C, R>(
|
||||
&self,
|
||||
cx: &mut C,
|
||||
f: impl FnOnce(&mut V, &mut ViewContext<V>) -> R,
|
||||
) -> C::Result<R>
|
||||
where
|
||||
C: VisualContext,
|
||||
{
|
||||
cx.update_view(self, f)
|
||||
}
|
||||
|
||||
/// Obtain a read-only reference to this view's state.
|
||||
pub fn read<'a>(&self, cx: &'a AppContext) -> &'a V {
|
||||
self.model.read(cx)
|
||||
}
|
||||
|
||||
/// Gets a [FocusHandle] for this view when its state implements [FocusableView].
|
||||
pub fn focus_handle(&self, cx: &AppContext) -> FocusHandle
|
||||
where
|
||||
V: FocusableView,
|
||||
{
|
||||
self.read(cx).focus_handle(cx)
|
||||
}
|
||||
}
|
||||
|
||||
impl<V: Render> Element for View<V> {
|
||||
impl<V: Render> Element for Entity<V> {
|
||||
type RequestLayoutState = AnyElement;
|
||||
type PrepaintState = ();
|
||||
|
||||
@@ -102,10 +35,11 @@ impl<V: Render> Element for View<V> {
|
||||
fn request_layout(
|
||||
&mut self,
|
||||
_id: Option<&GlobalElementId>,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> (LayoutId, Self::RequestLayoutState) {
|
||||
let mut element = self.update(cx, |view, cx| view.render(cx).into_any_element());
|
||||
let layout_id = element.request_layout(cx);
|
||||
let mut element = self.update(cx, |view, cx| view.render(window, cx).into_any_element());
|
||||
let layout_id = element.request_layout(window, cx);
|
||||
(layout_id, element)
|
||||
}
|
||||
|
||||
@@ -114,10 +48,11 @@ impl<V: Render> Element for View<V> {
|
||||
_id: Option<&GlobalElementId>,
|
||||
_: Bounds<Pixels>,
|
||||
element: &mut Self::RequestLayoutState,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) {
|
||||
cx.set_view_id(self.entity_id());
|
||||
element.prepaint(cx);
|
||||
window.set_view_id(self.entity_id());
|
||||
element.prepaint(window, cx);
|
||||
}
|
||||
|
||||
fn paint(
|
||||
@@ -126,110 +61,31 @@ impl<V: Render> Element for View<V> {
|
||||
_: Bounds<Pixels>,
|
||||
element: &mut Self::RequestLayoutState,
|
||||
_: &mut Self::PrepaintState,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) {
|
||||
element.paint(cx);
|
||||
element.paint(window, cx);
|
||||
}
|
||||
}
|
||||
|
||||
impl<V> Clone for View<V> {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
model: self.model.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> std::fmt::Debug for View<T> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct(&format!("View<{}>", type_name::<T>()))
|
||||
.field("entity_id", &self.model.entity_id)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl<V> Hash for View<V> {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
self.model.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
impl<V> PartialEq for View<V> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.model == other.model
|
||||
}
|
||||
}
|
||||
|
||||
impl<V> Eq for View<V> {}
|
||||
|
||||
/// A weak variant of [View] which does not prevent the view from being released.
|
||||
pub struct WeakView<V> {
|
||||
pub(crate) model: WeakModel<V>,
|
||||
}
|
||||
|
||||
impl<V: 'static> WeakView<V> {
|
||||
/// Gets the entity id associated with this handle.
|
||||
pub fn entity_id(&self) -> EntityId {
|
||||
self.model.entity_id
|
||||
}
|
||||
|
||||
/// Obtain a strong handle for the view if it hasn't been released.
|
||||
pub fn upgrade(&self) -> Option<View<V>> {
|
||||
Entity::upgrade_from(self)
|
||||
}
|
||||
|
||||
/// Updates this view's state if it hasn't been released.
|
||||
/// Returns an error if this view has been released.
|
||||
pub fn update<C, R>(
|
||||
&self,
|
||||
cx: &mut C,
|
||||
f: impl FnOnce(&mut V, &mut ViewContext<V>) -> R,
|
||||
) -> Result<R>
|
||||
where
|
||||
C: VisualContext,
|
||||
Result<C::Result<R>>: Flatten<R>,
|
||||
{
|
||||
let view = self.upgrade().context("error upgrading view")?;
|
||||
Ok(view.update(cx, f)).flatten()
|
||||
}
|
||||
|
||||
/// Assert that the view referenced by this handle has been released.
|
||||
#[cfg(any(test, feature = "test-support"))]
|
||||
pub fn assert_released(&self) {
|
||||
self.model.assert_released()
|
||||
}
|
||||
}
|
||||
|
||||
impl<V> Clone for WeakView<V> {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
model: self.model.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<V> Hash for WeakView<V> {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
self.model.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
impl<V> PartialEq for WeakView<V> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.model == other.model
|
||||
}
|
||||
}
|
||||
|
||||
impl<V> Eq for WeakView<V> {}
|
||||
|
||||
/// A dynamically-typed handle to a view, which can be downcast to a [View] for a specific type.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct AnyView {
|
||||
model: AnyModel,
|
||||
render: fn(&AnyView, &mut WindowContext) -> AnyElement,
|
||||
model: AnyEntity,
|
||||
render: fn(&AnyView, &mut Window, &mut App) -> AnyElement,
|
||||
cached_style: Option<StyleRefinement>,
|
||||
}
|
||||
|
||||
impl<V: Render> From<Entity<V>> for AnyView {
|
||||
fn from(value: Entity<V>) -> Self {
|
||||
AnyView {
|
||||
model: value.into_any(),
|
||||
render: any_view::render::<V>,
|
||||
cached_style: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AnyView {
|
||||
/// Indicate that this view should be cached when using it as an element.
|
||||
/// When using this method, the view's previous layout and paint will be recycled from the previous frame if [ViewContext::notify] has not been called since it was rendered.
|
||||
@@ -249,9 +105,9 @@ impl AnyView {
|
||||
|
||||
/// Convert this to a [View] of a specific type.
|
||||
/// If this handle does not contain a view of the specified type, returns itself in an `Err` variant.
|
||||
pub fn downcast<T: 'static>(self) -> Result<View<T>, Self> {
|
||||
pub fn downcast<T: 'static>(self) -> Result<Entity<T>, Self> {
|
||||
match self.model.downcast() {
|
||||
Ok(model) => Ok(View { model }),
|
||||
Ok(model) => Ok(model),
|
||||
Err(model) => Err(Self {
|
||||
model,
|
||||
render: self.render,
|
||||
@@ -271,16 +127,6 @@ impl AnyView {
|
||||
}
|
||||
}
|
||||
|
||||
impl<V: Render> From<View<V>> for AnyView {
|
||||
fn from(value: View<V>) -> Self {
|
||||
AnyView {
|
||||
model: value.model.into_any(),
|
||||
render: any_view::render::<V>,
|
||||
cached_style: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for AnyView {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.model == other.model
|
||||
@@ -300,16 +146,17 @@ impl Element for AnyView {
|
||||
fn request_layout(
|
||||
&mut self,
|
||||
_id: Option<&GlobalElementId>,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> (LayoutId, Self::RequestLayoutState) {
|
||||
if let Some(style) = self.cached_style.as_ref() {
|
||||
let mut root_style = Style::default();
|
||||
root_style.refine(style);
|
||||
let layout_id = cx.request_layout(root_style, None);
|
||||
let layout_id = window.request_layout(root_style, None, cx);
|
||||
(layout_id, None)
|
||||
} else {
|
||||
let mut element = (self.render)(self, cx);
|
||||
let layout_id = element.request_layout(cx);
|
||||
let mut element = (self.render)(self, window, cx);
|
||||
let layout_id = element.request_layout(window, cx);
|
||||
(layout_id, Some(element))
|
||||
}
|
||||
}
|
||||
@@ -319,53 +166,64 @@ impl Element for AnyView {
|
||||
global_id: Option<&GlobalElementId>,
|
||||
bounds: Bounds<Pixels>,
|
||||
element: &mut Self::RequestLayoutState,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> Option<AnyElement> {
|
||||
cx.set_view_id(self.entity_id());
|
||||
window.set_view_id(self.entity_id());
|
||||
if self.cached_style.is_some() {
|
||||
cx.with_element_state::<AnyViewState, _>(global_id.unwrap(), |element_state, cx| {
|
||||
let content_mask = cx.content_mask();
|
||||
let text_style = cx.text_style();
|
||||
window.with_element_state::<AnyViewState, _>(
|
||||
global_id.unwrap(),
|
||||
|element_state, window| {
|
||||
let content_mask = window.content_mask();
|
||||
let text_style = window.text_style();
|
||||
|
||||
if let Some(mut element_state) = element_state {
|
||||
if element_state.cache_key.bounds == bounds
|
||||
&& element_state.cache_key.content_mask == content_mask
|
||||
&& element_state.cache_key.text_style == text_style
|
||||
&& !cx.window.dirty_views.contains(&self.entity_id())
|
||||
&& !cx.window.refreshing
|
||||
{
|
||||
let prepaint_start = cx.prepaint_index();
|
||||
cx.reuse_prepaint(element_state.prepaint_range.clone());
|
||||
let prepaint_end = cx.prepaint_index();
|
||||
element_state.prepaint_range = prepaint_start..prepaint_end;
|
||||
return (None, element_state);
|
||||
if let Some(mut element_state) = element_state {
|
||||
if element_state.cache_key.bounds == bounds
|
||||
&& element_state.cache_key.content_mask == content_mask
|
||||
&& element_state.cache_key.text_style == text_style
|
||||
&& !window.dirty_views.contains(&self.entity_id())
|
||||
&& !window.refreshing
|
||||
{
|
||||
let prepaint_start = window.prepaint_index();
|
||||
window.reuse_prepaint(element_state.prepaint_range.clone());
|
||||
cx.entities
|
||||
.extend_accessed(&element_state.accessed_entities);
|
||||
let prepaint_end = window.prepaint_index();
|
||||
element_state.prepaint_range = prepaint_start..prepaint_end;
|
||||
|
||||
return (None, element_state);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let refreshing = mem::replace(&mut cx.window.refreshing, true);
|
||||
let prepaint_start = cx.prepaint_index();
|
||||
let mut element = (self.render)(self, cx);
|
||||
element.layout_as_root(bounds.size.into(), cx);
|
||||
element.prepaint_at(bounds.origin, cx);
|
||||
let prepaint_end = cx.prepaint_index();
|
||||
cx.window.refreshing = refreshing;
|
||||
let refreshing = mem::replace(&mut window.refreshing, true);
|
||||
let prepaint_start = window.prepaint_index();
|
||||
let (mut element, accessed_entities) = cx.detect_accessed_entities(|cx| {
|
||||
let mut element = (self.render)(self, window, cx);
|
||||
element.layout_as_root(bounds.size.into(), window, cx);
|
||||
element.prepaint_at(bounds.origin, window, cx);
|
||||
element
|
||||
});
|
||||
let prepaint_end = window.prepaint_index();
|
||||
window.refreshing = refreshing;
|
||||
|
||||
(
|
||||
Some(element),
|
||||
AnyViewState {
|
||||
prepaint_range: prepaint_start..prepaint_end,
|
||||
paint_range: PaintIndex::default()..PaintIndex::default(),
|
||||
cache_key: ViewCacheKey {
|
||||
bounds,
|
||||
content_mask,
|
||||
text_style,
|
||||
(
|
||||
Some(element),
|
||||
AnyViewState {
|
||||
accessed_entities,
|
||||
prepaint_range: prepaint_start..prepaint_end,
|
||||
paint_range: PaintIndex::default()..PaintIndex::default(),
|
||||
cache_key: ViewCacheKey {
|
||||
bounds,
|
||||
content_mask,
|
||||
text_style,
|
||||
},
|
||||
},
|
||||
},
|
||||
)
|
||||
})
|
||||
)
|
||||
},
|
||||
)
|
||||
} else {
|
||||
let mut element = element.take().unwrap();
|
||||
element.prepaint(cx);
|
||||
element.prepaint(window, cx);
|
||||
Some(element)
|
||||
}
|
||||
}
|
||||
@@ -376,35 +234,39 @@ impl Element for AnyView {
|
||||
_bounds: Bounds<Pixels>,
|
||||
_: &mut Self::RequestLayoutState,
|
||||
element: &mut Self::PrepaintState,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) {
|
||||
if self.cached_style.is_some() {
|
||||
cx.with_element_state::<AnyViewState, _>(global_id.unwrap(), |element_state, cx| {
|
||||
let mut element_state = element_state.unwrap();
|
||||
window.with_element_state::<AnyViewState, _>(
|
||||
global_id.unwrap(),
|
||||
|element_state, window| {
|
||||
let mut element_state = element_state.unwrap();
|
||||
|
||||
let paint_start = cx.paint_index();
|
||||
let paint_start = window.paint_index();
|
||||
|
||||
if let Some(element) = element {
|
||||
let refreshing = mem::replace(&mut cx.window.refreshing, true);
|
||||
element.paint(cx);
|
||||
cx.window.refreshing = refreshing;
|
||||
} else {
|
||||
cx.reuse_paint(element_state.paint_range.clone());
|
||||
}
|
||||
if let Some(element) = element {
|
||||
let refreshing = mem::replace(&mut window.refreshing, true);
|
||||
element.paint(window, cx);
|
||||
window.refreshing = refreshing;
|
||||
} else {
|
||||
window.reuse_paint(element_state.paint_range.clone());
|
||||
}
|
||||
|
||||
let paint_end = cx.paint_index();
|
||||
element_state.paint_range = paint_start..paint_end;
|
||||
let paint_end = window.paint_index();
|
||||
element_state.paint_range = paint_start..paint_end;
|
||||
|
||||
((), element_state)
|
||||
})
|
||||
((), element_state)
|
||||
},
|
||||
)
|
||||
} else {
|
||||
element.as_mut().unwrap().paint(cx);
|
||||
element.as_mut().unwrap().paint(window, cx);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<V: 'static + Render> IntoElement for View<V> {
|
||||
type Element = View<V>;
|
||||
impl<V: 'static + Render> IntoElement for Entity<V> {
|
||||
type Element = Entity<V>;
|
||||
|
||||
fn into_element(self) -> Self::Element {
|
||||
self
|
||||
@@ -421,8 +283,8 @@ impl IntoElement for AnyView {
|
||||
|
||||
/// A weak, dynamically-typed view handle that does not prevent the view from being released.
|
||||
pub struct AnyWeakView {
|
||||
model: AnyWeakModel,
|
||||
render: fn(&AnyView, &mut WindowContext) -> AnyElement,
|
||||
model: AnyWeakEntity,
|
||||
render: fn(&AnyView, &mut Window, &mut App) -> AnyElement,
|
||||
}
|
||||
|
||||
impl AnyWeakView {
|
||||
@@ -437,10 +299,10 @@ impl AnyWeakView {
|
||||
}
|
||||
}
|
||||
|
||||
impl<V: 'static + Render> From<WeakView<V>> for AnyWeakView {
|
||||
fn from(view: WeakView<V>) -> Self {
|
||||
Self {
|
||||
model: view.model.into(),
|
||||
impl<V: 'static + Render> From<WeakEntity<V>> for AnyWeakView {
|
||||
fn from(view: WeakEntity<V>) -> Self {
|
||||
AnyWeakView {
|
||||
model: view.into(),
|
||||
render: any_view::render::<V>,
|
||||
}
|
||||
}
|
||||
@@ -461,14 +323,15 @@ impl std::fmt::Debug for AnyWeakView {
|
||||
}
|
||||
|
||||
mod any_view {
|
||||
use crate::{AnyElement, AnyView, IntoElement, Render, WindowContext};
|
||||
use crate::{AnyElement, AnyView, App, IntoElement, Render, Window};
|
||||
|
||||
pub(crate) fn render<V: 'static + Render>(
|
||||
view: &AnyView,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> AnyElement {
|
||||
let view = view.clone().downcast::<V>().unwrap();
|
||||
view.update(cx, |view, cx| view.render(cx).into_any_element())
|
||||
view.update(cx, |view, cx| view.render(window, cx).into_any_element())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -476,7 +339,7 @@ mod any_view {
|
||||
pub struct EmptyView;
|
||||
|
||||
impl Render for EmptyView {
|
||||
fn render(&mut self, _cx: &mut ViewContext<Self>) -> impl IntoElement {
|
||||
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
|
||||
Empty
|
||||
}
|
||||
}
|
||||
|
||||
+955
-1889
File diff suppressed because it is too large
Load Diff
@@ -3,20 +3,22 @@ use std::ops::Deref;
|
||||
use futures::channel::oneshot;
|
||||
|
||||
use crate::{
|
||||
div, opaque_grey, white, AnyView, EventEmitter, FocusHandle, FocusableView, InteractiveElement,
|
||||
IntoElement, ParentElement, PromptLevel, Render, StatefulInteractiveElement, Styled, View,
|
||||
ViewContext, VisualContext, WindowContext,
|
||||
div, opaque_grey, white, AnyView, App, AppContext as _, Context, Entity, EventEmitter,
|
||||
FocusHandle, Focusable, InteractiveElement, IntoElement, ParentElement, PromptLevel, Render,
|
||||
StatefulInteractiveElement, Styled,
|
||||
};
|
||||
|
||||
use super::Window;
|
||||
|
||||
/// The event emitted when a prompt's option is selected.
|
||||
/// The usize is the index of the selected option, from the actions
|
||||
/// passed to the prompt.
|
||||
pub struct PromptResponse(pub usize);
|
||||
|
||||
/// A prompt that can be rendered in the window.
|
||||
pub trait Prompt: EventEmitter<PromptResponse> + FocusableView {}
|
||||
pub trait Prompt: EventEmitter<PromptResponse> + Focusable {}
|
||||
|
||||
impl<V: EventEmitter<PromptResponse> + FocusableView> Prompt for V {}
|
||||
impl<V: EventEmitter<PromptResponse> + Focusable> Prompt for V {}
|
||||
|
||||
/// A handle to a prompt that can be used to interact with it.
|
||||
pub struct PromptHandle {
|
||||
@@ -29,25 +31,31 @@ impl PromptHandle {
|
||||
}
|
||||
|
||||
/// Construct a new prompt handle from a view of the appropriate types
|
||||
pub fn with_view<V: Prompt>(
|
||||
pub fn with_view<V: Prompt + Render>(
|
||||
self,
|
||||
view: View<V>,
|
||||
cx: &mut WindowContext,
|
||||
view: Entity<V>,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> RenderablePromptHandle {
|
||||
let mut sender = Some(self.sender);
|
||||
let previous_focus = cx.focused();
|
||||
cx.subscribe(&view, move |_, e: &PromptResponse, cx| {
|
||||
let previous_focus = window.focused(cx);
|
||||
let window_handle = window.window_handle();
|
||||
cx.subscribe(&view, move |_: Entity<V>, e: &PromptResponse, cx| {
|
||||
if let Some(sender) = sender.take() {
|
||||
sender.send(e.0).ok();
|
||||
cx.window.prompt.take();
|
||||
if let Some(previous_focus) = &previous_focus {
|
||||
cx.focus(previous_focus);
|
||||
}
|
||||
window_handle
|
||||
.update(cx, |_, window, _cx| {
|
||||
window.prompt.take();
|
||||
if let Some(previous_focus) = &previous_focus {
|
||||
window.focus(previous_focus);
|
||||
}
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
|
||||
cx.focus_view(&view);
|
||||
window.focus(&view.focus_handle(cx));
|
||||
|
||||
RenderablePromptHandle {
|
||||
view: Box::new(view),
|
||||
@@ -68,19 +76,18 @@ pub fn fallback_prompt_renderer(
|
||||
detail: Option<&str>,
|
||||
actions: &[&str],
|
||||
handle: PromptHandle,
|
||||
cx: &mut WindowContext,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> RenderablePromptHandle {
|
||||
let renderer = cx.new_view({
|
||||
|cx| FallbackPromptRenderer {
|
||||
_level: level,
|
||||
message: message.to_string(),
|
||||
detail: detail.map(ToString::to_string),
|
||||
actions: actions.iter().map(ToString::to_string).collect(),
|
||||
focus: cx.focus_handle(),
|
||||
}
|
||||
let renderer = cx.new(|cx| FallbackPromptRenderer {
|
||||
_level: level,
|
||||
message: message.to_string(),
|
||||
detail: detail.map(ToString::to_string),
|
||||
actions: actions.iter().map(ToString::to_string).collect(),
|
||||
focus: cx.focus_handle(),
|
||||
});
|
||||
|
||||
handle.with_view(renderer, cx)
|
||||
handle.with_view(renderer, window, cx)
|
||||
}
|
||||
|
||||
/// The default GPUI fallback for rendering prompts, when the platform doesn't support it.
|
||||
@@ -93,7 +100,7 @@ pub struct FallbackPromptRenderer {
|
||||
}
|
||||
|
||||
impl Render for FallbackPromptRenderer {
|
||||
fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
|
||||
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
let prompt = div()
|
||||
.cursor_default()
|
||||
.track_focus(&self.focus)
|
||||
@@ -133,7 +140,7 @@ impl Render for FallbackPromptRenderer {
|
||||
.text_sm()
|
||||
.child(action.clone())
|
||||
.id(ix)
|
||||
.on_click(cx.listener(move |_, _, cx| {
|
||||
.on_click(cx.listener(move |_, _, _, cx| {
|
||||
cx.emit(PromptResponse(ix));
|
||||
}))
|
||||
}));
|
||||
@@ -171,8 +178,8 @@ impl Render for FallbackPromptRenderer {
|
||||
|
||||
impl EventEmitter<PromptResponse> for FallbackPromptRenderer {}
|
||||
|
||||
impl FocusableView for FallbackPromptRenderer {
|
||||
fn focus_handle(&self, _: &crate::AppContext) -> FocusHandle {
|
||||
impl Focusable for FallbackPromptRenderer {
|
||||
fn focus_handle(&self, _: &crate::App) -> FocusHandle {
|
||||
self.focus.clone()
|
||||
}
|
||||
}
|
||||
@@ -181,7 +188,7 @@ pub(crate) trait PromptViewHandle {
|
||||
fn any_view(&self) -> AnyView;
|
||||
}
|
||||
|
||||
impl<V: Prompt> PromptViewHandle for View<V> {
|
||||
impl<V: Prompt + Render> PromptViewHandle for Entity<V> {
|
||||
fn any_view(&self) -> AnyView {
|
||||
self.clone().into()
|
||||
}
|
||||
@@ -197,7 +204,8 @@ pub(crate) enum PromptBuilder {
|
||||
Option<&str>,
|
||||
&[&str],
|
||||
PromptHandle,
|
||||
&mut WindowContext,
|
||||
&mut Window,
|
||||
&mut App,
|
||||
) -> RenderablePromptHandle,
|
||||
>,
|
||||
),
|
||||
@@ -210,7 +218,8 @@ impl Deref for PromptBuilder {
|
||||
Option<&str>,
|
||||
&[&str],
|
||||
PromptHandle,
|
||||
&mut WindowContext,
|
||||
&mut Window,
|
||||
&mut App,
|
||||
) -> RenderablePromptHandle;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
|
||||
Reference in New Issue
Block a user