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