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