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