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