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