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