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