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 ]
7241);
7242actions!(
7243 zed,
7244 [
7245 /// Opens the Zed log file.
7246 OpenLog,
7247 /// Reveals the Zed log file in the system file manager.
7248 RevealLogInFileManager
7249 ]
7250);
7251
7252async fn join_channel_internal(
7253 channel_id: ChannelId,
7254 app_state: &Arc<AppState>,
7255 requesting_window: Option<WindowHandle<Workspace>>,
7256 active_call: &Entity<ActiveCall>,
7257 cx: &mut AsyncApp,
7258) -> Result<bool> {
7259 let (should_prompt, open_room) = active_call.update(cx, |active_call, cx| {
7260 let Some(room) = active_call.room().map(|room| room.read(cx)) else {
7261 return (false, None);
7262 };
7263
7264 let already_in_channel = room.channel_id() == Some(channel_id);
7265 let should_prompt = room.is_sharing_project()
7266 && !room.remote_participants().is_empty()
7267 && !already_in_channel;
7268 let open_room = if already_in_channel {
7269 active_call.room().cloned()
7270 } else {
7271 None
7272 };
7273 (should_prompt, open_room)
7274 })?;
7275
7276 if let Some(room) = open_room {
7277 let task = room.update(cx, |room, cx| {
7278 if let Some((project, host)) = room.most_active_project(cx) {
7279 return Some(join_in_room_project(project, host, app_state.clone(), cx));
7280 }
7281
7282 None
7283 })?;
7284 if let Some(task) = task {
7285 task.await?;
7286 }
7287 return anyhow::Ok(true);
7288 }
7289
7290 if should_prompt {
7291 if let Some(workspace) = requesting_window {
7292 let answer = workspace
7293 .update(cx, |_, window, cx| {
7294 window.prompt(
7295 PromptLevel::Warning,
7296 "Do you want to switch channels?",
7297 Some("Leaving this call will unshare your current project."),
7298 &["Yes, Join Channel", "Cancel"],
7299 cx,
7300 )
7301 })?
7302 .await;
7303
7304 if answer == Ok(1) {
7305 return Ok(false);
7306 }
7307 } else {
7308 return Ok(false); // unreachable!() hopefully
7309 }
7310 }
7311
7312 let client = cx.update(|cx| active_call.read(cx).client())?;
7313
7314 let mut client_status = client.status();
7315
7316 // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
7317 'outer: loop {
7318 let Some(status) = client_status.recv().await else {
7319 anyhow::bail!("error connecting");
7320 };
7321
7322 match status {
7323 Status::Connecting
7324 | Status::Authenticating
7325 | Status::Authenticated
7326 | Status::Reconnecting
7327 | Status::Reauthenticating
7328 | Status::Reauthenticated => continue,
7329 Status::Connected { .. } => break 'outer,
7330 Status::SignedOut | Status::AuthenticationError => {
7331 return Err(ErrorCode::SignedOut.into());
7332 }
7333 Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
7334 Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
7335 return Err(ErrorCode::Disconnected.into());
7336 }
7337 }
7338 }
7339
7340 let room = active_call
7341 .update(cx, |active_call, cx| {
7342 active_call.join_channel(channel_id, cx)
7343 })?
7344 .await?;
7345
7346 let Some(room) = room else {
7347 return anyhow::Ok(true);
7348 };
7349
7350 room.update(cx, |room, _| room.room_update_completed())?
7351 .await;
7352
7353 let task = room.update(cx, |room, cx| {
7354 if let Some((project, host)) = room.most_active_project(cx) {
7355 return Some(join_in_room_project(project, host, app_state.clone(), cx));
7356 }
7357
7358 // If you are the first to join a channel, see if you should share your project.
7359 if room.remote_participants().is_empty()
7360 && !room.local_participant_is_guest()
7361 && let Some(workspace) = requesting_window
7362 {
7363 let project = workspace.update(cx, |workspace, _, cx| {
7364 let project = workspace.project.read(cx);
7365
7366 if !CallSettings::get_global(cx).share_on_join {
7367 return None;
7368 }
7369
7370 if (project.is_local() || project.is_via_remote_server())
7371 && project.visible_worktrees(cx).any(|tree| {
7372 tree.read(cx)
7373 .root_entry()
7374 .is_some_and(|entry| entry.is_dir())
7375 })
7376 {
7377 Some(workspace.project.clone())
7378 } else {
7379 None
7380 }
7381 });
7382 if let Ok(Some(project)) = project {
7383 return Some(cx.spawn(async move |room, cx| {
7384 room.update(cx, |room, cx| room.share_project(project, cx))?
7385 .await?;
7386 Ok(())
7387 }));
7388 }
7389 }
7390
7391 None
7392 })?;
7393 if let Some(task) = task {
7394 task.await?;
7395 return anyhow::Ok(true);
7396 }
7397 anyhow::Ok(false)
7398}
7399
7400pub fn join_channel(
7401 channel_id: ChannelId,
7402 app_state: Arc<AppState>,
7403 requesting_window: Option<WindowHandle<Workspace>>,
7404 cx: &mut App,
7405) -> Task<Result<()>> {
7406 let active_call = ActiveCall::global(cx);
7407 cx.spawn(async move |cx| {
7408 let result =
7409 join_channel_internal(channel_id, &app_state, requesting_window, &active_call, cx)
7410 .await;
7411
7412 // join channel succeeded, and opened a window
7413 if matches!(result, Ok(true)) {
7414 return anyhow::Ok(());
7415 }
7416
7417 // find an existing workspace to focus and show call controls
7418 let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
7419 if active_window.is_none() {
7420 // no open workspaces, make one to show the error in (blergh)
7421 let (window_handle, _) = cx
7422 .update(|cx| {
7423 Workspace::new_local(vec![], app_state.clone(), requesting_window, None, cx)
7424 })?
7425 .await?;
7426
7427 if result.is_ok() {
7428 cx.update(|cx| {
7429 cx.dispatch_action(&OpenChannelNotes);
7430 })
7431 .log_err();
7432 }
7433
7434 active_window = Some(window_handle);
7435 }
7436
7437 if let Err(err) = result {
7438 log::error!("failed to join channel: {}", err);
7439 if let Some(active_window) = active_window {
7440 active_window
7441 .update(cx, |_, window, cx| {
7442 let detail: SharedString = match err.error_code() {
7443 ErrorCode::SignedOut => "Please sign in to continue.".into(),
7444 ErrorCode::UpgradeRequired => concat!(
7445 "Your are running an unsupported version of Zed. ",
7446 "Please update to continue."
7447 )
7448 .into(),
7449 ErrorCode::NoSuchChannel => concat!(
7450 "No matching channel was found. ",
7451 "Please check the link and try again."
7452 )
7453 .into(),
7454 ErrorCode::Forbidden => concat!(
7455 "This channel is private, and you do not have access. ",
7456 "Please ask someone to add you and try again."
7457 )
7458 .into(),
7459 ErrorCode::Disconnected => {
7460 "Please check your internet connection and try again.".into()
7461 }
7462 _ => format!("{}\n\nPlease try again.", err).into(),
7463 };
7464 window.prompt(
7465 PromptLevel::Critical,
7466 "Failed to join channel",
7467 Some(&detail),
7468 &["Ok"],
7469 cx,
7470 )
7471 })?
7472 .await
7473 .ok();
7474 }
7475 }
7476
7477 // return ok, we showed the error to the user.
7478 anyhow::Ok(())
7479 })
7480}
7481
7482pub async fn get_any_active_workspace(
7483 app_state: Arc<AppState>,
7484 mut cx: AsyncApp,
7485) -> anyhow::Result<WindowHandle<Workspace>> {
7486 // find an existing workspace to focus and show call controls
7487 let active_window = activate_any_workspace_window(&mut cx);
7488 if active_window.is_none() {
7489 cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, cx))?
7490 .await?;
7491 }
7492 activate_any_workspace_window(&mut cx).context("could not open zed")
7493}
7494
7495fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<Workspace>> {
7496 cx.update(|cx| {
7497 if let Some(workspace_window) = cx
7498 .active_window()
7499 .and_then(|window| window.downcast::<Workspace>())
7500 {
7501 return Some(workspace_window);
7502 }
7503
7504 for window in cx.windows() {
7505 if let Some(workspace_window) = window.downcast::<Workspace>() {
7506 workspace_window
7507 .update(cx, |_, window, _| window.activate_window())
7508 .ok();
7509 return Some(workspace_window);
7510 }
7511 }
7512 None
7513 })
7514 .ok()
7515 .flatten()
7516}
7517
7518pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<Workspace>> {
7519 cx.windows()
7520 .into_iter()
7521 .filter_map(|window| window.downcast::<Workspace>())
7522 .filter(|workspace| {
7523 workspace
7524 .read(cx)
7525 .is_ok_and(|workspace| workspace.project.read(cx).is_local())
7526 })
7527 .collect()
7528}
7529
7530#[derive(Default)]
7531pub struct OpenOptions {
7532 pub visible: Option<OpenVisible>,
7533 pub focus: Option<bool>,
7534 pub open_new_workspace: Option<bool>,
7535 pub prefer_focused_window: bool,
7536 pub replace_window: Option<WindowHandle<Workspace>>,
7537 pub env: Option<HashMap<String, String>>,
7538}
7539
7540#[allow(clippy::type_complexity)]
7541pub fn open_paths(
7542 abs_paths: &[PathBuf],
7543 app_state: Arc<AppState>,
7544 open_options: OpenOptions,
7545 cx: &mut App,
7546) -> Task<
7547 anyhow::Result<(
7548 WindowHandle<Workspace>,
7549 Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
7550 )>,
7551> {
7552 let abs_paths = abs_paths.to_vec();
7553 let mut existing = None;
7554 let mut best_match = None;
7555 let mut open_visible = OpenVisible::All;
7556 #[cfg(target_os = "windows")]
7557 let wsl_path = abs_paths
7558 .iter()
7559 .find_map(|p| util::paths::WslPath::from_path(p));
7560
7561 cx.spawn(async move |cx| {
7562 if open_options.open_new_workspace != Some(true) {
7563 let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
7564 let all_metadatas = futures::future::join_all(all_paths)
7565 .await
7566 .into_iter()
7567 .filter_map(|result| result.ok().flatten())
7568 .collect::<Vec<_>>();
7569
7570 cx.update(|cx| {
7571 for window in local_workspace_windows(cx) {
7572 if let Ok(workspace) = window.read(cx) {
7573 let m = workspace.project.read(cx).visibility_for_paths(
7574 &abs_paths,
7575 &all_metadatas,
7576 open_options.open_new_workspace == None,
7577 cx,
7578 );
7579 if m > best_match {
7580 existing = Some(window);
7581 best_match = m;
7582 } else if best_match.is_none()
7583 && open_options.open_new_workspace == Some(false)
7584 {
7585 existing = Some(window)
7586 }
7587 }
7588 }
7589 })?;
7590
7591 if open_options.open_new_workspace.is_none()
7592 && (existing.is_none() || open_options.prefer_focused_window)
7593 && all_metadatas.iter().all(|file| !file.is_dir)
7594 {
7595 cx.update(|cx| {
7596 if let Some(window) = cx
7597 .active_window()
7598 .and_then(|window| window.downcast::<Workspace>())
7599 && let Ok(workspace) = window.read(cx)
7600 {
7601 let project = workspace.project().read(cx);
7602 if project.is_local() && !project.is_via_collab() {
7603 existing = Some(window);
7604 open_visible = OpenVisible::None;
7605 return;
7606 }
7607 }
7608 for window in local_workspace_windows(cx) {
7609 if let Ok(workspace) = window.read(cx) {
7610 let project = workspace.project().read(cx);
7611 if project.is_via_collab() {
7612 continue;
7613 }
7614 existing = Some(window);
7615 open_visible = OpenVisible::None;
7616 break;
7617 }
7618 }
7619 })?;
7620 }
7621 }
7622
7623 let result = if let Some(existing) = existing {
7624 let open_task = existing
7625 .update(cx, |workspace, window, cx| {
7626 window.activate_window();
7627 workspace.open_paths(
7628 abs_paths,
7629 OpenOptions {
7630 visible: Some(open_visible),
7631 ..Default::default()
7632 },
7633 None,
7634 window,
7635 cx,
7636 )
7637 })?
7638 .await;
7639
7640 _ = existing.update(cx, |workspace, _, cx| {
7641 for item in open_task.iter().flatten() {
7642 if let Err(e) = item {
7643 workspace.show_error(&e, cx);
7644 }
7645 }
7646 });
7647
7648 Ok((existing, open_task))
7649 } else {
7650 cx.update(move |cx| {
7651 Workspace::new_local(
7652 abs_paths,
7653 app_state.clone(),
7654 open_options.replace_window,
7655 open_options.env,
7656 cx,
7657 )
7658 })?
7659 .await
7660 };
7661
7662 #[cfg(target_os = "windows")]
7663 if let Some(util::paths::WslPath{distro, path}) = wsl_path
7664 && let Ok((workspace, _)) = &result
7665 {
7666 workspace
7667 .update(cx, move |workspace, _window, cx| {
7668 struct OpenInWsl;
7669 workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
7670 let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
7671 let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
7672 cx.new(move |cx| {
7673 MessageNotification::new(msg, cx)
7674 .primary_message("Open in WSL")
7675 .primary_icon(IconName::FolderOpen)
7676 .primary_on_click(move |window, cx| {
7677 window.dispatch_action(Box::new(remote::OpenWslPath {
7678 distro: remote::WslConnectionOptions {
7679 distro_name: distro.clone(),
7680 user: None,
7681 },
7682 paths: vec![path.clone().into()],
7683 }), cx)
7684 })
7685 })
7686 });
7687 })
7688 .unwrap();
7689 };
7690 result
7691 })
7692}
7693
7694pub fn open_new(
7695 open_options: OpenOptions,
7696 app_state: Arc<AppState>,
7697 cx: &mut App,
7698 init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
7699) -> Task<anyhow::Result<()>> {
7700 let task = Workspace::new_local(Vec::new(), app_state, None, open_options.env, cx);
7701 cx.spawn(async move |cx| {
7702 let (workspace, opened_paths) = task.await?;
7703 workspace.update(cx, |workspace, window, cx| {
7704 if opened_paths.is_empty() {
7705 init(workspace, window, cx)
7706 }
7707 })?;
7708 Ok(())
7709 })
7710}
7711
7712pub fn create_and_open_local_file(
7713 path: &'static Path,
7714 window: &mut Window,
7715 cx: &mut Context<Workspace>,
7716 default_content: impl 'static + Send + FnOnce() -> Rope,
7717) -> Task<Result<Box<dyn ItemHandle>>> {
7718 cx.spawn_in(window, async move |workspace, cx| {
7719 let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
7720 if !fs.is_file(path).await {
7721 fs.create_file(path, Default::default()).await?;
7722 fs.save(path, &default_content(), Default::default())
7723 .await?;
7724 }
7725
7726 let mut items = workspace
7727 .update_in(cx, |workspace, window, cx| {
7728 workspace.with_local_workspace(window, cx, |workspace, window, cx| {
7729 workspace.open_paths(
7730 vec![path.to_path_buf()],
7731 OpenOptions {
7732 visible: Some(OpenVisible::None),
7733 ..Default::default()
7734 },
7735 None,
7736 window,
7737 cx,
7738 )
7739 })
7740 })?
7741 .await?
7742 .await;
7743
7744 let item = items.pop().flatten();
7745 item.with_context(|| format!("path {path:?} is not a file"))?
7746 })
7747}
7748
7749pub fn open_remote_project_with_new_connection(
7750 window: WindowHandle<Workspace>,
7751 remote_connection: Arc<dyn RemoteConnection>,
7752 cancel_rx: oneshot::Receiver<()>,
7753 delegate: Arc<dyn RemoteClientDelegate>,
7754 app_state: Arc<AppState>,
7755 paths: Vec<PathBuf>,
7756 cx: &mut App,
7757) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
7758 cx.spawn(async move |cx| {
7759 let (workspace_id, serialized_workspace) =
7760 serialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
7761 .await?;
7762
7763 let session = match cx
7764 .update(|cx| {
7765 remote::RemoteClient::new(
7766 ConnectionIdentifier::Workspace(workspace_id.0),
7767 remote_connection,
7768 cancel_rx,
7769 delegate,
7770 cx,
7771 )
7772 })?
7773 .await?
7774 {
7775 Some(result) => result,
7776 None => return Ok(Vec::new()),
7777 };
7778
7779 let project = cx.update(|cx| {
7780 project::Project::remote(
7781 session,
7782 app_state.client.clone(),
7783 app_state.node_runtime.clone(),
7784 app_state.user_store.clone(),
7785 app_state.languages.clone(),
7786 app_state.fs.clone(),
7787 cx,
7788 )
7789 })?;
7790
7791 open_remote_project_inner(
7792 project,
7793 paths,
7794 workspace_id,
7795 serialized_workspace,
7796 app_state,
7797 window,
7798 cx,
7799 )
7800 .await
7801 })
7802}
7803
7804pub fn open_remote_project_with_existing_connection(
7805 connection_options: RemoteConnectionOptions,
7806 project: Entity<Project>,
7807 paths: Vec<PathBuf>,
7808 app_state: Arc<AppState>,
7809 window: WindowHandle<Workspace>,
7810 cx: &mut AsyncApp,
7811) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
7812 cx.spawn(async move |cx| {
7813 let (workspace_id, serialized_workspace) =
7814 serialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
7815
7816 open_remote_project_inner(
7817 project,
7818 paths,
7819 workspace_id,
7820 serialized_workspace,
7821 app_state,
7822 window,
7823 cx,
7824 )
7825 .await
7826 })
7827}
7828
7829async fn open_remote_project_inner(
7830 project: Entity<Project>,
7831 paths: Vec<PathBuf>,
7832 workspace_id: WorkspaceId,
7833 serialized_workspace: Option<SerializedWorkspace>,
7834 app_state: Arc<AppState>,
7835 window: WindowHandle<Workspace>,
7836 cx: &mut AsyncApp,
7837) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
7838 let toolchains = DB.toolchains(workspace_id).await?;
7839 for (toolchain, worktree_id, path) in toolchains {
7840 project
7841 .update(cx, |this, cx| {
7842 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
7843 })?
7844 .await;
7845 }
7846 let mut project_paths_to_open = vec![];
7847 let mut project_path_errors = vec![];
7848
7849 for path in paths {
7850 let result = cx
7851 .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))?
7852 .await;
7853 match result {
7854 Ok((_, project_path)) => {
7855 project_paths_to_open.push((path.clone(), Some(project_path)));
7856 }
7857 Err(error) => {
7858 project_path_errors.push(error);
7859 }
7860 };
7861 }
7862
7863 if project_paths_to_open.is_empty() {
7864 return Err(project_path_errors.pop().context("no paths given")?);
7865 }
7866
7867 if let Some(detach_session_task) = window
7868 .update(cx, |_workspace, window, cx| {
7869 cx.spawn_in(window, async move |this, cx| {
7870 this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))
7871 })
7872 })
7873 .ok()
7874 {
7875 detach_session_task.await.ok();
7876 }
7877
7878 cx.update_window(window.into(), |_, window, cx| {
7879 window.replace_root(cx, |window, cx| {
7880 telemetry::event!("SSH Project Opened");
7881
7882 let mut workspace =
7883 Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
7884 workspace.update_history(cx);
7885
7886 if let Some(ref serialized) = serialized_workspace {
7887 workspace.centered_layout = serialized.centered_layout;
7888 }
7889
7890 workspace
7891 });
7892 })?;
7893
7894 let items = window
7895 .update(cx, |_, window, cx| {
7896 window.activate_window();
7897 open_items(serialized_workspace, project_paths_to_open, window, cx)
7898 })?
7899 .await?;
7900
7901 window.update(cx, |workspace, _, cx| {
7902 for error in project_path_errors {
7903 if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
7904 if let Some(path) = error.error_tag("path") {
7905 workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
7906 }
7907 } else {
7908 workspace.show_error(&error, cx)
7909 }
7910 }
7911 })?;
7912
7913 Ok(items.into_iter().map(|item| item?.ok()).collect())
7914}
7915
7916fn serialize_remote_project(
7917 connection_options: RemoteConnectionOptions,
7918 paths: Vec<PathBuf>,
7919 cx: &AsyncApp,
7920) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
7921 cx.background_spawn(async move {
7922 let remote_connection_id = persistence::DB
7923 .get_or_create_remote_connection(connection_options)
7924 .await?;
7925
7926 let serialized_workspace =
7927 persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
7928
7929 let workspace_id = if let Some(workspace_id) =
7930 serialized_workspace.as_ref().map(|workspace| workspace.id)
7931 {
7932 workspace_id
7933 } else {
7934 persistence::DB.next_id().await?
7935 };
7936
7937 Ok((workspace_id, serialized_workspace))
7938 })
7939}
7940
7941pub fn join_in_room_project(
7942 project_id: u64,
7943 follow_user_id: u64,
7944 app_state: Arc<AppState>,
7945 cx: &mut App,
7946) -> Task<Result<()>> {
7947 let windows = cx.windows();
7948 cx.spawn(async move |cx| {
7949 let existing_workspace = windows.into_iter().find_map(|window_handle| {
7950 window_handle
7951 .downcast::<Workspace>()
7952 .and_then(|window_handle| {
7953 window_handle
7954 .update(cx, |workspace, _window, cx| {
7955 if workspace.project().read(cx).remote_id() == Some(project_id) {
7956 Some(window_handle)
7957 } else {
7958 None
7959 }
7960 })
7961 .unwrap_or(None)
7962 })
7963 });
7964
7965 let workspace = if let Some(existing_workspace) = existing_workspace {
7966 existing_workspace
7967 } else {
7968 let active_call = cx.update(|cx| ActiveCall::global(cx))?;
7969 let room = active_call
7970 .read_with(cx, |call, _| call.room().cloned())?
7971 .context("not in a call")?;
7972 let project = room
7973 .update(cx, |room, cx| {
7974 room.join_project(
7975 project_id,
7976 app_state.languages.clone(),
7977 app_state.fs.clone(),
7978 cx,
7979 )
7980 })?
7981 .await?;
7982
7983 let window_bounds_override = window_bounds_env_override();
7984 cx.update(|cx| {
7985 let mut options = (app_state.build_window_options)(None, cx);
7986 options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
7987 cx.open_window(options, |window, cx| {
7988 cx.new(|cx| {
7989 Workspace::new(Default::default(), project, app_state.clone(), window, cx)
7990 })
7991 })
7992 })??
7993 };
7994
7995 workspace.update(cx, |workspace, window, cx| {
7996 cx.activate(true);
7997 window.activate_window();
7998
7999 if let Some(room) = ActiveCall::global(cx).read(cx).room().cloned() {
8000 let follow_peer_id = room
8001 .read(cx)
8002 .remote_participants()
8003 .iter()
8004 .find(|(_, participant)| participant.user.id == follow_user_id)
8005 .map(|(_, p)| p.peer_id)
8006 .or_else(|| {
8007 // If we couldn't follow the given user, follow the host instead.
8008 let collaborator = workspace
8009 .project()
8010 .read(cx)
8011 .collaborators()
8012 .values()
8013 .find(|collaborator| collaborator.is_host)?;
8014 Some(collaborator.peer_id)
8015 });
8016
8017 if let Some(follow_peer_id) = follow_peer_id {
8018 workspace.follow(follow_peer_id, window, cx);
8019 }
8020 }
8021 })?;
8022
8023 anyhow::Ok(())
8024 })
8025}
8026
8027pub fn reload(cx: &mut App) {
8028 let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
8029 let mut workspace_windows = cx
8030 .windows()
8031 .into_iter()
8032 .filter_map(|window| window.downcast::<Workspace>())
8033 .collect::<Vec<_>>();
8034
8035 // If multiple windows have unsaved changes, and need a save prompt,
8036 // prompt in the active window before switching to a different window.
8037 workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
8038
8039 let mut prompt = None;
8040 if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
8041 prompt = window
8042 .update(cx, |_, window, cx| {
8043 window.prompt(
8044 PromptLevel::Info,
8045 "Are you sure you want to restart?",
8046 None,
8047 &["Restart", "Cancel"],
8048 cx,
8049 )
8050 })
8051 .ok();
8052 }
8053
8054 cx.spawn(async move |cx| {
8055 if let Some(prompt) = prompt {
8056 let answer = prompt.await?;
8057 if answer != 0 {
8058 return Ok(());
8059 }
8060 }
8061
8062 // If the user cancels any save prompt, then keep the app open.
8063 for window in workspace_windows {
8064 if let Ok(should_close) = window.update(cx, |workspace, window, cx| {
8065 workspace.prepare_to_close(CloseIntent::Quit, window, cx)
8066 }) && !should_close.await?
8067 {
8068 return Ok(());
8069 }
8070 }
8071 cx.update(|cx| cx.restart())
8072 })
8073 .detach_and_log_err(cx);
8074}
8075
8076fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
8077 let mut parts = value.split(',');
8078 let x: usize = parts.next()?.parse().ok()?;
8079 let y: usize = parts.next()?.parse().ok()?;
8080 Some(point(px(x as f32), px(y as f32)))
8081}
8082
8083fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
8084 let mut parts = value.split(',');
8085 let width: usize = parts.next()?.parse().ok()?;
8086 let height: usize = parts.next()?.parse().ok()?;
8087 Some(size(px(width as f32), px(height as f32)))
8088}
8089
8090/// Add client-side decorations (rounded corners, shadows, resize handling) when appropriate.
8091pub fn client_side_decorations(
8092 element: impl IntoElement,
8093 window: &mut Window,
8094 cx: &mut App,
8095) -> Stateful<Div> {
8096 const BORDER_SIZE: Pixels = px(1.0);
8097 let decorations = window.window_decorations();
8098
8099 match decorations {
8100 Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
8101 Decorations::Server => window.set_client_inset(px(0.0)),
8102 }
8103
8104 struct GlobalResizeEdge(ResizeEdge);
8105 impl Global for GlobalResizeEdge {}
8106
8107 div()
8108 .id("window-backdrop")
8109 .bg(transparent_black())
8110 .map(|div| match decorations {
8111 Decorations::Server => div,
8112 Decorations::Client { tiling, .. } => div
8113 .when(!(tiling.top || tiling.right), |div| {
8114 div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING)
8115 })
8116 .when(!(tiling.top || tiling.left), |div| {
8117 div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
8118 })
8119 .when(!(tiling.bottom || tiling.right), |div| {
8120 div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING)
8121 })
8122 .when(!(tiling.bottom || tiling.left), |div| {
8123 div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
8124 })
8125 .when(!tiling.top, |div| {
8126 div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
8127 })
8128 .when(!tiling.bottom, |div| {
8129 div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
8130 })
8131 .when(!tiling.left, |div| {
8132 div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
8133 })
8134 .when(!tiling.right, |div| {
8135 div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
8136 })
8137 .on_mouse_move(move |e, window, cx| {
8138 let size = window.window_bounds().get_bounds().size;
8139 let pos = e.position;
8140
8141 let new_edge =
8142 resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
8143
8144 let edge = cx.try_global::<GlobalResizeEdge>();
8145 if new_edge != edge.map(|edge| edge.0) {
8146 window
8147 .window_handle()
8148 .update(cx, |workspace, _, cx| {
8149 cx.notify(workspace.entity_id());
8150 })
8151 .ok();
8152 }
8153 })
8154 .on_mouse_down(MouseButton::Left, move |e, window, _| {
8155 let size = window.window_bounds().get_bounds().size;
8156 let pos = e.position;
8157
8158 let edge = match resize_edge(
8159 pos,
8160 theme::CLIENT_SIDE_DECORATION_SHADOW,
8161 size,
8162 tiling,
8163 ) {
8164 Some(value) => value,
8165 None => return,
8166 };
8167
8168 window.start_window_resize(edge);
8169 }),
8170 })
8171 .size_full()
8172 .child(
8173 div()
8174 .cursor(CursorStyle::Arrow)
8175 .map(|div| match decorations {
8176 Decorations::Server => div,
8177 Decorations::Client { tiling } => div
8178 .border_color(cx.theme().colors().border)
8179 .when(!(tiling.top || tiling.right), |div| {
8180 div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING)
8181 })
8182 .when(!(tiling.top || tiling.left), |div| {
8183 div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
8184 })
8185 .when(!(tiling.bottom || tiling.right), |div| {
8186 div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING)
8187 })
8188 .when(!(tiling.bottom || tiling.left), |div| {
8189 div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
8190 })
8191 .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
8192 .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
8193 .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
8194 .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
8195 .when(!tiling.is_tiled(), |div| {
8196 div.shadow(vec![gpui::BoxShadow {
8197 color: Hsla {
8198 h: 0.,
8199 s: 0.,
8200 l: 0.,
8201 a: 0.4,
8202 },
8203 blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
8204 spread_radius: px(0.),
8205 offset: point(px(0.0), px(0.0)),
8206 }])
8207 }),
8208 })
8209 .on_mouse_move(|_e, _, cx| {
8210 cx.stop_propagation();
8211 })
8212 .size_full()
8213 .child(element),
8214 )
8215 .map(|div| match decorations {
8216 Decorations::Server => div,
8217 Decorations::Client { tiling, .. } => div.child(
8218 canvas(
8219 |_bounds, window, _| {
8220 window.insert_hitbox(
8221 Bounds::new(
8222 point(px(0.0), px(0.0)),
8223 window.window_bounds().get_bounds().size,
8224 ),
8225 HitboxBehavior::Normal,
8226 )
8227 },
8228 move |_bounds, hitbox, window, cx| {
8229 let mouse = window.mouse_position();
8230 let size = window.window_bounds().get_bounds().size;
8231 let Some(edge) =
8232 resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
8233 else {
8234 return;
8235 };
8236 cx.set_global(GlobalResizeEdge(edge));
8237 window.set_cursor_style(
8238 match edge {
8239 ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
8240 ResizeEdge::Left | ResizeEdge::Right => {
8241 CursorStyle::ResizeLeftRight
8242 }
8243 ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
8244 CursorStyle::ResizeUpLeftDownRight
8245 }
8246 ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
8247 CursorStyle::ResizeUpRightDownLeft
8248 }
8249 },
8250 &hitbox,
8251 );
8252 },
8253 )
8254 .size_full()
8255 .absolute(),
8256 ),
8257 })
8258}
8259
8260fn resize_edge(
8261 pos: Point<Pixels>,
8262 shadow_size: Pixels,
8263 window_size: Size<Pixels>,
8264 tiling: Tiling,
8265) -> Option<ResizeEdge> {
8266 let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
8267 if bounds.contains(&pos) {
8268 return None;
8269 }
8270
8271 let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
8272 let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
8273 if !tiling.top && top_left_bounds.contains(&pos) {
8274 return Some(ResizeEdge::TopLeft);
8275 }
8276
8277 let top_right_bounds = Bounds::new(
8278 Point::new(window_size.width - corner_size.width, px(0.)),
8279 corner_size,
8280 );
8281 if !tiling.top && top_right_bounds.contains(&pos) {
8282 return Some(ResizeEdge::TopRight);
8283 }
8284
8285 let bottom_left_bounds = Bounds::new(
8286 Point::new(px(0.), window_size.height - corner_size.height),
8287 corner_size,
8288 );
8289 if !tiling.bottom && bottom_left_bounds.contains(&pos) {
8290 return Some(ResizeEdge::BottomLeft);
8291 }
8292
8293 let bottom_right_bounds = Bounds::new(
8294 Point::new(
8295 window_size.width - corner_size.width,
8296 window_size.height - corner_size.height,
8297 ),
8298 corner_size,
8299 );
8300 if !tiling.bottom && bottom_right_bounds.contains(&pos) {
8301 return Some(ResizeEdge::BottomRight);
8302 }
8303
8304 if !tiling.top && pos.y < shadow_size {
8305 Some(ResizeEdge::Top)
8306 } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
8307 Some(ResizeEdge::Bottom)
8308 } else if !tiling.left && pos.x < shadow_size {
8309 Some(ResizeEdge::Left)
8310 } else if !tiling.right && pos.x > window_size.width - shadow_size {
8311 Some(ResizeEdge::Right)
8312 } else {
8313 None
8314 }
8315}
8316
8317fn join_pane_into_active(
8318 active_pane: &Entity<Pane>,
8319 pane: &Entity<Pane>,
8320 window: &mut Window,
8321 cx: &mut App,
8322) {
8323 if pane == active_pane {
8324 } else if pane.read(cx).items_len() == 0 {
8325 pane.update(cx, |_, cx| {
8326 cx.emit(pane::Event::Remove {
8327 focus_on_pane: None,
8328 });
8329 })
8330 } else {
8331 move_all_items(pane, active_pane, window, cx);
8332 }
8333}
8334
8335fn move_all_items(
8336 from_pane: &Entity<Pane>,
8337 to_pane: &Entity<Pane>,
8338 window: &mut Window,
8339 cx: &mut App,
8340) {
8341 let destination_is_different = from_pane != to_pane;
8342 let mut moved_items = 0;
8343 for (item_ix, item_handle) in from_pane
8344 .read(cx)
8345 .items()
8346 .enumerate()
8347 .map(|(ix, item)| (ix, item.clone()))
8348 .collect::<Vec<_>>()
8349 {
8350 let ix = item_ix - moved_items;
8351 if destination_is_different {
8352 // Close item from previous pane
8353 from_pane.update(cx, |source, cx| {
8354 source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
8355 });
8356 moved_items += 1;
8357 }
8358
8359 // This automatically removes duplicate items in the pane
8360 to_pane.update(cx, |destination, cx| {
8361 destination.add_item(item_handle, true, true, None, window, cx);
8362 window.focus(&destination.focus_handle(cx))
8363 });
8364 }
8365}
8366
8367pub fn move_item(
8368 source: &Entity<Pane>,
8369 destination: &Entity<Pane>,
8370 item_id_to_move: EntityId,
8371 destination_index: usize,
8372 activate: bool,
8373 window: &mut Window,
8374 cx: &mut App,
8375) {
8376 let Some((item_ix, item_handle)) = source
8377 .read(cx)
8378 .items()
8379 .enumerate()
8380 .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
8381 .map(|(ix, item)| (ix, item.clone()))
8382 else {
8383 // Tab was closed during drag
8384 return;
8385 };
8386
8387 if source != destination {
8388 // Close item from previous pane
8389 source.update(cx, |source, cx| {
8390 source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
8391 });
8392 }
8393
8394 // This automatically removes duplicate items in the pane
8395 destination.update(cx, |destination, cx| {
8396 destination.add_item_inner(
8397 item_handle,
8398 activate,
8399 activate,
8400 activate,
8401 Some(destination_index),
8402 window,
8403 cx,
8404 );
8405 if activate {
8406 window.focus(&destination.focus_handle(cx))
8407 }
8408 });
8409}
8410
8411pub fn move_active_item(
8412 source: &Entity<Pane>,
8413 destination: &Entity<Pane>,
8414 focus_destination: bool,
8415 close_if_empty: bool,
8416 window: &mut Window,
8417 cx: &mut App,
8418) {
8419 if source == destination {
8420 return;
8421 }
8422 let Some(active_item) = source.read(cx).active_item() else {
8423 return;
8424 };
8425 source.update(cx, |source_pane, cx| {
8426 let item_id = active_item.item_id();
8427 source_pane.remove_item(item_id, false, close_if_empty, window, cx);
8428 destination.update(cx, |target_pane, cx| {
8429 target_pane.add_item(
8430 active_item,
8431 focus_destination,
8432 focus_destination,
8433 Some(target_pane.items_len()),
8434 window,
8435 cx,
8436 );
8437 });
8438 });
8439}
8440
8441pub fn clone_active_item(
8442 workspace_id: Option<WorkspaceId>,
8443 source: &Entity<Pane>,
8444 destination: &Entity<Pane>,
8445 focus_destination: bool,
8446 window: &mut Window,
8447 cx: &mut App,
8448) {
8449 if source == destination {
8450 return;
8451 }
8452 let Some(active_item) = source.read(cx).active_item() else {
8453 return;
8454 };
8455 if !active_item.can_split(cx) {
8456 return;
8457 }
8458 let destination = destination.downgrade();
8459 let task = active_item.clone_on_split(workspace_id, window, cx);
8460 window
8461 .spawn(cx, async move |cx| {
8462 let Some(clone) = task.await else {
8463 return;
8464 };
8465 destination
8466 .update_in(cx, |target_pane, window, cx| {
8467 target_pane.add_item(
8468 clone,
8469 focus_destination,
8470 focus_destination,
8471 Some(target_pane.items_len()),
8472 window,
8473 cx,
8474 );
8475 })
8476 .log_err();
8477 })
8478 .detach();
8479}
8480
8481#[derive(Debug)]
8482pub struct WorkspacePosition {
8483 pub window_bounds: Option<WindowBounds>,
8484 pub display: Option<Uuid>,
8485 pub centered_layout: bool,
8486}
8487
8488pub fn remote_workspace_position_from_db(
8489 connection_options: RemoteConnectionOptions,
8490 paths_to_open: &[PathBuf],
8491 cx: &App,
8492) -> Task<Result<WorkspacePosition>> {
8493 let paths = paths_to_open.to_vec();
8494
8495 cx.background_spawn(async move {
8496 let remote_connection_id = persistence::DB
8497 .get_or_create_remote_connection(connection_options)
8498 .await
8499 .context("fetching serialized ssh project")?;
8500 let serialized_workspace =
8501 persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
8502
8503 let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
8504 (Some(WindowBounds::Windowed(bounds)), None)
8505 } else {
8506 let restorable_bounds = serialized_workspace
8507 .as_ref()
8508 .and_then(|workspace| Some((workspace.display?, workspace.window_bounds?)))
8509 .or_else(|| {
8510 let (display, window_bounds) = DB.last_window().log_err()?;
8511 Some((display?, window_bounds?))
8512 });
8513
8514 if let Some((serialized_display, serialized_status)) = restorable_bounds {
8515 (Some(serialized_status.0), Some(serialized_display))
8516 } else {
8517 (None, None)
8518 }
8519 };
8520
8521 let centered_layout = serialized_workspace
8522 .as_ref()
8523 .map(|w| w.centered_layout)
8524 .unwrap_or(false);
8525
8526 Ok(WorkspacePosition {
8527 window_bounds,
8528 display,
8529 centered_layout,
8530 })
8531 })
8532}
8533
8534pub fn with_active_or_new_workspace(
8535 cx: &mut App,
8536 f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
8537) {
8538 match cx.active_window().and_then(|w| w.downcast::<Workspace>()) {
8539 Some(workspace) => {
8540 cx.defer(move |cx| {
8541 workspace
8542 .update(cx, |workspace, window, cx| f(workspace, window, cx))
8543 .log_err();
8544 });
8545 }
8546 None => {
8547 let app_state = AppState::global(cx);
8548 if let Some(app_state) = app_state.upgrade() {
8549 open_new(
8550 OpenOptions::default(),
8551 app_state,
8552 cx,
8553 move |workspace, window, cx| f(workspace, window, cx),
8554 )
8555 .detach_and_log_err(cx);
8556 }
8557 }
8558 }
8559}
8560
8561#[cfg(test)]
8562mod tests {
8563 use std::{cell::RefCell, rc::Rc};
8564
8565 use super::*;
8566 use crate::{
8567 dock::{PanelEvent, test::TestPanel},
8568 item::{
8569 ItemBufferKind, ItemEvent,
8570 test::{TestItem, TestProjectItem},
8571 },
8572 };
8573 use fs::FakeFs;
8574 use gpui::{
8575 DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
8576 UpdateGlobal, VisualTestContext, px,
8577 };
8578 use project::{Project, ProjectEntryId};
8579 use serde_json::json;
8580 use settings::SettingsStore;
8581 use util::rel_path::rel_path;
8582
8583 #[gpui::test]
8584 async fn test_tab_disambiguation(cx: &mut TestAppContext) {
8585 init_test(cx);
8586
8587 let fs = FakeFs::new(cx.executor());
8588 let project = Project::test(fs, [], cx).await;
8589 let (workspace, cx) =
8590 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
8591
8592 // Adding an item with no ambiguity renders the tab without detail.
8593 let item1 = cx.new(|cx| {
8594 let mut item = TestItem::new(cx);
8595 item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
8596 item
8597 });
8598 workspace.update_in(cx, |workspace, window, cx| {
8599 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
8600 });
8601 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
8602
8603 // Adding an item that creates ambiguity increases the level of detail on
8604 // both tabs.
8605 let item2 = cx.new_window_entity(|_window, cx| {
8606 let mut item = TestItem::new(cx);
8607 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
8608 item
8609 });
8610 workspace.update_in(cx, |workspace, window, cx| {
8611 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
8612 });
8613 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
8614 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
8615
8616 // Adding an item that creates ambiguity increases the level of detail only
8617 // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
8618 // we stop at the highest detail available.
8619 let item3 = cx.new(|cx| {
8620 let mut item = TestItem::new(cx);
8621 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
8622 item
8623 });
8624 workspace.update_in(cx, |workspace, window, cx| {
8625 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
8626 });
8627 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
8628 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
8629 item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
8630 }
8631
8632 #[gpui::test]
8633 async fn test_tracking_active_path(cx: &mut TestAppContext) {
8634 init_test(cx);
8635
8636 let fs = FakeFs::new(cx.executor());
8637 fs.insert_tree(
8638 "/root1",
8639 json!({
8640 "one.txt": "",
8641 "two.txt": "",
8642 }),
8643 )
8644 .await;
8645 fs.insert_tree(
8646 "/root2",
8647 json!({
8648 "three.txt": "",
8649 }),
8650 )
8651 .await;
8652
8653 let project = Project::test(fs, ["root1".as_ref()], cx).await;
8654 let (workspace, cx) =
8655 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
8656 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
8657 let worktree_id = project.update(cx, |project, cx| {
8658 project.worktrees(cx).next().unwrap().read(cx).id()
8659 });
8660
8661 let item1 = cx.new(|cx| {
8662 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
8663 });
8664 let item2 = cx.new(|cx| {
8665 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
8666 });
8667
8668 // Add an item to an empty pane
8669 workspace.update_in(cx, |workspace, window, cx| {
8670 workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
8671 });
8672 project.update(cx, |project, cx| {
8673 assert_eq!(
8674 project.active_entry(),
8675 project
8676 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
8677 .map(|e| e.id)
8678 );
8679 });
8680 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
8681
8682 // Add a second item to a non-empty pane
8683 workspace.update_in(cx, |workspace, window, cx| {
8684 workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
8685 });
8686 assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
8687 project.update(cx, |project, cx| {
8688 assert_eq!(
8689 project.active_entry(),
8690 project
8691 .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
8692 .map(|e| e.id)
8693 );
8694 });
8695
8696 // Close the active item
8697 pane.update_in(cx, |pane, window, cx| {
8698 pane.close_active_item(&Default::default(), window, cx)
8699 })
8700 .await
8701 .unwrap();
8702 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
8703 project.update(cx, |project, cx| {
8704 assert_eq!(
8705 project.active_entry(),
8706 project
8707 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
8708 .map(|e| e.id)
8709 );
8710 });
8711
8712 // Add a project folder
8713 project
8714 .update(cx, |project, cx| {
8715 project.find_or_create_worktree("root2", true, cx)
8716 })
8717 .await
8718 .unwrap();
8719 assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
8720
8721 // Remove a project folder
8722 project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
8723 assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
8724 }
8725
8726 #[gpui::test]
8727 async fn test_close_window(cx: &mut TestAppContext) {
8728 init_test(cx);
8729
8730 let fs = FakeFs::new(cx.executor());
8731 fs.insert_tree("/root", json!({ "one": "" })).await;
8732
8733 let project = Project::test(fs, ["root".as_ref()], cx).await;
8734 let (workspace, cx) =
8735 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
8736
8737 // When there are no dirty items, there's nothing to do.
8738 let item1 = cx.new(TestItem::new);
8739 workspace.update_in(cx, |w, window, cx| {
8740 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
8741 });
8742 let task = workspace.update_in(cx, |w, window, cx| {
8743 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
8744 });
8745 assert!(task.await.unwrap());
8746
8747 // When there are dirty untitled items, prompt to save each one. If the user
8748 // cancels any prompt, then abort.
8749 let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
8750 let item3 = cx.new(|cx| {
8751 TestItem::new(cx)
8752 .with_dirty(true)
8753 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
8754 });
8755 workspace.update_in(cx, |w, window, cx| {
8756 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
8757 w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
8758 });
8759 let task = workspace.update_in(cx, |w, window, cx| {
8760 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
8761 });
8762 cx.executor().run_until_parked();
8763 cx.simulate_prompt_answer("Cancel"); // cancel save all
8764 cx.executor().run_until_parked();
8765 assert!(!cx.has_pending_prompt());
8766 assert!(!task.await.unwrap());
8767 }
8768
8769 #[gpui::test]
8770 async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
8771 init_test(cx);
8772
8773 // Register TestItem as a serializable item
8774 cx.update(|cx| {
8775 register_serializable_item::<TestItem>(cx);
8776 });
8777
8778 let fs = FakeFs::new(cx.executor());
8779 fs.insert_tree("/root", json!({ "one": "" })).await;
8780
8781 let project = Project::test(fs, ["root".as_ref()], cx).await;
8782 let (workspace, cx) =
8783 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
8784
8785 // When there are dirty untitled items, but they can serialize, then there is no prompt.
8786 let item1 = cx.new(|cx| {
8787 TestItem::new(cx)
8788 .with_dirty(true)
8789 .with_serialize(|| Some(Task::ready(Ok(()))))
8790 });
8791 let item2 = cx.new(|cx| {
8792 TestItem::new(cx)
8793 .with_dirty(true)
8794 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
8795 .with_serialize(|| Some(Task::ready(Ok(()))))
8796 });
8797 workspace.update_in(cx, |w, window, cx| {
8798 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
8799 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
8800 });
8801 let task = workspace.update_in(cx, |w, window, cx| {
8802 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
8803 });
8804 assert!(task.await.unwrap());
8805 }
8806
8807 #[gpui::test]
8808 async fn test_close_pane_items(cx: &mut TestAppContext) {
8809 init_test(cx);
8810
8811 let fs = FakeFs::new(cx.executor());
8812
8813 let project = Project::test(fs, None, cx).await;
8814 let (workspace, cx) =
8815 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
8816
8817 let item1 = cx.new(|cx| {
8818 TestItem::new(cx)
8819 .with_dirty(true)
8820 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
8821 });
8822 let item2 = cx.new(|cx| {
8823 TestItem::new(cx)
8824 .with_dirty(true)
8825 .with_conflict(true)
8826 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
8827 });
8828 let item3 = cx.new(|cx| {
8829 TestItem::new(cx)
8830 .with_dirty(true)
8831 .with_conflict(true)
8832 .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
8833 });
8834 let item4 = cx.new(|cx| {
8835 TestItem::new(cx).with_dirty(true).with_project_items(&[{
8836 let project_item = TestProjectItem::new_untitled(cx);
8837 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
8838 project_item
8839 }])
8840 });
8841 let pane = workspace.update_in(cx, |workspace, window, cx| {
8842 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
8843 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
8844 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
8845 workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
8846 workspace.active_pane().clone()
8847 });
8848
8849 let close_items = pane.update_in(cx, |pane, window, cx| {
8850 pane.activate_item(1, true, true, window, cx);
8851 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
8852 let item1_id = item1.item_id();
8853 let item3_id = item3.item_id();
8854 let item4_id = item4.item_id();
8855 pane.close_items(window, cx, SaveIntent::Close, move |id| {
8856 [item1_id, item3_id, item4_id].contains(&id)
8857 })
8858 });
8859 cx.executor().run_until_parked();
8860
8861 assert!(cx.has_pending_prompt());
8862 cx.simulate_prompt_answer("Save all");
8863
8864 cx.executor().run_until_parked();
8865
8866 // Item 1 is saved. There's a prompt to save item 3.
8867 pane.update(cx, |pane, cx| {
8868 assert_eq!(item1.read(cx).save_count, 1);
8869 assert_eq!(item1.read(cx).save_as_count, 0);
8870 assert_eq!(item1.read(cx).reload_count, 0);
8871 assert_eq!(pane.items_len(), 3);
8872 assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
8873 });
8874 assert!(cx.has_pending_prompt());
8875
8876 // Cancel saving item 3.
8877 cx.simulate_prompt_answer("Discard");
8878 cx.executor().run_until_parked();
8879
8880 // Item 3 is reloaded. There's a prompt to save item 4.
8881 pane.update(cx, |pane, cx| {
8882 assert_eq!(item3.read(cx).save_count, 0);
8883 assert_eq!(item3.read(cx).save_as_count, 0);
8884 assert_eq!(item3.read(cx).reload_count, 1);
8885 assert_eq!(pane.items_len(), 2);
8886 assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
8887 });
8888
8889 // There's a prompt for a path for item 4.
8890 cx.simulate_new_path_selection(|_| Some(Default::default()));
8891 close_items.await.unwrap();
8892
8893 // The requested items are closed.
8894 pane.update(cx, |pane, cx| {
8895 assert_eq!(item4.read(cx).save_count, 0);
8896 assert_eq!(item4.read(cx).save_as_count, 1);
8897 assert_eq!(item4.read(cx).reload_count, 0);
8898 assert_eq!(pane.items_len(), 1);
8899 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
8900 });
8901 }
8902
8903 #[gpui::test]
8904 async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
8905 init_test(cx);
8906
8907 let fs = FakeFs::new(cx.executor());
8908 let project = Project::test(fs, [], cx).await;
8909 let (workspace, cx) =
8910 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
8911
8912 // Create several workspace items with single project entries, and two
8913 // workspace items with multiple project entries.
8914 let single_entry_items = (0..=4)
8915 .map(|project_entry_id| {
8916 cx.new(|cx| {
8917 TestItem::new(cx)
8918 .with_dirty(true)
8919 .with_project_items(&[dirty_project_item(
8920 project_entry_id,
8921 &format!("{project_entry_id}.txt"),
8922 cx,
8923 )])
8924 })
8925 })
8926 .collect::<Vec<_>>();
8927 let item_2_3 = cx.new(|cx| {
8928 TestItem::new(cx)
8929 .with_dirty(true)
8930 .with_buffer_kind(ItemBufferKind::Multibuffer)
8931 .with_project_items(&[
8932 single_entry_items[2].read(cx).project_items[0].clone(),
8933 single_entry_items[3].read(cx).project_items[0].clone(),
8934 ])
8935 });
8936 let item_3_4 = cx.new(|cx| {
8937 TestItem::new(cx)
8938 .with_dirty(true)
8939 .with_buffer_kind(ItemBufferKind::Multibuffer)
8940 .with_project_items(&[
8941 single_entry_items[3].read(cx).project_items[0].clone(),
8942 single_entry_items[4].read(cx).project_items[0].clone(),
8943 ])
8944 });
8945
8946 // Create two panes that contain the following project entries:
8947 // left pane:
8948 // multi-entry items: (2, 3)
8949 // single-entry items: 0, 2, 3, 4
8950 // right pane:
8951 // single-entry items: 4, 1
8952 // multi-entry items: (3, 4)
8953 let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
8954 let left_pane = workspace.active_pane().clone();
8955 workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
8956 workspace.add_item_to_active_pane(
8957 single_entry_items[0].boxed_clone(),
8958 None,
8959 true,
8960 window,
8961 cx,
8962 );
8963 workspace.add_item_to_active_pane(
8964 single_entry_items[2].boxed_clone(),
8965 None,
8966 true,
8967 window,
8968 cx,
8969 );
8970 workspace.add_item_to_active_pane(
8971 single_entry_items[3].boxed_clone(),
8972 None,
8973 true,
8974 window,
8975 cx,
8976 );
8977 workspace.add_item_to_active_pane(
8978 single_entry_items[4].boxed_clone(),
8979 None,
8980 true,
8981 window,
8982 cx,
8983 );
8984
8985 let right_pane =
8986 workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
8987
8988 let boxed_clone = single_entry_items[1].boxed_clone();
8989 let right_pane = window.spawn(cx, async move |cx| {
8990 right_pane.await.inspect(|right_pane| {
8991 right_pane
8992 .update_in(cx, |pane, window, cx| {
8993 pane.add_item(boxed_clone, true, true, None, window, cx);
8994 pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
8995 })
8996 .unwrap();
8997 })
8998 });
8999
9000 (left_pane, right_pane)
9001 });
9002 let right_pane = right_pane.await.unwrap();
9003 cx.focus(&right_pane);
9004
9005 let mut close = right_pane.update_in(cx, |pane, window, cx| {
9006 pane.close_all_items(&CloseAllItems::default(), window, cx)
9007 .unwrap()
9008 });
9009 cx.executor().run_until_parked();
9010
9011 let msg = cx.pending_prompt().unwrap().0;
9012 assert!(msg.contains("1.txt"));
9013 assert!(!msg.contains("2.txt"));
9014 assert!(!msg.contains("3.txt"));
9015 assert!(!msg.contains("4.txt"));
9016
9017 cx.simulate_prompt_answer("Cancel");
9018 close.await;
9019
9020 left_pane
9021 .update_in(cx, |left_pane, window, cx| {
9022 left_pane.close_item_by_id(
9023 single_entry_items[3].entity_id(),
9024 SaveIntent::Skip,
9025 window,
9026 cx,
9027 )
9028 })
9029 .await
9030 .unwrap();
9031
9032 close = right_pane.update_in(cx, |pane, window, cx| {
9033 pane.close_all_items(&CloseAllItems::default(), window, cx)
9034 .unwrap()
9035 });
9036 cx.executor().run_until_parked();
9037
9038 let details = cx.pending_prompt().unwrap().1;
9039 assert!(details.contains("1.txt"));
9040 assert!(!details.contains("2.txt"));
9041 assert!(details.contains("3.txt"));
9042 // ideally this assertion could be made, but today we can only
9043 // save whole items not project items, so the orphaned item 3 causes
9044 // 4 to be saved too.
9045 // assert!(!details.contains("4.txt"));
9046
9047 cx.simulate_prompt_answer("Save all");
9048
9049 cx.executor().run_until_parked();
9050 close.await;
9051 right_pane.read_with(cx, |pane, _| {
9052 assert_eq!(pane.items_len(), 0);
9053 });
9054 }
9055
9056 #[gpui::test]
9057 async fn test_autosave(cx: &mut gpui::TestAppContext) {
9058 init_test(cx);
9059
9060 let fs = FakeFs::new(cx.executor());
9061 let project = Project::test(fs, [], cx).await;
9062 let (workspace, cx) =
9063 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9064 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
9065
9066 let item = cx.new(|cx| {
9067 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
9068 });
9069 let item_id = item.entity_id();
9070 workspace.update_in(cx, |workspace, window, cx| {
9071 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
9072 });
9073
9074 // Autosave on window change.
9075 item.update(cx, |item, cx| {
9076 SettingsStore::update_global(cx, |settings, cx| {
9077 settings.update_user_settings(cx, |settings| {
9078 settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
9079 })
9080 });
9081 item.is_dirty = true;
9082 });
9083
9084 // Deactivating the window saves the file.
9085 cx.deactivate_window();
9086 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
9087
9088 // Re-activating the window doesn't save the file.
9089 cx.update(|window, _| window.activate_window());
9090 cx.executor().run_until_parked();
9091 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
9092
9093 // Autosave on focus change.
9094 item.update_in(cx, |item, window, cx| {
9095 cx.focus_self(window);
9096 SettingsStore::update_global(cx, |settings, cx| {
9097 settings.update_user_settings(cx, |settings| {
9098 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
9099 })
9100 });
9101 item.is_dirty = true;
9102 });
9103 // Blurring the item saves the file.
9104 item.update_in(cx, |_, window, _| window.blur());
9105 cx.executor().run_until_parked();
9106 item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
9107
9108 // Deactivating the window still saves the file.
9109 item.update_in(cx, |item, window, cx| {
9110 cx.focus_self(window);
9111 item.is_dirty = true;
9112 });
9113 cx.deactivate_window();
9114 item.update(cx, |item, _| assert_eq!(item.save_count, 3));
9115
9116 // Autosave after delay.
9117 item.update(cx, |item, cx| {
9118 SettingsStore::update_global(cx, |settings, cx| {
9119 settings.update_user_settings(cx, |settings| {
9120 settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
9121 milliseconds: 500.into(),
9122 });
9123 })
9124 });
9125 item.is_dirty = true;
9126 cx.emit(ItemEvent::Edit);
9127 });
9128
9129 // Delay hasn't fully expired, so the file is still dirty and unsaved.
9130 cx.executor().advance_clock(Duration::from_millis(250));
9131 item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
9132
9133 // After delay expires, the file is saved.
9134 cx.executor().advance_clock(Duration::from_millis(250));
9135 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
9136
9137 // Autosave after delay, should save earlier than delay if tab is closed
9138 item.update(cx, |item, cx| {
9139 item.is_dirty = true;
9140 cx.emit(ItemEvent::Edit);
9141 });
9142 cx.executor().advance_clock(Duration::from_millis(250));
9143 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
9144
9145 // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
9146 pane.update_in(cx, |pane, window, cx| {
9147 pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
9148 })
9149 .await
9150 .unwrap();
9151 assert!(!cx.has_pending_prompt());
9152 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
9153
9154 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
9155 workspace.update_in(cx, |workspace, window, cx| {
9156 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
9157 });
9158 item.update_in(cx, |item, _window, cx| {
9159 item.is_dirty = true;
9160 for project_item in &mut item.project_items {
9161 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
9162 }
9163 });
9164 cx.run_until_parked();
9165 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
9166
9167 // Autosave on focus change, ensuring closing the tab counts as such.
9168 item.update(cx, |item, cx| {
9169 SettingsStore::update_global(cx, |settings, cx| {
9170 settings.update_user_settings(cx, |settings| {
9171 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
9172 })
9173 });
9174 item.is_dirty = true;
9175 for project_item in &mut item.project_items {
9176 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
9177 }
9178 });
9179
9180 pane.update_in(cx, |pane, window, cx| {
9181 pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
9182 })
9183 .await
9184 .unwrap();
9185 assert!(!cx.has_pending_prompt());
9186 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
9187
9188 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
9189 workspace.update_in(cx, |workspace, window, cx| {
9190 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
9191 });
9192 item.update_in(cx, |item, window, cx| {
9193 item.project_items[0].update(cx, |item, _| {
9194 item.entry_id = None;
9195 });
9196 item.is_dirty = true;
9197 window.blur();
9198 });
9199 cx.run_until_parked();
9200 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
9201
9202 // Ensure autosave is prevented for deleted files also when closing the buffer.
9203 let _close_items = pane.update_in(cx, |pane, window, cx| {
9204 pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
9205 });
9206 cx.run_until_parked();
9207 assert!(cx.has_pending_prompt());
9208 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
9209 }
9210
9211 #[gpui::test]
9212 async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
9213 init_test(cx);
9214
9215 let fs = FakeFs::new(cx.executor());
9216
9217 let project = Project::test(fs, [], cx).await;
9218 let (workspace, cx) =
9219 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9220
9221 let item = cx.new(|cx| {
9222 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
9223 });
9224 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
9225 let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
9226 let toolbar_notify_count = Rc::new(RefCell::new(0));
9227
9228 workspace.update_in(cx, |workspace, window, cx| {
9229 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
9230 let toolbar_notification_count = toolbar_notify_count.clone();
9231 cx.observe_in(&toolbar, window, move |_, _, _, _| {
9232 *toolbar_notification_count.borrow_mut() += 1
9233 })
9234 .detach();
9235 });
9236
9237 pane.read_with(cx, |pane, _| {
9238 assert!(!pane.can_navigate_backward());
9239 assert!(!pane.can_navigate_forward());
9240 });
9241
9242 item.update_in(cx, |item, _, cx| {
9243 item.set_state("one".to_string(), cx);
9244 });
9245
9246 // Toolbar must be notified to re-render the navigation buttons
9247 assert_eq!(*toolbar_notify_count.borrow(), 1);
9248
9249 pane.read_with(cx, |pane, _| {
9250 assert!(pane.can_navigate_backward());
9251 assert!(!pane.can_navigate_forward());
9252 });
9253
9254 workspace
9255 .update_in(cx, |workspace, window, cx| {
9256 workspace.go_back(pane.downgrade(), window, cx)
9257 })
9258 .await
9259 .unwrap();
9260
9261 assert_eq!(*toolbar_notify_count.borrow(), 2);
9262 pane.read_with(cx, |pane, _| {
9263 assert!(!pane.can_navigate_backward());
9264 assert!(pane.can_navigate_forward());
9265 });
9266 }
9267
9268 #[gpui::test]
9269 async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
9270 init_test(cx);
9271 let fs = FakeFs::new(cx.executor());
9272
9273 let project = Project::test(fs, [], cx).await;
9274 let (workspace, cx) =
9275 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9276
9277 let panel = workspace.update_in(cx, |workspace, window, cx| {
9278 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
9279 workspace.add_panel(panel.clone(), window, cx);
9280
9281 workspace
9282 .right_dock()
9283 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
9284
9285 panel
9286 });
9287
9288 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
9289 pane.update_in(cx, |pane, window, cx| {
9290 let item = cx.new(TestItem::new);
9291 pane.add_item(Box::new(item), true, true, None, window, cx);
9292 });
9293
9294 // Transfer focus from center to panel
9295 workspace.update_in(cx, |workspace, window, cx| {
9296 workspace.toggle_panel_focus::<TestPanel>(window, cx);
9297 });
9298
9299 workspace.update_in(cx, |workspace, window, cx| {
9300 assert!(workspace.right_dock().read(cx).is_open());
9301 assert!(!panel.is_zoomed(window, cx));
9302 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
9303 });
9304
9305 // Transfer focus from panel to center
9306 workspace.update_in(cx, |workspace, window, cx| {
9307 workspace.toggle_panel_focus::<TestPanel>(window, cx);
9308 });
9309
9310 workspace.update_in(cx, |workspace, window, cx| {
9311 assert!(workspace.right_dock().read(cx).is_open());
9312 assert!(!panel.is_zoomed(window, cx));
9313 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
9314 });
9315
9316 // Close the dock
9317 workspace.update_in(cx, |workspace, window, cx| {
9318 workspace.toggle_dock(DockPosition::Right, window, cx);
9319 });
9320
9321 workspace.update_in(cx, |workspace, window, cx| {
9322 assert!(!workspace.right_dock().read(cx).is_open());
9323 assert!(!panel.is_zoomed(window, cx));
9324 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
9325 });
9326
9327 // Open the dock
9328 workspace.update_in(cx, |workspace, window, cx| {
9329 workspace.toggle_dock(DockPosition::Right, window, cx);
9330 });
9331
9332 workspace.update_in(cx, |workspace, window, cx| {
9333 assert!(workspace.right_dock().read(cx).is_open());
9334 assert!(!panel.is_zoomed(window, cx));
9335 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
9336 });
9337
9338 // Focus and zoom panel
9339 panel.update_in(cx, |panel, window, cx| {
9340 cx.focus_self(window);
9341 panel.set_zoomed(true, window, cx)
9342 });
9343
9344 workspace.update_in(cx, |workspace, window, cx| {
9345 assert!(workspace.right_dock().read(cx).is_open());
9346 assert!(panel.is_zoomed(window, cx));
9347 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
9348 });
9349
9350 // Transfer focus to the center closes the dock
9351 workspace.update_in(cx, |workspace, window, cx| {
9352 workspace.toggle_panel_focus::<TestPanel>(window, cx);
9353 });
9354
9355 workspace.update_in(cx, |workspace, window, cx| {
9356 assert!(!workspace.right_dock().read(cx).is_open());
9357 assert!(panel.is_zoomed(window, cx));
9358 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
9359 });
9360
9361 // Transferring focus back to the panel keeps it zoomed
9362 workspace.update_in(cx, |workspace, window, cx| {
9363 workspace.toggle_panel_focus::<TestPanel>(window, cx);
9364 });
9365
9366 workspace.update_in(cx, |workspace, window, cx| {
9367 assert!(workspace.right_dock().read(cx).is_open());
9368 assert!(panel.is_zoomed(window, cx));
9369 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
9370 });
9371
9372 // Close the dock while it is zoomed
9373 workspace.update_in(cx, |workspace, window, cx| {
9374 workspace.toggle_dock(DockPosition::Right, window, cx)
9375 });
9376
9377 workspace.update_in(cx, |workspace, window, cx| {
9378 assert!(!workspace.right_dock().read(cx).is_open());
9379 assert!(panel.is_zoomed(window, cx));
9380 assert!(workspace.zoomed.is_none());
9381 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
9382 });
9383
9384 // Opening the dock, when it's zoomed, retains focus
9385 workspace.update_in(cx, |workspace, window, cx| {
9386 workspace.toggle_dock(DockPosition::Right, window, cx)
9387 });
9388
9389 workspace.update_in(cx, |workspace, window, cx| {
9390 assert!(workspace.right_dock().read(cx).is_open());
9391 assert!(panel.is_zoomed(window, cx));
9392 assert!(workspace.zoomed.is_some());
9393 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
9394 });
9395
9396 // Unzoom and close the panel, zoom the active pane.
9397 panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
9398 workspace.update_in(cx, |workspace, window, cx| {
9399 workspace.toggle_dock(DockPosition::Right, window, cx)
9400 });
9401 pane.update_in(cx, |pane, window, cx| {
9402 pane.toggle_zoom(&Default::default(), window, cx)
9403 });
9404
9405 // Opening a dock unzooms the pane.
9406 workspace.update_in(cx, |workspace, window, cx| {
9407 workspace.toggle_dock(DockPosition::Right, window, cx)
9408 });
9409 workspace.update_in(cx, |workspace, window, cx| {
9410 let pane = pane.read(cx);
9411 assert!(!pane.is_zoomed());
9412 assert!(!pane.focus_handle(cx).is_focused(window));
9413 assert!(workspace.right_dock().read(cx).is_open());
9414 assert!(workspace.zoomed.is_none());
9415 });
9416 }
9417
9418 #[gpui::test]
9419 async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
9420 init_test(cx);
9421 let fs = FakeFs::new(cx.executor());
9422
9423 let project = Project::test(fs, [], cx).await;
9424 let (workspace, cx) =
9425 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9426 workspace.update_in(cx, |workspace, window, cx| {
9427 // Open two docks
9428 let left_dock = workspace.dock_at_position(DockPosition::Left);
9429 let right_dock = workspace.dock_at_position(DockPosition::Right);
9430
9431 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
9432 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
9433
9434 assert!(left_dock.read(cx).is_open());
9435 assert!(right_dock.read(cx).is_open());
9436 });
9437
9438 workspace.update_in(cx, |workspace, window, cx| {
9439 // Toggle all docks - should close both
9440 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
9441
9442 let left_dock = workspace.dock_at_position(DockPosition::Left);
9443 let right_dock = workspace.dock_at_position(DockPosition::Right);
9444 assert!(!left_dock.read(cx).is_open());
9445 assert!(!right_dock.read(cx).is_open());
9446 });
9447
9448 workspace.update_in(cx, |workspace, window, cx| {
9449 // Toggle again - should reopen both
9450 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
9451
9452 let left_dock = workspace.dock_at_position(DockPosition::Left);
9453 let right_dock = workspace.dock_at_position(DockPosition::Right);
9454 assert!(left_dock.read(cx).is_open());
9455 assert!(right_dock.read(cx).is_open());
9456 });
9457 }
9458
9459 #[gpui::test]
9460 async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
9461 init_test(cx);
9462 let fs = FakeFs::new(cx.executor());
9463
9464 let project = Project::test(fs, [], cx).await;
9465 let (workspace, cx) =
9466 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9467 workspace.update_in(cx, |workspace, window, cx| {
9468 // Open two docks
9469 let left_dock = workspace.dock_at_position(DockPosition::Left);
9470 let right_dock = workspace.dock_at_position(DockPosition::Right);
9471
9472 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
9473 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
9474
9475 assert!(left_dock.read(cx).is_open());
9476 assert!(right_dock.read(cx).is_open());
9477 });
9478
9479 workspace.update_in(cx, |workspace, window, cx| {
9480 // Close them manually
9481 workspace.toggle_dock(DockPosition::Left, window, cx);
9482 workspace.toggle_dock(DockPosition::Right, window, cx);
9483
9484 let left_dock = workspace.dock_at_position(DockPosition::Left);
9485 let right_dock = workspace.dock_at_position(DockPosition::Right);
9486 assert!(!left_dock.read(cx).is_open());
9487 assert!(!right_dock.read(cx).is_open());
9488 });
9489
9490 workspace.update_in(cx, |workspace, window, cx| {
9491 // Toggle all docks - only last closed (right dock) should reopen
9492 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
9493
9494 let left_dock = workspace.dock_at_position(DockPosition::Left);
9495 let right_dock = workspace.dock_at_position(DockPosition::Right);
9496 assert!(!left_dock.read(cx).is_open());
9497 assert!(right_dock.read(cx).is_open());
9498 });
9499 }
9500
9501 #[gpui::test]
9502 async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
9503 init_test(cx);
9504 let fs = FakeFs::new(cx.executor());
9505 let project = Project::test(fs, [], cx).await;
9506 let (workspace, cx) =
9507 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9508
9509 // Open two docks (left and right) with one panel each
9510 let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
9511 let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
9512 workspace.add_panel(left_panel.clone(), window, cx);
9513
9514 let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
9515 workspace.add_panel(right_panel.clone(), window, cx);
9516
9517 workspace.toggle_dock(DockPosition::Left, window, cx);
9518 workspace.toggle_dock(DockPosition::Right, window, cx);
9519
9520 // Verify initial state
9521 assert!(
9522 workspace.left_dock().read(cx).is_open(),
9523 "Left dock should be open"
9524 );
9525 assert_eq!(
9526 workspace
9527 .left_dock()
9528 .read(cx)
9529 .visible_panel()
9530 .unwrap()
9531 .panel_id(),
9532 left_panel.panel_id(),
9533 "Left panel should be visible in left dock"
9534 );
9535 assert!(
9536 workspace.right_dock().read(cx).is_open(),
9537 "Right dock should be open"
9538 );
9539 assert_eq!(
9540 workspace
9541 .right_dock()
9542 .read(cx)
9543 .visible_panel()
9544 .unwrap()
9545 .panel_id(),
9546 right_panel.panel_id(),
9547 "Right panel should be visible in right dock"
9548 );
9549 assert!(
9550 !workspace.bottom_dock().read(cx).is_open(),
9551 "Bottom dock should be closed"
9552 );
9553
9554 (left_panel, right_panel)
9555 });
9556
9557 // Focus the left panel and move it to the next position (bottom dock)
9558 workspace.update_in(cx, |workspace, window, cx| {
9559 workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
9560 assert!(
9561 left_panel.read(cx).focus_handle(cx).is_focused(window),
9562 "Left panel should be focused"
9563 );
9564 });
9565
9566 cx.dispatch_action(MoveFocusedPanelToNextPosition);
9567
9568 // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
9569 workspace.update(cx, |workspace, cx| {
9570 assert!(
9571 !workspace.left_dock().read(cx).is_open(),
9572 "Left dock should be closed"
9573 );
9574 assert!(
9575 workspace.bottom_dock().read(cx).is_open(),
9576 "Bottom dock should now be open"
9577 );
9578 assert_eq!(
9579 left_panel.read(cx).position,
9580 DockPosition::Bottom,
9581 "Left panel should now be in the bottom dock"
9582 );
9583 assert_eq!(
9584 workspace
9585 .bottom_dock()
9586 .read(cx)
9587 .visible_panel()
9588 .unwrap()
9589 .panel_id(),
9590 left_panel.panel_id(),
9591 "Left panel should be the visible panel in the bottom dock"
9592 );
9593 });
9594
9595 // Toggle all docks off
9596 workspace.update_in(cx, |workspace, window, cx| {
9597 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
9598 assert!(
9599 !workspace.left_dock().read(cx).is_open(),
9600 "Left dock should be closed"
9601 );
9602 assert!(
9603 !workspace.right_dock().read(cx).is_open(),
9604 "Right dock should be closed"
9605 );
9606 assert!(
9607 !workspace.bottom_dock().read(cx).is_open(),
9608 "Bottom dock should be closed"
9609 );
9610 });
9611
9612 // Toggle all docks back on and verify positions are restored
9613 workspace.update_in(cx, |workspace, window, cx| {
9614 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
9615 assert!(
9616 !workspace.left_dock().read(cx).is_open(),
9617 "Left dock should remain closed"
9618 );
9619 assert!(
9620 workspace.right_dock().read(cx).is_open(),
9621 "Right dock should remain open"
9622 );
9623 assert!(
9624 workspace.bottom_dock().read(cx).is_open(),
9625 "Bottom dock should remain open"
9626 );
9627 assert_eq!(
9628 left_panel.read(cx).position,
9629 DockPosition::Bottom,
9630 "Left panel should remain in the bottom dock"
9631 );
9632 assert_eq!(
9633 right_panel.read(cx).position,
9634 DockPosition::Right,
9635 "Right panel should remain in the right dock"
9636 );
9637 assert_eq!(
9638 workspace
9639 .bottom_dock()
9640 .read(cx)
9641 .visible_panel()
9642 .unwrap()
9643 .panel_id(),
9644 left_panel.panel_id(),
9645 "Left panel should be the visible panel in the right dock"
9646 );
9647 });
9648 }
9649
9650 #[gpui::test]
9651 async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
9652 init_test(cx);
9653
9654 let fs = FakeFs::new(cx.executor());
9655
9656 let project = Project::test(fs, None, cx).await;
9657 let (workspace, cx) =
9658 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9659
9660 // Let's arrange the panes like this:
9661 //
9662 // +-----------------------+
9663 // | top |
9664 // +------+--------+-------+
9665 // | left | center | right |
9666 // +------+--------+-------+
9667 // | bottom |
9668 // +-----------------------+
9669
9670 let top_item = cx.new(|cx| {
9671 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
9672 });
9673 let bottom_item = cx.new(|cx| {
9674 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
9675 });
9676 let left_item = cx.new(|cx| {
9677 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
9678 });
9679 let right_item = cx.new(|cx| {
9680 TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
9681 });
9682 let center_item = cx.new(|cx| {
9683 TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
9684 });
9685
9686 let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
9687 let top_pane_id = workspace.active_pane().entity_id();
9688 workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
9689 workspace.split_pane(
9690 workspace.active_pane().clone(),
9691 SplitDirection::Down,
9692 window,
9693 cx,
9694 );
9695 top_pane_id
9696 });
9697 let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
9698 let bottom_pane_id = workspace.active_pane().entity_id();
9699 workspace.add_item_to_active_pane(
9700 Box::new(bottom_item.clone()),
9701 None,
9702 false,
9703 window,
9704 cx,
9705 );
9706 workspace.split_pane(
9707 workspace.active_pane().clone(),
9708 SplitDirection::Up,
9709 window,
9710 cx,
9711 );
9712 bottom_pane_id
9713 });
9714 let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
9715 let left_pane_id = workspace.active_pane().entity_id();
9716 workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
9717 workspace.split_pane(
9718 workspace.active_pane().clone(),
9719 SplitDirection::Right,
9720 window,
9721 cx,
9722 );
9723 left_pane_id
9724 });
9725 let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
9726 let right_pane_id = workspace.active_pane().entity_id();
9727 workspace.add_item_to_active_pane(
9728 Box::new(right_item.clone()),
9729 None,
9730 false,
9731 window,
9732 cx,
9733 );
9734 workspace.split_pane(
9735 workspace.active_pane().clone(),
9736 SplitDirection::Left,
9737 window,
9738 cx,
9739 );
9740 right_pane_id
9741 });
9742 let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
9743 let center_pane_id = workspace.active_pane().entity_id();
9744 workspace.add_item_to_active_pane(
9745 Box::new(center_item.clone()),
9746 None,
9747 false,
9748 window,
9749 cx,
9750 );
9751 center_pane_id
9752 });
9753 cx.executor().run_until_parked();
9754
9755 workspace.update_in(cx, |workspace, window, cx| {
9756 assert_eq!(center_pane_id, workspace.active_pane().entity_id());
9757
9758 // Join into next from center pane into right
9759 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
9760 });
9761
9762 workspace.update_in(cx, |workspace, window, cx| {
9763 let active_pane = workspace.active_pane();
9764 assert_eq!(right_pane_id, active_pane.entity_id());
9765 assert_eq!(2, active_pane.read(cx).items_len());
9766 let item_ids_in_pane =
9767 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
9768 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
9769 assert!(item_ids_in_pane.contains(&right_item.item_id()));
9770
9771 // Join into next from right pane into bottom
9772 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
9773 });
9774
9775 workspace.update_in(cx, |workspace, window, cx| {
9776 let active_pane = workspace.active_pane();
9777 assert_eq!(bottom_pane_id, active_pane.entity_id());
9778 assert_eq!(3, active_pane.read(cx).items_len());
9779 let item_ids_in_pane =
9780 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
9781 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
9782 assert!(item_ids_in_pane.contains(&right_item.item_id()));
9783 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
9784
9785 // Join into next from bottom pane into left
9786 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
9787 });
9788
9789 workspace.update_in(cx, |workspace, window, cx| {
9790 let active_pane = workspace.active_pane();
9791 assert_eq!(left_pane_id, active_pane.entity_id());
9792 assert_eq!(4, active_pane.read(cx).items_len());
9793 let item_ids_in_pane =
9794 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
9795 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
9796 assert!(item_ids_in_pane.contains(&right_item.item_id()));
9797 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
9798 assert!(item_ids_in_pane.contains(&left_item.item_id()));
9799
9800 // Join into next from left pane into top
9801 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
9802 });
9803
9804 workspace.update_in(cx, |workspace, window, cx| {
9805 let active_pane = workspace.active_pane();
9806 assert_eq!(top_pane_id, active_pane.entity_id());
9807 assert_eq!(5, active_pane.read(cx).items_len());
9808 let item_ids_in_pane =
9809 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
9810 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
9811 assert!(item_ids_in_pane.contains(&right_item.item_id()));
9812 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
9813 assert!(item_ids_in_pane.contains(&left_item.item_id()));
9814 assert!(item_ids_in_pane.contains(&top_item.item_id()));
9815
9816 // Single pane left: no-op
9817 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
9818 });
9819
9820 workspace.update(cx, |workspace, _cx| {
9821 let active_pane = workspace.active_pane();
9822 assert_eq!(top_pane_id, active_pane.entity_id());
9823 });
9824 }
9825
9826 fn add_an_item_to_active_pane(
9827 cx: &mut VisualTestContext,
9828 workspace: &Entity<Workspace>,
9829 item_id: u64,
9830 ) -> Entity<TestItem> {
9831 let item = cx.new(|cx| {
9832 TestItem::new(cx).with_project_items(&[TestProjectItem::new(
9833 item_id,
9834 "item{item_id}.txt",
9835 cx,
9836 )])
9837 });
9838 workspace.update_in(cx, |workspace, window, cx| {
9839 workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
9840 });
9841 item
9842 }
9843
9844 fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
9845 workspace.update_in(cx, |workspace, window, cx| {
9846 workspace.split_pane(
9847 workspace.active_pane().clone(),
9848 SplitDirection::Right,
9849 window,
9850 cx,
9851 )
9852 })
9853 }
9854
9855 #[gpui::test]
9856 async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
9857 init_test(cx);
9858 let fs = FakeFs::new(cx.executor());
9859 let project = Project::test(fs, None, cx).await;
9860 let (workspace, cx) =
9861 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9862
9863 add_an_item_to_active_pane(cx, &workspace, 1);
9864 split_pane(cx, &workspace);
9865 add_an_item_to_active_pane(cx, &workspace, 2);
9866 split_pane(cx, &workspace); // empty pane
9867 split_pane(cx, &workspace);
9868 let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
9869
9870 cx.executor().run_until_parked();
9871
9872 workspace.update(cx, |workspace, cx| {
9873 let num_panes = workspace.panes().len();
9874 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
9875 let active_item = workspace
9876 .active_pane()
9877 .read(cx)
9878 .active_item()
9879 .expect("item is in focus");
9880
9881 assert_eq!(num_panes, 4);
9882 assert_eq!(num_items_in_current_pane, 1);
9883 assert_eq!(active_item.item_id(), last_item.item_id());
9884 });
9885
9886 workspace.update_in(cx, |workspace, window, cx| {
9887 workspace.join_all_panes(window, cx);
9888 });
9889
9890 workspace.update(cx, |workspace, cx| {
9891 let num_panes = workspace.panes().len();
9892 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
9893 let active_item = workspace
9894 .active_pane()
9895 .read(cx)
9896 .active_item()
9897 .expect("item is in focus");
9898
9899 assert_eq!(num_panes, 1);
9900 assert_eq!(num_items_in_current_pane, 3);
9901 assert_eq!(active_item.item_id(), last_item.item_id());
9902 });
9903 }
9904 struct TestModal(FocusHandle);
9905
9906 impl TestModal {
9907 fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
9908 Self(cx.focus_handle())
9909 }
9910 }
9911
9912 impl EventEmitter<DismissEvent> for TestModal {}
9913
9914 impl Focusable for TestModal {
9915 fn focus_handle(&self, _cx: &App) -> FocusHandle {
9916 self.0.clone()
9917 }
9918 }
9919
9920 impl ModalView for TestModal {}
9921
9922 impl Render for TestModal {
9923 fn render(
9924 &mut self,
9925 _window: &mut Window,
9926 _cx: &mut Context<TestModal>,
9927 ) -> impl IntoElement {
9928 div().track_focus(&self.0)
9929 }
9930 }
9931
9932 #[gpui::test]
9933 async fn test_panels(cx: &mut gpui::TestAppContext) {
9934 init_test(cx);
9935 let fs = FakeFs::new(cx.executor());
9936
9937 let project = Project::test(fs, [], cx).await;
9938 let (workspace, cx) =
9939 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9940
9941 let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
9942 let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
9943 workspace.add_panel(panel_1.clone(), window, cx);
9944 workspace.toggle_dock(DockPosition::Left, window, cx);
9945 let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
9946 workspace.add_panel(panel_2.clone(), window, cx);
9947 workspace.toggle_dock(DockPosition::Right, window, cx);
9948
9949 let left_dock = workspace.left_dock();
9950 assert_eq!(
9951 left_dock.read(cx).visible_panel().unwrap().panel_id(),
9952 panel_1.panel_id()
9953 );
9954 assert_eq!(
9955 left_dock.read(cx).active_panel_size(window, cx).unwrap(),
9956 panel_1.size(window, cx)
9957 );
9958
9959 left_dock.update(cx, |left_dock, cx| {
9960 left_dock.resize_active_panel(Some(px(1337.)), window, cx)
9961 });
9962 assert_eq!(
9963 workspace
9964 .right_dock()
9965 .read(cx)
9966 .visible_panel()
9967 .unwrap()
9968 .panel_id(),
9969 panel_2.panel_id(),
9970 );
9971
9972 (panel_1, panel_2)
9973 });
9974
9975 // Move panel_1 to the right
9976 panel_1.update_in(cx, |panel_1, window, cx| {
9977 panel_1.set_position(DockPosition::Right, window, cx)
9978 });
9979
9980 workspace.update_in(cx, |workspace, window, cx| {
9981 // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
9982 // Since it was the only panel on the left, the left dock should now be closed.
9983 assert!(!workspace.left_dock().read(cx).is_open());
9984 assert!(workspace.left_dock().read(cx).visible_panel().is_none());
9985 let right_dock = workspace.right_dock();
9986 assert_eq!(
9987 right_dock.read(cx).visible_panel().unwrap().panel_id(),
9988 panel_1.panel_id()
9989 );
9990 assert_eq!(
9991 right_dock.read(cx).active_panel_size(window, cx).unwrap(),
9992 px(1337.)
9993 );
9994
9995 // Now we move panel_2 to the left
9996 panel_2.set_position(DockPosition::Left, window, cx);
9997 });
9998
9999 workspace.update(cx, |workspace, cx| {
10000 // Since panel_2 was not visible on the right, we don't open the left dock.
10001 assert!(!workspace.left_dock().read(cx).is_open());
10002 // And the right dock is unaffected in its displaying of panel_1
10003 assert!(workspace.right_dock().read(cx).is_open());
10004 assert_eq!(
10005 workspace
10006 .right_dock()
10007 .read(cx)
10008 .visible_panel()
10009 .unwrap()
10010 .panel_id(),
10011 panel_1.panel_id(),
10012 );
10013 });
10014
10015 // Move panel_1 back to the left
10016 panel_1.update_in(cx, |panel_1, window, cx| {
10017 panel_1.set_position(DockPosition::Left, window, cx)
10018 });
10019
10020 workspace.update_in(cx, |workspace, window, cx| {
10021 // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
10022 let left_dock = workspace.left_dock();
10023 assert!(left_dock.read(cx).is_open());
10024 assert_eq!(
10025 left_dock.read(cx).visible_panel().unwrap().panel_id(),
10026 panel_1.panel_id()
10027 );
10028 assert_eq!(
10029 left_dock.read(cx).active_panel_size(window, cx).unwrap(),
10030 px(1337.)
10031 );
10032 // And the right dock should be closed as it no longer has any panels.
10033 assert!(!workspace.right_dock().read(cx).is_open());
10034
10035 // Now we move panel_1 to the bottom
10036 panel_1.set_position(DockPosition::Bottom, window, cx);
10037 });
10038
10039 workspace.update_in(cx, |workspace, window, cx| {
10040 // Since panel_1 was visible on the left, we close the left dock.
10041 assert!(!workspace.left_dock().read(cx).is_open());
10042 // The bottom dock is sized based on the panel's default size,
10043 // since the panel orientation changed from vertical to horizontal.
10044 let bottom_dock = workspace.bottom_dock();
10045 assert_eq!(
10046 bottom_dock.read(cx).active_panel_size(window, cx).unwrap(),
10047 panel_1.size(window, cx),
10048 );
10049 // Close bottom dock and move panel_1 back to the left.
10050 bottom_dock.update(cx, |bottom_dock, cx| {
10051 bottom_dock.set_open(false, window, cx)
10052 });
10053 panel_1.set_position(DockPosition::Left, window, cx);
10054 });
10055
10056 // Emit activated event on panel 1
10057 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
10058
10059 // Now the left dock is open and panel_1 is active and focused.
10060 workspace.update_in(cx, |workspace, window, cx| {
10061 let left_dock = workspace.left_dock();
10062 assert!(left_dock.read(cx).is_open());
10063 assert_eq!(
10064 left_dock.read(cx).visible_panel().unwrap().panel_id(),
10065 panel_1.panel_id(),
10066 );
10067 assert!(panel_1.focus_handle(cx).is_focused(window));
10068 });
10069
10070 // Emit closed event on panel 2, which is not active
10071 panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
10072
10073 // Wo don't close the left dock, because panel_2 wasn't the active panel
10074 workspace.update(cx, |workspace, cx| {
10075 let left_dock = workspace.left_dock();
10076 assert!(left_dock.read(cx).is_open());
10077 assert_eq!(
10078 left_dock.read(cx).visible_panel().unwrap().panel_id(),
10079 panel_1.panel_id(),
10080 );
10081 });
10082
10083 // Emitting a ZoomIn event shows the panel as zoomed.
10084 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
10085 workspace.read_with(cx, |workspace, _| {
10086 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
10087 assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
10088 });
10089
10090 // Move panel to another dock while it is zoomed
10091 panel_1.update_in(cx, |panel, window, cx| {
10092 panel.set_position(DockPosition::Right, window, cx)
10093 });
10094 workspace.read_with(cx, |workspace, _| {
10095 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
10096
10097 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
10098 });
10099
10100 // This is a helper for getting a:
10101 // - valid focus on an element,
10102 // - that isn't a part of the panes and panels system of the Workspace,
10103 // - and doesn't trigger the 'on_focus_lost' API.
10104 let focus_other_view = {
10105 let workspace = workspace.clone();
10106 move |cx: &mut VisualTestContext| {
10107 workspace.update_in(cx, |workspace, window, cx| {
10108 if workspace.active_modal::<TestModal>(cx).is_some() {
10109 workspace.toggle_modal(window, cx, TestModal::new);
10110 workspace.toggle_modal(window, cx, TestModal::new);
10111 } else {
10112 workspace.toggle_modal(window, cx, TestModal::new);
10113 }
10114 })
10115 }
10116 };
10117
10118 // If focus is transferred to another view that's not a panel or another pane, we still show
10119 // the panel as zoomed.
10120 focus_other_view(cx);
10121 workspace.read_with(cx, |workspace, _| {
10122 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
10123 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
10124 });
10125
10126 // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
10127 workspace.update_in(cx, |_workspace, window, cx| {
10128 cx.focus_self(window);
10129 });
10130 workspace.read_with(cx, |workspace, _| {
10131 assert_eq!(workspace.zoomed, None);
10132 assert_eq!(workspace.zoomed_position, None);
10133 });
10134
10135 // If focus is transferred again to another view that's not a panel or a pane, we won't
10136 // show the panel as zoomed because it wasn't zoomed before.
10137 focus_other_view(cx);
10138 workspace.read_with(cx, |workspace, _| {
10139 assert_eq!(workspace.zoomed, None);
10140 assert_eq!(workspace.zoomed_position, None);
10141 });
10142
10143 // When the panel is activated, it is zoomed again.
10144 cx.dispatch_action(ToggleRightDock);
10145 workspace.read_with(cx, |workspace, _| {
10146 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
10147 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
10148 });
10149
10150 // Emitting a ZoomOut event unzooms the panel.
10151 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
10152 workspace.read_with(cx, |workspace, _| {
10153 assert_eq!(workspace.zoomed, None);
10154 assert_eq!(workspace.zoomed_position, None);
10155 });
10156
10157 // Emit closed event on panel 1, which is active
10158 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
10159
10160 // Now the left dock is closed, because panel_1 was the active panel
10161 workspace.update(cx, |workspace, cx| {
10162 let right_dock = workspace.right_dock();
10163 assert!(!right_dock.read(cx).is_open());
10164 });
10165 }
10166
10167 #[gpui::test]
10168 async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
10169 init_test(cx);
10170
10171 let fs = FakeFs::new(cx.background_executor.clone());
10172 let project = Project::test(fs, [], cx).await;
10173 let (workspace, cx) =
10174 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10175 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10176
10177 let dirty_regular_buffer = cx.new(|cx| {
10178 TestItem::new(cx)
10179 .with_dirty(true)
10180 .with_label("1.txt")
10181 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10182 });
10183 let dirty_regular_buffer_2 = cx.new(|cx| {
10184 TestItem::new(cx)
10185 .with_dirty(true)
10186 .with_label("2.txt")
10187 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10188 });
10189 let dirty_multi_buffer_with_both = cx.new(|cx| {
10190 TestItem::new(cx)
10191 .with_dirty(true)
10192 .with_buffer_kind(ItemBufferKind::Multibuffer)
10193 .with_label("Fake Project Search")
10194 .with_project_items(&[
10195 dirty_regular_buffer.read(cx).project_items[0].clone(),
10196 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
10197 ])
10198 });
10199 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
10200 workspace.update_in(cx, |workspace, window, cx| {
10201 workspace.add_item(
10202 pane.clone(),
10203 Box::new(dirty_regular_buffer.clone()),
10204 None,
10205 false,
10206 false,
10207 window,
10208 cx,
10209 );
10210 workspace.add_item(
10211 pane.clone(),
10212 Box::new(dirty_regular_buffer_2.clone()),
10213 None,
10214 false,
10215 false,
10216 window,
10217 cx,
10218 );
10219 workspace.add_item(
10220 pane.clone(),
10221 Box::new(dirty_multi_buffer_with_both.clone()),
10222 None,
10223 false,
10224 false,
10225 window,
10226 cx,
10227 );
10228 });
10229
10230 pane.update_in(cx, |pane, window, cx| {
10231 pane.activate_item(2, true, true, window, cx);
10232 assert_eq!(
10233 pane.active_item().unwrap().item_id(),
10234 multi_buffer_with_both_files_id,
10235 "Should select the multi buffer in the pane"
10236 );
10237 });
10238 let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
10239 pane.close_other_items(
10240 &CloseOtherItems {
10241 save_intent: Some(SaveIntent::Save),
10242 close_pinned: true,
10243 },
10244 None,
10245 window,
10246 cx,
10247 )
10248 });
10249 cx.background_executor.run_until_parked();
10250 assert!(!cx.has_pending_prompt());
10251 close_all_but_multi_buffer_task
10252 .await
10253 .expect("Closing all buffers but the multi buffer failed");
10254 pane.update(cx, |pane, cx| {
10255 assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
10256 assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
10257 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
10258 assert_eq!(pane.items_len(), 1);
10259 assert_eq!(
10260 pane.active_item().unwrap().item_id(),
10261 multi_buffer_with_both_files_id,
10262 "Should have only the multi buffer left in the pane"
10263 );
10264 assert!(
10265 dirty_multi_buffer_with_both.read(cx).is_dirty,
10266 "The multi buffer containing the unsaved buffer should still be dirty"
10267 );
10268 });
10269
10270 dirty_regular_buffer.update(cx, |buffer, cx| {
10271 buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
10272 });
10273
10274 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
10275 pane.close_active_item(
10276 &CloseActiveItem {
10277 save_intent: Some(SaveIntent::Close),
10278 close_pinned: false,
10279 },
10280 window,
10281 cx,
10282 )
10283 });
10284 cx.background_executor.run_until_parked();
10285 assert!(
10286 cx.has_pending_prompt(),
10287 "Dirty multi buffer should prompt a save dialog"
10288 );
10289 cx.simulate_prompt_answer("Save");
10290 cx.background_executor.run_until_parked();
10291 close_multi_buffer_task
10292 .await
10293 .expect("Closing the multi buffer failed");
10294 pane.update(cx, |pane, cx| {
10295 assert_eq!(
10296 dirty_multi_buffer_with_both.read(cx).save_count,
10297 1,
10298 "Multi buffer item should get be saved"
10299 );
10300 // Test impl does not save inner items, so we do not assert them
10301 assert_eq!(
10302 pane.items_len(),
10303 0,
10304 "No more items should be left in the pane"
10305 );
10306 assert!(pane.active_item().is_none());
10307 });
10308 }
10309
10310 #[gpui::test]
10311 async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
10312 cx: &mut TestAppContext,
10313 ) {
10314 init_test(cx);
10315
10316 let fs = FakeFs::new(cx.background_executor.clone());
10317 let project = Project::test(fs, [], cx).await;
10318 let (workspace, cx) =
10319 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10320 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10321
10322 let dirty_regular_buffer = cx.new(|cx| {
10323 TestItem::new(cx)
10324 .with_dirty(true)
10325 .with_label("1.txt")
10326 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10327 });
10328 let dirty_regular_buffer_2 = cx.new(|cx| {
10329 TestItem::new(cx)
10330 .with_dirty(true)
10331 .with_label("2.txt")
10332 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10333 });
10334 let clear_regular_buffer = cx.new(|cx| {
10335 TestItem::new(cx)
10336 .with_label("3.txt")
10337 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
10338 });
10339
10340 let dirty_multi_buffer_with_both = cx.new(|cx| {
10341 TestItem::new(cx)
10342 .with_dirty(true)
10343 .with_buffer_kind(ItemBufferKind::Multibuffer)
10344 .with_label("Fake Project Search")
10345 .with_project_items(&[
10346 dirty_regular_buffer.read(cx).project_items[0].clone(),
10347 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
10348 clear_regular_buffer.read(cx).project_items[0].clone(),
10349 ])
10350 });
10351 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
10352 workspace.update_in(cx, |workspace, window, cx| {
10353 workspace.add_item(
10354 pane.clone(),
10355 Box::new(dirty_regular_buffer.clone()),
10356 None,
10357 false,
10358 false,
10359 window,
10360 cx,
10361 );
10362 workspace.add_item(
10363 pane.clone(),
10364 Box::new(dirty_multi_buffer_with_both.clone()),
10365 None,
10366 false,
10367 false,
10368 window,
10369 cx,
10370 );
10371 });
10372
10373 pane.update_in(cx, |pane, window, cx| {
10374 pane.activate_item(1, true, true, window, cx);
10375 assert_eq!(
10376 pane.active_item().unwrap().item_id(),
10377 multi_buffer_with_both_files_id,
10378 "Should select the multi buffer in the pane"
10379 );
10380 });
10381 let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
10382 pane.close_active_item(
10383 &CloseActiveItem {
10384 save_intent: None,
10385 close_pinned: false,
10386 },
10387 window,
10388 cx,
10389 )
10390 });
10391 cx.background_executor.run_until_parked();
10392 assert!(
10393 cx.has_pending_prompt(),
10394 "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
10395 );
10396 }
10397
10398 /// Tests that when `close_on_file_delete` is enabled, files are automatically
10399 /// closed when they are deleted from disk.
10400 #[gpui::test]
10401 async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
10402 init_test(cx);
10403
10404 // Enable the close_on_disk_deletion setting
10405 cx.update_global(|store: &mut SettingsStore, cx| {
10406 store.update_user_settings(cx, |settings| {
10407 settings.workspace.close_on_file_delete = Some(true);
10408 });
10409 });
10410
10411 let fs = FakeFs::new(cx.background_executor.clone());
10412 let project = Project::test(fs, [], cx).await;
10413 let (workspace, cx) =
10414 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10415 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10416
10417 // Create a test item that simulates a file
10418 let item = cx.new(|cx| {
10419 TestItem::new(cx)
10420 .with_label("test.txt")
10421 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
10422 });
10423
10424 // Add item to workspace
10425 workspace.update_in(cx, |workspace, window, cx| {
10426 workspace.add_item(
10427 pane.clone(),
10428 Box::new(item.clone()),
10429 None,
10430 false,
10431 false,
10432 window,
10433 cx,
10434 );
10435 });
10436
10437 // Verify the item is in the pane
10438 pane.read_with(cx, |pane, _| {
10439 assert_eq!(pane.items().count(), 1);
10440 });
10441
10442 // Simulate file deletion by setting the item's deleted state
10443 item.update(cx, |item, _| {
10444 item.set_has_deleted_file(true);
10445 });
10446
10447 // Emit UpdateTab event to trigger the close behavior
10448 cx.run_until_parked();
10449 item.update(cx, |_, cx| {
10450 cx.emit(ItemEvent::UpdateTab);
10451 });
10452
10453 // Allow the close operation to complete
10454 cx.run_until_parked();
10455
10456 // Verify the item was automatically closed
10457 pane.read_with(cx, |pane, _| {
10458 assert_eq!(
10459 pane.items().count(),
10460 0,
10461 "Item should be automatically closed when file is deleted"
10462 );
10463 });
10464 }
10465
10466 /// Tests that when `close_on_file_delete` is disabled (default), files remain
10467 /// open with a strikethrough when they are deleted from disk.
10468 #[gpui::test]
10469 async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
10470 init_test(cx);
10471
10472 // Ensure close_on_disk_deletion is disabled (default)
10473 cx.update_global(|store: &mut SettingsStore, cx| {
10474 store.update_user_settings(cx, |settings| {
10475 settings.workspace.close_on_file_delete = Some(false);
10476 });
10477 });
10478
10479 let fs = FakeFs::new(cx.background_executor.clone());
10480 let project = Project::test(fs, [], cx).await;
10481 let (workspace, cx) =
10482 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10483 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10484
10485 // Create a test item that simulates a file
10486 let item = cx.new(|cx| {
10487 TestItem::new(cx)
10488 .with_label("test.txt")
10489 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
10490 });
10491
10492 // Add item to workspace
10493 workspace.update_in(cx, |workspace, window, cx| {
10494 workspace.add_item(
10495 pane.clone(),
10496 Box::new(item.clone()),
10497 None,
10498 false,
10499 false,
10500 window,
10501 cx,
10502 );
10503 });
10504
10505 // Verify the item is in the pane
10506 pane.read_with(cx, |pane, _| {
10507 assert_eq!(pane.items().count(), 1);
10508 });
10509
10510 // Simulate file deletion
10511 item.update(cx, |item, _| {
10512 item.set_has_deleted_file(true);
10513 });
10514
10515 // Emit UpdateTab event
10516 cx.run_until_parked();
10517 item.update(cx, |_, cx| {
10518 cx.emit(ItemEvent::UpdateTab);
10519 });
10520
10521 // Allow any potential close operation to complete
10522 cx.run_until_parked();
10523
10524 // Verify the item remains open (with strikethrough)
10525 pane.read_with(cx, |pane, _| {
10526 assert_eq!(
10527 pane.items().count(),
10528 1,
10529 "Item should remain open when close_on_disk_deletion is disabled"
10530 );
10531 });
10532
10533 // Verify the item shows as deleted
10534 item.read_with(cx, |item, _| {
10535 assert!(
10536 item.has_deleted_file,
10537 "Item should be marked as having deleted file"
10538 );
10539 });
10540 }
10541
10542 /// Tests that dirty files are not automatically closed when deleted from disk,
10543 /// even when `close_on_file_delete` is enabled. This ensures users don't lose
10544 /// unsaved changes without being prompted.
10545 #[gpui::test]
10546 async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
10547 init_test(cx);
10548
10549 // Enable the close_on_file_delete setting
10550 cx.update_global(|store: &mut SettingsStore, cx| {
10551 store.update_user_settings(cx, |settings| {
10552 settings.workspace.close_on_file_delete = Some(true);
10553 });
10554 });
10555
10556 let fs = FakeFs::new(cx.background_executor.clone());
10557 let project = Project::test(fs, [], cx).await;
10558 let (workspace, cx) =
10559 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10560 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10561
10562 // Create a dirty test item
10563 let item = cx.new(|cx| {
10564 TestItem::new(cx)
10565 .with_dirty(true)
10566 .with_label("test.txt")
10567 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
10568 });
10569
10570 // Add item to workspace
10571 workspace.update_in(cx, |workspace, window, cx| {
10572 workspace.add_item(
10573 pane.clone(),
10574 Box::new(item.clone()),
10575 None,
10576 false,
10577 false,
10578 window,
10579 cx,
10580 );
10581 });
10582
10583 // Simulate file deletion
10584 item.update(cx, |item, _| {
10585 item.set_has_deleted_file(true);
10586 });
10587
10588 // Emit UpdateTab event to trigger the close behavior
10589 cx.run_until_parked();
10590 item.update(cx, |_, cx| {
10591 cx.emit(ItemEvent::UpdateTab);
10592 });
10593
10594 // Allow any potential close operation to complete
10595 cx.run_until_parked();
10596
10597 // Verify the item remains open (dirty files are not auto-closed)
10598 pane.read_with(cx, |pane, _| {
10599 assert_eq!(
10600 pane.items().count(),
10601 1,
10602 "Dirty items should not be automatically closed even when file is deleted"
10603 );
10604 });
10605
10606 // Verify the item is marked as deleted and still dirty
10607 item.read_with(cx, |item, _| {
10608 assert!(
10609 item.has_deleted_file,
10610 "Item should be marked as having deleted file"
10611 );
10612 assert!(item.is_dirty, "Item should still be dirty");
10613 });
10614 }
10615
10616 /// Tests that navigation history is cleaned up when files are auto-closed
10617 /// due to deletion from disk.
10618 #[gpui::test]
10619 async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
10620 init_test(cx);
10621
10622 // Enable the close_on_file_delete setting
10623 cx.update_global(|store: &mut SettingsStore, cx| {
10624 store.update_user_settings(cx, |settings| {
10625 settings.workspace.close_on_file_delete = Some(true);
10626 });
10627 });
10628
10629 let fs = FakeFs::new(cx.background_executor.clone());
10630 let project = Project::test(fs, [], cx).await;
10631 let (workspace, cx) =
10632 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10633 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10634
10635 // Create test items
10636 let item1 = cx.new(|cx| {
10637 TestItem::new(cx)
10638 .with_label("test1.txt")
10639 .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
10640 });
10641 let item1_id = item1.item_id();
10642
10643 let item2 = cx.new(|cx| {
10644 TestItem::new(cx)
10645 .with_label("test2.txt")
10646 .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
10647 });
10648
10649 // Add items to workspace
10650 workspace.update_in(cx, |workspace, window, cx| {
10651 workspace.add_item(
10652 pane.clone(),
10653 Box::new(item1.clone()),
10654 None,
10655 false,
10656 false,
10657 window,
10658 cx,
10659 );
10660 workspace.add_item(
10661 pane.clone(),
10662 Box::new(item2.clone()),
10663 None,
10664 false,
10665 false,
10666 window,
10667 cx,
10668 );
10669 });
10670
10671 // Activate item1 to ensure it gets navigation entries
10672 pane.update_in(cx, |pane, window, cx| {
10673 pane.activate_item(0, true, true, window, cx);
10674 });
10675
10676 // Switch to item2 and back to create navigation history
10677 pane.update_in(cx, |pane, window, cx| {
10678 pane.activate_item(1, true, true, window, cx);
10679 });
10680 cx.run_until_parked();
10681
10682 pane.update_in(cx, |pane, window, cx| {
10683 pane.activate_item(0, true, true, window, cx);
10684 });
10685 cx.run_until_parked();
10686
10687 // Simulate file deletion for item1
10688 item1.update(cx, |item, _| {
10689 item.set_has_deleted_file(true);
10690 });
10691
10692 // Emit UpdateTab event to trigger the close behavior
10693 item1.update(cx, |_, cx| {
10694 cx.emit(ItemEvent::UpdateTab);
10695 });
10696 cx.run_until_parked();
10697
10698 // Verify item1 was closed
10699 pane.read_with(cx, |pane, _| {
10700 assert_eq!(
10701 pane.items().count(),
10702 1,
10703 "Should have 1 item remaining after auto-close"
10704 );
10705 });
10706
10707 // Check navigation history after close
10708 let has_item = pane.read_with(cx, |pane, cx| {
10709 let mut has_item = false;
10710 pane.nav_history().for_each_entry(cx, |entry, _| {
10711 if entry.item.id() == item1_id {
10712 has_item = true;
10713 }
10714 });
10715 has_item
10716 });
10717
10718 assert!(
10719 !has_item,
10720 "Navigation history should not contain closed item entries"
10721 );
10722 }
10723
10724 #[gpui::test]
10725 async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
10726 cx: &mut TestAppContext,
10727 ) {
10728 init_test(cx);
10729
10730 let fs = FakeFs::new(cx.background_executor.clone());
10731 let project = Project::test(fs, [], cx).await;
10732 let (workspace, cx) =
10733 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10734 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10735
10736 let dirty_regular_buffer = cx.new(|cx| {
10737 TestItem::new(cx)
10738 .with_dirty(true)
10739 .with_label("1.txt")
10740 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10741 });
10742 let dirty_regular_buffer_2 = cx.new(|cx| {
10743 TestItem::new(cx)
10744 .with_dirty(true)
10745 .with_label("2.txt")
10746 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10747 });
10748 let clear_regular_buffer = cx.new(|cx| {
10749 TestItem::new(cx)
10750 .with_label("3.txt")
10751 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
10752 });
10753
10754 let dirty_multi_buffer = cx.new(|cx| {
10755 TestItem::new(cx)
10756 .with_dirty(true)
10757 .with_buffer_kind(ItemBufferKind::Multibuffer)
10758 .with_label("Fake Project Search")
10759 .with_project_items(&[
10760 dirty_regular_buffer.read(cx).project_items[0].clone(),
10761 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
10762 clear_regular_buffer.read(cx).project_items[0].clone(),
10763 ])
10764 });
10765 workspace.update_in(cx, |workspace, window, cx| {
10766 workspace.add_item(
10767 pane.clone(),
10768 Box::new(dirty_regular_buffer.clone()),
10769 None,
10770 false,
10771 false,
10772 window,
10773 cx,
10774 );
10775 workspace.add_item(
10776 pane.clone(),
10777 Box::new(dirty_regular_buffer_2.clone()),
10778 None,
10779 false,
10780 false,
10781 window,
10782 cx,
10783 );
10784 workspace.add_item(
10785 pane.clone(),
10786 Box::new(dirty_multi_buffer.clone()),
10787 None,
10788 false,
10789 false,
10790 window,
10791 cx,
10792 );
10793 });
10794
10795 pane.update_in(cx, |pane, window, cx| {
10796 pane.activate_item(2, true, true, window, cx);
10797 assert_eq!(
10798 pane.active_item().unwrap().item_id(),
10799 dirty_multi_buffer.item_id(),
10800 "Should select the multi buffer in the pane"
10801 );
10802 });
10803 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
10804 pane.close_active_item(
10805 &CloseActiveItem {
10806 save_intent: None,
10807 close_pinned: false,
10808 },
10809 window,
10810 cx,
10811 )
10812 });
10813 cx.background_executor.run_until_parked();
10814 assert!(
10815 !cx.has_pending_prompt(),
10816 "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
10817 );
10818 close_multi_buffer_task
10819 .await
10820 .expect("Closing multi buffer failed");
10821 pane.update(cx, |pane, cx| {
10822 assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
10823 assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
10824 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
10825 assert_eq!(
10826 pane.items()
10827 .map(|item| item.item_id())
10828 .sorted()
10829 .collect::<Vec<_>>(),
10830 vec![
10831 dirty_regular_buffer.item_id(),
10832 dirty_regular_buffer_2.item_id(),
10833 ],
10834 "Should have no multi buffer left in the pane"
10835 );
10836 assert!(dirty_regular_buffer.read(cx).is_dirty);
10837 assert!(dirty_regular_buffer_2.read(cx).is_dirty);
10838 });
10839 }
10840
10841 #[gpui::test]
10842 async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
10843 init_test(cx);
10844 let fs = FakeFs::new(cx.executor());
10845 let project = Project::test(fs, [], cx).await;
10846 let (workspace, cx) =
10847 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10848
10849 // Add a new panel to the right dock, opening the dock and setting the
10850 // focus to the new panel.
10851 let panel = workspace.update_in(cx, |workspace, window, cx| {
10852 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
10853 workspace.add_panel(panel.clone(), window, cx);
10854
10855 workspace
10856 .right_dock()
10857 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
10858
10859 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10860
10861 panel
10862 });
10863
10864 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
10865 // panel to the next valid position which, in this case, is the left
10866 // dock.
10867 cx.dispatch_action(MoveFocusedPanelToNextPosition);
10868 workspace.update(cx, |workspace, cx| {
10869 assert!(workspace.left_dock().read(cx).is_open());
10870 assert_eq!(panel.read(cx).position, DockPosition::Left);
10871 });
10872
10873 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
10874 // panel to the next valid position which, in this case, is the bottom
10875 // dock.
10876 cx.dispatch_action(MoveFocusedPanelToNextPosition);
10877 workspace.update(cx, |workspace, cx| {
10878 assert!(workspace.bottom_dock().read(cx).is_open());
10879 assert_eq!(panel.read(cx).position, DockPosition::Bottom);
10880 });
10881
10882 // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
10883 // around moving the panel to its initial position, the right dock.
10884 cx.dispatch_action(MoveFocusedPanelToNextPosition);
10885 workspace.update(cx, |workspace, cx| {
10886 assert!(workspace.right_dock().read(cx).is_open());
10887 assert_eq!(panel.read(cx).position, DockPosition::Right);
10888 });
10889
10890 // Remove focus from the panel, ensuring that, if the panel is not
10891 // focused, the `MoveFocusedPanelToNextPosition` action does not update
10892 // the panel's position, so the panel is still in the right dock.
10893 workspace.update_in(cx, |workspace, window, cx| {
10894 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10895 });
10896
10897 cx.dispatch_action(MoveFocusedPanelToNextPosition);
10898 workspace.update(cx, |workspace, cx| {
10899 assert!(workspace.right_dock().read(cx).is_open());
10900 assert_eq!(panel.read(cx).position, DockPosition::Right);
10901 });
10902 }
10903
10904 #[gpui::test]
10905 async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
10906 init_test(cx);
10907
10908 let fs = FakeFs::new(cx.executor());
10909 let project = Project::test(fs, [], cx).await;
10910 let (workspace, cx) =
10911 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10912
10913 let item_1 = cx.new(|cx| {
10914 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
10915 });
10916 workspace.update_in(cx, |workspace, window, cx| {
10917 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
10918 workspace.move_item_to_pane_in_direction(
10919 &MoveItemToPaneInDirection {
10920 direction: SplitDirection::Right,
10921 focus: true,
10922 clone: false,
10923 },
10924 window,
10925 cx,
10926 );
10927 workspace.move_item_to_pane_at_index(
10928 &MoveItemToPane {
10929 destination: 3,
10930 focus: true,
10931 clone: false,
10932 },
10933 window,
10934 cx,
10935 );
10936
10937 assert_eq!(workspace.panes.len(), 1, "No new panes were created");
10938 assert_eq!(
10939 pane_items_paths(&workspace.active_pane, cx),
10940 vec!["first.txt".to_string()],
10941 "Single item was not moved anywhere"
10942 );
10943 });
10944
10945 let item_2 = cx.new(|cx| {
10946 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
10947 });
10948 workspace.update_in(cx, |workspace, window, cx| {
10949 workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
10950 assert_eq!(
10951 pane_items_paths(&workspace.panes[0], cx),
10952 vec!["first.txt".to_string(), "second.txt".to_string()],
10953 );
10954 workspace.move_item_to_pane_in_direction(
10955 &MoveItemToPaneInDirection {
10956 direction: SplitDirection::Right,
10957 focus: true,
10958 clone: false,
10959 },
10960 window,
10961 cx,
10962 );
10963
10964 assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
10965 assert_eq!(
10966 pane_items_paths(&workspace.panes[0], cx),
10967 vec!["first.txt".to_string()],
10968 "After moving, one item should be left in the original pane"
10969 );
10970 assert_eq!(
10971 pane_items_paths(&workspace.panes[1], cx),
10972 vec!["second.txt".to_string()],
10973 "New item should have been moved to the new pane"
10974 );
10975 });
10976
10977 let item_3 = cx.new(|cx| {
10978 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
10979 });
10980 workspace.update_in(cx, |workspace, window, cx| {
10981 let original_pane = workspace.panes[0].clone();
10982 workspace.set_active_pane(&original_pane, window, cx);
10983 workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
10984 assert_eq!(workspace.panes.len(), 2, "No new panes were created");
10985 assert_eq!(
10986 pane_items_paths(&workspace.active_pane, cx),
10987 vec!["first.txt".to_string(), "third.txt".to_string()],
10988 "New pane should be ready to move one item out"
10989 );
10990
10991 workspace.move_item_to_pane_at_index(
10992 &MoveItemToPane {
10993 destination: 3,
10994 focus: true,
10995 clone: false,
10996 },
10997 window,
10998 cx,
10999 );
11000 assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
11001 assert_eq!(
11002 pane_items_paths(&workspace.active_pane, cx),
11003 vec!["first.txt".to_string()],
11004 "After moving, one item should be left in the original pane"
11005 );
11006 assert_eq!(
11007 pane_items_paths(&workspace.panes[1], cx),
11008 vec!["second.txt".to_string()],
11009 "Previously created pane should be unchanged"
11010 );
11011 assert_eq!(
11012 pane_items_paths(&workspace.panes[2], cx),
11013 vec!["third.txt".to_string()],
11014 "New item should have been moved to the new pane"
11015 );
11016 });
11017 }
11018
11019 #[gpui::test]
11020 async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
11021 init_test(cx);
11022
11023 let fs = FakeFs::new(cx.executor());
11024 let project = Project::test(fs, [], cx).await;
11025 let (workspace, cx) =
11026 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
11027
11028 let item_1 = cx.new(|cx| {
11029 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
11030 });
11031 workspace.update_in(cx, |workspace, window, cx| {
11032 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
11033 workspace.move_item_to_pane_in_direction(
11034 &MoveItemToPaneInDirection {
11035 direction: SplitDirection::Right,
11036 focus: true,
11037 clone: true,
11038 },
11039 window,
11040 cx,
11041 );
11042 workspace.move_item_to_pane_at_index(
11043 &MoveItemToPane {
11044 destination: 3,
11045 focus: true,
11046 clone: true,
11047 },
11048 window,
11049 cx,
11050 );
11051 });
11052 cx.run_until_parked();
11053
11054 workspace.update(cx, |workspace, cx| {
11055 assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
11056 for pane in workspace.panes() {
11057 assert_eq!(
11058 pane_items_paths(pane, cx),
11059 vec!["first.txt".to_string()],
11060 "Single item exists in all panes"
11061 );
11062 }
11063 });
11064
11065 // verify that the active pane has been updated after waiting for the
11066 // pane focus event to fire and resolve
11067 workspace.read_with(cx, |workspace, _app| {
11068 assert_eq!(
11069 workspace.active_pane(),
11070 &workspace.panes[2],
11071 "The third pane should be the active one: {:?}",
11072 workspace.panes
11073 );
11074 })
11075 }
11076
11077 mod register_project_item_tests {
11078
11079 use super::*;
11080
11081 // View
11082 struct TestPngItemView {
11083 focus_handle: FocusHandle,
11084 }
11085 // Model
11086 struct TestPngItem {}
11087
11088 impl project::ProjectItem for TestPngItem {
11089 fn try_open(
11090 _project: &Entity<Project>,
11091 path: &ProjectPath,
11092 cx: &mut App,
11093 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
11094 if path.path.extension().unwrap() == "png" {
11095 Some(cx.spawn(async move |cx| cx.new(|_| TestPngItem {})))
11096 } else {
11097 None
11098 }
11099 }
11100
11101 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
11102 None
11103 }
11104
11105 fn project_path(&self, _: &App) -> Option<ProjectPath> {
11106 None
11107 }
11108
11109 fn is_dirty(&self) -> bool {
11110 false
11111 }
11112 }
11113
11114 impl Item for TestPngItemView {
11115 type Event = ();
11116 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
11117 "".into()
11118 }
11119 }
11120 impl EventEmitter<()> for TestPngItemView {}
11121 impl Focusable for TestPngItemView {
11122 fn focus_handle(&self, _cx: &App) -> FocusHandle {
11123 self.focus_handle.clone()
11124 }
11125 }
11126
11127 impl Render for TestPngItemView {
11128 fn render(
11129 &mut self,
11130 _window: &mut Window,
11131 _cx: &mut Context<Self>,
11132 ) -> impl IntoElement {
11133 Empty
11134 }
11135 }
11136
11137 impl ProjectItem for TestPngItemView {
11138 type Item = TestPngItem;
11139
11140 fn for_project_item(
11141 _project: Entity<Project>,
11142 _pane: Option<&Pane>,
11143 _item: Entity<Self::Item>,
11144 _: &mut Window,
11145 cx: &mut Context<Self>,
11146 ) -> Self
11147 where
11148 Self: Sized,
11149 {
11150 Self {
11151 focus_handle: cx.focus_handle(),
11152 }
11153 }
11154 }
11155
11156 // View
11157 struct TestIpynbItemView {
11158 focus_handle: FocusHandle,
11159 }
11160 // Model
11161 struct TestIpynbItem {}
11162
11163 impl project::ProjectItem for TestIpynbItem {
11164 fn try_open(
11165 _project: &Entity<Project>,
11166 path: &ProjectPath,
11167 cx: &mut App,
11168 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
11169 if path.path.extension().unwrap() == "ipynb" {
11170 Some(cx.spawn(async move |cx| cx.new(|_| TestIpynbItem {})))
11171 } else {
11172 None
11173 }
11174 }
11175
11176 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
11177 None
11178 }
11179
11180 fn project_path(&self, _: &App) -> Option<ProjectPath> {
11181 None
11182 }
11183
11184 fn is_dirty(&self) -> bool {
11185 false
11186 }
11187 }
11188
11189 impl Item for TestIpynbItemView {
11190 type Event = ();
11191 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
11192 "".into()
11193 }
11194 }
11195 impl EventEmitter<()> for TestIpynbItemView {}
11196 impl Focusable for TestIpynbItemView {
11197 fn focus_handle(&self, _cx: &App) -> FocusHandle {
11198 self.focus_handle.clone()
11199 }
11200 }
11201
11202 impl Render for TestIpynbItemView {
11203 fn render(
11204 &mut self,
11205 _window: &mut Window,
11206 _cx: &mut Context<Self>,
11207 ) -> impl IntoElement {
11208 Empty
11209 }
11210 }
11211
11212 impl ProjectItem for TestIpynbItemView {
11213 type Item = TestIpynbItem;
11214
11215 fn for_project_item(
11216 _project: Entity<Project>,
11217 _pane: Option<&Pane>,
11218 _item: Entity<Self::Item>,
11219 _: &mut Window,
11220 cx: &mut Context<Self>,
11221 ) -> Self
11222 where
11223 Self: Sized,
11224 {
11225 Self {
11226 focus_handle: cx.focus_handle(),
11227 }
11228 }
11229 }
11230
11231 struct TestAlternatePngItemView {
11232 focus_handle: FocusHandle,
11233 }
11234
11235 impl Item for TestAlternatePngItemView {
11236 type Event = ();
11237 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
11238 "".into()
11239 }
11240 }
11241
11242 impl EventEmitter<()> for TestAlternatePngItemView {}
11243 impl Focusable for TestAlternatePngItemView {
11244 fn focus_handle(&self, _cx: &App) -> FocusHandle {
11245 self.focus_handle.clone()
11246 }
11247 }
11248
11249 impl Render for TestAlternatePngItemView {
11250 fn render(
11251 &mut self,
11252 _window: &mut Window,
11253 _cx: &mut Context<Self>,
11254 ) -> impl IntoElement {
11255 Empty
11256 }
11257 }
11258
11259 impl ProjectItem for TestAlternatePngItemView {
11260 type Item = TestPngItem;
11261
11262 fn for_project_item(
11263 _project: Entity<Project>,
11264 _pane: Option<&Pane>,
11265 _item: Entity<Self::Item>,
11266 _: &mut Window,
11267 cx: &mut Context<Self>,
11268 ) -> Self
11269 where
11270 Self: Sized,
11271 {
11272 Self {
11273 focus_handle: cx.focus_handle(),
11274 }
11275 }
11276 }
11277
11278 #[gpui::test]
11279 async fn test_register_project_item(cx: &mut TestAppContext) {
11280 init_test(cx);
11281
11282 cx.update(|cx| {
11283 register_project_item::<TestPngItemView>(cx);
11284 register_project_item::<TestIpynbItemView>(cx);
11285 });
11286
11287 let fs = FakeFs::new(cx.executor());
11288 fs.insert_tree(
11289 "/root1",
11290 json!({
11291 "one.png": "BINARYDATAHERE",
11292 "two.ipynb": "{ totally a notebook }",
11293 "three.txt": "editing text, sure why not?"
11294 }),
11295 )
11296 .await;
11297
11298 let project = Project::test(fs, ["root1".as_ref()], cx).await;
11299 let (workspace, cx) =
11300 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
11301
11302 let worktree_id = project.update(cx, |project, cx| {
11303 project.worktrees(cx).next().unwrap().read(cx).id()
11304 });
11305
11306 let handle = workspace
11307 .update_in(cx, |workspace, window, cx| {
11308 let project_path = (worktree_id, rel_path("one.png"));
11309 workspace.open_path(project_path, None, true, window, cx)
11310 })
11311 .await
11312 .unwrap();
11313
11314 // Now we can check if the handle we got back errored or not
11315 assert_eq!(
11316 handle.to_any_view().entity_type(),
11317 TypeId::of::<TestPngItemView>()
11318 );
11319
11320 let handle = workspace
11321 .update_in(cx, |workspace, window, cx| {
11322 let project_path = (worktree_id, rel_path("two.ipynb"));
11323 workspace.open_path(project_path, None, true, window, cx)
11324 })
11325 .await
11326 .unwrap();
11327
11328 assert_eq!(
11329 handle.to_any_view().entity_type(),
11330 TypeId::of::<TestIpynbItemView>()
11331 );
11332
11333 let handle = workspace
11334 .update_in(cx, |workspace, window, cx| {
11335 let project_path = (worktree_id, rel_path("three.txt"));
11336 workspace.open_path(project_path, None, true, window, cx)
11337 })
11338 .await;
11339 assert!(handle.is_err());
11340 }
11341
11342 #[gpui::test]
11343 async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
11344 init_test(cx);
11345
11346 cx.update(|cx| {
11347 register_project_item::<TestPngItemView>(cx);
11348 register_project_item::<TestAlternatePngItemView>(cx);
11349 });
11350
11351 let fs = FakeFs::new(cx.executor());
11352 fs.insert_tree(
11353 "/root1",
11354 json!({
11355 "one.png": "BINARYDATAHERE",
11356 "two.ipynb": "{ totally a notebook }",
11357 "three.txt": "editing text, sure why not?"
11358 }),
11359 )
11360 .await;
11361 let project = Project::test(fs, ["root1".as_ref()], cx).await;
11362 let (workspace, cx) =
11363 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
11364 let worktree_id = project.update(cx, |project, cx| {
11365 project.worktrees(cx).next().unwrap().read(cx).id()
11366 });
11367
11368 let handle = workspace
11369 .update_in(cx, |workspace, window, cx| {
11370 let project_path = (worktree_id, rel_path("one.png"));
11371 workspace.open_path(project_path, None, true, window, cx)
11372 })
11373 .await
11374 .unwrap();
11375
11376 // This _must_ be the second item registered
11377 assert_eq!(
11378 handle.to_any_view().entity_type(),
11379 TypeId::of::<TestAlternatePngItemView>()
11380 );
11381
11382 let handle = workspace
11383 .update_in(cx, |workspace, window, cx| {
11384 let project_path = (worktree_id, rel_path("three.txt"));
11385 workspace.open_path(project_path, None, true, window, cx)
11386 })
11387 .await;
11388 assert!(handle.is_err());
11389 }
11390 }
11391
11392 #[gpui::test]
11393 async fn test_status_bar_visibility(cx: &mut TestAppContext) {
11394 init_test(cx);
11395
11396 let fs = FakeFs::new(cx.executor());
11397 let project = Project::test(fs, [], cx).await;
11398 let (workspace, _cx) =
11399 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
11400
11401 // Test with status bar shown (default)
11402 workspace.read_with(cx, |workspace, cx| {
11403 let visible = workspace.status_bar_visible(cx);
11404 assert!(visible, "Status bar should be visible by default");
11405 });
11406
11407 // Test with status bar hidden
11408 cx.update_global(|store: &mut SettingsStore, cx| {
11409 store.update_user_settings(cx, |settings| {
11410 settings.status_bar.get_or_insert_default().show = Some(false);
11411 });
11412 });
11413
11414 workspace.read_with(cx, |workspace, cx| {
11415 let visible = workspace.status_bar_visible(cx);
11416 assert!(!visible, "Status bar should be hidden when show is false");
11417 });
11418
11419 // Test with status bar shown explicitly
11420 cx.update_global(|store: &mut SettingsStore, cx| {
11421 store.update_user_settings(cx, |settings| {
11422 settings.status_bar.get_or_insert_default().show = Some(true);
11423 });
11424 });
11425
11426 workspace.read_with(cx, |workspace, cx| {
11427 let visible = workspace.status_bar_visible(cx);
11428 assert!(visible, "Status bar should be visible when show is true");
11429 });
11430 }
11431
11432 fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
11433 pane.read(cx)
11434 .items()
11435 .flat_map(|item| {
11436 item.project_paths(cx)
11437 .into_iter()
11438 .map(|path| path.path.display(PathStyle::local()).into_owned())
11439 })
11440 .collect()
11441 }
11442
11443 pub fn init_test(cx: &mut TestAppContext) {
11444 cx.update(|cx| {
11445 let settings_store = SettingsStore::test(cx);
11446 cx.set_global(settings_store);
11447 theme::init(theme::LoadThemes::JustBase, cx);
11448 });
11449 }
11450
11451 fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
11452 let item = TestProjectItem::new(id, path, cx);
11453 item.update(cx, |item, _| {
11454 item.is_dirty = true;
11455 });
11456 item
11457 }
11458}