Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
Merge branch 'main' into panels
Antonio Scandurra146809eef0ed
diff --cc Cargo.lockindex eee0873e5b1,3ae96f47517..2aea69e90b7--- a/Cargo.lock+++ b/Cargo.lock@@@ -4759,6 -4896,6 +4896,8 @@@ dependencies ="menu","postage","project",++ "schemars",++ "serde","serde_json","settings","theme",diff --cc assets/keymaps/jetbrains.jsonindex 69a583e1e96,383de079042..4825d3e8b5f--- a/assets/keymaps/jetbrains.json+++ b/assets/keymaps/jetbrains.json@@@ -63,10 -65,18 +65,11 @@@{"context": "Workspace","bindings": {+ "cmd-shift-o": "file_finder::Toggle","cmd-shift-a": "command_palette::Toggle","cmd-alt-o": "project_symbols::Toggle",- "cmd-1": "workspace::ToggleLeftSidebar",- "cmd-6": "diagnostics::Deploy",- "alt-f12": "dock::FocusDock"- }- },- {- "context": "Dock",- "bindings": {- "alt-f12": "dock::HideDock"+ "cmd-1": "workspace::ToggleLeftDock",+ "cmd-6": "diagnostics::Deploy"}}]diff --cc assets/settings/default.jsonindex d1a64996551,4f149edb105..3e4c59e8067--- a/assets/settings/default.json+++ b/assets/settings/default.json@@@ -106,11 -138,7 +128,14 @@@},// Automatically update Zed"auto_update": true,- // Git gutter behavior configuration.++ // Settings specific to the project panel+ "project_panel": {- "dock": "left",- "default_width": 240++ // Where to dock project panel. Can be 'left' or 'right'.++ "dock": "left",++ // Default width of the project panel.++ "default_width": 240+ },+ // Git gutter behavior configuration."git": {// Control whether the git gutter is shown. May take 2 values:// 1. Show the gutter@@@ -153,8 -181,6 +178,12 @@@// }// }"shell": "system",+ // Where to dock terminals panel. Can be 'left', 'right', 'bottom'.+ "dock": "bottom",++ // Default width when the terminal is docked to the left or right.++ "default_width": 640,++ // Default height when the terminal is docked to the bottom.++ "default_height": 320,// What working directory to use when launching the terminal.// May take 4 values:// 1. Use the current file's project directory. Will Fallback to thediff --cc crates/collab/src/tests.rsindex cbc4b3bd45c,3c571327eb2..b51c5240a83--- a/crates/collab/src/tests.rs+++ b/crates/collab/src/tests.rs@@@ -191,10 -190,10 +190,9 @@@ impl TestServerclient: client.clone(),user_store: user_store.clone(),languages: Arc::new(LanguageRegistry::test()),- themes: ThemeRegistry::new((), cx.font_cache()),fs: fs.clone(),build_window_options: |_, _, _| Default::default(),- initialize_workspace: |_, _, _| unimplemented!(),- dock_default_item_factory: |_, _| None,+ initialize_workspace: |_, _, _, _| unimplemented!(),background_actions: || &[],});diff --cc crates/file_finder/src/file_finder.rsindex f00430feb7e,5270b694b23..6d2ba115b7f--- a/crates/file_finder/src/file_finder.rs+++ b/crates/file_finder/src/file_finder.rs@@@ -268,11 -373,14 +373,14 @@@ impl PickerDelegate for FileFinderDeleg#[cfg(test)]mod tests {+ use std::{assert_eq, collections::HashMap, time::Duration};+use super::*;use editor::Editor;+ use gpui::{TestAppContext, ViewHandle};use menu::{Confirm, SelectNext};use serde_json::json;- use workspace::{AppState, Pane, Workspace};+ use workspace::{AppState, Workspace};#[ctor::ctor]fn init_logger() {@@@ -658,4 -947,268 +947,272 @@@assert_eq!(finder.delegate().matches.len(), 0);});}++ #[gpui::test]+ async fn test_query_history(+ deterministic: Arc<gpui::executor::Deterministic>,+ cx: &mut gpui::TestAppContext,+ ) {+ let app_state = init_test(cx);++ app_state+ .fs+ .as_fake()+ .insert_tree(+ "/src",+ json!({+ "test": {+ "first.rs": "// First Rust file",+ "second.rs": "// Second Rust file",+ "third.rs": "// Third Rust file",+ }+ }),+ )+ .await;++ let project = Project::test(app_state.fs.clone(), ["/src".as_ref()], cx).await;+ let (window_id, workspace) = cx.add_window(|cx| Workspace::test_new(project, cx));+ let worktree_id = cx.read(|cx| {+ let worktrees = workspace.read(cx).worktrees(cx).collect::<Vec<_>>();+ assert_eq!(worktrees.len(), 1);+ WorktreeId::from_usize(worktrees[0].id())+ });++ // Open and close panels, getting their history items afterwards.+ // Ensure history items get populated with opened items, and items are kept in a certain order.+ // The history lags one opened buffer behind, since it's updated in the search panel only on its reopen.+ //+ // TODO: without closing, the opened items do not propagate their history changes for some reason+ // it does work in real app though, only tests do not propagate.++ let initial_history = open_close_queried_buffer(+ "fir",+ 1,+ "first.rs",+ window_id,+ &workspace,+ &deterministic,+ cx,+ )+ .await;+ assert!(+ initial_history.is_empty(),+ "Should have no history before opening any files"+ );++ let history_after_first = open_close_queried_buffer(+ "sec",+ 1,+ "second.rs",+ window_id,+ &workspace,+ &deterministic,+ cx,+ )+ .await;+ assert_eq!(+ history_after_first,+ vec![ProjectPath {+ worktree_id,+ path: Arc::from(Path::new("test/first.rs")),+ }],+ "Should show 1st opened item in the history when opening the 2nd item"+ );++ let history_after_second = open_close_queried_buffer(+ "thi",+ 1,+ "third.rs",+ window_id,+ &workspace,+ &deterministic,+ cx,+ )+ .await;+ assert_eq!(+ history_after_second,+ vec![+ ProjectPath {+ worktree_id,+ path: Arc::from(Path::new("test/second.rs")),+ },+ ProjectPath {+ worktree_id,+ path: Arc::from(Path::new("test/first.rs")),+ },+ ],+ "Should show 1st and 2nd opened items in the history when opening the 3rd item. \+ 2nd item should be the first in the history, as the last opened."+ );++ let history_after_third = open_close_queried_buffer(+ "sec",+ 1,+ "second.rs",+ window_id,+ &workspace,+ &deterministic,+ cx,+ )+ .await;+ assert_eq!(+ history_after_third,+ vec![+ ProjectPath {+ worktree_id,+ path: Arc::from(Path::new("test/third.rs")),+ },+ ProjectPath {+ worktree_id,+ path: Arc::from(Path::new("test/second.rs")),+ },+ ProjectPath {+ worktree_id,+ path: Arc::from(Path::new("test/first.rs")),+ },+ ],+ "Should show 1st, 2nd and 3rd opened items in the history when opening the 2nd item again. \+ 3rd item should be the first in the history, as the last opened."+ );++ let history_after_second_again = open_close_queried_buffer(+ "thi",+ 1,+ "third.rs",+ window_id,+ &workspace,+ &deterministic,+ cx,+ )+ .await;+ assert_eq!(+ history_after_second_again,+ vec![+ ProjectPath {+ worktree_id,+ path: Arc::from(Path::new("test/second.rs")),+ },+ ProjectPath {+ worktree_id,+ path: Arc::from(Path::new("test/third.rs")),+ },+ ProjectPath {+ worktree_id,+ path: Arc::from(Path::new("test/first.rs")),+ },+ ],+ "Should show 1st, 2nd and 3rd opened items in the history when opening the 3rd item again. \+ 2nd item, as the last opened, 3rd item should go next as it was opened right before."+ );+ }++ async fn open_close_queried_buffer(+ input: &str,+ expected_matches: usize,+ expected_editor_title: &str,+ window_id: usize,+ workspace: &ViewHandle<Workspace>,+ deterministic: &gpui::executor::Deterministic,+ cx: &mut gpui::TestAppContext,+ ) -> Vec<ProjectPath> {+ cx.dispatch_action(window_id, Toggle);+ let finder = cx.read(|cx| workspace.read(cx).modal::<FileFinder>().unwrap());+ finder+ .update(cx, |finder, cx| {+ finder.delegate_mut().update_matches(input.to_string(), cx)+ })+ .await;+ let history_items = finder.read_with(cx, |finder, _| {+ assert_eq!(+ finder.delegate().matches.len(),+ expected_matches,+ "Unexpected number of matches found for query {input}"+ );+ finder.delegate().history_items.clone()+ });++ let active_pane = cx.read(|cx| workspace.read(cx).active_pane().clone());+ cx.dispatch_action(window_id, SelectNext);+ cx.dispatch_action(window_id, Confirm);+ deterministic.run_until_parked();+ active_pane+ .condition(cx, |pane, _| pane.active_item().is_some())+ .await;+ cx.read(|cx| {+ let active_item = active_pane.read(cx).active_item().unwrap();+ let active_editor_title = active_item+ .as_any()+ .downcast_ref::<Editor>()+ .unwrap()+ .read(cx)+ .title(cx);+ assert_eq!(+ expected_editor_title, active_editor_title,+ "Unexpected editor title for query {input}"+ );+ });++ let mut original_items = HashMap::new();+ cx.read(|cx| {+ for pane in workspace.read(cx).panes() {+ let pane_id = pane.id();+ let pane = pane.read(cx);+ let insertion_result = original_items.insert(pane_id, pane.items().count());+ assert!(insertion_result.is_none(), "Pane id {pane_id} collision");+ }+ });- workspace.update(cx, |workspace, cx| {- Pane::close_active_item(workspace, &workspace::CloseActiveItem, cx);- });++ active_pane++ .update(cx, |pane, cx| {++ pane.close_active_item(&workspace::CloseActiveItem, cx)++ .unwrap()++ })++ .await++ .unwrap();+ deterministic.run_until_parked();+ cx.read(|cx| {+ for pane in workspace.read(cx).panes() {+ let pane_id = pane.id();+ let pane = pane.read(cx);+ match original_items.remove(&pane_id) {+ Some(original_items) => {+ assert_eq!(+ pane.items().count(),+ original_items.saturating_sub(1),+ "Pane id {pane_id} should have item closed"+ );+ }+ None => panic!("Pane id {pane_id} not found in original items"),+ }+ }+ });++ history_items+ }++ fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {+ cx.foreground().forbid_parking();+ cx.update(|cx| {+ let state = AppState::test(cx);+ theme::init((), cx);+ language::init(cx);+ super::init(cx);+ editor::init(cx);+ workspace::init_settings(cx);+ state+ })+ }++ fn test_path_like(test_str: &str) -> PathLikeWithPosition<FileSearchQuery> {+ PathLikeWithPosition::parse_str(test_str, |path_like_str| {+ Ok::<_, std::convert::Infallible>(FileSearchQuery {+ raw_query: test_str.to_owned(),+ file_query_end: if path_like_str == test_str {+ None+ } else {+ Some(path_like_str.len())+ },+ })+ })+ .unwrap()+ }}diff --cc crates/project_panel/Cargo.tomlindex d3b28766752,6fcdf06d2c7..8cd5a066753--- a/crates/project_panel/Cargo.toml+++ b/crates/project_panel/Cargo.toml@@@ -21,6 -21,6 +21,8 @@@ util = { path = "../util"workspace = { path = "../workspace" }postage.workspace = truefutures.workspace = true++schemars.workspace = true++serde.workspace = trueunicase = "2.6"[dev-dependencies]diff --cc crates/project_panel/src/project_panel.rsindex 3476a6a155f,ce0dd9e2221..761d8030846--- a/crates/project_panel/src/project_panel.rs+++ b/crates/project_panel/src/project_panel.rs@@@ -13,11 -13,13 +13,16 @@@ use gpui::keymap_matcher::KeymapContext,platform::{CursorStyle, MouseButton, PromptLevel},AnyElement, AppContext, ClipboardItem, Element, Entity, ModelHandle, Task, View, ViewContext,- ViewHandle, WeakViewHandle,+ ViewHandle, WeakViewHandle, WindowContext,};use menu::{Confirm, SelectNext, SelectPrev};- use project::{Entry, EntryKind, Project, ProjectEntryId, ProjectPath, Worktree, WorktreeId};- use settings::{settings_file::SettingsFile, Settings};+ use project::{- repository::GitFileStatus, Entry, EntryKind, Project, ProjectEntryId, ProjectPath, Worktree,- WorktreeId,++ repository::GitFileStatus, Entry, EntryKind, Fs, Project, ProjectEntryId, ProjectPath,++ Worktree, WorktreeId,+ };++use schemars::JsonSchema;++use serde::{Deserialize, Serialize};++use settings::SettingsStore;use std::{cmp::Ordering,collections::{hash_map, HashMap},@@@ -26,17 -28,14 +31,50 @@@path::Path,sync::Arc,};- use theme::ProjectPanelEntry;+ use theme::{ui::FileName, ProjectPanelEntry};use unicase::UniCase;-use workspace::Workspace;+use workspace::{+ dock::{DockPosition, Panel},+ Workspace,+};const NEW_ENTRY_ID: ProjectEntryId = ProjectEntryId::MAX;++#[derive(Deserialize)]++pub struct ProjectPanelSettings {++ dock: ProjectPanelDockPosition,++ default_width: f32,++}++++impl settings::Setting for ProjectPanelSettings {++ const KEY: Option<&'static str> = Some("project_panel");++++ type FileContent = ProjectPanelSettingsContent;++++ fn load(++ default_value: &Self::FileContent,++ user_values: &[&Self::FileContent],++ _: &AppContext,++ ) -> Result<Self> {++ Self::load_via_json_merge(default_value, user_values)++ }++}++++#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]++pub struct ProjectPanelSettingsContent {++ dock: Option<ProjectPanelDockPosition>,++ default_width: Option<f32>,++}++++#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]++pub enum ProjectPanelDockPosition {++ Left,++ Right,++}++pub struct ProjectPanel {project: ModelHandle<Project>,++ fs: Arc<dyn Fs>,list: UniformListState,visible_entries: Vec<(WorktreeId, Vec<Entry>)>,last_worktree_root_id: Option<ProjectEntryId>,@@@ -112,6 -111,6 +151,7 @@@ actions!);pub fn init(cx: &mut AppContext) {++ settings::register::<ProjectPanelSettings>(cx);cx.add_action(ProjectPanel::expand_selected_entry);cx.add_action(ProjectPanel::collapse_selected_entry);cx.add_action(ProjectPanel::select_prev);@@@ -205,6 -202,6 +245,7 @@@ impl ProjectPanellet view_id = cx.view_id();let mut this = Self {project: project.clone(),++ fs: workspace.app_state().fs.clone(),list: Default::default(),visible_entries: Default::default(),last_worktree_root_id: Default::default(),@@@ -216,21 -213,8 +257,21 @@@context_menu: cx.add_view(|cx| ContextMenu::new(view_id, cx)),dragged_entry_destination: None,workspace: workspace.weak_handle(),+ has_focus: false,};this.update_visible_entries(None, cx);++ // Update the dock position when the setting changes.+ let mut old_dock_position = this.position(cx);- cx.observe_global::<Settings, _>(move |this, cx| {++ cx.observe_global::<SettingsStore, _>(move |this, cx| {+ let new_dock_position = this.position(cx);+ if new_dock_position != old_dock_position {+ old_dock_position = new_dock_position;+ cx.emit(Event::DockPositionChanged);+ }+ })+ .detach();+this});@@@ -1358,78 -1340,10 +1409,79 @@@ impl Entity for ProjectPaneltype Event = Event;}-impl workspace::sidebar::SidebarItem for ProjectPanel {- fn should_show_badge(&self, _: &AppContext) -> bool {+impl workspace::dock::Panel for ProjectPanel {+ fn position(&self, cx: &WindowContext) -> DockPosition {- let settings = cx.global::<Settings>();- match settings.project_panel.dock {- settings::ProjectPanelDockPosition::Left => DockPosition::Left,- settings::ProjectPanelDockPosition::Right => DockPosition::Right,++ match settings::get::<ProjectPanelSettings>(cx).dock {++ ProjectPanelDockPosition::Left => DockPosition::Left,++ ProjectPanelDockPosition::Right => DockPosition::Right,+ }+ }++ fn position_is_valid(&self, position: DockPosition) -> bool {+ matches!(position, DockPosition::Left | DockPosition::Right)+ }++ fn set_position(&mut self, position: DockPosition, cx: &mut ViewContext<Self>) {- SettingsFile::update(cx, move |settings| {- let dock = match position {- DockPosition::Left | DockPosition::Bottom => {- settings::ProjectPanelDockPosition::Left- }- DockPosition::Right => settings::ProjectPanelDockPosition::Right,- };- settings.project_panel.dock = Some(dock);- })++ settings::update_settings_file::<ProjectPanelSettings>(++ self.fs.clone(),++ cx,++ move |settings| {++ let dock = match position {++ DockPosition::Left | DockPosition::Bottom => ProjectPanelDockPosition::Left,++ DockPosition::Right => ProjectPanelDockPosition::Right,++ };++ settings.dock = Some(dock);++ },++ );+ }++ fn default_size(&self, cx: &WindowContext) -> f32 {- cx.global::<Settings>().project_panel.default_width++ settings::get::<ProjectPanelSettings>(cx).default_width+ }++ fn should_zoom_in_on_event(_: &Self::Event) -> bool {+ false+ }++ fn should_zoom_out_on_event(_: &Self::Event) -> bool {false}++ fn is_zoomed(&self, _: &WindowContext) -> bool {+ false+ }++ fn set_zoomed(&mut self, _: bool, _: &mut ViewContext<Self>) {}++ fn set_active(&mut self, _: bool, _: &mut ViewContext<Self>) {}++ fn icon_path(&self) -> &'static str {+ "icons/folder_tree_16.svg"+ }++ fn icon_tooltip(&self) -> String {+ "Project Panel".into()+ }++ fn should_change_position_on_event(event: &Self::Event) -> bool {+ matches!(event, Event::DockPositionChanged)+ }++ fn should_activate_on_event(_: &Self::Event) -> bool {+ false+ }++ fn should_close_on_event(_: &Self::Event) -> bool {+ false+ }++ fn has_focus(&self, _: &WindowContext) -> bool {+ self.has_focus+ }++ fn is_focus_event(event: &Self::Event) -> bool {+ matches!(event, Event::Focus)+ }}impl ClipboardEntry {diff --cc crates/terminal/src/terminal.rsindex 25852875c3b,98d85d00e1c..9cf3f529249--- a/crates/terminal/src/terminal.rs+++ b/crates/terminal/src/terminal.rs@@@ -114,6 -115,112 +115,125 @@@ impl EventListener for ZedListener}}+ pub fn init(cx: &mut AppContext) {+ settings::register::<TerminalSettings>(cx);+ }+++#[derive(Copy, Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]++pub enum TerminalDockPosition {++ Left,++ Bottom,++ Right,++}+++ #[derive(Deserialize)]+ pub struct TerminalSettings {+ pub shell: Shell,+ pub working_directory: WorkingDirectory,+ font_size: Option<f32>,+ pub font_family: Option<String>,+ pub line_height: TerminalLineHeight,+ pub font_features: Option<fonts::Features>,+ pub env: HashMap<String, String>,+ pub blinking: TerminalBlink,+ pub alternate_scroll: AlternateScroll,+ pub option_as_meta: bool,+ pub copy_on_select: bool,++ pub dock: TerminalDockPosition,++ pub default_width: f32,++ pub default_height: f32,+ }++ #[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]+ pub struct TerminalSettingsContent {+ pub shell: Option<Shell>,+ pub working_directory: Option<WorkingDirectory>,+ pub font_size: Option<f32>,+ pub font_family: Option<String>,+ pub line_height: Option<TerminalLineHeight>,+ pub font_features: Option<fonts::Features>,+ pub env: Option<HashMap<String, String>>,+ pub blinking: Option<TerminalBlink>,+ pub alternate_scroll: Option<AlternateScroll>,+ pub option_as_meta: Option<bool>,+ pub copy_on_select: Option<bool>,++ pub dock: Option<TerminalDockPosition>,++ pub default_width: Option<f32>,++ pub default_height: Option<f32>,+ }++ impl TerminalSettings {+ pub fn font_size(&self, cx: &AppContext) -> Option<f32> {+ self.font_size+ .map(|size| theme::adjusted_font_size(size, cx))+ }+ }++ impl settings::Setting for TerminalSettings {+ const KEY: Option<&'static str> = Some("terminal");++ type FileContent = TerminalSettingsContent;++ fn load(+ default_value: &Self::FileContent,+ user_values: &[&Self::FileContent],+ _: &AppContext,+ ) -> Result<Self> {+ Self::load_via_json_merge(default_value, user_values)+ }+ }++ #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema, Default)]+ #[serde(rename_all = "snake_case")]+ pub enum TerminalLineHeight {+ #[default]+ Comfortable,+ Standard,+ Custom(f32),+ }++ impl TerminalLineHeight {+ pub fn value(&self) -> f32 {+ match self {+ TerminalLineHeight::Comfortable => 1.618,+ TerminalLineHeight::Standard => 1.3,+ TerminalLineHeight::Custom(line_height) => *line_height,+ }+ }+ }++ #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]+ #[serde(rename_all = "snake_case")]+ pub enum TerminalBlink {+ Off,+ TerminalControlled,+ On,+ }++ #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]+ #[serde(rename_all = "snake_case")]+ pub enum Shell {+ System,+ Program(String),+ WithArguments { program: String, args: Vec<String> },+ }++ #[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]+ #[serde(rename_all = "snake_case")]+ pub enum AlternateScroll {+ On,+ Off,+ }++ #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]+ #[serde(rename_all = "snake_case")]+ pub enum WorkingDirectory {+ CurrentProjectDirectory,+ FirstProjectDirectory,+ AlwaysHome,+ Always { directory: String },+ }+#[derive(Clone, Copy, Debug, Serialize, Deserialize)]pub struct TerminalSize {pub cell_width: f32,diff --cc crates/terminal_view/src/terminal_panel.rsindex 1f4096880c9,00000000000..afd564fb56dmode 100644,000000..100644--- a/crates/terminal_view/src/terminal_panel.rs+++ b/crates/terminal_view/src/terminal_panel.rs@@@ -1,366 -1,0 +1,363 @@@++use std::sync::Arc;+++use crate::TerminalView;+use db::kvp::KEY_VALUE_STORE;+use gpui::{+ actions, anyhow::Result, elements::*, serde_json, AppContext, AsyncAppContext, Entity,+ Subscription, Task, View, ViewContext, ViewHandle, WeakViewHandle, WindowContext,+};++use project::Fs;+use serde::{Deserialize, Serialize};- use settings::{settings_file::SettingsFile, Settings, TerminalDockPosition, WorkingDirectory};++use settings::SettingsStore;++use terminal::{TerminalDockPosition, TerminalSettings};+use util::{ResultExt, TryFutureExt};+use workspace::{+ dock::{DockPosition, Panel},+ item::Item,+ pane, DraggedItem, Pane, Workspace,+};++const TERMINAL_PANEL_KEY: &'static str = "TerminalPanel";++actions!(terminal_panel, [ToggleFocus]);++pub fn init(cx: &mut AppContext) {+ cx.add_action(TerminalPanel::add_terminal);+}++pub enum Event {+ Close,+ DockPositionChanged,+ ZoomIn,+ ZoomOut,+ Focus,+}++pub struct TerminalPanel {+ pane: ViewHandle<Pane>,++ fs: Arc<dyn Fs>,+ workspace: WeakViewHandle<Workspace>,+ pending_serialization: Task<Option<()>>,+ _subscriptions: Vec<Subscription>,+}++impl TerminalPanel {+ pub fn new(workspace: &Workspace, cx: &mut ViewContext<Self>) -> Self {- let mut old_dock_position = cx.global::<Settings>().terminal_overrides.dock;- cx.observe_global::<Settings, _>(move |_, cx| {- let new_dock_position = cx.global::<Settings>().terminal_overrides.dock;- if new_dock_position != old_dock_position {- old_dock_position = new_dock_position;- cx.emit(Event::DockPositionChanged);- }- })- .detach();-- let this = cx.weak_handle();++ let weak_self = cx.weak_handle();+ let pane = cx.add_view(|cx| {+ let window_id = cx.window_id();+ let mut pane = Pane::new(+ workspace.weak_handle(),+ workspace.app_state().background_actions,++ Default::default(),+ cx,+ );+ pane.set_can_split(false, cx);+ pane.on_can_drop(move |drag_and_drop, cx| {+ drag_and_drop+ .currently_dragged::<DraggedItem>(window_id)+ .map_or(false, |(_, item)| {+ item.handle.act_as::<TerminalView>(cx).is_some()+ })+ });+ pane.set_render_tab_bar_buttons(cx, move |_, cx| {- let this = this.clone();++ let this = weak_self.clone();+ Pane::render_tab_bar_button(+ 0,+ "icons/plus_12.svg",+ cx,+ move |_, cx| {+ let this = this.clone();+ cx.window_context().defer(move |cx| {+ if let Some(this) = this.upgrade(cx) {+ this.update(cx, |this, cx| {+ this.add_terminal(&Default::default(), cx);+ });+ }+ })+ },+ None,+ )+ });+ pane+ });+ let subscriptions = vec![+ cx.observe(&pane, |_, _, cx| cx.notify()),+ cx.subscribe(&pane, Self::handle_pane_event),+ ];- Self {++ let this = Self {+ pane,++ fs: workspace.app_state().fs.clone(),+ workspace: workspace.weak_handle(),+ pending_serialization: Task::ready(None),+ _subscriptions: subscriptions,- }++ };++ let mut old_dock_position = this.position(cx);++ cx.observe_global::<SettingsStore, _>(move |this, cx| {++ let new_dock_position = this.position(cx);++ if new_dock_position != old_dock_position {++ old_dock_position = new_dock_position;++ cx.emit(Event::DockPositionChanged);++ }++ })++ .detach();++ this+ }++ pub fn load(+ workspace: WeakViewHandle<Workspace>,+ cx: AsyncAppContext,+ ) -> Task<Result<ViewHandle<Self>>> {+ cx.spawn(|mut cx| async move {+ let serialized_panel = if let Some(panel) = cx+ .background()+ .spawn(async move { KEY_VALUE_STORE.read_kvp(TERMINAL_PANEL_KEY) })+ .await?+ {+ Some(serde_json::from_str::<SerializedTerminalPanel>(&panel)?)+ } else {+ None+ };+ let (panel, pane, items) = workspace.update(&mut cx, |workspace, cx| {+ let panel = cx.add_view(|cx| TerminalPanel::new(workspace, cx));+ let items = if let Some(serialized_panel) = serialized_panel.as_ref() {+ panel.update(cx, |panel, cx| {+ panel.pane.update(cx, |_, cx| {+ serialized_panel+ .items+ .iter()+ .map(|item_id| {+ TerminalView::deserialize(+ workspace.project().clone(),+ workspace.weak_handle(),+ workspace.database_id(),+ *item_id,+ cx,+ )+ })+ .collect::<Vec<_>>()+ })+ })+ } else {+ Default::default()+ };+ let pane = panel.read(cx).pane.clone();+ (panel, pane, items)+ })?;++ let items = futures::future::join_all(items).await;+ workspace.update(&mut cx, |workspace, cx| {+ let active_item_id = serialized_panel+ .as_ref()+ .and_then(|panel| panel.active_item_id);+ let mut active_ix = None;+ for item in items {+ if let Some(item) = item.log_err() {+ let item_id = item.id();+ Pane::add_item(workspace, &pane, Box::new(item), false, false, None, cx);+ if Some(item_id) == active_item_id {+ active_ix = Some(pane.read(cx).items_len() - 1);+ }+ }+ }++ if let Some(active_ix) = active_ix {+ pane.update(cx, |pane, cx| {+ pane.activate_item(active_ix, false, false, cx)+ });+ }+ })?;++ Ok(panel)+ })+ }++ fn handle_pane_event(+ &mut self,+ _pane: ViewHandle<Pane>,+ event: &pane::Event,+ cx: &mut ViewContext<Self>,+ ) {+ match event {+ pane::Event::ActivateItem { .. } => self.serialize(cx),+ pane::Event::RemoveItem { .. } => self.serialize(cx),+ pane::Event::Remove => cx.emit(Event::Close),+ pane::Event::ZoomIn => cx.emit(Event::ZoomIn),+ pane::Event::ZoomOut => cx.emit(Event::ZoomOut),+ pane::Event::Focus => cx.emit(Event::Focus),+ _ => {}+ }+ }++ fn add_terminal(&mut self, _: &workspace::NewTerminal, cx: &mut ViewContext<Self>) {+ let workspace = self.workspace.clone();+ cx.spawn(|this, mut cx| async move {+ let pane = this.read_with(&cx, |this, _| this.pane.clone())?;+ workspace.update(&mut cx, |workspace, cx| {- let working_directory_strategy = cx- .global::<Settings>()- .terminal_overrides++ let working_directory_strategy = settings::get::<TerminalSettings>(cx)+ .working_directory- .clone()- .unwrap_or(WorkingDirectory::CurrentProjectDirectory);++ .clone();+ let working_directory =+ crate::get_working_directory(workspace, cx, working_directory_strategy);+ let window_id = cx.window_id();+ if let Some(terminal) = workspace.project().update(cx, |project, cx| {+ project+ .create_terminal(working_directory, window_id, cx)+ .log_err()+ }) {+ let terminal =+ Box::new(cx.add_view(|cx| {+ TerminalView::new(terminal, workspace.database_id(), cx)+ }));+ Pane::add_item(workspace, &pane, terminal, true, true, None, cx);+ }+ })?;+ this.update(&mut cx, |this, cx| this.serialize(cx))?;+ anyhow::Ok(())+ })+ .detach_and_log_err(cx);+ }++ fn serialize(&mut self, cx: &mut ViewContext<Self>) {+ let items = self+ .pane+ .read(cx)+ .items()+ .map(|item| item.id())+ .collect::<Vec<_>>();+ let active_item_id = self.pane.read(cx).active_item().map(|item| item.id());+ self.pending_serialization = cx.background().spawn(+ async move {+ KEY_VALUE_STORE+ .write_kvp(+ TERMINAL_PANEL_KEY.into(),+ serde_json::to_string(&SerializedTerminalPanel {+ items,+ active_item_id,+ })?,+ )+ .await?;+ anyhow::Ok(())+ }+ .log_err(),+ );+ }+}++impl Entity for TerminalPanel {+ type Event = Event;+}++impl View for TerminalPanel {+ fn ui_name() -> &'static str {+ "TerminalPanel"+ }++ fn render(&mut self, cx: &mut ViewContext<Self>) -> gpui::AnyElement<Self> {+ ChildView::new(&self.pane, cx).into_any()+ }++ fn focus_in(&mut self, _: gpui::AnyViewHandle, cx: &mut ViewContext<Self>) {+ if cx.is_self_focused() {+ cx.focus(&self.pane);+ }+ }+}++impl Panel for TerminalPanel {+ fn position(&self, cx: &WindowContext) -> DockPosition {- let settings = cx.global::<Settings>();- let dock = settings- .terminal_overrides- .dock- .or(settings.terminal_defaults.dock)- .unwrap()- .into();- match dock {- settings::TerminalDockPosition::Left => DockPosition::Left,- settings::TerminalDockPosition::Bottom => DockPosition::Bottom,- settings::TerminalDockPosition::Right => DockPosition::Right,++ match settings::get::<TerminalSettings>(cx).dock {++ TerminalDockPosition::Left => DockPosition::Left,++ TerminalDockPosition::Bottom => DockPosition::Bottom,++ TerminalDockPosition::Right => DockPosition::Right,+ }+ }++ fn position_is_valid(&self, _: DockPosition) -> bool {+ true+ }++ fn set_position(&mut self, position: DockPosition, cx: &mut ViewContext<Self>) {- SettingsFile::update(cx, move |settings| {++ settings::update_settings_file::<TerminalSettings>(self.fs.clone(), cx, move |settings| {+ let dock = match position {+ DockPosition::Left => TerminalDockPosition::Left,+ DockPosition::Bottom => TerminalDockPosition::Bottom,+ DockPosition::Right => TerminalDockPosition::Right,+ };- settings.terminal.dock = Some(dock);++ settings.dock = Some(dock);+ });+ }++ fn default_size(&self, cx: &WindowContext) -> f32 {- let settings = &cx.global::<Settings>().terminal_overrides;++ let settings = settings::get::<TerminalSettings>(cx);+ match self.position(cx) {- DockPosition::Left | DockPosition::Right => settings.default_width.unwrap_or(640.),- DockPosition::Bottom => settings.default_height.unwrap_or(320.),++ DockPosition::Left | DockPosition::Right => settings.default_width,++ DockPosition::Bottom => settings.default_height,+ }+ }++ fn should_zoom_in_on_event(event: &Event) -> bool {+ matches!(event, Event::ZoomIn)+ }++ fn should_zoom_out_on_event(event: &Event) -> bool {+ matches!(event, Event::ZoomOut)+ }++ fn is_zoomed(&self, cx: &WindowContext) -> bool {+ self.pane.read(cx).is_zoomed()+ }++ fn set_zoomed(&mut self, zoomed: bool, cx: &mut ViewContext<Self>) {+ self.pane.update(cx, |pane, cx| pane.set_zoomed(zoomed, cx));+ }++ fn set_active(&mut self, active: bool, cx: &mut ViewContext<Self>) {+ if active && self.pane.read(cx).items_len() == 0 {+ self.add_terminal(&Default::default(), cx)+ }+ }++ fn icon_path(&self) -> &'static str {+ "icons/terminal_12.svg"+ }++ fn icon_tooltip(&self) -> String {+ "Terminals".to_string()+ }++ fn icon_label(&self, cx: &WindowContext) -> Option<String> {+ let count = self.pane.read(cx).items_len();+ if count == 0 {+ None+ } else {+ Some(count.to_string())+ }+ }++ fn should_change_position_on_event(event: &Self::Event) -> bool {+ matches!(event, Event::DockPositionChanged)+ }++ fn should_activate_on_event(_: &Self::Event) -> bool {+ false+ }++ fn should_close_on_event(event: &Event) -> bool {+ matches!(event, Event::Close)+ }++ fn has_focus(&self, cx: &WindowContext) -> bool {+ self.pane.read(cx).has_focus()+ }++ fn is_focus_event(event: &Self::Event) -> bool {+ matches!(event, Event::Focus)+ }+}++#[derive(Serialize, Deserialize)]+struct SerializedTerminalPanel {+ items: Vec<usize>,+ active_item_id: Option<usize>,+}diff --cc crates/terminal_view/src/terminal_view.rsindex 2c33cc8f39d,0a7a69bf739..767e3bf4dbb--- a/crates/terminal_view/src/terminal_view.rs+++ b/crates/terminal_view/src/terminal_view.rs@@@ -1,7 -1,8 +1,8 @@@mod persistence;-pub mod terminal_button;pub mod terminal_element;+pub mod terminal_panel;+ use crate::{persistence::TERMINAL_DB, terminal_element::TerminalElement};use context_menu::{ContextMenu, ContextMenuItem};use dirs::home_dir;use gpui::{@@@ -63,7 -63,8 +63,9 @@@ actions!impl_actions!(terminal, [SendText, SendKeystroke]);pub fn init(cx: &mut AppContext) {+ terminal_panel::init(cx);+ terminal::init(cx);+cx.add_action(TerminalView::deploy);register_deserializable_item::<TerminalView>(cx);diff --cc crates/welcome/src/welcome.rsindex d78b230dd91,000c2fd8d97..b7460c4c461--- a/crates/welcome/src/welcome.rs+++ b/crates/welcome/src/welcome.rs@@@ -7,10 -8,10 +8,10 @@@ use gpui::elements::{Flex, Label, ParentElement},AnyElement, AppContext, Element, Entity, Subscription, View, ViewContext, WeakViewHandle,};- use settings::{settings_file::SettingsFile, Settings};-+ use settings::{update_settings_file, SettingsStore};+ use std::{borrow::Cow, sync::Arc};use workspace::{- item::Item, open_new, sidebar::SidebarSide, AppState, PaneBackdrop, Welcome, Workspace,+ dock::DockPosition, item::Item, open_new, AppState, PaneBackdrop, Welcome, Workspace,WorkspaceId,};diff --cc crates/workspace/src/dock.rsindex 83bb54d3be3,beec6a05152..c327c4ded8a--- a/crates/workspace/src/dock.rs+++ b/crates/workspace/src/dock.rs@@@ -1,106 -1,122 +1,106 @@@-mod toggle_dock_button;--use crate::{- sidebar::SidebarSide, BackgroundActions, DockAnchor, ItemHandle, Pane, Workspace,- WorkspaceSettings,-};-use collections::HashMap;+use crate::{StatusItemView, Workspace};+use context_menu::{ContextMenu, ContextMenuItem};use gpui::{- actions,- elements::{ChildView, Empty, MouseEventHandler, ParentElement, Side, Stack},- geometry::vector::Vector2F,- platform::{CursorStyle, MouseButton},- AnyElement, AppContext, Border, Element, SizeConstraint, ViewContext, ViewHandle,+ elements::*, impl_actions, platform::CursorStyle, platform::MouseButton, AnyViewHandle,+ AppContext, Axis, Entity, Subscription, View, ViewContext, ViewHandle, WeakViewHandle,+ WindowContext,};-use std::sync::{atomic::AtomicUsize, Arc};-use theme::Theme;-pub use toggle_dock_button::ToggleDockButton;--actions!(- dock,- [- FocusDock,- HideDock,- AnchorDockRight,- AnchorDockBottom,- ExpandDock,- AddTabToDock,- RemoveTabFromDock,- ]-);--pub fn init(cx: &mut AppContext) {- cx.add_action(Dock::focus_dock);- cx.add_action(Dock::hide_dock);- cx.add_action(- |workspace: &mut Workspace, _: &AnchorDockRight, cx: &mut ViewContext<Workspace>| {- Dock::move_dock(workspace, DockAnchor::Right, true, cx);- },- );- cx.add_action(- |workspace: &mut Workspace, _: &AnchorDockBottom, cx: &mut ViewContext<Workspace>| {- Dock::move_dock(workspace, DockAnchor::Bottom, true, cx)- },- );- cx.add_action(- |workspace: &mut Workspace, _: &ExpandDock, cx: &mut ViewContext<Workspace>| {- Dock::move_dock(workspace, DockAnchor::Expanded, true, cx)- },- );- cx.add_action(- |workspace: &mut Workspace, _: &AddTabToDock, cx: &mut ViewContext<Workspace>| {- if let Some(active_item) = workspace.active_item(cx) {- let item_id = active_item.id();-- let from = workspace.active_pane();- let to = workspace.dock_pane();- if from.id() == to.id() {- return;- }+use serde::Deserialize;- use settings::Settings;+use std::rc::Rc;++use theme::ThemeSettings;++pub trait Panel: View {+ fn position(&self, cx: &WindowContext) -> DockPosition;+ fn position_is_valid(&self, position: DockPosition) -> bool;+ fn set_position(&mut self, position: DockPosition, cx: &mut ViewContext<Self>);+ fn default_size(&self, cx: &WindowContext) -> f32;+ fn icon_path(&self) -> &'static str;+ fn icon_tooltip(&self) -> String;+ fn icon_label(&self, _: &WindowContext) -> Option<String> {+ None+ }+ fn should_change_position_on_event(_: &Self::Event) -> bool;+ fn should_zoom_in_on_event(_: &Self::Event) -> bool;+ fn should_zoom_out_on_event(_: &Self::Event) -> bool;+ fn is_zoomed(&self, cx: &WindowContext) -> bool;+ fn set_zoomed(&mut self, zoomed: bool, cx: &mut ViewContext<Self>);+ fn set_active(&mut self, active: bool, cx: &mut ViewContext<Self>);+ fn should_activate_on_event(_: &Self::Event) -> bool;+ fn should_close_on_event(_: &Self::Event) -> bool;+ fn has_focus(&self, cx: &WindowContext) -> bool;+ fn is_focus_event(_: &Self::Event) -> bool;+}- let destination_index = to.read(cx).items_len() + 1;+pub trait PanelHandle {+ fn id(&self) -> usize;+ fn position(&self, cx: &WindowContext) -> DockPosition;+ fn position_is_valid(&self, position: DockPosition, cx: &WindowContext) -> bool;+ fn set_position(&self, position: DockPosition, cx: &mut WindowContext);+ fn is_zoomed(&self, cx: &WindowContext) -> bool;+ fn set_zoomed(&self, zoomed: bool, cx: &mut WindowContext);+ fn set_active(&self, active: bool, cx: &mut WindowContext);+ fn default_size(&self, cx: &WindowContext) -> f32;+ fn icon_path(&self, cx: &WindowContext) -> &'static str;+ fn icon_tooltip(&self, cx: &WindowContext) -> String;+ fn icon_label(&self, cx: &WindowContext) -> Option<String>;+ fn has_focus(&self, cx: &WindowContext) -> bool;+ fn as_any(&self) -> &AnyViewHandle;+}- Pane::move_item(- workspace,- from.clone(),- to.clone(),- item_id,- destination_index,- cx,- );- }- },- );- cx.add_action(- |workspace: &mut Workspace, _: &RemoveTabFromDock, cx: &mut ViewContext<Workspace>| {- if let Some(active_item) = workspace.active_item(cx) {- let item_id = active_item.id();-- let from = workspace.dock_pane();- let to = workspace- .last_active_center_pane- .as_ref()- .and_then(|pane| pane.upgrade(cx))- .unwrap_or_else(|| {- workspace- .panes- .first()- .expect("There must be a pane")- .clone()- });-- if from.id() == to.id() {- return;- }+impl<T> PanelHandle for ViewHandle<T>+where+ T: Panel,+{+ fn id(&self) -> usize {+ self.id()+ }- let destination_index = to.read(cx).items_len() + 1;+ fn position(&self, cx: &WindowContext) -> DockPosition {+ self.read(cx).position(cx)+ }- Pane::move_item(- workspace,- from.clone(),- to.clone(),- item_id,- destination_index,- cx,- );- }- },- );-}+ fn position_is_valid(&self, position: DockPosition, cx: &WindowContext) -> bool {+ self.read(cx).position_is_valid(position)+ }-#[derive(Copy, Clone, PartialEq, Eq, Debug)]-pub enum DockPosition {- Shown(DockAnchor),- Hidden(DockAnchor),-}+ fn set_position(&self, position: DockPosition, cx: &mut WindowContext) {+ self.update(cx, |this, cx| this.set_position(position, cx))+ }++ fn default_size(&self, cx: &WindowContext) -> f32 {+ self.read(cx).default_size(cx)+ }++ fn is_zoomed(&self, cx: &WindowContext) -> bool {+ self.read(cx).is_zoomed(cx)+ }++ fn set_zoomed(&self, zoomed: bool, cx: &mut WindowContext) {+ self.update(cx, |this, cx| this.set_zoomed(zoomed, cx))+ }++ fn set_active(&self, active: bool, cx: &mut WindowContext) {+ self.update(cx, |this, cx| this.set_active(active, cx))+ }++ fn icon_path(&self, cx: &WindowContext) -> &'static str {+ self.read(cx).icon_path()+ }++ fn icon_tooltip(&self, cx: &WindowContext) -> String {+ self.read(cx).icon_tooltip()+ }++ fn icon_label(&self, cx: &WindowContext) -> Option<String> {+ self.read(cx).icon_label(cx)+ }++ fn has_focus(&self, cx: &WindowContext) -> bool {+ self.read(cx).has_focus(cx)+ }-impl Default for DockPosition {- fn default() -> Self {- DockPosition::Hidden(Default::default())+ fn as_any(&self) -> &AnyViewHandle {+ self}}@@@ -321,356 -278,549 +321,356 @@@ impl Dock}}- pub fn focus_dock(workspace: &mut Workspace, _: &FocusDock, cx: &mut ViewContext<Workspace>) {- Self::set_dock_position(workspace, workspace.dock.position.show(), true, cx);+ pub fn active_panel(&self) -> Option<&Rc<dyn PanelHandle>> {+ let entry = self.active_entry()?;+ Some(&entry.panel)}- pub fn hide_dock(workspace: &mut Workspace, _: &HideDock, cx: &mut ViewContext<Workspace>) {- Self::set_dock_position(workspace, workspace.dock.position.hide(), true, cx);+ fn active_entry(&self) -> Option<&PanelEntry> {+ if self.is_open {+ self.panel_entries.get(self.active_panel_index)+ } else {+ None+ }}- pub fn move_dock(- workspace: &mut Workspace,- new_anchor: DockAnchor,- focus: bool,- cx: &mut ViewContext<Workspace>,- ) {- Self::set_dock_position(workspace, DockPosition::Shown(new_anchor), focus, cx);- }-- pub fn render(- &self,- theme: &Theme,- anchor: DockAnchor,- cx: &mut ViewContext<Workspace>,- ) -> Option<AnyElement<Workspace>> {- let style = &theme.workspace.dock;-- self.position- .is_visible()- .then(|| self.position.anchor())- .filter(|current_anchor| *current_anchor == anchor)- .map(|anchor| match anchor {- DockAnchor::Bottom | DockAnchor::Right => {- let mut panel_style = style.panel.clone();- let (resize_side, initial_size) = if anchor == DockAnchor::Bottom {- panel_style.border = Border {- top: true,- bottom: false,- left: false,- right: false,- ..panel_style.border- };+ pub fn zoomed_panel(&self, cx: &WindowContext) -> Option<Rc<dyn PanelHandle>> {+ let entry = self.active_entry()?;+ if entry.panel.is_zoomed(cx) {+ Some(entry.panel.clone())+ } else {+ None+ }+ }- (Side::Top, style.initial_size_bottom)- } else {- panel_style.border = Border {- top: false,- bottom: false,- left: true,- right: false,- ..panel_style.border- };- (Side::Left, style.initial_size_right)- };-- enum DockResizeHandle {}-- let resizable = ChildView::new(&self.pane, cx)- .contained()- .with_style(panel_style)- .with_resize_handle::<DockResizeHandle>(- resize_side as usize,- resize_side,- 4.,- self.panel_sizes- .get(&anchor)- .copied()- .unwrap_or(initial_size),- cx,- );-- let size = resizable.current_size();- cx.defer(move |workspace, _| {- workspace.dock.panel_sizes.insert(anchor, size);- });-- if anchor == DockAnchor::Right {- resizable.constrained().dynamically(|constraint, _, cx| {- SizeConstraint::new(- Vector2F::new(20., constraint.min.y()),- Vector2F::new(cx.window_size().x() * 0.8, constraint.max.y()),- )- })- } else {- resizable.constrained().dynamically(|constraint, _, cx| {- SizeConstraint::new(- Vector2F::new(constraint.min.x(), 50.),- Vector2F::new(constraint.max.x(), cx.window_size().y() * 0.8),- )- })- }- .into_any()- }- DockAnchor::Expanded => {- enum ExpandedDockWash {}- enum ExpandedDockPane {}- Stack::new()- .with_child(- // Render wash under the dock which when clicked hides it- MouseEventHandler::<ExpandedDockWash, _>::new(0, cx, |_, _| {- Empty::new()- .contained()- .with_background_color(style.wash_color)- })- .capture_all()- .on_down(MouseButton::Left, |_, workspace, cx| {- Dock::hide_dock(workspace, &Default::default(), cx)- })- .with_cursor_style(CursorStyle::Arrow),- )- .with_child(- MouseEventHandler::<ExpandedDockPane, _>::new(0, cx, |_state, cx| {- ChildView::new(&self.pane, cx)- })- // Make sure all events directly under the dock pane- // are captured- .capture_all()- .contained()- .with_style(style.maximized),- )- .into_any()- }- })+ pub fn panel_size(&self, panel: &dyn PanelHandle) -> Option<f32> {+ self.panel_entries+ .iter()+ .find(|entry| entry.panel.id() == panel.id())+ .map(|entry| entry.size)+ }++ pub fn resize_panel(&mut self, panel: &dyn PanelHandle, size: f32) {+ let entry = self+ .panel_entries+ .iter_mut()+ .find(|entry| entry.panel.id() == panel.id());+ if let Some(entry) = entry {+ entry.size = size;+ }+ }++ pub fn active_panel_size(&self) -> Option<f32> {+ if self.is_open {+ self.panel_entries+ .get(self.active_panel_index)+ .map(|entry| entry.size)+ } else {+ None+ }+ }++ pub fn resize_active_panel(&mut self, size: f32, cx: &mut ViewContext<Self>) {+ if let Some(entry) = self.panel_entries.get_mut(self.active_panel_index) {+ entry.size = size;+ cx.notify();+ }}- pub fn position(&self) -> DockPosition {- self.position+ pub fn render_placeholder(&self, cx: &WindowContext) -> AnyElement<Workspace> {+ if let Some(active_entry) = self.active_entry() {- let style = &cx.global::<Settings>().theme.workspace.dock;++ let style = &settings::get::<ThemeSettings>(cx).theme.workspace.dock;+ Empty::new()+ .into_any()+ .contained()+ .with_style(style.container)+ .resizable(+ self.position.to_resize_handle_side(),+ active_entry.size,+ |_, _, _| {},+ )+ .into_any()+ } else {+ Empty::new().into_any()+ }}}-#[cfg(test)]-mod tests {- use std::{- ops::{Deref, DerefMut},- path::PathBuf,- sync::Arc,- };+impl Entity for Dock {+ type Event = ();+}- use gpui::{AppContext, BorrowWindowContext, TestAppContext, ViewContext, WindowContext};- use project::{FakeFs, Project};+impl View for Dock {+ fn ui_name() -> &'static str {+ "Dock"+ }- use super::*;- use crate::{- dock,- item::{self, test::TestItem},- persistence::model::{- SerializedItem, SerializedPane, SerializedPaneGroup, SerializedWorkspace,- },- register_deserializable_item,- sidebar::Sidebar,- tests::init_test,- AppState, ItemHandle, Workspace,- };-- pub fn default_item_factory(- _workspace: &mut Workspace,- cx: &mut ViewContext<Workspace>,- ) -> Option<Box<dyn ItemHandle>> {- Some(Box::new(cx.add_view(|_| TestItem::new())))- }-- #[gpui::test]- async fn test_dock_workspace_infinite_loop(cx: &mut TestAppContext) {- init_test(cx);-- cx.update(|cx| {- register_deserializable_item::<item::test::TestItem>(cx);- });+ fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {+ if let Some(active_entry) = self.active_entry() {- let style = &cx.global::<Settings>().theme.workspace.dock;++ let style = &settings::get::<ThemeSettings>(cx).theme.workspace.dock;+ ChildView::new(active_entry.panel.as_any(), cx)+ .contained()+ .with_style(style.container)+ .resizable(+ self.position.to_resize_handle_side(),+ active_entry.size,+ |dock: &mut Self, size, cx| dock.resize_active_panel(size, cx),+ )+ .into_any()+ } else {+ Empty::new().into_any()+ }+ }+}- let serialized_workspace = SerializedWorkspace {- id: 0,- location: Vec::<PathBuf>::new().into(),- dock_position: dock::DockPosition::Shown(DockAnchor::Expanded),- center_group: SerializedPaneGroup::Pane(SerializedPane {- active: false,- children: vec![],- }),- dock_pane: SerializedPane {- active: true,- children: vec![SerializedItem {- active: true,- item_id: 0,- kind: "TestItem".into(),- }],- },- left_sidebar_open: false,- bounds: Default::default(),- display: Default::default(),+impl PanelButtons {+ pub fn new(+ dock: ViewHandle<Dock>,+ workspace: WeakViewHandle<Workspace>,+ cx: &mut ViewContext<Self>,+ ) -> Self {+ cx.observe(&dock, |_, _, cx| cx.notify()).detach();+ Self { dock, workspace }+ }+}++impl Entity for PanelButtons {+ type Event = ();+}++impl View for PanelButtons {+ fn ui_name() -> &'static str {+ "PanelButtons"+ }++ fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {- let theme = &cx.global::<Settings>().theme;++ let theme = &settings::get::<ThemeSettings>(cx).theme;+ let tooltip_style = theme.tooltip.clone();+ let theme = &theme.workspace.status_bar.panel_buttons;+ let button_style = theme.button.clone();+ let dock = self.dock.read(cx);+ let active_ix = dock.active_panel_index;+ let is_open = dock.is_open;+ let dock_position = dock.position;+ let group_style = match dock_position {+ DockPosition::Left => theme.group_left,+ DockPosition::Bottom => theme.group_bottom,+ DockPosition::Right => theme.group_right,+ };+ let menu_corner = match dock_position {+ DockPosition::Left => AnchorCorner::BottomLeft,+ DockPosition::Bottom | DockPosition::Right => AnchorCorner::BottomRight,};- let fs = FakeFs::new(cx.background());- let project = Project::test(fs, [], cx).await;-- let (_, _workspace) = cx.add_window(|cx| {- Workspace::new(- 0,- project.clone(),- Arc::new(AppState {- languages: project.read(cx).languages().clone(),- client: project.read(cx).client(),- user_store: project.read(cx).user_store(),- fs: project.read(cx).fs().clone(),- build_window_options: |_, _, _| Default::default(),- initialize_workspace: |_, _, _| {},- dock_default_item_factory: default_item_factory,- background_actions: || &[],- }),- cx,- )- });+ let panels = dock+ .panel_entries+ .iter()+ .map(|item| (item.panel.clone(), item.context_menu.clone()))+ .collect::<Vec<_>>();+ Flex::row()+ .with_children(+ panels+ .into_iter()+ .enumerate()+ .map(|(ix, (view, context_menu))| {+ let action = TogglePanel {+ dock_position,+ panel_index: ix,+ };- cx.update(|cx| {- Workspace::load_workspace(_workspace.downgrade(), serialized_workspace, Vec::new(), cx)- })- .await;-- cx.foreground().run_until_parked();- //Should terminate- }-- #[gpui::test]- async fn test_dock_hides_when_pane_empty(cx: &mut TestAppContext) {- let mut cx = DockTestContext::new(cx).await;-- // Closing the last item in the dock hides the dock- cx.move_dock(DockAnchor::Right);- let old_items = cx.dock_items();- assert!(!old_items.is_empty());- cx.close_dock_items().await;- cx.assert_dock_position(DockPosition::Hidden(DockAnchor::Right));-- // Reopening the dock adds a new item- cx.move_dock(DockAnchor::Right);- let new_items = cx.dock_items();- assert!(!new_items.is_empty());- assert!(new_items- .into_iter()- .all(|new_item| !old_items.contains(&new_item)));- }-- #[gpui::test]- async fn test_dock_panel_collisions(cx: &mut TestAppContext) {- let mut cx = DockTestContext::new(cx).await;-- // Dock closes when expanded for either panel- cx.move_dock(DockAnchor::Expanded);- cx.open_sidebar(SidebarSide::Left);- cx.assert_dock_position(DockPosition::Hidden(DockAnchor::Expanded));- cx.close_sidebar(SidebarSide::Left);- cx.move_dock(DockAnchor::Expanded);- cx.open_sidebar(SidebarSide::Right);- cx.assert_dock_position(DockPosition::Hidden(DockAnchor::Expanded));-- // Dock closes in the right position if the right sidebar is opened- cx.move_dock(DockAnchor::Right);- cx.open_sidebar(SidebarSide::Left);- cx.assert_dock_position(DockPosition::Shown(DockAnchor::Right));- cx.open_sidebar(SidebarSide::Right);- cx.assert_dock_position(DockPosition::Hidden(DockAnchor::Right));- cx.close_sidebar(SidebarSide::Right);-- // Dock in bottom position ignores sidebars- cx.move_dock(DockAnchor::Bottom);- cx.open_sidebar(SidebarSide::Left);- cx.open_sidebar(SidebarSide::Right);- cx.assert_dock_position(DockPosition::Shown(DockAnchor::Bottom));-- // Opening the dock in the right position closes the right sidebar- cx.move_dock(DockAnchor::Right);- cx.assert_sidebar_closed(SidebarSide::Right);- }-- #[gpui::test]- async fn test_focusing_panes_shows_and_hides_dock(cx: &mut TestAppContext) {- let mut cx = DockTestContext::new(cx).await;-- // Focusing an item not in the dock when expanded hides the dock- let center_item = cx.add_item_to_center_pane();- cx.move_dock(DockAnchor::Expanded);- let dock_item = cx- .dock_items()- .get(0)- .cloned()- .expect("Dock should have an item at this point");- center_item.update(&mut cx, |_, cx| cx.focus_self());- cx.assert_dock_position(DockPosition::Hidden(DockAnchor::Expanded));-- // Focusing an item not in the dock when not expanded, leaves the dock open but inactive- cx.move_dock(DockAnchor::Right);- center_item.update(&mut cx, |_, cx| cx.focus_self());- cx.assert_dock_position(DockPosition::Shown(DockAnchor::Right));- cx.assert_dock_pane_inactive();- cx.assert_workspace_pane_active();-- // Focusing an item in the dock activates it's pane- dock_item.update(&mut cx, |_, cx| cx.focus_self());- cx.assert_dock_position(DockPosition::Shown(DockAnchor::Right));- cx.assert_dock_pane_active();- cx.assert_workspace_pane_inactive();- }-- #[gpui::test]- async fn test_toggle_dock_focus(cx: &mut TestAppContext) {- let mut cx = DockTestContext::new(cx).await;-- cx.move_dock(DockAnchor::Right);- cx.assert_dock_pane_active();- cx.hide_dock();- cx.move_dock(DockAnchor::Right);- cx.assert_dock_pane_active();- }-- #[gpui::test]- async fn test_activate_next_and_prev_pane(cx: &mut TestAppContext) {- let mut cx = DockTestContext::new(cx).await;-- cx.move_dock(DockAnchor::Right);- cx.assert_dock_pane_active();-- cx.update_workspace(|workspace, cx| workspace.activate_next_pane(cx));- cx.assert_dock_pane_active();-- cx.update_workspace(|workspace, cx| workspace.activate_previous_pane(cx));- cx.assert_dock_pane_active();- }-- struct DockTestContext<'a> {- pub cx: &'a mut TestAppContext,- pub window_id: usize,- pub workspace: ViewHandle<Workspace>,- }-- impl<'a> DockTestContext<'a> {- pub async fn new(cx: &'a mut TestAppContext) -> DockTestContext<'a> {- init_test(cx);- let fs = FakeFs::new(cx.background());-- cx.update(|cx| init(cx));- let project = Project::test(fs, [], cx).await;- let (window_id, workspace) = cx.add_window(|cx| {- Workspace::new(- 0,- project.clone(),- Arc::new(AppState {- languages: project.read(cx).languages().clone(),- client: project.read(cx).client(),- user_store: project.read(cx).user_store(),- fs: project.read(cx).fs().clone(),- build_window_options: |_, _, _| Default::default(),- initialize_workspace: |_, _, _| {},- dock_default_item_factory: default_item_factory,- background_actions: || &[],+ Stack::new()+ .with_child(+ MouseEventHandler::<Self, _>::new(ix, cx, |state, cx| {+ let is_active = is_open && ix == active_ix;+ let style = button_style.style_for(state, is_active);+ Flex::row()+ .with_child(+ Svg::new(view.icon_path(cx))+ .with_color(style.icon_color)+ .constrained()+ .with_width(style.icon_size)+ .aligned(),+ )+ .with_children(if let Some(label) = view.icon_label(cx) {+ Some(+ Label::new(label, style.label.text.clone())+ .contained()+ .with_style(style.label.container)+ .aligned(),+ )+ } else {+ None+ })+ .constrained()+ .with_height(style.icon_size)+ .contained()+ .with_style(style.container)+ })+ .with_cursor_style(CursorStyle::PointingHand)+ .on_click(MouseButton::Left, {+ let action = action.clone();+ move |_, this, cx| {+ if let Some(workspace) = this.workspace.upgrade(cx) {+ let action = action.clone();+ cx.window_context().defer(move |cx| {+ workspace.update(cx, |workspace, cx| {+ workspace.toggle_panel(&action, cx)+ });+ });+ }+ }+ })+ .on_click(MouseButton::Right, {+ let view = view.clone();+ let menu = context_menu.clone();+ move |_, _, cx| {+ const POSITIONS: [DockPosition; 3] = [+ DockPosition::Left,+ DockPosition::Right,+ DockPosition::Bottom,+ ];++ menu.update(cx, |menu, cx| {+ let items = POSITIONS+ .into_iter()+ .filter(|position| {+ *position != dock_position+ && view.position_is_valid(*position, cx)+ })+ .map(|position| {+ let view = view.clone();+ ContextMenuItem::handler(+ format!("Dock {}", position.to_label()),+ move |cx| view.set_position(position, cx),+ )+ })+ .collect();+ menu.show(Default::default(), menu_corner, items, cx);+ })+ }+ })+ .with_tooltip::<Self>(+ ix,+ view.icon_tooltip(cx),+ Some(Box::new(action)),+ tooltip_style.clone(),+ cx,+ ),+ )+ .with_child(ChildView::new(&context_menu, cx))}),- cx,- )- });-- workspace.update(cx, |workspace, cx| {- let left_panel = cx.add_view(|_| TestItem::new());- workspace.left_sidebar().update(cx, |sidebar, cx| {- sidebar.add_item(- "icons/folder_tree_16.svg",- "Left Test Panel".to_string(),- left_panel.clone(),- cx,- );- });-- let right_panel = cx.add_view(|_| TestItem::new());- workspace.right_sidebar().update(cx, |sidebar, cx| {- sidebar.add_item(- "icons/folder_tree_16.svg",- "Right Test Panel".to_string(),- right_panel.clone(),- cx,- );- });- });-- Self {- cx,- window_id,- workspace,- }- }+ )+ .contained()+ .with_style(group_style)+ .into_any()+ }+}- pub fn workspace<F, T>(&self, read: F) -> T- where- F: FnOnce(&Workspace, &ViewContext<Workspace>) -> T,- {- self.workspace.read_with(self.cx, read)- }+impl StatusItemView for PanelButtons {+ fn set_active_pane_item(+ &mut self,+ _: Option<&dyn crate::ItemHandle>,+ _: &mut ViewContext<Self>,+ ) {+ }+}- pub fn update_workspace<F, T>(&mut self, update: F) -> T- where- F: FnOnce(&mut Workspace, &mut ViewContext<Workspace>) -> T,- {- self.workspace.update(self.cx, update)- }+#[cfg(test)]+pub(crate) mod test {+ use super::*;- use gpui::Entity;++ use gpui::{ViewContext, WindowContext};- pub fn sidebar<F, T>(&self, sidebar_side: SidebarSide, read: F) -> T- where- F: FnOnce(&Sidebar, &AppContext) -> T,- {- self.workspace(|workspace, cx| {- let sidebar = match sidebar_side {- SidebarSide::Left => workspace.left_sidebar(),- SidebarSide::Right => workspace.right_sidebar(),- }- .read(cx);-- read(sidebar, cx)- })- }-- pub fn center_pane_handle(&self) -> ViewHandle<Pane> {- self.workspace(|workspace, cx| {- workspace- .last_active_center_pane- .clone()- .and_then(|pane| pane.upgrade(cx))- .unwrap_or_else(|| workspace.center.panes()[0].clone())- })- }-- pub fn add_item_to_center_pane(&mut self) -> ViewHandle<TestItem> {- self.update_workspace(|workspace, cx| {- let item = cx.add_view(|_| TestItem::new());- let pane = workspace- .last_active_center_pane- .clone()- .and_then(|pane| pane.upgrade(cx))- .unwrap_or_else(|| workspace.center.panes()[0].clone());- Pane::add_item(- workspace,- &pane,- Box::new(item.clone()),- true,- true,- None,- cx,- );- item- })- }-- pub fn dock_pane<F, T>(&self, read: F) -> T- where- F: FnOnce(&Pane, &AppContext) -> T,- {- self.workspace(|workspace, cx| {- let dock_pane = workspace.dock_pane().read(cx);- read(dock_pane, cx)- })+ pub enum TestPanelEvent {+ PositionChanged,+ Activated,+ Closed,+ }++ pub struct TestPanel {+ pub position: DockPosition,+ }++ impl Entity for TestPanel {+ type Event = TestPanelEvent;+ }++ impl View for TestPanel {+ fn ui_name() -> &'static str {+ "TestPanel"}- pub fn move_dock(&mut self, anchor: DockAnchor) {- self.update_workspace(|workspace, cx| Dock::move_dock(workspace, anchor, true, cx));+ fn render(&mut self, _: &mut ViewContext<'_, '_, Self>) -> AnyElement<Self> {+ Empty::new().into_any()}+ }- pub fn hide_dock(&mut self) {- self.cx.dispatch_action(self.window_id, HideDock);+ impl Panel for TestPanel {+ fn position(&self, _: &gpui::WindowContext) -> super::DockPosition {+ self.position}- pub fn open_sidebar(&mut self, sidebar_side: SidebarSide) {- if !self.sidebar(sidebar_side, |sidebar, _| sidebar.is_open()) {- self.update_workspace(|workspace, cx| workspace.toggle_sidebar(sidebar_side, cx));- }+ fn position_is_valid(&self, _: super::DockPosition) -> bool {+ true}- pub fn close_sidebar(&mut self, sidebar_side: SidebarSide) {- if self.sidebar(sidebar_side, |sidebar, _| sidebar.is_open()) {- self.update_workspace(|workspace, cx| workspace.toggle_sidebar(sidebar_side, cx));- }+ fn set_position(&mut self, position: DockPosition, cx: &mut ViewContext<Self>) {+ self.position = position;+ cx.emit(TestPanelEvent::PositionChanged);}- pub fn dock_items(&self) -> Vec<ViewHandle<TestItem>> {- self.dock_pane(|pane, cx| {- pane.items()- .map(|item| {- item.act_as::<TestItem>(cx)- .expect("Dock Test Context uses TestItems in the dock")- })- .collect()- })+ fn is_zoomed(&self, _: &WindowContext) -> bool {+ unimplemented!()}- pub async fn close_dock_items(&mut self) {- self.update_workspace(|workspace, cx| {- Pane::close_items(workspace, workspace.dock_pane().clone(), cx, |_| true)- })- .await- .expect("Could not close dock items")+ fn set_zoomed(&mut self, _zoomed: bool, _cx: &mut ViewContext<Self>) {+ unimplemented!()}- pub fn assert_dock_position(&self, expected_position: DockPosition) {- self.workspace(|workspace, _| assert_eq!(workspace.dock.position, expected_position));+ fn set_active(&mut self, _active: bool, _cx: &mut ViewContext<Self>) {+ unimplemented!()}- pub fn assert_sidebar_closed(&self, sidebar_side: SidebarSide) {- assert!(!self.sidebar(sidebar_side, |sidebar, _| sidebar.is_open()));+ fn default_size(&self, _: &WindowContext) -> f32 {+ match self.position.axis() {+ Axis::Horizontal => 300.,+ Axis::Vertical => 200.,+ }}- pub fn assert_workspace_pane_active(&self) {- assert!(self- .center_pane_handle()- .read_with(self.cx, |pane, _| pane.is_active()));+ fn icon_path(&self) -> &'static str {+ "icons/test_panel.svg"}- pub fn assert_workspace_pane_inactive(&self) {- assert!(!self- .center_pane_handle()- .read_with(self.cx, |pane, _| pane.is_active()));+ fn icon_tooltip(&self) -> String {+ "Test Panel".into()}- pub fn assert_dock_pane_active(&self) {- assert!(self.dock_pane(|pane, _| pane.is_active()))+ fn should_change_position_on_event(event: &Self::Event) -> bool {+ matches!(event, TestPanelEvent::PositionChanged)}- pub fn assert_dock_pane_inactive(&self) {- assert!(!self.dock_pane(|pane, _| pane.is_active()))+ fn should_zoom_in_on_event(_: &Self::Event) -> bool {+ false}- }- impl<'a> Deref for DockTestContext<'a> {- type Target = gpui::TestAppContext;+ fn should_zoom_out_on_event(_: &Self::Event) -> bool {+ false+ }- fn deref(&self) -> &Self::Target {- self.cx+ fn should_activate_on_event(event: &Self::Event) -> bool {+ matches!(event, TestPanelEvent::Activated)}- }- impl<'a> DerefMut for DockTestContext<'a> {- fn deref_mut(&mut self) -> &mut Self::Target {- &mut self.cx+ fn should_close_on_event(event: &Self::Event) -> bool {+ matches!(event, TestPanelEvent::Closed)}- }- impl BorrowWindowContext for DockTestContext<'_> {- fn read_with<T, F: FnOnce(&WindowContext) -> T>(&self, window_id: usize, f: F) -> T {- BorrowWindowContext::read_with(self.cx, window_id, f)+ fn has_focus(&self, _cx: &WindowContext) -> bool {+ unimplemented!()}- fn update<T, F: FnOnce(&mut WindowContext) -> T>(&mut self, window_id: usize, f: F) -> T {- BorrowWindowContext::update(self.cx, window_id, f)+ fn is_focus_event(_: &Self::Event) -> bool {+ unimplemented!()}}}diff --cc crates/workspace/src/pane.rsindex 681a7eda274,a196133f3ad..5f698d89a5c--- a/crates/workspace/src/pane.rs+++ b/crates/workspace/src/pane.rs@@@ -2,8 -2,11 +2,8 @@@ mod dragged_item_receiveruse super::{ItemHandle, SplitDirection};use crate::{- item::WeakItemHandle, toolbar::Toolbar, Item, NewFile, NewSearch, NewTerminal, ToggleZoom,- Workspace,- dock::{icon_for_dock_anchor, AnchorDockBottom, AnchorDockRight, Dock, ExpandDock},- item::WeakItemHandle,- toolbar::Toolbar,- AutosaveSetting, DockAnchor, Item, NewFile, NewSearch, NewTerminal, Workspace,- WorkspaceSettings,++ item::WeakItemHandle, toolbar::Toolbar, AutosaveSetting, Item, NewFile, NewSearch, NewTerminal,++ ToggleZoom, Workspace, WorkspaceSettings,};use anyhow::{anyhow, Result};use collections::{HashMap, HashSet, VecDeque};@@@ -27,9 -30,18 +27,18 @@@ use gpui::};use project::{Project, ProjectEntryId, ProjectPath};use serde::Deserialize;- use settings::{Autosave, Settings};- use std::{any::Any, cell::RefCell, cmp, mem, path::Path, rc::Rc};- use theme::Theme;+ use std::{+ any::Any,+ cell::RefCell,+ cmp, mem,+ path::Path,+ rc::Rc,+ sync::{+ atomic::{AtomicUsize, Ordering},+ Arc,+ },+ };-use theme::Theme;++use theme::{Theme, ThemeSettings};use util::ResultExt;#[derive(Clone, Deserialize, PartialEq)]@@@ -191,11 -200,12 +203,12 @@@ impl Default for NavigationModepub struct NavigationEntry {pub item: Rc<dyn WeakItemHandle>,pub data: Option<Box<dyn Any>>,+ pub timestamp: usize,}-struct DraggedItem {- item: Box<dyn ItemHandle>,- pane: WeakViewHandle<Pane>,+pub struct DraggedItem {+ pub handle: Box<dyn ItemHandle>,+ pub pane: WeakViewHandle<Pane>,}pub enum ReorderBehavior {@@@ -227,7 -238,9 +240,8 @@@ impl TabBarContextMenuimpl Pane {pub fn new(workspace: WeakViewHandle<Workspace>,- docked: Option<DockAnchor>,background_actions: BackgroundActions,+ next_timestamp: Arc<AtomicUsize>,cx: &mut ViewContext<Self>,) -> Self {let pane_view_id = cx.view_id();@@@ -752,12 -733,23 +771,16 @@@}pub fn close_inactive_items(- workspace: &mut Workspace,+ &mut self,_: &CloseInactiveItems,- cx: &mut ViewContext<Workspace>,+ cx: &mut ViewContext<Self>,) -> Option<Task<Result<()>>> {- let pane_handle = workspace.active_pane().clone();- let pane = pane_handle.read(cx);-- let active_item_id = pane.items.get(pane.active_item_index)?.id();-- let task = Self::close_items(workspace, pane_handle, cx, move |item_id| {- item_id != active_item_id- });++ if self.items.is_empty() {++ return None;++ }+- Some(cx.foreground().spawn(async move {- task.await?;- Ok(())- }))+ let active_item_id = self.items[self.active_item_index].id();+ Some(self.close_items(cx, move |item_id| item_id != active_item_id))}pub fn close_clean_items(@@@ -774,12 -777,20 +797,15 @@@}pub fn close_items_to_the_left(- workspace: &mut Workspace,+ &mut self,_: &CloseItemsToTheLeft,- cx: &mut ViewContext<Workspace>,+ cx: &mut ViewContext<Self>,) -> Option<Task<Result<()>>> {- let pane_handle = workspace.active_pane().clone();- let pane = pane_handle.read(cx);- let active_item_id = pane.items.get(pane.active_item_index)?.id();-- let task = Self::close_items_to_the_left_by_id(workspace, pane_handle, active_item_id, cx);-- Some(cx.foreground().spawn(async move {- task.await?;- Ok(())- }))++ if self.items.is_empty() {++ return None;++ }+ let active_item_id = self.items[self.active_item_index].id();+ Some(self.close_items_to_the_left_by_id(active_item_id, cx))}pub fn close_items_to_the_left_by_id(@@@ -796,12 -817,20 +822,15 @@@}pub fn close_items_to_the_right(- workspace: &mut Workspace,+ &mut self,_: &CloseItemsToTheRight,- cx: &mut ViewContext<Workspace>,+ cx: &mut ViewContext<Self>,) -> Option<Task<Result<()>>> {- let pane_handle = workspace.active_pane().clone();- let pane = pane_handle.read(cx);- let active_item_id = pane.items.get(pane.active_item_index)?.id();-- let task = Self::close_items_to_the_right_by_id(workspace, pane_handle, active_item_id, cx);-- Some(cx.foreground().spawn(async move {- task.await?;- Ok(())- }))++ if self.items.is_empty() {++ return None;++ }+ let active_item_id = self.items[self.active_item_index].id();+ Some(self.close_items_to_the_right_by_id(active_item_id, cx))}pub fn close_items_to_the_right_by_id(@@@ -1520,40 -1638,77 +1568,40 @@@.into_any()}- fn render_tab_bar_buttons(- &mut self,- theme: &Theme,- cx: &mut ViewContext<Self>,- ) -> AnyElement<Self> {- Flex::row()- // New menu- .with_child(render_tab_bar_button(- 0,- "icons/plus_12.svg",- cx,- |pane, cx| pane.deploy_new_menu(cx),- self.tab_bar_context_menu- .handle_if_kind(TabBarContextMenuKind::New),- ))+ pub fn render_tab_bar_button<F: 'static + Fn(&mut Pane, &mut EventContext<Pane>)>(+ index: usize,+ icon: &'static str,+ cx: &mut ViewContext<Pane>,+ on_click: F,+ context_menu: Option<ViewHandle<ContextMenu>>,+ ) -> AnyElement<Pane> {+ enum TabBarButton {}++ Stack::new().with_child(- self.docked- .map(|anchor| {- // Add the dock menu button if this pane is a dock- let dock_icon = icon_for_dock_anchor(anchor);-- render_tab_bar_button(- 1,- dock_icon,- cx,- |pane, cx| pane.deploy_dock_menu(cx),- self.tab_bar_context_menu- .handle_if_kind(TabBarContextMenuKind::Dock),- )- })- .unwrap_or_else(|| {- // Add the split menu if this pane is not a dock- render_tab_bar_button(- 2,- "icons/split_12.svg",- cx,- |pane, cx| pane.deploy_split_menu(cx),- self.tab_bar_context_menu- .handle_if_kind(TabBarContextMenuKind::Split),- )- }),+ MouseEventHandler::<TabBarButton, _>::new(index, cx, |mouse_state, cx| {- let theme = &cx.global::<Settings>().theme.workspace.tab_bar;++ let theme = &settings::get::<ThemeSettings>(cx).theme.workspace.tab_bar;+ let style = theme.pane_button.style_for(mouse_state, false);+ Svg::new(icon)+ .with_color(style.color)+ .constrained()+ .with_width(style.icon_width)+ .aligned()+ .constrained()+ .with_width(style.button_width)+ .with_height(style.button_width)+ })+ .with_cursor_style(CursorStyle::PointingHand)+ .on_click(MouseButton::Left, move |_, pane, cx| on_click(pane, cx)),+ )+ .with_children(+ context_menu.map(|menu| ChildView::new(&menu, cx).aligned().bottom().right()),)- // Add the close dock button if this pane is a dock- .with_children(self.docked.map(|_| {- render_tab_bar_button(- 3,- "icons/x_mark_8.svg",- cx,- |this, cx| {- if let Some(workspace) = this.workspace.upgrade(cx) {- cx.window_context().defer(move |cx| {- workspace.update(cx, |workspace, cx| {- Dock::hide_dock(workspace, &Default::default(), cx)- })- });- }- },- None,- )- }))- .contained()- .with_style(theme.workspace.tab_bar.pane_button_container).flex(1., false)- .into_any()+ .into_any_named("tab bar button")}- fn render_blank_pane(- &mut self,- theme: &Theme,- _cx: &mut ViewContext<Self>,- ) -> AnyElement<Self> {+ fn render_blank_pane(&self, theme: &Theme, _cx: &mut ViewContext<Self>) -> AnyElement<Self> {let background = theme.workspace.background;Empty::new().contained()@@@ -1659,9 -1801,9 +1707,9 @@@ impl View for Pane.into_any()} else {enum EmptyPane {}- let theme = cx.global::<Settings>().theme.clone();+ let theme = theme::current(cx).clone();- dragged_item_receiver::<EmptyPane, _, _>(0, 0, false, None, cx, |_, cx| {+ dragged_item_receiver::<EmptyPane, _, _>(self, 0, 0, false, None, cx, |_, cx| {self.render_blank_pane(&theme, cx)}).on_down(MouseButton::Left, |_, _, cx| {diff --cc crates/workspace/src/pane/dragged_item_receiver.rsindex 003cf1e4efc,532e6bff5c0..bb5d3a2464e--- a/crates/workspace/src/pane/dragged_item_receiver.rs+++ b/crates/workspace/src/pane/dragged_item_receiver.rs@@@ -8,14 -10,8 +10,9 @@@ use gpui::AppContext, Element, EventContext, MouseState, Quad, View, ViewContext, WeakViewHandle,};use project::ProjectEntryId;- use settings::Settings;-- use crate::{Pane, SplitDirection, Workspace};-- use super::DraggedItem;pub fn dragged_item_receiver<Tag, D, F>(+ pane: &Pane,region_id: usize,drop_index: usize,allow_same_pane: bool,diff --cc crates/workspace/src/persistence.rsindex 9cf13af681d,4ffae0d7e3c..fbefd3984ef--- a/crates/workspace/src/persistence.rs+++ b/crates/workspace/src/persistence.rs@@@ -497,10 -497,10 +497,8 @@@ impl WorkspaceDb#[cfg(test)]mod tests {-- use db::open_test_db;-use super::*;- use crate::DockAnchor;+ use db::open_test_db;- use std::sync::Arc;#[gpui::test]async fn test_next_id_stability() {diff --cc crates/workspace/src/persistence/model.rsindex bc10c931bb5,b73dfa495d4..fe7735753f7--- a/crates/workspace/src/persistence/model.rs+++ b/crates/workspace/src/persistence/model.rs@@@ -1,4 -1,7 +1,4 @@@- use crate::{ItemDeserializers, Member, Pane, PaneAxis, Workspace, WorkspaceId};-use crate::{- dock::DockPosition, item::ItemHandle, DockAnchor, ItemDeserializers, Member, Pane, PaneAxis,- Workspace, WorkspaceId,-};++use crate::{item::ItemHandle, ItemDeserializers, Member, Pane, PaneAxis, Workspace, WorkspaceId};use anyhow::{anyhow, Context, Result};use async_recursion::async_recursion;use db::sqlez::{@@@ -330,40 -287,64 +340,3 @@@ impl Column for SerializedItem))}}--impl StaticColumnCount for DockPosition {- fn column_count() -> usize {- 2- }-}-impl Bind for DockPosition {- fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {- let next_index = statement.bind(self.is_visible(), start_index)?;- statement.bind(self.anchor(), next_index)- }-}--impl Column for DockPosition {- fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {- let (visible, next_index) = bool::column(statement, start_index)?;- let (dock_anchor, next_index) = DockAnchor::column(statement, next_index)?;- let position = if visible {- DockPosition::Shown(dock_anchor)- } else {- DockPosition::Hidden(dock_anchor)- };- Ok((position, next_index))- }-}----#[cfg(test)]--mod tests {- use super::WorkspaceLocation;- use crate::DockAnchor;-- use db::sqlez::connection::Connection;-- // use super::WorkspaceLocation;---- #[test]-- fn test_workspace_round_trips() {- let _db = Connection::open_memory(Some("workspace_id_round_trips"));- let db = Connection::open_memory(Some("workspace_id_round_trips"));--- todo!();- // db.exec(indoc::indoc! {"- // CREATE TABLE workspace_id_test(- // workspace_id INTEGER,- // dock_anchor TEXT- // );"})- // .unwrap()()- // .unwrap();- db.exec(indoc::indoc! {"- CREATE TABLE workspace_id_test(- workspace_id INTEGER,- dock_anchor TEXT- );"})- .unwrap()()- .unwrap();--- // let workspace_id: WorkspaceLocation = WorkspaceLocation::from(&["\test2", "\test1"]);- let workspace_id: WorkspaceLocation = WorkspaceLocation::from(&["\test2", "\test1"]);--- // db.exec_bound("INSERT INTO workspace_id_test(workspace_id, dock_anchor) VALUES (?,?)")- // .unwrap()((&workspace_id, DockAnchor::Bottom))- // .unwrap();- db.exec_bound("INSERT INTO workspace_id_test(workspace_id, dock_anchor) VALUES (?,?)")- .unwrap()((&workspace_id, DockAnchor::Bottom))- .unwrap();--- // assert_eq!(- // db.select_row("SELECT workspace_id, dock_anchor FROM workspace_id_test LIMIT 1")- // .unwrap()()- // .unwrap(),- // Some((- // WorkspaceLocation::from(&["\test1", "\test2"]),- // DockAnchor::Bottom- // ))- // );- assert_eq!(- db.select_row("SELECT workspace_id, dock_anchor FROM workspace_id_test LIMIT 1")- .unwrap()()- .unwrap(),- Some((- WorkspaceLocation::from(&["\test1", "\test2"]),- DockAnchor::Bottom- ))- );-- }--}diff --cc crates/workspace/src/workspace.rsindex dfb8560843a,8a5ce7a105d..78900eb0021--- a/crates/workspace/src/workspace.rs+++ b/crates/workspace/src/workspace.rs@@@ -10,8 -10,10 +10,9 @@@ pub mod pane_groupmod persistence;pub mod searchable;pub mod shared_screen;-pub mod sidebar;mod status_bar;mod toolbar;+ mod workspace_settings;use anyhow::{anyhow, Context, Result};use assets::Assets;@@@ -75,13 -77,14 +77,13 @@@ pub use persistence::use postage::prelude::Stream;use project::{Project, ProjectEntryId, ProjectPath, Worktree, WorktreeId};use serde::Deserialize;- use settings::{Autosave, Settings};use shared_screen::SharedScreen;-use sidebar::{Sidebar, SidebarButtons, SidebarSide, ToggleSidebarItem};use status_bar::StatusBar;pub use status_bar::StatusItemView;- use theme::{Theme, ThemeRegistry};+ use theme::Theme;pub use toolbar::{ToolbarItemLocation, ToolbarItemView};- use util::{paths, ResultExt};+ use util::{async_iife, paths, ResultExt};-pub use workspace_settings::{AutosaveSetting, DockAnchor, GitGutterSetting, WorkspaceSettings};++pub use workspace_settings::{AutosaveSetting, GitGutterSetting, WorkspaceSettings};lazy_static! {static ref ZED_WINDOW_SIZE: Option<Vector2F> = env::var("ZED_WINDOW_SIZE")@@@ -184,8 -185,14 +186,13 @@@ pub type WorkspaceId = i64impl_actions!(workspace, [ActivatePane]);+ pub fn init_settings(cx: &mut AppContext) {+ settings::register::<WorkspaceSettings>(cx);+ }+pub fn init(app_state: Arc<AppState>, cx: &mut AppContext) {+ init_settings(cx);pane::init(cx);- dock::init(cx);notifications::init(cx);cx.add_global_action({@@@ -233,8 -240,7 +240,7 @@@workspace.save_active_item(true, cx).detach_and_log_err(cx);},);- cx.add_action(Workspace::toggle_sidebar_item);+ cx.add_action(Workspace::toggle_panel);- cx.add_action(Workspace::focus_center);cx.add_action(|workspace: &mut Workspace, _: &ActivatePreviousPane, cx| {workspace.activate_previous_pane(cx)});@@@ -466,9 -479,10 +477,10 @@@ pub struct Workspaceleader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,database_id: WorkspaceId,app_state: Arc<AppState>,- _window_subscriptions: [Subscription; 3],+ _subscriptions: Vec<Subscription>,_apply_leader_updates: Task<Result<()>>,_observe_current_user: Task<Result<()>>,+ pane_history_timestamp: Arc<AtomicUsize>,}#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]@@@ -531,9 -552,17 +550,16 @@@ impl Workspace.detach();let weak_handle = cx.weak_handle();-- let center_pane =- cx.add_view(|cx| Pane::new(weak_handle.clone(), app_state.background_actions, cx));+ let pane_history_timestamp = Arc::new(AtomicUsize::new(0));++ let center_pane = cx.add_view(|cx| {+ Pane::new(+ weak_handle.clone(),- None,+ app_state.background_actions,+ pane_history_timestamp.clone(),+ cx,+ )+ });cx.subscribe(¢er_pane, Self::handle_pane_event).detach();cx.focus(¢er_pane);cx.emit(Event::PaneAdded(center_pane.clone()));@@@ -657,17 -683,12 +683,11 @@@_observe_current_user,_apply_leader_updates,leader_updates_tx,- _window_subscriptions: subscriptions,+ _subscriptions: subscriptions,+ pane_history_timestamp,};this.project_remote_id_changed(project.read(cx).remote_id(), cx);cx.defer(|this, cx| this.update_window_title(cx));-- if let Some(serialized_workspace) = serialized_workspace {- cx.defer(move |_, cx| {- Self::load_from_serialized_workspace(weak_handle, serialized_workspace, cx)- });- }--this}@@@ -731,7 -749,13 +748,9 @@@))});- let was_deserialized = serialized_workspace.is_some();+ let build_workspace = |cx: &mut ViewContext<Workspace>| {- let mut workspace =- Workspace::new(workspace_id, project_handle.clone(), app_state.clone(), cx);- (app_state.initialize_workspace)(&mut workspace, &app_state, cx);-- workspace++ Workspace::new(workspace_id, project_handle.clone(), app_state.clone(), cx)+ };let workspace = requesting_window_id.and_then(|window_id| {@@@ -796,50 -802,16 +797,27 @@@.1});+ (app_state.initialize_workspace)(+ workspace.downgrade(),- was_deserialized,++ serialized_workspace.is_some(),+ app_state.clone(),+ cx.clone(),+ )+ .await+ .log_err();++ cx.update_window(workspace.window_id(), |cx| cx.activate_window());+let workspace = workspace.downgrade();notify_if_database_failed(&workspace, &mut cx);-- // Call open path for each of the project paths- // (this will bring them to the front if they were in the serialized workspace)- debug_assert!(paths_to_open.len() == project_paths.len());- let tasks = paths_to_open- .iter()- .cloned()- .zip(project_paths.into_iter())- .map(|(abs_path, project_path)| {- let workspace = workspace.clone();- cx.spawn(|mut cx| {- let fs = app_state.fs.clone();- async move {- let project_path = project_path?;- if fs.is_file(&abs_path).await {- Some(- workspace- .update(&mut cx, |workspace, cx| {- workspace.open_path(project_path, None, true, cx)- })- .log_err()?- .await,- )- } else {- None- }- }- })- });-- let opened_items = futures::future::join_all(tasks.into_iter()).await;+ let opened_items = open_items(+ serialized_workspace,+ &workspace,+ project_paths,+ app_state,+ cx,+ )+ .await;(workspace, opened_items)})@@@ -1527,14 -1433,16 +1540,15 @@@cx.notify();}- pub fn focus_center(&mut self, _: &menu::Cancel, cx: &mut ViewContext<Self>) {- cx.focus_self();- cx.notify();- }-fn add_pane(&mut self, cx: &mut ViewContext<Self>) -> ViewHandle<Pane> {- let pane =- cx.add_view(|cx| Pane::new(self.weak_handle(), self.app_state.background_actions, cx));+ let pane = cx.add_view(|cx| {+ Pane::new(+ self.weak_handle(),- None,+ self.app_state.background_actions,+ self.pane_history_timestamp.clone(),+ cx,+ )+ });cx.subscribe(&pane, Self::handle_pane_event).detach();self.panes.push(pane.clone());cx.focus(&pane);@@@ -2659,84 -2556,124 +2673,119 @@@}}- fn load_from_serialized_workspace(+ pub(crate) fn load_workspace(workspace: WeakViewHandle<Workspace>,serialized_workspace: SerializedWorkspace,+ paths_to_open: Vec<Option<ProjectPath>>,cx: &mut AppContext,- ) {+ ) -> Task<Vec<Option<Result<Box<dyn ItemHandle>, anyhow::Error>>>> {cx.spawn(|mut cx| async move {- let (project, old_center_pane) = workspace.read_with(&cx, |workspace, _| {- (- workspace.project().clone(),- workspace.last_active_center_pane.clone(),- )- })?;+ let result = async_iife! {{- let (project, dock_pane_handle, old_center_pane) =++ let (project, old_center_pane) =+ workspace.read_with(&cx, |workspace, _| {+ (+ workspace.project().clone(),- workspace.dock_pane().downgrade(),+ workspace.last_active_center_pane.clone(),+ )+ })?;- // Traverse the splits tree and add to things- let center_group = serialized_workspace- .center_group- .deserialize(&project, serialized_workspace.id, &workspace, &mut cx)- .await;- let dock_items = serialized_workspace- .dock_pane- .deserialize_to(- &project,- &dock_pane_handle,- serialized_workspace.id,- &workspace,- &mut cx,- )- .await?;-+ let mut center_items = None;+ let mut center_group = None;+ // Traverse the splits tree and add to things+ if let Some((group, active_pane, items)) = serialized_workspace+ .center_group+ .deserialize(&project, serialized_workspace.id, &workspace, &mut cx)+ .await {+ center_items = Some(items);+ center_group = Some((group, active_pane))+ }- // Remove old panes from workspace panes list- workspace.update(&mut cx, |workspace, cx| {- if let Some((center_group, active_pane)) = center_group {- workspace.remove_panes(workspace.center.root.clone(), cx);+ let resulting_list = cx.read(|cx| {+ let mut opened_items = center_items+ .unwrap_or_default()+ .into_iter()- .chain(dock_items.into_iter())+ .filter_map(|item| {+ let item = item?;+ let project_path = item.project_path(cx)?;+ Some((project_path, item))+ })+ .collect::<HashMap<_, _>>();- // Swap workspace center group- workspace.center = PaneGroup::with_root(center_group);+ paths_to_open+ .into_iter()+ .map(|path_to_open| {+ path_to_open.map(|path_to_open| {+ Ok(opened_items.remove(&path_to_open))+ })+ .transpose()+ .map(|item| item.flatten())+ .transpose()+ })+ .collect::<Vec<_>>()+ });- // Change the focus to the workspace first so that we retrigger focus in on the pane.- cx.focus_self();+ // Remove old panes from workspace panes list+ workspace.update(&mut cx, |workspace, cx| {+ if let Some((center_group, active_pane)) = center_group {+ workspace.remove_panes(workspace.center.root.clone(), cx);- if let Some(active_pane) = active_pane {- cx.focus(&active_pane);- } else {- cx.focus(workspace.panes.last().unwrap());- }- } else {- let old_center_handle = old_center_pane.and_then(|weak| weak.upgrade(cx));- if let Some(old_center_handle) = old_center_handle {- cx.focus(&old_center_handle)+ // Swap workspace center group+ workspace.center = PaneGroup::with_root(center_group);++ // Change the focus to the workspace first so that we retrigger focus in on the pane.+ cx.focus_self();++ if let Some(active_pane) = active_pane {+ cx.focus(&active_pane);+ } else {+ cx.focus(workspace.panes.last().unwrap());+ }} else {- cx.focus_self()+ let old_center_handle = old_center_pane.and_then(|weak| weak.upgrade(cx));+ if let Some(old_center_handle) = old_center_handle {+ cx.focus(&old_center_handle)+ } else {+ cx.focus_self()+ }}- }- let docks = serialized_workspace.docks;- workspace.left_dock.update(cx, |dock, cx| {- dock.set_open(docks.left.visible, cx);- if let Some(active_panel) = docks.left.active_panel {- if let Some(ix) = dock.panel_index_for_ui_name(&active_panel, cx) {- dock.activate_panel(ix, cx);- if workspace.left_sidebar().read(cx).is_open()- != serialized_workspace.left_sidebar_open- {- workspace.toggle_sidebar(SidebarSide::Left, cx);- }-- // Note that without after_window, the focus_self() and- // the focus the dock generates start generating alternating- // focus due to the deferred execution each triggering each other- cx.after_window_update(move |workspace, cx| {- Dock::set_dock_position(- workspace,- serialized_workspace.dock_position,- false,- cx,- );++ let docks = serialized_workspace.docks;++ workspace.left_dock.update(cx, |dock, cx| {++ dock.set_open(docks.left.visible, cx);++ if let Some(active_panel) = docks.left.active_panel {++ if let Some(ix) = dock.panel_index_for_ui_name(&active_panel, cx) {++ dock.activate_panel(ix, cx);++ }+ }- }- });- workspace.right_dock.update(cx, |dock, cx| {- dock.set_open(docks.right.visible, cx);- if let Some(active_panel) = docks.right.active_panel {- if let Some(ix) = dock.panel_index_for_ui_name(&active_panel, cx) {- dock.activate_panel(ix, cx);++ });++ workspace.right_dock.update(cx, |dock, cx| {++ dock.set_open(docks.right.visible, cx);++ if let Some(active_panel) = docks.right.active_panel {++ if let Some(ix) = dock.panel_index_for_ui_name(&active_panel, cx) {++ dock.activate_panel(ix, cx);++ }+ }- }- });- workspace.bottom_dock.update(cx, |dock, cx| {- dock.set_open(docks.bottom.visible, cx);- if let Some(active_panel) = docks.bottom.active_panel {- if let Some(ix) = dock.panel_index_for_ui_name(&active_panel, cx) {- dock.activate_panel(ix, cx);++ });++ workspace.bottom_dock.update(cx, |dock, cx| {++ dock.set_open(docks.bottom.visible, cx);++ if let Some(active_panel) = docks.bottom.active_panel {++ if let Some(ix) = dock.panel_index_for_ui_name(&active_panel, cx) {++ dock.activate_panel(ix, cx);++ }+ }- }- });+ });- cx.notify();- })?;+ cx.notify();+ })?;- // Serialize ourself to make sure our timestamps and any pane / item changes are replicated- workspace.read_with(&cx, |workspace, cx| workspace.serialize_workspace(cx))?;- anyhow::Ok(())+ // Serialize ourself to make sure our timestamps and any pane / item changes are replicated+ workspace.read_with(&cx, |workspace, cx| workspace.serialize_workspace(cx))?;++ Ok::<_, anyhow::Error>(resulting_list)+ }};++ result.await.unwrap_or_default()})- .detach_and_log_err(cx);}#[cfg(any(test, feature = "test-support"))]@@@ -2748,40 -2684,103 +2796,129 @@@user_store: project.read(cx).user_store(),fs: project.read(cx).fs().clone(),build_window_options: |_, _, _| Default::default(),- initialize_workspace: |_, _, _| {},- dock_default_item_factory: |_, _| None,+ initialize_workspace: |_, _, _, _| Task::ready(Ok(())),background_actions: || &[],});- Self::new(None, 0, project, app_state, cx)+ Self::new(0, project, app_state, cx)}++ fn render_dock(&self, position: DockPosition, cx: &WindowContext) -> Option<AnyElement<Self>> {+ let dock = match position {+ DockPosition::Left => &self.left_dock,+ DockPosition::Right => &self.right_dock,+ DockPosition::Bottom => &self.bottom_dock,+ };+ let active_panel = dock.read(cx).active_panel()?;+ let element = if Some(active_panel.as_any()) == self.zoomed(cx).as_ref() {+ dock.read(cx).render_placeholder(cx)+ } else {+ ChildView::new(dock, cx).into_any()+ };++ Some(+ element+ .constrained()+ .dynamically(move |constraint, _, cx| match position {+ DockPosition::Left | DockPosition::Right => SizeConstraint::new(+ Vector2F::new(20., constraint.min.y()),+ Vector2F::new(cx.window_size().x() * 0.8, constraint.max.y()),+ ),+ _ => constraint,+ })+ .into_any(),+ )+ }}+ async fn open_items(+ serialized_workspace: Option<SerializedWorkspace>,+ workspace: &WeakViewHandle<Workspace>,+ mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,+ app_state: Arc<AppState>,+ mut cx: AsyncAppContext,+ ) -> Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>> {+ let mut opened_items = Vec::with_capacity(project_paths_to_open.len());++ if let Some(serialized_workspace) = serialized_workspace {+ let workspace = workspace.clone();+ let restored_items = cx+ .update(|cx| {+ Workspace::load_workspace(+ workspace,+ serialized_workspace,+ project_paths_to_open+ .iter()+ .map(|(_, project_path)| project_path)+ .cloned()+ .collect(),+ cx,+ )+ })+ .await;++ let restored_project_paths = cx.read(|cx| {+ restored_items+ .iter()+ .filter_map(|item| item.as_ref()?.as_ref().ok()?.project_path(cx))+ .collect::<HashSet<_>>()+ });++ opened_items = restored_items;+ project_paths_to_open+ .iter_mut()+ .for_each(|(_, project_path)| {+ if let Some(project_path_to_open) = project_path {+ if restored_project_paths.contains(project_path_to_open) {+ *project_path = None;+ }+ }+ });+ } else {+ for _ in 0..project_paths_to_open.len() {+ opened_items.push(None);+ }+ }+ assert!(opened_items.len() == project_paths_to_open.len());++ let tasks =+ project_paths_to_open+ .into_iter()+ .enumerate()+ .map(|(i, (abs_path, project_path))| {+ let workspace = workspace.clone();+ cx.spawn(|mut cx| {+ let fs = app_state.fs.clone();+ async move {+ let file_project_path = project_path?;+ if fs.is_file(&abs_path).await {+ Some((+ i,+ workspace+ .update(&mut cx, |workspace, cx| {+ workspace.open_path(file_project_path, None, true, cx)+ })+ .log_err()?+ .await,+ ))+ } else {+ None+ }+ }+ })+ });++ for maybe_opened_path in futures::future::join_all(tasks.into_iter())+ .await+ .into_iter()+ {+ if let Some((i, path_open_result)) = maybe_opened_path {+ opened_items[i] = Some(path_open_result);+ }+ }++ opened_items+ }+fn notify_if_database_failed(workspace: &WeakViewHandle<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";@@@ -3105,17 -3148,12 +3240,17 @@@ pub fn join_remote_projectlet (_, workspace) = cx.add_window((app_state.build_window_options)(None, None, cx.platform().as_ref()),- |cx| Workspace::new(None, 0, project, app_state.clone(), cx),- |cx| {- let mut workspace = Workspace::new(0, project, app_state.clone(), cx);- (app_state.initialize_workspace)(&mut workspace, &app_state, cx);- workspace- },++ |cx| Workspace::new(0, project, app_state.clone(), cx),);+ (app_state.initialize_workspace)(+ workspace.downgrade(),+ false,+ app_state.clone(),+ cx.clone(),+ )+ .await+ .log_err();+workspace.downgrade()};@@@ -3217,14 -3255,8 +3352,11 @@@ fn parse_pixel_position_env_var(value:#[cfg(test)]mod tests {- use std::{cell::RefCell, rc::Rc};-+ use super::*;- use crate::item::test::{TestItem, TestItemEvent, TestProjectItem};+ use crate::{+ dock::test::{TestPanel, TestPanelEvent},+ item::test::{TestItem, TestItemEvent, TestProjectItem},+ };-- use super::*;use fs::FakeFs;use gpui::{executor::Deterministic, TestAppContext};use project::{Project, ProjectEntryId};@@@ -3793,153 -3843,13 +3930,162 @@@});}+ #[gpui::test]- async fn test_panels(deterministic: Arc<Deterministic>, cx: &mut gpui::TestAppContext) {- deterministic.forbid_parking();- Settings::test_async(cx);++ async fn test_panels(cx: &mut gpui::TestAppContext) {++ init_test(cx);+ let fs = FakeFs::new(cx.background());++ let project = Project::test(fs, [], cx).await;+ let (_window_id, workspace) = cx.add_window(|cx| Workspace::test_new(project, cx));++ let (panel_1, panel_2) = workspace.update(cx, |workspace, cx| {+ // Add panel_1 on the left, panel_2 on the right.+ let panel_1 = cx.add_view(|_| TestPanel {+ position: DockPosition::Left,+ });+ workspace.add_panel(panel_1.clone(), cx);+ workspace+ .left_dock()+ .update(cx, |left_dock, cx| left_dock.set_open(true, cx));+ let panel_2 = cx.add_view(|_| TestPanel {+ position: DockPosition::Right,+ });+ workspace.add_panel(panel_2.clone(), cx);+ workspace+ .right_dock()+ .update(cx, |right_dock, cx| right_dock.set_open(true, cx));++ let left_dock = workspace.left_dock();+ assert_eq!(+ left_dock.read(cx).active_panel().unwrap().id(),+ panel_1.id()+ );+ assert_eq!(+ left_dock.read(cx).active_panel_size().unwrap(),+ panel_1.default_size(cx)+ );++ left_dock.update(cx, |left_dock, cx| left_dock.resize_active_panel(1337., cx));+ assert_eq!(+ workspace.right_dock().read(cx).active_panel().unwrap().id(),+ panel_2.id()+ );++ (panel_1, panel_2)+ });++ // Move panel_1 to the right+ panel_1.update(cx, |panel_1, cx| {+ panel_1.set_position(DockPosition::Right, cx)+ });++ workspace.update(cx, |workspace, cx| {+ // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.+ // Since it was the only panel on the left, the left dock should now be closed.+ assert!(!workspace.left_dock().read(cx).is_open());+ assert!(workspace.left_dock().read(cx).active_panel().is_none());+ let right_dock = workspace.right_dock();+ assert_eq!(+ right_dock.read(cx).active_panel().unwrap().id(),+ panel_1.id()+ );+ assert_eq!(right_dock.read(cx).active_panel_size().unwrap(), 1337.);++ // Now we move panel_2 to the left+ panel_2.set_position(DockPosition::Left, cx);+ });++ workspace.update(cx, |workspace, cx| {+ // Since panel_2 was not visible on the right, we don't open the left dock.+ assert!(!workspace.left_dock().read(cx).is_open());+ // And the right dock is unaffected in it's displaying of panel_1+ assert!(workspace.right_dock().read(cx).is_open());+ assert_eq!(+ workspace.right_dock().read(cx).active_panel().unwrap().id(),+ panel_1.id()+ );+ });++ // Move panel_1 back to the left+ panel_1.update(cx, |panel_1, cx| {+ panel_1.set_position(DockPosition::Left, cx)+ });++ workspace.update(cx, |workspace, cx| {+ // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.+ let left_dock = workspace.left_dock();+ assert!(left_dock.read(cx).is_open());+ assert_eq!(+ left_dock.read(cx).active_panel().unwrap().id(),+ panel_1.id()+ );+ assert_eq!(left_dock.read(cx).active_panel_size().unwrap(), 1337.);+ // And right the dock should be closed as it no longer has any panels.+ assert!(!workspace.right_dock().read(cx).is_open());++ // Now we move panel_1 to the bottom+ panel_1.set_position(DockPosition::Bottom, cx);+ });++ workspace.update(cx, |workspace, cx| {+ // Since panel_1 was visible on the left, we close the left dock.+ assert!(!workspace.left_dock().read(cx).is_open());+ // The bottom dock is sized based on the panel's default size,+ // since the panel orientation changed from vertical to horizontal.+ let bottom_dock = workspace.bottom_dock();+ assert_eq!(+ bottom_dock.read(cx).active_panel_size().unwrap(),+ panel_1.default_size(cx),+ );+ // Close bottom dock and move panel_1 back to the left.+ bottom_dock.update(cx, |bottom_dock, cx| bottom_dock.set_open(false, cx));+ panel_1.set_position(DockPosition::Left, cx);+ });++ // Emit activated event on panel 1+ panel_1.update(cx, |_, cx| cx.emit(TestPanelEvent::Activated));++ // Now the left dock is open and panel_1 is active and focused.+ workspace.read_with(cx, |workspace, cx| {+ let left_dock = workspace.left_dock();+ assert!(left_dock.read(cx).is_open());+ assert_eq!(+ left_dock.read(cx).active_panel().unwrap().id(),+ panel_1.id()+ );+ assert!(panel_1.is_focused(cx));+ });++ // Emit closed event on panel 2, which is not active+ panel_2.update(cx, |_, cx| cx.emit(TestPanelEvent::Closed));++ // Wo don't close the left dock, because panel_2 wasn't the active panel+ workspace.read_with(cx, |workspace, cx| {+ let left_dock = workspace.left_dock();+ assert!(left_dock.read(cx).is_open());+ assert_eq!(+ left_dock.read(cx).active_panel().unwrap().id(),+ panel_1.id()+ );+ });++ // Emit closed event on panel 1, which is active+ panel_1.update(cx, |_, cx| cx.emit(TestPanelEvent::Closed));++ // Now the left dock is closed, because panel_1 was the active panel+ workspace.read_with(cx, |workspace, cx| {+ let left_dock = workspace.left_dock();+ assert!(!left_dock.read(cx).is_open());+ });+ }+++ pub fn init_test(cx: &mut TestAppContext) {+ cx.foreground().forbid_parking();+ cx.update(|cx| {+ cx.set_global(SettingsStore::test(cx));+ theme::init((), cx);+ language::init(cx);+ crate::init_settings(cx);+ });+ }}diff --cc crates/workspace/src/workspace_settings.rsindex 00000000000,41e47964910..b21c687050emode 000000,100644..100644--- a/crates/workspace/src/workspace_settings.rs+++ b/crates/workspace/src/workspace_settings.rs@@@ -1,0 -1,103 +1,58 @@@-use anyhow::bail;-use db::sqlez::{- bindable::{Bind, Column, StaticColumnCount},- statement::Statement,-};+ use schemars::JsonSchema;+ use serde::{Deserialize, Serialize};+ use settings::Setting;++ #[derive(Deserialize)]+ pub struct WorkspaceSettings {+ pub active_pane_magnification: f32,+ pub confirm_quit: bool,+ pub show_call_status_icon: bool,+ pub autosave: AutosaveSetting,- pub default_dock_anchor: DockAnchor,+ pub git: GitSettings,+ }++ #[derive(Clone, Serialize, Deserialize, JsonSchema)]+ pub struct WorkspaceSettingsContent {+ pub active_pane_magnification: Option<f32>,+ pub confirm_quit: Option<bool>,+ pub show_call_status_icon: Option<bool>,+ pub autosave: Option<AutosaveSetting>,- pub default_dock_anchor: Option<DockAnchor>,+ pub git: Option<GitSettings>,+ }++ #[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]+ #[serde(rename_all = "snake_case")]+ pub enum AutosaveSetting {+ Off,+ AfterDelay { milliseconds: u64 },+ OnFocusChange,+ OnWindowChange,+ }+-#[derive(PartialEq, Eq, Debug, Default, Copy, Clone, Hash, Serialize, Deserialize, JsonSchema)]-#[serde(rename_all = "snake_case")]-pub enum DockAnchor {- #[default]- Bottom,- Right,- Expanded,-}-+ #[derive(Copy, Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]+ pub struct GitSettings {+ pub git_gutter: Option<GitGutterSetting>,+ pub gutter_debounce: Option<u64>,+ }++ #[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, JsonSchema)]+ #[serde(rename_all = "snake_case")]+ pub enum GitGutterSetting {+ #[default]+ TrackedFiles,+ Hide,+ }+-impl StaticColumnCount for DockAnchor {}--impl Bind for DockAnchor {- fn bind(&self, statement: &Statement, start_index: i32) -> anyhow::Result<i32> {- match self {- DockAnchor::Bottom => "Bottom",- DockAnchor::Right => "Right",- DockAnchor::Expanded => "Expanded",- }- .bind(statement, start_index)- }-}--impl Column for DockAnchor {- fn column(statement: &mut Statement, start_index: i32) -> anyhow::Result<(Self, i32)> {- String::column(statement, start_index).and_then(|(anchor_text, next_index)| {- Ok((- match anchor_text.as_ref() {- "Bottom" => DockAnchor::Bottom,- "Right" => DockAnchor::Right,- "Expanded" => DockAnchor::Expanded,- _ => bail!("Stored dock anchor is incorrect"),- },- next_index,- ))- })- }-}-+ impl Setting for WorkspaceSettings {+ const KEY: Option<&'static str> = None;++ type FileContent = WorkspaceSettingsContent;++ fn load(+ default_value: &Self::FileContent,+ user_values: &[&Self::FileContent],+ _: &gpui::AppContext,+ ) -> anyhow::Result<Self> {+ Self::load_via_json_merge(default_value, user_values)+ }+ }diff --cc crates/zed/src/main.rsindex 362b714a927,2f359240bc7..c05efd3f027--- a/crates/zed/src/main.rs+++ b/crates/zed/src/main.rs@@@ -46,15 -52,16 +52,15 @@@ use util::use welcome::{show_welcome_experience, FIRST_OPEN};use fs::RealFs;- use settings::watched_json::WatchedJsonFile;#[cfg(debug_assertions)]use staff_mode::StaffMode;- use theme::ThemeRegistry;use util::{channel::RELEASE_CHANNEL, paths, ResultExt, TryFutureExt};use workspace::{- dock::FocusDock, item::ItemHandle, notifications::NotifyResultExt, AppState, OpenSettings,- Workspace,+ item::ItemHandle, notifications::NotifyResultExt, AppState, OpenSettings, Workspace,};- use zed::{self, build_window_options, initialize_workspace, languages, menus};+ use zed::{+ self, build_window_options, handle_keymap_file_changes, initialize_workspace, languages, menus,+ };fn main() {let http = http::client();diff --cc crates/zed/src/zed.rsindex 77a3bf350f1,376ecfc06bd..0c4b63081c0--- a/crates/zed/src/zed.rs+++ b/crates/zed/src/zed.rs@@@ -15,10 -15,9 +15,10 @@@ use anyhow::anyhowuse feedback::{feedback_info_text::FeedbackInfoText, submit_feedback_button::SubmitFeedbackButton,};- use futures::StreamExt;+ use futures::{channel::mpsc, StreamExt};use gpui::{actions,+ anyhow::{self, Result},geometry::vector::vec2f,impl_actions,platform::{Platform, PromptLevel, TitlebarOptions, WindowBounds, WindowKind, WindowOptions},@@@ -30,15 -29,16 +30,16 @@@ use project_panel::ProjectPaneluse search::{BufferSearchBar, ProjectSearchBar};use serde::Deserialize;use serde_json::to_string_pretty;- use settings::{Settings, DEFAULT_SETTINGS_ASSET_PATH};+ use settings::{KeymapFileContent, SettingsStore, DEFAULT_SETTINGS_ASSET_PATH};use std::{borrow::Cow, str, sync::Arc};-use terminal_view::terminal_button::TerminalButton;+use terminal_view::terminal_panel::{self, TerminalPanel};use util::{channel::ReleaseChannel, paths, ResultExt};use uuid::Uuid;+ use welcome::BaseKeymap;pub use workspace;use workspace::{- create_and_open_local_file, open_new, sidebar::SidebarSide, AppState, NewFile, NewWindow,+ create_and_open_local_file, dock::PanelHandle, open_new, AppState, NewFile, NewWindow,- Workspace,+ Workspace, WorkspaceSettings,};#[derive(Deserialize, Clone, PartialEq)]@@@ -282,105 -252,85 +260,106 @@@ pub fn init(app_state: &Arc<AppState>,}pub fn initialize_workspace(- workspace: &mut Workspace,- app_state: &Arc<AppState>,- cx: &mut ViewContext<Workspace>,-) {- let workspace_handle = cx.handle();- cx.subscribe(&workspace_handle, {- move |workspace, _, event, cx| {- if let workspace::Event::PaneAdded(pane) = event {- pane.update(cx, |pane, cx| {- pane.toolbar().update(cx, |toolbar, cx| {- let breadcrumbs = cx.add_view(|_| Breadcrumbs::new(workspace));- toolbar.add_item(breadcrumbs, cx);- let buffer_search_bar = cx.add_view(BufferSearchBar::new);- toolbar.add_item(buffer_search_bar, cx);- let project_search_bar = cx.add_view(|_| ProjectSearchBar::new());- toolbar.add_item(project_search_bar, cx);- let submit_feedback_button = cx.add_view(|_| SubmitFeedbackButton::new());- toolbar.add_item(submit_feedback_button, cx);- let feedback_info_text = cx.add_view(|_| FeedbackInfoText::new());- toolbar.add_item(feedback_info_text, cx);- let lsp_log_item = cx.add_view(|_| {- lsp_log::LspLogToolbarItemView::new(workspace.project().clone())+ workspace_handle: WeakViewHandle<Workspace>,+ was_deserialized: bool,+ app_state: Arc<AppState>,+ cx: AsyncAppContext,+) -> Task<Result<()>> {+ cx.spawn(|mut cx| async move {+ workspace_handle.update(&mut cx, |workspace, cx| {+ let workspace_handle = cx.handle();+ cx.subscribe(&workspace_handle, {+ move |workspace, _, event, cx| {+ if let workspace::Event::PaneAdded(pane) = event {+ pane.update(cx, |pane, cx| {+ pane.toolbar().update(cx, |toolbar, cx| {+ let breadcrumbs = cx.add_view(|_| Breadcrumbs::new(workspace));+ toolbar.add_item(breadcrumbs, cx);+ let buffer_search_bar = cx.add_view(BufferSearchBar::new);+ toolbar.add_item(buffer_search_bar, cx);+ let project_search_bar = cx.add_view(|_| ProjectSearchBar::new());+ toolbar.add_item(project_search_bar, cx);+ let submit_feedback_button =+ cx.add_view(|_| SubmitFeedbackButton::new());+ toolbar.add_item(submit_feedback_button, cx);+ let feedback_info_text = cx.add_view(|_| FeedbackInfoText::new());+ toolbar.add_item(feedback_info_text, cx);+ let lsp_log_item = cx.add_view(|_| {+ lsp_log::LspLogToolbarItemView::new(workspace.project().clone())+ });+ toolbar.add_item(lsp_log_item, cx);+ })});- toolbar.add_item(lsp_log_item, cx);- })- });- }- }- })- .detach();+ }+ }+ })+ .detach();- cx.emit(workspace::Event::PaneAdded(workspace.active_pane().clone()));- cx.emit(workspace::Event::PaneAdded(workspace.dock_pane().clone()));-- let collab_titlebar_item =- cx.add_view(|cx| CollabTitlebarItem::new(workspace, &workspace_handle, cx));- workspace.set_titlebar_item(collab_titlebar_item.into_any(), cx);-- let project_panel = ProjectPanel::new(workspace, cx);- workspace.left_sidebar().update(cx, |sidebar, cx| {- sidebar.add_item(- "icons/folder_tree_16.svg",- "Project Panel".to_string(),- project_panel,- cx,- )- });+ cx.emit(workspace::Event::PaneAdded(workspace.active_pane().clone()));- let toggle_terminal = cx.add_view(|cx| TerminalButton::new(workspace_handle.clone(), cx));- let copilot = cx.add_view(|cx| copilot_button::CopilotButton::new(app_state.fs.clone(), cx));- let diagnostic_summary =- cx.add_view(|cx| diagnostics::items::DiagnosticIndicator::new(workspace, cx));- let activity_indicator =- activity_indicator::ActivityIndicator::new(workspace, app_state.languages.clone(), cx);- let active_buffer_language =- cx.add_view(|_| language_selector::ActiveBufferLanguage::new(workspace));- let feedback_button =- cx.add_view(|_| feedback::deploy_feedback_button::DeployFeedbackButton::new(workspace));- let cursor_position = cx.add_view(|_| editor::items::CursorPosition::new());- workspace.status_bar().update(cx, |status_bar, cx| {- status_bar.add_left_item(diagnostic_summary, cx);- status_bar.add_left_item(activity_indicator, cx);- status_bar.add_right_item(toggle_terminal, cx);- status_bar.add_right_item(feedback_button, cx);- status_bar.add_right_item(copilot, cx);- status_bar.add_right_item(active_buffer_language, cx);- status_bar.add_right_item(cursor_position, cx);- });+ let collab_titlebar_item =+ cx.add_view(|cx| CollabTitlebarItem::new(workspace, &workspace_handle, cx));+ workspace.set_titlebar_item(collab_titlebar_item.into_any(), cx);- let copilot = cx.add_view(|cx| copilot_button::CopilotButton::new(cx));- auto_update::notify_of_any_new_update(cx.weak_handle(), cx);++ let copilot =++ cx.add_view(|cx| copilot_button::CopilotButton::new(app_state.fs.clone(), cx));+ let diagnostic_summary =+ cx.add_view(|cx| diagnostics::items::DiagnosticIndicator::new(workspace, cx));+ let activity_indicator = activity_indicator::ActivityIndicator::new(+ workspace,+ app_state.languages.clone(),+ cx,+ );+ let active_buffer_language =+ cx.add_view(|_| language_selector::ActiveBufferLanguage::new(workspace));+ let feedback_button = cx.add_view(|_| {+ feedback::deploy_feedback_button::DeployFeedbackButton::new(workspace)+ });+ let cursor_position = cx.add_view(|_| editor::items::CursorPosition::new());+ workspace.status_bar().update(cx, |status_bar, cx| {+ status_bar.add_left_item(diagnostic_summary, cx);+ status_bar.add_left_item(activity_indicator, cx);+ status_bar.add_right_item(feedback_button, cx);+ status_bar.add_right_item(copilot, cx);+ status_bar.add_right_item(active_buffer_language, cx);+ status_bar.add_right_item(cursor_position, cx);+ });- vim::observe_keystrokes(cx);+ auto_update::notify_of_any_new_update(cx.weak_handle(), cx);- cx.on_window_should_close(|workspace, cx| {- if let Some(task) = workspace.close(&Default::default(), cx) {- task.detach_and_log_err(cx);- }- false- });+ vim::observe_keystrokes(cx);++ cx.on_window_should_close(|workspace, cx| {+ if let Some(task) = workspace.close(&Default::default(), cx) {+ task.detach_and_log_err(cx);+ }+ false+ });++ let project_panel = ProjectPanel::new(workspace, cx);+ let project_panel_position = project_panel.position(cx);+ workspace.add_panel(project_panel, cx);+ if !was_deserialized+ && workspace+ .project()+ .read(cx)+ .visible_worktrees(cx)+ .any(|tree| {+ tree.read(cx)+ .root_entry()+ .map_or(false, |entry| entry.is_dir())+ })+ {+ workspace.toggle_dock(project_panel_position, cx);+ }+ })?;++ let terminal_panel = TerminalPanel::load(workspace_handle.clone(), cx.clone()).await?;+ workspace_handle.update(&mut cx, |workspace, cx| {+ workspace.add_panel(terminal_panel, cx)+ })?;+ Ok(())+ })}pub fn build_window_options(