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