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