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