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