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