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