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