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