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