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