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