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