1pub mod dock;
2pub mod history_manager;
3pub mod invalid_item_view;
4pub mod item;
5mod modal_layer;
6pub mod notifications;
7pub mod pane;
8pub mod pane_group;
9mod path_list;
10mod persistence;
11pub mod searchable;
12pub mod shared_screen;
13mod status_bar;
14pub mod tasks;
15mod theme_preview;
16mod toast_layer;
17mod toolbar;
18pub mod utility_pane;
19mod workspace_settings;
20
21pub use crate::notifications::NotificationFrame;
22pub use dock::Panel;
23pub use path_list::PathList;
24pub use toast_layer::{ToastAction, ToastLayer, ToastView};
25
26use anyhow::{Context as _, Result, anyhow};
27use call::{ActiveCall, call_settings::CallSettings};
28use client::{
29 ChannelId, Client, ErrorExt, Status, TypedEnvelope, UserStore,
30 proto::{self, ErrorCode, PanelId, PeerId},
31};
32use collections::{HashMap, HashSet, hash_map};
33use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
34use feature_flags::{AgentV2FeatureFlag, FeatureFlagAppExt};
35use futures::{
36 Future, FutureExt, StreamExt,
37 channel::{
38 mpsc::{self, UnboundedReceiver, UnboundedSender},
39 oneshot,
40 },
41 future::{Shared, try_join_all},
42};
43use gpui::{
44 Action, AnyEntity, AnyView, AnyWeakView, App, AsyncApp, AsyncWindowContext, Bounds, Context,
45 CursorStyle, Decorations, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle,
46 Focusable, Global, HitboxBehavior, Hsla, KeyContext, Keystroke, ManagedView, MouseButton,
47 PathPromptOptions, Point, PromptLevel, Render, ResizeEdge, Size, Stateful, Subscription,
48 SystemWindowTabController, Task, Tiling, WeakEntity, WindowBounds, WindowHandle, WindowId,
49 WindowOptions, actions, canvas, point, relative, size, transparent_black,
50};
51pub use history_manager::*;
52pub use item::{
53 FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings,
54 ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle,
55};
56use itertools::Itertools;
57use language::{Buffer, LanguageRegistry, Rope, language_settings::all_language_settings};
58pub use modal_layer::*;
59use node_runtime::NodeRuntime;
60use notifications::{
61 DetachAndPromptErr, Notifications, dismiss_app_notification,
62 simple_message_notification::MessageNotification,
63};
64pub use pane::*;
65pub use pane_group::{
66 ActivePaneDecorator, HANDLE_HITBOX_SIZE, Member, PaneAxis, PaneGroup, PaneRenderContext,
67 SplitDirection,
68};
69use persistence::{DB, SerializedWindowBounds, model::SerializedWorkspace};
70pub use persistence::{
71 DB as WORKSPACE_DB, WorkspaceDb, delete_unloaded_items,
72 model::{ItemId, SerializedWorkspaceLocation},
73};
74use postage::stream::Stream;
75use project::{
76 DirectoryLister, Project, ProjectEntryId, ProjectPath, ResolvedPath, Worktree, WorktreeId,
77 WorktreeSettings,
78 debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
79 toolchain_store::ToolchainStoreEvent,
80};
81use remote::{
82 RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions,
83 remote_client::ConnectionIdentifier,
84};
85use schemars::JsonSchema;
86use serde::Deserialize;
87use session::AppSession;
88use settings::{CenteredPaddingSettings, Settings, SettingsLocation, update_settings_file};
89use shared_screen::SharedScreen;
90use sqlez::{
91 bindable::{Bind, Column, StaticColumnCount},
92 statement::Statement,
93};
94use status_bar::StatusBar;
95pub use status_bar::StatusItemView;
96use std::{
97 any::TypeId,
98 borrow::Cow,
99 cell::RefCell,
100 cmp,
101 collections::{VecDeque, hash_map::DefaultHasher},
102 env,
103 hash::{Hash, Hasher},
104 path::{Path, PathBuf},
105 process::ExitStatus,
106 rc::Rc,
107 sync::{
108 Arc, LazyLock, Weak,
109 atomic::{AtomicBool, AtomicUsize},
110 },
111 time::Duration,
112};
113use task::{DebugScenario, SpawnInTerminal, TaskContext};
114use theme::{ActiveTheme, GlobalTheme, SystemAppearance, ThemeSettings};
115pub use toolbar::{Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView};
116pub use ui;
117use ui::{Window, prelude::*};
118use util::{
119 ResultExt, TryFutureExt,
120 paths::{PathStyle, SanitizedPath},
121 rel_path::RelPath,
122 serde::default_true,
123};
124use uuid::Uuid;
125pub use workspace_settings::{
126 AutosaveSetting, BottomDockLayout, RestoreOnStartupBehavior, StatusBarSettings, TabBarSettings,
127 WorkspaceSettings,
128};
129use zed_actions::{Spawn, feedback::FileBugReport};
130
131use crate::{
132 item::ItemBufferKind, notifications::NotificationId, utility_pane::UTILITY_PANE_MIN_WIDTH,
133};
134use crate::{
135 persistence::{
136 SerializedAxis,
137 model::{DockData, DockStructure, SerializedItem, SerializedPane, SerializedPaneGroup},
138 },
139 utility_pane::{DraggedUtilityPane, UtilityPaneFrame, UtilityPaneSlot, UtilityPaneState},
140};
141
142pub const SERIALIZATION_THROTTLE_TIME: Duration = Duration::from_millis(200);
143
144static ZED_WINDOW_SIZE: LazyLock<Option<Size<Pixels>>> = LazyLock::new(|| {
145 env::var("ZED_WINDOW_SIZE")
146 .ok()
147 .as_deref()
148 .and_then(parse_pixel_size_env_var)
149});
150
151static ZED_WINDOW_POSITION: LazyLock<Option<Point<Pixels>>> = LazyLock::new(|| {
152 env::var("ZED_WINDOW_POSITION")
153 .ok()
154 .as_deref()
155 .and_then(parse_pixel_position_env_var)
156});
157
158pub trait TerminalProvider {
159 fn spawn(
160 &self,
161 task: SpawnInTerminal,
162 window: &mut Window,
163 cx: &mut App,
164 ) -> Task<Option<Result<ExitStatus>>>;
165}
166
167pub trait DebuggerProvider {
168 // `active_buffer` is used to resolve build task's name against language-specific tasks.
169 fn start_session(
170 &self,
171 definition: DebugScenario,
172 task_context: TaskContext,
173 active_buffer: Option<Entity<Buffer>>,
174 worktree_id: Option<WorktreeId>,
175 window: &mut Window,
176 cx: &mut App,
177 );
178
179 fn spawn_task_or_modal(
180 &self,
181 workspace: &mut Workspace,
182 action: &Spawn,
183 window: &mut Window,
184 cx: &mut Context<Workspace>,
185 );
186
187 fn task_scheduled(&self, cx: &mut App);
188 fn debug_scenario_scheduled(&self, cx: &mut App);
189 fn debug_scenario_scheduled_last(&self, cx: &App) -> bool;
190
191 fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus>;
192}
193
194actions!(
195 workspace,
196 [
197 /// Activates the next pane in the workspace.
198 ActivateNextPane,
199 /// Activates the previous pane in the workspace.
200 ActivatePreviousPane,
201 /// Switches to the next window.
202 ActivateNextWindow,
203 /// Switches to the previous window.
204 ActivatePreviousWindow,
205 /// Adds a folder to the current project.
206 AddFolderToProject,
207 /// Clears all notifications.
208 ClearAllNotifications,
209 /// Clears all navigation history, including forward/backward navigation, recently opened files, and recently closed tabs. **This action is irreversible**.
210 ClearNavigationHistory,
211 /// Closes the active dock.
212 CloseActiveDock,
213 /// Closes all docks.
214 CloseAllDocks,
215 /// Toggles all docks.
216 ToggleAllDocks,
217 /// Closes the current window.
218 CloseWindow,
219 /// Opens the feedback dialog.
220 Feedback,
221 /// Follows the next collaborator in the session.
222 FollowNextCollaborator,
223 /// Moves the focused panel to the next position.
224 MoveFocusedPanelToNextPosition,
225 /// Opens a new terminal in the center.
226 NewCenterTerminal,
227 /// Creates a new file.
228 NewFile,
229 /// Creates a new file in a vertical split.
230 NewFileSplitVertical,
231 /// Creates a new file in a horizontal split.
232 NewFileSplitHorizontal,
233 /// Opens a new search.
234 NewSearch,
235 /// Opens a new terminal.
236 NewTerminal,
237 /// Opens a new window.
238 NewWindow,
239 /// Opens a file or directory.
240 Open,
241 /// Opens multiple files.
242 OpenFiles,
243 /// Opens the current location in terminal.
244 OpenInTerminal,
245 /// Opens the component preview.
246 OpenComponentPreview,
247 /// Reloads the active item.
248 ReloadActiveItem,
249 /// Resets the active dock to its default size.
250 ResetActiveDockSize,
251 /// Resets all open docks to their default sizes.
252 ResetOpenDocksSize,
253 /// Reloads the application
254 Reload,
255 /// Saves the current file with a new name.
256 SaveAs,
257 /// Saves without formatting.
258 SaveWithoutFormat,
259 /// Shuts down all debug adapters.
260 ShutdownDebugAdapters,
261 /// Suppresses the current notification.
262 SuppressNotification,
263 /// Toggles the bottom dock.
264 ToggleBottomDock,
265 /// Toggles centered layout mode.
266 ToggleCenteredLayout,
267 /// Toggles edit prediction feature globally for all files.
268 ToggleEditPrediction,
269 /// Toggles the left dock.
270 ToggleLeftDock,
271 /// Toggles the right dock.
272 ToggleRightDock,
273 /// Toggles zoom on the active pane.
274 ToggleZoom,
275 /// Zooms in on the active pane.
276 ZoomIn,
277 /// Zooms out of the active pane.
278 ZoomOut,
279 /// Stops following a collaborator.
280 Unfollow,
281 /// Restores the banner.
282 RestoreBanner,
283 /// Toggles expansion of the selected item.
284 ToggleExpandItem,
285 ]
286);
287
288/// Activates a specific pane by its index.
289#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
290#[action(namespace = workspace)]
291pub struct ActivatePane(pub usize);
292
293/// Moves an item to a specific pane by index.
294#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
295#[action(namespace = workspace)]
296#[serde(deny_unknown_fields)]
297pub struct MoveItemToPane {
298 #[serde(default = "default_1")]
299 pub destination: usize,
300 #[serde(default = "default_true")]
301 pub focus: bool,
302 #[serde(default)]
303 pub clone: bool,
304}
305
306fn default_1() -> usize {
307 1
308}
309
310/// Moves an item to a pane in the specified direction.
311#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
312#[action(namespace = workspace)]
313#[serde(deny_unknown_fields)]
314pub struct MoveItemToPaneInDirection {
315 #[serde(default = "default_right")]
316 pub direction: SplitDirection,
317 #[serde(default = "default_true")]
318 pub focus: bool,
319 #[serde(default)]
320 pub clone: bool,
321}
322
323/// Creates a new file in a split of the desired direction.
324#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
325#[action(namespace = workspace)]
326#[serde(deny_unknown_fields)]
327pub struct NewFileSplit(pub SplitDirection);
328
329fn default_right() -> SplitDirection {
330 SplitDirection::Right
331}
332
333/// Saves all open files in the workspace.
334#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
335#[action(namespace = workspace)]
336#[serde(deny_unknown_fields)]
337pub struct SaveAll {
338 #[serde(default)]
339 pub save_intent: Option<SaveIntent>,
340}
341
342/// Saves the current file with the specified options.
343#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
344#[action(namespace = workspace)]
345#[serde(deny_unknown_fields)]
346pub struct Save {
347 #[serde(default)]
348 pub save_intent: Option<SaveIntent>,
349}
350
351/// Closes all items and panes in the workspace.
352#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
353#[action(namespace = workspace)]
354#[serde(deny_unknown_fields)]
355pub struct CloseAllItemsAndPanes {
356 #[serde(default)]
357 pub save_intent: Option<SaveIntent>,
358}
359
360/// Closes all inactive tabs and panes in the workspace.
361#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
362#[action(namespace = workspace)]
363#[serde(deny_unknown_fields)]
364pub struct CloseInactiveTabsAndPanes {
365 #[serde(default)]
366 pub save_intent: Option<SaveIntent>,
367}
368
369/// Sends a sequence of keystrokes to the active element.
370#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
371#[action(namespace = workspace)]
372pub struct SendKeystrokes(pub String);
373
374actions!(
375 project_symbols,
376 [
377 /// Toggles the project symbols search.
378 #[action(name = "Toggle")]
379 ToggleProjectSymbols
380 ]
381);
382
383/// Toggles the file finder interface.
384#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
385#[action(namespace = file_finder, name = "Toggle")]
386#[serde(deny_unknown_fields)]
387pub struct ToggleFileFinder {
388 #[serde(default)]
389 pub separate_history: bool,
390}
391
392/// Increases size of a currently focused dock by a given amount of pixels.
393#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
394#[action(namespace = workspace)]
395#[serde(deny_unknown_fields)]
396pub struct IncreaseActiveDockSize {
397 /// For 0px parameter, uses UI font size value.
398 #[serde(default)]
399 pub px: u32,
400}
401
402/// Decreases size of a currently focused dock by a given amount of pixels.
403#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
404#[action(namespace = workspace)]
405#[serde(deny_unknown_fields)]
406pub struct DecreaseActiveDockSize {
407 /// For 0px parameter, uses UI font size value.
408 #[serde(default)]
409 pub px: u32,
410}
411
412/// Increases size of all currently visible docks uniformly, by a given amount of pixels.
413#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
414#[action(namespace = workspace)]
415#[serde(deny_unknown_fields)]
416pub struct IncreaseOpenDocksSize {
417 /// For 0px parameter, uses UI font size value.
418 #[serde(default)]
419 pub px: u32,
420}
421
422/// Decreases size of all currently visible docks uniformly, by a given amount of pixels.
423#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
424#[action(namespace = workspace)]
425#[serde(deny_unknown_fields)]
426pub struct DecreaseOpenDocksSize {
427 /// For 0px parameter, uses UI font size value.
428 #[serde(default)]
429 pub px: u32,
430}
431
432actions!(
433 workspace,
434 [
435 /// Activates the pane to the left.
436 ActivatePaneLeft,
437 /// Activates the pane to the right.
438 ActivatePaneRight,
439 /// Activates the pane above.
440 ActivatePaneUp,
441 /// Activates the pane below.
442 ActivatePaneDown,
443 /// Swaps the current pane with the one to the left.
444 SwapPaneLeft,
445 /// Swaps the current pane with the one to the right.
446 SwapPaneRight,
447 /// Swaps the current pane with the one above.
448 SwapPaneUp,
449 /// Swaps the current pane with the one below.
450 SwapPaneDown,
451 // Swaps the current pane with the first available adjacent pane (searching in order: below, above, right, left) and activates that pane.
452 SwapPaneAdjacent,
453 /// Move the current pane to be at the far left.
454 MovePaneLeft,
455 /// Move the current pane to be at the far right.
456 MovePaneRight,
457 /// Move the current pane to be at the very top.
458 MovePaneUp,
459 /// Move the current pane to be at the very bottom.
460 MovePaneDown,
461 ]
462);
463
464#[derive(PartialEq, Eq, Debug)]
465pub enum CloseIntent {
466 /// Quit the program entirely.
467 Quit,
468 /// Close a window.
469 CloseWindow,
470 /// Replace the workspace in an existing window.
471 ReplaceWindow,
472}
473
474#[derive(Clone)]
475pub struct Toast {
476 id: NotificationId,
477 msg: Cow<'static, str>,
478 autohide: bool,
479 on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut Window, &mut App)>)>,
480}
481
482impl Toast {
483 pub fn new<I: Into<Cow<'static, str>>>(id: NotificationId, msg: I) -> Self {
484 Toast {
485 id,
486 msg: msg.into(),
487 on_click: None,
488 autohide: false,
489 }
490 }
491
492 pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
493 where
494 M: Into<Cow<'static, str>>,
495 F: Fn(&mut Window, &mut App) + 'static,
496 {
497 self.on_click = Some((message.into(), Arc::new(on_click)));
498 self
499 }
500
501 pub fn autohide(mut self) -> Self {
502 self.autohide = true;
503 self
504 }
505}
506
507impl PartialEq for Toast {
508 fn eq(&self, other: &Self) -> bool {
509 self.id == other.id
510 && self.msg == other.msg
511 && self.on_click.is_some() == other.on_click.is_some()
512 }
513}
514
515/// Opens a new terminal with the specified working directory.
516#[derive(Debug, Default, Clone, Deserialize, PartialEq, JsonSchema, Action)]
517#[action(namespace = workspace)]
518#[serde(deny_unknown_fields)]
519pub struct OpenTerminal {
520 pub working_directory: PathBuf,
521}
522
523#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
524pub struct WorkspaceId(i64);
525
526impl StaticColumnCount for WorkspaceId {}
527impl Bind for WorkspaceId {
528 fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
529 self.0.bind(statement, start_index)
530 }
531}
532impl Column for WorkspaceId {
533 fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
534 i64::column(statement, start_index)
535 .map(|(i, next_index)| (Self(i), next_index))
536 .with_context(|| format!("Failed to read WorkspaceId at index {start_index}"))
537 }
538}
539impl From<WorkspaceId> for i64 {
540 fn from(val: WorkspaceId) -> Self {
541 val.0
542 }
543}
544
545fn prompt_and_open_paths(app_state: Arc<AppState>, options: PathPromptOptions, cx: &mut App) {
546 let paths = cx.prompt_for_paths(options);
547 cx.spawn(
548 async move |cx| match paths.await.anyhow().and_then(|res| res) {
549 Ok(Some(paths)) => {
550 cx.update(|cx| {
551 open_paths(&paths, app_state, OpenOptions::default(), cx).detach_and_log_err(cx)
552 })
553 .ok();
554 }
555 Ok(None) => {}
556 Err(err) => {
557 util::log_err(&err);
558 cx.update(|cx| {
559 if let Some(workspace_window) = cx
560 .active_window()
561 .and_then(|window| window.downcast::<Workspace>())
562 {
563 workspace_window
564 .update(cx, |workspace, _, cx| {
565 workspace.show_portal_error(err.to_string(), cx);
566 })
567 .ok();
568 }
569 })
570 .ok();
571 }
572 },
573 )
574 .detach();
575}
576
577pub fn init(app_state: Arc<AppState>, cx: &mut App) {
578 component::init();
579 theme_preview::init(cx);
580 toast_layer::init(cx);
581 history_manager::init(cx);
582
583 cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
584 .on_action(|_: &Reload, cx| reload(cx))
585 .on_action({
586 let app_state = Arc::downgrade(&app_state);
587 move |_: &Open, cx: &mut App| {
588 if let Some(app_state) = app_state.upgrade() {
589 prompt_and_open_paths(
590 app_state,
591 PathPromptOptions {
592 files: true,
593 directories: true,
594 multiple: true,
595 prompt: None,
596 },
597 cx,
598 );
599 }
600 }
601 })
602 .on_action({
603 let app_state = Arc::downgrade(&app_state);
604 move |_: &OpenFiles, cx: &mut App| {
605 let directories = cx.can_select_mixed_files_and_dirs();
606 if let Some(app_state) = app_state.upgrade() {
607 prompt_and_open_paths(
608 app_state,
609 PathPromptOptions {
610 files: true,
611 directories,
612 multiple: true,
613 prompt: None,
614 },
615 cx,
616 );
617 }
618 }
619 });
620}
621
622type BuildProjectItemFn =
623 fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
624
625type BuildProjectItemForPathFn =
626 fn(
627 &Entity<Project>,
628 &ProjectPath,
629 &mut Window,
630 &mut App,
631 ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
632
633#[derive(Clone, Default)]
634struct ProjectItemRegistry {
635 build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
636 build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
637}
638
639impl ProjectItemRegistry {
640 fn register<T: ProjectItem>(&mut self) {
641 self.build_project_item_fns_by_type.insert(
642 TypeId::of::<T::Item>(),
643 |item, project, pane, window, cx| {
644 let item = item.downcast().unwrap();
645 Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
646 as Box<dyn ItemHandle>
647 },
648 );
649 self.build_project_item_for_path_fns
650 .push(|project, project_path, window, cx| {
651 let project_path = project_path.clone();
652 let is_file = project
653 .read(cx)
654 .entry_for_path(&project_path, cx)
655 .is_some_and(|entry| entry.is_file());
656 let entry_abs_path = project.read(cx).absolute_path(&project_path, cx);
657 let is_local = project.read(cx).is_local();
658 let project_item =
659 <T::Item as project::ProjectItem>::try_open(project, &project_path, cx)?;
660 let project = project.clone();
661 Some(window.spawn(cx, async move |cx| {
662 match project_item.await.with_context(|| {
663 format!(
664 "opening project path {:?}",
665 entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
666 )
667 }) {
668 Ok(project_item) => {
669 let project_item = project_item;
670 let project_entry_id: Option<ProjectEntryId> =
671 project_item.read_with(cx, project::ProjectItem::entry_id)?;
672 let build_workspace_item = Box::new(
673 |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
674 Box::new(cx.new(|cx| {
675 T::for_project_item(
676 project,
677 Some(pane),
678 project_item,
679 window,
680 cx,
681 )
682 })) as Box<dyn ItemHandle>
683 },
684 ) as Box<_>;
685 Ok((project_entry_id, build_workspace_item))
686 }
687 Err(e) => {
688 log::warn!("Failed to open a project item: {e:#}");
689 if e.error_code() == ErrorCode::Internal {
690 if let Some(abs_path) =
691 entry_abs_path.as_deref().filter(|_| is_file)
692 {
693 if let Some(broken_project_item_view) =
694 cx.update(|window, cx| {
695 T::for_broken_project_item(
696 abs_path, is_local, &e, window, cx,
697 )
698 })?
699 {
700 let build_workspace_item = Box::new(
701 move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
702 cx.new(|_| broken_project_item_view).boxed_clone()
703 },
704 )
705 as Box<_>;
706 return Ok((None, build_workspace_item));
707 }
708 }
709 }
710 Err(e)
711 }
712 }
713 }))
714 });
715 }
716
717 fn open_path(
718 &self,
719 project: &Entity<Project>,
720 path: &ProjectPath,
721 window: &mut Window,
722 cx: &mut App,
723 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
724 let Some(open_project_item) = self
725 .build_project_item_for_path_fns
726 .iter()
727 .rev()
728 .find_map(|open_project_item| open_project_item(project, path, window, cx))
729 else {
730 return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
731 };
732 open_project_item
733 }
734
735 fn build_item<T: project::ProjectItem>(
736 &self,
737 item: Entity<T>,
738 project: Entity<Project>,
739 pane: Option<&Pane>,
740 window: &mut Window,
741 cx: &mut App,
742 ) -> Option<Box<dyn ItemHandle>> {
743 let build = self
744 .build_project_item_fns_by_type
745 .get(&TypeId::of::<T>())?;
746 Some(build(item.into_any(), project, pane, window, cx))
747 }
748}
749
750type WorkspaceItemBuilder =
751 Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
752
753impl Global for ProjectItemRegistry {}
754
755/// Registers a [ProjectItem] for the app. When opening a file, all the registered
756/// items will get a chance to open the file, starting from the project item that
757/// was added last.
758pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
759 cx.default_global::<ProjectItemRegistry>().register::<I>();
760}
761
762#[derive(Default)]
763pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
764
765struct FollowableViewDescriptor {
766 from_state_proto: fn(
767 Entity<Workspace>,
768 ViewId,
769 &mut Option<proto::view::Variant>,
770 &mut Window,
771 &mut App,
772 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
773 to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
774}
775
776impl Global for FollowableViewRegistry {}
777
778impl FollowableViewRegistry {
779 pub fn register<I: FollowableItem>(cx: &mut App) {
780 cx.default_global::<Self>().0.insert(
781 TypeId::of::<I>(),
782 FollowableViewDescriptor {
783 from_state_proto: |workspace, id, state, window, cx| {
784 I::from_state_proto(workspace, id, state, window, cx).map(|task| {
785 cx.foreground_executor()
786 .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
787 })
788 },
789 to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
790 },
791 );
792 }
793
794 pub fn from_state_proto(
795 workspace: Entity<Workspace>,
796 view_id: ViewId,
797 mut state: Option<proto::view::Variant>,
798 window: &mut Window,
799 cx: &mut App,
800 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
801 cx.update_default_global(|this: &mut Self, cx| {
802 this.0.values().find_map(|descriptor| {
803 (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
804 })
805 })
806 }
807
808 pub fn to_followable_view(
809 view: impl Into<AnyView>,
810 cx: &App,
811 ) -> Option<Box<dyn FollowableItemHandle>> {
812 let this = cx.try_global::<Self>()?;
813 let view = view.into();
814 let descriptor = this.0.get(&view.entity_type())?;
815 Some((descriptor.to_followable_view)(&view))
816 }
817}
818
819#[derive(Copy, Clone)]
820struct SerializableItemDescriptor {
821 deserialize: fn(
822 Entity<Project>,
823 WeakEntity<Workspace>,
824 WorkspaceId,
825 ItemId,
826 &mut Window,
827 &mut Context<Pane>,
828 ) -> Task<Result<Box<dyn ItemHandle>>>,
829 cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
830 view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
831}
832
833#[derive(Default)]
834struct SerializableItemRegistry {
835 descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
836 descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
837}
838
839impl Global for SerializableItemRegistry {}
840
841impl SerializableItemRegistry {
842 fn deserialize(
843 item_kind: &str,
844 project: Entity<Project>,
845 workspace: WeakEntity<Workspace>,
846 workspace_id: WorkspaceId,
847 item_item: ItemId,
848 window: &mut Window,
849 cx: &mut Context<Pane>,
850 ) -> Task<Result<Box<dyn ItemHandle>>> {
851 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
852 return Task::ready(Err(anyhow!(
853 "cannot deserialize {}, descriptor not found",
854 item_kind
855 )));
856 };
857
858 (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
859 }
860
861 fn cleanup(
862 item_kind: &str,
863 workspace_id: WorkspaceId,
864 loaded_items: Vec<ItemId>,
865 window: &mut Window,
866 cx: &mut App,
867 ) -> Task<Result<()>> {
868 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
869 return Task::ready(Err(anyhow!(
870 "cannot cleanup {}, descriptor not found",
871 item_kind
872 )));
873 };
874
875 (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
876 }
877
878 fn view_to_serializable_item_handle(
879 view: AnyView,
880 cx: &App,
881 ) -> Option<Box<dyn SerializableItemHandle>> {
882 let this = cx.try_global::<Self>()?;
883 let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
884 Some((descriptor.view_to_serializable_item)(view))
885 }
886
887 fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
888 let this = cx.try_global::<Self>()?;
889 this.descriptors_by_kind.get(item_kind).copied()
890 }
891}
892
893pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
894 let serialized_item_kind = I::serialized_item_kind();
895
896 let registry = cx.default_global::<SerializableItemRegistry>();
897 let descriptor = SerializableItemDescriptor {
898 deserialize: |project, workspace, workspace_id, item_id, window, cx| {
899 let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
900 cx.foreground_executor()
901 .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
902 },
903 cleanup: |workspace_id, loaded_items, window, cx| {
904 I::cleanup(workspace_id, loaded_items, window, cx)
905 },
906 view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
907 };
908 registry
909 .descriptors_by_kind
910 .insert(Arc::from(serialized_item_kind), descriptor);
911 registry
912 .descriptors_by_type
913 .insert(TypeId::of::<I>(), descriptor);
914}
915
916pub struct AppState {
917 pub languages: Arc<LanguageRegistry>,
918 pub client: Arc<Client>,
919 pub user_store: Entity<UserStore>,
920 pub workspace_store: Entity<WorkspaceStore>,
921 pub fs: Arc<dyn fs::Fs>,
922 pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
923 pub node_runtime: NodeRuntime,
924 pub session: Entity<AppSession>,
925}
926
927struct GlobalAppState(Weak<AppState>);
928
929impl Global for GlobalAppState {}
930
931pub struct WorkspaceStore {
932 workspaces: HashSet<WindowHandle<Workspace>>,
933 client: Arc<Client>,
934 _subscriptions: Vec<client::Subscription>,
935}
936
937#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
938pub enum CollaboratorId {
939 PeerId(PeerId),
940 Agent,
941}
942
943impl From<PeerId> for CollaboratorId {
944 fn from(peer_id: PeerId) -> Self {
945 CollaboratorId::PeerId(peer_id)
946 }
947}
948
949impl From<&PeerId> for CollaboratorId {
950 fn from(peer_id: &PeerId) -> Self {
951 CollaboratorId::PeerId(*peer_id)
952 }
953}
954
955#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
956struct Follower {
957 project_id: Option<u64>,
958 peer_id: PeerId,
959}
960
961impl AppState {
962 #[track_caller]
963 pub fn global(cx: &App) -> Weak<Self> {
964 cx.global::<GlobalAppState>().0.clone()
965 }
966 pub fn try_global(cx: &App) -> Option<Weak<Self>> {
967 cx.try_global::<GlobalAppState>()
968 .map(|state| state.0.clone())
969 }
970 pub fn set_global(state: Weak<AppState>, cx: &mut App) {
971 cx.set_global(GlobalAppState(state));
972 }
973
974 #[cfg(any(test, feature = "test-support"))]
975 pub fn test(cx: &mut App) -> Arc<Self> {
976 use node_runtime::NodeRuntime;
977 use session::Session;
978 use settings::SettingsStore;
979
980 if !cx.has_global::<SettingsStore>() {
981 let settings_store = SettingsStore::test(cx);
982 cx.set_global(settings_store);
983 }
984
985 let fs = fs::FakeFs::new(cx.background_executor().clone());
986 let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
987 let clock = Arc::new(clock::FakeSystemClock::new());
988 let http_client = http_client::FakeHttpClient::with_404_response();
989 let client = Client::new(clock, http_client, cx);
990 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
991 let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
992 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
993
994 theme::init(theme::LoadThemes::JustBase, cx);
995 client::init(&client, cx);
996
997 Arc::new(Self {
998 client,
999 fs,
1000 languages,
1001 user_store,
1002 workspace_store,
1003 node_runtime: NodeRuntime::unavailable(),
1004 build_window_options: |_, _| Default::default(),
1005 session,
1006 })
1007 }
1008}
1009
1010struct DelayedDebouncedEditAction {
1011 task: Option<Task<()>>,
1012 cancel_channel: Option<oneshot::Sender<()>>,
1013}
1014
1015impl DelayedDebouncedEditAction {
1016 fn new() -> DelayedDebouncedEditAction {
1017 DelayedDebouncedEditAction {
1018 task: None,
1019 cancel_channel: None,
1020 }
1021 }
1022
1023 fn fire_new<F>(
1024 &mut self,
1025 delay: Duration,
1026 window: &mut Window,
1027 cx: &mut Context<Workspace>,
1028 func: F,
1029 ) where
1030 F: 'static
1031 + Send
1032 + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
1033 {
1034 if let Some(channel) = self.cancel_channel.take() {
1035 _ = channel.send(());
1036 }
1037
1038 let (sender, mut receiver) = oneshot::channel::<()>();
1039 self.cancel_channel = Some(sender);
1040
1041 let previous_task = self.task.take();
1042 self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
1043 let mut timer = cx.background_executor().timer(delay).fuse();
1044 if let Some(previous_task) = previous_task {
1045 previous_task.await;
1046 }
1047
1048 futures::select_biased! {
1049 _ = receiver => return,
1050 _ = timer => {}
1051 }
1052
1053 if let Some(result) = workspace
1054 .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
1055 .log_err()
1056 {
1057 result.await.log_err();
1058 }
1059 }));
1060 }
1061}
1062
1063pub enum Event {
1064 PaneAdded(Entity<Pane>),
1065 PaneRemoved,
1066 ItemAdded {
1067 item: Box<dyn ItemHandle>,
1068 },
1069 ActiveItemChanged,
1070 ItemRemoved {
1071 item_id: EntityId,
1072 },
1073 UserSavedItem {
1074 pane: WeakEntity<Pane>,
1075 item: Box<dyn WeakItemHandle>,
1076 save_intent: SaveIntent,
1077 },
1078 ContactRequestedJoin(u64),
1079 WorkspaceCreated(WeakEntity<Workspace>),
1080 OpenBundledFile {
1081 text: Cow<'static, str>,
1082 title: &'static str,
1083 language: &'static str,
1084 },
1085 ZoomChanged,
1086 ModalOpened,
1087}
1088
1089#[derive(Debug)]
1090pub enum OpenVisible {
1091 All,
1092 None,
1093 OnlyFiles,
1094 OnlyDirectories,
1095}
1096
1097enum WorkspaceLocation {
1098 // Valid local paths or SSH project to serialize
1099 Location(SerializedWorkspaceLocation, PathList),
1100 // No valid location found hence clear session id
1101 DetachFromSession,
1102 // No valid location found to serialize
1103 None,
1104}
1105
1106type PromptForNewPath = Box<
1107 dyn Fn(
1108 &mut Workspace,
1109 DirectoryLister,
1110 &mut Window,
1111 &mut Context<Workspace>,
1112 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1113>;
1114
1115type PromptForOpenPath = Box<
1116 dyn Fn(
1117 &mut Workspace,
1118 DirectoryLister,
1119 &mut Window,
1120 &mut Context<Workspace>,
1121 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1122>;
1123
1124#[derive(Default)]
1125struct DispatchingKeystrokes {
1126 dispatched: HashSet<Vec<Keystroke>>,
1127 queue: VecDeque<Keystroke>,
1128 task: Option<Shared<Task<()>>>,
1129}
1130
1131/// Collects everything project-related for a certain window opened.
1132/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
1133///
1134/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
1135/// The `Workspace` owns everybody's state and serves as a default, "global context",
1136/// that can be used to register a global action to be triggered from any place in the window.
1137pub struct Workspace {
1138 weak_self: WeakEntity<Self>,
1139 workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
1140 zoomed: Option<AnyWeakView>,
1141 previous_dock_drag_coordinates: Option<Point<Pixels>>,
1142 zoomed_position: Option<DockPosition>,
1143 center: PaneGroup,
1144 left_dock: Entity<Dock>,
1145 bottom_dock: Entity<Dock>,
1146 right_dock: Entity<Dock>,
1147 panes: Vec<Entity<Pane>>,
1148 panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
1149 active_pane: Entity<Pane>,
1150 last_active_center_pane: Option<WeakEntity<Pane>>,
1151 last_active_view_id: Option<proto::ViewId>,
1152 status_bar: Entity<StatusBar>,
1153 modal_layer: Entity<ModalLayer>,
1154 toast_layer: Entity<ToastLayer>,
1155 titlebar_item: Option<AnyView>,
1156 notifications: Notifications,
1157 suppressed_notifications: HashSet<NotificationId>,
1158 project: Entity<Project>,
1159 follower_states: HashMap<CollaboratorId, FollowerState>,
1160 last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
1161 window_edited: bool,
1162 last_window_title: Option<String>,
1163 dirty_items: HashMap<EntityId, Subscription>,
1164 active_call: Option<(Entity<ActiveCall>, Vec<Subscription>)>,
1165 leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
1166 database_id: Option<WorkspaceId>,
1167 app_state: Arc<AppState>,
1168 dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
1169 _subscriptions: Vec<Subscription>,
1170 _apply_leader_updates: Task<Result<()>>,
1171 _observe_current_user: Task<Result<()>>,
1172 _schedule_serialize_workspace: Option<Task<()>>,
1173 _schedule_serialize_ssh_paths: Option<Task<()>>,
1174 pane_history_timestamp: Arc<AtomicUsize>,
1175 bounds: Bounds<Pixels>,
1176 pub centered_layout: bool,
1177 bounds_save_task_queued: Option<Task<()>>,
1178 on_prompt_for_new_path: Option<PromptForNewPath>,
1179 on_prompt_for_open_path: Option<PromptForOpenPath>,
1180 terminal_provider: Option<Box<dyn TerminalProvider>>,
1181 debugger_provider: Option<Arc<dyn DebuggerProvider>>,
1182 serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
1183 _items_serializer: Task<Result<()>>,
1184 session_id: Option<String>,
1185 scheduled_tasks: Vec<Task<()>>,
1186 last_open_dock_positions: Vec<DockPosition>,
1187 removing: bool,
1188 utility_panes: UtilityPaneState,
1189}
1190
1191impl EventEmitter<Event> for Workspace {}
1192
1193#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1194pub struct ViewId {
1195 pub creator: CollaboratorId,
1196 pub id: u64,
1197}
1198
1199pub struct FollowerState {
1200 center_pane: Entity<Pane>,
1201 dock_pane: Option<Entity<Pane>>,
1202 active_view_id: Option<ViewId>,
1203 items_by_leader_view_id: HashMap<ViewId, FollowerView>,
1204}
1205
1206struct FollowerView {
1207 view: Box<dyn FollowableItemHandle>,
1208 location: Option<proto::PanelId>,
1209}
1210
1211impl Workspace {
1212 pub fn new(
1213 workspace_id: Option<WorkspaceId>,
1214 project: Entity<Project>,
1215 app_state: Arc<AppState>,
1216 window: &mut Window,
1217 cx: &mut Context<Self>,
1218 ) -> Self {
1219 cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
1220 match event {
1221 project::Event::RemoteIdChanged(_) => {
1222 this.update_window_title(window, cx);
1223 }
1224
1225 project::Event::CollaboratorLeft(peer_id) => {
1226 this.collaborator_left(*peer_id, window, cx);
1227 }
1228
1229 project::Event::WorktreeRemoved(_) | project::Event::WorktreeAdded(_) => {
1230 this.update_window_title(window, cx);
1231 this.serialize_workspace(window, cx);
1232 // This event could be triggered by `AddFolderToProject` or `RemoveFromProject`.
1233 this.update_history(cx);
1234 }
1235
1236 project::Event::DisconnectedFromHost => {
1237 this.update_window_edited(window, cx);
1238 let leaders_to_unfollow =
1239 this.follower_states.keys().copied().collect::<Vec<_>>();
1240 for leader_id in leaders_to_unfollow {
1241 this.unfollow(leader_id, window, cx);
1242 }
1243 }
1244
1245 project::Event::DisconnectedFromSshRemote => {
1246 this.update_window_edited(window, cx);
1247 }
1248
1249 project::Event::Closed => {
1250 window.remove_window();
1251 }
1252
1253 project::Event::DeletedEntry(_, entry_id) => {
1254 for pane in this.panes.iter() {
1255 pane.update(cx, |pane, cx| {
1256 pane.handle_deleted_project_item(*entry_id, window, cx)
1257 });
1258 }
1259 }
1260
1261 project::Event::Toast {
1262 notification_id,
1263 message,
1264 } => this.show_notification(
1265 NotificationId::named(notification_id.clone()),
1266 cx,
1267 |cx| cx.new(|cx| MessageNotification::new(message.clone(), cx)),
1268 ),
1269
1270 project::Event::HideToast { notification_id } => {
1271 this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
1272 }
1273
1274 project::Event::LanguageServerPrompt(request) => {
1275 struct LanguageServerPrompt;
1276
1277 let mut hasher = DefaultHasher::new();
1278 request.lsp_name.as_str().hash(&mut hasher);
1279 let id = hasher.finish();
1280
1281 this.show_notification(
1282 NotificationId::composite::<LanguageServerPrompt>(id as usize),
1283 cx,
1284 |cx| {
1285 cx.new(|cx| {
1286 notifications::LanguageServerPrompt::new(request.clone(), cx)
1287 })
1288 },
1289 );
1290 }
1291
1292 project::Event::AgentLocationChanged => {
1293 this.handle_agent_location_changed(window, cx)
1294 }
1295
1296 _ => {}
1297 }
1298 cx.notify()
1299 })
1300 .detach();
1301
1302 cx.subscribe_in(
1303 &project.read(cx).breakpoint_store(),
1304 window,
1305 |workspace, _, event, window, cx| match event {
1306 BreakpointStoreEvent::BreakpointsUpdated(_, _)
1307 | BreakpointStoreEvent::BreakpointsCleared(_) => {
1308 workspace.serialize_workspace(window, cx);
1309 }
1310 BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
1311 },
1312 )
1313 .detach();
1314 if let Some(toolchain_store) = project.read(cx).toolchain_store() {
1315 cx.subscribe_in(
1316 &toolchain_store,
1317 window,
1318 |workspace, _, event, window, cx| match event {
1319 ToolchainStoreEvent::CustomToolchainsModified => {
1320 workspace.serialize_workspace(window, cx);
1321 }
1322 _ => {}
1323 },
1324 )
1325 .detach();
1326 }
1327
1328 cx.on_focus_lost(window, |this, window, cx| {
1329 let focus_handle = this.focus_handle(cx);
1330 window.focus(&focus_handle);
1331 })
1332 .detach();
1333
1334 let weak_handle = cx.entity().downgrade();
1335 let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
1336
1337 let center_pane = cx.new(|cx| {
1338 let mut center_pane = Pane::new(
1339 weak_handle.clone(),
1340 project.clone(),
1341 pane_history_timestamp.clone(),
1342 None,
1343 NewFile.boxed_clone(),
1344 true,
1345 window,
1346 cx,
1347 );
1348 center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
1349 center_pane
1350 });
1351 cx.subscribe_in(¢er_pane, window, Self::handle_pane_event)
1352 .detach();
1353
1354 window.focus(¢er_pane.focus_handle(cx));
1355
1356 cx.emit(Event::PaneAdded(center_pane.clone()));
1357
1358 let window_handle = window.window_handle().downcast::<Workspace>().unwrap();
1359 app_state.workspace_store.update(cx, |store, _| {
1360 store.workspaces.insert(window_handle);
1361 });
1362
1363 let mut current_user = app_state.user_store.read(cx).watch_current_user();
1364 let mut connection_status = app_state.client.status();
1365 let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
1366 current_user.next().await;
1367 connection_status.next().await;
1368 let mut stream =
1369 Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
1370
1371 while stream.recv().await.is_some() {
1372 this.update(cx, |_, cx| cx.notify())?;
1373 }
1374 anyhow::Ok(())
1375 });
1376
1377 // All leader updates are enqueued and then processed in a single task, so
1378 // that each asynchronous operation can be run in order.
1379 let (leader_updates_tx, mut leader_updates_rx) =
1380 mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
1381 let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
1382 while let Some((leader_id, update)) = leader_updates_rx.next().await {
1383 Self::process_leader_update(&this, leader_id, update, cx)
1384 .await
1385 .log_err();
1386 }
1387
1388 Ok(())
1389 });
1390
1391 cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
1392 let modal_layer = cx.new(|_| ModalLayer::new());
1393 let toast_layer = cx.new(|_| ToastLayer::new());
1394 cx.subscribe(
1395 &modal_layer,
1396 |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
1397 cx.emit(Event::ModalOpened);
1398 },
1399 )
1400 .detach();
1401
1402 let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
1403 let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
1404 let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
1405 let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
1406 let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
1407 let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
1408 let status_bar = cx.new(|cx| {
1409 let mut status_bar = StatusBar::new(¢er_pane.clone(), window, cx);
1410 status_bar.add_left_item(left_dock_buttons, window, cx);
1411 status_bar.add_right_item(right_dock_buttons, window, cx);
1412 status_bar.add_right_item(bottom_dock_buttons, window, cx);
1413 status_bar
1414 });
1415
1416 let session_id = app_state.session.read(cx).id().to_owned();
1417
1418 let mut active_call = None;
1419 if let Some(call) = ActiveCall::try_global(cx) {
1420 let subscriptions = vec![cx.subscribe_in(&call, window, Self::on_active_call_event)];
1421 active_call = Some((call, subscriptions));
1422 }
1423
1424 let (serializable_items_tx, serializable_items_rx) =
1425 mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
1426 let _items_serializer = cx.spawn_in(window, async move |this, cx| {
1427 Self::serialize_items(&this, serializable_items_rx, cx).await
1428 });
1429
1430 let subscriptions = vec![
1431 cx.observe_window_activation(window, Self::on_window_activation_changed),
1432 cx.observe_window_bounds(window, move |this, window, cx| {
1433 if this.bounds_save_task_queued.is_some() {
1434 return;
1435 }
1436 this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
1437 cx.background_executor()
1438 .timer(Duration::from_millis(100))
1439 .await;
1440 this.update_in(cx, |this, window, cx| {
1441 if let Some(display) = window.display(cx)
1442 && let Ok(display_uuid) = display.uuid()
1443 {
1444 let window_bounds = window.inner_window_bounds();
1445 if let Some(database_id) = workspace_id {
1446 cx.background_executor()
1447 .spawn(DB.set_window_open_status(
1448 database_id,
1449 SerializedWindowBounds(window_bounds),
1450 display_uuid,
1451 ))
1452 .detach_and_log_err(cx);
1453 }
1454 }
1455 this.bounds_save_task_queued.take();
1456 })
1457 .ok();
1458 }));
1459 cx.notify();
1460 }),
1461 cx.observe_window_appearance(window, |_, window, cx| {
1462 let window_appearance = window.appearance();
1463
1464 *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
1465
1466 GlobalTheme::reload_theme(cx);
1467 GlobalTheme::reload_icon_theme(cx);
1468 }),
1469 cx.on_release(move |this, cx| {
1470 this.app_state.workspace_store.update(cx, move |store, _| {
1471 store.workspaces.remove(&window_handle);
1472 })
1473 }),
1474 ];
1475
1476 cx.defer_in(window, |this, window, cx| {
1477 this.update_window_title(window, cx);
1478 this.show_initial_notifications(cx);
1479 });
1480
1481 let mut center = PaneGroup::new(center_pane.clone());
1482 center.set_is_center(true);
1483 center.mark_positions(cx);
1484
1485 Workspace {
1486 weak_self: weak_handle.clone(),
1487 zoomed: None,
1488 zoomed_position: None,
1489 previous_dock_drag_coordinates: None,
1490 center,
1491 panes: vec![center_pane.clone()],
1492 panes_by_item: Default::default(),
1493 active_pane: center_pane.clone(),
1494 last_active_center_pane: Some(center_pane.downgrade()),
1495 last_active_view_id: None,
1496 status_bar,
1497 modal_layer,
1498 toast_layer,
1499 titlebar_item: None,
1500 notifications: Notifications::default(),
1501 suppressed_notifications: HashSet::default(),
1502 left_dock,
1503 bottom_dock,
1504 right_dock,
1505 project: project.clone(),
1506 follower_states: Default::default(),
1507 last_leaders_by_pane: Default::default(),
1508 dispatching_keystrokes: Default::default(),
1509 window_edited: false,
1510 last_window_title: None,
1511 dirty_items: Default::default(),
1512 active_call,
1513 database_id: workspace_id,
1514 app_state,
1515 _observe_current_user,
1516 _apply_leader_updates,
1517 _schedule_serialize_workspace: None,
1518 _schedule_serialize_ssh_paths: None,
1519 leader_updates_tx,
1520 _subscriptions: subscriptions,
1521 pane_history_timestamp,
1522 workspace_actions: Default::default(),
1523 // This data will be incorrect, but it will be overwritten by the time it needs to be used.
1524 bounds: Default::default(),
1525 centered_layout: false,
1526 bounds_save_task_queued: None,
1527 on_prompt_for_new_path: None,
1528 on_prompt_for_open_path: None,
1529 terminal_provider: None,
1530 debugger_provider: None,
1531 serializable_items_tx,
1532 _items_serializer,
1533 session_id: Some(session_id),
1534
1535 scheduled_tasks: Vec::new(),
1536 last_open_dock_positions: Vec::new(),
1537 removing: false,
1538 utility_panes: UtilityPaneState::default(),
1539 }
1540 }
1541
1542 pub fn new_local(
1543 abs_paths: Vec<PathBuf>,
1544 app_state: Arc<AppState>,
1545 requesting_window: Option<WindowHandle<Workspace>>,
1546 env: Option<HashMap<String, String>>,
1547 cx: &mut App,
1548 ) -> Task<
1549 anyhow::Result<(
1550 WindowHandle<Workspace>,
1551 Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
1552 )>,
1553 > {
1554 let project_handle = Project::local(
1555 app_state.client.clone(),
1556 app_state.node_runtime.clone(),
1557 app_state.user_store.clone(),
1558 app_state.languages.clone(),
1559 app_state.fs.clone(),
1560 env,
1561 cx,
1562 );
1563
1564 cx.spawn(async move |cx| {
1565 let mut paths_to_open = Vec::with_capacity(abs_paths.len());
1566 for path in abs_paths.into_iter() {
1567 if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
1568 paths_to_open.push(canonical)
1569 } else {
1570 paths_to_open.push(path)
1571 }
1572 }
1573
1574 let serialized_workspace =
1575 persistence::DB.workspace_for_roots(paths_to_open.as_slice());
1576
1577 if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
1578 paths_to_open = paths.ordered_paths().cloned().collect();
1579 if !paths.is_lexicographically_ordered() {
1580 project_handle
1581 .update(cx, |project, cx| {
1582 project.set_worktrees_reordered(true, cx);
1583 })
1584 .log_err();
1585 }
1586 }
1587
1588 // Get project paths for all of the abs_paths
1589 let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
1590 Vec::with_capacity(paths_to_open.len());
1591
1592 for path in paths_to_open.into_iter() {
1593 if let Some((_, project_entry)) = cx
1594 .update(|cx| {
1595 Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
1596 })?
1597 .await
1598 .log_err()
1599 {
1600 project_paths.push((path, Some(project_entry)));
1601 } else {
1602 project_paths.push((path, None));
1603 }
1604 }
1605
1606 let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
1607 serialized_workspace.id
1608 } else {
1609 DB.next_id().await.unwrap_or_else(|_| Default::default())
1610 };
1611
1612 let toolchains = DB.toolchains(workspace_id).await?;
1613
1614 for (toolchain, worktree_id, path) in toolchains {
1615 let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
1616 if !app_state.fs.is_file(toolchain_path.as_path()).await {
1617 continue;
1618 }
1619
1620 project_handle
1621 .update(cx, |this, cx| {
1622 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
1623 })?
1624 .await;
1625 }
1626 if let Some(workspace) = serialized_workspace.as_ref() {
1627 project_handle.update(cx, |this, cx| {
1628 for (scope, toolchains) in &workspace.user_toolchains {
1629 for toolchain in toolchains {
1630 this.add_toolchain(toolchain.clone(), scope.clone(), cx);
1631 }
1632 }
1633 })?;
1634 }
1635
1636 let window = if let Some(window) = requesting_window {
1637 let centered_layout = serialized_workspace
1638 .as_ref()
1639 .map(|w| w.centered_layout)
1640 .unwrap_or(false);
1641
1642 cx.update_window(window.into(), |_, window, cx| {
1643 window.replace_root(cx, |window, cx| {
1644 let mut workspace = Workspace::new(
1645 Some(workspace_id),
1646 project_handle.clone(),
1647 app_state.clone(),
1648 window,
1649 cx,
1650 );
1651
1652 workspace.centered_layout = centered_layout;
1653 workspace
1654 });
1655 })?;
1656 window
1657 } else {
1658 let window_bounds_override = window_bounds_env_override();
1659
1660 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
1661 (Some(WindowBounds::Windowed(bounds)), None)
1662 } else if let Some(workspace) = serialized_workspace.as_ref() {
1663 // Reopening an existing workspace - restore its saved bounds
1664 if let (Some(display), Some(bounds)) =
1665 (workspace.display, workspace.window_bounds.as_ref())
1666 {
1667 (Some(bounds.0), Some(display))
1668 } else {
1669 (None, None)
1670 }
1671 } else {
1672 // New window - let GPUI's default_bounds() handle cascading
1673 (None, None)
1674 };
1675
1676 // Use the serialized workspace to construct the new window
1677 let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx))?;
1678 options.window_bounds = window_bounds;
1679 let centered_layout = serialized_workspace
1680 .as_ref()
1681 .map(|w| w.centered_layout)
1682 .unwrap_or(false);
1683 cx.open_window(options, {
1684 let app_state = app_state.clone();
1685 let project_handle = project_handle.clone();
1686 move |window, cx| {
1687 cx.new(|cx| {
1688 let mut workspace = Workspace::new(
1689 Some(workspace_id),
1690 project_handle,
1691 app_state,
1692 window,
1693 cx,
1694 );
1695 workspace.centered_layout = centered_layout;
1696 workspace
1697 })
1698 }
1699 })?
1700 };
1701
1702 notify_if_database_failed(window, cx);
1703 let opened_items = window
1704 .update(cx, |_workspace, window, cx| {
1705 open_items(serialized_workspace, project_paths, window, cx)
1706 })?
1707 .await
1708 .unwrap_or_default();
1709
1710 window
1711 .update(cx, |workspace, window, cx| {
1712 window.activate_window();
1713 workspace.update_history(cx);
1714 })
1715 .log_err();
1716 Ok((window, opened_items))
1717 })
1718 }
1719
1720 pub fn weak_handle(&self) -> WeakEntity<Self> {
1721 self.weak_self.clone()
1722 }
1723
1724 pub fn left_dock(&self) -> &Entity<Dock> {
1725 &self.left_dock
1726 }
1727
1728 pub fn bottom_dock(&self) -> &Entity<Dock> {
1729 &self.bottom_dock
1730 }
1731
1732 pub fn set_bottom_dock_layout(
1733 &mut self,
1734 layout: BottomDockLayout,
1735 window: &mut Window,
1736 cx: &mut Context<Self>,
1737 ) {
1738 let fs = self.project().read(cx).fs();
1739 settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
1740 content.workspace.bottom_dock_layout = Some(layout);
1741 });
1742
1743 cx.notify();
1744 self.serialize_workspace(window, cx);
1745 }
1746
1747 pub fn right_dock(&self) -> &Entity<Dock> {
1748 &self.right_dock
1749 }
1750
1751 pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
1752 [&self.left_dock, &self.bottom_dock, &self.right_dock]
1753 }
1754
1755 pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
1756 match position {
1757 DockPosition::Left => &self.left_dock,
1758 DockPosition::Bottom => &self.bottom_dock,
1759 DockPosition::Right => &self.right_dock,
1760 }
1761 }
1762
1763 pub fn is_edited(&self) -> bool {
1764 self.window_edited
1765 }
1766
1767 pub fn add_panel<T: Panel>(
1768 &mut self,
1769 panel: Entity<T>,
1770 window: &mut Window,
1771 cx: &mut Context<Self>,
1772 ) {
1773 let focus_handle = panel.panel_focus_handle(cx);
1774 cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
1775 .detach();
1776
1777 let dock_position = panel.position(window, cx);
1778 let dock = self.dock_at_position(dock_position);
1779
1780 dock.update(cx, |dock, cx| {
1781 dock.add_panel(panel, self.weak_self.clone(), window, cx)
1782 });
1783 }
1784
1785 pub fn remove_panel<T: Panel>(
1786 &mut self,
1787 panel: &Entity<T>,
1788 window: &mut Window,
1789 cx: &mut Context<Self>,
1790 ) {
1791 for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
1792 dock.update(cx, |dock, cx| {
1793 dock.remove_panel(panel, window, cx);
1794 })
1795 }
1796 }
1797
1798 pub fn status_bar(&self) -> &Entity<StatusBar> {
1799 &self.status_bar
1800 }
1801
1802 pub fn status_bar_visible(&self, cx: &App) -> bool {
1803 StatusBarSettings::get_global(cx).show
1804 }
1805
1806 pub fn app_state(&self) -> &Arc<AppState> {
1807 &self.app_state
1808 }
1809
1810 pub fn user_store(&self) -> &Entity<UserStore> {
1811 &self.app_state.user_store
1812 }
1813
1814 pub fn project(&self) -> &Entity<Project> {
1815 &self.project
1816 }
1817
1818 pub fn path_style(&self, cx: &App) -> PathStyle {
1819 self.project.read(cx).path_style(cx)
1820 }
1821
1822 pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
1823 let mut history: HashMap<EntityId, usize> = HashMap::default();
1824
1825 for pane_handle in &self.panes {
1826 let pane = pane_handle.read(cx);
1827
1828 for entry in pane.activation_history() {
1829 history.insert(
1830 entry.entity_id,
1831 history
1832 .get(&entry.entity_id)
1833 .cloned()
1834 .unwrap_or(0)
1835 .max(entry.timestamp),
1836 );
1837 }
1838 }
1839
1840 history
1841 }
1842
1843 pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
1844 let mut recent_item: Option<Entity<T>> = None;
1845 let mut recent_timestamp = 0;
1846 for pane_handle in &self.panes {
1847 let pane = pane_handle.read(cx);
1848 let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
1849 pane.items().map(|item| (item.item_id(), item)).collect();
1850 for entry in pane.activation_history() {
1851 if entry.timestamp > recent_timestamp
1852 && let Some(&item) = item_map.get(&entry.entity_id)
1853 && let Some(typed_item) = item.act_as::<T>(cx)
1854 {
1855 recent_timestamp = entry.timestamp;
1856 recent_item = Some(typed_item);
1857 }
1858 }
1859 }
1860 recent_item
1861 }
1862
1863 pub fn recent_navigation_history_iter(
1864 &self,
1865 cx: &App,
1866 ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
1867 let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
1868 let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
1869
1870 for pane in &self.panes {
1871 let pane = pane.read(cx);
1872
1873 pane.nav_history()
1874 .for_each_entry(cx, |entry, (project_path, fs_path)| {
1875 if let Some(fs_path) = &fs_path {
1876 abs_paths_opened
1877 .entry(fs_path.clone())
1878 .or_default()
1879 .insert(project_path.clone());
1880 }
1881 let timestamp = entry.timestamp;
1882 match history.entry(project_path) {
1883 hash_map::Entry::Occupied(mut entry) => {
1884 let (_, old_timestamp) = entry.get();
1885 if ×tamp > old_timestamp {
1886 entry.insert((fs_path, timestamp));
1887 }
1888 }
1889 hash_map::Entry::Vacant(entry) => {
1890 entry.insert((fs_path, timestamp));
1891 }
1892 }
1893 });
1894
1895 if let Some(item) = pane.active_item()
1896 && let Some(project_path) = item.project_path(cx)
1897 {
1898 let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
1899
1900 if let Some(fs_path) = &fs_path {
1901 abs_paths_opened
1902 .entry(fs_path.clone())
1903 .or_default()
1904 .insert(project_path.clone());
1905 }
1906
1907 history.insert(project_path, (fs_path, std::usize::MAX));
1908 }
1909 }
1910
1911 history
1912 .into_iter()
1913 .sorted_by_key(|(_, (_, order))| *order)
1914 .map(|(project_path, (fs_path, _))| (project_path, fs_path))
1915 .rev()
1916 .filter(move |(history_path, abs_path)| {
1917 let latest_project_path_opened = abs_path
1918 .as_ref()
1919 .and_then(|abs_path| abs_paths_opened.get(abs_path))
1920 .and_then(|project_paths| {
1921 project_paths
1922 .iter()
1923 .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
1924 });
1925
1926 latest_project_path_opened.is_none_or(|path| path == history_path)
1927 })
1928 }
1929
1930 pub fn recent_navigation_history(
1931 &self,
1932 limit: Option<usize>,
1933 cx: &App,
1934 ) -> Vec<(ProjectPath, Option<PathBuf>)> {
1935 self.recent_navigation_history_iter(cx)
1936 .take(limit.unwrap_or(usize::MAX))
1937 .collect()
1938 }
1939
1940 pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
1941 for pane in &self.panes {
1942 pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
1943 }
1944 }
1945
1946 fn navigate_history(
1947 &mut self,
1948 pane: WeakEntity<Pane>,
1949 mode: NavigationMode,
1950 window: &mut Window,
1951 cx: &mut Context<Workspace>,
1952 ) -> Task<Result<()>> {
1953 let to_load = if let Some(pane) = pane.upgrade() {
1954 pane.update(cx, |pane, cx| {
1955 window.focus(&pane.focus_handle(cx));
1956 loop {
1957 // Retrieve the weak item handle from the history.
1958 let entry = pane.nav_history_mut().pop(mode, cx)?;
1959
1960 // If the item is still present in this pane, then activate it.
1961 if let Some(index) = entry
1962 .item
1963 .upgrade()
1964 .and_then(|v| pane.index_for_item(v.as_ref()))
1965 {
1966 let prev_active_item_index = pane.active_item_index();
1967 pane.nav_history_mut().set_mode(mode);
1968 pane.activate_item(index, true, true, window, cx);
1969 pane.nav_history_mut().set_mode(NavigationMode::Normal);
1970
1971 let mut navigated = prev_active_item_index != pane.active_item_index();
1972 if let Some(data) = entry.data {
1973 navigated |= pane.active_item()?.navigate(data, window, cx);
1974 }
1975
1976 if navigated {
1977 break None;
1978 }
1979 } else {
1980 // If the item is no longer present in this pane, then retrieve its
1981 // path info in order to reopen it.
1982 break pane
1983 .nav_history()
1984 .path_for_item(entry.item.id())
1985 .map(|(project_path, abs_path)| (project_path, abs_path, entry));
1986 }
1987 }
1988 })
1989 } else {
1990 None
1991 };
1992
1993 if let Some((project_path, abs_path, entry)) = to_load {
1994 // If the item was no longer present, then load it again from its previous path, first try the local path
1995 let open_by_project_path = self.load_path(project_path.clone(), window, cx);
1996
1997 cx.spawn_in(window, async move |workspace, cx| {
1998 let open_by_project_path = open_by_project_path.await;
1999 let mut navigated = false;
2000 match open_by_project_path
2001 .with_context(|| format!("Navigating to {project_path:?}"))
2002 {
2003 Ok((project_entry_id, build_item)) => {
2004 let prev_active_item_id = pane.update(cx, |pane, _| {
2005 pane.nav_history_mut().set_mode(mode);
2006 pane.active_item().map(|p| p.item_id())
2007 })?;
2008
2009 pane.update_in(cx, |pane, window, cx| {
2010 let item = pane.open_item(
2011 project_entry_id,
2012 project_path,
2013 true,
2014 entry.is_preview,
2015 true,
2016 None,
2017 window, cx,
2018 build_item,
2019 );
2020 navigated |= Some(item.item_id()) != prev_active_item_id;
2021 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2022 if let Some(data) = entry.data {
2023 navigated |= item.navigate(data, window, cx);
2024 }
2025 })?;
2026 }
2027 Err(open_by_project_path_e) => {
2028 // Fall back to opening by abs path, in case an external file was opened and closed,
2029 // and its worktree is now dropped
2030 if let Some(abs_path) = abs_path {
2031 let prev_active_item_id = pane.update(cx, |pane, _| {
2032 pane.nav_history_mut().set_mode(mode);
2033 pane.active_item().map(|p| p.item_id())
2034 })?;
2035 let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
2036 workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
2037 })?;
2038 match open_by_abs_path
2039 .await
2040 .with_context(|| format!("Navigating to {abs_path:?}"))
2041 {
2042 Ok(item) => {
2043 pane.update_in(cx, |pane, window, cx| {
2044 navigated |= Some(item.item_id()) != prev_active_item_id;
2045 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2046 if let Some(data) = entry.data {
2047 navigated |= item.navigate(data, window, cx);
2048 }
2049 })?;
2050 }
2051 Err(open_by_abs_path_e) => {
2052 log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
2053 }
2054 }
2055 }
2056 }
2057 }
2058
2059 if !navigated {
2060 workspace
2061 .update_in(cx, |workspace, window, cx| {
2062 Self::navigate_history(workspace, pane, mode, window, cx)
2063 })?
2064 .await?;
2065 }
2066
2067 Ok(())
2068 })
2069 } else {
2070 Task::ready(Ok(()))
2071 }
2072 }
2073
2074 pub fn go_back(
2075 &mut self,
2076 pane: WeakEntity<Pane>,
2077 window: &mut Window,
2078 cx: &mut Context<Workspace>,
2079 ) -> Task<Result<()>> {
2080 self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
2081 }
2082
2083 pub fn go_forward(
2084 &mut self,
2085 pane: WeakEntity<Pane>,
2086 window: &mut Window,
2087 cx: &mut Context<Workspace>,
2088 ) -> Task<Result<()>> {
2089 self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
2090 }
2091
2092 pub fn reopen_closed_item(
2093 &mut self,
2094 window: &mut Window,
2095 cx: &mut Context<Workspace>,
2096 ) -> Task<Result<()>> {
2097 self.navigate_history(
2098 self.active_pane().downgrade(),
2099 NavigationMode::ReopeningClosedItem,
2100 window,
2101 cx,
2102 )
2103 }
2104
2105 pub fn client(&self) -> &Arc<Client> {
2106 &self.app_state.client
2107 }
2108
2109 pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
2110 self.titlebar_item = Some(item);
2111 cx.notify();
2112 }
2113
2114 pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
2115 self.on_prompt_for_new_path = Some(prompt)
2116 }
2117
2118 pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
2119 self.on_prompt_for_open_path = Some(prompt)
2120 }
2121
2122 pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
2123 self.terminal_provider = Some(Box::new(provider));
2124 }
2125
2126 pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
2127 self.debugger_provider = Some(Arc::new(provider));
2128 }
2129
2130 pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
2131 self.debugger_provider.clone()
2132 }
2133
2134 pub fn prompt_for_open_path(
2135 &mut self,
2136 path_prompt_options: PathPromptOptions,
2137 lister: DirectoryLister,
2138 window: &mut Window,
2139 cx: &mut Context<Self>,
2140 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2141 if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
2142 let prompt = self.on_prompt_for_open_path.take().unwrap();
2143 let rx = prompt(self, lister, window, cx);
2144 self.on_prompt_for_open_path = Some(prompt);
2145 rx
2146 } else {
2147 let (tx, rx) = oneshot::channel();
2148 let abs_path = cx.prompt_for_paths(path_prompt_options);
2149
2150 cx.spawn_in(window, async move |workspace, cx| {
2151 let Ok(result) = abs_path.await else {
2152 return Ok(());
2153 };
2154
2155 match result {
2156 Ok(result) => {
2157 tx.send(result).ok();
2158 }
2159 Err(err) => {
2160 let rx = workspace.update_in(cx, |workspace, window, cx| {
2161 workspace.show_portal_error(err.to_string(), cx);
2162 let prompt = workspace.on_prompt_for_open_path.take().unwrap();
2163 let rx = prompt(workspace, lister, window, cx);
2164 workspace.on_prompt_for_open_path = Some(prompt);
2165 rx
2166 })?;
2167 if let Ok(path) = rx.await {
2168 tx.send(path).ok();
2169 }
2170 }
2171 };
2172 anyhow::Ok(())
2173 })
2174 .detach();
2175
2176 rx
2177 }
2178 }
2179
2180 pub fn prompt_for_new_path(
2181 &mut self,
2182 lister: DirectoryLister,
2183 suggested_name: Option<String>,
2184 window: &mut Window,
2185 cx: &mut Context<Self>,
2186 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2187 if self.project.read(cx).is_via_collab()
2188 || self.project.read(cx).is_via_remote_server()
2189 || !WorkspaceSettings::get_global(cx).use_system_path_prompts
2190 {
2191 let prompt = self.on_prompt_for_new_path.take().unwrap();
2192 let rx = prompt(self, lister, window, cx);
2193 self.on_prompt_for_new_path = Some(prompt);
2194 return rx;
2195 }
2196
2197 let (tx, rx) = oneshot::channel();
2198 cx.spawn_in(window, async move |workspace, cx| {
2199 let abs_path = workspace.update(cx, |workspace, cx| {
2200 let relative_to = workspace
2201 .most_recent_active_path(cx)
2202 .and_then(|p| p.parent().map(|p| p.to_path_buf()))
2203 .or_else(|| {
2204 let project = workspace.project.read(cx);
2205 project.visible_worktrees(cx).find_map(|worktree| {
2206 Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
2207 })
2208 })
2209 .or_else(std::env::home_dir)
2210 .unwrap_or_else(|| PathBuf::from(""));
2211 cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
2212 })?;
2213 let abs_path = match abs_path.await? {
2214 Ok(path) => path,
2215 Err(err) => {
2216 let rx = workspace.update_in(cx, |workspace, window, cx| {
2217 workspace.show_portal_error(err.to_string(), cx);
2218
2219 let prompt = workspace.on_prompt_for_new_path.take().unwrap();
2220 let rx = prompt(workspace, lister, window, cx);
2221 workspace.on_prompt_for_new_path = Some(prompt);
2222 rx
2223 })?;
2224 if let Ok(path) = rx.await {
2225 tx.send(path).ok();
2226 }
2227 return anyhow::Ok(());
2228 }
2229 };
2230
2231 tx.send(abs_path.map(|path| vec![path])).ok();
2232 anyhow::Ok(())
2233 })
2234 .detach();
2235
2236 rx
2237 }
2238
2239 pub fn titlebar_item(&self) -> Option<AnyView> {
2240 self.titlebar_item.clone()
2241 }
2242
2243 /// Call the given callback with a workspace whose project is local.
2244 ///
2245 /// If the given workspace has a local project, then it will be passed
2246 /// to the callback. Otherwise, a new empty window will be created.
2247 pub fn with_local_workspace<T, F>(
2248 &mut self,
2249 window: &mut Window,
2250 cx: &mut Context<Self>,
2251 callback: F,
2252 ) -> Task<Result<T>>
2253 where
2254 T: 'static,
2255 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2256 {
2257 if self.project.read(cx).is_local() {
2258 Task::ready(Ok(callback(self, window, cx)))
2259 } else {
2260 let env = self.project.read(cx).cli_environment(cx);
2261 let task = Self::new_local(Vec::new(), self.app_state.clone(), None, env, cx);
2262 cx.spawn_in(window, async move |_vh, cx| {
2263 let (workspace, _) = task.await?;
2264 workspace.update(cx, callback)
2265 })
2266 }
2267 }
2268
2269 pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
2270 self.project.read(cx).worktrees(cx)
2271 }
2272
2273 pub fn visible_worktrees<'a>(
2274 &self,
2275 cx: &'a App,
2276 ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
2277 self.project.read(cx).visible_worktrees(cx)
2278 }
2279
2280 #[cfg(any(test, feature = "test-support"))]
2281 pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
2282 let futures = self
2283 .worktrees(cx)
2284 .filter_map(|worktree| worktree.read(cx).as_local())
2285 .map(|worktree| worktree.scan_complete())
2286 .collect::<Vec<_>>();
2287 async move {
2288 for future in futures {
2289 future.await;
2290 }
2291 }
2292 }
2293
2294 pub fn close_global(cx: &mut App) {
2295 cx.defer(|cx| {
2296 cx.windows().iter().find(|window| {
2297 window
2298 .update(cx, |_, window, _| {
2299 if window.is_window_active() {
2300 //This can only get called when the window's project connection has been lost
2301 //so we don't need to prompt the user for anything and instead just close the window
2302 window.remove_window();
2303 true
2304 } else {
2305 false
2306 }
2307 })
2308 .unwrap_or(false)
2309 });
2310 });
2311 }
2312
2313 pub fn close_window(&mut self, _: &CloseWindow, window: &mut Window, cx: &mut Context<Self>) {
2314 let prepare = self.prepare_to_close(CloseIntent::CloseWindow, window, cx);
2315 cx.spawn_in(window, async move |_, cx| {
2316 if prepare.await? {
2317 cx.update(|window, _cx| window.remove_window())?;
2318 }
2319 anyhow::Ok(())
2320 })
2321 .detach_and_log_err(cx)
2322 }
2323
2324 pub fn move_focused_panel_to_next_position(
2325 &mut self,
2326 _: &MoveFocusedPanelToNextPosition,
2327 window: &mut Window,
2328 cx: &mut Context<Self>,
2329 ) {
2330 let docks = self.all_docks();
2331 let active_dock = docks
2332 .into_iter()
2333 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
2334
2335 if let Some(dock) = active_dock {
2336 dock.update(cx, |dock, cx| {
2337 let active_panel = dock
2338 .active_panel()
2339 .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
2340
2341 if let Some(panel) = active_panel {
2342 panel.move_to_next_position(window, cx);
2343 }
2344 })
2345 }
2346 }
2347
2348 pub fn prepare_to_close(
2349 &mut self,
2350 close_intent: CloseIntent,
2351 window: &mut Window,
2352 cx: &mut Context<Self>,
2353 ) -> Task<Result<bool>> {
2354 let active_call = self.active_call().cloned();
2355
2356 cx.spawn_in(window, async move |this, cx| {
2357 this.update(cx, |this, _| {
2358 if close_intent == CloseIntent::CloseWindow {
2359 this.removing = true;
2360 }
2361 })?;
2362
2363 let workspace_count = cx.update(|_window, cx| {
2364 cx.windows()
2365 .iter()
2366 .filter(|window| window.downcast::<Workspace>().is_some())
2367 .count()
2368 })?;
2369
2370 #[cfg(target_os = "macos")]
2371 let save_last_workspace = false;
2372
2373 // On Linux and Windows, closing the last window should restore the last workspace.
2374 #[cfg(not(target_os = "macos"))]
2375 let save_last_workspace = {
2376 let remaining_workspaces = cx.update(|_window, cx| {
2377 cx.windows()
2378 .iter()
2379 .filter_map(|window| window.downcast::<Workspace>())
2380 .filter_map(|workspace| {
2381 workspace
2382 .update(cx, |workspace, _, _| workspace.removing)
2383 .ok()
2384 })
2385 .filter(|removing| !removing)
2386 .count()
2387 })?;
2388
2389 close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
2390 };
2391
2392 if let Some(active_call) = active_call
2393 && workspace_count == 1
2394 && active_call.read_with(cx, |call, _| call.room().is_some())?
2395 {
2396 if close_intent == CloseIntent::CloseWindow {
2397 let answer = cx.update(|window, cx| {
2398 window.prompt(
2399 PromptLevel::Warning,
2400 "Do you want to leave the current call?",
2401 None,
2402 &["Close window and hang up", "Cancel"],
2403 cx,
2404 )
2405 })?;
2406
2407 if answer.await.log_err() == Some(1) {
2408 return anyhow::Ok(false);
2409 } else {
2410 active_call
2411 .update(cx, |call, cx| call.hang_up(cx))?
2412 .await
2413 .log_err();
2414 }
2415 }
2416 if close_intent == CloseIntent::ReplaceWindow {
2417 _ = active_call.update(cx, |this, cx| {
2418 let workspace = cx
2419 .windows()
2420 .iter()
2421 .filter_map(|window| window.downcast::<Workspace>())
2422 .next()
2423 .unwrap();
2424 let project = workspace.read(cx)?.project.clone();
2425 if project.read(cx).is_shared() {
2426 this.unshare_project(project, cx)?;
2427 }
2428 Ok::<_, anyhow::Error>(())
2429 })?;
2430 }
2431 }
2432
2433 let save_result = this
2434 .update_in(cx, |this, window, cx| {
2435 this.save_all_internal(SaveIntent::Close, window, cx)
2436 })?
2437 .await;
2438
2439 // If we're not quitting, but closing, we remove the workspace from
2440 // the current session.
2441 if close_intent != CloseIntent::Quit
2442 && !save_last_workspace
2443 && save_result.as_ref().is_ok_and(|&res| res)
2444 {
2445 this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
2446 .await;
2447 }
2448
2449 save_result
2450 })
2451 }
2452
2453 fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
2454 self.save_all_internal(
2455 action.save_intent.unwrap_or(SaveIntent::SaveAll),
2456 window,
2457 cx,
2458 )
2459 .detach_and_log_err(cx);
2460 }
2461
2462 fn send_keystrokes(
2463 &mut self,
2464 action: &SendKeystrokes,
2465 window: &mut Window,
2466 cx: &mut Context<Self>,
2467 ) {
2468 let keystrokes: Vec<Keystroke> = action
2469 .0
2470 .split(' ')
2471 .flat_map(|k| Keystroke::parse(k).log_err())
2472 .map(|k| {
2473 cx.keyboard_mapper()
2474 .map_key_equivalent(k, true)
2475 .inner()
2476 .clone()
2477 })
2478 .collect();
2479 let _ = self.send_keystrokes_impl(keystrokes, window, cx);
2480 }
2481
2482 pub fn send_keystrokes_impl(
2483 &mut self,
2484 keystrokes: Vec<Keystroke>,
2485 window: &mut Window,
2486 cx: &mut Context<Self>,
2487 ) -> Shared<Task<()>> {
2488 let mut state = self.dispatching_keystrokes.borrow_mut();
2489 if !state.dispatched.insert(keystrokes.clone()) {
2490 cx.propagate();
2491 return state.task.clone().unwrap();
2492 }
2493
2494 state.queue.extend(keystrokes);
2495
2496 let keystrokes = self.dispatching_keystrokes.clone();
2497 if state.task.is_none() {
2498 state.task = Some(
2499 window
2500 .spawn(cx, async move |cx| {
2501 // limit to 100 keystrokes to avoid infinite recursion.
2502 for _ in 0..100 {
2503 let mut state = keystrokes.borrow_mut();
2504 let Some(keystroke) = state.queue.pop_front() else {
2505 state.dispatched.clear();
2506 state.task.take();
2507 return;
2508 };
2509 drop(state);
2510 cx.update(|window, cx| {
2511 let focused = window.focused(cx);
2512 window.dispatch_keystroke(keystroke.clone(), cx);
2513 if window.focused(cx) != focused {
2514 // dispatch_keystroke may cause the focus to change.
2515 // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
2516 // And we need that to happen before the next keystroke to keep vim mode happy...
2517 // (Note that the tests always do this implicitly, so you must manually test with something like:
2518 // "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
2519 // )
2520 window.draw(cx).clear();
2521 }
2522 })
2523 .ok();
2524 }
2525
2526 *keystrokes.borrow_mut() = Default::default();
2527 log::error!("over 100 keystrokes passed to send_keystrokes");
2528 })
2529 .shared(),
2530 );
2531 }
2532 state.task.clone().unwrap()
2533 }
2534
2535 fn save_all_internal(
2536 &mut self,
2537 mut save_intent: SaveIntent,
2538 window: &mut Window,
2539 cx: &mut Context<Self>,
2540 ) -> Task<Result<bool>> {
2541 if self.project.read(cx).is_disconnected(cx) {
2542 return Task::ready(Ok(true));
2543 }
2544 let dirty_items = self
2545 .panes
2546 .iter()
2547 .flat_map(|pane| {
2548 pane.read(cx).items().filter_map(|item| {
2549 if item.is_dirty(cx) {
2550 item.tab_content_text(0, cx);
2551 Some((pane.downgrade(), item.boxed_clone()))
2552 } else {
2553 None
2554 }
2555 })
2556 })
2557 .collect::<Vec<_>>();
2558
2559 let project = self.project.clone();
2560 cx.spawn_in(window, async move |workspace, cx| {
2561 let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
2562 let (serialize_tasks, remaining_dirty_items) =
2563 workspace.update_in(cx, |workspace, window, cx| {
2564 let mut remaining_dirty_items = Vec::new();
2565 let mut serialize_tasks = Vec::new();
2566 for (pane, item) in dirty_items {
2567 if let Some(task) = item
2568 .to_serializable_item_handle(cx)
2569 .and_then(|handle| handle.serialize(workspace, true, window, cx))
2570 {
2571 serialize_tasks.push(task);
2572 } else {
2573 remaining_dirty_items.push((pane, item));
2574 }
2575 }
2576 (serialize_tasks, remaining_dirty_items)
2577 })?;
2578
2579 futures::future::try_join_all(serialize_tasks).await?;
2580
2581 if remaining_dirty_items.len() > 1 {
2582 let answer = workspace.update_in(cx, |_, window, cx| {
2583 let detail = Pane::file_names_for_prompt(
2584 &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
2585 cx,
2586 );
2587 window.prompt(
2588 PromptLevel::Warning,
2589 "Do you want to save all changes in the following files?",
2590 Some(&detail),
2591 &["Save all", "Discard all", "Cancel"],
2592 cx,
2593 )
2594 })?;
2595 match answer.await.log_err() {
2596 Some(0) => save_intent = SaveIntent::SaveAll,
2597 Some(1) => save_intent = SaveIntent::Skip,
2598 Some(2) => return Ok(false),
2599 _ => {}
2600 }
2601 }
2602
2603 remaining_dirty_items
2604 } else {
2605 dirty_items
2606 };
2607
2608 for (pane, item) in dirty_items {
2609 let (singleton, project_entry_ids) = cx.update(|_, cx| {
2610 (
2611 item.buffer_kind(cx) == ItemBufferKind::Singleton,
2612 item.project_entry_ids(cx),
2613 )
2614 })?;
2615 if (singleton || !project_entry_ids.is_empty())
2616 && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
2617 {
2618 return Ok(false);
2619 }
2620 }
2621 Ok(true)
2622 })
2623 }
2624
2625 pub fn open_workspace_for_paths(
2626 &mut self,
2627 replace_current_window: bool,
2628 paths: Vec<PathBuf>,
2629 window: &mut Window,
2630 cx: &mut Context<Self>,
2631 ) -> Task<Result<()>> {
2632 let window_handle = window.window_handle().downcast::<Self>();
2633 let is_remote = self.project.read(cx).is_via_collab();
2634 let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
2635 let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
2636
2637 let window_to_replace = if replace_current_window {
2638 window_handle
2639 } else if is_remote || has_worktree || has_dirty_items {
2640 None
2641 } else {
2642 window_handle
2643 };
2644 let app_state = self.app_state.clone();
2645
2646 cx.spawn(async move |_, cx| {
2647 cx.update(|cx| {
2648 open_paths(
2649 &paths,
2650 app_state,
2651 OpenOptions {
2652 replace_window: window_to_replace,
2653 ..Default::default()
2654 },
2655 cx,
2656 )
2657 })?
2658 .await?;
2659 Ok(())
2660 })
2661 }
2662
2663 #[allow(clippy::type_complexity)]
2664 pub fn open_paths(
2665 &mut self,
2666 mut abs_paths: Vec<PathBuf>,
2667 options: OpenOptions,
2668 pane: Option<WeakEntity<Pane>>,
2669 window: &mut Window,
2670 cx: &mut Context<Self>,
2671 ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
2672 let fs = self.app_state.fs.clone();
2673
2674 // Sort the paths to ensure we add worktrees for parents before their children.
2675 abs_paths.sort_unstable();
2676 cx.spawn_in(window, async move |this, cx| {
2677 let mut tasks = Vec::with_capacity(abs_paths.len());
2678
2679 for abs_path in &abs_paths {
2680 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
2681 OpenVisible::All => Some(true),
2682 OpenVisible::None => Some(false),
2683 OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
2684 Some(Some(metadata)) => Some(!metadata.is_dir),
2685 Some(None) => Some(true),
2686 None => None,
2687 },
2688 OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
2689 Some(Some(metadata)) => Some(metadata.is_dir),
2690 Some(None) => Some(false),
2691 None => None,
2692 },
2693 };
2694 let project_path = match visible {
2695 Some(visible) => match this
2696 .update(cx, |this, cx| {
2697 Workspace::project_path_for_path(
2698 this.project.clone(),
2699 abs_path,
2700 visible,
2701 cx,
2702 )
2703 })
2704 .log_err()
2705 {
2706 Some(project_path) => project_path.await.log_err(),
2707 None => None,
2708 },
2709 None => None,
2710 };
2711
2712 let this = this.clone();
2713 let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
2714 let fs = fs.clone();
2715 let pane = pane.clone();
2716 let task = cx.spawn(async move |cx| {
2717 let (worktree, project_path) = project_path?;
2718 if fs.is_dir(&abs_path).await {
2719 this.update(cx, |workspace, cx| {
2720 let worktree = worktree.read(cx);
2721 let worktree_abs_path = worktree.abs_path();
2722 let entry_id = if abs_path.as_ref() == worktree_abs_path.as_ref() {
2723 worktree.root_entry()
2724 } else {
2725 abs_path
2726 .strip_prefix(worktree_abs_path.as_ref())
2727 .ok()
2728 .and_then(|relative_path| {
2729 let relative_path =
2730 RelPath::new(relative_path, PathStyle::local())
2731 .log_err()?;
2732 worktree.entry_for_path(&relative_path)
2733 })
2734 }
2735 .map(|entry| entry.id);
2736 if let Some(entry_id) = entry_id {
2737 workspace.project.update(cx, |_, cx| {
2738 cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
2739 })
2740 }
2741 })
2742 .ok()?;
2743 None
2744 } else {
2745 Some(
2746 this.update_in(cx, |this, window, cx| {
2747 this.open_path(
2748 project_path,
2749 pane,
2750 options.focus.unwrap_or(true),
2751 window,
2752 cx,
2753 )
2754 })
2755 .ok()?
2756 .await,
2757 )
2758 }
2759 });
2760 tasks.push(task);
2761 }
2762
2763 futures::future::join_all(tasks).await
2764 })
2765 }
2766
2767 pub fn open_resolved_path(
2768 &mut self,
2769 path: ResolvedPath,
2770 window: &mut Window,
2771 cx: &mut Context<Self>,
2772 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
2773 match path {
2774 ResolvedPath::ProjectPath { project_path, .. } => {
2775 self.open_path(project_path, None, true, window, cx)
2776 }
2777 ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
2778 PathBuf::from(path),
2779 OpenOptions {
2780 visible: Some(OpenVisible::None),
2781 ..Default::default()
2782 },
2783 window,
2784 cx,
2785 ),
2786 }
2787 }
2788
2789 pub fn absolute_path_of_worktree(
2790 &self,
2791 worktree_id: WorktreeId,
2792 cx: &mut Context<Self>,
2793 ) -> Option<PathBuf> {
2794 self.project
2795 .read(cx)
2796 .worktree_for_id(worktree_id, cx)
2797 // TODO: use `abs_path` or `root_dir`
2798 .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
2799 }
2800
2801 fn add_folder_to_project(
2802 &mut self,
2803 _: &AddFolderToProject,
2804 window: &mut Window,
2805 cx: &mut Context<Self>,
2806 ) {
2807 let project = self.project.read(cx);
2808 if project.is_via_collab() {
2809 self.show_error(
2810 &anyhow!("You cannot add folders to someone else's project"),
2811 cx,
2812 );
2813 return;
2814 }
2815 let paths = self.prompt_for_open_path(
2816 PathPromptOptions {
2817 files: false,
2818 directories: true,
2819 multiple: true,
2820 prompt: None,
2821 },
2822 DirectoryLister::Project(self.project.clone()),
2823 window,
2824 cx,
2825 );
2826 cx.spawn_in(window, async move |this, cx| {
2827 if let Some(paths) = paths.await.log_err().flatten() {
2828 let results = this
2829 .update_in(cx, |this, window, cx| {
2830 this.open_paths(
2831 paths,
2832 OpenOptions {
2833 visible: Some(OpenVisible::All),
2834 ..Default::default()
2835 },
2836 None,
2837 window,
2838 cx,
2839 )
2840 })?
2841 .await;
2842 for result in results.into_iter().flatten() {
2843 result.log_err();
2844 }
2845 }
2846 anyhow::Ok(())
2847 })
2848 .detach_and_log_err(cx);
2849 }
2850
2851 pub fn project_path_for_path(
2852 project: Entity<Project>,
2853 abs_path: &Path,
2854 visible: bool,
2855 cx: &mut App,
2856 ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
2857 let entry = project.update(cx, |project, cx| {
2858 project.find_or_create_worktree(abs_path, visible, cx)
2859 });
2860 cx.spawn(async move |cx| {
2861 let (worktree, path) = entry.await?;
2862 let worktree_id = worktree.read_with(cx, |t, _| t.id())?;
2863 Ok((
2864 worktree,
2865 ProjectPath {
2866 worktree_id,
2867 path: path,
2868 },
2869 ))
2870 })
2871 }
2872
2873 pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
2874 self.panes.iter().flat_map(|pane| pane.read(cx).items())
2875 }
2876
2877 pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
2878 self.items_of_type(cx).max_by_key(|item| item.item_id())
2879 }
2880
2881 pub fn items_of_type<'a, T: Item>(
2882 &'a self,
2883 cx: &'a App,
2884 ) -> impl 'a + Iterator<Item = Entity<T>> {
2885 self.panes
2886 .iter()
2887 .flat_map(|pane| pane.read(cx).items_of_type())
2888 }
2889
2890 pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
2891 self.active_pane().read(cx).active_item()
2892 }
2893
2894 pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
2895 let item = self.active_item(cx)?;
2896 item.to_any_view().downcast::<I>().ok()
2897 }
2898
2899 fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
2900 self.active_item(cx).and_then(|item| item.project_path(cx))
2901 }
2902
2903 pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
2904 self.recent_navigation_history_iter(cx)
2905 .filter_map(|(path, abs_path)| {
2906 let worktree = self
2907 .project
2908 .read(cx)
2909 .worktree_for_id(path.worktree_id, cx)?;
2910 if worktree.read(cx).is_visible() {
2911 abs_path
2912 } else {
2913 None
2914 }
2915 })
2916 .next()
2917 }
2918
2919 pub fn save_active_item(
2920 &mut self,
2921 save_intent: SaveIntent,
2922 window: &mut Window,
2923 cx: &mut App,
2924 ) -> Task<Result<()>> {
2925 let project = self.project.clone();
2926 let pane = self.active_pane();
2927 let item = pane.read(cx).active_item();
2928 let pane = pane.downgrade();
2929
2930 window.spawn(cx, async move |cx| {
2931 if let Some(item) = item {
2932 Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
2933 .await
2934 .map(|_| ())
2935 } else {
2936 Ok(())
2937 }
2938 })
2939 }
2940
2941 pub fn close_inactive_items_and_panes(
2942 &mut self,
2943 action: &CloseInactiveTabsAndPanes,
2944 window: &mut Window,
2945 cx: &mut Context<Self>,
2946 ) {
2947 if let Some(task) = self.close_all_internal(
2948 true,
2949 action.save_intent.unwrap_or(SaveIntent::Close),
2950 window,
2951 cx,
2952 ) {
2953 task.detach_and_log_err(cx)
2954 }
2955 }
2956
2957 pub fn close_all_items_and_panes(
2958 &mut self,
2959 action: &CloseAllItemsAndPanes,
2960 window: &mut Window,
2961 cx: &mut Context<Self>,
2962 ) {
2963 if let Some(task) = self.close_all_internal(
2964 false,
2965 action.save_intent.unwrap_or(SaveIntent::Close),
2966 window,
2967 cx,
2968 ) {
2969 task.detach_and_log_err(cx)
2970 }
2971 }
2972
2973 fn close_all_internal(
2974 &mut self,
2975 retain_active_pane: bool,
2976 save_intent: SaveIntent,
2977 window: &mut Window,
2978 cx: &mut Context<Self>,
2979 ) -> Option<Task<Result<()>>> {
2980 let current_pane = self.active_pane();
2981
2982 let mut tasks = Vec::new();
2983
2984 if retain_active_pane {
2985 let current_pane_close = current_pane.update(cx, |pane, cx| {
2986 pane.close_other_items(
2987 &CloseOtherItems {
2988 save_intent: None,
2989 close_pinned: false,
2990 },
2991 None,
2992 window,
2993 cx,
2994 )
2995 });
2996
2997 tasks.push(current_pane_close);
2998 }
2999
3000 for pane in self.panes() {
3001 if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
3002 continue;
3003 }
3004
3005 let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
3006 pane.close_all_items(
3007 &CloseAllItems {
3008 save_intent: Some(save_intent),
3009 close_pinned: false,
3010 },
3011 window,
3012 cx,
3013 )
3014 });
3015
3016 tasks.push(close_pane_items)
3017 }
3018
3019 if tasks.is_empty() {
3020 None
3021 } else {
3022 Some(cx.spawn_in(window, async move |_, _| {
3023 for task in tasks {
3024 task.await?
3025 }
3026 Ok(())
3027 }))
3028 }
3029 }
3030
3031 pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
3032 self.dock_at_position(position).read(cx).is_open()
3033 }
3034
3035 pub fn toggle_dock(
3036 &mut self,
3037 dock_side: DockPosition,
3038 window: &mut Window,
3039 cx: &mut Context<Self>,
3040 ) {
3041 let mut focus_center = false;
3042 let mut reveal_dock = false;
3043
3044 let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
3045 let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
3046 if was_visible {
3047 self.save_open_dock_positions(cx);
3048 }
3049
3050 let dock = self.dock_at_position(dock_side);
3051 dock.update(cx, |dock, cx| {
3052 dock.set_open(!was_visible, window, cx);
3053
3054 if dock.active_panel().is_none() {
3055 let Some(panel_ix) = dock
3056 .first_enabled_panel_idx(cx)
3057 .log_with_level(log::Level::Info)
3058 else {
3059 return;
3060 };
3061 dock.activate_panel(panel_ix, window, cx);
3062 }
3063
3064 if let Some(active_panel) = dock.active_panel() {
3065 if was_visible {
3066 if active_panel
3067 .panel_focus_handle(cx)
3068 .contains_focused(window, cx)
3069 {
3070 focus_center = true;
3071 }
3072 } else {
3073 let focus_handle = &active_panel.panel_focus_handle(cx);
3074 window.focus(focus_handle);
3075 reveal_dock = true;
3076 }
3077 }
3078 });
3079
3080 if reveal_dock {
3081 self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
3082 }
3083
3084 if focus_center {
3085 self.active_pane
3086 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)))
3087 }
3088
3089 cx.notify();
3090 self.serialize_workspace(window, cx);
3091 }
3092
3093 fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
3094 self.all_docks().into_iter().find(|&dock| {
3095 dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
3096 })
3097 }
3098
3099 fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
3100 if let Some(dock) = self.active_dock(window, cx).cloned() {
3101 self.save_open_dock_positions(cx);
3102 dock.update(cx, |dock, cx| {
3103 dock.set_open(false, window, cx);
3104 });
3105 return true;
3106 }
3107 false
3108 }
3109
3110 pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3111 self.save_open_dock_positions(cx);
3112 for dock in self.all_docks() {
3113 dock.update(cx, |dock, cx| {
3114 dock.set_open(false, window, cx);
3115 });
3116 }
3117
3118 cx.focus_self(window);
3119 cx.notify();
3120 self.serialize_workspace(window, cx);
3121 }
3122
3123 fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
3124 self.all_docks()
3125 .into_iter()
3126 .filter_map(|dock| {
3127 let dock_ref = dock.read(cx);
3128 if dock_ref.is_open() {
3129 Some(dock_ref.position())
3130 } else {
3131 None
3132 }
3133 })
3134 .collect()
3135 }
3136
3137 /// Saves the positions of currently open docks.
3138 ///
3139 /// Updates `last_open_dock_positions` with positions of all currently open
3140 /// docks, to later be restored by the 'Toggle All Docks' action.
3141 fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
3142 let open_dock_positions = self.get_open_dock_positions(cx);
3143 if !open_dock_positions.is_empty() {
3144 self.last_open_dock_positions = open_dock_positions;
3145 }
3146 }
3147
3148 /// Toggles all docks between open and closed states.
3149 ///
3150 /// If any docks are open, closes all and remembers their positions. If all
3151 /// docks are closed, restores the last remembered dock configuration.
3152 fn toggle_all_docks(
3153 &mut self,
3154 _: &ToggleAllDocks,
3155 window: &mut Window,
3156 cx: &mut Context<Self>,
3157 ) {
3158 let open_dock_positions = self.get_open_dock_positions(cx);
3159
3160 if !open_dock_positions.is_empty() {
3161 self.close_all_docks(window, cx);
3162 } else if !self.last_open_dock_positions.is_empty() {
3163 self.restore_last_open_docks(window, cx);
3164 }
3165 }
3166
3167 /// Reopens docks from the most recently remembered configuration.
3168 ///
3169 /// Opens all docks whose positions are stored in `last_open_dock_positions`
3170 /// and clears the stored positions.
3171 fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3172 let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
3173
3174 for position in positions_to_open {
3175 let dock = self.dock_at_position(position);
3176 dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
3177 }
3178
3179 cx.focus_self(window);
3180 cx.notify();
3181 self.serialize_workspace(window, cx);
3182 }
3183
3184 /// Transfer focus to the panel of the given type.
3185 pub fn focus_panel<T: Panel>(
3186 &mut self,
3187 window: &mut Window,
3188 cx: &mut Context<Self>,
3189 ) -> Option<Entity<T>> {
3190 let panel = self.focus_or_unfocus_panel::<T>(window, cx, |_, _, _| true)?;
3191 panel.to_any().downcast().ok()
3192 }
3193
3194 /// Focus the panel of the given type if it isn't already focused. If it is
3195 /// already focused, then transfer focus back to the workspace center.
3196 pub fn toggle_panel_focus<T: Panel>(
3197 &mut self,
3198 window: &mut Window,
3199 cx: &mut Context<Self>,
3200 ) -> bool {
3201 let mut did_focus_panel = false;
3202 self.focus_or_unfocus_panel::<T>(window, cx, |panel, window, cx| {
3203 did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
3204 did_focus_panel
3205 });
3206 did_focus_panel
3207 }
3208
3209 pub fn activate_panel_for_proto_id(
3210 &mut self,
3211 panel_id: PanelId,
3212 window: &mut Window,
3213 cx: &mut Context<Self>,
3214 ) -> Option<Arc<dyn PanelHandle>> {
3215 let mut panel = None;
3216 for dock in self.all_docks() {
3217 if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
3218 panel = dock.update(cx, |dock, cx| {
3219 dock.activate_panel(panel_index, window, cx);
3220 dock.set_open(true, window, cx);
3221 dock.active_panel().cloned()
3222 });
3223 break;
3224 }
3225 }
3226
3227 if panel.is_some() {
3228 cx.notify();
3229 self.serialize_workspace(window, cx);
3230 }
3231
3232 panel
3233 }
3234
3235 /// Focus or unfocus the given panel type, depending on the given callback.
3236 fn focus_or_unfocus_panel<T: Panel>(
3237 &mut self,
3238 window: &mut Window,
3239 cx: &mut Context<Self>,
3240 mut should_focus: impl FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
3241 ) -> Option<Arc<dyn PanelHandle>> {
3242 let mut result_panel = None;
3243 let mut serialize = false;
3244 for dock in self.all_docks() {
3245 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
3246 let mut focus_center = false;
3247 let panel = dock.update(cx, |dock, cx| {
3248 dock.activate_panel(panel_index, window, cx);
3249
3250 let panel = dock.active_panel().cloned();
3251 if let Some(panel) = panel.as_ref() {
3252 if should_focus(&**panel, window, cx) {
3253 dock.set_open(true, window, cx);
3254 panel.panel_focus_handle(cx).focus(window);
3255 } else {
3256 focus_center = true;
3257 }
3258 }
3259 panel
3260 });
3261
3262 if focus_center {
3263 self.active_pane
3264 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)))
3265 }
3266
3267 result_panel = panel;
3268 serialize = true;
3269 break;
3270 }
3271 }
3272
3273 if serialize {
3274 self.serialize_workspace(window, cx);
3275 }
3276
3277 cx.notify();
3278 result_panel
3279 }
3280
3281 /// Open the panel of the given type
3282 pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3283 for dock in self.all_docks() {
3284 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
3285 dock.update(cx, |dock, cx| {
3286 dock.activate_panel(panel_index, window, cx);
3287 dock.set_open(true, window, cx);
3288 });
3289 }
3290 }
3291 }
3292
3293 pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
3294 for dock in self.all_docks().iter() {
3295 dock.update(cx, |dock, cx| {
3296 if dock.panel::<T>().is_some() {
3297 dock.set_open(false, window, cx)
3298 }
3299 })
3300 }
3301 }
3302
3303 pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
3304 self.all_docks()
3305 .iter()
3306 .find_map(|dock| dock.read(cx).panel::<T>())
3307 }
3308
3309 fn dismiss_zoomed_items_to_reveal(
3310 &mut self,
3311 dock_to_reveal: Option<DockPosition>,
3312 window: &mut Window,
3313 cx: &mut Context<Self>,
3314 ) {
3315 // If a center pane is zoomed, unzoom it.
3316 for pane in &self.panes {
3317 if pane != &self.active_pane || dock_to_reveal.is_some() {
3318 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
3319 }
3320 }
3321
3322 // If another dock is zoomed, hide it.
3323 let mut focus_center = false;
3324 for dock in self.all_docks() {
3325 dock.update(cx, |dock, cx| {
3326 if Some(dock.position()) != dock_to_reveal
3327 && let Some(panel) = dock.active_panel()
3328 && panel.is_zoomed(window, cx)
3329 {
3330 focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
3331 dock.set_open(false, window, cx);
3332 }
3333 });
3334 }
3335
3336 if focus_center {
3337 self.active_pane
3338 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)))
3339 }
3340
3341 if self.zoomed_position != dock_to_reveal {
3342 self.zoomed = None;
3343 self.zoomed_position = None;
3344 cx.emit(Event::ZoomChanged);
3345 }
3346
3347 cx.notify();
3348 }
3349
3350 fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
3351 let pane = cx.new(|cx| {
3352 let mut pane = Pane::new(
3353 self.weak_handle(),
3354 self.project.clone(),
3355 self.pane_history_timestamp.clone(),
3356 None,
3357 NewFile.boxed_clone(),
3358 true,
3359 window,
3360 cx,
3361 );
3362 pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
3363 pane
3364 });
3365 cx.subscribe_in(&pane, window, Self::handle_pane_event)
3366 .detach();
3367 self.panes.push(pane.clone());
3368
3369 window.focus(&pane.focus_handle(cx));
3370
3371 cx.emit(Event::PaneAdded(pane.clone()));
3372 pane
3373 }
3374
3375 pub fn add_item_to_center(
3376 &mut self,
3377 item: Box<dyn ItemHandle>,
3378 window: &mut Window,
3379 cx: &mut Context<Self>,
3380 ) -> bool {
3381 if let Some(center_pane) = self.last_active_center_pane.clone() {
3382 if let Some(center_pane) = center_pane.upgrade() {
3383 center_pane.update(cx, |pane, cx| {
3384 pane.add_item(item, true, true, None, window, cx)
3385 });
3386 true
3387 } else {
3388 false
3389 }
3390 } else {
3391 false
3392 }
3393 }
3394
3395 pub fn add_item_to_active_pane(
3396 &mut self,
3397 item: Box<dyn ItemHandle>,
3398 destination_index: Option<usize>,
3399 focus_item: bool,
3400 window: &mut Window,
3401 cx: &mut App,
3402 ) {
3403 self.add_item(
3404 self.active_pane.clone(),
3405 item,
3406 destination_index,
3407 false,
3408 focus_item,
3409 window,
3410 cx,
3411 )
3412 }
3413
3414 pub fn add_item(
3415 &mut self,
3416 pane: Entity<Pane>,
3417 item: Box<dyn ItemHandle>,
3418 destination_index: Option<usize>,
3419 activate_pane: bool,
3420 focus_item: bool,
3421 window: &mut Window,
3422 cx: &mut App,
3423 ) {
3424 pane.update(cx, |pane, cx| {
3425 pane.add_item(
3426 item,
3427 activate_pane,
3428 focus_item,
3429 destination_index,
3430 window,
3431 cx,
3432 )
3433 });
3434 }
3435
3436 pub fn split_item(
3437 &mut self,
3438 split_direction: SplitDirection,
3439 item: Box<dyn ItemHandle>,
3440 window: &mut Window,
3441 cx: &mut Context<Self>,
3442 ) {
3443 let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
3444 self.add_item(new_pane, item, None, true, true, window, cx);
3445 }
3446
3447 pub fn open_abs_path(
3448 &mut self,
3449 abs_path: PathBuf,
3450 options: OpenOptions,
3451 window: &mut Window,
3452 cx: &mut Context<Self>,
3453 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3454 cx.spawn_in(window, async move |workspace, cx| {
3455 let open_paths_task_result = workspace
3456 .update_in(cx, |workspace, window, cx| {
3457 workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
3458 })
3459 .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
3460 .await;
3461 anyhow::ensure!(
3462 open_paths_task_result.len() == 1,
3463 "open abs path {abs_path:?} task returned incorrect number of results"
3464 );
3465 match open_paths_task_result
3466 .into_iter()
3467 .next()
3468 .expect("ensured single task result")
3469 {
3470 Some(open_result) => {
3471 open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
3472 }
3473 None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
3474 }
3475 })
3476 }
3477
3478 pub fn split_abs_path(
3479 &mut self,
3480 abs_path: PathBuf,
3481 visible: bool,
3482 window: &mut Window,
3483 cx: &mut Context<Self>,
3484 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3485 let project_path_task =
3486 Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
3487 cx.spawn_in(window, async move |this, cx| {
3488 let (_, path) = project_path_task.await?;
3489 this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
3490 .await
3491 })
3492 }
3493
3494 pub fn open_path(
3495 &mut self,
3496 path: impl Into<ProjectPath>,
3497 pane: Option<WeakEntity<Pane>>,
3498 focus_item: bool,
3499 window: &mut Window,
3500 cx: &mut App,
3501 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3502 self.open_path_preview(path, pane, focus_item, false, true, window, cx)
3503 }
3504
3505 pub fn open_path_preview(
3506 &mut self,
3507 path: impl Into<ProjectPath>,
3508 pane: Option<WeakEntity<Pane>>,
3509 focus_item: bool,
3510 allow_preview: bool,
3511 activate: bool,
3512 window: &mut Window,
3513 cx: &mut App,
3514 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3515 let pane = pane.unwrap_or_else(|| {
3516 self.last_active_center_pane.clone().unwrap_or_else(|| {
3517 self.panes
3518 .first()
3519 .expect("There must be an active pane")
3520 .downgrade()
3521 })
3522 });
3523
3524 let project_path = path.into();
3525 let task = self.load_path(project_path.clone(), window, cx);
3526 window.spawn(cx, async move |cx| {
3527 let (project_entry_id, build_item) = task.await?;
3528
3529 pane.update_in(cx, |pane, window, cx| {
3530 pane.open_item(
3531 project_entry_id,
3532 project_path,
3533 focus_item,
3534 allow_preview,
3535 activate,
3536 None,
3537 window,
3538 cx,
3539 build_item,
3540 )
3541 })
3542 })
3543 }
3544
3545 pub fn split_path(
3546 &mut self,
3547 path: impl Into<ProjectPath>,
3548 window: &mut Window,
3549 cx: &mut Context<Self>,
3550 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3551 self.split_path_preview(path, false, None, window, cx)
3552 }
3553
3554 pub fn split_path_preview(
3555 &mut self,
3556 path: impl Into<ProjectPath>,
3557 allow_preview: bool,
3558 split_direction: Option<SplitDirection>,
3559 window: &mut Window,
3560 cx: &mut Context<Self>,
3561 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3562 let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
3563 self.panes
3564 .first()
3565 .expect("There must be an active pane")
3566 .downgrade()
3567 });
3568
3569 if let Member::Pane(center_pane) = &self.center.root
3570 && center_pane.read(cx).items_len() == 0
3571 {
3572 return self.open_path(path, Some(pane), true, window, cx);
3573 }
3574
3575 let project_path = path.into();
3576 let task = self.load_path(project_path.clone(), window, cx);
3577 cx.spawn_in(window, async move |this, cx| {
3578 let (project_entry_id, build_item) = task.await?;
3579 this.update_in(cx, move |this, window, cx| -> Option<_> {
3580 let pane = pane.upgrade()?;
3581 let new_pane = this.split_pane(
3582 pane,
3583 split_direction.unwrap_or(SplitDirection::Right),
3584 window,
3585 cx,
3586 );
3587 new_pane.update(cx, |new_pane, cx| {
3588 Some(new_pane.open_item(
3589 project_entry_id,
3590 project_path,
3591 true,
3592 allow_preview,
3593 true,
3594 None,
3595 window,
3596 cx,
3597 build_item,
3598 ))
3599 })
3600 })
3601 .map(|option| option.context("pane was dropped"))?
3602 })
3603 }
3604
3605 fn load_path(
3606 &mut self,
3607 path: ProjectPath,
3608 window: &mut Window,
3609 cx: &mut App,
3610 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
3611 let registry = cx.default_global::<ProjectItemRegistry>().clone();
3612 registry.open_path(self.project(), &path, window, cx)
3613 }
3614
3615 pub fn find_project_item<T>(
3616 &self,
3617 pane: &Entity<Pane>,
3618 project_item: &Entity<T::Item>,
3619 cx: &App,
3620 ) -> Option<Entity<T>>
3621 where
3622 T: ProjectItem,
3623 {
3624 use project::ProjectItem as _;
3625 let project_item = project_item.read(cx);
3626 let entry_id = project_item.entry_id(cx);
3627 let project_path = project_item.project_path(cx);
3628
3629 let mut item = None;
3630 if let Some(entry_id) = entry_id {
3631 item = pane.read(cx).item_for_entry(entry_id, cx);
3632 }
3633 if item.is_none()
3634 && let Some(project_path) = project_path
3635 {
3636 item = pane.read(cx).item_for_path(project_path, cx);
3637 }
3638
3639 item.and_then(|item| item.downcast::<T>())
3640 }
3641
3642 pub fn is_project_item_open<T>(
3643 &self,
3644 pane: &Entity<Pane>,
3645 project_item: &Entity<T::Item>,
3646 cx: &App,
3647 ) -> bool
3648 where
3649 T: ProjectItem,
3650 {
3651 self.find_project_item::<T>(pane, project_item, cx)
3652 .is_some()
3653 }
3654
3655 pub fn open_project_item<T>(
3656 &mut self,
3657 pane: Entity<Pane>,
3658 project_item: Entity<T::Item>,
3659 activate_pane: bool,
3660 focus_item: bool,
3661 keep_old_preview: bool,
3662 allow_new_preview: bool,
3663 window: &mut Window,
3664 cx: &mut Context<Self>,
3665 ) -> Entity<T>
3666 where
3667 T: ProjectItem,
3668 {
3669 let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
3670
3671 if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
3672 if !keep_old_preview
3673 && let Some(old_id) = old_item_id
3674 && old_id != item.item_id()
3675 {
3676 // switching to a different item, so unpreview old active item
3677 pane.update(cx, |pane, _| {
3678 pane.unpreview_item_if_preview(old_id);
3679 });
3680 }
3681
3682 self.activate_item(&item, activate_pane, focus_item, window, cx);
3683 if !allow_new_preview {
3684 pane.update(cx, |pane, _| {
3685 pane.unpreview_item_if_preview(item.item_id());
3686 });
3687 }
3688 return item;
3689 }
3690
3691 let item = pane.update(cx, |pane, cx| {
3692 cx.new(|cx| {
3693 T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
3694 })
3695 });
3696 let mut destination_index = None;
3697 pane.update(cx, |pane, cx| {
3698 if !keep_old_preview && let Some(old_id) = old_item_id {
3699 pane.unpreview_item_if_preview(old_id);
3700 }
3701 if allow_new_preview {
3702 destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
3703 }
3704 });
3705
3706 self.add_item(
3707 pane,
3708 Box::new(item.clone()),
3709 destination_index,
3710 activate_pane,
3711 focus_item,
3712 window,
3713 cx,
3714 );
3715 item
3716 }
3717
3718 pub fn open_shared_screen(
3719 &mut self,
3720 peer_id: PeerId,
3721 window: &mut Window,
3722 cx: &mut Context<Self>,
3723 ) {
3724 if let Some(shared_screen) =
3725 self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
3726 {
3727 self.active_pane.update(cx, |pane, cx| {
3728 pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
3729 });
3730 }
3731 }
3732
3733 pub fn activate_item(
3734 &mut self,
3735 item: &dyn ItemHandle,
3736 activate_pane: bool,
3737 focus_item: bool,
3738 window: &mut Window,
3739 cx: &mut App,
3740 ) -> bool {
3741 let result = self.panes.iter().find_map(|pane| {
3742 pane.read(cx)
3743 .index_for_item(item)
3744 .map(|ix| (pane.clone(), ix))
3745 });
3746 if let Some((pane, ix)) = result {
3747 pane.update(cx, |pane, cx| {
3748 pane.activate_item(ix, activate_pane, focus_item, window, cx)
3749 });
3750 true
3751 } else {
3752 false
3753 }
3754 }
3755
3756 fn activate_pane_at_index(
3757 &mut self,
3758 action: &ActivatePane,
3759 window: &mut Window,
3760 cx: &mut Context<Self>,
3761 ) {
3762 let panes = self.center.panes();
3763 if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
3764 window.focus(&pane.focus_handle(cx));
3765 } else {
3766 self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
3767 .detach();
3768 }
3769 }
3770
3771 fn move_item_to_pane_at_index(
3772 &mut self,
3773 action: &MoveItemToPane,
3774 window: &mut Window,
3775 cx: &mut Context<Self>,
3776 ) {
3777 let panes = self.center.panes();
3778 let destination = match panes.get(action.destination) {
3779 Some(&destination) => destination.clone(),
3780 None => {
3781 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
3782 return;
3783 }
3784 let direction = SplitDirection::Right;
3785 let split_off_pane = self
3786 .find_pane_in_direction(direction, cx)
3787 .unwrap_or_else(|| self.active_pane.clone());
3788 let new_pane = self.add_pane(window, cx);
3789 if self
3790 .center
3791 .split(&split_off_pane, &new_pane, direction, cx)
3792 .log_err()
3793 .is_none()
3794 {
3795 return;
3796 };
3797 new_pane
3798 }
3799 };
3800
3801 if action.clone {
3802 if self
3803 .active_pane
3804 .read(cx)
3805 .active_item()
3806 .is_some_and(|item| item.can_split(cx))
3807 {
3808 clone_active_item(
3809 self.database_id(),
3810 &self.active_pane,
3811 &destination,
3812 action.focus,
3813 window,
3814 cx,
3815 );
3816 return;
3817 }
3818 }
3819 move_active_item(
3820 &self.active_pane,
3821 &destination,
3822 action.focus,
3823 true,
3824 window,
3825 cx,
3826 )
3827 }
3828
3829 pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
3830 let panes = self.center.panes();
3831 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
3832 let next_ix = (ix + 1) % panes.len();
3833 let next_pane = panes[next_ix].clone();
3834 window.focus(&next_pane.focus_handle(cx));
3835 }
3836 }
3837
3838 pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
3839 let panes = self.center.panes();
3840 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
3841 let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
3842 let prev_pane = panes[prev_ix].clone();
3843 window.focus(&prev_pane.focus_handle(cx));
3844 }
3845 }
3846
3847 pub fn activate_pane_in_direction(
3848 &mut self,
3849 direction: SplitDirection,
3850 window: &mut Window,
3851 cx: &mut App,
3852 ) {
3853 use ActivateInDirectionTarget as Target;
3854 enum Origin {
3855 LeftDock,
3856 RightDock,
3857 BottomDock,
3858 Center,
3859 }
3860
3861 let origin: Origin = [
3862 (&self.left_dock, Origin::LeftDock),
3863 (&self.right_dock, Origin::RightDock),
3864 (&self.bottom_dock, Origin::BottomDock),
3865 ]
3866 .into_iter()
3867 .find_map(|(dock, origin)| {
3868 if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
3869 Some(origin)
3870 } else {
3871 None
3872 }
3873 })
3874 .unwrap_or(Origin::Center);
3875
3876 let get_last_active_pane = || {
3877 let pane = self
3878 .last_active_center_pane
3879 .clone()
3880 .unwrap_or_else(|| {
3881 self.panes
3882 .first()
3883 .expect("There must be an active pane")
3884 .downgrade()
3885 })
3886 .upgrade()?;
3887 (pane.read(cx).items_len() != 0).then_some(pane)
3888 };
3889
3890 let try_dock =
3891 |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
3892
3893 let target = match (origin, direction) {
3894 // We're in the center, so we first try to go to a different pane,
3895 // otherwise try to go to a dock.
3896 (Origin::Center, direction) => {
3897 if let Some(pane) = self.find_pane_in_direction(direction, cx) {
3898 Some(Target::Pane(pane))
3899 } else {
3900 match direction {
3901 SplitDirection::Up => None,
3902 SplitDirection::Down => try_dock(&self.bottom_dock),
3903 SplitDirection::Left => try_dock(&self.left_dock),
3904 SplitDirection::Right => try_dock(&self.right_dock),
3905 }
3906 }
3907 }
3908
3909 (Origin::LeftDock, SplitDirection::Right) => {
3910 if let Some(last_active_pane) = get_last_active_pane() {
3911 Some(Target::Pane(last_active_pane))
3912 } else {
3913 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
3914 }
3915 }
3916
3917 (Origin::LeftDock, SplitDirection::Down)
3918 | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
3919
3920 (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
3921 (Origin::BottomDock, SplitDirection::Left) => try_dock(&self.left_dock),
3922 (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
3923
3924 (Origin::RightDock, SplitDirection::Left) => {
3925 if let Some(last_active_pane) = get_last_active_pane() {
3926 Some(Target::Pane(last_active_pane))
3927 } else {
3928 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.left_dock))
3929 }
3930 }
3931
3932 _ => None,
3933 };
3934
3935 match target {
3936 Some(ActivateInDirectionTarget::Pane(pane)) => {
3937 let pane = pane.read(cx);
3938 if let Some(item) = pane.active_item() {
3939 item.item_focus_handle(cx).focus(window);
3940 } else {
3941 log::error!(
3942 "Could not find a focus target when in switching focus in {direction} direction for a pane",
3943 );
3944 }
3945 }
3946 Some(ActivateInDirectionTarget::Dock(dock)) => {
3947 // Defer this to avoid a panic when the dock's active panel is already on the stack.
3948 window.defer(cx, move |window, cx| {
3949 let dock = dock.read(cx);
3950 if let Some(panel) = dock.active_panel() {
3951 panel.panel_focus_handle(cx).focus(window);
3952 } else {
3953 log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
3954 }
3955 })
3956 }
3957 None => {}
3958 }
3959 }
3960
3961 pub fn move_item_to_pane_in_direction(
3962 &mut self,
3963 action: &MoveItemToPaneInDirection,
3964 window: &mut Window,
3965 cx: &mut Context<Self>,
3966 ) {
3967 let destination = match self.find_pane_in_direction(action.direction, cx) {
3968 Some(destination) => destination,
3969 None => {
3970 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
3971 return;
3972 }
3973 let new_pane = self.add_pane(window, cx);
3974 if self
3975 .center
3976 .split(&self.active_pane, &new_pane, action.direction, cx)
3977 .log_err()
3978 .is_none()
3979 {
3980 return;
3981 };
3982 new_pane
3983 }
3984 };
3985
3986 if action.clone {
3987 if self
3988 .active_pane
3989 .read(cx)
3990 .active_item()
3991 .is_some_and(|item| item.can_split(cx))
3992 {
3993 clone_active_item(
3994 self.database_id(),
3995 &self.active_pane,
3996 &destination,
3997 action.focus,
3998 window,
3999 cx,
4000 );
4001 return;
4002 }
4003 }
4004 move_active_item(
4005 &self.active_pane,
4006 &destination,
4007 action.focus,
4008 true,
4009 window,
4010 cx,
4011 );
4012 }
4013
4014 pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
4015 self.center.bounding_box_for_pane(pane)
4016 }
4017
4018 pub fn find_pane_in_direction(
4019 &mut self,
4020 direction: SplitDirection,
4021 cx: &App,
4022 ) -> Option<Entity<Pane>> {
4023 self.center
4024 .find_pane_in_direction(&self.active_pane, direction, cx)
4025 .cloned()
4026 }
4027
4028 pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4029 if let Some(to) = self.find_pane_in_direction(direction, cx) {
4030 self.center.swap(&self.active_pane, &to, cx);
4031 cx.notify();
4032 }
4033 }
4034
4035 pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4036 if self
4037 .center
4038 .move_to_border(&self.active_pane, direction, cx)
4039 .unwrap()
4040 {
4041 cx.notify();
4042 }
4043 }
4044
4045 pub fn resize_pane(
4046 &mut self,
4047 axis: gpui::Axis,
4048 amount: Pixels,
4049 window: &mut Window,
4050 cx: &mut Context<Self>,
4051 ) {
4052 let docks = self.all_docks();
4053 let active_dock = docks
4054 .into_iter()
4055 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
4056
4057 if let Some(dock) = active_dock {
4058 let Some(panel_size) = dock.read(cx).active_panel_size(window, cx) else {
4059 return;
4060 };
4061 match dock.read(cx).position() {
4062 DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
4063 DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
4064 DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
4065 }
4066 } else {
4067 self.center
4068 .resize(&self.active_pane, axis, amount, &self.bounds, cx);
4069 }
4070 cx.notify();
4071 }
4072
4073 pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
4074 self.center.reset_pane_sizes(cx);
4075 cx.notify();
4076 }
4077
4078 fn handle_pane_focused(
4079 &mut self,
4080 pane: Entity<Pane>,
4081 window: &mut Window,
4082 cx: &mut Context<Self>,
4083 ) {
4084 // This is explicitly hoisted out of the following check for pane identity as
4085 // terminal panel panes are not registered as a center panes.
4086 self.status_bar.update(cx, |status_bar, cx| {
4087 status_bar.set_active_pane(&pane, window, cx);
4088 });
4089 if self.active_pane != pane {
4090 self.set_active_pane(&pane, window, cx);
4091 }
4092
4093 if self.last_active_center_pane.is_none() {
4094 self.last_active_center_pane = Some(pane.downgrade());
4095 }
4096
4097 self.dismiss_zoomed_items_to_reveal(None, window, cx);
4098 if pane.read(cx).is_zoomed() {
4099 self.zoomed = Some(pane.downgrade().into());
4100 } else {
4101 self.zoomed = None;
4102 }
4103 self.zoomed_position = None;
4104 cx.emit(Event::ZoomChanged);
4105 self.update_active_view_for_followers(window, cx);
4106 pane.update(cx, |pane, _| {
4107 pane.track_alternate_file_items();
4108 });
4109
4110 cx.notify();
4111 }
4112
4113 fn set_active_pane(
4114 &mut self,
4115 pane: &Entity<Pane>,
4116 window: &mut Window,
4117 cx: &mut Context<Self>,
4118 ) {
4119 self.active_pane = pane.clone();
4120 self.active_item_path_changed(window, cx);
4121 self.last_active_center_pane = Some(pane.downgrade());
4122 }
4123
4124 fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4125 self.update_active_view_for_followers(window, cx);
4126 }
4127
4128 fn handle_pane_event(
4129 &mut self,
4130 pane: &Entity<Pane>,
4131 event: &pane::Event,
4132 window: &mut Window,
4133 cx: &mut Context<Self>,
4134 ) {
4135 let mut serialize_workspace = true;
4136 match event {
4137 pane::Event::AddItem { item } => {
4138 item.added_to_pane(self, pane.clone(), window, cx);
4139 cx.emit(Event::ItemAdded {
4140 item: item.boxed_clone(),
4141 });
4142 }
4143 pane::Event::Split {
4144 direction,
4145 clone_active_item,
4146 } => {
4147 if *clone_active_item {
4148 self.split_and_clone(pane.clone(), *direction, window, cx)
4149 .detach();
4150 } else {
4151 self.split_and_move(pane.clone(), *direction, window, cx);
4152 }
4153 }
4154 pane::Event::JoinIntoNext => {
4155 self.join_pane_into_next(pane.clone(), window, cx);
4156 }
4157 pane::Event::JoinAll => {
4158 self.join_all_panes(window, cx);
4159 }
4160 pane::Event::Remove { focus_on_pane } => {
4161 self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
4162 }
4163 pane::Event::ActivateItem {
4164 local,
4165 focus_changed,
4166 } => {
4167 window.invalidate_character_coordinates();
4168
4169 pane.update(cx, |pane, _| {
4170 pane.track_alternate_file_items();
4171 });
4172 if *local {
4173 self.unfollow_in_pane(pane, window, cx);
4174 }
4175 serialize_workspace = *focus_changed || pane != self.active_pane();
4176 if pane == self.active_pane() {
4177 self.active_item_path_changed(window, cx);
4178 self.update_active_view_for_followers(window, cx);
4179 } else if *local {
4180 self.set_active_pane(pane, window, cx);
4181 }
4182 }
4183 pane::Event::UserSavedItem { item, save_intent } => {
4184 cx.emit(Event::UserSavedItem {
4185 pane: pane.downgrade(),
4186 item: item.boxed_clone(),
4187 save_intent: *save_intent,
4188 });
4189 serialize_workspace = false;
4190 }
4191 pane::Event::ChangeItemTitle => {
4192 if *pane == self.active_pane {
4193 self.active_item_path_changed(window, cx);
4194 }
4195 serialize_workspace = false;
4196 }
4197 pane::Event::RemovedItem { item } => {
4198 cx.emit(Event::ActiveItemChanged);
4199 self.update_window_edited(window, cx);
4200 if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
4201 && entry.get().entity_id() == pane.entity_id()
4202 {
4203 entry.remove();
4204 }
4205 cx.emit(Event::ItemRemoved {
4206 item_id: item.item_id(),
4207 });
4208 }
4209 pane::Event::Focus => {
4210 window.invalidate_character_coordinates();
4211 self.handle_pane_focused(pane.clone(), window, cx);
4212 }
4213 pane::Event::ZoomIn => {
4214 if *pane == self.active_pane {
4215 pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
4216 if pane.read(cx).has_focus(window, cx) {
4217 self.zoomed = Some(pane.downgrade().into());
4218 self.zoomed_position = None;
4219 cx.emit(Event::ZoomChanged);
4220 }
4221 cx.notify();
4222 }
4223 }
4224 pane::Event::ZoomOut => {
4225 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
4226 if self.zoomed_position.is_none() {
4227 self.zoomed = None;
4228 cx.emit(Event::ZoomChanged);
4229 }
4230 cx.notify();
4231 }
4232 pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
4233 }
4234
4235 if serialize_workspace {
4236 self.serialize_workspace(window, cx);
4237 }
4238 }
4239
4240 pub fn unfollow_in_pane(
4241 &mut self,
4242 pane: &Entity<Pane>,
4243 window: &mut Window,
4244 cx: &mut Context<Workspace>,
4245 ) -> Option<CollaboratorId> {
4246 let leader_id = self.leader_for_pane(pane)?;
4247 self.unfollow(leader_id, window, cx);
4248 Some(leader_id)
4249 }
4250
4251 pub fn split_pane(
4252 &mut self,
4253 pane_to_split: Entity<Pane>,
4254 split_direction: SplitDirection,
4255 window: &mut Window,
4256 cx: &mut Context<Self>,
4257 ) -> Entity<Pane> {
4258 let new_pane = self.add_pane(window, cx);
4259 self.center
4260 .split(&pane_to_split, &new_pane, split_direction, cx)
4261 .unwrap();
4262 cx.notify();
4263 new_pane
4264 }
4265
4266 pub fn split_and_move(
4267 &mut self,
4268 pane: Entity<Pane>,
4269 direction: SplitDirection,
4270 window: &mut Window,
4271 cx: &mut Context<Self>,
4272 ) {
4273 let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
4274 return;
4275 };
4276 let new_pane = self.add_pane(window, cx);
4277 new_pane.update(cx, |pane, cx| {
4278 pane.add_item(item, true, true, None, window, cx)
4279 });
4280 self.center.split(&pane, &new_pane, direction, cx).unwrap();
4281 cx.notify();
4282 }
4283
4284 pub fn split_and_clone(
4285 &mut self,
4286 pane: Entity<Pane>,
4287 direction: SplitDirection,
4288 window: &mut Window,
4289 cx: &mut Context<Self>,
4290 ) -> Task<Option<Entity<Pane>>> {
4291 let Some(item) = pane.read(cx).active_item() else {
4292 return Task::ready(None);
4293 };
4294 if !item.can_split(cx) {
4295 return Task::ready(None);
4296 }
4297 let task = item.clone_on_split(self.database_id(), window, cx);
4298 cx.spawn_in(window, async move |this, cx| {
4299 if let Some(clone) = task.await {
4300 this.update_in(cx, |this, window, cx| {
4301 let new_pane = this.add_pane(window, cx);
4302 new_pane.update(cx, |pane, cx| {
4303 pane.add_item(clone, true, true, None, window, cx)
4304 });
4305 this.center.split(&pane, &new_pane, direction, cx).unwrap();
4306 cx.notify();
4307 new_pane
4308 })
4309 .ok()
4310 } else {
4311 None
4312 }
4313 })
4314 }
4315
4316 pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4317 let active_item = self.active_pane.read(cx).active_item();
4318 for pane in &self.panes {
4319 join_pane_into_active(&self.active_pane, pane, window, cx);
4320 }
4321 if let Some(active_item) = active_item {
4322 self.activate_item(active_item.as_ref(), true, true, window, cx);
4323 }
4324 cx.notify();
4325 }
4326
4327 pub fn join_pane_into_next(
4328 &mut self,
4329 pane: Entity<Pane>,
4330 window: &mut Window,
4331 cx: &mut Context<Self>,
4332 ) {
4333 let next_pane = self
4334 .find_pane_in_direction(SplitDirection::Right, cx)
4335 .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
4336 .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
4337 .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
4338 let Some(next_pane) = next_pane else {
4339 return;
4340 };
4341 move_all_items(&pane, &next_pane, window, cx);
4342 cx.notify();
4343 }
4344
4345 fn remove_pane(
4346 &mut self,
4347 pane: Entity<Pane>,
4348 focus_on: Option<Entity<Pane>>,
4349 window: &mut Window,
4350 cx: &mut Context<Self>,
4351 ) {
4352 if self.center.remove(&pane, cx).unwrap() {
4353 self.force_remove_pane(&pane, &focus_on, window, cx);
4354 self.unfollow_in_pane(&pane, window, cx);
4355 self.last_leaders_by_pane.remove(&pane.downgrade());
4356 for removed_item in pane.read(cx).items() {
4357 self.panes_by_item.remove(&removed_item.item_id());
4358 }
4359
4360 cx.notify();
4361 } else {
4362 self.active_item_path_changed(window, cx);
4363 }
4364 cx.emit(Event::PaneRemoved);
4365 }
4366
4367 pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
4368 &mut self.panes
4369 }
4370
4371 pub fn panes(&self) -> &[Entity<Pane>] {
4372 &self.panes
4373 }
4374
4375 pub fn active_pane(&self) -> &Entity<Pane> {
4376 &self.active_pane
4377 }
4378
4379 pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
4380 for dock in self.all_docks() {
4381 if dock.focus_handle(cx).contains_focused(window, cx)
4382 && let Some(pane) = dock
4383 .read(cx)
4384 .active_panel()
4385 .and_then(|panel| panel.pane(cx))
4386 {
4387 return pane;
4388 }
4389 }
4390 self.active_pane().clone()
4391 }
4392
4393 pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
4394 self.find_pane_in_direction(SplitDirection::Right, cx)
4395 .unwrap_or_else(|| {
4396 self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
4397 })
4398 }
4399
4400 pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
4401 let weak_pane = self.panes_by_item.get(&handle.item_id())?;
4402 weak_pane.upgrade()
4403 }
4404
4405 fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
4406 self.follower_states.retain(|leader_id, state| {
4407 if *leader_id == CollaboratorId::PeerId(peer_id) {
4408 for item in state.items_by_leader_view_id.values() {
4409 item.view.set_leader_id(None, window, cx);
4410 }
4411 false
4412 } else {
4413 true
4414 }
4415 });
4416 cx.notify();
4417 }
4418
4419 pub fn start_following(
4420 &mut self,
4421 leader_id: impl Into<CollaboratorId>,
4422 window: &mut Window,
4423 cx: &mut Context<Self>,
4424 ) -> Option<Task<Result<()>>> {
4425 let leader_id = leader_id.into();
4426 let pane = self.active_pane().clone();
4427
4428 self.last_leaders_by_pane
4429 .insert(pane.downgrade(), leader_id);
4430 self.unfollow(leader_id, window, cx);
4431 self.unfollow_in_pane(&pane, window, cx);
4432 self.follower_states.insert(
4433 leader_id,
4434 FollowerState {
4435 center_pane: pane.clone(),
4436 dock_pane: None,
4437 active_view_id: None,
4438 items_by_leader_view_id: Default::default(),
4439 },
4440 );
4441 cx.notify();
4442
4443 match leader_id {
4444 CollaboratorId::PeerId(leader_peer_id) => {
4445 let room_id = self.active_call()?.read(cx).room()?.read(cx).id();
4446 let project_id = self.project.read(cx).remote_id();
4447 let request = self.app_state.client.request(proto::Follow {
4448 room_id,
4449 project_id,
4450 leader_id: Some(leader_peer_id),
4451 });
4452
4453 Some(cx.spawn_in(window, async move |this, cx| {
4454 let response = request.await?;
4455 this.update(cx, |this, _| {
4456 let state = this
4457 .follower_states
4458 .get_mut(&leader_id)
4459 .context("following interrupted")?;
4460 state.active_view_id = response
4461 .active_view
4462 .as_ref()
4463 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
4464 anyhow::Ok(())
4465 })??;
4466 if let Some(view) = response.active_view {
4467 Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
4468 }
4469 this.update_in(cx, |this, window, cx| {
4470 this.leader_updated(leader_id, window, cx)
4471 })?;
4472 Ok(())
4473 }))
4474 }
4475 CollaboratorId::Agent => {
4476 self.leader_updated(leader_id, window, cx)?;
4477 Some(Task::ready(Ok(())))
4478 }
4479 }
4480 }
4481
4482 pub fn follow_next_collaborator(
4483 &mut self,
4484 _: &FollowNextCollaborator,
4485 window: &mut Window,
4486 cx: &mut Context<Self>,
4487 ) {
4488 let collaborators = self.project.read(cx).collaborators();
4489 let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
4490 let mut collaborators = collaborators.keys().copied();
4491 for peer_id in collaborators.by_ref() {
4492 if CollaboratorId::PeerId(peer_id) == leader_id {
4493 break;
4494 }
4495 }
4496 collaborators.next().map(CollaboratorId::PeerId)
4497 } else if let Some(last_leader_id) =
4498 self.last_leaders_by_pane.get(&self.active_pane.downgrade())
4499 {
4500 match last_leader_id {
4501 CollaboratorId::PeerId(peer_id) => {
4502 if collaborators.contains_key(peer_id) {
4503 Some(*last_leader_id)
4504 } else {
4505 None
4506 }
4507 }
4508 CollaboratorId::Agent => Some(CollaboratorId::Agent),
4509 }
4510 } else {
4511 None
4512 };
4513
4514 let pane = self.active_pane.clone();
4515 let Some(leader_id) = next_leader_id.or_else(|| {
4516 Some(CollaboratorId::PeerId(
4517 collaborators.keys().copied().next()?,
4518 ))
4519 }) else {
4520 return;
4521 };
4522 if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
4523 return;
4524 }
4525 if let Some(task) = self.start_following(leader_id, window, cx) {
4526 task.detach_and_log_err(cx)
4527 }
4528 }
4529
4530 pub fn follow(
4531 &mut self,
4532 leader_id: impl Into<CollaboratorId>,
4533 window: &mut Window,
4534 cx: &mut Context<Self>,
4535 ) {
4536 let leader_id = leader_id.into();
4537
4538 if let CollaboratorId::PeerId(peer_id) = leader_id {
4539 let Some(room) = ActiveCall::global(cx).read(cx).room() else {
4540 return;
4541 };
4542 let room = room.read(cx);
4543 let Some(remote_participant) = room.remote_participant_for_peer_id(peer_id) else {
4544 return;
4545 };
4546
4547 let project = self.project.read(cx);
4548
4549 let other_project_id = match remote_participant.location {
4550 call::ParticipantLocation::External => None,
4551 call::ParticipantLocation::UnsharedProject => None,
4552 call::ParticipantLocation::SharedProject { project_id } => {
4553 if Some(project_id) == project.remote_id() {
4554 None
4555 } else {
4556 Some(project_id)
4557 }
4558 }
4559 };
4560
4561 // if they are active in another project, follow there.
4562 if let Some(project_id) = other_project_id {
4563 let app_state = self.app_state.clone();
4564 crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
4565 .detach_and_log_err(cx);
4566 }
4567 }
4568
4569 // if you're already following, find the right pane and focus it.
4570 if let Some(follower_state) = self.follower_states.get(&leader_id) {
4571 window.focus(&follower_state.pane().focus_handle(cx));
4572
4573 return;
4574 }
4575
4576 // Otherwise, follow.
4577 if let Some(task) = self.start_following(leader_id, window, cx) {
4578 task.detach_and_log_err(cx)
4579 }
4580 }
4581
4582 pub fn unfollow(
4583 &mut self,
4584 leader_id: impl Into<CollaboratorId>,
4585 window: &mut Window,
4586 cx: &mut Context<Self>,
4587 ) -> Option<()> {
4588 cx.notify();
4589
4590 let leader_id = leader_id.into();
4591 let state = self.follower_states.remove(&leader_id)?;
4592 for (_, item) in state.items_by_leader_view_id {
4593 item.view.set_leader_id(None, window, cx);
4594 }
4595
4596 if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
4597 let project_id = self.project.read(cx).remote_id();
4598 let room_id = self.active_call()?.read(cx).room()?.read(cx).id();
4599 self.app_state
4600 .client
4601 .send(proto::Unfollow {
4602 room_id,
4603 project_id,
4604 leader_id: Some(leader_peer_id),
4605 })
4606 .log_err();
4607 }
4608
4609 Some(())
4610 }
4611
4612 pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
4613 self.follower_states.contains_key(&id.into())
4614 }
4615
4616 fn active_item_path_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4617 cx.emit(Event::ActiveItemChanged);
4618 let active_entry = self.active_project_path(cx);
4619 self.project.update(cx, |project, cx| {
4620 project.set_active_path(active_entry.clone(), cx)
4621 });
4622
4623 if let Some(project_path) = &active_entry {
4624 let git_store_entity = self.project.read(cx).git_store().clone();
4625 git_store_entity.update(cx, |git_store, cx| {
4626 git_store.set_active_repo_for_path(project_path, cx);
4627 });
4628 }
4629
4630 self.update_window_title(window, cx);
4631 }
4632
4633 fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
4634 let project = self.project().read(cx);
4635 let mut title = String::new();
4636
4637 for (i, worktree) in project.visible_worktrees(cx).enumerate() {
4638 let name = {
4639 let settings_location = SettingsLocation {
4640 worktree_id: worktree.read(cx).id(),
4641 path: RelPath::empty(),
4642 };
4643
4644 let settings = WorktreeSettings::get(Some(settings_location), cx);
4645 match &settings.project_name {
4646 Some(name) => name.as_str(),
4647 None => worktree.read(cx).root_name_str(),
4648 }
4649 };
4650 if i > 0 {
4651 title.push_str(", ");
4652 }
4653 title.push_str(name);
4654 }
4655
4656 if title.is_empty() {
4657 title = "empty project".to_string();
4658 }
4659
4660 if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
4661 let filename = path.path.file_name().or_else(|| {
4662 Some(
4663 project
4664 .worktree_for_id(path.worktree_id, cx)?
4665 .read(cx)
4666 .root_name_str(),
4667 )
4668 });
4669
4670 if let Some(filename) = filename {
4671 title.push_str(" — ");
4672 title.push_str(filename.as_ref());
4673 }
4674 }
4675
4676 if project.is_via_collab() {
4677 title.push_str(" ↙");
4678 } else if project.is_shared() {
4679 title.push_str(" ↗");
4680 }
4681
4682 if let Some(last_title) = self.last_window_title.as_ref()
4683 && &title == last_title
4684 {
4685 return;
4686 }
4687 window.set_window_title(&title);
4688 SystemWindowTabController::update_tab_title(
4689 cx,
4690 window.window_handle().window_id(),
4691 SharedString::from(&title),
4692 );
4693 self.last_window_title = Some(title);
4694 }
4695
4696 fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
4697 let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
4698 if is_edited != self.window_edited {
4699 self.window_edited = is_edited;
4700 window.set_window_edited(self.window_edited)
4701 }
4702 }
4703
4704 fn update_item_dirty_state(
4705 &mut self,
4706 item: &dyn ItemHandle,
4707 window: &mut Window,
4708 cx: &mut App,
4709 ) {
4710 let is_dirty = item.is_dirty(cx);
4711 let item_id = item.item_id();
4712 let was_dirty = self.dirty_items.contains_key(&item_id);
4713 if is_dirty == was_dirty {
4714 return;
4715 }
4716 if was_dirty {
4717 self.dirty_items.remove(&item_id);
4718 self.update_window_edited(window, cx);
4719 return;
4720 }
4721 if let Some(window_handle) = window.window_handle().downcast::<Self>() {
4722 let s = item.on_release(
4723 cx,
4724 Box::new(move |cx| {
4725 window_handle
4726 .update(cx, |this, window, cx| {
4727 this.dirty_items.remove(&item_id);
4728 this.update_window_edited(window, cx)
4729 })
4730 .ok();
4731 }),
4732 );
4733 self.dirty_items.insert(item_id, s);
4734 self.update_window_edited(window, cx);
4735 }
4736 }
4737
4738 fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
4739 if self.notifications.is_empty() {
4740 None
4741 } else {
4742 Some(
4743 div()
4744 .absolute()
4745 .right_3()
4746 .bottom_3()
4747 .w_112()
4748 .h_full()
4749 .flex()
4750 .flex_col()
4751 .justify_end()
4752 .gap_2()
4753 .children(
4754 self.notifications
4755 .iter()
4756 .map(|(_, notification)| notification.clone().into_any()),
4757 ),
4758 )
4759 }
4760 }
4761
4762 // RPC handlers
4763
4764 fn active_view_for_follower(
4765 &self,
4766 follower_project_id: Option<u64>,
4767 window: &mut Window,
4768 cx: &mut Context<Self>,
4769 ) -> Option<proto::View> {
4770 let (item, panel_id) = self.active_item_for_followers(window, cx);
4771 let item = item?;
4772 let leader_id = self
4773 .pane_for(&*item)
4774 .and_then(|pane| self.leader_for_pane(&pane));
4775 let leader_peer_id = match leader_id {
4776 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
4777 Some(CollaboratorId::Agent) | None => None,
4778 };
4779
4780 let item_handle = item.to_followable_item_handle(cx)?;
4781 let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
4782 let variant = item_handle.to_state_proto(window, cx)?;
4783
4784 if item_handle.is_project_item(window, cx)
4785 && (follower_project_id.is_none()
4786 || follower_project_id != self.project.read(cx).remote_id())
4787 {
4788 return None;
4789 }
4790
4791 Some(proto::View {
4792 id: id.to_proto(),
4793 leader_id: leader_peer_id,
4794 variant: Some(variant),
4795 panel_id: panel_id.map(|id| id as i32),
4796 })
4797 }
4798
4799 fn handle_follow(
4800 &mut self,
4801 follower_project_id: Option<u64>,
4802 window: &mut Window,
4803 cx: &mut Context<Self>,
4804 ) -> proto::FollowResponse {
4805 let active_view = self.active_view_for_follower(follower_project_id, window, cx);
4806
4807 cx.notify();
4808 proto::FollowResponse {
4809 // TODO: Remove after version 0.145.x stabilizes.
4810 active_view_id: active_view.as_ref().and_then(|view| view.id.clone()),
4811 views: active_view.iter().cloned().collect(),
4812 active_view,
4813 }
4814 }
4815
4816 fn handle_update_followers(
4817 &mut self,
4818 leader_id: PeerId,
4819 message: proto::UpdateFollowers,
4820 _window: &mut Window,
4821 _cx: &mut Context<Self>,
4822 ) {
4823 self.leader_updates_tx
4824 .unbounded_send((leader_id, message))
4825 .ok();
4826 }
4827
4828 async fn process_leader_update(
4829 this: &WeakEntity<Self>,
4830 leader_id: PeerId,
4831 update: proto::UpdateFollowers,
4832 cx: &mut AsyncWindowContext,
4833 ) -> Result<()> {
4834 match update.variant.context("invalid update")? {
4835 proto::update_followers::Variant::CreateView(view) => {
4836 let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
4837 let should_add_view = this.update(cx, |this, _| {
4838 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
4839 anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
4840 } else {
4841 anyhow::Ok(false)
4842 }
4843 })??;
4844
4845 if should_add_view {
4846 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
4847 }
4848 }
4849 proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
4850 let should_add_view = this.update(cx, |this, _| {
4851 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
4852 state.active_view_id = update_active_view
4853 .view
4854 .as_ref()
4855 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
4856
4857 if state.active_view_id.is_some_and(|view_id| {
4858 !state.items_by_leader_view_id.contains_key(&view_id)
4859 }) {
4860 anyhow::Ok(true)
4861 } else {
4862 anyhow::Ok(false)
4863 }
4864 } else {
4865 anyhow::Ok(false)
4866 }
4867 })??;
4868
4869 if should_add_view && let Some(view) = update_active_view.view {
4870 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
4871 }
4872 }
4873 proto::update_followers::Variant::UpdateView(update_view) => {
4874 let variant = update_view.variant.context("missing update view variant")?;
4875 let id = update_view.id.context("missing update view id")?;
4876 let mut tasks = Vec::new();
4877 this.update_in(cx, |this, window, cx| {
4878 let project = this.project.clone();
4879 if let Some(state) = this.follower_states.get(&leader_id.into()) {
4880 let view_id = ViewId::from_proto(id.clone())?;
4881 if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
4882 tasks.push(item.view.apply_update_proto(
4883 &project,
4884 variant.clone(),
4885 window,
4886 cx,
4887 ));
4888 }
4889 }
4890 anyhow::Ok(())
4891 })??;
4892 try_join_all(tasks).await.log_err();
4893 }
4894 }
4895 this.update_in(cx, |this, window, cx| {
4896 this.leader_updated(leader_id, window, cx)
4897 })?;
4898 Ok(())
4899 }
4900
4901 async fn add_view_from_leader(
4902 this: WeakEntity<Self>,
4903 leader_id: PeerId,
4904 view: &proto::View,
4905 cx: &mut AsyncWindowContext,
4906 ) -> Result<()> {
4907 let this = this.upgrade().context("workspace dropped")?;
4908
4909 let Some(id) = view.id.clone() else {
4910 anyhow::bail!("no id for view");
4911 };
4912 let id = ViewId::from_proto(id)?;
4913 let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
4914
4915 let pane = this.update(cx, |this, _cx| {
4916 let state = this
4917 .follower_states
4918 .get(&leader_id.into())
4919 .context("stopped following")?;
4920 anyhow::Ok(state.pane().clone())
4921 })??;
4922 let existing_item = pane.update_in(cx, |pane, window, cx| {
4923 let client = this.read(cx).client().clone();
4924 pane.items().find_map(|item| {
4925 let item = item.to_followable_item_handle(cx)?;
4926 if item.remote_id(&client, window, cx) == Some(id) {
4927 Some(item)
4928 } else {
4929 None
4930 }
4931 })
4932 })?;
4933 let item = if let Some(existing_item) = existing_item {
4934 existing_item
4935 } else {
4936 let variant = view.variant.clone();
4937 anyhow::ensure!(variant.is_some(), "missing view variant");
4938
4939 let task = cx.update(|window, cx| {
4940 FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
4941 })?;
4942
4943 let Some(task) = task else {
4944 anyhow::bail!(
4945 "failed to construct view from leader (maybe from a different version of zed?)"
4946 );
4947 };
4948
4949 let mut new_item = task.await?;
4950 pane.update_in(cx, |pane, window, cx| {
4951 let mut item_to_remove = None;
4952 for (ix, item) in pane.items().enumerate() {
4953 if let Some(item) = item.to_followable_item_handle(cx) {
4954 match new_item.dedup(item.as_ref(), window, cx) {
4955 Some(item::Dedup::KeepExisting) => {
4956 new_item =
4957 item.boxed_clone().to_followable_item_handle(cx).unwrap();
4958 break;
4959 }
4960 Some(item::Dedup::ReplaceExisting) => {
4961 item_to_remove = Some((ix, item.item_id()));
4962 break;
4963 }
4964 None => {}
4965 }
4966 }
4967 }
4968
4969 if let Some((ix, id)) = item_to_remove {
4970 pane.remove_item(id, false, false, window, cx);
4971 pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
4972 }
4973 })?;
4974
4975 new_item
4976 };
4977
4978 this.update_in(cx, |this, window, cx| {
4979 let state = this.follower_states.get_mut(&leader_id.into())?;
4980 item.set_leader_id(Some(leader_id.into()), window, cx);
4981 state.items_by_leader_view_id.insert(
4982 id,
4983 FollowerView {
4984 view: item,
4985 location: panel_id,
4986 },
4987 );
4988
4989 Some(())
4990 })?;
4991
4992 Ok(())
4993 }
4994
4995 fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4996 let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
4997 return;
4998 };
4999
5000 if let Some(agent_location) = self.project.read(cx).agent_location() {
5001 let buffer_entity_id = agent_location.buffer.entity_id();
5002 let view_id = ViewId {
5003 creator: CollaboratorId::Agent,
5004 id: buffer_entity_id.as_u64(),
5005 };
5006 follower_state.active_view_id = Some(view_id);
5007
5008 let item = match follower_state.items_by_leader_view_id.entry(view_id) {
5009 hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
5010 hash_map::Entry::Vacant(entry) => {
5011 let existing_view =
5012 follower_state
5013 .center_pane
5014 .read(cx)
5015 .items()
5016 .find_map(|item| {
5017 let item = item.to_followable_item_handle(cx)?;
5018 if item.buffer_kind(cx) == ItemBufferKind::Singleton
5019 && item.project_item_model_ids(cx).as_slice()
5020 == [buffer_entity_id]
5021 {
5022 Some(item)
5023 } else {
5024 None
5025 }
5026 });
5027 let view = existing_view.or_else(|| {
5028 agent_location.buffer.upgrade().and_then(|buffer| {
5029 cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
5030 registry.build_item(buffer, self.project.clone(), None, window, cx)
5031 })?
5032 .to_followable_item_handle(cx)
5033 })
5034 });
5035
5036 view.map(|view| {
5037 entry.insert(FollowerView {
5038 view,
5039 location: None,
5040 })
5041 })
5042 }
5043 };
5044
5045 if let Some(item) = item {
5046 item.view
5047 .set_leader_id(Some(CollaboratorId::Agent), window, cx);
5048 item.view
5049 .update_agent_location(agent_location.position, window, cx);
5050 }
5051 } else {
5052 follower_state.active_view_id = None;
5053 }
5054
5055 self.leader_updated(CollaboratorId::Agent, window, cx);
5056 }
5057
5058 pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
5059 let mut is_project_item = true;
5060 let mut update = proto::UpdateActiveView::default();
5061 if window.is_window_active() {
5062 let (active_item, panel_id) = self.active_item_for_followers(window, cx);
5063
5064 if let Some(item) = active_item
5065 && item.item_focus_handle(cx).contains_focused(window, cx)
5066 {
5067 let leader_id = self
5068 .pane_for(&*item)
5069 .and_then(|pane| self.leader_for_pane(&pane));
5070 let leader_peer_id = match leader_id {
5071 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5072 Some(CollaboratorId::Agent) | None => None,
5073 };
5074
5075 if let Some(item) = item.to_followable_item_handle(cx) {
5076 let id = item
5077 .remote_id(&self.app_state.client, window, cx)
5078 .map(|id| id.to_proto());
5079
5080 if let Some(id) = id
5081 && let Some(variant) = item.to_state_proto(window, cx)
5082 {
5083 let view = Some(proto::View {
5084 id: id.clone(),
5085 leader_id: leader_peer_id,
5086 variant: Some(variant),
5087 panel_id: panel_id.map(|id| id as i32),
5088 });
5089
5090 is_project_item = item.is_project_item(window, cx);
5091 update = proto::UpdateActiveView {
5092 view,
5093 // TODO: Remove after version 0.145.x stabilizes.
5094 id,
5095 leader_id: leader_peer_id,
5096 };
5097 };
5098 }
5099 }
5100 }
5101
5102 let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
5103 if active_view_id != self.last_active_view_id.as_ref() {
5104 self.last_active_view_id = active_view_id.cloned();
5105 self.update_followers(
5106 is_project_item,
5107 proto::update_followers::Variant::UpdateActiveView(update),
5108 window,
5109 cx,
5110 );
5111 }
5112 }
5113
5114 fn active_item_for_followers(
5115 &self,
5116 window: &mut Window,
5117 cx: &mut App,
5118 ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
5119 let mut active_item = None;
5120 let mut panel_id = None;
5121 for dock in self.all_docks() {
5122 if dock.focus_handle(cx).contains_focused(window, cx)
5123 && let Some(panel) = dock.read(cx).active_panel()
5124 && let Some(pane) = panel.pane(cx)
5125 && let Some(item) = pane.read(cx).active_item()
5126 {
5127 active_item = Some(item);
5128 panel_id = panel.remote_id();
5129 break;
5130 }
5131 }
5132
5133 if active_item.is_none() {
5134 active_item = self.active_pane().read(cx).active_item();
5135 }
5136 (active_item, panel_id)
5137 }
5138
5139 fn update_followers(
5140 &self,
5141 project_only: bool,
5142 update: proto::update_followers::Variant,
5143 _: &mut Window,
5144 cx: &mut App,
5145 ) -> Option<()> {
5146 // If this update only applies to for followers in the current project,
5147 // then skip it unless this project is shared. If it applies to all
5148 // followers, regardless of project, then set `project_id` to none,
5149 // indicating that it goes to all followers.
5150 let project_id = if project_only {
5151 Some(self.project.read(cx).remote_id()?)
5152 } else {
5153 None
5154 };
5155 self.app_state().workspace_store.update(cx, |store, cx| {
5156 store.update_followers(project_id, update, cx)
5157 })
5158 }
5159
5160 pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
5161 self.follower_states.iter().find_map(|(leader_id, state)| {
5162 if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
5163 Some(*leader_id)
5164 } else {
5165 None
5166 }
5167 })
5168 }
5169
5170 fn leader_updated(
5171 &mut self,
5172 leader_id: impl Into<CollaboratorId>,
5173 window: &mut Window,
5174 cx: &mut Context<Self>,
5175 ) -> Option<Box<dyn ItemHandle>> {
5176 cx.notify();
5177
5178 let leader_id = leader_id.into();
5179 let (panel_id, item) = match leader_id {
5180 CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
5181 CollaboratorId::Agent => (None, self.active_item_for_agent()?),
5182 };
5183
5184 let state = self.follower_states.get(&leader_id)?;
5185 let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
5186 let pane;
5187 if let Some(panel_id) = panel_id {
5188 pane = self
5189 .activate_panel_for_proto_id(panel_id, window, cx)?
5190 .pane(cx)?;
5191 let state = self.follower_states.get_mut(&leader_id)?;
5192 state.dock_pane = Some(pane.clone());
5193 } else {
5194 pane = state.center_pane.clone();
5195 let state = self.follower_states.get_mut(&leader_id)?;
5196 if let Some(dock_pane) = state.dock_pane.take() {
5197 transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
5198 }
5199 }
5200
5201 pane.update(cx, |pane, cx| {
5202 let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
5203 if let Some(index) = pane.index_for_item(item.as_ref()) {
5204 pane.activate_item(index, false, false, window, cx);
5205 } else {
5206 pane.add_item(item.boxed_clone(), false, false, None, window, cx)
5207 }
5208
5209 if focus_active_item {
5210 pane.focus_active_item(window, cx)
5211 }
5212 });
5213
5214 Some(item)
5215 }
5216
5217 fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
5218 let state = self.follower_states.get(&CollaboratorId::Agent)?;
5219 let active_view_id = state.active_view_id?;
5220 Some(
5221 state
5222 .items_by_leader_view_id
5223 .get(&active_view_id)?
5224 .view
5225 .boxed_clone(),
5226 )
5227 }
5228
5229 fn active_item_for_peer(
5230 &self,
5231 peer_id: PeerId,
5232 window: &mut Window,
5233 cx: &mut Context<Self>,
5234 ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
5235 let call = self.active_call()?;
5236 let room = call.read(cx).room()?.read(cx);
5237 let participant = room.remote_participant_for_peer_id(peer_id)?;
5238 let leader_in_this_app;
5239 let leader_in_this_project;
5240 match participant.location {
5241 call::ParticipantLocation::SharedProject { project_id } => {
5242 leader_in_this_app = true;
5243 leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
5244 }
5245 call::ParticipantLocation::UnsharedProject => {
5246 leader_in_this_app = true;
5247 leader_in_this_project = false;
5248 }
5249 call::ParticipantLocation::External => {
5250 leader_in_this_app = false;
5251 leader_in_this_project = false;
5252 }
5253 };
5254 let state = self.follower_states.get(&peer_id.into())?;
5255 let mut item_to_activate = None;
5256 if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
5257 if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
5258 && (leader_in_this_project || !item.view.is_project_item(window, cx))
5259 {
5260 item_to_activate = Some((item.location, item.view.boxed_clone()));
5261 }
5262 } else if let Some(shared_screen) =
5263 self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
5264 {
5265 item_to_activate = Some((None, Box::new(shared_screen)));
5266 }
5267 item_to_activate
5268 }
5269
5270 fn shared_screen_for_peer(
5271 &self,
5272 peer_id: PeerId,
5273 pane: &Entity<Pane>,
5274 window: &mut Window,
5275 cx: &mut App,
5276 ) -> Option<Entity<SharedScreen>> {
5277 let call = self.active_call()?;
5278 let room = call.read(cx).room()?.clone();
5279 let participant = room.read(cx).remote_participant_for_peer_id(peer_id)?;
5280 let track = participant.video_tracks.values().next()?.clone();
5281 let user = participant.user.clone();
5282
5283 for item in pane.read(cx).items_of_type::<SharedScreen>() {
5284 if item.read(cx).peer_id == peer_id {
5285 return Some(item);
5286 }
5287 }
5288
5289 Some(cx.new(|cx| SharedScreen::new(track, peer_id, user.clone(), room.clone(), window, cx)))
5290 }
5291
5292 pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5293 if window.is_window_active() {
5294 self.update_active_view_for_followers(window, cx);
5295
5296 if let Some(database_id) = self.database_id {
5297 cx.background_spawn(persistence::DB.update_timestamp(database_id))
5298 .detach();
5299 }
5300 } else {
5301 for pane in &self.panes {
5302 pane.update(cx, |pane, cx| {
5303 if let Some(item) = pane.active_item() {
5304 item.workspace_deactivated(window, cx);
5305 }
5306 for item in pane.items() {
5307 if matches!(
5308 item.workspace_settings(cx).autosave,
5309 AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
5310 ) {
5311 Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
5312 .detach_and_log_err(cx);
5313 }
5314 }
5315 });
5316 }
5317 }
5318 }
5319
5320 pub fn active_call(&self) -> Option<&Entity<ActiveCall>> {
5321 self.active_call.as_ref().map(|(call, _)| call)
5322 }
5323
5324 fn on_active_call_event(
5325 &mut self,
5326 _: &Entity<ActiveCall>,
5327 event: &call::room::Event,
5328 window: &mut Window,
5329 cx: &mut Context<Self>,
5330 ) {
5331 match event {
5332 call::room::Event::ParticipantLocationChanged { participant_id }
5333 | call::room::Event::RemoteVideoTracksChanged { participant_id } => {
5334 self.leader_updated(participant_id, window, cx);
5335 }
5336 _ => {}
5337 }
5338 }
5339
5340 pub fn database_id(&self) -> Option<WorkspaceId> {
5341 self.database_id
5342 }
5343
5344 pub fn session_id(&self) -> Option<String> {
5345 self.session_id.clone()
5346 }
5347
5348 pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
5349 let project = self.project().read(cx);
5350 project
5351 .visible_worktrees(cx)
5352 .map(|worktree| worktree.read(cx).abs_path())
5353 .collect::<Vec<_>>()
5354 }
5355
5356 fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
5357 match member {
5358 Member::Axis(PaneAxis { members, .. }) => {
5359 for child in members.iter() {
5360 self.remove_panes(child.clone(), window, cx)
5361 }
5362 }
5363 Member::Pane(pane) => {
5364 self.force_remove_pane(&pane, &None, window, cx);
5365 }
5366 }
5367 }
5368
5369 fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
5370 self.session_id.take();
5371 self.serialize_workspace_internal(window, cx)
5372 }
5373
5374 fn force_remove_pane(
5375 &mut self,
5376 pane: &Entity<Pane>,
5377 focus_on: &Option<Entity<Pane>>,
5378 window: &mut Window,
5379 cx: &mut Context<Workspace>,
5380 ) {
5381 self.panes.retain(|p| p != pane);
5382 if let Some(focus_on) = focus_on {
5383 focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)));
5384 } else if self.active_pane() == pane {
5385 self.panes
5386 .last()
5387 .unwrap()
5388 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)));
5389 }
5390 if self.last_active_center_pane == Some(pane.downgrade()) {
5391 self.last_active_center_pane = None;
5392 }
5393 cx.notify();
5394 }
5395
5396 fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5397 if self._schedule_serialize_workspace.is_none() {
5398 self._schedule_serialize_workspace =
5399 Some(cx.spawn_in(window, async move |this, cx| {
5400 cx.background_executor()
5401 .timer(SERIALIZATION_THROTTLE_TIME)
5402 .await;
5403 this.update_in(cx, |this, window, cx| {
5404 this.serialize_workspace_internal(window, cx).detach();
5405 this._schedule_serialize_workspace.take();
5406 })
5407 .log_err();
5408 }));
5409 }
5410 }
5411
5412 fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
5413 let Some(database_id) = self.database_id() else {
5414 return Task::ready(());
5415 };
5416
5417 fn serialize_pane_handle(
5418 pane_handle: &Entity<Pane>,
5419 window: &mut Window,
5420 cx: &mut App,
5421 ) -> SerializedPane {
5422 let (items, active, pinned_count) = {
5423 let pane = pane_handle.read(cx);
5424 let active_item_id = pane.active_item().map(|item| item.item_id());
5425 (
5426 pane.items()
5427 .filter_map(|handle| {
5428 let handle = handle.to_serializable_item_handle(cx)?;
5429
5430 Some(SerializedItem {
5431 kind: Arc::from(handle.serialized_item_kind()),
5432 item_id: handle.item_id().as_u64(),
5433 active: Some(handle.item_id()) == active_item_id,
5434 preview: pane.is_active_preview_item(handle.item_id()),
5435 })
5436 })
5437 .collect::<Vec<_>>(),
5438 pane.has_focus(window, cx),
5439 pane.pinned_count(),
5440 )
5441 };
5442
5443 SerializedPane::new(items, active, pinned_count)
5444 }
5445
5446 fn build_serialized_pane_group(
5447 pane_group: &Member,
5448 window: &mut Window,
5449 cx: &mut App,
5450 ) -> SerializedPaneGroup {
5451 match pane_group {
5452 Member::Axis(PaneAxis {
5453 axis,
5454 members,
5455 flexes,
5456 bounding_boxes: _,
5457 }) => SerializedPaneGroup::Group {
5458 axis: SerializedAxis(*axis),
5459 children: members
5460 .iter()
5461 .map(|member| build_serialized_pane_group(member, window, cx))
5462 .collect::<Vec<_>>(),
5463 flexes: Some(flexes.lock().clone()),
5464 },
5465 Member::Pane(pane_handle) => {
5466 SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
5467 }
5468 }
5469 }
5470
5471 fn build_serialized_docks(
5472 this: &Workspace,
5473 window: &mut Window,
5474 cx: &mut App,
5475 ) -> DockStructure {
5476 let left_dock = this.left_dock.read(cx);
5477 let left_visible = left_dock.is_open();
5478 let left_active_panel = left_dock
5479 .active_panel()
5480 .map(|panel| panel.persistent_name().to_string());
5481 let left_dock_zoom = left_dock
5482 .active_panel()
5483 .map(|panel| panel.is_zoomed(window, cx))
5484 .unwrap_or(false);
5485
5486 let right_dock = this.right_dock.read(cx);
5487 let right_visible = right_dock.is_open();
5488 let right_active_panel = right_dock
5489 .active_panel()
5490 .map(|panel| panel.persistent_name().to_string());
5491 let right_dock_zoom = right_dock
5492 .active_panel()
5493 .map(|panel| panel.is_zoomed(window, cx))
5494 .unwrap_or(false);
5495
5496 let bottom_dock = this.bottom_dock.read(cx);
5497 let bottom_visible = bottom_dock.is_open();
5498 let bottom_active_panel = bottom_dock
5499 .active_panel()
5500 .map(|panel| panel.persistent_name().to_string());
5501 let bottom_dock_zoom = bottom_dock
5502 .active_panel()
5503 .map(|panel| panel.is_zoomed(window, cx))
5504 .unwrap_or(false);
5505
5506 DockStructure {
5507 left: DockData {
5508 visible: left_visible,
5509 active_panel: left_active_panel,
5510 zoom: left_dock_zoom,
5511 },
5512 right: DockData {
5513 visible: right_visible,
5514 active_panel: right_active_panel,
5515 zoom: right_dock_zoom,
5516 },
5517 bottom: DockData {
5518 visible: bottom_visible,
5519 active_panel: bottom_active_panel,
5520 zoom: bottom_dock_zoom,
5521 },
5522 }
5523 }
5524
5525 match self.serialize_workspace_location(cx) {
5526 WorkspaceLocation::Location(location, paths) => {
5527 let breakpoints = self.project.update(cx, |project, cx| {
5528 project
5529 .breakpoint_store()
5530 .read(cx)
5531 .all_source_breakpoints(cx)
5532 });
5533 let user_toolchains = self
5534 .project
5535 .read(cx)
5536 .user_toolchains(cx)
5537 .unwrap_or_default();
5538
5539 let center_group = build_serialized_pane_group(&self.center.root, window, cx);
5540 let docks = build_serialized_docks(self, window, cx);
5541 let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
5542
5543 let serialized_workspace = SerializedWorkspace {
5544 id: database_id,
5545 location,
5546 paths,
5547 center_group,
5548 window_bounds,
5549 display: Default::default(),
5550 docks,
5551 centered_layout: self.centered_layout,
5552 session_id: self.session_id.clone(),
5553 breakpoints,
5554 window_id: Some(window.window_handle().window_id().as_u64()),
5555 user_toolchains,
5556 };
5557
5558 window.spawn(cx, async move |_| {
5559 persistence::DB.save_workspace(serialized_workspace).await;
5560 })
5561 }
5562 WorkspaceLocation::DetachFromSession => window.spawn(cx, async move |_| {
5563 persistence::DB
5564 .set_session_id(database_id, None)
5565 .await
5566 .log_err();
5567 }),
5568 WorkspaceLocation::None => Task::ready(()),
5569 }
5570 }
5571
5572 fn serialize_workspace_location(&self, cx: &App) -> WorkspaceLocation {
5573 let paths = PathList::new(&self.root_paths(cx));
5574 if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
5575 WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
5576 } else if self.project.read(cx).is_local() {
5577 if !paths.is_empty() {
5578 WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
5579 } else {
5580 WorkspaceLocation::DetachFromSession
5581 }
5582 } else {
5583 WorkspaceLocation::None
5584 }
5585 }
5586
5587 fn update_history(&self, cx: &mut App) {
5588 let Some(id) = self.database_id() else {
5589 return;
5590 };
5591 if !self.project.read(cx).is_local() {
5592 return;
5593 }
5594 if let Some(manager) = HistoryManager::global(cx) {
5595 let paths = PathList::new(&self.root_paths(cx));
5596 manager.update(cx, |this, cx| {
5597 this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
5598 });
5599 }
5600 }
5601
5602 async fn serialize_items(
5603 this: &WeakEntity<Self>,
5604 items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
5605 cx: &mut AsyncWindowContext,
5606 ) -> Result<()> {
5607 const CHUNK_SIZE: usize = 200;
5608
5609 let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
5610
5611 while let Some(items_received) = serializable_items.next().await {
5612 let unique_items =
5613 items_received
5614 .into_iter()
5615 .fold(HashMap::default(), |mut acc, item| {
5616 acc.entry(item.item_id()).or_insert(item);
5617 acc
5618 });
5619
5620 // We use into_iter() here so that the references to the items are moved into
5621 // the tasks and not kept alive while we're sleeping.
5622 for (_, item) in unique_items.into_iter() {
5623 if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
5624 item.serialize(workspace, false, window, cx)
5625 }) {
5626 cx.background_spawn(async move { task.await.log_err() })
5627 .detach();
5628 }
5629 }
5630
5631 cx.background_executor()
5632 .timer(SERIALIZATION_THROTTLE_TIME)
5633 .await;
5634 }
5635
5636 Ok(())
5637 }
5638
5639 pub(crate) fn enqueue_item_serialization(
5640 &mut self,
5641 item: Box<dyn SerializableItemHandle>,
5642 ) -> Result<()> {
5643 self.serializable_items_tx
5644 .unbounded_send(item)
5645 .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
5646 }
5647
5648 pub(crate) fn load_workspace(
5649 serialized_workspace: SerializedWorkspace,
5650 paths_to_open: Vec<Option<ProjectPath>>,
5651 window: &mut Window,
5652 cx: &mut Context<Workspace>,
5653 ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
5654 cx.spawn_in(window, async move |workspace, cx| {
5655 let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
5656
5657 let mut center_group = None;
5658 let mut center_items = None;
5659
5660 // Traverse the splits tree and add to things
5661 if let Some((group, active_pane, items)) = serialized_workspace
5662 .center_group
5663 .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
5664 .await
5665 {
5666 center_items = Some(items);
5667 center_group = Some((group, active_pane))
5668 }
5669
5670 let mut items_by_project_path = HashMap::default();
5671 let mut item_ids_by_kind = HashMap::default();
5672 let mut all_deserialized_items = Vec::default();
5673 cx.update(|_, cx| {
5674 for item in center_items.unwrap_or_default().into_iter().flatten() {
5675 if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
5676 item_ids_by_kind
5677 .entry(serializable_item_handle.serialized_item_kind())
5678 .or_insert(Vec::new())
5679 .push(item.item_id().as_u64() as ItemId);
5680 }
5681
5682 if let Some(project_path) = item.project_path(cx) {
5683 items_by_project_path.insert(project_path, item.clone());
5684 }
5685 all_deserialized_items.push(item);
5686 }
5687 })?;
5688
5689 let opened_items = paths_to_open
5690 .into_iter()
5691 .map(|path_to_open| {
5692 path_to_open
5693 .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
5694 })
5695 .collect::<Vec<_>>();
5696
5697 // Remove old panes from workspace panes list
5698 workspace.update_in(cx, |workspace, window, cx| {
5699 if let Some((center_group, active_pane)) = center_group {
5700 workspace.remove_panes(workspace.center.root.clone(), window, cx);
5701
5702 // Swap workspace center group
5703 workspace.center = PaneGroup::with_root(center_group);
5704 workspace.center.set_is_center(true);
5705 workspace.center.mark_positions(cx);
5706
5707 if let Some(active_pane) = active_pane {
5708 workspace.set_active_pane(&active_pane, window, cx);
5709 cx.focus_self(window);
5710 } else {
5711 workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
5712 }
5713 }
5714
5715 let docks = serialized_workspace.docks;
5716
5717 for (dock, serialized_dock) in [
5718 (&mut workspace.right_dock, docks.right),
5719 (&mut workspace.left_dock, docks.left),
5720 (&mut workspace.bottom_dock, docks.bottom),
5721 ]
5722 .iter_mut()
5723 {
5724 dock.update(cx, |dock, cx| {
5725 dock.serialized_dock = Some(serialized_dock.clone());
5726 dock.restore_state(window, cx);
5727 });
5728 }
5729
5730 cx.notify();
5731 })?;
5732
5733 let _ = project
5734 .update(cx, |project, cx| {
5735 project
5736 .breakpoint_store()
5737 .update(cx, |breakpoint_store, cx| {
5738 breakpoint_store
5739 .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
5740 })
5741 })?
5742 .await;
5743
5744 // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
5745 // after loading the items, we might have different items and in order to avoid
5746 // the database filling up, we delete items that haven't been loaded now.
5747 //
5748 // The items that have been loaded, have been saved after they've been added to the workspace.
5749 let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
5750 item_ids_by_kind
5751 .into_iter()
5752 .map(|(item_kind, loaded_items)| {
5753 SerializableItemRegistry::cleanup(
5754 item_kind,
5755 serialized_workspace.id,
5756 loaded_items,
5757 window,
5758 cx,
5759 )
5760 .log_err()
5761 })
5762 .collect::<Vec<_>>()
5763 })?;
5764
5765 futures::future::join_all(clean_up_tasks).await;
5766
5767 workspace
5768 .update_in(cx, |workspace, window, cx| {
5769 // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
5770 workspace.serialize_workspace_internal(window, cx).detach();
5771
5772 // Ensure that we mark the window as edited if we did load dirty items
5773 workspace.update_window_edited(window, cx);
5774 })
5775 .ok();
5776
5777 Ok(opened_items)
5778 })
5779 }
5780
5781 fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
5782 self.add_workspace_actions_listeners(div, window, cx)
5783 .on_action(cx.listener(
5784 |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
5785 for action in &action_sequence.0 {
5786 window.dispatch_action(action.boxed_clone(), cx);
5787 }
5788 },
5789 ))
5790 .on_action(cx.listener(Self::close_inactive_items_and_panes))
5791 .on_action(cx.listener(Self::close_all_items_and_panes))
5792 .on_action(cx.listener(Self::save_all))
5793 .on_action(cx.listener(Self::send_keystrokes))
5794 .on_action(cx.listener(Self::add_folder_to_project))
5795 .on_action(cx.listener(Self::follow_next_collaborator))
5796 .on_action(cx.listener(Self::close_window))
5797 .on_action(cx.listener(Self::activate_pane_at_index))
5798 .on_action(cx.listener(Self::move_item_to_pane_at_index))
5799 .on_action(cx.listener(Self::move_focused_panel_to_next_position))
5800 .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
5801 .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
5802 let pane = workspace.active_pane().clone();
5803 workspace.unfollow_in_pane(&pane, window, cx);
5804 }))
5805 .on_action(cx.listener(|workspace, action: &Save, window, cx| {
5806 workspace
5807 .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
5808 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
5809 }))
5810 .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
5811 workspace
5812 .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
5813 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
5814 }))
5815 .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
5816 workspace
5817 .save_active_item(SaveIntent::SaveAs, window, cx)
5818 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
5819 }))
5820 .on_action(
5821 cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
5822 workspace.activate_previous_pane(window, cx)
5823 }),
5824 )
5825 .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
5826 workspace.activate_next_pane(window, cx)
5827 }))
5828 .on_action(
5829 cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
5830 workspace.activate_next_window(cx)
5831 }),
5832 )
5833 .on_action(
5834 cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
5835 workspace.activate_previous_window(cx)
5836 }),
5837 )
5838 .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
5839 workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
5840 }))
5841 .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
5842 workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
5843 }))
5844 .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
5845 workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
5846 }))
5847 .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
5848 workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
5849 }))
5850 .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
5851 workspace.activate_next_pane(window, cx)
5852 }))
5853 .on_action(cx.listener(
5854 |workspace, action: &MoveItemToPaneInDirection, window, cx| {
5855 workspace.move_item_to_pane_in_direction(action, window, cx)
5856 },
5857 ))
5858 .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
5859 workspace.swap_pane_in_direction(SplitDirection::Left, cx)
5860 }))
5861 .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
5862 workspace.swap_pane_in_direction(SplitDirection::Right, cx)
5863 }))
5864 .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
5865 workspace.swap_pane_in_direction(SplitDirection::Up, cx)
5866 }))
5867 .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
5868 workspace.swap_pane_in_direction(SplitDirection::Down, cx)
5869 }))
5870 .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
5871 const DIRECTION_PRIORITY: [SplitDirection; 4] = [
5872 SplitDirection::Down,
5873 SplitDirection::Up,
5874 SplitDirection::Right,
5875 SplitDirection::Left,
5876 ];
5877 for dir in DIRECTION_PRIORITY {
5878 if workspace.find_pane_in_direction(dir, cx).is_some() {
5879 workspace.swap_pane_in_direction(dir, cx);
5880 workspace.activate_pane_in_direction(dir.opposite(), window, cx);
5881 break;
5882 }
5883 }
5884 }))
5885 .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
5886 workspace.move_pane_to_border(SplitDirection::Left, cx)
5887 }))
5888 .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
5889 workspace.move_pane_to_border(SplitDirection::Right, cx)
5890 }))
5891 .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
5892 workspace.move_pane_to_border(SplitDirection::Up, cx)
5893 }))
5894 .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
5895 workspace.move_pane_to_border(SplitDirection::Down, cx)
5896 }))
5897 .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
5898 this.toggle_dock(DockPosition::Left, window, cx);
5899 }))
5900 .on_action(cx.listener(
5901 |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
5902 workspace.toggle_dock(DockPosition::Right, window, cx);
5903 },
5904 ))
5905 .on_action(cx.listener(
5906 |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
5907 workspace.toggle_dock(DockPosition::Bottom, window, cx);
5908 },
5909 ))
5910 .on_action(cx.listener(
5911 |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
5912 if !workspace.close_active_dock(window, cx) {
5913 cx.propagate();
5914 }
5915 },
5916 ))
5917 .on_action(
5918 cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
5919 workspace.close_all_docks(window, cx);
5920 }),
5921 )
5922 .on_action(cx.listener(Self::toggle_all_docks))
5923 .on_action(cx.listener(
5924 |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
5925 workspace.clear_all_notifications(cx);
5926 },
5927 ))
5928 .on_action(cx.listener(
5929 |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
5930 workspace.clear_navigation_history(window, cx);
5931 },
5932 ))
5933 .on_action(cx.listener(
5934 |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
5935 if let Some((notification_id, _)) = workspace.notifications.pop() {
5936 workspace.suppress_notification(¬ification_id, cx);
5937 }
5938 },
5939 ))
5940 .on_action(cx.listener(
5941 |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
5942 workspace.reopen_closed_item(window, cx).detach();
5943 },
5944 ))
5945 .on_action(cx.listener(
5946 |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
5947 for dock in workspace.all_docks() {
5948 if dock.focus_handle(cx).contains_focused(window, cx) {
5949 let Some(panel) = dock.read(cx).active_panel() else {
5950 return;
5951 };
5952
5953 // Set to `None`, then the size will fall back to the default.
5954 panel.clone().set_size(None, window, cx);
5955
5956 return;
5957 }
5958 }
5959 },
5960 ))
5961 .on_action(cx.listener(
5962 |workspace: &mut Workspace, _: &ResetOpenDocksSize, window, cx| {
5963 for dock in workspace.all_docks() {
5964 if let Some(panel) = dock.read(cx).visible_panel() {
5965 // Set to `None`, then the size will fall back to the default.
5966 panel.clone().set_size(None, window, cx);
5967 }
5968 }
5969 },
5970 ))
5971 .on_action(cx.listener(
5972 |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
5973 adjust_active_dock_size_by_px(
5974 px_with_ui_font_fallback(act.px, cx),
5975 workspace,
5976 window,
5977 cx,
5978 );
5979 },
5980 ))
5981 .on_action(cx.listener(
5982 |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
5983 adjust_active_dock_size_by_px(
5984 px_with_ui_font_fallback(act.px, cx) * -1.,
5985 workspace,
5986 window,
5987 cx,
5988 );
5989 },
5990 ))
5991 .on_action(cx.listener(
5992 |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
5993 adjust_open_docks_size_by_px(
5994 px_with_ui_font_fallback(act.px, cx),
5995 workspace,
5996 window,
5997 cx,
5998 );
5999 },
6000 ))
6001 .on_action(cx.listener(
6002 |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
6003 adjust_open_docks_size_by_px(
6004 px_with_ui_font_fallback(act.px, cx) * -1.,
6005 workspace,
6006 window,
6007 cx,
6008 );
6009 },
6010 ))
6011 .on_action(cx.listener(Workspace::toggle_centered_layout))
6012 .on_action(cx.listener(
6013 |workspace: &mut Workspace, _action: &pane::ActivateNextItem, window, cx| {
6014 if let Some(active_dock) = workspace.active_dock(window, cx) {
6015 let dock = active_dock.read(cx);
6016 if let Some(active_panel) = dock.active_panel() {
6017 if active_panel.pane(cx).is_none() {
6018 let mut recent_pane: Option<Entity<Pane>> = None;
6019 let mut recent_timestamp = 0;
6020 for pane_handle in workspace.panes() {
6021 let pane = pane_handle.read(cx);
6022 for entry in pane.activation_history() {
6023 if entry.timestamp > recent_timestamp {
6024 recent_timestamp = entry.timestamp;
6025 recent_pane = Some(pane_handle.clone());
6026 }
6027 }
6028 }
6029
6030 if let Some(pane) = recent_pane {
6031 pane.update(cx, |pane, cx| {
6032 let current_index = pane.active_item_index();
6033 let items_len = pane.items_len();
6034 if items_len > 0 {
6035 let next_index = if current_index + 1 < items_len {
6036 current_index + 1
6037 } else {
6038 0
6039 };
6040 pane.activate_item(
6041 next_index, false, false, window, cx,
6042 );
6043 }
6044 });
6045 return;
6046 }
6047 }
6048 }
6049 }
6050 cx.propagate();
6051 },
6052 ))
6053 .on_action(cx.listener(
6054 |workspace: &mut Workspace, _action: &pane::ActivatePreviousItem, window, cx| {
6055 if let Some(active_dock) = workspace.active_dock(window, cx) {
6056 let dock = active_dock.read(cx);
6057 if let Some(active_panel) = dock.active_panel() {
6058 if active_panel.pane(cx).is_none() {
6059 let mut recent_pane: Option<Entity<Pane>> = None;
6060 let mut recent_timestamp = 0;
6061 for pane_handle in workspace.panes() {
6062 let pane = pane_handle.read(cx);
6063 for entry in pane.activation_history() {
6064 if entry.timestamp > recent_timestamp {
6065 recent_timestamp = entry.timestamp;
6066 recent_pane = Some(pane_handle.clone());
6067 }
6068 }
6069 }
6070
6071 if let Some(pane) = recent_pane {
6072 pane.update(cx, |pane, cx| {
6073 let current_index = pane.active_item_index();
6074 let items_len = pane.items_len();
6075 if items_len > 0 {
6076 let prev_index = if current_index > 0 {
6077 current_index - 1
6078 } else {
6079 items_len.saturating_sub(1)
6080 };
6081 pane.activate_item(
6082 prev_index, false, false, window, cx,
6083 );
6084 }
6085 });
6086 return;
6087 }
6088 }
6089 }
6090 }
6091 cx.propagate();
6092 },
6093 ))
6094 .on_action(cx.listener(Workspace::cancel))
6095 }
6096
6097 #[cfg(any(test, feature = "test-support"))]
6098 pub fn set_random_database_id(&mut self) {
6099 self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
6100 }
6101
6102 #[cfg(any(test, feature = "test-support"))]
6103 pub fn test_new(project: Entity<Project>, window: &mut Window, cx: &mut Context<Self>) -> Self {
6104 use node_runtime::NodeRuntime;
6105 use session::Session;
6106
6107 let client = project.read(cx).client();
6108 let user_store = project.read(cx).user_store();
6109 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
6110 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
6111 window.activate_window();
6112 let app_state = Arc::new(AppState {
6113 languages: project.read(cx).languages().clone(),
6114 workspace_store,
6115 client,
6116 user_store,
6117 fs: project.read(cx).fs().clone(),
6118 build_window_options: |_, _| Default::default(),
6119 node_runtime: NodeRuntime::unavailable(),
6120 session,
6121 });
6122 let workspace = Self::new(Default::default(), project, app_state, window, cx);
6123 workspace
6124 .active_pane
6125 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)));
6126 workspace
6127 }
6128
6129 pub fn register_action<A: Action>(
6130 &mut self,
6131 callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
6132 ) -> &mut Self {
6133 let callback = Arc::new(callback);
6134
6135 self.workspace_actions.push(Box::new(move |div, _, _, cx| {
6136 let callback = callback.clone();
6137 div.on_action(cx.listener(move |workspace, event, window, cx| {
6138 (callback)(workspace, event, window, cx)
6139 }))
6140 }));
6141 self
6142 }
6143 pub fn register_action_renderer(
6144 &mut self,
6145 callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
6146 ) -> &mut Self {
6147 self.workspace_actions.push(Box::new(callback));
6148 self
6149 }
6150
6151 fn add_workspace_actions_listeners(
6152 &self,
6153 mut div: Div,
6154 window: &mut Window,
6155 cx: &mut Context<Self>,
6156 ) -> Div {
6157 for action in self.workspace_actions.iter() {
6158 div = (action)(div, self, window, cx)
6159 }
6160 div
6161 }
6162
6163 pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
6164 self.modal_layer.read(cx).has_active_modal()
6165 }
6166
6167 pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
6168 self.modal_layer.read(cx).active_modal()
6169 }
6170
6171 pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
6172 where
6173 B: FnOnce(&mut Window, &mut Context<V>) -> V,
6174 {
6175 self.modal_layer.update(cx, |modal_layer, cx| {
6176 modal_layer.toggle_modal(window, cx, build)
6177 })
6178 }
6179
6180 pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
6181 self.modal_layer
6182 .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
6183 }
6184
6185 pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
6186 self.toast_layer
6187 .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
6188 }
6189
6190 pub fn toggle_centered_layout(
6191 &mut self,
6192 _: &ToggleCenteredLayout,
6193 _: &mut Window,
6194 cx: &mut Context<Self>,
6195 ) {
6196 self.centered_layout = !self.centered_layout;
6197 if let Some(database_id) = self.database_id() {
6198 cx.background_spawn(DB.set_centered_layout(database_id, self.centered_layout))
6199 .detach_and_log_err(cx);
6200 }
6201 cx.notify();
6202 }
6203
6204 fn adjust_padding(padding: Option<f32>) -> f32 {
6205 padding
6206 .unwrap_or(CenteredPaddingSettings::default().0)
6207 .clamp(
6208 CenteredPaddingSettings::MIN_PADDING,
6209 CenteredPaddingSettings::MAX_PADDING,
6210 )
6211 }
6212
6213 fn render_dock(
6214 &self,
6215 position: DockPosition,
6216 dock: &Entity<Dock>,
6217 window: &mut Window,
6218 cx: &mut App,
6219 ) -> Option<Div> {
6220 if self.zoomed_position == Some(position) {
6221 return None;
6222 }
6223
6224 let leader_border = dock.read(cx).active_panel().and_then(|panel| {
6225 let pane = panel.pane(cx)?;
6226 let follower_states = &self.follower_states;
6227 leader_border_for_pane(follower_states, &pane, window, cx)
6228 });
6229
6230 Some(
6231 div()
6232 .flex()
6233 .flex_none()
6234 .overflow_hidden()
6235 .child(dock.clone())
6236 .children(leader_border),
6237 )
6238 }
6239
6240 pub fn for_window(window: &mut Window, _: &mut App) -> Option<Entity<Workspace>> {
6241 window.root().flatten()
6242 }
6243
6244 pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
6245 self.zoomed.as_ref()
6246 }
6247
6248 pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
6249 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
6250 return;
6251 };
6252 let windows = cx.windows();
6253 let next_window =
6254 SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
6255 || {
6256 windows
6257 .iter()
6258 .cycle()
6259 .skip_while(|window| window.window_id() != current_window_id)
6260 .nth(1)
6261 },
6262 );
6263
6264 if let Some(window) = next_window {
6265 window
6266 .update(cx, |_, window, _| window.activate_window())
6267 .ok();
6268 }
6269 }
6270
6271 pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
6272 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
6273 return;
6274 };
6275 let windows = cx.windows();
6276 let prev_window =
6277 SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
6278 || {
6279 windows
6280 .iter()
6281 .rev()
6282 .cycle()
6283 .skip_while(|window| window.window_id() != current_window_id)
6284 .nth(1)
6285 },
6286 );
6287
6288 if let Some(window) = prev_window {
6289 window
6290 .update(cx, |_, window, _| window.activate_window())
6291 .ok();
6292 }
6293 }
6294
6295 pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
6296 if cx.stop_active_drag(window) {
6297 } else if let Some((notification_id, _)) = self.notifications.pop() {
6298 dismiss_app_notification(¬ification_id, cx);
6299 } else {
6300 cx.propagate();
6301 }
6302 }
6303
6304 fn adjust_dock_size_by_px(
6305 &mut self,
6306 panel_size: Pixels,
6307 dock_pos: DockPosition,
6308 px: Pixels,
6309 window: &mut Window,
6310 cx: &mut Context<Self>,
6311 ) {
6312 match dock_pos {
6313 DockPosition::Left => self.resize_left_dock(panel_size + px, window, cx),
6314 DockPosition::Right => self.resize_right_dock(panel_size + px, window, cx),
6315 DockPosition::Bottom => self.resize_bottom_dock(panel_size + px, window, cx),
6316 }
6317 }
6318
6319 fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
6320 let size = new_size.min(self.bounds.right() - RESIZE_HANDLE_SIZE);
6321
6322 self.left_dock.update(cx, |left_dock, cx| {
6323 if WorkspaceSettings::get_global(cx)
6324 .resize_all_panels_in_dock
6325 .contains(&DockPosition::Left)
6326 {
6327 left_dock.resize_all_panels(Some(size), window, cx);
6328 } else {
6329 left_dock.resize_active_panel(Some(size), window, cx);
6330 }
6331 });
6332 self.clamp_utility_pane_widths(window, cx);
6333 }
6334
6335 fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
6336 let mut size = new_size.max(self.bounds.left() - RESIZE_HANDLE_SIZE);
6337 self.left_dock.read_with(cx, |left_dock, cx| {
6338 let left_dock_size = left_dock
6339 .active_panel_size(window, cx)
6340 .unwrap_or(Pixels::ZERO);
6341 if left_dock_size + size > self.bounds.right() {
6342 size = self.bounds.right() - left_dock_size
6343 }
6344 });
6345 self.right_dock.update(cx, |right_dock, cx| {
6346 if WorkspaceSettings::get_global(cx)
6347 .resize_all_panels_in_dock
6348 .contains(&DockPosition::Right)
6349 {
6350 right_dock.resize_all_panels(Some(size), window, cx);
6351 } else {
6352 right_dock.resize_active_panel(Some(size), window, cx);
6353 }
6354 });
6355 self.clamp_utility_pane_widths(window, cx);
6356 }
6357
6358 fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
6359 let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
6360 self.bottom_dock.update(cx, |bottom_dock, cx| {
6361 if WorkspaceSettings::get_global(cx)
6362 .resize_all_panels_in_dock
6363 .contains(&DockPosition::Bottom)
6364 {
6365 bottom_dock.resize_all_panels(Some(size), window, cx);
6366 } else {
6367 bottom_dock.resize_active_panel(Some(size), window, cx);
6368 }
6369 });
6370 self.clamp_utility_pane_widths(window, cx);
6371 }
6372
6373 fn max_utility_pane_width(&self, window: &Window, cx: &App) -> Pixels {
6374 let left_dock_width = self
6375 .left_dock
6376 .read(cx)
6377 .active_panel_size(window, cx)
6378 .unwrap_or(px(0.0));
6379 let right_dock_width = self
6380 .right_dock
6381 .read(cx)
6382 .active_panel_size(window, cx)
6383 .unwrap_or(px(0.0));
6384 let center_pane_width = self.bounds.size.width - left_dock_width - right_dock_width;
6385 center_pane_width - px(10.0)
6386 }
6387
6388 fn clamp_utility_pane_widths(&mut self, window: &mut Window, cx: &mut App) {
6389 let max_width = self.max_utility_pane_width(window, cx);
6390
6391 // Clamp left slot utility pane if it exists
6392 if let Some(handle) = self.utility_pane(UtilityPaneSlot::Left) {
6393 let current_width = handle.width(cx);
6394 if current_width > max_width {
6395 handle.set_width(Some(max_width.max(UTILITY_PANE_MIN_WIDTH)), cx);
6396 }
6397 }
6398
6399 // Clamp right slot utility pane if it exists
6400 if let Some(handle) = self.utility_pane(UtilityPaneSlot::Right) {
6401 let current_width = handle.width(cx);
6402 if current_width > max_width {
6403 handle.set_width(Some(max_width.max(UTILITY_PANE_MIN_WIDTH)), cx);
6404 }
6405 }
6406 }
6407
6408 fn toggle_edit_predictions_all_files(
6409 &mut self,
6410 _: &ToggleEditPrediction,
6411 _window: &mut Window,
6412 cx: &mut Context<Self>,
6413 ) {
6414 let fs = self.project().read(cx).fs().clone();
6415 let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
6416 update_settings_file(fs, cx, move |file, _| {
6417 file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
6418 });
6419 }
6420}
6421
6422fn leader_border_for_pane(
6423 follower_states: &HashMap<CollaboratorId, FollowerState>,
6424 pane: &Entity<Pane>,
6425 _: &Window,
6426 cx: &App,
6427) -> Option<Div> {
6428 let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
6429 if state.pane() == pane {
6430 Some((*leader_id, state))
6431 } else {
6432 None
6433 }
6434 })?;
6435
6436 let mut leader_color = match leader_id {
6437 CollaboratorId::PeerId(leader_peer_id) => {
6438 let room = ActiveCall::try_global(cx)?.read(cx).room()?.read(cx);
6439 let leader = room.remote_participant_for_peer_id(leader_peer_id)?;
6440
6441 cx.theme()
6442 .players()
6443 .color_for_participant(leader.participant_index.0)
6444 .cursor
6445 }
6446 CollaboratorId::Agent => cx.theme().players().agent().cursor,
6447 };
6448 leader_color.fade_out(0.3);
6449 Some(
6450 div()
6451 .absolute()
6452 .size_full()
6453 .left_0()
6454 .top_0()
6455 .border_2()
6456 .border_color(leader_color),
6457 )
6458}
6459
6460fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
6461 ZED_WINDOW_POSITION
6462 .zip(*ZED_WINDOW_SIZE)
6463 .map(|(position, size)| Bounds {
6464 origin: position,
6465 size,
6466 })
6467}
6468
6469fn open_items(
6470 serialized_workspace: Option<SerializedWorkspace>,
6471 mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
6472 window: &mut Window,
6473 cx: &mut Context<Workspace>,
6474) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
6475 let restored_items = serialized_workspace.map(|serialized_workspace| {
6476 Workspace::load_workspace(
6477 serialized_workspace,
6478 project_paths_to_open
6479 .iter()
6480 .map(|(_, project_path)| project_path)
6481 .cloned()
6482 .collect(),
6483 window,
6484 cx,
6485 )
6486 });
6487
6488 cx.spawn_in(window, async move |workspace, cx| {
6489 let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
6490
6491 if let Some(restored_items) = restored_items {
6492 let restored_items = restored_items.await?;
6493
6494 let restored_project_paths = restored_items
6495 .iter()
6496 .filter_map(|item| {
6497 cx.update(|_, cx| item.as_ref()?.project_path(cx))
6498 .ok()
6499 .flatten()
6500 })
6501 .collect::<HashSet<_>>();
6502
6503 for restored_item in restored_items {
6504 opened_items.push(restored_item.map(Ok));
6505 }
6506
6507 project_paths_to_open
6508 .iter_mut()
6509 .for_each(|(_, project_path)| {
6510 if let Some(project_path_to_open) = project_path
6511 && restored_project_paths.contains(project_path_to_open)
6512 {
6513 *project_path = None;
6514 }
6515 });
6516 } else {
6517 for _ in 0..project_paths_to_open.len() {
6518 opened_items.push(None);
6519 }
6520 }
6521 assert!(opened_items.len() == project_paths_to_open.len());
6522
6523 let tasks =
6524 project_paths_to_open
6525 .into_iter()
6526 .enumerate()
6527 .map(|(ix, (abs_path, project_path))| {
6528 let workspace = workspace.clone();
6529 cx.spawn(async move |cx| {
6530 let file_project_path = project_path?;
6531 let abs_path_task = workspace.update(cx, |workspace, cx| {
6532 workspace.project().update(cx, |project, cx| {
6533 project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
6534 })
6535 });
6536
6537 // We only want to open file paths here. If one of the items
6538 // here is a directory, it was already opened further above
6539 // with a `find_or_create_worktree`.
6540 if let Ok(task) = abs_path_task
6541 && task.await.is_none_or(|p| p.is_file())
6542 {
6543 return Some((
6544 ix,
6545 workspace
6546 .update_in(cx, |workspace, window, cx| {
6547 workspace.open_path(
6548 file_project_path,
6549 None,
6550 true,
6551 window,
6552 cx,
6553 )
6554 })
6555 .log_err()?
6556 .await,
6557 ));
6558 }
6559 None
6560 })
6561 });
6562
6563 let tasks = tasks.collect::<Vec<_>>();
6564
6565 let tasks = futures::future::join_all(tasks);
6566 for (ix, path_open_result) in tasks.await.into_iter().flatten() {
6567 opened_items[ix] = Some(path_open_result);
6568 }
6569
6570 Ok(opened_items)
6571 })
6572}
6573
6574enum ActivateInDirectionTarget {
6575 Pane(Entity<Pane>),
6576 Dock(Entity<Dock>),
6577}
6578
6579fn notify_if_database_failed(workspace: WindowHandle<Workspace>, cx: &mut AsyncApp) {
6580 workspace
6581 .update(cx, |workspace, _, cx| {
6582 if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
6583 struct DatabaseFailedNotification;
6584
6585 workspace.show_notification(
6586 NotificationId::unique::<DatabaseFailedNotification>(),
6587 cx,
6588 |cx| {
6589 cx.new(|cx| {
6590 MessageNotification::new("Failed to load the database file.", cx)
6591 .primary_message("File an Issue")
6592 .primary_icon(IconName::Plus)
6593 .primary_on_click(|window, cx| {
6594 window.dispatch_action(Box::new(FileBugReport), cx)
6595 })
6596 })
6597 },
6598 );
6599 }
6600 })
6601 .log_err();
6602}
6603
6604fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
6605 if val == 0 {
6606 ThemeSettings::get_global(cx).ui_font_size(cx)
6607 } else {
6608 px(val as f32)
6609 }
6610}
6611
6612fn adjust_active_dock_size_by_px(
6613 px: Pixels,
6614 workspace: &mut Workspace,
6615 window: &mut Window,
6616 cx: &mut Context<Workspace>,
6617) {
6618 let Some(active_dock) = workspace
6619 .all_docks()
6620 .into_iter()
6621 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
6622 else {
6623 return;
6624 };
6625 let dock = active_dock.read(cx);
6626 let Some(panel_size) = dock.active_panel_size(window, cx) else {
6627 return;
6628 };
6629 let dock_pos = dock.position();
6630 workspace.adjust_dock_size_by_px(panel_size, dock_pos, px, window, cx);
6631}
6632
6633fn adjust_open_docks_size_by_px(
6634 px: Pixels,
6635 workspace: &mut Workspace,
6636 window: &mut Window,
6637 cx: &mut Context<Workspace>,
6638) {
6639 let docks = workspace
6640 .all_docks()
6641 .into_iter()
6642 .filter_map(|dock| {
6643 if dock.read(cx).is_open() {
6644 let dock = dock.read(cx);
6645 let panel_size = dock.active_panel_size(window, cx)?;
6646 let dock_pos = dock.position();
6647 Some((panel_size, dock_pos, px))
6648 } else {
6649 None
6650 }
6651 })
6652 .collect::<Vec<_>>();
6653
6654 docks
6655 .into_iter()
6656 .for_each(|(panel_size, dock_pos, offset)| {
6657 workspace.adjust_dock_size_by_px(panel_size, dock_pos, offset, window, cx);
6658 });
6659}
6660
6661impl Focusable for Workspace {
6662 fn focus_handle(&self, cx: &App) -> FocusHandle {
6663 self.active_pane.focus_handle(cx)
6664 }
6665}
6666
6667#[derive(Clone)]
6668struct DraggedDock(DockPosition);
6669
6670impl Render for DraggedDock {
6671 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
6672 gpui::Empty
6673 }
6674}
6675
6676impl Render for Workspace {
6677 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
6678 static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
6679 if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
6680 log::info!("Rendered first frame");
6681 }
6682 let mut context = KeyContext::new_with_defaults();
6683 context.add("Workspace");
6684 context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
6685 if let Some(status) = self
6686 .debugger_provider
6687 .as_ref()
6688 .and_then(|provider| provider.active_thread_state(cx))
6689 {
6690 match status {
6691 ThreadStatus::Running | ThreadStatus::Stepping => {
6692 context.add("debugger_running");
6693 }
6694 ThreadStatus::Stopped => context.add("debugger_stopped"),
6695 ThreadStatus::Exited | ThreadStatus::Ended => {}
6696 }
6697 }
6698
6699 if self.left_dock.read(cx).is_open() {
6700 if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
6701 context.set("left_dock", active_panel.panel_key());
6702 }
6703 }
6704
6705 if self.right_dock.read(cx).is_open() {
6706 if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
6707 context.set("right_dock", active_panel.panel_key());
6708 }
6709 }
6710
6711 if self.bottom_dock.read(cx).is_open() {
6712 if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
6713 context.set("bottom_dock", active_panel.panel_key());
6714 }
6715 }
6716
6717 let centered_layout = self.centered_layout
6718 && self.center.panes().len() == 1
6719 && self.active_item(cx).is_some();
6720 let render_padding = |size| {
6721 (size > 0.0).then(|| {
6722 div()
6723 .h_full()
6724 .w(relative(size))
6725 .bg(cx.theme().colors().editor_background)
6726 .border_color(cx.theme().colors().pane_group_border)
6727 })
6728 };
6729 let paddings = if centered_layout {
6730 let settings = WorkspaceSettings::get_global(cx).centered_layout;
6731 (
6732 render_padding(Self::adjust_padding(
6733 settings.left_padding.map(|padding| padding.0),
6734 )),
6735 render_padding(Self::adjust_padding(
6736 settings.right_padding.map(|padding| padding.0),
6737 )),
6738 )
6739 } else {
6740 (None, None)
6741 };
6742 let ui_font = theme::setup_ui_font(window, cx);
6743
6744 let theme = cx.theme().clone();
6745 let colors = theme.colors();
6746 let notification_entities = self
6747 .notifications
6748 .iter()
6749 .map(|(_, notification)| notification.entity_id())
6750 .collect::<Vec<_>>();
6751 let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
6752
6753 client_side_decorations(
6754 self.actions(div(), window, cx)
6755 .key_context(context)
6756 .relative()
6757 .size_full()
6758 .flex()
6759 .flex_col()
6760 .font(ui_font)
6761 .gap_0()
6762 .justify_start()
6763 .items_start()
6764 .text_color(colors.text)
6765 .overflow_hidden()
6766 .children(self.titlebar_item.clone())
6767 .on_modifiers_changed(move |_, _, cx| {
6768 for &id in ¬ification_entities {
6769 cx.notify(id);
6770 }
6771 })
6772 .child(
6773 div()
6774 .size_full()
6775 .relative()
6776 .flex_1()
6777 .flex()
6778 .flex_col()
6779 .child(
6780 div()
6781 .id("workspace")
6782 .bg(colors.background)
6783 .relative()
6784 .flex_1()
6785 .w_full()
6786 .flex()
6787 .flex_col()
6788 .overflow_hidden()
6789 .border_t_1()
6790 .border_b_1()
6791 .border_color(colors.border)
6792 .child({
6793 let this = cx.entity();
6794 canvas(
6795 move |bounds, window, cx| {
6796 this.update(cx, |this, cx| {
6797 let bounds_changed = this.bounds != bounds;
6798 this.bounds = bounds;
6799
6800 if bounds_changed {
6801 this.left_dock.update(cx, |dock, cx| {
6802 dock.clamp_panel_size(
6803 bounds.size.width,
6804 window,
6805 cx,
6806 )
6807 });
6808
6809 this.right_dock.update(cx, |dock, cx| {
6810 dock.clamp_panel_size(
6811 bounds.size.width,
6812 window,
6813 cx,
6814 )
6815 });
6816
6817 this.bottom_dock.update(cx, |dock, cx| {
6818 dock.clamp_panel_size(
6819 bounds.size.height,
6820 window,
6821 cx,
6822 )
6823 });
6824 }
6825 })
6826 },
6827 |_, _, _, _| {},
6828 )
6829 .absolute()
6830 .size_full()
6831 })
6832 .when(self.zoomed.is_none(), |this| {
6833 this.on_drag_move(cx.listener(
6834 move |workspace,
6835 e: &DragMoveEvent<DraggedDock>,
6836 window,
6837 cx| {
6838 if workspace.previous_dock_drag_coordinates
6839 != Some(e.event.position)
6840 {
6841 workspace.previous_dock_drag_coordinates =
6842 Some(e.event.position);
6843 match e.drag(cx).0 {
6844 DockPosition::Left => {
6845 workspace.resize_left_dock(
6846 e.event.position.x
6847 - workspace.bounds.left(),
6848 window,
6849 cx,
6850 );
6851 }
6852 DockPosition::Right => {
6853 workspace.resize_right_dock(
6854 workspace.bounds.right()
6855 - e.event.position.x,
6856 window,
6857 cx,
6858 );
6859 }
6860 DockPosition::Bottom => {
6861 workspace.resize_bottom_dock(
6862 workspace.bounds.bottom()
6863 - e.event.position.y,
6864 window,
6865 cx,
6866 );
6867 }
6868 };
6869 workspace.serialize_workspace(window, cx);
6870 }
6871 },
6872 ))
6873 .on_drag_move(cx.listener(
6874 move |workspace,
6875 e: &DragMoveEvent<DraggedUtilityPane>,
6876 window,
6877 cx| {
6878 let slot = e.drag(cx).0;
6879 match slot {
6880 UtilityPaneSlot::Left => {
6881 let left_dock_width = workspace.left_dock.read(cx)
6882 .active_panel_size(window, cx)
6883 .unwrap_or(gpui::px(0.0));
6884 let new_width = e.event.position.x
6885 - workspace.bounds.left()
6886 - left_dock_width;
6887 workspace.resize_utility_pane(slot, new_width, window, cx);
6888 }
6889 UtilityPaneSlot::Right => {
6890 let right_dock_width = workspace.right_dock.read(cx)
6891 .active_panel_size(window, cx)
6892 .unwrap_or(gpui::px(0.0));
6893 let new_width = workspace.bounds.right()
6894 - e.event.position.x
6895 - right_dock_width;
6896 workspace.resize_utility_pane(slot, new_width, window, cx);
6897 }
6898 }
6899 },
6900 ))
6901 })
6902 .child({
6903 match bottom_dock_layout {
6904 BottomDockLayout::Full => div()
6905 .flex()
6906 .flex_col()
6907 .h_full()
6908 .child(
6909 div()
6910 .flex()
6911 .flex_row()
6912 .flex_1()
6913 .overflow_hidden()
6914 .children(self.render_dock(
6915 DockPosition::Left,
6916 &self.left_dock,
6917 window,
6918 cx,
6919 ))
6920 .when(cx.has_flag::<AgentV2FeatureFlag>(), |this| {
6921 this.when_some(self.utility_pane(UtilityPaneSlot::Left), |this, pane| {
6922 this.when(pane.expanded(cx), |this| {
6923 this.child(
6924 UtilityPaneFrame::new(UtilityPaneSlot::Left, pane.box_clone(), cx)
6925 )
6926 })
6927 })
6928 })
6929 .child(
6930 div()
6931 .flex()
6932 .flex_col()
6933 .flex_1()
6934 .overflow_hidden()
6935 .child(
6936 h_flex()
6937 .flex_1()
6938 .when_some(
6939 paddings.0,
6940 |this, p| {
6941 this.child(
6942 p.border_r_1(),
6943 )
6944 },
6945 )
6946 .child(self.center.render(
6947 self.zoomed.as_ref(),
6948 &PaneRenderContext {
6949 follower_states:
6950 &self.follower_states,
6951 active_call: self.active_call(),
6952 active_pane: &self.active_pane,
6953 app_state: &self.app_state,
6954 project: &self.project,
6955 workspace: &self.weak_self,
6956 },
6957 window,
6958 cx,
6959 ))
6960 .when_some(
6961 paddings.1,
6962 |this, p| {
6963 this.child(
6964 p.border_l_1(),
6965 )
6966 },
6967 ),
6968 ),
6969 )
6970 .when(cx.has_flag::<AgentV2FeatureFlag>(), |this| {
6971 this.when_some(self.utility_pane(UtilityPaneSlot::Right), |this, pane| {
6972 this.when(pane.expanded(cx), |this| {
6973 this.child(
6974 UtilityPaneFrame::new(UtilityPaneSlot::Right, pane.box_clone(), cx)
6975 )
6976 })
6977 })
6978 })
6979 .children(self.render_dock(
6980 DockPosition::Right,
6981 &self.right_dock,
6982 window,
6983 cx,
6984 )),
6985 )
6986 .child(div().w_full().children(self.render_dock(
6987 DockPosition::Bottom,
6988 &self.bottom_dock,
6989 window,
6990 cx
6991 ))),
6992
6993 BottomDockLayout::LeftAligned => div()
6994 .flex()
6995 .flex_row()
6996 .h_full()
6997 .child(
6998 div()
6999 .flex()
7000 .flex_col()
7001 .flex_1()
7002 .h_full()
7003 .child(
7004 div()
7005 .flex()
7006 .flex_row()
7007 .flex_1()
7008 .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
7009 .when(cx.has_flag::<AgentV2FeatureFlag>(), |this| {
7010 this.when_some(self.utility_pane(UtilityPaneSlot::Left), |this, pane| {
7011 this.when(pane.expanded(cx), |this| {
7012 this.child(
7013 UtilityPaneFrame::new(UtilityPaneSlot::Left, pane.box_clone(), cx)
7014 )
7015 })
7016 })
7017 })
7018 .child(
7019 div()
7020 .flex()
7021 .flex_col()
7022 .flex_1()
7023 .overflow_hidden()
7024 .child(
7025 h_flex()
7026 .flex_1()
7027 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
7028 .child(self.center.render(
7029 self.zoomed.as_ref(),
7030 &PaneRenderContext {
7031 follower_states:
7032 &self.follower_states,
7033 active_call: self.active_call(),
7034 active_pane: &self.active_pane,
7035 app_state: &self.app_state,
7036 project: &self.project,
7037 workspace: &self.weak_self,
7038 },
7039 window,
7040 cx,
7041 ))
7042 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
7043 )
7044 )
7045 .when_some(self.utility_pane(UtilityPaneSlot::Right), |this, pane| {
7046 this.when(pane.expanded(cx), |this| {
7047 this.child(
7048 UtilityPaneFrame::new(UtilityPaneSlot::Right, pane.box_clone(), cx)
7049 )
7050 })
7051 })
7052 )
7053 .child(
7054 div()
7055 .w_full()
7056 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
7057 ),
7058 )
7059 .children(self.render_dock(
7060 DockPosition::Right,
7061 &self.right_dock,
7062 window,
7063 cx,
7064 )),
7065
7066 BottomDockLayout::RightAligned => div()
7067 .flex()
7068 .flex_row()
7069 .h_full()
7070 .children(self.render_dock(
7071 DockPosition::Left,
7072 &self.left_dock,
7073 window,
7074 cx,
7075 ))
7076 .when(cx.has_flag::<AgentV2FeatureFlag>(), |this| {
7077 this.when_some(self.utility_pane(UtilityPaneSlot::Left), |this, pane| {
7078 this.when(pane.expanded(cx), |this| {
7079 this.child(
7080 UtilityPaneFrame::new(UtilityPaneSlot::Left, pane.box_clone(), cx)
7081 )
7082 })
7083 })
7084 })
7085 .child(
7086 div()
7087 .flex()
7088 .flex_col()
7089 .flex_1()
7090 .h_full()
7091 .child(
7092 div()
7093 .flex()
7094 .flex_row()
7095 .flex_1()
7096 .child(
7097 div()
7098 .flex()
7099 .flex_col()
7100 .flex_1()
7101 .overflow_hidden()
7102 .child(
7103 h_flex()
7104 .flex_1()
7105 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
7106 .child(self.center.render(
7107 self.zoomed.as_ref(),
7108 &PaneRenderContext {
7109 follower_states:
7110 &self.follower_states,
7111 active_call: self.active_call(),
7112 active_pane: &self.active_pane,
7113 app_state: &self.app_state,
7114 project: &self.project,
7115 workspace: &self.weak_self,
7116 },
7117 window,
7118 cx,
7119 ))
7120 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
7121 )
7122 )
7123 .when(cx.has_flag::<AgentV2FeatureFlag>(), |this| {
7124 this.when_some(self.utility_pane(UtilityPaneSlot::Right), |this, pane| {
7125 this.when(pane.expanded(cx), |this| {
7126 this.child(
7127 UtilityPaneFrame::new(UtilityPaneSlot::Right, pane.box_clone(), cx)
7128 )
7129 })
7130 })
7131 })
7132 .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
7133 )
7134 .child(
7135 div()
7136 .w_full()
7137 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
7138 ),
7139 ),
7140
7141 BottomDockLayout::Contained => div()
7142 .flex()
7143 .flex_row()
7144 .h_full()
7145 .children(self.render_dock(
7146 DockPosition::Left,
7147 &self.left_dock,
7148 window,
7149 cx,
7150 ))
7151 .when_some(self.utility_pane(UtilityPaneSlot::Left), |this, pane| {
7152 this.when(pane.expanded(cx), |this| {
7153 this.child(
7154 UtilityPaneFrame::new(UtilityPaneSlot::Left, pane.box_clone(), cx)
7155 )
7156 })
7157 })
7158 .child(
7159 div()
7160 .flex()
7161 .flex_col()
7162 .flex_1()
7163 .overflow_hidden()
7164 .child(
7165 h_flex()
7166 .flex_1()
7167 .when_some(paddings.0, |this, p| {
7168 this.child(p.border_r_1())
7169 })
7170 .child(self.center.render(
7171 self.zoomed.as_ref(),
7172 &PaneRenderContext {
7173 follower_states:
7174 &self.follower_states,
7175 active_call: self.active_call(),
7176 active_pane: &self.active_pane,
7177 app_state: &self.app_state,
7178 project: &self.project,
7179 workspace: &self.weak_self,
7180 },
7181 window,
7182 cx,
7183 ))
7184 .when_some(paddings.1, |this, p| {
7185 this.child(p.border_l_1())
7186 }),
7187 )
7188 .children(self.render_dock(
7189 DockPosition::Bottom,
7190 &self.bottom_dock,
7191 window,
7192 cx,
7193 )),
7194 )
7195 .when(cx.has_flag::<AgentV2FeatureFlag>(), |this| {
7196 this.when_some(self.utility_pane(UtilityPaneSlot::Right), |this, pane| {
7197 this.when(pane.expanded(cx), |this| {
7198 this.child(
7199 UtilityPaneFrame::new(UtilityPaneSlot::Right, pane.box_clone(), cx)
7200 )
7201 })
7202 })
7203 })
7204 .children(self.render_dock(
7205 DockPosition::Right,
7206 &self.right_dock,
7207 window,
7208 cx,
7209 )),
7210 }
7211 })
7212 .children(self.zoomed.as_ref().and_then(|view| {
7213 let zoomed_view = view.upgrade()?;
7214 let div = div()
7215 .occlude()
7216 .absolute()
7217 .overflow_hidden()
7218 .border_color(colors.border)
7219 .bg(colors.background)
7220 .child(zoomed_view)
7221 .inset_0()
7222 .shadow_lg();
7223
7224 if !WorkspaceSettings::get_global(cx).zoomed_padding {
7225 return Some(div);
7226 }
7227
7228 Some(match self.zoomed_position {
7229 Some(DockPosition::Left) => div.right_2().border_r_1(),
7230 Some(DockPosition::Right) => div.left_2().border_l_1(),
7231 Some(DockPosition::Bottom) => div.top_2().border_t_1(),
7232 None => {
7233 div.top_2().bottom_2().left_2().right_2().border_1()
7234 }
7235 })
7236 }))
7237 .children(self.render_notifications(window, cx)),
7238 )
7239 .when(self.status_bar_visible(cx), |parent| {
7240 parent.child(self.status_bar.clone())
7241 })
7242 .child(self.modal_layer.clone())
7243 .child(self.toast_layer.clone()),
7244 ),
7245 window,
7246 cx,
7247 )
7248 }
7249}
7250
7251impl WorkspaceStore {
7252 pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
7253 Self {
7254 workspaces: Default::default(),
7255 _subscriptions: vec![
7256 client.add_request_handler(cx.weak_entity(), Self::handle_follow),
7257 client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
7258 ],
7259 client,
7260 }
7261 }
7262
7263 pub fn update_followers(
7264 &self,
7265 project_id: Option<u64>,
7266 update: proto::update_followers::Variant,
7267 cx: &App,
7268 ) -> Option<()> {
7269 let active_call = ActiveCall::try_global(cx)?;
7270 let room_id = active_call.read(cx).room()?.read(cx).id();
7271 self.client
7272 .send(proto::UpdateFollowers {
7273 room_id,
7274 project_id,
7275 variant: Some(update),
7276 })
7277 .log_err()
7278 }
7279
7280 pub async fn handle_follow(
7281 this: Entity<Self>,
7282 envelope: TypedEnvelope<proto::Follow>,
7283 mut cx: AsyncApp,
7284 ) -> Result<proto::FollowResponse> {
7285 this.update(&mut cx, |this, cx| {
7286 let follower = Follower {
7287 project_id: envelope.payload.project_id,
7288 peer_id: envelope.original_sender_id()?,
7289 };
7290
7291 let mut response = proto::FollowResponse::default();
7292 this.workspaces.retain(|workspace| {
7293 workspace
7294 .update(cx, |workspace, window, cx| {
7295 let handler_response =
7296 workspace.handle_follow(follower.project_id, window, cx);
7297 if let Some(active_view) = handler_response.active_view
7298 && workspace.project.read(cx).remote_id() == follower.project_id
7299 {
7300 response.active_view = Some(active_view)
7301 }
7302 })
7303 .is_ok()
7304 });
7305
7306 Ok(response)
7307 })?
7308 }
7309
7310 async fn handle_update_followers(
7311 this: Entity<Self>,
7312 envelope: TypedEnvelope<proto::UpdateFollowers>,
7313 mut cx: AsyncApp,
7314 ) -> Result<()> {
7315 let leader_id = envelope.original_sender_id()?;
7316 let update = envelope.payload;
7317
7318 this.update(&mut cx, |this, cx| {
7319 this.workspaces.retain(|workspace| {
7320 workspace
7321 .update(cx, |workspace, window, cx| {
7322 let project_id = workspace.project.read(cx).remote_id();
7323 if update.project_id != project_id && update.project_id.is_some() {
7324 return;
7325 }
7326 workspace.handle_update_followers(leader_id, update.clone(), window, cx);
7327 })
7328 .is_ok()
7329 });
7330 Ok(())
7331 })?
7332 }
7333
7334 pub fn workspaces(&self) -> &HashSet<WindowHandle<Workspace>> {
7335 &self.workspaces
7336 }
7337}
7338
7339impl ViewId {
7340 pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
7341 Ok(Self {
7342 creator: message
7343 .creator
7344 .map(CollaboratorId::PeerId)
7345 .context("creator is missing")?,
7346 id: message.id,
7347 })
7348 }
7349
7350 pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
7351 if let CollaboratorId::PeerId(peer_id) = self.creator {
7352 Some(proto::ViewId {
7353 creator: Some(peer_id),
7354 id: self.id,
7355 })
7356 } else {
7357 None
7358 }
7359 }
7360}
7361
7362impl FollowerState {
7363 fn pane(&self) -> &Entity<Pane> {
7364 self.dock_pane.as_ref().unwrap_or(&self.center_pane)
7365 }
7366}
7367
7368pub trait WorkspaceHandle {
7369 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
7370}
7371
7372impl WorkspaceHandle for Entity<Workspace> {
7373 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
7374 self.read(cx)
7375 .worktrees(cx)
7376 .flat_map(|worktree| {
7377 let worktree_id = worktree.read(cx).id();
7378 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
7379 worktree_id,
7380 path: f.path.clone(),
7381 })
7382 })
7383 .collect::<Vec<_>>()
7384 }
7385}
7386
7387pub async fn last_opened_workspace_location() -> Option<(SerializedWorkspaceLocation, PathList)> {
7388 DB.last_workspace().await.log_err().flatten()
7389}
7390
7391pub fn last_session_workspace_locations(
7392 last_session_id: &str,
7393 last_session_window_stack: Option<Vec<WindowId>>,
7394) -> Option<Vec<(SerializedWorkspaceLocation, PathList)>> {
7395 DB.last_session_workspace_locations(last_session_id, last_session_window_stack)
7396 .log_err()
7397}
7398
7399actions!(
7400 collab,
7401 [
7402 /// Opens the channel notes for the current call.
7403 ///
7404 /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
7405 /// channel in the collab panel.
7406 ///
7407 /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
7408 /// can be copied via "Copy link to section" in the context menu of the channel notes
7409 /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
7410 OpenChannelNotes,
7411 /// Mutes your microphone.
7412 Mute,
7413 /// Deafens yourself (mute both microphone and speakers).
7414 Deafen,
7415 /// Leaves the current call.
7416 LeaveCall,
7417 /// Shares the current project with collaborators.
7418 ShareProject,
7419 /// Shares your screen with collaborators.
7420 ScreenShare,
7421 /// Copies the current room name and session id for debugging purposes.
7422 CopyRoomId,
7423 ]
7424);
7425actions!(
7426 zed,
7427 [
7428 /// Opens the Zed log file.
7429 OpenLog,
7430 /// Reveals the Zed log file in the system file manager.
7431 RevealLogInFileManager
7432 ]
7433);
7434
7435async fn join_channel_internal(
7436 channel_id: ChannelId,
7437 app_state: &Arc<AppState>,
7438 requesting_window: Option<WindowHandle<Workspace>>,
7439 active_call: &Entity<ActiveCall>,
7440 cx: &mut AsyncApp,
7441) -> Result<bool> {
7442 let (should_prompt, open_room) = active_call.update(cx, |active_call, cx| {
7443 let Some(room) = active_call.room().map(|room| room.read(cx)) else {
7444 return (false, None);
7445 };
7446
7447 let already_in_channel = room.channel_id() == Some(channel_id);
7448 let should_prompt = room.is_sharing_project()
7449 && !room.remote_participants().is_empty()
7450 && !already_in_channel;
7451 let open_room = if already_in_channel {
7452 active_call.room().cloned()
7453 } else {
7454 None
7455 };
7456 (should_prompt, open_room)
7457 })?;
7458
7459 if let Some(room) = open_room {
7460 let task = room.update(cx, |room, cx| {
7461 if let Some((project, host)) = room.most_active_project(cx) {
7462 return Some(join_in_room_project(project, host, app_state.clone(), cx));
7463 }
7464
7465 None
7466 })?;
7467 if let Some(task) = task {
7468 task.await?;
7469 }
7470 return anyhow::Ok(true);
7471 }
7472
7473 if should_prompt {
7474 if let Some(workspace) = requesting_window {
7475 let answer = workspace
7476 .update(cx, |_, window, cx| {
7477 window.prompt(
7478 PromptLevel::Warning,
7479 "Do you want to switch channels?",
7480 Some("Leaving this call will unshare your current project."),
7481 &["Yes, Join Channel", "Cancel"],
7482 cx,
7483 )
7484 })?
7485 .await;
7486
7487 if answer == Ok(1) {
7488 return Ok(false);
7489 }
7490 } else {
7491 return Ok(false); // unreachable!() hopefully
7492 }
7493 }
7494
7495 let client = cx.update(|cx| active_call.read(cx).client())?;
7496
7497 let mut client_status = client.status();
7498
7499 // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
7500 'outer: loop {
7501 let Some(status) = client_status.recv().await else {
7502 anyhow::bail!("error connecting");
7503 };
7504
7505 match status {
7506 Status::Connecting
7507 | Status::Authenticating
7508 | Status::Authenticated
7509 | Status::Reconnecting
7510 | Status::Reauthenticating
7511 | Status::Reauthenticated => continue,
7512 Status::Connected { .. } => break 'outer,
7513 Status::SignedOut | Status::AuthenticationError => {
7514 return Err(ErrorCode::SignedOut.into());
7515 }
7516 Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
7517 Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
7518 return Err(ErrorCode::Disconnected.into());
7519 }
7520 }
7521 }
7522
7523 let room = active_call
7524 .update(cx, |active_call, cx| {
7525 active_call.join_channel(channel_id, cx)
7526 })?
7527 .await?;
7528
7529 let Some(room) = room else {
7530 return anyhow::Ok(true);
7531 };
7532
7533 room.update(cx, |room, _| room.room_update_completed())?
7534 .await;
7535
7536 let task = room.update(cx, |room, cx| {
7537 if let Some((project, host)) = room.most_active_project(cx) {
7538 return Some(join_in_room_project(project, host, app_state.clone(), cx));
7539 }
7540
7541 // If you are the first to join a channel, see if you should share your project.
7542 if room.remote_participants().is_empty()
7543 && !room.local_participant_is_guest()
7544 && let Some(workspace) = requesting_window
7545 {
7546 let project = workspace.update(cx, |workspace, _, cx| {
7547 let project = workspace.project.read(cx);
7548
7549 if !CallSettings::get_global(cx).share_on_join {
7550 return None;
7551 }
7552
7553 if (project.is_local() || project.is_via_remote_server())
7554 && project.visible_worktrees(cx).any(|tree| {
7555 tree.read(cx)
7556 .root_entry()
7557 .is_some_and(|entry| entry.is_dir())
7558 })
7559 {
7560 Some(workspace.project.clone())
7561 } else {
7562 None
7563 }
7564 });
7565 if let Ok(Some(project)) = project {
7566 return Some(cx.spawn(async move |room, cx| {
7567 room.update(cx, |room, cx| room.share_project(project, cx))?
7568 .await?;
7569 Ok(())
7570 }));
7571 }
7572 }
7573
7574 None
7575 })?;
7576 if let Some(task) = task {
7577 task.await?;
7578 return anyhow::Ok(true);
7579 }
7580 anyhow::Ok(false)
7581}
7582
7583pub fn join_channel(
7584 channel_id: ChannelId,
7585 app_state: Arc<AppState>,
7586 requesting_window: Option<WindowHandle<Workspace>>,
7587 cx: &mut App,
7588) -> Task<Result<()>> {
7589 let active_call = ActiveCall::global(cx);
7590 cx.spawn(async move |cx| {
7591 let result =
7592 join_channel_internal(channel_id, &app_state, requesting_window, &active_call, cx)
7593 .await;
7594
7595 // join channel succeeded, and opened a window
7596 if matches!(result, Ok(true)) {
7597 return anyhow::Ok(());
7598 }
7599
7600 // find an existing workspace to focus and show call controls
7601 let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
7602 if active_window.is_none() {
7603 // no open workspaces, make one to show the error in (blergh)
7604 let (window_handle, _) = cx
7605 .update(|cx| {
7606 Workspace::new_local(vec![], app_state.clone(), requesting_window, None, cx)
7607 })?
7608 .await?;
7609
7610 if result.is_ok() {
7611 cx.update(|cx| {
7612 cx.dispatch_action(&OpenChannelNotes);
7613 })
7614 .log_err();
7615 }
7616
7617 active_window = Some(window_handle);
7618 }
7619
7620 if let Err(err) = result {
7621 log::error!("failed to join channel: {}", err);
7622 if let Some(active_window) = active_window {
7623 active_window
7624 .update(cx, |_, window, cx| {
7625 let detail: SharedString = match err.error_code() {
7626 ErrorCode::SignedOut => "Please sign in to continue.".into(),
7627 ErrorCode::UpgradeRequired => concat!(
7628 "Your are running an unsupported version of Zed. ",
7629 "Please update to continue."
7630 )
7631 .into(),
7632 ErrorCode::NoSuchChannel => concat!(
7633 "No matching channel was found. ",
7634 "Please check the link and try again."
7635 )
7636 .into(),
7637 ErrorCode::Forbidden => concat!(
7638 "This channel is private, and you do not have access. ",
7639 "Please ask someone to add you and try again."
7640 )
7641 .into(),
7642 ErrorCode::Disconnected => {
7643 "Please check your internet connection and try again.".into()
7644 }
7645 _ => format!("{}\n\nPlease try again.", err).into(),
7646 };
7647 window.prompt(
7648 PromptLevel::Critical,
7649 "Failed to join channel",
7650 Some(&detail),
7651 &["Ok"],
7652 cx,
7653 )
7654 })?
7655 .await
7656 .ok();
7657 }
7658 }
7659
7660 // return ok, we showed the error to the user.
7661 anyhow::Ok(())
7662 })
7663}
7664
7665pub async fn get_any_active_workspace(
7666 app_state: Arc<AppState>,
7667 mut cx: AsyncApp,
7668) -> anyhow::Result<WindowHandle<Workspace>> {
7669 // find an existing workspace to focus and show call controls
7670 let active_window = activate_any_workspace_window(&mut cx);
7671 if active_window.is_none() {
7672 cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, cx))?
7673 .await?;
7674 }
7675 activate_any_workspace_window(&mut cx).context("could not open zed")
7676}
7677
7678fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<Workspace>> {
7679 cx.update(|cx| {
7680 if let Some(workspace_window) = cx
7681 .active_window()
7682 .and_then(|window| window.downcast::<Workspace>())
7683 {
7684 return Some(workspace_window);
7685 }
7686
7687 for window in cx.windows() {
7688 if let Some(workspace_window) = window.downcast::<Workspace>() {
7689 workspace_window
7690 .update(cx, |_, window, _| window.activate_window())
7691 .ok();
7692 return Some(workspace_window);
7693 }
7694 }
7695 None
7696 })
7697 .ok()
7698 .flatten()
7699}
7700
7701pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<Workspace>> {
7702 cx.windows()
7703 .into_iter()
7704 .filter_map(|window| window.downcast::<Workspace>())
7705 .filter(|workspace| {
7706 workspace
7707 .read(cx)
7708 .is_ok_and(|workspace| workspace.project.read(cx).is_local())
7709 })
7710 .collect()
7711}
7712
7713#[derive(Default)]
7714pub struct OpenOptions {
7715 pub visible: Option<OpenVisible>,
7716 pub focus: Option<bool>,
7717 pub open_new_workspace: Option<bool>,
7718 pub prefer_focused_window: bool,
7719 pub replace_window: Option<WindowHandle<Workspace>>,
7720 pub env: Option<HashMap<String, String>>,
7721}
7722
7723#[allow(clippy::type_complexity)]
7724pub fn open_paths(
7725 abs_paths: &[PathBuf],
7726 app_state: Arc<AppState>,
7727 open_options: OpenOptions,
7728 cx: &mut App,
7729) -> Task<
7730 anyhow::Result<(
7731 WindowHandle<Workspace>,
7732 Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
7733 )>,
7734> {
7735 let abs_paths = abs_paths.to_vec();
7736 let mut existing = None;
7737 let mut best_match = None;
7738 let mut open_visible = OpenVisible::All;
7739 #[cfg(target_os = "windows")]
7740 let wsl_path = abs_paths
7741 .iter()
7742 .find_map(|p| util::paths::WslPath::from_path(p));
7743
7744 cx.spawn(async move |cx| {
7745 if open_options.open_new_workspace != Some(true) {
7746 let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
7747 let all_metadatas = futures::future::join_all(all_paths)
7748 .await
7749 .into_iter()
7750 .filter_map(|result| result.ok().flatten())
7751 .collect::<Vec<_>>();
7752
7753 cx.update(|cx| {
7754 for window in local_workspace_windows(cx) {
7755 if let Ok(workspace) = window.read(cx) {
7756 let m = workspace.project.read(cx).visibility_for_paths(
7757 &abs_paths,
7758 &all_metadatas,
7759 open_options.open_new_workspace == None,
7760 cx,
7761 );
7762 if m > best_match {
7763 existing = Some(window);
7764 best_match = m;
7765 } else if best_match.is_none()
7766 && open_options.open_new_workspace == Some(false)
7767 {
7768 existing = Some(window)
7769 }
7770 }
7771 }
7772 })?;
7773
7774 if open_options.open_new_workspace.is_none()
7775 && (existing.is_none() || open_options.prefer_focused_window)
7776 && all_metadatas.iter().all(|file| !file.is_dir)
7777 {
7778 cx.update(|cx| {
7779 if let Some(window) = cx
7780 .active_window()
7781 .and_then(|window| window.downcast::<Workspace>())
7782 && let Ok(workspace) = window.read(cx)
7783 {
7784 let project = workspace.project().read(cx);
7785 if project.is_local() && !project.is_via_collab() {
7786 existing = Some(window);
7787 open_visible = OpenVisible::None;
7788 return;
7789 }
7790 }
7791 for window in local_workspace_windows(cx) {
7792 if let Ok(workspace) = window.read(cx) {
7793 let project = workspace.project().read(cx);
7794 if project.is_via_collab() {
7795 continue;
7796 }
7797 existing = Some(window);
7798 open_visible = OpenVisible::None;
7799 break;
7800 }
7801 }
7802 })?;
7803 }
7804 }
7805
7806 let result = if let Some(existing) = existing {
7807 let open_task = existing
7808 .update(cx, |workspace, window, cx| {
7809 window.activate_window();
7810 workspace.open_paths(
7811 abs_paths,
7812 OpenOptions {
7813 visible: Some(open_visible),
7814 ..Default::default()
7815 },
7816 None,
7817 window,
7818 cx,
7819 )
7820 })?
7821 .await;
7822
7823 _ = existing.update(cx, |workspace, _, cx| {
7824 for item in open_task.iter().flatten() {
7825 if let Err(e) = item {
7826 workspace.show_error(&e, cx);
7827 }
7828 }
7829 });
7830
7831 Ok((existing, open_task))
7832 } else {
7833 cx.update(move |cx| {
7834 Workspace::new_local(
7835 abs_paths,
7836 app_state.clone(),
7837 open_options.replace_window,
7838 open_options.env,
7839 cx,
7840 )
7841 })?
7842 .await
7843 };
7844
7845 #[cfg(target_os = "windows")]
7846 if let Some(util::paths::WslPath{distro, path}) = wsl_path
7847 && let Ok((workspace, _)) = &result
7848 {
7849 workspace
7850 .update(cx, move |workspace, _window, cx| {
7851 struct OpenInWsl;
7852 workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
7853 let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
7854 let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
7855 cx.new(move |cx| {
7856 MessageNotification::new(msg, cx)
7857 .primary_message("Open in WSL")
7858 .primary_icon(IconName::FolderOpen)
7859 .primary_on_click(move |window, cx| {
7860 window.dispatch_action(Box::new(remote::OpenWslPath {
7861 distro: remote::WslConnectionOptions {
7862 distro_name: distro.clone(),
7863 user: None,
7864 },
7865 paths: vec![path.clone().into()],
7866 }), cx)
7867 })
7868 })
7869 });
7870 })
7871 .unwrap();
7872 };
7873 result
7874 })
7875}
7876
7877pub fn open_new(
7878 open_options: OpenOptions,
7879 app_state: Arc<AppState>,
7880 cx: &mut App,
7881 init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
7882) -> Task<anyhow::Result<()>> {
7883 let task = Workspace::new_local(Vec::new(), app_state, None, open_options.env, cx);
7884 cx.spawn(async move |cx| {
7885 let (workspace, opened_paths) = task.await?;
7886 workspace.update(cx, |workspace, window, cx| {
7887 if opened_paths.is_empty() {
7888 init(workspace, window, cx)
7889 }
7890 })?;
7891 Ok(())
7892 })
7893}
7894
7895pub fn create_and_open_local_file(
7896 path: &'static Path,
7897 window: &mut Window,
7898 cx: &mut Context<Workspace>,
7899 default_content: impl 'static + Send + FnOnce() -> Rope,
7900) -> Task<Result<Box<dyn ItemHandle>>> {
7901 cx.spawn_in(window, async move |workspace, cx| {
7902 let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
7903 if !fs.is_file(path).await {
7904 fs.create_file(path, Default::default()).await?;
7905 fs.save(path, &default_content(), Default::default())
7906 .await?;
7907 }
7908
7909 let mut items = workspace
7910 .update_in(cx, |workspace, window, cx| {
7911 workspace.with_local_workspace(window, cx, |workspace, window, cx| {
7912 workspace.open_paths(
7913 vec![path.to_path_buf()],
7914 OpenOptions {
7915 visible: Some(OpenVisible::None),
7916 ..Default::default()
7917 },
7918 None,
7919 window,
7920 cx,
7921 )
7922 })
7923 })?
7924 .await?
7925 .await;
7926
7927 let item = items.pop().flatten();
7928 item.with_context(|| format!("path {path:?} is not a file"))?
7929 })
7930}
7931
7932pub fn open_remote_project_with_new_connection(
7933 window: WindowHandle<Workspace>,
7934 remote_connection: Arc<dyn RemoteConnection>,
7935 cancel_rx: oneshot::Receiver<()>,
7936 delegate: Arc<dyn RemoteClientDelegate>,
7937 app_state: Arc<AppState>,
7938 paths: Vec<PathBuf>,
7939 cx: &mut App,
7940) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
7941 cx.spawn(async move |cx| {
7942 let (workspace_id, serialized_workspace) =
7943 deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
7944 .await?;
7945
7946 let session = match cx
7947 .update(|cx| {
7948 remote::RemoteClient::new(
7949 ConnectionIdentifier::Workspace(workspace_id.0),
7950 remote_connection,
7951 cancel_rx,
7952 delegate,
7953 cx,
7954 )
7955 })?
7956 .await?
7957 {
7958 Some(result) => result,
7959 None => return Ok(Vec::new()),
7960 };
7961
7962 let project = cx.update(|cx| {
7963 project::Project::remote(
7964 session,
7965 app_state.client.clone(),
7966 app_state.node_runtime.clone(),
7967 app_state.user_store.clone(),
7968 app_state.languages.clone(),
7969 app_state.fs.clone(),
7970 cx,
7971 )
7972 })?;
7973
7974 open_remote_project_inner(
7975 project,
7976 paths,
7977 workspace_id,
7978 serialized_workspace,
7979 app_state,
7980 window,
7981 cx,
7982 )
7983 .await
7984 })
7985}
7986
7987pub fn open_remote_project_with_existing_connection(
7988 connection_options: RemoteConnectionOptions,
7989 project: Entity<Project>,
7990 paths: Vec<PathBuf>,
7991 app_state: Arc<AppState>,
7992 window: WindowHandle<Workspace>,
7993 cx: &mut AsyncApp,
7994) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
7995 cx.spawn(async move |cx| {
7996 let (workspace_id, serialized_workspace) =
7997 deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
7998
7999 open_remote_project_inner(
8000 project,
8001 paths,
8002 workspace_id,
8003 serialized_workspace,
8004 app_state,
8005 window,
8006 cx,
8007 )
8008 .await
8009 })
8010}
8011
8012async fn open_remote_project_inner(
8013 project: Entity<Project>,
8014 paths: Vec<PathBuf>,
8015 workspace_id: WorkspaceId,
8016 serialized_workspace: Option<SerializedWorkspace>,
8017 app_state: Arc<AppState>,
8018 window: WindowHandle<Workspace>,
8019 cx: &mut AsyncApp,
8020) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
8021 let toolchains = DB.toolchains(workspace_id).await?;
8022 for (toolchain, worktree_id, path) in toolchains {
8023 project
8024 .update(cx, |this, cx| {
8025 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
8026 })?
8027 .await;
8028 }
8029 let mut project_paths_to_open = vec![];
8030 let mut project_path_errors = vec![];
8031
8032 for path in paths {
8033 let result = cx
8034 .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))?
8035 .await;
8036 match result {
8037 Ok((_, project_path)) => {
8038 project_paths_to_open.push((path.clone(), Some(project_path)));
8039 }
8040 Err(error) => {
8041 project_path_errors.push(error);
8042 }
8043 };
8044 }
8045
8046 if project_paths_to_open.is_empty() {
8047 return Err(project_path_errors.pop().context("no paths given")?);
8048 }
8049
8050 if let Some(detach_session_task) = window
8051 .update(cx, |_workspace, window, cx| {
8052 cx.spawn_in(window, async move |this, cx| {
8053 this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))
8054 })
8055 })
8056 .ok()
8057 {
8058 detach_session_task.await.ok();
8059 }
8060
8061 cx.update_window(window.into(), |_, window, cx| {
8062 window.replace_root(cx, |window, cx| {
8063 telemetry::event!("SSH Project Opened");
8064
8065 let mut workspace =
8066 Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
8067 workspace.update_history(cx);
8068
8069 if let Some(ref serialized) = serialized_workspace {
8070 workspace.centered_layout = serialized.centered_layout;
8071 }
8072
8073 workspace
8074 });
8075 })?;
8076
8077 let items = window
8078 .update(cx, |_, window, cx| {
8079 window.activate_window();
8080 open_items(serialized_workspace, project_paths_to_open, window, cx)
8081 })?
8082 .await?;
8083
8084 window.update(cx, |workspace, _, cx| {
8085 for error in project_path_errors {
8086 if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
8087 if let Some(path) = error.error_tag("path") {
8088 workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
8089 }
8090 } else {
8091 workspace.show_error(&error, cx)
8092 }
8093 }
8094 })?;
8095
8096 Ok(items.into_iter().map(|item| item?.ok()).collect())
8097}
8098
8099fn deserialize_remote_project(
8100 connection_options: RemoteConnectionOptions,
8101 paths: Vec<PathBuf>,
8102 cx: &AsyncApp,
8103) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
8104 cx.background_spawn(async move {
8105 let remote_connection_id = persistence::DB
8106 .get_or_create_remote_connection(connection_options)
8107 .await?;
8108
8109 let serialized_workspace =
8110 persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
8111
8112 let workspace_id = if let Some(workspace_id) =
8113 serialized_workspace.as_ref().map(|workspace| workspace.id)
8114 {
8115 workspace_id
8116 } else {
8117 persistence::DB.next_id().await?
8118 };
8119
8120 Ok((workspace_id, serialized_workspace))
8121 })
8122}
8123
8124pub fn join_in_room_project(
8125 project_id: u64,
8126 follow_user_id: u64,
8127 app_state: Arc<AppState>,
8128 cx: &mut App,
8129) -> Task<Result<()>> {
8130 let windows = cx.windows();
8131 cx.spawn(async move |cx| {
8132 let existing_workspace = windows.into_iter().find_map(|window_handle| {
8133 window_handle
8134 .downcast::<Workspace>()
8135 .and_then(|window_handle| {
8136 window_handle
8137 .update(cx, |workspace, _window, cx| {
8138 if workspace.project().read(cx).remote_id() == Some(project_id) {
8139 Some(window_handle)
8140 } else {
8141 None
8142 }
8143 })
8144 .unwrap_or(None)
8145 })
8146 });
8147
8148 let workspace = if let Some(existing_workspace) = existing_workspace {
8149 existing_workspace
8150 } else {
8151 let active_call = cx.update(|cx| ActiveCall::global(cx))?;
8152 let room = active_call
8153 .read_with(cx, |call, _| call.room().cloned())?
8154 .context("not in a call")?;
8155 let project = room
8156 .update(cx, |room, cx| {
8157 room.join_project(
8158 project_id,
8159 app_state.languages.clone(),
8160 app_state.fs.clone(),
8161 cx,
8162 )
8163 })?
8164 .await?;
8165
8166 let window_bounds_override = window_bounds_env_override();
8167 cx.update(|cx| {
8168 let mut options = (app_state.build_window_options)(None, cx);
8169 options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
8170 cx.open_window(options, |window, cx| {
8171 cx.new(|cx| {
8172 Workspace::new(Default::default(), project, app_state.clone(), window, cx)
8173 })
8174 })
8175 })??
8176 };
8177
8178 workspace.update(cx, |workspace, window, cx| {
8179 cx.activate(true);
8180 window.activate_window();
8181
8182 if let Some(room) = ActiveCall::global(cx).read(cx).room().cloned() {
8183 let follow_peer_id = room
8184 .read(cx)
8185 .remote_participants()
8186 .iter()
8187 .find(|(_, participant)| participant.user.id == follow_user_id)
8188 .map(|(_, p)| p.peer_id)
8189 .or_else(|| {
8190 // If we couldn't follow the given user, follow the host instead.
8191 let collaborator = workspace
8192 .project()
8193 .read(cx)
8194 .collaborators()
8195 .values()
8196 .find(|collaborator| collaborator.is_host)?;
8197 Some(collaborator.peer_id)
8198 });
8199
8200 if let Some(follow_peer_id) = follow_peer_id {
8201 workspace.follow(follow_peer_id, window, cx);
8202 }
8203 }
8204 })?;
8205
8206 anyhow::Ok(())
8207 })
8208}
8209
8210pub fn reload(cx: &mut App) {
8211 let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
8212 let mut workspace_windows = cx
8213 .windows()
8214 .into_iter()
8215 .filter_map(|window| window.downcast::<Workspace>())
8216 .collect::<Vec<_>>();
8217
8218 // If multiple windows have unsaved changes, and need a save prompt,
8219 // prompt in the active window before switching to a different window.
8220 workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
8221
8222 let mut prompt = None;
8223 if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
8224 prompt = window
8225 .update(cx, |_, window, cx| {
8226 window.prompt(
8227 PromptLevel::Info,
8228 "Are you sure you want to restart?",
8229 None,
8230 &["Restart", "Cancel"],
8231 cx,
8232 )
8233 })
8234 .ok();
8235 }
8236
8237 cx.spawn(async move |cx| {
8238 if let Some(prompt) = prompt {
8239 let answer = prompt.await?;
8240 if answer != 0 {
8241 return Ok(());
8242 }
8243 }
8244
8245 // If the user cancels any save prompt, then keep the app open.
8246 for window in workspace_windows {
8247 if let Ok(should_close) = window.update(cx, |workspace, window, cx| {
8248 workspace.prepare_to_close(CloseIntent::Quit, window, cx)
8249 }) && !should_close.await?
8250 {
8251 return Ok(());
8252 }
8253 }
8254 cx.update(|cx| cx.restart())
8255 })
8256 .detach_and_log_err(cx);
8257}
8258
8259fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
8260 let mut parts = value.split(',');
8261 let x: usize = parts.next()?.parse().ok()?;
8262 let y: usize = parts.next()?.parse().ok()?;
8263 Some(point(px(x as f32), px(y as f32)))
8264}
8265
8266fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
8267 let mut parts = value.split(',');
8268 let width: usize = parts.next()?.parse().ok()?;
8269 let height: usize = parts.next()?.parse().ok()?;
8270 Some(size(px(width as f32), px(height as f32)))
8271}
8272
8273/// Add client-side decorations (rounded corners, shadows, resize handling) when appropriate.
8274pub fn client_side_decorations(
8275 element: impl IntoElement,
8276 window: &mut Window,
8277 cx: &mut App,
8278) -> Stateful<Div> {
8279 const BORDER_SIZE: Pixels = px(1.0);
8280 let decorations = window.window_decorations();
8281
8282 match decorations {
8283 Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
8284 Decorations::Server => window.set_client_inset(px(0.0)),
8285 }
8286
8287 struct GlobalResizeEdge(ResizeEdge);
8288 impl Global for GlobalResizeEdge {}
8289
8290 div()
8291 .id("window-backdrop")
8292 .bg(transparent_black())
8293 .map(|div| match decorations {
8294 Decorations::Server => div,
8295 Decorations::Client { tiling, .. } => div
8296 .when(!(tiling.top || tiling.right), |div| {
8297 div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING)
8298 })
8299 .when(!(tiling.top || tiling.left), |div| {
8300 div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
8301 })
8302 .when(!(tiling.bottom || tiling.right), |div| {
8303 div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING)
8304 })
8305 .when(!(tiling.bottom || tiling.left), |div| {
8306 div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
8307 })
8308 .when(!tiling.top, |div| {
8309 div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
8310 })
8311 .when(!tiling.bottom, |div| {
8312 div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
8313 })
8314 .when(!tiling.left, |div| {
8315 div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
8316 })
8317 .when(!tiling.right, |div| {
8318 div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
8319 })
8320 .on_mouse_move(move |e, window, cx| {
8321 let size = window.window_bounds().get_bounds().size;
8322 let pos = e.position;
8323
8324 let new_edge =
8325 resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
8326
8327 let edge = cx.try_global::<GlobalResizeEdge>();
8328 if new_edge != edge.map(|edge| edge.0) {
8329 window
8330 .window_handle()
8331 .update(cx, |workspace, _, cx| {
8332 cx.notify(workspace.entity_id());
8333 })
8334 .ok();
8335 }
8336 })
8337 .on_mouse_down(MouseButton::Left, move |e, window, _| {
8338 let size = window.window_bounds().get_bounds().size;
8339 let pos = e.position;
8340
8341 let edge = match resize_edge(
8342 pos,
8343 theme::CLIENT_SIDE_DECORATION_SHADOW,
8344 size,
8345 tiling,
8346 ) {
8347 Some(value) => value,
8348 None => return,
8349 };
8350
8351 window.start_window_resize(edge);
8352 }),
8353 })
8354 .size_full()
8355 .child(
8356 div()
8357 .cursor(CursorStyle::Arrow)
8358 .map(|div| match decorations {
8359 Decorations::Server => div,
8360 Decorations::Client { tiling } => div
8361 .border_color(cx.theme().colors().border)
8362 .when(!(tiling.top || tiling.right), |div| {
8363 div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING)
8364 })
8365 .when(!(tiling.top || tiling.left), |div| {
8366 div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
8367 })
8368 .when(!(tiling.bottom || tiling.right), |div| {
8369 div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING)
8370 })
8371 .when(!(tiling.bottom || tiling.left), |div| {
8372 div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
8373 })
8374 .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
8375 .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
8376 .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
8377 .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
8378 .when(!tiling.is_tiled(), |div| {
8379 div.shadow(vec![gpui::BoxShadow {
8380 color: Hsla {
8381 h: 0.,
8382 s: 0.,
8383 l: 0.,
8384 a: 0.4,
8385 },
8386 blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
8387 spread_radius: px(0.),
8388 offset: point(px(0.0), px(0.0)),
8389 }])
8390 }),
8391 })
8392 .on_mouse_move(|_e, _, cx| {
8393 cx.stop_propagation();
8394 })
8395 .size_full()
8396 .child(element),
8397 )
8398 .map(|div| match decorations {
8399 Decorations::Server => div,
8400 Decorations::Client { tiling, .. } => div.child(
8401 canvas(
8402 |_bounds, window, _| {
8403 window.insert_hitbox(
8404 Bounds::new(
8405 point(px(0.0), px(0.0)),
8406 window.window_bounds().get_bounds().size,
8407 ),
8408 HitboxBehavior::Normal,
8409 )
8410 },
8411 move |_bounds, hitbox, window, cx| {
8412 let mouse = window.mouse_position();
8413 let size = window.window_bounds().get_bounds().size;
8414 let Some(edge) =
8415 resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
8416 else {
8417 return;
8418 };
8419 cx.set_global(GlobalResizeEdge(edge));
8420 window.set_cursor_style(
8421 match edge {
8422 ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
8423 ResizeEdge::Left | ResizeEdge::Right => {
8424 CursorStyle::ResizeLeftRight
8425 }
8426 ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
8427 CursorStyle::ResizeUpLeftDownRight
8428 }
8429 ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
8430 CursorStyle::ResizeUpRightDownLeft
8431 }
8432 },
8433 &hitbox,
8434 );
8435 },
8436 )
8437 .size_full()
8438 .absolute(),
8439 ),
8440 })
8441}
8442
8443fn resize_edge(
8444 pos: Point<Pixels>,
8445 shadow_size: Pixels,
8446 window_size: Size<Pixels>,
8447 tiling: Tiling,
8448) -> Option<ResizeEdge> {
8449 let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
8450 if bounds.contains(&pos) {
8451 return None;
8452 }
8453
8454 let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
8455 let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
8456 if !tiling.top && top_left_bounds.contains(&pos) {
8457 return Some(ResizeEdge::TopLeft);
8458 }
8459
8460 let top_right_bounds = Bounds::new(
8461 Point::new(window_size.width - corner_size.width, px(0.)),
8462 corner_size,
8463 );
8464 if !tiling.top && top_right_bounds.contains(&pos) {
8465 return Some(ResizeEdge::TopRight);
8466 }
8467
8468 let bottom_left_bounds = Bounds::new(
8469 Point::new(px(0.), window_size.height - corner_size.height),
8470 corner_size,
8471 );
8472 if !tiling.bottom && bottom_left_bounds.contains(&pos) {
8473 return Some(ResizeEdge::BottomLeft);
8474 }
8475
8476 let bottom_right_bounds = Bounds::new(
8477 Point::new(
8478 window_size.width - corner_size.width,
8479 window_size.height - corner_size.height,
8480 ),
8481 corner_size,
8482 );
8483 if !tiling.bottom && bottom_right_bounds.contains(&pos) {
8484 return Some(ResizeEdge::BottomRight);
8485 }
8486
8487 if !tiling.top && pos.y < shadow_size {
8488 Some(ResizeEdge::Top)
8489 } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
8490 Some(ResizeEdge::Bottom)
8491 } else if !tiling.left && pos.x < shadow_size {
8492 Some(ResizeEdge::Left)
8493 } else if !tiling.right && pos.x > window_size.width - shadow_size {
8494 Some(ResizeEdge::Right)
8495 } else {
8496 None
8497 }
8498}
8499
8500fn join_pane_into_active(
8501 active_pane: &Entity<Pane>,
8502 pane: &Entity<Pane>,
8503 window: &mut Window,
8504 cx: &mut App,
8505) {
8506 if pane == active_pane {
8507 } else if pane.read(cx).items_len() == 0 {
8508 pane.update(cx, |_, cx| {
8509 cx.emit(pane::Event::Remove {
8510 focus_on_pane: None,
8511 });
8512 })
8513 } else {
8514 move_all_items(pane, active_pane, window, cx);
8515 }
8516}
8517
8518fn move_all_items(
8519 from_pane: &Entity<Pane>,
8520 to_pane: &Entity<Pane>,
8521 window: &mut Window,
8522 cx: &mut App,
8523) {
8524 let destination_is_different = from_pane != to_pane;
8525 let mut moved_items = 0;
8526 for (item_ix, item_handle) in from_pane
8527 .read(cx)
8528 .items()
8529 .enumerate()
8530 .map(|(ix, item)| (ix, item.clone()))
8531 .collect::<Vec<_>>()
8532 {
8533 let ix = item_ix - moved_items;
8534 if destination_is_different {
8535 // Close item from previous pane
8536 from_pane.update(cx, |source, cx| {
8537 source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
8538 });
8539 moved_items += 1;
8540 }
8541
8542 // This automatically removes duplicate items in the pane
8543 to_pane.update(cx, |destination, cx| {
8544 destination.add_item(item_handle, true, true, None, window, cx);
8545 window.focus(&destination.focus_handle(cx))
8546 });
8547 }
8548}
8549
8550pub fn move_item(
8551 source: &Entity<Pane>,
8552 destination: &Entity<Pane>,
8553 item_id_to_move: EntityId,
8554 destination_index: usize,
8555 activate: bool,
8556 window: &mut Window,
8557 cx: &mut App,
8558) {
8559 let Some((item_ix, item_handle)) = source
8560 .read(cx)
8561 .items()
8562 .enumerate()
8563 .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
8564 .map(|(ix, item)| (ix, item.clone()))
8565 else {
8566 // Tab was closed during drag
8567 return;
8568 };
8569
8570 if source != destination {
8571 // Close item from previous pane
8572 source.update(cx, |source, cx| {
8573 source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
8574 });
8575 }
8576
8577 // This automatically removes duplicate items in the pane
8578 destination.update(cx, |destination, cx| {
8579 destination.add_item_inner(
8580 item_handle,
8581 activate,
8582 activate,
8583 activate,
8584 Some(destination_index),
8585 window,
8586 cx,
8587 );
8588 if activate {
8589 window.focus(&destination.focus_handle(cx))
8590 }
8591 });
8592}
8593
8594pub fn move_active_item(
8595 source: &Entity<Pane>,
8596 destination: &Entity<Pane>,
8597 focus_destination: bool,
8598 close_if_empty: bool,
8599 window: &mut Window,
8600 cx: &mut App,
8601) {
8602 if source == destination {
8603 return;
8604 }
8605 let Some(active_item) = source.read(cx).active_item() else {
8606 return;
8607 };
8608 source.update(cx, |source_pane, cx| {
8609 let item_id = active_item.item_id();
8610 source_pane.remove_item(item_id, false, close_if_empty, window, cx);
8611 destination.update(cx, |target_pane, cx| {
8612 target_pane.add_item(
8613 active_item,
8614 focus_destination,
8615 focus_destination,
8616 Some(target_pane.items_len()),
8617 window,
8618 cx,
8619 );
8620 });
8621 });
8622}
8623
8624pub fn clone_active_item(
8625 workspace_id: Option<WorkspaceId>,
8626 source: &Entity<Pane>,
8627 destination: &Entity<Pane>,
8628 focus_destination: bool,
8629 window: &mut Window,
8630 cx: &mut App,
8631) {
8632 if source == destination {
8633 return;
8634 }
8635 let Some(active_item) = source.read(cx).active_item() else {
8636 return;
8637 };
8638 if !active_item.can_split(cx) {
8639 return;
8640 }
8641 let destination = destination.downgrade();
8642 let task = active_item.clone_on_split(workspace_id, window, cx);
8643 window
8644 .spawn(cx, async move |cx| {
8645 let Some(clone) = task.await else {
8646 return;
8647 };
8648 destination
8649 .update_in(cx, |target_pane, window, cx| {
8650 target_pane.add_item(
8651 clone,
8652 focus_destination,
8653 focus_destination,
8654 Some(target_pane.items_len()),
8655 window,
8656 cx,
8657 );
8658 })
8659 .log_err();
8660 })
8661 .detach();
8662}
8663
8664#[derive(Debug)]
8665pub struct WorkspacePosition {
8666 pub window_bounds: Option<WindowBounds>,
8667 pub display: Option<Uuid>,
8668 pub centered_layout: bool,
8669}
8670
8671pub fn remote_workspace_position_from_db(
8672 connection_options: RemoteConnectionOptions,
8673 paths_to_open: &[PathBuf],
8674 cx: &App,
8675) -> Task<Result<WorkspacePosition>> {
8676 let paths = paths_to_open.to_vec();
8677
8678 cx.background_spawn(async move {
8679 let remote_connection_id = persistence::DB
8680 .get_or_create_remote_connection(connection_options)
8681 .await
8682 .context("fetching serialized ssh project")?;
8683 let serialized_workspace =
8684 persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
8685
8686 let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
8687 (Some(WindowBounds::Windowed(bounds)), None)
8688 } else {
8689 let restorable_bounds = serialized_workspace
8690 .as_ref()
8691 .and_then(|workspace| Some((workspace.display?, workspace.window_bounds?)))
8692 .or_else(|| {
8693 let (display, window_bounds) = DB.last_window().log_err()?;
8694 Some((display?, window_bounds?))
8695 });
8696
8697 if let Some((serialized_display, serialized_status)) = restorable_bounds {
8698 (Some(serialized_status.0), Some(serialized_display))
8699 } else {
8700 (None, None)
8701 }
8702 };
8703
8704 let centered_layout = serialized_workspace
8705 .as_ref()
8706 .map(|w| w.centered_layout)
8707 .unwrap_or(false);
8708
8709 Ok(WorkspacePosition {
8710 window_bounds,
8711 display,
8712 centered_layout,
8713 })
8714 })
8715}
8716
8717pub fn with_active_or_new_workspace(
8718 cx: &mut App,
8719 f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
8720) {
8721 match cx.active_window().and_then(|w| w.downcast::<Workspace>()) {
8722 Some(workspace) => {
8723 cx.defer(move |cx| {
8724 workspace
8725 .update(cx, |workspace, window, cx| f(workspace, window, cx))
8726 .log_err();
8727 });
8728 }
8729 None => {
8730 let app_state = AppState::global(cx);
8731 if let Some(app_state) = app_state.upgrade() {
8732 open_new(
8733 OpenOptions::default(),
8734 app_state,
8735 cx,
8736 move |workspace, window, cx| f(workspace, window, cx),
8737 )
8738 .detach_and_log_err(cx);
8739 }
8740 }
8741 }
8742}
8743
8744#[cfg(test)]
8745mod tests {
8746 use std::{cell::RefCell, rc::Rc};
8747
8748 use super::*;
8749 use crate::{
8750 dock::{PanelEvent, test::TestPanel},
8751 item::{
8752 ItemBufferKind, ItemEvent,
8753 test::{TestItem, TestProjectItem},
8754 },
8755 };
8756 use fs::FakeFs;
8757 use gpui::{
8758 DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
8759 UpdateGlobal, VisualTestContext, px,
8760 };
8761 use project::{Project, ProjectEntryId};
8762 use serde_json::json;
8763 use settings::SettingsStore;
8764 use util::rel_path::rel_path;
8765
8766 #[gpui::test]
8767 async fn test_tab_disambiguation(cx: &mut TestAppContext) {
8768 init_test(cx);
8769
8770 let fs = FakeFs::new(cx.executor());
8771 let project = Project::test(fs, [], cx).await;
8772 let (workspace, cx) =
8773 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
8774
8775 // Adding an item with no ambiguity renders the tab without detail.
8776 let item1 = cx.new(|cx| {
8777 let mut item = TestItem::new(cx);
8778 item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
8779 item
8780 });
8781 workspace.update_in(cx, |workspace, window, cx| {
8782 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
8783 });
8784 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
8785
8786 // Adding an item that creates ambiguity increases the level of detail on
8787 // both tabs.
8788 let item2 = cx.new_window_entity(|_window, cx| {
8789 let mut item = TestItem::new(cx);
8790 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
8791 item
8792 });
8793 workspace.update_in(cx, |workspace, window, cx| {
8794 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
8795 });
8796 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
8797 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
8798
8799 // Adding an item that creates ambiguity increases the level of detail only
8800 // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
8801 // we stop at the highest detail available.
8802 let item3 = cx.new(|cx| {
8803 let mut item = TestItem::new(cx);
8804 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
8805 item
8806 });
8807 workspace.update_in(cx, |workspace, window, cx| {
8808 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
8809 });
8810 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
8811 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
8812 item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
8813 }
8814
8815 #[gpui::test]
8816 async fn test_tracking_active_path(cx: &mut TestAppContext) {
8817 init_test(cx);
8818
8819 let fs = FakeFs::new(cx.executor());
8820 fs.insert_tree(
8821 "/root1",
8822 json!({
8823 "one.txt": "",
8824 "two.txt": "",
8825 }),
8826 )
8827 .await;
8828 fs.insert_tree(
8829 "/root2",
8830 json!({
8831 "three.txt": "",
8832 }),
8833 )
8834 .await;
8835
8836 let project = Project::test(fs, ["root1".as_ref()], cx).await;
8837 let (workspace, cx) =
8838 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
8839 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
8840 let worktree_id = project.update(cx, |project, cx| {
8841 project.worktrees(cx).next().unwrap().read(cx).id()
8842 });
8843
8844 let item1 = cx.new(|cx| {
8845 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
8846 });
8847 let item2 = cx.new(|cx| {
8848 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
8849 });
8850
8851 // Add an item to an empty pane
8852 workspace.update_in(cx, |workspace, window, cx| {
8853 workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
8854 });
8855 project.update(cx, |project, cx| {
8856 assert_eq!(
8857 project.active_entry(),
8858 project
8859 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
8860 .map(|e| e.id)
8861 );
8862 });
8863 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
8864
8865 // Add a second item to a non-empty pane
8866 workspace.update_in(cx, |workspace, window, cx| {
8867 workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
8868 });
8869 assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
8870 project.update(cx, |project, cx| {
8871 assert_eq!(
8872 project.active_entry(),
8873 project
8874 .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
8875 .map(|e| e.id)
8876 );
8877 });
8878
8879 // Close the active item
8880 pane.update_in(cx, |pane, window, cx| {
8881 pane.close_active_item(&Default::default(), window, cx)
8882 })
8883 .await
8884 .unwrap();
8885 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
8886 project.update(cx, |project, cx| {
8887 assert_eq!(
8888 project.active_entry(),
8889 project
8890 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
8891 .map(|e| e.id)
8892 );
8893 });
8894
8895 // Add a project folder
8896 project
8897 .update(cx, |project, cx| {
8898 project.find_or_create_worktree("root2", true, cx)
8899 })
8900 .await
8901 .unwrap();
8902 assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
8903
8904 // Remove a project folder
8905 project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
8906 assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
8907 }
8908
8909 #[gpui::test]
8910 async fn test_close_window(cx: &mut TestAppContext) {
8911 init_test(cx);
8912
8913 let fs = FakeFs::new(cx.executor());
8914 fs.insert_tree("/root", json!({ "one": "" })).await;
8915
8916 let project = Project::test(fs, ["root".as_ref()], cx).await;
8917 let (workspace, cx) =
8918 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
8919
8920 // When there are no dirty items, there's nothing to do.
8921 let item1 = cx.new(TestItem::new);
8922 workspace.update_in(cx, |w, window, cx| {
8923 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
8924 });
8925 let task = workspace.update_in(cx, |w, window, cx| {
8926 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
8927 });
8928 assert!(task.await.unwrap());
8929
8930 // When there are dirty untitled items, prompt to save each one. If the user
8931 // cancels any prompt, then abort.
8932 let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
8933 let item3 = cx.new(|cx| {
8934 TestItem::new(cx)
8935 .with_dirty(true)
8936 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
8937 });
8938 workspace.update_in(cx, |w, window, cx| {
8939 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
8940 w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
8941 });
8942 let task = workspace.update_in(cx, |w, window, cx| {
8943 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
8944 });
8945 cx.executor().run_until_parked();
8946 cx.simulate_prompt_answer("Cancel"); // cancel save all
8947 cx.executor().run_until_parked();
8948 assert!(!cx.has_pending_prompt());
8949 assert!(!task.await.unwrap());
8950 }
8951
8952 #[gpui::test]
8953 async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
8954 init_test(cx);
8955
8956 // Register TestItem as a serializable item
8957 cx.update(|cx| {
8958 register_serializable_item::<TestItem>(cx);
8959 });
8960
8961 let fs = FakeFs::new(cx.executor());
8962 fs.insert_tree("/root", json!({ "one": "" })).await;
8963
8964 let project = Project::test(fs, ["root".as_ref()], cx).await;
8965 let (workspace, cx) =
8966 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
8967
8968 // When there are dirty untitled items, but they can serialize, then there is no prompt.
8969 let item1 = cx.new(|cx| {
8970 TestItem::new(cx)
8971 .with_dirty(true)
8972 .with_serialize(|| Some(Task::ready(Ok(()))))
8973 });
8974 let item2 = cx.new(|cx| {
8975 TestItem::new(cx)
8976 .with_dirty(true)
8977 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
8978 .with_serialize(|| Some(Task::ready(Ok(()))))
8979 });
8980 workspace.update_in(cx, |w, window, cx| {
8981 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
8982 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
8983 });
8984 let task = workspace.update_in(cx, |w, window, cx| {
8985 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
8986 });
8987 assert!(task.await.unwrap());
8988 }
8989
8990 #[gpui::test]
8991 async fn test_close_pane_items(cx: &mut TestAppContext) {
8992 init_test(cx);
8993
8994 let fs = FakeFs::new(cx.executor());
8995
8996 let project = Project::test(fs, None, cx).await;
8997 let (workspace, cx) =
8998 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
8999
9000 let item1 = cx.new(|cx| {
9001 TestItem::new(cx)
9002 .with_dirty(true)
9003 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
9004 });
9005 let item2 = cx.new(|cx| {
9006 TestItem::new(cx)
9007 .with_dirty(true)
9008 .with_conflict(true)
9009 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
9010 });
9011 let item3 = cx.new(|cx| {
9012 TestItem::new(cx)
9013 .with_dirty(true)
9014 .with_conflict(true)
9015 .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
9016 });
9017 let item4 = cx.new(|cx| {
9018 TestItem::new(cx).with_dirty(true).with_project_items(&[{
9019 let project_item = TestProjectItem::new_untitled(cx);
9020 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
9021 project_item
9022 }])
9023 });
9024 let pane = workspace.update_in(cx, |workspace, window, cx| {
9025 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
9026 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
9027 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
9028 workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
9029 workspace.active_pane().clone()
9030 });
9031
9032 let close_items = pane.update_in(cx, |pane, window, cx| {
9033 pane.activate_item(1, true, true, window, cx);
9034 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
9035 let item1_id = item1.item_id();
9036 let item3_id = item3.item_id();
9037 let item4_id = item4.item_id();
9038 pane.close_items(window, cx, SaveIntent::Close, move |id| {
9039 [item1_id, item3_id, item4_id].contains(&id)
9040 })
9041 });
9042 cx.executor().run_until_parked();
9043
9044 assert!(cx.has_pending_prompt());
9045 cx.simulate_prompt_answer("Save all");
9046
9047 cx.executor().run_until_parked();
9048
9049 // Item 1 is saved. There's a prompt to save item 3.
9050 pane.update(cx, |pane, cx| {
9051 assert_eq!(item1.read(cx).save_count, 1);
9052 assert_eq!(item1.read(cx).save_as_count, 0);
9053 assert_eq!(item1.read(cx).reload_count, 0);
9054 assert_eq!(pane.items_len(), 3);
9055 assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
9056 });
9057 assert!(cx.has_pending_prompt());
9058
9059 // Cancel saving item 3.
9060 cx.simulate_prompt_answer("Discard");
9061 cx.executor().run_until_parked();
9062
9063 // Item 3 is reloaded. There's a prompt to save item 4.
9064 pane.update(cx, |pane, cx| {
9065 assert_eq!(item3.read(cx).save_count, 0);
9066 assert_eq!(item3.read(cx).save_as_count, 0);
9067 assert_eq!(item3.read(cx).reload_count, 1);
9068 assert_eq!(pane.items_len(), 2);
9069 assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
9070 });
9071
9072 // There's a prompt for a path for item 4.
9073 cx.simulate_new_path_selection(|_| Some(Default::default()));
9074 close_items.await.unwrap();
9075
9076 // The requested items are closed.
9077 pane.update(cx, |pane, cx| {
9078 assert_eq!(item4.read(cx).save_count, 0);
9079 assert_eq!(item4.read(cx).save_as_count, 1);
9080 assert_eq!(item4.read(cx).reload_count, 0);
9081 assert_eq!(pane.items_len(), 1);
9082 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
9083 });
9084 }
9085
9086 #[gpui::test]
9087 async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
9088 init_test(cx);
9089
9090 let fs = FakeFs::new(cx.executor());
9091 let project = Project::test(fs, [], cx).await;
9092 let (workspace, cx) =
9093 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9094
9095 // Create several workspace items with single project entries, and two
9096 // workspace items with multiple project entries.
9097 let single_entry_items = (0..=4)
9098 .map(|project_entry_id| {
9099 cx.new(|cx| {
9100 TestItem::new(cx)
9101 .with_dirty(true)
9102 .with_project_items(&[dirty_project_item(
9103 project_entry_id,
9104 &format!("{project_entry_id}.txt"),
9105 cx,
9106 )])
9107 })
9108 })
9109 .collect::<Vec<_>>();
9110 let item_2_3 = cx.new(|cx| {
9111 TestItem::new(cx)
9112 .with_dirty(true)
9113 .with_buffer_kind(ItemBufferKind::Multibuffer)
9114 .with_project_items(&[
9115 single_entry_items[2].read(cx).project_items[0].clone(),
9116 single_entry_items[3].read(cx).project_items[0].clone(),
9117 ])
9118 });
9119 let item_3_4 = cx.new(|cx| {
9120 TestItem::new(cx)
9121 .with_dirty(true)
9122 .with_buffer_kind(ItemBufferKind::Multibuffer)
9123 .with_project_items(&[
9124 single_entry_items[3].read(cx).project_items[0].clone(),
9125 single_entry_items[4].read(cx).project_items[0].clone(),
9126 ])
9127 });
9128
9129 // Create two panes that contain the following project entries:
9130 // left pane:
9131 // multi-entry items: (2, 3)
9132 // single-entry items: 0, 2, 3, 4
9133 // right pane:
9134 // single-entry items: 4, 1
9135 // multi-entry items: (3, 4)
9136 let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
9137 let left_pane = workspace.active_pane().clone();
9138 workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
9139 workspace.add_item_to_active_pane(
9140 single_entry_items[0].boxed_clone(),
9141 None,
9142 true,
9143 window,
9144 cx,
9145 );
9146 workspace.add_item_to_active_pane(
9147 single_entry_items[2].boxed_clone(),
9148 None,
9149 true,
9150 window,
9151 cx,
9152 );
9153 workspace.add_item_to_active_pane(
9154 single_entry_items[3].boxed_clone(),
9155 None,
9156 true,
9157 window,
9158 cx,
9159 );
9160 workspace.add_item_to_active_pane(
9161 single_entry_items[4].boxed_clone(),
9162 None,
9163 true,
9164 window,
9165 cx,
9166 );
9167
9168 let right_pane =
9169 workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
9170
9171 let boxed_clone = single_entry_items[1].boxed_clone();
9172 let right_pane = window.spawn(cx, async move |cx| {
9173 right_pane.await.inspect(|right_pane| {
9174 right_pane
9175 .update_in(cx, |pane, window, cx| {
9176 pane.add_item(boxed_clone, true, true, None, window, cx);
9177 pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
9178 })
9179 .unwrap();
9180 })
9181 });
9182
9183 (left_pane, right_pane)
9184 });
9185 let right_pane = right_pane.await.unwrap();
9186 cx.focus(&right_pane);
9187
9188 let mut close = right_pane.update_in(cx, |pane, window, cx| {
9189 pane.close_all_items(&CloseAllItems::default(), window, cx)
9190 .unwrap()
9191 });
9192 cx.executor().run_until_parked();
9193
9194 let msg = cx.pending_prompt().unwrap().0;
9195 assert!(msg.contains("1.txt"));
9196 assert!(!msg.contains("2.txt"));
9197 assert!(!msg.contains("3.txt"));
9198 assert!(!msg.contains("4.txt"));
9199
9200 cx.simulate_prompt_answer("Cancel");
9201 close.await;
9202
9203 left_pane
9204 .update_in(cx, |left_pane, window, cx| {
9205 left_pane.close_item_by_id(
9206 single_entry_items[3].entity_id(),
9207 SaveIntent::Skip,
9208 window,
9209 cx,
9210 )
9211 })
9212 .await
9213 .unwrap();
9214
9215 close = right_pane.update_in(cx, |pane, window, cx| {
9216 pane.close_all_items(&CloseAllItems::default(), window, cx)
9217 .unwrap()
9218 });
9219 cx.executor().run_until_parked();
9220
9221 let details = cx.pending_prompt().unwrap().1;
9222 assert!(details.contains("1.txt"));
9223 assert!(!details.contains("2.txt"));
9224 assert!(details.contains("3.txt"));
9225 // ideally this assertion could be made, but today we can only
9226 // save whole items not project items, so the orphaned item 3 causes
9227 // 4 to be saved too.
9228 // assert!(!details.contains("4.txt"));
9229
9230 cx.simulate_prompt_answer("Save all");
9231
9232 cx.executor().run_until_parked();
9233 close.await;
9234 right_pane.read_with(cx, |pane, _| {
9235 assert_eq!(pane.items_len(), 0);
9236 });
9237 }
9238
9239 #[gpui::test]
9240 async fn test_autosave(cx: &mut gpui::TestAppContext) {
9241 init_test(cx);
9242
9243 let fs = FakeFs::new(cx.executor());
9244 let project = Project::test(fs, [], cx).await;
9245 let (workspace, cx) =
9246 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9247 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
9248
9249 let item = cx.new(|cx| {
9250 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
9251 });
9252 let item_id = item.entity_id();
9253 workspace.update_in(cx, |workspace, window, cx| {
9254 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
9255 });
9256
9257 // Autosave on window change.
9258 item.update(cx, |item, cx| {
9259 SettingsStore::update_global(cx, |settings, cx| {
9260 settings.update_user_settings(cx, |settings| {
9261 settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
9262 })
9263 });
9264 item.is_dirty = true;
9265 });
9266
9267 // Deactivating the window saves the file.
9268 cx.deactivate_window();
9269 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
9270
9271 // Re-activating the window doesn't save the file.
9272 cx.update(|window, _| window.activate_window());
9273 cx.executor().run_until_parked();
9274 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
9275
9276 // Autosave on focus change.
9277 item.update_in(cx, |item, window, cx| {
9278 cx.focus_self(window);
9279 SettingsStore::update_global(cx, |settings, cx| {
9280 settings.update_user_settings(cx, |settings| {
9281 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
9282 })
9283 });
9284 item.is_dirty = true;
9285 });
9286 // Blurring the item saves the file.
9287 item.update_in(cx, |_, window, _| window.blur());
9288 cx.executor().run_until_parked();
9289 item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
9290
9291 // Deactivating the window still saves the file.
9292 item.update_in(cx, |item, window, cx| {
9293 cx.focus_self(window);
9294 item.is_dirty = true;
9295 });
9296 cx.deactivate_window();
9297 item.update(cx, |item, _| assert_eq!(item.save_count, 3));
9298
9299 // Autosave after delay.
9300 item.update(cx, |item, cx| {
9301 SettingsStore::update_global(cx, |settings, cx| {
9302 settings.update_user_settings(cx, |settings| {
9303 settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
9304 milliseconds: 500.into(),
9305 });
9306 })
9307 });
9308 item.is_dirty = true;
9309 cx.emit(ItemEvent::Edit);
9310 });
9311
9312 // Delay hasn't fully expired, so the file is still dirty and unsaved.
9313 cx.executor().advance_clock(Duration::from_millis(250));
9314 item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
9315
9316 // After delay expires, the file is saved.
9317 cx.executor().advance_clock(Duration::from_millis(250));
9318 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
9319
9320 // Autosave after delay, should save earlier than delay if tab is closed
9321 item.update(cx, |item, cx| {
9322 item.is_dirty = true;
9323 cx.emit(ItemEvent::Edit);
9324 });
9325 cx.executor().advance_clock(Duration::from_millis(250));
9326 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
9327
9328 // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
9329 pane.update_in(cx, |pane, window, cx| {
9330 pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
9331 })
9332 .await
9333 .unwrap();
9334 assert!(!cx.has_pending_prompt());
9335 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
9336
9337 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
9338 workspace.update_in(cx, |workspace, window, cx| {
9339 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
9340 });
9341 item.update_in(cx, |item, _window, cx| {
9342 item.is_dirty = true;
9343 for project_item in &mut item.project_items {
9344 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
9345 }
9346 });
9347 cx.run_until_parked();
9348 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
9349
9350 // Autosave on focus change, ensuring closing the tab counts as such.
9351 item.update(cx, |item, cx| {
9352 SettingsStore::update_global(cx, |settings, cx| {
9353 settings.update_user_settings(cx, |settings| {
9354 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
9355 })
9356 });
9357 item.is_dirty = true;
9358 for project_item in &mut item.project_items {
9359 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
9360 }
9361 });
9362
9363 pane.update_in(cx, |pane, window, cx| {
9364 pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
9365 })
9366 .await
9367 .unwrap();
9368 assert!(!cx.has_pending_prompt());
9369 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
9370
9371 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
9372 workspace.update_in(cx, |workspace, window, cx| {
9373 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
9374 });
9375 item.update_in(cx, |item, window, cx| {
9376 item.project_items[0].update(cx, |item, _| {
9377 item.entry_id = None;
9378 });
9379 item.is_dirty = true;
9380 window.blur();
9381 });
9382 cx.run_until_parked();
9383 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
9384
9385 // Ensure autosave is prevented for deleted files also when closing the buffer.
9386 let _close_items = pane.update_in(cx, |pane, window, cx| {
9387 pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
9388 });
9389 cx.run_until_parked();
9390 assert!(cx.has_pending_prompt());
9391 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
9392 }
9393
9394 #[gpui::test]
9395 async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
9396 init_test(cx);
9397
9398 let fs = FakeFs::new(cx.executor());
9399
9400 let project = Project::test(fs, [], cx).await;
9401 let (workspace, cx) =
9402 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9403
9404 let item = cx.new(|cx| {
9405 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
9406 });
9407 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
9408 let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
9409 let toolbar_notify_count = Rc::new(RefCell::new(0));
9410
9411 workspace.update_in(cx, |workspace, window, cx| {
9412 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
9413 let toolbar_notification_count = toolbar_notify_count.clone();
9414 cx.observe_in(&toolbar, window, move |_, _, _, _| {
9415 *toolbar_notification_count.borrow_mut() += 1
9416 })
9417 .detach();
9418 });
9419
9420 pane.read_with(cx, |pane, _| {
9421 assert!(!pane.can_navigate_backward());
9422 assert!(!pane.can_navigate_forward());
9423 });
9424
9425 item.update_in(cx, |item, _, cx| {
9426 item.set_state("one".to_string(), cx);
9427 });
9428
9429 // Toolbar must be notified to re-render the navigation buttons
9430 assert_eq!(*toolbar_notify_count.borrow(), 1);
9431
9432 pane.read_with(cx, |pane, _| {
9433 assert!(pane.can_navigate_backward());
9434 assert!(!pane.can_navigate_forward());
9435 });
9436
9437 workspace
9438 .update_in(cx, |workspace, window, cx| {
9439 workspace.go_back(pane.downgrade(), window, cx)
9440 })
9441 .await
9442 .unwrap();
9443
9444 assert_eq!(*toolbar_notify_count.borrow(), 2);
9445 pane.read_with(cx, |pane, _| {
9446 assert!(!pane.can_navigate_backward());
9447 assert!(pane.can_navigate_forward());
9448 });
9449 }
9450
9451 #[gpui::test]
9452 async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
9453 init_test(cx);
9454 let fs = FakeFs::new(cx.executor());
9455
9456 let project = Project::test(fs, [], cx).await;
9457 let (workspace, cx) =
9458 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9459
9460 let panel = workspace.update_in(cx, |workspace, window, cx| {
9461 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
9462 workspace.add_panel(panel.clone(), window, cx);
9463
9464 workspace
9465 .right_dock()
9466 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
9467
9468 panel
9469 });
9470
9471 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
9472 pane.update_in(cx, |pane, window, cx| {
9473 let item = cx.new(TestItem::new);
9474 pane.add_item(Box::new(item), true, true, None, window, cx);
9475 });
9476
9477 // Transfer focus from center to panel
9478 workspace.update_in(cx, |workspace, window, cx| {
9479 workspace.toggle_panel_focus::<TestPanel>(window, cx);
9480 });
9481
9482 workspace.update_in(cx, |workspace, window, cx| {
9483 assert!(workspace.right_dock().read(cx).is_open());
9484 assert!(!panel.is_zoomed(window, cx));
9485 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
9486 });
9487
9488 // Transfer focus from panel to center
9489 workspace.update_in(cx, |workspace, window, cx| {
9490 workspace.toggle_panel_focus::<TestPanel>(window, cx);
9491 });
9492
9493 workspace.update_in(cx, |workspace, window, cx| {
9494 assert!(workspace.right_dock().read(cx).is_open());
9495 assert!(!panel.is_zoomed(window, cx));
9496 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
9497 });
9498
9499 // Close the dock
9500 workspace.update_in(cx, |workspace, window, cx| {
9501 workspace.toggle_dock(DockPosition::Right, window, cx);
9502 });
9503
9504 workspace.update_in(cx, |workspace, window, cx| {
9505 assert!(!workspace.right_dock().read(cx).is_open());
9506 assert!(!panel.is_zoomed(window, cx));
9507 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
9508 });
9509
9510 // Open the dock
9511 workspace.update_in(cx, |workspace, window, cx| {
9512 workspace.toggle_dock(DockPosition::Right, window, cx);
9513 });
9514
9515 workspace.update_in(cx, |workspace, window, cx| {
9516 assert!(workspace.right_dock().read(cx).is_open());
9517 assert!(!panel.is_zoomed(window, cx));
9518 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
9519 });
9520
9521 // Focus and zoom panel
9522 panel.update_in(cx, |panel, window, cx| {
9523 cx.focus_self(window);
9524 panel.set_zoomed(true, window, cx)
9525 });
9526
9527 workspace.update_in(cx, |workspace, window, cx| {
9528 assert!(workspace.right_dock().read(cx).is_open());
9529 assert!(panel.is_zoomed(window, cx));
9530 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
9531 });
9532
9533 // Transfer focus to the center closes the dock
9534 workspace.update_in(cx, |workspace, window, cx| {
9535 workspace.toggle_panel_focus::<TestPanel>(window, cx);
9536 });
9537
9538 workspace.update_in(cx, |workspace, window, cx| {
9539 assert!(!workspace.right_dock().read(cx).is_open());
9540 assert!(panel.is_zoomed(window, cx));
9541 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
9542 });
9543
9544 // Transferring focus back to the panel keeps it zoomed
9545 workspace.update_in(cx, |workspace, window, cx| {
9546 workspace.toggle_panel_focus::<TestPanel>(window, cx);
9547 });
9548
9549 workspace.update_in(cx, |workspace, window, cx| {
9550 assert!(workspace.right_dock().read(cx).is_open());
9551 assert!(panel.is_zoomed(window, cx));
9552 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
9553 });
9554
9555 // Close the dock while it is zoomed
9556 workspace.update_in(cx, |workspace, window, cx| {
9557 workspace.toggle_dock(DockPosition::Right, window, cx)
9558 });
9559
9560 workspace.update_in(cx, |workspace, window, cx| {
9561 assert!(!workspace.right_dock().read(cx).is_open());
9562 assert!(panel.is_zoomed(window, cx));
9563 assert!(workspace.zoomed.is_none());
9564 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
9565 });
9566
9567 // Opening the dock, when it's zoomed, retains focus
9568 workspace.update_in(cx, |workspace, window, cx| {
9569 workspace.toggle_dock(DockPosition::Right, window, cx)
9570 });
9571
9572 workspace.update_in(cx, |workspace, window, cx| {
9573 assert!(workspace.right_dock().read(cx).is_open());
9574 assert!(panel.is_zoomed(window, cx));
9575 assert!(workspace.zoomed.is_some());
9576 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
9577 });
9578
9579 // Unzoom and close the panel, zoom the active pane.
9580 panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
9581 workspace.update_in(cx, |workspace, window, cx| {
9582 workspace.toggle_dock(DockPosition::Right, window, cx)
9583 });
9584 pane.update_in(cx, |pane, window, cx| {
9585 pane.toggle_zoom(&Default::default(), window, cx)
9586 });
9587
9588 // Opening a dock unzooms the pane.
9589 workspace.update_in(cx, |workspace, window, cx| {
9590 workspace.toggle_dock(DockPosition::Right, window, cx)
9591 });
9592 workspace.update_in(cx, |workspace, window, cx| {
9593 let pane = pane.read(cx);
9594 assert!(!pane.is_zoomed());
9595 assert!(!pane.focus_handle(cx).is_focused(window));
9596 assert!(workspace.right_dock().read(cx).is_open());
9597 assert!(workspace.zoomed.is_none());
9598 });
9599 }
9600
9601 #[gpui::test]
9602 async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
9603 init_test(cx);
9604 let fs = FakeFs::new(cx.executor());
9605
9606 let project = Project::test(fs, [], cx).await;
9607 let (workspace, cx) =
9608 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9609
9610 let pane = workspace.update_in(cx, |workspace, _window, _cx| {
9611 workspace.active_pane().clone()
9612 });
9613
9614 // Add an item to the pane so it can be zoomed
9615 workspace.update_in(cx, |workspace, window, cx| {
9616 let item = cx.new(TestItem::new);
9617 workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
9618 });
9619
9620 // Initially not zoomed
9621 workspace.update_in(cx, |workspace, _window, cx| {
9622 assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
9623 assert!(
9624 workspace.zoomed.is_none(),
9625 "Workspace should track no zoomed pane"
9626 );
9627 assert!(pane.read(cx).items_len() > 0, "Pane should have items");
9628 });
9629
9630 // Zoom In
9631 pane.update_in(cx, |pane, window, cx| {
9632 pane.zoom_in(&crate::ZoomIn, window, cx);
9633 });
9634
9635 workspace.update_in(cx, |workspace, window, cx| {
9636 assert!(
9637 pane.read(cx).is_zoomed(),
9638 "Pane should be zoomed after ZoomIn"
9639 );
9640 assert!(
9641 workspace.zoomed.is_some(),
9642 "Workspace should track the zoomed pane"
9643 );
9644 assert!(
9645 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
9646 "ZoomIn should focus the pane"
9647 );
9648 });
9649
9650 // Zoom In again is a no-op
9651 pane.update_in(cx, |pane, window, cx| {
9652 pane.zoom_in(&crate::ZoomIn, window, cx);
9653 });
9654
9655 workspace.update_in(cx, |workspace, window, cx| {
9656 assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
9657 assert!(
9658 workspace.zoomed.is_some(),
9659 "Workspace still tracks zoomed pane"
9660 );
9661 assert!(
9662 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
9663 "Pane remains focused after repeated ZoomIn"
9664 );
9665 });
9666
9667 // Zoom Out
9668 pane.update_in(cx, |pane, window, cx| {
9669 pane.zoom_out(&crate::ZoomOut, window, cx);
9670 });
9671
9672 workspace.update_in(cx, |workspace, _window, cx| {
9673 assert!(
9674 !pane.read(cx).is_zoomed(),
9675 "Pane should unzoom after ZoomOut"
9676 );
9677 assert!(
9678 workspace.zoomed.is_none(),
9679 "Workspace clears zoom tracking after ZoomOut"
9680 );
9681 });
9682
9683 // Zoom Out again is a no-op
9684 pane.update_in(cx, |pane, window, cx| {
9685 pane.zoom_out(&crate::ZoomOut, window, cx);
9686 });
9687
9688 workspace.update_in(cx, |workspace, _window, cx| {
9689 assert!(
9690 !pane.read(cx).is_zoomed(),
9691 "Second ZoomOut keeps pane unzoomed"
9692 );
9693 assert!(
9694 workspace.zoomed.is_none(),
9695 "Workspace remains without zoomed pane"
9696 );
9697 });
9698 }
9699
9700 #[gpui::test]
9701 async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
9702 init_test(cx);
9703 let fs = FakeFs::new(cx.executor());
9704
9705 let project = Project::test(fs, [], cx).await;
9706 let (workspace, cx) =
9707 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9708 workspace.update_in(cx, |workspace, window, cx| {
9709 // Open two docks
9710 let left_dock = workspace.dock_at_position(DockPosition::Left);
9711 let right_dock = workspace.dock_at_position(DockPosition::Right);
9712
9713 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
9714 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
9715
9716 assert!(left_dock.read(cx).is_open());
9717 assert!(right_dock.read(cx).is_open());
9718 });
9719
9720 workspace.update_in(cx, |workspace, window, cx| {
9721 // Toggle all docks - should close both
9722 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
9723
9724 let left_dock = workspace.dock_at_position(DockPosition::Left);
9725 let right_dock = workspace.dock_at_position(DockPosition::Right);
9726 assert!(!left_dock.read(cx).is_open());
9727 assert!(!right_dock.read(cx).is_open());
9728 });
9729
9730 workspace.update_in(cx, |workspace, window, cx| {
9731 // Toggle again - should reopen both
9732 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
9733
9734 let left_dock = workspace.dock_at_position(DockPosition::Left);
9735 let right_dock = workspace.dock_at_position(DockPosition::Right);
9736 assert!(left_dock.read(cx).is_open());
9737 assert!(right_dock.read(cx).is_open());
9738 });
9739 }
9740
9741 #[gpui::test]
9742 async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
9743 init_test(cx);
9744 let fs = FakeFs::new(cx.executor());
9745
9746 let project = Project::test(fs, [], cx).await;
9747 let (workspace, cx) =
9748 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9749 workspace.update_in(cx, |workspace, window, cx| {
9750 // Open two docks
9751 let left_dock = workspace.dock_at_position(DockPosition::Left);
9752 let right_dock = workspace.dock_at_position(DockPosition::Right);
9753
9754 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
9755 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
9756
9757 assert!(left_dock.read(cx).is_open());
9758 assert!(right_dock.read(cx).is_open());
9759 });
9760
9761 workspace.update_in(cx, |workspace, window, cx| {
9762 // Close them manually
9763 workspace.toggle_dock(DockPosition::Left, window, cx);
9764 workspace.toggle_dock(DockPosition::Right, window, cx);
9765
9766 let left_dock = workspace.dock_at_position(DockPosition::Left);
9767 let right_dock = workspace.dock_at_position(DockPosition::Right);
9768 assert!(!left_dock.read(cx).is_open());
9769 assert!(!right_dock.read(cx).is_open());
9770 });
9771
9772 workspace.update_in(cx, |workspace, window, cx| {
9773 // Toggle all docks - only last closed (right dock) should reopen
9774 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
9775
9776 let left_dock = workspace.dock_at_position(DockPosition::Left);
9777 let right_dock = workspace.dock_at_position(DockPosition::Right);
9778 assert!(!left_dock.read(cx).is_open());
9779 assert!(right_dock.read(cx).is_open());
9780 });
9781 }
9782
9783 #[gpui::test]
9784 async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
9785 init_test(cx);
9786 let fs = FakeFs::new(cx.executor());
9787 let project = Project::test(fs, [], cx).await;
9788 let (workspace, cx) =
9789 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9790
9791 // Open two docks (left and right) with one panel each
9792 let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
9793 let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
9794 workspace.add_panel(left_panel.clone(), window, cx);
9795
9796 let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
9797 workspace.add_panel(right_panel.clone(), window, cx);
9798
9799 workspace.toggle_dock(DockPosition::Left, window, cx);
9800 workspace.toggle_dock(DockPosition::Right, window, cx);
9801
9802 // Verify initial state
9803 assert!(
9804 workspace.left_dock().read(cx).is_open(),
9805 "Left dock should be open"
9806 );
9807 assert_eq!(
9808 workspace
9809 .left_dock()
9810 .read(cx)
9811 .visible_panel()
9812 .unwrap()
9813 .panel_id(),
9814 left_panel.panel_id(),
9815 "Left panel should be visible in left dock"
9816 );
9817 assert!(
9818 workspace.right_dock().read(cx).is_open(),
9819 "Right dock should be open"
9820 );
9821 assert_eq!(
9822 workspace
9823 .right_dock()
9824 .read(cx)
9825 .visible_panel()
9826 .unwrap()
9827 .panel_id(),
9828 right_panel.panel_id(),
9829 "Right panel should be visible in right dock"
9830 );
9831 assert!(
9832 !workspace.bottom_dock().read(cx).is_open(),
9833 "Bottom dock should be closed"
9834 );
9835
9836 (left_panel, right_panel)
9837 });
9838
9839 // Focus the left panel and move it to the next position (bottom dock)
9840 workspace.update_in(cx, |workspace, window, cx| {
9841 workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
9842 assert!(
9843 left_panel.read(cx).focus_handle(cx).is_focused(window),
9844 "Left panel should be focused"
9845 );
9846 });
9847
9848 cx.dispatch_action(MoveFocusedPanelToNextPosition);
9849
9850 // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
9851 workspace.update(cx, |workspace, cx| {
9852 assert!(
9853 !workspace.left_dock().read(cx).is_open(),
9854 "Left dock should be closed"
9855 );
9856 assert!(
9857 workspace.bottom_dock().read(cx).is_open(),
9858 "Bottom dock should now be open"
9859 );
9860 assert_eq!(
9861 left_panel.read(cx).position,
9862 DockPosition::Bottom,
9863 "Left panel should now be in the bottom dock"
9864 );
9865 assert_eq!(
9866 workspace
9867 .bottom_dock()
9868 .read(cx)
9869 .visible_panel()
9870 .unwrap()
9871 .panel_id(),
9872 left_panel.panel_id(),
9873 "Left panel should be the visible panel in the bottom dock"
9874 );
9875 });
9876
9877 // Toggle all docks off
9878 workspace.update_in(cx, |workspace, window, cx| {
9879 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
9880 assert!(
9881 !workspace.left_dock().read(cx).is_open(),
9882 "Left dock should be closed"
9883 );
9884 assert!(
9885 !workspace.right_dock().read(cx).is_open(),
9886 "Right dock should be closed"
9887 );
9888 assert!(
9889 !workspace.bottom_dock().read(cx).is_open(),
9890 "Bottom dock should be closed"
9891 );
9892 });
9893
9894 // Toggle all docks back on and verify positions are restored
9895 workspace.update_in(cx, |workspace, window, cx| {
9896 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
9897 assert!(
9898 !workspace.left_dock().read(cx).is_open(),
9899 "Left dock should remain closed"
9900 );
9901 assert!(
9902 workspace.right_dock().read(cx).is_open(),
9903 "Right dock should remain open"
9904 );
9905 assert!(
9906 workspace.bottom_dock().read(cx).is_open(),
9907 "Bottom dock should remain open"
9908 );
9909 assert_eq!(
9910 left_panel.read(cx).position,
9911 DockPosition::Bottom,
9912 "Left panel should remain in the bottom dock"
9913 );
9914 assert_eq!(
9915 right_panel.read(cx).position,
9916 DockPosition::Right,
9917 "Right panel should remain in the right dock"
9918 );
9919 assert_eq!(
9920 workspace
9921 .bottom_dock()
9922 .read(cx)
9923 .visible_panel()
9924 .unwrap()
9925 .panel_id(),
9926 left_panel.panel_id(),
9927 "Left panel should be the visible panel in the right dock"
9928 );
9929 });
9930 }
9931
9932 #[gpui::test]
9933 async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
9934 init_test(cx);
9935
9936 let fs = FakeFs::new(cx.executor());
9937
9938 let project = Project::test(fs, None, cx).await;
9939 let (workspace, cx) =
9940 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9941
9942 // Let's arrange the panes like this:
9943 //
9944 // +-----------------------+
9945 // | top |
9946 // +------+--------+-------+
9947 // | left | center | right |
9948 // +------+--------+-------+
9949 // | bottom |
9950 // +-----------------------+
9951
9952 let top_item = cx.new(|cx| {
9953 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
9954 });
9955 let bottom_item = cx.new(|cx| {
9956 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
9957 });
9958 let left_item = cx.new(|cx| {
9959 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
9960 });
9961 let right_item = cx.new(|cx| {
9962 TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
9963 });
9964 let center_item = cx.new(|cx| {
9965 TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
9966 });
9967
9968 let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
9969 let top_pane_id = workspace.active_pane().entity_id();
9970 workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
9971 workspace.split_pane(
9972 workspace.active_pane().clone(),
9973 SplitDirection::Down,
9974 window,
9975 cx,
9976 );
9977 top_pane_id
9978 });
9979 let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
9980 let bottom_pane_id = workspace.active_pane().entity_id();
9981 workspace.add_item_to_active_pane(
9982 Box::new(bottom_item.clone()),
9983 None,
9984 false,
9985 window,
9986 cx,
9987 );
9988 workspace.split_pane(
9989 workspace.active_pane().clone(),
9990 SplitDirection::Up,
9991 window,
9992 cx,
9993 );
9994 bottom_pane_id
9995 });
9996 let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
9997 let left_pane_id = workspace.active_pane().entity_id();
9998 workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
9999 workspace.split_pane(
10000 workspace.active_pane().clone(),
10001 SplitDirection::Right,
10002 window,
10003 cx,
10004 );
10005 left_pane_id
10006 });
10007 let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
10008 let right_pane_id = workspace.active_pane().entity_id();
10009 workspace.add_item_to_active_pane(
10010 Box::new(right_item.clone()),
10011 None,
10012 false,
10013 window,
10014 cx,
10015 );
10016 workspace.split_pane(
10017 workspace.active_pane().clone(),
10018 SplitDirection::Left,
10019 window,
10020 cx,
10021 );
10022 right_pane_id
10023 });
10024 let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
10025 let center_pane_id = workspace.active_pane().entity_id();
10026 workspace.add_item_to_active_pane(
10027 Box::new(center_item.clone()),
10028 None,
10029 false,
10030 window,
10031 cx,
10032 );
10033 center_pane_id
10034 });
10035 cx.executor().run_until_parked();
10036
10037 workspace.update_in(cx, |workspace, window, cx| {
10038 assert_eq!(center_pane_id, workspace.active_pane().entity_id());
10039
10040 // Join into next from center pane into right
10041 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
10042 });
10043
10044 workspace.update_in(cx, |workspace, window, cx| {
10045 let active_pane = workspace.active_pane();
10046 assert_eq!(right_pane_id, active_pane.entity_id());
10047 assert_eq!(2, active_pane.read(cx).items_len());
10048 let item_ids_in_pane =
10049 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
10050 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
10051 assert!(item_ids_in_pane.contains(&right_item.item_id()));
10052
10053 // Join into next from right pane into bottom
10054 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
10055 });
10056
10057 workspace.update_in(cx, |workspace, window, cx| {
10058 let active_pane = workspace.active_pane();
10059 assert_eq!(bottom_pane_id, active_pane.entity_id());
10060 assert_eq!(3, active_pane.read(cx).items_len());
10061 let item_ids_in_pane =
10062 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
10063 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
10064 assert!(item_ids_in_pane.contains(&right_item.item_id()));
10065 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
10066
10067 // Join into next from bottom pane into left
10068 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
10069 });
10070
10071 workspace.update_in(cx, |workspace, window, cx| {
10072 let active_pane = workspace.active_pane();
10073 assert_eq!(left_pane_id, active_pane.entity_id());
10074 assert_eq!(4, active_pane.read(cx).items_len());
10075 let item_ids_in_pane =
10076 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
10077 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
10078 assert!(item_ids_in_pane.contains(&right_item.item_id()));
10079 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
10080 assert!(item_ids_in_pane.contains(&left_item.item_id()));
10081
10082 // Join into next from left pane into top
10083 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
10084 });
10085
10086 workspace.update_in(cx, |workspace, window, cx| {
10087 let active_pane = workspace.active_pane();
10088 assert_eq!(top_pane_id, active_pane.entity_id());
10089 assert_eq!(5, active_pane.read(cx).items_len());
10090 let item_ids_in_pane =
10091 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
10092 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
10093 assert!(item_ids_in_pane.contains(&right_item.item_id()));
10094 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
10095 assert!(item_ids_in_pane.contains(&left_item.item_id()));
10096 assert!(item_ids_in_pane.contains(&top_item.item_id()));
10097
10098 // Single pane left: no-op
10099 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
10100 });
10101
10102 workspace.update(cx, |workspace, _cx| {
10103 let active_pane = workspace.active_pane();
10104 assert_eq!(top_pane_id, active_pane.entity_id());
10105 });
10106 }
10107
10108 fn add_an_item_to_active_pane(
10109 cx: &mut VisualTestContext,
10110 workspace: &Entity<Workspace>,
10111 item_id: u64,
10112 ) -> Entity<TestItem> {
10113 let item = cx.new(|cx| {
10114 TestItem::new(cx).with_project_items(&[TestProjectItem::new(
10115 item_id,
10116 "item{item_id}.txt",
10117 cx,
10118 )])
10119 });
10120 workspace.update_in(cx, |workspace, window, cx| {
10121 workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
10122 });
10123 item
10124 }
10125
10126 fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
10127 workspace.update_in(cx, |workspace, window, cx| {
10128 workspace.split_pane(
10129 workspace.active_pane().clone(),
10130 SplitDirection::Right,
10131 window,
10132 cx,
10133 )
10134 })
10135 }
10136
10137 #[gpui::test]
10138 async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
10139 init_test(cx);
10140 let fs = FakeFs::new(cx.executor());
10141 let project = Project::test(fs, None, cx).await;
10142 let (workspace, cx) =
10143 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10144
10145 add_an_item_to_active_pane(cx, &workspace, 1);
10146 split_pane(cx, &workspace);
10147 add_an_item_to_active_pane(cx, &workspace, 2);
10148 split_pane(cx, &workspace); // empty pane
10149 split_pane(cx, &workspace);
10150 let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
10151
10152 cx.executor().run_until_parked();
10153
10154 workspace.update(cx, |workspace, cx| {
10155 let num_panes = workspace.panes().len();
10156 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
10157 let active_item = workspace
10158 .active_pane()
10159 .read(cx)
10160 .active_item()
10161 .expect("item is in focus");
10162
10163 assert_eq!(num_panes, 4);
10164 assert_eq!(num_items_in_current_pane, 1);
10165 assert_eq!(active_item.item_id(), last_item.item_id());
10166 });
10167
10168 workspace.update_in(cx, |workspace, window, cx| {
10169 workspace.join_all_panes(window, cx);
10170 });
10171
10172 workspace.update(cx, |workspace, cx| {
10173 let num_panes = workspace.panes().len();
10174 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
10175 let active_item = workspace
10176 .active_pane()
10177 .read(cx)
10178 .active_item()
10179 .expect("item is in focus");
10180
10181 assert_eq!(num_panes, 1);
10182 assert_eq!(num_items_in_current_pane, 3);
10183 assert_eq!(active_item.item_id(), last_item.item_id());
10184 });
10185 }
10186 struct TestModal(FocusHandle);
10187
10188 impl TestModal {
10189 fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
10190 Self(cx.focus_handle())
10191 }
10192 }
10193
10194 impl EventEmitter<DismissEvent> for TestModal {}
10195
10196 impl Focusable for TestModal {
10197 fn focus_handle(&self, _cx: &App) -> FocusHandle {
10198 self.0.clone()
10199 }
10200 }
10201
10202 impl ModalView for TestModal {}
10203
10204 impl Render for TestModal {
10205 fn render(
10206 &mut self,
10207 _window: &mut Window,
10208 _cx: &mut Context<TestModal>,
10209 ) -> impl IntoElement {
10210 div().track_focus(&self.0)
10211 }
10212 }
10213
10214 #[gpui::test]
10215 async fn test_panels(cx: &mut gpui::TestAppContext) {
10216 init_test(cx);
10217 let fs = FakeFs::new(cx.executor());
10218
10219 let project = Project::test(fs, [], cx).await;
10220 let (workspace, cx) =
10221 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10222
10223 let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
10224 let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
10225 workspace.add_panel(panel_1.clone(), window, cx);
10226 workspace.toggle_dock(DockPosition::Left, window, cx);
10227 let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
10228 workspace.add_panel(panel_2.clone(), window, cx);
10229 workspace.toggle_dock(DockPosition::Right, window, cx);
10230
10231 let left_dock = workspace.left_dock();
10232 assert_eq!(
10233 left_dock.read(cx).visible_panel().unwrap().panel_id(),
10234 panel_1.panel_id()
10235 );
10236 assert_eq!(
10237 left_dock.read(cx).active_panel_size(window, cx).unwrap(),
10238 panel_1.size(window, cx)
10239 );
10240
10241 left_dock.update(cx, |left_dock, cx| {
10242 left_dock.resize_active_panel(Some(px(1337.)), window, cx)
10243 });
10244 assert_eq!(
10245 workspace
10246 .right_dock()
10247 .read(cx)
10248 .visible_panel()
10249 .unwrap()
10250 .panel_id(),
10251 panel_2.panel_id(),
10252 );
10253
10254 (panel_1, panel_2)
10255 });
10256
10257 // Move panel_1 to the right
10258 panel_1.update_in(cx, |panel_1, window, cx| {
10259 panel_1.set_position(DockPosition::Right, window, cx)
10260 });
10261
10262 workspace.update_in(cx, |workspace, window, cx| {
10263 // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
10264 // Since it was the only panel on the left, the left dock should now be closed.
10265 assert!(!workspace.left_dock().read(cx).is_open());
10266 assert!(workspace.left_dock().read(cx).visible_panel().is_none());
10267 let right_dock = workspace.right_dock();
10268 assert_eq!(
10269 right_dock.read(cx).visible_panel().unwrap().panel_id(),
10270 panel_1.panel_id()
10271 );
10272 assert_eq!(
10273 right_dock.read(cx).active_panel_size(window, cx).unwrap(),
10274 px(1337.)
10275 );
10276
10277 // Now we move panel_2 to the left
10278 panel_2.set_position(DockPosition::Left, window, cx);
10279 });
10280
10281 workspace.update(cx, |workspace, cx| {
10282 // Since panel_2 was not visible on the right, we don't open the left dock.
10283 assert!(!workspace.left_dock().read(cx).is_open());
10284 // And the right dock is unaffected in its displaying of panel_1
10285 assert!(workspace.right_dock().read(cx).is_open());
10286 assert_eq!(
10287 workspace
10288 .right_dock()
10289 .read(cx)
10290 .visible_panel()
10291 .unwrap()
10292 .panel_id(),
10293 panel_1.panel_id(),
10294 );
10295 });
10296
10297 // Move panel_1 back to the left
10298 panel_1.update_in(cx, |panel_1, window, cx| {
10299 panel_1.set_position(DockPosition::Left, window, cx)
10300 });
10301
10302 workspace.update_in(cx, |workspace, window, cx| {
10303 // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
10304 let left_dock = workspace.left_dock();
10305 assert!(left_dock.read(cx).is_open());
10306 assert_eq!(
10307 left_dock.read(cx).visible_panel().unwrap().panel_id(),
10308 panel_1.panel_id()
10309 );
10310 assert_eq!(
10311 left_dock.read(cx).active_panel_size(window, cx).unwrap(),
10312 px(1337.)
10313 );
10314 // And the right dock should be closed as it no longer has any panels.
10315 assert!(!workspace.right_dock().read(cx).is_open());
10316
10317 // Now we move panel_1 to the bottom
10318 panel_1.set_position(DockPosition::Bottom, window, cx);
10319 });
10320
10321 workspace.update_in(cx, |workspace, window, cx| {
10322 // Since panel_1 was visible on the left, we close the left dock.
10323 assert!(!workspace.left_dock().read(cx).is_open());
10324 // The bottom dock is sized based on the panel's default size,
10325 // since the panel orientation changed from vertical to horizontal.
10326 let bottom_dock = workspace.bottom_dock();
10327 assert_eq!(
10328 bottom_dock.read(cx).active_panel_size(window, cx).unwrap(),
10329 panel_1.size(window, cx),
10330 );
10331 // Close bottom dock and move panel_1 back to the left.
10332 bottom_dock.update(cx, |bottom_dock, cx| {
10333 bottom_dock.set_open(false, window, cx)
10334 });
10335 panel_1.set_position(DockPosition::Left, window, cx);
10336 });
10337
10338 // Emit activated event on panel 1
10339 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
10340
10341 // Now the left dock is open and panel_1 is active and focused.
10342 workspace.update_in(cx, |workspace, window, cx| {
10343 let left_dock = workspace.left_dock();
10344 assert!(left_dock.read(cx).is_open());
10345 assert_eq!(
10346 left_dock.read(cx).visible_panel().unwrap().panel_id(),
10347 panel_1.panel_id(),
10348 );
10349 assert!(panel_1.focus_handle(cx).is_focused(window));
10350 });
10351
10352 // Emit closed event on panel 2, which is not active
10353 panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
10354
10355 // Wo don't close the left dock, because panel_2 wasn't the active panel
10356 workspace.update(cx, |workspace, cx| {
10357 let left_dock = workspace.left_dock();
10358 assert!(left_dock.read(cx).is_open());
10359 assert_eq!(
10360 left_dock.read(cx).visible_panel().unwrap().panel_id(),
10361 panel_1.panel_id(),
10362 );
10363 });
10364
10365 // Emitting a ZoomIn event shows the panel as zoomed.
10366 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
10367 workspace.read_with(cx, |workspace, _| {
10368 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
10369 assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
10370 });
10371
10372 // Move panel to another dock while it is zoomed
10373 panel_1.update_in(cx, |panel, window, cx| {
10374 panel.set_position(DockPosition::Right, window, cx)
10375 });
10376 workspace.read_with(cx, |workspace, _| {
10377 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
10378
10379 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
10380 });
10381
10382 // This is a helper for getting a:
10383 // - valid focus on an element,
10384 // - that isn't a part of the panes and panels system of the Workspace,
10385 // - and doesn't trigger the 'on_focus_lost' API.
10386 let focus_other_view = {
10387 let workspace = workspace.clone();
10388 move |cx: &mut VisualTestContext| {
10389 workspace.update_in(cx, |workspace, window, cx| {
10390 if workspace.active_modal::<TestModal>(cx).is_some() {
10391 workspace.toggle_modal(window, cx, TestModal::new);
10392 workspace.toggle_modal(window, cx, TestModal::new);
10393 } else {
10394 workspace.toggle_modal(window, cx, TestModal::new);
10395 }
10396 })
10397 }
10398 };
10399
10400 // If focus is transferred to another view that's not a panel or another pane, we still show
10401 // the panel as zoomed.
10402 focus_other_view(cx);
10403 workspace.read_with(cx, |workspace, _| {
10404 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
10405 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
10406 });
10407
10408 // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
10409 workspace.update_in(cx, |_workspace, window, cx| {
10410 cx.focus_self(window);
10411 });
10412 workspace.read_with(cx, |workspace, _| {
10413 assert_eq!(workspace.zoomed, None);
10414 assert_eq!(workspace.zoomed_position, None);
10415 });
10416
10417 // If focus is transferred again to another view that's not a panel or a pane, we won't
10418 // show the panel as zoomed because it wasn't zoomed before.
10419 focus_other_view(cx);
10420 workspace.read_with(cx, |workspace, _| {
10421 assert_eq!(workspace.zoomed, None);
10422 assert_eq!(workspace.zoomed_position, None);
10423 });
10424
10425 // When the panel is activated, it is zoomed again.
10426 cx.dispatch_action(ToggleRightDock);
10427 workspace.read_with(cx, |workspace, _| {
10428 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
10429 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
10430 });
10431
10432 // Emitting a ZoomOut event unzooms the panel.
10433 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
10434 workspace.read_with(cx, |workspace, _| {
10435 assert_eq!(workspace.zoomed, None);
10436 assert_eq!(workspace.zoomed_position, None);
10437 });
10438
10439 // Emit closed event on panel 1, which is active
10440 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
10441
10442 // Now the left dock is closed, because panel_1 was the active panel
10443 workspace.update(cx, |workspace, cx| {
10444 let right_dock = workspace.right_dock();
10445 assert!(!right_dock.read(cx).is_open());
10446 });
10447 }
10448
10449 #[gpui::test]
10450 async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
10451 init_test(cx);
10452
10453 let fs = FakeFs::new(cx.background_executor.clone());
10454 let project = Project::test(fs, [], cx).await;
10455 let (workspace, cx) =
10456 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10457 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10458
10459 let dirty_regular_buffer = cx.new(|cx| {
10460 TestItem::new(cx)
10461 .with_dirty(true)
10462 .with_label("1.txt")
10463 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10464 });
10465 let dirty_regular_buffer_2 = cx.new(|cx| {
10466 TestItem::new(cx)
10467 .with_dirty(true)
10468 .with_label("2.txt")
10469 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10470 });
10471 let dirty_multi_buffer_with_both = cx.new(|cx| {
10472 TestItem::new(cx)
10473 .with_dirty(true)
10474 .with_buffer_kind(ItemBufferKind::Multibuffer)
10475 .with_label("Fake Project Search")
10476 .with_project_items(&[
10477 dirty_regular_buffer.read(cx).project_items[0].clone(),
10478 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
10479 ])
10480 });
10481 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
10482 workspace.update_in(cx, |workspace, window, cx| {
10483 workspace.add_item(
10484 pane.clone(),
10485 Box::new(dirty_regular_buffer.clone()),
10486 None,
10487 false,
10488 false,
10489 window,
10490 cx,
10491 );
10492 workspace.add_item(
10493 pane.clone(),
10494 Box::new(dirty_regular_buffer_2.clone()),
10495 None,
10496 false,
10497 false,
10498 window,
10499 cx,
10500 );
10501 workspace.add_item(
10502 pane.clone(),
10503 Box::new(dirty_multi_buffer_with_both.clone()),
10504 None,
10505 false,
10506 false,
10507 window,
10508 cx,
10509 );
10510 });
10511
10512 pane.update_in(cx, |pane, window, cx| {
10513 pane.activate_item(2, true, true, window, cx);
10514 assert_eq!(
10515 pane.active_item().unwrap().item_id(),
10516 multi_buffer_with_both_files_id,
10517 "Should select the multi buffer in the pane"
10518 );
10519 });
10520 let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
10521 pane.close_other_items(
10522 &CloseOtherItems {
10523 save_intent: Some(SaveIntent::Save),
10524 close_pinned: true,
10525 },
10526 None,
10527 window,
10528 cx,
10529 )
10530 });
10531 cx.background_executor.run_until_parked();
10532 assert!(!cx.has_pending_prompt());
10533 close_all_but_multi_buffer_task
10534 .await
10535 .expect("Closing all buffers but the multi buffer failed");
10536 pane.update(cx, |pane, cx| {
10537 assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
10538 assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
10539 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
10540 assert_eq!(pane.items_len(), 1);
10541 assert_eq!(
10542 pane.active_item().unwrap().item_id(),
10543 multi_buffer_with_both_files_id,
10544 "Should have only the multi buffer left in the pane"
10545 );
10546 assert!(
10547 dirty_multi_buffer_with_both.read(cx).is_dirty,
10548 "The multi buffer containing the unsaved buffer should still be dirty"
10549 );
10550 });
10551
10552 dirty_regular_buffer.update(cx, |buffer, cx| {
10553 buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
10554 });
10555
10556 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
10557 pane.close_active_item(
10558 &CloseActiveItem {
10559 save_intent: Some(SaveIntent::Close),
10560 close_pinned: false,
10561 },
10562 window,
10563 cx,
10564 )
10565 });
10566 cx.background_executor.run_until_parked();
10567 assert!(
10568 cx.has_pending_prompt(),
10569 "Dirty multi buffer should prompt a save dialog"
10570 );
10571 cx.simulate_prompt_answer("Save");
10572 cx.background_executor.run_until_parked();
10573 close_multi_buffer_task
10574 .await
10575 .expect("Closing the multi buffer failed");
10576 pane.update(cx, |pane, cx| {
10577 assert_eq!(
10578 dirty_multi_buffer_with_both.read(cx).save_count,
10579 1,
10580 "Multi buffer item should get be saved"
10581 );
10582 // Test impl does not save inner items, so we do not assert them
10583 assert_eq!(
10584 pane.items_len(),
10585 0,
10586 "No more items should be left in the pane"
10587 );
10588 assert!(pane.active_item().is_none());
10589 });
10590 }
10591
10592 #[gpui::test]
10593 async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
10594 cx: &mut TestAppContext,
10595 ) {
10596 init_test(cx);
10597
10598 let fs = FakeFs::new(cx.background_executor.clone());
10599 let project = Project::test(fs, [], cx).await;
10600 let (workspace, cx) =
10601 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10602 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10603
10604 let dirty_regular_buffer = cx.new(|cx| {
10605 TestItem::new(cx)
10606 .with_dirty(true)
10607 .with_label("1.txt")
10608 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10609 });
10610 let dirty_regular_buffer_2 = cx.new(|cx| {
10611 TestItem::new(cx)
10612 .with_dirty(true)
10613 .with_label("2.txt")
10614 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10615 });
10616 let clear_regular_buffer = cx.new(|cx| {
10617 TestItem::new(cx)
10618 .with_label("3.txt")
10619 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
10620 });
10621
10622 let dirty_multi_buffer_with_both = cx.new(|cx| {
10623 TestItem::new(cx)
10624 .with_dirty(true)
10625 .with_buffer_kind(ItemBufferKind::Multibuffer)
10626 .with_label("Fake Project Search")
10627 .with_project_items(&[
10628 dirty_regular_buffer.read(cx).project_items[0].clone(),
10629 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
10630 clear_regular_buffer.read(cx).project_items[0].clone(),
10631 ])
10632 });
10633 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
10634 workspace.update_in(cx, |workspace, window, cx| {
10635 workspace.add_item(
10636 pane.clone(),
10637 Box::new(dirty_regular_buffer.clone()),
10638 None,
10639 false,
10640 false,
10641 window,
10642 cx,
10643 );
10644 workspace.add_item(
10645 pane.clone(),
10646 Box::new(dirty_multi_buffer_with_both.clone()),
10647 None,
10648 false,
10649 false,
10650 window,
10651 cx,
10652 );
10653 });
10654
10655 pane.update_in(cx, |pane, window, cx| {
10656 pane.activate_item(1, true, true, window, cx);
10657 assert_eq!(
10658 pane.active_item().unwrap().item_id(),
10659 multi_buffer_with_both_files_id,
10660 "Should select the multi buffer in the pane"
10661 );
10662 });
10663 let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
10664 pane.close_active_item(
10665 &CloseActiveItem {
10666 save_intent: None,
10667 close_pinned: false,
10668 },
10669 window,
10670 cx,
10671 )
10672 });
10673 cx.background_executor.run_until_parked();
10674 assert!(
10675 cx.has_pending_prompt(),
10676 "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
10677 );
10678 }
10679
10680 /// Tests that when `close_on_file_delete` is enabled, files are automatically
10681 /// closed when they are deleted from disk.
10682 #[gpui::test]
10683 async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
10684 init_test(cx);
10685
10686 // Enable the close_on_disk_deletion setting
10687 cx.update_global(|store: &mut SettingsStore, cx| {
10688 store.update_user_settings(cx, |settings| {
10689 settings.workspace.close_on_file_delete = Some(true);
10690 });
10691 });
10692
10693 let fs = FakeFs::new(cx.background_executor.clone());
10694 let project = Project::test(fs, [], cx).await;
10695 let (workspace, cx) =
10696 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10697 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10698
10699 // Create a test item that simulates a file
10700 let item = cx.new(|cx| {
10701 TestItem::new(cx)
10702 .with_label("test.txt")
10703 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
10704 });
10705
10706 // Add item to workspace
10707 workspace.update_in(cx, |workspace, window, cx| {
10708 workspace.add_item(
10709 pane.clone(),
10710 Box::new(item.clone()),
10711 None,
10712 false,
10713 false,
10714 window,
10715 cx,
10716 );
10717 });
10718
10719 // Verify the item is in the pane
10720 pane.read_with(cx, |pane, _| {
10721 assert_eq!(pane.items().count(), 1);
10722 });
10723
10724 // Simulate file deletion by setting the item's deleted state
10725 item.update(cx, |item, _| {
10726 item.set_has_deleted_file(true);
10727 });
10728
10729 // Emit UpdateTab event to trigger the close behavior
10730 cx.run_until_parked();
10731 item.update(cx, |_, cx| {
10732 cx.emit(ItemEvent::UpdateTab);
10733 });
10734
10735 // Allow the close operation to complete
10736 cx.run_until_parked();
10737
10738 // Verify the item was automatically closed
10739 pane.read_with(cx, |pane, _| {
10740 assert_eq!(
10741 pane.items().count(),
10742 0,
10743 "Item should be automatically closed when file is deleted"
10744 );
10745 });
10746 }
10747
10748 /// Tests that when `close_on_file_delete` is disabled (default), files remain
10749 /// open with a strikethrough when they are deleted from disk.
10750 #[gpui::test]
10751 async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
10752 init_test(cx);
10753
10754 // Ensure close_on_disk_deletion is disabled (default)
10755 cx.update_global(|store: &mut SettingsStore, cx| {
10756 store.update_user_settings(cx, |settings| {
10757 settings.workspace.close_on_file_delete = Some(false);
10758 });
10759 });
10760
10761 let fs = FakeFs::new(cx.background_executor.clone());
10762 let project = Project::test(fs, [], cx).await;
10763 let (workspace, cx) =
10764 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10765 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10766
10767 // Create a test item that simulates a file
10768 let item = cx.new(|cx| {
10769 TestItem::new(cx)
10770 .with_label("test.txt")
10771 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
10772 });
10773
10774 // Add item to workspace
10775 workspace.update_in(cx, |workspace, window, cx| {
10776 workspace.add_item(
10777 pane.clone(),
10778 Box::new(item.clone()),
10779 None,
10780 false,
10781 false,
10782 window,
10783 cx,
10784 );
10785 });
10786
10787 // Verify the item is in the pane
10788 pane.read_with(cx, |pane, _| {
10789 assert_eq!(pane.items().count(), 1);
10790 });
10791
10792 // Simulate file deletion
10793 item.update(cx, |item, _| {
10794 item.set_has_deleted_file(true);
10795 });
10796
10797 // Emit UpdateTab event
10798 cx.run_until_parked();
10799 item.update(cx, |_, cx| {
10800 cx.emit(ItemEvent::UpdateTab);
10801 });
10802
10803 // Allow any potential close operation to complete
10804 cx.run_until_parked();
10805
10806 // Verify the item remains open (with strikethrough)
10807 pane.read_with(cx, |pane, _| {
10808 assert_eq!(
10809 pane.items().count(),
10810 1,
10811 "Item should remain open when close_on_disk_deletion is disabled"
10812 );
10813 });
10814
10815 // Verify the item shows as deleted
10816 item.read_with(cx, |item, _| {
10817 assert!(
10818 item.has_deleted_file,
10819 "Item should be marked as having deleted file"
10820 );
10821 });
10822 }
10823
10824 /// Tests that dirty files are not automatically closed when deleted from disk,
10825 /// even when `close_on_file_delete` is enabled. This ensures users don't lose
10826 /// unsaved changes without being prompted.
10827 #[gpui::test]
10828 async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
10829 init_test(cx);
10830
10831 // Enable the close_on_file_delete setting
10832 cx.update_global(|store: &mut SettingsStore, cx| {
10833 store.update_user_settings(cx, |settings| {
10834 settings.workspace.close_on_file_delete = Some(true);
10835 });
10836 });
10837
10838 let fs = FakeFs::new(cx.background_executor.clone());
10839 let project = Project::test(fs, [], cx).await;
10840 let (workspace, cx) =
10841 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10842 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10843
10844 // Create a dirty test item
10845 let item = cx.new(|cx| {
10846 TestItem::new(cx)
10847 .with_dirty(true)
10848 .with_label("test.txt")
10849 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
10850 });
10851
10852 // Add item to workspace
10853 workspace.update_in(cx, |workspace, window, cx| {
10854 workspace.add_item(
10855 pane.clone(),
10856 Box::new(item.clone()),
10857 None,
10858 false,
10859 false,
10860 window,
10861 cx,
10862 );
10863 });
10864
10865 // Simulate file deletion
10866 item.update(cx, |item, _| {
10867 item.set_has_deleted_file(true);
10868 });
10869
10870 // Emit UpdateTab event to trigger the close behavior
10871 cx.run_until_parked();
10872 item.update(cx, |_, cx| {
10873 cx.emit(ItemEvent::UpdateTab);
10874 });
10875
10876 // Allow any potential close operation to complete
10877 cx.run_until_parked();
10878
10879 // Verify the item remains open (dirty files are not auto-closed)
10880 pane.read_with(cx, |pane, _| {
10881 assert_eq!(
10882 pane.items().count(),
10883 1,
10884 "Dirty items should not be automatically closed even when file is deleted"
10885 );
10886 });
10887
10888 // Verify the item is marked as deleted and still dirty
10889 item.read_with(cx, |item, _| {
10890 assert!(
10891 item.has_deleted_file,
10892 "Item should be marked as having deleted file"
10893 );
10894 assert!(item.is_dirty, "Item should still be dirty");
10895 });
10896 }
10897
10898 /// Tests that navigation history is cleaned up when files are auto-closed
10899 /// due to deletion from disk.
10900 #[gpui::test]
10901 async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
10902 init_test(cx);
10903
10904 // Enable the close_on_file_delete setting
10905 cx.update_global(|store: &mut SettingsStore, cx| {
10906 store.update_user_settings(cx, |settings| {
10907 settings.workspace.close_on_file_delete = Some(true);
10908 });
10909 });
10910
10911 let fs = FakeFs::new(cx.background_executor.clone());
10912 let project = Project::test(fs, [], cx).await;
10913 let (workspace, cx) =
10914 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10915 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10916
10917 // Create test items
10918 let item1 = cx.new(|cx| {
10919 TestItem::new(cx)
10920 .with_label("test1.txt")
10921 .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
10922 });
10923 let item1_id = item1.item_id();
10924
10925 let item2 = cx.new(|cx| {
10926 TestItem::new(cx)
10927 .with_label("test2.txt")
10928 .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
10929 });
10930
10931 // Add items to workspace
10932 workspace.update_in(cx, |workspace, window, cx| {
10933 workspace.add_item(
10934 pane.clone(),
10935 Box::new(item1.clone()),
10936 None,
10937 false,
10938 false,
10939 window,
10940 cx,
10941 );
10942 workspace.add_item(
10943 pane.clone(),
10944 Box::new(item2.clone()),
10945 None,
10946 false,
10947 false,
10948 window,
10949 cx,
10950 );
10951 });
10952
10953 // Activate item1 to ensure it gets navigation entries
10954 pane.update_in(cx, |pane, window, cx| {
10955 pane.activate_item(0, true, true, window, cx);
10956 });
10957
10958 // Switch to item2 and back to create navigation history
10959 pane.update_in(cx, |pane, window, cx| {
10960 pane.activate_item(1, true, true, window, cx);
10961 });
10962 cx.run_until_parked();
10963
10964 pane.update_in(cx, |pane, window, cx| {
10965 pane.activate_item(0, true, true, window, cx);
10966 });
10967 cx.run_until_parked();
10968
10969 // Simulate file deletion for item1
10970 item1.update(cx, |item, _| {
10971 item.set_has_deleted_file(true);
10972 });
10973
10974 // Emit UpdateTab event to trigger the close behavior
10975 item1.update(cx, |_, cx| {
10976 cx.emit(ItemEvent::UpdateTab);
10977 });
10978 cx.run_until_parked();
10979
10980 // Verify item1 was closed
10981 pane.read_with(cx, |pane, _| {
10982 assert_eq!(
10983 pane.items().count(),
10984 1,
10985 "Should have 1 item remaining after auto-close"
10986 );
10987 });
10988
10989 // Check navigation history after close
10990 let has_item = pane.read_with(cx, |pane, cx| {
10991 let mut has_item = false;
10992 pane.nav_history().for_each_entry(cx, |entry, _| {
10993 if entry.item.id() == item1_id {
10994 has_item = true;
10995 }
10996 });
10997 has_item
10998 });
10999
11000 assert!(
11001 !has_item,
11002 "Navigation history should not contain closed item entries"
11003 );
11004 }
11005
11006 #[gpui::test]
11007 async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
11008 cx: &mut TestAppContext,
11009 ) {
11010 init_test(cx);
11011
11012 let fs = FakeFs::new(cx.background_executor.clone());
11013 let project = Project::test(fs, [], cx).await;
11014 let (workspace, cx) =
11015 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11016 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11017
11018 let dirty_regular_buffer = cx.new(|cx| {
11019 TestItem::new(cx)
11020 .with_dirty(true)
11021 .with_label("1.txt")
11022 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
11023 });
11024 let dirty_regular_buffer_2 = cx.new(|cx| {
11025 TestItem::new(cx)
11026 .with_dirty(true)
11027 .with_label("2.txt")
11028 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
11029 });
11030 let clear_regular_buffer = cx.new(|cx| {
11031 TestItem::new(cx)
11032 .with_label("3.txt")
11033 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
11034 });
11035
11036 let dirty_multi_buffer = cx.new(|cx| {
11037 TestItem::new(cx)
11038 .with_dirty(true)
11039 .with_buffer_kind(ItemBufferKind::Multibuffer)
11040 .with_label("Fake Project Search")
11041 .with_project_items(&[
11042 dirty_regular_buffer.read(cx).project_items[0].clone(),
11043 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
11044 clear_regular_buffer.read(cx).project_items[0].clone(),
11045 ])
11046 });
11047 workspace.update_in(cx, |workspace, window, cx| {
11048 workspace.add_item(
11049 pane.clone(),
11050 Box::new(dirty_regular_buffer.clone()),
11051 None,
11052 false,
11053 false,
11054 window,
11055 cx,
11056 );
11057 workspace.add_item(
11058 pane.clone(),
11059 Box::new(dirty_regular_buffer_2.clone()),
11060 None,
11061 false,
11062 false,
11063 window,
11064 cx,
11065 );
11066 workspace.add_item(
11067 pane.clone(),
11068 Box::new(dirty_multi_buffer.clone()),
11069 None,
11070 false,
11071 false,
11072 window,
11073 cx,
11074 );
11075 });
11076
11077 pane.update_in(cx, |pane, window, cx| {
11078 pane.activate_item(2, true, true, window, cx);
11079 assert_eq!(
11080 pane.active_item().unwrap().item_id(),
11081 dirty_multi_buffer.item_id(),
11082 "Should select the multi buffer in the pane"
11083 );
11084 });
11085 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
11086 pane.close_active_item(
11087 &CloseActiveItem {
11088 save_intent: None,
11089 close_pinned: false,
11090 },
11091 window,
11092 cx,
11093 )
11094 });
11095 cx.background_executor.run_until_parked();
11096 assert!(
11097 !cx.has_pending_prompt(),
11098 "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
11099 );
11100 close_multi_buffer_task
11101 .await
11102 .expect("Closing multi buffer failed");
11103 pane.update(cx, |pane, cx| {
11104 assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
11105 assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
11106 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
11107 assert_eq!(
11108 pane.items()
11109 .map(|item| item.item_id())
11110 .sorted()
11111 .collect::<Vec<_>>(),
11112 vec![
11113 dirty_regular_buffer.item_id(),
11114 dirty_regular_buffer_2.item_id(),
11115 ],
11116 "Should have no multi buffer left in the pane"
11117 );
11118 assert!(dirty_regular_buffer.read(cx).is_dirty);
11119 assert!(dirty_regular_buffer_2.read(cx).is_dirty);
11120 });
11121 }
11122
11123 #[gpui::test]
11124 async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
11125 init_test(cx);
11126 let fs = FakeFs::new(cx.executor());
11127 let project = Project::test(fs, [], cx).await;
11128 let (workspace, cx) =
11129 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11130
11131 // Add a new panel to the right dock, opening the dock and setting the
11132 // focus to the new panel.
11133 let panel = workspace.update_in(cx, |workspace, window, cx| {
11134 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11135 workspace.add_panel(panel.clone(), window, cx);
11136
11137 workspace
11138 .right_dock()
11139 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
11140
11141 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11142
11143 panel
11144 });
11145
11146 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
11147 // panel to the next valid position which, in this case, is the left
11148 // dock.
11149 cx.dispatch_action(MoveFocusedPanelToNextPosition);
11150 workspace.update(cx, |workspace, cx| {
11151 assert!(workspace.left_dock().read(cx).is_open());
11152 assert_eq!(panel.read(cx).position, DockPosition::Left);
11153 });
11154
11155 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
11156 // panel to the next valid position which, in this case, is the bottom
11157 // dock.
11158 cx.dispatch_action(MoveFocusedPanelToNextPosition);
11159 workspace.update(cx, |workspace, cx| {
11160 assert!(workspace.bottom_dock().read(cx).is_open());
11161 assert_eq!(panel.read(cx).position, DockPosition::Bottom);
11162 });
11163
11164 // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
11165 // around moving the panel to its initial position, the right dock.
11166 cx.dispatch_action(MoveFocusedPanelToNextPosition);
11167 workspace.update(cx, |workspace, cx| {
11168 assert!(workspace.right_dock().read(cx).is_open());
11169 assert_eq!(panel.read(cx).position, DockPosition::Right);
11170 });
11171
11172 // Remove focus from the panel, ensuring that, if the panel is not
11173 // focused, the `MoveFocusedPanelToNextPosition` action does not update
11174 // the panel's position, so the panel is still in the right dock.
11175 workspace.update_in(cx, |workspace, window, cx| {
11176 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11177 });
11178
11179 cx.dispatch_action(MoveFocusedPanelToNextPosition);
11180 workspace.update(cx, |workspace, cx| {
11181 assert!(workspace.right_dock().read(cx).is_open());
11182 assert_eq!(panel.read(cx).position, DockPosition::Right);
11183 });
11184 }
11185
11186 #[gpui::test]
11187 async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
11188 init_test(cx);
11189
11190 let fs = FakeFs::new(cx.executor());
11191 let project = Project::test(fs, [], cx).await;
11192 let (workspace, cx) =
11193 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
11194
11195 let item_1 = cx.new(|cx| {
11196 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
11197 });
11198 workspace.update_in(cx, |workspace, window, cx| {
11199 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
11200 workspace.move_item_to_pane_in_direction(
11201 &MoveItemToPaneInDirection {
11202 direction: SplitDirection::Right,
11203 focus: true,
11204 clone: false,
11205 },
11206 window,
11207 cx,
11208 );
11209 workspace.move_item_to_pane_at_index(
11210 &MoveItemToPane {
11211 destination: 3,
11212 focus: true,
11213 clone: false,
11214 },
11215 window,
11216 cx,
11217 );
11218
11219 assert_eq!(workspace.panes.len(), 1, "No new panes were created");
11220 assert_eq!(
11221 pane_items_paths(&workspace.active_pane, cx),
11222 vec!["first.txt".to_string()],
11223 "Single item was not moved anywhere"
11224 );
11225 });
11226
11227 let item_2 = cx.new(|cx| {
11228 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
11229 });
11230 workspace.update_in(cx, |workspace, window, cx| {
11231 workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
11232 assert_eq!(
11233 pane_items_paths(&workspace.panes[0], cx),
11234 vec!["first.txt".to_string(), "second.txt".to_string()],
11235 );
11236 workspace.move_item_to_pane_in_direction(
11237 &MoveItemToPaneInDirection {
11238 direction: SplitDirection::Right,
11239 focus: true,
11240 clone: false,
11241 },
11242 window,
11243 cx,
11244 );
11245
11246 assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
11247 assert_eq!(
11248 pane_items_paths(&workspace.panes[0], cx),
11249 vec!["first.txt".to_string()],
11250 "After moving, one item should be left in the original pane"
11251 );
11252 assert_eq!(
11253 pane_items_paths(&workspace.panes[1], cx),
11254 vec!["second.txt".to_string()],
11255 "New item should have been moved to the new pane"
11256 );
11257 });
11258
11259 let item_3 = cx.new(|cx| {
11260 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
11261 });
11262 workspace.update_in(cx, |workspace, window, cx| {
11263 let original_pane = workspace.panes[0].clone();
11264 workspace.set_active_pane(&original_pane, window, cx);
11265 workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
11266 assert_eq!(workspace.panes.len(), 2, "No new panes were created");
11267 assert_eq!(
11268 pane_items_paths(&workspace.active_pane, cx),
11269 vec!["first.txt".to_string(), "third.txt".to_string()],
11270 "New pane should be ready to move one item out"
11271 );
11272
11273 workspace.move_item_to_pane_at_index(
11274 &MoveItemToPane {
11275 destination: 3,
11276 focus: true,
11277 clone: false,
11278 },
11279 window,
11280 cx,
11281 );
11282 assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
11283 assert_eq!(
11284 pane_items_paths(&workspace.active_pane, cx),
11285 vec!["first.txt".to_string()],
11286 "After moving, one item should be left in the original pane"
11287 );
11288 assert_eq!(
11289 pane_items_paths(&workspace.panes[1], cx),
11290 vec!["second.txt".to_string()],
11291 "Previously created pane should be unchanged"
11292 );
11293 assert_eq!(
11294 pane_items_paths(&workspace.panes[2], cx),
11295 vec!["third.txt".to_string()],
11296 "New item should have been moved to the new pane"
11297 );
11298 });
11299 }
11300
11301 #[gpui::test]
11302 async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
11303 init_test(cx);
11304
11305 let fs = FakeFs::new(cx.executor());
11306 let project = Project::test(fs, [], cx).await;
11307 let (workspace, cx) =
11308 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
11309
11310 let item_1 = cx.new(|cx| {
11311 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
11312 });
11313 workspace.update_in(cx, |workspace, window, cx| {
11314 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
11315 workspace.move_item_to_pane_in_direction(
11316 &MoveItemToPaneInDirection {
11317 direction: SplitDirection::Right,
11318 focus: true,
11319 clone: true,
11320 },
11321 window,
11322 cx,
11323 );
11324 workspace.move_item_to_pane_at_index(
11325 &MoveItemToPane {
11326 destination: 3,
11327 focus: true,
11328 clone: true,
11329 },
11330 window,
11331 cx,
11332 );
11333 });
11334 cx.run_until_parked();
11335
11336 workspace.update(cx, |workspace, cx| {
11337 assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
11338 for pane in workspace.panes() {
11339 assert_eq!(
11340 pane_items_paths(pane, cx),
11341 vec!["first.txt".to_string()],
11342 "Single item exists in all panes"
11343 );
11344 }
11345 });
11346
11347 // verify that the active pane has been updated after waiting for the
11348 // pane focus event to fire and resolve
11349 workspace.read_with(cx, |workspace, _app| {
11350 assert_eq!(
11351 workspace.active_pane(),
11352 &workspace.panes[2],
11353 "The third pane should be the active one: {:?}",
11354 workspace.panes
11355 );
11356 })
11357 }
11358
11359 mod register_project_item_tests {
11360
11361 use super::*;
11362
11363 // View
11364 struct TestPngItemView {
11365 focus_handle: FocusHandle,
11366 }
11367 // Model
11368 struct TestPngItem {}
11369
11370 impl project::ProjectItem for TestPngItem {
11371 fn try_open(
11372 _project: &Entity<Project>,
11373 path: &ProjectPath,
11374 cx: &mut App,
11375 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
11376 if path.path.extension().unwrap() == "png" {
11377 Some(cx.spawn(async move |cx| cx.new(|_| TestPngItem {})))
11378 } else {
11379 None
11380 }
11381 }
11382
11383 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
11384 None
11385 }
11386
11387 fn project_path(&self, _: &App) -> Option<ProjectPath> {
11388 None
11389 }
11390
11391 fn is_dirty(&self) -> bool {
11392 false
11393 }
11394 }
11395
11396 impl Item for TestPngItemView {
11397 type Event = ();
11398 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
11399 "".into()
11400 }
11401 }
11402 impl EventEmitter<()> for TestPngItemView {}
11403 impl Focusable for TestPngItemView {
11404 fn focus_handle(&self, _cx: &App) -> FocusHandle {
11405 self.focus_handle.clone()
11406 }
11407 }
11408
11409 impl Render for TestPngItemView {
11410 fn render(
11411 &mut self,
11412 _window: &mut Window,
11413 _cx: &mut Context<Self>,
11414 ) -> impl IntoElement {
11415 Empty
11416 }
11417 }
11418
11419 impl ProjectItem for TestPngItemView {
11420 type Item = TestPngItem;
11421
11422 fn for_project_item(
11423 _project: Entity<Project>,
11424 _pane: Option<&Pane>,
11425 _item: Entity<Self::Item>,
11426 _: &mut Window,
11427 cx: &mut Context<Self>,
11428 ) -> Self
11429 where
11430 Self: Sized,
11431 {
11432 Self {
11433 focus_handle: cx.focus_handle(),
11434 }
11435 }
11436 }
11437
11438 // View
11439 struct TestIpynbItemView {
11440 focus_handle: FocusHandle,
11441 }
11442 // Model
11443 struct TestIpynbItem {}
11444
11445 impl project::ProjectItem for TestIpynbItem {
11446 fn try_open(
11447 _project: &Entity<Project>,
11448 path: &ProjectPath,
11449 cx: &mut App,
11450 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
11451 if path.path.extension().unwrap() == "ipynb" {
11452 Some(cx.spawn(async move |cx| cx.new(|_| TestIpynbItem {})))
11453 } else {
11454 None
11455 }
11456 }
11457
11458 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
11459 None
11460 }
11461
11462 fn project_path(&self, _: &App) -> Option<ProjectPath> {
11463 None
11464 }
11465
11466 fn is_dirty(&self) -> bool {
11467 false
11468 }
11469 }
11470
11471 impl Item for TestIpynbItemView {
11472 type Event = ();
11473 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
11474 "".into()
11475 }
11476 }
11477 impl EventEmitter<()> for TestIpynbItemView {}
11478 impl Focusable for TestIpynbItemView {
11479 fn focus_handle(&self, _cx: &App) -> FocusHandle {
11480 self.focus_handle.clone()
11481 }
11482 }
11483
11484 impl Render for TestIpynbItemView {
11485 fn render(
11486 &mut self,
11487 _window: &mut Window,
11488 _cx: &mut Context<Self>,
11489 ) -> impl IntoElement {
11490 Empty
11491 }
11492 }
11493
11494 impl ProjectItem for TestIpynbItemView {
11495 type Item = TestIpynbItem;
11496
11497 fn for_project_item(
11498 _project: Entity<Project>,
11499 _pane: Option<&Pane>,
11500 _item: Entity<Self::Item>,
11501 _: &mut Window,
11502 cx: &mut Context<Self>,
11503 ) -> Self
11504 where
11505 Self: Sized,
11506 {
11507 Self {
11508 focus_handle: cx.focus_handle(),
11509 }
11510 }
11511 }
11512
11513 struct TestAlternatePngItemView {
11514 focus_handle: FocusHandle,
11515 }
11516
11517 impl Item for TestAlternatePngItemView {
11518 type Event = ();
11519 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
11520 "".into()
11521 }
11522 }
11523
11524 impl EventEmitter<()> for TestAlternatePngItemView {}
11525 impl Focusable for TestAlternatePngItemView {
11526 fn focus_handle(&self, _cx: &App) -> FocusHandle {
11527 self.focus_handle.clone()
11528 }
11529 }
11530
11531 impl Render for TestAlternatePngItemView {
11532 fn render(
11533 &mut self,
11534 _window: &mut Window,
11535 _cx: &mut Context<Self>,
11536 ) -> impl IntoElement {
11537 Empty
11538 }
11539 }
11540
11541 impl ProjectItem for TestAlternatePngItemView {
11542 type Item = TestPngItem;
11543
11544 fn for_project_item(
11545 _project: Entity<Project>,
11546 _pane: Option<&Pane>,
11547 _item: Entity<Self::Item>,
11548 _: &mut Window,
11549 cx: &mut Context<Self>,
11550 ) -> Self
11551 where
11552 Self: Sized,
11553 {
11554 Self {
11555 focus_handle: cx.focus_handle(),
11556 }
11557 }
11558 }
11559
11560 #[gpui::test]
11561 async fn test_register_project_item(cx: &mut TestAppContext) {
11562 init_test(cx);
11563
11564 cx.update(|cx| {
11565 register_project_item::<TestPngItemView>(cx);
11566 register_project_item::<TestIpynbItemView>(cx);
11567 });
11568
11569 let fs = FakeFs::new(cx.executor());
11570 fs.insert_tree(
11571 "/root1",
11572 json!({
11573 "one.png": "BINARYDATAHERE",
11574 "two.ipynb": "{ totally a notebook }",
11575 "three.txt": "editing text, sure why not?"
11576 }),
11577 )
11578 .await;
11579
11580 let project = Project::test(fs, ["root1".as_ref()], cx).await;
11581 let (workspace, cx) =
11582 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
11583
11584 let worktree_id = project.update(cx, |project, cx| {
11585 project.worktrees(cx).next().unwrap().read(cx).id()
11586 });
11587
11588 let handle = workspace
11589 .update_in(cx, |workspace, window, cx| {
11590 let project_path = (worktree_id, rel_path("one.png"));
11591 workspace.open_path(project_path, None, true, window, cx)
11592 })
11593 .await
11594 .unwrap();
11595
11596 // Now we can check if the handle we got back errored or not
11597 assert_eq!(
11598 handle.to_any_view().entity_type(),
11599 TypeId::of::<TestPngItemView>()
11600 );
11601
11602 let handle = workspace
11603 .update_in(cx, |workspace, window, cx| {
11604 let project_path = (worktree_id, rel_path("two.ipynb"));
11605 workspace.open_path(project_path, None, true, window, cx)
11606 })
11607 .await
11608 .unwrap();
11609
11610 assert_eq!(
11611 handle.to_any_view().entity_type(),
11612 TypeId::of::<TestIpynbItemView>()
11613 );
11614
11615 let handle = workspace
11616 .update_in(cx, |workspace, window, cx| {
11617 let project_path = (worktree_id, rel_path("three.txt"));
11618 workspace.open_path(project_path, None, true, window, cx)
11619 })
11620 .await;
11621 assert!(handle.is_err());
11622 }
11623
11624 #[gpui::test]
11625 async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
11626 init_test(cx);
11627
11628 cx.update(|cx| {
11629 register_project_item::<TestPngItemView>(cx);
11630 register_project_item::<TestAlternatePngItemView>(cx);
11631 });
11632
11633 let fs = FakeFs::new(cx.executor());
11634 fs.insert_tree(
11635 "/root1",
11636 json!({
11637 "one.png": "BINARYDATAHERE",
11638 "two.ipynb": "{ totally a notebook }",
11639 "three.txt": "editing text, sure why not?"
11640 }),
11641 )
11642 .await;
11643 let project = Project::test(fs, ["root1".as_ref()], cx).await;
11644 let (workspace, cx) =
11645 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
11646 let worktree_id = project.update(cx, |project, cx| {
11647 project.worktrees(cx).next().unwrap().read(cx).id()
11648 });
11649
11650 let handle = workspace
11651 .update_in(cx, |workspace, window, cx| {
11652 let project_path = (worktree_id, rel_path("one.png"));
11653 workspace.open_path(project_path, None, true, window, cx)
11654 })
11655 .await
11656 .unwrap();
11657
11658 // This _must_ be the second item registered
11659 assert_eq!(
11660 handle.to_any_view().entity_type(),
11661 TypeId::of::<TestAlternatePngItemView>()
11662 );
11663
11664 let handle = workspace
11665 .update_in(cx, |workspace, window, cx| {
11666 let project_path = (worktree_id, rel_path("three.txt"));
11667 workspace.open_path(project_path, None, true, window, cx)
11668 })
11669 .await;
11670 assert!(handle.is_err());
11671 }
11672 }
11673
11674 #[gpui::test]
11675 async fn test_status_bar_visibility(cx: &mut TestAppContext) {
11676 init_test(cx);
11677
11678 let fs = FakeFs::new(cx.executor());
11679 let project = Project::test(fs, [], cx).await;
11680 let (workspace, _cx) =
11681 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
11682
11683 // Test with status bar shown (default)
11684 workspace.read_with(cx, |workspace, cx| {
11685 let visible = workspace.status_bar_visible(cx);
11686 assert!(visible, "Status bar should be visible by default");
11687 });
11688
11689 // Test with status bar hidden
11690 cx.update_global(|store: &mut SettingsStore, cx| {
11691 store.update_user_settings(cx, |settings| {
11692 settings.status_bar.get_or_insert_default().show = Some(false);
11693 });
11694 });
11695
11696 workspace.read_with(cx, |workspace, cx| {
11697 let visible = workspace.status_bar_visible(cx);
11698 assert!(!visible, "Status bar should be hidden when show is false");
11699 });
11700
11701 // Test with status bar shown explicitly
11702 cx.update_global(|store: &mut SettingsStore, cx| {
11703 store.update_user_settings(cx, |settings| {
11704 settings.status_bar.get_or_insert_default().show = Some(true);
11705 });
11706 });
11707
11708 workspace.read_with(cx, |workspace, cx| {
11709 let visible = workspace.status_bar_visible(cx);
11710 assert!(visible, "Status bar should be visible when show is true");
11711 });
11712 }
11713
11714 fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
11715 pane.read(cx)
11716 .items()
11717 .flat_map(|item| {
11718 item.project_paths(cx)
11719 .into_iter()
11720 .map(|path| path.path.display(PathStyle::local()).into_owned())
11721 })
11722 .collect()
11723 }
11724
11725 pub fn init_test(cx: &mut TestAppContext) {
11726 cx.update(|cx| {
11727 let settings_store = SettingsStore::test(cx);
11728 cx.set_global(settings_store);
11729 theme::init(theme::LoadThemes::JustBase, cx);
11730 });
11731 }
11732
11733 fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
11734 let item = TestProjectItem::new(id, path, cx);
11735 item.update(cx, |item, _| {
11736 item.is_dirty = true;
11737 });
11738 item
11739 }
11740}