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