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