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