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