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