Merge branch 'master' into close-window

This commit is contained in:
Max Brunsfeld
2021-05-07 14:24:48 -07:00
19 changed files with 1842 additions and 1018 deletions
+149 -93
View File
@@ -12,16 +12,16 @@ use keymap::MatchResult;
use parking_lot::{Mutex, RwLock};
use pathfinder_geometry::{rect::RectF, vector::vec2f};
use platform::Event;
use postage::{sink::Sink as _, stream::Stream as _};
use postage::{mpsc, sink::Sink as _, stream::Stream as _};
use smol::prelude::*;
use std::{
any::{type_name, Any, TypeId},
cell::RefCell,
collections::{hash_map::Entry, HashMap, HashSet, VecDeque},
collections::{HashMap, HashSet, VecDeque},
fmt::{self, Debug},
hash::{Hash, Hasher},
marker::PhantomData,
path::PathBuf,
path::{Path, PathBuf},
rc::{self, Rc},
sync::{Arc, Weak},
time::Duration,
@@ -87,7 +87,7 @@ pub enum MenuItem<'a> {
pub struct App(Rc<RefCell<MutableAppContext>>);
#[derive(Clone)]
pub struct TestAppContext(Rc<RefCell<MutableAppContext>>);
pub struct TestAppContext(Rc<RefCell<MutableAppContext>>, Rc<platform::test::Platform>);
impl App {
pub fn test<T, A: AssetSource, F: FnOnce(&mut MutableAppContext) -> T>(
@@ -111,13 +111,16 @@ impl App {
Fn: FnOnce(TestAppContext) -> F,
F: Future<Output = T>,
{
let platform = platform::test::platform();
let platform = Rc::new(platform::test::platform());
let foreground = Rc::new(executor::Foreground::test());
let ctx = TestAppContext(Rc::new(RefCell::new(MutableAppContext::new(
foreground.clone(),
Rc::new(platform),
asset_source,
))));
let ctx = TestAppContext(
Rc::new(RefCell::new(MutableAppContext::new(
foreground.clone(),
platform.clone(),
asset_source,
))),
platform,
);
ctx.0.borrow_mut().weak_self = Some(Rc::downgrade(&ctx.0));
let future = f(ctx);
@@ -332,6 +335,14 @@ impl TestAppContext {
pub fn platform(&self) -> Rc<dyn platform::Platform> {
self.0.borrow().platform.clone()
}
pub fn simulate_new_path_selection(&self, result: impl FnOnce(PathBuf) -> Option<PathBuf>) {
self.1.as_ref().simulate_new_path_selection(result);
}
pub fn did_prompt_for_new_path(&self) -> bool {
self.1.as_ref().did_prompt_for_new_path()
}
}
impl UpdateModel for TestAppContext {
@@ -381,7 +392,6 @@ pub struct MutableAppContext {
subscriptions: HashMap<usize, Vec<Subscription>>,
model_observations: HashMap<usize, Vec<ModelObservation>>,
view_observations: HashMap<usize, Vec<ViewObservation>>,
async_observations: HashMap<usize, postage::broadcast::Sender<()>>,
presenters_and_platform_windows:
HashMap<usize, (Rc<RefCell<Presenter>>, Box<dyn platform::Window>)>,
debug_elements_callbacks: HashMap<usize, Box<dyn Fn(&AppContext) -> crate::json::Value>>,
@@ -423,7 +433,6 @@ impl MutableAppContext {
subscriptions: HashMap::new(),
model_observations: HashMap::new(),
view_observations: HashMap::new(),
async_observations: HashMap::new(),
presenters_and_platform_windows: HashMap::new(),
debug_elements_callbacks: HashMap::new(),
foreground,
@@ -585,6 +594,22 @@ impl MutableAppContext {
);
}
pub fn prompt_for_new_path<F>(&self, directory: &Path, done_fn: F)
where
F: 'static + FnOnce(Option<PathBuf>, &mut MutableAppContext),
{
let app = self.weak_self.as_ref().unwrap().upgrade().unwrap();
let foreground = self.foreground.clone();
self.platform().prompt_for_new_path(
directory,
Box::new(move |path| {
foreground
.spawn(async move { (done_fn)(path, &mut *app.borrow_mut()) })
.detach();
}),
);
}
pub(crate) fn notify_view(&mut self, window_id: usize, view_id: usize) {
self.pending_effects
.push_back(Effect::ViewNotification { window_id, view_id });
@@ -878,13 +903,11 @@ impl MutableAppContext {
self.ctx.models.remove(&model_id);
self.subscriptions.remove(&model_id);
self.model_observations.remove(&model_id);
self.async_observations.remove(&model_id);
}
for (window_id, view_id) in dropped_views {
self.subscriptions.remove(&view_id);
self.model_observations.remove(&view_id);
self.async_observations.remove(&view_id);
self.ctx.views.remove(&(window_id, view_id));
let change_focus_to = self.ctx.windows.get_mut(&window_id).and_then(|window| {
window
@@ -1061,12 +1084,6 @@ impl MutableAppContext {
}
}
}
if let Entry::Occupied(mut entry) = self.async_observations.entry(observed_id) {
if entry.get_mut().blocking_send(()).is_err() {
entry.remove_entry();
}
}
}
fn notify_view_observers(&mut self, window_id: usize, view_id: usize) {
@@ -1079,7 +1096,7 @@ impl MutableAppContext {
}
if let Some(observations) = self.view_observations.remove(&view_id) {
if self.ctx.models.contains_key(&view_id) {
if self.ctx.views.contains_key(&(window_id, view_id)) {
for mut observation in observations {
let alive = if let Some(mut view) = self
.ctx
@@ -1111,12 +1128,6 @@ impl MutableAppContext {
}
}
}
if let Entry::Occupied(mut entry) = self.async_observations.entry(view_id) {
if entry.get_mut().blocking_send(()).is_err() {
entry.remove_entry();
}
}
}
fn focus(&mut self, window_id: usize, focused_id: usize) {
@@ -1748,6 +1759,10 @@ impl<'a, T: View> ViewContext<'a, T> {
self.window_id
}
pub fn view_id(&self) -> usize {
self.view_id
}
pub fn foreground(&self) -> &Rc<executor::Foreground> {
self.app.foreground_executor()
}
@@ -1756,6 +1771,20 @@ impl<'a, T: View> ViewContext<'a, T> {
&self.app.ctx.background
}
pub fn prompt_for_paths<F>(&self, options: PathPromptOptions, done_fn: F)
where
F: 'static + FnOnce(Option<Vec<PathBuf>>, &mut MutableAppContext),
{
self.app.prompt_for_paths(options, done_fn)
}
pub fn prompt_for_new_path<F>(&self, directory: &Path, done_fn: F)
where
F: 'static + FnOnce(Option<PathBuf>, &mut MutableAppContext),
{
self.app.prompt_for_new_path(directory, done_fn)
}
pub fn debug_elements(&self) -> crate::json::Value {
self.app.debug_elements(self.window_id).unwrap()
}
@@ -1809,22 +1838,11 @@ impl<'a, T: View> ViewContext<'a, T> {
F: 'static + FnMut(&mut T, ModelHandle<E>, &E::Event, &mut ViewContext<T>),
{
let emitter_handle = handle.downgrade();
self.app
.subscriptions
.entry(handle.id())
.or_default()
.push(Subscription::FromView {
window_id: self.window_id,
view_id: self.view_id,
callback: Box::new(move |view, payload, app, window_id, view_id| {
if let Some(emitter_handle) = emitter_handle.upgrade(app.as_ref()) {
let model = view.downcast_mut().expect("downcast is type safe");
let payload = payload.downcast_ref().expect("downcast is type safe");
let mut ctx = ViewContext::new(app, window_id, view_id);
callback(model, emitter_handle, payload, &mut ctx);
}
}),
});
self.subscribe(handle, move |model, payload, ctx| {
if let Some(emitter_handle) = emitter_handle.upgrade(ctx.as_ref()) {
callback(model, emitter_handle, payload, ctx);
}
});
}
pub fn subscribe_to_view<V, F>(&mut self, handle: &ViewHandle<V>, mut callback: F)
@@ -1834,7 +1852,19 @@ impl<'a, T: View> ViewContext<'a, T> {
F: 'static + FnMut(&mut T, ViewHandle<V>, &V::Event, &mut ViewContext<T>),
{
let emitter_handle = handle.downgrade();
self.subscribe(handle, move |view, payload, ctx| {
if let Some(emitter_handle) = emitter_handle.upgrade(ctx.as_ref()) {
callback(view, emitter_handle, payload, ctx);
}
});
}
pub fn subscribe<E, F>(&mut self, handle: &impl Handle<E>, mut callback: F)
where
E: Entity,
E::Event: 'static,
F: 'static + FnMut(&mut T, &E::Event, &mut ViewContext<T>),
{
self.app
.subscriptions
.entry(handle.id())
@@ -1842,13 +1872,11 @@ impl<'a, T: View> ViewContext<'a, T> {
.push(Subscription::FromView {
window_id: self.window_id,
view_id: self.view_id,
callback: Box::new(move |view, payload, app, window_id, view_id| {
if let Some(emitter_handle) = emitter_handle.upgrade(&app) {
let model = view.downcast_mut().expect("downcast is type safe");
let payload = payload.downcast_ref().expect("downcast is type safe");
let mut ctx = ViewContext::new(app, window_id, view_id);
callback(model, emitter_handle, payload, &mut ctx);
}
callback: Box::new(move |entity, payload, app, window_id, view_id| {
let entity = entity.downcast_mut().expect("downcast is type safe");
let payload = payload.downcast_ref().expect("downcast is type safe");
let mut ctx = ViewContext::new(app, window_id, view_id);
callback(entity, payload, &mut ctx);
}),
});
}
@@ -2072,7 +2100,7 @@ impl<T: Entity> ModelHandle<T> {
}
}
fn downgrade(&self) -> WeakModelHandle<T> {
pub fn downgrade(&self) -> WeakModelHandle<T> {
WeakModelHandle::new(self.model_id)
}
@@ -2106,12 +2134,24 @@ impl<T: Entity> ModelHandle<T> {
ctx: &TestAppContext,
mut predicate: impl FnMut(&T, &AppContext) -> bool,
) -> impl Future<Output = ()> {
let (tx, mut rx) = mpsc::channel(1024);
let mut ctx = ctx.0.borrow_mut();
let tx = ctx
.async_observations
.entry(self.id())
.or_insert_with(|| postage::broadcast::channel(128).0);
let mut rx = tx.subscribe();
self.update(&mut *ctx, |_, ctx| {
ctx.observe(self, {
let mut tx = tx.clone();
move |_, _, _| {
tx.blocking_send(()).ok();
}
});
ctx.subscribe(self, {
let mut tx = tx.clone();
move |_, _, _| {
tx.blocking_send(()).ok();
}
})
});
let ctx = ctx.weak_self.as_ref().unwrap().upgrade().unwrap();
let handle = self.downgrade();
@@ -2232,27 +2272,6 @@ impl<T> Clone for WeakModelHandle<T> {
}
}
pub struct AnyModelHandle {
model_id: usize,
ref_counts: Arc<Mutex<RefCounts>>,
}
impl<T: Entity> From<ModelHandle<T>> for AnyModelHandle {
fn from(handle: ModelHandle<T>) -> Self {
handle.ref_counts.lock().inc_entity(handle.model_id);
Self {
model_id: handle.model_id,
ref_counts: handle.ref_counts.clone(),
}
}
}
impl Drop for AnyModelHandle {
fn drop(&mut self) {
self.ref_counts.lock().dec_model(self.model_id);
}
}
pub struct ViewHandle<T> {
window_id: usize,
view_id: usize,
@@ -2303,19 +2322,41 @@ impl<T: View> ViewHandle<T> {
pub fn condition(
&self,
ctx: &TestAppContext,
mut predicate: impl 'static + FnMut(&T, &AppContext) -> bool,
) -> impl 'static + Future<Output = ()> {
predicate: impl FnMut(&T, &AppContext) -> bool,
) -> impl Future<Output = ()> {
self.condition_with_duration(Duration::from_millis(500), ctx, predicate)
}
pub fn condition_with_duration(
&self,
duration: Duration,
ctx: &TestAppContext,
mut predicate: impl FnMut(&T, &AppContext) -> bool,
) -> impl Future<Output = ()> {
let (tx, mut rx) = mpsc::channel(1024);
let mut ctx = ctx.0.borrow_mut();
let tx = ctx
.async_observations
.entry(self.id())
.or_insert_with(|| postage::broadcast::channel(128).0);
let mut rx = tx.subscribe();
self.update(&mut *ctx, |_, ctx| {
ctx.observe_view(self, {
let mut tx = tx.clone();
move |_, _, _| {
tx.blocking_send(()).ok();
}
});
ctx.subscribe(self, {
let mut tx = tx.clone();
move |_, _, _| {
tx.blocking_send(()).ok();
}
})
});
let ctx = ctx.weak_self.as_ref().unwrap().upgrade().unwrap();
let handle = self.downgrade();
async move {
timeout(Duration::from_millis(200), async move {
timeout(duration, async move {
loop {
{
let ctx = ctx.borrow();
@@ -2323,7 +2364,7 @@ impl<T: View> ViewHandle<T> {
if predicate(
handle
.upgrade(ctx)
.expect("model dropped with pending condition")
.expect("view dropped with pending condition")
.read(ctx),
ctx,
) {
@@ -2333,7 +2374,7 @@ impl<T: View> ViewHandle<T> {
rx.recv()
.await
.expect("model dropped with pending condition");
.expect("view dropped with pending condition");
}
})
.await
@@ -2472,6 +2513,26 @@ impl Drop for AnyViewHandle {
}
}
pub struct AnyModelHandle {
model_id: usize,
ref_counts: Arc<Mutex<RefCounts>>,
}
impl<T: Entity> From<ModelHandle<T>> for AnyModelHandle {
fn from(handle: ModelHandle<T>) -> Self {
handle.ref_counts.lock().inc_entity(handle.model_id);
Self {
model_id: handle.model_id,
ref_counts: handle.ref_counts.clone(),
}
}
}
impl Drop for AnyModelHandle {
fn drop(&mut self) {
self.ref_counts.lock().dec_model(self.model_id);
}
}
pub struct WeakViewHandle<T> {
window_id: usize,
view_id: usize,
@@ -3576,9 +3637,7 @@ mod tests {
model.update(&mut app, |model, ctx| model.inc(ctx));
assert_eq!(poll_once(&mut condition2).await, Some(()));
// Broadcast channel should be removed if no conditions remain on next notification.
model.update(&mut app, |_, ctx| ctx.notify());
app.update(|ctx| assert!(ctx.async_observations.get(&model.id()).is_none()));
});
}
@@ -3656,10 +3715,7 @@ mod tests {
view.update(&mut app, |view, ctx| view.inc(ctx));
assert_eq!(poll_once(&mut condition2).await, Some(()));
// Broadcast channel should be removed if no conditions remain on next notification.
view.update(&mut app, |_, ctx| ctx.notify());
app.update(|ctx| assert!(ctx.async_observations.get(&view.id()).is_none()));
});
}
@@ -3689,7 +3745,7 @@ mod tests {
}
#[test]
#[should_panic(expected = "model dropped with pending condition")]
#[should_panic(expected = "view dropped with pending condition")]
fn test_view_condition_panic_on_drop() {
struct View;
+39 -2
View File
@@ -5,7 +5,7 @@ use cocoa::{
appkit::{
NSApplication, NSApplicationActivationPolicy::NSApplicationActivationPolicyRegular,
NSEventModifierFlags, NSMenu, NSMenuItem, NSModalResponse, NSOpenPanel, NSPasteboard,
NSPasteboardTypeString, NSWindow,
NSPasteboardTypeString, NSSavePanel, NSWindow,
},
base::{id, nil, selector},
foundation::{NSArray, NSAutoreleasePool, NSData, NSInteger, NSString, NSURL},
@@ -25,7 +25,7 @@ use std::{
convert::TryInto,
ffi::{c_void, CStr},
os::raw::c_char,
path::PathBuf,
path::{Path, PathBuf},
ptr,
rc::Rc,
slice, str,
@@ -305,6 +305,43 @@ impl platform::Platform for MacPlatform {
}
}
fn prompt_for_new_path(
&self,
directory: &Path,
done_fn: Box<dyn FnOnce(Option<std::path::PathBuf>)>,
) {
unsafe {
let panel = NSSavePanel::savePanel(nil);
let path = ns_string(directory.to_string_lossy().as_ref());
let url = NSURL::fileURLWithPath_isDirectory_(nil, path, true.to_objc());
panel.setDirectoryURL(url);
let done_fn = Cell::new(Some(done_fn));
let block = ConcreteBlock::new(move |response: NSModalResponse| {
let result = if response == NSModalResponse::NSModalResponseOk {
let url = panel.URL();
let string = url.absoluteString();
let string = std::ffi::CStr::from_ptr(string.UTF8String())
.to_string_lossy()
.to_string();
if let Some(path) = string.strip_prefix("file://") {
Some(PathBuf::from(path))
} else {
None
}
} else {
None
};
if let Some(done_fn) = done_fn.take() {
(done_fn)(result);
}
});
let block = block.copy();
let _: () = msg_send![panel, beginWithCompletionHandler: block];
}
}
fn fonts(&self) -> Arc<dyn platform::FontSystem> {
self.fonts.clone()
}
+12 -1
View File
@@ -19,7 +19,13 @@ use crate::{
};
use async_task::Runnable;
pub use event::Event;
use std::{any::Any, ops::Range, path::PathBuf, rc::Rc, sync::Arc};
use std::{
any::Any,
ops::Range,
path::{Path, PathBuf},
rc::Rc,
sync::Arc,
};
pub trait Platform {
fn on_menu_command(&self, callback: Box<dyn FnMut(&str, Option<&dyn Any>)>);
@@ -45,6 +51,11 @@ pub trait Platform {
options: PathPromptOptions,
done_fn: Box<dyn FnOnce(Option<Vec<std::path::PathBuf>>)>,
);
fn prompt_for_new_path(
&self,
directory: &Path,
done_fn: Box<dyn FnOnce(Option<std::path::PathBuf>)>,
);
fn quit(&self);
fn write_to_clipboard(&self, item: ClipboardItem);
fn read_from_clipboard(&self) -> Option<ClipboardItem>;
+31 -4
View File
@@ -1,11 +1,18 @@
use crate::ClipboardItem;
use pathfinder_geometry::vector::Vector2F;
use std::{any::Any, cell::RefCell, rc::Rc, sync::Arc};
use std::{
any::Any,
cell::RefCell,
path::{Path, PathBuf},
rc::Rc,
sync::Arc,
};
struct Platform {
pub(crate) struct Platform {
dispatcher: Arc<dyn super::Dispatcher>,
fonts: Arc<dyn super::FontSystem>,
current_clipboard_item: RefCell<Option<ClipboardItem>>,
last_prompt_for_new_path_args: RefCell<Option<(PathBuf, Box<dyn FnOnce(Option<PathBuf>)>)>>,
}
struct Dispatcher;
@@ -24,9 +31,25 @@ impl Platform {
Self {
dispatcher: Arc::new(Dispatcher),
fonts: Arc::new(super::current::FontSystem::new()),
current_clipboard_item: RefCell::new(None),
current_clipboard_item: Default::default(),
last_prompt_for_new_path_args: Default::default(),
}
}
pub(crate) fn simulate_new_path_selection(
&self,
result: impl FnOnce(PathBuf) -> Option<PathBuf>,
) {
let (dir_path, callback) = self
.last_prompt_for_new_path_args
.take()
.expect("prompt_for_new_path was not called");
callback(result(dir_path));
}
pub(crate) fn did_prompt_for_new_path(&self) -> bool {
self.last_prompt_for_new_path_args.borrow().is_some()
}
}
impl super::Platform for Platform {
@@ -78,6 +101,10 @@ impl super::Platform for Platform {
) {
}
fn prompt_for_new_path(&self, path: &Path, f: Box<dyn FnOnce(Option<std::path::PathBuf>)>) {
*self.last_prompt_for_new_path_args.borrow_mut() = Some((path.to_path_buf(), f));
}
fn write_to_clipboard(&self, item: ClipboardItem) {
*self.current_clipboard_item.borrow_mut() = Some(item);
}
@@ -138,6 +165,6 @@ impl super::Window for Window {
}
}
pub fn platform() -> impl super::Platform {
pub(crate) fn platform() -> Platform {
Platform::new()
}