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