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