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