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 Some(div()
6626 .occlude()
6627 .absolute()
6628 .overflow_hidden()
6629 .border_color(colors.border)
6630 .bg(colors.background)
6631 .child(view.upgrade()?)
6632 .inset_0()
6633 .shadow_lg())
6634 }))
6635 .children(self.render_notifications(window, cx)),
6636 )
6637 .child(self.status_bar.clone())
6638 .child(self.modal_layer.clone())
6639 .child(self.toast_layer.clone()),
6640 ),
6641 window,
6642 cx,
6643 )
6644 }
6645}
6646
6647impl WorkspaceStore {
6648 pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
6649 Self {
6650 workspaces: Default::default(),
6651 _subscriptions: vec![
6652 client.add_request_handler(cx.weak_entity(), Self::handle_follow),
6653 client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
6654 ],
6655 client,
6656 }
6657 }
6658
6659 pub fn update_followers(
6660 &self,
6661 project_id: Option<u64>,
6662 update: proto::update_followers::Variant,
6663 cx: &App,
6664 ) -> Option<()> {
6665 let active_call = ActiveCall::try_global(cx)?;
6666 let room_id = active_call.read(cx).room()?.read(cx).id();
6667 self.client
6668 .send(proto::UpdateFollowers {
6669 room_id,
6670 project_id,
6671 variant: Some(update),
6672 })
6673 .log_err()
6674 }
6675
6676 pub async fn handle_follow(
6677 this: Entity<Self>,
6678 envelope: TypedEnvelope<proto::Follow>,
6679 mut cx: AsyncApp,
6680 ) -> Result<proto::FollowResponse> {
6681 this.update(&mut cx, |this, cx| {
6682 let follower = Follower {
6683 project_id: envelope.payload.project_id,
6684 peer_id: envelope.original_sender_id()?,
6685 };
6686
6687 let mut response = proto::FollowResponse::default();
6688 this.workspaces.retain(|workspace| {
6689 workspace
6690 .update(cx, |workspace, window, cx| {
6691 let handler_response =
6692 workspace.handle_follow(follower.project_id, window, cx);
6693 if let Some(active_view) = handler_response.active_view
6694 && workspace.project.read(cx).remote_id() == follower.project_id
6695 {
6696 response.active_view = Some(active_view)
6697 }
6698 })
6699 .is_ok()
6700 });
6701
6702 Ok(response)
6703 })?
6704 }
6705
6706 async fn handle_update_followers(
6707 this: Entity<Self>,
6708 envelope: TypedEnvelope<proto::UpdateFollowers>,
6709 mut cx: AsyncApp,
6710 ) -> Result<()> {
6711 let leader_id = envelope.original_sender_id()?;
6712 let update = envelope.payload;
6713
6714 this.update(&mut cx, |this, cx| {
6715 this.workspaces.retain(|workspace| {
6716 workspace
6717 .update(cx, |workspace, window, cx| {
6718 let project_id = workspace.project.read(cx).remote_id();
6719 if update.project_id != project_id && update.project_id.is_some() {
6720 return;
6721 }
6722 workspace.handle_update_followers(leader_id, update.clone(), window, cx);
6723 })
6724 .is_ok()
6725 });
6726 Ok(())
6727 })?
6728 }
6729
6730 pub fn workspaces(&self) -> &HashSet<WindowHandle<Workspace>> {
6731 &self.workspaces
6732 }
6733}
6734
6735impl ViewId {
6736 pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
6737 Ok(Self {
6738 creator: message
6739 .creator
6740 .map(CollaboratorId::PeerId)
6741 .context("creator is missing")?,
6742 id: message.id,
6743 })
6744 }
6745
6746 pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
6747 if let CollaboratorId::PeerId(peer_id) = self.creator {
6748 Some(proto::ViewId {
6749 creator: Some(peer_id),
6750 id: self.id,
6751 })
6752 } else {
6753 None
6754 }
6755 }
6756}
6757
6758impl FollowerState {
6759 fn pane(&self) -> &Entity<Pane> {
6760 self.dock_pane.as_ref().unwrap_or(&self.center_pane)
6761 }
6762}
6763
6764pub trait WorkspaceHandle {
6765 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
6766}
6767
6768impl WorkspaceHandle for Entity<Workspace> {
6769 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
6770 self.read(cx)
6771 .worktrees(cx)
6772 .flat_map(|worktree| {
6773 let worktree_id = worktree.read(cx).id();
6774 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
6775 worktree_id,
6776 path: f.path.clone(),
6777 })
6778 })
6779 .collect::<Vec<_>>()
6780 }
6781}
6782
6783pub async fn last_opened_workspace_location() -> Option<(SerializedWorkspaceLocation, PathList)> {
6784 DB.last_workspace().await.log_err().flatten()
6785}
6786
6787pub fn last_session_workspace_locations(
6788 last_session_id: &str,
6789 last_session_window_stack: Option<Vec<WindowId>>,
6790) -> Option<Vec<(SerializedWorkspaceLocation, PathList)>> {
6791 DB.last_session_workspace_locations(last_session_id, last_session_window_stack)
6792 .log_err()
6793}
6794
6795actions!(
6796 collab,
6797 [
6798 /// Opens the channel notes for the current call.
6799 ///
6800 /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
6801 /// can be copied via "Copy link to section" in the context menu of the channel notes
6802 /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
6803 OpenChannelNotes,
6804 /// Mutes your microphone.
6805 Mute,
6806 /// Deafens yourself (mute both microphone and speakers).
6807 Deafen,
6808 /// Leaves the current call.
6809 LeaveCall,
6810 /// Shares the current project with collaborators.
6811 ShareProject,
6812 /// Shares your screen with collaborators.
6813 ScreenShare
6814 ]
6815);
6816actions!(
6817 zed,
6818 [
6819 /// Opens the Zed log file.
6820 OpenLog
6821 ]
6822);
6823
6824async fn join_channel_internal(
6825 channel_id: ChannelId,
6826 app_state: &Arc<AppState>,
6827 requesting_window: Option<WindowHandle<Workspace>>,
6828 active_call: &Entity<ActiveCall>,
6829 cx: &mut AsyncApp,
6830) -> Result<bool> {
6831 let (should_prompt, open_room) = active_call.update(cx, |active_call, cx| {
6832 let Some(room) = active_call.room().map(|room| room.read(cx)) else {
6833 return (false, None);
6834 };
6835
6836 let already_in_channel = room.channel_id() == Some(channel_id);
6837 let should_prompt = room.is_sharing_project()
6838 && !room.remote_participants().is_empty()
6839 && !already_in_channel;
6840 let open_room = if already_in_channel {
6841 active_call.room().cloned()
6842 } else {
6843 None
6844 };
6845 (should_prompt, open_room)
6846 })?;
6847
6848 if let Some(room) = open_room {
6849 let task = room.update(cx, |room, cx| {
6850 if let Some((project, host)) = room.most_active_project(cx) {
6851 return Some(join_in_room_project(project, host, app_state.clone(), cx));
6852 }
6853
6854 None
6855 })?;
6856 if let Some(task) = task {
6857 task.await?;
6858 }
6859 return anyhow::Ok(true);
6860 }
6861
6862 if should_prompt {
6863 if let Some(workspace) = requesting_window {
6864 let answer = workspace
6865 .update(cx, |_, window, cx| {
6866 window.prompt(
6867 PromptLevel::Warning,
6868 "Do you want to switch channels?",
6869 Some("Leaving this call will unshare your current project."),
6870 &["Yes, Join Channel", "Cancel"],
6871 cx,
6872 )
6873 })?
6874 .await;
6875
6876 if answer == Ok(1) {
6877 return Ok(false);
6878 }
6879 } else {
6880 return Ok(false); // unreachable!() hopefully
6881 }
6882 }
6883
6884 let client = cx.update(|cx| active_call.read(cx).client())?;
6885
6886 let mut client_status = client.status();
6887
6888 // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
6889 'outer: loop {
6890 let Some(status) = client_status.recv().await else {
6891 anyhow::bail!("error connecting");
6892 };
6893
6894 match status {
6895 Status::Connecting
6896 | Status::Authenticating
6897 | Status::Authenticated
6898 | Status::Reconnecting
6899 | Status::Reauthenticating => continue,
6900 Status::Connected { .. } => break 'outer,
6901 Status::SignedOut | Status::AuthenticationError => {
6902 return Err(ErrorCode::SignedOut.into());
6903 }
6904 Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
6905 Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
6906 return Err(ErrorCode::Disconnected.into());
6907 }
6908 }
6909 }
6910
6911 let room = active_call
6912 .update(cx, |active_call, cx| {
6913 active_call.join_channel(channel_id, cx)
6914 })?
6915 .await?;
6916
6917 let Some(room) = room else {
6918 return anyhow::Ok(true);
6919 };
6920
6921 room.update(cx, |room, _| room.room_update_completed())?
6922 .await;
6923
6924 let task = room.update(cx, |room, cx| {
6925 if let Some((project, host)) = room.most_active_project(cx) {
6926 return Some(join_in_room_project(project, host, app_state.clone(), cx));
6927 }
6928
6929 // If you are the first to join a channel, see if you should share your project.
6930 if room.remote_participants().is_empty()
6931 && !room.local_participant_is_guest()
6932 && let Some(workspace) = requesting_window
6933 {
6934 let project = workspace.update(cx, |workspace, _, cx| {
6935 let project = workspace.project.read(cx);
6936
6937 if !CallSettings::get_global(cx).share_on_join {
6938 return None;
6939 }
6940
6941 if (project.is_local() || project.is_via_ssh())
6942 && project.visible_worktrees(cx).any(|tree| {
6943 tree.read(cx)
6944 .root_entry()
6945 .is_some_and(|entry| entry.is_dir())
6946 })
6947 {
6948 Some(workspace.project.clone())
6949 } else {
6950 None
6951 }
6952 });
6953 if let Ok(Some(project)) = project {
6954 return Some(cx.spawn(async move |room, cx| {
6955 room.update(cx, |room, cx| room.share_project(project, cx))?
6956 .await?;
6957 Ok(())
6958 }));
6959 }
6960 }
6961
6962 None
6963 })?;
6964 if let Some(task) = task {
6965 task.await?;
6966 return anyhow::Ok(true);
6967 }
6968 anyhow::Ok(false)
6969}
6970
6971pub fn join_channel(
6972 channel_id: ChannelId,
6973 app_state: Arc<AppState>,
6974 requesting_window: Option<WindowHandle<Workspace>>,
6975 cx: &mut App,
6976) -> Task<Result<()>> {
6977 let active_call = ActiveCall::global(cx);
6978 cx.spawn(async move |cx| {
6979 let result = join_channel_internal(
6980 channel_id,
6981 &app_state,
6982 requesting_window,
6983 &active_call,
6984 cx,
6985 )
6986 .await;
6987
6988 // join channel succeeded, and opened a window
6989 if matches!(result, Ok(true)) {
6990 return anyhow::Ok(());
6991 }
6992
6993 // find an existing workspace to focus and show call controls
6994 let mut active_window =
6995 requesting_window.or_else(|| activate_any_workspace_window( cx));
6996 if active_window.is_none() {
6997 // no open workspaces, make one to show the error in (blergh)
6998 let (window_handle, _) = cx
6999 .update(|cx| {
7000 Workspace::new_local(vec![], app_state.clone(), requesting_window, None, cx)
7001 })?
7002 .await?;
7003
7004 if result.is_ok() {
7005 cx.update(|cx| {
7006 cx.dispatch_action(&OpenChannelNotes);
7007 }).log_err();
7008 }
7009
7010 active_window = Some(window_handle);
7011 }
7012
7013 if let Err(err) = result {
7014 log::error!("failed to join channel: {}", err);
7015 if let Some(active_window) = active_window {
7016 active_window
7017 .update(cx, |_, window, cx| {
7018 let detail: SharedString = match err.error_code() {
7019 ErrorCode::SignedOut => {
7020 "Please sign in to continue.".into()
7021 }
7022 ErrorCode::UpgradeRequired => {
7023 "Your are running an unsupported version of Zed. Please update to continue.".into()
7024 }
7025 ErrorCode::NoSuchChannel => {
7026 "No matching channel was found. Please check the link and try again.".into()
7027 }
7028 ErrorCode::Forbidden => {
7029 "This channel is private, and you do not have access. Please ask someone to add you and try again.".into()
7030 }
7031 ErrorCode::Disconnected => "Please check your internet connection and try again.".into(),
7032 _ => format!("{}\n\nPlease try again.", err).into(),
7033 };
7034 window.prompt(
7035 PromptLevel::Critical,
7036 "Failed to join channel",
7037 Some(&detail),
7038 &["Ok"],
7039 cx)
7040 })?
7041 .await
7042 .ok();
7043 }
7044 }
7045
7046 // return ok, we showed the error to the user.
7047 anyhow::Ok(())
7048 })
7049}
7050
7051pub async fn get_any_active_workspace(
7052 app_state: Arc<AppState>,
7053 mut cx: AsyncApp,
7054) -> anyhow::Result<WindowHandle<Workspace>> {
7055 // find an existing workspace to focus and show call controls
7056 let active_window = activate_any_workspace_window(&mut cx);
7057 if active_window.is_none() {
7058 cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, cx))?
7059 .await?;
7060 }
7061 activate_any_workspace_window(&mut cx).context("could not open zed")
7062}
7063
7064fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<Workspace>> {
7065 cx.update(|cx| {
7066 if let Some(workspace_window) = cx
7067 .active_window()
7068 .and_then(|window| window.downcast::<Workspace>())
7069 {
7070 return Some(workspace_window);
7071 }
7072
7073 for window in cx.windows() {
7074 if let Some(workspace_window) = window.downcast::<Workspace>() {
7075 workspace_window
7076 .update(cx, |_, window, _| window.activate_window())
7077 .ok();
7078 return Some(workspace_window);
7079 }
7080 }
7081 None
7082 })
7083 .ok()
7084 .flatten()
7085}
7086
7087pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<Workspace>> {
7088 cx.windows()
7089 .into_iter()
7090 .filter_map(|window| window.downcast::<Workspace>())
7091 .filter(|workspace| {
7092 workspace
7093 .read(cx)
7094 .is_ok_and(|workspace| workspace.project.read(cx).is_local())
7095 })
7096 .collect()
7097}
7098
7099#[derive(Default)]
7100pub struct OpenOptions {
7101 pub visible: Option<OpenVisible>,
7102 pub focus: Option<bool>,
7103 pub open_new_workspace: Option<bool>,
7104 pub replace_window: Option<WindowHandle<Workspace>>,
7105 pub env: Option<HashMap<String, String>>,
7106}
7107
7108#[allow(clippy::type_complexity)]
7109pub fn open_paths(
7110 abs_paths: &[PathBuf],
7111 app_state: Arc<AppState>,
7112 open_options: OpenOptions,
7113 cx: &mut App,
7114) -> Task<
7115 anyhow::Result<(
7116 WindowHandle<Workspace>,
7117 Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
7118 )>,
7119> {
7120 let abs_paths = abs_paths.to_vec();
7121 let mut existing = None;
7122 let mut best_match = None;
7123 let mut open_visible = OpenVisible::All;
7124
7125 cx.spawn(async move |cx| {
7126 if open_options.open_new_workspace != Some(true) {
7127 let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
7128 let all_metadatas = futures::future::join_all(all_paths)
7129 .await
7130 .into_iter()
7131 .filter_map(|result| result.ok().flatten())
7132 .collect::<Vec<_>>();
7133
7134 cx.update(|cx| {
7135 for window in local_workspace_windows(cx) {
7136 if let Ok(workspace) = window.read(cx) {
7137 let m = workspace.project.read(cx).visibility_for_paths(
7138 &abs_paths,
7139 &all_metadatas,
7140 open_options.open_new_workspace == None,
7141 cx,
7142 );
7143 if m > best_match {
7144 existing = Some(window);
7145 best_match = m;
7146 } else if best_match.is_none()
7147 && open_options.open_new_workspace == Some(false)
7148 {
7149 existing = Some(window)
7150 }
7151 }
7152 }
7153 })?;
7154
7155 if open_options.open_new_workspace.is_none()
7156 && existing.is_none()
7157 && all_metadatas.iter().all(|file| !file.is_dir)
7158 {
7159 cx.update(|cx| {
7160 if let Some(window) = cx
7161 .active_window()
7162 .and_then(|window| window.downcast::<Workspace>())
7163 && let Ok(workspace) = window.read(cx)
7164 {
7165 let project = workspace.project().read(cx);
7166 if project.is_local() && !project.is_via_collab() {
7167 existing = Some(window);
7168 open_visible = OpenVisible::None;
7169 return;
7170 }
7171 }
7172 for window in local_workspace_windows(cx) {
7173 if let Ok(workspace) = window.read(cx) {
7174 let project = workspace.project().read(cx);
7175 if project.is_via_collab() {
7176 continue;
7177 }
7178 existing = Some(window);
7179 open_visible = OpenVisible::None;
7180 break;
7181 }
7182 }
7183 })?;
7184 }
7185 }
7186
7187 if let Some(existing) = existing {
7188 let open_task = existing
7189 .update(cx, |workspace, window, cx| {
7190 window.activate_window();
7191 workspace.open_paths(
7192 abs_paths,
7193 OpenOptions {
7194 visible: Some(open_visible),
7195 ..Default::default()
7196 },
7197 None,
7198 window,
7199 cx,
7200 )
7201 })?
7202 .await;
7203
7204 _ = existing.update(cx, |workspace, _, cx| {
7205 for item in open_task.iter().flatten() {
7206 if let Err(e) = item {
7207 workspace.show_error(&e, cx);
7208 }
7209 }
7210 });
7211
7212 Ok((existing, open_task))
7213 } else {
7214 cx.update(move |cx| {
7215 Workspace::new_local(
7216 abs_paths,
7217 app_state.clone(),
7218 open_options.replace_window,
7219 open_options.env,
7220 cx,
7221 )
7222 })?
7223 .await
7224 }
7225 })
7226}
7227
7228pub fn open_new(
7229 open_options: OpenOptions,
7230 app_state: Arc<AppState>,
7231 cx: &mut App,
7232 init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
7233) -> Task<anyhow::Result<()>> {
7234 let task = Workspace::new_local(Vec::new(), app_state, None, open_options.env, cx);
7235 cx.spawn(async move |cx| {
7236 let (workspace, opened_paths) = task.await?;
7237 workspace.update(cx, |workspace, window, cx| {
7238 if opened_paths.is_empty() {
7239 init(workspace, window, cx)
7240 }
7241 })?;
7242 Ok(())
7243 })
7244}
7245
7246pub fn create_and_open_local_file(
7247 path: &'static Path,
7248 window: &mut Window,
7249 cx: &mut Context<Workspace>,
7250 default_content: impl 'static + Send + FnOnce() -> Rope,
7251) -> Task<Result<Box<dyn ItemHandle>>> {
7252 cx.spawn_in(window, async move |workspace, cx| {
7253 let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
7254 if !fs.is_file(path).await {
7255 fs.create_file(path, Default::default()).await?;
7256 fs.save(path, &default_content(), Default::default())
7257 .await?;
7258 }
7259
7260 let mut items = workspace
7261 .update_in(cx, |workspace, window, cx| {
7262 workspace.with_local_workspace(window, cx, |workspace, window, cx| {
7263 workspace.open_paths(
7264 vec![path.to_path_buf()],
7265 OpenOptions {
7266 visible: Some(OpenVisible::None),
7267 ..Default::default()
7268 },
7269 None,
7270 window,
7271 cx,
7272 )
7273 })
7274 })?
7275 .await?
7276 .await;
7277
7278 let item = items.pop().flatten();
7279 item.with_context(|| format!("path {path:?} is not a file"))?
7280 })
7281}
7282
7283pub fn open_ssh_project_with_new_connection(
7284 window: WindowHandle<Workspace>,
7285 connection_options: SshConnectionOptions,
7286 cancel_rx: oneshot::Receiver<()>,
7287 delegate: Arc<dyn SshClientDelegate>,
7288 app_state: Arc<AppState>,
7289 paths: Vec<PathBuf>,
7290 cx: &mut App,
7291) -> Task<Result<()>> {
7292 cx.spawn(async move |cx| {
7293 let (workspace_id, serialized_workspace) =
7294 serialize_ssh_project(connection_options.clone(), paths.clone(), cx).await?;
7295
7296 let session = match cx
7297 .update(|cx| {
7298 remote::SshRemoteClient::new(
7299 ConnectionIdentifier::Workspace(workspace_id.0),
7300 connection_options,
7301 cancel_rx,
7302 delegate,
7303 cx,
7304 )
7305 })?
7306 .await?
7307 {
7308 Some(result) => result,
7309 None => return Ok(()),
7310 };
7311
7312 let project = cx.update(|cx| {
7313 project::Project::ssh(
7314 session,
7315 app_state.client.clone(),
7316 app_state.node_runtime.clone(),
7317 app_state.user_store.clone(),
7318 app_state.languages.clone(),
7319 app_state.fs.clone(),
7320 cx,
7321 )
7322 })?;
7323
7324 open_ssh_project_inner(
7325 project,
7326 paths,
7327 workspace_id,
7328 serialized_workspace,
7329 app_state,
7330 window,
7331 cx,
7332 )
7333 .await
7334 })
7335}
7336
7337pub fn open_ssh_project_with_existing_connection(
7338 connection_options: SshConnectionOptions,
7339 project: Entity<Project>,
7340 paths: Vec<PathBuf>,
7341 app_state: Arc<AppState>,
7342 window: WindowHandle<Workspace>,
7343 cx: &mut AsyncApp,
7344) -> Task<Result<()>> {
7345 cx.spawn(async move |cx| {
7346 let (workspace_id, serialized_workspace) =
7347 serialize_ssh_project(connection_options.clone(), paths.clone(), cx).await?;
7348
7349 open_ssh_project_inner(
7350 project,
7351 paths,
7352 workspace_id,
7353 serialized_workspace,
7354 app_state,
7355 window,
7356 cx,
7357 )
7358 .await
7359 })
7360}
7361
7362async fn open_ssh_project_inner(
7363 project: Entity<Project>,
7364 paths: Vec<PathBuf>,
7365 workspace_id: WorkspaceId,
7366 serialized_workspace: Option<SerializedWorkspace>,
7367 app_state: Arc<AppState>,
7368 window: WindowHandle<Workspace>,
7369 cx: &mut AsyncApp,
7370) -> Result<()> {
7371 let toolchains = DB.toolchains(workspace_id).await?;
7372 for (toolchain, worktree_id, path) in toolchains {
7373 project
7374 .update(cx, |this, cx| {
7375 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
7376 })?
7377 .await;
7378 }
7379 let mut project_paths_to_open = vec![];
7380 let mut project_path_errors = vec![];
7381
7382 for path in paths {
7383 let result = cx
7384 .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))?
7385 .await;
7386 match result {
7387 Ok((_, project_path)) => {
7388 project_paths_to_open.push((path.clone(), Some(project_path)));
7389 }
7390 Err(error) => {
7391 project_path_errors.push(error);
7392 }
7393 };
7394 }
7395
7396 if project_paths_to_open.is_empty() {
7397 return Err(project_path_errors.pop().context("no paths given")?);
7398 }
7399
7400 if let Some(detach_session_task) = window
7401 .update(cx, |_workspace, window, cx| {
7402 cx.spawn_in(window, async move |this, cx| {
7403 this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))
7404 })
7405 })
7406 .ok()
7407 {
7408 detach_session_task.await.ok();
7409 }
7410
7411 cx.update_window(window.into(), |_, window, cx| {
7412 window.replace_root(cx, |window, cx| {
7413 telemetry::event!("SSH Project Opened");
7414
7415 let mut workspace =
7416 Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
7417 workspace.update_history(cx);
7418
7419 if let Some(ref serialized) = serialized_workspace {
7420 workspace.centered_layout = serialized.centered_layout;
7421 }
7422
7423 workspace
7424 });
7425 })?;
7426
7427 window
7428 .update(cx, |_, window, cx| {
7429 window.activate_window();
7430 open_items(serialized_workspace, project_paths_to_open, window, cx)
7431 })?
7432 .await?;
7433
7434 window.update(cx, |workspace, _, cx| {
7435 for error in project_path_errors {
7436 if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
7437 if let Some(path) = error.error_tag("path") {
7438 workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
7439 }
7440 } else {
7441 workspace.show_error(&error, cx)
7442 }
7443 }
7444 })?;
7445
7446 Ok(())
7447}
7448
7449fn serialize_ssh_project(
7450 connection_options: SshConnectionOptions,
7451 paths: Vec<PathBuf>,
7452 cx: &AsyncApp,
7453) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
7454 cx.background_spawn(async move {
7455 let ssh_connection_id = persistence::DB
7456 .get_or_create_ssh_connection(
7457 connection_options.host.clone(),
7458 connection_options.port,
7459 connection_options.username.clone(),
7460 )
7461 .await?;
7462
7463 let serialized_workspace =
7464 persistence::DB.ssh_workspace_for_roots(&paths, ssh_connection_id);
7465
7466 let workspace_id = if let Some(workspace_id) =
7467 serialized_workspace.as_ref().map(|workspace| workspace.id)
7468 {
7469 workspace_id
7470 } else {
7471 persistence::DB.next_id().await?
7472 };
7473
7474 Ok((workspace_id, serialized_workspace))
7475 })
7476}
7477
7478pub fn join_in_room_project(
7479 project_id: u64,
7480 follow_user_id: u64,
7481 app_state: Arc<AppState>,
7482 cx: &mut App,
7483) -> Task<Result<()>> {
7484 let windows = cx.windows();
7485 cx.spawn(async move |cx| {
7486 let existing_workspace = windows.into_iter().find_map(|window_handle| {
7487 window_handle
7488 .downcast::<Workspace>()
7489 .and_then(|window_handle| {
7490 window_handle
7491 .update(cx, |workspace, _window, cx| {
7492 if workspace.project().read(cx).remote_id() == Some(project_id) {
7493 Some(window_handle)
7494 } else {
7495 None
7496 }
7497 })
7498 .unwrap_or(None)
7499 })
7500 });
7501
7502 let workspace = if let Some(existing_workspace) = existing_workspace {
7503 existing_workspace
7504 } else {
7505 let active_call = cx.update(|cx| ActiveCall::global(cx))?;
7506 let room = active_call
7507 .read_with(cx, |call, _| call.room().cloned())?
7508 .context("not in a call")?;
7509 let project = room
7510 .update(cx, |room, cx| {
7511 room.join_project(
7512 project_id,
7513 app_state.languages.clone(),
7514 app_state.fs.clone(),
7515 cx,
7516 )
7517 })?
7518 .await?;
7519
7520 let window_bounds_override = window_bounds_env_override();
7521 cx.update(|cx| {
7522 let mut options = (app_state.build_window_options)(None, cx);
7523 options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
7524 cx.open_window(options, |window, cx| {
7525 cx.new(|cx| {
7526 Workspace::new(Default::default(), project, app_state.clone(), window, cx)
7527 })
7528 })
7529 })??
7530 };
7531
7532 workspace.update(cx, |workspace, window, cx| {
7533 cx.activate(true);
7534 window.activate_window();
7535
7536 if let Some(room) = ActiveCall::global(cx).read(cx).room().cloned() {
7537 let follow_peer_id = room
7538 .read(cx)
7539 .remote_participants()
7540 .iter()
7541 .find(|(_, participant)| participant.user.id == follow_user_id)
7542 .map(|(_, p)| p.peer_id)
7543 .or_else(|| {
7544 // If we couldn't follow the given user, follow the host instead.
7545 let collaborator = workspace
7546 .project()
7547 .read(cx)
7548 .collaborators()
7549 .values()
7550 .find(|collaborator| collaborator.is_host)?;
7551 Some(collaborator.peer_id)
7552 });
7553
7554 if let Some(follow_peer_id) = follow_peer_id {
7555 workspace.follow(follow_peer_id, window, cx);
7556 }
7557 }
7558 })?;
7559
7560 anyhow::Ok(())
7561 })
7562}
7563
7564pub fn reload(cx: &mut App) {
7565 let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
7566 let mut workspace_windows = cx
7567 .windows()
7568 .into_iter()
7569 .filter_map(|window| window.downcast::<Workspace>())
7570 .collect::<Vec<_>>();
7571
7572 // If multiple windows have unsaved changes, and need a save prompt,
7573 // prompt in the active window before switching to a different window.
7574 workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
7575
7576 let mut prompt = None;
7577 if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
7578 prompt = window
7579 .update(cx, |_, window, cx| {
7580 window.prompt(
7581 PromptLevel::Info,
7582 "Are you sure you want to restart?",
7583 None,
7584 &["Restart", "Cancel"],
7585 cx,
7586 )
7587 })
7588 .ok();
7589 }
7590
7591 cx.spawn(async move |cx| {
7592 if let Some(prompt) = prompt {
7593 let answer = prompt.await?;
7594 if answer != 0 {
7595 return Ok(());
7596 }
7597 }
7598
7599 // If the user cancels any save prompt, then keep the app open.
7600 for window in workspace_windows {
7601 if let Ok(should_close) = window.update(cx, |workspace, window, cx| {
7602 workspace.prepare_to_close(CloseIntent::Quit, window, cx)
7603 }) && !should_close.await?
7604 {
7605 return Ok(());
7606 }
7607 }
7608 cx.update(|cx| cx.restart())
7609 })
7610 .detach_and_log_err(cx);
7611}
7612
7613fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
7614 let mut parts = value.split(',');
7615 let x: usize = parts.next()?.parse().ok()?;
7616 let y: usize = parts.next()?.parse().ok()?;
7617 Some(point(px(x as f32), px(y as f32)))
7618}
7619
7620fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
7621 let mut parts = value.split(',');
7622 let width: usize = parts.next()?.parse().ok()?;
7623 let height: usize = parts.next()?.parse().ok()?;
7624 Some(size(px(width as f32), px(height as f32)))
7625}
7626
7627/// Add client-side decorations (rounded corners, shadows, resize handling) when appropriate.
7628pub fn client_side_decorations(
7629 element: impl IntoElement,
7630 window: &mut Window,
7631 cx: &mut App,
7632) -> Stateful<Div> {
7633 const BORDER_SIZE: Pixels = px(1.0);
7634 let decorations = window.window_decorations();
7635
7636 match decorations {
7637 Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
7638 Decorations::Server => window.set_client_inset(px(0.0)),
7639 }
7640
7641 struct GlobalResizeEdge(ResizeEdge);
7642 impl Global for GlobalResizeEdge {}
7643
7644 div()
7645 .id("window-backdrop")
7646 .bg(transparent_black())
7647 .map(|div| match decorations {
7648 Decorations::Server => div,
7649 Decorations::Client { tiling, .. } => div
7650 .when(!(tiling.top || tiling.right), |div| {
7651 div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING)
7652 })
7653 .when(!(tiling.top || tiling.left), |div| {
7654 div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
7655 })
7656 .when(!(tiling.bottom || tiling.right), |div| {
7657 div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING)
7658 })
7659 .when(!(tiling.bottom || tiling.left), |div| {
7660 div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
7661 })
7662 .when(!tiling.top, |div| {
7663 div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
7664 })
7665 .when(!tiling.bottom, |div| {
7666 div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
7667 })
7668 .when(!tiling.left, |div| {
7669 div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
7670 })
7671 .when(!tiling.right, |div| {
7672 div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
7673 })
7674 .on_mouse_move(move |e, window, cx| {
7675 let size = window.window_bounds().get_bounds().size;
7676 let pos = e.position;
7677
7678 let new_edge =
7679 resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
7680
7681 let edge = cx.try_global::<GlobalResizeEdge>();
7682 if new_edge != edge.map(|edge| edge.0) {
7683 window
7684 .window_handle()
7685 .update(cx, |workspace, _, cx| {
7686 cx.notify(workspace.entity_id());
7687 })
7688 .ok();
7689 }
7690 })
7691 .on_mouse_down(MouseButton::Left, move |e, window, _| {
7692 let size = window.window_bounds().get_bounds().size;
7693 let pos = e.position;
7694
7695 let edge = match resize_edge(
7696 pos,
7697 theme::CLIENT_SIDE_DECORATION_SHADOW,
7698 size,
7699 tiling,
7700 ) {
7701 Some(value) => value,
7702 None => return,
7703 };
7704
7705 window.start_window_resize(edge);
7706 }),
7707 })
7708 .size_full()
7709 .child(
7710 div()
7711 .cursor(CursorStyle::Arrow)
7712 .map(|div| match decorations {
7713 Decorations::Server => div,
7714 Decorations::Client { tiling } => div
7715 .border_color(cx.theme().colors().border)
7716 .when(!(tiling.top || tiling.right), |div| {
7717 div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING)
7718 })
7719 .when(!(tiling.top || tiling.left), |div| {
7720 div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
7721 })
7722 .when(!(tiling.bottom || tiling.right), |div| {
7723 div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING)
7724 })
7725 .when(!(tiling.bottom || tiling.left), |div| {
7726 div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
7727 })
7728 .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
7729 .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
7730 .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
7731 .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
7732 .when(!tiling.is_tiled(), |div| {
7733 div.shadow(vec![gpui::BoxShadow {
7734 color: Hsla {
7735 h: 0.,
7736 s: 0.,
7737 l: 0.,
7738 a: 0.4,
7739 },
7740 blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
7741 spread_radius: px(0.),
7742 offset: point(px(0.0), px(0.0)),
7743 }])
7744 }),
7745 })
7746 .on_mouse_move(|_e, _, cx| {
7747 cx.stop_propagation();
7748 })
7749 .size_full()
7750 .child(element),
7751 )
7752 .map(|div| match decorations {
7753 Decorations::Server => div,
7754 Decorations::Client { tiling, .. } => div.child(
7755 canvas(
7756 |_bounds, window, _| {
7757 window.insert_hitbox(
7758 Bounds::new(
7759 point(px(0.0), px(0.0)),
7760 window.window_bounds().get_bounds().size,
7761 ),
7762 HitboxBehavior::Normal,
7763 )
7764 },
7765 move |_bounds, hitbox, window, cx| {
7766 let mouse = window.mouse_position();
7767 let size = window.window_bounds().get_bounds().size;
7768 let Some(edge) =
7769 resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
7770 else {
7771 return;
7772 };
7773 cx.set_global(GlobalResizeEdge(edge));
7774 window.set_cursor_style(
7775 match edge {
7776 ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
7777 ResizeEdge::Left | ResizeEdge::Right => {
7778 CursorStyle::ResizeLeftRight
7779 }
7780 ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
7781 CursorStyle::ResizeUpLeftDownRight
7782 }
7783 ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
7784 CursorStyle::ResizeUpRightDownLeft
7785 }
7786 },
7787 &hitbox,
7788 );
7789 },
7790 )
7791 .size_full()
7792 .absolute(),
7793 ),
7794 })
7795}
7796
7797fn resize_edge(
7798 pos: Point<Pixels>,
7799 shadow_size: Pixels,
7800 window_size: Size<Pixels>,
7801 tiling: Tiling,
7802) -> Option<ResizeEdge> {
7803 let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
7804 if bounds.contains(&pos) {
7805 return None;
7806 }
7807
7808 let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
7809 let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
7810 if !tiling.top && top_left_bounds.contains(&pos) {
7811 return Some(ResizeEdge::TopLeft);
7812 }
7813
7814 let top_right_bounds = Bounds::new(
7815 Point::new(window_size.width - corner_size.width, px(0.)),
7816 corner_size,
7817 );
7818 if !tiling.top && top_right_bounds.contains(&pos) {
7819 return Some(ResizeEdge::TopRight);
7820 }
7821
7822 let bottom_left_bounds = Bounds::new(
7823 Point::new(px(0.), window_size.height - corner_size.height),
7824 corner_size,
7825 );
7826 if !tiling.bottom && bottom_left_bounds.contains(&pos) {
7827 return Some(ResizeEdge::BottomLeft);
7828 }
7829
7830 let bottom_right_bounds = Bounds::new(
7831 Point::new(
7832 window_size.width - corner_size.width,
7833 window_size.height - corner_size.height,
7834 ),
7835 corner_size,
7836 );
7837 if !tiling.bottom && bottom_right_bounds.contains(&pos) {
7838 return Some(ResizeEdge::BottomRight);
7839 }
7840
7841 if !tiling.top && pos.y < shadow_size {
7842 Some(ResizeEdge::Top)
7843 } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
7844 Some(ResizeEdge::Bottom)
7845 } else if !tiling.left && pos.x < shadow_size {
7846 Some(ResizeEdge::Left)
7847 } else if !tiling.right && pos.x > window_size.width - shadow_size {
7848 Some(ResizeEdge::Right)
7849 } else {
7850 None
7851 }
7852}
7853
7854fn join_pane_into_active(
7855 active_pane: &Entity<Pane>,
7856 pane: &Entity<Pane>,
7857 window: &mut Window,
7858 cx: &mut App,
7859) {
7860 if pane == active_pane {
7861 } else if pane.read(cx).items_len() == 0 {
7862 pane.update(cx, |_, cx| {
7863 cx.emit(pane::Event::Remove {
7864 focus_on_pane: None,
7865 });
7866 })
7867 } else {
7868 move_all_items(pane, active_pane, window, cx);
7869 }
7870}
7871
7872fn move_all_items(
7873 from_pane: &Entity<Pane>,
7874 to_pane: &Entity<Pane>,
7875 window: &mut Window,
7876 cx: &mut App,
7877) {
7878 let destination_is_different = from_pane != to_pane;
7879 let mut moved_items = 0;
7880 for (item_ix, item_handle) in from_pane
7881 .read(cx)
7882 .items()
7883 .enumerate()
7884 .map(|(ix, item)| (ix, item.clone()))
7885 .collect::<Vec<_>>()
7886 {
7887 let ix = item_ix - moved_items;
7888 if destination_is_different {
7889 // Close item from previous pane
7890 from_pane.update(cx, |source, cx| {
7891 source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
7892 });
7893 moved_items += 1;
7894 }
7895
7896 // This automatically removes duplicate items in the pane
7897 to_pane.update(cx, |destination, cx| {
7898 destination.add_item(item_handle, true, true, None, window, cx);
7899 window.focus(&destination.focus_handle(cx))
7900 });
7901 }
7902}
7903
7904pub fn move_item(
7905 source: &Entity<Pane>,
7906 destination: &Entity<Pane>,
7907 item_id_to_move: EntityId,
7908 destination_index: usize,
7909 activate: bool,
7910 window: &mut Window,
7911 cx: &mut App,
7912) {
7913 let Some((item_ix, item_handle)) = source
7914 .read(cx)
7915 .items()
7916 .enumerate()
7917 .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
7918 .map(|(ix, item)| (ix, item.clone()))
7919 else {
7920 // Tab was closed during drag
7921 return;
7922 };
7923
7924 if source != destination {
7925 // Close item from previous pane
7926 source.update(cx, |source, cx| {
7927 source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
7928 });
7929 }
7930
7931 // This automatically removes duplicate items in the pane
7932 destination.update(cx, |destination, cx| {
7933 destination.add_item_inner(
7934 item_handle,
7935 activate,
7936 activate,
7937 activate,
7938 Some(destination_index),
7939 window,
7940 cx,
7941 );
7942 if activate {
7943 window.focus(&destination.focus_handle(cx))
7944 }
7945 });
7946}
7947
7948pub fn move_active_item(
7949 source: &Entity<Pane>,
7950 destination: &Entity<Pane>,
7951 focus_destination: bool,
7952 close_if_empty: bool,
7953 window: &mut Window,
7954 cx: &mut App,
7955) {
7956 if source == destination {
7957 return;
7958 }
7959 let Some(active_item) = source.read(cx).active_item() else {
7960 return;
7961 };
7962 source.update(cx, |source_pane, cx| {
7963 let item_id = active_item.item_id();
7964 source_pane.remove_item(item_id, false, close_if_empty, window, cx);
7965 destination.update(cx, |target_pane, cx| {
7966 target_pane.add_item(
7967 active_item,
7968 focus_destination,
7969 focus_destination,
7970 Some(target_pane.items_len()),
7971 window,
7972 cx,
7973 );
7974 });
7975 });
7976}
7977
7978pub fn clone_active_item(
7979 workspace_id: Option<WorkspaceId>,
7980 source: &Entity<Pane>,
7981 destination: &Entity<Pane>,
7982 focus_destination: bool,
7983 window: &mut Window,
7984 cx: &mut App,
7985) {
7986 if source == destination {
7987 return;
7988 }
7989 let Some(active_item) = source.read(cx).active_item() else {
7990 return;
7991 };
7992 destination.update(cx, |target_pane, cx| {
7993 let Some(clone) = active_item.clone_on_split(workspace_id, window, cx) else {
7994 return;
7995 };
7996 target_pane.add_item(
7997 clone,
7998 focus_destination,
7999 focus_destination,
8000 Some(target_pane.items_len()),
8001 window,
8002 cx,
8003 );
8004 });
8005}
8006
8007#[derive(Debug)]
8008pub struct WorkspacePosition {
8009 pub window_bounds: Option<WindowBounds>,
8010 pub display: Option<Uuid>,
8011 pub centered_layout: bool,
8012}
8013
8014pub fn ssh_workspace_position_from_db(
8015 host: String,
8016 port: Option<u16>,
8017 user: Option<String>,
8018 paths_to_open: &[PathBuf],
8019 cx: &App,
8020) -> Task<Result<WorkspacePosition>> {
8021 let paths = paths_to_open.to_vec();
8022
8023 cx.background_spawn(async move {
8024 let ssh_connection_id = persistence::DB
8025 .get_or_create_ssh_connection(host, port, user)
8026 .await
8027 .context("fetching serialized ssh project")?;
8028 let serialized_workspace =
8029 persistence::DB.ssh_workspace_for_roots(&paths, ssh_connection_id);
8030
8031 let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
8032 (Some(WindowBounds::Windowed(bounds)), None)
8033 } else {
8034 let restorable_bounds = serialized_workspace
8035 .as_ref()
8036 .and_then(|workspace| Some((workspace.display?, workspace.window_bounds?)))
8037 .or_else(|| {
8038 let (display, window_bounds) = DB.last_window().log_err()?;
8039 Some((display?, window_bounds?))
8040 });
8041
8042 if let Some((serialized_display, serialized_status)) = restorable_bounds {
8043 (Some(serialized_status.0), Some(serialized_display))
8044 } else {
8045 (None, None)
8046 }
8047 };
8048
8049 let centered_layout = serialized_workspace
8050 .as_ref()
8051 .map(|w| w.centered_layout)
8052 .unwrap_or(false);
8053
8054 Ok(WorkspacePosition {
8055 window_bounds,
8056 display,
8057 centered_layout,
8058 })
8059 })
8060}
8061
8062pub fn with_active_or_new_workspace(
8063 cx: &mut App,
8064 f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
8065) {
8066 match cx.active_window().and_then(|w| w.downcast::<Workspace>()) {
8067 Some(workspace) => {
8068 cx.defer(move |cx| {
8069 workspace
8070 .update(cx, |workspace, window, cx| f(workspace, window, cx))
8071 .log_err();
8072 });
8073 }
8074 None => {
8075 let app_state = AppState::global(cx);
8076 if let Some(app_state) = app_state.upgrade() {
8077 open_new(
8078 OpenOptions::default(),
8079 app_state,
8080 cx,
8081 move |workspace, window, cx| f(workspace, window, cx),
8082 )
8083 .detach_and_log_err(cx);
8084 }
8085 }
8086 }
8087}
8088
8089#[cfg(test)]
8090mod tests {
8091 use std::{cell::RefCell, rc::Rc};
8092
8093 use super::*;
8094 use crate::{
8095 dock::{PanelEvent, test::TestPanel},
8096 item::{
8097 ItemEvent,
8098 test::{TestItem, TestProjectItem},
8099 },
8100 };
8101 use fs::FakeFs;
8102 use gpui::{
8103 DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
8104 UpdateGlobal, VisualTestContext, px,
8105 };
8106 use project::{Project, ProjectEntryId};
8107 use serde_json::json;
8108 use settings::SettingsStore;
8109
8110 #[gpui::test]
8111 async fn test_tab_disambiguation(cx: &mut TestAppContext) {
8112 init_test(cx);
8113
8114 let fs = FakeFs::new(cx.executor());
8115 let project = Project::test(fs, [], cx).await;
8116 let (workspace, cx) =
8117 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
8118
8119 // Adding an item with no ambiguity renders the tab without detail.
8120 let item1 = cx.new(|cx| {
8121 let mut item = TestItem::new(cx);
8122 item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
8123 item
8124 });
8125 workspace.update_in(cx, |workspace, window, cx| {
8126 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
8127 });
8128 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
8129
8130 // Adding an item that creates ambiguity increases the level of detail on
8131 // both tabs.
8132 let item2 = cx.new_window_entity(|_window, cx| {
8133 let mut item = TestItem::new(cx);
8134 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
8135 item
8136 });
8137 workspace.update_in(cx, |workspace, window, cx| {
8138 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
8139 });
8140 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
8141 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
8142
8143 // Adding an item that creates ambiguity increases the level of detail only
8144 // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
8145 // we stop at the highest detail available.
8146 let item3 = cx.new(|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(item3.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(3)));
8156 item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
8157 }
8158
8159 #[gpui::test]
8160 async fn test_tracking_active_path(cx: &mut TestAppContext) {
8161 init_test(cx);
8162
8163 let fs = FakeFs::new(cx.executor());
8164 fs.insert_tree(
8165 "/root1",
8166 json!({
8167 "one.txt": "",
8168 "two.txt": "",
8169 }),
8170 )
8171 .await;
8172 fs.insert_tree(
8173 "/root2",
8174 json!({
8175 "three.txt": "",
8176 }),
8177 )
8178 .await;
8179
8180 let project = Project::test(fs, ["root1".as_ref()], cx).await;
8181 let (workspace, cx) =
8182 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
8183 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
8184 let worktree_id = project.update(cx, |project, cx| {
8185 project.worktrees(cx).next().unwrap().read(cx).id()
8186 });
8187
8188 let item1 = cx.new(|cx| {
8189 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
8190 });
8191 let item2 = cx.new(|cx| {
8192 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
8193 });
8194
8195 // Add an item to an empty pane
8196 workspace.update_in(cx, |workspace, window, cx| {
8197 workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
8198 });
8199 project.update(cx, |project, cx| {
8200 assert_eq!(
8201 project.active_entry(),
8202 project
8203 .entry_for_path(&(worktree_id, "one.txt").into(), cx)
8204 .map(|e| e.id)
8205 );
8206 });
8207 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
8208
8209 // Add a second item to a non-empty pane
8210 workspace.update_in(cx, |workspace, window, cx| {
8211 workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
8212 });
8213 assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
8214 project.update(cx, |project, cx| {
8215 assert_eq!(
8216 project.active_entry(),
8217 project
8218 .entry_for_path(&(worktree_id, "two.txt").into(), cx)
8219 .map(|e| e.id)
8220 );
8221 });
8222
8223 // Close the active item
8224 pane.update_in(cx, |pane, window, cx| {
8225 pane.close_active_item(&Default::default(), window, cx)
8226 })
8227 .await
8228 .unwrap();
8229 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
8230 project.update(cx, |project, cx| {
8231 assert_eq!(
8232 project.active_entry(),
8233 project
8234 .entry_for_path(&(worktree_id, "one.txt").into(), cx)
8235 .map(|e| e.id)
8236 );
8237 });
8238
8239 // Add a project folder
8240 project
8241 .update(cx, |project, cx| {
8242 project.find_or_create_worktree("root2", true, cx)
8243 })
8244 .await
8245 .unwrap();
8246 assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
8247
8248 // Remove a project folder
8249 project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
8250 assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
8251 }
8252
8253 #[gpui::test]
8254 async fn test_close_window(cx: &mut TestAppContext) {
8255 init_test(cx);
8256
8257 let fs = FakeFs::new(cx.executor());
8258 fs.insert_tree("/root", json!({ "one": "" })).await;
8259
8260 let project = Project::test(fs, ["root".as_ref()], cx).await;
8261 let (workspace, cx) =
8262 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
8263
8264 // When there are no dirty items, there's nothing to do.
8265 let item1 = cx.new(TestItem::new);
8266 workspace.update_in(cx, |w, window, cx| {
8267 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
8268 });
8269 let task = workspace.update_in(cx, |w, window, cx| {
8270 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
8271 });
8272 assert!(task.await.unwrap());
8273
8274 // When there are dirty untitled items, prompt to save each one. If the user
8275 // cancels any prompt, then abort.
8276 let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
8277 let item3 = cx.new(|cx| {
8278 TestItem::new(cx)
8279 .with_dirty(true)
8280 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
8281 });
8282 workspace.update_in(cx, |w, window, cx| {
8283 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
8284 w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
8285 });
8286 let task = workspace.update_in(cx, |w, window, cx| {
8287 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
8288 });
8289 cx.executor().run_until_parked();
8290 cx.simulate_prompt_answer("Cancel"); // cancel save all
8291 cx.executor().run_until_parked();
8292 assert!(!cx.has_pending_prompt());
8293 assert!(!task.await.unwrap());
8294 }
8295
8296 #[gpui::test]
8297 async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
8298 init_test(cx);
8299
8300 // Register TestItem as a serializable item
8301 cx.update(|cx| {
8302 register_serializable_item::<TestItem>(cx);
8303 });
8304
8305 let fs = FakeFs::new(cx.executor());
8306 fs.insert_tree("/root", json!({ "one": "" })).await;
8307
8308 let project = Project::test(fs, ["root".as_ref()], cx).await;
8309 let (workspace, cx) =
8310 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
8311
8312 // When there are dirty untitled items, but they can serialize, then there is no prompt.
8313 let item1 = cx.new(|cx| {
8314 TestItem::new(cx)
8315 .with_dirty(true)
8316 .with_serialize(|| Some(Task::ready(Ok(()))))
8317 });
8318 let item2 = cx.new(|cx| {
8319 TestItem::new(cx)
8320 .with_dirty(true)
8321 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
8322 .with_serialize(|| Some(Task::ready(Ok(()))))
8323 });
8324 workspace.update_in(cx, |w, window, cx| {
8325 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
8326 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
8327 });
8328 let task = workspace.update_in(cx, |w, window, cx| {
8329 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
8330 });
8331 assert!(task.await.unwrap());
8332 }
8333
8334 #[gpui::test]
8335 async fn test_close_pane_items(cx: &mut TestAppContext) {
8336 init_test(cx);
8337
8338 let fs = FakeFs::new(cx.executor());
8339
8340 let project = Project::test(fs, None, cx).await;
8341 let (workspace, cx) =
8342 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
8343
8344 let item1 = cx.new(|cx| {
8345 TestItem::new(cx)
8346 .with_dirty(true)
8347 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
8348 });
8349 let item2 = cx.new(|cx| {
8350 TestItem::new(cx)
8351 .with_dirty(true)
8352 .with_conflict(true)
8353 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
8354 });
8355 let item3 = cx.new(|cx| {
8356 TestItem::new(cx)
8357 .with_dirty(true)
8358 .with_conflict(true)
8359 .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
8360 });
8361 let item4 = cx.new(|cx| {
8362 TestItem::new(cx).with_dirty(true).with_project_items(&[{
8363 let project_item = TestProjectItem::new_untitled(cx);
8364 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
8365 project_item
8366 }])
8367 });
8368 let pane = workspace.update_in(cx, |workspace, window, cx| {
8369 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
8370 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
8371 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
8372 workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
8373 workspace.active_pane().clone()
8374 });
8375
8376 let close_items = pane.update_in(cx, |pane, window, cx| {
8377 pane.activate_item(1, true, true, window, cx);
8378 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
8379 let item1_id = item1.item_id();
8380 let item3_id = item3.item_id();
8381 let item4_id = item4.item_id();
8382 pane.close_items(window, cx, SaveIntent::Close, move |id| {
8383 [item1_id, item3_id, item4_id].contains(&id)
8384 })
8385 });
8386 cx.executor().run_until_parked();
8387
8388 assert!(cx.has_pending_prompt());
8389 cx.simulate_prompt_answer("Save all");
8390
8391 cx.executor().run_until_parked();
8392
8393 // Item 1 is saved. There's a prompt to save item 3.
8394 pane.update(cx, |pane, cx| {
8395 assert_eq!(item1.read(cx).save_count, 1);
8396 assert_eq!(item1.read(cx).save_as_count, 0);
8397 assert_eq!(item1.read(cx).reload_count, 0);
8398 assert_eq!(pane.items_len(), 3);
8399 assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
8400 });
8401 assert!(cx.has_pending_prompt());
8402
8403 // Cancel saving item 3.
8404 cx.simulate_prompt_answer("Discard");
8405 cx.executor().run_until_parked();
8406
8407 // Item 3 is reloaded. There's a prompt to save item 4.
8408 pane.update(cx, |pane, cx| {
8409 assert_eq!(item3.read(cx).save_count, 0);
8410 assert_eq!(item3.read(cx).save_as_count, 0);
8411 assert_eq!(item3.read(cx).reload_count, 1);
8412 assert_eq!(pane.items_len(), 2);
8413 assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
8414 });
8415
8416 // There's a prompt for a path for item 4.
8417 cx.simulate_new_path_selection(|_| Some(Default::default()));
8418 close_items.await.unwrap();
8419
8420 // The requested items are closed.
8421 pane.update(cx, |pane, cx| {
8422 assert_eq!(item4.read(cx).save_count, 0);
8423 assert_eq!(item4.read(cx).save_as_count, 1);
8424 assert_eq!(item4.read(cx).reload_count, 0);
8425 assert_eq!(pane.items_len(), 1);
8426 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
8427 });
8428 }
8429
8430 #[gpui::test]
8431 async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
8432 init_test(cx);
8433
8434 let fs = FakeFs::new(cx.executor());
8435 let project = Project::test(fs, [], cx).await;
8436 let (workspace, cx) =
8437 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
8438
8439 // Create several workspace items with single project entries, and two
8440 // workspace items with multiple project entries.
8441 let single_entry_items = (0..=4)
8442 .map(|project_entry_id| {
8443 cx.new(|cx| {
8444 TestItem::new(cx)
8445 .with_dirty(true)
8446 .with_project_items(&[dirty_project_item(
8447 project_entry_id,
8448 &format!("{project_entry_id}.txt"),
8449 cx,
8450 )])
8451 })
8452 })
8453 .collect::<Vec<_>>();
8454 let item_2_3 = cx.new(|cx| {
8455 TestItem::new(cx)
8456 .with_dirty(true)
8457 .with_singleton(false)
8458 .with_project_items(&[
8459 single_entry_items[2].read(cx).project_items[0].clone(),
8460 single_entry_items[3].read(cx).project_items[0].clone(),
8461 ])
8462 });
8463 let item_3_4 = cx.new(|cx| {
8464 TestItem::new(cx)
8465 .with_dirty(true)
8466 .with_singleton(false)
8467 .with_project_items(&[
8468 single_entry_items[3].read(cx).project_items[0].clone(),
8469 single_entry_items[4].read(cx).project_items[0].clone(),
8470 ])
8471 });
8472
8473 // Create two panes that contain the following project entries:
8474 // left pane:
8475 // multi-entry items: (2, 3)
8476 // single-entry items: 0, 2, 3, 4
8477 // right pane:
8478 // single-entry items: 4, 1
8479 // multi-entry items: (3, 4)
8480 let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
8481 let left_pane = workspace.active_pane().clone();
8482 workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
8483 workspace.add_item_to_active_pane(
8484 single_entry_items[0].boxed_clone(),
8485 None,
8486 true,
8487 window,
8488 cx,
8489 );
8490 workspace.add_item_to_active_pane(
8491 single_entry_items[2].boxed_clone(),
8492 None,
8493 true,
8494 window,
8495 cx,
8496 );
8497 workspace.add_item_to_active_pane(
8498 single_entry_items[3].boxed_clone(),
8499 None,
8500 true,
8501 window,
8502 cx,
8503 );
8504 workspace.add_item_to_active_pane(
8505 single_entry_items[4].boxed_clone(),
8506 None,
8507 true,
8508 window,
8509 cx,
8510 );
8511
8512 let right_pane = workspace
8513 .split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx)
8514 .unwrap();
8515
8516 right_pane.update(cx, |pane, cx| {
8517 pane.add_item(
8518 single_entry_items[1].boxed_clone(),
8519 true,
8520 true,
8521 None,
8522 window,
8523 cx,
8524 );
8525 pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
8526 });
8527
8528 (left_pane, right_pane)
8529 });
8530
8531 cx.focus(&right_pane);
8532
8533 let mut close = right_pane.update_in(cx, |pane, window, cx| {
8534 pane.close_all_items(&CloseAllItems::default(), window, cx)
8535 .unwrap()
8536 });
8537 cx.executor().run_until_parked();
8538
8539 let msg = cx.pending_prompt().unwrap().0;
8540 assert!(msg.contains("1.txt"));
8541 assert!(!msg.contains("2.txt"));
8542 assert!(!msg.contains("3.txt"));
8543 assert!(!msg.contains("4.txt"));
8544
8545 cx.simulate_prompt_answer("Cancel");
8546 close.await;
8547
8548 left_pane
8549 .update_in(cx, |left_pane, window, cx| {
8550 left_pane.close_item_by_id(
8551 single_entry_items[3].entity_id(),
8552 SaveIntent::Skip,
8553 window,
8554 cx,
8555 )
8556 })
8557 .await
8558 .unwrap();
8559
8560 close = right_pane.update_in(cx, |pane, window, cx| {
8561 pane.close_all_items(&CloseAllItems::default(), window, cx)
8562 .unwrap()
8563 });
8564 cx.executor().run_until_parked();
8565
8566 let details = cx.pending_prompt().unwrap().1;
8567 assert!(details.contains("1.txt"));
8568 assert!(!details.contains("2.txt"));
8569 assert!(details.contains("3.txt"));
8570 // ideally this assertion could be made, but today we can only
8571 // save whole items not project items, so the orphaned item 3 causes
8572 // 4 to be saved too.
8573 // assert!(!details.contains("4.txt"));
8574
8575 cx.simulate_prompt_answer("Save all");
8576
8577 cx.executor().run_until_parked();
8578 close.await;
8579 right_pane.read_with(cx, |pane, _| {
8580 assert_eq!(pane.items_len(), 0);
8581 });
8582 }
8583
8584 #[gpui::test]
8585 async fn test_autosave(cx: &mut gpui::TestAppContext) {
8586 init_test(cx);
8587
8588 let fs = FakeFs::new(cx.executor());
8589 let project = Project::test(fs, [], cx).await;
8590 let (workspace, cx) =
8591 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
8592 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
8593
8594 let item = cx.new(|cx| {
8595 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
8596 });
8597 let item_id = item.entity_id();
8598 workspace.update_in(cx, |workspace, window, cx| {
8599 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
8600 });
8601
8602 // Autosave on window change.
8603 item.update(cx, |item, cx| {
8604 SettingsStore::update_global(cx, |settings, cx| {
8605 settings.update_user_settings::<WorkspaceSettings>(cx, |settings| {
8606 settings.autosave = Some(AutosaveSetting::OnWindowChange);
8607 })
8608 });
8609 item.is_dirty = true;
8610 });
8611
8612 // Deactivating the window saves the file.
8613 cx.deactivate_window();
8614 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
8615
8616 // Re-activating the window doesn't save the file.
8617 cx.update(|window, _| window.activate_window());
8618 cx.executor().run_until_parked();
8619 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
8620
8621 // Autosave on focus change.
8622 item.update_in(cx, |item, window, cx| {
8623 cx.focus_self(window);
8624 SettingsStore::update_global(cx, |settings, cx| {
8625 settings.update_user_settings::<WorkspaceSettings>(cx, |settings| {
8626 settings.autosave = Some(AutosaveSetting::OnFocusChange);
8627 })
8628 });
8629 item.is_dirty = true;
8630 });
8631
8632 // Blurring the item saves the file.
8633 item.update_in(cx, |_, window, _| window.blur());
8634 cx.executor().run_until_parked();
8635 item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
8636
8637 // Deactivating the window still saves the file.
8638 item.update_in(cx, |item, window, cx| {
8639 cx.focus_self(window);
8640 item.is_dirty = true;
8641 });
8642 cx.deactivate_window();
8643 item.update(cx, |item, _| assert_eq!(item.save_count, 3));
8644
8645 // Autosave after delay.
8646 item.update(cx, |item, cx| {
8647 SettingsStore::update_global(cx, |settings, cx| {
8648 settings.update_user_settings::<WorkspaceSettings>(cx, |settings| {
8649 settings.autosave = Some(AutosaveSetting::AfterDelay { milliseconds: 500 });
8650 })
8651 });
8652 item.is_dirty = true;
8653 cx.emit(ItemEvent::Edit);
8654 });
8655
8656 // Delay hasn't fully expired, so the file is still dirty and unsaved.
8657 cx.executor().advance_clock(Duration::from_millis(250));
8658 item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
8659
8660 // After delay expires, the file is saved.
8661 cx.executor().advance_clock(Duration::from_millis(250));
8662 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
8663
8664 // Autosave on focus change, ensuring closing the tab counts as such.
8665 item.update(cx, |item, cx| {
8666 SettingsStore::update_global(cx, |settings, cx| {
8667 settings.update_user_settings::<WorkspaceSettings>(cx, |settings| {
8668 settings.autosave = Some(AutosaveSetting::OnFocusChange);
8669 })
8670 });
8671 item.is_dirty = true;
8672 for project_item in &mut item.project_items {
8673 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
8674 }
8675 });
8676
8677 pane.update_in(cx, |pane, window, cx| {
8678 pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
8679 })
8680 .await
8681 .unwrap();
8682 assert!(!cx.has_pending_prompt());
8683 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
8684
8685 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
8686 workspace.update_in(cx, |workspace, window, cx| {
8687 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
8688 });
8689 item.update_in(cx, |item, window, cx| {
8690 item.project_items[0].update(cx, |item, _| {
8691 item.entry_id = None;
8692 });
8693 item.is_dirty = true;
8694 window.blur();
8695 });
8696 cx.run_until_parked();
8697 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
8698
8699 // Ensure autosave is prevented for deleted files also when closing the buffer.
8700 let _close_items = pane.update_in(cx, |pane, window, cx| {
8701 pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
8702 });
8703 cx.run_until_parked();
8704 assert!(cx.has_pending_prompt());
8705 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
8706 }
8707
8708 #[gpui::test]
8709 async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
8710 init_test(cx);
8711
8712 let fs = FakeFs::new(cx.executor());
8713
8714 let project = Project::test(fs, [], cx).await;
8715 let (workspace, cx) =
8716 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
8717
8718 let item = cx.new(|cx| {
8719 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
8720 });
8721 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
8722 let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
8723 let toolbar_notify_count = Rc::new(RefCell::new(0));
8724
8725 workspace.update_in(cx, |workspace, window, cx| {
8726 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
8727 let toolbar_notification_count = toolbar_notify_count.clone();
8728 cx.observe_in(&toolbar, window, move |_, _, _, _| {
8729 *toolbar_notification_count.borrow_mut() += 1
8730 })
8731 .detach();
8732 });
8733
8734 pane.read_with(cx, |pane, _| {
8735 assert!(!pane.can_navigate_backward());
8736 assert!(!pane.can_navigate_forward());
8737 });
8738
8739 item.update_in(cx, |item, _, cx| {
8740 item.set_state("one".to_string(), cx);
8741 });
8742
8743 // Toolbar must be notified to re-render the navigation buttons
8744 assert_eq!(*toolbar_notify_count.borrow(), 1);
8745
8746 pane.read_with(cx, |pane, _| {
8747 assert!(pane.can_navigate_backward());
8748 assert!(!pane.can_navigate_forward());
8749 });
8750
8751 workspace
8752 .update_in(cx, |workspace, window, cx| {
8753 workspace.go_back(pane.downgrade(), window, cx)
8754 })
8755 .await
8756 .unwrap();
8757
8758 assert_eq!(*toolbar_notify_count.borrow(), 2);
8759 pane.read_with(cx, |pane, _| {
8760 assert!(!pane.can_navigate_backward());
8761 assert!(pane.can_navigate_forward());
8762 });
8763 }
8764
8765 #[gpui::test]
8766 async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
8767 init_test(cx);
8768 let fs = FakeFs::new(cx.executor());
8769
8770 let project = Project::test(fs, [], cx).await;
8771 let (workspace, cx) =
8772 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
8773
8774 let panel = workspace.update_in(cx, |workspace, window, cx| {
8775 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, cx));
8776 workspace.add_panel(panel.clone(), window, cx);
8777
8778 workspace
8779 .right_dock()
8780 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
8781
8782 panel
8783 });
8784
8785 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
8786 pane.update_in(cx, |pane, window, cx| {
8787 let item = cx.new(TestItem::new);
8788 pane.add_item(Box::new(item), true, true, None, window, cx);
8789 });
8790
8791 // Transfer focus from center to panel
8792 workspace.update_in(cx, |workspace, window, cx| {
8793 workspace.toggle_panel_focus::<TestPanel>(window, cx);
8794 });
8795
8796 workspace.update_in(cx, |workspace, window, cx| {
8797 assert!(workspace.right_dock().read(cx).is_open());
8798 assert!(!panel.is_zoomed(window, cx));
8799 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
8800 });
8801
8802 // Transfer focus from panel to center
8803 workspace.update_in(cx, |workspace, window, cx| {
8804 workspace.toggle_panel_focus::<TestPanel>(window, cx);
8805 });
8806
8807 workspace.update_in(cx, |workspace, window, cx| {
8808 assert!(workspace.right_dock().read(cx).is_open());
8809 assert!(!panel.is_zoomed(window, cx));
8810 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
8811 });
8812
8813 // Close the dock
8814 workspace.update_in(cx, |workspace, window, cx| {
8815 workspace.toggle_dock(DockPosition::Right, window, cx);
8816 });
8817
8818 workspace.update_in(cx, |workspace, window, cx| {
8819 assert!(!workspace.right_dock().read(cx).is_open());
8820 assert!(!panel.is_zoomed(window, cx));
8821 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
8822 });
8823
8824 // Open the dock
8825 workspace.update_in(cx, |workspace, window, cx| {
8826 workspace.toggle_dock(DockPosition::Right, window, cx);
8827 });
8828
8829 workspace.update_in(cx, |workspace, window, cx| {
8830 assert!(workspace.right_dock().read(cx).is_open());
8831 assert!(!panel.is_zoomed(window, cx));
8832 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
8833 });
8834
8835 // Focus and zoom panel
8836 panel.update_in(cx, |panel, window, cx| {
8837 cx.focus_self(window);
8838 panel.set_zoomed(true, window, cx)
8839 });
8840
8841 workspace.update_in(cx, |workspace, window, cx| {
8842 assert!(workspace.right_dock().read(cx).is_open());
8843 assert!(panel.is_zoomed(window, cx));
8844 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
8845 });
8846
8847 // Transfer focus to the center closes the dock
8848 workspace.update_in(cx, |workspace, window, cx| {
8849 workspace.toggle_panel_focus::<TestPanel>(window, cx);
8850 });
8851
8852 workspace.update_in(cx, |workspace, window, cx| {
8853 assert!(!workspace.right_dock().read(cx).is_open());
8854 assert!(panel.is_zoomed(window, cx));
8855 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
8856 });
8857
8858 // Transferring focus back to the panel keeps it zoomed
8859 workspace.update_in(cx, |workspace, window, cx| {
8860 workspace.toggle_panel_focus::<TestPanel>(window, cx);
8861 });
8862
8863 workspace.update_in(cx, |workspace, window, cx| {
8864 assert!(workspace.right_dock().read(cx).is_open());
8865 assert!(panel.is_zoomed(window, cx));
8866 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
8867 });
8868
8869 // Close the dock while it is zoomed
8870 workspace.update_in(cx, |workspace, window, cx| {
8871 workspace.toggle_dock(DockPosition::Right, window, cx)
8872 });
8873
8874 workspace.update_in(cx, |workspace, window, cx| {
8875 assert!(!workspace.right_dock().read(cx).is_open());
8876 assert!(panel.is_zoomed(window, cx));
8877 assert!(workspace.zoomed.is_none());
8878 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
8879 });
8880
8881 // Opening the dock, when it's zoomed, retains focus
8882 workspace.update_in(cx, |workspace, window, cx| {
8883 workspace.toggle_dock(DockPosition::Right, window, cx)
8884 });
8885
8886 workspace.update_in(cx, |workspace, window, cx| {
8887 assert!(workspace.right_dock().read(cx).is_open());
8888 assert!(panel.is_zoomed(window, cx));
8889 assert!(workspace.zoomed.is_some());
8890 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
8891 });
8892
8893 // Unzoom and close the panel, zoom the active pane.
8894 panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
8895 workspace.update_in(cx, |workspace, window, cx| {
8896 workspace.toggle_dock(DockPosition::Right, window, cx)
8897 });
8898 pane.update_in(cx, |pane, window, cx| {
8899 pane.toggle_zoom(&Default::default(), window, cx)
8900 });
8901
8902 // Opening a dock unzooms the pane.
8903 workspace.update_in(cx, |workspace, window, cx| {
8904 workspace.toggle_dock(DockPosition::Right, window, cx)
8905 });
8906 workspace.update_in(cx, |workspace, window, cx| {
8907 let pane = pane.read(cx);
8908 assert!(!pane.is_zoomed());
8909 assert!(!pane.focus_handle(cx).is_focused(window));
8910 assert!(workspace.right_dock().read(cx).is_open());
8911 assert!(workspace.zoomed.is_none());
8912 });
8913 }
8914
8915 #[gpui::test]
8916 async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
8917 init_test(cx);
8918
8919 let fs = FakeFs::new(cx.executor());
8920
8921 let project = Project::test(fs, None, cx).await;
8922 let (workspace, cx) =
8923 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
8924
8925 // Let's arrange the panes like this:
8926 //
8927 // +-----------------------+
8928 // | top |
8929 // +------+--------+-------+
8930 // | left | center | right |
8931 // +------+--------+-------+
8932 // | bottom |
8933 // +-----------------------+
8934
8935 let top_item = cx.new(|cx| {
8936 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
8937 });
8938 let bottom_item = cx.new(|cx| {
8939 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
8940 });
8941 let left_item = cx.new(|cx| {
8942 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
8943 });
8944 let right_item = cx.new(|cx| {
8945 TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
8946 });
8947 let center_item = cx.new(|cx| {
8948 TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
8949 });
8950
8951 let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
8952 let top_pane_id = workspace.active_pane().entity_id();
8953 workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
8954 workspace.split_pane(
8955 workspace.active_pane().clone(),
8956 SplitDirection::Down,
8957 window,
8958 cx,
8959 );
8960 top_pane_id
8961 });
8962 let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
8963 let bottom_pane_id = workspace.active_pane().entity_id();
8964 workspace.add_item_to_active_pane(
8965 Box::new(bottom_item.clone()),
8966 None,
8967 false,
8968 window,
8969 cx,
8970 );
8971 workspace.split_pane(
8972 workspace.active_pane().clone(),
8973 SplitDirection::Up,
8974 window,
8975 cx,
8976 );
8977 bottom_pane_id
8978 });
8979 let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
8980 let left_pane_id = workspace.active_pane().entity_id();
8981 workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
8982 workspace.split_pane(
8983 workspace.active_pane().clone(),
8984 SplitDirection::Right,
8985 window,
8986 cx,
8987 );
8988 left_pane_id
8989 });
8990 let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
8991 let right_pane_id = workspace.active_pane().entity_id();
8992 workspace.add_item_to_active_pane(
8993 Box::new(right_item.clone()),
8994 None,
8995 false,
8996 window,
8997 cx,
8998 );
8999 workspace.split_pane(
9000 workspace.active_pane().clone(),
9001 SplitDirection::Left,
9002 window,
9003 cx,
9004 );
9005 right_pane_id
9006 });
9007 let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
9008 let center_pane_id = workspace.active_pane().entity_id();
9009 workspace.add_item_to_active_pane(
9010 Box::new(center_item.clone()),
9011 None,
9012 false,
9013 window,
9014 cx,
9015 );
9016 center_pane_id
9017 });
9018 cx.executor().run_until_parked();
9019
9020 workspace.update_in(cx, |workspace, window, cx| {
9021 assert_eq!(center_pane_id, workspace.active_pane().entity_id());
9022
9023 // Join into next from center pane into right
9024 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
9025 });
9026
9027 workspace.update_in(cx, |workspace, window, cx| {
9028 let active_pane = workspace.active_pane();
9029 assert_eq!(right_pane_id, active_pane.entity_id());
9030 assert_eq!(2, active_pane.read(cx).items_len());
9031 let item_ids_in_pane =
9032 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
9033 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
9034 assert!(item_ids_in_pane.contains(&right_item.item_id()));
9035
9036 // Join into next from right pane into bottom
9037 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
9038 });
9039
9040 workspace.update_in(cx, |workspace, window, cx| {
9041 let active_pane = workspace.active_pane();
9042 assert_eq!(bottom_pane_id, active_pane.entity_id());
9043 assert_eq!(3, active_pane.read(cx).items_len());
9044 let item_ids_in_pane =
9045 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
9046 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
9047 assert!(item_ids_in_pane.contains(&right_item.item_id()));
9048 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
9049
9050 // Join into next from bottom pane into left
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!(left_pane_id, active_pane.entity_id());
9057 assert_eq!(4, 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 assert!(item_ids_in_pane.contains(&left_item.item_id()));
9064
9065 // Join into next from left pane into top
9066 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
9067 });
9068
9069 workspace.update_in(cx, |workspace, window, cx| {
9070 let active_pane = workspace.active_pane();
9071 assert_eq!(top_pane_id, active_pane.entity_id());
9072 assert_eq!(5, active_pane.read(cx).items_len());
9073 let item_ids_in_pane =
9074 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
9075 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
9076 assert!(item_ids_in_pane.contains(&right_item.item_id()));
9077 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
9078 assert!(item_ids_in_pane.contains(&left_item.item_id()));
9079 assert!(item_ids_in_pane.contains(&top_item.item_id()));
9080
9081 // Single pane left: no-op
9082 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
9083 });
9084
9085 workspace.update(cx, |workspace, _cx| {
9086 let active_pane = workspace.active_pane();
9087 assert_eq!(top_pane_id, active_pane.entity_id());
9088 });
9089 }
9090
9091 fn add_an_item_to_active_pane(
9092 cx: &mut VisualTestContext,
9093 workspace: &Entity<Workspace>,
9094 item_id: u64,
9095 ) -> Entity<TestItem> {
9096 let item = cx.new(|cx| {
9097 TestItem::new(cx).with_project_items(&[TestProjectItem::new(
9098 item_id,
9099 "item{item_id}.txt",
9100 cx,
9101 )])
9102 });
9103 workspace.update_in(cx, |workspace, window, cx| {
9104 workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
9105 });
9106 item
9107 }
9108
9109 fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
9110 workspace.update_in(cx, |workspace, window, cx| {
9111 workspace.split_pane(
9112 workspace.active_pane().clone(),
9113 SplitDirection::Right,
9114 window,
9115 cx,
9116 )
9117 })
9118 }
9119
9120 #[gpui::test]
9121 async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
9122 init_test(cx);
9123 let fs = FakeFs::new(cx.executor());
9124 let project = Project::test(fs, None, cx).await;
9125 let (workspace, cx) =
9126 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9127
9128 add_an_item_to_active_pane(cx, &workspace, 1);
9129 split_pane(cx, &workspace);
9130 add_an_item_to_active_pane(cx, &workspace, 2);
9131 split_pane(cx, &workspace); // empty pane
9132 split_pane(cx, &workspace);
9133 let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
9134
9135 cx.executor().run_until_parked();
9136
9137 workspace.update(cx, |workspace, cx| {
9138 let num_panes = workspace.panes().len();
9139 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
9140 let active_item = workspace
9141 .active_pane()
9142 .read(cx)
9143 .active_item()
9144 .expect("item is in focus");
9145
9146 assert_eq!(num_panes, 4);
9147 assert_eq!(num_items_in_current_pane, 1);
9148 assert_eq!(active_item.item_id(), last_item.item_id());
9149 });
9150
9151 workspace.update_in(cx, |workspace, window, cx| {
9152 workspace.join_all_panes(window, cx);
9153 });
9154
9155 workspace.update(cx, |workspace, cx| {
9156 let num_panes = workspace.panes().len();
9157 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
9158 let active_item = workspace
9159 .active_pane()
9160 .read(cx)
9161 .active_item()
9162 .expect("item is in focus");
9163
9164 assert_eq!(num_panes, 1);
9165 assert_eq!(num_items_in_current_pane, 3);
9166 assert_eq!(active_item.item_id(), last_item.item_id());
9167 });
9168 }
9169 struct TestModal(FocusHandle);
9170
9171 impl TestModal {
9172 fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
9173 Self(cx.focus_handle())
9174 }
9175 }
9176
9177 impl EventEmitter<DismissEvent> for TestModal {}
9178
9179 impl Focusable for TestModal {
9180 fn focus_handle(&self, _cx: &App) -> FocusHandle {
9181 self.0.clone()
9182 }
9183 }
9184
9185 impl ModalView for TestModal {}
9186
9187 impl Render for TestModal {
9188 fn render(
9189 &mut self,
9190 _window: &mut Window,
9191 _cx: &mut Context<TestModal>,
9192 ) -> impl IntoElement {
9193 div().track_focus(&self.0)
9194 }
9195 }
9196
9197 #[gpui::test]
9198 async fn test_panels(cx: &mut gpui::TestAppContext) {
9199 init_test(cx);
9200 let fs = FakeFs::new(cx.executor());
9201
9202 let project = Project::test(fs, [], cx).await;
9203 let (workspace, cx) =
9204 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9205
9206 let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
9207 let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, cx));
9208 workspace.add_panel(panel_1.clone(), window, cx);
9209 workspace.toggle_dock(DockPosition::Left, window, cx);
9210 let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, cx));
9211 workspace.add_panel(panel_2.clone(), window, cx);
9212 workspace.toggle_dock(DockPosition::Right, window, cx);
9213
9214 let left_dock = workspace.left_dock();
9215 assert_eq!(
9216 left_dock.read(cx).visible_panel().unwrap().panel_id(),
9217 panel_1.panel_id()
9218 );
9219 assert_eq!(
9220 left_dock.read(cx).active_panel_size(window, cx).unwrap(),
9221 panel_1.size(window, cx)
9222 );
9223
9224 left_dock.update(cx, |left_dock, cx| {
9225 left_dock.resize_active_panel(Some(px(1337.)), window, cx)
9226 });
9227 assert_eq!(
9228 workspace
9229 .right_dock()
9230 .read(cx)
9231 .visible_panel()
9232 .unwrap()
9233 .panel_id(),
9234 panel_2.panel_id(),
9235 );
9236
9237 (panel_1, panel_2)
9238 });
9239
9240 // Move panel_1 to the right
9241 panel_1.update_in(cx, |panel_1, window, cx| {
9242 panel_1.set_position(DockPosition::Right, window, cx)
9243 });
9244
9245 workspace.update_in(cx, |workspace, window, cx| {
9246 // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
9247 // Since it was the only panel on the left, the left dock should now be closed.
9248 assert!(!workspace.left_dock().read(cx).is_open());
9249 assert!(workspace.left_dock().read(cx).visible_panel().is_none());
9250 let right_dock = workspace.right_dock();
9251 assert_eq!(
9252 right_dock.read(cx).visible_panel().unwrap().panel_id(),
9253 panel_1.panel_id()
9254 );
9255 assert_eq!(
9256 right_dock.read(cx).active_panel_size(window, cx).unwrap(),
9257 px(1337.)
9258 );
9259
9260 // Now we move panel_2 to the left
9261 panel_2.set_position(DockPosition::Left, window, cx);
9262 });
9263
9264 workspace.update(cx, |workspace, cx| {
9265 // Since panel_2 was not visible on the right, we don't open the left dock.
9266 assert!(!workspace.left_dock().read(cx).is_open());
9267 // And the right dock is unaffected in its displaying of panel_1
9268 assert!(workspace.right_dock().read(cx).is_open());
9269 assert_eq!(
9270 workspace
9271 .right_dock()
9272 .read(cx)
9273 .visible_panel()
9274 .unwrap()
9275 .panel_id(),
9276 panel_1.panel_id(),
9277 );
9278 });
9279
9280 // Move panel_1 back to the left
9281 panel_1.update_in(cx, |panel_1, window, cx| {
9282 panel_1.set_position(DockPosition::Left, window, cx)
9283 });
9284
9285 workspace.update_in(cx, |workspace, window, cx| {
9286 // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
9287 let left_dock = workspace.left_dock();
9288 assert!(left_dock.read(cx).is_open());
9289 assert_eq!(
9290 left_dock.read(cx).visible_panel().unwrap().panel_id(),
9291 panel_1.panel_id()
9292 );
9293 assert_eq!(
9294 left_dock.read(cx).active_panel_size(window, cx).unwrap(),
9295 px(1337.)
9296 );
9297 // And the right dock should be closed as it no longer has any panels.
9298 assert!(!workspace.right_dock().read(cx).is_open());
9299
9300 // Now we move panel_1 to the bottom
9301 panel_1.set_position(DockPosition::Bottom, window, cx);
9302 });
9303
9304 workspace.update_in(cx, |workspace, window, cx| {
9305 // Since panel_1 was visible on the left, we close the left dock.
9306 assert!(!workspace.left_dock().read(cx).is_open());
9307 // The bottom dock is sized based on the panel's default size,
9308 // since the panel orientation changed from vertical to horizontal.
9309 let bottom_dock = workspace.bottom_dock();
9310 assert_eq!(
9311 bottom_dock.read(cx).active_panel_size(window, cx).unwrap(),
9312 panel_1.size(window, cx),
9313 );
9314 // Close bottom dock and move panel_1 back to the left.
9315 bottom_dock.update(cx, |bottom_dock, cx| {
9316 bottom_dock.set_open(false, window, cx)
9317 });
9318 panel_1.set_position(DockPosition::Left, window, cx);
9319 });
9320
9321 // Emit activated event on panel 1
9322 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
9323
9324 // Now the left dock is open and panel_1 is active and focused.
9325 workspace.update_in(cx, |workspace, window, cx| {
9326 let left_dock = workspace.left_dock();
9327 assert!(left_dock.read(cx).is_open());
9328 assert_eq!(
9329 left_dock.read(cx).visible_panel().unwrap().panel_id(),
9330 panel_1.panel_id(),
9331 );
9332 assert!(panel_1.focus_handle(cx).is_focused(window));
9333 });
9334
9335 // Emit closed event on panel 2, which is not active
9336 panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
9337
9338 // Wo don't close the left dock, because panel_2 wasn't the active panel
9339 workspace.update(cx, |workspace, 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 });
9347
9348 // Emitting a ZoomIn event shows the panel as zoomed.
9349 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
9350 workspace.read_with(cx, |workspace, _| {
9351 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
9352 assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
9353 });
9354
9355 // Move panel to another dock while it is zoomed
9356 panel_1.update_in(cx, |panel, window, cx| {
9357 panel.set_position(DockPosition::Right, window, cx)
9358 });
9359 workspace.read_with(cx, |workspace, _| {
9360 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
9361
9362 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
9363 });
9364
9365 // This is a helper for getting a:
9366 // - valid focus on an element,
9367 // - that isn't a part of the panes and panels system of the Workspace,
9368 // - and doesn't trigger the 'on_focus_lost' API.
9369 let focus_other_view = {
9370 let workspace = workspace.clone();
9371 move |cx: &mut VisualTestContext| {
9372 workspace.update_in(cx, |workspace, window, cx| {
9373 if workspace.active_modal::<TestModal>(cx).is_some() {
9374 workspace.toggle_modal(window, cx, TestModal::new);
9375 workspace.toggle_modal(window, cx, TestModal::new);
9376 } else {
9377 workspace.toggle_modal(window, cx, TestModal::new);
9378 }
9379 })
9380 }
9381 };
9382
9383 // If focus is transferred to another view that's not a panel or another pane, we still show
9384 // the panel as zoomed.
9385 focus_other_view(cx);
9386 workspace.read_with(cx, |workspace, _| {
9387 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
9388 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
9389 });
9390
9391 // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
9392 workspace.update_in(cx, |_workspace, window, cx| {
9393 cx.focus_self(window);
9394 });
9395 workspace.read_with(cx, |workspace, _| {
9396 assert_eq!(workspace.zoomed, None);
9397 assert_eq!(workspace.zoomed_position, None);
9398 });
9399
9400 // If focus is transferred again to another view that's not a panel or a pane, we won't
9401 // show the panel as zoomed because it wasn't zoomed before.
9402 focus_other_view(cx);
9403 workspace.read_with(cx, |workspace, _| {
9404 assert_eq!(workspace.zoomed, None);
9405 assert_eq!(workspace.zoomed_position, None);
9406 });
9407
9408 // When the panel is activated, it is zoomed again.
9409 cx.dispatch_action(ToggleRightDock);
9410 workspace.read_with(cx, |workspace, _| {
9411 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
9412 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
9413 });
9414
9415 // Emitting a ZoomOut event unzooms the panel.
9416 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
9417 workspace.read_with(cx, |workspace, _| {
9418 assert_eq!(workspace.zoomed, None);
9419 assert_eq!(workspace.zoomed_position, None);
9420 });
9421
9422 // Emit closed event on panel 1, which is active
9423 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
9424
9425 // Now the left dock is closed, because panel_1 was the active panel
9426 workspace.update(cx, |workspace, cx| {
9427 let right_dock = workspace.right_dock();
9428 assert!(!right_dock.read(cx).is_open());
9429 });
9430 }
9431
9432 #[gpui::test]
9433 async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
9434 init_test(cx);
9435
9436 let fs = FakeFs::new(cx.background_executor.clone());
9437 let project = Project::test(fs, [], cx).await;
9438 let (workspace, cx) =
9439 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9440 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
9441
9442 let dirty_regular_buffer = cx.new(|cx| {
9443 TestItem::new(cx)
9444 .with_dirty(true)
9445 .with_label("1.txt")
9446 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
9447 });
9448 let dirty_regular_buffer_2 = cx.new(|cx| {
9449 TestItem::new(cx)
9450 .with_dirty(true)
9451 .with_label("2.txt")
9452 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
9453 });
9454 let dirty_multi_buffer_with_both = cx.new(|cx| {
9455 TestItem::new(cx)
9456 .with_dirty(true)
9457 .with_singleton(false)
9458 .with_label("Fake Project Search")
9459 .with_project_items(&[
9460 dirty_regular_buffer.read(cx).project_items[0].clone(),
9461 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
9462 ])
9463 });
9464 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
9465 workspace.update_in(cx, |workspace, window, cx| {
9466 workspace.add_item(
9467 pane.clone(),
9468 Box::new(dirty_regular_buffer.clone()),
9469 None,
9470 false,
9471 false,
9472 window,
9473 cx,
9474 );
9475 workspace.add_item(
9476 pane.clone(),
9477 Box::new(dirty_regular_buffer_2.clone()),
9478 None,
9479 false,
9480 false,
9481 window,
9482 cx,
9483 );
9484 workspace.add_item(
9485 pane.clone(),
9486 Box::new(dirty_multi_buffer_with_both.clone()),
9487 None,
9488 false,
9489 false,
9490 window,
9491 cx,
9492 );
9493 });
9494
9495 pane.update_in(cx, |pane, window, cx| {
9496 pane.activate_item(2, true, true, window, cx);
9497 assert_eq!(
9498 pane.active_item().unwrap().item_id(),
9499 multi_buffer_with_both_files_id,
9500 "Should select the multi buffer in the pane"
9501 );
9502 });
9503 let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
9504 pane.close_other_items(
9505 &CloseOtherItems {
9506 save_intent: Some(SaveIntent::Save),
9507 close_pinned: true,
9508 },
9509 None,
9510 window,
9511 cx,
9512 )
9513 });
9514 cx.background_executor.run_until_parked();
9515 assert!(!cx.has_pending_prompt());
9516 close_all_but_multi_buffer_task
9517 .await
9518 .expect("Closing all buffers but the multi buffer failed");
9519 pane.update(cx, |pane, cx| {
9520 assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
9521 assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
9522 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
9523 assert_eq!(pane.items_len(), 1);
9524 assert_eq!(
9525 pane.active_item().unwrap().item_id(),
9526 multi_buffer_with_both_files_id,
9527 "Should have only the multi buffer left in the pane"
9528 );
9529 assert!(
9530 dirty_multi_buffer_with_both.read(cx).is_dirty,
9531 "The multi buffer containing the unsaved buffer should still be dirty"
9532 );
9533 });
9534
9535 dirty_regular_buffer.update(cx, |buffer, cx| {
9536 buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
9537 });
9538
9539 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
9540 pane.close_active_item(
9541 &CloseActiveItem {
9542 save_intent: Some(SaveIntent::Close),
9543 close_pinned: false,
9544 },
9545 window,
9546 cx,
9547 )
9548 });
9549 cx.background_executor.run_until_parked();
9550 assert!(
9551 cx.has_pending_prompt(),
9552 "Dirty multi buffer should prompt a save dialog"
9553 );
9554 cx.simulate_prompt_answer("Save");
9555 cx.background_executor.run_until_parked();
9556 close_multi_buffer_task
9557 .await
9558 .expect("Closing the multi buffer failed");
9559 pane.update(cx, |pane, cx| {
9560 assert_eq!(
9561 dirty_multi_buffer_with_both.read(cx).save_count,
9562 1,
9563 "Multi buffer item should get be saved"
9564 );
9565 // Test impl does not save inner items, so we do not assert them
9566 assert_eq!(
9567 pane.items_len(),
9568 0,
9569 "No more items should be left in the pane"
9570 );
9571 assert!(pane.active_item().is_none());
9572 });
9573 }
9574
9575 #[gpui::test]
9576 async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
9577 cx: &mut TestAppContext,
9578 ) {
9579 init_test(cx);
9580
9581 let fs = FakeFs::new(cx.background_executor.clone());
9582 let project = Project::test(fs, [], cx).await;
9583 let (workspace, cx) =
9584 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9585 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
9586
9587 let dirty_regular_buffer = cx.new(|cx| {
9588 TestItem::new(cx)
9589 .with_dirty(true)
9590 .with_label("1.txt")
9591 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
9592 });
9593 let dirty_regular_buffer_2 = cx.new(|cx| {
9594 TestItem::new(cx)
9595 .with_dirty(true)
9596 .with_label("2.txt")
9597 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
9598 });
9599 let clear_regular_buffer = cx.new(|cx| {
9600 TestItem::new(cx)
9601 .with_label("3.txt")
9602 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
9603 });
9604
9605 let dirty_multi_buffer_with_both = cx.new(|cx| {
9606 TestItem::new(cx)
9607 .with_dirty(true)
9608 .with_singleton(false)
9609 .with_label("Fake Project Search")
9610 .with_project_items(&[
9611 dirty_regular_buffer.read(cx).project_items[0].clone(),
9612 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
9613 clear_regular_buffer.read(cx).project_items[0].clone(),
9614 ])
9615 });
9616 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
9617 workspace.update_in(cx, |workspace, window, cx| {
9618 workspace.add_item(
9619 pane.clone(),
9620 Box::new(dirty_regular_buffer.clone()),
9621 None,
9622 false,
9623 false,
9624 window,
9625 cx,
9626 );
9627 workspace.add_item(
9628 pane.clone(),
9629 Box::new(dirty_multi_buffer_with_both.clone()),
9630 None,
9631 false,
9632 false,
9633 window,
9634 cx,
9635 );
9636 });
9637
9638 pane.update_in(cx, |pane, window, cx| {
9639 pane.activate_item(1, true, true, window, cx);
9640 assert_eq!(
9641 pane.active_item().unwrap().item_id(),
9642 multi_buffer_with_both_files_id,
9643 "Should select the multi buffer in the pane"
9644 );
9645 });
9646 let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
9647 pane.close_active_item(
9648 &CloseActiveItem {
9649 save_intent: None,
9650 close_pinned: false,
9651 },
9652 window,
9653 cx,
9654 )
9655 });
9656 cx.background_executor.run_until_parked();
9657 assert!(
9658 cx.has_pending_prompt(),
9659 "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
9660 );
9661 }
9662
9663 /// Tests that when `close_on_file_delete` is enabled, files are automatically
9664 /// closed when they are deleted from disk.
9665 #[gpui::test]
9666 async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
9667 init_test(cx);
9668
9669 // Enable the close_on_disk_deletion setting
9670 cx.update_global(|store: &mut SettingsStore, cx| {
9671 store.update_user_settings::<WorkspaceSettings>(cx, |settings| {
9672 settings.close_on_file_delete = Some(true);
9673 });
9674 });
9675
9676 let fs = FakeFs::new(cx.background_executor.clone());
9677 let project = Project::test(fs, [], cx).await;
9678 let (workspace, cx) =
9679 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9680 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
9681
9682 // Create a test item that simulates a file
9683 let item = cx.new(|cx| {
9684 TestItem::new(cx)
9685 .with_label("test.txt")
9686 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
9687 });
9688
9689 // Add item to workspace
9690 workspace.update_in(cx, |workspace, window, cx| {
9691 workspace.add_item(
9692 pane.clone(),
9693 Box::new(item.clone()),
9694 None,
9695 false,
9696 false,
9697 window,
9698 cx,
9699 );
9700 });
9701
9702 // Verify the item is in the pane
9703 pane.read_with(cx, |pane, _| {
9704 assert_eq!(pane.items().count(), 1);
9705 });
9706
9707 // Simulate file deletion by setting the item's deleted state
9708 item.update(cx, |item, _| {
9709 item.set_has_deleted_file(true);
9710 });
9711
9712 // Emit UpdateTab event to trigger the close behavior
9713 cx.run_until_parked();
9714 item.update(cx, |_, cx| {
9715 cx.emit(ItemEvent::UpdateTab);
9716 });
9717
9718 // Allow the close operation to complete
9719 cx.run_until_parked();
9720
9721 // Verify the item was automatically closed
9722 pane.read_with(cx, |pane, _| {
9723 assert_eq!(
9724 pane.items().count(),
9725 0,
9726 "Item should be automatically closed when file is deleted"
9727 );
9728 });
9729 }
9730
9731 /// Tests that when `close_on_file_delete` is disabled (default), files remain
9732 /// open with a strikethrough when they are deleted from disk.
9733 #[gpui::test]
9734 async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
9735 init_test(cx);
9736
9737 // Ensure close_on_disk_deletion is disabled (default)
9738 cx.update_global(|store: &mut SettingsStore, cx| {
9739 store.update_user_settings::<WorkspaceSettings>(cx, |settings| {
9740 settings.close_on_file_delete = Some(false);
9741 });
9742 });
9743
9744 let fs = FakeFs::new(cx.background_executor.clone());
9745 let project = Project::test(fs, [], cx).await;
9746 let (workspace, cx) =
9747 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9748 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
9749
9750 // Create a test item that simulates a file
9751 let item = cx.new(|cx| {
9752 TestItem::new(cx)
9753 .with_label("test.txt")
9754 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
9755 });
9756
9757 // Add item to workspace
9758 workspace.update_in(cx, |workspace, window, cx| {
9759 workspace.add_item(
9760 pane.clone(),
9761 Box::new(item.clone()),
9762 None,
9763 false,
9764 false,
9765 window,
9766 cx,
9767 );
9768 });
9769
9770 // Verify the item is in the pane
9771 pane.read_with(cx, |pane, _| {
9772 assert_eq!(pane.items().count(), 1);
9773 });
9774
9775 // Simulate file deletion
9776 item.update(cx, |item, _| {
9777 item.set_has_deleted_file(true);
9778 });
9779
9780 // Emit UpdateTab event
9781 cx.run_until_parked();
9782 item.update(cx, |_, cx| {
9783 cx.emit(ItemEvent::UpdateTab);
9784 });
9785
9786 // Allow any potential close operation to complete
9787 cx.run_until_parked();
9788
9789 // Verify the item remains open (with strikethrough)
9790 pane.read_with(cx, |pane, _| {
9791 assert_eq!(
9792 pane.items().count(),
9793 1,
9794 "Item should remain open when close_on_disk_deletion is disabled"
9795 );
9796 });
9797
9798 // Verify the item shows as deleted
9799 item.read_with(cx, |item, _| {
9800 assert!(
9801 item.has_deleted_file,
9802 "Item should be marked as having deleted file"
9803 );
9804 });
9805 }
9806
9807 /// Tests that dirty files are not automatically closed when deleted from disk,
9808 /// even when `close_on_file_delete` is enabled. This ensures users don't lose
9809 /// unsaved changes without being prompted.
9810 #[gpui::test]
9811 async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
9812 init_test(cx);
9813
9814 // Enable the close_on_file_delete setting
9815 cx.update_global(|store: &mut SettingsStore, cx| {
9816 store.update_user_settings::<WorkspaceSettings>(cx, |settings| {
9817 settings.close_on_file_delete = Some(true);
9818 });
9819 });
9820
9821 let fs = FakeFs::new(cx.background_executor.clone());
9822 let project = Project::test(fs, [], cx).await;
9823 let (workspace, cx) =
9824 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9825 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
9826
9827 // Create a dirty test item
9828 let item = cx.new(|cx| {
9829 TestItem::new(cx)
9830 .with_dirty(true)
9831 .with_label("test.txt")
9832 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
9833 });
9834
9835 // Add item to workspace
9836 workspace.update_in(cx, |workspace, window, cx| {
9837 workspace.add_item(
9838 pane.clone(),
9839 Box::new(item.clone()),
9840 None,
9841 false,
9842 false,
9843 window,
9844 cx,
9845 );
9846 });
9847
9848 // Simulate file deletion
9849 item.update(cx, |item, _| {
9850 item.set_has_deleted_file(true);
9851 });
9852
9853 // Emit UpdateTab event to trigger the close behavior
9854 cx.run_until_parked();
9855 item.update(cx, |_, cx| {
9856 cx.emit(ItemEvent::UpdateTab);
9857 });
9858
9859 // Allow any potential close operation to complete
9860 cx.run_until_parked();
9861
9862 // Verify the item remains open (dirty files are not auto-closed)
9863 pane.read_with(cx, |pane, _| {
9864 assert_eq!(
9865 pane.items().count(),
9866 1,
9867 "Dirty items should not be automatically closed even when file is deleted"
9868 );
9869 });
9870
9871 // Verify the item is marked as deleted and still dirty
9872 item.read_with(cx, |item, _| {
9873 assert!(
9874 item.has_deleted_file,
9875 "Item should be marked as having deleted file"
9876 );
9877 assert!(item.is_dirty, "Item should still be dirty");
9878 });
9879 }
9880
9881 /// Tests that navigation history is cleaned up when files are auto-closed
9882 /// due to deletion from disk.
9883 #[gpui::test]
9884 async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
9885 init_test(cx);
9886
9887 // Enable the close_on_file_delete setting
9888 cx.update_global(|store: &mut SettingsStore, cx| {
9889 store.update_user_settings::<WorkspaceSettings>(cx, |settings| {
9890 settings.close_on_file_delete = Some(true);
9891 });
9892 });
9893
9894 let fs = FakeFs::new(cx.background_executor.clone());
9895 let project = Project::test(fs, [], cx).await;
9896 let (workspace, cx) =
9897 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9898 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
9899
9900 // Create test items
9901 let item1 = cx.new(|cx| {
9902 TestItem::new(cx)
9903 .with_label("test1.txt")
9904 .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
9905 });
9906 let item1_id = item1.item_id();
9907
9908 let item2 = cx.new(|cx| {
9909 TestItem::new(cx)
9910 .with_label("test2.txt")
9911 .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
9912 });
9913
9914 // Add items to workspace
9915 workspace.update_in(cx, |workspace, window, cx| {
9916 workspace.add_item(
9917 pane.clone(),
9918 Box::new(item1.clone()),
9919 None,
9920 false,
9921 false,
9922 window,
9923 cx,
9924 );
9925 workspace.add_item(
9926 pane.clone(),
9927 Box::new(item2.clone()),
9928 None,
9929 false,
9930 false,
9931 window,
9932 cx,
9933 );
9934 });
9935
9936 // Activate item1 to ensure it gets navigation entries
9937 pane.update_in(cx, |pane, window, cx| {
9938 pane.activate_item(0, true, true, window, cx);
9939 });
9940
9941 // Switch to item2 and back to create navigation history
9942 pane.update_in(cx, |pane, window, cx| {
9943 pane.activate_item(1, true, true, window, cx);
9944 });
9945 cx.run_until_parked();
9946
9947 pane.update_in(cx, |pane, window, cx| {
9948 pane.activate_item(0, true, true, window, cx);
9949 });
9950 cx.run_until_parked();
9951
9952 // Simulate file deletion for item1
9953 item1.update(cx, |item, _| {
9954 item.set_has_deleted_file(true);
9955 });
9956
9957 // Emit UpdateTab event to trigger the close behavior
9958 item1.update(cx, |_, cx| {
9959 cx.emit(ItemEvent::UpdateTab);
9960 });
9961 cx.run_until_parked();
9962
9963 // Verify item1 was closed
9964 pane.read_with(cx, |pane, _| {
9965 assert_eq!(
9966 pane.items().count(),
9967 1,
9968 "Should have 1 item remaining after auto-close"
9969 );
9970 });
9971
9972 // Check navigation history after close
9973 let has_item = pane.read_with(cx, |pane, cx| {
9974 let mut has_item = false;
9975 pane.nav_history().for_each_entry(cx, |entry, _| {
9976 if entry.item.id() == item1_id {
9977 has_item = true;
9978 }
9979 });
9980 has_item
9981 });
9982
9983 assert!(
9984 !has_item,
9985 "Navigation history should not contain closed item entries"
9986 );
9987 }
9988
9989 #[gpui::test]
9990 async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
9991 cx: &mut TestAppContext,
9992 ) {
9993 init_test(cx);
9994
9995 let fs = FakeFs::new(cx.background_executor.clone());
9996 let project = Project::test(fs, [], cx).await;
9997 let (workspace, cx) =
9998 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9999 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10000
10001 let dirty_regular_buffer = cx.new(|cx| {
10002 TestItem::new(cx)
10003 .with_dirty(true)
10004 .with_label("1.txt")
10005 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10006 });
10007 let dirty_regular_buffer_2 = cx.new(|cx| {
10008 TestItem::new(cx)
10009 .with_dirty(true)
10010 .with_label("2.txt")
10011 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10012 });
10013 let clear_regular_buffer = cx.new(|cx| {
10014 TestItem::new(cx)
10015 .with_label("3.txt")
10016 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
10017 });
10018
10019 let dirty_multi_buffer = cx.new(|cx| {
10020 TestItem::new(cx)
10021 .with_dirty(true)
10022 .with_singleton(false)
10023 .with_label("Fake Project Search")
10024 .with_project_items(&[
10025 dirty_regular_buffer.read(cx).project_items[0].clone(),
10026 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
10027 clear_regular_buffer.read(cx).project_items[0].clone(),
10028 ])
10029 });
10030 workspace.update_in(cx, |workspace, window, cx| {
10031 workspace.add_item(
10032 pane.clone(),
10033 Box::new(dirty_regular_buffer.clone()),
10034 None,
10035 false,
10036 false,
10037 window,
10038 cx,
10039 );
10040 workspace.add_item(
10041 pane.clone(),
10042 Box::new(dirty_regular_buffer_2.clone()),
10043 None,
10044 false,
10045 false,
10046 window,
10047 cx,
10048 );
10049 workspace.add_item(
10050 pane.clone(),
10051 Box::new(dirty_multi_buffer.clone()),
10052 None,
10053 false,
10054 false,
10055 window,
10056 cx,
10057 );
10058 });
10059
10060 pane.update_in(cx, |pane, window, cx| {
10061 pane.activate_item(2, true, true, window, cx);
10062 assert_eq!(
10063 pane.active_item().unwrap().item_id(),
10064 dirty_multi_buffer.item_id(),
10065 "Should select the multi buffer in the pane"
10066 );
10067 });
10068 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
10069 pane.close_active_item(
10070 &CloseActiveItem {
10071 save_intent: None,
10072 close_pinned: false,
10073 },
10074 window,
10075 cx,
10076 )
10077 });
10078 cx.background_executor.run_until_parked();
10079 assert!(
10080 !cx.has_pending_prompt(),
10081 "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
10082 );
10083 close_multi_buffer_task
10084 .await
10085 .expect("Closing multi buffer failed");
10086 pane.update(cx, |pane, cx| {
10087 assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
10088 assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
10089 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
10090 assert_eq!(
10091 pane.items()
10092 .map(|item| item.item_id())
10093 .sorted()
10094 .collect::<Vec<_>>(),
10095 vec![
10096 dirty_regular_buffer.item_id(),
10097 dirty_regular_buffer_2.item_id(),
10098 ],
10099 "Should have no multi buffer left in the pane"
10100 );
10101 assert!(dirty_regular_buffer.read(cx).is_dirty);
10102 assert!(dirty_regular_buffer_2.read(cx).is_dirty);
10103 });
10104 }
10105
10106 #[gpui::test]
10107 async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
10108 init_test(cx);
10109 let fs = FakeFs::new(cx.executor());
10110 let project = Project::test(fs, [], cx).await;
10111 let (workspace, cx) =
10112 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10113
10114 // Add a new panel to the right dock, opening the dock and setting the
10115 // focus to the new panel.
10116 let panel = workspace.update_in(cx, |workspace, window, cx| {
10117 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, cx));
10118 workspace.add_panel(panel.clone(), window, cx);
10119
10120 workspace
10121 .right_dock()
10122 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
10123
10124 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10125
10126 panel
10127 });
10128
10129 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
10130 // panel to the next valid position which, in this case, is the left
10131 // dock.
10132 cx.dispatch_action(MoveFocusedPanelToNextPosition);
10133 workspace.update(cx, |workspace, cx| {
10134 assert!(workspace.left_dock().read(cx).is_open());
10135 assert_eq!(panel.read(cx).position, DockPosition::Left);
10136 });
10137
10138 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
10139 // panel to the next valid position which, in this case, is the bottom
10140 // dock.
10141 cx.dispatch_action(MoveFocusedPanelToNextPosition);
10142 workspace.update(cx, |workspace, cx| {
10143 assert!(workspace.bottom_dock().read(cx).is_open());
10144 assert_eq!(panel.read(cx).position, DockPosition::Bottom);
10145 });
10146
10147 // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
10148 // around moving the panel to its initial position, the right dock.
10149 cx.dispatch_action(MoveFocusedPanelToNextPosition);
10150 workspace.update(cx, |workspace, cx| {
10151 assert!(workspace.right_dock().read(cx).is_open());
10152 assert_eq!(panel.read(cx).position, DockPosition::Right);
10153 });
10154
10155 // Remove focus from the panel, ensuring that, if the panel is not
10156 // focused, the `MoveFocusedPanelToNextPosition` action does not update
10157 // the panel's position, so the panel is still in the right dock.
10158 workspace.update_in(cx, |workspace, window, cx| {
10159 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10160 });
10161
10162 cx.dispatch_action(MoveFocusedPanelToNextPosition);
10163 workspace.update(cx, |workspace, cx| {
10164 assert!(workspace.right_dock().read(cx).is_open());
10165 assert_eq!(panel.read(cx).position, DockPosition::Right);
10166 });
10167 }
10168
10169 #[gpui::test]
10170 async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
10171 init_test(cx);
10172
10173 let fs = FakeFs::new(cx.executor());
10174 let project = Project::test(fs, [], cx).await;
10175 let (workspace, cx) =
10176 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10177
10178 let item_1 = cx.new(|cx| {
10179 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
10180 });
10181 workspace.update_in(cx, |workspace, window, cx| {
10182 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
10183 workspace.move_item_to_pane_in_direction(
10184 &MoveItemToPaneInDirection {
10185 direction: SplitDirection::Right,
10186 focus: true,
10187 clone: false,
10188 },
10189 window,
10190 cx,
10191 );
10192 workspace.move_item_to_pane_at_index(
10193 &MoveItemToPane {
10194 destination: 3,
10195 focus: true,
10196 clone: false,
10197 },
10198 window,
10199 cx,
10200 );
10201
10202 assert_eq!(workspace.panes.len(), 1, "No new panes were created");
10203 assert_eq!(
10204 pane_items_paths(&workspace.active_pane, cx),
10205 vec!["first.txt".to_string()],
10206 "Single item was not moved anywhere"
10207 );
10208 });
10209
10210 let item_2 = cx.new(|cx| {
10211 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
10212 });
10213 workspace.update_in(cx, |workspace, window, cx| {
10214 workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
10215 assert_eq!(
10216 pane_items_paths(&workspace.panes[0], cx),
10217 vec!["first.txt".to_string(), "second.txt".to_string()],
10218 );
10219 workspace.move_item_to_pane_in_direction(
10220 &MoveItemToPaneInDirection {
10221 direction: SplitDirection::Right,
10222 focus: true,
10223 clone: false,
10224 },
10225 window,
10226 cx,
10227 );
10228
10229 assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
10230 assert_eq!(
10231 pane_items_paths(&workspace.panes[0], cx),
10232 vec!["first.txt".to_string()],
10233 "After moving, one item should be left in the original pane"
10234 );
10235 assert_eq!(
10236 pane_items_paths(&workspace.panes[1], cx),
10237 vec!["second.txt".to_string()],
10238 "New item should have been moved to the new pane"
10239 );
10240 });
10241
10242 let item_3 = cx.new(|cx| {
10243 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
10244 });
10245 workspace.update_in(cx, |workspace, window, cx| {
10246 let original_pane = workspace.panes[0].clone();
10247 workspace.set_active_pane(&original_pane, window, cx);
10248 workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
10249 assert_eq!(workspace.panes.len(), 2, "No new panes were created");
10250 assert_eq!(
10251 pane_items_paths(&workspace.active_pane, cx),
10252 vec!["first.txt".to_string(), "third.txt".to_string()],
10253 "New pane should be ready to move one item out"
10254 );
10255
10256 workspace.move_item_to_pane_at_index(
10257 &MoveItemToPane {
10258 destination: 3,
10259 focus: true,
10260 clone: false,
10261 },
10262 window,
10263 cx,
10264 );
10265 assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
10266 assert_eq!(
10267 pane_items_paths(&workspace.active_pane, cx),
10268 vec!["first.txt".to_string()],
10269 "After moving, one item should be left in the original pane"
10270 );
10271 assert_eq!(
10272 pane_items_paths(&workspace.panes[1], cx),
10273 vec!["second.txt".to_string()],
10274 "Previously created pane should be unchanged"
10275 );
10276 assert_eq!(
10277 pane_items_paths(&workspace.panes[2], cx),
10278 vec!["third.txt".to_string()],
10279 "New item should have been moved to the new pane"
10280 );
10281 });
10282 }
10283
10284 #[gpui::test]
10285 async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
10286 init_test(cx);
10287
10288 let fs = FakeFs::new(cx.executor());
10289 let project = Project::test(fs, [], cx).await;
10290 let (workspace, cx) =
10291 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10292
10293 let item_1 = cx.new(|cx| {
10294 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
10295 });
10296 workspace.update_in(cx, |workspace, window, cx| {
10297 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
10298 workspace.move_item_to_pane_in_direction(
10299 &MoveItemToPaneInDirection {
10300 direction: SplitDirection::Right,
10301 focus: true,
10302 clone: true,
10303 },
10304 window,
10305 cx,
10306 );
10307 workspace.move_item_to_pane_at_index(
10308 &MoveItemToPane {
10309 destination: 3,
10310 focus: true,
10311 clone: true,
10312 },
10313 window,
10314 cx,
10315 );
10316
10317 assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
10318 for pane in workspace.panes() {
10319 assert_eq!(
10320 pane_items_paths(pane, cx),
10321 vec!["first.txt".to_string()],
10322 "Single item exists in all panes"
10323 );
10324 }
10325 });
10326
10327 // verify that the active pane has been updated after waiting for the
10328 // pane focus event to fire and resolve
10329 workspace.read_with(cx, |workspace, _app| {
10330 assert_eq!(
10331 workspace.active_pane(),
10332 &workspace.panes[2],
10333 "The third pane should be the active one: {:?}",
10334 workspace.panes
10335 );
10336 })
10337 }
10338
10339 mod register_project_item_tests {
10340
10341 use super::*;
10342
10343 // View
10344 struct TestPngItemView {
10345 focus_handle: FocusHandle,
10346 }
10347 // Model
10348 struct TestPngItem {}
10349
10350 impl project::ProjectItem for TestPngItem {
10351 fn try_open(
10352 _project: &Entity<Project>,
10353 path: &ProjectPath,
10354 cx: &mut App,
10355 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
10356 if path.path.extension().unwrap() == "png" {
10357 Some(cx.spawn(async move |cx| cx.new(|_| TestPngItem {})))
10358 } else {
10359 None
10360 }
10361 }
10362
10363 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
10364 None
10365 }
10366
10367 fn project_path(&self, _: &App) -> Option<ProjectPath> {
10368 None
10369 }
10370
10371 fn is_dirty(&self) -> bool {
10372 false
10373 }
10374 }
10375
10376 impl Item for TestPngItemView {
10377 type Event = ();
10378 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
10379 "".into()
10380 }
10381 }
10382 impl EventEmitter<()> for TestPngItemView {}
10383 impl Focusable for TestPngItemView {
10384 fn focus_handle(&self, _cx: &App) -> FocusHandle {
10385 self.focus_handle.clone()
10386 }
10387 }
10388
10389 impl Render for TestPngItemView {
10390 fn render(
10391 &mut self,
10392 _window: &mut Window,
10393 _cx: &mut Context<Self>,
10394 ) -> impl IntoElement {
10395 Empty
10396 }
10397 }
10398
10399 impl ProjectItem for TestPngItemView {
10400 type Item = TestPngItem;
10401
10402 fn for_project_item(
10403 _project: Entity<Project>,
10404 _pane: Option<&Pane>,
10405 _item: Entity<Self::Item>,
10406 _: &mut Window,
10407 cx: &mut Context<Self>,
10408 ) -> Self
10409 where
10410 Self: Sized,
10411 {
10412 Self {
10413 focus_handle: cx.focus_handle(),
10414 }
10415 }
10416 }
10417
10418 // View
10419 struct TestIpynbItemView {
10420 focus_handle: FocusHandle,
10421 }
10422 // Model
10423 struct TestIpynbItem {}
10424
10425 impl project::ProjectItem for TestIpynbItem {
10426 fn try_open(
10427 _project: &Entity<Project>,
10428 path: &ProjectPath,
10429 cx: &mut App,
10430 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
10431 if path.path.extension().unwrap() == "ipynb" {
10432 Some(cx.spawn(async move |cx| cx.new(|_| TestIpynbItem {})))
10433 } else {
10434 None
10435 }
10436 }
10437
10438 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
10439 None
10440 }
10441
10442 fn project_path(&self, _: &App) -> Option<ProjectPath> {
10443 None
10444 }
10445
10446 fn is_dirty(&self) -> bool {
10447 false
10448 }
10449 }
10450
10451 impl Item for TestIpynbItemView {
10452 type Event = ();
10453 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
10454 "".into()
10455 }
10456 }
10457 impl EventEmitter<()> for TestIpynbItemView {}
10458 impl Focusable for TestIpynbItemView {
10459 fn focus_handle(&self, _cx: &App) -> FocusHandle {
10460 self.focus_handle.clone()
10461 }
10462 }
10463
10464 impl Render for TestIpynbItemView {
10465 fn render(
10466 &mut self,
10467 _window: &mut Window,
10468 _cx: &mut Context<Self>,
10469 ) -> impl IntoElement {
10470 Empty
10471 }
10472 }
10473
10474 impl ProjectItem for TestIpynbItemView {
10475 type Item = TestIpynbItem;
10476
10477 fn for_project_item(
10478 _project: Entity<Project>,
10479 _pane: Option<&Pane>,
10480 _item: Entity<Self::Item>,
10481 _: &mut Window,
10482 cx: &mut Context<Self>,
10483 ) -> Self
10484 where
10485 Self: Sized,
10486 {
10487 Self {
10488 focus_handle: cx.focus_handle(),
10489 }
10490 }
10491 }
10492
10493 struct TestAlternatePngItemView {
10494 focus_handle: FocusHandle,
10495 }
10496
10497 impl Item for TestAlternatePngItemView {
10498 type Event = ();
10499 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
10500 "".into()
10501 }
10502 }
10503
10504 impl EventEmitter<()> for TestAlternatePngItemView {}
10505 impl Focusable for TestAlternatePngItemView {
10506 fn focus_handle(&self, _cx: &App) -> FocusHandle {
10507 self.focus_handle.clone()
10508 }
10509 }
10510
10511 impl Render for TestAlternatePngItemView {
10512 fn render(
10513 &mut self,
10514 _window: &mut Window,
10515 _cx: &mut Context<Self>,
10516 ) -> impl IntoElement {
10517 Empty
10518 }
10519 }
10520
10521 impl ProjectItem for TestAlternatePngItemView {
10522 type Item = TestPngItem;
10523
10524 fn for_project_item(
10525 _project: Entity<Project>,
10526 _pane: Option<&Pane>,
10527 _item: Entity<Self::Item>,
10528 _: &mut Window,
10529 cx: &mut Context<Self>,
10530 ) -> Self
10531 where
10532 Self: Sized,
10533 {
10534 Self {
10535 focus_handle: cx.focus_handle(),
10536 }
10537 }
10538 }
10539
10540 #[gpui::test]
10541 async fn test_register_project_item(cx: &mut TestAppContext) {
10542 init_test(cx);
10543
10544 cx.update(|cx| {
10545 register_project_item::<TestPngItemView>(cx);
10546 register_project_item::<TestIpynbItemView>(cx);
10547 });
10548
10549 let fs = FakeFs::new(cx.executor());
10550 fs.insert_tree(
10551 "/root1",
10552 json!({
10553 "one.png": "BINARYDATAHERE",
10554 "two.ipynb": "{ totally a notebook }",
10555 "three.txt": "editing text, sure why not?"
10556 }),
10557 )
10558 .await;
10559
10560 let project = Project::test(fs, ["root1".as_ref()], cx).await;
10561 let (workspace, cx) =
10562 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10563
10564 let worktree_id = project.update(cx, |project, cx| {
10565 project.worktrees(cx).next().unwrap().read(cx).id()
10566 });
10567
10568 let handle = workspace
10569 .update_in(cx, |workspace, window, cx| {
10570 let project_path = (worktree_id, "one.png");
10571 workspace.open_path(project_path, None, true, window, cx)
10572 })
10573 .await
10574 .unwrap();
10575
10576 // Now we can check if the handle we got back errored or not
10577 assert_eq!(
10578 handle.to_any().entity_type(),
10579 TypeId::of::<TestPngItemView>()
10580 );
10581
10582 let handle = workspace
10583 .update_in(cx, |workspace, window, cx| {
10584 let project_path = (worktree_id, "two.ipynb");
10585 workspace.open_path(project_path, None, true, window, cx)
10586 })
10587 .await
10588 .unwrap();
10589
10590 assert_eq!(
10591 handle.to_any().entity_type(),
10592 TypeId::of::<TestIpynbItemView>()
10593 );
10594
10595 let handle = workspace
10596 .update_in(cx, |workspace, window, cx| {
10597 let project_path = (worktree_id, "three.txt");
10598 workspace.open_path(project_path, None, true, window, cx)
10599 })
10600 .await;
10601 assert!(handle.is_err());
10602 }
10603
10604 #[gpui::test]
10605 async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
10606 init_test(cx);
10607
10608 cx.update(|cx| {
10609 register_project_item::<TestPngItemView>(cx);
10610 register_project_item::<TestAlternatePngItemView>(cx);
10611 });
10612
10613 let fs = FakeFs::new(cx.executor());
10614 fs.insert_tree(
10615 "/root1",
10616 json!({
10617 "one.png": "BINARYDATAHERE",
10618 "two.ipynb": "{ totally a notebook }",
10619 "three.txt": "editing text, sure why not?"
10620 }),
10621 )
10622 .await;
10623 let project = Project::test(fs, ["root1".as_ref()], cx).await;
10624 let (workspace, cx) =
10625 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10626 let worktree_id = project.update(cx, |project, cx| {
10627 project.worktrees(cx).next().unwrap().read(cx).id()
10628 });
10629
10630 let handle = workspace
10631 .update_in(cx, |workspace, window, cx| {
10632 let project_path = (worktree_id, "one.png");
10633 workspace.open_path(project_path, None, true, window, cx)
10634 })
10635 .await
10636 .unwrap();
10637
10638 // This _must_ be the second item registered
10639 assert_eq!(
10640 handle.to_any().entity_type(),
10641 TypeId::of::<TestAlternatePngItemView>()
10642 );
10643
10644 let handle = workspace
10645 .update_in(cx, |workspace, window, cx| {
10646 let project_path = (worktree_id, "three.txt");
10647 workspace.open_path(project_path, None, true, window, cx)
10648 })
10649 .await;
10650 assert!(handle.is_err());
10651 }
10652 }
10653
10654 fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
10655 pane.read(cx)
10656 .items()
10657 .flat_map(|item| {
10658 item.project_paths(cx)
10659 .into_iter()
10660 .map(|path| path.path.to_string_lossy().to_string())
10661 })
10662 .collect()
10663 }
10664
10665 pub fn init_test(cx: &mut TestAppContext) {
10666 cx.update(|cx| {
10667 let settings_store = SettingsStore::test(cx);
10668 cx.set_global(settings_store);
10669 theme::init(theme::LoadThemes::JustBase, cx);
10670 language::init(cx);
10671 crate::init_settings(cx);
10672 Project::init_settings(cx);
10673 });
10674 }
10675
10676 fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
10677 let item = TestProjectItem::new(id, path, cx);
10678 item.update(cx, |item, _| {
10679 item.is_dirty = true;
10680 });
10681 item
10682 }
10683}