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