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