mostly working now

This commit is contained in:
Kay Simmons 2023-01-25 11:30:03 -08:00
parent a581d0c5b8
commit 5eac797a93
20 changed files with 675 additions and 454 deletions

11
Cargo.lock generated
View File

@ -1275,6 +1275,7 @@ source = "git+https://github.com/servo/core-foundation-rs?rev=079665882507dd5e2f
dependencies = [
"core-foundation-sys",
"libc",
"uuid 0.5.1",
]
[[package]]
@ -2591,6 +2592,7 @@ dependencies = [
"tiny-skia",
"usvg",
"util",
"uuid 1.2.2",
"waker-fn",
]
@ -6014,6 +6016,7 @@ dependencies = [
"parking_lot 0.11.2",
"smol",
"thread_local",
"uuid 1.2.2",
]
[[package]]
@ -7324,6 +7327,12 @@ dependencies = [
"tempdir",
]
[[package]]
name = "uuid"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bcc7e3b898aa6f6c08e5295b6c89258d1331e9ac578cc992fb818759951bdc22"
[[package]]
name = "uuid"
version = "0.8.2"
@ -8169,6 +8178,7 @@ dependencies = [
"smallvec",
"theme",
"util",
"uuid 1.2.2",
]
[[package]]
@ -8312,6 +8322,7 @@ dependencies = [
"url",
"urlencoding",
"util",
"uuid 1.2.2",
"vim",
"workspace",
]

View File

@ -196,7 +196,7 @@ impl TestServer {
languages: Arc::new(LanguageRegistry::new(Task::ready(()))),
themes: ThemeRegistry::new((), cx.font_cache()),
fs: fs.clone(),
build_window_options: |_| Default::default(),
build_window_options: |_, _, _| Default::default(),
initialize_workspace: |_, _, _| unimplemented!(),
dock_default_item_factory: |_, _| unimplemented!(),
});

View File

@ -54,17 +54,20 @@ pub fn init(app_state: Arc<AppState>, cx: &mut MutableAppContext) {
})
.await?;
let (_, workspace) = cx.add_window((app_state.build_window_options)(None), |cx| {
let mut workspace = Workspace::new(
Default::default(),
0,
project,
app_state.dock_default_item_factory,
cx,
);
(app_state.initialize_workspace)(&mut workspace, &app_state, cx);
workspace
});
let (_, workspace) = cx.add_window(
(app_state.build_window_options)(None, None, cx.platform().as_ref()),
|cx| {
let mut workspace = Workspace::new(
Default::default(),
0,
project,
app_state.dock_default_item_factory,
cx,
);
(app_state.initialize_workspace)(&mut workspace, &app_state, cx);
workspace
},
);
workspace
};

View File

@ -47,6 +47,7 @@ smol = "1.2"
time = { version = "0.3", features = ["serde", "serde-well-known"] }
tiny-skia = "0.5"
usvg = "0.14"
uuid = { version = "1.1.2", features = ["v4"] }
waker-fn = "1.1.0"
[build-dependencies]
@ -66,7 +67,7 @@ media = { path = "../media" }
anyhow = "1"
block = "0.1"
cocoa = "0.24"
core-foundation = "0.9.3"
core-foundation = { version = "0.9.3", features = ["with-uuid"] }
core-graphics = "0.22.3"
core-text = "19.2"
font-kit = { git = "https://github.com/zed-industries/font-kit", rev = "8eaf7a918eafa28b0a37dc759e2e0e7683fa24f1" }

View File

