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