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