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