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