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