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