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