Merge branch 'main' into unborked-git-zed2-diagnostics-view
This commit is contained in:
+118
-131
@@ -1,10 +1,12 @@
|
||||
use crate::SharedString;
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use collections::HashMap;
|
||||
use lazy_static::lazy_static;
|
||||
use parking_lot::{MappedRwLockReadGuard, RwLock, RwLockReadGuard};
|
||||
use serde::Deserialize;
|
||||
use std::any::{type_name, Any, TypeId};
|
||||
pub use no_action::NoAction;
|
||||
use serde_json::json;
|
||||
use std::{
|
||||
any::{Any, TypeId},
|
||||
ops::Deref,
|
||||
};
|
||||
|
||||
/// Actions are used to implement keyboard-driven UI.
|
||||
/// When you declare an action, you can bind keys to the action in the keymap and
|
||||
@@ -15,24 +17,16 @@ use std::any::{type_name, Any, TypeId};
|
||||
/// ```rust
|
||||
/// actions!(MoveUp, MoveDown, MoveLeft, MoveRight, Newline);
|
||||
/// ```
|
||||
/// More complex data types can also be actions. If you annotate your type with the `#[action]` proc macro,
|
||||
/// it will automatically
|
||||
/// More complex data types can also be actions. If you annotate your type with the action derive macro
|
||||
/// it will be implemented and registered automatically.
|
||||
/// ```
|
||||
/// #[action]
|
||||
/// #[derive(Clone, PartialEq, serde_derive::Deserialize, Action)]
|
||||
/// pub struct SelectNext {
|
||||
/// pub replace_newest: bool,
|
||||
/// }
|
||||
///
|
||||
/// Any type A that satisfies the following bounds is automatically an action:
|
||||
///
|
||||
/// ```
|
||||
/// A: for<'a> Deserialize<'a> + PartialEq + Clone + Default + std::fmt::Debug + 'static,
|
||||
/// ```
|
||||
///
|
||||
/// The `#[action]` annotation will derive these implementations for your struct automatically. If you
|
||||
/// want to control them manually, you can use the lower-level `#[register_action]` macro, which only
|
||||
/// generates the code needed to register your action before `main`. Then you'll need to implement all
|
||||
/// the traits manually.
|
||||
/// If you want to control the behavior of the action trait manually, you can use the lower-level `#[register_action]`
|
||||
/// macro, which only generates the code needed to register your action before `main`.
|
||||
///
|
||||
/// ```
|
||||
/// #[gpui::register_action]
|
||||
@@ -41,77 +35,29 @@ use std::any::{type_name, Any, TypeId};
|
||||
/// pub content: SharedString,
|
||||
/// }
|
||||
///
|
||||
/// impl std::default::Default for Paste {
|
||||
/// fn default() -> Self {
|
||||
/// Self {
|
||||
/// content: SharedString::from("🍝"),
|
||||
/// }
|
||||
/// }
|
||||
/// impl gpui::Action for Paste {
|
||||
/// ///...
|
||||
/// }
|
||||
/// ```
|
||||
pub trait Action: std::fmt::Debug + 'static {
|
||||
fn qualified_name() -> SharedString
|
||||
where
|
||||
Self: Sized;
|
||||
fn build(value: Option<serde_json::Value>) -> Result<Box<dyn Action>>
|
||||
where
|
||||
Self: Sized;
|
||||
fn is_registered() -> bool
|
||||
where
|
||||
Self: Sized;
|
||||
|
||||
fn partial_eq(&self, action: &dyn Action) -> bool;
|
||||
pub trait Action: 'static {
|
||||
fn boxed_clone(&self) -> Box<dyn Action>;
|
||||
fn as_any(&self) -> &dyn Any;
|
||||
fn partial_eq(&self, action: &dyn Action) -> bool;
|
||||
fn name(&self) -> &str;
|
||||
|
||||
fn debug_name() -> &'static str
|
||||
where
|
||||
Self: Sized;
|
||||
fn build(value: serde_json::Value) -> Result<Box<dyn Action>>
|
||||
where
|
||||
Self: Sized;
|
||||
}
|
||||
|
||||
// Types become actions by satisfying a list of trait bounds.
|
||||
impl<A> Action for A
|
||||
where
|
||||
A: for<'a> Deserialize<'a> + PartialEq + Clone + Default + std::fmt::Debug + 'static,
|
||||
{
|
||||
fn qualified_name() -> SharedString {
|
||||
let name = type_name::<A>();
|
||||
let mut separator_matches = name.rmatch_indices("::");
|
||||
separator_matches.next().unwrap();
|
||||
let name_start_ix = separator_matches.next().map_or(0, |(ix, _)| ix + 2);
|
||||
// todo!() remove the 2 replacement when migration is done
|
||||
name[name_start_ix..].replace("2::", "::").into()
|
||||
}
|
||||
|
||||
fn build(params: Option<serde_json::Value>) -> Result<Box<dyn Action>>
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
let action = if let Some(params) = params {
|
||||
serde_json::from_value(params).context("failed to deserialize action")?
|
||||
} else {
|
||||
Self::default()
|
||||
};
|
||||
Ok(Box::new(action))
|
||||
}
|
||||
|
||||
fn is_registered() -> bool {
|
||||
ACTION_REGISTRY
|
||||
.read()
|
||||
.names_by_type_id
|
||||
.get(&TypeId::of::<A>())
|
||||
.is_some()
|
||||
}
|
||||
|
||||
fn partial_eq(&self, action: &dyn Action) -> bool {
|
||||
action
|
||||
.as_any()
|
||||
.downcast_ref::<Self>()
|
||||
.map_or(false, |a| self == a)
|
||||
}
|
||||
|
||||
fn boxed_clone(&self) -> Box<dyn Action> {
|
||||
Box::new(self.clone())
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &dyn Any {
|
||||
self
|
||||
impl std::fmt::Debug for dyn Action {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("dyn Action")
|
||||
.field("type_name", &self.name())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -119,69 +65,93 @@ impl dyn Action {
|
||||
pub fn type_id(&self) -> TypeId {
|
||||
self.as_any().type_id()
|
||||
}
|
||||
|
||||
pub fn name(&self) -> SharedString {
|
||||
ACTION_REGISTRY
|
||||
.read()
|
||||
.names_by_type_id
|
||||
.get(&self.type_id())
|
||||
.expect("type is not a registered action")
|
||||
.clone()
|
||||
}
|
||||
}
|
||||
|
||||
type ActionBuilder = fn(json: Option<serde_json::Value>) -> anyhow::Result<Box<dyn Action>>;
|
||||
type ActionBuilder = fn(json: serde_json::Value) -> anyhow::Result<Box<dyn Action>>;
|
||||
|
||||
lazy_static! {
|
||||
static ref ACTION_REGISTRY: RwLock<ActionRegistry> = RwLock::default();
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct ActionRegistry {
|
||||
pub(crate) struct ActionRegistry {
|
||||
builders_by_name: HashMap<SharedString, ActionBuilder>,
|
||||
names_by_type_id: HashMap<TypeId, SharedString>,
|
||||
all_names: Vec<SharedString>, // So we can return a static slice.
|
||||
}
|
||||
|
||||
/// Register an action type to allow it to be referenced in keymaps.
|
||||
pub fn register_action<A: Action>() {
|
||||
let name = A::qualified_name();
|
||||
let mut lock = ACTION_REGISTRY.write();
|
||||
lock.builders_by_name.insert(name.clone(), A::build);
|
||||
lock.names_by_type_id
|
||||
.insert(TypeId::of::<A>(), name.clone());
|
||||
lock.all_names.push(name);
|
||||
impl Default for ActionRegistry {
|
||||
fn default() -> Self {
|
||||
let mut this = ActionRegistry {
|
||||
builders_by_name: Default::default(),
|
||||
names_by_type_id: Default::default(),
|
||||
all_names: Default::default(),
|
||||
};
|
||||
|
||||
this.load_actions();
|
||||
|
||||
this
|
||||
}
|
||||
}
|
||||
|
||||
/// Construct an action based on its name and optional JSON parameters sourced from the keymap.
|
||||
pub fn build_action_from_type(type_id: &TypeId) -> Result<Box<dyn Action>> {
|
||||
let lock = ACTION_REGISTRY.read();
|
||||
let name = lock
|
||||
.names_by_type_id
|
||||
.get(type_id)
|
||||
.ok_or_else(|| anyhow!("no action type registered for {:?}", type_id))?
|
||||
.clone();
|
||||
drop(lock);
|
||||
/// This type must be public so that our macros can build it in other crates.
|
||||
/// But this is an implementation detail and should not be used directly.
|
||||
#[doc(hidden)]
|
||||
pub type MacroActionBuilder = fn() -> ActionData;
|
||||
|
||||
build_action(&name, None)
|
||||
/// This type must be public so that our macros can build it in other crates.
|
||||
/// But this is an implementation detail and should not be used directly.
|
||||
#[doc(hidden)]
|
||||
pub struct ActionData {
|
||||
pub name: &'static str,
|
||||
pub type_id: TypeId,
|
||||
pub build: ActionBuilder,
|
||||
}
|
||||
|
||||
/// Construct an action based on its name and optional JSON parameters sourced from the keymap.
|
||||
pub fn build_action(name: &str, params: Option<serde_json::Value>) -> Result<Box<dyn Action>> {
|
||||
let lock = ACTION_REGISTRY.read();
|
||||
/// This constant must be public to be accessible from other crates.
|
||||
/// But it's existence is an implementation detail and should not be used directly.
|
||||
#[doc(hidden)]
|
||||
#[linkme::distributed_slice]
|
||||
pub static __GPUI_ACTIONS: [MacroActionBuilder];
|
||||
|
||||
let build_action = lock
|
||||
.builders_by_name
|
||||
.get(name)
|
||||
.ok_or_else(|| anyhow!("no action type registered for {}", name))?;
|
||||
(build_action)(params)
|
||||
}
|
||||
impl ActionRegistry {
|
||||
/// Load all registered actions into the registry.
|
||||
pub(crate) fn load_actions(&mut self) {
|
||||
for builder in __GPUI_ACTIONS {
|
||||
let action = builder();
|
||||
//todo(remove)
|
||||
let name: SharedString = remove_the_2(action.name).into();
|
||||
self.builders_by_name.insert(name.clone(), action.build);
|
||||
self.names_by_type_id.insert(action.type_id, name.clone());
|
||||
self.all_names.push(name);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn all_action_names() -> MappedRwLockReadGuard<'static, [SharedString]> {
|
||||
let lock = ACTION_REGISTRY.read();
|
||||
RwLockReadGuard::map(lock, |registry: &ActionRegistry| {
|
||||
registry.all_names.as_slice()
|
||||
})
|
||||
/// Construct an action based on its name and optional JSON parameters sourced from the keymap.
|
||||
pub fn build_action_type(&self, type_id: &TypeId) -> Result<Box<dyn Action>> {
|
||||
let name = self
|
||||
.names_by_type_id
|
||||
.get(type_id)
|
||||
.ok_or_else(|| anyhow!("no action type registered for {:?}", type_id))?
|
||||
.clone();
|
||||
|
||||
self.build_action(&name, None)
|
||||
}
|
||||
|
||||
/// Construct an action based on its name and optional JSON parameters sourced from the keymap.
|
||||
pub fn build_action(
|
||||
&self,
|
||||
name: &str,
|
||||
params: Option<serde_json::Value>,
|
||||
) -> Result<Box<dyn Action>> {
|
||||
//todo(remove)
|
||||
let name = remove_the_2(name);
|
||||
let build_action = self
|
||||
.builders_by_name
|
||||
.get(name.deref())
|
||||
.ok_or_else(|| anyhow!("no action type registered for {}", name))?;
|
||||
(build_action)(params.unwrap_or_else(|| json!({})))
|
||||
.with_context(|| format!("Attempting to build action {}", name))
|
||||
}
|
||||
|
||||
pub fn all_action_names(&self) -> &[SharedString] {
|
||||
self.all_names.as_slice()
|
||||
}
|
||||
}
|
||||
|
||||
/// Defines unit structs that can be used as actions.
|
||||
@@ -191,7 +161,7 @@ macro_rules! actions {
|
||||
() => {};
|
||||
|
||||
( $name:ident ) => {
|
||||
#[gpui::action]
|
||||
#[derive(::std::cmp::PartialEq, ::std::clone::Clone, ::std::default::Default, gpui::serde_derive::Deserialize, gpui::Action)]
|
||||
pub struct $name;
|
||||
};
|
||||
|
||||
@@ -200,3 +170,20 @@ macro_rules! actions {
|
||||
actions!($($rest)*);
|
||||
};
|
||||
}
|
||||
|
||||
//todo!(remove)
|
||||
pub fn remove_the_2(action_name: &str) -> String {
|
||||
let mut separator_matches = action_name.rmatch_indices("::");
|
||||
separator_matches.next().unwrap();
|
||||
let name_start_ix = separator_matches.next().map_or(0, |(ix, _)| ix + 2);
|
||||
// todo!() remove the 2 replacement when migration is done
|
||||
action_name[name_start_ix..]
|
||||
.replace("2::", "::")
|
||||
.to_string()
|
||||
}
|
||||
|
||||
mod no_action {
|
||||
use crate as gpui;
|
||||
|
||||
actions!(NoAction);
|
||||
}
|
||||
|
||||
+21
-6
@@ -14,12 +14,13 @@ use smallvec::SmallVec;
|
||||
pub use test_context::*;
|
||||
|
||||
use crate::{
|
||||
current_platform, image_cache::ImageCache, Action, AnyBox, AnyView, AnyWindowHandle,
|
||||
AppMetadata, AssetSource, BackgroundExecutor, ClipboardItem, Context, DispatchPhase, DisplayId,
|
||||
Entity, EventEmitter, FocusEvent, FocusHandle, FocusId, ForegroundExecutor, KeyBinding, Keymap,
|
||||
LayoutId, PathPromptOptions, Pixels, Platform, PlatformDisplay, Point, Render, SubscriberSet,
|
||||
Subscription, SvgRenderer, Task, TextStyle, TextStyleRefinement, TextSystem, View, ViewContext,
|
||||
Window, WindowContext, WindowHandle, WindowId,
|
||||
current_platform, image_cache::ImageCache, Action, ActionRegistry, AnyBox, AnyView,
|
||||
AnyWindowHandle, AppMetadata, AssetSource, BackgroundExecutor, ClipboardItem, Context,
|
||||
DispatchPhase, DisplayId, Entity, EventEmitter, FocusEvent, FocusHandle, FocusId,
|
||||
ForegroundExecutor, KeyBinding, Keymap, LayoutId, PathPromptOptions, Pixels, Platform,
|
||||
PlatformDisplay, Point, Render, SharedString, SubscriberSet, Subscription, SvgRenderer, Task,
|
||||
TextStyle, TextStyleRefinement, TextSystem, View, ViewContext, Window, WindowContext,
|
||||
WindowHandle, WindowId,
|
||||
};
|
||||
use anyhow::{anyhow, Result};
|
||||
use collections::{HashMap, HashSet, VecDeque};
|
||||
@@ -182,6 +183,7 @@ pub struct AppContext {
|
||||
text_system: Arc<TextSystem>,
|
||||
flushing_effects: bool,
|
||||
pending_updates: usize,
|
||||
pub(crate) actions: Rc<ActionRegistry>,
|
||||
pub(crate) active_drag: Option<AnyDrag>,
|
||||
pub(crate) active_tooltip: Option<AnyTooltip>,
|
||||
pub(crate) next_frame_callbacks: HashMap<DisplayId, Vec<FrameCallback>>,
|
||||
@@ -240,6 +242,7 @@ impl AppContext {
|
||||
platform: platform.clone(),
|
||||
app_metadata,
|
||||
text_system,
|
||||
actions: Rc::new(ActionRegistry::default()),
|
||||
flushing_effects: false,
|
||||
pending_updates: 0,
|
||||
active_drag: None,
|
||||
@@ -964,6 +967,18 @@ impl AppContext {
|
||||
pub fn propagate(&mut self) {
|
||||
self.propagate_event = true;
|
||||
}
|
||||
|
||||
pub fn build_action(
|
||||
&self,
|
||||
name: &str,
|
||||
data: Option<serde_json::Value>,
|
||||
) -> Result<Box<dyn Action>> {
|
||||
self.actions.build_action(name, data)
|
||||
}
|
||||
|
||||
pub fn all_action_names(&self) -> &[SharedString] {
|
||||
self.actions.all_action_names()
|
||||
}
|
||||
}
|
||||
|
||||
impl Context for AppContext {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use crate::{
|
||||
AnyView, AnyWindowHandle, AppCell, AppContext, BackgroundExecutor, Context, ForegroundExecutor,
|
||||
Model, ModelContext, Render, Result, Task, View, ViewContext, VisualContext, WindowContext,
|
||||
WindowHandle,
|
||||
AnyView, AnyWindowHandle, AppCell, AppContext, BackgroundExecutor, Context, FocusableView,
|
||||
ForegroundExecutor, Model, ModelContext, Render, Result, Task, View, ViewContext,
|
||||
VisualContext, WindowContext, WindowHandle,
|
||||
};
|
||||
use anyhow::{anyhow, Context as _};
|
||||
use derive_more::{Deref, DerefMut};
|
||||
@@ -182,6 +182,10 @@ pub struct AsyncWindowContext {
|
||||
}
|
||||
|
||||
impl AsyncWindowContext {
|
||||
pub fn window_handle(&self) -> AnyWindowHandle {
|
||||
self.window
|
||||
}
|
||||
|
||||
pub(crate) fn new(app: AsyncAppContext, window: AnyWindowHandle) -> Self {
|
||||
Self { app, window }
|
||||
}
|
||||
@@ -307,4 +311,13 @@ impl VisualContext for AsyncWindowContext {
|
||||
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);
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -68,6 +68,7 @@ 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);
|
||||
let entity = Some(
|
||||
|
||||
@@ -370,10 +370,19 @@ impl<T: Send> Model<T> {
|
||||
})
|
||||
});
|
||||
|
||||
cx.executor().run_until_parked();
|
||||
rx.try_next()
|
||||
.expect("no event received")
|
||||
.expect("model was dropped")
|
||||
// Run other tasks until the event is emitted.
|
||||
loop {
|
||||
match rx.try_next() {
|
||||
Ok(Some(event)) => return event,
|
||||
Ok(None) => panic!("model was dropped"),
|
||||
Err(_) => {
|
||||
if !cx.executor().tick() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
panic!("no event received")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -588,6 +597,14 @@ impl<'a> VisualContext for VisualTestContext<'a> {
|
||||
.update(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(self.cx, |_, cx| {
|
||||
view.read(cx).focus_handle(cx).clone().focus(cx)
|
||||
})
|
||||
.unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl AnyWindowHandle {
|
||||
|
||||
+17
-73
@@ -10,21 +10,12 @@ pub trait Element<V: 'static> {
|
||||
|
||||
fn element_id(&self) -> Option<ElementId>;
|
||||
|
||||
/// Called to initialize this element for the current frame. If this
|
||||
/// element had state in a previous frame, it will be passed in for the 3rd argument.
|
||||
fn initialize(
|
||||
fn layout(
|
||||
&mut self,
|
||||
view_state: &mut V,
|
||||
element_state: Option<Self::ElementState>,
|
||||
cx: &mut ViewContext<V>,
|
||||
) -> Self::ElementState;
|
||||
|
||||
fn layout(
|
||||
&mut self,
|
||||
view_state: &mut V,
|
||||
element_state: &mut Self::ElementState,
|
||||
cx: &mut ViewContext<V>,
|
||||
) -> LayoutId;
|
||||
) -> (LayoutId, Self::ElementState);
|
||||
|
||||
fn paint(
|
||||
&mut self,
|
||||
@@ -97,7 +88,6 @@ pub trait ParentComponent<V: 'static> {
|
||||
|
||||
trait ElementObject<V> {
|
||||
fn element_id(&self) -> Option<ElementId>;
|
||||
fn initialize(&mut self, view_state: &mut V, cx: &mut ViewContext<V>);
|
||||
fn layout(&mut self, view_state: &mut V, cx: &mut ViewContext<V>) -> LayoutId;
|
||||
fn paint(&mut self, view_state: &mut V, cx: &mut ViewContext<V>);
|
||||
fn measure(
|
||||
@@ -124,9 +114,6 @@ struct RenderedElement<V: 'static, E: Element<V>> {
|
||||
enum ElementRenderPhase<V> {
|
||||
#[default]
|
||||
Start,
|
||||
Initialized {
|
||||
frame_state: Option<V>,
|
||||
},
|
||||
LayoutRequested {
|
||||
layout_id: LayoutId,
|
||||
frame_state: Option<V>,
|
||||
@@ -162,42 +149,19 @@ where
|
||||
self.element.element_id()
|
||||
}
|
||||
|
||||
fn initialize(&mut self, view_state: &mut V, cx: &mut ViewContext<V>) {
|
||||
let frame_state = if let Some(id) = self.element.element_id() {
|
||||
cx.with_element_state(id, |element_state, cx| {
|
||||
let element_state = self.element.initialize(view_state, element_state, cx);
|
||||
((), element_state)
|
||||
});
|
||||
None
|
||||
} else {
|
||||
let frame_state = self.element.initialize(view_state, None, cx);
|
||||
Some(frame_state)
|
||||
};
|
||||
|
||||
self.phase = ElementRenderPhase::Initialized { frame_state };
|
||||
}
|
||||
|
||||
fn layout(&mut self, state: &mut V, cx: &mut ViewContext<V>) -> LayoutId {
|
||||
let layout_id;
|
||||
let mut frame_state;
|
||||
match mem::take(&mut self.phase) {
|
||||
ElementRenderPhase::Initialized {
|
||||
frame_state: initial_frame_state,
|
||||
} => {
|
||||
frame_state = initial_frame_state;
|
||||
let (layout_id, frame_state) = match mem::take(&mut self.phase) {
|
||||
ElementRenderPhase::Start => {
|
||||
if let Some(id) = self.element.element_id() {
|
||||
layout_id = cx.with_element_state(id, |element_state, cx| {
|
||||
let mut element_state = element_state.unwrap();
|
||||
let layout_id = self.element.layout(state, &mut element_state, cx);
|
||||
(layout_id, element_state)
|
||||
let layout_id = cx.with_element_state(id, |element_state, cx| {
|
||||
self.element.layout(state, element_state, cx)
|
||||
});
|
||||
(layout_id, None)
|
||||
} else {
|
||||
layout_id = self
|
||||
.element
|
||||
.layout(state, frame_state.as_mut().unwrap(), cx);
|
||||
let (layout_id, frame_state) = self.element.layout(state, None, cx);
|
||||
(layout_id, Some(frame_state))
|
||||
}
|
||||
}
|
||||
ElementRenderPhase::Start => panic!("must call initialize before layout"),
|
||||
ElementRenderPhase::LayoutRequested { .. }
|
||||
| ElementRenderPhase::LayoutComputed { .. }
|
||||
| ElementRenderPhase::Painted { .. } => {
|
||||
@@ -249,10 +213,6 @@ where
|
||||
cx: &mut ViewContext<V>,
|
||||
) -> Size<Pixels> {
|
||||
if matches!(&self.phase, ElementRenderPhase::Start) {
|
||||
self.initialize(view_state, cx);
|
||||
}
|
||||
|
||||
if matches!(&self.phase, ElementRenderPhase::Initialized { .. }) {
|
||||
self.layout(view_state, cx);
|
||||
}
|
||||
|
||||
@@ -289,16 +249,13 @@ where
|
||||
|
||||
fn draw(
|
||||
&mut self,
|
||||
mut origin: Point<Pixels>,
|
||||
origin: Point<Pixels>,
|
||||
available_space: Size<AvailableSpace>,
|
||||
view_state: &mut V,
|
||||
cx: &mut ViewContext<V>,
|
||||
) {
|
||||
self.measure(available_space, view_state, cx);
|
||||
// Ignore the element offset when drawing this element, as the origin is already specified
|
||||
// in absolute terms.
|
||||
origin -= cx.element_offset();
|
||||
cx.with_element_offset(origin, |cx| self.paint(view_state, cx))
|
||||
cx.with_absolute_element_offset(origin, |cx| self.paint(view_state, cx))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -318,10 +275,6 @@ impl<V> AnyElement<V> {
|
||||
self.0.element_id()
|
||||
}
|
||||
|
||||
pub fn initialize(&mut self, view_state: &mut V, cx: &mut ViewContext<V>) {
|
||||
self.0.initialize(view_state, cx);
|
||||
}
|
||||
|
||||
pub fn layout(&mut self, view_state: &mut V, cx: &mut ViewContext<V>) -> LayoutId {
|
||||
self.0.layout(view_state, cx)
|
||||
}
|
||||
@@ -402,25 +355,16 @@ where
|
||||
None
|
||||
}
|
||||
|
||||
fn initialize(
|
||||
&mut self,
|
||||
view_state: &mut V,
|
||||
_rendered_element: Option<Self::ElementState>,
|
||||
cx: &mut ViewContext<V>,
|
||||
) -> Self::ElementState {
|
||||
let render = self.take().unwrap();
|
||||
let mut rendered_element = (render)(view_state, cx).render();
|
||||
rendered_element.initialize(view_state, cx);
|
||||
rendered_element
|
||||
}
|
||||
|
||||
fn layout(
|
||||
&mut self,
|
||||
view_state: &mut V,
|
||||
rendered_element: &mut Self::ElementState,
|
||||
_: Option<Self::ElementState>,
|
||||
cx: &mut ViewContext<V>,
|
||||
) -> LayoutId {
|
||||
rendered_element.layout(view_state, cx)
|
||||
) -> (LayoutId, Self::ElementState) {
|
||||
let render = self.take().unwrap();
|
||||
let mut rendered_element = (render)(view_state, cx).render();
|
||||
let layout_id = rendered_element.layout(view_state, cx);
|
||||
(layout_id, rendered_element)
|
||||
}
|
||||
|
||||
fn paint(
|
||||
|
||||
@@ -22,7 +22,6 @@ use util::ResultExt;
|
||||
|
||||
const DRAG_THRESHOLD: f64 = 2.;
|
||||
const TOOLTIP_DELAY: Duration = Duration::from_millis(500);
|
||||
const TOOLTIP_OFFSET: Point<Pixels> = Point::new(px(10.0), px(8.0));
|
||||
|
||||
pub struct GroupStyle {
|
||||
pub group: SharedString,
|
||||
@@ -238,11 +237,11 @@ pub trait InteractiveComponent<V: 'static>: Sized + Element<V> {
|
||||
//
|
||||
// if we are relying on this side-effect still, removing the debug_assert!
|
||||
// likely breaks the command_palette tests.
|
||||
debug_assert!(
|
||||
A::is_registered(),
|
||||
"{:?} is not registered as an action",
|
||||
A::qualified_name()
|
||||
);
|
||||
// debug_assert!(
|
||||
// A::is_registered(),
|
||||
// "{:?} is not registered as an action",
|
||||
// A::qualified_name()
|
||||
// );
|
||||
self.interactivity().action_listeners.push((
|
||||
TypeId::of::<A>(),
|
||||
Box::new(move |view, action, phase, cx| {
|
||||
@@ -408,21 +407,19 @@ pub trait StatefulInteractiveComponent<V: 'static, E: Element<V>>: InteractiveCo
|
||||
self
|
||||
}
|
||||
|
||||
fn tooltip<W>(
|
||||
fn tooltip(
|
||||
mut self,
|
||||
build_tooltip: impl Fn(&mut V, &mut ViewContext<V>) -> View<W> + 'static,
|
||||
build_tooltip: impl Fn(&mut V, &mut ViewContext<V>) -> AnyView + 'static,
|
||||
) -> Self
|
||||
where
|
||||
Self: Sized,
|
||||
W: 'static + Render,
|
||||
{
|
||||
debug_assert!(
|
||||
self.interactivity().tooltip_builder.is_none(),
|
||||
"calling tooltip more than once on the same element is not supported"
|
||||
);
|
||||
self.interactivity().tooltip_builder = Some(Rc::new(move |view_state, cx| {
|
||||
build_tooltip(view_state, cx).into()
|
||||
}));
|
||||
self.interactivity().tooltip_builder =
|
||||
Some(Rc::new(move |view_state, cx| build_tooltip(view_state, cx)));
|
||||
|
||||
self
|
||||
}
|
||||
@@ -437,14 +434,6 @@ pub trait FocusableComponent<V: 'static>: InteractiveComponent<V> {
|
||||
self
|
||||
}
|
||||
|
||||
fn focus_in(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
self.interactivity().focus_in_style = f(StyleRefinement::default());
|
||||
self
|
||||
}
|
||||
|
||||
fn in_focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
|
||||
where
|
||||
Self: Sized,
|
||||
@@ -617,46 +606,36 @@ impl<V: 'static> Element<V> for Div<V> {
|
||||
self.interactivity.element_id.clone()
|
||||
}
|
||||
|
||||
fn initialize(
|
||||
fn layout(
|
||||
&mut self,
|
||||
view_state: &mut V,
|
||||
element_state: Option<Self::ElementState>,
|
||||
cx: &mut ViewContext<V>,
|
||||
) -> Self::ElementState {
|
||||
let interactive_state = self
|
||||
.interactivity
|
||||
.initialize(element_state.map(|s| s.interactive_state), cx);
|
||||
|
||||
for child in &mut self.children {
|
||||
child.initialize(view_state, cx);
|
||||
}
|
||||
|
||||
DivState {
|
||||
interactive_state,
|
||||
child_layout_ids: SmallVec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn layout(
|
||||
&mut self,
|
||||
view_state: &mut V,
|
||||
element_state: &mut Self::ElementState,
|
||||
cx: &mut ViewContext<V>,
|
||||
) -> crate::LayoutId {
|
||||
) -> (LayoutId, Self::ElementState) {
|
||||
let mut child_layout_ids = SmallVec::new();
|
||||
let mut interactivity = mem::take(&mut self.interactivity);
|
||||
let layout_id =
|
||||
interactivity.layout(&mut element_state.interactive_state, cx, |style, cx| {
|
||||
let (layout_id, interactive_state) = interactivity.layout(
|
||||
element_state.map(|s| s.interactive_state),
|
||||
cx,
|
||||
|style, cx| {
|
||||
cx.with_text_style(style.text_style().cloned(), |cx| {
|
||||
element_state.child_layout_ids = self
|
||||
child_layout_ids = self
|
||||
.children
|
||||
.iter_mut()
|
||||
.map(|child| child.layout(view_state, cx))
|
||||
.collect::<SmallVec<_>>();
|
||||
cx.request_layout(&style, element_state.child_layout_ids.iter().copied())
|
||||
cx.request_layout(&style, child_layout_ids.iter().copied())
|
||||
})
|
||||
});
|
||||
},
|
||||
);
|
||||
self.interactivity = interactivity;
|
||||
layout_id
|
||||
(
|
||||
layout_id,
|
||||
DivState {
|
||||
interactive_state,
|
||||
child_layout_ids,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn paint(
|
||||
@@ -740,7 +719,6 @@ pub struct Interactivity<V> {
|
||||
pub group: Option<SharedString>,
|
||||
pub base_style: StyleRefinement,
|
||||
pub focus_style: StyleRefinement,
|
||||
pub focus_in_style: StyleRefinement,
|
||||
pub in_focus_style: StyleRefinement,
|
||||
pub hover_style: StyleRefinement,
|
||||
pub group_hover_style: Option<GroupStyle>,
|
||||
@@ -766,11 +744,12 @@ impl<V> Interactivity<V>
|
||||
where
|
||||
V: 'static,
|
||||
{
|
||||
pub fn initialize(
|
||||
pub fn layout(
|
||||
&mut self,
|
||||
element_state: Option<InteractiveElementState>,
|
||||
cx: &mut ViewContext<V>,
|
||||
) -> InteractiveElementState {
|
||||
f: impl FnOnce(Style, &mut ViewContext<V>) -> LayoutId,
|
||||
) -> (LayoutId, InteractiveElementState) {
|
||||
let mut element_state = element_state.unwrap_or_default();
|
||||
|
||||
// Ensure we store a focus handle in our element state if we're focusable.
|
||||
@@ -785,17 +764,9 @@ where
|
||||
});
|
||||
}
|
||||
|
||||
element_state
|
||||
}
|
||||
|
||||
pub fn layout(
|
||||
&mut self,
|
||||
element_state: &mut InteractiveElementState,
|
||||
cx: &mut ViewContext<V>,
|
||||
f: impl FnOnce(Style, &mut ViewContext<V>) -> LayoutId,
|
||||
) -> LayoutId {
|
||||
let style = self.compute_style(None, element_state, cx);
|
||||
f(style, cx)
|
||||
let style = self.compute_style(None, &mut element_state, cx);
|
||||
let layout_id = f(style, cx);
|
||||
(layout_id, element_state)
|
||||
}
|
||||
|
||||
pub fn paint(
|
||||
@@ -989,11 +960,11 @@ where
|
||||
cx.background_executor().timer(TOOLTIP_DELAY).await;
|
||||
view.update(&mut cx, move |view_state, cx| {
|
||||
active_tooltip.borrow_mut().replace(ActiveTooltip {
|
||||
waiting: None,
|
||||
tooltip: Some(AnyTooltip {
|
||||
view: tooltip_builder(view_state, cx),
|
||||
cursor_offset: cx.mouse_position() + TOOLTIP_OFFSET,
|
||||
cursor_offset: cx.mouse_position(),
|
||||
}),
|
||||
_task: None,
|
||||
});
|
||||
cx.notify();
|
||||
})
|
||||
@@ -1001,12 +972,17 @@ where
|
||||
}
|
||||
});
|
||||
active_tooltip.borrow_mut().replace(ActiveTooltip {
|
||||
waiting: Some(task),
|
||||
tooltip: None,
|
||||
_task: Some(task),
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
let active_tooltip = element_state.active_tooltip.clone();
|
||||
cx.on_mouse_event(move |_, _: &MouseDownEvent, _, _| {
|
||||
active_tooltip.borrow_mut().take();
|
||||
});
|
||||
|
||||
if let Some(active_tooltip) = element_state.active_tooltip.borrow().as_ref() {
|
||||
if active_tooltip.tooltip.is_some() {
|
||||
cx.active_tooltip = active_tooltip.tooltip.clone()
|
||||
@@ -1130,10 +1106,6 @@ where
|
||||
style.refine(&self.base_style);
|
||||
|
||||
if let Some(focus_handle) = self.tracked_focus_handle.as_ref() {
|
||||
if focus_handle.contains_focused(cx) {
|
||||
style.refine(&self.focus_in_style);
|
||||
}
|
||||
|
||||
if focus_handle.within_focused(cx) {
|
||||
style.refine(&self.in_focus_style);
|
||||
}
|
||||
@@ -1206,7 +1178,6 @@ impl<V: 'static> Default for Interactivity<V> {
|
||||
group: None,
|
||||
base_style: StyleRefinement::default(),
|
||||
focus_style: StyleRefinement::default(),
|
||||
focus_in_style: StyleRefinement::default(),
|
||||
in_focus_style: StyleRefinement::default(),
|
||||
hover_style: StyleRefinement::default(),
|
||||
group_hover_style: None,
|
||||
@@ -1241,9 +1212,8 @@ pub struct InteractiveElementState {
|
||||
}
|
||||
|
||||
pub struct ActiveTooltip {
|
||||
#[allow(unused)] // used to drop the task
|
||||
waiting: Option<Task<()>>,
|
||||
tooltip: Option<AnyTooltip>,
|
||||
_task: Option<Task<()>>,
|
||||
}
|
||||
|
||||
/// Whether or not the element or a group that contains it is clicked by the mouse.
|
||||
@@ -1327,21 +1297,12 @@ where
|
||||
self.element.element_id()
|
||||
}
|
||||
|
||||
fn initialize(
|
||||
fn layout(
|
||||
&mut self,
|
||||
view_state: &mut V,
|
||||
element_state: Option<Self::ElementState>,
|
||||
cx: &mut ViewContext<V>,
|
||||
) -> Self::ElementState {
|
||||
self.element.initialize(view_state, element_state, cx)
|
||||
}
|
||||
|
||||
fn layout(
|
||||
&mut self,
|
||||
view_state: &mut V,
|
||||
element_state: &mut Self::ElementState,
|
||||
cx: &mut ViewContext<V>,
|
||||
) -> LayoutId {
|
||||
) -> (LayoutId, Self::ElementState) {
|
||||
self.element.layout(view_state, element_state, cx)
|
||||
}
|
||||
|
||||
@@ -1422,21 +1383,12 @@ where
|
||||
self.element.element_id()
|
||||
}
|
||||
|
||||
fn initialize(
|
||||
fn layout(
|
||||
&mut self,
|
||||
view_state: &mut V,
|
||||
element_state: Option<Self::ElementState>,
|
||||
cx: &mut ViewContext<V>,
|
||||
) -> Self::ElementState {
|
||||
self.element.initialize(view_state, element_state, cx)
|
||||
}
|
||||
|
||||
fn layout(
|
||||
&mut self,
|
||||
view_state: &mut V,
|
||||
element_state: &mut Self::ElementState,
|
||||
cx: &mut ViewContext<V>,
|
||||
) -> LayoutId {
|
||||
) -> (LayoutId, Self::ElementState) {
|
||||
self.element.layout(view_state, element_state, cx)
|
||||
}
|
||||
|
||||
|
||||
@@ -48,21 +48,12 @@ impl<V> Element<V> for Img<V> {
|
||||
self.interactivity.element_id.clone()
|
||||
}
|
||||
|
||||
fn initialize(
|
||||
fn layout(
|
||||
&mut self,
|
||||
_view_state: &mut V,
|
||||
element_state: Option<Self::ElementState>,
|
||||
cx: &mut ViewContext<V>,
|
||||
) -> Self::ElementState {
|
||||
self.interactivity.initialize(element_state, cx)
|
||||
}
|
||||
|
||||
fn layout(
|
||||
&mut self,
|
||||
_view_state: &mut V,
|
||||
element_state: &mut Self::ElementState,
|
||||
cx: &mut ViewContext<V>,
|
||||
) -> LayoutId {
|
||||
) -> (LayoutId, Self::ElementState) {
|
||||
self.interactivity.layout(element_state, cx, |style, cx| {
|
||||
cx.request_layout(&style, None)
|
||||
})
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
mod div;
|
||||
mod img;
|
||||
mod overlay;
|
||||
mod svg;
|
||||
mod text;
|
||||
mod uniform_list;
|
||||
|
||||
pub use div::*;
|
||||
pub use img::*;
|
||||
pub use overlay::*;
|
||||
pub use svg::*;
|
||||
pub use text::*;
|
||||
pub use uniform_list::*;
|
||||
|
||||
@@ -0,0 +1,232 @@
|
||||
use smallvec::SmallVec;
|
||||
use taffy::style::{Display, Position};
|
||||
|
||||
use crate::{
|
||||
point, AnyElement, BorrowWindow, Bounds, Component, Element, LayoutId, ParentComponent, Pixels,
|
||||
Point, Size, Style,
|
||||
};
|
||||
|
||||
pub struct OverlayState {
|
||||
child_layout_ids: SmallVec<[LayoutId; 4]>,
|
||||
}
|
||||
|
||||
pub struct Overlay<V> {
|
||||
children: SmallVec<[AnyElement<V>; 2]>,
|
||||
anchor_corner: AnchorCorner,
|
||||
fit_mode: OverlayFitMode,
|
||||
// todo!();
|
||||
anchor_position: Option<Point<Pixels>>,
|
||||
// position_mode: OverlayPositionMode,
|
||||
}
|
||||
|
||||
/// overlay gives you a floating element that will avoid overflowing the window bounds.
|
||||
/// Its children should have no margin to avoid measurement issues.
|
||||
pub fn overlay<V: 'static>() -> Overlay<V> {
|
||||
Overlay {
|
||||
children: SmallVec::new(),
|
||||
anchor_corner: AnchorCorner::TopLeft,
|
||||
fit_mode: OverlayFitMode::SwitchAnchor,
|
||||
anchor_position: None,
|
||||
}
|
||||
}
|
||||
|
||||
impl<V> Overlay<V> {
|
||||
/// Sets which corner of the overlay should be anchored to the current position.
|
||||
pub fn anchor(mut self, anchor: AnchorCorner) -> Self {
|
||||
self.anchor_corner = anchor;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the position in window co-ordinates
|
||||
/// (otherwise the location the overlay is rendered is used)
|
||||
pub fn position(mut self, anchor: Point<Pixels>) -> Self {
|
||||
self.anchor_position = Some(anchor);
|
||||
self
|
||||
}
|
||||
|
||||
/// Snap to window edge instead of switching anchor corner when an overflow would occur.
|
||||
pub fn snap_to_window(mut self) -> Self {
|
||||
self.fit_mode = OverlayFitMode::SnapToWindow;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl<V: 'static> ParentComponent<V> for Overlay<V> {
|
||||
fn children_mut(&mut self) -> &mut SmallVec<[AnyElement<V>; 2]> {
|
||||
&mut self.children
|
||||
}
|
||||
}
|
||||
|
||||
impl<V: 'static> Component<V> for Overlay<V> {
|
||||
fn render(self) -> AnyElement<V> {
|
||||
AnyElement::new(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<V: 'static> Element<V> for Overlay<V> {
|
||||
type ElementState = OverlayState;
|
||||
|
||||
fn element_id(&self) -> Option<crate::ElementId> {
|
||||
None
|
||||
}
|
||||
|
||||
fn layout(
|
||||
&mut self,
|
||||
view_state: &mut V,
|
||||
_: Option<Self::ElementState>,
|
||||
cx: &mut crate::ViewContext<V>,
|
||||
) -> (crate::LayoutId, Self::ElementState) {
|
||||
let child_layout_ids = self
|
||||
.children
|
||||
.iter_mut()
|
||||
.map(|child| child.layout(view_state, cx))
|
||||
.collect::<SmallVec<_>>();
|
||||
|
||||
let mut overlay_style = Style::default();
|
||||
overlay_style.position = Position::Absolute;
|
||||
overlay_style.display = Display::Flex;
|
||||
|
||||
let layout_id = cx.request_layout(&overlay_style, child_layout_ids.iter().copied());
|
||||
|
||||
(layout_id, OverlayState { child_layout_ids })
|
||||
}
|
||||
|
||||
fn paint(
|
||||
&mut self,
|
||||
bounds: crate::Bounds<crate::Pixels>,
|
||||
view_state: &mut V,
|
||||
element_state: &mut Self::ElementState,
|
||||
cx: &mut crate::ViewContext<V>,
|
||||
) {
|
||||
if element_state.child_layout_ids.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let mut child_min = point(Pixels::MAX, Pixels::MAX);
|
||||
let mut child_max = Point::default();
|
||||
for child_layout_id in &element_state.child_layout_ids {
|
||||
let child_bounds = cx.layout_bounds(*child_layout_id);
|
||||
child_min = child_min.min(&child_bounds.origin);
|
||||
child_max = child_max.max(&child_bounds.lower_right());
|
||||
}
|
||||
let size: Size<Pixels> = (child_max - child_min).into();
|
||||
let origin = self.anchor_position.unwrap_or(bounds.origin);
|
||||
|
||||
let mut desired = self.anchor_corner.get_bounds(origin, size);
|
||||
let limits = Bounds {
|
||||
origin: Point::zero(),
|
||||
size: cx.viewport_size(),
|
||||
};
|
||||
|
||||
match self.fit_mode {
|
||||
OverlayFitMode::SnapToWindow => {
|
||||
// Snap the horizontal edges of the overlay to the horizontal edges of the window if
|
||||
// its horizontal bounds overflow
|
||||
if desired.right() > limits.right() {
|
||||
desired.origin.x -= desired.right() - limits.right();
|
||||
} else if desired.left() < limits.left() {
|
||||
desired.origin.x = limits.origin.x;
|
||||
}
|
||||
|
||||
// Snap the vertical edges of the overlay to the vertical edges of the window if
|
||||
// its vertical bounds overflow.
|
||||
if desired.bottom() > limits.bottom() {
|
||||
desired.origin.y -= desired.bottom() - limits.bottom();
|
||||
} else if desired.top() < limits.top() {
|
||||
desired.origin.y = limits.origin.y;
|
||||
}
|
||||
}
|
||||
OverlayFitMode::SwitchAnchor => {
|
||||
let mut anchor_corner = self.anchor_corner;
|
||||
|
||||
if desired.left() < limits.left() || desired.right() > limits.right() {
|
||||
anchor_corner = anchor_corner.switch_axis(Axis::Horizontal);
|
||||
}
|
||||
|
||||
if bounds.top() < limits.top() || bounds.bottom() > limits.bottom() {
|
||||
anchor_corner = anchor_corner.switch_axis(Axis::Vertical);
|
||||
}
|
||||
|
||||
// Update bounds if needed
|
||||
if anchor_corner != self.anchor_corner {
|
||||
desired = anchor_corner.get_bounds(origin, size)
|
||||
}
|
||||
}
|
||||
OverlayFitMode::None => {}
|
||||
}
|
||||
|
||||
cx.with_element_offset(desired.origin - bounds.origin, |cx| {
|
||||
for child in &mut self.children {
|
||||
child.paint(view_state, cx);
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
enum Axis {
|
||||
Horizontal,
|
||||
Vertical,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone)]
|
||||
pub enum OverlayFitMode {
|
||||
SnapToWindow,
|
||||
SwitchAnchor,
|
||||
None,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub enum AnchorCorner {
|
||||
TopLeft,
|
||||
TopRight,
|
||||
BottomLeft,
|
||||
BottomRight,
|
||||
}
|
||||
|
||||
impl AnchorCorner {
|
||||
fn get_bounds(&self, origin: Point<Pixels>, size: Size<Pixels>) -> Bounds<Pixels> {
|
||||
let origin = match self {
|
||||
Self::TopLeft => origin,
|
||||
Self::TopRight => Point {
|
||||
x: origin.x - size.width,
|
||||
y: origin.y,
|
||||
},
|
||||
Self::BottomLeft => Point {
|
||||
x: origin.x,
|
||||
y: origin.y - size.height,
|
||||
},
|
||||
Self::BottomRight => Point {
|
||||
x: origin.x - size.width,
|
||||
y: origin.y - size.height,
|
||||
},
|
||||
};
|
||||
|
||||
Bounds { origin, size }
|
||||
}
|
||||
|
||||
pub fn corner(&self, bounds: Bounds<Pixels>) -> Point<Pixels> {
|
||||
match self {
|
||||
Self::TopLeft => bounds.origin,
|
||||
Self::TopRight => bounds.upper_right(),
|
||||
Self::BottomLeft => bounds.lower_left(),
|
||||
Self::BottomRight => bounds.lower_right(),
|
||||
}
|
||||
}
|
||||
|
||||
fn switch_axis(self, axis: Axis) -> Self {
|
||||
match axis {
|
||||
Axis::Vertical => match self {
|
||||
AnchorCorner::TopLeft => AnchorCorner::BottomLeft,
|
||||
AnchorCorner::TopRight => AnchorCorner::BottomRight,
|
||||
AnchorCorner::BottomLeft => AnchorCorner::TopLeft,
|
||||
AnchorCorner::BottomRight => AnchorCorner::TopRight,
|
||||
},
|
||||
Axis::Horizontal => match self {
|
||||
AnchorCorner::TopLeft => AnchorCorner::TopRight,
|
||||
AnchorCorner::TopRight => AnchorCorner::TopLeft,
|
||||
AnchorCorner::BottomLeft => AnchorCorner::BottomRight,
|
||||
AnchorCorner::BottomRight => AnchorCorner::BottomLeft,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -37,21 +37,12 @@ impl<V> Element<V> for Svg<V> {
|
||||
self.interactivity.element_id.clone()
|
||||
}
|
||||
|
||||
fn initialize(
|
||||
fn layout(
|
||||
&mut self,
|
||||
_view_state: &mut V,
|
||||
element_state: Option<Self::ElementState>,
|
||||
cx: &mut ViewContext<V>,
|
||||
) -> Self::ElementState {
|
||||
self.interactivity.initialize(element_state, cx)
|
||||
}
|
||||
|
||||
fn layout(
|
||||
&mut self,
|
||||
_view_state: &mut V,
|
||||
element_state: &mut Self::ElementState,
|
||||
cx: &mut ViewContext<V>,
|
||||
) -> LayoutId {
|
||||
) -> (LayoutId, Self::ElementState) {
|
||||
self.interactivity.layout(element_state, cx, |style, cx| {
|
||||
cx.request_layout(&style, None)
|
||||
})
|
||||
|
||||
@@ -1,96 +1,51 @@
|
||||
use crate::{
|
||||
AnyElement, BorrowWindow, Bounds, Component, Element, LayoutId, Line, Pixels, SharedString,
|
||||
Size, TextRun, ViewContext,
|
||||
AnyElement, BorrowWindow, Bounds, Component, Element, ElementId, LayoutId, Pixels,
|
||||
SharedString, Size, TextRun, ViewContext, WrappedLine,
|
||||
};
|
||||
use parking_lot::Mutex;
|
||||
use parking_lot::{Mutex, MutexGuard};
|
||||
use smallvec::SmallVec;
|
||||
use std::{marker::PhantomData, sync::Arc};
|
||||
use std::{cell::Cell, rc::Rc, sync::Arc};
|
||||
use util::ResultExt;
|
||||
|
||||
impl<V: 'static> Component<V> for SharedString {
|
||||
fn render(self) -> AnyElement<V> {
|
||||
Text {
|
||||
text: self,
|
||||
runs: None,
|
||||
state_type: PhantomData,
|
||||
}
|
||||
.render()
|
||||
}
|
||||
}
|
||||
|
||||
impl<V: 'static> Component<V> for &'static str {
|
||||
fn render(self) -> AnyElement<V> {
|
||||
Text {
|
||||
text: self.into(),
|
||||
runs: None,
|
||||
state_type: PhantomData,
|
||||
}
|
||||
.render()
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Figure out how to pass `String` to `child` without this.
|
||||
// This impl doesn't exist in the `gpui2` crate.
|
||||
impl<V: 'static> Component<V> for String {
|
||||
fn render(self) -> AnyElement<V> {
|
||||
Text {
|
||||
text: self.into(),
|
||||
runs: None,
|
||||
state_type: PhantomData,
|
||||
}
|
||||
.render()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Text<V> {
|
||||
pub struct Text {
|
||||
text: SharedString,
|
||||
runs: Option<Vec<TextRun>>,
|
||||
state_type: PhantomData<V>,
|
||||
}
|
||||
|
||||
impl<V: 'static> Text<V> {
|
||||
/// styled renders text that has different runs of different styles.
|
||||
/// callers are responsible for setting the correct style for each run.
|
||||
////
|
||||
/// For uniform text you can usually just pass a string as a child, and
|
||||
/// cx.text_style() will be used automatically.
|
||||
impl Text {
|
||||
/// Renders text with runs of different styles.
|
||||
///
|
||||
/// Callers are responsible for setting the correct style for each run.
|
||||
/// For text with a uniform style, you can usually avoid calling this constructor
|
||||
/// and just pass text directly.
|
||||
pub fn styled(text: SharedString, runs: Vec<TextRun>) -> Self {
|
||||
Text {
|
||||
text,
|
||||
runs: Some(runs),
|
||||
state_type: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<V: 'static> Component<V> for Text<V> {
|
||||
impl<V: 'static> Component<V> for Text {
|
||||
fn render(self) -> AnyElement<V> {
|
||||
AnyElement::new(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<V: 'static> Element<V> for Text<V> {
|
||||
type ElementState = Arc<Mutex<Option<TextElementState>>>;
|
||||
impl<V: 'static> Element<V> for Text {
|
||||
type ElementState = TextState;
|
||||
|
||||
fn element_id(&self) -> Option<crate::ElementId> {
|
||||
None
|
||||
}
|
||||
|
||||
fn initialize(
|
||||
&mut self,
|
||||
_view_state: &mut V,
|
||||
element_state: Option<Self::ElementState>,
|
||||
_cx: &mut ViewContext<V>,
|
||||
) -> Self::ElementState {
|
||||
element_state.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn layout(
|
||||
&mut self,
|
||||
_view: &mut V,
|
||||
element_state: &mut Self::ElementState,
|
||||
element_state: Option<Self::ElementState>,
|
||||
cx: &mut ViewContext<V>,
|
||||
) -> LayoutId {
|
||||
) -> (LayoutId, Self::ElementState) {
|
||||
let element_state = element_state.unwrap_or_default();
|
||||
let text_system = cx.text_system().clone();
|
||||
let text_style = cx.text_style();
|
||||
let font_size = text_style.font_size.to_pixels(cx.rem_size());
|
||||
@@ -111,7 +66,7 @@ impl<V: 'static> Element<V> for Text<V> {
|
||||
let element_state = element_state.clone();
|
||||
move |known_dimensions, _| {
|
||||
let Some(lines) = text_system
|
||||
.layout_text(
|
||||
.shape_text(
|
||||
&text,
|
||||
font_size,
|
||||
&runs[..],
|
||||
@@ -119,36 +74,29 @@ impl<V: 'static> Element<V> for Text<V> {
|
||||
)
|
||||
.log_err()
|
||||
else {
|
||||
element_state.lock().replace(TextElementState {
|
||||
element_state.lock().replace(TextStateInner {
|
||||
lines: Default::default(),
|
||||
line_height,
|
||||
});
|
||||
return Size::default();
|
||||
};
|
||||
|
||||
let line_count = lines
|
||||
.iter()
|
||||
.map(|line| line.wrap_count() + 1)
|
||||
.sum::<usize>();
|
||||
let size = Size {
|
||||
width: lines
|
||||
.iter()
|
||||
.map(|line| line.layout.width)
|
||||
.max()
|
||||
.unwrap()
|
||||
.ceil(),
|
||||
height: line_height * line_count,
|
||||
};
|
||||
let mut size: Size<Pixels> = Size::default();
|
||||
for line in &lines {
|
||||
let line_size = line.size(line_height);
|
||||
size.height += line_size.height;
|
||||
size.width = size.width.max(line_size.width);
|
||||
}
|
||||
|
||||
element_state
|
||||
.lock()
|
||||
.replace(TextElementState { lines, line_height });
|
||||
.replace(TextStateInner { lines, line_height });
|
||||
|
||||
size
|
||||
}
|
||||
});
|
||||
|
||||
layout_id
|
||||
(layout_id, element_state)
|
||||
}
|
||||
|
||||
fn paint(
|
||||
@@ -173,7 +121,104 @@ impl<V: 'static> Element<V> for Text<V> {
|
||||
}
|
||||
}
|
||||
|
||||
pub struct TextElementState {
|
||||
lines: SmallVec<[Line; 1]>,
|
||||
#[derive(Default, Clone)]
|
||||
pub struct TextState(Arc<Mutex<Option<TextStateInner>>>);
|
||||
|
||||
impl TextState {
|
||||
fn lock(&self) -> MutexGuard<Option<TextStateInner>> {
|
||||
self.0.lock()
|
||||
}
|
||||
}
|
||||
|
||||
struct TextStateInner {
|
||||
lines: SmallVec<[WrappedLine; 1]>,
|
||||
line_height: Pixels,
|
||||
}
|
||||
|
||||
struct InteractiveText {
|
||||
id: ElementId,
|
||||
text: Text,
|
||||
}
|
||||
|
||||
struct InteractiveTextState {
|
||||
text_state: TextState,
|
||||
clicked_range_ixs: Rc<Cell<SmallVec<[usize; 1]>>>,
|
||||
}
|
||||
|
||||
impl<V: 'static> Element<V> for InteractiveText {
|
||||
type ElementState = InteractiveTextState;
|
||||
|
||||
fn element_id(&self) -> Option<ElementId> {
|
||||
Some(self.id.clone())
|
||||
}
|
||||
|
||||
fn layout(
|
||||
&mut self,
|
||||
view_state: &mut V,
|
||||
element_state: Option<Self::ElementState>,
|
||||
cx: &mut ViewContext<V>,
|
||||
) -> (LayoutId, Self::ElementState) {
|
||||
if let Some(InteractiveTextState {
|
||||
text_state,
|
||||
clicked_range_ixs,
|
||||
}) = element_state
|
||||
{
|
||||
let (layout_id, text_state) = self.text.layout(view_state, Some(text_state), cx);
|
||||
let element_state = InteractiveTextState {
|
||||
text_state,
|
||||
clicked_range_ixs,
|
||||
};
|
||||
(layout_id, element_state)
|
||||
} else {
|
||||
let (layout_id, text_state) = self.text.layout(view_state, None, cx);
|
||||
let element_state = InteractiveTextState {
|
||||
text_state,
|
||||
clicked_range_ixs: Rc::default(),
|
||||
};
|
||||
(layout_id, element_state)
|
||||
}
|
||||
}
|
||||
|
||||
fn paint(
|
||||
&mut self,
|
||||
bounds: Bounds<Pixels>,
|
||||
view_state: &mut V,
|
||||
element_state: &mut Self::ElementState,
|
||||
cx: &mut ViewContext<V>,
|
||||
) {
|
||||
self.text
|
||||
.paint(bounds, view_state, &mut element_state.text_state, cx)
|
||||
}
|
||||
}
|
||||
|
||||
impl<V: 'static> Component<V> for SharedString {
|
||||
fn render(self) -> AnyElement<V> {
|
||||
Text {
|
||||
text: self,
|
||||
runs: None,
|
||||
}
|
||||
.render()
|
||||
}
|
||||
}
|
||||
|
||||
impl<V: 'static> Component<V> for &'static str {
|
||||
fn render(self) -> AnyElement<V> {
|
||||
Text {
|
||||
text: self.into(),
|
||||
runs: None,
|
||||
}
|
||||
.render()
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Figure out how to pass `String` to `child` without this.
|
||||
// This impl doesn't exist in the `gpui2` crate.
|
||||
impl<V: 'static> Component<V> for String {
|
||||
fn render(self) -> AnyElement<V> {
|
||||
Text {
|
||||
text: self.into(),
|
||||
runs: None,
|
||||
}
|
||||
.render()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -108,62 +108,54 @@ impl<V: 'static> Element<V> for UniformList<V> {
|
||||
Some(self.id.clone())
|
||||
}
|
||||
|
||||
fn initialize(
|
||||
fn layout(
|
||||
&mut self,
|
||||
view_state: &mut V,
|
||||
element_state: Option<Self::ElementState>,
|
||||
cx: &mut ViewContext<V>,
|
||||
) -> Self::ElementState {
|
||||
if let Some(mut element_state) = element_state {
|
||||
element_state.interactive = self
|
||||
.interactivity
|
||||
.initialize(Some(element_state.interactive), cx);
|
||||
element_state
|
||||
} else {
|
||||
let item_size = self.measure_item(view_state, None, cx);
|
||||
UniformListState {
|
||||
interactive: self.interactivity.initialize(None, cx),
|
||||
item_size,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn layout(
|
||||
&mut self,
|
||||
_view_state: &mut V,
|
||||
element_state: &mut Self::ElementState,
|
||||
cx: &mut ViewContext<V>,
|
||||
) -> LayoutId {
|
||||
) -> (LayoutId, Self::ElementState) {
|
||||
let max_items = self.item_count;
|
||||
let item_size = element_state.item_size;
|
||||
let rem_size = cx.rem_size();
|
||||
let item_size = element_state
|
||||
.as_ref()
|
||||
.map(|s| s.item_size)
|
||||
.unwrap_or_else(|| self.measure_item(view_state, None, cx));
|
||||
|
||||
self.interactivity
|
||||
.layout(&mut element_state.interactive, cx, |style, cx| {
|
||||
cx.request_measured_layout(
|
||||
style,
|
||||
rem_size,
|
||||
move |known_dimensions: Size<Option<Pixels>>,
|
||||
available_space: Size<AvailableSpace>| {
|
||||
let desired_height = item_size.height * max_items;
|
||||
let width = known_dimensions
|
||||
.width
|
||||
.unwrap_or(match available_space.width {
|
||||
AvailableSpace::Definite(x) => x,
|
||||
let (layout_id, interactive) =
|
||||
self.interactivity
|
||||
.layout(element_state.map(|s| s.interactive), cx, |style, cx| {
|
||||
cx.request_measured_layout(
|
||||
style,
|
||||
rem_size,
|
||||
move |known_dimensions: Size<Option<Pixels>>,
|
||||
available_space: Size<AvailableSpace>| {
|
||||
let desired_height = item_size.height * max_items;
|
||||
let width =
|
||||
known_dimensions
|
||||
.width
|
||||
.unwrap_or(match available_space.width {
|
||||
AvailableSpace::Definite(x) => x,
|
||||
AvailableSpace::MinContent | AvailableSpace::MaxContent => {
|
||||
item_size.width
|
||||
}
|
||||
});
|
||||
let height = match available_space.height {
|
||||
AvailableSpace::Definite(x) => desired_height.min(x),
|
||||
AvailableSpace::MinContent | AvailableSpace::MaxContent => {
|
||||
item_size.width
|
||||
desired_height
|
||||
}
|
||||
});
|
||||
let height = match available_space.height {
|
||||
AvailableSpace::Definite(x) => desired_height.min(x),
|
||||
AvailableSpace::MinContent | AvailableSpace::MaxContent => {
|
||||
desired_height
|
||||
}
|
||||
};
|
||||
size(width, height)
|
||||
},
|
||||
)
|
||||
})
|
||||
};
|
||||
size(width, height)
|
||||
},
|
||||
)
|
||||
});
|
||||
|
||||
let element_state = UniformListState {
|
||||
interactive,
|
||||
item_size,
|
||||
};
|
||||
|
||||
(layout_id, element_state)
|
||||
}
|
||||
|
||||
fn paint(
|
||||
|
||||
@@ -5,10 +5,11 @@ use std::{
|
||||
fmt::Debug,
|
||||
marker::PhantomData,
|
||||
mem,
|
||||
num::NonZeroUsize,
|
||||
pin::Pin,
|
||||
rc::Rc,
|
||||
sync::{
|
||||
atomic::{AtomicBool, Ordering::SeqCst},
|
||||
atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
|
||||
Arc,
|
||||
},
|
||||
task::{Context, Poll},
|
||||
@@ -71,30 +72,57 @@ impl<T> Future for Task<T> {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
|
||||
pub struct TaskLabel(NonZeroUsize);
|
||||
|
||||
impl TaskLabel {
|
||||
pub fn new() -> Self {
|
||||
static NEXT_TASK_LABEL: AtomicUsize = AtomicUsize::new(1);
|
||||
Self(NEXT_TASK_LABEL.fetch_add(1, SeqCst).try_into().unwrap())
|
||||
}
|
||||
}
|
||||
|
||||
type AnyLocalFuture<R> = Pin<Box<dyn 'static + Future<Output = R>>>;
|
||||
|
||||
type AnyFuture<R> = Pin<Box<dyn 'static + Send + Future<Output = R>>>;
|
||||
|
||||
impl BackgroundExecutor {
|
||||
pub fn new(dispatcher: Arc<dyn PlatformDispatcher>) -> Self {
|
||||
Self { dispatcher }
|
||||
}
|
||||
|
||||
/// Enqueues the given closure to be run on any thread. The closure returns
|
||||
/// a future which will be run to completion on any available thread.
|
||||
/// Enqueues the given future to be run to completion on a background thread.
|
||||
pub fn spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
|
||||
where
|
||||
R: Send + 'static,
|
||||
{
|
||||
self.spawn_internal::<R>(Box::pin(future), None)
|
||||
}
|
||||
|
||||
/// Enqueues the given future to be run to completion on a background thread.
|
||||
/// The given label can be used to control the priority of the task in tests.
|
||||
pub fn spawn_labeled<R>(
|
||||
&self,
|
||||
label: TaskLabel,
|
||||
future: impl Future<Output = R> + Send + 'static,
|
||||
) -> Task<R>
|
||||
where
|
||||
R: Send + 'static,
|
||||
{
|
||||
self.spawn_internal::<R>(Box::pin(future), Some(label))
|
||||
}
|
||||
|
||||
fn spawn_internal<R: Send + 'static>(
|
||||
&self,
|
||||
future: AnyFuture<R>,
|
||||
label: Option<TaskLabel>,
|
||||
) -> Task<R> {
|
||||
let dispatcher = self.dispatcher.clone();
|
||||
fn inner<R: Send + 'static>(
|
||||
dispatcher: Arc<dyn PlatformDispatcher>,
|
||||
future: AnyFuture<R>,
|
||||
) -> Task<R> {
|
||||
let (runnable, task) =
|
||||
async_task::spawn(future, move |runnable| dispatcher.dispatch(runnable));
|
||||
runnable.schedule();
|
||||
Task::Spawned(task)
|
||||
}
|
||||
inner::<R>(dispatcher, Box::pin(future))
|
||||
let (runnable, task) =
|
||||
async_task::spawn(future, move |runnable| dispatcher.dispatch(runnable, label));
|
||||
runnable.schedule();
|
||||
Task::Spawned(task)
|
||||
}
|
||||
|
||||
#[cfg(any(test, feature = "test-support"))]
|
||||
@@ -130,7 +158,7 @@ impl BackgroundExecutor {
|
||||
match future.as_mut().poll(&mut cx) {
|
||||
Poll::Ready(result) => return result,
|
||||
Poll::Pending => {
|
||||
if !self.dispatcher.poll(background_only) {
|
||||
if !self.dispatcher.tick(background_only) {
|
||||
if awoken.swap(false, SeqCst) {
|
||||
continue;
|
||||
}
|
||||
@@ -216,11 +244,21 @@ impl BackgroundExecutor {
|
||||
self.dispatcher.as_test().unwrap().simulate_random_delay()
|
||||
}
|
||||
|
||||
#[cfg(any(test, feature = "test-support"))]
|
||||
pub fn deprioritize(&self, task_label: TaskLabel) {
|
||||
self.dispatcher.as_test().unwrap().deprioritize(task_label)
|
||||
}
|
||||
|
||||
#[cfg(any(test, feature = "test-support"))]
|
||||
pub fn advance_clock(&self, duration: Duration) {
|
||||
self.dispatcher.as_test().unwrap().advance_clock(duration)
|
||||
}
|
||||
|
||||
#[cfg(any(test, feature = "test-support"))]
|
||||
pub fn tick(&self) -> bool {
|
||||
self.dispatcher.as_test().unwrap().tick(false)
|
||||
}
|
||||
|
||||
#[cfg(any(test, feature = "test-support"))]
|
||||
pub fn run_until_parked(&self) {
|
||||
self.dispatcher.as_test().unwrap().run_until_parked()
|
||||
|
||||
@@ -335,11 +335,15 @@ where
|
||||
};
|
||||
Bounds { origin, size }
|
||||
}
|
||||
|
||||
pub fn new(origin: Point<T>, size: Size<T>) -> Self {
|
||||
Bounds { origin, size }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Bounds<T>
|
||||
where
|
||||
T: Clone + Debug + PartialOrd + Add<T, Output = T> + Sub<Output = T> + Default,
|
||||
T: Clone + Debug + PartialOrd + Add<T, Output = T> + Sub<Output = T> + Default + Half,
|
||||
{
|
||||
pub fn intersects(&self, other: &Bounds<T>) -> bool {
|
||||
let my_lower_right = self.lower_right();
|
||||
@@ -358,6 +362,13 @@ where
|
||||
self.size.width = self.size.width.clone() + double_amount.clone();
|
||||
self.size.height = self.size.height.clone() + double_amount;
|
||||
}
|
||||
|
||||
pub fn center(&self) -> Point<T> {
|
||||
Point {
|
||||
x: self.origin.x.clone() + self.size.width.clone().half(),
|
||||
y: self.origin.y.clone() + self.size.height.clone().half(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Clone + Default + Debug + PartialOrd + Add<T, Output = T> + Sub<Output = T>> Bounds<T> {
|
||||
@@ -421,6 +432,22 @@ impl<T> Bounds<T>
|
||||
where
|
||||
T: Add<T, Output = T> + Clone + Default + Debug,
|
||||
{
|
||||
pub fn top(&self) -> T {
|
||||
self.origin.y.clone()
|
||||
}
|
||||
|
||||
pub fn bottom(&self) -> T {
|
||||
self.origin.y.clone() + self.size.height.clone()
|
||||
}
|
||||
|
||||
pub fn left(&self) -> T {
|
||||
self.origin.x.clone()
|
||||
}
|
||||
|
||||
pub fn right(&self) -> T {
|
||||
self.origin.x.clone() + self.size.width.clone()
|
||||
}
|
||||
|
||||
pub fn upper_right(&self) -> Point<T> {
|
||||
Point {
|
||||
x: self.origin.x.clone() + self.size.width.clone(),
|
||||
@@ -1191,6 +1218,46 @@ impl From<()> for Length {
|
||||
}
|
||||
}
|
||||
|
||||
pub trait Half {
|
||||
fn half(&self) -> Self;
|
||||
}
|
||||
|
||||
impl Half for f32 {
|
||||
fn half(&self) -> Self {
|
||||
self / 2.
|
||||
}
|
||||
}
|
||||
|
||||
impl Half for DevicePixels {
|
||||
fn half(&self) -> Self {
|
||||
Self(self.0 / 2)
|
||||
}
|
||||
}
|
||||
|
||||
impl Half for ScaledPixels {
|
||||
fn half(&self) -> Self {
|
||||
Self(self.0 / 2.)
|
||||
}
|
||||
}
|
||||
|
||||
impl Half for Pixels {
|
||||
fn half(&self) -> Self {
|
||||
Self(self.0 / 2.)
|
||||
}
|
||||
}
|
||||
|
||||
impl Half for Rems {
|
||||
fn half(&self) -> Self {
|
||||
Self(self.0 / 2.)
|
||||
}
|
||||
}
|
||||
|
||||
impl Half for GlobalPixels {
|
||||
fn half(&self) -> Self {
|
||||
Self(self.0 / 2.)
|
||||
}
|
||||
}
|
||||
|
||||
pub trait IsZero {
|
||||
fn is_zero(&self) -> bool;
|
||||
}
|
||||
|
||||
@@ -49,11 +49,13 @@ pub use input::*;
|
||||
pub use interactive::*;
|
||||
pub use key_dispatch::*;
|
||||
pub use keymap::*;
|
||||
pub use linkme;
|
||||
pub use platform::*;
|
||||
use private::Sealed;
|
||||
pub use refineable::*;
|
||||
pub use scene::*;
|
||||
pub use serde;
|
||||
pub use serde_derive;
|
||||
pub use serde_json;
|
||||
pub use smallvec;
|
||||
pub use smol::Timer;
|
||||
@@ -135,6 +137,10 @@ pub trait VisualContext: Context {
|
||||
) -> Self::Result<View<V>>
|
||||
where
|
||||
V: Render;
|
||||
|
||||
fn focus_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
|
||||
where
|
||||
V: FocusableView;
|
||||
}
|
||||
|
||||
pub trait Entity<T>: Sealed {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::{
|
||||
build_action_from_type, Action, DispatchPhase, FocusId, KeyBinding, KeyContext, KeyMatch,
|
||||
Keymap, Keystroke, KeystrokeMatcher, WindowContext,
|
||||
Action, ActionRegistry, DispatchPhase, FocusId, KeyBinding, KeyContext, KeyMatch, Keymap,
|
||||
Keystroke, KeystrokeMatcher, WindowContext,
|
||||
};
|
||||
use collections::HashMap;
|
||||
use parking_lot::Mutex;
|
||||
@@ -10,7 +10,6 @@ use std::{
|
||||
rc::Rc,
|
||||
sync::Arc,
|
||||
};
|
||||
use util::ResultExt;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
|
||||
pub struct DispatchNodeId(usize);
|
||||
@@ -22,6 +21,7 @@ pub(crate) struct DispatchTree {
|
||||
focusable_node_ids: HashMap<FocusId, DispatchNodeId>,
|
||||
keystroke_matchers: HashMap<SmallVec<[KeyContext; 4]>, KeystrokeMatcher>,
|
||||
keymap: Arc<Mutex<Keymap>>,
|
||||
action_registry: Rc<ActionRegistry>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -41,7 +41,7 @@ pub(crate) struct DispatchActionListener {
|
||||
}
|
||||
|
||||
impl DispatchTree {
|
||||
pub fn new(keymap: Arc<Mutex<Keymap>>) -> Self {
|
||||
pub fn new(keymap: Arc<Mutex<Keymap>>, action_registry: Rc<ActionRegistry>) -> Self {
|
||||
Self {
|
||||
node_stack: Vec::new(),
|
||||
context_stack: Vec::new(),
|
||||
@@ -49,6 +49,7 @@ impl DispatchTree {
|
||||
focusable_node_ids: HashMap::default(),
|
||||
keystroke_matchers: HashMap::default(),
|
||||
keymap,
|
||||
action_registry,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -153,7 +154,9 @@ impl DispatchTree {
|
||||
for node_id in self.dispatch_path(*node) {
|
||||
let node = &self.nodes[node_id.0];
|
||||
for DispatchActionListener { action_type, .. } in &node.action_listeners {
|
||||
actions.extend(build_action_from_type(action_type).log_err());
|
||||
// Intentionally silence these errors without logging.
|
||||
// If an action cannot be built by default, it's not available.
|
||||
actions.extend(self.action_registry.build_action_type(action_type).ok());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
use crate::{KeyBinding, KeyBindingContextPredicate, Keystroke};
|
||||
use crate::{KeyBinding, KeyBindingContextPredicate, Keystroke, NoAction};
|
||||
use collections::HashSet;
|
||||
use smallvec::SmallVec;
|
||||
use std::{any::TypeId, collections::HashMap};
|
||||
use std::{
|
||||
any::{Any, TypeId},
|
||||
collections::HashMap,
|
||||
};
|
||||
|
||||
#[derive(Copy, Clone, Eq, PartialEq, Default)]
|
||||
pub struct KeymapVersion(usize);
|
||||
@@ -37,20 +40,19 @@ impl Keymap {
|
||||
}
|
||||
|
||||
pub fn add_bindings<T: IntoIterator<Item = KeyBinding>>(&mut self, bindings: T) {
|
||||
// todo!("no action")
|
||||
// let no_action_id = (NoAction {}).id();
|
||||
let no_action_id = &(NoAction {}).type_id();
|
||||
let mut new_bindings = Vec::new();
|
||||
let has_new_disabled_keystrokes = false;
|
||||
let mut has_new_disabled_keystrokes = false;
|
||||
for binding in bindings {
|
||||
// if binding.action().id() == no_action_id {
|
||||
// has_new_disabled_keystrokes |= self
|
||||
// .disabled_keystrokes
|
||||
// .entry(binding.keystrokes)
|
||||
// .or_default()
|
||||
// .insert(binding.context_predicate);
|
||||
// } else {
|
||||
new_bindings.push(binding);
|
||||
// }
|
||||
if binding.action.type_id() == *no_action_id {
|
||||
has_new_disabled_keystrokes |= self
|
||||
.disabled_keystrokes
|
||||
.entry(binding.keystrokes)
|
||||
.or_default()
|
||||
.insert(binding.context_predicate);
|
||||
} else {
|
||||
new_bindings.push(binding);
|
||||
}
|
||||
}
|
||||
|
||||
if has_new_disabled_keystrokes {
|
||||
|
||||
@@ -8,7 +8,7 @@ use crate::{
|
||||
point, size, AnyWindowHandle, BackgroundExecutor, Bounds, DevicePixels, Font, FontId,
|
||||
FontMetrics, FontRun, ForegroundExecutor, GlobalPixels, GlyphId, InputEvent, LineLayout,
|
||||
Pixels, Point, RenderGlyphParams, RenderImageParams, RenderSvgParams, Result, Scene,
|
||||
SharedString, Size,
|
||||
SharedString, Size, TaskLabel,
|
||||
};
|
||||
use anyhow::{anyhow, bail};
|
||||
use async_task::Runnable;
|
||||
@@ -162,10 +162,10 @@ pub(crate) trait PlatformWindow {
|
||||
|
||||
pub trait PlatformDispatcher: Send + Sync {
|
||||
fn is_main_thread(&self) -> bool;
|
||||
fn dispatch(&self, runnable: Runnable);
|
||||
fn dispatch(&self, runnable: Runnable, label: Option<TaskLabel>);
|
||||
fn dispatch_on_main_thread(&self, runnable: Runnable);
|
||||
fn dispatch_after(&self, duration: Duration, runnable: Runnable);
|
||||
fn poll(&self, background_only: bool) -> bool;
|
||||
fn tick(&self, background_only: bool) -> bool;
|
||||
fn park(&self);
|
||||
fn unparker(&self) -> Unparker;
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
#![allow(non_camel_case_types)]
|
||||
#![allow(non_snake_case)]
|
||||
|
||||
use crate::PlatformDispatcher;
|
||||
use crate::{PlatformDispatcher, TaskLabel};
|
||||
use async_task::Runnable;
|
||||
use objc::{
|
||||
class, msg_send,
|
||||
@@ -37,7 +37,7 @@ impl PlatformDispatcher for MacDispatcher {
|
||||
is_main_thread == YES
|
||||
}
|
||||
|
||||
fn dispatch(&self, runnable: Runnable) {
|
||||
fn dispatch(&self, runnable: Runnable, _: Option<TaskLabel>) {
|
||||
unsafe {
|
||||
dispatch_async_f(
|
||||
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT.try_into().unwrap(), 0),
|
||||
@@ -71,7 +71,7 @@ impl PlatformDispatcher for MacDispatcher {
|
||||
}
|
||||
}
|
||||
|
||||
fn poll(&self, _background_only: bool) -> bool {
|
||||
fn tick(&self, _background_only: bool) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
|
||||
@@ -343,10 +343,10 @@ impl MacTextSystemState {
|
||||
// Construct the attributed string, converting UTF8 ranges to UTF16 ranges.
|
||||
let mut string = CFMutableAttributedString::new();
|
||||
{
|
||||
string.replace_str(&CFString::new(text), CFRange::init(0, 0));
|
||||
string.replace_str(&CFString::new(text.as_ref()), CFRange::init(0, 0));
|
||||
let utf16_line_len = string.char_len() as usize;
|
||||
|
||||
let mut ix_converter = StringIndexConverter::new(text);
|
||||
let mut ix_converter = StringIndexConverter::new(text.as_ref());
|
||||
for run in font_runs {
|
||||
let utf8_end = ix_converter.utf8_ix + run.len;
|
||||
let utf16_start = ix_converter.utf16_ix;
|
||||
@@ -390,7 +390,7 @@ impl MacTextSystemState {
|
||||
};
|
||||
let font_id = self.id_for_native_font(font);
|
||||
|
||||
let mut ix_converter = StringIndexConverter::new(text);
|
||||
let mut ix_converter = StringIndexConverter::new(text.as_ref());
|
||||
let mut glyphs = SmallVec::new();
|
||||
for ((glyph_id, position), glyph_utf16_ix) in run
|
||||
.glyphs()
|
||||
@@ -413,11 +413,11 @@ impl MacTextSystemState {
|
||||
|
||||
let typographic_bounds = line.get_typographic_bounds();
|
||||
LineLayout {
|
||||
runs,
|
||||
font_size,
|
||||
width: typographic_bounds.width.into(),
|
||||
ascent: typographic_bounds.ascent.into(),
|
||||
descent: typographic_bounds.descent.into(),
|
||||
runs,
|
||||
font_size,
|
||||
len: text.len(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1141,7 +1141,7 @@ extern "C" fn handle_view_event(this: &Object, _: Sel, native_event: id) {
|
||||
let event = unsafe { InputEvent::from_native(native_event, Some(window_height)) };
|
||||
|
||||
if let Some(mut event) = event {
|
||||
let synthesized_second_event = match &mut event {
|
||||
match &mut event {
|
||||
InputEvent::MouseDown(
|
||||
event @ MouseDownEvent {
|
||||
button: MouseButton::Left,
|
||||
@@ -1149,6 +1149,7 @@ extern "C" fn handle_view_event(this: &Object, _: Sel, native_event: id) {
|
||||
..
|
||||
},
|
||||
) => {
|
||||
// On mac, a ctrl-left click should be handled as a right click.
|
||||
*event = MouseDownEvent {
|
||||
button: MouseButton::Right,
|
||||
modifiers: Modifiers {
|
||||
@@ -1158,26 +1159,30 @@ extern "C" fn handle_view_event(this: &Object, _: Sel, native_event: id) {
|
||||
click_count: 1,
|
||||
..*event
|
||||
};
|
||||
|
||||
Some(InputEvent::MouseDown(MouseDownEvent {
|
||||
button: MouseButton::Right,
|
||||
..*event
|
||||
}))
|
||||
}
|
||||
|
||||
// Because we map a ctrl-left_down to a right_down -> right_up let's ignore
|
||||
// the ctrl-left_up to avoid having a mismatch in button down/up events if the
|
||||
// user is still holding ctrl when releasing the left mouse button
|
||||
InputEvent::MouseUp(MouseUpEvent {
|
||||
button: MouseButton::Left,
|
||||
modifiers: Modifiers { control: true, .. },
|
||||
..
|
||||
}) => {
|
||||
lock.synthetic_drag_counter += 1;
|
||||
return;
|
||||
InputEvent::MouseUp(
|
||||
event @ MouseUpEvent {
|
||||
button: MouseButton::Left,
|
||||
modifiers: Modifiers { control: true, .. },
|
||||
..
|
||||
},
|
||||
) => {
|
||||
*event = MouseUpEvent {
|
||||
button: MouseButton::Right,
|
||||
modifiers: Modifiers {
|
||||
control: false,
|
||||
..event.modifiers
|
||||
},
|
||||
click_count: 1,
|
||||
..*event
|
||||
};
|
||||
}
|
||||
|
||||
_ => None,
|
||||
_ => {}
|
||||
};
|
||||
|
||||
match &event {
|
||||
@@ -1227,9 +1232,6 @@ extern "C" fn handle_view_event(this: &Object, _: Sel, native_event: id) {
|
||||
if let Some(mut callback) = lock.event_callback.take() {
|
||||
drop(lock);
|
||||
callback(event);
|
||||
if let Some(event) = synthesized_second_event {
|
||||
callback(event);
|
||||
}
|
||||
window_state.lock().event_callback = Some(callback);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use crate::PlatformDispatcher;
|
||||
use crate::{PlatformDispatcher, TaskLabel};
|
||||
use async_task::Runnable;
|
||||
use backtrace::Backtrace;
|
||||
use collections::{HashMap, VecDeque};
|
||||
use collections::{HashMap, HashSet, VecDeque};
|
||||
use parking::{Parker, Unparker};
|
||||
use parking_lot::Mutex;
|
||||
use rand::prelude::*;
|
||||
@@ -28,12 +28,14 @@ struct TestDispatcherState {
|
||||
random: StdRng,
|
||||
foreground: HashMap<TestDispatcherId, VecDeque<Runnable>>,
|
||||
background: Vec<Runnable>,
|
||||
deprioritized_background: Vec<Runnable>,
|
||||
delayed: Vec<(Duration, Runnable)>,
|
||||
time: Duration,
|
||||
is_main_thread: bool,
|
||||
next_id: TestDispatcherId,
|
||||
allow_parking: bool,
|
||||
waiting_backtrace: Option<Backtrace>,
|
||||
deprioritized_task_labels: HashSet<TaskLabel>,
|
||||
}
|
||||
|
||||
impl TestDispatcher {
|
||||
@@ -43,12 +45,14 @@ impl TestDispatcher {
|
||||
random,
|
||||
foreground: HashMap::default(),
|
||||
background: Vec::new(),
|
||||
deprioritized_background: Vec::new(),
|
||||
delayed: Vec::new(),
|
||||
time: Duration::ZERO,
|
||||
is_main_thread: true,
|
||||
next_id: TestDispatcherId(1),
|
||||
allow_parking: false,
|
||||
waiting_backtrace: None,
|
||||
deprioritized_task_labels: Default::default(),
|
||||
};
|
||||
|
||||
TestDispatcher {
|
||||
@@ -101,8 +105,15 @@ impl TestDispatcher {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn deprioritize(&self, task_label: TaskLabel) {
|
||||
self.state
|
||||
.lock()
|
||||
.deprioritized_task_labels
|
||||
.insert(task_label);
|
||||
}
|
||||
|
||||
pub fn run_until_parked(&self) {
|
||||
while self.poll(false) {}
|
||||
while self.tick(false) {}
|
||||
}
|
||||
|
||||
pub fn parking_allowed(&self) -> bool {
|
||||
@@ -150,8 +161,17 @@ impl PlatformDispatcher for TestDispatcher {
|
||||
self.state.lock().is_main_thread
|
||||
}
|
||||
|
||||
fn dispatch(&self, runnable: Runnable) {
|
||||
self.state.lock().background.push(runnable);
|
||||
fn dispatch(&self, runnable: Runnable, label: Option<TaskLabel>) {
|
||||
{
|
||||
let mut state = self.state.lock();
|
||||
if label.map_or(false, |label| {
|
||||
state.deprioritized_task_labels.contains(&label)
|
||||
}) {
|
||||
state.deprioritized_background.push(runnable);
|
||||
} else {
|
||||
state.background.push(runnable);
|
||||
}
|
||||
}
|
||||
self.unparker.unpark();
|
||||
}
|
||||
|
||||
@@ -174,7 +194,7 @@ impl PlatformDispatcher for TestDispatcher {
|
||||
state.delayed.insert(ix, (next_time, runnable));
|
||||
}
|
||||
|
||||
fn poll(&self, background_only: bool) -> bool {
|
||||
fn tick(&self, background_only: bool) -> bool {
|
||||
let mut state = self.state.lock();
|
||||
|
||||
while let Some((deadline, _)) = state.delayed.first() {
|
||||
@@ -196,34 +216,41 @@ impl PlatformDispatcher for TestDispatcher {
|
||||
};
|
||||
let background_len = state.background.len();
|
||||
|
||||
let runnable;
|
||||
let main_thread;
|
||||
if foreground_len == 0 && background_len == 0 {
|
||||
return false;
|
||||
}
|
||||
|
||||
let main_thread = state.random.gen_ratio(
|
||||
foreground_len as u32,
|
||||
(foreground_len + background_len) as u32,
|
||||
);
|
||||
let was_main_thread = state.is_main_thread;
|
||||
state.is_main_thread = main_thread;
|
||||
|
||||
let runnable = if main_thread {
|
||||
let state = &mut *state;
|
||||
let runnables = state
|
||||
.foreground
|
||||
.values_mut()
|
||||
.filter(|runnables| !runnables.is_empty())
|
||||
.choose(&mut state.random)
|
||||
.unwrap();
|
||||
runnables.pop_front().unwrap()
|
||||
let deprioritized_background_len = state.deprioritized_background.len();
|
||||
if deprioritized_background_len == 0 {
|
||||
return false;
|
||||
}
|
||||
let ix = state.random.gen_range(0..deprioritized_background_len);
|
||||
main_thread = false;
|
||||
runnable = state.deprioritized_background.swap_remove(ix);
|
||||
} else {
|
||||
let ix = state.random.gen_range(0..background_len);
|
||||
state.background.swap_remove(ix)
|
||||
main_thread = state.random.gen_ratio(
|
||||
foreground_len as u32,
|
||||
(foreground_len + background_len) as u32,
|
||||
);
|
||||
if main_thread {
|
||||
let state = &mut *state;
|
||||
runnable = state
|
||||
.foreground
|
||||
.values_mut()
|
||||
.filter(|runnables| !runnables.is_empty())
|
||||
.choose(&mut state.random)
|
||||
.unwrap()
|
||||
.pop_front()
|
||||
.unwrap();
|
||||
} else {
|
||||
let ix = state.random.gen_range(0..background_len);
|
||||
runnable = state.background.swap_remove(ix);
|
||||
};
|
||||
};
|
||||
|
||||
let was_main_thread = state.is_main_thread;
|
||||
state.is_main_thread = main_thread;
|
||||
drop(state);
|
||||
runnable.run();
|
||||
|
||||
self.state.lock().is_main_thread = was_main_thread;
|
||||
|
||||
true
|
||||
|
||||
@@ -203,6 +203,7 @@ impl TextStyle {
|
||||
style: self.font_style,
|
||||
},
|
||||
color: self.color,
|
||||
background_color: None,
|
||||
underline: self.underline.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,20 +3,20 @@ mod line;
|
||||
mod line_layout;
|
||||
mod line_wrapper;
|
||||
|
||||
use anyhow::anyhow;
|
||||
pub use font_features::*;
|
||||
pub use line::*;
|
||||
pub use line_layout::*;
|
||||
pub use line_wrapper::*;
|
||||
use smallvec::SmallVec;
|
||||
|
||||
use crate::{
|
||||
px, Bounds, DevicePixels, Hsla, Pixels, PlatformTextSystem, Point, Result, SharedString, Size,
|
||||
UnderlineStyle,
|
||||
};
|
||||
use anyhow::anyhow;
|
||||
use collections::HashMap;
|
||||
use core::fmt;
|
||||
use parking_lot::{Mutex, RwLock, RwLockUpgradableReadGuard};
|
||||
use smallvec::SmallVec;
|
||||
use std::{
|
||||
cmp,
|
||||
fmt::{Debug, Display, Formatter},
|
||||
@@ -151,13 +151,79 @@ impl TextSystem {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn layout_text(
|
||||
pub fn layout_line(
|
||||
&self,
|
||||
text: &str,
|
||||
font_size: Pixels,
|
||||
runs: &[TextRun],
|
||||
) -> Result<Arc<LineLayout>> {
|
||||
let mut font_runs = self.font_runs_pool.lock().pop().unwrap_or_default();
|
||||
for run in runs.iter() {
|
||||
let font_id = self.font_id(&run.font)?;
|
||||
if let Some(last_run) = font_runs.last_mut() {
|
||||
if last_run.font_id == font_id {
|
||||
last_run.len += run.len;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
font_runs.push(FontRun {
|
||||
len: run.len,
|
||||
font_id,
|
||||
});
|
||||
}
|
||||
|
||||
let layout = self
|
||||
.line_layout_cache
|
||||
.layout_line(&text, font_size, &font_runs);
|
||||
|
||||
font_runs.clear();
|
||||
self.font_runs_pool.lock().push(font_runs);
|
||||
|
||||
Ok(layout)
|
||||
}
|
||||
|
||||
pub fn shape_line(
|
||||
&self,
|
||||
text: SharedString,
|
||||
font_size: Pixels,
|
||||
runs: &[TextRun],
|
||||
) -> Result<ShapedLine> {
|
||||
debug_assert!(
|
||||
text.find('\n').is_none(),
|
||||
"text argument should not contain newlines"
|
||||
);
|
||||
|
||||
let mut decoration_runs = SmallVec::<[DecorationRun; 32]>::new();
|
||||
for run in runs {
|
||||
if let Some(last_run) = decoration_runs.last_mut() {
|
||||
if last_run.color == run.color && last_run.underline == run.underline {
|
||||
last_run.len += run.len as u32;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
decoration_runs.push(DecorationRun {
|
||||
len: run.len as u32,
|
||||
color: run.color,
|
||||
underline: run.underline.clone(),
|
||||
});
|
||||
}
|
||||
|
||||
let layout = self.layout_line(text.as_ref(), font_size, runs)?;
|
||||
|
||||
Ok(ShapedLine {
|
||||
layout,
|
||||
text,
|
||||
decoration_runs,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn shape_text(
|
||||
&self,
|
||||
text: &str, // todo!("pass a SharedString and preserve it when passed a single line?")
|
||||
font_size: Pixels,
|
||||
runs: &[TextRun],
|
||||
wrap_width: Option<Pixels>,
|
||||
) -> Result<SmallVec<[Line; 1]>> {
|
||||
) -> Result<SmallVec<[WrappedLine; 1]>> {
|
||||
let mut runs = runs.iter().cloned().peekable();
|
||||
let mut font_runs = self.font_runs_pool.lock().pop().unwrap_or_default();
|
||||
|
||||
@@ -210,10 +276,11 @@ impl TextSystem {
|
||||
|
||||
let layout = self
|
||||
.line_layout_cache
|
||||
.layout_line(&line_text, font_size, &font_runs, wrap_width);
|
||||
lines.push(Line {
|
||||
.layout_wrapped_line(&line_text, font_size, &font_runs, wrap_width);
|
||||
lines.push(WrappedLine {
|
||||
layout,
|
||||
decorations: decoration_runs,
|
||||
decoration_runs,
|
||||
text: SharedString::from(line_text),
|
||||
});
|
||||
|
||||
line_start = line_end + 1; // Skip `\n` character.
|
||||
@@ -384,6 +451,7 @@ pub struct TextRun {
|
||||
pub len: usize,
|
||||
pub font: Font,
|
||||
pub color: Hsla,
|
||||
pub background_color: Option<Hsla>,
|
||||
pub underline: Option<UnderlineStyle>,
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::{
|
||||
black, point, px, size, BorrowWindow, Bounds, Hsla, Pixels, Point, Result, Size,
|
||||
black, point, px, BorrowWindow, Bounds, Hsla, LineLayout, Pixels, Point, Result, SharedString,
|
||||
UnderlineStyle, WindowContext, WrapBoundary, WrappedLineLayout,
|
||||
};
|
||||
use derive_more::{Deref, DerefMut};
|
||||
@@ -14,23 +14,17 @@ pub struct DecorationRun {
|
||||
}
|
||||
|
||||
#[derive(Clone, Default, Debug, Deref, DerefMut)]
|
||||
pub struct Line {
|
||||
pub struct ShapedLine {
|
||||
#[deref]
|
||||
#[deref_mut]
|
||||
pub(crate) layout: Arc<WrappedLineLayout>,
|
||||
pub(crate) decorations: SmallVec<[DecorationRun; 32]>,
|
||||
pub(crate) layout: Arc<LineLayout>,
|
||||
pub text: SharedString,
|
||||
pub(crate) decoration_runs: SmallVec<[DecorationRun; 32]>,
|
||||
}
|
||||
|
||||
impl Line {
|
||||
pub fn size(&self, line_height: Pixels) -> Size<Pixels> {
|
||||
size(
|
||||
self.layout.width,
|
||||
line_height * (self.layout.wrap_boundaries.len() + 1),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn wrap_count(&self) -> usize {
|
||||
self.layout.wrap_boundaries.len()
|
||||
impl ShapedLine {
|
||||
pub fn len(&self) -> usize {
|
||||
self.layout.len
|
||||
}
|
||||
|
||||
pub fn paint(
|
||||
@@ -39,75 +33,84 @@ impl Line {
|
||||
line_height: Pixels,
|
||||
cx: &mut WindowContext,
|
||||
) -> Result<()> {
|
||||
let padding_top =
|
||||
(line_height - self.layout.layout.ascent - self.layout.layout.descent) / 2.;
|
||||
let baseline_offset = point(px(0.), padding_top + self.layout.layout.ascent);
|
||||
paint_line(
|
||||
origin,
|
||||
&self.layout,
|
||||
line_height,
|
||||
&self.decoration_runs,
|
||||
None,
|
||||
&[],
|
||||
cx,
|
||||
)?;
|
||||
|
||||
let mut style_runs = self.decorations.iter();
|
||||
let mut wraps = self.layout.wrap_boundaries.iter().peekable();
|
||||
let mut run_end = 0;
|
||||
let mut color = black();
|
||||
let mut current_underline: Option<(Point<Pixels>, UnderlineStyle)> = None;
|
||||
let text_system = cx.text_system().clone();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
let mut glyph_origin = origin;
|
||||
let mut prev_glyph_position = Point::default();
|
||||
for (run_ix, run) in self.layout.layout.runs.iter().enumerate() {
|
||||
let max_glyph_size = text_system
|
||||
.bounding_box(run.font_id, self.layout.layout.font_size)?
|
||||
.size;
|
||||
#[derive(Clone, Default, Debug, Deref, DerefMut)]
|
||||
pub struct WrappedLine {
|
||||
#[deref]
|
||||
#[deref_mut]
|
||||
pub(crate) layout: Arc<WrappedLineLayout>,
|
||||
pub text: SharedString,
|
||||
pub(crate) decoration_runs: SmallVec<[DecorationRun; 32]>,
|
||||
}
|
||||
|
||||
for (glyph_ix, glyph) in run.glyphs.iter().enumerate() {
|
||||
glyph_origin.x += glyph.position.x - prev_glyph_position.x;
|
||||
impl WrappedLine {
|
||||
pub fn len(&self) -> usize {
|
||||
self.layout.len()
|
||||
}
|
||||
|
||||
if wraps.peek() == Some(&&WrapBoundary { run_ix, glyph_ix }) {
|
||||
wraps.next();
|
||||
if let Some((underline_origin, underline_style)) = current_underline.take() {
|
||||
cx.paint_underline(
|
||||
underline_origin,
|
||||
glyph_origin.x - underline_origin.x,
|
||||
&underline_style,
|
||||
)?;
|
||||
}
|
||||
pub fn paint(
|
||||
&self,
|
||||
origin: Point<Pixels>,
|
||||
line_height: Pixels,
|
||||
cx: &mut WindowContext,
|
||||
) -> Result<()> {
|
||||
paint_line(
|
||||
origin,
|
||||
&self.layout.unwrapped_layout,
|
||||
line_height,
|
||||
&self.decoration_runs,
|
||||
self.wrap_width,
|
||||
&self.wrap_boundaries,
|
||||
cx,
|
||||
)?;
|
||||
|
||||
glyph_origin.x = origin.x;
|
||||
glyph_origin.y += line_height;
|
||||
}
|
||||
prev_glyph_position = glyph.position;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
let mut finished_underline: Option<(Point<Pixels>, UnderlineStyle)> = None;
|
||||
if glyph.index >= run_end {
|
||||
if let Some(style_run) = style_runs.next() {
|
||||
if let Some((_, underline_style)) = &mut current_underline {
|
||||
if style_run.underline.as_ref() != Some(underline_style) {
|
||||
finished_underline = current_underline.take();
|
||||
}
|
||||
}
|
||||
if let Some(run_underline) = style_run.underline.as_ref() {
|
||||
current_underline.get_or_insert((
|
||||
point(
|
||||
glyph_origin.x,
|
||||
origin.y
|
||||
+ baseline_offset.y
|
||||
+ (self.layout.layout.descent * 0.618),
|
||||
),
|
||||
UnderlineStyle {
|
||||
color: Some(run_underline.color.unwrap_or(style_run.color)),
|
||||
thickness: run_underline.thickness,
|
||||
wavy: run_underline.wavy,
|
||||
},
|
||||
));
|
||||
}
|
||||
fn paint_line(
|
||||
origin: Point<Pixels>,
|
||||
layout: &LineLayout,
|
||||
line_height: Pixels,
|
||||
decoration_runs: &[DecorationRun],
|
||||
wrap_width: Option<Pixels>,
|
||||
wrap_boundaries: &[WrapBoundary],
|
||||
cx: &mut WindowContext<'_>,
|
||||
) -> Result<()> {
|
||||
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();
|
||||
let mut wraps = wrap_boundaries.iter().peekable();
|
||||
let mut run_end = 0;
|
||||
let mut color = black();
|
||||
let mut current_underline: Option<(Point<Pixels>, UnderlineStyle)> = None;
|
||||
let text_system = cx.text_system().clone();
|
||||
let mut glyph_origin = origin;
|
||||
let mut prev_glyph_position = Point::default();
|
||||
for (run_ix, run) in layout.runs.iter().enumerate() {
|
||||
let max_glyph_size = text_system
|
||||
.bounding_box(run.font_id, layout.font_size)?
|
||||
.size;
|
||||
|
||||
run_end += style_run.len as usize;
|
||||
color = style_run.color;
|
||||
} else {
|
||||
run_end = self.layout.text.len();
|
||||
finished_underline = current_underline.take();
|
||||
}
|
||||
}
|
||||
for (glyph_ix, glyph) in run.glyphs.iter().enumerate() {
|
||||
glyph_origin.x += glyph.position.x - prev_glyph_position.x;
|
||||
|
||||
if let Some((underline_origin, underline_style)) = finished_underline {
|
||||
if wraps.peek() == Some(&&WrapBoundary { run_ix, glyph_ix }) {
|
||||
wraps.next();
|
||||
if let Some((underline_origin, underline_style)) = current_underline.take() {
|
||||
cx.paint_underline(
|
||||
underline_origin,
|
||||
glyph_origin.x - underline_origin.x,
|
||||
@@ -115,42 +118,84 @@ impl Line {
|
||||
)?;
|
||||
}
|
||||
|
||||
let max_glyph_bounds = Bounds {
|
||||
origin: glyph_origin,
|
||||
size: max_glyph_size,
|
||||
};
|
||||
glyph_origin.x = origin.x;
|
||||
glyph_origin.y += line_height;
|
||||
}
|
||||
prev_glyph_position = glyph.position;
|
||||
|
||||
let content_mask = cx.content_mask();
|
||||
if max_glyph_bounds.intersects(&content_mask.bounds) {
|
||||
if glyph.is_emoji {
|
||||
cx.paint_emoji(
|
||||
glyph_origin + baseline_offset,
|
||||
run.font_id,
|
||||
glyph.id,
|
||||
self.layout.layout.font_size,
|
||||
)?;
|
||||
} else {
|
||||
cx.paint_glyph(
|
||||
glyph_origin + baseline_offset,
|
||||
run.font_id,
|
||||
glyph.id,
|
||||
self.layout.layout.font_size,
|
||||
color,
|
||||
)?;
|
||||
let mut finished_underline: Option<(Point<Pixels>, UnderlineStyle)> = None;
|
||||
if glyph.index >= run_end {
|
||||
if let Some(style_run) = decoration_runs.next() {
|
||||
if let Some((_, underline_style)) = &mut current_underline {
|
||||
if style_run.underline.as_ref() != Some(underline_style) {
|
||||
finished_underline = current_underline.take();
|
||||
}
|
||||
}
|
||||
if let Some(run_underline) = style_run.underline.as_ref() {
|
||||
current_underline.get_or_insert((
|
||||
point(
|
||||
glyph_origin.x,
|
||||
origin.y + baseline_offset.y + (layout.descent * 0.618),
|
||||
),
|
||||
UnderlineStyle {
|
||||
color: Some(run_underline.color.unwrap_or(style_run.color)),
|
||||
thickness: run_underline.thickness,
|
||||
wavy: run_underline.wavy,
|
||||
},
|
||||
));
|
||||
}
|
||||
|
||||
run_end += style_run.len as usize;
|
||||
color = style_run.color;
|
||||
} else {
|
||||
run_end = layout.len;
|
||||
finished_underline = current_underline.take();
|
||||
}
|
||||
}
|
||||
|
||||
if let Some((underline_origin, underline_style)) = finished_underline {
|
||||
cx.paint_underline(
|
||||
underline_origin,
|
||||
glyph_origin.x - underline_origin.x,
|
||||
&underline_style,
|
||||
)?;
|
||||
}
|
||||
|
||||
let max_glyph_bounds = Bounds {
|
||||
origin: glyph_origin,
|
||||
size: max_glyph_size,
|
||||
};
|
||||
|
||||
let content_mask = cx.content_mask();
|
||||
if max_glyph_bounds.intersects(&content_mask.bounds) {
|
||||
if glyph.is_emoji {
|
||||
cx.paint_emoji(
|
||||
glyph_origin + baseline_offset,
|
||||
run.font_id,
|
||||
glyph.id,
|
||||
layout.font_size,
|
||||
)?;
|
||||
} else {
|
||||
cx.paint_glyph(
|
||||
glyph_origin + baseline_offset,
|
||||
run.font_id,
|
||||
glyph.id,
|
||||
layout.font_size,
|
||||
color,
|
||||
)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some((underline_start, underline_style)) = current_underline.take() {
|
||||
let line_end_x = origin.x + self.layout.layout.width;
|
||||
cx.paint_underline(
|
||||
underline_start,
|
||||
line_end_x - underline_start.x,
|
||||
&underline_style,
|
||||
)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
if let Some((underline_start, underline_style)) = current_underline.take() {
|
||||
let line_end_x = origin.x + wrap_width.unwrap_or(Pixels::MAX).min(layout.width);
|
||||
cx.paint_underline(
|
||||
underline_start,
|
||||
line_end_x - underline_start.x,
|
||||
&underline_style,
|
||||
)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
use crate::{px, FontId, GlyphId, Pixels, PlatformTextSystem, Point, SharedString};
|
||||
use derive_more::{Deref, DerefMut};
|
||||
use crate::{px, FontId, GlyphId, Pixels, PlatformTextSystem, Point, Size};
|
||||
use parking_lot::{Mutex, RwLock, RwLockUpgradableReadGuard};
|
||||
use smallvec::SmallVec;
|
||||
use std::{
|
||||
@@ -149,13 +148,11 @@ impl LineLayout {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deref, DerefMut, Default, Debug)]
|
||||
#[derive(Default, Debug)]
|
||||
pub struct WrappedLineLayout {
|
||||
#[deref]
|
||||
#[deref_mut]
|
||||
pub layout: LineLayout,
|
||||
pub text: SharedString,
|
||||
pub unwrapped_layout: Arc<LineLayout>,
|
||||
pub wrap_boundaries: SmallVec<[WrapBoundary; 1]>,
|
||||
pub wrap_width: Option<Pixels>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
@@ -164,31 +161,74 @@ pub struct WrapBoundary {
|
||||
pub glyph_ix: usize,
|
||||
}
|
||||
|
||||
impl WrappedLineLayout {
|
||||
pub fn len(&self) -> usize {
|
||||
self.unwrapped_layout.len
|
||||
}
|
||||
|
||||
pub fn width(&self) -> Pixels {
|
||||
self.wrap_width
|
||||
.unwrap_or(Pixels::MAX)
|
||||
.min(self.unwrapped_layout.width)
|
||||
}
|
||||
|
||||
pub fn size(&self, line_height: Pixels) -> Size<Pixels> {
|
||||
Size {
|
||||
width: self.width(),
|
||||
height: line_height * (self.wrap_boundaries.len() + 1),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn ascent(&self) -> Pixels {
|
||||
self.unwrapped_layout.ascent
|
||||
}
|
||||
|
||||
pub fn descent(&self) -> Pixels {
|
||||
self.unwrapped_layout.descent
|
||||
}
|
||||
|
||||
pub fn wrap_boundaries(&self) -> &[WrapBoundary] {
|
||||
&self.wrap_boundaries
|
||||
}
|
||||
|
||||
pub fn font_size(&self) -> Pixels {
|
||||
self.unwrapped_layout.font_size
|
||||
}
|
||||
|
||||
pub fn runs(&self) -> &[ShapedRun] {
|
||||
&self.unwrapped_layout.runs
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct LineLayoutCache {
|
||||
prev_frame: Mutex<HashMap<CacheKey, Arc<WrappedLineLayout>>>,
|
||||
curr_frame: RwLock<HashMap<CacheKey, Arc<WrappedLineLayout>>>,
|
||||
previous_frame: Mutex<HashMap<CacheKey, Arc<LineLayout>>>,
|
||||
current_frame: RwLock<HashMap<CacheKey, Arc<LineLayout>>>,
|
||||
previous_frame_wrapped: Mutex<HashMap<CacheKey, Arc<WrappedLineLayout>>>,
|
||||
current_frame_wrapped: RwLock<HashMap<CacheKey, Arc<WrappedLineLayout>>>,
|
||||
platform_text_system: Arc<dyn PlatformTextSystem>,
|
||||
}
|
||||
|
||||
impl LineLayoutCache {
|
||||
pub fn new(platform_text_system: Arc<dyn PlatformTextSystem>) -> Self {
|
||||
Self {
|
||||
prev_frame: Mutex::new(HashMap::new()),
|
||||
curr_frame: RwLock::new(HashMap::new()),
|
||||
previous_frame: Mutex::default(),
|
||||
current_frame: RwLock::default(),
|
||||
previous_frame_wrapped: Mutex::default(),
|
||||
current_frame_wrapped: RwLock::default(),
|
||||
platform_text_system,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn start_frame(&self) {
|
||||
let mut prev_frame = self.prev_frame.lock();
|
||||
let mut curr_frame = self.curr_frame.write();
|
||||
let mut prev_frame = self.previous_frame.lock();
|
||||
let mut curr_frame = self.current_frame.write();
|
||||
std::mem::swap(&mut *prev_frame, &mut *curr_frame);
|
||||
curr_frame.clear();
|
||||
}
|
||||
|
||||
pub fn layout_line(
|
||||
pub fn layout_wrapped_line(
|
||||
&self,
|
||||
text: &SharedString,
|
||||
text: &str,
|
||||
font_size: Pixels,
|
||||
runs: &[FontRun],
|
||||
wrap_width: Option<Pixels>,
|
||||
@@ -199,34 +239,66 @@ impl LineLayoutCache {
|
||||
runs,
|
||||
wrap_width,
|
||||
} as &dyn AsCacheKeyRef;
|
||||
let curr_frame = self.curr_frame.upgradable_read();
|
||||
if let Some(layout) = curr_frame.get(key) {
|
||||
|
||||
let current_frame = self.current_frame_wrapped.upgradable_read();
|
||||
if let Some(layout) = current_frame.get(key) {
|
||||
return layout.clone();
|
||||
}
|
||||
|
||||
let mut curr_frame = RwLockUpgradableReadGuard::upgrade(curr_frame);
|
||||
if let Some((key, layout)) = self.prev_frame.lock().remove_entry(key) {
|
||||
curr_frame.insert(key, layout.clone());
|
||||
let mut current_frame = RwLockUpgradableReadGuard::upgrade(current_frame);
|
||||
if let Some((key, layout)) = self.previous_frame_wrapped.lock().remove_entry(key) {
|
||||
current_frame.insert(key, layout.clone());
|
||||
layout
|
||||
} else {
|
||||
let layout = self.platform_text_system.layout_line(text, font_size, runs);
|
||||
let wrap_boundaries = wrap_width
|
||||
.map(|wrap_width| layout.compute_wrap_boundaries(text.as_ref(), wrap_width))
|
||||
.unwrap_or_default();
|
||||
let wrapped_line = Arc::new(WrappedLineLayout {
|
||||
layout,
|
||||
text: text.clone(),
|
||||
let unwrapped_layout = self.layout_line(text, font_size, runs);
|
||||
let wrap_boundaries = if let Some(wrap_width) = wrap_width {
|
||||
unwrapped_layout.compute_wrap_boundaries(text.as_ref(), wrap_width)
|
||||
} else {
|
||||
SmallVec::new()
|
||||
};
|
||||
let layout = Arc::new(WrappedLineLayout {
|
||||
unwrapped_layout,
|
||||
wrap_boundaries,
|
||||
wrap_width,
|
||||
});
|
||||
|
||||
let key = CacheKey {
|
||||
text: text.clone(),
|
||||
text: text.into(),
|
||||
font_size,
|
||||
runs: SmallVec::from(runs),
|
||||
wrap_width,
|
||||
};
|
||||
curr_frame.insert(key, wrapped_line.clone());
|
||||
wrapped_line
|
||||
current_frame.insert(key, layout.clone());
|
||||
layout
|
||||
}
|
||||
}
|
||||
|
||||
pub fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> Arc<LineLayout> {
|
||||
let key = &CacheKeyRef {
|
||||
text,
|
||||
font_size,
|
||||
runs,
|
||||
wrap_width: None,
|
||||
} as &dyn AsCacheKeyRef;
|
||||
|
||||
let current_frame = self.current_frame.upgradable_read();
|
||||
if let Some(layout) = current_frame.get(key) {
|
||||
return layout.clone();
|
||||
}
|
||||
|
||||
let mut current_frame = RwLockUpgradableReadGuard::upgrade(current_frame);
|
||||
if let Some((key, layout)) = self.previous_frame.lock().remove_entry(key) {
|
||||
current_frame.insert(key, layout.clone());
|
||||
layout
|
||||
} else {
|
||||
let layout = Arc::new(self.platform_text_system.layout_line(text, font_size, runs));
|
||||
let key = CacheKey {
|
||||
text: text.into(),
|
||||
font_size,
|
||||
runs: SmallVec::from(runs),
|
||||
wrap_width: None,
|
||||
};
|
||||
current_frame.insert(key, layout.clone());
|
||||
layout
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -243,7 +315,7 @@ trait AsCacheKeyRef {
|
||||
|
||||
#[derive(Eq)]
|
||||
struct CacheKey {
|
||||
text: SharedString,
|
||||
text: String,
|
||||
font_size: Pixels,
|
||||
runs: SmallVec<[FontRun; 1]>,
|
||||
wrap_width: Option<Pixels>,
|
||||
|
||||
+38
-59
@@ -1,7 +1,8 @@
|
||||
use crate::{
|
||||
private::Sealed, AnyBox, AnyElement, AnyModel, AnyWeakModel, AppContext, AvailableSpace,
|
||||
Bounds, Component, Element, ElementId, Entity, EntityId, Flatten, LayoutId, Model, Pixels,
|
||||
Size, ViewContext, VisualContext, WeakModel, WindowContext,
|
||||
BorrowWindow, Bounds, Component, Element, ElementId, Entity, EntityId, Flatten, FocusHandle,
|
||||
FocusableView, LayoutId, Model, Pixels, Point, Size, ViewContext, VisualContext, WeakModel,
|
||||
WindowContext,
|
||||
};
|
||||
use anyhow::{Context, Result};
|
||||
use std::{
|
||||
@@ -73,6 +74,13 @@ impl<V: 'static> View<V> {
|
||||
component: Some(component),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn focus_handle(&self, cx: &AppContext) -> FocusHandle
|
||||
where
|
||||
V: FocusableView,
|
||||
{
|
||||
self.read(cx).focus_handle(cx)
|
||||
}
|
||||
}
|
||||
|
||||
impl<V> Clone for View<V> {
|
||||
@@ -155,8 +163,7 @@ impl<V> Eq for WeakView<V> {}
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct AnyView {
|
||||
model: AnyModel,
|
||||
initialize: fn(&AnyView, &mut WindowContext) -> AnyBox,
|
||||
layout: fn(&AnyView, &mut AnyBox, &mut WindowContext) -> LayoutId,
|
||||
layout: fn(&AnyView, &mut WindowContext) -> (LayoutId, Box<dyn Any>),
|
||||
paint: fn(&AnyView, &mut AnyBox, &mut WindowContext),
|
||||
}
|
||||
|
||||
@@ -164,7 +171,6 @@ impl AnyView {
|
||||
pub fn downgrade(&self) -> AnyWeakView {
|
||||
AnyWeakView {
|
||||
model: self.model.downgrade(),
|
||||
initialize: self.initialize,
|
||||
layout: self.layout,
|
||||
paint: self.paint,
|
||||
}
|
||||
@@ -175,7 +181,6 @@ impl AnyView {
|
||||
Ok(model) => Ok(View { model }),
|
||||
Err(model) => Err(Self {
|
||||
model,
|
||||
initialize: self.initialize,
|
||||
layout: self.layout,
|
||||
paint: self.paint,
|
||||
}),
|
||||
@@ -186,13 +191,19 @@ impl AnyView {
|
||||
self.model.entity_type
|
||||
}
|
||||
|
||||
pub(crate) fn draw(&self, available_space: Size<AvailableSpace>, cx: &mut WindowContext) {
|
||||
let mut rendered_element = (self.initialize)(self, cx);
|
||||
let layout_id = (self.layout)(self, &mut rendered_element, cx);
|
||||
cx.window
|
||||
.layout_engine
|
||||
.compute_layout(layout_id, available_space);
|
||||
(self.paint)(self, &mut rendered_element, cx);
|
||||
pub(crate) fn draw(
|
||||
&self,
|
||||
origin: Point<Pixels>,
|
||||
available_space: Size<AvailableSpace>,
|
||||
cx: &mut WindowContext,
|
||||
) {
|
||||
cx.with_absolute_element_offset(origin, |cx| {
|
||||
let (layout_id, mut rendered_element) = (self.layout)(self, cx);
|
||||
cx.window
|
||||
.layout_engine
|
||||
.compute_layout(layout_id, available_space);
|
||||
(self.paint)(self, &mut rendered_element, cx);
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -206,7 +217,6 @@ impl<V: Render> From<View<V>> for AnyView {
|
||||
fn from(value: View<V>) -> Self {
|
||||
AnyView {
|
||||
model: value.model.into_any(),
|
||||
initialize: any_view::initialize::<V>,
|
||||
layout: any_view::layout::<V>,
|
||||
paint: any_view::paint::<V>,
|
||||
}
|
||||
@@ -220,22 +230,13 @@ impl<ParentViewState: 'static> Element<ParentViewState> for AnyView {
|
||||
Some(self.model.entity_id.into())
|
||||
}
|
||||
|
||||
fn initialize(
|
||||
fn layout(
|
||||
&mut self,
|
||||
_view_state: &mut ParentViewState,
|
||||
_element_state: Option<Self::ElementState>,
|
||||
cx: &mut ViewContext<ParentViewState>,
|
||||
) -> Self::ElementState {
|
||||
(self.initialize)(self, cx)
|
||||
}
|
||||
|
||||
fn layout(
|
||||
&mut self,
|
||||
_view_state: &mut ParentViewState,
|
||||
rendered_element: &mut Self::ElementState,
|
||||
cx: &mut ViewContext<ParentViewState>,
|
||||
) -> LayoutId {
|
||||
(self.layout)(self, rendered_element, cx)
|
||||
) -> (LayoutId, Self::ElementState) {
|
||||
(self.layout)(self, cx)
|
||||
}
|
||||
|
||||
fn paint(
|
||||
@@ -251,8 +252,7 @@ impl<ParentViewState: 'static> Element<ParentViewState> for AnyView {
|
||||
|
||||
pub struct AnyWeakView {
|
||||
model: AnyWeakModel,
|
||||
initialize: fn(&AnyView, &mut WindowContext) -> AnyBox,
|
||||
layout: fn(&AnyView, &mut AnyBox, &mut WindowContext) -> LayoutId,
|
||||
layout: fn(&AnyView, &mut WindowContext) -> (LayoutId, Box<dyn Any>),
|
||||
paint: fn(&AnyView, &mut AnyBox, &mut WindowContext),
|
||||
}
|
||||
|
||||
@@ -261,7 +261,6 @@ impl AnyWeakView {
|
||||
let model = self.model.upgrade()?;
|
||||
Some(AnyView {
|
||||
model,
|
||||
initialize: self.initialize,
|
||||
layout: self.layout,
|
||||
paint: self.paint,
|
||||
})
|
||||
@@ -272,7 +271,6 @@ impl<V: Render> From<WeakView<V>> for AnyWeakView {
|
||||
fn from(view: WeakView<V>) -> Self {
|
||||
Self {
|
||||
model: view.model.into(),
|
||||
initialize: any_view::initialize::<V>,
|
||||
layout: any_view::layout::<V>,
|
||||
paint: any_view::paint::<V>,
|
||||
}
|
||||
@@ -319,28 +317,19 @@ where
|
||||
Some(self.view.entity_id().into())
|
||||
}
|
||||
|
||||
fn initialize(
|
||||
fn layout(
|
||||
&mut self,
|
||||
_: &mut ParentViewState,
|
||||
_: Option<Self::ElementState>,
|
||||
cx: &mut ViewContext<ParentViewState>,
|
||||
) -> Self::ElementState {
|
||||
) -> (LayoutId, Self::ElementState) {
|
||||
self.view.update(cx, |view, cx| {
|
||||
let mut element = self.component.take().unwrap().render();
|
||||
element.initialize(view, cx);
|
||||
element
|
||||
let layout_id = element.layout(view, cx);
|
||||
(layout_id, element)
|
||||
})
|
||||
}
|
||||
|
||||
fn layout(
|
||||
&mut self,
|
||||
_: &mut ParentViewState,
|
||||
element: &mut Self::ElementState,
|
||||
cx: &mut ViewContext<ParentViewState>,
|
||||
) -> LayoutId {
|
||||
self.view.update(cx, |view, cx| element.layout(view, cx))
|
||||
}
|
||||
|
||||
fn paint(
|
||||
&mut self,
|
||||
_: Bounds<Pixels>,
|
||||
@@ -356,27 +345,17 @@ mod any_view {
|
||||
use crate::{AnyElement, AnyView, BorrowWindow, LayoutId, Render, WindowContext};
|
||||
use std::any::Any;
|
||||
|
||||
pub(crate) fn initialize<V: Render>(view: &AnyView, cx: &mut WindowContext) -> Box<dyn Any> {
|
||||
cx.with_element_id(Some(view.model.entity_id), |cx| {
|
||||
let view = view.clone().downcast::<V>().unwrap();
|
||||
let element = view.update(cx, |view, cx| {
|
||||
let mut element = AnyElement::new(view.render(cx));
|
||||
element.initialize(view, cx);
|
||||
element
|
||||
});
|
||||
Box::new(element)
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn layout<V: Render>(
|
||||
view: &AnyView,
|
||||
element: &mut Box<dyn Any>,
|
||||
cx: &mut WindowContext,
|
||||
) -> LayoutId {
|
||||
) -> (LayoutId, Box<dyn Any>) {
|
||||
cx.with_element_id(Some(view.model.entity_id), |cx| {
|
||||
let view = view.clone().downcast::<V>().unwrap();
|
||||
let element = element.downcast_mut::<AnyElement<V>>().unwrap();
|
||||
view.update(cx, |view, cx| element.layout(view, cx))
|
||||
view.update(cx, |view, cx| {
|
||||
let mut element = AnyElement::new(view.render(cx));
|
||||
let layout_id = element.layout(view, cx);
|
||||
(layout_id, Box::new(element) as Box<dyn Any>)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
+73
-22
@@ -185,6 +185,27 @@ impl Drop for FocusHandle {
|
||||
}
|
||||
}
|
||||
|
||||
/// FocusableView allows users of your view to easily
|
||||
/// focus it (using cx.focus_view(view))
|
||||
pub trait FocusableView: Render {
|
||||
fn focus_handle(&self, cx: &AppContext) -> FocusHandle;
|
||||
}
|
||||
|
||||
/// ManagedView is a view (like a Modal, Popover, Menu, etc.)
|
||||
/// where the lifecycle of the view is handled by another view.
|
||||
pub trait ManagedView: Render {
|
||||
fn focus_handle(&self, cx: &AppContext) -> FocusHandle;
|
||||
}
|
||||
|
||||
pub struct Dismiss;
|
||||
impl<T: ManagedView> EventEmitter<Dismiss> for T {}
|
||||
|
||||
impl<T: ManagedView> FocusableView for T {
|
||||
fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
|
||||
self.focus_handle(cx)
|
||||
}
|
||||
}
|
||||
|
||||
// Holds the state for a specific window.
|
||||
pub struct Window {
|
||||
pub(crate) handle: AnyWindowHandle,
|
||||
@@ -307,8 +328,8 @@ impl Window {
|
||||
layout_engine: TaffyLayoutEngine::new(),
|
||||
root_view: None,
|
||||
element_id_stack: GlobalElementId::default(),
|
||||
previous_frame: Frame::new(DispatchTree::new(cx.keymap.clone())),
|
||||
current_frame: Frame::new(DispatchTree::new(cx.keymap.clone())),
|
||||
previous_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
|
||||
current_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
|
||||
focus_handles: Arc::new(RwLock::new(SlotMap::with_key())),
|
||||
focus_listeners: SubscriberSet::new(),
|
||||
default_prevented: true,
|
||||
@@ -570,6 +591,7 @@ impl<'a> WindowContext<'a> {
|
||||
result
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
/// Add a node to the layout tree for the current frame. Takes the `Style` of the element for which
|
||||
/// layout is being requested, along with the layout ids of any children. This method is called during
|
||||
/// calls to the `Element::layout` trait method and enables any element to participate in layout.
|
||||
@@ -1076,26 +1098,22 @@ impl<'a> WindowContext<'a> {
|
||||
|
||||
self.with_z_index(0, |cx| {
|
||||
let available_space = cx.window.viewport_size.map(Into::into);
|
||||
root_view.draw(available_space, cx);
|
||||
root_view.draw(Point::zero(), available_space, cx);
|
||||
});
|
||||
|
||||
if let Some(active_drag) = self.app.active_drag.take() {
|
||||
self.with_z_index(1, |cx| {
|
||||
let offset = cx.mouse_position() - active_drag.cursor_offset;
|
||||
cx.with_element_offset(offset, |cx| {
|
||||
let available_space =
|
||||
size(AvailableSpace::MinContent, AvailableSpace::MinContent);
|
||||
active_drag.view.draw(available_space, cx);
|
||||
cx.active_drag = Some(active_drag);
|
||||
});
|
||||
let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
|
||||
active_drag.view.draw(offset, available_space, cx);
|
||||
cx.active_drag = Some(active_drag);
|
||||
});
|
||||
} else if let Some(active_tooltip) = self.app.active_tooltip.take() {
|
||||
self.with_z_index(1, |cx| {
|
||||
cx.with_element_offset(active_tooltip.cursor_offset, |cx| {
|
||||
let available_space =
|
||||
size(AvailableSpace::MinContent, AvailableSpace::MinContent);
|
||||
active_tooltip.view.draw(available_space, cx);
|
||||
});
|
||||
let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
|
||||
active_tooltip
|
||||
.view
|
||||
.draw(active_tooltip.cursor_offset, available_space, cx);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1150,6 +1168,14 @@ impl<'a> WindowContext<'a> {
|
||||
self.window.mouse_position = mouse_move.position;
|
||||
InputEvent::MouseMove(mouse_move)
|
||||
}
|
||||
InputEvent::MouseDown(mouse_down) => {
|
||||
self.window.mouse_position = mouse_down.position;
|
||||
InputEvent::MouseDown(mouse_down)
|
||||
}
|
||||
InputEvent::MouseUp(mouse_up) => {
|
||||
self.window.mouse_position = mouse_up.position;
|
||||
InputEvent::MouseUp(mouse_up)
|
||||
}
|
||||
// Translate dragging and dropping of external files from the operating system
|
||||
// to internal drag and drop events.
|
||||
InputEvent::FileDrop(file_drop) => match file_drop {
|
||||
@@ -1550,6 +1576,12 @@ impl VisualContext for WindowContext<'_> {
|
||||
self.window.root_view = Some(view.clone().into());
|
||||
view
|
||||
}
|
||||
|
||||
fn focus_view<V: crate::FocusableView>(&mut self, view: &View<V>) -> Self::Result<()> {
|
||||
self.update_view(view, |view, cx| {
|
||||
view.focus_handle(cx).clone().focus(cx);
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> std::ops::Deref for WindowContext<'a> {
|
||||
@@ -1633,8 +1665,8 @@ pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Update the global element offset based on the given offset. This is used to implement
|
||||
/// scrolling and position drag handles.
|
||||
/// Update the global element offset relative to the current offset. This is used to implement
|
||||
/// scrolling.
|
||||
fn with_element_offset<R>(
|
||||
&mut self,
|
||||
offset: Point<Pixels>,
|
||||
@@ -1644,7 +1676,17 @@ pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
|
||||
return f(self);
|
||||
};
|
||||
|
||||
let offset = self.element_offset() + offset;
|
||||
let abs_offset = self.element_offset() + offset;
|
||||
self.with_absolute_element_offset(abs_offset, f)
|
||||
}
|
||||
|
||||
/// Update the global element offset based on the given offset. This is used to implement
|
||||
/// drag handles and other manual painting of elements.
|
||||
fn with_absolute_element_offset<R>(
|
||||
&mut self,
|
||||
offset: Point<Pixels>,
|
||||
f: impl FnOnce(&mut Self) -> R,
|
||||
) -> R {
|
||||
self.window_mut()
|
||||
.current_frame
|
||||
.element_offset_stack
|
||||
@@ -1814,8 +1856,8 @@ impl<'a, V: 'static> ViewContext<'a, V> {
|
||||
self.view
|
||||
}
|
||||
|
||||
pub fn model(&self) -> Model<V> {
|
||||
self.view.model.clone()
|
||||
pub fn model(&self) -> &Model<V> {
|
||||
&self.view.model
|
||||
}
|
||||
|
||||
/// Access the underlying window context.
|
||||
@@ -2147,7 +2189,7 @@ impl<'a, V: 'static> ViewContext<'a, V> {
|
||||
|
||||
pub fn observe_global<G: 'static>(
|
||||
&mut self,
|
||||
f: impl Fn(&mut V, &mut ViewContext<'_, V>) + 'static,
|
||||
mut f: impl FnMut(&mut V, &mut ViewContext<'_, V>) + 'static,
|
||||
) -> Subscription {
|
||||
let window_handle = self.window.handle;
|
||||
let view = self.view().downgrade();
|
||||
@@ -2213,9 +2255,7 @@ impl<'a, V: 'static> ViewContext<'a, V> {
|
||||
.set_input_handler(Box::new(input_handler));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<V> ViewContext<'_, V> {
|
||||
pub fn emit<Evt>(&mut self, event: Evt)
|
||||
where
|
||||
Evt: 'static,
|
||||
@@ -2228,6 +2268,13 @@ impl<V> ViewContext<'_, V> {
|
||||
event: Box::new(event),
|
||||
});
|
||||
}
|
||||
|
||||
pub fn focus_self(&mut self)
|
||||
where
|
||||
V: FocusableView,
|
||||
{
|
||||
self.defer(|view, cx| view.focus_handle(cx).focus(cx))
|
||||
}
|
||||
}
|
||||
|
||||
impl<V> Context for ViewContext<'_, V> {
|
||||
@@ -2303,6 +2350,10 @@ impl<V: 'static> VisualContext for ViewContext<'_, V> {
|
||||
{
|
||||
self.window_cx.replace_root_view(build_view)
|
||||
}
|
||||
|
||||
fn focus_view<W: FocusableView>(&mut self, view: &View<W>) -> Self::Result<()> {
|
||||
self.window_cx.focus_view(view)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, V> std::ops::Deref for ViewContext<'a, V> {
|
||||
|
||||
Reference in New Issue
Block a user