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