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