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