Uncomment more gpui2 (#3221)

Release Notes:

- N/A
This commit is contained in:
Kirill Bulatov 2023-11-03 13:45:35 +02:00 committed by GitHub
commit 90d532f0ba
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
22 changed files with 987 additions and 990 deletions

2
Cargo.lock generated
View file

@ -4232,7 +4232,7 @@ dependencies = [
"settings2", "settings2",
"shellexpand", "shellexpand",
"util", "util",
"workspace", "workspace2",
] ]
[[package]] [[package]]

View file

@ -12,7 +12,7 @@ doctest = false
editor = { path = "../editor" } editor = { path = "../editor" }
gpui = { package = "gpui2", path = "../gpui2" } gpui = { package = "gpui2", path = "../gpui2" }
util = { path = "../util" } util = { path = "../util" }
workspace = { path = "../workspace" } workspace2 = { path = "../workspace2" }
settings2 = { path = "../settings2" } settings2 = { path = "../settings2" }
anyhow.workspace = true anyhow.workspace = true

View file

@ -9,7 +9,7 @@ use std::{
path::{Path, PathBuf}, path::{Path, PathBuf},
sync::Arc, sync::Arc,
}; };
use workspace::AppState; use workspace2::AppState;
// use zed::AppState; // use zed::AppState;
// todo!(); // todo!();
@ -59,7 +59,7 @@ pub fn init(_: Arc<AppState>, cx: &mut AppContext) {
// cx.add_global_action(move |_: &NewJournalEntry, cx| new_journal_entry(app_state.clone(), cx)); // cx.add_global_action(move |_: &NewJournalEntry, cx| new_journal_entry(app_state.clone(), cx));
} }
pub fn new_journal_entry(_: Arc<AppState>, cx: &mut AppContext) { pub fn new_journal_entry(app_state: Arc<AppState>, cx: &mut AppContext) {
let settings = JournalSettings::get_global(cx); let settings = JournalSettings::get_global(cx);
let journal_dir = match journal_dir(settings.path.as_ref().unwrap()) { let journal_dir = match journal_dir(settings.path.as_ref().unwrap()) {
Some(journal_dir) => journal_dir, Some(journal_dir) => journal_dir,
@ -77,7 +77,7 @@ pub fn new_journal_entry(_: Arc<AppState>, cx: &mut AppContext) {
let now = now.time(); let now = now.time();
let _entry_heading = heading_entry(now, &settings.hour_format); let _entry_heading = heading_entry(now, &settings.hour_format);
let _create_entry = cx.background_executor().spawn(async move { let create_entry = cx.background_executor().spawn(async move {
std::fs::create_dir_all(month_dir)?; std::fs::create_dir_all(month_dir)?;
OpenOptions::new() OpenOptions::new()
.create(true) .create(true)
@ -86,37 +86,38 @@ pub fn new_journal_entry(_: Arc<AppState>, cx: &mut AppContext) {
Ok::<_, std::io::Error>((journal_dir, entry_path)) Ok::<_, std::io::Error>((journal_dir, entry_path))
}); });
// todo!("workspace") cx.spawn(|mut cx| async move {
// cx.spawn(|cx| async move { let (journal_dir, entry_path) = create_entry.await?;
// let (journal_dir, entry_path) = create_entry.await?; let (workspace, _) = cx
// let (workspace, _) = .update(|cx| workspace2::open_paths(&[journal_dir], &app_state, None, cx))?
// cx.update(|cx| workspace::open_paths(&[journal_dir], &app_state, None, cx))?; .await?;
// let opened = workspace let _opened = workspace
// .update(&mut cx, |workspace, cx| { .update(&mut cx, |workspace, cx| {
// workspace.open_paths(vec![entry_path], true, cx) workspace.open_paths(vec![entry_path], true, cx)
// })? })?
// .await; .await;
// if let Some(Some(Ok(item))) = opened.first() { // todo!("editor")
// if let Some(editor) = item.downcast::<Editor>().map(|editor| editor.downgrade()) { // if let Some(Some(Ok(item))) = opened.first() {
// editor.update(&mut cx, |editor, cx| { // if let Some(editor) = item.downcast::<Editor>().map(|editor| editor.downgrade()) {
// let len = editor.buffer().read(cx).len(cx); // editor.update(&mut cx, |editor, cx| {
// editor.change_selections(Some(Autoscroll::center()), cx, |s| { // let len = editor.buffer().read(cx).len(cx);
// s.select_ranges([len..len]) // editor.change_selections(Some(Autoscroll::center()), cx, |s| {
// }); // s.select_ranges([len..len])
// if len > 0 { // });
// editor.insert("\n\n", cx); // if len > 0 {
// } // editor.insert("\n\n", cx);
// editor.insert(&entry_heading, cx); // }
// editor.insert("\n\n", cx); // editor.insert(&entry_heading, cx);
// })?; // editor.insert("\n\n", cx);
// } // })?;
// } // }
// }
// anyhow::Ok(()) anyhow::Ok(())
// }) })
// .detach_and_log_err(cx); .detach_and_log_err(cx);
} }
fn journal_dir(path: &str) -> Option<PathBuf> { fn journal_dir(path: &str) -> Option<PathBuf> {

View file

@ -234,7 +234,6 @@ impl SyntaxMap {
self.snapshot.interpolate(text); self.snapshot.interpolate(text);
} }
#[allow(dead_code)] // todo!()
#[cfg(test)] #[cfg(test)]
pub fn reparse(&mut self, language: Arc<Language>, text: &BufferSnapshot) { pub fn reparse(&mut self, language: Arc<Language>, text: &BufferSnapshot) {
self.snapshot self.snapshot
@ -786,7 +785,6 @@ impl SyntaxSnapshot {
) )
} }
#[allow(dead_code)] // todo!()
#[cfg(test)] #[cfg(test)]
pub fn layers<'a>(&'a self, buffer: &'a BufferSnapshot) -> Vec<SyntaxLayerInfo> { pub fn layers<'a>(&'a self, buffer: &'a BufferSnapshot) -> Vec<SyntaxLayerInfo> {
self.layers_for_range(0..buffer.len(), buffer).collect() self.layers_for_range(0..buffer.len(), buffer).collect()

View file

@ -289,12 +289,12 @@ async fn test_code_context_retrieval_rust() {
impl E { impl E {
// This is also a preceding comment // This is also a preceding comment
pub fn function_1() -> Option<()> { pub fn function_1() -> Option<()> {
todo!(); unimplemented!();
} }
// This is a preceding comment // This is a preceding comment
fn function_2() -> Result<()> { fn function_2() -> Result<()> {
todo!(); unimplemented!();
} }
} }
@ -344,7 +344,7 @@ async fn test_code_context_retrieval_rust() {
" "
// This is also a preceding comment // This is also a preceding comment
pub fn function_1() -> Option<()> { pub fn function_1() -> Option<()> {
todo!(); unimplemented!();
}" }"
.unindent(), .unindent(),
text.find("pub fn function_1").unwrap(), text.find("pub fn function_1").unwrap(),
@ -353,7 +353,7 @@ async fn test_code_context_retrieval_rust() {
" "
// This is a preceding comment // This is a preceding comment
fn function_2() -> Result<()> { fn function_2() -> Result<()> {
todo!(); unimplemented!();
}" }"
.unindent(), .unindent(),
text.find("fn function_2").unwrap(), text.find("fn function_2").unwrap(),

View file

@ -14,7 +14,7 @@ test-support = [
"client2/test-support", "client2/test-support",
"project2/test-support", "project2/test-support",
"settings2/test-support", "settings2/test-support",
"gpui2/test-support", "gpui/test-support",
"fs2/test-support" "fs2/test-support"
] ]
@ -25,7 +25,7 @@ client2 = { path = "../client2" }
collections = { path = "../collections" } collections = { path = "../collections" }
# context_menu = { path = "../context_menu" } # context_menu = { path = "../context_menu" }
fs2 = { path = "../fs2" } fs2 = { path = "../fs2" }
gpui2 = { path = "../gpui2" } gpui = { package = "gpui2", path = "../gpui2" }
install_cli2 = { path = "../install_cli2" } install_cli2 = { path = "../install_cli2" }
language2 = { path = "../language2" } language2 = { path = "../language2" }
#menu = { path = "../menu" } #menu = { path = "../menu" }
@ -56,7 +56,7 @@ uuid.workspace = true
[dev-dependencies] [dev-dependencies]
call2 = { path = "../call2", features = ["test-support"] } call2 = { path = "../call2", features = ["test-support"] }
client2 = { path = "../client2", features = ["test-support"] } client2 = { path = "../client2", features = ["test-support"] }
gpui2 = { path = "../gpui2", features = ["test-support"] } gpui = { package = "gpui2", path = "../gpui2", features = ["test-support"] }
project2 = { path = "../project2", features = ["test-support"] } project2 = { path = "../project2", features = ["test-support"] }
settings2 = { path = "../settings2", features = ["test-support"] } settings2 = { path = "../settings2", features = ["test-support"] }
fs2 = { path = "../fs2", features = ["test-support"] } fs2 = { path = "../fs2", features = ["test-support"] }

View file

@ -1,5 +1,5 @@
use crate::{status_bar::StatusItemView, Axis, Workspace}; use crate::{status_bar::StatusItemView, Axis, Workspace};
use gpui2::{ use gpui::{
div, Action, AnyView, AppContext, Div, Entity, EntityId, EventEmitter, ParentElement, Render, div, Action, AnyView, AppContext, Div, Entity, EntityId, EventEmitter, ParentElement, Render,
Subscription, View, ViewContext, WeakView, WindowContext, Subscription, View, ViewContext, WeakView, WindowContext,
}; };
@ -226,9 +226,9 @@ impl Dock {
// }) // })
} }
// pub fn active_panel_index(&self) -> usize { pub fn active_panel_index(&self) -> usize {
// self.active_panel_index self.active_panel_index
// } }
pub(crate) fn set_open(&mut self, open: bool, cx: &mut ViewContext<Self>) { pub(crate) fn set_open(&mut self, open: bool, cx: &mut ViewContext<Self>) {
if open != self.is_open { if open != self.is_open {
@ -241,84 +241,87 @@ impl Dock {
} }
} }
// pub fn set_panel_zoomed(&mut self, panel: &AnyView, zoomed: bool, cx: &mut ViewContext<Self>) { // todo!()
// for entry in &mut self.panel_entries { // pub fn set_panel_zoomed(&mut self, panel: &AnyView, zoomed: bool, cx: &mut ViewContext<Self>) {
// if entry.panel.as_any() == panel { // for entry in &mut self.panel_entries {
// if zoomed != entry.panel.is_zoomed(cx) { // if entry.panel.as_any() == panel {
// entry.panel.set_zoomed(zoomed, cx); // if zoomed != entry.panel.is_zoomed(cx) {
// } // entry.panel.set_zoomed(zoomed, cx);
// } else if entry.panel.is_zoomed(cx) {
// entry.panel.set_zoomed(false, cx);
// }
// }
// cx.notify();
// }
// pub fn zoom_out(&mut self, cx: &mut ViewContext<Self>) {
// for entry in &mut self.panel_entries {
// if entry.panel.is_zoomed(cx) {
// entry.panel.set_zoomed(false, cx);
// } // }
// } else if entry.panel.is_zoomed(cx) {
// entry.panel.set_zoomed(false, cx);
// } // }
// } // }
// pub(crate) fn add_panel<T: Panel>(&mut self, panel: View<T>, cx: &mut ViewContext<Self>) { // cx.notify();
// let subscriptions = [ // }
// cx.observe(&panel, |_, _, cx| cx.notify()),
// cx.subscribe(&panel, |this, panel, event, cx| {
// if T::should_activate_on_event(event) {
// if let Some(ix) = this
// .panel_entries
// .iter()
// .position(|entry| entry.panel.id() == panel.id())
// {
// this.set_open(true, cx);
// this.activate_panel(ix, cx);
// cx.focus(&panel);
// }
// } else if T::should_close_on_event(event)
// && this.visible_panel().map_or(false, |p| p.id() == panel.id())
// {
// this.set_open(false, cx);
// }
// }),
// ];
// let dock_view_id = cx.view_id(); pub fn zoom_out(&mut self, cx: &mut ViewContext<Self>) {
// self.panel_entries.push(PanelEntry { for entry in &mut self.panel_entries {
// panel: Arc::new(panel), if entry.panel.is_zoomed(cx) {
// // todo!() entry.panel.set_zoomed(false, cx);
// // context_menu: cx.add_view(|cx| { }
// // let mut menu = ContextMenu::new(dock_view_id, cx); }
// // menu.set_position_mode(OverlayPositionMode::Local); }
// // menu
// // }),
// _subscriptions: subscriptions,
// });
// cx.notify()
// }
// pub fn remove_panel<T: Panel>(&mut self, panel: &View<T>, cx: &mut ViewContext<Self>) { pub(crate) fn add_panel<T: Panel>(&mut self, panel: View<T>, cx: &mut ViewContext<Self>) {
// if let Some(panel_ix) = self let subscriptions = [
// .panel_entries cx.observe(&panel, |_, _, cx| cx.notify()),
// .iter() cx.subscribe(&panel, |this, panel, event, cx| {
// .position(|entry| entry.panel.id() == panel.id()) if T::should_activate_on_event(event) {
// { if let Some(ix) = this
// if panel_ix == self.active_panel_index { .panel_entries
// self.active_panel_index = 0; .iter()
// self.set_open(false, cx); .position(|entry| entry.panel.id() == panel.id())
// } else if panel_ix < self.active_panel_index { {
// self.active_panel_index -= 1; this.set_open(true, cx);
// } this.activate_panel(ix, cx);
// self.panel_entries.remove(panel_ix); // todo!()
// cx.notify(); // cx.focus(&panel);
// } }
// } } else if T::should_close_on_event(event)
&& this.visible_panel().map_or(false, |p| p.id() == panel.id())
{
this.set_open(false, cx);
}
}),
];
// pub fn panels_len(&self) -> usize { // todo!()
// self.panel_entries.len() // let dock_view_id = cx.view_id();
// } self.panel_entries.push(PanelEntry {
panel: Arc::new(panel),
// todo!()
// context_menu: cx.add_view(|cx| {
// let mut menu = ContextMenu::new(dock_view_id, cx);
// menu.set_position_mode(OverlayPositionMode::Local);
// menu
// }),
_subscriptions: subscriptions,
});
cx.notify()
}
pub fn remove_panel<T: Panel>(&mut self, panel: &View<T>, cx: &mut ViewContext<Self>) {
if let Some(panel_ix) = self
.panel_entries
.iter()
.position(|entry| entry.panel.id() == panel.id())
{
if panel_ix == self.active_panel_index {
self.active_panel_index = 0;
self.set_open(false, cx);
} else if panel_ix < self.active_panel_index {
self.active_panel_index -= 1;
}
self.panel_entries.remove(panel_ix);
cx.notify();
}
}
pub fn panels_len(&self) -> usize {
self.panel_entries.len()
}
pub fn activate_panel(&mut self, panel_ix: usize, cx: &mut ViewContext<Self>) { pub fn activate_panel(&mut self, panel_ix: usize, cx: &mut ViewContext<Self>) {
if panel_ix != self.active_panel_index { if panel_ix != self.active_panel_index {
@ -352,38 +355,38 @@ impl Dock {
} }
} }
// pub fn zoomed_panel(&self, cx: &WindowContext) -> Option<Arc<dyn PanelHandle>> { pub fn zoomed_panel(&self, cx: &WindowContext) -> Option<Arc<dyn PanelHandle>> {
// let entry = self.visible_entry()?; let entry = self.visible_entry()?;
// if entry.panel.is_zoomed(cx) { if entry.panel.is_zoomed(cx) {
// Some(entry.panel.clone()) Some(entry.panel.clone())
// } else { } else {
// None None
// } }
// } }
// pub fn panel_size(&self, panel: &dyn PanelHandle, cx: &WindowContext) -> Option<f32> { pub fn panel_size(&self, panel: &dyn PanelHandle, cx: &WindowContext) -> Option<f32> {
// self.panel_entries self.panel_entries
// .iter() .iter()
// .find(|entry| entry.panel.id() == panel.id()) .find(|entry| entry.panel.id() == panel.id())
// .map(|entry| entry.panel.size(cx)) .map(|entry| entry.panel.size(cx))
// } }
// pub fn active_panel_size(&self, cx: &WindowContext) -> Option<f32> { pub fn active_panel_size(&self, cx: &WindowContext) -> Option<f32> {
// if self.is_open { if self.is_open {
// self.panel_entries self.panel_entries
// .get(self.active_panel_index) .get(self.active_panel_index)
// .map(|entry| entry.panel.size(cx)) .map(|entry| entry.panel.size(cx))
// } else { } else {
// None None
// } }
// } }
// pub fn resize_active_panel(&mut self, size: Option<f32>, cx: &mut ViewContext<Self>) { pub fn resize_active_panel(&mut self, size: Option<f32>, cx: &mut ViewContext<Self>) {
// if let Some(entry) = self.panel_entries.get_mut(self.active_panel_index) { if let Some(entry) = self.panel_entries.get_mut(self.active_panel_index) {
// entry.panel.set_size(size, cx); entry.panel.set_size(size, cx);
// cx.notify(); cx.notify();
// } }
// } }
// pub fn render_placeholder(&self, cx: &WindowContext) -> AnyElement<Workspace> { // pub fn render_placeholder(&self, cx: &WindowContext) -> AnyElement<Workspace> {
// todo!() // todo!()
@ -629,7 +632,7 @@ impl StatusItemView for PanelButtons {
#[cfg(any(test, feature = "test-support"))] #[cfg(any(test, feature = "test-support"))]
pub mod test { pub mod test {
use super::*; use super::*;
use gpui2::{div, Div, ViewContext, WindowContext}; use gpui::{div, Div, ViewContext, WindowContext};
#[derive(Debug)] #[derive(Debug)]
pub enum TestPanelEvent { pub enum TestPanelEvent {
@ -678,7 +681,7 @@ pub mod test {
"TestPanel" "TestPanel"
} }
fn position(&self, _: &gpui2::WindowContext) -> super::DockPosition { fn position(&self, _: &gpui::WindowContext) -> super::DockPosition {
self.position self.position
} }

View file

@ -11,7 +11,7 @@ use client2::{
proto::{self, PeerId}, proto::{self, PeerId},
Client, Client,
}; };
use gpui2::{ use gpui::{
AnyElement, AnyView, AppContext, Entity, EntityId, EventEmitter, HighlightStyle, Model, Pixels, AnyElement, AnyView, AppContext, Entity, EntityId, EventEmitter, HighlightStyle, Model, Pixels,
Point, Render, SharedString, Task, View, ViewContext, WeakView, WindowContext, Point, Render, SharedString, Task, View, ViewContext, WeakView, WindowContext,
}; };
@ -212,7 +212,7 @@ pub trait ItemHandle: 'static + Send {
&self, &self,
cx: &mut WindowContext, cx: &mut WindowContext,
handler: Box<dyn Fn(ItemEvent, &mut WindowContext) + Send>, handler: Box<dyn Fn(ItemEvent, &mut WindowContext) + Send>,
) -> gpui2::Subscription; ) -> gpui::Subscription;
fn tab_tooltip_text(&self, cx: &AppContext) -> Option<SharedString>; fn tab_tooltip_text(&self, cx: &AppContext) -> Option<SharedString>;
fn tab_description(&self, detail: usize, cx: &AppContext) -> Option<SharedString>; fn tab_description(&self, detail: usize, cx: &AppContext) -> Option<SharedString>;
fn tab_content(&self, detail: Option<usize>, cx: &AppContext) -> AnyElement<Pane>; fn tab_content(&self, detail: Option<usize>, cx: &AppContext) -> AnyElement<Pane>;
@ -256,7 +256,7 @@ pub trait ItemHandle: 'static + Send {
&mut self, &mut self,
cx: &mut AppContext, cx: &mut AppContext,
callback: Box<dyn FnOnce(&mut AppContext) + Send>, callback: Box<dyn FnOnce(&mut AppContext) + Send>,
) -> gpui2::Subscription; ) -> gpui::Subscription;
fn to_searchable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn SearchableItemHandle>>; fn to_searchable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn SearchableItemHandle>>;
fn breadcrumb_location(&self, cx: &AppContext) -> ToolbarItemLocation; fn breadcrumb_location(&self, cx: &AppContext) -> ToolbarItemLocation;
fn breadcrumbs(&self, theme: &ThemeVariant, cx: &AppContext) -> Option<Vec<BreadcrumbText>>; fn breadcrumbs(&self, theme: &ThemeVariant, cx: &AppContext) -> Option<Vec<BreadcrumbText>>;
@ -286,7 +286,7 @@ impl<T: Item> ItemHandle for View<T> {
&self, &self,
cx: &mut WindowContext, cx: &mut WindowContext,
handler: Box<dyn Fn(ItemEvent, &mut WindowContext) + Send>, handler: Box<dyn Fn(ItemEvent, &mut WindowContext) + Send>,
) -> gpui2::Subscription { ) -> gpui::Subscription {
cx.subscribe(self, move |_, event, cx| { cx.subscribe(self, move |_, event, cx| {
for item_event in T::to_item_events(event) { for item_event in T::to_item_events(event) {
handler(item_event, cx) handler(item_event, cx)
@ -573,7 +573,7 @@ impl<T: Item> ItemHandle for View<T> {
&mut self, &mut self,
cx: &mut AppContext, cx: &mut AppContext,
callback: Box<dyn FnOnce(&mut AppContext) + Send>, callback: Box<dyn FnOnce(&mut AppContext) + Send>,
) -> gpui2::Subscription { ) -> gpui::Subscription {
cx.observe_release(self, move |_, cx| callback(cx)) cx.observe_release(self, move |_, cx| callback(cx))
} }
@ -747,7 +747,7 @@ impl<T: FollowableItem> FollowableItemHandle for View<T> {
// pub mod test { // pub mod test {
// use super::{Item, ItemEvent}; // use super::{Item, ItemEvent};
// use crate::{ItemId, ItemNavHistory, Pane, Workspace, WorkspaceId}; // use crate::{ItemId, ItemNavHistory, Pane, Workspace, WorkspaceId};
// use gpui2::{ // use gpui::{
// elements::Empty, AnyElement, AppContext, Element, Entity, Model, Task, View, // elements::Empty, AnyElement, AppContext, Element, Entity, Model, Task, View,
// ViewContext, View, WeakViewHandle, // ViewContext, View, WeakViewHandle,
// }; // };

View file

@ -1,6 +1,6 @@
use crate::{Toast, Workspace}; use crate::{Toast, Workspace};
use collections::HashMap; use collections::HashMap;
use gpui2::{AnyView, AppContext, Entity, EntityId, EventEmitter, Render, View, ViewContext}; use gpui::{AnyView, AppContext, Entity, EntityId, EventEmitter, Render, View, ViewContext};
use std::{any::TypeId, ops::DerefMut}; use std::{any::TypeId, ops::DerefMut};
pub fn init(cx: &mut AppContext) { pub fn init(cx: &mut AppContext) {
@ -160,7 +160,7 @@ impl Workspace {
pub mod simple_message_notification { pub mod simple_message_notification {
use super::Notification; use super::Notification;
use gpui2::{AnyElement, AppContext, Div, EventEmitter, Render, TextStyle, ViewContext}; use gpui::{AnyElement, AppContext, Div, EventEmitter, Render, TextStyle, ViewContext};
use serde::Deserialize; use serde::Deserialize;
use std::{borrow::Cow, sync::Arc}; use std::{borrow::Cow, sync::Arc};
@ -220,36 +220,36 @@ pub mod simple_message_notification {
} }
} }
pub fn new_element(
message: fn(TextStyle, &AppContext) -> AnyElement<MessageNotification>,
) -> MessageNotification {
Self {
message: NotificationMessage::Element(message),
on_click: None,
click_message: None,
}
}
pub fn with_click_message<S>(mut self, message: S) -> Self
where
S: Into<Cow<'static, str>>,
{
self.click_message = Some(message.into());
self
}
pub fn on_click<F>(mut self, on_click: F) -> Self
where
F: 'static + Send + Sync + Fn(&mut ViewContext<Self>),
{
self.on_click = Some(Arc::new(on_click));
self
}
// todo!() // todo!()
// pub fn new_element( // pub fn dismiss(&mut self, _: &CancelMessageNotification, cx: &mut ViewContext<Self>) {
// message: fn(TextStyle, &AppContext) -> AnyElement<MessageNotification>, // cx.emit(MessageNotificationEvent::Dismiss);
// ) -> MessageNotification { // }
// Self {
// message: NotificationMessage::Element(message),
// on_click: None,
// click_message: None,
// }
// }
// pub fn with_click_message<S>(mut self, message: S) -> Self
// where
// S: Into<Cow<'static, str>>,
// {
// self.click_message = Some(message.into());
// self
// }
// pub fn on_click<F>(mut self, on_click: F) -> Self
// where
// F: 'static + Fn(&mut ViewContext<Self>),
// {
// self.on_click = Some(Arc::new(on_click));
// self
// }
// pub fn dismiss(&mut self, _: &CancelMessageNotification, cx: &mut ViewContext<Self>) {
// cx.emit(MessageNotificationEvent::Dismiss);
// }
} }
impl Render for MessageNotification { impl Render for MessageNotification {
@ -265,7 +265,7 @@ pub mod simple_message_notification {
// "MessageNotification" // "MessageNotification"
// } // }
// fn render(&mut self, cx: &mut gpui2::ViewContext<Self>) -> gpui::AnyElement<Self> { // fn render(&mut self, cx: &mut gpui::ViewContext<Self>) -> gpui::AnyElement<Self> {
// let theme = theme2::current(cx).clone(); // let theme = theme2::current(cx).clone();
// let theme = &theme.simple_message_notification; // let theme = &theme.simple_message_notification;

View file

@ -8,7 +8,7 @@ use crate::{
}; };
use anyhow::Result; use anyhow::Result;
use collections::{HashMap, HashSet, VecDeque}; use collections::{HashMap, HashSet, VecDeque};
use gpui2::{ use gpui::{
AppContext, AsyncWindowContext, Component, Div, EntityId, EventEmitter, Model, PromptLevel, AppContext, AsyncWindowContext, Component, Div, EntityId, EventEmitter, Model, PromptLevel,
Render, Task, View, ViewContext, VisualContext, WeakView, WindowContext, Render, Task, View, ViewContext, VisualContext, WeakView, WindowContext,
}; };
@ -416,17 +416,17 @@ impl Pane {
} }
} }
// pub(crate) fn workspace(&self) -> &WeakView<Workspace> { pub(crate) fn workspace(&self) -> &WeakView<Workspace> {
// &self.workspace &self.workspace
// } }
pub fn has_focus(&self) -> bool { pub fn has_focus(&self) -> bool {
self.has_focus self.has_focus
} }
// pub fn active_item_index(&self) -> usize { pub fn active_item_index(&self) -> usize {
// self.active_item_index self.active_item_index
// } }
// pub fn on_can_drop<F>(&mut self, can_drop: F) // pub fn on_can_drop<F>(&mut self, can_drop: F)
// where // where
@ -1865,14 +1865,14 @@ impl Pane {
// .into_any() // .into_any()
// } // }
// pub fn set_zoomed(&mut self, zoomed: bool, cx: &mut ViewContext<Self>) { pub fn set_zoomed(&mut self, zoomed: bool, cx: &mut ViewContext<Self>) {
// self.zoomed = zoomed; self.zoomed = zoomed;
// cx.notify(); cx.notify();
// } }
// pub fn is_zoomed(&self) -> bool { pub fn is_zoomed(&self) -> bool {
// self.zoomed self.zoomed
// } }
} }
// impl Entity for Pane { // impl Entity for Pane {
@ -2907,6 +2907,6 @@ impl Render for DraggedTab {
type Element = Div<Self>; type Element = Div<Self>;
fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element { fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
div().w_8().h_4().bg(gpui2::red()) div().w_8().h_4().bg(gpui::red())
} }
} }

View file

@ -1,6 +1,6 @@
use super::DraggedItem; use super::DraggedItem;
use crate::{Pane, SplitDirection, Workspace}; use crate::{Pane, SplitDirection, Workspace};
use gpui2::{ use gpui::{
color::Color, color::Color,
elements::{Canvas, MouseEventHandler, ParentElement, Stack}, elements::{Canvas, MouseEventHandler, ParentElement, Stack},
geometry::{rect::RectF, vector::Vector2F}, geometry::{rect::RectF, vector::Vector2F},

View file

@ -6,9 +6,7 @@ use db2::sqlez::{
bindable::{Bind, Column, StaticColumnCount}, bindable::{Bind, Column, StaticColumnCount},
statement::Statement, statement::Statement,
}; };
use gpui2::{ use gpui::{point, size, AnyElement, AnyWeakView, Bounds, Model, Pixels, Point, View, ViewContext};
point, size, AnyElement, AnyWeakView, Bounds, Model, Pixels, Point, View, ViewContext,
};
use parking_lot::Mutex; use parking_lot::Mutex;
use project2::Project; use project2::Project;
use serde::Deserialize; use serde::Deserialize;

View file

@ -6,7 +6,7 @@ use std::path::Path;
use anyhow::{anyhow, bail, Context, Result}; use anyhow::{anyhow, bail, Context, Result};
use db2::{define_connection, query, sqlez::connection::Connection, sqlez_macros::sql}; use db2::{define_connection, query, sqlez::connection::Connection, sqlez_macros::sql};
use gpui2::WindowBounds; use gpui::WindowBounds;
use util::{unzip_option, ResultExt}; use util::{unzip_option, ResultExt};
use uuid::Uuid; use uuid::Uuid;
@ -549,425 +549,425 @@ impl WorkspaceDb {
} }
} }
// todo!() #[cfg(test)]
// #[cfg(test)] mod tests {
// mod tests { use super::*;
// use super::*; use db2::open_test_db;
// use db::open_test_db; use gpui;
// #[gpui::test] #[gpui::test]
// async fn test_next_id_stability() { async fn test_next_id_stability() {
// env_logger::try_init().ok(); env_logger::try_init().ok();
// let db = WorkspaceDb(open_test_db("test_next_id_stability").await); let db = WorkspaceDb(open_test_db("test_next_id_stability").await);
// db.write(|conn| { db.write(|conn| {
// conn.migrate( conn.migrate(
// "test_table", "test_table",
// &[sql!( &[sql!(
// CREATE TABLE test_table( CREATE TABLE test_table(
// text TEXT, text TEXT,
// workspace_id INTEGER, workspace_id INTEGER,
// FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id) FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
// ON DELETE CASCADE ON DELETE CASCADE
// ) STRICT; ) STRICT;
// )], )],
// ) )
// .unwrap(); .unwrap();
// }) })
// .await; .await;
// let id = db.next_id().await.unwrap(); let id = db.next_id().await.unwrap();
// // Assert the empty row got inserted // Assert the empty row got inserted
// assert_eq!( assert_eq!(
// Some(id), Some(id),
// db.select_row_bound::<WorkspaceId, WorkspaceId>(sql!( db.select_row_bound::<WorkspaceId, WorkspaceId>(sql!(
// SELECT workspace_id FROM workspaces WHERE workspace_id = ? SELECT workspace_id FROM workspaces WHERE workspace_id = ?
// )) ))
// .unwrap()(id) .unwrap()(id)
// .unwrap() .unwrap()
// ); );
// db.write(move |conn| { db.write(move |conn| {
// conn.exec_bound(sql!(INSERT INTO test_table(text, workspace_id) VALUES (?, ?))) conn.exec_bound(sql!(INSERT INTO test_table(text, workspace_id) VALUES (?, ?)))
// .unwrap()(("test-text-1", id)) .unwrap()(("test-text-1", id))
// .unwrap() .unwrap()
// }) })
// .await; .await;
// let test_text_1 = db let test_text_1 = db
// .select_row_bound::<_, String>(sql!(SELECT text FROM test_table WHERE workspace_id = ?)) .select_row_bound::<_, String>(sql!(SELECT text FROM test_table WHERE workspace_id = ?))
// .unwrap()(1) .unwrap()(1)
// .unwrap() .unwrap()
// .unwrap(); .unwrap();
// assert_eq!(test_text_1, "test-text-1"); assert_eq!(test_text_1, "test-text-1");
// } }
// #[gpui::test] #[gpui::test]
// async fn test_workspace_id_stability() { async fn test_workspace_id_stability() {
// env_logger::try_init().ok(); env_logger::try_init().ok();
// let db = WorkspaceDb(open_test_db("test_workspace_id_stability").await); let db = WorkspaceDb(open_test_db("test_workspace_id_stability").await);
// db.write(|conn| { db.write(|conn| {
// conn.migrate( conn.migrate(
// "test_table", "test_table",
// &[sql!( &[sql!(
// CREATE TABLE test_table( CREATE TABLE test_table(
// text TEXT, text TEXT,
// workspace_id INTEGER, workspace_id INTEGER,
// FOREIGN KEY(workspace_id) FOREIGN KEY(workspace_id)
// REFERENCES workspaces(workspace_id) REFERENCES workspaces(workspace_id)
// ON DELETE CASCADE ON DELETE CASCADE
// ) STRICT;)], ) STRICT;)],
// ) )
// }) })
// .await .await
// .unwrap(); .unwrap();
// let mut workspace_1 = SerializedWorkspace { let mut workspace_1 = SerializedWorkspace {
// id: 1, id: 1,
// location: (["/tmp", "/tmp2"]).into(), location: (["/tmp", "/tmp2"]).into(),
// center_group: Default::default(), center_group: Default::default(),
// bounds: Default::default(), bounds: Default::default(),
// display: Default::default(), display: Default::default(),
// docks: Default::default(), docks: Default::default(),
// }; };
// let workspace_2 = SerializedWorkspace { let workspace_2 = SerializedWorkspace {
// id: 2, id: 2,
// location: (["/tmp"]).into(), location: (["/tmp"]).into(),
// center_group: Default::default(), center_group: Default::default(),
// bounds: Default::default(), bounds: Default::default(),
// display: Default::default(), display: Default::default(),
// docks: Default::default(), docks: Default::default(),
// }; };
// db.save_workspace(workspace_1.clone()).await; db.save_workspace(workspace_1.clone()).await;
// db.write(|conn| { db.write(|conn| {
// conn.exec_bound(sql!(INSERT INTO test_table(text, workspace_id) VALUES (?, ?))) conn.exec_bound(sql!(INSERT INTO test_table(text, workspace_id) VALUES (?, ?)))
// .unwrap()(("test-text-1", 1)) .unwrap()(("test-text-1", 1))
// .unwrap(); .unwrap();
// }) })
// .await; .await;
// db.save_workspace(workspace_2.clone()).await; db.save_workspace(workspace_2.clone()).await;
// db.write(|conn| { db.write(|conn| {
// conn.exec_bound(sql!(INSERT INTO test_table(text, workspace_id) VALUES (?, ?))) conn.exec_bound(sql!(INSERT INTO test_table(text, workspace_id) VALUES (?, ?)))
// .unwrap()(("test-text-2", 2)) .unwrap()(("test-text-2", 2))
// .unwrap(); .unwrap();
// }) })
// .await; .await;
// workspace_1.location = (["/tmp", "/tmp3"]).into(); workspace_1.location = (["/tmp", "/tmp3"]).into();
// db.save_workspace(workspace_1.clone()).await; db.save_workspace(workspace_1.clone()).await;
// db.save_workspace(workspace_1).await; db.save_workspace(workspace_1).await;
// db.save_workspace(workspace_2).await; db.save_workspace(workspace_2).await;
// let test_text_2 = db let test_text_2 = db
// .select_row_bound::<_, String>(sql!(SELECT text FROM test_table WHERE workspace_id = ?)) .select_row_bound::<_, String>(sql!(SELECT text FROM test_table WHERE workspace_id = ?))
// .unwrap()(2) .unwrap()(2)
// .unwrap() .unwrap()
// .unwrap(); .unwrap();
// assert_eq!(test_text_2, "test-text-2"); assert_eq!(test_text_2, "test-text-2");
// let test_text_1 = db let test_text_1 = db
// .select_row_bound::<_, String>(sql!(SELECT text FROM test_table WHERE workspace_id = ?)) .select_row_bound::<_, String>(sql!(SELECT text FROM test_table WHERE workspace_id = ?))
// .unwrap()(1) .unwrap()(1)
// .unwrap() .unwrap()
// .unwrap(); .unwrap();
// assert_eq!(test_text_1, "test-text-1"); assert_eq!(test_text_1, "test-text-1");
// } }
// fn group(axis: gpui::Axis, children: Vec<SerializedPaneGroup>) -> SerializedPaneGroup { fn group(axis: Axis, children: Vec<SerializedPaneGroup>) -> SerializedPaneGroup {
// SerializedPaneGroup::Group { SerializedPaneGroup::Group {
// axis, axis,
// flexes: None, flexes: None,
// children, children,
// } }
// } }
// #[gpui::test] #[gpui::test]
// async fn test_full_workspace_serialization() { async fn test_full_workspace_serialization() {
// env_logger::try_init().ok(); env_logger::try_init().ok();
// let db = WorkspaceDb(open_test_db("test_full_workspace_serialization").await); let db = WorkspaceDb(open_test_db("test_full_workspace_serialization").await);
// // ----------------- // -----------------
// // | 1,2 | 5,6 | // | 1,2 | 5,6 |
// // | - - - | | // | - - - | |
// // | 3,4 | | // | 3,4 | |
// // ----------------- // -----------------
// let center_group = group( let center_group = group(
// gpui::Axis::Horizontal, Axis::Horizontal,
// vec![ vec![
// group( group(
// gpui::Axis::Vertical, Axis::Vertical,
// vec![ vec![
// SerializedPaneGroup::Pane(SerializedPane::new( SerializedPaneGroup::Pane(SerializedPane::new(
// vec![ vec![
// SerializedItem::new("Terminal", 5, false), SerializedItem::new("Terminal", 5, false),
// SerializedItem::new("Terminal", 6, true), SerializedItem::new("Terminal", 6, true),
// ], ],
// false, false,
// )), )),
// SerializedPaneGroup::Pane(SerializedPane::new( SerializedPaneGroup::Pane(SerializedPane::new(
// vec![ vec![
// SerializedItem::new("Terminal", 7, true), SerializedItem::new("Terminal", 7, true),
// SerializedItem::new("Terminal", 8, false), SerializedItem::new("Terminal", 8, false),
// ], ],
// false, false,
// )), )),
// ], ],
// ), ),
// SerializedPaneGroup::Pane(SerializedPane::new( SerializedPaneGroup::Pane(SerializedPane::new(
// vec![ vec![
// SerializedItem::new("Terminal", 9, false), SerializedItem::new("Terminal", 9, false),
// SerializedItem::new("Terminal", 10, true), SerializedItem::new("Terminal", 10, true),
// ], ],
// false, false,
// )), )),
// ], ],
// ); );
// let workspace = SerializedWorkspace { let workspace = SerializedWorkspace {
// id: 5, id: 5,
// location: (["/tmp", "/tmp2"]).into(), location: (["/tmp", "/tmp2"]).into(),
// center_group, center_group,
// bounds: Default::default(), bounds: Default::default(),
// display: Default::default(), display: Default::default(),
// docks: Default::default(), docks: Default::default(),
// }; };
// db.save_workspace(workspace.clone()).await; db.save_workspace(workspace.clone()).await;
// let round_trip_workspace = db.workspace_for_roots(&["/tmp2", "/tmp"]); let round_trip_workspace = db.workspace_for_roots(&["/tmp2", "/tmp"]);
// assert_eq!(workspace, round_trip_workspace.unwrap()); assert_eq!(workspace, round_trip_workspace.unwrap());
// // Test guaranteed duplicate IDs // Test guaranteed duplicate IDs
// db.save_workspace(workspace.clone()).await; db.save_workspace(workspace.clone()).await;
// db.save_workspace(workspace.clone()).await; db.save_workspace(workspace.clone()).await;
// let round_trip_workspace = db.workspace_for_roots(&["/tmp", "/tmp2"]); let round_trip_workspace = db.workspace_for_roots(&["/tmp", "/tmp2"]);
// assert_eq!(workspace, round_trip_workspace.unwrap()); assert_eq!(workspace, round_trip_workspace.unwrap());
// } }
// #[gpui::test] #[gpui::test]
// async fn test_workspace_assignment() { async fn test_workspace_assignment() {
// env_logger::try_init().ok(); env_logger::try_init().ok();
// let db = WorkspaceDb(open_test_db("test_basic_functionality").await); let db = WorkspaceDb(open_test_db("test_basic_functionality").await);
// let workspace_1 = SerializedWorkspace { let workspace_1 = SerializedWorkspace {
// id: 1, id: 1,
// location: (["/tmp", "/tmp2"]).into(), location: (["/tmp", "/tmp2"]).into(),
// center_group: Default::default(), center_group: Default::default(),
// bounds: Default::default(), bounds: Default::default(),
// display: Default::default(), display: Default::default(),
// docks: Default::default(), docks: Default::default(),
// }; };
// let mut workspace_2 = SerializedWorkspace { let mut workspace_2 = SerializedWorkspace {
// id: 2, id: 2,
// location: (["/tmp"]).into(), location: (["/tmp"]).into(),
// center_group: Default::default(), center_group: Default::default(),
// bounds: Default::default(), bounds: Default::default(),
// display: Default::default(), display: Default::default(),
// docks: Default::default(), docks: Default::default(),
// }; };
// db.save_workspace(workspace_1.clone()).await; db.save_workspace(workspace_1.clone()).await;
// db.save_workspace(workspace_2.clone()).await; db.save_workspace(workspace_2.clone()).await;
// // Test that paths are treated as a set // Test that paths are treated as a set
// assert_eq!( assert_eq!(
// db.workspace_for_roots(&["/tmp", "/tmp2"]).unwrap(), db.workspace_for_roots(&["/tmp", "/tmp2"]).unwrap(),
// workspace_1 workspace_1
// ); );
// assert_eq!( assert_eq!(
// db.workspace_for_roots(&["/tmp2", "/tmp"]).unwrap(), db.workspace_for_roots(&["/tmp2", "/tmp"]).unwrap(),
// workspace_1 workspace_1
// ); );
// // Make sure that other keys work // Make sure that other keys work
// assert_eq!(db.workspace_for_roots(&["/tmp"]).unwrap(), workspace_2); assert_eq!(db.workspace_for_roots(&["/tmp"]).unwrap(), workspace_2);
// assert_eq!(db.workspace_for_roots(&["/tmp3", "/tmp2", "/tmp4"]), None); assert_eq!(db.workspace_for_roots(&["/tmp3", "/tmp2", "/tmp4"]), None);
// // Test 'mutate' case of updating a pre-existing id // Test 'mutate' case of updating a pre-existing id
// workspace_2.location = (["/tmp", "/tmp2"]).into(); workspace_2.location = (["/tmp", "/tmp2"]).into();
// db.save_workspace(workspace_2.clone()).await; db.save_workspace(workspace_2.clone()).await;
// assert_eq!( assert_eq!(
// db.workspace_for_roots(&["/tmp", "/tmp2"]).unwrap(), db.workspace_for_roots(&["/tmp", "/tmp2"]).unwrap(),
// workspace_2 workspace_2
// ); );
// // Test other mechanism for mutating // Test other mechanism for mutating
// let mut workspace_3 = SerializedWorkspace { let mut workspace_3 = SerializedWorkspace {
// id: 3, id: 3,
// location: (&["/tmp", "/tmp2"]).into(), location: (&["/tmp", "/tmp2"]).into(),
// center_group: Default::default(), center_group: Default::default(),
// bounds: Default::default(), bounds: Default::default(),
// display: Default::default(), display: Default::default(),
// docks: Default::default(), docks: Default::default(),
// }; };
// db.save_workspace(workspace_3.clone()).await; db.save_workspace(workspace_3.clone()).await;
// assert_eq!( assert_eq!(
// db.workspace_for_roots(&["/tmp", "/tmp2"]).unwrap(), db.workspace_for_roots(&["/tmp", "/tmp2"]).unwrap(),
// workspace_3 workspace_3
// ); );
// // Make sure that updating paths differently also works // Make sure that updating paths differently also works
// workspace_3.location = (["/tmp3", "/tmp4", "/tmp2"]).into(); workspace_3.location = (["/tmp3", "/tmp4", "/tmp2"]).into();
// db.save_workspace(workspace_3.clone()).await; db.save_workspace(workspace_3.clone()).await;
// assert_eq!(db.workspace_for_roots(&["/tmp2", "tmp"]), None); assert_eq!(db.workspace_for_roots(&["/tmp2", "tmp"]), None);
// assert_eq!( assert_eq!(
// db.workspace_for_roots(&["/tmp2", "/tmp3", "/tmp4"]) db.workspace_for_roots(&["/tmp2", "/tmp3", "/tmp4"])
// .unwrap(), .unwrap(),
// workspace_3 workspace_3
// ); );
// } }
// use crate::persistence::model::SerializedWorkspace; use crate::persistence::model::SerializedWorkspace;
// use crate::persistence::model::{SerializedItem, SerializedPane, SerializedPaneGroup}; use crate::persistence::model::{SerializedItem, SerializedPane, SerializedPaneGroup};
// fn default_workspace<P: AsRef<Path>>( fn default_workspace<P: AsRef<Path>>(
// workspace_id: &[P], workspace_id: &[P],
// center_group: &SerializedPaneGroup, center_group: &SerializedPaneGroup,
// ) -> SerializedWorkspace { ) -> SerializedWorkspace {
// SerializedWorkspace { SerializedWorkspace {
// id: 4, id: 4,
// location: workspace_id.into(), location: workspace_id.into(),
// center_group: center_group.clone(), center_group: center_group.clone(),
// bounds: Default::default(), bounds: Default::default(),
// display: Default::default(), display: Default::default(),
// docks: Default::default(), docks: Default::default(),
// } }
// } }
// #[gpui::test] #[gpui::test]
// async fn test_simple_split() { async fn test_simple_split() {
// env_logger::try_init().ok(); env_logger::try_init().ok();
// let db = WorkspaceDb(open_test_db("simple_split").await); let db = WorkspaceDb(open_test_db("simple_split").await);
// // ----------------- // -----------------
// // | 1,2 | 5,6 | // | 1,2 | 5,6 |
// // | - - - | | // | - - - | |
// // | 3,4 | | // | 3,4 | |
// // ----------------- // -----------------
// let center_pane = group( let center_pane = group(
// gpui::Axis::Horizontal, Axis::Horizontal,
// vec![ vec![
// group( group(
// gpui::Axis::Vertical, Axis::Vertical,
// vec![ vec![
// SerializedPaneGroup::Pane(SerializedPane::new( SerializedPaneGroup::Pane(SerializedPane::new(
// vec![ vec![
// SerializedItem::new("Terminal", 1, false), SerializedItem::new("Terminal", 1, false),
// SerializedItem::new("Terminal", 2, true), SerializedItem::new("Terminal", 2, true),
// ], ],
// false, false,
// )), )),
// SerializedPaneGroup::Pane(SerializedPane::new( SerializedPaneGroup::Pane(SerializedPane::new(
// vec![ vec![
// SerializedItem::new("Terminal", 4, false), SerializedItem::new("Terminal", 4, false),
// SerializedItem::new("Terminal", 3, true), SerializedItem::new("Terminal", 3, true),
// ], ],
// true, true,
// )), )),
// ], ],
// ), ),
// SerializedPaneGroup::Pane(SerializedPane::new( SerializedPaneGroup::Pane(SerializedPane::new(
// vec![ vec![
// SerializedItem::new("Terminal", 5, true), SerializedItem::new("Terminal", 5, true),
// SerializedItem::new("Terminal", 6, false), SerializedItem::new("Terminal", 6, false),
// ], ],
// false, false,
// )), )),
// ], ],
// ); );
// let workspace = default_workspace(&["/tmp"], &center_pane); let workspace = default_workspace(&["/tmp"], &center_pane);
// db.save_workspace(workspace.clone()).await; db.save_workspace(workspace.clone()).await;
// let new_workspace = db.workspace_for_roots(&["/tmp"]).unwrap(); let new_workspace = db.workspace_for_roots(&["/tmp"]).unwrap();
// assert_eq!(workspace.center_group, new_workspace.center_group); assert_eq!(workspace.center_group, new_workspace.center_group);
// } }
// #[gpui::test] #[gpui::test]
// async fn test_cleanup_panes() { async fn test_cleanup_panes() {
// env_logger::try_init().ok(); env_logger::try_init().ok();
// let db = WorkspaceDb(open_test_db("test_cleanup_panes").await); let db = WorkspaceDb(open_test_db("test_cleanup_panes").await);
// let center_pane = group( let center_pane = group(
// gpui::Axis::Horizontal, Axis::Horizontal,
// vec![ vec![
// group( group(
// gpui::Axis::Vertical, Axis::Vertical,
// vec![ vec![
// SerializedPaneGroup::Pane(SerializedPane::new( SerializedPaneGroup::Pane(SerializedPane::new(
// vec![ vec![
// SerializedItem::new("Terminal", 1, false), SerializedItem::new("Terminal", 1, false),
// SerializedItem::new("Terminal", 2, true), SerializedItem::new("Terminal", 2, true),
// ], ],
// false, false,
// )), )),
// SerializedPaneGroup::Pane(SerializedPane::new( SerializedPaneGroup::Pane(SerializedPane::new(
// vec![ vec![
// SerializedItem::new("Terminal", 4, false), SerializedItem::new("Terminal", 4, false),
// SerializedItem::new("Terminal", 3, true), SerializedItem::new("Terminal", 3, true),
// ], ],
// true, true,
// )), )),
// ], ],
// ), ),
// SerializedPaneGroup::Pane(SerializedPane::new( SerializedPaneGroup::Pane(SerializedPane::new(
// vec![ vec![
// SerializedItem::new("Terminal", 5, false), SerializedItem::new("Terminal", 5, false),
// SerializedItem::new("Terminal", 6, true), SerializedItem::new("Terminal", 6, true),
// ], ],
// false, false,
// )), )),
// ], ],
// ); );
// let id = &["/tmp"]; let id = &["/tmp"];
// let mut workspace = default_workspace(id, &center_pane); let mut workspace = default_workspace(id, &center_pane);
// db.save_workspace(workspace.clone()).await; db.save_workspace(workspace.clone()).await;
// workspace.center_group = group( workspace.center_group = group(
// gpui::Axis::Vertical, Axis::Vertical,
// vec![ vec![
// SerializedPaneGroup::Pane(SerializedPane::new( SerializedPaneGroup::Pane(SerializedPane::new(
// vec![ vec![
// SerializedItem::new("Terminal", 1, false), SerializedItem::new("Terminal", 1, false),
// SerializedItem::new("Terminal", 2, true), SerializedItem::new("Terminal", 2, true),
// ], ],
// false, false,
// )), )),
// SerializedPaneGroup::Pane(SerializedPane::new( SerializedPaneGroup::Pane(SerializedPane::new(
// vec![ vec![
// SerializedItem::new("Terminal", 4, true), SerializedItem::new("Terminal", 4, true),
// SerializedItem::new("Terminal", 3, false), SerializedItem::new("Terminal", 3, false),
// ], ],
// true, true,
// )), )),
// ], ],
// ); );
// db.save_workspace(workspace.clone()).await; db.save_workspace(workspace.clone()).await;
// let new_workspace = db.workspace_for_roots(id).unwrap(); let new_workspace = db.workspace_for_roots(id).unwrap();
// assert_eq!(workspace.center_group, new_workspace.center_group); assert_eq!(workspace.center_group, new_workspace.center_group);
// } }
// } }

View file

@ -7,7 +7,7 @@ use db2::sqlez::{
bindable::{Bind, Column, StaticColumnCount}, bindable::{Bind, Column, StaticColumnCount},
statement::Statement, statement::Statement,
}; };
use gpui2::{AsyncWindowContext, Model, Task, View, WeakView, WindowBounds}; use gpui::{AsyncWindowContext, Model, Task, View, WeakView, WindowBounds};
use project2::Project; use project2::Project;
use std::{ use std::{
path::{Path, PathBuf}, path::{Path, PathBuf},
@ -55,7 +55,7 @@ impl Column for WorkspaceLocation {
} }
} }
#[derive(PartialEq, Clone)] #[derive(Debug, PartialEq, Clone)]
pub struct SerializedWorkspace { pub struct SerializedWorkspace {
pub id: WorkspaceId, pub id: WorkspaceId,
pub location: WorkspaceLocation, pub location: WorkspaceLocation,
@ -127,7 +127,7 @@ impl Bind for DockData {
} }
} }
#[derive(PartialEq, Clone)] #[derive(Debug, PartialEq, Clone)]
pub enum SerializedPaneGroup { pub enum SerializedPaneGroup {
Group { Group {
axis: Axis, axis: Axis,
@ -286,15 +286,15 @@ pub struct SerializedItem {
pub active: bool, pub active: bool,
} }
// impl SerializedItem { impl SerializedItem {
// pub fn new(kind: impl AsRef<str>, item_id: ItemId, active: bool) -> Self { pub fn new(kind: impl AsRef<str>, item_id: ItemId, active: bool) -> Self {
// Self { Self {
// kind: Arc::from(kind.as_ref()), kind: Arc::from(kind.as_ref()),
// item_id, item_id,
// active, active,
// } }
// } }
// } }
#[cfg(test)] #[cfg(test)]
impl Default for SerializedItem { impl Default for SerializedItem {

View file

@ -1,6 +1,6 @@
use std::{any::Any, sync::Arc}; use std::{any::Any, sync::Arc};
use gpui2::{AnyView, AppContext, Subscription, Task, View, ViewContext, WindowContext}; use gpui::{AnyView, AppContext, Subscription, Task, View, ViewContext, WindowContext};
use project2::search::SearchQuery; use project2::search::SearchQuery;
use crate::{ use crate::{

View file

@ -1,7 +1,7 @@
use std::any::TypeId; use std::any::TypeId;
use crate::{ItemHandle, Pane}; use crate::{ItemHandle, Pane};
use gpui2::{ use gpui::{
div, AnyView, Component, Div, ParentElement, Render, Styled, Subscription, View, ViewContext, div, AnyView, Component, Div, ParentElement, Render, Styled, Subscription, View, ViewContext,
WindowContext, WindowContext,
}; };

View file

@ -1,5 +1,5 @@
use crate::ItemHandle; use crate::ItemHandle;
use gpui2::{ use gpui::{
AnyView, AppContext, Entity, EntityId, EventEmitter, Render, View, ViewContext, WindowContext, AnyView, AppContext, Entity, EntityId, EventEmitter, Render, View, ViewContext, WindowContext,
}; };

View file

@ -8,6 +8,7 @@ pub mod pane;
pub mod pane_group; pub mod pane_group;
mod persistence; mod persistence;
pub mod searchable; pub mod searchable;
// todo!()
// pub mod shared_screen; // pub mod shared_screen;
mod status_bar; mod status_bar;
mod toolbar; mod toolbar;
@ -23,14 +24,14 @@ use client2::{
proto::{self, PeerId}, proto::{self, PeerId},
Client, TypedEnvelope, UserStore, Client, TypedEnvelope, UserStore,
}; };
use collections::{HashMap, HashSet}; use collections::{hash_map, HashMap, HashSet};
use dock::{Dock, DockPosition, PanelButtons}; use dock::{Dock, DockPosition, PanelButtons};
use futures::{ use futures::{
channel::{mpsc, oneshot}, channel::{mpsc, oneshot},
future::try_join_all, future::try_join_all,
Future, FutureExt, StreamExt, Future, FutureExt, StreamExt,
}; };
use gpui2::{ use gpui::{
div, point, size, AnyModel, AnyView, AnyWeakView, AppContext, AsyncAppContext, div, point, size, AnyModel, AnyView, AnyWeakView, AppContext, AsyncAppContext,
AsyncWindowContext, Bounds, Component, Div, EntityId, EventEmitter, GlobalPixels, Model, AsyncWindowContext, Bounds, Component, Div, EntityId, EventEmitter, GlobalPixels, Model,
ModelContext, ParentElement, Point, Render, Size, StatefulInteractive, Styled, Subscription, ModelContext, ParentElement, Point, Render, Size, StatefulInteractive, Styled, Subscription,
@ -38,6 +39,7 @@ use gpui2::{
WindowOptions, WindowOptions,
}; };
use item::{FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, ProjectItem}; use item::{FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, ProjectItem};
use itertools::Itertools;
use language2::LanguageRegistry; use language2::LanguageRegistry;
use lazy_static::lazy_static; use lazy_static::lazy_static;
use node_runtime::NodeRuntime; use node_runtime::NodeRuntime;
@ -174,42 +176,42 @@ pub struct Toast {
on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut WindowContext)>)>, on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut WindowContext)>)>,
} }
// impl Toast { impl Toast {
// pub fn new<I: Into<Cow<'static, str>>>(id: usize, msg: I) -> Self { pub fn new<I: Into<Cow<'static, str>>>(id: usize, msg: I) -> Self {
// Toast { Toast {
// id, id,
// msg: msg.into(), msg: msg.into(),
// on_click: None, on_click: None,
// } }
// } }
// pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
// where where
// M: Into<Cow<'static, str>>, M: Into<Cow<'static, str>>,
// F: Fn(&mut WindowContext) + 'static, F: Fn(&mut WindowContext) + 'static,
// { {
// self.on_click = Some((message.into(), Arc::new(on_click))); self.on_click = Some((message.into(), Arc::new(on_click)));
// self self
// } }
// } }
// impl PartialEq for Toast { impl PartialEq for Toast {
// fn eq(&self, other: &Self) -> bool { fn eq(&self, other: &Self) -> bool {
// self.id == other.id self.id == other.id
// && self.msg == other.msg && self.msg == other.msg
// && self.on_click.is_some() == other.on_click.is_some() && self.on_click.is_some() == other.on_click.is_some()
// } }
// } }
// impl Clone for Toast { impl Clone for Toast {
// fn clone(&self) -> Self { fn clone(&self) -> Self {
// Toast { Toast {
// id: self.id, id: self.id,
// msg: self.msg.to_owned(), msg: self.msg.to_owned(),
// on_click: self.on_click.clone(), on_click: self.on_click.clone(),
// } }
// } }
// } }
// #[derive(Clone, Deserialize, PartialEq)] // #[derive(Clone, Deserialize, PartialEq)]
// pub struct OpenTerminal { // pub struct OpenTerminal {
@ -460,7 +462,7 @@ struct Follower {
impl AppState { impl AppState {
#[cfg(any(test, feature = "test-support"))] #[cfg(any(test, feature = "test-support"))]
pub fn test(cx: &mut AppContext) -> Arc<Self> { pub fn test(cx: &mut AppContext) -> Arc<Self> {
use gpui2::Context; use gpui::Context;
use node_runtime::FakeNodeRuntime; use node_runtime::FakeNodeRuntime;
use settings2::SettingsStore; use settings2::SettingsStore;
@ -476,8 +478,7 @@ impl AppState {
let user_store = cx.build_model(|cx| UserStore::new(client.clone(), http_client, cx)); let user_store = cx.build_model(|cx| UserStore::new(client.clone(), http_client, cx));
let workspace_store = cx.build_model(|cx| WorkspaceStore::new(client.clone(), cx)); let workspace_store = cx.build_model(|cx| WorkspaceStore::new(client.clone(), cx));
// todo!() theme2::init(cx);
// theme::init((), cx);
client2::init(&client, cx); client2::init(&client, cx);
crate::init_settings(cx); crate::init_settings(cx);
@ -549,7 +550,7 @@ pub struct Workspace {
weak_self: WeakView<Self>, weak_self: WeakView<Self>,
// modal: Option<ActiveModal>, // modal: Option<ActiveModal>,
zoomed: Option<AnyWeakView>, zoomed: Option<AnyWeakView>,
// zoomed_position: Option<DockPosition>, zoomed_position: Option<DockPosition>,
center: PaneGroup, center: PaneGroup,
left_dock: View<Dock>, left_dock: View<Dock>,
bottom_dock: View<Dock>, bottom_dock: View<Dock>,
@ -626,7 +627,7 @@ impl Workspace {
} }
project2::Event::Closed => { project2::Event::Closed => {
// cx.remove_window(); cx.remove_window();
} }
project2::Event::DeletedEntry(entry_id) => { project2::Event::DeletedEntry(entry_id) => {
@ -768,7 +769,7 @@ impl Workspace {
weak_self: weak_handle.clone(), weak_self: weak_handle.clone(),
// modal: None, // modal: None,
zoomed: None, zoomed: None,
// zoomed_position: None, zoomed_position: None,
center: PaneGroup::new(center_pane.clone()), center: PaneGroup::new(center_pane.clone()),
panes: vec![center_pane.clone()], panes: vec![center_pane.clone()],
panes_by_item: Default::default(), panes_by_item: Default::default(),
@ -1059,183 +1060,185 @@ impl Workspace {
&self.project &self.project
} }
// pub fn recent_navigation_history( pub fn recent_navigation_history(
// &self, &self,
// limit: Option<usize>, limit: Option<usize>,
// cx: &AppContext, cx: &AppContext,
// ) -> Vec<(ProjectPath, Option<PathBuf>)> { ) -> Vec<(ProjectPath, Option<PathBuf>)> {
// let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default(); let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
// let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default(); let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
// for pane in &self.panes { for pane in &self.panes {
// let pane = pane.read(cx); let pane = pane.read(cx);
// pane.nav_history() pane.nav_history()
// .for_each_entry(cx, |entry, (project_path, fs_path)| { .for_each_entry(cx, |entry, (project_path, fs_path)| {
// if let Some(fs_path) = &fs_path { if let Some(fs_path) = &fs_path {
// abs_paths_opened abs_paths_opened
// .entry(fs_path.clone()) .entry(fs_path.clone())
// .or_default() .or_default()
// .insert(project_path.clone()); .insert(project_path.clone());
// } }
// let timestamp = entry.timestamp; let timestamp = entry.timestamp;
// match history.entry(project_path) { match history.entry(project_path) {
// hash_map::Entry::Occupied(mut entry) => { hash_map::Entry::Occupied(mut entry) => {
// let (_, old_timestamp) = entry.get(); let (_, old_timestamp) = entry.get();
// if &timestamp > old_timestamp { if &timestamp > old_timestamp {
// entry.insert((fs_path, timestamp)); entry.insert((fs_path, timestamp));
// } }
// } }
// hash_map::Entry::Vacant(entry) => { hash_map::Entry::Vacant(entry) => {
// entry.insert((fs_path, timestamp)); entry.insert((fs_path, timestamp));
// } }
// } }
// }); });
// } }
// history history
// .into_iter() .into_iter()
// .sorted_by_key(|(_, (_, timestamp))| *timestamp) .sorted_by_key(|(_, (_, timestamp))| *timestamp)
// .map(|(project_path, (fs_path, _))| (project_path, fs_path)) .map(|(project_path, (fs_path, _))| (project_path, fs_path))
// .rev() .rev()
// .filter(|(history_path, abs_path)| { .filter(|(history_path, abs_path)| {
// let latest_project_path_opened = abs_path let latest_project_path_opened = abs_path
// .as_ref() .as_ref()
// .and_then(|abs_path| abs_paths_opened.get(abs_path)) .and_then(|abs_path| abs_paths_opened.get(abs_path))
// .and_then(|project_paths| { .and_then(|project_paths| {
// project_paths project_paths
// .iter() .iter()
// .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id)) .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
// }); });
// match latest_project_path_opened { match latest_project_path_opened {
// Some(latest_project_path_opened) => latest_project_path_opened == history_path, Some(latest_project_path_opened) => latest_project_path_opened == history_path,
// None => true, None => true,
// } }
// }) })
// .take(limit.unwrap_or(usize::MAX)) .take(limit.unwrap_or(usize::MAX))
// .collect() .collect()
// } }
// fn navigate_history( fn navigate_history(
// &mut self, &mut self,
// pane: WeakView<Pane>, pane: WeakView<Pane>,
// mode: NavigationMode, mode: NavigationMode,
// cx: &mut ViewContext<Workspace>, cx: &mut ViewContext<Workspace>,
// ) -> Task<Result<()>> { ) -> Task<Result<()>> {
// let to_load = if let Some(pane) = pane.upgrade(cx) { let to_load = if let Some(pane) = pane.upgrade() {
// cx.focus(&pane); // todo!("focus")
// cx.focus(&pane);
// pane.update(cx, |pane, cx| { pane.update(cx, |pane, cx| {
// loop { loop {
// // Retrieve the weak item handle from the history. // Retrieve the weak item handle from the history.
// let entry = pane.nav_history_mut().pop(mode, cx)?; let entry = pane.nav_history_mut().pop(mode, cx)?;
// // If the item is still present in this pane, then activate it. // If the item is still present in this pane, then activate it.
// if let Some(index) = entry if let Some(index) = entry
// .item .item
// .upgrade(cx) .upgrade()
// .and_then(|v| pane.index_for_item(v.as_ref())) .and_then(|v| pane.index_for_item(v.as_ref()))
// { {
// let prev_active_item_index = pane.active_item_index(); let prev_active_item_index = pane.active_item_index();
// pane.nav_history_mut().set_mode(mode); pane.nav_history_mut().set_mode(mode);
// pane.activate_item(index, true, true, cx); pane.activate_item(index, true, true, cx);
// pane.nav_history_mut().set_mode(NavigationMode::Normal); pane.nav_history_mut().set_mode(NavigationMode::Normal);
// let mut navigated = prev_active_item_index != pane.active_item_index(); let mut navigated = prev_active_item_index != pane.active_item_index();
// if let Some(data) = entry.data { if let Some(data) = entry.data {
// navigated |= pane.active_item()?.navigate(data, cx); navigated |= pane.active_item()?.navigate(data, cx);
// } }
// if navigated { if navigated {
// break None; break None;
// } }
// } }
// // If the item is no longer present in this pane, then retrieve its // If the item is no longer present in this pane, then retrieve its
// // project path in order to reopen it. // project path in order to reopen it.
// else { else {
// break pane break pane
// .nav_history() .nav_history()
// .path_for_item(entry.item.id()) .path_for_item(entry.item.id())
// .map(|(project_path, _)| (project_path, entry)); .map(|(project_path, _)| (project_path, entry));
// } }
// } }
// }) })
// } else { } else {
// None None
// }; };
// if let Some((project_path, entry)) = to_load { if let Some((project_path, entry)) = to_load {
// // If the item was no longer present, then load it again from its previous path. // If the item was no longer present, then load it again from its previous path.
// let task = self.load_path(project_path, cx); let task = self.load_path(project_path, cx);
// cx.spawn(|workspace, mut cx| async move { cx.spawn(|workspace, mut cx| async move {
// let task = task.await; let task = task.await;
// let mut navigated = false; let mut navigated = false;
// if let Some((project_entry_id, build_item)) = task.log_err() { if let Some((project_entry_id, build_item)) = task.log_err() {
// let prev_active_item_id = pane.update(&mut cx, |pane, _| { let prev_active_item_id = pane.update(&mut cx, |pane, _| {
// pane.nav_history_mut().set_mode(mode); pane.nav_history_mut().set_mode(mode);
// pane.active_item().map(|p| p.id()) pane.active_item().map(|p| p.id())
// })?; })?;
// pane.update(&mut cx, |pane, cx| { pane.update(&mut cx, |pane, cx| {
// let item = pane.open_item(project_entry_id, true, cx, build_item); let item = pane.open_item(project_entry_id, true, cx, build_item);
// navigated |= Some(item.id()) != prev_active_item_id; navigated |= Some(item.id()) != prev_active_item_id;
// pane.nav_history_mut().set_mode(NavigationMode::Normal); pane.nav_history_mut().set_mode(NavigationMode::Normal);
// if let Some(data) = entry.data { if let Some(data) = entry.data {
// navigated |= item.navigate(data, cx); navigated |= item.navigate(data, cx);
// } }
// })?; })?;
// } }
// if !navigated { if !navigated {
// workspace workspace
// .update(&mut cx, |workspace, cx| { .update(&mut cx, |workspace, cx| {
// Self::navigate_history(workspace, pane, mode, cx) Self::navigate_history(workspace, pane, mode, cx)
// })? })?
// .await?; .await?;
// } }
// Ok(()) Ok(())
// }) })
// } else { } else {
// Task::ready(Ok(())) Task::ready(Ok(()))
// } }
// } }
// pub fn go_back( pub fn go_back(
// &mut self, &mut self,
// pane: WeakView<Pane>, pane: WeakView<Pane>,
// cx: &mut ViewContext<Workspace>, cx: &mut ViewContext<Workspace>,
// ) -> Task<Result<()>> { ) -> Task<Result<()>> {
// self.navigate_history(pane, NavigationMode::GoingBack, cx) self.navigate_history(pane, NavigationMode::GoingBack, cx)
// } }
// pub fn go_forward( pub fn go_forward(
// &mut self, &mut self,
// pane: WeakView<Pane>, pane: WeakView<Pane>,
// cx: &mut ViewContext<Workspace>, cx: &mut ViewContext<Workspace>,
// ) -> Task<Result<()>> { ) -> Task<Result<()>> {
// self.navigate_history(pane, NavigationMode::GoingForward, cx) self.navigate_history(pane, NavigationMode::GoingForward, cx)
// } }
// pub fn reopen_closed_item(&mut self, cx: &mut ViewContext<Workspace>) -> Task<Result<()>> { pub fn reopen_closed_item(&mut self, cx: &mut ViewContext<Workspace>) -> Task<Result<()>> {
// self.navigate_history( self.navigate_history(
// self.active_pane().downgrade(), self.active_pane().downgrade(),
// NavigationMode::ReopeningClosedItem, NavigationMode::ReopeningClosedItem,
// cx, cx,
// ) )
// } }
// pub fn client(&self) -> &Client { pub fn client(&self) -> &Client {
// &self.app_state.client &self.app_state.client
// } }
// pub fn set_titlebar_item(&mut self, item: AnyViewHandle, cx: &mut ViewContext<Self>) { // todo!()
// self.titlebar_item = Some(item); // pub fn set_titlebar_item(&mut self, item: AnyViewHandle, cx: &mut ViewContext<Self>) {
// cx.notify(); // self.titlebar_item = Some(item);
// } // cx.notify();
// }
// pub fn titlebar_item(&self) -> Option<AnyViewHandle> { // pub fn titlebar_item(&self) -> Option<AnyViewHandle> {
// self.titlebar_item.clone() // self.titlebar_item.clone()
// } // }
// /// Call the given callback with a workspace whose project is local. // /// Call the given callback with a workspace whose project is local.
// /// // ///
@ -1261,32 +1264,29 @@ impl Workspace {
// } // }
// } // }
// pub fn worktrees<'a>( pub fn worktrees<'a>(&self, cx: &'a AppContext) -> impl 'a + Iterator<Item = Model<Worktree>> {
// &self, self.project.read(cx).worktrees()
// cx: &'a AppContext, }
// ) -> impl 'a + Iterator<Item = ModelHandle<Worktree>> {
// self.project.read(cx).worktrees(cx)
// }
// pub fn visible_worktrees<'a>( pub fn visible_worktrees<'a>(
// &self, &self,
// cx: &'a AppContext, cx: &'a AppContext,
// ) -> impl 'a + Iterator<Item = ModelHandle<Worktree>> { ) -> impl 'a + Iterator<Item = Model<Worktree>> {
// self.project.read(cx).visible_worktrees(cx) self.project.read(cx).visible_worktrees(cx)
// } }
// pub fn worktree_scans_complete(&self, cx: &AppContext) -> impl Future<Output = ()> + 'static { pub fn worktree_scans_complete(&self, cx: &AppContext) -> impl Future<Output = ()> + 'static {
// let futures = self let futures = self
// .worktrees(cx) .worktrees(cx)
// .filter_map(|worktree| worktree.read(cx).as_local()) .filter_map(|worktree| worktree.read(cx).as_local())
// .map(|worktree| worktree.scan_complete()) .map(|worktree| worktree.scan_complete())
// .collect::<Vec<_>>(); .collect::<Vec<_>>();
// async move { async move {
// for future in futures { for future in futures {
// future.await; future.await;
// } }
// } }
// } }
// pub fn close_global(_: &CloseWindow, cx: &mut AppContext) { // pub fn close_global(_: &CloseWindow, cx: &mut AppContext) {
// cx.spawn(|mut cx| async move { // cx.spawn(|mut cx| async move {
@ -1699,31 +1699,31 @@ impl Workspace {
self.active_pane().read(cx).active_item() self.active_pane().read(cx).active_item()
} }
// fn active_project_path(&self, cx: &ViewContext<Self>) -> Option<ProjectPath> { fn active_project_path(&self, cx: &ViewContext<Self>) -> Option<ProjectPath> {
// self.active_item(cx).and_then(|item| item.project_path(cx)) self.active_item(cx).and_then(|item| item.project_path(cx))
// } }
// pub fn save_active_item( pub fn save_active_item(
// &mut self, &mut self,
// save_intent: SaveIntent, save_intent: SaveIntent,
// cx: &mut ViewContext<Self>, cx: &mut ViewContext<Self>,
// ) -> Task<Result<()>> { ) -> Task<Result<()>> {
// let project = self.project.clone(); let project = self.project.clone();
// let pane = self.active_pane(); let pane = self.active_pane();
// let item_ix = pane.read(cx).active_item_index(); let item_ix = pane.read(cx).active_item_index();
// let item = pane.read(cx).active_item(); let item = pane.read(cx).active_item();
// let pane = pane.downgrade(); let pane = pane.downgrade();
// cx.spawn(|_, mut cx| async move { cx.spawn(|_, mut cx| async move {
// if let Some(item) = item { if let Some(item) = item {
// Pane::save_item(project, &pane, item_ix, item.as_ref(), save_intent, &mut cx) Pane::save_item(project, &pane, item_ix, item.as_ref(), save_intent, &mut cx)
// .await .await
// .map(|_| ()) .map(|_| ())
// } else { } else {
// Ok(()) Ok(())
// } }
// }) })
// } }
// pub fn close_inactive_items_and_panes( // pub fn close_inactive_items_and_panes(
// &mut self, // &mut self,
@ -1825,19 +1825,20 @@ impl Workspace {
// self.serialize_workspace(cx); // self.serialize_workspace(cx);
// } // }
// pub fn close_all_docks(&mut self, cx: &mut ViewContext<Self>) { pub fn close_all_docks(&mut self, cx: &mut ViewContext<Self>) {
// let docks = [&self.left_dock, &self.bottom_dock, &self.right_dock]; let docks = [&self.left_dock, &self.bottom_dock, &self.right_dock];
// for dock in docks { for dock in docks {
// dock.update(cx, |dock, cx| { dock.update(cx, |dock, cx| {
// dock.set_open(false, cx); dock.set_open(false, cx);
// }); });
// } }
// cx.focus_self(); // todo!("focus")
// cx.notify(); // cx.focus_self();
// self.serialize_workspace(cx); cx.notify();
// } self.serialize_workspace(cx);
}
// /// Transfer focus to the panel of the given type. // /// Transfer focus to the panel of the given type.
// pub fn focus_panel<T: Panel>(&mut self, cx: &mut ViewContext<Self>) -> Option<View<T>> { // pub fn focus_panel<T: Panel>(&mut self, cx: &mut ViewContext<Self>) -> Option<View<T>> {
@ -1904,19 +1905,19 @@ impl Workspace {
// None // None
// } // }
// fn zoom_out(&mut self, cx: &mut ViewContext<Self>) { fn zoom_out(&mut self, cx: &mut ViewContext<Self>) {
// for pane in &self.panes { for pane in &self.panes {
// pane.update(cx, |pane, cx| pane.set_zoomed(false, cx)); pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
// } }
// self.left_dock.update(cx, |dock, cx| dock.zoom_out(cx)); self.left_dock.update(cx, |dock, cx| dock.zoom_out(cx));
// self.bottom_dock.update(cx, |dock, cx| dock.zoom_out(cx)); self.bottom_dock.update(cx, |dock, cx| dock.zoom_out(cx));
// self.right_dock.update(cx, |dock, cx| dock.zoom_out(cx)); self.right_dock.update(cx, |dock, cx| dock.zoom_out(cx));
// self.zoomed = None; self.zoomed = None;
// self.zoomed_position = None; self.zoomed_position = None;
// cx.notify(); cx.notify();
// } }
// #[cfg(any(test, feature = "test-support"))] // #[cfg(any(test, feature = "test-support"))]
// pub fn zoomed_view(&self, cx: &AppContext) -> Option<AnyViewHandle> { // pub fn zoomed_view(&self, cx: &AppContext) -> Option<AnyViewHandle> {
@ -1962,22 +1963,21 @@ impl Workspace {
// cx.notify(); // cx.notify();
// } // }
fn add_pane(&mut self, _cx: &mut ViewContext<Self>) -> View<Pane> { fn add_pane(&mut self, cx: &mut ViewContext<Self>) -> View<Pane> {
todo!() let pane = cx.build_view(|cx| {
// let pane = cx.build_view(|cx| { Pane::new(
// Pane::new( self.weak_handle(),
// self.weak_handle(), self.project.clone(),
// self.project.clone(), self.pane_history_timestamp.clone(),
// self.pane_history_timestamp.clone(), cx,
// cx, )
// ) });
// }); cx.subscribe(&pane, Self::handle_pane_event).detach();
// cx.subscribe(&pane, Self::handle_pane_event).detach(); self.panes.push(pane.clone());
// self.panes.push(pane.clone());
// todo!() // todo!()
// cx.focus(&pane); // cx.focus(&pane);
// cx.emit(Event::PaneAdded(pane.clone())); cx.emit(Event::PaneAdded(pane.clone()));
// pane pane
} }
// pub fn add_item_to_center( // pub fn add_item_to_center(
@ -3122,6 +3122,7 @@ impl Workspace {
None None
} }
// todo!()
// fn shared_screen_for_peer( // fn shared_screen_for_peer(
// &self, // &self,
// peer_id: PeerId, // peer_id: PeerId,
@ -3498,6 +3499,7 @@ impl Workspace {
}) })
} }
// todo!()
// #[cfg(any(test, feature = "test-support"))] // #[cfg(any(test, feature = "test-support"))]
// pub fn test_new(project: ModelHandle<Project>, cx: &mut ViewContext<Self>) -> Self { // pub fn test_new(project: ModelHandle<Project>, cx: &mut ViewContext<Self>) -> Self {
// use node_runtime::FakeNodeRuntime; // use node_runtime::FakeNodeRuntime;
@ -3658,6 +3660,7 @@ fn open_items(
}) })
} }
// todo!()
// fn notify_of_new_dock(workspace: &WeakView<Workspace>, cx: &mut AsyncAppContext) { // fn notify_of_new_dock(workspace: &WeakView<Workspace>, cx: &mut AsyncAppContext) {
// const NEW_PANEL_BLOG_POST: &str = "https://zed.dev/blog/new-panel-system"; // const NEW_PANEL_BLOG_POST: &str = "https://zed.dev/blog/new-panel-system";
// const NEW_DOCK_HINT_KEY: &str = "show_new_dock_key"; // const NEW_DOCK_HINT_KEY: &str = "show_new_dock_key";
@ -3738,23 +3741,22 @@ fn open_items(
// }) // })
// .ok(); // .ok();
fn notify_if_database_failed(_workspace: WindowHandle<Workspace>, _cx: &mut AsyncAppContext) { fn notify_if_database_failed(workspace: WindowHandle<Workspace>, cx: &mut AsyncAppContext) {
const REPORT_ISSUE_URL: &str ="https://github.com/zed-industries/community/issues/new?assignees=&labels=defect%2Ctriage&template=2_bug_report.yml"; const REPORT_ISSUE_URL: &str ="https://github.com/zed-industries/community/issues/new?assignees=&labels=defect%2Ctriage&template=2_bug_report.yml";
// todo!() workspace
// workspace .update(cx, |workspace, cx| {
// .update(cx, |workspace, cx| { if (*db2::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
// if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) { workspace.show_notification_once(0, cx, |cx| {
// workspace.show_notification_once(0, cx, |cx| { cx.build_view(|_| {
// cx.build_view(|_| { MessageNotification::new("Failed to load the database file.")
// MessageNotification::new("Failed to load the database file.") .with_click_message("Click to let us know about this error")
// .with_click_message("Click to let us know about this error") .on_click(|cx| cx.open_url(REPORT_ISSUE_URL))
// .on_click(|cx| cx.platform().open_url(REPORT_ISSUE_URL)) })
// }) });
// }); }
// } })
// }) .log_err();
// .log_err();
} }
impl EventEmitter for Workspace { impl EventEmitter for Workspace {
@ -4176,36 +4178,32 @@ impl WorkspaceStore {
} }
async fn handle_update_followers( async fn handle_update_followers(
_this: Model<Self>, this: Model<Self>,
_envelope: TypedEnvelope<proto::UpdateFollowers>, envelope: TypedEnvelope<proto::UpdateFollowers>,
_: Arc<Client>, _: Arc<Client>,
mut _cx: AsyncWindowContext, mut cx: AsyncWindowContext,
) -> Result<()> { ) -> Result<()> {
// let leader_id = envelope.original_sender_id()?; let leader_id = envelope.original_sender_id()?;
// let update = envelope.payload; let update = envelope.payload;
// this.update(&mut cx, |this, cx| { this.update(&mut cx, |this, cx| {
// for workspace in &this.workspaces { for workspace in &this.workspaces {
// let Some(workspace) = workspace.upgrade() else { workspace.update(cx, |workspace, cx| {
// continue; let project_id = workspace.project.read(cx).remote_id();
// }; if update.project_id != project_id && update.project_id.is_some() {
// workspace.update(cx, |workspace, cx| { return;
// let project_id = workspace.project.read(cx).remote_id(); }
// if update.project_id != project_id && update.project_id.is_some() { workspace.handle_update_followers(leader_id, update.clone(), cx);
// return; })?;
// } }
// workspace.handle_update_followers(leader_id, update.clone(), cx); Ok(())
// }); })?
// }
// Ok(())
// })?
todo!()
} }
} }
// impl Entity for WorkspaceStore { impl EventEmitter for WorkspaceStore {
// type Event = (); type Event = ();
// } }
impl ViewId { impl ViewId {
pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> { pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {

View file

@ -49,7 +49,7 @@ impl Settings for WorkspaceSettings {
fn load( fn load(
default_value: &Self::FileContent, default_value: &Self::FileContent,
user_values: &[&Self::FileContent], user_values: &[&Self::FileContent],
_: &mut gpui2::AppContext, _: &mut gpui::AppContext,
) -> anyhow::Result<Self> { ) -> anyhow::Result<Self> {
Self::load_via_json_merge(default_value, user_values) Self::load_via_json_merge(default_value, user_values)
} }

View file

@ -12,6 +12,7 @@ use cli::{
CliRequest, CliResponse, IpcHandshake, FORCE_CLI_MODE_ENV_VAR_NAME, CliRequest, CliResponse, IpcHandshake, FORCE_CLI_MODE_ENV_VAR_NAME,
}; };
use client::UserStore; use client::UserStore;
use collections::HashMap;
use db::kvp::KEY_VALUE_STORE; use db::kvp::KEY_VALUE_STORE;
use fs::RealFs; use fs::RealFs;
use futures::{channel::mpsc, SinkExt, StreamExt}; use futures::{channel::mpsc, SinkExt, StreamExt};
@ -42,11 +43,13 @@ use std::{
thread, thread,
time::{SystemTime, UNIX_EPOCH}, time::{SystemTime, UNIX_EPOCH},
}; };
use text::Point;
use util::{ use util::{
async_maybe, async_maybe,
channel::{parse_zed_link, ReleaseChannel, RELEASE_CHANNEL}, channel::{parse_zed_link, ReleaseChannel, RELEASE_CHANNEL},
http::{self, HttpClient}, http::{self, HttpClient},
paths, ResultExt, paths::{self, PathLikeWithPosition},
ResultExt,
}; };
use uuid::Uuid; use uuid::Uuid;
use workspace2::{AppState, WorkspaceStore}; use workspace2::{AppState, WorkspaceStore};
@ -228,10 +231,8 @@ fn main() {
let mut _triggered_authentication = false; let mut _triggered_authentication = false;
match open_rx.try_next() { match open_rx.try_next() {
Ok(Some(OpenRequest::Paths { paths: _ })) => { Ok(Some(OpenRequest::Paths { paths })) => {
// todo!("workspace") workspace2::open_paths(&paths, &app_state, None, cx).detach();
// cx.update(|cx| workspace::open_paths(&paths, &app_state, None, cx))
// .detach();
} }
Ok(Some(OpenRequest::CliConnection { connection })) => { Ok(Some(OpenRequest::CliConnection { connection })) => {
let app_state = app_state.clone(); let app_state = app_state.clone();
@ -263,10 +264,10 @@ fn main() {
async move { async move {
while let Some(request) = open_rx.next().await { while let Some(request) = open_rx.next().await {
match request { match request {
OpenRequest::Paths { paths: _ } => { OpenRequest::Paths { paths } => {
// todo!("workspace") cx.update(|cx| workspace2::open_paths(&paths, &app_state, None, cx))
// cx.update(|cx| workspace::open_paths(&paths, &app_state, None, cx)) .ok()
// .detach(); .map(|t| t.detach());
} }
OpenRequest::CliConnection { connection } => { OpenRequest::CliConnection { connection } => {
let app_state = app_state.clone(); let app_state = app_state.clone();
@ -781,45 +782,45 @@ async fn handle_cli_connection(
) { ) {
if let Some(request) = requests.next().await { if let Some(request) = requests.next().await {
match request { match request {
CliRequest::Open { paths: _, wait: _ } => { CliRequest::Open { paths, wait } => {
// let mut caret_positions = HashMap::new(); let mut caret_positions = HashMap::default();
// todo!("workspace") let paths = if paths.is_empty() {
// let paths = if paths.is_empty() { workspace2::last_opened_workspace_paths()
// workspace::last_opened_workspace_paths() .await
// .await .map(|location| location.paths().to_vec())
// .map(|location| location.paths().to_vec()) .unwrap_or_default()
// .unwrap_or_default() } else {
// } else { paths
// paths .into_iter()
// .into_iter() .filter_map(|path_with_position_string| {
// .filter_map(|path_with_position_string| { let path_with_position = PathLikeWithPosition::parse_str(
// let path_with_position = PathLikeWithPosition::parse_str( &path_with_position_string,
// &path_with_position_string, |path_str| {
// |path_str| { Ok::<_, std::convert::Infallible>(
// Ok::<_, std::convert::Infallible>( Path::new(path_str).to_path_buf(),
// Path::new(path_str).to_path_buf(), )
// ) },
// }, )
// ) .expect("Infallible");
// .expect("Infallible"); let path = path_with_position.path_like;
// let path = path_with_position.path_like; if let Some(row) = path_with_position.row {
// if let Some(row) = path_with_position.row { if path.is_file() {
// if path.is_file() { let row = row.saturating_sub(1);
// let row = row.saturating_sub(1); let col =
// let col = path_with_position.column.unwrap_or(0).saturating_sub(1);
// path_with_position.column.unwrap_or(0).saturating_sub(1); caret_positions.insert(path.clone(), Point::new(row, col));
// caret_positions.insert(path.clone(), Point::new(row, col)); }
// } }
// } Some(path)
// Some(path) })
// }) .collect()
// .collect() };
// };
// todo!("editor")
// let mut errored = false; // let mut errored = false;
// match cx // match cx
// .update(|cx| workspace::open_paths(&paths, &app_state, None, cx)) // .update(|cx| workspace2::open_paths(&paths, &app_state, None, cx))
// .await // .await
// { // {
// Ok((workspace, items)) => { // Ok((workspace, items)) => {

View file

@ -37,10 +37,9 @@ pub enum IsOnlyInstance {
} }
pub fn ensure_only_instance() -> IsOnlyInstance { pub fn ensure_only_instance() -> IsOnlyInstance {
// todo!("zed_stateless") if *db::ZED_STATELESS {
// if *db::ZED_STATELESS { return IsOnlyInstance::Yes;
// return IsOnlyInstance::Yes; }
// }
if check_got_handshake() { if check_got_handshake() {
return IsOnlyInstance::No; return IsOnlyInstance::No;

View file

@ -69,11 +69,10 @@ pub async fn handle_cli_connection(
let mut caret_positions = HashMap::default(); let mut caret_positions = HashMap::default();
let paths = if paths.is_empty() { let paths = if paths.is_empty() {
todo!() workspace2::last_opened_workspace_paths()
// workspace::last_opened_workspace_paths() .await
// .await .map(|location| location.paths().to_vec())
// .map(|location| location.paths().to_vec()) .unwrap_or_default()
// .unwrap_or_default()
} else { } else {
paths paths
.into_iter() .into_iter()
@ -115,7 +114,7 @@ pub async fn handle_cli_connection(
match item { match item {
Some(Ok(mut item)) => { Some(Ok(mut item)) => {
if let Some(point) = caret_positions.remove(path) { if let Some(point) = caret_positions.remove(path) {
todo!() todo!("editor")
// if let Some(active_editor) = item.downcast::<Editor>() { // if let Some(active_editor) = item.downcast::<Editor>() {
// active_editor // active_editor
// .downgrade() // .downgrade()
@ -260,33 +259,33 @@ pub fn initialize_workspace(
move |workspace, _, event, cx| { move |workspace, _, event, cx| {
if let workspace2::Event::PaneAdded(pane) = event { if let workspace2::Event::PaneAdded(pane) = event {
pane.update(cx, |pane, cx| { pane.update(cx, |pane, cx| {
// todo!() pane.toolbar().update(cx, |toolbar, cx| {
// pane.toolbar().update(cx, |toolbar, cx| { // todo!()
// let breadcrumbs = cx.add_view(|_| Breadcrumbs::new(workspace)); // let breadcrumbs = cx.add_view(|_| Breadcrumbs::new(workspace));
// toolbar.add_item(breadcrumbs, cx); // toolbar.add_item(breadcrumbs, cx);
// let buffer_search_bar = cx.add_view(BufferSearchBar::new); // let buffer_search_bar = cx.add_view(BufferSearchBar::new);
// toolbar.add_item(buffer_search_bar.clone(), cx); // toolbar.add_item(buffer_search_bar.clone(), cx);
// let quick_action_bar = cx.add_view(|_| { // let quick_action_bar = cx.add_view(|_| {
// QuickActionBar::new(buffer_search_bar, workspace) // QuickActionBar::new(buffer_search_bar, workspace)
// }); // });
// toolbar.add_item(quick_action_bar, cx); // toolbar.add_item(quick_action_bar, cx);
// let diagnostic_editor_controls = // let diagnostic_editor_controls =
// cx.add_view(|_| diagnostics2::ToolbarControls::new()); // cx.add_view(|_| diagnostics2::ToolbarControls::new());
// toolbar.add_item(diagnostic_editor_controls, cx); // toolbar.add_item(diagnostic_editor_controls, cx);
// let project_search_bar = cx.add_view(|_| ProjectSearchBar::new()); // let project_search_bar = cx.add_view(|_| ProjectSearchBar::new());
// toolbar.add_item(project_search_bar, cx); // toolbar.add_item(project_search_bar, cx);
// let submit_feedback_button = // let submit_feedback_button =
// cx.add_view(|_| SubmitFeedbackButton::new()); // cx.add_view(|_| SubmitFeedbackButton::new());
// toolbar.add_item(submit_feedback_button, cx); // toolbar.add_item(submit_feedback_button, cx);
// let feedback_info_text = cx.add_view(|_| FeedbackInfoText::new()); // let feedback_info_text = cx.add_view(|_| FeedbackInfoText::new());
// toolbar.add_item(feedback_info_text, cx); // toolbar.add_item(feedback_info_text, cx);
// let lsp_log_item = // let lsp_log_item =
// cx.add_view(|_| language_tools::LspLogToolbarItemView::new()); // cx.add_view(|_| language_tools::LspLogToolbarItemView::new());
// toolbar.add_item(lsp_log_item, cx); // toolbar.add_item(lsp_log_item, cx);
// let syntax_tree_item = cx // let syntax_tree_item = cx
// .add_view(|_| language_tools::SyntaxTreeToolbarItemView::new()); // .add_view(|_| language_tools::SyntaxTreeToolbarItemView::new());
// toolbar.add_item(syntax_tree_item, cx); // toolbar.add_item(syntax_tree_item, cx);
// }) })
}); });
} }
} }