@ -32,6 +32,7 @@ use collections::{hash_map::Entry, HashMap, HashSet, VecDeque};
use platform::Event;
#[cfg(any(test, feature = "test-support"))]
pub use test_app_context::{ContextHandle, TestAppContext};
use uuid::Uuid;
use crate::{
elements::ElementBox,
@ -595,7 +596,7 @@ type ReleaseObservationCallback = Box<dyn FnMut(&dyn Any, &mut MutableAppContext
type ActionObservationCallback = Box<dyn FnMut(TypeId, &mut MutableAppContext)>;
type WindowActivationCallback = Box<dyn FnMut(bool, &mut MutableAppContext) -> bool>;
type WindowFullscreenCallback = Box<dyn FnMut(bool, &mut MutableAppContext) -> bool>;
type WindowBoundsCallback = Box<dyn FnMut(WindowBounds, &mut MutableAppContext) -> bool>;
type WindowBoundsCallback = Box<dyn FnMut(WindowBounds, Uuid, &mut MutableAppContext) -> bool>;
type KeystrokeCallback = Box<
dyn FnMut(&Keystroke, &MatchResult, Option<&Box<dyn Action>>, &mut MutableAppContext) -> bool,
>;
@ -909,10 +910,17 @@ impl MutableAppContext {
.map_or(false, |window| window.is_fullscreen)
}
pub fn window_bounds(&self, window_id: usize) -> RectF {
pub fn window_bounds(&self, window_id: usize) -> WindowBounds {
self.presenters_and_platform_windows[&window_id].1.bounds()
}
pub fn window_display_uuid(&self, window_id: usize) -> Uuid {
self.presenters_and_platform_windows[&window_id]
.1
.screen()
.display_uuid()
}
pub fn render_view(&mut self, params: RenderParams) -> Result<ElementBox> {
let window_id = params.window_id;
let view_id = params.view_id;
@ -1246,7 +1254,7 @@ impl MutableAppContext {
fn observe_window_bounds<F>(&mut self, window_id: usize, callback: F) -> Subscription
where
F: 'static + FnMut(WindowBounds, &mut MutableAppContext) -> bool,
F: 'static + FnMut(WindowBounds, Uuid, &mut MutableAppContext) -> bool,
{
let subscription_id = post_inc(&mut self.next_subscription_id);
self.pending_effects
@ -2382,14 +2390,12 @@ impl MutableAppContext {
callback(is_fullscreen, this)
});
let bounds = if this.window_is_fullscreen(window_id) {
WindowBounds::Fullscreen
} else {
WindowBounds::Fixed(this.window_bounds(window_id))
};
let bounds = this.window_bounds(window_id);
let uuid = this.window_display_uuid(window_id);
let mut bounds_observations = this.window_bounds_observations.clone();
bounds_observations.emit(window_id, this, |callback, this| callback(bounds, this));
bounds_observations.emit(window_id, this, |callback, this| {
callback(bounds, uuid, this)
});
Some(())
});
@ -2568,15 +2574,12 @@ impl MutableAppContext {
}
fn handle_window_moved(&mut self, window_id: usize) {
let bounds = if self.window_is_fullscreen(window_id) {
WindowBounds::Fullscreen
} else {
WindowBounds::Fixed(self.window_bounds(window_id))
};
let bounds = self.window_bounds(window_id);
let display = self.window_display_uuid(window_id);
self.window_bounds_observations
.clone()
.emit(window_id, self, move |callback, this| {
callback(bounds, this);
callback(bounds, display, this);
true
});
}
@ -3717,7 +3720,7 @@ impl<'a, T: View> ViewContext<'a, T> {
self.app.toggle_window_full_screen(self.window_id)
}
pub fn window_bounds(&self) -> RectF {
pub fn window_bounds(&self) -> WindowBounds {
self.app.window_bounds(self.window_id)
}
@ -4023,14 +4026,14 @@ impl<'a, T: View> ViewContext<'a, T> {
pub fn observe_window_bounds<F>(&mut self, mut callback: F) -> Subscription
where
F: 'static + FnMut(&mut T, WindowBounds, &mut ViewContext<T>),
F: 'static + FnMut(&mut T, WindowBounds, Uuid, &mut ViewContext<T>),
{
let observer = self.weak_handle();
self.app
.observe_window_bounds(self.window_id(), move |bounds, cx| {
.observe_window_bounds(self.window_id(), move |bounds, display, cx| {
if let Some(observer) = observer.upgrade(cx) {
observer.update(cx, |observer, cx| {
callback(observer, bounds, cx);
callback(observer, bounds, display, cx);
});
true
} else {

View File

@ -18,11 +18,15 @@ use crate::{
text_layout::{LineLayout, RunStyle},
Action, ClipboardItem, Menu, Scene,
};
use anyhow::{anyhow, Result};
use anyhow::{anyhow, bail, Result};
use async_task::Runnable;
pub use event::*;
use postage::oneshot;
use serde::Deserialize;
use sqlez::{
bindable::{Bind, Column, StaticColumnCount},
statement::Statement,
};
use std::{
any::Any,
fmt::{self, Debug, Display},
@ -33,6 +37,7 @@ use std::{
sync::Arc,
};
use time::UtcOffset;
use uuid::Uuid;
pub trait Platform: Send + Sync {
fn dispatcher(&self) -> Arc<dyn Dispatcher>;
@ -44,6 +49,7 @@ pub trait Platform: Send + Sync {
fn unhide_other_apps(&self);
fn quit(&self);
fn screen_by_id(&self, id: Uuid) -> Option<Rc<dyn Screen>>;
fn screens(&self) -> Vec<Rc<dyn Screen>>;
fn open_window(
@ -118,17 +124,18 @@ pub trait InputHandler {
pub trait Screen: Debug {
fn as_any(&self) -> &dyn Any;
fn size(&self) -> Vector2F;
fn display_uuid(&self) -> Uuid;
}
pub trait Window {
fn bounds(&self) -> WindowBounds;
fn content_size(&self) -> Vector2F;
fn scale_factor(&self) -> f32;
fn titlebar_height(&self) -> f32;
fn appearance(&self) -> Appearance;
fn screen(&self) -> Rc<dyn Screen>;
fn as_any_mut(&mut self) -> &mut dyn Any;
fn on_event(&mut self, callback: Box<dyn FnMut(Event) -> bool>);
fn on_active_status_change(&mut self, callback: Box<dyn FnMut(bool)>);
fn on_resize(&mut self, callback: Box<dyn FnMut()>);
fn on_fullscreen(&mut self, callback: Box<dyn FnMut(bool)>);
fn on_moved(&mut self, callback: Box<dyn FnMut()>);
fn on_should_close(&mut self, callback: Box<dyn FnMut() -> bool>);
fn on_close(&mut self, callback: Box<dyn FnOnce()>);
fn set_input_handler(&mut self, input_handler: Box<dyn InputHandler>);
fn prompt(&self, level: PromptLevel, msg: &str, answers: &[&str]) -> oneshot::Receiver<usize>;
fn activate(&self);
@ -137,14 +144,16 @@ pub trait Window {
fn show_character_palette(&self);
fn minimize(&self);
fn zoom(&self);
fn present_scene(&mut self, scene: Scene);
fn toggle_full_screen(&self);
fn bounds(&self) -> RectF;
fn content_size(&self) -> Vector2F;
fn scale_factor(&self) -> f32;
fn titlebar_height(&self) -> f32;
fn present_scene(&mut self, scene: Scene);
fn appearance(&self) -> Appearance;
fn on_event(&mut self, callback: Box<dyn FnMut(Event) -> bool>);
fn on_active_status_change(&mut self, callback: Box<dyn FnMut(bool)>);
fn on_resize(&mut self, callback: Box<dyn FnMut()>);
fn on_fullscreen(&mut self, callback: Box<dyn FnMut(bool)>);
fn on_moved(&mut self, callback: Box<dyn FnMut()>);
fn on_should_close(&mut self, callback: Box<dyn FnMut() -> bool>);
fn on_close(&mut self, callback: Box<dyn FnOnce()>);
fn on_appearance_changed(&mut self, callback: Box<dyn FnMut()>);
fn is_topmost_for_position(&self, position: Vector2F) -> bool;
}
@ -187,13 +196,70 @@ pub enum WindowKind {
PopUp,
}
#[derive(Copy, Clone, Debug)]
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum WindowBounds {
Fullscreen,
Maximized,
Fixed(RectF),
}
impl StaticColumnCount for WindowBounds {
fn column_count() -> usize {
5
}
}
impl Bind for WindowBounds {
fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
let (region, next_index) = match self {
WindowBounds::Fullscreen => {
let next_index = statement.bind("Fullscreen", start_index)?;
(None, next_index)
}
WindowBounds::Maximized => {
let next_index = statement.bind("Maximized", start_index)?;
(None, next_index)
}
WindowBounds::Fixed(region) => {
let next_index = statement.bind("Fixed", start_index)?;
(Some(*region), next_index)
}
};
statement.bind(
region.map(|region| {
(
region.min_x(),
region.min_y(),
region.width(),
region.height(),
)
}),
next_index,
)
}
}
impl Column for WindowBounds {
fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
let (window_state, next_index) = String::column(statement, start_index)?;
let bounds = match window_state.as_str() {
"Fullscreen" => WindowBounds::Fullscreen,
"Maximized" => WindowBounds::Maximized,
"Fixed" => {
let ((x, y, width, height), _) = Column::column(statement, next_index)?;
WindowBounds::Fixed(RectF::new(
Vector2F::new(x, y),
Vector2F::new(width, height),
))
}
_ => bail!("Window State did not have a valid string"),
};
Ok((bounds, next_index + 4))
}
}
pub struct PathPromptOptions {
pub files: bool,
pub directories: bool,

View File

@ -440,6 +440,10 @@ impl platform::Platform for MacPlatform {
self.dispatcher.clone()
}
fn fonts(&self) -> Arc<dyn platform::FontSystem> {
self.fonts.clone()
}
fn activate(&self, ignoring_other_apps: bool) {
unsafe {
let app = NSApplication::sharedApplication(nil);
@ -488,6 +492,10 @@ impl platform::Platform for MacPlatform {
}
}
fn screen_by_id(&self, id: uuid::Uuid) -> Option<Rc<dyn crate::Screen>> {
Screen::find_by_id(id).map(|screen| Rc::new(screen) as Rc<_>)
}
fn screens(&self) -> Vec<Rc<dyn platform::Screen>> {
Screen::all()
.into_iter()
@ -512,10 +520,6 @@ impl platform::Platform for MacPlatform {
Box::new(StatusItem::add(self.fonts()))
}
fn fonts(&self) -> Arc<dyn platform::FontSystem> {
self.fonts.clone()
}
fn write_to_clipboard(&self, item: ClipboardItem) {
unsafe {
self.pasteboard.clearContents();

View File

@ -1,4 +1,4 @@
use std::any::Any;
use std::{any::Any, ffi::c_void};
use crate::{
geometry::vector::{vec2f, Vector2F},
@ -7,8 +7,19 @@ use crate::{
use cocoa::{
appkit::NSScreen,
base::{id, nil},
foundation::NSArray,
foundation::{NSArray, NSDictionary, NSString},
};
use core_foundation::{
number::{kCFNumberIntType, CFNumberGetValue, CFNumberRef},
uuid::{CFUUIDGetUUIDBytes, CFUUIDRef},
};
use core_graphics::display::CGDirectDisplayID;
use uuid::Uuid;
#[link(name = "ApplicationServices", kind = "framework")]
extern "C" {
pub fn CGDisplayCreateUUIDFromDisplayID(display: CGDirectDisplayID) -> CFUUIDRef;
}
#[derive(Debug)]
pub struct Screen {
@ -16,11 +27,23 @@ pub struct Screen {
}
impl Screen {
pub fn find_by_id(uuid: Uuid) -> Option<Self> {
unsafe {
let native_screens = NSScreen::screens(nil);
(0..NSArray::count(native_screens))
.into_iter()
.map(|ix| Screen {
native_screen: native_screens.objectAtIndex(ix),
})
.find(|screen| platform::Screen::display_uuid(screen) == uuid)
}
}
pub fn all() -> Vec<Self> {
let mut screens = Vec::new();
unsafe {
let native_screens = NSScreen::screens(nil);
for ix in 0..native_screens.count() {
for ix in 0..NSArray::count(native_screens) {
screens.push(Screen {
native_screen: native_screens.objectAtIndex(ix),
});
@ -41,4 +64,42 @@ impl platform::Screen for Screen {
vec2f(frame.size.width as f32, frame.size.height as f32)
}
}
fn display_uuid(&self) -> uuid::Uuid {
unsafe {
// Screen ids are not stable. Further, the default device id is also unstable across restarts.
// CGDisplayCreateUUIDFromDisplayID is stable but not exposed in the bindings we use.
// This approach is similar to that which winit takes
// https://github.com/rust-windowing/winit/blob/402cbd55f932e95dbfb4e8b5e8551c49e56ff9ac/src/platform_impl/macos/monitor.rs#L99
let device_description = self.native_screen.deviceDescription();
let key = NSString::alloc(nil).init_str("NSScreenNumber");
let device_id_obj = device_description.objectForKey_(key);
let mut device_id: u32 = 0;
CFNumberGetValue(
device_id_obj as CFNumberRef,
kCFNumberIntType,
(&mut device_id) as *mut _ as *mut c_void,
);
let cfuuid = CGDisplayCreateUUIDFromDisplayID(device_id as CGDirectDisplayID);
let bytes = CFUUIDGetUUIDBytes(cfuuid);
Uuid::from_bytes([
bytes.byte0,
bytes.byte1,
bytes.byte2,
bytes.byte3,
bytes.byte4,
bytes.byte5,
bytes.byte6,
bytes.byte7,
bytes.byte8,
bytes.byte9,
bytes.byte10,
bytes.byte11,
bytes.byte12,
bytes.byte13,
bytes.byte14,
bytes.byte15,
])
}
}
}

View File

@ -7,7 +7,7 @@ use crate::{
self,
mac::{platform::NSViewLayerContentsRedrawDuringViewResize, renderer::Renderer},
},
Event, FontSystem, Scene,
Event, FontSystem, Scene, WindowBounds,
};
use cocoa::{
appkit::{NSScreen, NSSquareStatusItemLength, NSStatusBar, NSStatusItem, NSView, NSWindow},
@ -32,6 +32,8 @@ use std::{
sync::Arc,
};
use super::screen::Screen;
static mut VIEW_CLASS: *const Class = ptr::null();
const STATE_IVAR: &str = "state";
@ -167,30 +169,42 @@ impl StatusItem {
}
impl platform::Window for StatusItem {
fn bounds(&self) -> WindowBounds {
self.0.borrow().bounds()
}
fn content_size(&self) -> Vector2F {
self.0.borrow().content_size()
}
fn scale_factor(&self) -> f32 {
self.0.borrow().scale_factor()
}
fn titlebar_height(&self) -> f32 {
0.
}
fn appearance(&self) -> crate::Appearance {
unsafe {
let appearance: id =
msg_send![self.0.borrow().native_item.button(), effectiveAppearance];
crate::Appearance::from_native(appearance)
}
}
fn screen(&self) -> Rc<dyn crate::Screen> {
unsafe {
Rc::new(Screen {
native_screen: self.0.borrow().native_window().screen(),
})
}
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
fn on_event(&mut self, callback: Box<dyn FnMut(crate::Event) -> bool>) {
self.0.borrow_mut().event_callback = Some(callback);
}
fn on_appearance_changed(&mut self, callback: Box<dyn FnMut()>) {
self.0.borrow_mut().appearance_changed_callback = Some(callback);
}
fn on_active_status_change(&mut self, _: Box<dyn FnMut(bool)>) {}
fn on_resize(&mut self, _: Box<dyn FnMut()>) {}
fn on_moved(&mut self, _: Box<dyn FnMut()>) {}
fn on_fullscreen(&mut self, _: Box<dyn FnMut(bool)>) {}
fn on_should_close(&mut self, _: Box<dyn FnMut() -> bool>) {}
fn on_close(&mut self, _: Box<dyn FnOnce()>) {}
fn set_input_handler(&mut self, _: Box<dyn crate::InputHandler>) {}
fn prompt(
@ -226,26 +240,6 @@ impl platform::Window for StatusItem {
unimplemented!()
}
fn toggle_full_screen(&self) {
unimplemented!()
}
fn bounds(&self) -> RectF {
self.0.borrow().bounds()
}
fn content_size(&self) -> Vector2F {
self.0.borrow().content_size()
}
fn scale_factor(&self) -> f32 {
self.0.borrow().scale_factor()
}
fn titlebar_height(&self) -> f32 {
0.
}
fn present_scene(&mut self, scene: Scene) {
self.0.borrow_mut().scene = Some(scene);
unsafe {
@ -253,12 +247,28 @@ impl platform::Window for StatusItem {
}
}
fn appearance(&self) -> crate::Appearance {
unsafe {
let appearance: id =
msg_send![self.0.borrow().native_item.button(), effectiveAppearance];
crate::Appearance::from_native(appearance)
}
fn toggle_full_screen(&self) {
unimplemented!()
}
fn on_event(&mut self, callback: Box<dyn FnMut(crate::Event) -> bool>) {
self.0.borrow_mut().event_callback = Some(callback);
}
fn on_active_status_change(&mut self, _: Box<dyn FnMut(bool)>) {}
fn on_resize(&mut self, _: Box<dyn FnMut()>) {}
fn on_fullscreen(&mut self, _: Box<dyn FnMut(bool)>) {}
fn on_moved(&mut self, _: Box<dyn FnMut()>) {}
fn on_should_close(&mut self, _: Box<dyn FnMut() -> bool>) {}
fn on_close(&mut self, _: Box<dyn FnOnce()>) {}
fn on_appearance_changed(&mut self, callback: Box<dyn FnMut()>) {
self.0.borrow_mut().appearance_changed_callback = Some(callback);
}
fn is_topmost_for_position(&self, _: Vector2F) -> bool {
@ -267,9 +277,9 @@ impl platform::Window for StatusItem {
}
impl StatusItemState {
fn bounds(&self) -> RectF {
fn bounds(&self) -> WindowBounds {
unsafe {
let window: id = msg_send![self.native_item.button(), window];
let window: id = self.native_window();
let screen_frame = window.screen().visibleFrame();
let window_frame = NSWindow::frame(window);
let origin = vec2f(
@ -281,7 +291,7 @@ impl StatusItemState {
window_frame.size.width as f32,
window_frame.size.height as f32,
);
RectF::new(origin, size)
WindowBounds::Fixed(RectF::new(origin, size))
}
}
@ -299,6 +309,10 @@ impl StatusItemState {
NSScreen::backingScaleFactor(window.screen()) as f32
}
}
pub fn native_window(&self) -> id {
unsafe { msg_send![self.native_item.button(), window] }
}
}
extern "C" fn dealloc_view(this: &Object, _: Sel) {

View File

@ -419,19 +419,17 @@ impl Window {
WindowBounds::Fixed(top_left_bounds) => {
let frame = screen.visibleFrame();
let bottom_left_bounds = RectF::new(
vec2f(
dbg!(vec2f(
top_left_bounds.origin_x(),
frame.size.height as f32
- top_left_bounds.origin_y()
- top_left_bounds.height(),
),
top_left_bounds.size(),
)),
dbg!(top_left_bounds.size()),
)
.to_ns_rect();
native_window.setFrame_display_(
native_window.convertRectToScreen_(bottom_left_bounds),
YES,
);
let screen_rect = native_window.convertRectToScreen_(bottom_left_bounds);
native_window.setFrame_display_(screen_rect, YES);
}
}
@ -585,38 +583,41 @@ impl Drop for Window {
}
impl platform::Window for Window {
fn bounds(&self) -> WindowBounds {
self.0.as_ref().borrow().bounds()
}
fn content_size(&self) -> Vector2F {
self.0.as_ref().borrow().content_size()
}
fn scale_factor(&self) -> f32 {
self.0.as_ref().borrow().scale_factor()
}
fn titlebar_height(&self) -> f32 {
self.0.as_ref().borrow().titlebar_height()
}
fn appearance(&self) -> crate::Appearance {
unsafe {
let appearance: id = msg_send![self.0.borrow().native_window, effectiveAppearance];
crate::Appearance::from_native(appearance)
}
}
fn screen(&self) -> Rc<dyn crate::Screen> {
unsafe {
Rc::new(Screen {
native_screen: self.0.as_ref().borrow().native_window.screen(),
})
}
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
fn on_event(&mut self, callback: Box<dyn FnMut(Event) -> bool>) {
self.0.as_ref().borrow_mut().event_callback = Some(callback);
}
fn on_resize(&mut self, callback: Box<dyn FnMut()>) {
self.0.as_ref().borrow_mut().resize_callback = Some(callback);
}
fn on_moved(&mut self, callback: Box<dyn FnMut()>) {
self.0.as_ref().borrow_mut().moved_callback = Some(callback);
}
fn on_fullscreen(&mut self, callback: Box<dyn FnMut(bool)>) {
self.0.as_ref().borrow_mut().fullscreen_callback = Some(callback);
}
fn on_should_close(&mut self, callback: Box<dyn FnMut() -> bool>) {
self.0.as_ref().borrow_mut().should_close_callback = Some(callback);
}
fn on_close(&mut self, callback: Box<dyn FnOnce()>) {
self.0.as_ref().borrow_mut().close_callback = Some(callback);
}
fn on_active_status_change(&mut self, callback: Box<dyn FnMut(bool)>) {
self.0.as_ref().borrow_mut().activate_callback = Some(callback);
}
fn set_input_handler(&mut self, input_handler: Box<dyn InputHandler>) {
self.0.as_ref().borrow_mut().input_handler = Some(input_handler);
}
@ -726,6 +727,10 @@ impl platform::Window for Window {
.detach();
}
fn present_scene(&mut self, scene: Scene) {
self.0.as_ref().borrow_mut().present_scene(scene);
}
fn toggle_full_screen(&self) {
let this = self.0.borrow();
let window = this.native_window;
@ -738,31 +743,32 @@ impl platform::Window for Window {
.detach();
}
fn bounds(&self) -> RectF {
self.0.as_ref().borrow().bounds()
fn on_event(&mut self, callback: Box<dyn FnMut(Event) -> bool>) {
self.0.as_ref().borrow_mut().event_callback = Some(callback);
}
fn content_size(&self) -> Vector2F {
self.0.as_ref().borrow().content_size()
fn on_active_status_change(&mut self, callback: Box<dyn FnMut(bool)>) {
self.0.as_ref().borrow_mut().activate_callback = Some(callback);
}
fn scale_factor(&self) -> f32 {
self.0.as_ref().borrow().scale_factor()
fn on_resize(&mut self, callback: Box<dyn FnMut()>) {
self.0.as_ref().borrow_mut().resize_callback = Some(callback);
}
fn present_scene(&mut self, scene: Scene) {
self.0.as_ref().borrow_mut().present_scene(scene);
fn on_fullscreen(&mut self, callback: Box<dyn FnMut(bool)>) {
self.0.as_ref().borrow_mut().fullscreen_callback = Some(callback);
}
fn titlebar_height(&self) -> f32 {
self.0.as_ref().borrow().titlebar_height()
fn on_moved(&mut self, callback: Box<dyn FnMut()>) {
self.0.as_ref().borrow_mut().moved_callback = Some(callback);
}
fn appearance(&self) -> crate::Appearance {
unsafe {
let appearance: id = msg_send![self.0.borrow().native_window, effectiveAppearance];
crate::Appearance::from_native(appearance)
}
fn on_should_close(&mut self, callback: Box<dyn FnMut() -> bool>) {
self.0.as_ref().borrow_mut().should_close_callback = Some(callback);
}
fn on_close(&mut self, callback: Box<dyn FnOnce()>) {
self.0.as_ref().borrow_mut().close_callback = Some(callback);
}
fn on_appearance_changed(&mut self, callback: Box<dyn FnMut()>) {
@ -846,20 +852,39 @@ impl WindowState {
}
}
fn bounds(&self) -> RectF {
fn is_fullscreen(&self) -> bool {
unsafe {
let style_mask = self.native_window.styleMask();
style_mask.contains(NSWindowStyleMask::NSFullScreenWindowMask)
}
}
fn bounds(&self) -> WindowBounds {
unsafe {
if self.is_fullscreen() {
return WindowBounds::Fullscreen;
}
let screen_frame = self.native_window.screen().visibleFrame();
let window_frame = NSWindow::frame(self.native_window);
let origin = vec2f(
window_frame.origin.x as f32,
(window_frame.origin.y - screen_frame.size.height - window_frame.size.height)
(screen_frame.size.height - window_frame.origin.y - window_frame.size.height)
as f32,
);
let size = vec2f(
window_frame.size.width as f32,
window_frame.size.height as f32,
);
RectF::new(origin, size)
if origin.is_zero()
&& size.x() == screen_frame.size.width as f32
&& size.y() == screen_frame.size.height as f32
{
WindowBounds::Maximized
} else {
WindowBounds::Fixed(RectF::new(origin, size))
}
}
}

View File

@ -20,11 +20,20 @@ use std::{
};
use time::UtcOffset;
pub struct Platform {
dispatcher: Arc<dyn super::Dispatcher>,
fonts: Arc<dyn super::FontSystem>,
current_clipboard_item: Mutex<Option<ClipboardItem>>,
cursor: Mutex<CursorStyle>,
struct Dispatcher;
impl super::Dispatcher for Dispatcher {
fn is_main_thread(&self) -> bool {
true
}
fn run_on_main_thread(&self, task: async_task::Runnable) {
task.run();
}
}
pub fn foreground_platform() -> ForegroundPlatform {
ForegroundPlatform::default()
}
#[derive(Default)]
@ -32,24 +41,6 @@ pub struct ForegroundPlatform {
last_prompt_for_new_path_args: RefCell<Option<(PathBuf, oneshot::Sender<Option<PathBuf>>)>>,
}
struct Dispatcher;
pub struct Window {
pub(crate) size: Vector2F,
scale_factor: f32,
current_scene: Option<crate::Scene>,
event_handlers: Vec<Box<dyn FnMut(super::Event) -> bool>>,
pub(crate) resize_handlers: Vec<Box<dyn FnMut()>>,
pub(crate) moved_handlers: Vec<Box<dyn FnMut()>>,
close_handlers: Vec<Box<dyn FnOnce()>>,
fullscreen_handlers: Vec<Box<dyn FnMut(bool)>>,
pub(crate) active_status_change_handlers: Vec<Box<dyn FnMut(bool)>>,
pub(crate) should_close_handler: Option<Box<dyn FnMut() -> bool>>,
pub(crate) title: Option<String>,
pub(crate) edited: bool,
pub(crate) pending_prompts: RefCell<VecDeque<oneshot::Sender<usize>>>,
}
#[cfg(any(test, feature = "test-support"))]
impl ForegroundPlatform {
pub(crate) fn simulate_new_path_selection(
@ -103,6 +94,17 @@ impl super::ForegroundPlatform for ForegroundPlatform {
}
}
pub fn platform() -> Platform {
Platform::new()
}
pub struct Platform {
dispatcher: Arc<dyn super::Dispatcher>,
fonts: Arc<dyn super::FontSystem>,
current_clipboard_item: Mutex<Option<ClipboardItem>>,
cursor: Mutex<CursorStyle>,
}
impl Platform {
fn new() -> Self {
Self {
@ -133,6 +135,10 @@ impl super::Platform for Platform {
fn quit(&self) {}
fn screen_by_id(&self, _id: uuid::Uuid) -> Option<Rc<dyn crate::Screen>> {
None
}
fn screens(&self) -> Vec<Rc<dyn crate::Screen>> {
Default::default()
}
@ -220,6 +226,39 @@ impl super::Platform for Platform {
}
}
#[derive(Debug)]
pub struct Screen;
impl super::Screen for Screen {
fn as_any(&self) -> &dyn Any {
self
}
fn size(&self) -> Vector2F {
Vector2F::new(1920., 1080.)
}
fn display_uuid(&self) -> uuid::Uuid {
uuid::Uuid::new_v4()
}
}
pub struct Window {
pub(crate) size: Vector2F,
scale_factor: f32,
current_scene: Option<crate::Scene>,
event_handlers: Vec<Box<dyn FnMut(super::Event) -> bool>>,
pub(crate) resize_handlers: Vec<Box<dyn FnMut()>>,
pub(crate) moved_handlers: Vec<Box<dyn FnMut()>>,
close_handlers: Vec<Box<dyn FnOnce()>>,
fullscreen_handlers: Vec<Box<dyn FnMut(bool)>>,
pub(crate) active_status_change_handlers: Vec<Box<dyn FnMut(bool)>>,
pub(crate) should_close_handler: Option<Box<dyn FnMut() -> bool>>,
pub(crate) title: Option<String>,
pub(crate) edited: bool,
pub(crate) pending_prompts: RefCell<VecDeque<oneshot::Sender<usize>>>,
}
impl Window {
fn new(size: Vector2F) -> Self {
Self {
@ -244,45 +283,35 @@ impl Window {
}
}
impl super::Dispatcher for Dispatcher {
fn is_main_thread(&self) -> bool {
true
}
fn run_on_main_thread(&self, task: async_task::Runnable) {
task.run();
}
}
impl super::Window for Window {
fn bounds(&self) -> WindowBounds {
WindowBounds::Fixed(RectF::new(Vector2F::zero(), self.size))
}
fn content_size(&self) -> Vector2F {
self.size
}
fn scale_factor(&self) -> f32 {
self.scale_factor
}
fn titlebar_height(&self) -> f32 {
24.
}
fn appearance(&self) -> crate::Appearance {
crate::Appearance::Light
}
fn screen(&self) -> Rc<dyn crate::Screen> {
Rc::new(Screen)
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
fn on_event(&mut self, callback: Box<dyn FnMut(crate::Event) -> bool>) {
self.event_handlers.push(callback);
}
fn on_active_status_change(&mut self, callback: Box<dyn FnMut(bool)>) {
self.active_status_change_handlers.push(callback);
}
fn on_fullscreen(&mut self, callback: Box<dyn FnMut(bool)>) {
self.fullscreen_handlers.push(callback)
}
fn on_resize(&mut self, callback: Box<dyn FnMut()>) {
self.resize_handlers.push(callback);
}
fn on_moved(&mut self, callback: Box<dyn FnMut()>) {
self.moved_handlers.push(callback);
}
fn on_close(&mut self, callback: Box<dyn FnOnce()>) {
self.close_handlers.push(callback);
}
fn set_input_handler(&mut self, _: Box<dyn crate::InputHandler>) {}
fn prompt(&self, _: crate::PromptLevel, _: &str, _: &[&str]) -> oneshot::Receiver<usize> {
@ -301,40 +330,44 @@ impl super::Window for Window {
self.edited = edited;
}
fn on_should_close(&mut self, callback: Box<dyn FnMut() -> bool>) {
self.should_close_handler = Some(callback);
}
fn show_character_palette(&self) {}
fn minimize(&self) {}
fn zoom(&self) {}
fn toggle_full_screen(&self) {}
fn bounds(&self) -> RectF {
RectF::new(Default::default(), self.size)
}
fn content_size(&self) -> Vector2F {
self.size
}
fn scale_factor(&self) -> f32 {
self.scale_factor
}
fn titlebar_height(&self) -> f32 {
24.
}
fn present_scene(&mut self, scene: crate::Scene) {
self.current_scene = Some(scene);
}
fn appearance(&self) -> crate::Appearance {
crate::Appearance::Light
fn toggle_full_screen(&self) {}
fn on_event(&mut self, callback: Box<dyn FnMut(crate::Event) -> bool>) {
self.event_handlers.push(callback);
}
fn on_active_status_change(&mut self, callback: Box<dyn FnMut(bool)>) {
self.active_status_change_handlers.push(callback);
}
fn on_resize(&mut self, callback: Box<dyn FnMut()>) {
self.resize_handlers.push(callback);
}
fn on_fullscreen(&mut self, callback: Box<dyn FnMut(bool)>) {
self.fullscreen_handlers.push(callback)
}
fn on_moved(&mut self, callback: Box<dyn FnMut()>) {
self.moved_handlers.push(callback);
}
fn on_should_close(&mut self, callback: Box<dyn FnMut() -> bool>) {
self.should_close_handler = Some(callback);
}
fn on_close(&mut self, callback: Box<dyn FnOnce()>) {
self.close_handlers.push(callback);
}
fn on_appearance_changed(&mut self, _: Box<dyn FnMut()>) {}
@ -343,11 +376,3 @@ impl super::Window for Window {
true
}
}
pub fn platform() -> Platform {
Platform::new()
}
pub fn foreground_platform() -> ForegroundPlatform {
ForegroundPlatform::default()
}

View File

@ -15,3 +15,4 @@ thread_local = "1.1.4"
lazy_static = "1.4"
parking_lot = "0.11.1"
futures = "0.3"
uuid = { version = "1.1.2", features = ["v4"] }

View File

@ -60,6 +60,14 @@ impl<const C: usize> Bind for &[u8; C] {
}
}
impl<const C: usize> Column for [u8; C] {
fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
let bytes_slice = statement.column_blob(start_index)?;
let array = bytes_slice.try_into()?;
Ok((array, start_index + 1))
}
}
impl StaticColumnCount for Vec<u8> {}
impl Bind for Vec<u8> {
fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
@ -236,8 +244,7 @@ impl<T: Bind + StaticColumnCount> Bind for Option<T> {
if let Some(this) = self {
this.bind(statement, start_index)
} else {
for i in 0..T::column_count() {
dbg!(i);
for _ in 0..T::column_count() {
statement.bind_null(start_index)?;
start_index += 1;
}
@ -272,17 +279,6 @@ impl<T: Bind, const COUNT: usize> Bind for [T; COUNT] {
}
}
impl<T: Column + Default + Copy, const COUNT: usize> Column for [T; COUNT] {
fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
let mut array = [Default::default(); COUNT];
let mut current_index = start_index;
for i in 0..COUNT {
(array[i], current_index) = T::column(statement, current_index)?;
}
Ok((array, current_index))
}
}
impl StaticColumnCount for &Path {}
impl Bind for &Path {
fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
@ -315,6 +311,25 @@ impl Column for PathBuf {
}
}
impl StaticColumnCount for uuid::Uuid {
fn column_count() -> usize {
1
}
}
impl Bind for uuid::Uuid {
fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
self.as_bytes().bind(statement, start_index)
}
}
impl Column for uuid::Uuid {
fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
let (bytes, next_index) = Column::column(statement, start_index)?;
Ok((uuid::Uuid::from_bytes(bytes), next_index))
}
}
impl StaticColumnCount for () {
fn column_count() -> usize {
0

View File

@ -46,6 +46,7 @@ serde = { version = "1.0", features = ["derive", "rc"] }
serde_json = { version = "1.0", features = ["preserve_order"] }
smallvec = { version = "1.6", features = ["union"] }
indoc = "1.0.4"
uuid = { version = "1.1.2", features = ["v4"] }
[dev-dependencies]
call = { path = "../call", features = ["test-support"] }

View File

@ -534,8 +534,8 @@ mod tests {
}],
},
left_sidebar_open: false,
fullscreen: false,
bounds: Default::default(),
display: Default::default(),
};
let fs = FakeFs::new(cx.background());

View File

@ -6,9 +6,10 @@ use std::path::Path;
use anyhow::{anyhow, bail, Context, Result};
use db::{define_connection, query, sqlez::connection::Connection, sqlez_macros::sql};
use gpui::{Axis, geometry::{rect::RectF, vector::Vector2F}};
use gpui::{Axis, WindowBounds};
use util::{unzip_option, ResultExt};
use uuid::Uuid;
use crate::dock::DockPosition;
use crate::WorkspaceId;
@ -29,11 +30,12 @@ define_connection! {
// dock_pane: Option<usize>, // PaneId
// left_sidebar_open: boolean,
// timestamp: String, // UTC YYYY-MM-DD HH:MM:SS
// fullscreen bool, // Boolean
// window_x: f32,
// window_y: f32,
// window_width: f32,
// window_height: f32,
// window_state: String, // WindowBounds Discriminant
// window_x: Option<f32>, // WindowBounds::Fixed RectF x
// window_y: Option<f32>, // WindowBounds::Fixed RectF y
// window_width: Option<f32>, // WindowBounds::Fixed RectF width
// window_height: Option<f32>, // WindowBounds::Fixed RectF height
// display: Option<Uuid>, // Display id
// )
//
// pane_groups(
@ -123,11 +125,12 @@ define_connection! {
) STRICT;
),
sql!(
ALTER TABLE workspaces ADD COLUMN fullscreen INTEGER; // Boolean
ALTER TABLE workspaces ADD COLUMN window_x REAL; // Null means set to whatever
ALTER TABLE workspaces ADD COLUMN window_y REAL; // Null means set to whatever
ALTER TABLE workspaces ADD COLUMN window_width REAL; // Null means set to whatever
ALTER TABLE workspaces ADD COLUMN window_height REAL; // Null means set to whatever
ALTER TABLE workspaces ADD COLUMN window_state TEXT;
ALTER TABLE workspaces ADD COLUMN window_x REAL;
ALTER TABLE workspaces ADD COLUMN window_y REAL;
ALTER TABLE workspaces ADD COLUMN window_width REAL;
ALTER TABLE workspaces ADD COLUMN window_height REAL;
ALTER TABLE workspaces ADD COLUMN display BLOB;
)];
}
@ -143,13 +146,13 @@ impl WorkspaceDb {
// Note that we re-assign the workspace_id here in case it's empty
// and we've grabbed the most recent workspace
let (workspace_id, workspace_location, left_sidebar_open, dock_position, fullscreen, window_region): (
let (workspace_id, workspace_location, left_sidebar_open, dock_position, bounds, display): (
WorkspaceId,
WorkspaceLocation,
bool,
DockPosition,
bool,
Option<(f32, f32, f32, f32)>
Option<WindowBounds>,
Option<Uuid>,
) = self
.select_row_bound(sql! {
SELECT
@ -158,11 +161,12 @@ impl WorkspaceDb {
left_sidebar_open,
dock_visible,
dock_anchor,
fullscreen,
window_state,
window_x,
window_y,
window_width,
window_height
window_height,
display
FROM workspaces
WHERE workspace_location = ?
})
@ -184,11 +188,8 @@ impl WorkspaceDb {
.log_err()?,
dock_position,
left_sidebar_open,
fullscreen,
bounds: dbg!(window_region).map(|(x, y, width, height)| RectF::new(
Vector2F::new(x, y),
Vector2F::new(width, height)
))
bounds,
display,
})
}
@ -222,11 +223,11 @@ impl WorkspaceDb {
VALUES (?1, ?2, ?3, ?4, ?5, CURRENT_TIMESTAMP)
ON CONFLICT DO
UPDATE SET
workspace_location = ?2,
left_sidebar_open = ?3,
dock_visible = ?4,
dock_anchor = ?5,
timestamp = CURRENT_TIMESTAMP
workspace_location = ?2,
left_sidebar_open = ?3,
dock_visible = ?4,
dock_anchor = ?5,
timestamp = CURRENT_TIMESTAMP
))?((
workspace.id,
&workspace.location,
@ -286,7 +287,7 @@ impl WorkspaceDb {
let mut delete_tasks = Vec::new();
for (id, location) in self.recent_workspaces()? {
if location.paths().iter().all(|path| path.exists())
&& location.paths().iter().any(|path| path.is_dir())
&& location.paths().iter().any(|path| path.is_dir())
{
result.push((id, location));
} else {
@ -481,13 +482,14 @@ impl WorkspaceDb {
}
query! {
pub async fn set_bounds(workspace_id: WorkspaceId, fullscreen: bool, bounds: Option<(f32, f32, f32, f32)>) -> Result<()> {
pub async fn set_window_bounds(workspace_id: WorkspaceId, bounds: WindowBounds, display: Uuid) -> Result<()> {
UPDATE workspaces
SET fullscreen = ?2,
SET window_state = ?2,
window_x = ?3,
window_y = ?4,
window_width = ?5,
window_height = ?6
window_height = ?6,
display = ?7
WHERE workspace_id = ?1
}
}
@ -539,15 +541,15 @@ mod tests {
db.write(move |conn| {
conn.exec_bound(sql!(INSERT INTO test_table(text, workspace_id) VALUES (?, ?)))
.unwrap()(("test-text-1", id))
.unwrap()
.unwrap()
})
.await;
let test_text_1 = db
.select_row_bound::<_, String>(sql!(SELECT text FROM test_table WHERE workspace_id = ?))
.unwrap()(1)
.unwrap()
.unwrap();
.unwrap()
.unwrap();
assert_eq!(test_text_1, "test-text-1");
}
@ -580,8 +582,8 @@ mod tests {
center_group: Default::default(),
dock_pane: Default::default(),
left_sidebar_open: true,
fullscreen: false,
bounds: Default::default(),
display: Default::default(),
};
let mut workspace_2 = SerializedWorkspace {
@ -591,8 +593,8 @@ mod tests {
center_group: Default::default(),
dock_pane: Default::default(),
left_sidebar_open: false,
fullscreen: false,
bounds: Default::default(),
display: Default::default(),
};
db.save_workspace(workspace_1.clone()).await;
@ -600,7 +602,7 @@ mod tests {
db.write(|conn| {
conn.exec_bound(sql!(INSERT INTO test_table(text, workspace_id) VALUES (?, ?)))
.unwrap()(("test-text-1", 1))
.unwrap();
.unwrap();
})
.await;
@ -609,7 +611,7 @@ mod tests {
db.write(|conn| {
conn.exec_bound(sql!(INSERT INTO test_table(text, workspace_id) VALUES (?, ?)))
.unwrap()(("test-text-2", 2))
.unwrap();
.unwrap();
})
.await;
@ -627,15 +629,15 @@ mod tests {
let test_text_2 = db
.select_row_bound::<_, String>(sql!(SELECT text FROM test_table WHERE workspace_id = ?))
.unwrap()(2)
.unwrap()
.unwrap();
.unwrap()
.unwrap();
assert_eq!(test_text_2, "test-text-2");
let test_text_1 = db
.select_row_bound::<_, String>(sql!(SELECT text FROM test_table WHERE workspace_id = ?))
.unwrap()(1)
.unwrap()
.unwrap();
.unwrap()
.unwrap();
assert_eq!(test_text_1, "test-text-1");
}
@ -699,8 +701,8 @@ mod tests {
center_group,
dock_pane,
left_sidebar_open: true,
fullscreen: false,
bounds: Default::default(),
display: Default::default(),
};
db.save_workspace(workspace.clone()).await;
@ -729,8 +731,8 @@ mod tests {
center_group: Default::default(),
dock_pane: Default::default(),
left_sidebar_open: true,
fullscreen: false,
bounds: Default::default(),
display: Default::default(),
};
let mut workspace_2 = SerializedWorkspace {
@ -740,8 +742,8 @@ mod tests {
center_group: Default::default(),
dock_pane: Default::default(),
left_sidebar_open: false,
fullscreen: false,
bounds: Default::default(),
display: Default::default(),
};
db.save_workspace(workspace_1.clone()).await;
@ -778,8 +780,8 @@ mod tests {
center_group: Default::default(),
dock_pane: Default::default(),
left_sidebar_open: false,
fullscreen: false,
bounds: Default::default(),
display: Default::default(),
};
db.save_workspace(workspace_3.clone()).await;
@ -815,8 +817,8 @@ mod tests {
center_group: center_group.clone(),
dock_pane,
left_sidebar_open: true,
fullscreen: false,
bounds: Default::default(),
display: Default::default(),
}
}

View File

@ -6,9 +6,7 @@ use std::{
use anyhow::{Context, Result};
use async_recursion::async_recursion;
use gpui::{
geometry::rect::RectF, AsyncAppContext, Axis, ModelHandle, Task, ViewHandle, WindowBounds,
};
use gpui::{AsyncAppContext, Axis, ModelHandle, Task, ViewHandle, WindowBounds};
use db::sqlez::{
bindable::{Bind, Column, StaticColumnCount},
@ -17,6 +15,7 @@ use db::sqlez::{
use project::Project;
use settings::DockAnchor;
use util::ResultExt;
use uuid::Uuid;
use crate::{
dock::DockPosition, ItemDeserializers, Member, Pane, PaneAxis, Workspace, WorkspaceId,
@ -69,20 +68,8 @@ pub struct SerializedWorkspace {
pub center_group: SerializedPaneGroup,
pub dock_pane: SerializedPane,
pub left_sidebar_open: bool,
pub fullscreen: bool,
pub bounds: Option<RectF>,
}
impl SerializedWorkspace {
pub fn bounds(&self) -> WindowBounds {
if self.fullscreen {
WindowBounds::Fullscreen
} else if let Some(bounds) = self.bounds {
WindowBounds::Fixed(bounds)
} else {
WindowBounds::Maximized
}
}
pub bounds: Option<WindowBounds>,
pub display: Option<Uuid>,
}
#[derive(Debug, PartialEq, Eq, Clone)]

View File

@ -37,8 +37,8 @@ use gpui::{
keymap_matcher::KeymapContext,
platform::{CursorStyle, WindowOptions},
AnyModelHandle, AnyViewHandle, AppContext, AsyncAppContext, Entity, ModelContext, ModelHandle,
MouseButton, MutableAppContext, PathPromptOptions, PromptLevel, RenderContext, SizeConstraint,
Task, View, ViewContext, ViewHandle, WeakViewHandle, WindowBounds,
MouseButton, MutableAppContext, PathPromptOptions, Platform, PromptLevel, RenderContext,
SizeConstraint, Task, View, ViewContext, ViewHandle, WeakViewHandle, WindowBounds,
};
use item::{FollowableItem, FollowableItemHandle, Item, ItemHandle, ProjectItem};
use language::LanguageRegistry;
@ -339,7 +339,8 @@ pub struct AppState {
pub client: Arc<client::Client>,
pub user_store: ModelHandle<client::UserStore>,
pub fs: Arc<dyn fs::Fs>,
pub build_window_options: fn(Option<WindowBounds>) -> WindowOptions<'static>,
pub build_window_options:
fn(Option<WindowBounds>, Option<uuid::Uuid>, &dyn Platform) -> WindowOptions<'static>,
pub initialize_workspace: fn(&mut Workspace, &Arc<AppState>, &mut ViewContext<Workspace>),
pub dock_default_item_factory: DockDefaultItemFactory,
}
@ -366,7 +367,7 @@ impl AppState {
languages,
user_store,
initialize_workspace: |_, _, _| {},
build_window_options: |_| Default::default(),
build_window_options: |_, _, _| Default::default(),
dock_default_item_factory: |_, _| unimplemented!(),
})
}
@ -681,11 +682,14 @@ impl Workspace {
DB.next_id().await.unwrap_or(0)
};
let (bounds, display) = dbg!(serialized_workspace
.as_ref()
.and_then(|sw| sw.bounds.zip(sw.display))
.unzip());
// Use the serialized workspace to construct the new window
let (_, workspace) = cx.add_window(
(app_state.build_window_options)(dbg!(serialized_workspace
.as_ref()
.map(|sw| sw.bounds()))),
(app_state.build_window_options)(bounds, display, cx.platform().as_ref()),
|cx| {
let mut workspace = Workspace::new(
serialized_workspace,
@ -695,20 +699,9 @@ impl Workspace {
cx,
);
(app_state.initialize_workspace)(&mut workspace, &app_state, cx);
cx.observe_window_bounds(move |_, bounds, cx| {
let fullscreen = cx.window_is_fullscreen(cx.window_id());
let bounds = if let WindowBounds::Fixed(region) = bounds {
Some((
region.min_x(),
region.min_y(),
region.width(),
region.height(),
))
} else {
None
};
cx.observe_window_bounds(move |_, bounds, display, cx| {
cx.background()
.spawn(DB.set_bounds(workspace_id, fullscreen, bounds))
.spawn(DB.set_window_bounds(workspace_id, dbg!(bounds), dbg!(display)))
.detach_and_log_err(cx);
})
.detach();
@ -2349,8 +2342,8 @@ impl Workspace {
dock_pane,
center_group,
left_sidebar_open: self.left_sidebar.read(cx).is_open(),
fullscreen: false,
bounds: Default::default(),
display: Default::default(),
};
cx.background()

View File

@ -111,6 +111,7 @@ tree-sitter-scheme = { git = "https://github.com/6cdh/tree-sitter-scheme", rev =
tree-sitter-racket = { git = "https://github.com/zed-industries/tree-sitter-racket", rev = "eb010cf2c674c6fd9a6316a84e28ef90190fe51a"}
url = "2.2"
urlencoding = "2.1.2"
uuid = { version = "1.1.2", features = ["v4"] }
[dev-dependencies]
call = { path = "../call", features = ["test-support"] }

View File

@ -20,7 +20,8 @@ use gpui::{
},
impl_actions,
platform::{WindowBounds, WindowOptions},
AssetSource, AsyncAppContext, PromptLevel, TitlebarOptions, ViewContext, WindowKind,
AssetSource, AsyncAppContext, ClipboardItem, Platform, PromptLevel, TitlebarOptions,
ViewContext, WindowKind,
};
use language::Rope;
use lazy_static::lazy_static;
@ -33,6 +34,7 @@ use serde_json::to_string_pretty;
use settings::{keymap_file_json_schema, settings_file_json_schema, Settings};
use std::{borrow::Cow, env, path::Path, str, sync::Arc};
use util::{channel::ReleaseChannel, paths, ResultExt};
use uuid::Uuid;
pub use workspace;
use workspace::{sidebar::SidebarSide, AppState, Workspace};
@ -369,7 +371,11 @@ pub fn initialize_workspace(
});
}
pub fn build_window_options(bounds: Option<WindowBounds>) -> WindowOptions<'static> {
pub fn build_window_options(
bounds: Option<WindowBounds>,
display: Option<Uuid>,
platform: &dyn Platform,
) -> WindowOptions<'static> {
let bounds = bounds
.or_else(|| {
ZED_WINDOW_POSITION
@ -378,8 +384,9 @@ pub fn build_window_options(bounds: Option<WindowBounds>) -> WindowOptions<'stat
})
.unwrap_or(WindowBounds::Maximized);
let screen = display.and_then(|display| platform.screen_by_id(display));
WindowOptions {
bounds,
titlebar: Some(TitlebarOptions {
title: None,
appears_transparent: true,
@ -389,7 +396,8 @@ pub fn build_window_options(bounds: Option<WindowBounds>) -> WindowOptions<'stat
focus: true,
kind: WindowKind::Normal,
is_movable: true,
screen: None,
bounds,
screen,
}
}