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