Document party 2 (#4106)
@mikayla-maki and @nathansobo's contributions Release Notes: - N/A
This commit is contained in:
commit
75f8748509
14 changed files with 193 additions and 43 deletions
|
@ -249,7 +249,7 @@ async fn test_basic_following(
|
||||||
executor.run_until_parked();
|
executor.run_until_parked();
|
||||||
cx_c.cx.update(|_| {});
|
cx_c.cx.update(|_| {});
|
||||||
|
|
||||||
weak_workspace_c.assert_dropped();
|
weak_workspace_c.assert_released();
|
||||||
|
|
||||||
// Clients A and B see that client B is following A, and client C is not present in the followers.
|
// Clients A and B see that client B is following A, and client C is not present in the followers.
|
||||||
executor.run_until_parked();
|
executor.run_until_parked();
|
||||||
|
|
|
@ -1,3 +1,5 @@
|
||||||
|
#![deny(missing_docs)]
|
||||||
|
|
||||||
mod async_context;
|
mod async_context;
|
||||||
mod entity_map;
|
mod entity_map;
|
||||||
mod model_context;
|
mod model_context;
|
||||||
|
@ -43,6 +45,9 @@ use util::{
|
||||||
ResultExt,
|
ResultExt,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/// The duration for which futures returned from [AppContext::on_app_context] or [ModelContext::on_app_quit] can run before the application fully quits.
|
||||||
|
pub const SHUTDOWN_TIMEOUT: Duration = Duration::from_millis(100);
|
||||||
|
|
||||||
/// Temporary(?) wrapper around [`RefCell<AppContext>`] to help us debug any double borrows.
|
/// Temporary(?) wrapper around [`RefCell<AppContext>`] to help us debug any double borrows.
|
||||||
/// Strongly consider removing after stabilization.
|
/// Strongly consider removing after stabilization.
|
||||||
#[doc(hidden)]
|
#[doc(hidden)]
|
||||||
|
@ -187,6 +192,9 @@ type QuitHandler = Box<dyn FnOnce(&mut AppContext) -> LocalBoxFuture<'static, ()
|
||||||
type ReleaseListener = Box<dyn FnOnce(&mut dyn Any, &mut AppContext) + 'static>;
|
type ReleaseListener = Box<dyn FnOnce(&mut dyn Any, &mut AppContext) + 'static>;
|
||||||
type NewViewListener = Box<dyn FnMut(AnyView, &mut WindowContext) + 'static>;
|
type NewViewListener = Box<dyn FnMut(AnyView, &mut WindowContext) + '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 AppContext {
|
||||||
pub(crate) this: Weak<AppCell>,
|
pub(crate) this: Weak<AppCell>,
|
||||||
pub(crate) platform: Rc<dyn Platform>,
|
pub(crate) platform: Rc<dyn Platform>,
|
||||||
|
@ -312,7 +320,7 @@ impl AppContext {
|
||||||
let futures = futures::future::join_all(futures);
|
let futures = futures::future::join_all(futures);
|
||||||
if self
|
if self
|
||||||
.background_executor
|
.background_executor
|
||||||
.block_with_timeout(Duration::from_millis(100), futures)
|
.block_with_timeout(SHUTDOWN_TIMEOUT, futures)
|
||||||
.is_err()
|
.is_err()
|
||||||
{
|
{
|
||||||
log::error!("timed out waiting on app_will_quit");
|
log::error!("timed out waiting on app_will_quit");
|
||||||
|
@ -446,6 +454,7 @@ impl AppContext {
|
||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Returns a handle to the window that is currently focused at the platform level, if one exists.
|
||||||
pub fn active_window(&self) -> Option<AnyWindowHandle> {
|
pub fn active_window(&self) -> Option<AnyWindowHandle> {
|
||||||
self.platform.active_window()
|
self.platform.active_window()
|
||||||
}
|
}
|
||||||
|
@ -474,14 +483,17 @@ impl AppContext {
|
||||||
self.platform.activate(ignoring_other_apps);
|
self.platform.activate(ignoring_other_apps);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Hide the application at the platform level.
|
||||||
pub fn hide(&self) {
|
pub fn hide(&self) {
|
||||||
self.platform.hide();
|
self.platform.hide();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Hide other applications at the platform level.
|
||||||
pub fn hide_other_apps(&self) {
|
pub fn hide_other_apps(&self) {
|
||||||
self.platform.hide_other_apps();
|
self.platform.hide_other_apps();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Unhide other applications at the platform level.
|
||||||
pub fn unhide_other_apps(&self) {
|
pub fn unhide_other_apps(&self) {
|
||||||
self.platform.unhide_other_apps();
|
self.platform.unhide_other_apps();
|
||||||
}
|
}
|
||||||
|
@ -521,18 +533,25 @@ impl AppContext {
|
||||||
self.platform.open_url(url);
|
self.platform.open_url(url);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Returns the full pathname of the current app bundle.
|
||||||
|
/// If the app is not being run from a bundle, returns an error.
|
||||||
pub fn app_path(&self) -> Result<PathBuf> {
|
pub fn app_path(&self) -> Result<PathBuf> {
|
||||||
self.platform.app_path()
|
self.platform.app_path()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Returns the file URL of the executable with the specified name in the application bundle
|
||||||
pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
|
pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
|
||||||
self.platform.path_for_auxiliary_executable(name)
|
self.platform.path_for_auxiliary_executable(name)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Returns the maximum duration in which a second mouse click must occur for an event to be a double-click event.
|
||||||
pub fn double_click_interval(&self) -> Duration {
|
pub fn double_click_interval(&self) -> Duration {
|
||||||
self.platform.double_click_interval()
|
self.platform.double_click_interval()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Displays a platform modal for selecting paths.
|
||||||
|
/// When one or more paths are selected, they'll be relayed asynchronously via the returned oneshot channel.
|
||||||
|
/// If cancelled, a `None` will be relayed instead.
|
||||||
pub fn prompt_for_paths(
|
pub fn prompt_for_paths(
|
||||||
&self,
|
&self,
|
||||||
options: PathPromptOptions,
|
options: PathPromptOptions,
|
||||||
|
@ -540,22 +559,30 @@ impl AppContext {
|
||||||
self.platform.prompt_for_paths(options)
|
self.platform.prompt_for_paths(options)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Displays a platform modal for selecting a new path where a file can be saved.
|
||||||
|
/// The provided directory will be used to set the iniital location.
|
||||||
|
/// When a path is selected, it is relayed asynchronously via the returned oneshot channel.
|
||||||
|
/// If cancelled, a `None` will be relayed instead.
|
||||||
pub fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
|
pub fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
|
||||||
self.platform.prompt_for_new_path(directory)
|
self.platform.prompt_for_new_path(directory)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Reveals the specified path at the platform level, such as in Finder on macOS.
|
||||||
pub fn reveal_path(&self, path: &Path) {
|
pub fn reveal_path(&self, path: &Path) {
|
||||||
self.platform.reveal_path(path)
|
self.platform.reveal_path(path)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Returns whether the user has configured scrollbars to auto-hide at the platform level.
|
||||||
pub fn should_auto_hide_scrollbars(&self) -> bool {
|
pub fn should_auto_hide_scrollbars(&self) -> bool {
|
||||||
self.platform.should_auto_hide_scrollbars()
|
self.platform.should_auto_hide_scrollbars()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Restart the application.
|
||||||
pub fn restart(&self) {
|
pub fn restart(&self) {
|
||||||
self.platform.restart()
|
self.platform.restart()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Returns the local timezone at the platform level.
|
||||||
pub fn local_timezone(&self) -> UtcOffset {
|
pub fn local_timezone(&self) -> UtcOffset {
|
||||||
self.platform.local_timezone()
|
self.platform.local_timezone()
|
||||||
}
|
}
|
||||||
|
@ -745,7 +772,7 @@ impl AppContext {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Spawns the future returned by the given function on the thread pool. The closure will be invoked
|
/// Spawns the future returned by the given function on the thread pool. The closure will be invoked
|
||||||
/// with AsyncAppContext, which allows the application state to be accessed across await points.
|
/// with [AsyncAppContext], which allows the application state to be accessed across await points.
|
||||||
pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncAppContext) -> Fut) -> Task<R>
|
pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncAppContext) -> Fut) -> Task<R>
|
||||||
where
|
where
|
||||||
Fut: Future<Output = R> + 'static,
|
Fut: Future<Output = R> + 'static,
|
||||||
|
@ -896,6 +923,8 @@ impl AppContext {
|
||||||
self.globals_by_type.insert(global_type, lease.global);
|
self.globals_by_type.insert(global_type, lease.global);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 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>(
|
pub fn observe_new_views<V: 'static>(
|
||||||
&mut self,
|
&mut self,
|
||||||
on_new: impl 'static + Fn(&mut V, &mut ViewContext<V>),
|
on_new: impl 'static + Fn(&mut V, &mut ViewContext<V>),
|
||||||
|
@ -915,6 +944,8 @@ impl AppContext {
|
||||||
subscription
|
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<E, T>(
|
pub fn observe_release<E, T>(
|
||||||
&mut self,
|
&mut self,
|
||||||
handle: &E,
|
handle: &E,
|
||||||
|
@ -935,6 +966,9 @@ impl AppContext {
|
||||||
subscription
|
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 mechansims have resolved
|
||||||
|
/// and that this API will not be invoked if the event's propogation is stopped.
|
||||||
pub fn observe_keystrokes(
|
pub fn observe_keystrokes(
|
||||||
&mut self,
|
&mut self,
|
||||||
f: impl FnMut(&KeystrokeEvent, &mut WindowContext) + 'static,
|
f: impl FnMut(&KeystrokeEvent, &mut WindowContext) + 'static,
|
||||||
|
@ -958,6 +992,7 @@ impl AppContext {
|
||||||
self.pending_effects.push_back(Effect::Refresh);
|
self.pending_effects.push_back(Effect::Refresh);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Clear all key bindings in the app.
|
||||||
pub fn clear_key_bindings(&mut self) {
|
pub fn clear_key_bindings(&mut self) {
|
||||||
self.keymap.lock().clear();
|
self.keymap.lock().clear();
|
||||||
self.pending_effects.push_back(Effect::Refresh);
|
self.pending_effects.push_back(Effect::Refresh);
|
||||||
|
@ -992,6 +1027,7 @@ impl AppContext {
|
||||||
self.propagate_event = true;
|
self.propagate_event = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Build an action from some arbitrary data, typically a keymap entry.
|
||||||
pub fn build_action(
|
pub fn build_action(
|
||||||
&self,
|
&self,
|
||||||
name: &str,
|
name: &str,
|
||||||
|
@ -1000,10 +1036,16 @@ impl AppContext {
|
||||||
self.actions.build_action(name, data)
|
self.actions.build_action(name, data)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Get a list of all action names that have been registered.
|
||||||
|
/// in the application. Note that registration only allows for
|
||||||
|
/// actions to be built dynamically, and is unrelated to binding
|
||||||
|
/// actions in the element tree.
|
||||||
pub fn all_action_names(&self) -> &[SharedString] {
|
pub fn all_action_names(&self) -> &[SharedString] {
|
||||||
self.actions.all_action_names()
|
self.actions.all_action_names()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Register a callback to be invoked when the application is about to quit.
|
||||||
|
/// It is not possible to cancel the quit event at this point.
|
||||||
pub fn on_app_quit<Fut>(
|
pub fn on_app_quit<Fut>(
|
||||||
&mut self,
|
&mut self,
|
||||||
mut on_quit: impl FnMut(&mut AppContext) -> Fut + 'static,
|
mut on_quit: impl FnMut(&mut AppContext) -> Fut + 'static,
|
||||||
|
@ -1039,6 +1081,8 @@ impl AppContext {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Checks if the given action is bound in the current context, as defined by the app's current focus,
|
||||||
|
/// the bindings in the element tree, and any global action listeners.
|
||||||
pub fn is_action_available(&mut self, action: &dyn Action) -> bool {
|
pub fn is_action_available(&mut self, action: &dyn Action) -> bool {
|
||||||
if let Some(window) = self.active_window() {
|
if let Some(window) = self.active_window() {
|
||||||
if let Ok(window_action_available) =
|
if let Ok(window_action_available) =
|
||||||
|
@ -1052,10 +1096,13 @@ impl AppContext {
|
||||||
.contains_key(&action.as_any().type_id())
|
.contains_key(&action.as_any().type_id())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Set the menu bar for this application. This will replace any existing menu bar.
|
||||||
pub fn set_menus(&mut self, menus: Vec<Menu>) {
|
pub fn set_menus(&mut self, menus: Vec<Menu>) {
|
||||||
self.platform.set_menus(menus, &self.keymap.lock());
|
self.platform.set_menus(menus, &self.keymap.lock());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Dispatch an action to the currently active window or global action handler
|
||||||
|
/// See [action::Action] for more information on how actions work
|
||||||
pub fn dispatch_action(&mut self, action: &dyn Action) {
|
pub fn dispatch_action(&mut self, action: &dyn Action) {
|
||||||
if let Some(active_window) = self.active_window() {
|
if let Some(active_window) = self.active_window() {
|
||||||
active_window
|
active_window
|
||||||
|
@ -1110,6 +1157,7 @@ impl AppContext {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Is there currently something being dragged?
|
||||||
pub fn has_active_drag(&self) -> bool {
|
pub fn has_active_drag(&self) -> bool {
|
||||||
self.active_drag.is_some()
|
self.active_drag.is_some()
|
||||||
}
|
}
|
||||||
|
@ -1262,8 +1310,14 @@ impl<G: 'static> DerefMut for GlobalLease<G> {
|
||||||
/// Contains state associated with an active drag operation, started by dragging an element
|
/// Contains state associated with an active drag operation, started by dragging an element
|
||||||
/// within the window or by dragging into the app from the underlying platform.
|
/// within the window or by dragging into the app from the underlying platform.
|
||||||
pub struct AnyDrag {
|
pub struct AnyDrag {
|
||||||
|
/// The view used to render this drag
|
||||||
pub view: AnyView,
|
pub view: AnyView,
|
||||||
|
|
||||||
|
/// The value of the dragged item, to be dropped
|
||||||
pub value: Box<dyn Any>,
|
pub value: Box<dyn Any>,
|
||||||
|
|
||||||
|
/// This is used to render the dragged item in the same place
|
||||||
|
/// on the original element that the drag was initiated
|
||||||
pub cursor_offset: Point<Pixels>,
|
pub cursor_offset: Point<Pixels>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1271,12 +1325,19 @@ pub struct AnyDrag {
|
||||||
/// tooltip behavior on a custom element. Otherwise, use [Div::tooltip].
|
/// tooltip behavior on a custom element. Otherwise, use [Div::tooltip].
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct AnyTooltip {
|
pub struct AnyTooltip {
|
||||||
|
/// The view used to display the tooltip
|
||||||
pub view: AnyView,
|
pub view: AnyView,
|
||||||
|
|
||||||
|
/// The offset from the cursor to use, relative to the parent view
|
||||||
pub cursor_offset: Point<Pixels>,
|
pub cursor_offset: Point<Pixels>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A keystroke event, and potentially the associated action
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct KeystrokeEvent {
|
pub struct KeystrokeEvent {
|
||||||
|
/// The keystroke that occurred
|
||||||
pub keystroke: Keystroke,
|
pub keystroke: Keystroke,
|
||||||
|
|
||||||
|
/// The action that was resolved for the keystroke, if any
|
||||||
pub action: Option<Box<dyn Action>>,
|
pub action: Option<Box<dyn Action>>,
|
||||||
}
|
}
|
||||||
|
|
|
@ -7,6 +7,9 @@ use anyhow::{anyhow, Context as _};
|
||||||
use derive_more::{Deref, DerefMut};
|
use derive_more::{Deref, DerefMut};
|
||||||
use std::{future::Future, rc::Weak};
|
use std::{future::Future, rc::Weak};
|
||||||
|
|
||||||
|
/// 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.
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct AsyncAppContext {
|
pub struct AsyncAppContext {
|
||||||
pub(crate) app: Weak<AppCell>,
|
pub(crate) app: Weak<AppCell>,
|
||||||
|
@ -139,6 +142,8 @@ impl AsyncAppContext {
|
||||||
self.foreground_executor.spawn(f(self.clone()))
|
self.foreground_executor.spawn(f(self.clone()))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Determine whether global state of the specified type has been assigned.
|
||||||
|
/// Returns an error if the `AppContext` has been dropped.
|
||||||
pub fn has_global<G: 'static>(&self) -> Result<bool> {
|
pub fn has_global<G: 'static>(&self) -> Result<bool> {
|
||||||
let app = self
|
let app = self
|
||||||
.app
|
.app
|
||||||
|
@ -148,6 +153,9 @@ impl AsyncAppContext {
|
||||||
Ok(app.has_global::<G>())
|
Ok(app.has_global::<G>())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Reads the global state of the specified type, passing it to the given callback.
|
||||||
|
/// 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: 'static, R>(&self, read: impl FnOnce(&G, &AppContext) -> R) -> Result<R> {
|
pub fn read_global<G: 'static, R>(&self, read: impl FnOnce(&G, &AppContext) -> R) -> Result<R> {
|
||||||
let app = self
|
let app = self
|
||||||
.app
|
.app
|
||||||
|
@ -157,6 +165,9 @@ impl AsyncAppContext {
|
||||||
Ok(read(app.global(), &app))
|
Ok(read(app.global(), &app))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Reads the global state of the specified type, passing it to the given callback.
|
||||||
|
/// Similar to [read_global], but returns an error instead of panicking 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: 'static, R>(
|
pub fn try_read_global<G: 'static, R>(
|
||||||
&self,
|
&self,
|
||||||
read: impl FnOnce(&G, &AppContext) -> R,
|
read: impl FnOnce(&G, &AppContext) -> R,
|
||||||
|
@ -166,6 +177,8 @@ impl AsyncAppContext {
|
||||||
Some(read(app.try_global()?, &app))
|
Some(read(app.try_global()?, &app))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A convenience method for [AppContext::update_global]
|
||||||
|
/// for updating the global state of the specified type.
|
||||||
pub fn update_global<G: 'static, R>(
|
pub fn update_global<G: 'static, R>(
|
||||||
&mut self,
|
&mut self,
|
||||||
update: impl FnOnce(&mut G, &mut AppContext) -> R,
|
update: impl FnOnce(&mut G, &mut AppContext) -> R,
|
||||||
|
@ -179,6 +192,8 @@ impl AsyncAppContext {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A cloneable, owned handle to the application context,
|
||||||
|
/// composed with the window associated with the current task.
|
||||||
#[derive(Clone, Deref, DerefMut)]
|
#[derive(Clone, Deref, DerefMut)]
|
||||||
pub struct AsyncWindowContext {
|
pub struct AsyncWindowContext {
|
||||||
#[deref]
|
#[deref]
|
||||||
|
@ -188,14 +203,16 @@ pub struct AsyncWindowContext {
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AsyncWindowContext {
|
impl AsyncWindowContext {
|
||||||
pub fn window_handle(&self) -> AnyWindowHandle {
|
|
||||||
self.window
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn new(app: AsyncAppContext, window: AnyWindowHandle) -> Self {
|
pub(crate) fn new(app: AsyncAppContext, window: AnyWindowHandle) -> Self {
|
||||||
Self { app, window }
|
Self { app, window }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Get the handle of the window this context is associated with.
|
||||||
|
pub fn window_handle(&self) -> AnyWindowHandle {
|
||||||
|
self.window
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A convenience method for [WindowContext::update()]
|
||||||
pub fn update<R>(
|
pub fn update<R>(
|
||||||
&mut self,
|
&mut self,
|
||||||
update: impl FnOnce(AnyView, &mut WindowContext) -> R,
|
update: impl FnOnce(AnyView, &mut WindowContext) -> R,
|
||||||
|
@ -203,10 +220,12 @@ impl AsyncWindowContext {
|
||||||
self.app.update_window(self.window, update)
|
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) {
|
pub fn on_next_frame(&mut self, f: impl FnOnce(&mut WindowContext) + 'static) {
|
||||||
self.window.update(self, |_, cx| cx.on_next_frame(f)).ok();
|
self.window.update(self, |_, cx| cx.on_next_frame(f)).ok();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A convenience method for [AppContext::global()]
|
||||||
pub fn read_global<G: 'static, R>(
|
pub fn read_global<G: 'static, R>(
|
||||||
&mut self,
|
&mut self,
|
||||||
read: impl FnOnce(&G, &WindowContext) -> R,
|
read: impl FnOnce(&G, &WindowContext) -> R,
|
||||||
|
@ -214,6 +233,8 @@ impl AsyncWindowContext {
|
||||||
self.window.update(self, |_, cx| read(cx.global(), cx))
|
self.window.update(self, |_, cx| read(cx.global(), cx))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A convenience method for [AppContext::update_global()]
|
||||||
|
/// for updating the global state of the specified type.
|
||||||
pub fn update_global<G, R>(
|
pub fn update_global<G, R>(
|
||||||
&mut self,
|
&mut self,
|
||||||
update: impl FnOnce(&mut G, &mut WindowContext) -> R,
|
update: impl FnOnce(&mut G, &mut WindowContext) -> R,
|
||||||
|
@ -224,6 +245,8 @@ impl AsyncWindowContext {
|
||||||
self.window.update(self, |_, cx| cx.update_global(update))
|
self.window.update(self, |_, cx| cx.update_global(update))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Schedule a future to be executed on the main thread. This is used for collecting
|
||||||
|
/// the results of background tasks and updating the UI.
|
||||||
pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncWindowContext) -> Fut) -> Task<R>
|
pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncWindowContext) -> Fut) -> Task<R>
|
||||||
where
|
where
|
||||||
Fut: Future<Output = R> + 'static,
|
Fut: Future<Output = R> + 'static,
|
||||||
|
|
|
@ -31,6 +31,7 @@ impl From<u64> for EntityId {
|
||||||
}
|
}
|
||||||
|
|
||||||
impl EntityId {
|
impl EntityId {
|
||||||
|
/// Converts this entity id to a [u64]
|
||||||
pub fn as_u64(self) -> u64 {
|
pub fn as_u64(self) -> u64 {
|
||||||
self.0.as_ffi()
|
self.0.as_ffi()
|
||||||
}
|
}
|
||||||
|
@ -140,7 +141,7 @@ impl EntityMap {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct Lease<'a, T> {
|
pub(crate) struct Lease<'a, T> {
|
||||||
entity: Option<Box<dyn Any>>,
|
entity: Option<Box<dyn Any>>,
|
||||||
pub model: &'a Model<T>,
|
pub model: &'a Model<T>,
|
||||||
entity_type: PhantomData<T>,
|
entity_type: PhantomData<T>,
|
||||||
|
@ -169,8 +170,9 @@ impl<'a, T> Drop for Lease<'a, T> {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deref, DerefMut)]
|
#[derive(Deref, DerefMut)]
|
||||||
pub struct Slot<T>(Model<T>);
|
pub(crate) struct Slot<T>(Model<T>);
|
||||||
|
|
||||||
|
/// A dynamically typed reference to a model, which can be downcast into a `Model<T>`.
|
||||||
pub struct AnyModel {
|
pub struct AnyModel {
|
||||||
pub(crate) entity_id: EntityId,
|
pub(crate) entity_id: EntityId,
|
||||||
pub(crate) entity_type: TypeId,
|
pub(crate) entity_type: TypeId,
|
||||||
|
@ -195,14 +197,17 @@ impl AnyModel {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Returns the id associated with this model.
|
||||||
pub fn entity_id(&self) -> EntityId {
|
pub fn entity_id(&self) -> EntityId {
|
||||||
self.entity_id
|
self.entity_id
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Returns the [TypeId] associated with this model.
|
||||||
pub fn entity_type(&self) -> TypeId {
|
pub fn entity_type(&self) -> TypeId {
|
||||||
self.entity_type
|
self.entity_type
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Converts this model handle into a weak variant, which does not prevent it from being released.
|
||||||
pub fn downgrade(&self) -> AnyWeakModel {
|
pub fn downgrade(&self) -> AnyWeakModel {
|
||||||
AnyWeakModel {
|
AnyWeakModel {
|
||||||
entity_id: self.entity_id,
|
entity_id: self.entity_id,
|
||||||
|
@ -211,6 +216,8 @@ 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<Model<T>, AnyModel> {
|
||||||
if TypeId::of::<T>() == self.entity_type {
|
if TypeId::of::<T>() == self.entity_type {
|
||||||
Ok(Model {
|
Ok(Model {
|
||||||
|
@ -274,7 +281,7 @@ impl Drop for AnyModel {
|
||||||
entity_map
|
entity_map
|
||||||
.write()
|
.write()
|
||||||
.leak_detector
|
.leak_detector
|
||||||
.handle_dropped(self.entity_id, self.handle_id)
|
.handle_released(self.entity_id, self.handle_id)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -307,6 +314,8 @@ impl std::fmt::Debug for AnyModel {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A strong, well typed reference to a struct which is managed
|
||||||
|
/// by GPUI
|
||||||
#[derive(Deref, DerefMut)]
|
#[derive(Deref, DerefMut)]
|
||||||
pub struct Model<T> {
|
pub struct Model<T> {
|
||||||
#[deref]
|
#[deref]
|
||||||
|
@ -368,10 +377,12 @@ impl<T: 'static> Model<T> {
|
||||||
self.any_model
|
self.any_model
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 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 AppContext) -> &'a T {
|
||||||
cx.entities.read(self)
|
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: Context>(
|
||||||
&self,
|
&self,
|
||||||
cx: &C,
|
cx: &C,
|
||||||
|
@ -437,6 +448,7 @@ impl<T> PartialEq<WeakModel<T>> for Model<T> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A type erased, weak reference to a model.
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct AnyWeakModel {
|
pub struct AnyWeakModel {
|
||||||
pub(crate) entity_id: EntityId,
|
pub(crate) entity_id: EntityId,
|
||||||
|
@ -445,10 +457,12 @@ pub struct AnyWeakModel {
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AnyWeakModel {
|
impl AnyWeakModel {
|
||||||
|
/// Get the entity ID associated with this weak reference.
|
||||||
pub fn entity_id(&self) -> EntityId {
|
pub fn entity_id(&self) -> EntityId {
|
||||||
self.entity_id
|
self.entity_id
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Check if this weak handle can be upgraded, or if the model has already been dropped
|
||||||
pub fn is_upgradable(&self) -> bool {
|
pub fn is_upgradable(&self) -> bool {
|
||||||
let ref_count = self
|
let ref_count = self
|
||||||
.entity_ref_counts
|
.entity_ref_counts
|
||||||
|
@ -458,6 +472,7 @@ impl AnyWeakModel {
|
||||||
ref_count > 0
|
ref_count > 0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Upgrade this weak model reference to a strong reference.
|
||||||
pub fn upgrade(&self) -> Option<AnyModel> {
|
pub fn upgrade(&self) -> Option<AnyModel> {
|
||||||
let ref_counts = &self.entity_ref_counts.upgrade()?;
|
let ref_counts = &self.entity_ref_counts.upgrade()?;
|
||||||
let ref_counts = ref_counts.read();
|
let ref_counts = ref_counts.read();
|
||||||
|
@ -485,14 +500,15 @@ impl AnyWeakModel {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Assert that model referenced by this weak handle has been released.
|
||||||
#[cfg(any(test, feature = "test-support"))]
|
#[cfg(any(test, feature = "test-support"))]
|
||||||
pub fn assert_dropped(&self) {
|
pub fn assert_released(&self) {
|
||||||
self.entity_ref_counts
|
self.entity_ref_counts
|
||||||
.upgrade()
|
.upgrade()
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.write()
|
.write()
|
||||||
.leak_detector
|
.leak_detector
|
||||||
.assert_dropped(self.entity_id);
|
.assert_released(self.entity_id);
|
||||||
|
|
||||||
if self
|
if self
|
||||||
.entity_ref_counts
|
.entity_ref_counts
|
||||||
|
@ -527,6 +543,7 @@ impl PartialEq for AnyWeakModel {
|
||||||
|
|
||||||
impl Eq for AnyWeakModel {}
|
impl Eq for AnyWeakModel {}
|
||||||
|
|
||||||
|
/// A weak reference to a model of the given type.
|
||||||
#[derive(Deref, DerefMut)]
|
#[derive(Deref, DerefMut)]
|
||||||
pub struct WeakModel<T> {
|
pub struct WeakModel<T> {
|
||||||
#[deref]
|
#[deref]
|
||||||
|
@ -617,12 +634,12 @@ lazy_static::lazy_static! {
|
||||||
|
|
||||||
#[cfg(any(test, feature = "test-support"))]
|
#[cfg(any(test, feature = "test-support"))]
|
||||||
#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq)]
|
#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq)]
|
||||||
pub struct HandleId {
|
pub(crate) struct HandleId {
|
||||||
id: u64, // id of the handle itself, not the pointed at object
|
id: u64, // id of the handle itself, not the pointed at object
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(any(test, feature = "test-support"))]
|
#[cfg(any(test, feature = "test-support"))]
|
||||||
pub struct LeakDetector {
|
pub(crate) struct LeakDetector {
|
||||||
next_handle_id: u64,
|
next_handle_id: u64,
|
||||||
entity_handles: HashMap<EntityId, HashMap<HandleId, Option<backtrace::Backtrace>>>,
|
entity_handles: HashMap<EntityId, HashMap<HandleId, Option<backtrace::Backtrace>>>,
|
||||||
}
|
}
|
||||||
|
@ -641,12 +658,12 @@ impl LeakDetector {
|
||||||
handle_id
|
handle_id
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn handle_dropped(&mut self, entity_id: EntityId, handle_id: HandleId) {
|
pub fn handle_released(&mut self, entity_id: EntityId, handle_id: HandleId) {
|
||||||
let handles = self.entity_handles.entry(entity_id).or_default();
|
let handles = self.entity_handles.entry(entity_id).or_default();
|
||||||
handles.remove(&handle_id);
|
handles.remove(&handle_id);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn assert_dropped(&mut self, entity_id: EntityId) {
|
pub fn assert_released(&mut self, entity_id: EntityId) {
|
||||||
let handles = self.entity_handles.entry(entity_id).or_default();
|
let handles = self.entity_handles.entry(entity_id).or_default();
|
||||||
if !handles.is_empty() {
|
if !handles.is_empty() {
|
||||||
for (_, backtrace) in handles {
|
for (_, backtrace) in handles {
|
||||||
|
|
|
@ -11,6 +11,7 @@ use std::{
|
||||||
future::Future,
|
future::Future,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/// The app context, with specialized behavior for the given model.
|
||||||
#[derive(Deref, DerefMut)]
|
#[derive(Deref, DerefMut)]
|
||||||
pub struct ModelContext<'a, T> {
|
pub struct ModelContext<'a, T> {
|
||||||
#[deref]
|
#[deref]
|
||||||
|
@ -24,20 +25,24 @@ impl<'a, T: 'static> ModelContext<'a, T> {
|
||||||
Self { app, model_state }
|
Self { app, model_state }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The entity id of the model backing this context.
|
||||||
pub fn entity_id(&self) -> EntityId {
|
pub fn entity_id(&self) -> EntityId {
|
||||||
self.model_state.entity_id
|
self.model_state.entity_id
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Returns a handle to the model belonging to this context.
|
||||||
pub fn handle(&self) -> Model<T> {
|
pub fn handle(&self) -> Model<T> {
|
||||||
self.weak_model()
|
self.weak_model()
|
||||||
.upgrade()
|
.upgrade()
|
||||||
.expect("The entity must be alive if we have a model context")
|
.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) -> WeakModel<T> {
|
||||||
self.model_state.clone()
|
self.model_state.clone()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Arranges for the given function to be called whenever [ModelContext::notify] or [ViewContext::notify] is called with the given model or view.
|
||||||
pub fn observe<W, E>(
|
pub fn observe<W, E>(
|
||||||
&mut self,
|
&mut self,
|
||||||
entity: &E,
|
entity: &E,
|
||||||
|
@ -59,6 +64,7 @@ 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, E, Evt>(
|
||||||
&mut self,
|
&mut self,
|
||||||
entity: &E,
|
entity: &E,
|
||||||
|
@ -81,6 +87,7 @@ impl<'a, T: 'static> ModelContext<'a, T> {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Register a callback to be invoked when GPUI releases this model.
|
||||||
pub fn on_release(
|
pub fn on_release(
|
||||||
&mut self,
|
&mut self,
|
||||||
on_release: impl FnOnce(&mut T, &mut AppContext) + 'static,
|
on_release: impl FnOnce(&mut T, &mut AppContext) + 'static,
|
||||||
|
@ -99,6 +106,7 @@ impl<'a, T: 'static> ModelContext<'a, T> {
|
||||||
subscription
|
subscription
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 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, E>(
|
||||||
&mut self,
|
&mut self,
|
||||||
entity: &E,
|
entity: &E,
|
||||||
|
@ -124,6 +132,7 @@ impl<'a, T: 'static> ModelContext<'a, T> {
|
||||||
subscription
|
subscription
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Register a callback to for updates to the given global
|
||||||
pub fn observe_global<G: 'static>(
|
pub fn observe_global<G: 'static>(
|
||||||
&mut self,
|
&mut self,
|
||||||
mut f: impl FnMut(&mut T, &mut ModelContext<'_, T>) + 'static,
|
mut f: impl FnMut(&mut T, &mut ModelContext<'_, T>) + 'static,
|
||||||
|
@ -140,6 +149,8 @@ impl<'a, T: 'static> ModelContext<'a, T> {
|
||||||
subscription
|
subscription
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Arrange for the given function to be invoked whenever the application is quit.
|
||||||
|
/// The future returned from this callback will be polled for up to [gpui::SHUTDOWN_TIMEOUT] until the app fully quits.
|
||||||
pub fn on_app_quit<Fut>(
|
pub fn on_app_quit<Fut>(
|
||||||
&mut self,
|
&mut self,
|
||||||
mut on_quit: impl FnMut(&mut T, &mut ModelContext<T>) -> Fut + 'static,
|
mut on_quit: impl FnMut(&mut T, &mut ModelContext<T>) -> Fut + 'static,
|
||||||
|
@ -165,6 +176,7 @@ impl<'a, T: 'static> ModelContext<'a, T> {
|
||||||
subscription
|
subscription
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Tell GPUI that this model has changed and observers of it should be notified.
|
||||||
pub fn notify(&mut self) {
|
pub fn notify(&mut self) {
|
||||||
if self
|
if self
|
||||||
.app
|
.app
|
||||||
|
@ -177,6 +189,7 @@ impl<'a, T: 'static> ModelContext<'a, T> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Update the given global
|
||||||
pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
|
pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
|
||||||
where
|
where
|
||||||
G: 'static,
|
G: 'static,
|
||||||
|
@ -187,6 +200,9 @@ impl<'a, T: 'static> ModelContext<'a, T> {
|
||||||
result
|
result
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 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(WeakModel<T>, AsyncAppContext) -> Fut) -> Task<R>
|
||||||
where
|
where
|
||||||
T: 'static,
|
T: 'static,
|
||||||
|
@ -199,6 +215,7 @@ impl<'a, T: 'static> ModelContext<'a, T> {
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a, T> ModelContext<'a, T> {
|
impl<'a, T> ModelContext<'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)
|
pub fn emit<Evt>(&mut self, event: Evt)
|
||||||
where
|
where
|
||||||
T: EventEmitter<Evt>,
|
T: EventEmitter<Evt>,
|
||||||
|
|
|
@ -109,9 +109,10 @@ type AnyFuture<R> = Pin<Box<dyn 'static + Send + Future<Output = R>>>;
|
||||||
|
|
||||||
/// BackgroundExecutor lets you run things on background threads.
|
/// BackgroundExecutor lets you run things on background threads.
|
||||||
/// In production this is a thread pool with no ordering guarantees.
|
/// In production this is a thread pool with no ordering guarantees.
|
||||||
/// In tests this is simalated by running tasks one by one in a deterministic
|
/// In tests this is simulated by running tasks one by one in a deterministic
|
||||||
/// (but arbitrary) order controlled by the `SEED` environment variable.
|
/// (but arbitrary) order controlled by the `SEED` environment variable.
|
||||||
impl BackgroundExecutor {
|
impl BackgroundExecutor {
|
||||||
|
#[doc(hidden)]
|
||||||
pub fn new(dispatcher: Arc<dyn PlatformDispatcher>) -> Self {
|
pub fn new(dispatcher: Arc<dyn PlatformDispatcher>) -> Self {
|
||||||
Self { dispatcher }
|
Self { dispatcher }
|
||||||
}
|
}
|
||||||
|
|
|
@ -114,15 +114,20 @@ pub(crate) trait Platform: 'static {
|
||||||
fn delete_credentials(&self, url: &str) -> Result<()>;
|
fn delete_credentials(&self, url: &str) -> Result<()>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A handle to a platform's display, e.g. a monitor or laptop screen.
|
||||||
pub trait PlatformDisplay: Send + Sync + Debug {
|
pub trait PlatformDisplay: Send + Sync + Debug {
|
||||||
|
/// Get the ID for this display
|
||||||
fn id(&self) -> DisplayId;
|
fn id(&self) -> DisplayId;
|
||||||
|
|
||||||
/// Returns a stable identifier for this display that can be persisted and used
|
/// Returns a stable identifier for this display that can be persisted and used
|
||||||
/// across system restarts.
|
/// across system restarts.
|
||||||
fn uuid(&self) -> Result<Uuid>;
|
fn uuid(&self) -> Result<Uuid>;
|
||||||
fn as_any(&self) -> &dyn Any;
|
|
||||||
|
/// Get the bounds for this display
|
||||||
fn bounds(&self) -> Bounds<GlobalPixels>;
|
fn bounds(&self) -> Bounds<GlobalPixels>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// An opaque identifier for a hardware display
|
||||||
#[derive(PartialEq, Eq, Hash, Copy, Clone)]
|
#[derive(PartialEq, Eq, Hash, Copy, Clone)]
|
||||||
pub struct DisplayId(pub(crate) u32);
|
pub struct DisplayId(pub(crate) u32);
|
||||||
|
|
||||||
|
@ -134,7 +139,7 @@ impl Debug for DisplayId {
|
||||||
|
|
||||||
unsafe impl Send for DisplayId {}
|
unsafe impl Send for DisplayId {}
|
||||||
|
|
||||||
pub trait PlatformWindow {
|
pub(crate) trait PlatformWindow {
|
||||||
fn bounds(&self) -> WindowBounds;
|
fn bounds(&self) -> WindowBounds;
|
||||||
fn content_size(&self) -> Size<Pixels>;
|
fn content_size(&self) -> Size<Pixels>;
|
||||||
fn scale_factor(&self) -> f32;
|
fn scale_factor(&self) -> f32;
|
||||||
|
@ -175,6 +180,9 @@ pub trait PlatformWindow {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// This type is public so that our test macro can generate and use it, but it should not
|
||||||
|
/// be considered part of our public API.
|
||||||
|
#[doc(hidden)]
|
||||||
pub trait PlatformDispatcher: Send + Sync {
|
pub trait PlatformDispatcher: Send + Sync {
|
||||||
fn is_main_thread(&self) -> bool;
|
fn is_main_thread(&self) -> bool;
|
||||||
fn dispatch(&self, runnable: Runnable, label: Option<TaskLabel>);
|
fn dispatch(&self, runnable: Runnable, label: Option<TaskLabel>);
|
||||||
|
@ -190,7 +198,7 @@ pub trait PlatformDispatcher: Send + Sync {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub trait PlatformTextSystem: Send + Sync {
|
pub(crate) trait PlatformTextSystem: Send + Sync {
|
||||||
fn add_fonts(&self, fonts: &[Arc<Vec<u8>>]) -> Result<()>;
|
fn add_fonts(&self, fonts: &[Arc<Vec<u8>>]) -> Result<()>;
|
||||||
fn all_font_names(&self) -> Vec<String>;
|
fn all_font_names(&self) -> Vec<String>;
|
||||||
fn font_id(&self, descriptor: &Font) -> Result<FontId>;
|
fn font_id(&self, descriptor: &Font) -> Result<FontId>;
|
||||||
|
@ -214,15 +222,21 @@ pub trait PlatformTextSystem: Send + Sync {
|
||||||
) -> Vec<usize>;
|
) -> Vec<usize>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Basic metadata about the current application and operating system.
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
pub struct AppMetadata {
|
pub struct AppMetadata {
|
||||||
|
/// The name of the current operating system
|
||||||
pub os_name: &'static str,
|
pub os_name: &'static str,
|
||||||
|
|
||||||
|
/// The operating system's version
|
||||||
pub os_version: Option<SemanticVersion>,
|
pub os_version: Option<SemanticVersion>,
|
||||||
|
|
||||||
|
/// The current version of the application
|
||||||
pub app_version: Option<SemanticVersion>,
|
pub app_version: Option<SemanticVersion>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(PartialEq, Eq, Hash, Clone)]
|
#[derive(PartialEq, Eq, Hash, Clone)]
|
||||||
pub enum AtlasKey {
|
pub(crate) enum AtlasKey {
|
||||||
Glyph(RenderGlyphParams),
|
Glyph(RenderGlyphParams),
|
||||||
Svg(RenderSvgParams),
|
Svg(RenderSvgParams),
|
||||||
Image(RenderImageParams),
|
Image(RenderImageParams),
|
||||||
|
@ -262,7 +276,7 @@ impl From<RenderImageParams> for AtlasKey {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub trait PlatformAtlas: Send + Sync {
|
pub(crate) trait PlatformAtlas: Send + Sync {
|
||||||
fn get_or_insert_with<'a>(
|
fn get_or_insert_with<'a>(
|
||||||
&self,
|
&self,
|
||||||
key: &AtlasKey,
|
key: &AtlasKey,
|
||||||
|
@ -274,7 +288,7 @@ pub trait PlatformAtlas: Send + Sync {
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
#[repr(C)]
|
#[repr(C)]
|
||||||
pub struct AtlasTile {
|
pub(crate) struct AtlasTile {
|
||||||
pub(crate) texture_id: AtlasTextureId,
|
pub(crate) texture_id: AtlasTextureId,
|
||||||
pub(crate) tile_id: TileId,
|
pub(crate) tile_id: TileId,
|
||||||
pub(crate) bounds: Bounds<DevicePixels>,
|
pub(crate) bounds: Bounds<DevicePixels>,
|
||||||
|
|
|
@ -11,7 +11,6 @@ use core_graphics::{
|
||||||
geometry::{CGPoint, CGRect, CGSize},
|
geometry::{CGPoint, CGRect, CGSize},
|
||||||
};
|
};
|
||||||
use objc::{msg_send, sel, sel_impl};
|
use objc::{msg_send, sel, sel_impl};
|
||||||
use std::any::Any;
|
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
|
@ -154,10 +153,6 @@ impl PlatformDisplay for MacDisplay {
|
||||||
]))
|
]))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn as_any(&self) -> &dyn Any {
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
fn bounds(&self) -> Bounds<GlobalPixels> {
|
fn bounds(&self) -> Bounds<GlobalPixels> {
|
||||||
unsafe {
|
unsafe {
|
||||||
let native_bounds = CGDisplayBounds(self.0);
|
let native_bounds = CGDisplayBounds(self.0);
|
||||||
|
|
|
@ -31,10 +31,6 @@ impl PlatformDisplay for TestDisplay {
|
||||||
Ok(self.uuid)
|
Ok(self.uuid)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn as_any(&self) -> &dyn std::any::Any {
|
|
||||||
unimplemented!()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn bounds(&self) -> crate::Bounds<crate::GlobalPixels> {
|
fn bounds(&self) -> crate::Bounds<crate::GlobalPixels> {
|
||||||
self.bounds
|
self.bounds
|
||||||
}
|
}
|
||||||
|
|
|
@ -93,7 +93,7 @@ impl Scene {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn insert(&mut self, order: &StackingOrder, primitive: impl Into<Primitive>) {
|
pub(crate) fn insert(&mut self, order: &StackingOrder, primitive: impl Into<Primitive>) {
|
||||||
let primitive = primitive.into();
|
let primitive = primitive.into();
|
||||||
let clipped_bounds = primitive
|
let clipped_bounds = primitive
|
||||||
.bounds()
|
.bounds()
|
||||||
|
@ -440,7 +440,7 @@ pub enum PrimitiveKind {
|
||||||
Surface,
|
Surface,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub enum Primitive {
|
pub(crate) enum Primitive {
|
||||||
Shadow(Shadow),
|
Shadow(Shadow),
|
||||||
Quad(Quad),
|
Quad(Quad),
|
||||||
Path(Path<ScaledPixels>),
|
Path(Path<ScaledPixels>),
|
||||||
|
@ -589,7 +589,7 @@ impl From<Shadow> for Primitive {
|
||||||
|
|
||||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||||
#[repr(C)]
|
#[repr(C)]
|
||||||
pub struct MonochromeSprite {
|
pub(crate) struct MonochromeSprite {
|
||||||
pub view_id: ViewId,
|
pub view_id: ViewId,
|
||||||
pub layer_id: LayerId,
|
pub layer_id: LayerId,
|
||||||
pub order: DrawOrder,
|
pub order: DrawOrder,
|
||||||
|
@ -622,7 +622,7 @@ impl From<MonochromeSprite> for Primitive {
|
||||||
|
|
||||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||||
#[repr(C)]
|
#[repr(C)]
|
||||||
pub struct PolychromeSprite {
|
pub(crate) struct PolychromeSprite {
|
||||||
pub view_id: ViewId,
|
pub view_id: ViewId,
|
||||||
pub layer_id: LayerId,
|
pub layer_id: LayerId,
|
||||||
pub order: DrawOrder,
|
pub order: DrawOrder,
|
||||||
|
|
|
@ -47,7 +47,7 @@ pub struct TextSystem {
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TextSystem {
|
impl TextSystem {
|
||||||
pub fn new(platform_text_system: Arc<dyn PlatformTextSystem>) -> Self {
|
pub(crate) fn new(platform_text_system: Arc<dyn PlatformTextSystem>) -> Self {
|
||||||
TextSystem {
|
TextSystem {
|
||||||
line_layout_cache: Arc::new(LineLayoutCache::new(platform_text_system.clone())),
|
line_layout_cache: Arc::new(LineLayoutCache::new(platform_text_system.clone())),
|
||||||
platform_text_system,
|
platform_text_system,
|
||||||
|
|
|
@ -13,7 +13,7 @@ pub struct LineWrapper {
|
||||||
impl LineWrapper {
|
impl LineWrapper {
|
||||||
pub const MAX_INDENT: u32 = 256;
|
pub const MAX_INDENT: u32 = 256;
|
||||||
|
|
||||||
pub fn new(
|
pub(crate) fn new(
|
||||||
font_id: FontId,
|
font_id: FontId,
|
||||||
font_size: Pixels,
|
font_size: Pixels,
|
||||||
text_system: Arc<dyn PlatformTextSystem>,
|
text_system: Arc<dyn PlatformTextSystem>,
|
||||||
|
|
|
@ -1,3 +1,5 @@
|
||||||
|
#![deny(missing_docs)]
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
seal::Sealed, AnyElement, AnyModel, AnyWeakModel, AppContext, AvailableSpace, BorrowWindow,
|
seal::Sealed, AnyElement, AnyModel, AnyWeakModel, AppContext, AvailableSpace, BorrowWindow,
|
||||||
Bounds, ContentMask, Element, ElementId, Entity, EntityId, Flatten, FocusHandle, FocusableView,
|
Bounds, ContentMask, Element, ElementId, Entity, EntityId, Flatten, FocusHandle, FocusableView,
|
||||||
|
@ -11,12 +13,16 @@ use std::{
|
||||||
hash::{Hash, Hasher},
|
hash::{Hash, Hasher},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/// 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> {
|
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>,
|
pub model: Model<V>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<V> Sealed for View<V> {}
|
impl<V> Sealed for View<V> {}
|
||||||
|
|
||||||
|
#[doc(hidden)]
|
||||||
pub struct AnyViewState {
|
pub struct AnyViewState {
|
||||||
root_style: Style,
|
root_style: Style,
|
||||||
cache_key: Option<ViewCacheKey>,
|
cache_key: Option<ViewCacheKey>,
|
||||||
|
@ -58,6 +64,7 @@ impl<V: 'static> View<V> {
|
||||||
Entity::downgrade(self)
|
Entity::downgrade(self)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Update the view's state with the given function, which is passed a mutable reference and a context.
|
||||||
pub fn update<C, R>(
|
pub fn update<C, R>(
|
||||||
&self,
|
&self,
|
||||||
cx: &mut C,
|
cx: &mut C,
|
||||||
|
@ -69,10 +76,12 @@ impl<V: 'static> View<V> {
|
||||||
cx.update_view(self, f)
|
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 {
|
pub fn read<'a>(&self, cx: &'a AppContext) -> &'a V {
|
||||||
self.model.read(cx)
|
self.model.read(cx)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Gets a [FocusHandle] for this view when its state implements [FocusableView].
|
||||||
pub fn focus_handle(&self, cx: &AppContext) -> FocusHandle
|
pub fn focus_handle(&self, cx: &AppContext) -> FocusHandle
|
||||||
where
|
where
|
||||||
V: FocusableView,
|
V: FocusableView,
|
||||||
|
@ -131,19 +140,24 @@ impl<V> PartialEq for View<V> {
|
||||||
|
|
||||||
impl<V> Eq for View<V> {}
|
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 struct WeakView<V> {
|
||||||
pub(crate) model: WeakModel<V>,
|
pub(crate) model: WeakModel<V>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<V: 'static> WeakView<V> {
|
impl<V: 'static> WeakView<V> {
|
||||||
|
/// Gets the entity id associated with this handle.
|
||||||
pub fn entity_id(&self) -> EntityId {
|
pub fn entity_id(&self) -> EntityId {
|
||||||
self.model.entity_id
|
self.model.entity_id
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Obtain a strong handle for the view if it hasn't been released.
|
||||||
pub fn upgrade(&self) -> Option<View<V>> {
|
pub fn upgrade(&self) -> Option<View<V>> {
|
||||||
Entity::upgrade_from(self)
|
Entity::upgrade_from(self)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Update this view's state if it hasn't been released.
|
||||||
|
/// Returns an error if this view has been released.
|
||||||
pub fn update<C, R>(
|
pub fn update<C, R>(
|
||||||
&self,
|
&self,
|
||||||
cx: &mut C,
|
cx: &mut C,
|
||||||
|
@ -157,9 +171,10 @@ impl<V: 'static> WeakView<V> {
|
||||||
Ok(view.update(cx, f)).flatten()
|
Ok(view.update(cx, f)).flatten()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Assert that the view referenced by this handle has been released.
|
||||||
#[cfg(any(test, feature = "test-support"))]
|
#[cfg(any(test, feature = "test-support"))]
|
||||||
pub fn assert_dropped(&self) {
|
pub fn assert_released(&self) {
|
||||||
self.model.assert_dropped()
|
self.model.assert_released()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -185,6 +200,7 @@ impl<V> PartialEq for WeakView<V> {
|
||||||
|
|
||||||
impl<V> Eq for WeakView<V> {}
|
impl<V> Eq for WeakView<V> {}
|
||||||
|
|
||||||
|
/// A dynically-typed handle to a view, which can be downcast to a [View] for a specific type.
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
pub struct AnyView {
|
pub struct AnyView {
|
||||||
model: AnyModel,
|
model: AnyModel,
|
||||||
|
@ -193,11 +209,15 @@ pub struct AnyView {
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AnyView {
|
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.
|
||||||
|
/// The one exception is when [WindowContext::refresh] is called, in which case caching is ignored.
|
||||||
pub fn cached(mut self) -> Self {
|
pub fn cached(mut self) -> Self {
|
||||||
self.cache = true;
|
self.cache = true;
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Convert this to a weak handle.
|
||||||
pub fn downgrade(&self) -> AnyWeakView {
|
pub fn downgrade(&self) -> AnyWeakView {
|
||||||
AnyWeakView {
|
AnyWeakView {
|
||||||
model: self.model.downgrade(),
|
model: self.model.downgrade(),
|
||||||
|
@ -205,6 +225,8 @@ 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<View<T>, Self> {
|
||||||
match self.model.downcast() {
|
match self.model.downcast() {
|
||||||
Ok(model) => Ok(View { model }),
|
Ok(model) => Ok(View { model }),
|
||||||
|
@ -216,10 +238,12 @@ impl AnyView {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Gets the [TypeId] of the underlying view.
|
||||||
pub fn entity_type(&self) -> TypeId {
|
pub fn entity_type(&self) -> TypeId {
|
||||||
self.model.entity_type
|
self.model.entity_type
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Gets the entity id of this handle.
|
||||||
pub fn entity_id(&self) -> EntityId {
|
pub fn entity_id(&self) -> EntityId {
|
||||||
self.model.entity_id()
|
self.model.entity_id()
|
||||||
}
|
}
|
||||||
|
@ -337,12 +361,14 @@ impl IntoElement for AnyView {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A weak, dynamically-typed view handle that does not prevent the view from being released.
|
||||||
pub struct AnyWeakView {
|
pub struct AnyWeakView {
|
||||||
model: AnyWeakModel,
|
model: AnyWeakModel,
|
||||||
layout: fn(&AnyView, &mut WindowContext) -> (LayoutId, AnyElement),
|
layout: fn(&AnyView, &mut WindowContext) -> (LayoutId, AnyElement),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AnyWeakView {
|
impl AnyWeakView {
|
||||||
|
/// Convert to a strongly-typed handle if the referenced view has not yet been released.
|
||||||
pub fn upgrade(&self) -> Option<AnyView> {
|
pub fn upgrade(&self) -> Option<AnyView> {
|
||||||
let model = self.model.upgrade()?;
|
let model = self.model.upgrade()?;
|
||||||
Some(AnyView {
|
Some(AnyView {
|
||||||
|
|
|
@ -1809,9 +1809,9 @@ mod tests {
|
||||||
assert!(workspace.active_item(cx).is_none());
|
assert!(workspace.active_item(cx).is_none());
|
||||||
})
|
})
|
||||||
.unwrap();
|
.unwrap();
|
||||||
editor_1.assert_dropped();
|
editor_1.assert_released();
|
||||||
editor_2.assert_dropped();
|
editor_2.assert_released();
|
||||||
buffer.assert_dropped();
|
buffer.assert_released();
|
||||||
}
|
}
|
||||||
|
|
||||||
#[gpui::test]
|
#[gpui::test]
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue